text:
Q: Is it known for which pairs of integers Ackermann 's function is commutative? I was recently writing test for checking the termination of programs and I wanted to write some difficult condition to verify so that the solver didn't use the if-condition to simplify the goal to proof.
It turned that writing in the if, ackermann(x,y) == 1 (for the definition of Ackermann see Wikipedia)  was sufficient to confuse the solver, but I also tried ackermann(x,y) == ackermann(y,x) and of course the solver didn't go better on this instance.
I'm thinking of other programs that imply difficult problems in mathematics, for instance the so-called Collatz problem (also Syracuse, Kakutani, Hasse or Ulam's problem):
while n > 1 do
 if(n mod 2) != 0 then n = 3n + 1
 else n = n div 2

So my question is, is there any problem with Ackermann's commutativity. Is it known what pairs (if any) of numbers make it commutative?

A: To finish up Ross Millikan's answer:
Note that if $m>n>1$ we have
\begin{align}A(m,n)&=A(m-1,A(m,n-1))\\&\ge A(n,A(m,n-1))\\&\ge A(n,m+n-1)\\&>A(n,m)\end{align}
using the fact that the Ackermann function is increasing in all arguments.

A: Aside from $m=n$ the only cases of commutativity are $A(1,0)=A(0,1)$ and $A(2,0)=A(0,2)$.  In all other cases $m \gt n \implies A(m,n) \gt A(n,m)$.  I don't have a nice proof of that, but the height of the tower is much more important than the numbers that make up the tower.  You can find cases where different pairs of arguments give equal values, like $A(0,12)=A(1,11)=A(2,5)=A(3,1)=A(4,0)=13$ and $A(0,65534)=A(1,65533)=A(2,32765)=A(3,13)=A(4,1)=65533$
Looking at the definition, given $A(m,n)$ you can also express it as $A(p,q)$ for every $p \lt m$.


text:
Q: Formatting Slack notification from Travis Is it possible to format a Slack notification template in Travis, in order to use bold, italic and links?

A: Have you tried using slack emphasis (basically it is like markdown) text?
Try surrounding words in ** like *so* for bold.
*bold* will show as bold
_itaic_ will show as italic
~strikethrough~ will show as strikethrough
>will indent a line
>>> will indent multiple paragraphs

Source:
https://get.slack.help/hc/en-us/articles/202288908-Format-your-messages
As for links refer to: https://api.slack.com/docs/message-formatting

redpajama_set_name: RedPajamaStackExchange


text:
Q: DB2 - Inserting a timestamp operation result in a timestamp field I got a some javascript Dojo code assembling a query from JSON variables and I have been trying to insert a timestamp in it.
This is my test table (schema.mdummy):

*

*k and v are varchars

*n is an integer

*t is a timestamp

I found out these statements work fine:
INSERT INTO mschema.MDUMMY (k, v)
VALUES ((SELECT k FROM mschema.MDUMMY WHERE k LIKE 'xp3'), '33');

SELECT TIMESTAMP('1965-07-27', '15:30:00') + 59 SECONDS FROM SYSIBM.SYSDUMMY1;

But this one does not work as expected.
INSERT INTO mschema.MDUMMY (k, n, t) VALUES (
 '70',
 70,
 (SELECT TIMESTAMP('1965-07-27-15.30.00') + 59 SECONDS FROM SYSIBM.SYSDUMMY1)
);

Is it some error on the syntax or is it impossible to perform in DB2?
DB Server OS is the latest Fedora server.

A: Following sequence of statements worked fine in Db2 (for LUW)
create table mschema.MDUMMY (k varchar(10), n int, t timestamp)

INSERT INTO mschema.MDUMMY (k, n, t) VALUES (   '70',   70,   (SELECT
TIMESTAMP('1965-07-27-15.30.00') + 59 SECONDS FROM SYSIBM.SYSDUMMY1)
);

SELECT * FROM mschema.MDUMMY

I just copied the second statement from your question.
This means you made some other mistake running it or you are maybe not running it on Db2 LUW - this is why it is always useful to specify the OS.


text:
Q: Get value of Label in Javascript as Datetime I want to take label value and convert into datetime in javascript. I have a label in that I have binded datetime from database.
Asp.net Code
<asp:Label ID="expiryTimeLbl" Visible="false" runat="server"></asp:Label>
//10/27/2020 8:10:00 AM

JavaScript
 var countDownDate = new Date(document.getElementById("expiryTimeLbl")).getTime();

Now I will compare countDownDate with CurrentTime. Thank You!

A: Try this:
var countDownDate = new Date(document.getElementById('<%=expiryTimeLbl.ClientID %>')).getTime();

A: Use textContent or innerHTML. Try below
var countDownDate = new Date(document.getElementById("expiryTimeLbl").textContent).getTime();

or if any master page involve.
var countDownDate = new Date(document.getElementById('<%=expiryTimeLbl.ClientID %>').textContent).getTime();

for specific Hour/minute/seconds
var countDownDate = new Date(document.getElementById("expiryTimeLbl").textContent).getHours();
var countDownDate = new Date(document.getElementById("expiryTimeLbl").textContent).getMinutes();
var countDownDate = new Date(document.getElementById("expiryTimeLbl").textContent).getSeconds();


text:
Q: How does the CPU know it's executing a Kernel/Ring-0 instruction? Let's say you compile a C program into an executable and run it. (Assume code running on x86 architecture)
When the CPU is executing the machine code, it will inevitably need to execute instructions outside of ring-3 (user-mode). When executing some instructions, it will need to jump down to ring-0.
But how does the CPU know it needs to change modes? My first guess was that when the CPU fetches an instruction from RAM, it decodes it and a register value gets set. Depending on the register value during the execution of that instruction, the CPU will change modes.
But if this is the case, couldn't someone write malicious code to purposefully tell the CPU to switch modes so that it always executes in Kernel mode for the desired instructions?
Thank you!
Also, if there's a good resource/textbook for the intro/learning about CPU-modes, I would love to check that out. I can't find any good ones so far.


text:
Q: Is the %c fprintf specifier required to take an int argument In section 7.19.6.1 paragraph 8 of the C99 standard:

c If no l length modifier is present, the int argument is converted to an
  unsigned char, and the resulting character is written.

In section 7.19.6.1 paragraph 9 of the C99 standard:

If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

*

*Does the fprintf function require an int argument?

For example, would passing an unsigned int result in undefined behavior:
unsigned int foo = 42;

fprintf(fp, "%c\n", foo); /* undefined behavior? */

This worries me since an implementation could have defined char as having the same behavior as unsigned char (section 6.2.5 paragraph 15).
For these cases integer promotion may dictate that the char to be promoted to unsigned int on some implementations. Thus leaving the following code to risk undefined behavior on those implementations:
char bar = 'B';

fprintf(fp, "%c\n", bar); /* possible undefined behavior? */

*

*Are int variables and literal int constants the only safe way to pass a value to fprintf with the %c specifier?

A: %c conversion specification for fprintf requires an int argument. The value has to be of type int after the default argument promotions.
unsigned int foo = 42;
fprintf(fp, "%c\n", foo);

undefined behavior: foo has to be an int.
char bar = 'B';
fprintf(fp, "%c\n", bar);

not undefined behavior:bar is promoted (default argument promotions) to int as fprintf is a variadic function.
EDIT: to be fair, there are still some very rare implementations where it can be undefined behavior. For example, if char is an unsigned type with not all char values representable in an int (like in this implementation), the default argument promotion is done to unsigned int.

A: Yes, printf with "%c" requires an int argument -- more or less.
If the argument is of a type narrower than int, then it will be promoted. In most cases, the promotion is to int, with well defined behavior. In the very rare case that plain char is unsigned and sizeof (int) == 1 (which implies CHAR_BIT >= 16), a char argument is promoted to unsigned int, which can cause undefined behavior.
A character constant is already of type int, so printf("%c", 'x') is well defined even on exotic systems. (Off-topic: In C++, character constants are of type char.)
This:
unsigned int foo = 42;
fprintf(fp, "%c\n", foo);

strictly speaking has undefined behavior.  N1570 7.1.4p1 says:

If an argument to a function has ... a type (after promotion) not
  expected by a function with variable number of arguments, the behavior
  is undefined.

and the fprintf call clearly runs afoul of that. (Thanks to ouah for pointing that out.)
On the other hand, 6.2.5p6 says:

For each of the signed integer types, there is a corresponding (but
  different) unsigned integer type (designated with the keyword
  unsigned) that uses the same amount of storage (including sign information) and has the same alignment requirements.

and 6.2.5p9 says:

The range of nonnegative values of a signed integer type is a subrange
  of the corresponding unsigned integer type, and the representation of
  the same value in each type is the same.

with a footnote:

The same representation and alignment requirements are meant to imply
  interchangeability as arguments to functions, return values from
  functions, and members of unions.

The footnote says that function arguments of types int and unsigned int are interchangeable, as long as the value is within the representable range of both types. (For a typical 32-bit system, that means the value has to be in the range 0 to 231-1; int values from -231 to -1, and unsigned int values from 231 to 232-1, are outside the range of the other type, and are not interchangeable.)
But footnotes in the C standard are non-normative. They are generally intended to clarify requirements stated in the normative text, not to impose new requirements. But the normative text here merely states that corresponding signed and unsigned types have the same representation, which doesn't necessarily imply that they're passed the same way as function arguments. In principle, a compiler could ignore that footnote and, for example, pass int and unsigned int arguments in different registers, making fprintf(fp, "%c\n", foo); undefined.
But in practice, there's no reason for an implementation to play that kind of game, and you can rely on fprintf(fp, "%c\n", foo); to work as expected. I've never seen or heard of an implementation where it wouldn't work.
Personally, I prefer not to rely on that. If I were writing that code, I'd add an explicit conversion, via a cast, just so these questions don't arise in the first place:
unsigned int foo = 42;
fprintf(fp, "%c\n", (int)foo);

Or I'd make foo an int in the first place.


text:
Q: Adding a next Button to loop through elements in javascript I have some items in firestore.I want to show them sequentially but in random serial. So, I did the following code. Here I want to show a specific question and then when "next" button is clicked I want to show the next item. Here, in the forEach loop, I am rendering items to the renderQuestion function. And they are showing them in frontend using HTML and CSS.
But I am fetching this issue, where they keep showing everything till the end of the loop. They don't wait for the "next" button to be pressed. So, how can I fix this? I am new to JS, please forgive me, if I am already doing something wrong.
renderQuestion = (qID, roomID) => {
  q.innerHTML = qID.data().question;
  ans1.innerHTML = qID.data().a;
  ans2.innerHTML = qID.data().b;
  ans3.innerHTML = qID.data().c;
  ans4.innerHTML = qID.data().d;
  /* next.addEventListener("click", (e) => { //not working
    e.preventDefault();
    console.log("done");
  }); */
};

runningExam = async (review) => {
  const totalQ = review.data().total_questions;
  let arr = [];
  for (let i = 0; i <= totalQ; i++) {
    arr.push(false);
  }
  let n = totalQ;

  while (n) {
    let randomNumber = getRandom(totalQ);
    if (!arr[randomNumber]) {
      arr[randomNumber] = true;
      await db
        .collection("examrooms")
        .doc(review.id)
        .collection("questions")
        .where("serial", "==", randomNumber)
        .get()
        .then((snapshot) => {
          snapshot.docs.forEach((doc) => {
            renderQuestion(doc, review);
          });
        });
      n--;
    }
  }
};

A: It looks like you're trying to block the runningExam function until the user presses a button. I found another thread to achieve this.
Basically, turn the renderQuestion function into an asynchronous one, and wait for user input everytime it's called.
renderQuestion = async (qID, roomID) => {
  const timeout = async ms => new Promise(res => setTimeout(res, ms));
  let userClicked = false;

  q.innerHTML = qID.data().question;
  ans1.innerHTML = qID.data().a;
  ans2.innerHTML = qID.data().b;
  ans3.innerHTML = qID.data().c;
  ans4.innerHTML = qID.data().d;
  next.addEventListener("click", (e) => {
    userClicked = true;
    e.preventDefault();
    console.log("done");
  });

  while (userClicked === false) await timeout(50);
};

and in runningExam:
then( async (snapshot) => {
      for(let doc of snapshot.docs) {
        await renderQuestion(doc, review);
      };
  });

There's probably better ways to program this task, this is just a possible method to do it the way you were trying to.


text:
Q: set Java class Object values into JSP Page I want to set Java class Object values into JSP Page.
My Test_Object code
public class Test_Object {
    public String email;
    public String first_name;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFirst_name() {
        return first_name;
    }

    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }
}

My test.jsp page
<%@page import="test.io.Test_Object"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>TEST</title>

    <form action="loginServlet" method="post">

                First Name :
                <input type="text" value="" name="txtFirstname"
                    value='<%=((Test_Object) request.getAttribute("reqObj")).getFirst_name()%>' />

                Email :
                <input type="text" name="txtEmail"
                    value='<%=request.getParameter("email")%>' />

                <input type="submit" value="Submit" />

    </form>

My servlet code
String jb = "{\"email\":\"test@xyz.com\",\"fname\":\"test01\"}";
JSONObject jsonObject = new JSONObject(jb);
Test_Object obj = new Test_Object();
obj.email=jsonObject.getString("email");
obj.first_name=jsonObject.getString("fname");
request.setAttribute("reqObj", obj);
RequestDispatcher view = request.getRequestDispatcher("/test.jsp");
view.forward(request, response);

But when i redirect to test.jsp page there is no value display in TextBox.
I am using Eclipse Mars 2 with Java.

A: The problem might be in the way you are dispatching the request. In your Servlet you are dispatching the request to the /otn.jsp page. But you are trying to read the properties of the object you put in the request scope in the test.jsp page.
So you have to do the following:

*

*In the Servlet code:
RequestDispatcher view = request.getRequestDispatcher("/test.jsp");

*In the test.jsp page change the input elements as follows:
<input type="text" value="${reqObj.first_name}" name="txtFirstname"/>
<input type="text" value="${reqObj.email}" name="txtEmail" />

I am using here Expression Language with the assumption that you are using one of the current web containers such as Tomcat version 7 and later.
Some minor comments:

*

*Why are you creating the JSONObject eventhough you are not doing anything useful with it in your Servlet code?

*When you define Java types (classes, interfaces, ...) use camelcase instead of underscore in the names: use TestObject instead of Test_Object and firstName instead of first_name. Here you'll find naming conventions for Java.


text:
Q: What's the difference between a gemspec summary and a gemspec description? When you write a gemspec file, what is the practical difference, if any, between the summary and description fields?

A: They are used in different places. summary is seen you do gem list -d, while description is seen on http://rubygems.org. Description "should be more detailed than summary" (http://guides.rubygems.org/specification-reference/), but in reality you see
s.description = s.summary

in .gemspecs a lot.

A: I realize this is an old question, but I found my way here.
Per the reference, the description is optional and the summary is required. So I define a summary but no description.


text:
Q: Problems with BinaryFormatter on class with DataContract? I have a class
[DataContract]
    public class Car
   {
        public bool pbIsHatchBack;
        string prSt = "royi";

    }

And i want to serialize it with BinaryFormatter:
  BinaryFormatter binFormat = new BinaryFormatter();
        Stream fStream = new FileStream("c:\\CarData.dat", FileMode.Create, FileAccess.Write, FileShare.None);
        binFormat.Serialize(fStream, carObj);
        fStream.Close();

But u get this error

Type 'SerializationTypes+Car' in Assembly 'ConsoleApplication2,
  Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked
  as serializable.

If i remove the [DataContract] and replace it with [Serializable] its ok. but why ?
how WCF does it behind the scene (when tcpBinding ?)?
Why can't i use the DataContract ???

A: WCF does not use the BinaryFormatter to serialize its objects, it uses either the DataContractSerializer (by default) or some of its other serializers (XmlSerializer, DataContractJsonSerializer, etc). BinaryFormatter was released before WCF (in .NET Framework 1.0, IIRC) so is not aware of the [DataContract]/[DataMember] attributes (which were released in .NET Framework 3.0, along with WCF.
On netTcpBinding WCF still uses the DataContractSerializer, but instead of using a "normal" XML reader/writer, it uses a binary-aware XML reader/writer, which is how we have the binary encoding in WCF.
The WCF serializers understand the [Serializable] attribute, so you can use it with WCF as well. Or you can also use both attributes, if you want your type to be serializable by the BinaryFormatter but use the more fine-grained control that the [DC]/[DM] attributes give you.


text:
Q: Normal distribution, uncorrelated random variables $Y$ is a random variable such that $$Y = \cases{X,\hspace{2mm} \mathrm{for}\hspace{1mm} |X| \leq c \\ \\-X,\hspace{2mm}\mathrm{for}\hspace{1mm}|X|>c,} $$ where $c \geq 0,$ and $X$ has the standard normal distribution. I'd like to show that there exists a $c$ so that $\mathrm{Cov}(X,Y)=0$.
What I know so far is that $Y$ also has the standard normal distribution, which means that $\mathrm{E}X \mathrm{E}Y = 0 \cdot 0.$ Hence, I suppose I need to find some $c$ that will make $\mathrm{E}XY$ equal to zero, in order to get $\mathrm{Cov}(X,Y) = \mathrm{E}XY - \mathrm{E}X\mathrm{E}Y = 0$. I haven't had any success, though.
Since if $c \rightarrow \infty$, we get $\mathrm{Cov}(X,Y) = 1$, I suppose that if $c \rightarrow 0$, we'll have $\mathrm{Cov}(X,Y) = -1$ (?), but I don't know if that is something I can use. I'm pretty lost on how to solve this.

A: $$XY = \begin{cases}X^2 & |X| \le c \\ -X^2 & |X|>c\end{cases}$$
$$E[XY] = E[X^2 \mathbf{1}_{|X| \le c}] - E[X^2 \mathbf{1}_{|X| > c}]$$
(I think you already did the above.)
So as you noted, when $c \to \infty$ this becomes approaches $1$, while when $c \to 0$ this approaches $-1$. If you accept that the above quantity varies continuously with $c$, then you are done (intermediate value theorem). I think proving continuity is pretty straightforward; you can write down the integral and even use integration by parts to give an explicit expression in terms of $c$ and the CDF of the standard normal.

A: You are correct that $Y \sim \text{N}(0,1)$ under your specification, so you have $\mathbb{E}(X) = \mathbb{E}(Y) = 0$.  Letting $y(x)$ be your specified function and letting $\phi$ be the standard normal density you then have:
$$\begin{equation} \begin{aligned}
\mathbb{Cov}(X,Y) = \mathbb{E}(XY) &= \int \limits_{-\infty}^\infty x y(x) \phi(x) dx \\[8pt]
&= - \int \limits_{-\infty}^c x^2 \phi(x) dx +
 \int \limits_{-c}^c x^2 \phi(x) dx -\int \limits_c^\infty x^2 \phi (x) dx \\[8pt]
&= 4 \int \limits_0^c x^2 \phi (x) dx  - \int \limits_{-\infty}^\infty x^2 \phi(x) dx \\[8pt]
&= 4 \int \limits_0^c x^2 \phi (x) dx - 1. \\[8pt]
\end{aligned} \end{equation}$$
Now, using integration by parts, it can be shown that:
$$I(c) \equiv \int \limits_0^c x^2 \phi(x) dx = \int \limits_0^c \Big( \phi(x) - \phi (c) \Big) dx.$$
Hence, we have $\mathbb{Cov}(X,Y) = 0$ at the point where:
$$\begin{equation} \begin{aligned}
\int \limits_0^c \Big( \phi(x) - \phi (c) \Big) dx = \frac{1}{4}.
\end{aligned} \end{equation}$$
This integral condition can be solved numerically to yield $c = 1.538172$ (rounded to six decimal places).  Note that with this value the random variables $X$ and $Y$ are uncorrelated, but of course, they are not independent.


text:
Q: Post Multidemensional Array with jQuery to PHP I'm trying to send a multidimensional array to my PHP Webservice.
As you can see in the console logs, the normal variable test2 is send successful, but my array is not transferred to my server. What am I doing wrong?
JavaScript:
function filter() {
    var filters = [];
    filters["f1"] = $("#filter-select").val() || [];

    console.log("Filters Array:")
    console.log(filters);

    $.post("/service/test",{test : filters, test2 : "test"},function(data){
        console.log("Webservice Response:");
        console.log(data);
    })

}
PHP:
var_dump($_POST);
die();

Console:
Filters Array:
[f1: Array[1]]
Webservice Response:
array(1) {
  ["test2"]=>
  string(4) "test"
}

A: First of all as mentioned by cocco in the comments I needed to use JSON.stringify, but it would return an empty array.
I used var filters = {}; for generating an object.


text:
Q: sforce.console.refreshPrimaryTabById is not refreshing feed publisher have developed a VF form and put it in a quick action & assigned it to case page layout. I am refreshing the current case tab by using console integration toolkit at submit button's oncomplete event (note that I have 30 of this command because I was unable to obtain enclosing tab id from inside quick action VF, so I refresh all open tabs)
var primaryTabId_0 = 'scc-pt-0';
sforce.console.refreshPrimaryTabById(primaryTabId_0, true);

The problem is; console components of page layout and detail view of record refreshes successfully, but the feed actions remain unrefreshed. This VF form links an account to the case, and I cannot see this account prepopulated in one of "update case" quick actions, in the account lookup field. When I manually refresh the page or tab, this field is prepopulated.
Has this issue acknowledged as a bug yet, or is there any other code I can add that will allow me to refresh the feed view as well?
Cheers


text:
Q: HTML5/Javascript canvas - draw circle with 7 partitions I need draw circle with 7 partitions.
I have already this code done:
HTML
<body style="background:#F6A631;">
    <canvas id="wheelcanvas" width="730" height="730"></canvas>
</body>

JS
var services = ["paragraphs", "paragraphs", "paragraphs", "paragraphs", "paragraphs", "paragraphs", "paragraphs"];

  function serviceCircle() {
    var canvas = document.getElementById("wheelcanvas");
    if (canvas.getContext) {
      var outsideRadius = 360;
      var textRadius = 280;
      var insideRadius = 220;

      ctx = canvas.getContext("2d");
      ctx.clearRect(0,0,720,720); // 720 - 360 - 180 (500 - 250)

      ctx.strokeStyle = "#fff";
      ctx.lineWidth = 5;

      ctx.font = 'bold 18px Tahoma';

      for(var i = 0; i < 7; i++) {
        var angle = startAngle + i * arc;
        ctx.fillStyle = "#ffc000";

        ctx.translate(360 + Math.cos(angle + arc / 2) * textRadius, 360 + Math.sin(angle + arc / 2) * textRadius);
        // ctx.rotate(angle + arc / 2 + Math.PI / 2);
        var text = services[i];
        ctx.fillText(text, -ctx.measureText(text).width / 2, 0);
        ctx.restore();
      }

      //Arrow
      ctx.fillStyle = "#fff";
      ctx.beginPath();
      ctx.moveTo(250 - 4, 250 - (outsideRadius + 5));
      ctx.lineTo(250 + 4, 250 - (outsideRadius + 5));
      ctx.lineTo(250 + 4, 250 - (outsideRadius - 5));
      ctx.lineTo(250 + 9, 250 - (outsideRadius - 5));
      ctx.lineTo(250 + 0, 250 - (outsideRadius - 13));
      ctx.lineTo(250 - 9, 250 - (outsideRadius - 5));
      ctx.lineTo(250 - 4, 250 - (outsideRadius - 5));
      ctx.lineTo(250 - 4, 250 - (outsideRadius + 5));
      ctx.fill();
    }
  }
  draw();

My result - Image
I need this one. With hover on partition and changing it's background.
Don't have any idea how to solve it.

A: Here's some pseudo-code to highlight the partition under the mouse...
Calc the angle of mouse vs centerpoint using:
// mx,my are mouse coordinates, cx,cy are centerpoint coordinates
var angle=Math.atan2(my-cy,mx-cx).

Calc the distance to the mouse from the centerpoint using:
var distance=Math.sqrt((mx-cx)*(mx-cx)+(my-cy)*(my-cy)).

If angle is between the starting & ending angle of a partition and distance is between the inner and outer radius then the mouse is in that partition.
var isInsidePartition1 =
      angle>partition1StartingAngle &&
      angle<=partition1EndingAngle &&
      distance>=innerRadius &&
      distance<=outerRadius;

Now redraw everything (nothing highlighted);
And finally, if the mouse 'hit' a partition, redraw just the 'hit' partition in your highlighted color.


text:
Q: My Tools folder has gone how to get it Today at morning about 6 hour ago I was updating tools and installing new features from SDK Manager. And due to my Internet connection shutdown Updating process canceled automatically. Now when I try to open Android SDK Manager it says

Failed to execute tools/android.bat.
  The system cannot find the file specified.

Then I try to find the android.bat file in tools And I realized that my Tools folder is missing with all its components. But  as I know everything is fine except this problem. How can I get that folder back or download that specific folder instead of the whole android SDK.

A: Take a look at where the SDK location is defined in Android Studio (File -> Settings -> Appearance & Behaviour -> System Settings -> Android SDK -> Android SDK location) and verify if the folder and its contents still exist on your system.

If the folder has gone, you will need to re-download the SDK (link, see "Get just the command line tools"). Download and extract to the location defined in Android Studio, or point Android SDK Location to wherever you extract the SDK to.
You will also need to re-download whatever tools and libraries you need, time consuming but unfortunately necessary if your existing SDK has indeed been wiped.

A: You need re-install or update Android SDK


text:
Q: A.e. vanishing function has a.e. vanishing derivative? Let $f:[a,b]\rightarrow\mathbb{R}$ be differentiable almost everywhere and $f(x)=0$ almost everywhere. Does this imply $f'(x)=0$ almost everywhere?

A: Proof of your statement:
Take any $x$ from the set $\{x|f'(x) \text{ exists}\}$, which has measure 1. Consider the set with positive measure $[x-\frac 1 n,x+\frac 1 n]\cap [a,b]$. Due to $f=0$ almost everywhere, there exists an $x_n$ in this set with $f(x_n)=0$. By the Squeeze Theorem we have $x_n\rightarrow x$.
As existence of $f'(x)$ implies continuity at $x$ we have $f(x)=0$ and there therefore for any $n$:
$$\frac{f(x_n)-f(x)}{a_n-x}=0 $$
As the limit $f'(x)$ equals any sequential limit, this concludes the proof.


text:
Q: Prove if $X$ is an integrable errv, then $X\geq 0$ a.s iff $\int_{A} XdP\geq 0$ I am trying to prove this question:
If $X$ is an integrable errv then $X\geq 0$ a.s iff $\forall A\in \Omega$, $\int_{A} XdP\geq 0$
Can you give me any hint to construct a proof? I know that $E(X)=\int_{A} XdP +\int_{A^c} XdP$ and $\int_{A} XdP = \int \mathbb{1}_A XdP$
Do I have to use those equation, or am i wrong?

A: Assume that $\mathbb E[|X|]<\infty$. If $\mathbb P(X\geqslant 0)=1$, then for any $A\in\Omega$ we have
$$
\mathbb E[X\mathsf 1_A] = \mathbb E\left[X\mathsf 1_A\mathsf 1_{\{X\geqslant 0\}}\right] + \mathbb E\left[X\mathsf 1_A\mathsf 1_{\{X< 0\}}\right] = \mathbb E\left[X\mathsf 1_A\mathsf 1_{\{X\geqslant 0\}}\right] \geqslant 0,
$$
since $\mathbb E\left[\mathsf 1_{\{X>0\}}\right]=\mathbb P(X<0)=0$ and the expectation of a nonnegative random variable is nonnegative. This follows from the Lebesgue integral of a nonnegative measurable function being nonnegative.
Conversely, suppose that $\mathbb E\left[X\mathsf 1_A\right]\geqslant 0$ for all $A\in\Omega$. Then in particular $\mathbb E\left[X\mathsf 1_{\{X<0\}} \right]\geqslant 0$. This implies that $\mathbb P(X\geqslant 0)=1$.


text:
Q: In Clojure 1.3, How to read and write a file I'd like to know the "recommended" way of reading and writing a file in clojure 1.3 .

*

*How to read the whole file

*How to read a file line by line

*How to write a new file

*How to add a line to an existing file

A: Regarding question 2, one sometimes wants the stream of lines returned as a first-class object. To get this as a lazy sequence, and still have the file closed automatically on EOF, I used this function:
(use 'clojure.java.io)

(defn read-lines [filename]
  (let [rdr (reader filename)]
    (defn read-next-line []
      (if-let [line (.readLine rdr)]
       (cons line (lazy-seq (read-next-line)))
       (.close rdr)))
    (lazy-seq (read-next-line)))
)

(defn echo-file []
  (doseq [line (read-lines "myfile.txt")]
    (println line)))

A: If the file fits into memory you can read and write it with slurp and spit:
(def s (slurp "filename.txt"))

(s now contains the content of a file as a string)
(spit "newfile.txt" s)

This creates newfile.txt if it doesnt exit and writes the file content.
If you want to append to the file you can do
(spit "filename.txt" s :append true)

To read or write a file linewise you would use Java's reader and writer. They are wrapped in the namespace clojure.java.io:
(ns file.test
  (:require [clojure.java.io :as io]))

(let [wrtr (io/writer "test.txt")]
  (.write wrtr "hello, world!\n")
  (.close wrtr))

(let [wrtr (io/writer "test.txt" :append true)]
  (.write wrtr "hello again!")
  (.close wrtr))

(let [rdr (io/reader "test.txt")]
  (println (.readLine rdr))
  (println (.readLine rdr)))
; "hello, world!"
; "hello again!"

Note that the difference between slurp/spit and the reader/writer examples is that the file remains open (in the let statements) in the latter and the reading and writing is buffered, thus more efficient when repeatedly reading from / writing to a file.
Here is more information: slurp spit
clojure.java.io
Java's BufferedReader
Java's Writer

A: Assuming we're only doing text files here and not some crazy binary stuff.
Number 1: how to read an entire file into memory.
(slurp "/tmp/test.txt")

Not recommended when it is a really big file.
Number 2: how to read a file line by line.
(use 'clojure.java.io)
(with-open [rdr (reader "/tmp/test.txt")]
  (doseq [line (line-seq rdr)]
    (println line)))

The with-open macro takes care that the reader is closed at the end of the body. The reader function coerces a string (it can also do a URL, etc) into a BufferedReader. line-seq delivers a lazy seq. Demanding the next element of the lazy seq results into a line being read from the reader.
Note that from Clojure 1.7 onwards, you can also use transducers for reading text files.
Number 3: how to write to a new file.
(use 'clojure.java.io)
(with-open [wrtr (writer "/tmp/test.txt")]
  (.write wrtr "Line to be written"))

Again, with-open takes care that the BufferedWriter is closed at the end of the body. Writer coerces a string into a BufferedWriter, that you use use via java interop: (.write wrtr "something").
You could also use spit, the opposite of slurp:
(spit "/tmp/test.txt" "Line to be written")

Number 4: append a line to an existing file.
(use 'clojure.java.io)
(with-open [wrtr (writer "/tmp/test.txt" :append true)]
  (.write wrtr "Line to be appended"))

Same as above, but now with append option.
Or again with spit, the opposite of slurp:
(spit "/tmp/test.txt" "Line to be written" :append true)

PS: To be more explicit about the fact that you are reading and writing to a File and not something else, you could first create a File object and then coerce it into a BufferedReader or Writer:
(reader (file "/tmp/test.txt"))
;; or
(writer (file "tmp/test.txt"))

The file function is also in clojure.java.io.
PS2: Sometimes it's handy to be able to see what the current directory (so ".") is. You can get the absolute path in two ways:
(System/getProperty "user.dir")

or
(-> (java.io.File. ".") .getAbsolutePath)

A: This is how to read the whole file.
If the file is in the resource directory, you can do this:
(let [file-content-str (slurp (clojure.java.io/resource "public/myfile.txt")])

remember to require/use clojure.java.io.

A: To read a file line by line you no longer need to resort to interop:
(->> "data.csv"
      io/resource
      io/reader
      line-seq
      (drop 1))

This assumes that your data file is kept in the resources directory and that the first line is header information that can be discarded.

A: (require '[clojure.java.io :as io])
(io/copy (io/file "/etc/passwd") \*out*\)


text:
Q: Generate List of custom Actions Taken by a specific user in my app Hi I've developed a Facebook app that allows user to take custom actions that result in custom open graph objects. I would now like to generate lists of what actions specific users have taken in my app. is this information stored somewhere in the open graph? Do I need to use FQL? Can anyone point me in a good direction?
Much Thanks!

A: The developer tool has a "Get Code" link. Click it and you can see how to read all the actions.


text:
Q: Why is MaterialAlertDialog so slow when measuring a custom view/layout? I'm working on a hobby project where I'm building a custom Bluetooth remote that can be configured using a companion native Android app. Everything is working just fine but I'm running into this weird performance issue with the MaterialAlertDialog using a custom layout and View Binding.
To be specific, when first showing the dialog, inflating, measuring, and then drawing the dialog takes quite a long time. According to some systraces I've recorded, the UI hangs for about 1 to 2 seconds before rendering the next frame after starting the MaterialAlertDialogBuilder logic.
For context, this screenshot from Android Studio shows the UI I've built and this is the custom view for the AlertDialog.

These are the related libraries I'm using and their respective versions
Kotlin 1.4.30
AndroidX AppCompat 1.3.0-beta01
AndroidX ConstraintLayout 2.0.4
AndroidX Fragment KTX 1.3.0
Material Components 1.3.0

And here's the XML for this layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingHorizontal="24dp"
    android:paddingTop="24dp">

    <com.google.android.material.textview.MaterialTextView
        android:id="@+id/dialogEditPresetHotkeyButtonPosition"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:textAppearance="@style/TextAppearance.ctrl.Overline"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.textview.MaterialTextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:text="@string/edit_hotkey"
        android:textAppearance="@style/TextAppearance.ctrl.Headline6.Emphasis"
        app:layout_constraintEnd_toEndOf="@id/dialogEditPresetHotkeyButtonPosition"
        app:layout_constraintStart_toStartOf="@id/dialogEditPresetHotkeyButtonPosition"
        app:layout_constraintTop_toBottomOf="@id/dialogEditPresetHotkeyButtonPosition" />

    <androidx.appcompat.widget.AppCompatSpinner
        android:id="@+id/dialogEditPresetHotkeyGroup"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:layout_marginTop="40dp"
        android:layout_marginEnd="1dp"
        android:background="@drawable/bg_spinner_key_groups"
        app:layout_constraintEnd_toStartOf="@id/dialogEditPresetHotkeyKeyContainer"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/dialogEditPresetHotkeyButtonPosition" />

    <FrameLayout android:id="@+id/dialogEditPresetHotkeyKeyContainer"
        android:layout_width="0dp"
        android:layout_height="48dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/dialogEditPresetHotkeyGroup"
        app:layout_constraintTop_toTopOf="@+id/dialogEditPresetHotkeyGroup">

        <androidx.appcompat.widget.AppCompatEditText
            android:id="@+id/dialogEditPresetHotkeyKeyAlphanumeric"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingHorizontal="16dp"
            android:background="@drawable/bg_key"
            android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
            android:inputType="textCapCharacters"
            android:maxLength="1" />

        <androidx.appcompat.widget.AppCompatSpinner
            android:id="@+id/dialogEditPresetHotkeyKey"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/bg_spinner_keys"
            android:visibility="gone" />

    </FrameLayout>

    <com.google.android.material.button.MaterialButton
        android:id="@+id/dialogEditPresetHotkeyModifierShift"
        style="@style/Widget.ctrl.Button.Outline.Narrow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:checkable="true"
        android:text="@string/shift"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/dialogEditPresetHotkeyGroup" />

    <com.google.android.material.button.MaterialButtonToggleGroup
        android:id="@+id/dialogEditPresetHotkeyModifiers"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/dialogEditPresetHotkeyModifierShift">

        <com.google.android.material.button.MaterialButton
            android:id="@+id/dialogEditPresetHotkeyModifierCtrl"
            style="@style/Widget.ctrl.Button.Outline.Narrow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/ctrl" />

        <com.google.android.material.button.MaterialButton
            android:id="@+id/dialogEditPresetHotkeyModifierMeta"
            style="@style/Widget.ctrl.Button.Outline.Narrow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/meta" />

        <com.google.android.material.button.MaterialButton
            android:id="@+id/dialogEditPresetHotkeyModifierAlt"
            style="@style/Widget.ctrl.Button.Outline.Narrow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/alt" />

    </com.google.android.material.button.MaterialButtonToggleGroup>

    <com.google.android.material.button.MaterialButton
        android:id="@+id/dialogEditPresetHotkeyModifierRShift"
        style="@style/Widget.ctrl.Button.Outline.Narrow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checkable="true"
        android:text="@string/rshift"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@id/dialogEditPresetHotkeyModifierShift" />

    <com.google.android.material.button.MaterialButtonToggleGroup
        android:id="@+id/dialogEditPresetHotkeyRModifiers"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@id/dialogEditPresetHotkeyModifiers">

        <com.google.android.material.button.MaterialButton
            android:id="@+id/dialogEditPresetHotkeyModifierRAlt"
            style="@style/Widget.ctrl.Button.Outline.Narrow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/ralt" />

        <com.google.android.material.button.MaterialButton
            android:id="@+id/dialogEditPresetHotkeyModifierRMeta"
            style="@style/Widget.ctrl.Button.Outline.Narrow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/rmeta" />

        <com.google.android.material.button.MaterialButton
            android:id="@+id/dialogEditPresetHotkeyModifierRCtrl"
            style="@style/Widget.ctrl.Button.Outline.Narrow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/rctrl" />

    </com.google.android.material.button.MaterialButtonToggleGroup>

</androidx.constraintlayout.widget.ConstraintLayout>

To help keep my Fragment's code clean, I've written a few Kotlin Extension functions to set up the MaterialAlertDialog, with ViewBinding, like I'm also using in my Fragments.
class ViewBindingMaterialAlertDialogBuilder<VB : ViewBinding>(
    context: Context,
    viewBindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> VB
) : MaterialAlertDialogBuilder(context) {
    val viewBinding: VB by lazy {
        viewBindingInflater(LayoutInflater.from(context), null, false)
    }
}
inline fun <VB: ViewBinding> Context.customViewAlertDialogBuilder(
    noinline viewBindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> VB,
    cancelable: Boolean = false,
    showManually: Boolean = false,
    init: ViewBindingMaterialAlertDialogBuilder<VB>.() -> Unit
) = ViewBindingMaterialAlertDialogBuilder(this, viewBindingInflater).apply {
    setCancelable(cancelable)
    init()
    if (!showManually) show()
}
inline fun <VB : ViewBinding> ViewBindingMaterialAlertDialogBuilder<VB>.initCustomView(
    init: VB.() -> Unit
) = setView(viewBinding.apply(init).root)
inline fun MaterialAlertDialogBuilder.positiveButton(
    @StringRes text: Int,
    automaticallyDismiss: Boolean = true,
    crossinline action: () -> Unit
) = setPositiveButton(text) { dialog, _ -> if (automaticallyDismiss) dialog.dismiss(); action() }
inline fun MaterialAlertDialogBuilder.negativeButton(
    @StringRes text: Int,
    automaticallyDismiss: Boolean = true,
    crossinline action: () -> Unit
) = setNegativeButton(text) { dialog, _ -> if (automaticallyDismiss) dialog.dismiss(); action() }
inline fun MaterialAlertDialogBuilder.neutralButton(
    @StringRes text: Int,
    automaticallyDismiss: Boolean = true,
    crossinline action: () -> Unit
) = setNeutralButton(text) { dialog, _ -> if (automaticallyDismiss) dialog.dismiss(); action() }
inline fun MaterialAlertDialogBuilder.show(
    crossinline onShow: AlertDialog.() -> Unit
) = create().apply {
    setOnShowListener { onShow(it as AlertDialog) }
}.show()

And then I use these as follows in my Fragment.
NOTE: The actual code described in the comments below had been commented out at the time of recording the systrace further down. This was done to make sure the initialization code wasn't impacting performance or skewing data.
context.customViewAlertDialogBuilder(DialogEditPresetHotkeyBinding::inflate, showManually = true) {
    initCustomView {
        //Populate TextView and set two adapters for the Spinners
    }
    positiveButton(R.string.save) {
        //Persist entered value to device
    }
    negativeButton(R.string.discard) {} //Simply dismisses
    neutralButton(R.string.clear) {
        //Persists default value to device
    }
    show {
        /*
        Set OnItemSelectedListeners for Spinners
        Add TextWatcher for EditText
        Check if entered values are valid (else disable Save button)
         */
    }
}

After then cleaning, building, and running my app on a physical device (LG G6 H870), I get the following systrace.
NOTE: I restarted my phone before running this trace to make sure the least amount of apps possible were running in the background to not skew results.

For good measure (pun intended) and as a performance comparison, I used the same layout in a separate Fragment
class TestFragment : Fragment() {
    private var viewBinding: DialogEditPresetHotkeyBinding? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        viewBinding = DialogEditPresetHotkeyBinding.inflate(inflater, container, false)
        return viewBinding?.root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        viewBinding = null
    }
}

And the systrace when navigating to this Fragment.
NOTE: I force-stopped the app from Settings, then ran it after again cleaning and building

So, after all that, my question boils down to:
Why is inflating and measuring a custom layout in an AlertDialog so much slower than when using a Fragment?
I know there probably are some optimizations possible within my XML, but it still takes over a second to first show the AlertDialog, compared to half that when using a Fragment.
This is a best-case scenario as I've seen it go as high as 1.7 seconds with some apps running in the background. This is way higher than the 700ms Android 'jank' threshold, so I'm also getting Davey! log messages, skipped frames, halted ripple animations, etc.
P.S. I know this is a very long question, thank you for reading :)

EDIT 1
Adding my styles.xml and themes.xml, nothing but colors and some dimensions, I like to keep it simple, plus the fact that I'm not a designer :)
styles.xml
<resources>
    <style name="Widget.ctrl.AlertDialog" parent="MaterialAlertDialog.MaterialComponents">
        <item name="backgroundInsetTop">@dimen/mtrl_alert_dialog_background_inset_start</item>
    </style>

    <style name="Widget.ctrl.Button.Outline.Narrow" parent="Widget.MaterialComponents.Button.OutlinedButton">
        <item name="android:minWidth">64dp</item>
    </style>
    <style name="Widget.ctrl.Button.Dialog" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
    </style>
    <style name="Widget.ctrl.Button.Dialog.Positive">
        <item name="android:textColor">@color/dialog_button_positive</item>
        <item name="rippleColor">@color/colorPrimary</item>
    </style>
    <style name="Widget.ctrl.Button.Dialog.Negative">
        <item name="android:textColor">@color/colorError</item>
        <item name="rippleColor">@color/colorError</item>
    </style>
    <style name="Widget.ctrl.Button.Dialog.Neutral">
        <item name="android:textColor">@color/colorOnSurface</item>
        <item name="rippleColor">@color/colorOnSurface</item>
    </style>

    <style name="TextAppearance.ctrl.Headline6" parent="TextAppearance.MaterialComponents.Headline6">
        <item name="android:textColor">@color/colorTextNormal</item>
    </style>
    <style name="TextAppearance.ctrl.Headline6.Emphasis">
        <item name="android:textColor">@color/colorTextEmphasis</item>
    </style>
    <style name="TextAppearance.ctrl.Subtitle1" parent="TextAppearance.MaterialComponents.Subtitle1">
        <item name="android:textColor">@color/colorTextNormal</item>
    </style>
    <style name="TextAppearance.ctrl.Subtitle1.Emphasis">
        <item name="android:textColor">@color/colorTextEmphasis</item>
    </style>
    <style name="TextAppearance.ctrl.Body1" parent="TextAppearance.MaterialComponents.Body1">
        <item name="android:textColor">@color/colorTextNormal</item>
    </style>
    <style name="TextAppearance.ctrl.Body1.Emphasis">
        <item name="android:textColor">@color/colorTextEmphasis</item>
    </style>
    <style name="TextAppearance.ctrl.Body2" parent="TextAppearance.MaterialComponents.Body2">
        <item name="android:textColor">@color/colorTextNormal</item>
    </style>
    <style name="TextAppearance.ctrl.Overline" parent="TextAppearance.MaterialComponents.Overline">
        <item name="android:textColor">@color/colorTextNormal</item>
    </style>

    <style name="ShapeAppearance.ctrl.40dpCircle" parent="ShapeAppearance.MaterialComponents">
        <item name="cornerSize">20dp</item>
    </style>
</resources>

themes.xml
<resources>
    <style name="Theme.ctrl" parent="Theme.MaterialComponents.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryVariant">@color/colorPrimaryVariant</item>
        <item name="colorOnPrimary">@color/colorOnPrimary</item>
        <item name="colorSecondary">@color/colorSecondary</item>
        <item name="colorSecondaryVariant">@color/colorSecondaryVariant</item>
        <item name="colorOnSecondary">@color/colorOnSecondary</item>
        <item name="android:colorBackground">@color/colorBackground</item>
        <item name="colorOnBackground">@color/colorOnBackground</item>
        <item name="colorSurface">@color/colorSurface</item>
        <item name="colorOnSurface">@color/colorOnSurface</item>
        <item name="colorError">@color/colorError</item>
        <item name="colorOnError">@color/colorOnError</item>
        <item name="android:statusBarColor">@color/colorBackground</item>

        <item name="materialAlertDialogTheme">@style/ThemeOverlay.ctrl.MaterialAlertDialog</item>
    </style>

    <style name="ThemeOverlay.ctrl.MaterialAlertDialog" parent="ThemeOverlay.MaterialComponents.MaterialAlertDialog">
        <item name="elevationOverlayEnabled">false</item>
        <item name="alertDialogStyle">@style/Widget.ctrl.AlertDialog</item>
        <item name="buttonBarPositiveButtonStyle">@style/Widget.ctrl.Button.Dialog.Positive</item>
        <item name="buttonBarNegativeButtonStyle">@style/Widget.ctrl.Button.Dialog.Negative</item>
        <item name="buttonBarNeutralButtonStyle">@style/Widget.ctrl.Button.Dialog.Neutral</item>
    </style>
</resources>

EDIT 2:
I tried using the AndroidX AsyncLayoutInflater to see if it makes a difference. It does...
...but it feels even worse. What ends up happening is that the ripple animation no longer hangs halfway through, instead, it completes and a second later, a dialog finally pops up. I feel this is confusing to a user as one part of the interface feels responsive but there's a lot of lag on the dialog showing due to the long measuring. So I don't see this as a fix.

A: In the end, it turned out my device I was testing on was just very slow...
I switched from an LG G6 to a OnePlus 8T and the dialog now pops up almost instantaneously, oh well...


text:
Q: open connection() method exist in which class also tell me the sub classes of the this class URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setInstanceFollowRedirects(true);
HttpURLConnection.setFollowRedirects(true)

openconnection() method in this code of this class
What is the meaning of (Httpurlconnection). is that casting or not?

A: If I understand weel your question, yes, a type in parethesis is always casting.
(double)x = 8;

forces x, which can be an int for example, to have an double behavior


text:
Q: Twitter Bootstrap Carousel Events i work on bootstrap carousel to Create new Carousel:
The goal of the idea is that the image thumbnail contains the following slide
I arrived one of the solutions but there are three problems:

first problem:
the image thumbnail don't appear until the slide change, what i need that when page loaded, image thumbnail appear when page loaded not when slide change.

second problem:
i need image thumbnail get the next slide of the current slide, For there is a problem in my code.
third problem:
when i click in the previous arrow control, Problem appear until the code is not working properly.

$(document).ready(function () {
    $('.carousel').carousel({
        interval: 250000
    })
    $('#my-carousel').bind('slide.bs.carousel', function (e) {
        $(".my img").attr("src", $(".active").next().children("img").attr("src"));
    });
});
.my{
     width:100px;
     height:100px;
     margin:20px auto;
     border:1px solid #808080;
}
.my img{
    width:100px;
    height:100px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Caption heading 1

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Caption heading 2

Morbi eget libero quis metus consectetur semper.

Caption heading 3

Suspendisse ullamcorper massa eget eleifend iaculis.

Caption heading 3

Suspendisse ullamcorper massa eget eleifend iaculis.

            Previous

            Next

A: Here is the solution of your first and second problem
$(document).ready(function () {
    $('.carousel').carousel({
        interval: 250000
    })
    $(".my img").attr("src", $(".active").next().children("img").attr("src"));
    $('#my-carousel').bind('slid.bs.carousel', function (e) {
        $(".my img").attr("src", $(".active").next().children("img").attr("src"));
    });
});

You can also check here on fiddle https://jsfiddle.net/bhumi/t05u7Lzu/
UPDATE: solution of third
$(document).ready(function () {
    $('.carousel').carousel({
        interval: 250000
    })
    $(".my img").attr("src", $(".active").next().children("img").attr("src"));
    $('#my-carousel').bind('slid.bs.carousel', function (e) {console.log(e.direction);
            if(e.direction=='left'){
         $(".my img").attr("src", $(".active").next().children("img").attr("src"));
        }else{
        $(".my img").attr("src", $(".active").prev().children("img").attr("src"));
        }
    });
});

https://jsfiddle.net/bhumi/t05u7Lzu/1/


text:
Q: How to visualize a Schrödinger cat state? I recently read about Schrödinger cat states, which are basically a superposition of two coherent states $|\alpha\rangle$ with opposite phases, that is,
$$
|\mathrm{cat}\rangle = |\alpha\rangle \pm |{-\alpha}\rangle
$$
which gives us an even Shcrödinger cat states with only even parts and an odd cat state with only odd parts,
\begin{align}
\left| \mathrm{cat}_\mathrm{even} \right\rangle & \propto 2 e^{-\frac{|\alpha|^2}{2}} \left( \frac{\alpha^0}{\sqrt{0!}}| 0 \rangle + \frac{\alpha^2}{\sqrt{2!}}| 2 \rangle + \frac{\alpha^4}{\sqrt{4!}}| 4 \rangle + \dots \right),
\quad\text{and}
\\
\left| \mathrm{cat}_\mathrm{odd} \right\rangle & \propto 2 e^{- \frac{|\alpha|^2}{2}} \left( \frac{\alpha^1}{\sqrt{1!}} | 1 \rangle + \frac{\alpha^3}{\sqrt{3!}} | 3 \rangle + \frac{\alpha^5}{\sqrt{5!}} | 5 \rangle + \dots\right).
\end{align}
My question is, how can I visualize something like this? I've seen a few pictures of density matrices and Wigner functions, but I'm not exactly knowledgeable about those. Is there an easier way to understand this/plot it myself? I'm thinking of something similar to the probabilities for a coherent state, which is basically a Poisson distribution. Or do I explicitly need Wigner functions and such?

A: The visualization method you choose is directly and completely determined by the information you need to see regarding your state. For the states of a single bosonic mode, there are multiple different visualization methods, and they all have their pros and cons. In particular, there is a direct trade-off between the amount of information you can display on a plot and the work you will need to put in to understand the plots. Simply put, plots which are easy to understand won't depict the states in sufficient detail.
Thus, you might want to plot

*

*the photon-number distribution, which is completely insensitive to the phases and therefore cannot distinguish between coherent superpositions of those number states and incoherent ones;

*the position- and momentum-space probability distributions, which are insensitive to the phase of the wavefunction in those spaces and therefore do not convey where the state is moving towards, or whether the state is pure or mixed;

*the position- and momentum-space wavefunctions, which are only applicable to pure states and for which momentum and position encodings can be hard to unentangle;

*the phase-space based functions (i.e. the Wigner function as well as the Sudarshan $P$ and Husimi $Q$ representations), which graphically and explicitly depict the entire phase-space dependence of the state, and which take all of about ten minutes to understand.

If you really want to properly understand a state like a coherent-state cat superposition, there really is no way to get around a phase-space-based approach, because you are specifically selecting the states you superpose based on their phase-space characteristics.
This leaves you with the Wigner function, which isn't that hard. In particular, if you integrate over vertical (horizontal) strips, the resulting marginal distributions are exactly the position-(momentum-)space probability distributions. This is fairly easy and intuitive to display graphically:

Mathematica source via Import["http://halirutan.github.io/Mathematica-SE-Tools/decode.m"]["http://i.stack.imgur.com/32PpE.png"]
The variables on the plane are position (horizontal) and momentum (vertical). Each cat-state coherent-state component is a blob which rotates once around the origin over the oscillator period. In between any two such cat "eyes", you get a "smile": a fringe pattern along their separation. These fringes are precisely where the information about the superposition is encoded, and they are crucial to get the correct interference between the two components.
In particular:

*

*When the two blobs are spatially separate, you integrate across the fringes, and the result is essentially zero, so there is no probability between the blobs.

*When the two blobs overlap spatially, then they must interfere because they have different phase profiles. Here the Wigner function fringes are integrated over longitudinally, so the positive regions give you constructive interference and the negative regions account for the destructive interference.

It should be easy to see how this can account perfectly naturally for mixed states, i.e. states where the coherence of the superposition is less than perfect. The two blobs will remain - they represent the population at each $\alpha$ - but the contrast in the interference fringes will go down, which means that the amplitude of the "smile" will also decrease. Easy!


text:
Q: Connection between Different Kinds of Entropy (Boltzmann, Volume, and Surface Entropies) On Wikipedia for Microcanonical Ensemble it says,

$ \omega $ is said to be an energy width. I am not entirely sure what that means, but I believe it means that it is a variable stuck in to annihilate the units (like $ h $).
I am only familiar with the Boltzmann Entropy, but by further reading, it seems that only the volume entropy reproduces thermodynamics.

The volume entropy Sv and associated Tv form a close analogy to
  thermodynamic entropy and temperature. It is possible to show exactly
  that
$ dE=T_{\rm {v}}dS_{\rm {v}}-\langle P\rangle dV, $

Ignoring the warning that preferred solution to these problems is avoid use of the microcanonical ensemble, I am concerned at where these entropies come from. I have a reasonable intuition for the Boltzmann entropy as is is a special case of entropy from information theory, but these other entropies seem to not be based on information theory. Furthermore, I have trouble finding additional material on them.
Can you explain the origin of volume entropy and surface entropy? If possible explain their origin from information theory so I can understand them better.

A: You can find a very good discussion in K. Huang, Statistical Mechanics, chapter 6. I will use the notation of Wikipedia instead of that of Huang.
In the microcanonical ensemble, you are considering a system with energy between $E$ and $E+\omega$, with $\omega \ll E$.
The total phase space volume with energy between $E$ and $E+\omega$ is
$$W(E)=\int_{E<H(p,q)<E+\omega} d^{3N} p d^{3N} q$$
If you define the quantity
$$v(E)=\int_{H<E} d^{3N} p d^{3N} q$$
you can see that
$$W(E) = v(E+\omega)-v(E)$$
and in the limit in which $\omega/E \rightarrow 0$, we can write
$$W(E) = \frac{\partial v}{\partial E} \omega $$
Now, the Boltzmann entropy is defined as
$$S= k \log W(E)$$
It can be shown that the following definitions
$$
\begin{align}
S & = k \log W(E)\\
S & = k \log \left( \frac{\partial v}{\partial E} \right)\\
S & = k \log v(E)
\end{align}
$$
are equivalent up to a constant of order $\log N$ or smaller. Since $S$ is usually of order $N$, it means that we can consider the above expressions as practically equivalent.
Basically, $W$ is an "hypershell", $v$ an hypervolume and $\frac{\partial v}{\partial E}$ an hypersurface. We are basically saying that it doesn't matter if we consider the shell, the volume or the surface: the result will be the same. The reason is the large number of degrees of freedom of the system: $6N$, where usually $N \simeq 10^{23}$.
For an ideal gas,
$$v(E) = c_N V^N E^{3N/2}$$
where $c_N$ is a constant and $V$is the volume. Therefore, in this simple case you can verify yourself that the above expressions are equal up to a constant of order $\log N$ or less. In the more general case, this is a more complicated task.

A: This is how I picture the different entropies: The microcanonical ensemble states that the total energy E is constant. This condition selects only specific states from the phase space, forming a surface in phase space (this sketch from wikipedia is a nice illustration). Here, $\omega$ is the (infinitesimal) width of this surface. This is the basis of the Boltzmann and surface entropy, which differ only by a constant factor. The Gibbs or volume entropy on the other hand considers all states with an energy smaller than $E$, which forms a volume in phase space.
In the formulas, the difference is that the volume entropy uses $v(E)$, the phase space volume with all states of energy smaller than $E$. This is the cumulative function of the number of states at a given $E$. Thus, the surface entropy uses the derivative $\frac{dv}{dE}$, where $\omega$ is the infinitesimal width of the surface.
If the canonical ensemble is used or if the system is large enough, both definitions of entropy give the same results. However, in small systems they can differ significantly. For example, the volume entropy always has a positive temperature $T_s > 0$, whereas the surface entropy can lead to negative temperatures if the number of accessible states decrease with increasing energy.
Which form of entropy is appropriate in which situation is still heavily discussed in the scientific community. See for example [1] vs [2] and [3]
[1] J. Dunkel and S. Hilbert, Inconsistent thermostatistics and negative absolute temperatures, Nature Physics 10, 67-72 (2014)
[2] R. Swendsen and J.-S. Wang, Gibbs volume entropy is incorrect, Phys. Rev. E 92, 020103 (2015)
[3] J. Poulter, In defense of negative temperature, Phys. Rev. E 93, 032149 (2016)


text:
Q: Change color scheme of heatmap in Plotly I wanted to create a heatmap of a probability density matrix using plotly.
import numpy as np
from plotly.offline import download_plotlyjs, init_notebook_mode, plot
import plotly.graph_objs as go

probability_matrix = np.loadtxt("/path/to/file")
trace = go.Heatmap(z = probability_matrix)
data=[trace]
plot(data, filename='basic-heatmap')

This gives me an image like this:

But after printing the image on a piece of paper, it looks very dark (color printing) and becomes completely indiscernible after black and white printing. I was wondering if I could change the color range arbitrarily; so that the whole image looks a bit softer or lighter.
For example: 1 could be white and 0 could be very light blue or a softer color; so that the whole image looks more lighter after printing on a paper.
Note: not sure if this should be a separate question, since I have asked another question related to plotly here.

A: You will need to manually insert a colour scale
trace = go.Heatmap(z=probability_matrix, colorscale=[[0.0, '#F5FFFA'],
                         [0.2, '#ADD8E6'],
                         [0.4, '#87CEEB'],
                         [0.6, '#87CEFA'],
                         [0.8, '#40E0D0'],
                         [1.0, '#00CED1']])
data=[trace]


text:
Q: MSI Property Value get reset when uninstallation get interrupt or clicking cancel during uninstallation If I save the Authkey in MSI property for eg : "AUTHKEY" , when I click on cancel or uninstallation get interrupt, the property value is reset to default.
Do we have other way other than MSI property to store a value. Kindly advise.

A: Windows Installer properties, like AUTHKEY, have a valid scope only while the installer package is running. When an installation is finished/canceled and started again all values are reset to their defaults.
To have a value persistent, i.e. use on maintenance the value set when the package was installed, you need to save it, usually in a registry value, and read it from there using a registry search. The search should have the exact property name, so when it is executed is sets the property directly with the value found in the registry value.


text:
Q: Yum install / update not working inside docker images but working otherwise from the centos machine I am able to yum install, or yum update from the server, but when trying to do same (as specified in the Dockerfile) inside a docker container, it fails stating the following common error :
 One of the configured repositories failed (Unknown),
 and yum doesn't have enough cached data to continue. At this point the only
 safe thing yum can do is fail. There are a few ways to work "fix" this:
     1. Contact the upstream for the repository and get them to fix the problem.

     2. Reconfigure the baseurl/etc. for the repository, to point to a working
        upstream. This is most often useful if you are using a newer
        distribution release than is supported by the repository (and the
        packages for the previous distribution release still work).

     3. Run the command with the repository temporarily disabled
            yum --disablerepo=<repoid> ...

     4. Disable the repository permanently, so yum won't use it by default. Yum
        will then just ignore the repository until you permanently enable it
        again or use --enablerepo for temporary usage:

            yum-config-manager --disable <repoid>
        or
            subscription-manager repos --disable=<repoid>

     5. Configure the failing repository to be skipped, if it is unavailable.
        Note that yum will try to contact the repo. when it runs most commands,
        so will have to try and fail each time (and thus. yum will be be much
        slower). If it is a very temporary problem though, this is often a nice
        compromise:

            yum-config-manager --save --setopt=<repoid>.skip_if_unavailable=true

Cannot find a valid baseurl for repo: base/7/x86_64

my Docker file is a simple :
FROM centos:centos7
RUN echo "nameserver 8.8.8.8" > /etc/resolv.conf
RUN echo "nameserver 8.8.4.4" >> /etc/resolv.conf
RUN yum -y update; yum clean all
RUN yum -y install epel-release; yum clean all
RUN yum -y install python-pip; yum clean all

I have tried various things like adding ip_resolve=4 in /etc/yum.conf, or addinf 8.8.8.8 and 4.4.4.4 to /etc/resolv.conf and other methods, in vain.
here's the docker info :
Containers: 28
 Running: 0
 Paused: 0
 Stopped: 28
Images: 144
Server Version: 1.13.0

docker-compose version 1.10.1, build b252738
docker-py version: 2.0.2
CPython version: 2.7.5
OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013

Please help. I am only running things under a VPN, no proxy.
machine is an AMI : 3.10.0-514.el7.x86_64.
Need I add it's IP anywhere insde docker container? Please help.
TIA!


text:
Q: error in getting the fetching path I actually trying to check my connection in connection file tester to check if it is connected to the database but the problem is I got this error
Warning: include(obj\database_connection\SqlHandler.php): failed to open stream: No such file or directory in /home/devhostt/public_html/bcc/gradingsystemmodule/root/root.php on line 16

Warning: include(): Failed opening 'obj\database_connection\SqlHandler.php' for inclusion (include_path='/home/devhostt/public_html/bcc/gradingsystemmodule:.:/opt/alt/php55/usr/share/pear:/opt/alt/php55/usr/share/php') in /home/devhostt/public_html/bcc/gradingsystemmodule/root/root.php on line 16

Fatal error: Class 'obj\database_connection\SqlHandler' not found in /home/devhostt/public_html/bcc/gradingsystemmodule/function/checkconnection.php on line 8

and here is my code to set & get the path (root.php)
<?php
error_reporting( E_ALL );

define("setRealpath", realpath("../"));

const ERROR_EXCEPTION_MESSAGE = "SOMETHING WENT WRONG HERE: ";

try
{
$getPath = array(setRealpath, get_include_path());

if(!set_include_path(implode($getPath, PATH_SEPARATOR)))
{
define("setRealpath", realpath("./"));
$getPath = array(setRealpath, get_include_path());
set_include_path(implode($getPath, PATH_SEPARATOR));
}

function GetClassFile($class)
{
$file = str_replace('/', '\\', $class).".php";
include $file;
}

spl_autoload_register('GetClassFile');

}
catch(Exception $x)
{
die(ERROR_EXCEPTION_MESSAGE.$x->getMessage());
}

?>

here is the file where my connection (SqlHandler.php).
<?php
namespace obj\connection_database;
use \PDO;
class SqlHandler extends Connection
{
const ERROR_EXCEPTION_MESSAGE = "SOMETHING WENT WRONG HERE:";

protected $db = null;

public function __construct()
{
$this->db = $this->getConnection();
}

public function checkConnection()
{
if($this->db)
{
return "CONNECTED";
}
return "NO CONNECTION";
}
}
?>

and lastly here in this file where i'm trying to check the connection(checkconnection.php)
<?php
error_reporting(E_ALL);

include "./root/root.php";

use \obj\database_connection\SqlHandler;

$checkConnection = new SqlHandler;

echo $checkConnection->checkConnection();
?>

A: now i found my mistake, the only mistake is that i'm using the old version of php, instead of using php 7.1 version , i'm using php 5. so i change it and it works.


text:
Q: Assert that string has a required ending In C# I would like to check whether a string ends with *.js.The string is the name of a file and I want to know if the file is JavaScript or not.
So far, I only found this way of doing it:
Assert.IsTrue(Regex.Matches(myFilename, "*.js").Count != 0);

To me, this seems a bit backhanded because I need to count the number of occurrences rather than just checking if there is one.
Also, the code fails with this error:
Message: System.ArgumentException : parsing "*.js" - Quantifier {x,y} following nothing.

Any idea what could be wrong with the code?
What is the simplest way to assert that a string is in accordance with a given regex?

A: Just use EndsWith
Assert.IsTrue(myFilename!=null && myFilename.EndsWith(".js"));

A: The problems with your regex are :

*

** is special quantifier, it cannot follow nothing (source of your error). You mean "I want anything before". In regex, this is .*, but in your case you don't even need it ! Regex are not forced to match all the string, just the expression part .

*. is a special character too. It means "any character". You want only an actual dot . character, so you have to escape it as well. : \.

*Finally, there is no precision to match the end of string.  $
Correct regex would be either "\.js$" (or ".*\.js$") instead of "*.js" .

And anyway, to check if a string ends with a specific substring, you can simply use string.EndsWith(".js"), as answered by @Toshi. Probably a much better choice in any aspect.

A: You can use the substring function to extract the last three characters of the string and compare whether it is equal to ".js" or not.
Assert.IsTrue(myFile.Substring(myFile.Length-3), ".js" )

Apart from it, as already mentioned EndsWith is also an optimal solution.


text:
Q: Disable Chrome Autocomplete/Dropdown Suggestions on WooCommerce Checkout I'm trying to disable Chromes Autofill/Dropdown suggestions for my customers when checking out. I have an address validation tool, but customers are still using Chromes drop down suggestions, and at times, street names and other detail is left out, so I'm having to contact customers manually for the information.
I've tried the following code for removing autocomplete for billing address, since text is the input type without success.
add_filter( 'woocommerce_form_field', 'change_autofill', 1, 1 );

function change_autofill( $field) {

    $agent = $_SERVER['HTTP_USER_AGENT'];

    if (strpos($agent, 'Firefox') !== false) {
        $field = str_replace('autocomplete="text"', 'autocomplete="off"', $field);
        return $field;
    }
    else {
        $field = str_replace('autocomplete="text"', 'autocomplete="none"', $field);
        return $field;
    }

}

A: Solution below using the attributes provided here
https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete
/* Disable autofill address */

add_filter( 'woocommerce_form_field', 'change_autofill', 1, 1 );

function change_autofill( $field) {

    $agent = $_SERVER['HTTP_USER_AGENT'];

    if (strpos($agent, 'Firefox') !== false) {
        $field = str_replace('autocomplete="address-line1"', 'autocomplete="off"', $field);
        return $field;
    }
    else {
        $field = str_replace('autocomplete="address-line1"', 'autocomplete="none"', $field);
        return $field;
    }

}


text:
Q: Adding system or utility live logs for pytest I'm building a pytest fixture that starts some long process before any tests are executed.
I would like to have utility logs reporting about that process while it's taking place after being initiated by pytest.
The fixture looks something like this:
import logging

logger = logging.getLogger(__name__)

@fixture
def some_long_process():

    logger.info("Process started")

    logger.info("Process ongoing..")

    yield

    logger.info("Process ended")

The problem is that pytest automatically captures all outputs during test runs and although you can enable live logging I wish I could enable live logging specifically for my logger.
Is there a way to do that? Or alternatively, a way to add system logs to pytest?

A: Basically you just need to enable live logs.
It can be done directly at the command line by passing the log_cli_level .
pytest --log-cli-level=INFO test_log_feature.py

# ----- live log setup -------------------------------------------
# INFO     test_log_feature:test_log_feature.py:9 Process started
# INFO     test_log_feature:test_log_feature.py:10 Process ongoing..
# PASSED                                                                                [100%]
# ----- live log teardown ----------------------------------------
# INFO     test_log_feature:test_log_feature.py:12 Process ended

You can do the same in a pytest.ini configuration file.
[pytest]
log_cli=true
log_cli_level=INFO

Update

I want live logging solely for my logger, is that possible?

I think in this case you have to play with loggers and define various loggers according to your needs and enable log_cli_level at the lower level you want to see. Here is an example to illustrate this solution.
import logging
import pytest

fixture_logger = logging.getLogger("fixture")
logger = logging.getLogger(__name__)
# can also be set by configuration
logger.setLevel(logging.WARNING)

@pytest.fixture()
def some_long_process(caplog):
    fixture_logger.info("Process started")
    fixture_logger.info("Process ongoing..")
    yield
    fixture_logger.info("Process ended")

def test_long_process(some_long_process, caplog, request):
    logger.info("Log I don't want to see")
    pass

Gives.
pytest --log-cli-level=INFO test_log_feature.py

# --- live log setup ---
# INFO     fixture:test_log_feature.py:10 Process started
# INFO     fixture:test_log_feature.py:11 Process ongoing..
# PASSED                                                                                [100%]
# ---- live log teardown ---
# INFO     fixture:test_log_feature.py:13 Process ended


text:
Q: Canvas centre 0,0 is top left how to make it centre of the screen? I have an customview which draws a canvas, im trying to draw a circle at the centre 0,0 but that goes to the top left corner, I want it to be the centre of the screen, how do you go about moving the coordinates?

A: You have to get the width and height of the canvas and then divide them by 2.
Code Example:
int CenterOfx = (int)canvas.getWidth()/2;
int CenterOfy = (int)canvas.getHeight()/2;

canvas.drawCircle(CenterOfx,CenterOfy,25f,paintLines);

you can also use the size of the screen to get the center values.


text:
Q: Bitmap not loading in picturebox I am unable to load the bitmap image in the PictureBox. It gives me an error saying the parameter is not valid.
        Image up = Image.FromFile("somePath");
        Image down = Image.FromFile("anotherPath");

        using (down)
        {
            using(var bmp = new Bitmap(1000, 1000))
            {
                using(var canvas = Graphics.FromImage(bmp))
                {
                    canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    canvas.DrawImage(up, 0, 0);
                    canvas.DrawImage(down, 0, 500);
                    canvas.Save();
                    pictureBox1.Image = bmp;// this line gives the error
                }
            }
        }

The size of my pictureBox is also 1000X1000. Can anyone tell me where am I going wrong?
EDIT 1:
Error Description:

System.ArgumentException: Parameter is not valid.    at
  System.Drawing.Image.get_Width()    at System.Drawing.Image.get_Size()
  at
  System.Windows.Forms.PictureBox.ImageRectangleFromSizeMode(PictureBoxSizeMode
  mode)    at System.Windows.Forms.PictureBox.OnPaint(PaintEventArgs pe)
  at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs
  e, Int16 layer)    at System.Windows.Forms.Control.WmPaint(Message& m)
  at System.Windows.Forms.Control.WndProc(Message& m)    at
  System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
  at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&
  m)    at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32
  msg, IntPtr wparam, IntPtr lparam)

A: Remove using statements on bmp. Because, your bitmap is disposed after pictureBox1.Image = bmp; and you get an error on paint event.
Image up = Image.FromFile("somePath");
Image down = Image.FromFile("anotherPath");

using (down)
{
    var bmp = new Bitmap(1000, 1000);
    using(var canvas = Graphics.FromImage(bmp))
    {
        canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
        canvas.DrawImage(up, 0, 0);
        canvas.DrawImage(down, 0, 500);
        canvas.Save();
        pictureBox1.Image = bmp;// this line gives the error
    }
 }


text:
Q: Добавить текущую дату в имя файла Доброго времени суток! Я собираюсь настроить создание бэкапов через скрипт на SQL 2008 R2, скрипт есть, но у меня возник вопрос. Вот скрипт
BACKUP DATABASE [mybase1] TO DISK = N'c:\sqlbackup\mybase1.bak' WITH INIT, NOUNLOAD, NAME = N'MyBase1 Backup', NOSKIP, STATS = 10, NOFORMAT;

'c:\sqlbackup\mybase1.bak' - это имя файла бэкапа, как мне сделать так что бы перед расширением вставала текущая дата (без двоеточия)!? Например c:\sqlbackup\mybase270112.bak И если можно, то пример кода!
A: лучше будет изменить порядок yy mm dd
N'c:sqlbackupmybase'+REPLACE(CONVERT(VARCHAR, getdate(), 2), '.', '')+'.bak'

DECLARE @path VARCHAR(260)
SET @path = N'd:003sqlbackupmybase'+REPLACE(CONVERT(VARCHAR, getdate(), 2), '.', '') +'.bak'
BACKUP DATABASE [Ut_demo] TO DISK = @path  WITH INIT, NOUNLOAD, NAME = N'UT_demo Backup', NOSKIP, STATS = 10, NOFORMAT;

A: А если динамически выполнить?
A: Попробуйте использовать Maintenance Plan вместо самописного кода. Задача не такого уровня, чтобы через разработку ее решать.


text:
Q: Is $\liminf_{n \to \infty} \arctan(x_n) = \arctan( \liminf_{n \to \infty} x_n)$? Let $\{x_n\}_{n=1}^\infty$ be any sequence of real numbers. In a proof I'm reading, it is used that
$$\liminf_{n \to \infty} \arctan(x_n) = \arctan( \liminf_{n \to \infty} x_n)$$
where $\arctan: [-\infty, + \infty] \to [-\pi/2, \pi/2]$ is the inverse  of $\tan$ extended with $\arctan(\pm\infty) := \pm \pi/2$;
It seems odd to me that you can interchange the $\arctan$ and $\liminf$. I can find counterexamples for continuous functions that this does not hold in general. Is there any reason why this relation does hold for $\arctan$? Or is my book wrong?

A: It is true for any increasing continuous function (on the extended real line with finite limits at $\pm \infty)$.  $\arctan $ has these properties.


text:
Q: MVVMCross+Android: DataBinding Context Menu options on ViewModel properties? How can I Databind my menu options properties(eg the Enabled Property) to a ViewModel property?
My menu is created within my MvxActivity-inherited class as follows:
public override void OnCreateContextMenu( IContextMenu menu, View v, IContextMenuContextMenuInfo info )
{
        switch (v.Id)
        {
            case Resource.Id.textView1:
                menu.Add( 0, 0, 0, "Menu Option1" );
                menu.Add( 0, 1, 0, "Menu Option2" );

                break;
            case Resource.Id.textView2:
                menu.Add( 0, 2, 0, "Menu Option3" );
                menu.Add( 0, 3, 0, "Menu Option4" );

                break;
        ...
        }
        ...
}

I know that I can enable/disable individual Menu Items as follows:
IMenuItem menuOption = menu.FindItem( 1 ); // Refers to "Menu Option2" above

if (menuOption != null)
{
    menuOption.SetEnabled(false);
}

But how can I achieve this using MVVMCross binding? I suppose I could do this in C#(dynamically) but I'm not sure how to do this. Can anybody show me please?
Thanks In Advance.

A: Since Menu's are created "on demand" then I generally handle this by just implementing SetEnabled type things using ViewModel current properties.
e.g.
  var myViewModel = (MyViewModel)ViewModel;
  var menuOption = menu.FindItem( 1 ); // Refers to "Menu Option2" above
  menuOption.SetEnabled(myViewModel.CanDoSomething);

Cleverer - more "binding" options are available - e.g. we could create a menu-wrapping object to hook things up automatically - but in the few cases where I use menus, then I find this ViewModel approach works OK


text:
Q: Character that projects to a given subgroup The character of the regular representation $\chi_R$ satisfies
$$\chi_R(g)=\begin{cases} |G| & g=id \\ 0 & \textrm{otherwise}\end{cases},$$
(https://en.wikipedia.org/wiki/Regular_representation). In a way, one could say that the character of the regular representation projects the group to the identity subgroup. In this line, is there a generalization where one projects to a generic subgroup? More precisely, exists some representation $\rho_K$ such that
$$\chi_K(g)=\begin{cases} 1 & g\in K \\ 0 & \textrm{otherwise}\end{cases}$$
for a given subgroup $K\subset G$?

A: This is not a character if $K$ is a proper subgroup of $G$. For suppose $\chi$ were a character: take the Frobenius inproduct with the principal character $1_{G}$, then the multiplicity is $\frac{|K|}{|G|}$. This must be a non-negative integer, and this only occurs when $K=G$.
Yet another approach, if it would be a character then it is linear and cannot have values equal to $0$, being a homomorphism to $\mathbb{C}^*$.
The right generalization of the regular character would be the induced character $1_{K}^G$. This is the permutation character of $G$ acting on the right cosets of $K$ by multiplication from the right. The regular character of $G$ is $1_{1}^G$, so the supertrivial character induced to the whole group.


text:
Q: Image src not appearing in view Building a simple ionic app which connects to an API i've also built. I'm passing some data through to a view and all data is appearing apart fromm the src attribute of an image. If I console.log the data in my controller then the src is there but it doesn't appear in the view - it comes through as a 0 like:

I'm passing it through in my controller like:
.controller('VenuesController', ['$state','$scope','$http','Venue', function($state,$scope,$http,Venue){
    $scope.venues = Venue.query();
    $scope.showVenue = function(id){
        $state.go('venues/:id',{id:id});
    };
}])

and in the view template itself:
<ion-view view-title="Venues">

{{ venue.name }}

{{ venue.description }}

</ion-view>

The image path is a full external link like http://lorempixel.com/100/100/?51467 , not sure if i'm missing something here?

A: venu.image-small variable has - that fails the variable declaration syntax like variable should not have -, variable shouldn't start various number, etc.
As your property image-small contains an hyphen (-) in it, you should use array annotation there to get the value like  venue['image-small']
Markup

Update
Seems like your img source url is different than the you current domain, you need to set the different domain URL trusted first using $sce service trustAsResourceUrl function.
Markup

Code
$scope.trustSrc = function(src) {
   return $sce.trustAsResourceUrl(src);
}

Additionally your ng-click shouldn't use {{}} interpolation directive
ng-click="showVenue(venue.id)"

and then your function should change the implementation of it
$scope.showVenue = function(id){
    //removed `venues/:id` and should be replace by its stateName
    $state.go('stateName',{id:id});
};

Above redirection thing could improved to use ui-sref directive like
Final Markup

{{ venue.name }}

{{ venue.description }}


text:
Q: Harmonic analysis on the Heisenberg group It is well known that:
Theorem 1. For $f\in L^{2}(\mathbb H_{n}=\text{The Heisenberg group of dimesion } 2n+1)$ we have the expansion
$$f(z, s)= (2\pi)^{-n} \sum_{k=0}^{\infty} \int_{0}^{\infty}  f \ast e_{k}^{\lambda} (z, s)  |\lambda |^{n} d\lambda  $$
where $\lambda \in \mathbb R^{\ast}$, $e_{k}^{\lambda}(z, s):= e^{i\lambda s}\phi_{k}(\sqrt{\mid \lambda \mid}z )$;
where $\phi_{k}(z)= (2\pi)^{\frac {n}{2}} \sum_{|\alpha | = k} \Phi_{\alpha, \alpha}(z)$, and for each $\alpha, \beta \in \mathbb N^{n}$ and $z\in \mathbb C^{n}$, we define the special Hermite functions $\Phi_{\alpha, \beta }$ by
$$\Phi_{\alpha, \beta}(z):= (2\pi)^{-\frac{n}{2}} \int_{\mathbb R^{n}} e^{i x\cdot \xi}  \Phi_{\alpha}(\xi + \frac{y}{2}) \Phi_{\beta}(\xi- \frac{y}{2}) d\xi .$$
Theorem 2. For $f\in L^{2}(\mathbb H_{n})$ we have
$$\parallel f \parallel_{2}^{2} = (2\pi)^{-n-1} \sum_{k=0}^{\infty} \int_{-\infty}^{\infty} \int_{\mathbb C^{n}} \mid f \ast e_{k}^{\lambda} (z, 0)\mid^{2}   \lambda ^{2n} dz  d\lambda . $$
My question is: Put $\eta= r+it, r>0$, and $$ T_{\eta}f(z,s):= (2\pi)^{-n} \sum_{k=0}^{\infty} \int_{0}^{\infty} e^{-\eta(2k+n)|\lambda |}  f \ast e_{k}^{\lambda} (z, s)  |\lambda |^{n} d\lambda. $$  Can we say this operator is bounded on $L^{2}(\mathbb H_{n})$, furthermore, on $L^{p}(\mathbb H_{n}), 1\leq p \leq \infty $ ?


text:
Q: How to require running serviced service in RPM We have an RPM package that requires a running Docker service to perform its installation. (Part of the RPM package is going to install new Docker images on the system).
Is there a standard way (like package dependencies) in the RPM spec to require that a specific systemd service is running?

A: In your %pre section, you can call systemctl - there are some examples on https://rpm-packaging-guide.github.io


text:
Q: Hiding table columns with jQuery based on column header I've looked at a couple of similar questions here but I still can's seem to get it to work.  I'm trying to hide specific columns in a table that is being automatically generated on the page. I've managed to hide column header and the corresponding cells in the first row but I'm not sure how to make it work for the rest of the rows. What am I missing?
$(document).ready(function() {
    $("table.lc_Table:eq(0) tr:eq(0) th").each(function(ind,ele) {
        if( $.trim($(this).text()).match(/(Available|Order Limit)/gi) )
        {
          $("table.lc_Table:eq(0) tr th:eq("+ind+"), table.lc_Table:eq(0) tr td:eq("+ind+")").hide();
        }
    });
});

Ticket Class

Available

Order Limit

Price

Attendee1

50

No Limit

$0.00

Attendee2

50

No Limit

$0.00

A: Should work
$('tr').each(function(){
    $(this).find('td').eq(0).hide();
})

For both TH & TD can use
$('tr').each(function(){
    $('tr').children().eq(0).hide();
})

A: :eq is evaluating to only one element. Instead use :nth-child which counts relative to an elements parent.


text:
Q: Is thin kind of implementation safe(reimplement max with auto and type_traits) #include <iostream>
#include <type_traits>

#include <boost/type_traits.hpp>

template<typename T, typename U>
struct promote
{
  private:
    typedef typename std::conditional<(sizeof(T) > sizeof(U)), T, U>::type Bigger;
    typedef typename std::add_const<Bigger>::type BConst;

  public:
    //because mingw4.6.2 do not implement std::add_reference
    typedef typename boost::add_reference<BConst>::type type;
};

template<typename T, typename U>
auto max(T const &a, U const &b)->typename promote<T, U>::type
{
  return a > b ? a : b;
}

int main(int argc, char *argv[])
{
  std::cout<<max(3, 4.5)<<std::endl;
  std::cout<<max(4.5, 3)<<std::endl;

  return 0;
}

std::max of mingw4.6.2
template<typename T>
inline T const& max(T const &a, T const &b)
{
  return a > b ? a : b;
}

This will give me warning messages
main.cpp:27:24: warning: returning reference to temporary [enabled by default]
main.cpp:27:24: warning: returning reference to temporary [enabled by default]
Compiler is migw4.6.2, OS is win7 64bits
second version, only support scalar type
template<typename T, typename U>
struct promote
{
   typedef typename std::conditional<(sizeof(T) > sizeof(U)), T, U>::type type;

};

template<typename T, typename U>
inline typename promote<T, U>::type max(T a, U b)
{
  static_assert(std::is_scalar<T>::value, "inhomogeneous max only support scalar type");
  static_assert(std::is_scalar<U>::value, "inhomogeneous max only support scalar type");

  return a > b ? a : b;
}

The other solution are using SFINAE and boost::mpl to do some "overload".
I think I would just explicitly name the type of std::max in the real case

A: No, it's not safe. That's exactly what the compiler warns you about. You return reference to a temporary value (4.5 in this case). If you assign the result to something like int &x = max(3, 4,5);, x will become a dangling reference immediately after this line.

A: The problem with max() in general is that you want it to do one of two things:

*

*Select the maximum of homogenous values and return a reference to this value.

*Select the maximum of inhomogenous values and return the result value converted to the most general type.

Returning a reference in the inhomogenous case does not work because a reference to a temporary is returned which will cease to exist before the call of the function can take hold of it. Returning a value in the homogenous case is probably not desirable.


text:
Q: Create a list from enum I'd like to be able to create a List from an enum that conforms to CaseIterable and CustomStringConvertible e.g.
public enum HairColor: Int, Codable, CaseIterable, CustomStringConvertible {
    public var description: String {
        switch self {
        case .black:
            return "Black"
        case .blond:
            return "Blond"
        case .brown:
            return "Brown"
        case .red:
            return "Red"
        case .grey:
            return "Gray"
        case .bald:
            return "Bald"
        }
    }
    case blond, brown, black, red, grey, bald
}
struct ContentView: View {
    var body: some View {
        SwiftUIHelpers.enumToList(HairColor)
    }
}

This is the approach I've tried but I get the error: "Cannot convert value of type 'Text' to closure result type '_"

struct SwiftUIHelpers {
    static func enumToList<T: CaseIterable, RandomAccessCollection>(_ a: T) -> some View {
        List {
            ForEach(a, id: \.rawValue) { (o: CustomStringConvertible) in
                Text(o.description)
            }
        }
    }
}

What is the error on my ways?!?

A: Here is working solution. Tested with Xcode 11.4 / iOS 13.4.
struct SwiftUIHelpers {
    static func enumToList<T: CaseIterable>(_ t: T.Type) -> some View
           where T.AllCases: RandomAccessCollection, T: Hashable & CustomStringConvertible {
        List {
            ForEach(t.self.allCases, id: \.self) { o in
                Text(o.description)
            }
        }
    }
}

struct ContentView: View {
    var body: some View {
        SwiftUIHelpers.enumToList(HairColor.self)
    }
}

public enum HairColor: Int, Codable, Hashable, CaseIterable, CustomStringConvertible {
    public var description: String {
        switch self {
        case .black:
            return "Black"
        case .blond:
            return "Blond"
        case .brown:
            return "Brown"
        case .red:
            return "Red"
        case .grey:
            return "Gray"
        case .bald:
            return "Bald"
        }
    }
    case blond, brown, black, red, grey, bald
}

Update: Having played with this more I've found that the following extension can be much more helpful
extension CaseIterable where Self.AllCases: RandomAccessCollection, Self: Hashable & CustomStringConvertible {
    static func toForEach() -> some View  {
        ForEach(Self.allCases, id: \.self) { o in
            Text(o.description).tag(o)
        }
    }
}

because gives wider reuse possibility, like
List { HairColor.toForEach() }

and this
Form { HairColor.toForEach() }

and

struct DemoHairColorPicker: View {
    @State private var hairColor: HairColor = .red
    var body: some View {
        VStack {
            Text("Selected: \(hairColor.description)")
            Picker(selection: $hairColor, label: Text("Hair")) { HairColor.toForEach() }
        }
    }
}

and of course in any stack VStack { HairColor.toForEach() }

A: Not really an answer to all parts of your question - only the first part - but offered here as an alternative...
Might be worth considering the use of @EnvironmentObject for a @Published property? I used this to populate a sidebar style menu for a macOS target.
Step 1:
Use your enum. My enum is written a little differently to yours but I thought to leave it that way because it provides an alternate construction... but with the same outcome.
(Conforming to CaseIterable here allows us to use the .allCases method in Step 2.)
enum HairColor: Int, CaseIterable {

    case blond = 0, brown, black, red, grey, none

    var description: String {

        switch self {

        case .blond: return "Blond"
        case .brown: return "Brown"
        case .black: return "Black"
        case .red:   return "Red"
        case .grey:  return "Grey"
        case .none:  return "Bald"
        }
    }
}

Step 2:
Create a struct for your model and include a static property that maps all cases of your HairColor enum.
(Conforming to Identifiable here allows us to use the cleaner ForEach syntax in Step 4 - that is - use ForEach(appData.hairColors) in lieu of ForEach(appData.hairColors, id: \.id)).
import SwiftUI

struct Hair: Codable, Hashable, Identifiable {

    var id: Int
    var name: String

    init(id: Int, name: String) {
        self.id = id
        self.name = name
    }

    static var colors: [Hair] {
        return HairColor.allCases.map({ Hair(id: $0.rawValue, name: $0.description ) })
    }
}

Step 3:
Create a class that conforms to ObservableObject and that contains a @Published wrapped property to allow you to broadcast your HairColor via @EnvironmentObject.
import Combine // <- don't forget this framework import!
import SwiftUI

final class AppData: ObservableObject {

    @Published var hairColors = Hair.colors
}

Step 4:
Use in a View.
struct HairList: View {

    @EnvironmentObject var appData: AppData

    @State var selectedHair: Hair?

    var body: some View {

        VStack(alignment: .leading) {

            Text("Select...")
                .font(.headline)

            List(selection: $selectedHair) {

                ForEach(appData.hairColors) { hairColor in

                    Text(hairColor.name).tag(hairColor)
                }
            }
            .listStyle(SidebarListStyle())
        }
        .frame(minWidth: 100, maxWidth: 150)
        .padding()
    }
}

Step 5:
Remember to inject the environment object into the preview to make the preview usable.
struct HairList_Previews: PreviewProvider {

    static var previews: some View {

        HairList(selectedHair: .constant(AppData().hairColors[1]))
            .environmentObject(AppData())
    }
}