text:
Q: What does the single exclamation "!" mean after the type in Kotlin? I'm learning to Develop Android Apps using Kotlin. I previously used to Develop using Java. While coding in Android Studio, I can see that the return types, parameters, etc. used in the Lambdas, methods, etc. are written as View!.
I know that the ? after the type in Kotlin means a Nullable type. Though what does the ! mean.
For example:
val item = mySpinner.selectedItem

The return type is Any! What does the ! mean? Is it the same as a Nullable type i.e. Any? ?
Thanks.

A: It's a platform type  indicating that Kotlin is not sure whether it will  be null or not  null, it's like saying "maybe".

platform types can't be mentioned explicitly in the program, so there's no syntax for them in the language. Nevertheless, the compiler and IDE need to display them sometimes (for example, in error messages or parameter info), so there is a mnemonic notation for them:

*

*T! means "T or T?",

*(Mutable)Collection! means "Java collection of    T may be mutable or not, may be nullable or not",

*Array<(out) T>!    means "Java array of T (or a subtype of T), nullable or not"

And because it can either be null or not null, it is up to you how you will treat it.
Also check this another post


text:
Q: How to add Metatags/Search data to a domain I have two websites, one is the main website with everything on it, and the other which is a domain with a simple redirect to the main site. I just want to know how to add metadata/keywords/description and such to this domain without creating a new site.
How can I do this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Solving the infinite series $1-\frac{2^3}{1!}+\frac{3^3}{2!}-\frac{4^3}{3!}+\cdots$ I have the following question:

Evaluate the infinite series:
   $$S=1-\frac{2^3}{1!}+\frac{3^3}{2!}-\frac{4^3}{3!}+\cdots$$
  (a) $\displaystyle\frac1e$   (b) $\displaystyle\frac{-1}e$ (c) $\displaystyle\frac{2}e$ (d) $\displaystyle\frac{-2}e$

Now in the book they have given a strange explanation using $$(n+1)^3=[n(n-1)(n-2)+6n(n-1)+7n+1].$$ I don't understand how did they get this. So I have two doubts:

*

*How did they get this "trick"?

*If you would have got this question in a competitive exam, how would you have solved it (in the minimum amount of time), either directly or with numerical methods?

A: You want to evaluate $\sum_{n=0}^{\infty} \frac{(-1)^n(n+1)^3}{n!}$.
Now the idea (at the latest if you see some $e$ as a possible answer)  should be to relate this to the well-known formula
$$\sum_{n=0}^{\infty} \frac{x^n}{n!}=e^x$$
In this particular case (given the $(-1)^n$ included) it is useful to plug in $x=-1$ and obtain $$\sum_{n=0}^{\infty} \frac{(-1)^n}{n!}=e^{-1}=\frac{1}{e}$$
But you still have a $(n+1)^3$ in the numerator where you wish to have $1$.
So you might want to split this into several parts such that you get one (or several) related sums.
As an example of this technique, if you want to know $\sum_{n=0}^{\infty} \frac{n+1}{n!}$ you might try:
$$\sum_{n=0}^{\infty} \frac{n+1}{n!}=\sum_{n=0}^{\infty} \frac{n}{n!}+\sum_{n=0}^{\infty} \frac{1}{n!}$$
Now, the second sum is just $e$ and the first one is (after cancelling) $$\sum_{n=1}^{\infty} \frac{1}{(n-1)!}=\sum_{n=0}^{\infty} \frac{1}{n!}=e$$
and so the total sum is $2e$.
Can you now understand the "trick" and tackle your problem by yourself?
Concerning the second question:
If one happens to know this "trick", it is not hard to get the result by just a few computations so it would be my preferential choice.
But if you sit in the exam and have absolutely no idea of how to solve this algebraically (and especially if you don't have to give a proof of your result!) it might be a good idea to estimate the sum by computing a few terms. At least the sign of the result ($\pm$) should be approachable...

A: In general, if $p_i(x)$ is a sequence of polynomials with $\deg p_i=i$, then it is relatively easy to prove that every polynomial can be written as a linear combination of a finite number of $p_i$. When the $p_i$ are monic, you can do this easily. Let $P(x)=a_kx^k + ... a_0$. Then $P(x)-a_kp_k(x)$ is a polynomial of lower degree. Find it's first coefficient of that, and proceed inductively.
The standard basis for polynomials is $e_i(x)=x^i$.
So in your case; $p_i(n)=x(x-1)\cdots(x-(i-1))$ with $p_0(x)=1$. We chose this particular basis because $$\frac{p_i(n)}{n!} =\begin{cases}\frac{1}{(n-i)!} & n\geq i\\0&0\leq n<i\end{cases}$$
So:$$\sum_{n=0}^\infty \frac{p_i(n)z^n}{n!} = z^ie^{z}$$
In your case, $z=-1$.
With these polynomials, we get: $$\begin{align}(n+1)^3 &= n^3+3n^2+3n+1\\
(n+1)^3-p_3(n) &= n^3 +3n^2+3n+1 - (n^3-3n^2+2n)\\& = 6n^2+n+1\\
(n+1)^3-p_3(n)-6p_2(n) &= 6n^2+n+1 - 6n(n-1)\\&= 7n+1\\
\end{align}$$
So you get: $$(n+1)^3=p_3(n) + 6p_2(n) + 7p_1(n) +p_0(n)$$
The key is that the leading coefficient of the cubic $(n+1)^3$ is $1$, so we subtract $1\cdot p_3(n)$. Then the leading coefficient of the remaining quadratic is $6$, so we subtract $6p_2(n)$. The leading coefficient of the remaining linear polynomial is $7$, so we subtract $7p_1(x)$. You are left with a constant.
The relationship between the standard basis of the polynomials and the basis $p_i(x)=x(x-1)\cdots(x-(i-1))$ is actually fairly interesting and comes up again and again. The $p_i(x)$ are often called "falling factorials."

A: My way to solve it:
If the numerators were all $1$, we would have the well-known series for $e^{-1}$, obtained from the entire series
$$e^{-x}=\sum_{k=0}^\infty(-1)^k\frac{x^k}{k!}.$$
Now we want to make numerators $(k+1)^3$ appear. Multiply by $x$ and derive, to get
$$(xe^{-x})'=\left(\sum_{k=0}^\infty(-1)^k\frac{x^{k+1}}{k!}\right)'=\sum_{k=0}^\infty(-1)^k\frac{(k+1)x^k}{k!}.$$
Repeating this three times,
$$(x(x(xe^{-x})')')'=\sum_{k=0}^\infty(-1)^k\frac{(k+1)^3x^k}{k!}.$$
Then evaluate at $x=1$.
$$e^{-x}\to (1-x)e^{-x}\to (1-3x+x^2)e^{-x}\to (1-7x+6x^2-x^3)e^{-x}\to -\frac1e.$$

For such problems, you can often start from a known Taylor series (in particular $e^x$ and $1/(1-x)$)and perform the following operations

*

*multiply or divide by a power of $x$ (shifts the exponents),

*derive on $x$ (multiplies by the exponents),

*integrate on $x$ (divides by the exponents),

to modify the coefficients.

A: Since $(n+1)^3 = \color{red}{1}\cdot n(n-1)(n-2)+\color{red}{6}\cdot n(n-1) +\color{red}{7}\cdot n+\color{red}{1}$ we have:
$$\begin{eqnarray*}\sum_{n=0}^{+\infty}\frac{(-1)^n (n+1)^3}{n!} &=& \frac{13}{2}+\sum_{n\geq 3}\frac{(-1)^n (n+1)^3}{n!}\\&=&\frac{13}{2}+\color{red}{1}\cdot\sum_{n\geq 3}\frac{(-1)^n}{(n-3)!}+\color{red}{6}\cdot\sum_{n\geq 3}\frac{(-1)^n}{(n-2)!}+\color{red}{7}\cdot\sum_{n\geq 3}\frac{(-1)^n}{(n-1)!}+\color{red}{1}\cdot\sum_{n\geq 3}\frac{(-1)^n}{n!}\\&=&\frac{13}{2}-\sum_{n\geq 0}\frac{(-1)^n}{n!}+6\cdot\sum_{n\geq 1}\frac{(-1)^n}{n!}-7\cdot\sum_{n\geq 2}\frac{(-1)^n}{n!}+\sum_{n\geq 3}\frac{(-1)^n}{n!}\\&=&\sum_{n\geq 0}(-1+6-7+1)\frac{(-1)^n}{n!}\\&=&-\sum_{n\geq 0}\frac{(-1)^n}{n!}=\color{red}{-\frac{1}{e}}.\end{eqnarray*}$$
We simply get the initial decomposition by induction. Obviously $(n+1)^3-n(n-1)(n-2)$ is a quadratic polynomial in $n$, whose leading term is $6n^2$. So we substract $6n(n-1)$ and we are left with a linear polynomial and so on. Another chance is to tackle our problem this way:
$$\begin{eqnarray*} \sum_{n\geq 0}\frac{(-1)^n(n+1)^3}{n!}&=&\sum_{n\geq 1}\frac{(-1)^n n(n+1)^2}{n!}+\sum_{n\geq 0}\frac{(-1)^n(n+1)^2}{n!}\\&=&\sum_{n\geq 0}\frac{(-1)^n(n+1)^2}{n!}-\sum_{n\geq 0}\frac{(-1)^n(n+2)^2}{n!}\\&=&-\sum_{n\geq 0}\frac{(-1)^n(2n+3)}{n!}\\&=&-3\sum_{n\geq 0}\frac{(-1)^n}{n!}+2\sum_{n\geq 0}\frac{(-1)^n}{n!}=\frac{2-3}{e}.\end{eqnarray*}$$

A: Looking at the given identity:
\begin{align}
(n+1)^3 &= [n(n-1)(n-2)+6n(n-1)+7n+1] \\
&= n(n^2 - 3n + 2) + 6 n^2 + n + 1 \\
&= n^3 + 3 n^2 + 3 n + 1 = (n+1)^3
\end{align}
Now, consider differentiation of the exponential series:
\begin{align}
D \, e^{t} &= \sum_{n=0}^{\infty} \frac{1}{n!} \, \frac{d}{dt} \, t^{n} =
\sum_{n=0}^{\infty} \frac{n \, t^{n-1}}{n!}
\end{align}
Further differentiation can be applied.
Now, consider the series in question:
\begin{align}
S &= 1 - \frac{2^{3}}{1!} + \frac{3^{3}}{2!} - \cdots \\
&= \sum_{n=0}^{\infty} \frac{(-1)^{n} \, (n+1)^{3}}{n!} \\
&= \left. \sum_{n=0}^{\infty} \frac{(-1)^{n} \, (n+1)^{3} \, t^{n}}{n!} \, \right|_{t=1} \\
&= \left. t^{3} \, \sum_{n=0}^{\infty} \frac{(-1)^{n} \, n(n-1)(n-2) \, t^{n-3}}{n!} + 6 t^{2} \, \sum_{n=0}^{\infty} \frac{(-1)^{n} \, n(n-1) \, t^{n-2}}{n!} + 7 t \, \sum_{n=0}^{\infty} \frac{(-1)^{n} \, n \, t^{n-1}}{n!} + e^{-t} \, \right|_{t=1} \\
&= \left. t^3 \, D^{3} e^{-t} + 6 \, t^{2} \, D^{2} e^{-t} + 7 \, t \, D e^{-t} + e^{-t} \right|_{t=1} \\
&= \left. (-t^3 + 6 \, t^2 - 7 \, t + 1) \, e^{-t} \right|_{t=1} \\
&= - \frac{1}{e}
\end{align}


text:
Q: Что такое bash? Подскажите для понимания:
можно ли сказать, что Bash — это просто расширение функционала Shell, как в случае PowerShell к cmd?

A: Это два разных вопроса. Их стоило бы разделить.
По второму вопросу: bash - это не расширение над sh ( если я правильно понял, что Вы понимаете под Shell ). Это отдельная оболочка, в которой многие вещи обратно совместимы с sh, но некоторые - нет.

A: unix shell (оболочка операционной системы unix) — это стандарт, являющийся частью набора стандартов posix.
программа bash — это одна из множества реализаций стандарта unix shell.

да, как и практически любая из реализаций практически любого стандарта, программа bash «умеет» значительно больше, чем описано в стандарте unix shell, но называть программу «расширением стандарта», естественно, неправильно.

A: Строго говоря и PowerShell -- не совсем расширение для cmd, сказанное выше об отношении bash к shell применимо и к PowerShell: это другая оболочка, обратно совместимая с cmd.

A: Ныне /bin/sh это алиас на что-нибудь в системе, но изначально bash это расширение обычного sh (  усовершенствованная и модернизированная вариация командной оболочки Bourne shell (sh).читаем тут . Если скрипт с башизмами - то использовать нужно /bin/bash, если POSIX-совместим - то /bin/sh.
Ссылки раз, два


text:
Q: HTTP Error 502.5 running ASP.NET Core 2.0 app from IIS I'm getting an HTTP 502.5 error when trying to run my ASP.NET core 2.0 web app from IIS.
I've installed the .NET Core Windows Server Hosting Bundle and checked all my IIS settings as per this document https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/index?tabs=aspnetcore2x
The web.config looks like this.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath="dotnet" arguments=".\OscarWeb.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" />
  </system.webServer>
</configuration>

The Windows event log produces the following errors.

It is IIS v6.2 running on Windows Server 2012 R2. The web application was built using ASP.NET Core 2.0.
When I run dotnet from the commandline as follows there are no errors:
dotnet oscarweb.dll

A: The first thing you have to do in this scenario is to create the logs folder if it is missing and check the stdout logs generated.
It can be several different things but from personal experience the most common issue i had was IIS not having enough permissions to run it. In IIS you can configure the Identity used in Advanced Settings. If it is using ApplicationPoolIdentity then change it to LocalSystem and see if it works. The logs in the stdtout file however will give you the answer.

A: The solution to this problem (in my case at least) was to reboot the web server. After installing the .NET Core Windows Server Hosting Bundle you need to reboot the server for them to be registered correctly.
Thanks to Chris Pratt (first comment underneath my question) for suggesting the answer :)

A: Not sure if your webconfig is complete. I believe aspnetcore tag needs to have the ASPNETCORE_ENVIRONMENT environment variable set as well.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath="dotnet" arguments=".\OscarWeb.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" >
        <environmentVariables>
            <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="YourRuntimeEnv" />
        </environmentVariables>
    </aspNetCore>
  </system.webServer>
</configuration>


text:
Q: Set GC time limit / Remove allocation in Events Is there a way to set a time limit on the GC?
I'm asking because I'm writing a game which allocates some floats, ints and longs on each event, and I'd rather call the GC for a short period of time (5-20ms) to remove those. I'd then call the GC in each Game Loop. This way would be my personal favourite as I still have some allocations which I can't backtrace without a lot of effort (I've already removed most stuff).
Alternatively I'd look for the other allocations and prevent them somehow, but then I'd need a way to prevent allocations in events.
Here's the result of allocation tracker if needed: http://textsave.de/?p=67220
EDIT:
I can't really find anything with the allocation tracker, all the objects are from some far off java-internal class (even in the trace). Also, the shown objects are nowhere near the numbers being collected (unless the garbage collector counts float[] as multiple objects).
Anybody have this problem?

A:
Is there a way to set a time limit on the GC?

No, but it is already fairly short.

I'm asking because I'm writing a game which allocates some floats, ints and longs on each event

Don't do that. Pre-allocate your memory.

and I'd rather call the GC for a short period of time (5-20ms) to remove those. I'd then call the GC in each Game Loop

You are welcome to call System.gc(), but you cannot control the duration for which it runs. It is usually on the order of low tens of milliseconds. However, you are better served by avoiding the allocations in the first place, by maintaining your own object pool.


text:
Q: Can 'npm update' use global packages? If I have a Node.js package with a missing node_modules folder. Executing the npm update command will create and properly populate the node_modules folder with all the necessary packages.
What I don't understand is;

*

*Why does it include packages which are already present in the global node_modules folder?

*Why will it not create folder links instead?

*Am I missing a command line parameter?
Thanks!
Edit:

*

*Running the npm update -g command will not solve the problem.

*I don't know if it is relevant information, but I'd like to solve it in Windows OS.

A: Global and local packages are treated differently (rightly so!).
npm update -g will update all global packages
This is documented here.


text:
Q: Define method parameters for meta programming in Ruby In Ruby, we can define instance methods with meta-programming like:
define_method(:hi) { 'Hello, SO world!' } # => :hi
hi                                        # => "Hello, SO world!"

This way, it is possible to define a method with a dynamic name:
dynamic_name = :hi                                 # => :hi
define_method(dynamic_name) { 'Hello, SO world!' } # => :hi
hi                                                 # => "Hello, SO world!"

We can also inject arguments in to a dynamic method:
dynamic_name = :hi # => :hi
define_method(dynamic_name) do |arg1, arg2, &block|
  'Hello, SO world!'
end                # => :hi
hi(42, 42) { 42 }  # => "Hello, SO world!"

So far, so good.
But how could we do to inject dynamic arguments?
Would it be possible to replace arg1, arg2, &block by a dynamic notation?
Thanks for any tips, best practices, or even ideas.
Edit:
In other words, I would like to dynamically also define the parameters and the block of an instance method.
However, I would like to do so with a particular number of parameters (which could be 0), an array in option, and to finish the block of the method.
This way, I could avoid having methods such as:
dynamic_name = :hi      # => :hi
define_method(dynamic_name) do |*args, &block|
  'f'
end                     # => :hi
hi                      # => "f"
hi(:foo)                # => "f"
hi(:foo, :fooo)         # => "f"
hi(:foo, :fooo, :foooo) # => "f"

...which is a nonsense, because here we can give to the method an infinite number of unused parameters.  I would like to avoid this situation.
Edit 2:
The reason is the following:
In Ruby, when we need a method which do not need any parameters, we can simply do:
def my_method
  "Hello, SO world!"
end

However, if instead I do this:
def my_method(*args)
  "Hello, SO world!"
end

...the result is still the same, but because the parameter (the array args) is useless, it would be better to keep it simple by removing it from the method.

A: Try passing an array or dictionary.
UPDATE:
if condition1
  class_eval <<-EVAL
    def #{"my_method"}(arg1)
    end
  EVAL
else
    class_eval <<-EVAL
      def #{"my_method"}
      end
  EVAL
end

UPDATE2:
if condition1
  self.instance_eval <<-EVAL
    def #{"my_method"}(arg1)
    end
  EVAL
else
    self.instance_eval <<-EVAL
      def #{"my_method"}
      end
  EVAL
end

UPDATE3:
# or
self.instance_eval("def method1(arg1) puts 'hellowa' + arg1.to_s; end")
self.instance_eval("def method2() puts 'hellowa2'; end")

# and then
method1(33) # => hellowa33
method2 # => hellowa2


text:
Q: javascript stacking bug I have this code:
 $jq('.pop-tip').click( function(event) {
        width = '';
        height = '';
        var img = new Image();
        img.onload = function() {
            width = 'width='+(this.width + 240);
            height = 'height='+(this.height + 360);
        }
        img.src = 'http://www.domain.com/uploads/2011/10/dealoftheweek.jpg';
        destination = $jq(this).attr('title');
        postPop = $jq(this).attr('href');
        alert ( width );
        window.open(postPop, 'tip_pop',''+ width +', '+ height +', scrollbars=0' ).focus();
        window.open(destination, '_parent','' );
        event.preventDefault();
)};

For some reason it only works with the alert() just above the window.open call why is this and how can i fix it?

A: It is because you are setting height and width in onload event which will occur only after image is totally loaded.
Putting an alert will let the image load completely, by the time you click alert's ok, the image's onload will get called and the values would be set. But if u remove that, the height and width values are not set and so it would not work.
you can fix this by calling rest of the code inside the onload event.

A: Image load is asynchronous; the code continues executing while your image loads. Then you hit the window.open line, which needs width and height, which are not yet defined. A few milliseconds later, your image loads, and so do your width and height.
With the alert, you delay the window.open call long enough for the image to finish loading, and the dimension variables will be ready to be used when you click the "OK" button.
The solution is to stuff the window.open, and everything that depends on the data from the image, inside the img.onload handler function.
EDIT: damn, I type slowly :P And Tomalak... ROFL


text:
Q: User-Marked Polygon on existing image I need to create a program that presents a certain image for the user, lets him mark a polygon on the image and returns the coordinates of the polygon marked.
Is there something allready implemented that could give me this functionality??
thanks in advance


text:
Q: Splitting Zip Files Based on Number of Files, Not Size I'm looking to setup an automater script on my Mac.
On a daily basis I'm compressing thousands of files into groups of 75 files by manually selecting the 75 and compressing them.
Is there a way to setup an automater script to where I can highlight 1000 images and run a script that would take 75 files at a time and zip them together without me having to manually select the 75 files?


text:
Q: Pointer is not incremented (moved) to expected location or pointer arithmetic is not providing expected answer In the following snippet of code I expect pointer to move to next location i.e. current location + sizeof(datatype) but not happening unless I type cast to int.
#include <iostream>
#include <string.h>

int sizeOf()
{
    int a = 0;
    int* b = &a;
    int* c = &a;
    c++;// expect pointer to move "current location + sizeof(int)"
    return c - b;
}

int main()
{
    std::cout << "Size of int is " << sizeOf() << ", actual size of int is  "<< sizeof(int) << "\n";
    return 0;
}

Output:
Size of int is 1, actual size of int is  4

Expectation: if I increment pointer of type int then pointer should move to current location + sizeof(int) but not happening
But it actually works when I use following line
return (int)c - (int)b;

Compiler warns
my-pc $ g++ test.cpp -fpermissive
test.cpp: In function 'int sizeOf()':
test.cpp:10:17: warning: cast from 'int*' to 'int' loses precision [-fpermissive]
   10 |     return (int)c - (int)b;
      |                 ^
test.cpp:10:26: warning: cast from 'int*' to 'int' loses precision [-fpermissive]
   10 |     return (int)c - (int)b;
      |                          ^

my-pc $ ./a.out
Size of int is 4, actual size of int is  4

Now I got the output what I expect. I know int* is typecasted to int. I want to know the reason why it did not worked in first case and worked later.

A: The difference is in terms of the size of the pointed object.
So a difference of 1 means the pointers point to 1 * sizeof(int) bytes apart.
For example,
&( a[2] ) - &( a[0] )

always gives 2 for a C array. It doesn't matter if it's an array of char, int, or some struct.
And it's easy to show why this is necessary, given that a[i] is equivalent to *(a+i) for a C array.
   &( a[2] ) - &( a[0] )
=  &( *( a + 2 ) ) - &( *( a + 0 ) )
=  ( a + 2 ) - ( a + 0 )
=  2


text:
Q: "Authentication is required to refresh the system repositories" A few months ago, I updated Debian to 10.  (I believe I'm using Wayland and GNOME?)  Among the several problems that suddenly started occurring is the following:
Once in a while, I'll come back to my computer, and there will be a password dialog reading "Authentication required" and "Authentication is required to refresh the system repositories".  It has a password box, a cancel button, and an authenticate button.  The cancel button does nothing.  If I type in my password and click the authenticate button, a "thinking" spinner pops up next to the password box...and never goes away.  There's a "Sorry, that didn't work.  Please try again." text below the password dialog, but I can't remember if that is always there, or if it shows up after e.g. hitting cancel.  The has happened a handful of times.  I think in one of the cases, hitting cancel actually removed a layer (out of several dozen) of dialogs, so eventually I was able to cancel them all?  That's only once been the case, though, and the problem happening right now (I'm on a different computer) seems not to respond to the cancel button at all.
I've tried googling the message, but solutions were far and few between, and were largely inapplicable - for instance, one said to uninstall "appcenter", but Aptitude doesn't recognize any packages containing that name.  I have root access to the virtual terminals, btw.  I've tried looking for ways to just "make the dialog go away", via root, like looking for likely processes and killing them.  Technically this has worked, but also killed my entire desktop environment, and everything I was working on.
What I'd like - well, what I need is probably a fix to make the dialog stop appearing (or at least accept cancel/password).  I'd also accept a method of killing it without losing the other windows I have open.  BOTH would be preferable, since the latter seems useful to have.  Does anybody know either of these, or even a way of debugging the source of the issue?


text:
Q: USB to Serial, Port Name Changing Unexpectedly I've got a Windows 7 Pro 64 PC with a FTDI based 4 port USB to RS232 converter.  I've been having periodic problems with the port name (port numbers) changing.  Most recently this occurred when the USB cable got accidently yanked out of the PC while connected to one device.  The original port numbers were 3, 4, 5, 6.  When I plugged the cable back in the ports were reallocated as 7, 8, 9, 10.
Does anyone have any ideas on how to prevent Windows from reassigning the port names / numbers?


text:
Q: Globals and when they need to be declared In the following code:
>>> import time
>>> cache = {}
>>>
>>> def squared(num):
...     if num in cache: return cache[num]
...     print ("Calculating...")
...     time.sleep(1) # fake a calculation
...     result = num * num
...     cache[num] = result
...     return result
...
>>> squared(2)
Calculating...
4
>>> squared(2)
4
>>> cache
{2: 4}

Why is it that I can modify the cache from within the function and don't have to call global in the function? Is global directly related to whether a variable is mutable/immutable, or why does it work in the above case?

A: Your function sees the outside cache variable.
Because it is mutable it can mutate it and it can be seen inside the function as well as outside the function.
You will need to use global if you want to assign a new value to a name and want also the outer name to be bound to this value.
For example if you want to assign 3 to the name "cache" you use cache =3. If you don't declare it as global it would be a simple local variable inside the function and the outer cache name will still be bound to its original value.


text:
Q: Drag/Drop con Raphael.js, cualquier botón del mouse inicia dragstart Buen día,
Estoy utilizando raphael.js para manipular imágenes dentro de un "paper"
He notado que todos los eventos (click, mousedown, mouseup, dragstart...) se inician con cualquier botón del mouse.
En este JSFiddle hay un ejemplo de drag a dos objetos, es posible moverlos con el click izquierdo, derecho y central del mouse
¿Cómo puedo hacer para que el click derecho y medio no puedan hacer drag a un objeto?
He leido que para diferenciar qué botón inicia el evento puedo utilizar e.which, que devuelve 1, 2 ó 3 dependiendo del botón que se utilizó pero no he encontrado la forma de utilizar esta variable para filtrar el inicio de un click, mousedown o drag
Encontré un Bug report sobre el tema pero no ha solucionado desde el 2012. Intenté utilizar el código que viene en el reporte comentándolo todo y excepto la parte de if(e.which == 1) para luego hacer una entrada en la consola. Al hacer esto la entrada únicamente aparece cuando intento hacer drag con el click izquierdo así que en teoría está bien pero no encuentro forma de adaptar lo demás
Alguien sabe que es g.doc.documentElement o g.doc.body?
De antemano muchas gracias
Saludos

A: He encontrado una forma de hacerlo.
En lugar de instalar raphael.js con npm install raphael, descargué el archivo js desde github, al tener el código fuente edité la función drag de la siguiente forma:
elproto.drag = function (onmove, onstart, onend, move_scope, start_scope, end_scope) {
        function start(e) {
            if (e.which == 1) {
                (e.originalEvent || e).preventDefault();
                var x = e.clientX,
                    y = e.clientY,
                    scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
                    scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft;
                this._drag.id = e.identifier;
                if (supportsTouch && e.touches) {
                    var i = e.touches.length, touch;
                    while (i--) {
                        touch = e.touches[i];
                        this._drag.id = touch.identifier;
                        if (touch.identifier == this._drag.id) {
                            x = touch.clientX;
                            y = touch.clientY;
                            break;
                        }
                    }
                }
                this._drag.x = x + scrollX;
                this._drag.y = y + scrollY;
                !drag.length && R.mousemove(dragMove).mouseup(dragUp);
                drag.push({el: this, move_scope: move_scope, start_scope: start_scope, end_scope: end_scope});
                onstart && eve.on("raphael.drag.start." + this.id, onstart);
                onmove && eve.on("raphael.drag.move." + this.id, onmove);
                onend && eve.on("raphael.drag.end." + this.id, onend);
                eve("raphael.drag.start." + this.id, start_scope || move_scope || this, this._drag.x, this._drag.y, e);
            }
        }
        this._drag = {};
        draggable.push({el: this, start: start});
        this.mousedown(start);
        return this;
    };

Se tiene que agregar la condición e.which==1 para cada evento de raphael en caso de que se desee distinguir el botón de mouse que inicia el evento
Espero que la información sea de utilidad


text:
Q: mouse over and mouse out. Collapse content header when hovering I am trying to get a simple collapse on a content header that has list items below it.  Currently the JavaScript I am using is set to onClick.  I want to change this to mouseOver (to expand) and mouseOut (to go back to collapse). Here is the JSfiddle.
I don't know much about JavaScript yet, but I am working on it.  Thanks.
function headerClicked(headerObj) {
  if ($(headerObj).parent().find('.contentList').css('display') == 'none') $(headerObj).parent().find('.contentList').slideDown(300);
  else $(headerObj).parent().find('.contentList').slideUp(300);
}

A: I see you are using JQuery, why not add an event handler to react when the mouse get's on or leaves the header? You can do this with the mouse mouseout function from JQuery.
You can write something like this for when the mouse leaves
$(".header").mouseout(function(e){
    $(e.currentTarget).parent().find('.contentList').slideUp(300)
})

The docs are here http://api.jquery.com/mouseenter/ and http://api.jquery.com/mouseout/

A: There are a lot of solutions of your problem. e.g it can be handled easily using jQuery hover
http://api.jquery.com/hover/ . But for this time, the simplest solution can be the following one...
http://jsfiddle.net/r486Y/
Here, instead of using 'onClick' function I have used two functions, one for 'onmouseover' and another one for 'onmouseleave' the functions are as following...
function headerClicked(headerObj) {
       $(headerObj).parent().find('.contentList').slideDown(300);
}
function headerClickedUp(headerObj) {
       $(headerObj).parent().find('.contentList').slideUp(300);
}

Do not forget to add
.contentList
{
    display:none;
}

to the css to hide the '' at the time of page loading.
To use it as drop down list reorder it as following...
http://jsfiddle.net/69gNB/


text:
Q: The output of numerical calculation of BCEWithLogitsLoss for PyTorch example When I looked the example code of BCEWithLogitsLoss in PyTorch Docs. I am confusing about the output result of loss function and formula.
PyTorch Example:
>>> loss = nn.BCEWithLogitsLoss()
>>> input = torch.randn(3, requires_grad=True)
>>> target = torch.empty(3).random_(2)
>>> output = loss(input, target)
>>> output.backward()

input : tensor([0.4764, -2.4063,  0.1563], requires_grad=True)
target: tensor([0., 1., 1.])
output: tensor(1.3567, grad_fn=<BinaryCrossEntropyWithLogitsBackward>)

But according to the formula by showing:

The output of loss function should have shape (3,) instead of single value ,since the shape of input and output both are (3,) . I was thinking that the output may was the sum of Ln or else, but still no idea. Could someone help me to explain that?
As @Dishin H Goyani reminded that the default reduction is 'mean'. I did a simple test.
>>> target_n = target.numpy()
>>> input_n  = input.detach().numpy()
>>> def sigmoid(array):return 1/(1+np.exp(-array))
>>> output_n = -1*(target_n*np.log(sigmoid(input_n))+(1-target_n)*np.log(1-sigmoid(input_n)))
output_n : array([0.95947516, 2.4926252 , 0.61806685], dtype=float32)
>>> np.mean(output_n)
1.3567224

The result is matched.
As you seen, the default Wn is 1.

A: As reduction parameter default value is 'mean' in BCEWithLogitsLoss.
The output is mean - the sum of the output will be divided by the number of elements in the output.
Read Doc here for more detail:
Parameters
...
reduction (string, optional) – Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.

'none': no reduction will be applied,
'mean': the sum of the output will be divided by the number of elements in the output,
'sum': the output will be summed.

Note: size_average and reduce are in the process of being deprecated, and in the meantime, specifying either of those two args will override reduction. Default: 'mean'
...


text:
Q: ng-file-upload directive not working with ng-messages I am using ng-file-upload directive to upload multiple mp3 files and want to apply validation for wrong file extention.

        {{constant.SELECT_FILE_OR_MULTIPLE_FILES}}:
        <input
            type="file"
            ngf-select
            ng-model="series.myfiles"
            name="myfiles"
            id="myfiles"
            ngf-max-size="100MB"
            ngf-validate="{ pattern: '.mp3' }"
            multiple

            />

{{constant.UPLOAD_TALK_ERROR}}

A: As said in comment : the answer was that the field's name generated in the $error is not ngf-validate but depends of the type of validation.
Here it is a pattern match so the name of the error is pattern


text:
Q: Docplex vs CPLEX Python API What is the difference between Docplex and CPLEX Python API? Is any of them faster than the other?

A: The CPLEX Python API is a lightweight wrapper around the C API (aka, the C Callable Library). As such, it provides access to nearly all of the functionality CPLEX has to offer. Variables and constraints are identified by their indices in the matrix.
docplex is an object oriented modeling API that is numpy/pandas friendly, which may be more natural to work with. The model can be solved locally (using the CPLEX Python API under the hood), or on the cloud. In addition to providing access to CPLEX for mathematical programming, it can also be used to access the CP Optimizer constraint programming engine.
It is usually faster to build the model directly with the CPLEX Python API as it is a lower-level API. However, docplex can take care of some of the intricacies of getting the best performance when building a model while only incurring a relatively low overhead. The actual solve time should be more or less identical.


text:
Q: SwitchToThisWindow
Possible Duplicate:
How can I bring my application window to the front?

I am having an issue with SwitchToThisWindow
using System;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace BringToFront
{
    public partial class Form1 : Form
    {
        [DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
        public static extern IntPtr FindWindow(String className, String windowName);

        [DllImport("user32.dll", SetLastError = true)]
        static extern void SwitchToThisWindow(IntPtr hWnd, bool turnOn);

        [DllImport("user32.dll")]
        public static extern IntPtr GetForegroundWindow();

        IntPtr activeWindowHandle = GetForegroundWindow();

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (!checkBox1.Checked)
                    bringToFront(comboBox1.SelectedItem.ToString());
                else
                    timer1.Enabled = true;
            }
            catch
            {
                MessageBox.Show("Please choose a Process Name");
            }
        }

        public static void bringToFront(string title)
        {
            IntPtr handle = FindWindow(null, title);
            if (handle == IntPtr.Zero)
            {
                return;
            }
            SwitchToThisWindow(handle, true);
        }

        private void comboBox1_Click(object sender, EventArgs e)
        {
            comboBox1.Items.Clear();
            Process[] process = Process.GetProcesses();
            foreach (Process processes in process)
            {
                if (!String.IsNullOrEmpty(processes.MainWindowTitle))
                    comboBox1.Items.Add(processes.MainWindowTitle.ToString());
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            Process process = Process.GetCurrentProcess();
            string title = process.ProcessName.ToString();
            IntPtr handle = FindWindow(null, title);

            if (activeWindowHandle != handle)
                bringToFront(comboBox1.SelectedItem.ToString());
            if (!checkBox1.Checked)
                timer1.Enabled = false;
        }
    }
}

As you can see I'm trying to bring the process that is selected to the front and keep it in the front by doing a timer every 5 seconds and rebringing it to the front. It works perfectly when running the application through Microsoft Visual Studios, but when I run the program as a standalone, it works how every other function like this does and only makes it flash in taskbar instead of bringing it to the front.
Why are the permissions different and is there anyway to fix this?

A: Via the solution by @ReedCopsy here, I suggest to make the selected handle TopMost after you've switched to that window. Using this solution, no new app can become top over the selected window.
Add the following to your code:
 [DllImport("user32.dll")]
 static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

 static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
 const UInt32 SWP_NOSIZE = 0x0001;
 const UInt32 SWP_NOMOVE = 0x0002;
 const UInt32 SWP_SHOWWINDOW = 0x0040;

and change your bringToFront by adding a call to SetWindowPos:
   public static void bringToFront(string title)
    {
        IntPtr handle = FindWindow(null, title);
        if (handle == IntPtr.Zero)
        {
            return;
        }
        SwitchToThisWindow(handle, true);

        // Call this way:
        SetWindowPos(handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
    }


text:
Q: How to define by using C# code a space between controls? I have a PictureBox and two labels that I make dynamically in a loop. How do I calculate from picbox1 location, the label1 and label2 locations, so that align as the following example:
picbox1 label1
label2
Seems a calcula somewhat simple, but I really not thought how do now.

A: Something like this, though for simplicity, I omitted the labels.
It starts at point p, and stacks the controls (a text box and a picture box to the right), then loops.
Point p = new Point(15,35);
foreach (var field in fields)
{
   Label lbl = new Label {Text = field.Key, Location = p, AutoSize =  true};
   Point ppic = lbl.Location;
   ppic.Offset(lbl.Width + 20, 0);
   Control pic;
   pic = new PictureBox {Width = 400 - ptxt.X, Location = ppic};
   p.Offset(0, pic.Height + 3);
}

A: This might help:
label1.Position=new Point(picbox1.Right, picbox1.Top);
label2.Position=new Point(picbox1.Left, picbox1.Bottom);


text:
Q: ArrayList, Each object can only exist in one ArrayList at a time I have two simple classes, NetworkDevice.java and Channel.java
in Channel.java i have
private ArrayList<Channel> channel = new ArrayList<Channel>();

which i am trying to change to store only NetworkDevices
The specification i am trying to get is:

Each NetworkDevice has the ability to join a Channel, but can only
  exist in one Channel at a time.

NetworkDevice.java is shown below
    public class NetworkDevice {

    // Fields
    private String address;
    //Constructor
    public NetworkDevice(String address, Channel channel){
        this.address = address;
        addToChannel(channel);
    }

    // Add a NetworkDevice to the
    public void addToChannel(Channel channel){
            channel.addChannel(this);
    }
}

Channel.java shown below
   import java.util.List;
import java.util.ArrayList;

public class Channel {

    // Fields
    private ArrayList<Channel> channel = new ArrayList<Channel>();
    private int number;
    private List<Packet> packet;

    /*
     * Constructor
     * Initializes the number of the the Channel
     * Allows for a packet to be passed in
     */
    public Channel(int number, Packet packets) {
        this.number = number;
        packet.add(packets);
    }

    /*
     * Adds to the Channel array
     * @Param a network device object
     */
    public void addChannel(NetworkDevice device) {
        channel.add(this);
    }
}

A: It looks like you messed up quite a few names and concepts there.
I rewrote the code a bit so it makes sense to me. That is, me,  without any real clue what is to be achieved. But see what results my code brings:
public class MultiInst {
    static public class NetworkDevice {
        private final String    mAddress;
        private Channel         mCurrentChannel = null;

        public NetworkDevice(final String address, final Channel channel) {
            this.mAddress = address;
            addToChannel(channel);
        }

        public void addToChannel(final Channel channel) {
            if (mCurrentChannel == channel) return; // may do this
            if (mCurrentChannel != channel && mCurrentChannel != null) mCurrentChannel.removeNetworkDevice(this);

            mCurrentChannel = channel;
            mCurrentChannel.addNetworkDevice(this);
        }

        @Override public String toString() {
            return mAddress;
        }
    }

    static public class Channel {

        private final ArrayList<NetworkDevice>  mNetworkDevices = new ArrayList<>();
        private final List<Packet>              mPackets        = new ArrayList<>();
        private final int                       mNumber;

        public Channel(final int number, final Packet... packets) {
            this.mNumber = number;
            if (packets != null) for (final Packet p : packets) {
                mPackets.add(p);
            }
        }

        public void addNetworkDevice(final NetworkDevice device) {
            mNetworkDevices.add(device);
        }
        public void removeNetworkDevice(final NetworkDevice device) {
            mNetworkDevices.remove(device);
        }

        @Override public String toString() {
            String acc = "Channel #" + mNumber + ":\t";
            if (mNetworkDevices.size() < 1) return acc + " [EMPTY] ";
            for (final NetworkDevice c : mNetworkDevices) {
                acc += "\t" + c;
            }
            return acc;
        }
    }

    public static void main(final String[] args) {
        final Channel c1 = new Channel(1);
        final Channel c2 = new Channel(2);
        final NetworkDevice d = new NetworkDevice("lol", null);

        System.out.println("Start\n");

        System.out.println(c1);
        System.out.println(c2);
        System.out.println();

        System.out.println("Adding to channel 1...");
        d.addToChannel(c1);
        System.out.println(c1);
        System.out.println(c2);
        System.out.println();

        System.out.println("Adding to channel 2...");
        d.addToChannel(c2);
        System.out.println(c1);
        System.out.println(c2);
        System.out.println();

        System.out.println("End");
    }

}

will create the output
Start

Channel #1:  [EMPTY]
Channel #2:  [EMPTY]

Adding to channel 1...
Channel #1:     lol
Channel #2:  [EMPTY]

Adding to channel 2...
Channel #1:  [EMPTY]
Channel #2:     lol

End


text:
Q: Is there a way to return the top or second parent element of a specified element using JavaScript? I would like to get the top parent element (section) of a myLI id.
My HTML code is:

Coffee

Tea

My code is:
var x = document.getElementById("myLI").parentElement.nodeName;

My code returns UL but I would like for it to return section.

A: If you want to target the parent by tagName you could use .closest(selector); like :
var x = document.getElementById("myLI").closest('section');

NOTE : Take a look to the Browser compatibility section.
Hope this helps.

var x = document.getElementById("myLI").closest('section');

console.log(x.tagName);

Coffee

Tea

A:

var topParent = document.getElementById("myLI");
while( topParent.parentElement.nodeName != 'BODY' ){
  topParent = topParent.parentElement;
  }
  console.log( topParent.nodeName );

Coffee

Tea

So I'm assuming you want the element right before the 'BODY' element?

A: "I will probably have it execute when a user clicks a radio button or on some type of click."
Then just set up the click event on the section elements:

var sections = Array.prototype.slice.call(document.querySelectorAll("section"));

sections.forEach(function(section){
  section.addEventListener("click", function(){
    console.log(this.id);
  });
});

Coffee

Tea

Coffee

Tea

Coffee

Tea


text:
Q: Getting started with blackberry Push notification Where do I register with RIM to get push notifications in my app? Are there other alternatives apart from urbanairship?
Thanks.

A: Inorder to get the push notifications for your blackberry application , you need to register the application in RIM for receiving the application Id and other credentials.
If you are looking for a sample code to implement push registration from device,check the link below :
Simplified BIS-Push client sample
You could use xtify instead of urbanarirship. try this Xtify


text:
Q: 2 processes with the same name. How do I only end one of them? I have a small "problem" windows has a system file that cant be killed csrss.exe but if there is another file named csrss.exe in a different folder and it is running, how do I end its process? All i would know about the file is it's location and name/size.. basic file info.
lol i answered my question with a question.. anyway i just wanted to say I dont want to kill the process of the system file csrss, i want to kill the process of a file who happens to have the same filename & process name. is it even possible?

A: I'm not saying should kill the csrss.exe process, but you could check the main ProcessModule.FileName property that contains the full path to the executable if you want to find specific processes with the same name:
Process process = // Get your process here
process.Modules[0].FileName == "C:\\MyPath\csrss.exe";

A: If you would like to end a process based on its FileInfo such as Size/Attributes/etc.... Then, this is possible! Here's a simple example
Example
int FileSize = 0; //This belongs to the process you would like to terminate
//Create the process csrss for every process with the name csrss
foreach (Process csrss in Process.GetProcessesByName("csrss"))
{
     FileInfo csrssFile = new FileInfo(csrss.StartInfo.FileName); //Get the properties of its file name
     if (csrssFile.Length == FileSize)
     {
         csrss.Kill(); //Terminate the process based on its file length (size)
     }

}

Another Example
int FileSize = 0;
Process[] RunningProcesses = Process.GetProcesses();
foreach (Process csrss in RunningProcesses)
{
     if (csrss.ProcessName == "csrss")
     {
          FileInfo csrssFile = new FileInfo(csrss.StartInfo.FileName);
          if (csrssFile.Length == FileSize)
          {
               csrss.Kill();
          }
     }
}

Thanks,
I hope you find this helpful :)


text:
Q: Are disposable fields of disposable classes disposed of automatically My question is fairly straightforward: If a class that implements IDisposable has fields which are also disposable, will disposing of the instance also dispose of the field values?
Example:
Say I have a class, OuterDisposable, which has a field innerDisposable, who's type is another disposable class:
public class OuterDisposable : IDisposable
{
    private InnerDisposable innerDisposable;
}

I intend to wrap all instances of OuterDisposable in a using statement so that they are disposed of automatically and safely:
using (var outerDisposable = new OuterDisposable())
{
    // Stuff
}

However, I'm not sure what will happen to innerDisposable once the end of the using is reached. It is very important that it is disposed of correctly, so I need to be sure what the behavior will be.
I presume explicitly disposing of innerDisposable will achieve my desired result:
public void Dispose()
{
    this.innerDisposable.Dispose();
}

But is this necessary? If the outer using statement takes care of disposing innerDisposable as well as outerDisposable, then it is redundant.
So, how are such disposable fields handled?

A: IDisposable is an interface and a pattern. It's not really part of the C# language, outside of explicit support in using and foreach. Nothing happens "automatically".
Consider, contrariwise, if this disposal did happen automatically. And consider further that it's perfectly valid for a class to hold a reference to a shared resource of some kind that may be disposable. You would have to invent new syntax to then be able to "opt out" of this automatic disposal that you were looking for.
C# is a simpler language by not having such a feature. It's always your responsibility to clean up IDisposable objects at a time when you, the programmer, know that they're no longer being used. Often, for a class such as the one here, that will be when your own Dispose method is being called.


text:
Q: Presenting Fullscreen Modal View controller from PageSheet Modal View Controller on iPad Actually two questions in one, but occurring together so bear with me...
My iPad (landscape) app presents a modal view controller in the .PageSheet style, instantiating it programmatically from its storyboard ID. The view controller is a UINavigationController embedding the actual, custom UIViewController subclass that displays my app's content:
@IBAction func showDetails(sender:AnyObject)
{
    guard let detailsNavigation = storyboard?.instantiateViewControllerWithIdentifier("DetailsNavigationControllerID") as? UINavigationController else {
        // Failed to instantiate navigation controller (this should not
        // happen); abort:
        return
    }

    guard let detailsViewController = detailsNavigation.topViewController as? DetailsViewController else {
        // Top view controller of navigation is not of the right type (this
        // should not happen); abort:
        return
    }

    // Configure content view controller:
    detailsViewController.title = "MyTitle"

    // etc...

    // Present the containing navigation controller, modally, as page sheet:

    detailsNavigation.modalPresentationStyle = UIModalPresentationStyle.PageSheet

    presentViewController(detailsNavigation, animated: true, completion: nil)
}

This view controller, in turn, has a UIButton that triggers a segue. The segue consists of presenting a third view controller modally, but this time full-screen (with transition "Default", i.e. "Cover Vertical").
I am experiencing two issues:

*

*During the transition, the rounded corners of the presenting page sheet view controller disappear (i.e., become perfectly square). This happens both during presentation and dismissal.

*The presented fullscreen view controller (also UINavigationController) has the wrong status bar style, and I can't seem to fix it.
The navigation bar for this full-screen, modal navigation controller is defined in IB as Style: Default, Translucent: true, Bar tint: Default (i.e., Clear Color). The bar being almost white, the status bar text should be black (.Default). However, it stays white (.LightContent) like in the rest of the app (which has a blue navigation bar throughout).
I have tried the following in the top view controller of the presented navigation:
override func viewDidAppear(animated: Bool)
{
    super.viewDidAppear(animated)

    self.navigationController?.setNeedsStatusBarAppearanceUpdate()
}

override func preferredStatusBarStyle() -> UIStatusBarStyle
{
    return UIStatusBarStyle.Default
}

...to no avail.
(The app has UIViewControllerBasedStatusBarAppearance set to YES on Info.plist, and other modal view controllers with light-colored nav bars have their status bar style show appropriately.)
UPDATE 1: I have read this question and some of its answers but still can't get it to work (haven't tried subclassing UINavigationController), but now I now why preferredStatusBarStyle isn't being called on the top view controller.
UPDATE 2: I tried presenting the same navigation controller but programmatically, and directly from my (already fullscreen) root view controller -instead of from within the page sheet). Now, the status bar correctly displays black characters. Perhaps I'm better off changing my user interface...


text:
Q: Distributing colored balls into bins such that each bin is distinct. Suppose I have $n = n_1 + n_2 + \dots + n_k$ balls of $k$ colors, with exactly $n_i \geq 1$ balls of color $i$. Balls that are the same color are indistinguishable. Additionally, we have $m$ indistinguishable bins. I would like to count the number of ways in which we can distribute the balls over all bins such that each bin is non-empty, and no two bins have the exact same multiset of balls (i.e. we can not have two bins $\{R, B\}$, but we can have both of the bins $\{R, B\}$ and $\{R, R, B\}$).
Example: say we have $m=2$ and $n_1 = 3$ ('red') and $n_2 = 2$ ('blue'). Then the valid distributions are:

*

*$\{\{R, R, R, B\}, \{B\}\}$

*$\{\{R, R, R\}, \{B, B\}\}$

*$\{\{R, R, B, B\}, \{R\}\}$

*$\{\{R, R, B\}, \{R, B\}\}$

*$\{\{R, R\}, \{R, B, B\}\}$
So the answer is $5$ (modulo an overseen distribution on my part :-) ).
How can I compute this quantity for given $n_1,n_2, \dots, n_k$ and $m$?

A: Note:   what   follows   is   a  close   adaptation   of   this   MSE
link,  which treats
unique factorizations of  integers into multisets of  factors.  In the
present problem the factors have to  be unique.  Suppose we start with
the source multiset and using the notation from the cited link
$$\def\textsc#1{\dosc#1\csod}
\def\dosc#1#2\csod{{\rm #1{\small #2}}}
\prod_{k=1}^l A_k^{\tau_k}$$
where we  have $l$ different  values and their multiplicities  are the
$\tau_k.$
If we  have a  CAS like Maple,  $N$ is reasonable  and we  seek fairly
instant computation  of these values  then we  may just use  the cycle
index  $Z(P_N)$ of  the unlabeled  operator $\textsc{SET}_{=N}.$  This
yields the formula
$$\left[\prod_{k=1}^l A_k^{\tau_k}\right]
Z\left(P_N; -1 + \prod_{k=1}^l \frac{1}{1-A_k}\right).$$
Here we have used the recurrence by Lovasz for the quoted cycle index,
which is
$$Z(P_N) = \frac{1}{N} \sum_{l=1}^N (-1)^{l-1} a_l Z(P_{N-l})
\quad\text{where}\quad
Z(P_0) = 1.$$
Maple can extract these coefficients  by asking for the coefficient of
the corresponding Taylor series.  We get the following transcript:

> MSETS([3,2], 2);
                             5

> map(el->el[1], select(el->el[\
> 2]>0, [seq([n, FACTORS(n,3)], n=1..256)]));
[24, 30, 36, 40, 42, 48, 54, 56, 60, 64, 66, 70, 72, 78, 80,

    84, 88, 90, 96, 100, 102, 104, 105, 108, 110, 112, 114,

    120, 126, 128, 130, 132, 135, 136, 138, 140, 144, 150,

    152, 154, 156, 160, 162, 165, 168, 170, 174, 176, 180,

    182, 184, 186, 189, 190, 192, 195, 196, 198, 200, 204,

    208, 210, 216, 220, 222, 224, 225, 228, 230, 231, 232,

    234, 238, 240, 246, 248, 250, 252, 255, 256]

The sequence is OEIS  A122181 and looks to
have the  right values. The Maple  code here is quite  simple and also
includes a  recurrence that does not  use PET, which is  based on MSE
Link II.

with(combinat);
with(numtheory);

pet_cycleind_set :=
proc(n)
option remember;

    if n=0 then return 1; fi;

    expand(1/n*
           add((-1)^(l-1)*a[l]*pet_cycleind_set(n-l), l=1..n));
end;

pet_varinto_cind :=
proc(poly, ind)
local subs1, subsl, polyvars, indvars, v, pot;

    polyvars := indets(poly);
    indvars := indets(ind);

    subsl := [];

    for v in indvars do
        pot := op(1, v);

        subs1 :=
        [seq(polyvars[k]=polyvars[k]^pot,
             k=1..nops(polyvars))];

        subsl := [op(subsl), v=subs(subs1, poly)];
    od;

    subs(subsl, ind);
end;

MSETS :=
proc(src, N)
local msetgf, cind, gf, cf;

    msetgf := mul(1/(1-A[q]), q=1..nops(src))-1;
    cind := pet_cycleind_set(N);

    gf := pet_varinto_cind(msetgf, cind);

    for cf to nops(src) do
        gf := coeftayl(gf, A[cf] = 0, src[cf]);
    od;

    gf;
end;

FACTORS :=
proc(n, N)
local mults;

    mults := map(el -> el[2], op(2, ifactors(n)));
    MSETS(mults, N);
end;

FACTREC :=
proc(val, numel, maxfact)
option remember;
local divs;

    if numel = 1 then
        return `if`(1 < val and val <= maxfact, 1, 0);
    fi;

    divs := select(d -> d <= maxfact, divisors(val));
    add(FACTREC(val/d, numel-1, d-1), d in divs);
end;

FACTORSX := (n, N) -> FACTREC(n, N, n);


text:
Q: What happen's to content inside in rows on columns defined as varchar, when illegally reduced length? Certainly a noobish question, but I got to ask: :-) Assuming a column of type varchar and length 255 and the longest string stored in a row at this column shold have length 200. What happens, if I altered the columns length to less then 200? Would the strings all get "cut"?

A: By default, it will allow you to alter the column, it will truncate strings longer than the new length, and it will generate a warning.
mysql> create table t (v varchar(20));
Query OK, 0 rows affected (0.06 sec)

mysql> insert into t values ('12345678901234567890');
Query OK, 1 row affected (0.00 sec)

mysql> alter table t modify column v varchar(10);
Query OK, 1 row affected, 1 warning (0.04 sec)
Records: 1  Duplicates: 0  Warnings: 1

mysql> show warnings;
+---------+------+----------------------------------------+
| Level   | Code | Message                                |
+---------+------+----------------------------------------+
| Warning | 1265 | Data truncated for column 'v' at row 1 |
+---------+------+----------------------------------------+
1 row in set (0.00 sec)

mysql> select * from t;
+------------+
| v          |
+------------+
| 1234567890 |
+------------+
1 row in set (0.00 sec)

If you have the SQL mode STRICT_ALL_TABLES or STRICT_TRANS_TABLES set, the warning becomes an error and the ALTER will fail.
mysql> alter table t modify column v varchar(10);
ERROR 1265 (01000): Data truncated for column 'v' at row 1


text:
Q: "Change in rotation" matrix Given two rotation matrices A and B (rotated from the same initial frame), how can I find the rotation matrix that represents the change in rotation from A to B? (I actually want to find the Euler axis and angle that represents that change in rotation.)
My one idea seems too involved: Convert A and B into their equivalent Euler angles, find the difference in Euler angles, convert the difference back into a rotation matrix, and then convert the new rotation matrix into Euler axis and angle.
Thanks for the help!

A: Background: It is very convenient to use the following notation:
$\mathtt R_{UV}$ is a rotation matrix which transform points from reference frame $V$ into the reference frame $U$. Thus: $\mathbf x_U = \mathtt R_{UV} \mathbf x_V$.
The inverse rotation is $\mathtt R_{VU} = \mathtt R_{UV}^{-1}=\mathtt R_{UV}^\top$.
Lets, call the initial frame $O$. I assume you mean with "rotated from the same initial frame" a change in the observer frame/passive transformation (http://en.wikipedia.org/wiki/Active_and_passive_transformation).
Thus, you have the rotation matrices $\mathtt R_{OA}$ and $\mathtt R_{OB}$ (which describe the motion of the observer from $O$ to $A$/$B$, or in other words maps points from $A$/$B$ to $O$). Now, I assume you are interested in $\mathtt R_{AB} = \mathtt R_{AO}\mathtt R_{OB} = \mathtt R_{OA}^\top\mathtt R_{OB}$.
Finally, convert $\mathtt R_{AB}$ into axis-angle...
(In case you have $\mathtt R_{AO}$ and $\mathtt R_{BO}$ and want to calculate $\mathtt R_{BA}$ , you get $\mathtt R_{BA}=\mathtt R_{BO}\mathtt R_{AO}^\top$.)


text:
Q: How to use a dict to subset a DataFrame? Say, I have given a DataFrame with most of the columns being categorical data.
> data.head()
  age risk     sex smoking
0  28   no    male      no
1  58   no  female      no
2  27   no    male     yes
3  26   no    male      no
4  29  yes  female     yes

And I would like to subset this data by a dict of key-value pairs for those categorical variables.
tmp = {'risk':'no', 'smoking':'yes', 'sex':'female'}

Hence, I would like to have the following subset.
data[ (data.risk == 'no') & (data.smoking == 'yes') & (data.sex == 'female')]

What I want to do is:
data[tmp]

What is the most python / pandas way of doing this?

Minimal example:
import numpy as np
import pandas as pd
from pandas import Series, DataFrame

x = Series(random.randint(0,2,50), dtype='category')
x.cat.categories = ['no', 'yes']

y = Series(random.randint(0,2,50), dtype='category')
y.cat.categories = ['no', 'yes']

z = Series(random.randint(0,2,50), dtype='category')
z.cat.categories = ['male', 'female']

a = Series(random.randint(20,60,50), dtype='category')

data = DataFrame({'risk':x, 'smoking':y, 'sex':z, 'age':a})

tmp = {'risk':'no', 'smoking':'yes', 'sex':'female'}

A: I would use .query() method for this task:
qry = ' and '.join(["{} == '{}'".format(k,v) for k,v in tmp.items()])

data.query(qry)

output:
   age risk     sex smoking
7   24   no  female     yes
22  43   no  female     yes
23  42   no  female     yes
25  24   no  female     yes
32  29   no  female     yes
40  34   no  female     yes
43  35   no  female     yes

Query string:
print(qry)
"sex == 'female' and risk == 'no' and smoking == 'yes'"

A: You can use list comprehension with concat and all:
import numpy as np
import pandas as pd

np.random.seed(123)
x = pd.Series(np.random.randint(0,2,10), dtype='category')
x.cat.categories = ['no', 'yes']
y = pd.Series(np.random.randint(0,2,10), dtype='category')
y.cat.categories = ['no', 'yes']
z = pd.Series(np.random.randint(0,2,10), dtype='category')
z.cat.categories = ['male', 'female']

a = pd.Series(np.random.randint(20,60,10), dtype='category')

data = pd.DataFrame({'risk':x, 'smoking':y, 'sex':z, 'age':a})
print (data)
  age risk     sex smoking
0  24   no    male     yes
1  23  yes    male     yes
2  22   no  female      no
3  40   no  female     yes
4  59   no  female      no
5  22   no    male     yes
6  40   no  female      no
7  27  yes    male     yes
8  55  yes    male     yes
9  48   no    male      no

tmp = {'risk':'no', 'smoking':'yes', 'sex':'female'}
mask = pd.concat([data[x[0]].eq(x[1]) for x in tmp.items()], axis=1).all(axis=1)
print (mask)
0    False
1    False
2    False
3     True
4    False
5    False
6    False
7    False
8    False
9    False
dtype: bool

df1 = data[mask]
print (df1)
 age risk     sex smoking
3  40   no  female     yes

L = [(x[0], x[1]) for x in tmp.items()]
print (L)
[('smoking', 'yes'), ('sex', 'female'), ('risk', 'no')]

L = pd.concat([data[x[0]].eq(x[1]) for x in tmp.items()], axis=1)
print (L)
  smoking    sex   risk
0    True  False   True
1    True  False  False
2   False   True   True
3    True   True   True
4   False   True   True
5    True  False   True
6   False   True   True
7    True  False  False
8    True  False  False
9   False  False   True

Timings:
len(data)=1M.
N = 1000000
np.random.seed(123)
x = pd.Series(np.random.randint(0,2,N), dtype='category')
x.cat.categories = ['no', 'yes']
y = pd.Series(np.random.randint(0,2,N), dtype='category')
y.cat.categories = ['no', 'yes']
z = pd.Series(np.random.randint(0,2,N), dtype='category')
z.cat.categories = ['male', 'female']

a = pd.Series(np.random.randint(20,60,N), dtype='category')

data = pd.DataFrame({'risk':x, 'smoking':y, 'sex':z, 'age':a})

#[1000000 rows x 4 columns]
print (data)

tmp = {'risk':'no', 'smoking':'yes', 'sex':'female'}

In [133]: %timeit (data[pd.concat([data[x[0]].eq(x[1]) for x in tmp.items()], axis=1).all(axis=1)])
10 loops, best of 3: 89.1 ms per loop

In [134]: %timeit (data.query(' and '.join(["{} == '{}'".format(k,v) for k,v in tmp.items()])))
1 loop, best of 3: 237 ms per loop

In [135]: %timeit (pd.merge(pd.DataFrame(tmp, index =[0]), data.reset_index()).set_index('index'))
1 loop, best of 3: 256 ms per loop

A: You can create a look up data frame from the dictionary and then do an inner join with the data which will have the same effect as query:
from pandas import merge, DataFrame
merge(DataFrame(tmp, index =[0]), data)

A: You could build a boolean vector that checks those attributes.  Probably a better way though:
df[risk == 'no' and smoking == 'yes' and sex == 'female' for (age, risk, sex, smoking) in df.itertuples()]

A: I think you can could use the to_dict method on your dataframe, and then filter using a list comprehension:
df = pd.DataFrame(data={'age':[28, 29], 'sex':["M", "F"], 'smoking':['y', 'n']})
print df
tmp = {'age': 28, 'smoking': 'y', 'sex': 'M'}

print pd.DataFrame([i for i in df.to_dict('records') if i == tmp])

>>>    age sex smoking
0   28   M       y
1   29   F       n

   age sex smoking
0   28   M       y

You could also convert tmp to a series:
ts = pd.Series(tmp)

print pd.DataFrame([i[1] for i in df.iterrows() if i[1].equals(ts)])


text:
Q: How to can I make certain fields appear in R file? I have these pieces of code:
btnStart = (Button) findViewById(R.id.buttonstart);
btnStop = (Button) findViewById(R.id.buttonstop);
ipfield = (EditText) findViewById(R.id.ipfield);
portfield = (EditText) findViewById(R.id.portfield);

and
addPreferencesFromResource(R.xml.preferences);

It gives me these errors:

buttonstart cannot be resolved or is not a field
buttonstop cannot be resolved or is not a field
ipfield cannot be resolved or is not a field
portfield cannot be resolved or is not a field
xml cannot be resolved or is not a field

So I went into R to see if I can find them and they aren't there. I tried setting them manually, but I still get errors. I cleaned the project multiple times and R still didn't generate them.
These are my imports:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;

Button btnStart, btnStop;
EditText ipfield, portfield;

A: I think that you have not declare the ID in the xml file where you have define your Buttons and EditTexts.
You have to declare it with (for example):
android:id="@+id/buttonstart"

A: try using [your package name].R to reference your views, also make sure that your xml files have the id attribute set like this;
android:id="@+id/buttonstart"

and so on.


text:
Q: Using watir-webdriver, how can I click a table row? I'm trying to convert my old watir scripts to use watir-webdriver instead, as that will (eventually) support IE9 and Firefox 4. $browser.table_row(:id => "account_1").click is what I used to click the first row of a table on screen in watir/firewatir, but the API for this was modified in watir-webdriver. Now, the code is this: $browser.table(:class => "sortable")[0].click which should grab the first row of the table then click it. It seems to be successful, as it continues code execution, but it doesn't actually click the row.
Can someone explain what the right syntax would be in this case?
Here's the source code around the area I want to click:

         Name
         Number

        Test Account
        1

A: Your code is finding the first row of the table, which is inside the
 and does not have an onclick handler. Try this instead:
browser.tr(:id => "account_1").click

Here's a script that demonstrates the behavior, and here's an overview of the revised table API.

A: A Row isn't an HTTP object that would normally respond to a click.  Is there something inside the row like a link that you want to click on, or is the row itself setup using event handling to respond to a particular event such as 'onclick' or 'onmousedown' ??
If the former, try actually clicking on the object within the row.  If the latter then try experimenting with the .fire_event method and different events.
For example:
browser.table(:class => "sortable")[0].fire_event("onmousedown")

or maybe
browser.table(:class => "sortable").row(:index, 0).fire_event("onmousedown")

(addendum)   AH now that we have the HTML we can see where the onclick handler is  and as pointed out by Jarib, you were clicking on the header row (which is technically the first row of the table)   To click the thing you want, you need something along the lines of
browser.row(:id, "account_1").click
browser.row(:text, /Test Account/).click
browser.table(:class => "sortable").row(:index, 1).fire_event("onclick")

(unless your intent is to sort the table, in which case I suspect you need to click a CELL in the first (header) row in order to sort the table on that column.
browser.cell(:text, ' Name ').click


text:
Q: Error in Django 2.0 tutorial, part 7 -- is this a bug? When I follow the 2.0 tutorial, on part 7, I noticed there is an error icon under "PUBLISHED RECENTLY" in this screenshot:

The "was_published_attribute" was set to True in the tutorial. But if set it to False, it can show "False" correctly, as in below:

The related code is in the polls/models.py,
class Question(models.Model):
    ... ...
    def was_published_recently(self):
        ... ...
    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = False
    was_published_recently.short_description = 'Published recently?'

What I changed is the line was_published_recently.boolean = False. Again it shows the little on/off icons with the attribute initialized as True, and shows the text "True/False" with the attribute initialized as False.
Is this a bug? Any suggestion of fixing? Many thanks!
I apologize that I describe this question poorly in the title. I appreciate it if anyone can suggest me a better title.

A: "It's not a bug, it's a feature". Quote from django doc:

If the string given is a method of the model, ModelAdmin or a callable that returns True or False Django will display a pretty "on" or "off" icon if you give the method a boolean attribute whose value is True.

So when you add was_published_attribute.boolean = True into admin class django will replace words False and True with  red or green image. So in your case error symbol is just indicator that actual value of was_published_attribute is false. Try to create new record with was_published_attribute=True and you will see pretty green sign instead of error symbol for this new object.


text:
Q: How to decrypt encrypted String in C# but encrypted in java (jasypt) i need to decrypt the encrypted string in MsSQl. the encrypted String is encrypted using jasypt as i have the source code (java)
my problem is, i cannot decrypt back the encrypted string in C#.
this is the code used in java:
public String encrypt(String strClearText){
    String strKey="password";
    StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        encryptor.setPassword(strKey);
        String encrypted= encryptor.encrypt(strClearText);

        return encrypted;
    }

I try to convert the jasypt.jar to dll using ikvm and still no luck.
Is there any way i can do to overcome this problem? so that the encrypted password can be use in java and also in c#?
i cannot change the method of encryption as this encrypted String is being used by many other software. i hope you guys can tell me/teach me another way to overcome this problem..
Thank you :)


text:
Q: execute "vagrant up" from ROR application I have an ROR application from which I am trying to execute vagrant up command in the following way system("vagrant up")
I am getting the below error
Vagrant experienced a version conflict with some installed plugins!
This usually happens if you recently upgraded Vagrant. As part of the
upgrade process, some existing plugins are no longer compatible with
this version of Vagrant. The recommended way to fix this is to remove
your existing plugins and reinstall them one-by-one. To remove all
plugins:
    rm -r ~/.vagrant.d/plugins.json ~/.vagrant.d/gems
Note if you have an alternate VAGRANT_HOME environmental variable
set, the folders above will be in that directory rather than your
user's home directory.
The error message is shown below:
Bundler could not find compatible versions for gem "bundler":
  In Gemfile:
    vagrant (= 1.7.2) x86-mingw32 depends on
      bundler (< 1.8.0, >= 1.5.2) x86-mingw32
  Current Bundler version:
    bundler (1.10.0.pre.2)
This Gemfile requires a different version of Bundler.
Perhaps you need to update Bundler by running `gem install bundler`?
Could not find gem 'bundler (< 1.8.0, >= 1.5.2) x86-mingw32', which is required by gem 'vagrant (= 1.7.2) x86-mingw32', in any of the sources.

I have tried to do  gem install bundler , it always installs bundler 1.9.9
If i try to execute vagrant up from command line it works fine
Below are the versions which I am using
ruby -> 2.1.6p336 (2015-04-13 revision 50298) [x64-mingw32]
Vagrant -> 1.7.2
Rails -> 4.2.1

Any sort of help is much appreciated


text:
Q: Postgres: Cannot connect from NodeJS (PG) with md5 Node v6.2 on Windows 10; PG (node-postgres) v4.4.2
Postgres 9.5 on Ubuntu 14.04 Trusty VirtualBox
I'm using the PG (node-postgres) module to connect to Postgres on Ubuntu in a virtual machine. I was able to connect using Navicat no problem, but those same credentials didn't work when I was connecting with NodeJS. The postgres log shows this:
xxxx@yyyy FATAL:  password authentication failed for user "xxxx"
xxxx@yyyy DETAIL:  Connection matched pg_hba.conf line 96: "host    all             all             all        $

I added this line to my pg_hba.conf file and now it works but can anyone explain why md5 isn't working?
# I added this line:
host    all             all             all                     password
# This line was already here:
host    all             all             all                     md5

A: There is a breaking change in Node v6 so you need to upgrade "pg" (node-postgres) to v6.0.1 from v4.4.2 that you said you are using.
https://github.com/brianc/node-postgres/issues/1000


text:
Q: Why is there a huge space in between my two slideshows? I didn't add any br in between the two slideshows so why is there a huge space (as big as 7 line breaks) in between it?
All I know is basic html and css (which I learned on my own). I don't know anything about Javascript AT ALL. The Javascript code I have below is from w3schools which my teacher showed us.

function openNav() {
  document.getElementById("mySidebar").style.width = "250px";
  document.getElementById("main").style.marginLeft = "250px";
}

function closeNav() {
  document.getElementById("mySidebar").style.width = "0";
  document.getElementById("main").style.marginLeft = "0";
}

var slideIndex = [1, 1];
var slideId = ["mySlides1", "mySlides2"]
showSlides(1, 0);
showSlides(1, 1);

function plusSlides(n, no) {
  showSlides(slideIndex[no] += n, no);
}

function showSlides(n, no) {
  var i;
  var x = document.getElementsByClassName(slideId[no]);
  if (n > x.length) {
    slideIndex[no] = 1
  }
  if (n < 1) {
    slideIndex[no] = x.length
  }
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  x[slideIndex[no] - 1].style.display = "block";
}
/* B O D Y */

body {
  font-family: "Lato", sans-serif;
  background-image: url(stars.gif);
  margin: 0;
}

#content {
  background-color: rgba(255, 255, 255, 0.2);
  margin-left: 200px;
  margin-right: 200px;
  padding-top: 15px;
  padding-bottom: 15px;
}

/* S I D E B A R */

.sidebar {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}

.sidebar a {
  padding: 8px 8px 8px 32px;
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
  transition: 0.3s;
}

.sidebar a:hover {
  color: #f1f1f1;
}

.sidebar .closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}

.openbtn {
  font-size: 20px;
  cursor: pointer;
  background-color: #111;
  color: white;
  padding: 10px 15px;
  border: none;
}

.openbtn:hover {
  background-color: #444;
}

#main {
  transition: margin-left .5s;
  padding: 16px;
}

/* On smaller screens, where height is less than 450px, change the style of the sidenav (less padding and a smaller font size) */

@media screen and (max-height: 450px) {
  .sidebar {
    padding-top: 15px;
  }
  .sidebar a {
    font-size: 18px;
  }
}

/* A B O U T  T H E  A U T H O R */

#about-the-author-heading {
  text-align: center;
  margin-left: 200px;
  margin-right: 200px;
  padding-top: 5px;
  padding-bottom: 5px;
  border-top: 1px solid rgb(188, 184, 184);
  border-bottom: 1px solid rgb(188, 184, 184);
  color: white;
}

#about-the-author-description {
  text-align: justify;
  margin-left: 200px;
  margin-right: 200px;
  font-size: 24px;
}

#about-the-author-image {
  width: 200px;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

#about-the-author-description {
  color: white;
}

/* S L I D E S H O W */

* {
  box-sizing: border-box
}

.mySlides1,
.mySlides2 {
  display: none text-align: center;
  height: 600px;
}

img {
  vertical-align: middle;
}

.mySlides1 img,
.mySlides2 img {
  width: 100%;
  max-height: 100%;
  object-fit: contain;
}

/* Slideshow container */

.slideshow-container {
  max-width: 600px;
  position: relative;
  margin: auto;
}

/* Next & previous buttons */

.prev,
.next {
  cursor: pointer;
  position: absolute;
  top: 33%;
  width: auto;
  padding: 16px;
  margin-top: -22px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
  user-select: none;
}

/* Position the "next button" to the right */

.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

/* On hover, add a black background color with a little bit see-through */

.prev:hover,
.next:hover {
  background-color: rgba(0, 0, 0, 0.8);
}

/* Fading animation */

.fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  animation-name: fade;
  animation-duration: 1.5s;
}

@-webkit-keyframes fade {
  from {
    opacity: .4
  }
  to {
    opacity: 1
  }
}

@keyframes fade {
  from {
    opacity: .4
  }
  to {
    opacity: 1
  }
}

.slideshow-title {
  color: white;
  text-align: center;
}

/* Caption text */

.text {
  color: #f2f2f2;
  font-size: 15px;
  padding: 8px 12px;
  position: absolute;
  bottom: 8px;
  width: 100%;
  text-align: center;
}

/* Number text (1/3 etc) */

.numbertext {
  color: #f2f2f2;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
}

  ×
  About
  Bucket List
  Interests
  Education

  <button class="openbtn" onclick="openNav()">☰ MENU</button>

About the Author

 Dana has been a student for over 14 years. She's currently a Grade 12 honor student of her section, St. Benedict, in Malate Catholic School. Her experience in cramming and staying late at night has enabled her to finish this project.

Bohol Travel (2019)

1 / 21

2 / 21

3 / 21

4 / 21

5 / 21

6 / 21

7 / 21

8 / 21

9 / 21

10 / 21

11 / 21

12 / 21

13 / 21

14 / 21

15 / 21

16 / 21

17 / 21

18 / 21

19 / 21

20 / 21

21 / 21

    ❮
    ❯

Jeyen :>

1 / 20

2 / 20

3 / 20

4 / 20

5 / 20

6 / 20

7 / 20

8 / 20

9 / 20

10 / 20

11 / 20

12 / 20

13 / 20

14 / 20

15 / 20

16 / 20

17 / 20

18 / 20

19 / 20

20 / 20

    ❮
    ❯

A: It's because there's text between your slideshows! All of your text is white on a white background, so you can't see any of the words. Highlight that empty space and you'll find the word Jeyen :>. To see all of the text on your page, change .content's background-color to something like lightgray.
Remove the line
Jeyen :>
 and the space between your slideshows goes away.


text:
Q: Impossible to plot a currency value into a plot I have a dataframe with a numerical column in euro (ex: 7 000 €) that I want to show on a map with the tool .plot.
df
        item price
    1   A   7 000 €
    2   B   10 880 €
    3   C   10 990 €

maps = df.plot()
maps

    ValueError: could not convert string to float: '7 000 €'

I get an error message because it considers the column as an object and not a float.
df.dtypes
    item object
    price object
    dtype: object

I first deleted the ' €' characters with rstrip.
df['price'] = df['price'].map(lambda x: x.rstrip(' €'))
df
        item price
    1   A   7 000
    2   B   10 880
    3   C   10 990

Then I tried to convert the column to float, but impossible because there is a separator (space) of thousands (ex: 7 000).
df.price = pd.to_numeric(df.price, errors='ignore')
maps = df.plot()
maps

    ValueError: could not convert string to float: '7 000'

When I replace the ' ' to '', I get no error message, however when I show the dataframe, I always have the separator, and the column is always considered an object (no possibility to plot it)
df['price'].replace(' ','', inplace=True)
df
        item price
    1   A   7 000
    2   B   10 880
    3   C   10 990

I can't get out of this. Can you help me please ?
Thank you very much.

A: You might want to use  to_numeric to ensure the plot function considers it a number.
df['price'] = df['price'].apply(lambda x: x.replace(' ', '').replace('$', ''))
df['price'] = pd.to_numeric(df['price'])


text:
Q: Illegal assignment from List to List? public class Aggregateresult {

    public static void aggregateresults()
    {
        aggregate result[] results = [select count(id) records,name from account group by name having count(id)>1];
    }

}

A: You have a namespace collision. Change the name of your class from Aggregateresult.
Since Apex is a case-insensitive language, the compiler sees this as the same as the built-in class AggregateResult. The SOQL query is known to return a List<AggregateResult>, as in the built-in class, but your local variable results is being read as a List<Aggregateresult>, as in the class you're writing here. Since those are different types, an error results.

A: Got the answer... I have a class with name as aggregateresult in my organisation, so it is not able to identify it properly..
Worked fine after deleting that aggregateresult class.
public class Aggrresulstduplicate
{
     public static void aggres()
     {
          aggregateresult[] results = [select count(id) records,name from account group by name having count(id) > 1];
          system.debug(results.size());
     }
}


text:
Q: Delegate Closure with no memory allocation I wrote a Thread helper class that can be used to execute a piece of code in Unity's main Thread.
This is the functions blue print:
public static void executeInUpdate(System.Action action)

The complete script is really long and will make this post unnecessarily long. You can see the rest of the script helper class here.
Then I can use unity's API from another Thread like this:
UnityThread.executeInUpdate(() =>
{
    transform.Rotate(new Vector3(0f, 90f, 0f));
});

The problem is that when I use a variable declared outside of that delegate, it would allocate memory. The code above allocates 104 bytes each frame. That's because of the transform variable that is used inside that closure.
This may seem like nothing now but I do this 60 times per-sec and I have about 6 camera's I need to connect to and display images on the screen. I do not like the amount of garbage that is generated.
Below is an example of how I am downloading images from a camera and uploading it into Unity. I get about 60 frames per-sec. The receiveVideoFrame() function runs on a separate Thread. It downloads the image, send's it to Unity's main Thread and Unity uploads the image bytes into Texture2D. The Texture2D is then displayed with RawImage. The allocation happens when closure is captured due to UnityThread.executeInUpdate.
bool doneUploading = false;
byte[] videoBytes = new byte[25000];
public Texture2D videoDisplay;

void receiveVideoFrame()
{
    while (true)
    {
        //Download Video Frame
        downloadVideoFrameFromNetwork(videoBytes);

        //Display Video Frame
        UnityThread.executeInUpdate(() =>
        {
            //Upload the videobytes to Texture to display
            videoDisplay.LoadImage(videoBytes);
            doneUploading = true;
        });

        //Wait until video is done uploading to Texture/Displayed
        while (!doneUploading)
        {
            Thread.Sleep(1);
        }

        //Done uploading Texture. Now set to false for the next run
        doneUploading = false;

        //Repeat again
    }
}

How can I use closure without causing memory allocation?
If that's not possible, is there another way to do this?
I can just remove the class I use to execute code in the main Thread and re-write those logic in the main script but that would be messy and long.

A: After hours of experiment I discovered that if you put the code with the closure in a function, then cache it to an Action variable once in the Start or Awake function, the closure memory allocation will be gone when you invoke it in inside the while loop.
Also, I made the doneUploading boolean variable a volatile so that both Threads can see the changes. I don't think that the lock keyword is needed for this boolean variable here.
private volatile bool doneUploading = false;

byte[] videoBytes = new byte[25000];
public Texture2D videoDisplay;

Action chachedUploader;

void Start()
{
    chachedUploader = uploadToTexture;
}

void uploadToTexture()
{
    UnityThread.executeInUpdate(() =>
    {
        //Upload the videobytes to Texture to display
        videoDisplay.LoadImage(videoBytes);
        doneUploading = true;
    });
}

//running in another Thread
void receiveVideoFrame()
{
    while (true)
    {
        //Download Video Frame
        downloadVideoFrameFromNetwork(videoBytes);

        //Display Video Frame (Called on main thread)
        UnityThread.executeInUpdate(chachedUploader);

        //Wait until video is done uploading to Texture/Displayed
        while (!doneUploading)
        {
            Thread.Sleep(1);
        }

        //Done uploading Texture. Now set to false for the next run
        doneUploading = false;

        //Repeat again
    }
}

I am open to more improvement if anyone find anything bad. Although, I have solved my problem. Closures does not allocate memory anymore.


text:
Q: Very Simple clock in react js How to use setInterval function in react to repeatedly render a function in react . Please provide a very simple example . I am using Node js local environment. Here I am trying for a simple clock given in react documentation (but mine file structure is different). I don't know about didMount etc.. Just starting.
Below is my App.jsx
import React,{ Component } from 'react';
class App extends Component {

good(){
  {new Date().toLocaleTimeString()}
}
   render() {
      return (

{setInterval(()=>this.good(),500)}

      );
   }
}
export default App;

main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

  ReactDOM.render(<App />, document.getElementById('app'));

index.html
<!DOCTYPE html>

      <meta charset = "UTF-8">
      <title>React App</title>

My folder structure is like below

A: I suggest you to read more about React components, state and props as these are fundamental parts for which you have chosen to use React in first place. Basic steps would be:

*

*Store time as state of your component.

*Start ticking functionality as soon as your component loads (that is what componentDidMount does - it's triggered when component loads in page)

*On each tick use setState to change time value (setState triggers render)

If you follow these steps you would achieve similar result to example from React site, and this is how it should really be done (if you really want to do it in React design)


text:
Q: Getting leaf nodes in an MDX query I'm trying to create an MDX query on the TFS cube which gets the historical values of the Estimate field.  For each task I want to get the last estimate for each person who set the Estimate field.  For example if Bob the project manager sets the estimate to 24 hours and then Dave the developer sets it to 32 hours, I want to create a query which shows the variance of each of their estimates to the real hours worked [Work Completed].
The problem I'm running into is that the historical values of Work Items in TFS are tracked with revs (revisions), but TFS puts both a positive and negative value in a single rev for work items which are changed.  Which makes the sum look like 0 / empty cell.
For example Bob sets the estimate to 24 in rev 2.  Then Dave sets it to 32 in rev 3.  TFS adds another row to the data warehouse of -24 for rev 2.  When this gets rolled up I can't see bob's estimate.
How Do I select only the positive values?  I tried using the filter function and this returns the right members, but the value of the cell is still null
with
member [Last Estimate] as [Measures].[Microsoft_VSTS_CMMI_Estimate]
SELECT
    {nonempty([Changed By].[Person].[All].Children*[Last Estimate])} ON 0,
    {nonempty([Work Item].[System_Id].[System_Id]*Filter([Work Item].[System_Rev].[All].Children, [Measures].[Microsoft_VSTS_CMMI_Estimate] > 0))} ON 1

FROM [Work Item History]
WHERE [Team Project].[Team Project].&[29];

Here is the results
Work     rev     Bob             Dave
Item         Last Estimate  Last Estimate
7446      2  (null)          (null)
7446      3  (null)          32.0

Every row should have a value for one of the two people.
Thanks in advance!

A: The filter function filters the members of the dimension but this is not enough because a member can contain for example both 24 and -24. Try filtering the measure itself with the Iif function:
with
member [Last Estimate] as
'
Iif([Measures].[Microsoft_VSTS_CMMI_Estimate] > 0, [Measures].[Microsoft_VSTS_CMMI_Estimate], 0)
'
SELECT
    {nonempty([Changed By].[Person].[All].Children*[Last Estimate])} ON 0,
    {nonempty([Work Item].[System_Id].[System_Id]*Filter([Work Item].[System_Rev].[All].Children, [Measures].[Microsoft_VSTS_CMMI_Estimate] > 0))} ON 1

FROM [Work Item History]
WHERE [Team Project].[Team Project].&[29];


text:
Q: MDX - Filter members using AND operator in Query designer or otherwise I have the following table:
ID Column A
1    ValA
1    ValA
1    Special
2    ValA
3    ValA

I need to return only IDs which has a Special value in Column A. So the output would be:
ID Column A
1   ValA
1   ValA
1   Special

I thought that one way would be to use the MDX operator but there is very little documentation on it. I am a real beginner of MDX.
Thanks in Advance.

A: The Exists function, as documented here and then a cross join should do what you want, as the cross join within a dimension uses autoexists and thus does not really do a full cross join, but only a kind of inner join, resulting in tuples really existing in the dimension table.
Assuming the table that you show in your question is a dimension table, and the attributes are named [Your Dimension].[Id] and [Your Dimension].[A], you would use
Exists([Your Dimension].[Id].[Id].Members, [Your Dimension].[A].[Special])
*
[Your Dimension].[A].[A].Members


text:
Q: one-way between-subject anova lmer error I am trying to fit a one-way between-subject anova with lmer based on this question (see second answer) but I am getting an error. What am I doing wrong?
Reproducible example:
library(lme4)

set.seed(123)
n <- 50
DF <- data.frame(score = c(rnorm(n), rnorm(n), rnorm(n)),
                 treatment = rep(c("A", "B", "C"), each = n),
                 subject = 1:(n*3))

lm(score ~ treatment, data = DF) # works fine
lmer(score ~ treatment + (1|subject), data = DF) # Error: number of levels of each grouping factor must be < number of observations (problems: subject)


text:
Q: Modeling a network in Python: instantiating objects in different threads and passing objects between threads in python I have a program in which I have modelled a network (i.e. it has switch, host, links, interfaces, etc. classes). I want each node in the network to operate in its own thread without waiting for another node to finish an operation. for example without multi-threading when I broadcast a packet from interfaces of a node, each packet (on each interface) has to wait for the previous packet to reach destination, get processed and terminated before it is transmitted. I am putting a part of my single-thread code down here so can anyone suggest a way I multi-thread my program?
main.py
from Simulation import Simulator

def main():

    newSim = Simulator()    #Simulator class holds the list of all nodes

    h1 = newSim.addNewHost()    #adds hosts
    h2 = newSim.addNewHost()

    s1 = newSim.addNewSwitch()    #adds switches
    s2 = newSim.addNewSwitch()

    c0 = newSim.addNewCont()    #adds a controller, which acts like a switch

    c0.connectTo(s1)    #creates NIC on each node and a link object which stores them
    c0.connectTo(s2)

    s1.connectTo(h1)
    s2.connectTo(h2)

    c0.initiateCtrl()    #initiates some operations on the controller

    # h1 has an interface (NIC) with 10.0.1.1
    # h2 has an interface (NIC) with 10.0.2.1

    h1.echo("Say hello to my little friend!!! BoooM!!!", "10.0.2.1")
    h2.echo("whats up!" , "10.0.1.1")

if __name__ == '__main__':
    main()

now when I run this h2 waits until h1 sends its echo packet (and its ack) then it starts sending echo packet to h1. I suppose it is possible to send both echo packets simultaneously with multi-threading. but the examples online couldnt help me figure out how I should divide my program into threads, where to put locks and use queues
Thank you in advance.

A: class SwitchCreator1(Thread):

    def __init__(self):
        Thread.__init__(self)
        self.newSim = Simulator()
        self.s1 = self.newSim.addNewSwitch()

    def getSwitch1(self):
        return self.s1

class SwitchCreator2(Thread):

    def __init__(self):
        Thread.__init__(self)
        self.newSim = Simulator()
        self.s2 = self.newSim.addNewSwitch()

    def getSwitch2(self):
        return self.s2

def main():

    threadList = []

    sc1 = SwitchCreator1()
    threadList.append(sc1)
    sc1.start()
    s1 = sc1.getSwitch1()

    sc2 = SwitchCreator2()
    threadList.append(sc2)
    sc2.start()
    s2 = sc2.getSwitch2()

    s1.connectTo(s2)

    s1.echo("Say hello to my little friend!!! BoooM!!!", s2)

    for t in threadList:
        t.join()

if __name__ == '__main__':
    main()


text:
Q: How can I run a Maven project in Intellij Idea (and have all dependencies downloaded)? In Intellij IDEA I created a Maven project and added dependencies to the pom.xml file. However when I run the project using ALT + SHIFT + F10, as with 'plain' projects, I get ClassNotFoundExceptions.
My question is: is that the proper way to run a Maven project, and have all the dependencies been downloaded? Or is there another way?

A: Reload all dependencies: CTRL+SHIFT+A and input "reimport" as an action. You will find the "Reimport All Maven Projects" option. Afterwards, rebuild the project.

A: I am more experienced with setting it up on Eclipse but I believe the Intellij plugin should also offer some option to Update Maven Dependencies, which should download the jars you are missing.
In fact, a quick search I just did directed me at this post
Force Intellij IDEA to reread all maven dependencies
Good luck!


text:
Q: Retrieving permission IDs for Microsoft Graph API - Delegated / Application Permissions GUID for various Scopes Is there a quick and easy way to find Microsoft Graph API - Delegated / Application Permissions GUID (or even deprecated Azure AD API Permissions).
Tried to follow the official document but find it not very intuitive.
https://learn.microsoft.com/en-us/graph/permissions-reference
Since permissions names are similar, eg: group.readwrite.all between delegated vs application, is there any tool or technique to easily find these IDs.
az ad sp list --query "[?appDisplayName=='Microsoft Graph'].{permissions:oauth2Permissions}[0].permissions[?value=='Group.ReadWrite.All'].{id: id, value: value, adminConsentDisplayName: adminConsentDisplayName, adminConsentDescription: adminConsentDescription}[0]" --all
{
  "adminConsentDescription": "Allows the app to create groups and read all group properties and memberships on behalf of the signed-in user.  Additionally allows group owners to manage their groups and allows group members to update group content.",
  "adminConsentDisplayName": "Read and write all groups",
  "id": "4e46008b-f24c-477d-8fff-7bb4ec7aafe0",
  "value": "Group.ReadWrite.All"
}

this seems to be incorrect as the ID that is correct is:
        Group_ReadWrite_All = {
          id   = "62a82d76-70ea-41e2-9197-370581804d09"
          type = "Role"
        }

Am I missing something obvious here? especially the Role/Scope or its Delegated vs Application issue?

A: Query to list all the Apps
az ad sp list  --query '[].{appDisplayName:appDisplayName, appId:appId}'

Query "Microsoft Graph" app, to find "oauth2" scope of "Group.ReadWrite.All" permission
az ad sp list --query "[?appDisplayName=='Microsoft Graph'].{permissions:oauth2Permissions}[0].permissions[?value=='Group.ReadWrite.All'].{id: id, value: value, adminConsentDisplayName: adminConsentDisplayName, adminConsentDescription: adminConsentDescription}[0]" --all

{
  "adminConsentDescription": "Allows the app to create groups and read all group properties and memberships on behalf of the signed-in user.  Additionally allows group owners to manage their groups and allows group members to update group content.",
  "adminConsentDisplayName": "Read and write all groups",
  "id": "4e46008b-f24c-477d-8fff-7bb4ec7aafe0",
  "value": "Group.ReadWrite.All"
}

Query "Microsoft Graph" app, to find app "Role" of "Group.ReadWrite.All" permission
az ad sp list --query "[?appDisplayName=='Microsoft Graph'].{permissions:appRoles}[0].permissions[?value=='Group.ReadWrite.All'].{id: id, value: value, adminConsentDisplayName: adminConsentDisplayName, adminConsentDescription: adminConsentDescription}[0]" --all

{
  "adminConsentDescription": null,
  "adminConsentDisplayName": null,
  "id": "62a82d76-70ea-41e2-9197-370581804d09",
  "value": "Group.ReadWrite.All"
}


text:
Q: Disable Cut, Copy, Paste and Paste Special in a specified sheet and in a specified column from outside sources I need to disable Cut, Copy, Paste and Paste Special in a specified sheet and in a specified column from the outside sources.
I'm using the below code for disabling these features in the third column of a specified sheet. But the user is able to copy and use paste special to paste data.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    'TARGET IS YOUR VALIDATION CELL
    Select Case Target.Column
        Case 3

        Application.CutCopyMode = False

        Application.EnableAutoComplete = Intersect(Target, Me.Columns(3)) Is Nothing
    End Select
End Sub

How do I restrict Cut, Copy, Paste, and Paste Special in the specified sheet and in the specified column?