text:
Q: Convergence in probability vs. almost sure convergence I've never really grokked the difference between these two measures of convergence. (Or, in fact, any of the different types of convergence, but I mention these two in particular because of the Weak and Strong Laws of Large Numbers.)
Sure, I can quote the definition of each and give an example where they differ, but I still don't quite get it.
What's a good way to understand the difference? Why is the difference important? Is there a particularly memorable example where they differ?

A: I understand it as follows,
Convergence in probability
The probability that the sequence of random variables equals the target value is asymptotically decreasing and approaches 0 but never actually attains 0.
Almost Sure Convergence
The sequence of random variables will equal the target value asymptotically but you cannot predict at what point it will happen.
Almost sure convergence is a stronger condition on the behavior of a sequence of random variables because it states that "something will definitely happen" (we just don't know when). In contrast, convergence in probability states that "while something is likely to happen" the likelihood of "something not happening" decreases asymptotically but never actually reaches 0. (something $\equiv$ a sequence of random variables converging to a particular value).
The wiki has some examples of both which should help clarify the above (in particular see the example of the archer in the context of convergence in prob and the example of the charity in the context of almost sure convergence).
From a practical standpoint, convergence in probability is enough as we do not particularly care about very unlikely events. As an example, consistency of an estimator is essentially convergence in probability. Thus, when using a consistent estimate, we implicitly acknowledge the fact that in large samples there is a very small probability that our estimate is far from the true value. We live with this 'defect' of convergence in probability as we know that asymptotically the probability of the estimator being far from the truth is vanishingly small.

A: If you enjoy visual explanations, there was a nice 'Teacher's Corner' article on this subject in the American Statistician (cite below).  As a bonus, the authors included an R package to facilitate learning.
@article{lafaye09,
  title={Understanding Convergence Concepts: A Visual-Minded and Graphical Simulation-Based Approach},
  author={Lafaye de Micheaux, P. and Liquet, B.},
  journal={The American Statistician},
  volume={63},
  number={2},
  pages={173--178},
  year={2009},
  publisher={ASA}
}

A: I know this question has already been answered (and quite well, in my view), but there was a different question here which had a comment @NRH that mentioned the graphical explanation, and rather than put the pictures there it would seem more fitting to put them here.
So, here goes.  It's not as cool as an R package.  But it's self-contained and doesn't require a subscription to JSTOR.
In the following we're talking about a simple random walk, $X_{i}= \pm 1$ with equal probability, and we are calculating running averages,
$$
\frac{S_{n}}{n} = \frac{1}{n}\sum_{i = 1}^{n}X_{i},\quad n=1,2,\ldots.
$$

The SLLN (convergence almost surely) says that we can be 100% sure that this curve stretching off to the right will eventually, at some finite time, fall entirely within the bands forever afterward (to the right).
The R code used to generate this graph is below (plot labels omitted for brevity).
n <- 1000;  m <- 50; e <- 0.05
s <- cumsum(2*(rbinom(n, size=1, prob=0.5) - 0.5))
plot(s/seq.int(n), type = "l", ylim = c(-0.4, 0.4))
abline(h = c(-e,e), lty = 2)

The WLLN (convergence in probability) says that a large proportion of the sample paths will be in the bands on the right-hand side, at time $n$ (for the above it looks like around 48 or 9 out of 50).  We can never be sure that any particular curve will be inside at any finite time, but looking at the mass of noodles above it'd be a pretty safe bet.  The WLLN also says that we can make the proportion of noodles inside as close to 1 as we like by making the plot sufficiently wide.
The R code for the graph follows (again, skipping labels).
x <- matrix(2*(rbinom(n*m, size=1, prob=0.5) - 0.5), ncol = m)
y <- apply(x, 2, function(z) cumsum(z)/seq_along(z))
matplot(y, type = "l", ylim = c(-0.4,0.4))
abline(h = c(-e,e), lty = 2, lwd = 2)

A: One thing that helped me to grasp the difference is the following equivalence
$$P\left({\lim_{n\to\infty}|X_n-X|=0}\right) = 1 \iff \lim_{n\to\infty} P\left({\sup_{m\geq n}|X_m-X|>\epsilon }\right) = 0  ~\forall \epsilon > 0.$$
In comparison stochastic convergence:
$$\lim_{n\to\infty}P(|X_n-X|>\epsilon) = 0   ~\forall \epsilon >0.$$
When comparing the right side of the upper equivalence with the stochastic convergence, the difference becomes clearer, I think.

A: From my point of view the difference is important, but largely for philosophical reasons.  Assume you have some device, that improves with time.  So, every time you use the device the probability of it failing is less than before.
Convergence in probability says that the chance of failure goes to zero as the number of usages goes to infinity.  So, after using the device a large number of times, you can be very confident of it working correctly, it still might fail, it's just very unlikely.
Convergence almost surely is a bit stronger.  It says that the total number of failures is finite. That is, if you count the number of failures as the number of usages goes to infinity, you will get a finite number.  The impact of this is as follows:  As you use the device more and more, you will, after some finite number of usages, exhaust all failures.  From then on the device will work perfectly.
As Srikant points out, you don't actually know when you have exhausted all failures, so from a purely practical point of view, there is not much difference between the two modes of convergence.
However, personally I am very glad that, for example, the strong law of large numbers exists, as opposed to just the weak law.  Because now, a scientific experiment to obtain, say, the speed of light, is justified in taking averages.  At least in theory, after obtaining enough data, you can get arbitrarily close to the true speed of light.  There wont be any failures (however improbable) in the averaging process.
Let me clarify what I mean by ''failures (however improbable) in the averaging process''.  Choose some $\delta > 0$ arbitrarily small. You obtain $n$ estimates $X_1,X_2,\dots,X_n$ of the speed of light (or some other quantity) that has some `true' value, say $\mu$. You compute the average
$$S_n = \frac{1}{n}\sum_{k=1}^n X_k.$$
As we obtain more data ($n$ increases) we can compute $S_n$ for each $n = 1,2,\dots$.  The weak law says (under some assumptions about the $X_n$) that the probability
$$P(|S_n - \mu| > \delta) \rightarrow 0$$
as $n$ goes to $\infty$. The strong law says that the number of times that $|S_n - \mu|$ is larger than $\delta$ is finite (with probability 1).  That is, if we define the indicator function $I(|S_n - \mu| > \delta)$ that returns one when $|S_n - \mu| > \delta$ and zero otherwise, then
$$\sum_{n=1}^{\infty}I(|S_n - \mu| > \delta)$$
converges. This gives you considerable confidence in the value of $S_n$, because it guarantees (i.e. with probability 1) the existence of some finite $n_0$ such that $|S_n - \mu| < \delta$ for all $n > n_0$ (i.e. the average never fails for $n > n_0$).  Note that the weak law gives no such guarantee.

A: This last guy explains it very well.  If you take a sequence of random variables Xn= 1 with probability 1/n  and zero otherwise.  It is easy to see taking limits that this converges to zero in probability, but fails to converge almost surely.  As he said, probability doesn't care that we might get a one down the road.  Almost surely does.
Almost surely implies convergence in probability, but not the other way around yah?


text:
Q: why does range-v3 yield require default constructor I am trying to understand, for what reasons does the yield family of functions require that class be default constructible?
In the following example, the vnums1 line compiles only if CNum has a default constructor. The vnums2 line does not require a default constructor.
I am using Visual Studio 2017 and Range-V3-VS2015. Thank you!
#include <range/v3/all.hpp>

struct CNum
{
    // CNum() = default;
    explicit CNum(int num) : m_num(num) {}
    int m_num;
};

int main()
{
    auto ints = ranges::view::ints(0, 10);

    // this compiles only of CNum has a default constructor
    auto vnums1 = ints
        | ranges::view::for_each([](int num) { return ranges::yield_if(num % 2, CNum(num)); })
        | ranges::to_vector;

    // this compiles even if CNum does not have a default constructor
    auto vnums2 = ints
        | ranges::view::remove_if([](int num) { return num % 2 == 0; })
        | ranges::view::transform([](int num) { return CNum(num); })
        | ranges::to_vector;

    return 0;
}

A: We just changed the code to not require DefaultConstructible. git pull and enjoy.

A: The reason you need to default constructor to use ranges::yield_if is that the machinery it uses requires the type to be default constructable.  If we look at the code we have
struct yield_if_fn
{
    template<typename V>
    repeat_n_view<V> operator()(bool b, V v) const
    {
        return view::repeat_n(std::move(v), b ? 1 : 0);
    }
};

/// \relates yield_if_fn
/// \ingroup group-views
RANGES_INLINE_VARIABLE(yield_if_fn, yield_if)

And we can see that it calls view::repeat_n.  Looking at that code we get
repeat_n_view<Val> operator()(Val value, std::ptrdiff_t n) const
{
    return repeat_n_view<Val>{std::move(value), n};
}

And if we look at repeat_n_view we have
// Ordinarily, a view shouldn't contain its elements. This is so that copying
// and assigning ranges is O(1), and also so that in the event of element
// mutation, all the copies of the range see the mutation the same way. The
// repeat_n_view *does* own its lone element, though. This is OK because:
//  - O(N) copying is fine when N==1 as it is in this case, and
//  - The element is immutable, so there is no potential for incorrect
//    semantics.

struct repeat_n_view
  : view_facade<repeat_n_view<Val>, finite>
{
private:
    friend range_access;
    Val value_;
    std::ptrdiff_t n_;

    // ...
public:
    repeat_n_view() = default;
    constexpr repeat_n_view(Val value, std::ptrdiff_t n)
      : value_(detail::move(value)), n_((RANGES_EXPECT(0 <= n), n))
    {}
    constexpr std::size_t size() const
    {
        return static_cast<std::size_t>(n_);
    }
};

We see from the comment that this was a design decision and because of this design you need your type to be default constructable.  Eric describes the type required as being SemiRegular which is documented as

it needs to be default constructable, copy and move constructable, and destructable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does this split not work? Why does this split not work? When I run the code split_1 is not printed.
with open ('r_3exp', 'a+') as file_1:
 choice = input ('1 (write) or 2? ')
 number = input ('What number?')

 if choice == '1':
    file_1.write ('\n')
    file_1.write ('Here are some numbers : 1233 8989' + ' ' + number)
 else:
    for line in file_1:
        split_1 = line.split (":")
        print (split_1)

A: This is because you are opening your file up in a+ mode.
a+ allows for both reading and appending to a file. On the surface, this sounds ideal for what you want. However, there are some subtle tricky mechanics you've missed about this mode:

*

*A file opened in a+ is automatically opened at the end of the file. In other words, you are no longer reading from the beginning of the file, but rather starting from the very end of it.

*As a consequence, when you do for line in file_1, you are actually starting to read from the character at the very end of the file. Since there is, by definition, nothing there, line returns an empty string and line.split(':') is also empty.
To correct this, it is more prudent to reorganise your code a little to use either r mode or a mode:
choice = input("1 (write) or 2? ")
if choice == "1":
    number = input("What number? ")
    with open("r_3exp","a") as file_1:
        file_1.write ('\n')
        file_1.write ('Here are some numbers : 1233 8989' + ' ' + number)
elif choice == "2":
    with open("r_3exp","r") as file_1:
        for line in file_1:
            split_1 = line.split (":")
            print (split_1)

r opens up your file to start reading from the first character of the file, rather than from the last.

I would still recommend the above code for someone using Python 2.7, but with one additional caveat: input() returns None in Python 2.7, because it's actually evaluating the input as a Python command. The correct function to use in Python 2.7 is raw_input(), which correctly returns a string.


text:
Q: How to verify ownership of a Google Apps Script in Webmaster I am trying to write a script and use it as a Webhook listener for gmail pub/sub notifications.
Therefore, I would need to verify the domain associated with the script in domain verification in API&Services.
However, a modal asks me to verify the domain's ownership on webmaster.
I have tried to add the google-site-verification using the following dotGet function in google apps script and can see the tag in the head:
function doGet(e) { return HtmlService.createHtmlOutputFromFile('index.html').setTitle("Hello World").addMetaTag('google-site-verification', 'verification-code'); }
However, the Webmaster verification does not go through and it shows that it found a different verification code.


text:
Q: Exclude nodes based on attribute wildcard in XSL node selection Using cruisecontrol for continuous integration, I have some annoyances with Weblogic Ant tasks and how they think that server debug information are warnings rather than debug, so are shown in my build report emails. The XML output from cruise is similar to:
<cruisecontrol>
<build>
    <target name="compile-xxx">
        <task name="xxx" />
    </target>
    <target name="xxx.weblogic">
        <task name="wldeploy">
            <message priority="warn">Message which isn't really a warning"</message>
        </task>
    </target>
</build>
</cruisecontrol>

In the cruisecontrol XSL template the current selection for the task list is:
<xsl:variable name="tasklist" select="/cruisecontrol/build//target/task"/>

What I would like is something which selects the tasklist in the same way, but doesn't include any target nodes which have the attribute name="*weblogic" where * is a wildcard. I have tried
<xsl:variable name="tasklist" select="/cruisecontrol/build//target[@name!='*weblogic']/task"/>

but this doesn't seem to have worked. I'm not an expert with XSLT, and just want to get this fixed so I can carry on the real development of the project. Any help is much appreciated.

A:
In the cruisecontrol XSL template the
  current selection for the task list
  is:
<xsl:variable name="tasklist" select="/cruisecontrol/build//target/task"/>

What I would like is something which
  selects the tasklist in the same way,
  but doesn't include any target nodes
  which have the attribute
  name="*weblogic" where * is a wildcard

Use:
  /cruisecontrol/build
                 //target
                     [not(substring(@name, string-length(@name)-7)
                         = 'weblogic'
                          )
                     ]/task


text:
Q: Javascript iterating through array issue I currently have this code:
var values = [
[3.5,3,3.2,3.1,3.6,3.9,3.4,3.4,2.9,3.1,3.7,3.4,3,3,4,4.4,3.9,3.5,3.8,3.8,3.4,3.7,3.6,3.3,3.4,3,3.4,3.5,3.4,3.2,3.1,3.4,4.1,4.2,3.1,3.2,3.5,3.1,3,3.4,3.5,2.3,3.2,3.5,3.8,3,3.8,3.2,3.7,3.3,3.2,3.2,3.1,2.3,2.8,2.8,3.3,2.4,2.9,2.7,2,3,2.2,2.9,2.9,3.1,3,2.7,2.2,2.5,3.2,2.8,2.5,2.8,2.9,3,2.8,3,2.9,2.6,2.4,2.4,2.7,2.7,3,3.4,3.1,2.3,3,2.5,2.6,3,2.6,2.3,2.7,3,2.9,2.9,2.5,2.8,3.3,2.7,3,2.9,3,3,2.5,2.9,2.5,3.6,3.2,2.7,3,2.5,2.8,3.2,3,3.8,2.6,2.2,3.2,2.8,2.8,2.7,3.3,3.2,2.8,3,2.8,3,2.8,3.8,2.8,2.8,2.6,3,3.4,3.1,3,3.1,3.1,3.1,2.7,3.2,3.3,3,2.5,3,3.4,3],
[5.1,4.9,4.7,4.6,5,5.4,4.6,5,4.4,4.9,5.4,4.8,4.8,4.3,5.8,5.7,5.4,5.1,5.7,5.1,5.4,5.1,4.6,5.1,4.8,5,5,5.2,5.2,4.7,4.8,5.4,5.2,5.5,4.9,5,5.5,4.9,4.4,5.1,5,4.5,4.4,5,5.1,4.8,5.1,4.6,5.3,5,7,6.4,6.9,5.5,6.5,5.7,6.3,4.9,6.6,5.2,5,5.9,6,6.1,5.6,6.7,5.6,5.8,6.2,5.6,5.9,6.1,6.3,6.1,6.4,6.6,6.8,6.7,6,5.7,5.5,5.5,5.8,6,5.4,6,6.7,6.3,5.6,5.5,5.5,6.1,5.8,5,5.6,5.7,5.7,6.2,5.1,5.7,6.3,5.8,7.1,6.3,6.5,7.6,4.9,7.3,6.7,7.2,6.5,6.4,6.8,5.7,5.8,6.4,6.5,7.7,7.7,6,6.9,5.6,7.7,6.3,6.7,7.2,6.2,6.1,6.4,7.2,7.4,7.9,6.4,6.3,6.1,7.7,6.3,6.4,6,6.9,6.7,6.9,5.8,6.8,6.7,6.7,6.3,6.5,6.2,5.9]
];
var counter = 0;

function updateGauges() {
    if (counter < values[0].length) {
        for (var key in gauges) {
            gauges[key].redraw(values[key][counter]);
            //gauges[key].redraw(getRandomValue(gauges[key]));
        }
        counter = counter + 1;
    }
    else {
        counter = 0;
        clearInterval(timerid);
    }
}

function getRandomValue(gauge) {
    var overflow = 0; //10;
    return gauge.config.min - overflow + (gauge.config.max - gauge.config.min + overflow*2) *  Math.random();
}

When I try to run this, my D3 gauge doesn't show the values. However, if I replace the uncommented line with the commented line, it runs fine.
Am I not defining my multidimensional array properly?
Thanks


text:
Q: Is there a convention for how Global Descriptor Table entries should be laid out? Is there an agreed upon convention for operating systems specifying what each table index should describe? For example, on Windows systems (as described here), entry 4 describes 32 bit usermode code (RPL = 3), and entry 6 describes 64 bit usermode code. Is this a convention? What about other entries?

A: x86-64 syscall/sysret, and 32-bit sysenter/sysexit, apparently do care about the order of your GDT entries: kernel CS, kernel data, user CS, user data in that order.  (Thanks @Brendan for that detail.)  Or at least, syscall loads fixed values into the CS and SS internal state:

SYSCALL loads the CS and SS selectors with values derived from bits 47:32 of the IA32_STAR MSR. However, the CS and SS descriptor caches are not loaded from the descriptors (in GDT or LDT) referenced by those selectors. Instead, the descriptor caches are loaded with fixed values. See the Operation section for details. It is the responsibility of OS software to ensure that the descriptors (in GDT or LDT) referenced by those selector values correspond to the fixed values loaded into the descriptor caches; the SYSCALL instruction does not ensure this correspondence.

Other than that, the hardware doesn't care; any pattern that makes sense to you is fine if you only use legacy system-call mechanisms like int 0x80.
AFAIK, there's no standard convention across OSes, but it's not something I've looked at.

The entries are probably fetched through cache when the kernel sets them (e.g. on context switches), so there could be a tiny advantage to placing ones used together into the same 64-byte cache line. (Reducing cache misses / number of cache lines of footprint.)  Especially for 32-bit user-space if you can't just use the null selector (0) for their SS/DS/ES.
But if the whole GDT is 8 entries or less, the whole thing fits in one cache line (if you align the start by 64).  Older CPUs (before Pentium 4 / Core 2) had 32-byte cache lines, but those didn't support 64-bit mode so fewer GDT entries were needed.
Note that the index 0 will never actually be accessed by the CPU, so you can align the first "real" GDT entry and lgdt with that address minus 8.  (The "null descriptor" is a special case.)


text:
Q: Postgres audit trigger only fired by one row UPDATE Hi I'm up to develop a simple audit trigger for postgresql server. According to this document, I pretty much understand how it works. But I want to record my activity only when the certain row is updated. Below is the code from the link. And it records when there is update no matter what row is updated.
    IF (TG_OP = 'UPDATE') THEN
...

Please help me how to give a condition to above code. Thanks!

A: The trigger is written in PL/PgSQL. I strongly suggest you study the PL/PgSQL manual if you're going to  modify PL/PgSQL code.
In triggers, the row data is in OLD and NEW (for UPDATE triggers). So you can do IF tests on that like anything else. E.g.:
IF (TG_OP = 'UPDATE') THEN
  IF NEW."name" = 'name_to_audit' OR OLD."name" = 'name_to_audit' THEN
   -- do audit commands
  END IF;
END IF;

Both NEW and OLD are tested in case the name is being changed from/to the name of interest.
In this case you could instead change it to use a WHEN clause on the CREATE TRIGGER, so you never fire the trigger at all unless the conditions to audit are met. See the WHEN clause on triggers.
This is just a basic programming problem; you'll need to learn the programming language in order to use it.
See also the updated trigger for Pg 9.1.
Oh, and remember to think about NULL; remember NULL = 'anything' is NULL. Use IS DISTINCT FROM if you want to say "these things are equal, or are both null".

A: From Postgresql Docs:
CREATE TRIGGER log_update
    AFTER UPDATE ON accounts
    FOR EACH ROW
    WHEN (OLD.* IS DISTINCT FROM NEW.*)
    EXECUTE PROCEDURE log_account_update();

This only work for UPDATE on that table. For INSERT AND DELETE you can use same without WHERE query. Hope this help others.


text:
Q: What are the steps for making an API response global using TypeScript and useContext? Having trouble figuring this out:
I want to use use Context with TypeScript to pass down a REST API response consisting of a json object with a shape like:
Type Recipe {
isVegan: boolean;
title: string;
extendedIngredients: NestedObjects[];
};

What is the best way to go about creating an object that encompasses the expected API response and the set State function I want to provide as context?
My plan is to make an get request tied to an on Click event in a child component, and set the state to the response so the information is available globally.


text:
Q: Rudin and exponential function construction I have been dusting the cobwebs off of my math knowledge and in working through Rudin's PMA, I have come to a rather small detail that I have been unable to supply an explanation for. In constructing the exponential and logarithmic functions in chapter 8, Rudin eventually writes that if $x>0$, $n$ is an integer, and $m$ is a positive integer, we have
$$ x^{\frac{1}{m}}=E\bigg(\frac{1}{m}L(x)\bigg) $$
I find myself unable to confidently supply the missing details using anything in the section on exponents and logarithms up to that point. Is it simply a consequence of the fact that Rudin has already constructed $E(p)=e^p$ for rational $p$ and defined $E(x)=e^x=\mathrm{sup}\ e^p$, where $x$ is real, and $p<x$, in which case I would suppose that $$E\bigg(\frac{1}{m}L(x)\bigg)=E\bigg(L(x)\frac{1}{m}\bigg)=(e^{ln(x)})^\frac{1}{m}=x^\frac{1}{m}$$ I feel as though I am overlooking something.

A: Note that $E\left(\frac{1}{m}L(x)\right) > 0$ and $$\left(E\left(\frac{1}{m}L(x)\right)\right)^m = E\left(m\cdot \frac{1}{m}L(x)\right) = E(L(x)) = x$$
where the first equality follows from (29) with $z_1=\ldots=z_n = \frac{1}{m}L(x)$ and $n=m$.
It follows from the theorem-definition 1.21 that $$E\left(\frac{1}{m}L(x)\right) = x^{1/m}$$


text:
Q: Converting a list to multiple data frames, to be able to convert only a column of each data frame to numeric data I'm new in programming in R, and I've been having this problem for several days now. I started with a list I created from splitting a file. This list contains lots of data frames. I was able to perform some operations in them, like replacing some data to NA with lapply. But right now, I got stuck and don't know how to convert only a column of this data frames inside of this huge list.
This is an example of what I have in my file:
d1 <- data.frame(foo = c("a", "b", "c", "d", "e"), bar = as.character(c(4.27, 5.68, 5.52, 5.20, 3.67)))
d2 <- data.frame(bla = c("a", "e", "c"), blu = as.character(c(10.14, 9.88, 10.01)))
d3 <- data.frame(lol = c("p", "s", "q", "r"), pum = as.character(c(5.96, 1.22, -1.61, 5.05)))
d1[, 2] <- as.character(d1[, 2])
d2[, 2] <- as.character(d2[, 2])
d3[, 2] <- as.character(d3[, 2])
file <- list(d1, d2, d3)

Which yields something like this:
[[1]]
 foo  bar
1   a 4.27
2   b 5.68
3   c 5.52
4   d  5.2
5   e 3.67

[[2]]
 bla   blu
1   a 10.14
2   e  9.88
3   c 10.01

[[3]]
 lol   pum
1   p  5.96
2   s  1.22
3   q -1.61
4   r  5.05

I would like to have as a result this:
[[1]]
 foo  bar
5   e 3.67
1   a 4.27
4   d  5.2
3   c 5.52
2   b 5.68

[[2]]
 bla   blu
2   e  9.88
3   c 10.01
1   a 10.14

[[3]]
 lol   pum
3   q -1.61
2   s  1.22
4   r  5.05
1   p  5.96

After this is ordered, I will have to extract a specific row on each of the data frames, but I guess if I understand how to perform this operation, I might be able to do this.
After a lot of trying, and finding a thread here, I was finally able to do this:
for(i in 1:length(names(file))){
    assign(paste("df", i, sep = ""), file[[i]])
    }

This piece of code let me separate the data frames I had after using the split function. Now I want to add inside this for loop, a way to reconvert the character data I have in one column to numeric data. I have tried to use a code like this inside the for loop:
df[, 2] <- sapply(df[,2], as.numeric)

But I get an error: 'Closure' type object is not a subset.
Anyone can help? If anyone can tell me a simpler alternative (if there is) it will be very welcome.

A: I think you want
lapply(file, function(x) {
    x[[2]] <- as.numeric(x[[2]])
    x[order(x[[2]]), ]
})

Explained:

*

*lapply iterates a function over a list

*file is your list, the one we are operating on

*function(x) is an "anonymous" function, where x will be each individual element of file

*x[[2]] <- as.numeric(x[[2]]) converts the second column to numeric

*x[order(x[[2]]), ] orders the rows of the data frame by the second column.


text:
Q: How to set PWM fan speed manually? How can I set a speed for a certain PMW-driven fan manually? I tried LM-Sensors but there it seems the speed can be only set automatically.

A: this may work ... you could try to edit your /etc/fancontrol file changing all the values for the specific pwm MINSTART, MINSTOP, MINPWM to all the same values  .. that should make it a set speed. You may have to change MAXTEMP to a very high value so it doesn't try to spin up  higher then the min values. you will probably have to restart it for the changes to take effect

A: echo 2500 | sudo tee /sys/class/hwmon/hwmon2/fan3_min

hwmon[0-9] and fan[0-9] vary by system.
The BIOS might take over and stop this working, though.


text:
Q: Calculating relative frequencies in SQL I am working on a tag recommendation system that takes metadata strings (e.g. text descriptions) of an object, and splits it into 1-, 2- and 3-grams.
The data for this system is kept in 3 tables:

*

*The "object" table (e.g. what is being described),

*The "token" table, filled with all 1-, 2- and 3-grams found (examples below), and

*The "mapping" table, which maintains associations between (1) and (2), as well as a frequency count for these occurrences.

I am therefore able to construct a table via a LEFT JOIN, that looks somewhat like this:
SELECT mapping.object_id, mapping.token_id, mapping.freq, token.token_size, token.token
FROM mapping LEFT JOIN
     token
     ON (mapping.token_id = token.id)
WHERE mapping.object_id = 1;

  object_id   token_id   freq   token_size   token
+-----------+----------+------+------------+--------------
  1           1          1      2            'a big'
  1           2          1      1            'a'
  1           3          1      1            'big'
  1           4          2      3            'a big slice'
  1           5          1      1            'slice'
  1           6          3      2            'big slice'

Now I'd like to be able to get the relative probability of each term within the context of a single object ID, so that I can sort them by probability, and see which terms are most probably (e.g. ORDER BY rel_prob DESC LIMIT 25)
For each row, I'm envisioning the addition of a column which gives the result of freq/sum of all freqs for that given token_size. In the case of 'a big', for instance, that would be 1/(1+3) = 0.25. For 'a', that's 1/3 = 0.333, etc.
I can't, for the life of me, figure out how to do this. Any help is greatly appreciated!

A: If I understood your problem, here's the query you need
select
    m.object_id, m.token_id, m.freq,
    t.token_size, t.token,
    cast(m.freq as decimal(29, 10)) / sum(m.freq) over (partition by t.token_size, m.object_id)
from mapping as m
    left outer join token on m.token_id = t.id
where m.object_id = 1;

sql fiddle example
hope that helps


text:
Q: VB.NET Open word document In VB.NET how do you open a word/PDF doc? I used to have the code and I remember it was very short.

A: Assuming there is an app registered to handle .PDF or .DOC files, you could use the following:

System.Diagnostics.Process.Start("C:\path\filename.pdf")
System.Diagnostics.Process.Start("C:\path\filename.doc")

A: Are you thinking of VSTO (Visual Studio Tools for Office)?


text: Q: can we give xml request in body for post request in artillery.if yes please give example of request can we give xml request in body for post request  in artillery.if yes please give example of request. I need xml request to pass in post request for artillery


text:
Q: If $AB+BA=0$ and $B=AX+XB$, then $B$ is nilpotent. Suppose $A,B,X \in M_n(\mathbb{R})$ and that $AB+BA=0$ and $B=AX+XA$. Prove that $B$ is a nilpotent matrix.

A: Here is a related problem: Show that a matrix is nilpotent.
The proof for this one is almost the same.
We have $$AB=-BA$$, thus it follows by multiplying $B$ on the right, that
$$AB^2 = -BAB = B^2 A$$
Then by induction, we have $$AB^n=(-1)^nB^nA.$$
Now, following the solution in the link: we have
$$B^n = B^{n-1}B = B^{n-1}(AX+XA) = A (-1)^{n-1} B^{n-1}X + B^{n-1} XA.$$
Thus, $$\textrm{Tr} B^{2n} = 0 $$ for all $n$.
This shows that $B^2$ is nilpotent.


text:
Q: How do I install python-virtualenv on Ubuntu server 12.04? When ever I try to sudo apt-get install python-virtualenv, I'm told that Ubuntu is unable to locate the package.
I'm running the server in a VirtualBox. It has networking and can access the web via NAT, so that's not an issue. Aptitude can see the normal Python module, but just not this particular bit that I need.
So does anyone have a way, direct or roundabout, for me to resolve this?

A: You can install it with these instructions.
curl -O https://pypi.python.org/packages/source/v/virtualenv/virtualenv-1.10.1.tar.gz
tar xvfz virtualenv-1.10.1.tar.gz
cd virtualenv-1.10.1
sudo python setup.py install

If you want to know how to use it then you can visit its home page: virtualenv


text:
Q: Javascript Converter Coding Error ~ Showing Bug the converter is not showing up an answer when I input value into the forms. It shows up pop-up alert "You must enter a number between 32 and 40"  ~Thanks

    <TITLE>Bra Size to Chest Size Converter - CM</TITLE>

Bra Size to Chest Size Converter

    <FORM NAME="Calculator" METHOD="post">

Enter Bra Size: <INPUT TYPE=TEXT NAME="input_A" SIZE=8>

Enter Cup Size: <INPUT TYPE=TEXT NAME="input_B" SIZE=8>

<INPUT TYPE="button" VALUE="Get Chest Size" name="AddButton" onClick="CalculateSum(this.form.input_A.value, this.form.input_B.value, this.form)">

Your Chest Size is <INPUT TYPE=TEXT NAME="Answer" SIZE=8> inch

<INPUT TYPE="button" VALUE="Clear" name="ClearButton" onClick="ClearForm(this.form)">

    </FORM>

A:  var A = BratoNum(Atext);

You are passing Btext instead!

A:
Actually you are passing invalid
  argument to BratoNum function. That is
  why it always going into default case'

var A = BratoNum(Atext);
// Here I have changed the argument , which you suppose to pass.

;


text:
Q: Where to declare application scope variables on marionettejs I I am using marionettejs yeoman generator
https://github.com/mrichard/generator-marionette
what's the best way to declare global variables like application root path and API endpoint ?

A: Declare them right on the app itself, or create a Util module or something.  There are numerous ways to do it.


text:
Q: clang: error: linker command failed with exit code 1 (use -v to see invocation) I am new to LLVM. I am using Clang 3.0 to execute c programs.
I am using mandriva spring 2010. GCC version 4.4.1 is installed in the system.
I used the following link to install LLVM.
svn co http://llvm.org/svn/llvm-project/llvm/trunk llvm

I run it by using the below command
clang file.c.

I am getting the following error.
/usr/bin/ld: cannot find -lgcc
clang: error: linker command failed with exit code 1 (use -v to see invocation)

A: Right now clang only has hardcoded paths to your system libraries (different linux distors are pretty different wrt this). This error means that it does not know your distribution and thus cannot infer the necessary stuff.
You have to patch clang sources and provide the necessary paths. Alternatively, you can just pass -L option with the appropriate directory in the cmdline.


text:
Q: What is wrong with my File::Find::Rule->grep call? I am trying to fetch the list of .cpp files that have a class "MyClass" being used in it.
Here is the snippet:
use File::Find::Rule;
my @match_files = File::Find::Rule->file()->name('*.cpp')->in('.')->grep("MyClass");

However, this is giving the following error:
Can't call method "grep" without a package or object reference at ./script.pl line 20.

Can someone help me understand what is wrong with this call?

A: The error tells you that the LHS of the last -> operator was not an object. That is because the in method evaluates the rule and returns a list of matching files.
So you should probably swap the grep and the in:
my @files = File::Find::Rule->file->name('*.cpp')->grep(qr/MyClass/)->in('.');

You can re-read the documentation at MetaCPAN.


text:
Q: Merging writable node streams into one stream I have an array of writable streams in a gulp task. I would like to merge them and return one stream. I am using the merge-stream node module to do this. I get the following error though.
[14:22:56] Error: Cannot pipe, not readable
    at WriteStream.Writable.pipe (_stream_writable.js:161:22)
    at add (C:\workspace\mediafly-viewer\desktop\node_modules\merge-stream\index.js:28:12)
    at Array.forEach (native)

Is merging writable streams supported? If so, how do I go about doing this?
Here is what I tried with promises.
const promises = streams.map(s => new Promise((resolve, reject) => s.on('finish', resolve).on('error', reject)));

return Promise.all(promises);

A: The problem is that merge-stream treats each stream as a Transform stream, i.e. it tries to call pipe on the writable stream, but writable streams do not have pipe method, only write. What you can do to fix this is to either use Transform streams for your writes, or do as you've done by using Promise to wait for the finish event.


text:
Q: Mel expression in mule anypoint Studio Is there a MEL expression to find the log level and store it in a string variable. I searched Google but didn't find it. Can any one help me?

A: Through MEL, you can access a logger using
#[org.apache.commons.logging.LogFactory.getLog(loggerName)]

The Log interface does not contain any direct method to obtain its level, but you can know if a certain level is active or not. So you can use the following expression to obtain a logger level in MEL:
#[log = org.apache.commons.logging.LogFactory.getLog(loggerName); return log.isTraceEnabled() ? "TRACE" : log.isDebugEnabled() ? "DEBUG" : log.isInfoEnabled() ? "INFO" : log.isWarnEnabled() ? "WARN" : log.isErrorEnabled() ? "ERROR" : log.isFatalEnabled() ? "FATAL" : "OFF"]

A: There is no way of doing such thing, for a number of reasons. First there is no such thing as a loglevel but a combinations of log levels for packages or classes and a default log level, then each appender will have a minimum log level too, etc.
Also Mule tipically use SLF4J but not necesarily all code will. To make things complicated, in the soon to be released 3.6 the logging system has changed quite a bit.
If I had to do that I would probably have your log4j.properties as a maven processed resource that had the level set and then also would have a property file that mule should use as a property placeholder that will have the property also set as a processed resource.


text:
Q: Google Map Iterate through all the objects I am dynamically loading json map data. Once the data is loaded, I wanted to iterate over all items (Features) on the map. Then I want to add a 'listener' when a user clicks on the feature.
map.data.forEach(function(feature) {
   console.log(feature);

   map.data.addListener(feature, 'click', function(event) {
        console.log('click');
   });

});

When I console.log(feature) there are objects. (see image)
Other examples show map.data.addListener(polygon, 'click', function(event) {////}
Loggin shows 'feature.getGeometry().getType().toLowerCase()' = polygon so I know I have good objects.
How do I iterate through all the objects and listen for the click?

A: You can add a click listener to the data layer like this google example, replacing the "mouseover" with "click" (outside of the .forEach).
// Set click event for each feature.
map.data.addListener('click', function(event) {
  console.log('click');
});


text:
Q: Declared JComboBox within class constructor but it won't transfer over to the actionPerformed(Event action) method I declared my JComboBox objects within my class constructor for my GUI. I'm trying to make it so when a button is pressed on the GUI, the actionPerformed() method is activated. Within that method, I'm trying to make a calculation based on selections within 2 JComboBoxes, so I have to access the item selected within each comboBox. I was going to do this using the (JComboBox var).getSelectedItem().toString(); call within my actionPerformed() method, but I get a "symbol not found" error for the JComboBox variable even though I already declared it within the constructor. I'll paste the code here:
private JButton calcButton;
private JComboBox listInput;
private JComboBox listOutput;
private JLabel amountLabel;
private JLabel inputTypeLabel;
private JLabel outputTypeLabel;
private JLabel outputLabel;
private JFormattedTextField amountField;
private JTextField outputField;

/* Constructor creates GUI components and adds GUI components
   using a GridBagLayout. */
public ConverterFrame() {
    // Used to specify GUI component layout
    GridBagConstraints layoutConst = null;

    // Set frame's title
    setTitle("Currency Converter");

    // Create labels
    amountLabel = new JLabel("Amount to be converted: ");
    inputTypeLabel = new JLabel("Select input currency:");
    outputTypeLabel = new JLabel("Select output currency:");
    outputLabel = new JLabel("Output amount");

    // Create button and add action listener
    calcButton = new JButton("Convert");
    calcButton.addActionListener(this);

    // Create JComboBoxs
    JComboBox comboBoxInput = new JComboBox();
    comboBoxInput.addItem("USD");
    comboBoxInput.addItem("EUR");
    comboBoxInput.addItem("GBP");
    JComboBox comboBoxOutput = new JComboBox();
    comboBoxOutput.addItem("USD");
    comboBoxOutput.addItem("EUR");
    comboBoxOutput.addItem("GBP");

    // Create and set-up an input field for numbers (not text)
    amountField = new JFormattedTextField(NumberFormat.getNumberInstance());
    amountField.setEditable(true);
    amountField.setText("0");
    amountField.setColumns(15); // Initial width of 10 units

    // Create output field for converted dollars
    outputField = new JTextField(15);
    outputField.setEditable(false);

    // Use a GridBagLayout
    setLayout(new GridBagLayout());

    // Specify component's grid location
    layoutConst = new GridBagConstraints();
    layoutConst.insets = new Insets(10, 10, 10, 1);
    layoutConst.gridx = 0;
    layoutConst.gridy = 0;
    add(amountLabel, layoutConst);

    layoutConst = new GridBagConstraints();
    layoutConst.insets = new Insets(10, 1, 10, 10);
    layoutConst.gridx = 1;
    layoutConst.gridy = 0;
    add(amountField, layoutConst);

    layoutConst = new GridBagConstraints();
    layoutConst.insets = new Insets(10, 5, 10, 10);
    layoutConst.gridx = 2;
    layoutConst.gridy = 0;
    add(calcButton, layoutConst);

    layoutConst = new GridBagConstraints();
    layoutConst.insets = new Insets(10, 0, 5, 10);
    layoutConst.gridx = 0;
    layoutConst.gridy = 1;
    add(inputTypeLabel, layoutConst);

    layoutConst = new GridBagConstraints();
    layoutConst.insets = new Insets(1, 0, 10, 10);
    layoutConst.gridx = 0;
    layoutConst.gridy = 2;
    add(comboBoxInput, layoutConst);

    layoutConst = new GridBagConstraints();
    layoutConst.insets = new Insets(10, 0, 5, 10);
    layoutConst.gridx = 1;
    layoutConst.gridy = 1;
    add(outputTypeLabel, layoutConst);

    layoutConst = new GridBagConstraints();
    layoutConst.insets = new Insets(1, 0, 10, 10);
    layoutConst.gridx = 1;
    layoutConst.gridy = 2;
    add(comboBoxOutput, layoutConst);

    layoutConst = new GridBagConstraints();
    layoutConst.insets = new Insets(10, 1, 10, 0);
    layoutConst.gridx = 0;
    layoutConst.gridy = 3;
    add(outputLabel, layoutConst);

    layoutConst = new GridBagConstraints();
    layoutConst.insets = new Insets(10, 0, 10, 10);
    layoutConst.gridx = 1;
    layoutConst.gridy = 3;
    add(outputField, layoutConst);
}

/* Method is automatically called when an event
  occurs (e.g, Enter key is pressed) */
@Override
public void actionPerformed(ActionEvent event)
{
    double initialAmount;
    double output;
    double exchangeRate;
    String inputType;
    String outputType;

    initialAmount = ((Number) amountField.getValue()).doubleValue();
    inputType = comboBoxInput.getSelectedItem().toString();
    outputType = comboBoxOutput.getSelectedItem().toString();

    if (inputType.equals(outputType))
    {
        exchangeRate = 1.0;
    }
    else if (inputType.equals("USD"))
    {
        if (outputType.equals("EUR"))
            exchangeRate = .704225352;
        else if (outputType.equals("GBP"))
            exchangeRate = .609756097;
    }
    else if (inputType.equals("EUR"))
    {
        if (outputType.equals("USD"))
            exchangeRate = 1.42;
        else if (outputType.equals("GBP"))
            exchangeRate = .884955752;
    }
    else if (inputType.equals("GBP"))
    {
        if (outputType.equals("USD"))
            exchangeRate = 1.64;
        else if (outputType.equals("EUR"))
            exchangeRate = 1.13;
    }

    outputField.setText((initialAmount * exchangeRate) + " " + outputType);
}


text:
Q: How to handle downloads with phantomjs/casperjs? Is it possible to download a file to a folder and give it a specific name with panthomjs/casperjs ?
For instance how can I download the .csv at the bottom of this page : http://www.nasdaq.com/symbol/aapl/historical and name it aapl.txt ?
The download link is :
<a href="javascript:getQuotes(true);" id="lnkDownLoad">
                Download this file in Excel Format
            </a>

Its goal is to call a javascript function whose goal is to obfuscate the direct download link (I think) but when you click on it it summons a classic download prompt. I would like phantomjs to handle that download normally (to change the name of the file and chose where to save it on the drive disk)
Edit : This code is supposed to click on the download link and listen for incoming ressources :
var casper = require('casper').create();

var x = require('casper').selectXPath;

casper.userAgent("Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36")

casper.start('http://www.nasdaq.com/symbol/aapl/historical', function () {
    //this.echo(this.getTitle());
    console.log('TITLE : ' + this.getTitle());

});

casper.wait(5000, function() {
    casper.on('resource.received', function (resource) {
        casper.echo("LISTENING");
        casper.echo(resource.url);
    });
});

casper.thenClick(x('//*[@id="lnkDownLoad"]'), function() {
    console.log('CLICKED');
});

casper.run();

But for some reason I dont receive any file unlike on a normal browser. The console log is : b'TITLE : (AAPL) Historical Prices & Data - NASDAQ.com\r\nCLICKED\r\nLISTENING\r\nhttp://www.nasdaq.com/symbol/aapl/historical\r\n'
Any idea ?

A: When you look into the code, you see that it is not really obfuscated. By clicking on the download link, the file is actually downloaded through casper, but it cannot be easily accessed. The culprit is PhantomJS, because PhantomJS does not expose the request and response contents (see page.onResourceReceived), but only meta data.
It means that you need to repeat the request through the download function. When you look into the page source in your browser's developer tools, you see that getQuotes(true) is called on click. By searching for getQuotes (Ctrl+Shift+F in Chrome), you find the function in question.
By analysing the function, you could arrive at the conclusion that $("#getFile").submit(); is the actual download which is just a POST request from a form with a lot of hidden values. If you look closely into getQuotes, you see that the function also adds one of the hidden values to the form. This means that you need to call getQuotes before faking the submission of the form.
The actual faking is relatively easy. The first thing is to generate the request object from the form to be used in the POST request and second thing is finding out the URL of the request. Here is the complete code:
var casper = require('casper').create();
var x = require('casper').selectXPath;

casper.userAgent("Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36")

casper.start('http://www.nasdaq.com/symbol/aapl/historical');
casper.wait(5000); // probably not necessary
casper.thenClick('#lnkDownLoad');
casper.then(function(){
    var parameters = this.evaluate(function(){
        // from http://stackoverflow.com/a/2403206
        var paramObj = {};
        $.each($('#getFile').serializeArray(), function(_, kv) {
            paramObj[kv.name] = kv.value;
        });
        return paramObj;
    });
    var url = this.getElementAttribute('#getFile', 'action');
    this.download(url, 'aapl.csv', 'POST', parameters);
});
casper.run();


text:
Q: Aggregate of 2 vectors in VHDL I am checking what I can and cannot do in aggregating and concatenating in VHDL.
while I can combine two vectors by concatenating them, I keep getting error if I use aggregate.
I saw one answer here shows it is possible.
Can someone explain why they are giving errors, or maybe it is the language which does not allow this?
I appreciate any suggestion.
here is my code. I marked the correct and the wrong lines.I use ModelSim.
I comment/uncomment when checking to avoid multiple drivers.
architecture RTL of example_array is
--signal Z_BUS                                  : std_logic_vector(7 downto 0);
--signal R_BUS                                  : std_logic_vector(3 downto 0);
--signal A_BIT, B_BIT, C_BIT, D_BIT     : std_logic;

signal T_BUS                                    :  std_logic_vector(7 downto 0);
signal Y_BUS                                    :  std_logic_vector(7 downto 0);
signal U_BUS                                    :  std_logic_vector(3 downto 0);
signal P_BUS                                    :   std_logic_vector(3 downto 0);
signal E_BIT, F_BIT, G_BIT, H_BIT       :  std_logic;

BEGIN
Z_BUS <= A_BIT & R_BUS & B_BIT & C_BIT & D_BIT;                 -- correct
--Z_BUS <= W_BUS & R_BUS;                                       -- correct

P_BUS <= (E_BIT, F_BIT, G_BIT, H_BIT);                          -- correct
U_BUS <= (E_BIT, F_BIT, G_BIT, H_BIT);                          -- correct

(E_BIT, F_BIT, G_BIT, H_BIT)    <= std_logic_vector'("1011");       -- correct
(E_BIT, F_BIT, G_BIT, H_BIT)    <= P_BUS(3 downto 0);               -- correct
(E_BIT, F_BIT, G_BIT, H_BIT)    <= P_BUS;                           -- correct
Y_BUS <= (2 => '1', 3 => F_BIT, 1 downto 0 => '0', others => '0');  -- correct

--T_BUS(7 downto 0) <= (U_BUS(3 downto 0), P_BUS(3 downto 0));  -- WRONG!!
--T_BUS <= (U_BUS, P_BUS);                                      -- WRONG!!
--(U_BUS(3 downto 0), P_BUS(3 downto 0)) <= T_BUS(7 downto 0);  -- WRONG!!

END architecture RTL;

A: Use the VHDL-2008 Library in ModelSim and your error is resolved. VHDL-93/2002 packages don't support aggregating vectors like the way you have expressed.


text:
Q: SQL server, difference two tables and mix together For example I have two tables: tbMetals and tbSells
tbMetals
mId - name   - cost
1   - Iron   - 100
2   - Steel  - 200
3   - Copper - 300
4   - Zinc   - 150

tbSells
CustomerId - mId - SellDate - weight
100        - 1   - 2017/1/1 - 1.2
100        - 2   - 2017/1/2 - 3.5
111        - 1   - 2017/3/3 - 2.1

I need like this output for ClientId=100
mId - SellDate - weight
1   - 2017/1/1 - 1.2
2   - 2017/1/2 - 3.5
3   - NULL     - NULL
4   - NULL     - NULL

A: This is a simple left join.
select
    m.mId
    ,s.SellDate
    ,s.weight
from
    tbMetals m
left join
    tbSells s on
    s.mId = m.mId
    and s.ClientId = 100   --optional, if you really want it.


text:
Q: Running same custom domain in different Azure App Services in same region I need to have the same Azure App Service Custom Domain running in different App Services on the same region. Is that possible?

A: Custom domians are based in DNS, only one record should be pointing to one App Service, so I think it would not be recommended to have same custom domain in multiple App Services in the same region. Being said that, it works for different regions and it is common to see this deployments for instance behind Traffic Manager or Azure Frontdoor.
In order to do this in the same region is a bit more challenging as the only way is to make sure your App Service goes to a different webspace (https://learn.microsoft.com/en-us/azure/app-service/app-service-plan-manage#move-an-app-to-another-app-service-plan). So basically to make sure it goes to a different webspace you need to create a new Resource Group and a new App service Plan, then you can create the specific App Service and add the custom domain. In order to make sure they are in different webspaces, check if the Inbound IP is different.


text:
Q: Time Optimization for pandas dataframe reconstruction (random to fixed sampling) I am very new to python and pandas and my limited experience has led me to come up with an inefficient solution making my code too slow.
I have some data corresponding to stock market prices.
Sampling is random at nanosecond level.
What I am trying to achieve is transform to a new data-set with fixed sampling rate.
I am transforming my data-set as follows:

*

*I'm setting a time_delta as a static time step of 0.5 seconds

*I'm dropping reccords corresponding to the same nanosecond

*I'm generating timestamps from my start_time to the calculated end_time

*I'm iterating through my original dataframe copying (and duplicating when needed) the last known record in my time_delta for each step to a new dataframe.

I believe that my issue is probably that I am appending the records one-by-one to my new dataframe, however I haven't been able to figure out a way utilizing pandas built-ins to optimize my code.
Runtime is currently ~4min for a day's data (turning ~30K samples to 57600) when executing on Google Colab.
I've also tested locally without any improvement.

# ====================================================================
# Rate Re-Definition
# ====================================================================

SAMPLES_PER_SECOND = 2
dt = 1000000000 / SAMPLES_PER_SECOND # Time delta in nanoseconds
SECONDS_IN_WORK_DAY = 28800 # 60 seconds * 60 minutes * 8 hours
TOTAL_SAMPLES = SECONDS_IN_WORK_DAY * SAMPLES_PER_SECOND
SAMPLING_PERIOD = dt * TOTAL_SAMPLES

start_of_day_timestamp = ceil_to_minute(df['TimeStamp'].iloc[0])
end_of_day_timestamp = start_of_day_timestamp + SAMPLING_PERIOD

fixed_timestamps = np.arange(start_of_day_timestamp,
                             end_of_day_timestamp,
                             dt,
                             dtype=np.uint64
                            )

# ====================================================================
# Drop records corresponding to the same timestamps
# ====================================================================

df1 = df.drop_duplicates(subset='TimeStamp', keep="last")

# ====================================================================
# Construct new dataframe
# ====================================================================

df2 = df1.iloc[0:1]
index_bounds_limit = df1.shape[0] - 1
index = 0

for i in tqdm(range(1, TOTAL_SAMPLES), desc="Constructing fixed sampling rate records... "):
  while index < index_bounds_limit and df1['TimeStamp'].iloc[index] < fixed_timestamps[i]:
    index += 1
  df2 = df2.append(df1.iloc[index], ignore_index=True)

df2['TimeStamp'] = fixed_timestamps

I need to reduce the time as much as possible (while maintaining readability/maintainability, no need to use "hacks").
I would appreciate any help and pointers towards the right direction.
Thanks in advance


text:
Q: validating JWT token on aws with https load balancer I am using aws(amazon web services) to host my app . My hosting server has no SSL installed but load balancer (the internet facing gateway) has SSL so whenever I make call to https:// mydomain .com it first goes to load balancer and then http:// mydomain .com.
However the problem with this architecture is when server creates a token it has issuer http:// mydomain .com so in jwtbeaererauthentication configuration if I put http:// mydomain .com as authority it throws CORS error and if I put https:// mydomain .com it wont authorize.
If there is any workaround for this kind of issue please let me know. I am using asp.net core, openiddict and jwtauthentication as middleware.


text:
Q: Count of List values in spark - dataframe In cassandra I have a list column type. I am new to spark and scala, and have no idea where to start.
In spark I want get count of each values, is it possible to do so.
Below is the dataframe
+--------------------+------------+
|                  id|        data|
+--------------------+------------+
|53e5c3b0-8c83-11e...|      [b, c]|
|508c1160-8c83-11e...|      [a, b]|
|4d16c0c0-8c83-11e...|   [a, b, c]|
|5774dde0-8c83-11e...|[a, b, c, d]|
+--------------------+------------+

I want output as
+--------------------+------------+
|   value            |      count |
+--------------------+------------+
|a                   |      3     |
|b                   |      4     |
|c                   |      3     |
|d                   |      1     |
+--------------------+------------+

spark version: 1.4

A: Here you go :
scala> val rdd = sc.parallelize(
  Seq(
    ("53e5c3b0-8c83-11e", Array("b", "c")),
    ("53e5c3b0-8c83-11e1", Array("a", "b")),
    ("53e5c3b0-8c83-11e2", Array("a", "b", "c")),
    ("53e5c3b0-8c83-11e3", Array("a", "b", "c", "d"))))
// rdd: org.apache.spark.rdd.RDD[(String, Array[String])] = ParallelCollectionRDD[22] at parallelize at <console>:27

scala> rdd.flatMap(_._2).map((_, 1)).reduceByKey(_ + _)
// res11: org.apache.spark.rdd.RDD[(String, Int)] = ShuffledRDD[21] at reduceByKey at <console>:30

scala> rdd.flatMap(_._2).map((_,1)).reduceByKey(_ + _).collect
// res16: Array[(String, Int)] = Array((a,3), (b,4), (c,3), (d,1))

This is also actually quite easy with the DataFrame API :
scala> val df = rdd.toDF("id", "data")
// res12: org.apache.spark.sql.DataFrame = ["id": string, "data": array<string>]

scala> df.select(explode($"data").as("value")).groupBy("value").count.show
// +-----+-----+
// |value|count|
// +-----+-----+
// |    d|    1|
// |    c|    3|
// |    b|    4|
// |    a|    3|
// +-----+-----+

A: You need something like this (from Apache Spark Examples):
val textFile = sc.textFile("hdfs://...")
val counts = textFile
             .flatMap(line => line.split(" "))
             .map(word => (word, 1))
             .reduceByKey(_ + _)

Guessing that you already have pairs, .reduceByKey(_ + _) will return what you need.
You can also try in spark shell something like this:
sc.parallelize(Array[Integer](1,1,1,2,2),3).map(x=>(x,1)).reduceByKey(_+_).foreach(println)


text:
Q: Access function in another js file with $(document).ready(function() According to this post Click here to see the referred post
I tried to get access to a function which is defined in another .js file following the post instruction. However, I still have a problem. See my code below:
sildemenu.js
$(document).ready(function() {
    var window.slideMenu=function(){
        //do something here
    }();
});

control.js
$(document).ready(function() {
    $('#foo').on('click', function() {
         window.slideMenu();
    });
});

I got the error "Object [object Window] has no method 'sildeMenu' ".
I am very new in programming. Please give me a mercy.

A: You try to define a complex variable, (which is impossible this way) instead of assign a value to the global object- window.
  var window.slideMenu=function(){
//^^^ Get rid of this
    //do something here
  }();
 //^^  and remove this

And get rid of the var
Fixed code:
window.slideMenu=function(){
    //do something here
};

A: There is no need of window object just write:
sildemenu.js
$(document).ready(function() {
    slideMenu=function(){
      //Do your stuff here!
    };
});

control.js
$(document).ready(function() {
    $('#foo').on('click', function() {
         slideMenu();
    });
});


text:
Q: Simulated device with Azure Function on IoT Hub is not able to trigger Currently I have simulated device that receives message from IoT Hub and processes it and after it is done, device sends message to IoT Hub. The device is working but it is running as .exe file on computer and Im trying to transform it and upload on Azure as function so I can avoid it not working when computer turns off or freezes while Im not around it.

I wanted to make it function triggered by events on IoT Hub but Im facing problem. Currently the function that sends message, sends it directly to device on IoTHub(my device) but in case like this, message is not "displayed" on IoT Hub so Im unable to use it as trigger. I'm unable to change function that sends message to device. Are there any options how to catch those messages on IoTHub or possibility to trigger it any other way?

A: There is no direct way to send messages from Azure function to Azure IoT Hub. You can probably utilize Device event Azure IoT Hub Rest API end point from the Azure Function and send the message to the Azure IoT Hub. Here is the request you can make to send the message to Azure IoT Hub.
POST https://fully-qualified-iothubname.azure-devices.net/devices/{id}/messages/events?api-version=2020-03-13

Please find the following reference to all the Supported bindings for Azure Functions runtime

You can trigger the Azure Function by using the IoT Hub trigger. Refer the following resource that runs you through the steps needed to set up the Azure IoT Hub trigger for Azure Functions


text:
Q: An error while compiling I downloaded the template from here and compiled it, I get the error
NEURAL_NETWORK not found. \includegraphics[width=2.5in]{NEURAL_NETWORK}

Then, I compiled it in an other PC, there is no problem. What is the problem in my PC and how can I solve the problem?


text:
Q: Angular not displaying JSON array data I've spent a few hours on this and I just can't get the array data to display on the page. I'm not getting any errors.
     (function() {
        var app = angular.module('myApp', []);

        app.controller('AppController', ['$http', function($http){
            this.files = [];

            $http.get('angular-data.json').success(function(data){
                this.files = data;
            });
        }]);
    })();

And inside my angular-data.json file:
[{"name": "myfile.doc","ext": "doc","size": "168KB","modified": "5 mins"}]

Someone please help :-(

A: Convert your .success to .then
Then convert this
this.files = data;

to this
this.files = data.data;

A: Try this
this.files = data[0];

In angular-data.json file it have object in array

A: I think the this in success callback is not getting its context.
Try binding it in $scope or if you are using vm, just like
for $scope
(function() {
    var app = angular.module('myApp', []);

    app.controller('AppController', ['$http', '$scope', function($http, $scope){
        $scope.files = [];

        $http.get('angular-data.json').success(function(data){
            $scope.files = data;
        });
    }]);
})();

For vm
(function() {
    var app = angular.module('myApp', []);

    app.controller('AppController', ['$http', function($http){
        var vm = this;
        vm.files = [];

        $http.get('angular-data.json').success(function(data){
            vm.files = data;
        });
    }]);
})();


text:
Q: CodeIgniter Session Class and disable logging in from 2 different places at the same time to the same account I wonder how to disable logging into the one account, eq. admin from 2 different places/PC's/browsers/so on using CodeIgniter Session Class and MySQL database?
Any suggestions?

A: Keep a "uniqueID" field for each account.
When the account sucessfully logs in, generate a random unique id and store it in that account, as well as store it in the session.
At the top of every secured page, verify the unique id in the session with that in the database, if they match, hurray. If not, it means that since the time this account logs in from this browser, someone else has used the same account and logged in from another browser. Just kick the current user out of the system then.


text:
Q: UILabel displaying countdown timer text I'm displaying a count down timer using a UILabel like this:
func updateTime() {
            var elapsedTime: NSTimeInterval = startDate!.timeIntervalSinceNow
            var daysFloat = floor(elapsedTime/24/60/60)
            var hoursLeftFloat = floor((elapsedTime) - (daysFloat*86400))
            var hoursFloat = floor(hoursLeftFloat/3600)
            var minutesLeftFloat = floor((hoursLeftFloat) - (hoursFloat*3600))
            var minutesFloat = floor(minutesLeftFloat/60)
            var remainingSeconds = elapsedTime % 60

            var daysInt = Int(daysFloat)
            var hoursInt = Int(hoursFloat)
            var minutesInt = Int(minutesFloat)
            var remainingSecondsInt = Int(remainingSeconds)

            var startsIn = NSMutableAttributedString()
            var days = NSMutableAttributedString()
            var hours = NSMutableAttributedString()
            var minutes = NSMutableAttributedString()
            var seconds = NSMutableAttributedString()
            var dot = NSMutableAttributedString()
            startsIn = NSMutableAttributedString(string: "STARTS IN:  ", attributes: [NSFontAttributeName:UIFont(name: "Tungsten-Semibold", size: 37.0)!, NSForegroundColorAttributeName:color])
            days = NSMutableAttributedString(string: String(format: "%02d", daysInt) + " DAYS", attributes: [NSFontAttributeName:UIFont(name: "Tungsten-Semibold", size: 37.0)!, NSForegroundColorAttributeName:UIColor.blackColor()])
            hours = NSMutableAttributedString(string: String(format: "%02d", hoursInt) + " HRS", attributes: [NSFontAttributeName:UIFont(name: "Tungsten-Semibold", size: 37.0)!, NSForegroundColorAttributeName:UIColor.blackColor()])
            minutes = NSMutableAttributedString(string: String(format: "%02d", minutesInt) + " MIN", attributes: [NSFontAttributeName:UIFont(name: "Tungsten-Semibold", size: 37.0)!, NSForegroundColorAttributeName:UIColor.blackColor()])
            seconds = NSMutableAttributedString(string: String(format: "%02d", remainingSecondsInt) + " SEC", attributes: [NSFontAttributeName:UIFont(name: "Tungsten-Semibold", size: 37.0)!, NSForegroundColorAttributeName:UIColor.blackColor()])
            dot = NSMutableAttributedString(string: " . ", attributes: [NSFontAttributeName:UIFont(name: "Tungsten-Semibold", size: 39.0)!, NSForegroundColorAttributeName:UIColor.lightGrayColor()])

            var countdownText = NSMutableAttributedString()
            countdownText.appendAttributedString(startsIn)
            countdownText.appendAttributedString(days)
            countdownText.appendAttributedString(dot)
            countdownText.appendAttributedString(hours)
            countdownText.appendAttributedString(dot)
            countdownText.appendAttributedString(minutes)
            countdownText.appendAttributedString(dot)
            countdownText.appendAttributedString(seconds)
            countdownLabel.attributedText = countdownText
    }

I have Autoshrink enabled on my UILabel so that the font will scale down and look right on all devices. The issue I'm seeing is that certain seconds and/or minutes will cause the font size to jump around and it will look awkward with the label text getting temporarily bigger during one second and then going back to a smaller size the next second. How can I prevent the font size from jumping around with my label and count down timer?

A: You should use a "monospaced" font with fixed width like Consolas, Courier, DejaVu Sans Mono, Letter Gothic, Liberation Mono, Monaco...
https://en.wikipedia.org/wiki/Monospaced_font
Your issue is that with non fixed width font some numbers will be larger than others.

If your font is imposed, you need to "manually" impose your font size.
You might try to hide your UILabel, set the widest possible string eg:
STARTS IN:  44 DAYS 44 HRS 44 MIN ... (assuming 4 is the widest number with your font)

then retrieve the used font size, force your application to use. Disabling autoshrink at this point is unnecessary: with the computed font size the label should always fit.

Is your font mandatory for all the text or only for words? You might also use a different (monospaced) font for numbers and keep your one for the rest.

A: iOS auto shrinks when the width is not enough to show the entire string. So instead of trimming it the string get's smaller until the minimum scale factor/ font size.
So this depends on the width of the label. If you set it's width via auto layout and the label can't expand to fit it's content it will shrink the font size when that's not enough. If you let it expand to fit the content the label will always try to show the content without shrinking.

A: Do also check if you have AutoShrink turned on or off.

In theory, iOS should only reduce the font size to squeeze in extra text if this isn't set to "Fixed font size".


text:
Q: Azure Network Watcher Reachability Report and Providers List I was trying to get Reachability report an Providers list. I tried Powershell commands and REST API.
reachability report
list available providers
get-aznetworkwatcherreachabilityreport
get-aznetworkwatcherreachabilityproviderslist
None of these seem to provide the actual result

A: You could follow this tutorial to view relative latency to Azure regions from specific locations.
However, after my validation, the returned output of Get-AzNetworkWatcherReachabilityProvidersList is always null. I tried the commands Get-AzNetworkWatcherReachabilityProvidersList -NetworkWatcherName NetworkWatcher_eastus -ResourceGroupName NetworkWatcherRG within the Azure cloud shell with NetworkWatcher region. It's still the same.

It seems that ReachabilityProviders are not available currently or something wrong with the API so you could not get the content for the network watcher reachability report. I suggest requesting feedback at the bottom of this page.


text:
Q: How to hide navigation bar on Android phonegap I'm trying to hide the navigation bar on phonegap but without success.
I manage to do it in a native application using
WebView webview = new WebView(this);
webview.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
setContentView(webview);

On phonegap nothing seems to work. I've tried the following without success
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
ViewGroup view = (ViewGroup)getWindow().getDecorView();
view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
super.loadUrl(Config.getStartUrl());

Thanks

A: I figured out. It works on a device but not on the emulator.
Thanks


text:
Q: What is the topology on the set of symmetric matrices? What is the topology on the set of $n\times n$ real symmetric matrices?
So, it is claimed that the set of nonnegative definite matrices are closed, but what counts as an open set (topology) in this case?
(Kind of bonkers I can't find an answer to this elementary question by googling).


text:
Q: Iterating  having value contains List , that contains another list is not working? I'm using richFaces 3.3 and JSF 1.2.
In my sample application I need to  display List of items  in  and  contains  also
i.e( 2 columns having  and  third one is )
If I try to give List with in another List as value for rich:columns means its not working but direct bean value  is working ???
mainClass
having getter , setter of String item1 , String item2, List  priceList
mainList

 contains item 1
          item 2
          List<price>  priceList like that...

so in  <rich:dataTable> if i try to  give value like

                            <rich:dataTable  id="positions" value="#{bean.mainList}" var="var">

                                    <rich:column>
                                        <f:facet name="header">
                                            <h:outputText   value="item1"/>
                                        </f:facet>
                                        <h:outputText id="contname" value="#{var.item1}">
                                    </rich:column>

                                    <rich:column>
                                        <f:facet name="header">
                                            <h:outputText   value="item2"/>
                                        </f:facet>
                                        <h:outputText id="contname" value="#{var.item2}">
                                    </rich:column>

                                    <rich:columns value="#{var.priceList}" var="partnerPriceItem"  columns="2" index="ind">
                                        <f:facet name="header">
                                                <h:outputText id="output#{ind}" value="#{partnerPriceItem.id}"  />
                                            </f:facet>
                                                <h:outputText id="price#{ind}" value="#{partnerPriceItem.price}" />
                                    </rich:columns>

                                    </rich:dataTable>

here for first 2 columns working fine. but when I try  to give  referencing from  another List  means not working ??
output like
item 1 item 2  price1 price2 price3
1   2   100    200  300
2   2       50     100  75

A: To resolve your problem, you need to use the rich:dataTable and rich:subTable. There is an example in the exadel live demo site.
Let's have a look in the code (this is not the real code of the site, it's just an example to get the idea):
Java Classes
//POJOs
public class Expenses {
    private Date day;
    private decimal meals;
    private decimal hotels;
    private decimal transports;
    //getters and setters for the attributes;
}

public class Record {
    private String city;
    private List<Expenses> items;
    private decimal totalMeals;
    private decimal totalHotels;
    private decimal totalTransport;
    private decimal total;
    //getters and setters for the attributes;
}

public class ExpReport {
    private List<Record> records;
    private decimal totalMeals;
    private decimal totalHotels;
    private decimal totalTransport;
    private decimal grandTotal;
    //getters and setters for the attributes;
}

//Managed Bean
public class Report {
    private ExpReport expReport;
    //getter and setter for the attribute;
}

We have the managed bean Report that contains an instance of ExpReport. Inside ExpReport we have a List of Records (the list we want to display in the table), but each record has its own inner List of Expenses (the list we want to display along with the records). Now, we just need to set up our rich:dataTable and the rich:subTable in it to get the magic flowing in our jsp.
Note: You can get more info on the documentation of rich:column.
<!-- Here we set the data list for the dataTable as the list of records of our
     object expReport. Also, the name of the iterator will be 'record' -->
<rich:dataTable width="100%" value="#{report.expReport.records}" var="record">
    <f:facet name="header">
        <!-- This columnGroup tag component will define a group of columns for
             the header of the dataTable (the body of the dataTable can has
             more columns, for this example there will be the same).-->
        <rich:columnGroup>
            <rich:column rowspan="2">
                <rich:spacer />
            </rich:column>
            <rich:column colspan="3">
                <h:outputText value="Expenses" />
            </rich:column>
            <rich:column rowspan="2">
                <h:outputText value="subtotals" />
            </rich:column>
            <!-- The 'breakBefore' attribute tells the column  to start from the
                 next row to be rendered in the dataTable. This attribute doesn't
                 affect the rows generated in rich:extendedDataTable. For more
                 info, see the documentation (link above the code). -->
            <rich:column breakBefore="true">
                <h:outputText value="Meals" />
            </rich:column>
            <rich:column>
                <h:outputText value="Hotels" />
            </rich:column>
            <rich:column>
                <h:outputText value="Transport" />
            </rich:column>
        </rich:columnGroup>
    </f:facet>
    <!-- Now, let's set the content of the rows of the dataTable -->

    <!-- This column will show city from our 'record' iterator. -->
    <rich:column colspan="5">
        <h:outputText value="#{record.city}" />
    </rich:column>
    <!-- After printing the city, we want to show the data from the expenses
         made in this record. For this, we will use the subTable tag
         component, setting the 'record.items' list as the data list for
         subTable and naming the inner iterator 'expense'. The syntax for the
         subTable is like the dataTable. -->
    <rich:subTable value="#{record.items}" var="expense">
        <rich:column>
            <h:outputText value="#{expense.day}" />
        </rich:column>
        <rich:column>
            <h:outputText value="#{expense.meals}">
                <f:convertNumber pattern="$####.00" />
            </h:outputText>
        </rich:column>
        <rich:column>
            <h:outputText value="#{expense.hotels}">
                <f:convertNumber pattern="$####.00" />
            </h:outputText>
        </rich:column>
        <rich:column>
            <h:outputText value="#{expense.transport}">
                <f:convertNumber pattern="$####.00" />
            </h:outputText>
        </rich:column>
        <rich:column>
            <rich:spacer />
        </rich:column>
    </rich:subTable>
</rich:dataTable>

Sorry for my bad english, I hope this can be helpful in your application.


text:
Q: How to migrate map from tile size 256 to 512 in d3-geo-tile and ArcGIS We have a developed a map using d3-map-tile and using ArcGIS services which is having tile-size 256X256. We were able to render our map and plot the latitude longitude properly.
Now we have to move to the service where tile size is 512X512. Rendering of lat-long is not working properly by just merely changing the services.
Can someone tell me how I can do it in my existing code. what are the things I need to change apart from services.

A: Strictly speaking (as of August 2017), no. The size is fixed within the tile module:

Computes the set of 256x256 quadtree tiles to display given the
  current layout extent, scale and translate. (API docs)

And Mike states:

It currently is limited to 256 [px] (discussion)

However, as coincidence has it, work is occurring to address multiple tile sizes.
See the discussion here. In fact, it seems that a possible implementation has been developed, see this thread, and this block for an example using the possible implementation.


text:
Q: PHP uploading 0 bytes image When I upload an imagen with PHP, I get no errors and the image is 0 bytes on server.
Things considered:

*

*File_uploads is On in phpinfo()

*Upload_max_filesize is 8M in phpinfo()

*Upload_tmp_dir is set and has 777 permisions

*If I run file_exists($_FILES['userfile']['tmp_name']), it returns
true

*If i run getimagesize($_FILES['userfile']['tmp_name']), I get an Read
Error notice. The image is valid and can be opened with system image
viewer

I am using a very simple upload script for testing:
HTML:
<form enctype="multipart/form-data" action="upload.php" method="POST">
        <input type="hidden" name="MAX_FILE_SIZE" value="512000" />
        Send this file: <input name="userfile" type="file" />
        <input type="submit" value="Send File" />
</form>

PHP:
<?php

//$uploaddir = '/var/www/html/upload';
$uploaddir = '';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo "
";

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
  echo "File is valid, and was successfully uploaded.\n";
} else {
   echo "Upload failed";
}

echo "
";
echo '
';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "
";

?>

When I submit the file, I get no errors and the image is created in the destination folder, with the correct name and extension, but as the title says, it is 0 bytes (of course, it can't be oppened).
Thanks for your time.
EDIT
Sajad Karuthedath just made me see that $_FILE['file']['size'] value is 0 !! What can be the problem causing files are not being uploaded correctly?
EDIT 2
Uploading txt, pdf, tar files is working properly.. The problem is only with image type files!

A: try this simple upload script ,
you should check for errors before saving to server
 if ( 0 < $_FILES['file']['error'] ) {
    echo 'Error: ' . $_FILES['file']['error'] . '
';
    }
    else {
    move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/'.$_FILES['file']['name']);
      }

Note: don't forget to restart your server or xampp after changing phpinfo()
Note: also change post_max_size = 25M in php

A: In order to track the issue just add an "exit;" straight after the "move_uploaded_file..." command and if the file is properly uploaded it's the code after the "move_upload" which is wrong.
In my case I was opening the uploaded file after upload with an overwrite (w+) option in order to check the lock state of the file. which was making a empty file.


text:
Q: How do I case fold a string in Python 2? Python 3.3 adds the casefold method to the str type, but in 2.x I don't have anything. What's the best way to work around this?

A: Check out py2casefold.
>>> from py2casefold import casefold
>>> print casefold(u"tschüß")
tschüss
>>> casefold(u"ΣίσυφοςfiÆ") == casefold(u"ΣΊΣΥΦΟσFIæ") == u"σίσυφοσfiæ"
True

A: There is a thread here which covers some of the issues (but may not resolve all), you can judge whether it is suitable for what you need. If this is no good then there are some useful tips for implementing case folding on the W3C site here.

A: If PyICU is already installed; you could use it to define casefold(). Using the same example strings as in @Russ' answer:
>>> import icu
>>> casefold = lambda u: unicode(icu.UnicodeString(u).foldCase())
>>> print casefold(u"tschüß")
tschüss
>>> casefold(u"ΣίσυφοςfiÆ") == casefold(u"ΣΊΣΥΦΟσFIæ") == u"σίσυφοσfiæ"
True
>>> icu.UNICODE_VERSION
'6.3'
>>> import unicodedata
>>> unicodedata.unidata_version
'5.2.0'

The result may depend on the version of Unicode standard.


text:
Q: what is the equivalent of register(Ansible) in Saltstack? In ansible we use register to holding the output of an external command
the question is what is the equivalent in Saltstack ?

A: To my knowledge and reading documentation, at the moment, there is no option to capture output from a state.
What you could do it write your own state and run the task you would like to capture the output and process/perform another task.

A: To my knowledge there is not a one-to-one mapping for this it is however possible to do this in Saltstack:
{% set return = salt['cmd.run']('echo hello') %}

and then use the return variable.

A: There are many options, but the most common would be to use the cmd.run execution function in a Jinja template.
If you need to capture data during state execution, rather than templating, then there is the slots feature.


text:
Q: Akka. How to complete a stream with Source.actorRef? I'd like to complete a stream with predefined messages count:
Source.actorRef(Integer.MAX_VALUE, OverflowStrategy.fail())
    .limit(1)
    .to(Sink.onComplete(System.out::println))
    .run(materializer);
    .tell("Do Complete!", ActorRef.noSender());

From the limit method documentation:

Completes when the defined number of elements has been taken or
  upstream completes

Why does stream not complete?

A: That is the documentation for take , not limit.
And indeed, you should use take to solve your problem.


text:
Q: Why is my Graphql project throwing Error: field type must be Output Type but got: undefined Github Repo
I am fetching data from this espn endpoint
I am also brand new to GraphQL and am not super familiar with fetching nested information.
In the above github repo, I'm currently working in on the "schema1.js" file and when I run it the console throws Error: Boxscore.teams field type must be Output Type but got: undefined.
Normally I would post the schema1.js below but it is too large to format correctly.
Any help is appreciated!

A: You are currently writing your fields as
...
teams: new GraphQLObjectType({ ... })
...

The correct syntax is
...
teams: {
    type: new GraphQLObjectType({ ... })
}
...

Also, I strongly advise you to not define your types nested like you did ; instead, define them independently :
const TeamType = new GraphQLObjectType({ ... });

const BoxscoreType = new GraphQLObjectType({
  name: 'Boxscore',
  fields: () => ({
    teams: {
      type: TeamType
    },
    ...
  })
});


text:
Q: Cannot start SQL Server express I want to start SQL Server 2017 Express and enter the command
"D:\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\Binn\sqlservr.exe" -sSQLEXPRESS

The following error message appeared. How to solve the problem?
2018-11-28 10:06:25.72 spid5s      Uploading data collector package from disk: d:\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\Install\SqlTraceCollect.dtsx
2018-11-28 10:06:25.72 spid5s      Uploading data collector package from disk: d:\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\Install\SqlTraceCollect.dtsx
2018-11-28 10:06:25.72 spid5s      Error: 2775, Severity: 17, State: 12.
2018-11-28 10:06:25.72 spid5s      The code page 65001 is not supported by the server.
2018-11-28 10:06:25.74 spid5s      Error: 912, Severity: 21, State: 2.
2018-11-28 10:06:25.74 spid5s      Script level upgrade for database 'master' failed because upgrade step 'msdb110_upgrade.sql' encountered error 200, state 7, severity 25. This is a serious error condition which might interfere with regular operation and the database will be taken offline. If the error happened during upgrade of the 'master' database, it will prevent the entire SQL Server instance from starting. Examine the previous errorlog entries for errors, take the appropriate corrective actions and re-start the database so that the script upgrade steps run to completion.
2018-11-28 10:06:25.74 spid5s      Error: 3417, Severity: 21, State: 3.
2018-11-28 10:06:25.74 spid5s      Cannot recover the master database. SQL Server is unable to run. Restore master from a full backup, repair it, or rebuild it. For more information about how to rebuild the master database, see SQL Server Books Online.
2018-11-28 10:06:25.74 spid5s      SQL Server shutdown has been initiated
2018-11-28 10:06:25.74 spid5s      SQL Trace was stopped due to server shutdown. Trace ID = '1'. This is an informational message only; no user action is required.

A: Try this:
control panel > Region and Time
and try as u see in this:


text:
Q: Как вернуться в верх определенного элемента на странице? Создал функцию, знаю что .scrollTo(0,0) работает для window, но как применить это к элементу на странице?  Подскажите пожалуйста

function returnToTopElement(clickingObjId, element){
 let clickOn = document.getElementById(clickingObjId);
 let topElement = document.getElementById(element);
 clickOn.addEventListener('click', function(){
  topElement.scrollTo(0,0);
 });
};

returnToTopElement("top-button", "elem-b");
.elem-a{
  height: 200px;
  width: 200px;
  background-color: #f6f6f6;
  color: black;
}
.elem-b{
  height: 300px;
  width: 200px;
  background-color: #263B42;
  color: white;
}
.top-button{
  margin-top: 200px;
  cursor: pointer;
}
.top-button:hover{
  background-color: #b2b2b2;
}

 a

  b

 Return to the top


text:
Q: How do I get sencha js and JSP to work together? I am looking into using Sencha touch to create the "view" portion of my webapp so that it will work on mobile devices. The web app is created using Spring MVC and therefore the "view" part of it is actually rendered using JSP.
Suppose I pass a model called "invoice" from my controller to my view, in JSP, I would get the model as such:
${invoice.number}

However, when I use Sencha touch, since all the coding is done in a js file, how do I call that model?
I tried something like this:
Ext.application({
    name: 'Landing',

    launch: function(){
        Ext.create("Ext.TabPanel", {
            fullscreen: true,
            tabBarPosition: 'bottom',

            items: [
                   {
                       title: 'Landing',
                       iconCls: 'landing',
                       html: [
                              '
Invoice Id is ${invoice.number}
'
                              ]
                    }

                    ]
            }
            ); // --Ext.create
        }

}); // --Ext.application

But that does not work.
Thanks!

A: Generally the way we go about this is decoupling the Sencha Touch application and the back-end as much as possible. You would have your Spring app expose an API (read: RESTful Services) that Sencha Touch would use. The data (models) would be serialized over JSON or XML (or whatever format you would like) and parsed by Sencha Touch's readers.
Sencha Touch is designed to be a MVC application framework in it of itself.
You can take a look at these articles:
http://www.sencha.com/learn/architecting-your-app-in-ext-js-4-part-1
http://www.slideshare.net/senchainc/structuring-your-sencha-touch-application


text:
Q: joomla set JTable property to null How i can set JTable property too null and save it
my code so far w/o succes:
$table = JTable::getInstance($type='detalegrupy', $prefix='FootsalTable', $config = array());
$table->load($id);
$table->promotion = NULL;
$id_group = $table->id_group;
$table->store();

or how to restore it to it's default value.

A: i found answer for it,
$table->store(TRUE);

done the work.
sorry for spam

A: Edit the file administrator/components/YOUR_COMPONENT/tables/NAME_OF_YOUR_TABLE.php and add this function inside the table class:
public function store($updateNulls = true)
{
    return parent::store($updateNulls);
}


text: Q: Android Studio показывает мне ненужную информацию в диалоге проекта, как отключить? Нажал случайно какое-то сочетание горячих клавиш в Android Studio, теперь показывается ненужная информация  о дате последнего изменения и размере файлов, как отключить? Подскажите пожалуйста.


text:
Q: setting background image of UIToolBar in iphone I want to set a background image of UIToolbar in my iPhone application.
Currently I am setting by using the UIColor's initWithPatternImage:.
But it's not doing what I want.
Kindly suggest some other solution.

A: You don't need to create a custom class. You can add a catagory to UIToolBar as below
@implementation UIToolbar (UIToolbarCategory)
- (void)drawRect:(CGRect)rect {
    UIColor *color = [UIColor colorWithRed:0.547 green:0.344 blue:0.118 alpha:1.000]; //whatever goes well with your background image.
    UIImage *img  = [UIImage imageNamed: @"your-navbar-img.png"];
    [img drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    [img release];
    self.tintColor = color;
    [super drawRect:rect];
}
@end

I've tested and it is working well.
P.S: I've tested with 4.3 last night & it didn't work as expected but works fine with 4.2. I don't find any reasons yet, will update once I find right snippet.
For 4.3 and above, you should subclass the UIToolbar or UINavigationBar category addition is not supported. The following code works with 4.3
#import <UIKit/UIKit.h>

@interface MyAppToolBar : UIToolbar{

}

@end

@implementation MyAppToolBar

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    UIColor *color = [UIColor colorWithRed:0.547 green:0.344 blue:0.118 alpha:1.000]; //wood tan color
    UIImage *img  = [UIImage imageNamed: @"your-navbar-img.png"];
    [img drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    [img release];
    self.tintColor = color;

}

@end

The problem with the limitation is, you need to change the customclass of every UIToolbar object you have in all of your XIB file. And I'm afraid that it will not affect navigation bar when you open UIImagePickerController to match your app style.

A: Or you can Make custom class and assign it to your control (through interface builder) and inside that implement drawRect method...
like
- (void)drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed: @"CustomImage.png"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}

A: See this recent question: Custom logo on top of UINavigationBar?


text:
Q: Performance of static methods vs instance methods My question is relating to the performance characteristics of static methods vs instance methods and their scalability. Assume for this scenario that all class definitions are in a single assembly and that multiple discrete pointer types are required.
Consider:
public sealed class InstanceClass
{
      public int DoOperation1(string input)
      {
          // Some operation.
      }

      public int DoOperation2(string input)
      {
          // Some operation.
      }

      // … more instance methods.
}

public static class StaticClass
{
      public static int DoOperation1(string input)
      {
          // Some operation.
      }

      public static int DoOperation2(string input)
      {
          // Some operation.
      }

      // … more static methods.
}

The above classes represent a helper style pattern.
In an instance class, resolving the instance method take a moment to do as oppose to StaticClass.
My questions are:

*

*When keeping state is not a concern (no fields or properties are required), is it always better to use a static class?

*Where there is a considerable number of these static class definitions (say 100 for example, with a number of static methods each) will this affect execution performance or memory consumption negatively as compared with the same number of instance class definitions?

*When another method within the same instance class is called, does the instance resolution still occur? For example using the [this] keyword like this.DoOperation2("abc") from within DoOperation1 of the same instance.

A: In theory, a static method should perform slightly better than an instance method, all other things being equal, because of the extra hidden this parameter.
In practice, this makes so little difference that it'll be hidden in the noise of various compiler decisions. (Hence two people could "prove" one better than the other with disagreeing results). Not least since the this is normally passed in a register and is often in that register to begin with.
This last point means that in theory, we should expect a static method that takes an object as a parameter and does something with it to be slightly less good than the equivalent as an instance on that same object. Again though, the difference is so slight that if you tried to measure it you'd probably end up measuring some other compiler decision. (Especially since the likelihood if that reference being in a register the whole time is quite high too).
The real performance differences will come down to whether you've artificially got objects in memory to do something that should naturally be static, or you're tangling up chains of object-passing in complicated ways to do what should naturally be instance.
Hence for number 1. When keeping state isn't a concern, it's always better to be static, because that's what static is for. It's not a performance concern, though there is an overall rule of playing nicely with compiler optimisations - it's more likely that someone went to the effort of optimising cases that come up with normal use than those which come up with strange use.
Number 2. Makes no difference. There's a certain amount of per-class cost for each member it terms of both how much metadata there is, how much code there is in the actual DLL or EXE file, and how much jitted code there'll be. This is the same whether it's instance or static.
With item 3, this is as this does. However note:

*

*The this parameter is passed in a particular register. When calling an instance method within the same class, it'll likely be in that register already (unless it was stashed and the register used for some reason) and hence there is no action required to set the this to what it needs to be set to. This applies to a certain extent to e.g. the first two parameters to the method being the first two parameters of a call it makes.

*Since it'll be clear that this isn't null, this may be used to optimise calls in some cases.

*Since it'll be clear that this isn't null, this may make inlined method calls more efficient again, as the code produced to fake the method call can omit some null-checks it might need anyway.

*That said, null checks are cheap!
It is worth noting that generic static methods acting on an object, rather than instance methods, can reduce some of the costs discussed at http://joeduffyblog.com/2011/10/23/on-generics-and-some-of-the-associated-overheads/ in the case where that given static isn't called for a given type. As he puts it "As an aside, it turns out that extension methods are a great way to make generic abstractions more pay-for-play."
However, note that this relates only to the instantiation of other types used by the method, that don't otherwise exist. As such, it really doesn't apply to a lot of cases (some other instance method used that type, some other code somewhere else used that type).
Summary:

*

*Mostly the performance costs of instance vs static are below negligible.

*What costs there are will generally come where you abuse static for instance or vice-versa. If you don't make it part of your decision between static and instance, you are more likely to get the correct result.

*There are rare cases where static generic methods in another type result in fewer types being created, than instance generic methods, that can make it sometimes have a small benefit to turn rarely used (and "rarely" refers to which types it's used with in the lifetime of the application, not how often it's called). Once you get what he's talking about in that article you'll see that it's 100% irrelevant to most static-vs-instance decisions anyway. Edit: And it mostly only has that cost with ngen, not with jitted code.

Edit: A note on just how cheap null-checks are (which I claimed above). Most null-checks in .NET don't check for null at all, rather they continue what they were going to do with the assumption that it'll work, and if a access exception happens it gets turned into a NullReferenceException. As such, mostly when conceptually the C# code involves a null-check because it's accessing an instance member, the cost if it succeeds is actually zero. An exception would be some inlined calls, (because they want to behave as if they called an instance member) and they just hit a field to trigger the same behaviour, so they are also very cheap, and they can still often be left out anyway (e.g. if the first step in the method involved accessing a field as it was).

A:
When keeping state is not a concern (no fields or properties are
required), is it always better to use a static class?

I would say, yes. As declaring something static you declare an intent of stateless execution (it's not mandatory, but an intent of something one would expect)

Where there is a considerable number of these static classes (say 100
for instance, with a number of static methods each) will this affect
execution performance or memory consumption negatively as compared
with the same number of instance classes?

Don't think so, unless you're sure that static classes are really stateless, cause if not it's easy mess up memory allocations and get memory leaks.

When the [this] keyword is used to call another method within the same
instance class, does the instance resolution still occur?

Not sure, about this point (this is a purely implementation detail of CLR), but think yes.

A: Static methods are faster but less OOP. If you'll be using design patterns, static method is likely bad code. Business logic are better written as non-Static. Common functions like file reading, WebRequest etc are better as static. Your questions have no universal answer.