问:
How can I do the opposite .include?
So the goal here is to print the index of the element if the element is in the array or print -1 if the element is not in the array. I have to do this using loops. PLEASE HELP!</p>

```<code>def element_index(element, my_array)
  while my_array.map.include? element do
    puts my_array.index(element)
    break
  end

  until my_array.include? element do
    puts -1
    break
  end
end

p element_index("c", ["a","b","c"])
</code>```

答:
I know this is an assignment, but I'll first cover this as if it were real code because it's teaching you some not-so-great Ruby.

Ruby has a method for doing this, Array#index. It returns the index of the first matching element (there can be more than one), or nil.

```<code>p ["a","b","c"].index("c")  # 2
p ["a","b","c"].index("d")  # nil
</code>```

Returning -1 is inadvisable. nil is a safer "this thing does not exist" value because its never a valid value, always false (-1 and 0 are true in Ruby), and does not compare equal to anything but itself. Returning -1 indicates whomever came up with this exercise is converting it from another language like C.

If you must, a simple wrapper will do.

```<code>def element_index(element, array)
    idx = array.index(element)
    if idx == nil
        return -1
    else
        return idx
    end
end
</code>```

I have to do this using loops.

Ok, it's homework. Let's rewrite Array#index.

The basic idea is to loop through each element until you find one which matches. Iterating through each element of an array is done with Array#each, but you need each index, that's done with Array#each_index. The element can be then gotten with array[idx].

```<code>def index(array, want)
    # Run the block for each index of the array.
    # idx will be assigned the index: 0, 1, 2, ...
    array.each_index { |idx|
        # If it's the element we want, return the index immediately.
        # No need to spend more time searching.
        if array[idx] == want
            return idx
        end
    }

    # Otherwise return -1.
    # nil is better, but the assignment wants -1.
    return -1
end

# It's better to put the thing you're working on first,
# and the thing you're looking for second.
# Its like verb( subject, object ) or subject.verb(object) if this were a method.
p index(["a","b","c"], "c")
p index(["a","b","c"], "d")
</code>```

Get used to using list.each { |thing| ... }, that's how you loop in Ruby, along with many other similar methods. There's little call for while and for loops in Ruby. Instead, you ask the object to loop and tell it what to do with each thing. It's very powerful.

Title: How can I do the opposite .include?

Body:
So the goal here is to print the index of the element if the element is in the array or print -1 if the element is not in the array. I have to do this using loops. PLEASE HELP!

def element_index(element, my_array)
  while my_array.map.include? element do
    puts my_array.index(element)
    break
  end

  until my_array.include? element do
    puts -1
    break
  end
end

p element_index("c", ["a","b","c"])

Body:
I know this is an assignment, but I'll first cover this as if it were real code because it's teaching you some not-so-great Ruby.

Ruby has a method for doing this, Array#index. It returns the index of the first matching element (there can be more than one), or nil.

p ["a","b","c"].index("c")  # 2
p ["a","b","c"].index("d")  # nil

Returning -1 is inadvisable. nil is a safer "this thing does not exist" value because its never a valid value, always false (-1 and 0 are true in Ruby), and does not compare equal to anything but itself. Returning -1 indicates whomever came up with this exercise is converting it from another language like C.

If you must, a simple wrapper will do.

def element_index(element, array)
    idx = array.index(element)
    if idx == nil
        return -1
    else
        return idx
    end
end

I have to do this using loops.

Ok, it's homework. Let's rewrite Array#index.

The basic idea is to loop through each element until you find one which matches. Iterating through each element of an array is done with Array#each, but you need each index, that's done with Array#each_index. The element can be then gotten with array[idx].

def index(array, want)
    # Run the block for each index of the array.
    # idx will be assigned the index: 0, 1, 2, ...
    array.each_index { |idx|
        # If it's the element we want, return the index immediately.
        # No need to spend more time searching.
        if array[idx] == want
            return idx
        end
    }

    # Otherwise return -1.
    # nil is better, but the assignment wants -1.
    return -1
end

# It's better to put the thing you're working on first,
# and the thing you're looking for second.
# Its like verb( subject, object ) or subject.verb(object) if this were a method.
p index(["a","b","c"], "c")
p index(["a","b","c"], "d")

Get used to using list.each { |thing| ... }, that's how you loop in Ruby, along with many other similar methods. There's little call for while and for loops in Ruby. Instead, you ask the object to loop and tell it what to do with each thing. It's very powerful.


来源: stackexchange

问:
UISearchBar cancel button no action
My UISearchBar's cancel button doesn't seem to do anything when clicked. Here is my current code:

```<code>var searchBar = UISearchBar()
</code>```

and in my ViewDidLoad:

```<code>searchBar.sizeToFit()
searchBar.searchBarStyle = .minimal
searchBar.placeholder = "Search City"
searchBar.showsCancelButton = true
searchBar.delegate = self
myTable.tableHeaderView = searchBar
</code>```

Wondering if you can help me figure out what's wrong with my SearchBar and why the cancel button doesn't give any action.

答:
Implement SearchBar Delegate

```<code>func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    searchBar.setShowsCancelButton(false, animated: true)
    searchBar.resignFirstResponder()
}
</code>```

You can also hide and show cancel button as follow:

```<code>searchBar.setShowsCancelButton(false, animated: true)
</code>```

ContentLicense: CC BY-SA 3.0

Title: UISearchBar cancel button no action

Body:
My UISearchBar's cancel button doesn't seem to do anything when clicked. Here is my current code:

var searchBar = UISearchBar()

and in my ViewDidLoad:

searchBar.sizeToFit()
searchBar.searchBarStyle = .minimal
searchBar.placeholder = "Search City"
searchBar.showsCancelButton = true
searchBar.delegate = self
myTable.tableHeaderView = searchBar

Wondering if you can help me figure out what's wrong with my SearchBar and why the cancel button doesn't give any action.

Body:
Implement SearchBar Delegate

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    searchBar.setShowsCancelButton(false, animated: true)
    searchBar.resignFirstResponder()
}

You can also hide and show cancel button as follow:

searchBar.setShowsCancelButton(false, animated: true)


问:
ArrayType in extension where clause

```<code>extension Array where Element: _ArrayType, Element.Generator.Element: Any {
    func transpose() -> [Element] {
        if self.isEmpty { return [Element]() }
        let count = self[0].count
        var out = [Element](repeating: Element(), count: count)
        for outer in self {
            for (index, inner) in outer.enumerated() {
                out[index].append(inner)
            }
        }
        return out
    }
}
</code>```

I am getting this error in Swift 3.0 after converting it from Swift 2.2. The elements of the array are also array. So how to define it in Swift 3.0?

答:
```<code>extension Array where Element : Collection, Element.Index == Int, Element.IndexDistance == Int {
    func transpose() -> [[Element.Iterator.Element]] {
        typealias InnerElement = Element.Iterator.Element
        if self.isEmpty { return [] }
        let count = self[0].count
        var out = [[InnerElement]](repeating: [InnerElement](), count: count)
        for outer in self {
            for (index, inner) in outer.enumerated() {
                out[index].append(inner)
            }
        }
        return out
    }
}
</code>```

Title: ArrayType in extension where clause

Body:
extension Array where Element: _ArrayType, Element.Generator.Element: Any {
    func transpose() -> [Element] {
        if self.isEmpty { return [Element]() }
        let count = self[0].count
        var out = [Element](repeating: Element(), count: count)
        for outer in self {
            for (index, inner) in outer.enumerated() {
                out[index].append(inner)
            }
        }
        return out
    }
}

I am getting this error in Swift 3.0 after converting it from Swift 2.2. The elements of the array are also array. So how to define it in Swift 3.0?


问:
Find out the error_log's path
I have this domain.com pointed to /home/username/public_html/domain.com.

I added these lines to the .htaccess file:

ErrorDocument 500 /oohps.php
ErrorDocument 404 /where.php
```

So I can show some styled template.

The problem is that when trying to access a nonexisting page, I get an additional internal server error, so these files are not opened.

I wanted to check for the logs, but I cannot find the error log in that path (/home/username/public_html/domain.com).

I found one in /var/log/httpd, but I don't think it’s the right folder, because there are many errors not involved with this page and I didn't see any involved.

Is there a PHP function that would output the errors log file path?

答:
To only get the path where PHP stores its logs, use:

```<code>pathinfo(ini_get('error_log'),PATHINFO_DIRNAME);
</code>```

Which should return something like this (on localhost):

```<code>/Applications/MAMP/logs
</code>```

ContentLicense: CC BY-SA 4.0

Title: Find out the error_log's path

Body:
I have this domain.com pointed to /home/username/public_html/domain.com.

I added these lines to the .htaccess file:

ErrorDocument 500 /oohps.php
ErrorDocument 404 /where.php

So I can show some styled template.

The problem is that when trying to access a nonexisting page, I get an additional internal server error, so these files are not opened.

I wanted to check for the logs, but I cannot find the error log in that path (/home/username/public_html/domain.com).

I found one in /var/log/httpd, but I don't think it’s the right folder, because there are many errors not involved with this page and I didn't see any involved.

Is there a PHP function that would output the errors log file path?

Body:
To only get the path where PHP stores its logs, use:

pathinfo(ini_get('error_log'),PATHINFO_DIRNAME);

Which should return something like this (on localhost):

/Applications/MAMP/logs


问:
How to find non-retweets in a MongoDB collection of tweets?
I have a collection of about 1.4 million tweets in a MongoDB collection. I want to find all that are NOT retweets, and am using Python. The structure of a document is as follows:

```<code>{
  '_id': ObjectId('59388c046b0c1901172555b9'),
  'coordinates': None,
  'created_at': datetime.datetime(2016, 8, 18, 17, 17, 12),
  'geo': None,
  'is_quote': False,
  'lang': 'en',
  'text': b'Adam Cole Praises Kevin Owens + A Preview For Next Week\xe2\x80\x99s',
  'tw_id': 766323071976247296,
  'user_id': 2231233110,
  'user_lang': 'en',
  'user_loc': 'main; @Kan1shk3',
  'user_name': 'sheezy0',
  'user_timezone': 'Chennai'
}
</code>```

I can write a query that works to find the particular tweet from above:

```<code>twitter_mongo_collection.find_one({
  'text': b'Adam Cole Praises Kevin Owens + A Preview For Next Week\xe2\x80\x99s'
})
</code>```

But when I try to find retweets, my code doesn't work, for example I try to find any tweets that start like this:

```<code>'text': b'RT some tweet'
</code>```

Using this query:

```<code>find_one( {'text': {'$regex': "/^RT/" } }  )
</code>```

It doesn't return an error, but it doesn't find anything. I suspect it has something to do with that 'b' at the beginning before the text starts. I know I also need to put '$not:' in there somewhere but am not sure where.

Thanks!

答:
It looks like your regex search is trying to match the string

b'RT'

but you want to match strings like

b'RT some text afterwards'

try using this regex instead

find_one( {'text': {'$regex': "/^RT.*/" } }  )

Body:
I have a collection of about 1.4 million tweets in a MongoDB collection. I want to find all that are NOT retweets, and am using Python. The structure of a document is as follows:

{
  '_id': ObjectId('59388c046b0c1901172555b9'),
  'coordinates': None,
  'created_at': datetime.datetime(2016, 8, 18, 17, 17, 12),
  'geo': None,
  'is_quote': False,
  'lang': 'en',
  'text': b'Adam Cole Praises Kevin Owens + A Preview For Next Week\xe2\x80\x99s',
  'tw_id': 766323071976247296,
  'user_id': 2231233110,
  'user_lang': 'en',
  'user_loc': 'main; @Kan1shk3',
  'user_name': 'sheezy0',
  'user_timezone': 'Chennai'
}

I can write a query that works to find the particular tweet from above:

twitter_mongo_collection.find_one({
  'text': b'Adam Cole Praises Kevin Owens + A Preview For Next Week\xe2\x80\x99s'
})

But when I try to find retweets, my code doesn't work, for example I try to find any tweets that start like this:

'text': b'RT some tweet'

Using this query:

find_one( {'text': {'$regex': "/^RT/" } }  )

It doesn't return an error, but it doesn't find anything. I suspect it has something to do with that 'b' at the beginning before the text starts. I know I also need to put '$not:' in there somewhere but am not sure where.

Thanks!


问:
Calculating Days Between Two Dates Failing A Single Case (python, Udacity)
Working on a calculator that calculates the number of days between two dates specified by a user. In every case except one this calculator works, but it's unknown to me as to why this one case is failing. Here is the code I've written. </p>

```<code>daysOfMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

def month2dayz(month):
    i = 0
    month2day = 0
    while i != month - 1:
        month2day = month2day + daysOfMonths[i]
        i = i + 1
    return month2day

def leapDayz(year1, year2, month):
    leapDays = 0
    while year1 != year2 + 1:
        if year1%4 == 0:
            leapDays = leapDays + 1
        year1 = year1 + 1
    if year2%4 == 0 and month < 3:
        leapDays = leapDays - 1
    return leapDays

def daysBetweenDates(year1, month1, day1, year2, month2, day2):
    yearTday = (year2 - year1)*365

    monthTday = month2dayz(month2) - month2dayz(month1)
    leapDays = leapDayz(year1, year2, month2)

    return yearTday + monthTday + (day2 - day1) + leapDays

def test():
    test_cases = [((2012,1,1,2012,2,28), 58),
                  ((2012,1,1,2012,3,1), 60),
                  ((2011,6,30,2012,6,30), 366),
                  ((2011,1,1,2012,8,8), 585),
                  ((1900,1,1,1999,12,31), 36523)]
    for (args, answer) in test_cases:
        result = daysBetweenDates(*args)
        if result != answer:
            print "Test with data:", args, "failed"
        else:
            print "Test case passed!"
test()
</code>```

<p>The case that's failing is the final one, counting the days from January 1st, 1900 to December 31st, 1999. The correct number of days is 36523, the program spits out 36524. </p>

答: You appear to be treating 1900 as being a leap year.  But it's not - centuries are leap years only when they're divisible by 400 (so 1900 is not, but 2000 is, but not 2100, 2200, or 2300 either).</p>

Body:
Working on a calculator that calculates the number of days between two dates specified by a user. In every case except one this calculator works, but it's unknown to me as to why this one case is failing. Here is the code I've written.

daysOfMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

def month2dayz(month):
    i = 0
    month2day = 0
    while i != month - 1:
        month2day = month2day + daysOfMonths[i]
        i = i + 1
    return month2day

def leapDayz(year1, year2, month):
    leapDays = 0
    while year1 != year2 + 1:
        if year1%4 == 0:
            leapDays = leapDays + 1
        year1 = year1 + 1
    if year2%4 == 0 and month < 3:
        leapDays = leapDays - 1
    return leapDays

def daysBetweenDates(year1, month1, day1, year2, month2, day2):
    yearTday = (year2 - year1)*365

    monthTday = month2dayz(month2) - month2dayz(month1)
    leapDays = leapDayz(year1, year2, month2)

    return yearTday + monthTday + (day2 - day1) + leapDays

def test():
    test_cases = [((2012,1,1,2012,2,28), 58),
                  ((2012,1,1,2012,3,1), 60),
                  ((2011,6,30,2012,6,30), 366),
                  ((2011,1,1,2012,8,8), 585),
                  ((1900,1,1,1999,12,31), 36523)]
    for (args, answer) in test_cases:
        result = daysBetweenDates(*args)
        if result != answer:
            print "Test with data:", args, "failed"
        else:
            print "Test case passed!"
test()

The case that's failing is the final one, counting the days from January 1st, 1900 to December 31st, 1999. The correct number of days is 36523, the program spits out 36524.


问:
R ggplot scatter plot and mean with error bar
I want to produce a scatter plot and mean value with error bars. My code is as follows. When I add the geom_errorbar(), there is an error message:

Error in FUN(X[[i]], ...) : object 'value' not found

```<code>Z <- c(.1,.5,1.)
T <- seq(1:10)
ZT <- expand.grid(Z,T)
colnames(ZT) <- c("Z","T")

n <- nrow(ZT)

nrep <- 100

rmat <- replicate(nrep, rnorm(n))

ave <- apply(rmat,1,mean)
var <- apply(rmat,1,var)
se <- sqrt(var)/sqrt(nrep)

rmat.summary <- as.data.frame(cbind(ZT,ave,se))
colnames(rmat.summary) <- c("Z","T","ave","se")

library(reshape)
library(ggplot2)

rmat <- as.data.frame(cbind(ZT,rmat))
rmat <- melt(as.data.frame(rmat),id=c(1,2))

ggplot(rmat, aes(x = T, y = value)) + geom_point() + geom_line(data =
  rmat.summary, aes(x = T, y = ave)) + facet_wrap( ~ Z)

ggplot(rmat, aes(x = T, y = value)) + geom_point() + geom_line(data =
  rmat.summary, aes(x = T, y = ave)) +
  geom_errorbar(data = rmat.summary, aes(ymin = ave - se, ymax = ave + se))
  + facet_wrap( ~ Z)
</code>```

So can anybody please help me to correct this error? Thanks in advance!

答:
This should work:

```<code>ggplot() +
  geom_point(data = rmat, aes(x = T, y = value)) +
  geom_line(data = rmat.summary, aes(x = T, y = ave)) +
  geom_errorbar(data = rmat.summary, aes(x = T, y = ave, ymin = ave - se, ymax = ave + se)) +
  facet_wrap( ~ Z)
</code>```

But I think you have to play around with ymin and ymax.

Body:
I want to produce a scatter plot and mean value with error bars. My code is as follows. When I add the geom_errorbar(), there is an error message:

Error in FUN(X[[i]], ...) : object 'value' not found

Z <- c(.1,.5,1.)
T <- seq(1:10)
ZT <- expand.grid(Z,T)
colnames(ZT) <- c("Z","T")

n <- nrow(ZT)

nrep <- 100

rmat <- replicate(nrep, rnorm(n))

ave <- apply(rmat,1,mean)
var <- apply(rmat,1,var)
se <- sqrt(var)/sqrt(nrep)

rmat.summary <- as.data.frame(cbind(ZT,ave,se))
colnames(rmat.summary) <- c("Z","T","ave","se")

library(reshape)
library(ggplot2)

rmat <- as.data.frame(cbind(ZT,rmat))
rmat <- melt(as.data.frame(rmat),id=c(1,2))

ggplot(rmat, aes(x = T, y = value)) + geom_point() + geom_line(data =
  rmat.summary, aes(x = T, y = ave)) + facet_wrap( ~ Z)

ggplot(rmat, aes(x = T, y = value)) + geom_point() + geom_line(data =
  rmat.summary, aes(x = T, y = ave)) +
  geom_errorbar(data = rmat.summary, aes(ymin = ave - se, ymax = ave + se))
  + facet_wrap( ~ Z)

So can anybody please help me to correct this error? Thanks in advance!

Body:
This should work:

ggplot() +
  geom_point(data = rmat, aes(x = T, y = value)) +
  geom_line(data = rmat.summary, aes(x = T, y = ave)) +
  geom_errorbar(data = rmat.summary, aes(x = T, y = ave, ymin = ave - se, ymax = ave + se)) +
  facet_wrap( ~ Z)

But I think you have to play around with ymin and ymax.


答:
It seems that you need to extend the function leapDayz. Current implementation of this function thinks that 29-Feb leap year day is added to years that are divisible by 4. But in the Gregorian calendar, years that are divisible by 100, but not by 400, do not contain a leap day.

So, try this modification:

```<code>if (year1%4 == 0 and year1%100 != 0) or year1%400 == 0:
    leapDays = leapDays + 1
</code>```

and

```<code>if ((year2%4 == 0 and year2%100 != 0) or year2%400 == 0) and month < 3:
    leapDays = leapDays - 1
</code>```

Title: Calculating Days Between Two Dates Failing A Single Case (python, Udacity)

Body:
It seems that you need to extend the function leapDayz. Current implementation of this function thinks that 29-Feb leap year day is added to years that are divisible by 4. But in the Gregorian calendar, years that are divisible by 100, but not by 400, do not contain a leap day.

So, try this modification:

if (year1%4 == 0 and year1%100 != 0) or year1%400 == 0:
    leapDays = leapDays + 1

and

if ((year2%4 == 0 and year2%100 != 0) or year2%400 == 0) and month < 3:
    leapDays = leapDays - 1


问:
Using Jenkins and Jenkins Github Plugin, how to prevent pushing to a branch if the unit test fails
My objective is to prevent pushing to a branch if unit test fails using Jenkins and its Github Plugin.

I saw it works in TeamCity in my previous company, and I believe it is common practice.

However, from this tutorial, the code will always be pushed to github branch even if the unit test fails, because the webhook is triggered after the git push.

How do I configure Jenkins to achieve my objective? If it is possible using Jenkins and Githb Plugin.

答:
jenkins won't do that for you, github might, or failing that you need a pre-commit hook.

https://git-scm.com/book/gr/v2/Customizing-Git-Git-Hooks


问:
django m2m_changed with custom through model
In Django I do have two models "Author" and "Publication" that are connected with a Many-to-Many-Field, so that I can assign different authors to a publication. Additionally, I have to use a custom through-model "Authorship" to define the correct order.

```<code>class Author(models.Model):
    first_name = models.CharField(max_length=48)
    .....

class Authorship(models.Model):
    author = models.ForeignKey(Author)
    publication = models.ForeignKey('Publication')
    order_of_authorship = models.IntegerField(default=1)

class Publication(models.Model):
    title = models.CharField(max_length=128)
    authors = models.ManyToManyField(Author, through=Authorship)
    year = models.IntegerField(max_length=4)
    ...

    citation_key = models.CharField(max_length=9, blank=True, default="")
</code>```

At the moment I use the Admin Interface to populate my data with a form for the "Publication" and an inline form "Authorship".

What I want to achieve now:
An additional citation_key-field (e.g. "Einstein1950") should be auto-populated after data has changed.

What I tried to do:
I found out that using signals must be the best practice.

However the "m2m_changed"-Signal on "Publication.authors.through" is not fired, when I change the Authorships.

```<code>@receiver(m2m_changed, sender=Publication.authors.through)
def authors_changed(sender, **kwargs):
    print("authors changed")
</code>```

This problem is also discussed in a related topic, where the author seems to use "post_save" on the through-model.

```<code>@receiver(post_save, sender=Authorship)
def authorship_changed(sender, instance, **kwargs):
    print("authors changed")
</code>```

This seems to work out, but I have to keep in mind, that a deletion is not covered yet, so I added a post_delete-signal:

```<code>@receiver(post_delete, sender=Authorship)
def authorship_deleted(sender, instance, **kwargs):
    print("authors deleted")
</code>```

The problem now is: If I add 4 authors, I get that event fired 4 times. If I want to update my citation_key as described before, this happens also 4 times.

Can this be the correct solution? Or is there a better best practice? I assume it must work somehow with the m2m_changed signal, but I don't know how.
Since I am new to Django, I don't know if this is the obvious solution for you. Furthermore, in this scenario the unnecessary calculation should not have a huge impact, but it is not nice at all.

I only found a really old bug-report in the Django-Trac that seems to address this problem as well. But there is not solution yet.

答: This is a known bug, reported as ticket 17688 on Django.</p>

Body:
In Django I do have two models "Author" and "Publication" that are connected with a Many-to-Many-Field, so that I can assign different authors to a publication. Additionally, I have to use a custom through-model "Authorship" to define the correct order.

class Author(models.Model):
    first_name = models.CharField(max_length=48)
    .....

class Authorship(models.Model):
    author = models.ForeignKey(Author)
    publication = models.ForeignKey('Publication')
    order_of_authorship = models.IntegerField(default=1)

class Publication(models.Model):
    title = models.CharField(max_length=128)
    authors = models.ManyToManyField(Author, through=Authorship)
    year = models.IntegerField(max_length=4)
    ...

    citation_key = models.CharField(max_length=9, blank=True, default="")

At the moment I use the Admin Interface to populate my data with a form for the "Publication" and an inline form "Authorship".

What I want to achieve now:
An additional citation_key-field (e.g. "Einstein1950") should be auto-populated after data has changed.

What I tried to do:
I found out that using signals must be the best practice.

However the "m2m_changed"-Signal on "Publication.authors.through" is not fired, when I change the Authorships.

@receiver(m2m_changed, sender=Publication.authors.through)
def authors_changed(sender, **kwargs):
    print("authors changed")

This problem is also discussed in a related topic, where the author seems to use "post_save" on the through-model.

@receiver(post_save, sender=Authorship)
def authorship_changed(sender, instance, **kwargs):
    print("authors changed")

This seems to work out, but I have to keep in mind, that a deletion is not covered yet, so I added a post_delete-signal:

@receiver(post_delete, sender=Authorship)
def authorship_deleted(sender, instance, **kwargs):
    print("authors deleted")

The problem now is: If I add 4 authors, I get that event fired 4 times. If I want to update my citation_key as described before, this happens also 4 times.

Can this be the correct solution? Or is there a better best practice? I assume it must work somehow with the m2m_changed signal, but I don't know how.
Since I am new to Django, I don't know if this is the obvious solution for you. Furthermore, in this scenario the unnecessary calculation should not have a huge impact, but it is not nice at all.

I only found a really old bug-report in the Django-Trac that seems to address this problem as well. But there is not solution yet.


问:
In Hudson, how do I get the current build's git commit sha?
We are using Hudson with git. We have a build/test server which compiles our project and then a QA server to which we need to deploy.

We want to get the current built git commit sha and use it to pull the appropriate commit for deployment on our QA server.

Unfortunately it seems that the hudon git plugin does not set the git commit sha in the environment variables (as the svn plugin does in  SVN_REVISION for example). How do we get around this?

Pointer/ examples will be helpful as I am a hudson noob.

Thanks

答:
Jenkins Version: 2.46.2

Git Client: 2.4.5

The following GIT variables are available by running the env command from a shell.

GIT_BRANCH

GIT_COMMIT

GIT_PREVIOUS_COMMIT

GIT_PREVIOUS_SUCCESSFUL_COMMIT

GIT_URL

So, to inject them back into the Job's environment variables add the word env to the Script Content section...

tl;dr

Job > Configure > Build Environment > Inject environment variables to the build process > Script Content

ContentLicense: CC BY-SA 2.5


问:
PHP array returns nothing (OOP newbie needs some help)
I am trying to create an form validator class that will check to make sure that people have typed a particular number of characters into specified fields.  Here is my page:

```<code>if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    require_once('functions.php');
    require_once('formValidator.php');

    $validator = new FormValidator();
    $validator->setFirst($_POST['first']);
    $validator->setLast($_POST['last']);
    $validator->setEmail($_POST['email']);

    $errors = array();
    $validator->checkLength($errors);
    echo $errors;

    if (!empty($errors)) {
        echo '<p>' . $message . '</p>';
    }
}
</code>```

// form here (code above is in PHP tags, of course)

Here is my class:

```<code>class FormValidator {

    public $first;
    public $last;
    public $email;
    public $fields_with_lengths;

    public function setFirst($first) {
        $this->first = $first;
    }

    public function setLast($last) {
        $this->last = $last;
    }

    public function setEmail($email) {
        $this->email = $email;
    }

    function setLengths() {
        $this->fields_with_lengths = array('first' => 2, 'last' => 2, 'email' => 8);
    }

    function checkLength($fields_with_lengths) {
        $length_errors = array();

        foreach($fields_with_lengths as $fieldname => $maxlength) {
            if (strlen(trim($_POST[$fieldname])) > $maxlength) {
                $length_errors[] = $fieldname;
            }
        }

        if (!empty($length_errors)) {
            $message = 'There were no errors';
        } else {
            $message = 'There were errors';

        }
        return $message;
    }

}

$validator = new FormValidator();
$validator->setFirst($_POST['first']);
$validator->setLast($_POST['last']);
$validator->setEmail($_POST['email']);
</code>```

Can anyone see what I am doing wrong?  I'd be grateful for some help. Thanks.

答: $errors is empty because you initialize it but never change it. $message is unset because you never assign anything to it.

Body:
I am trying to create an form validator class that will check to make sure that people have typed a particular number of characters into specified fields.  Here is my page:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    require_once('functions.php');
    require_once('formValidator.php');

    $validator = new FormValidator();
    $validator->setFirst($_POST['first']);
    $validator->setLast($_POST['last']);
    $validator->setEmail($_POST['email']);

    $errors = array();
    $validator->checkLength($errors);
    echo $errors;

    if (!empty($errors)) {
        echo '
' . $message . '
';
    }
}

// form here (code above is in PHP tags, of course)

Here is my class:

class FormValidator {

    public $first;
    public $last;
    public $email;
    public $fields_with_lengths;

    public function setFirst($first) {
        $this->first = $first;
    }

    public function setLast($last) {
        $this->last = $last;
    }

    public function setEmail($email) {
        $this->email = $email;
    }

    function setLengths() {
        $this->fields_with_lengths = array('first' => 2, 'last' => 2, 'email' => 8);
    }

    function checkLength($fields_with_lengths) {
        $length_errors = array();

        foreach($fields_with_lengths as $fieldname => $maxlength) {
            if (strlen(trim($_POST[$fieldname])) > $maxlength) {
                $length_errors[] = $fieldname;
            }
        }

        if (!empty($length_errors)) {
            $message = 'There were no errors';
        } else {
            $message = 'There were errors';

        }
        return $message;
    }

}

$validator = new FormValidator();
$validator->setFirst($_POST['first']);
$validator->setLast($_POST['last']);
$validator->setEmail($_POST['email']);

Can anyone see what I am doing wrong?  I'd be grateful for some help. Thanks.


问:
Bot.SendDocumentAsync(tgId, streamFile, "file sended!", false); throw exception Additional information: Error while copying content to a stream
i have created a async method , that its task is to send file to telegram server (then telegram bot can send the file to user) on user request  , its working fine when user are limited but when number of concurrent user increased , project crash , and throw exception

Exception thrown: 'System.Net.Http.HttpRequestException' in mscorlib.dll

Additional information: Error while copying content to a stream.

i have tried to not use "using" and dispose it but it didnt run and throw the same error instantaneously ,

my question is my method correct and its just telegram bug ? if so would creating a queue or a hashmap of sended file will help me ?

```<code>public static async void sendFileToUser(long tgId, int fileId)
    {
    ExceptionDispatchInfo capturedException = null;
    String occuredException = "";
    try
    {
    string pathPhysical1 = (string)myHT[fileId];

    using (

    var fs = new FileStream(pathPhysical1, FileMode.Open,FileAccess.Read, FileShare.Read, 1000, false))
    {

                        string fileName = fileId + ".pdf";
                        FileToSend streamFile = new FileToSend(fileName, fs);

                        await Bot.SendDocumentAsync(tgId, streamFile, "file sended", false);
                        await Bot.SendChatActionAsync(tgId, ChatAction.UploadDocument);

                    }
                }
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                capturedException = ExceptionDispatchInfo.Capture(ex);
                occuredException = "System.Net.Http.HttpRequestException";

            }
            catch (ApiRequestException ex)
            {
                capturedException = ExceptionDispatchInfo.Capture(ex);
                occuredException = "ApiRequestException";

            }
            catch (TaskCanceledException ex)
            {
                capturedException = ExceptionDispatchInfo.Capture(ex);
                occuredException = "TaskCanceledException";

            }
            catch (Exception ex)
            {
                occuredException = "Exception";

                capturedException = ExceptionDispatchInfo.Capture(ex);

            }

            if (capturedException != null)
            {

                printExceptionINConsole(capturedException.SourceException, "capturedException-" + occuredException);

                      }
        }
</code>```

thanks in advance
p.s i have post this issue to creator of this api
https://github.com/MrRoundRobin/telegram.bot/issues/348

答:
how about this:

```<code>public static async void sendFileToUser(long tgId, int fileId)
        {
            ExceptionDispatchInfo capturedException = null;
            String occuredException = "";
            try
            {
                string pathPhysical1 = (string)myHT[fileId];

                string fileName = fileId + ".pdf";
                var fs = new MemoryStream(File.ReadAllBytes(pathPhysical1));
                FileToSend streamFile = new FileToSend(fileName, fs);

                await Bot.SendDocumentAsync(tgId, streamFile, "file sended", false);
                await Bot.SendChatActionAsync(tgId, ChatAction.UploadDocument);
            }
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                capturedException = ExceptionDispatchInfo.Capture(ex);
                occuredException = "System.Net.Http.HttpRequestException";

            }
            catch (ApiRequestException ex)
            {
                capturedException = ExceptionDispatchInfo.Capture(ex);
                occuredException = "ApiRequestException";

            }
            catch (TaskCanceledException ex)
            {
                capturedException = ExceptionDispatchInfo.Capture(ex);
                occuredException = "TaskCanceledException";

            }
            catch (Exception ex)
            {
                occuredException = "Exception";

                capturedException = ExceptionDispatchInfo.Capture(ex);

            }

            if (capturedException != null)
            {

                printExceptionINConsole(capturedException.SourceException, "capturedException-" + occuredException);

                      }
        }
</code>```

i think something is wrong with your stream.

Body:
i have created a async method , that its task is to send file to telegram server (then telegram bot can send the file to user) on user request  , its working fine when user are limited but when number of concurrent user increased , project crash , and throw exception

Exception thrown: 'System.Net.Http.HttpRequestException' in mscorlib.dll

Additional information: Error while copying content to a stream.

i have tried to not use "using" and dispose it but it didnt run and throw the same error instantaneously ,

my question is my method correct and its just telegram bug ? if so would creating a queue or a hashmap of sended file will help me ?

public static async void sendFileToUser(long tgId, int fileId)
    {
    ExceptionDispatchInfo capturedException = null;
    String occuredException = "";
    try
    {
    string pathPhysical1 = (string)myHT[fileId];

    using (

    var fs = new FileStream(pathPhysical1, FileMode.Open,FileAccess.Read, FileShare.Read, 1000, false))
    {

                        string fileName = fileId + ".pdf";
                        FileToSend streamFile = new FileToSend(fileName, fs);

                        await Bot.SendDocumentAsync(tgId, streamFile, "file sended", false);
                        await Bot.SendChatActionAsync(tgId, ChatAction.UploadDocument);

                    }
                }
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                capturedException = ExceptionDispatchInfo.Capture(ex);
                occuredException = "System.Net.Http.HttpRequestException";

            }
            catch (ApiRequestException ex)
            {
                capturedException = ExceptionDispatchInfo.Capture(ex);
                occuredException = "ApiRequestException";

            }
            catch (TaskCanceledException ex)
            {
                capturedException = ExceptionDispatchInfo.Capture(ex);
                occuredException = "TaskCanceledException";

            }
            catch (Exception ex)
            {
                occuredException = "Exception";

                capturedException = ExceptionDispatchInfo.Capture(ex);

            }

            if (capturedException != null)
            {

                printExceptionINConsole(capturedException.SourceException, "capturedException-" + occuredException);

                      }
        }

thanks in advance
p.s i have post this issue to creator of this api
https://github.com/MrRoundRobin/telegram.bot/issues/348

Body:
how about this:

public static async void sendFileToUser(long tgId, int fileId)
        {
            ExceptionDispatchInfo capturedException = null;
            String occuredException = "";
            try
            {
                string pathPhysical1 = (string)myHT[fileId];

                string fileName = fileId + ".pdf";
                var fs = new MemoryStream(File.ReadAllBytes(pathPhysical1));
                FileToSend streamFile = new FileToSend(fileName, fs);

                await Bot.SendDocumentAsync(tgId, streamFile, "file sended", false);
                await Bot.SendChatActionAsync(tgId, ChatAction.UploadDocument);
            }
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                capturedException = ExceptionDispatchInfo.Capture(ex);
                occuredException = "System.Net.Http.HttpRequestException";

            }
            catch (ApiRequestException ex)
            {
                capturedException = ExceptionDispatchInfo.Capture(ex);
                occuredException = "ApiRequestException";

            }
            catch (TaskCanceledException ex)
            {
                capturedException = ExceptionDispatchInfo.Capture(ex);
                occuredException = "TaskCanceledException";

            }
            catch (Exception ex)
            {
                occuredException = "Exception";

                capturedException = ExceptionDispatchInfo.Capture(ex);

            }

            if (capturedException != null)
            {

                printExceptionINConsole(capturedException.SourceException, "capturedException-" + occuredException);

                      }
        }

i think something is wrong with your stream.


问:
Parsing JSON response in Angular2
```<code>Id  FirstName LastName  Action
1.  Foo       Bar       Edit
2.  Happy     Kid       Edit
</code>```

The json which I get from my backend is [{"id":1,"firstName":"Foo","lastName":"Bar"},{"id":2,"firstName":"Happy","lastName":"Kid"}].

Below is my HTML file -

```<code><table datatable class="row-border hover">
  <thead>
    <tr>
      <th>ID</th>
      <th>First name</th>
      <th>Last name</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>

    <tr *ngIf="userList" >
      <td *ngFor="let user of userList">{{user.firstName}}</td>

      <td>
        <button>Edit</button>
      </td>
    </tr>
    </tbody>
</table>
</code>```

The "userList" holds my json response.

Problem :- I get the error "Error trying to diff '[{"id":1,"firstName":"Foo","lastName":"Bar"},{"id":2,"firstName":"Happy","lastName":"Kid"}]'. Only arrays and iterables are allowed".

How do I parse my json into my required ui ?

答:
The json that you get in this case is just a string and not a javascript array. ngFor expects an array to iterate over but the supplied parameter is a string. You need to convert the string to javascript object by using the json() method on the response.

Example code:

```<code>return this.http.get("some-api-url")
                .toPromise()
                .then(response => response.json().data); // check this line
</code>```

If you are using observables directly and not converting toPromise, even then you need to call json() method on the response. You can even use the native JSON.parse method to convert the string response to javascript object.

Title: Parsing JSON response in Angular2

Body:
Id  FirstName LastName  Action
1.  Foo       Bar       Edit
2.  Happy     Kid       Edit

The json which I get from my backend is [{"id":1,"firstName":"Foo","lastName":"Bar"},{"id":2,"firstName":"Happy","lastName":"Kid"}].

Below is my HTML file -

      ID
      First name
      Last name
      Action

      {{user.firstName}}

        <button>Edit</button>

The "userList" holds my json response.

Problem :- I get the error "Error trying to diff '[{"id":1,"firstName":"Foo","lastName":"Bar"},{"id":2,"firstName":"Happy","lastName":"Kid"}]'. Only arrays and iterables are allowed".

How do I parse my json into my required ui ?

Body:
The json that you get in this case is just a string and not a javascript array. ngFor expects an array to iterate over but the supplied parameter is a string. You need to convert the string to javascript object by using the json() method on the response.

Example code:

return this.http.get("some-api-url")
                .toPromise()
                .then(response => response.json().data); // check this line

If you are using observables directly and not converting toPromise, even then you need to call json() method on the response. You can even use the native JSON.parse method to convert the string response to javascript object.


问:
How to create number list 1 until 9 and plus 1 at another row in php?
How to create number list in php 1 until 9 with this out put

1 2 3 4 5 6 7 8 9

2 3 4 5 6 7 8 9 1

3 4 5 6 7 8 9 1 2

4 5 6 7 8 9 1 2 3

5 6 7 8 9 1 2 3 4

6 7 8 9 1 2 3 4 5

7 8 9 1 2 3 4 5 6

8 9 1 2 3 4 5 6 7

9 1 2 3 4 5 6 7 8

Please Let me know ...

Body:
try this,

 <?php

    for( $i = 1; $i<10; $i++ ) {
       $count=$i;
       for($j=1;$j<10;$j++){
             echo($count);

             if($count==9)
                 {$count=0;}
             $count++;

         }
         echo('<br>');
      }

      ?>


答:
Let data be your matrix read/ lodaded from txst file. To pick rows which have 2 in column 7, you can do the following:

```<code>col7 = data(:,7) ;
idx = col7==2 ;
iwant = data(idx,:) ;
</code>```

Title: matlab - filter out row by condition on certain column

Body:
I have a data structured like this

3159,417.236206055,300.815246582,264.060791016,341.630493164,7.86748231008e-06,2
3159,134.812591553,184.91859436,531.439208984,269.763793945,4.9377590905e-07,2
3159,760.162597656,166.481231689,476.437255859,468.503387451,2.78121348174e-07,2
3159,551.595581055,74.2536621094,479.859985352,303.471374512,1.48180667736e-07,2
3159,1065.83898926,314.981079102,204.258789062,326.364746094,8.80023665051e-08,2
3159,248.040405273,21.629524231,829.945678711,138.450164795,1.37097971864e-08,2
3159,80.3406066895,28.684425354,386.45324707,143.023040771,4.562183617e-09,2
3159,947.76953125,31.7755508423,305.259033203,202.499755859,3.76411957159e-09,2
3159,358.889862061,47.3729171753,382.564605713,221.994903564,1.59999635069e-09,2
3159,1078.03979492,99.2788238525,186.233398438,341.675964355,5.5474613618e-10,2
1,387.461395264,272.173980713,43.5688476562,63.8592529297,0.108503072988,3
1,152.127593994,277.128143311,64.2265625,44.8813476562,0.0766168581322,3
1,226.51335144,153.107879639,31.1640167236,43.1790161133,0.0501157774124,3
1,247.809906006,180.634460449,24.0384521484,21.3278198242,0.0226649455726,3
1,518.350952148,446.070495605,71.6326904297,71.5654296875,0.0222841088544,3
1,506.014434814,452.800079346,38.2752990723,80.2373962402,0.00226600914175,3
1,421.329223633,201.027603149,32.4918823242,24.7145996094,0.000995551727101,3
1,253.987335205,195.959823608,21.352722168,17.3350830078,0.000434513503933,3
1,375.351654053,180.608520508,29.7174682617,29.6880187988,7.9327679714e-05,3
1,194.039138794,145.845596313,40.6948547363,49.4976196289,5.12218832682e-05,3
1,416.31741333,157.50378418,26.3580932617,25.781036377,3.00556763477e-05,3
1,251.972137451,163.274612427,19.8468017578,25.6938781738,2.31373164183e-05,3
1,403.309234619,160.924667358,24.6165771484,22.4505004883,1.56914580884e-05,3
1,385.329711914,156.467712402,17.0793457031,17.9400939941,4.03955411343e-06,3

Now I need to loop over column7 which is 2,3,... and count the filter out others(ex: just keep row contain 2 in columns for a iteration)
Now my solution is to loop over the whole file. However my file is so big that take so many time. Is there any smarter way to do so?

Body:
Let data be your matrix read/ lodaded from txst file. To pick rows which have 2 in column 7, you can do the following:

col7 = data(:,7) ;
idx = col7==2 ;
iwant = data(idx,:) ;


问:
JS document.on for cached element
I have code like this:

```<code>$(document).on("click", "#element_1, #element_2", function() {
  alert("clicked")
})
</code>```

Suppose I cached both element_1 and element_2, then how would I write (if possible) the eventHandler?

```<code>element_1 = $("#element_1")
element_2 = $("#element_2")

// obviously below fails with a syntax error because an object has been passed rather than a string selector
$(document).on("click", element_1, element_2, function() {
  alert("clicked")
})
</code>```

答:
You can use .add() to merge one or more jQuery objects into a single  jQuery object collection passed at second parameter to .on()

var element_1 = $("#element_1");
var element_2 = $("#element_2");
var element_3 = $("#element_3");

$(document).on("click", element_1.add(element_2, element_3 /* element_N */)
 , function(e) {
  alert(e.target.id + " clicked")
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div id="element_1">element 1</div>
<div id="element_2">element 2</div>
<div id="element_3">element 3</div></code>```

Title: JS document.on for cached element

Body:
I have code like this:

$(document).on("click", "#element_1, #element_2", function() {
  alert("clicked")
})

Suppose I cached both element_1 and element_2, then how would I write (if possible) the eventHandler?

element_1 = $("#element_1")
element_2 = $("#element_2")

// obviously below fails with a syntax error because an object has been passed rather than a string selector
$(document).on("click", element_1, element_2, function() {
  alert("clicked")
})

Body:
You can use .add() to merge one or more jQuery objects into a single  jQuery object collection passed at second parameter to .on()

var element_1 = $("#element_1");
var element_2 = $("#element_2");
var element_3 = $("#element_3");

$(document).on("click", element_1.add(element_2, element_3 /* element_N */)
 , function(e) {
  alert(e.target.id + " clicked")
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div id="element_1">element 1</div>
<div id="element_2">element 2</div>
<div id="element_3">element 3</div>


问:
Difference between public and private variables
```<code>namespace hi
{
    class hithere
    {
         public int numberOne = 12;
         private int numberTwo = 12;

         static void yo()
         {
         }
    }
}
</code>```

Can someone tell me the difference between the variables numberOne and numberTwo in this code excerpt?

答:
In the simplest terms numberOne being marked as public means that if you create an instance of your hithere class this member variable will be accessible.  For example:

```<code>hithere h = new hithere()
h.numberOne = 42;
</code>```

numberTwo being private means that this is not accessible and can only be used within the hithere class. So taking the above example further:

```<code>hithere h = new hithere()
h.numberOne = 42;
h.numberTwo = 84;
</code>```

The last line would cause a compiler error as you cannot access numberTwo as this is private.

It is probably worth spending some time reading up on access modifiers, a quick google will find many examples, e.g:

http://www.devsource.com/c/a/Techniques/Understanding-C-Class-and-Member-Modifiers/
http://msdn.microsoft.com/en-us/library/ba0a1yw2%28v=vs.80%29.aspx

Additionally your hithere class does not have an access modifier defined therefore the compiler assumes this to be private.  As such if you were to reference your library from another you would not be able to create instances of the hithere class.

Body:
namespace hi
{
    class hithere
    {
         public int numberOne = 12;
         private int numberTwo = 12;

         static void yo()
         {
         }
    }
}

Can someone tell me the difference between the variables numberOne and numberTwo in this code excerpt?

Body:
In the simplest terms numberOne being marked as public means that if you create an instance of your hithere class this member variable will be accessible.  For example:

hithere h = new hithere()
h.numberOne = 42;

numberTwo being private means that this is not accessible and can only be used within the hithere class. So taking the above example further:

hithere h = new hithere()
h.numberOne = 42;
h.numberTwo = 84;

The last line would cause a compiler error as you cannot access numberTwo as this is private.

It is probably worth spending some time reading up on access modifiers, a quick google will find many examples, e.g:

http://www.devsource.com/c/a/Techniques/Understanding-C-Class-and-Member-Modifiers/
http://msdn.microsoft.com/en-us/library/ba0a1yw2%28v=vs.80%29.aspx

Additionally your hithere class does not have an access modifier defined therefore the compiler assumes this to be private.  As such if you were to reference your library from another you would not be able to create instances of the hithere class.


问:
How to customize TinyMCE plugin button text?
I'm making use of TinyMCE's template plugin, but I'd like to customize the text that it displays in the menu bar. Currently it defaults to an icon:

What is the correct way of replacing this icon with some text that just says "Use Template"? Approaches I've considered:

Brute force content of the button with JavaScript.

Make my own custom button that launches the template plugin. What's the best way to do this?

Write my own plugin that reproduces the functionality of templates and just replaces the content of the editor.

Unfortunately, hiding templates within the insert menu or using the icon are not an option. Apologies if there's something that I've missed in the docs.

答:
I ended up solving this by going through the plugin's source code, and modifying the following line:

```<code>editor.addButton('template', {
    title: 'Insert template',
    text: 'Use Template', // Added this attribute
    onclick: createTemplateList(showDialog)
});
</code>```

To avoid setting up the build process for TinyMCE, I just searched for Insert template in the compiled/minified plugin and then added my text attribute.

Body:
I ended up solving this by going through the plugin's source code, and modifying the following line:

editor.addButton('template', {
    title: 'Insert template',
    text: 'Use Template', // Added this attribute
    onclick: createTemplateList(showDialog)
});

To avoid setting up the build process for TinyMCE, I just searched for Insert template in the compiled/minified plugin and then added my text attribute.


问:
Laravel whereIn OR whereIn
I'm making a products search by filters:

My code:

```<code>->where(function($query) use($filter)
{
  if(!empty($filter)){
    foreach ($filter as $key => $value) {
      $f = explode(",", $value);
      $query-> whereIn('products.value', $f);
    }
  }
})
</code>```

Query:

```<code>and (products.value in (Bomann, PHILIPS) and products.value in (red,white))
</code>```

But I need:

```<code>and (products.value in (Bomann, PHILIPS) OR products.value in (red,white))
</code>```

Is there something similar in Laravel:

```<code>orWhereIn
</code>```

答:
For example, if you have multiple whereIn OR whereIn conditions and you want to put brackets, do it like this:</p>

```<code>$getrecord = DiamondMaster::where('is_delete','0')->where('user_id',Auth::user()->id);
if(!empty($request->stone_id))
{
    $postdata = $request->stone_id;
    $certi_id =trim($postdata,",");
    $getrecord = $getrecord->whereIn('id',explode(",", $certi_id))
                           ->orWhereIn('Certi_NO',explode(",", $certi_id));
}
$getrecord = $getrecord->get();
</code>```

Title: Laravel whereIn OR whereIn

Body:
I'm making a products search by filters:

My code:

->where(function($query) use($filter)
{
  if(!empty($filter)){
    foreach ($filter as $key => $value) {
      $f = explode(",", $value);
      $query-> whereIn('products.value', $f);
    }
  }
})

Query:

and (products.value in (Bomann, PHILIPS) and products.value in (red,white))

But I need:

and (products.value in (Bomann, PHILIPS) OR products.value in (red,white))

Is there something similar in Laravel:

orWhereIn

Body:
For example, if you have multiple whereIn OR whereIn conditions and you want to put brackets, do it like this:

$getrecord = DiamondMaster::where('is_delete','0')->where('user_id',Auth::user()->id);
if(!empty($request->stone_id))
{
    $postdata = $request->stone_id;
    $certi_id =trim($postdata,",");
    $getrecord = $getrecord->whereIn('id',explode(",", $certi_id))
                           ->orWhereIn('Certi_NO',explode(",", $certi_id));
}
$getrecord = $getrecord->get();


问:
Efficient way to sum specific row groupings in R
As a quick example, I have a 3x5 matrix

```<code>mat <- matrix(rep(seq(5),3),nrow=3,byrow = T)
</code>```

I'd like to sum across elements in each row based on a specific grouping defined by map.list, which has the same number of main elements as the nrow(mat). It could look something like this:

```<code>map.list <- list(list(c(1,2),c(3,4),5),
             list(c(1,2),3,c(4,5)),
             list(c(1,2),4,5))

> map.list
[[1]]
[[1]][[1]]
[1] 1 2

[[1]][[2]]
[1] 3 4

[[1]][[3]]
[1] 5

[[2]]
[[2]][[1]]
[1] 1 2

[[2]][[2]]
[1] 3

[[2]][[3]]
[1] 4 5

[[3]]
[[3]][[1]]
[1] 1 2

[[3]][[2]]
[1] 3

[[3]][[3]]
[1] 5
</code>```

This means that for the first row of mat, we would sum 1+2=3, 3+4=7, and 5=5 to create the first row of a new matrix mat2. We proceed similarly for the other two elements, corresponding to rows 2 and 3 of the new matrix.

```<code>> mat2
     [,1] [,2] [,3]
[1,]    3    7    5
[2,]    3    3    9
[3,]    3    3    5
</code>```

How could I efficiently create this? Potentially, I'd have a mat that has many rows and many columns.

答:
We can do

```<code>t(sapply(seq_len(nrow(mat)), function(i) sapply(map.list[[i]],function(j) sum(mat[i, j]))))
#     [,1] [,2] [,3]
#[1,]    3    7    5
#[2,]    3    3    9
#[3,]    3    3    5
</code>```

Or another option is

```<code>library(reshape2)
dM <- melt(map.list)[, 3:1]
m1 <- sapply(split(mat[as.matrix(dM[-2])],
       interaction(dM[1:2], drop = TRUE, lex.order = TRUE)), sum)
matrix(m1, 3, 3, byrow=TRUE)
#     [,1] [,2] [,3]
#[1,]    3    7    5
#[2,]    3    3    9
#[3,]    3    3    5
</code>```

data

```<code>map.list <- list(list(c(1,2),c(3,4),5),
         list(c(1,2),3,c(4,5)),
         list(c(1,2),3,5))
</code>```

Body:
As a quick example, I have a 3x5 matrix

mat <- matrix(rep(seq(5),3),nrow=3,byrow = T)

I'd like to sum across elements in each row based on a specific grouping defined by map.list, which has the same number of main elements as the nrow(mat). It could look something like this:

map.list <- list(list(c(1,2),c(3,4),5),
             list(c(1,2),3,c(4,5)),
             list(c(1,2),4,5))

> map.list
[[1]]
[[1]][[1]]
[1] 1 2

[[1]][[2]]
[1] 3 4

[[1]][[3]]
[1] 5

[[2]]
[[2]][[1]]
[1] 1 2

[[2]][[2]]
[1] 3

[[2]][[3]]
[1] 4 5

[[3]]
[[3]][[1]]
[1] 1 2

[[3]][[2]]
[1] 3

[[3]][[3]]
[1] 5

This means that for the first row of mat, we would sum 1+2=3, 3+4=7, and 5=5 to create the first row of a new matrix mat2. We proceed similarly for the other two elements, corresponding to rows 2 and 3 of the new matrix.

> mat2
     [,1] [,2] [,3]
[1,]    3    7    5
[2,]    3    3    9
[3,]    3    3    5

How could I efficiently create this? Potentially, I'd have a mat that has many rows and many columns.

Body:
We can do

t(sapply(seq_len(nrow(mat)), function(i) sapply(map.list[[i]],function(j) sum(mat[i, j]))))
#     [,1] [,2] [,3]
#[1,]    3    7    5
#[2,]    3    3    9
#[3,]    3    3    5

Or another option is

library(reshape2)
dM <- melt(map.list)[, 3:1]
m1 <- sapply(split(mat[as.matrix(dM[-2])],
       interaction(dM[1:2], drop = TRUE, lex.order = TRUE)), sum)
matrix(m1, 3, 3, byrow=TRUE)
#     [,1] [,2] [,3]
#[1,]    3    7    5
#[2,]    3    3    9
#[3,]    3    3    5

data

map.list <- list(list(c(1,2),c(3,4),5),
         list(c(1,2),3,c(4,5)),
         list(c(1,2),3,5))


问:
combobox data bind (C# winforms)
where is the problem with this code? When i start the program there is no values to choose from comboBox. There is no problems with compiling and starting an application. I have no idea what is wrong here. Maybe someone have solution for this problem.

Link to pastebin https://pastebin.com/pASVNWq

```<code>using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace parKing_new
{
    public partial class editClient : Form
    {
        public editClient()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {}

    //Load customer ID to a combobox
        private void LoadCustomersId()
        {
            var connectionString =
"Server=localhost;Port=3306;Database=ewisys;Uid=root;password=;";
            using (var connection = new MySqlConnection(connectionString))
            {
                connection.Open();
                var query = "SELECT clientID FROM clients";
                using (var command = new MySqlCommand(query, connection))
                {
                    using (var reader = command.ExecuteReader())
                    {
                        //Iterate through the rows and add it to the
combobox's items
                        while (reader.Read())
                        {
                        comboBox1.Items.Add(reader.GetString("clientID"));
                        }
                    }
                }
            }
       }

        //Load customer details using the ID
        private void LoadCustomerDetailsById(int id)
        {
            var connectionString =
"Server=localhost;Port=3306;Database=ewisys;Uid=root;password=;";
            using (var connection = new MySqlConnection(connectionString))
           {
               connection.Open();
               var query = "SELECT clientID, name, surName FROM clients WHERE
Id = @clientID";
                using (var command = new MySqlCommand(query, connection))
                {
                //Always use SQL parameters to avoid SQL injection and it
automatically escapes characters
                    command.Parameters.AddWithValue("@clientID", id);
                    using (var reader = command.ExecuteReader())
                    {
                        //No customer found by supplied ID
                        if (!reader.HasRows)
                            return;

                        ClientIDTextBox.Text =
                    reader.GetInt32("clientID").ToString();
                    nameTextBox.Text = reader.GetString("name");
                    surNameTextBox.Text = reader.GetString("surName");
                    }
                }
           }
       }

      private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var clientID = Convert.ToInt32(comboBox1.Text);
            LoadCustomerDetailsById(clientID);
        }
   }
}
</code>```

答: I think you have only defined  LoadCustomersId() method, but you are not calling it from anywhere.you need to call the method</p>

Title: combobox data bind (C# winforms)

Body:
where is the problem with this code? When i start the program there is no values to choose from comboBox. There is no problems with compiling and starting an application. I have no idea what is wrong here. Maybe someone have solution for this problem.

Link to pastebin https://pastebin.com/pASVNWq

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace parKing_new
{
    public partial class editClient : Form
    {
        public editClient()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {}

    //Load customer ID to a combobox
        private void LoadCustomersId()
        {
            var connectionString =
"Server=localhost;Port=3306;Database=ewisys;Uid=root;password=;";
            using (var connection = new MySqlConnection(connectionString))
            {
                connection.Open();
                var query = "SELECT clientID FROM clients";
                using (var command = new MySqlCommand(query, connection))
                {
                    using (var reader = command.ExecuteReader())
                    {
                        //Iterate through the rows and add it to the
combobox's items
                        while (reader.Read())
                        {
                        comboBox1.Items.Add(reader.GetString("clientID"));
                        }
                    }
                }
            }
       }

        //Load customer details using the ID
        private void LoadCustomerDetailsById(int id)
        {
            var connectionString =
"Server=localhost;Port=3306;Database=ewisys;Uid=root;password=;";
            using (var connection = new MySqlConnection(connectionString))
           {
               connection.Open();
               var query = "SELECT clientID, name, surName FROM clients WHERE
Id = @clientID";
                using (var command = new MySqlCommand(query, connection))
                {
                //Always use SQL parameters to avoid SQL injection and it
automatically escapes characters
                    command.Parameters.AddWithValue("@clientID", id);
                    using (var reader = command.ExecuteReader())
                    {
                        //No customer found by supplied ID
                        if (!reader.HasRows)
                            return;

                        ClientIDTextBox.Text =
                    reader.GetInt32("clientID").ToString();
                    nameTextBox.Text = reader.GetString("name");
                    surNameTextBox.Text = reader.GetString("surName");
                    }
                }
           }
       }

      private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var clientID = Convert.ToInt32(comboBox1.Text);
            LoadCustomerDetailsById(clientID);
        }
   }
}


问:
Is the Oct 2010 Macbook Air able to run WP7 tools with GPU recognition?
Pretty much as the title says, using bootcamp.

WDDM1.1 compliance and GPU recognition confirmed by the WP7 emulator running with EnableFrameRateCounters showing.

I'm considering a Macbook air as a compromise to resolve a need to access iphone dev tools and upgrade my Win7 mobile capability to something reasonably performant with one device.

My current laptop barely runs Win7 and borders on unusable for WP7 tooling hence the interest to try and solve two problems with one device - if realistic.

I assume if the device can run WP7 tools satisfactorily, it would be capable of anything else I might want to do when booted under Win7.

答:
I've bought one, but since it's going to the wife, I won't be able to test it in depth.

Instead, the MacbookPro 13" from '09 works fine (monoTouch+iOS dev and bootcamp to vstudio+wp7 dev). I upgraded to 4 gigs memory and that helped, also the disk is slower than I'd like. It responds like a mid-grade desktop, imo.

The problem I see is that the processor on the air's is ULV with a really slow clock, also the sdd in the base version is only 64g which is going to be cramped, I think.


问:
what's the relationship between /dev/tty and stdin/stdout/stderr?
I know they have different file descriptors, stdxx can be redirected.

```<code>int tty_fd = open("/dev/tty", O_RDWR);
</code>```

So, what's the difference in the codes below(stdxx not redirected):

```<code>n = read(tty_fd, buf, sizeof(buf));
n = read(STDIN_FILENO, buf, sizeof(buf));

n = write(tty_fd, buf, sizeof(buf));
n = write(STDOUT_FILENO, buf, sizeof(buf));
</code>```

is stdxx same as a link to /dev/tty ?

答: Unless there is no redirection "/dev/tty" would be used to display both the standard-output or standard-error. You can selectively output your stdout/stderr onto different file descriptors other than /dev/tty.</p>

Body:
I know they have different file descriptors, stdxx can be redirected.

int tty_fd = open("/dev/tty", O_RDWR);

So, what's the difference in the codes below(stdxx not redirected):

n = read(tty_fd, buf, sizeof(buf));
n = read(STDIN_FILENO, buf, sizeof(buf));

n = write(tty_fd, buf, sizeof(buf));
n = write(STDOUT_FILENO, buf, sizeof(buf));

is stdxx same as a link to /dev/tty ?


问:
Getting unique values in Excel by using formulas only
Do you know a way in Excel to "calculate" by formula a list of unique values ?

E.g: a vertical range contains values "red", "blue", "red", "green", "blue", "black"

and I want to have as result "red, "blue", "green", "black" + eventually 2 other blank cells.

I already found a way to get a calculated sorted list using SMALL or LARGE combined with INDEX, but I'd like to have this calculated sort as well, WITHOUT USING VBA.

答: Resorting to a PivotTable might not count as using formulas only but seems more practical that most other suggestions so far:


问:
How can I do the opposite .include?
So the goal here is to print the index of the element if the element is in the array or print -1 if the element is not in the array. I have to do this using loops. PLEASE HELP!</p>

```<code>def element_index(element, my_array)
  while my_array.map.include? element do
    puts my_array.index(element)
    break
  end

  until my_array.include? element do
    puts -1
    break
  end
end

p element_index("c", ["a","b","c"])
</code>```

答:
If it's OK to use Array#index, then

```<code>def element_index(elem, collection)
  collection.index(elem) || -1
end
</code>```

Or if it's a homework that you should not use Array#index, or you want to do this on arbitrary collections, then

```<code>def element_index(elem, collection)
  collection.each_with_index.reduce(-1) do |default, (curr, index)|
    curr == elem ? (return index) : default
  end
end
</code>```

By the way, I always turn to Enumerable#reduce when I want to iterate over a collection (array, map, set, ...) to compute one value.

Title: How can I do the opposite .include?

Body:
So the goal here is to print the index of the element if the element is in the array or print -1 if the element is not in the array. I have to do this using loops. PLEASE HELP!

def element_index(element, my_array)
  while my_array.map.include? element do
    puts my_array.index(element)
    break
  end

  until my_array.include? element do
    puts -1
    break
  end
end

p element_index("c", ["a","b","c"])

Body:
If it's OK to use Array#index, then

def element_index(elem, collection)
  collection.index(elem) || -1
end

Or if it's a homework that you should not use Array#index, or you want to do this on arbitrary collections, then

def element_index(elem, collection)
  collection.each_with_index.reduce(-1) do |default, (curr, index)|
    curr == elem ? (return index) : default
  end
end

By the way, I always turn to Enumerable#reduce when I want to iterate over a collection (array, map, set, ...) to compute one value.


问:
How do I update/upsert a document in Mongoose?
Perhaps it's the time, perhaps it's me drowning in sparse documentation and not being able to wrap my head around the concept of updating in Mongoose :)

Here's the deal:

I have a contact schema and model (shortened properties):

```<code>var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var mongooseTypes = require("mongoose-types"),
    useTimestamps = mongooseTypes.useTimestamps;

var ContactSchema = new Schema({
    phone: {
        type: String,
        index: {
            unique: true,
            dropDups: true
        }
    },
    status: {
        type: String,
        lowercase: true,
        trim: true,
        default: 'on'
    }
});
ContactSchema.plugin(useTimestamps);
var Contact = mongoose.model('Contact', ContactSchema);
</code>```

I receive a request from the client, containing the fields I need and use my model thusly:

```<code>mongoose.connect(connectionString);
var contact = new Contact({
    phone: request.phone,
    status: request.status
});
</code>```

And now we reach the problem:

If I call contact.save(function(err){...}) I'll receive an error if the contact with the same phone number already exists (as expected - unique)

I can't call update() on contact, since that method does not exist on a document

If I call update on the model:

Contact.update({phone:request.phone}, contact, {upsert: true}, function(err{...})

I get into an infinite loop of some sorts, since the Mongoose update implementation clearly doesn't want an object as the second parameter.

If I do the same, but in the second parameter I pass an associative array of the request properties {status: request.status, phone: request.phone ...} it works - but then I have no reference to the specific contact and cannot find out its createdAt and updatedAt properties.

So the bottom line, after all I tried: given a document contact, how do I update it if it exists, or add it if it doesn't?

Thanks for your time.

答:
Here's the simplest way to create/update while also calling the middleware and validators.</p>

```<code>Contact.findOne({ phone: request.phone }, (err, doc) => {
    const contact = (doc) ? doc.set(request) : new Contact(request);

    contact.save((saveErr, savedContact) => {
        if (saveErr) throw saveErr;
        console.log(savedContact);
    });
})
</code>```

Body:
Perhaps it's the time, perhaps it's me drowning in sparse documentation and not being able to wrap my head around the concept of updating in Mongoose :)

Here's the deal:

I have a contact schema and model (shortened properties):

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var mongooseTypes = require("mongoose-types"),
    useTimestamps = mongooseTypes.useTimestamps;

var ContactSchema = new Schema({
    phone: {
        type: String,
        index: {
            unique: true,
            dropDups: true
        }
    },
    status: {
        type: String,
        lowercase: true,
        trim: true,
        default: 'on'
    }
});
ContactSchema.plugin(useTimestamps);
var Contact = mongoose.model('Contact', ContactSchema);

I receive a request from the client, containing the fields I need and use my model thusly:

mongoose.connect(connectionString);
var contact = new Contact({
    phone: request.phone,
    status: request.status
});

And now we reach the problem:

If I call contact.save(function(err){...}) I'll receive an error if the contact with the same phone number already exists (as expected - unique)

I can't call update() on contact, since that method does not exist on a document

If I call update on the model:

Contact.update({phone:request.phone}, contact, {upsert: true}, function(err{...})

I get into an infinite loop of some sorts, since the Mongoose update implementation clearly doesn't want an object as the second parameter.

If I do the same, but in the second parameter I pass an associative array of the request properties {status: request.status, phone: request.phone ...} it works - but then I have no reference to the specific contact and cannot find out its createdAt and updatedAt properties.

So the bottom line, after all I tried: given a document contact, how do I update it if it exists, or add it if it doesn't?

Thanks for your time.

Body:
Here's the simplest way to create/update while also calling the middleware and validators.

Contact.findOne({ phone: request.phone }, (err, doc) => {
    const contact = (doc) ? doc.set(request) : new Contact(request);

    contact.save((saveErr, savedContact) => {
        if (saveErr) throw saveErr;
        console.log(savedContact);
    });
})


问:
PHP function to make text from an RSS feed render properly?
I'm pulling some text from an RSS feed and need to wrap it in a PHP function to get it to render right.  The text has been augmented and looks like this:

Reply to this update by 4PM & you're entered to win a pair of tickets to the SOLD OUT 'Twas the Night Before Christmas Tour' featuring Relient K (Acoustic) with Sherwood and Deas Vail show on Friday at 7PM (All Ages). We'll be making our list, checking it twice, etc. at 4PM down in the comments- remember to stop by and see if you've won. Happy Holidays :)

12-17-2010 Relient K Acoustic | Lincoln Hall
www.lincolnhallchicago.com
Lincoln Hall in Chicago, Illinois - Live Music Nightly

I don't know what to call the formatting of this text, but whatever it is, I don't want it to display this way, I want it to display as properly readable, rendered HTML.

Can someone point me to the right resources? I don't even know what to google.  Thanks.

答: Run it through htmlspecialchars_decode(). Do note, though, that the onmousedown events are probably going to cause JavaScript errors on your page. You might want to create dummy UntrustedLink.bootstrap functions that do nothing.


问:
How to create dialogue node in watson conversation through java/ python sdk
I found in conversation SDK how to create entity, intents.But did not find any API to create dialogue node. Can anyone help me out with proper documentation?
I also posted a question in Watson-developer-cloud.

Thanks in advance

答:
The easiest way to create a dialog node is to create sample nodes you want in the conversation tooling.

Then using the workspace API you can export those nodes, and use them as a baseline to create others.

Looking at the Java SDK you would use updateWorkspace() method to push your changes to the workspace.


问:
How to import javax.faces library in Eclipse using JDK8?
Based on the advice to use JSF, the following sample would like to be run in order to learn more about JSF and to implement this technique into the servlet. However, a number of libraries is unable to be imported:

```<code>package tobedefinedservlet;

import javax.faces.bean.ManagedBean;

@ManagedBean
public class Hello {

    final String world = "Hello World!";

    public String getworld() {
        return world;
    }
}
</code>```

javax.faces

The import javax.faces cannot be resolved

ManagedBean

ManagedBean cannot be resolved to a type

答:
If you're using maven for build automation, add the latest jsf-api dependency to your pom.xml:

```<code><dependency>
    <groupId>javax.faces</groupId>
    <artifactId>jsf-api</artifactId>
    <version>2.1</version>
</dependency>
</code>```

Or the latest javax.faces-api implementation:

```<code><dependency>
  <groupId>javax.faces</groupId>
  <artifactId>javax.faces-api</artifactId>
  <version>2.3</version>
</dependency>
</code>```

However, note that JSF is integrated into most Java EE application servers, such as JBoss.

See also this answer.

Body:
Based on the advice to use JSF, the following sample would like to be run in order to learn more about JSF and to implement this technique into the servlet. However, a number of libraries is unable to be imported:

package tobedefinedservlet;

import javax.faces.bean.ManagedBean;

@ManagedBean
public class Hello {

    final String world = "Hello World!";

    public String getworld() {
        return world;
    }
}

javax.faces

The import javax.faces cannot be resolved

ManagedBean

ManagedBean cannot be resolved to a type

Body:
If you're using maven for build automation, add the latest jsf-api dependency to your pom.xml:

<dependency>
    <groupId>javax.faces</groupId>
    <artifactId>jsf-api</artifactId>
    <version>2.1</version>
</dependency>

Or the latest javax.faces-api implementation:

<dependency>
  <groupId>javax.faces</groupId>
  <artifactId>javax.faces-api</artifactId>
  <version>2.3</version>
</dependency>

However, note that JSF is integrated into most Java EE application servers, such as JBoss.

See also this answer.


问:
Expose access and assignment operator from private vector
I am working in a code in C++ where a class that I created stores a vector of boost/dynamic_bitset as a private field. I need to be able to access and modify any position in the vector to do bitset operations (&, |, ^, ...).

It's possible to expose the vector assignment (=) and access([]) operators without having to reimplement them? Just like I did with iterators.

Here is the header:

```<code>class graph{
  typedef vector<boost::dynamic_bitset<>> tgraph;

  node person;
  tgraph gg;

 public:
  graph();
  graph(const uint person, const uint max_days, const uint max_nodes);

  void add_encounter_index(const node);
  void add_encounter_index(const node, const node, const node);

  void dump(ofstream& f, const vector<encounter>&);

  // iterators
  using iterator = tgraph::iterator;
  // using pointer = tgraph::value_type;
  using reference = tgraph::reference;
  // using value_type = tgraph::value_type;

  using const_iterator = tgraph::const_iterator;
  using const_reference = tgraph::const_reference;

  iterator begin() { return gg.begin(); }
  iterator end() { return gg.end(); }

  const_iterator begin() const { return gg.begin(); }
  const_iterator end() const { return gg.end(); }
  const_iterator cbegin() const { return gg.cbegin(); }
  const_iterator cend() const { return gg.cend(); }

};
</code>```

答:
You can overload operator[] for graph so that it resolves to a reference to the vector element, e.g.:

```<code>// Inline member function
auto& operator[](size_t index)
{
    return gg[i];
}
</code>```

(In older versions of C++ you'll need to specify the dynamic_bitset type instead of auto).  This enables you to use:

```<code>graph1[i] = dynamic_bitset<>(size);
</code>```

and other such statements.  You could overload operator=, but that applies to the usage graph1 =, and it can get confusing to overload this operator to do something different to its default behaviour. So if just the operator[] overload suits your requirements then I'd recommend just doing that one.

Body:
I am working in a code in C++ where a class that I created stores a vector of boost/dynamic_bitset as a private field. I need to be able to access and modify any position in the vector to do bitset operations (&, |, ^, ...).

It's possible to expose the vector assignment (=) and access([]) operators without having to reimplement them? Just like I did with iterators.

Here is the header:

class graph{
  typedef vector<boost::dynamic_bitset<>> tgraph;

  node person;
  tgraph gg;

 public:
  graph();
  graph(const uint person, const uint max_days, const uint max_nodes);

  void add_encounter_index(const node);
  void add_encounter_index(const node, const node, const node);

  void dump(ofstream& f, const vector<encounter>&);

  // iterators
  using iterator = tgraph::iterator;
  // using pointer = tgraph::value_type;
  using reference = tgraph::reference;
  // using value_type = tgraph::value_type;

  using const_iterator = tgraph::const_iterator;
  using const_reference = tgraph::const_reference;

  iterator begin() { return gg.begin(); }
  iterator end() { return gg.end(); }

  const_iterator begin() const { return gg.begin(); }
  const_iterator end() const { return gg.end(); }
  const_iterator cbegin() const { return gg.cbegin(); }
  const_iterator cend() const { return gg.cend(); }

};

Body:
You can overload operator[] for graph so that it resolves to a reference to the vector element, e.g.:

// Inline member function
auto& operator[](size_t index)
{
    return gg[i];
}

(In older versions of C++ you'll need to specify the dynamic_bitset type instead of auto).  This enables you to use:

graph1[i] = dynamic_bitset<>(size);

and other such statements.  You could overload operator=, but that applies to the usage graph1 =, and it can get confusing to overload this operator to do something different to its default behaviour. So if just the operator[] overload suits your requirements then I'd recommend just doing that one.


问:
bootstrap nested row issue not in one row
i want picture and L1 and L2 be in one row ...
but L2 always in botton of picture ...
why ?
i think my nested row is correct ... is that OK ?

```<code><!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>appLanding</title>
    <link href="../css/bootstrap.css" rel="stylesheet">

</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-xs-1">
            <img src="face-03.jpg" class="img-rounded img-responsive" style="margin-top: 4%">
        </div>
        <div class="col-xs-9 col-xs-offset-2">
            <div class="row">
                <div class="col-xs-12">L1</div>
            </div>
            <div class="row">
                <div class="col-xs-12">L2</div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-xs-12" dir="rtl">
            <div style="height:120px;width:100%;overflow:auto;padding: 1%">
                As you can see, once there's enough text in this box, the box will grow scroll bars... that's why we
                call it a scroll box! You could also place an image into the scroll box.
            </div>
        </div>
    </div>
</div>
</body>
</html>
</code>```

答:
Looks like you want to be using more of the Bootstrap Media Alignment.

Here is a fiddle to review the code you provided, but modified using the Bootstrap Media Alignment.

Notice the img-responsive class has been removed. If added it floats the rows to the left.

Let me know if that helps.

.top {
  margin-top: 10px;
}
#no-inline-styles {
  height:120px;
  width:100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<!-- EXAMPLE CODE STARTS -->

<div class="container top">
<div class="media">
  <div class="media-left">
      <img class="media-object img-rounded" src="http://via.placeholder.com/140x100" alt="...">
  </div>
  <div class="media-body">
    <div class="row">
      <div class="col-md-6">
        <h3>L1</h3>
      </div>
    </div>
       <div class="row">
      <div class="col-md-6">
        <h3>L2</h3>
      </div>
    </div>
    <div id="no-inline-styles">
                As you can see, once there's enough text in this box, the box will grow scroll bars... that's why we
                call it a scroll box! You could also place an image into the scroll box.
            </div>
  </div>
</div>

</div>

<!-- EXAMPLE CODE ENDS -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script></code>```

Body:
i want picture and L1 and L2 be in one row ...
but L2 always in botton of picture ...
why ?
i think my nested row is correct ... is that OK ?

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>appLanding</title>
    <link href="../css/bootstrap.css" rel="stylesheet">

L1

L2

                As you can see, once there's enough text in this box, the box will grow scroll bars... that's why we
                call it a scroll box! You could also place an image into the scroll box.

Body:
Looks like you want to be using more of the Bootstrap Media Alignment.

Here is a fiddle to review the code you provided, but modified using the Bootstrap Media Alignment.

Notice the img-responsive class has been removed. If added it floats the rows to the left.

Let me know if that helps.

.top {
  margin-top: 10px;
}
#no-inline-styles {
  height:120px;
  width:100%;
}

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

<!-- EXAMPLE CODE STARTS -->

<div class="container top">
<div class="media">
  <div class="media-left">
      <img class="media-object img-rounded" src="http://via.placeholder.com/140x100" alt="...">
  </div>
  <div class="media-body">
    <div class="row">
      <div class="col-md-6">
        <h3>L1</h3>
      </div>
    </div>
       <div class="row">
      <div class="col-md-6">
        <h3>L2</h3>
      </div>
    </div>
    <div id="no-inline-styles">
                As you can see, once there's enough text in this box, the box will grow scroll bars... that's why we
                call it a scroll box! You could also place an image into the scroll box.
            </div>
  </div>
</div>

</div>

<!-- EXAMPLE CODE ENDS -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>


问:
Is it a good idea to use Workers for checking events?
I mean, let's say an User signs up and buy a monthly membership. Is it a good idea set a job to run in a month to see if the user renewed his membership and take appropriate actions? Is there a better or a more "Railsy" way?</p>

答:
I would put it in a rake job that you execute daily (or hourly on heroku or whatever).</p>

```<code>task :cron => :environment do
  desc "Daily and Monthly tasks tasks"

  # monthly tasks
  if Date.today.day == 1
    puts "monthly status check - #{Time.now}"
    Rake::Task["your_task"].invoke
  end
end
</code>```

Body:
I would put it in a rake job that you execute daily (or hourly on heroku or whatever).

task :cron => :environment do
  desc "Daily and Monthly tasks tasks"

  # monthly tasks
  if Date.today.day == 1
    puts "monthly status check - #{Time.now}"
    Rake::Task["your_task"].invoke
  end
end


问:
force browser to reload page(ignore cache)
When i setup static resources like js,css,templates on my web server, i forget to set cache period for them. by default web server set it "cache forever" (this is tomcat server and spring mvc)

```<code><mvc:resources mapping="/resources/**" location="/resources/" />
</code>```

if dont specify cache-period then server will send headers like "cache it forever".
now i try different ways to solve this:

try to change static resource url

```<code>mvc:resources mapping="/static/**" location="/resources/" cache-period="10800"
</code>```

but this does not help(i think that browser cache the whole html page, but it does not)

i try to force reloading page using JS:

location.reload(true)

but this does not help much to

how can i force browser to reload cached files?
P.S. i dont send any cache headers to cache my html pages

答:
You can append a version number to the URL

```<code>http://mydomin.com/resources/file.css?version=1
</code>```

For example;

```<code><html>
    <head>
        <link href="resources/file.css?version=1" type="text/css" rel="stylesheet"/>
    <head>
    <body></body>
</html>
</code>```

Body:
When i setup static resources like js,css,templates on my web server, i forget to set cache period for them. by default web server set it "cache forever" (this is tomcat server and spring mvc)

<mvc:resources mapping="/resources/**" location="/resources/" />

if dont specify cache-period then server will send headers like "cache it forever".
now i try different ways to solve this:

try to change static resource url

mvc:resources mapping="/static/**" location="/resources/" cache-period="10800"

but this does not help(i think that browser cache the whole html page, but it does not)

i try to force reloading page using JS:

location.reload(true)

but this does not help much to

how can i force browser to reload cached files?
P.S. i dont send any cache headers to cache my html pages

Body:
You can append a version number to the URL

http://mydomin.com/resources/file.css?version=1

For example;

<html>
    <head>
        <link href="resources/file.css?version=1" type="text/css" rel="stylesheet"/>
    <head>
    <body></body>
</html>


问:
Python Sum of Linked List
These are my code

```<code>class Node():
'''A node in a linked list'''
    def __init__(self, data, next_node=None):
        self.data = data
        self.next_node = next_node

def sum(LL):

    head = LL

    # If Linked list is empty, return 0
    if (head.data is None or head.data == []):
        result = 0

    # If Linked List contain only 1 node then return it
    elif (head.next_node is None):
        result = head.data

    else:
        curr = head
        result = curr.data
        # If next is not None then add up to result
        while (curr.next_node is not None):
            curr = curr.next_node
            result += curr.data

    return result
</code>```

Problem is at the end of the code

```<code>while (curr.next_node is not None):
    curr = curr.next_node
    result += curr.data
</code>```

If i try this

```<code>LL = Node(1, Node(2, 3))
sum(LL)
</code>```

I don't understand why it said

builtins.AttributeError: 'int' object has no attribute 'data'

The while loop works until it reach the last node

result should be 6

答:
Because 3 is your next node. You probably wanted something like:

```<code>LL = Node(1, Node(2, Node(3)))
</code>```

Title: Python Sum of Linked List

Body:
These are my code

class Node():
'''A node in a linked list'''
    def __init__(self, data, next_node=None):
        self.data = data
        self.next_node = next_node

def sum(LL):

    head = LL

    # If Linked list is empty, return 0
    if (head.data is None or head.data == []):
        result = 0

    # If Linked List contain only 1 node then return it
    elif (head.next_node is None):
        result = head.data

    else:
        curr = head
        result = curr.data
        # If next is not None then add up to result
        while (curr.next_node is not None):
            curr = curr.next_node
            result += curr.data

    return result

Problem is at the end of the code

while (curr.next_node is not None):
    curr = curr.next_node
    result += curr.data

If i try this

LL = Node(1, Node(2, 3))
sum(LL)

I don't understand why it said

builtins.AttributeError: 'int' object has no attribute 'data'

The while loop works until it reach the last node

result should be 6

Body:
Because 3 is your next node. You probably wanted something like:

LL = Node(1, Node(2, Node(3)))


问:
Make a makefile for cjson code with -lcjson for json parser in c
I'm very new to the makefiles. I'm compiling the c code file which contains cJson library from terminal using command

```<code>gcc -test1.c -o test -lcjson
</code>```

with -lcjson at last and its running perfectly. But how to compile the same code using makefile as I have to add -lcjson at last.
if I'm using without -lcjson I'm getting error

```<code>/tmp/cc4ESrx1.o: In function `parse_json':
test1.c:(.text+0x2d): undefined reference to `cJSON_Parse'
test1.c:(.text+0x42): undefined reference to `cJSON_GetObjectItem'
test1.c:(.text+0x59): undefined reference to `cJSON_GetObjectItem'
collect2: error: ld returned 1 exit status
</code>```

I'm using a RTOS code

thanks in advance

答:
First, avoid naming your executable test since it is a standard program name (at least on POSIX).

Then, read documentation of GNU make. It contains a tutorial section.

At last, GNU make has several built-in rules, which you can get with make -p

See this answer for an example.

I strongly recommend compiling with all warnings and debug info (that is, with gcc -Wall -Wextra -g if using GCC). So put CFLAGS+= -Wall -Wextra -g and CC=gcc in your Makefile.

To link with your -lcjson  add LIBES+= -lcjson in your Makefile. Remember that tab characters are important in a Makefile (so use some editor, e.g. emacs, able to edit them).

So try:

```<code># your Makefile, replace four spaces with tab
CC= gcc
CFLAGS+= -Wall -Wextra -g
RM= rm -f
MY_SOURCES=$(wildcard *.c)
## above could be an MY_SOURCES= file1.c file2.c otherfile.c
MY_OBJECTS=$(patsubst %.c,%.o,$(MY_SOURCES))
#
LIBES= -lcjson
#
.PHONY: all clean
##
all: myprog
##
clean:
     $(RM) myprog *.o *~
myprog: $(MY_OBJECTS)
</code>```

Use make --trace or remake -x to debug your Makefile

If you haver several *.c source files (that is translation units) linked together into the same program, you should have a common header file myheader.h (to share common declarations of all your public functions and variables) which should be #include-ed in every source file. Then you need to depend on it:

```<code> MY_HEADER= myheader.h
 %.o: %.c $(MY_HEADER)
</code>```

Notice that (with or without any Makefile) the order of program arguments to gcc is very significant. See this.

Body:
I'm very new to the makefiles. I'm compiling the c code file which contains cJson library from terminal using command

gcc -test1.c -o test -lcjson

with -lcjson at last and its running perfectly. But how to compile the same code using makefile as I have to add -lcjson at last.
if I'm using without -lcjson I'm getting error

/tmp/cc4ESrx1.o: In function `parse_json':
test1.c:(.text+0x2d): undefined reference to `cJSON_Parse'
test1.c:(.text+0x42): undefined reference to `cJSON_GetObjectItem'
test1.c:(.text+0x59): undefined reference to `cJSON_GetObjectItem'
collect2: error: ld returned 1 exit status

I'm using a RTOS code

thanks in advance

Body:
First, avoid naming your executable test since it is a standard program name (at least on POSIX).

Then, read documentation of GNU make. It contains a tutorial section.

At last, GNU make has several built-in rules, which you can get with make -p

See this answer for an example.

I strongly recommend compiling with all warnings and debug info (that is, with gcc -Wall -Wextra -g if using GCC). So put CFLAGS+= -Wall -Wextra -g and CC=gcc in your Makefile.

To link with your -lcjson  add LIBES+= -lcjson in your Makefile. Remember that tab characters are important in a Makefile (so use some editor, e.g. emacs, able to edit them).

So try:

# your Makefile, replace four spaces with tab
CC= gcc
CFLAGS+= -Wall -Wextra -g
RM= rm -f
MY_SOURCES=$(wildcard *.c)
## above could be an MY_SOURCES= file1.c file2.c otherfile.c
MY_OBJECTS=$(patsubst %.c,%.o,$(MY_SOURCES))
#
LIBES= -lcjson
#
.PHONY: all clean
##
all: myprog
##
clean:
     $(RM) myprog *.o *~
myprog: $(MY_OBJECTS)

Use make --trace or remake -x to debug your Makefile

If you haver several *.c source files (that is translation units) linked together into the same program, you should have a common header file myheader.h (to share common declarations of all your public functions and variables) which should be #include-ed in every source file. Then you need to depend on it:

 MY_HEADER= myheader.h
 %.o: %.c $(MY_HEADER)

Notice that (with or without any Makefile) the order of program arguments to gcc is very significant. See this.


问:
How to check azure storage availability through SDK or Rest API?
In my application im trying to get the metrics of azure storage i.e metrics for each of its services(blob,queue,file,table) but before trying to get the metrics i want to check the availability of the storage ,can i do that please suggest.

i want to check if the storage status if its up or down before collecting metrics via SDK

答:
One way of doing it is to invoke the Metadata Rest API's for each of those storage services (blob, queue, table and file). You can go through below links to see the REST API specification that returns the metadata.

Storage - https://learn.microsoft.com/en-us/rest/api/storageservices/setting-and-retrieving-properties-and-metadata-for-blob-resources

Queue - https://learn.microsoft.com/en-us/rest/api/storageservices/get-queue-metadata

Table - https://learn.microsoft.com/en-us/rest/api/storageservices/get-table-service-properties

File - https://learn.microsoft.com/en-us/rest/api/storageservices/get-directory-metadata


问:
How do you call a function once a day at a certain time in c++?
Well i need to figure out how to call a function at a certain time if my application is running.

it will probably be in a while loop and check the time but i don't want it to check the time every minute but i don't want it to miss the exact time, say 18:00.

is there any way do to this?

答:
EDIT: I don't know why I assumed this was Windows.  I don't see anywhere that it says so.  The API info below is only applicable for Windows but the principle is the same.  Boost.Asio has portable async timers, if not Windows.

Windows Info : When your app starts up, check the interval remaining to your desired event and start a Timer Queue Timer to pop at the appropriate time.  The timer will pop after an initial interval, and then repeatedly after a periodic interval.

CreateTimerQueueTimer Function

Creates a timer-queue timer. This
  timer expires at the specified due
  time, then after every specified
  period. When the timer expires, the
  callback function is called.

Much more efficient to make this event-driven than to periodically check the clock.