text:
Q: List all files changed in a pull request in Git/GitHub Is there a way (from the command line) to list the names of all files changed in a PR in Git/GitHub? This would be used to find what tests need to be run in a Travis CI build for that PR.
The CI build runs these commands before it calls our script:
git clone --depth=50 git://github.com/jekyll/jekyll.git jekyll/jekyll
cd jekyll/jekyll
git fetch origin +refs/pull/2615/merge
git checkout -qf FETCH_HEAD

A: For GitHub specifically, this can be accomplished using the REST API:
GET /repos/:owner/:repo/pulls/:pull_number/files

You can use one of the GitHub libraries for this purpose.

A: In general, you can list the files changed between any two commits with git diff --name-only  :
How to list only the file names that changed between two commits?
The problem here seems to be determining the 'merge base'. If all branches originate with master, then you could do:
git --no-pager diff --name-only FETCH_HEAD $(git merge-base FETCH_HEAD master)
This will show you the changes between the point at which the FETCH_HEAD was branched from master to the current FETCH_HEAD. I tested this locally, and the PR branches are cut from master I believe it should work.

A: Chrome console...
Note: This will break if Github changes the tags/classes/IDs in the page.
const fileElems = document.querySelectorAll('#files div.js-diff-progressive-container div.file div.file-header div.file-info a.Link--primary');
const filePaths = [];

for (let a of fileElems) {
    filePaths.push(a.title);
}

const filePathsStr = filePaths.join('\n');
console.log(filePathsStr);
copy(filePathsStr);
console.log('Copied to the clipboard as well ');

A: Using GitHub cli (gh) you can run:
gh pr view 2615 --json files --jq '.files.[].path'

I have made a gh alias because I use it regularly:
gh alias set pr_files "pr view $1 --json files --jq '.files.[].path'"

and then I call it with gh pr_files 2615 or gh pr_files 2615 | cat
gh pr_files 2615 | cat

A: Google search sent me here though it is slightly different question.
This question [details] has command-line.
However, I needed the list of files, its ok if I can see in GUI
Here a way to see list of files in GUI:

*

*open the pull request

*click on the [Files changed] tab

Conversation 0   Commits 3   [Files changed] 8

*click on drop down after 'n files' in the below line of [Files changed]

Changes from all commits v ... [8 files v] ... +638 −266

(click on the v, drop down, after files in the above line)

A: I couldn't find a way to see just the list of changed files in GitHub (i.e. without the diff and comments), but it can be done with this one-liner in the browser console:
Array.from(document.getElementsByClassName('js-details-target')).forEach((e) => {e.click();})

This will collapse all the diff blocks leaving only the filenames.

A: Here is the simple method:

*

*Generate below url for POST request
https://dev.azure.com/**{OranizationName}**/_apis/Contribution/HierarchyQuery/project/**{ProjectID}**?api-version=5.0-preview.1

*Refer this link for any value you need
https://learn.microsoft.com/en-us/rest/api/azure/devops/?view=azure-devops-rest-5.1

*Use below Json as a request param
{"contributionIds":["ms.vss-code-web.pr-detail-data-provider"],"dataProviderContext":{"properties":{"pullRequestId":{PullRequestID},"repositoryId":"{repositoryId}","sourcePage":{"url":"https://dev.azure.com/{OrganizationName}/{ProjectName}/_git/{RepositoryName}/pullrequest/{PullRequestID}?_a=files"}}}}

*Send POST request

*Get Count from highlighted property to get the file count for each PR

6. Create access token in Azure DevOps and use it for authentication
7. Provide Code and Token Administration access to token

A: According to @AdamHickey's 2019 answer, update the tag's class to 'Link--primary' as below
// the changes were only done on the **line** below
const fileElems = document.querySelectorAll('#files div.file-info a.Link--primary');
const filePaths = [];

for (let a of fileElems) {
    filePaths.push(a.title);
}

const filePathsStr = filePaths.join('\n');
console.log(filePathsStr);
copy(filePathsStr);
console.log('Copied to the clipboard as well ');

A: The alternative to zoispag's answer (using the new GitHub CLI 2.14.5) and gh pr diff:
gh pr diff --name-only

From PR 6074 and issue 6060.

A: Inspired by @AdamHickey, that answer was not working anymore. So, I created a working script.
let changes = document.getElementsByClassName("file-info");
let files = []
for(let i =0;i<changes.length;i++)
{
    files.push(changes[i].getElementsByClassName("link-gray-dark")[0].title);

}
navigator.clipboard.writeText(JSON.stringify(files));

Disclaimer: This may stop working if someday the structure of html change.

A: There are some ways to find changed files but you have to experiment on what you compare.
Two examples that I mainly use in GitHub Actions are:
git --no-pager diff --name-only --diff-filter=ACMRT ${{github.event.pull_request.base.sha}} ${{ github.event.pull_request.head.sha }}

and:
git --no-pager diff --name-only --diff-filter=ACMRT ${{github.event.pull_request.base.sha}} ${{github.sha}}

This results in a list such as:
.github/workflows/potato.yml
.tomato.yml
app/assets/javascripts/cucumber.js

Experiment with the SHA signatures according to your needs.


text:
Q: External DLL in VB6 with namespaces I'm currently having some trouble with a VB6 application that needs to encode some text using the same encoding method available at .NET framework 4.5.
I've searched through the internet and found some functions that tries to do the encoding based in UTF-8, but it still doesn't match the 4.5 output.
Then I looked for a way to import the 4.5 framework DLL within the VB6 project. This is what I accomplished so far:
Private Declare Function dotNetUrlEncode Lib "System.Web.dll" Alias "UrlEncode" (str As String) As String

The problem is that the method "UrlEncode" it's inside the namespace "HttpUtility", "System.Web.HttpUtility.UrlEncode" and using the code above I cant access the method. I've tried changing it to look like the code below, but the problem persists, I cant reach the method UrlEncode:
Private Declare Function dotNetUrlEncode Lib "System.Web.dll" Alias "HttpUtility.UrlEncode" (str As String) As String
Private Declare Function dotNetUrlEncode Lib "System.Web.HttpUtility.dll" Alias "UrlEncode" (str As String) As String

Is there a way to reach the method UrlEncode inside "System.Web.dll"? Where am I going wrong?
Thanks for the help!
Best regards.

A: This will not work. The .NET DLLs contained managed code, which requires the .NET runtime. Your VB6 app can't call that code. Its process does not have the .NET runtime loaded.
You can only import functions from native DLLs this way. That's why it works for system DLLs included with the operating system.
The best solution would really be to consult the documentation and determine precisely how the UrlEncode function works. The internals of the implementation will not be documented, of course, but that doesn't matter. All you're interested in is the specification. Follow that same specification when implementing your own function if you cannot find a system function that has equivalent behavior.
If you absolutely needed to call .NET functions from a VB 6 application, it can be done. You will need to create a .NET wrapper that calls the framework-provided function and exposes in a COM-compatible manner using the ComVisibleAttribute. More information here, here, and here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Average Train Speed I'm repeating this question since they don't seem to like it over there:
https://stackoverflow.com/questions/21972403/average-train-speed
This is the question I have:
If a train is traveling at 50 mph for 30 miles and makes 3 stops 15 min apart what is the average mph for the trip? 35 mph 42 mph 26 mph
My question here is, anyone can explain to me this question? I tried all combination of thoughts and never got an answer close to the available options.
If the train is traveling at 50mph for 30 miles then it will take 36 minutes to arrive at its destination, but what it's meant here by 3 stops "15 min" apart?
Is it 15 minutes taken as a rest at each stop (total trip time will be 81 minutes)? Is it 15 minutes travel time till the train stops? then on average 10 miles per 15 minutes and hence the average speed would be 40mph...
The final destination is considered as a stop?
The question for me is too vague, can someone explain it better for me?

A: The problem is not well stated. You don't care the time between stops, just the total time stopped. Add that to the $36$ minutes spent traveling to get the total time.


text:
Q: Converting a function that output a Monad type to a function that output the raw value type I have 2 type definitions
type Mapper a k v = a -> [(k,v)]
type MapperM m a k v = a -> m [(k,v)]

I want to write a function that convert a value from type
(Ord k, Monad m) => MapperM m a k v

to  type
Ord k => Mapper a k v

basically a function that takes a -> m [(k,v)] as an argument and return a -> [(k,v)] as output.
All my attempts are failing with the Haskell type checks.

A: I believe it is mathematically impossible.
Consider the case when m is Maybe: the function could return [(k,v)] from Just [(k,v)], but what would it return from Nothing?
If the monad is IO, extracting the argument from the monad would break the safety that IO provides.
Also consider that your function would have to work for any conceivable monad.


text:
Q: Modularity of Lattice We know that a finite lattice $L$ is modular if and only if for all $s,t,u \in L$ such that $s \le u$, we have
$$
s \vee (t \wedge u)=(s \vee t) \wedge u.
$$
If we remove the condition  $s \le u$, that is, if
for all $s,t,u \in L$ a finite lattice $L$ satisfies
$s \vee (t \wedge u)=(s \vee t) \wedge u$ for all $s,t,u \in L,$
what is such an $L$ would be?

A: Suppose that $L$ satisfies $$s\lor(t\land u)=(s\lor t)\land u\tag{1}$$ for some $s,t,u\in L$. Then $$s\le s\lor(t\land u)=(s\lor t)\land u\le u\;,$$ so $(1)$ already implies that $s\le u$. Thus, if $L$ satisfies $(1)$ for all $s,t,u\in L$, $s\le u$ for all $s,u\in L$, and $|L|=1$. $L$ is not a very interesting lattice!


text:
Q: How do I translate 'no philosopher student admires any rotten lecturer' into quantificational logic formula? Let's assume that $Fx=x$ is a philosophy student, $Rx=x$ is a rotten lecturer, and $Mxy=x$ admires $y$.
My translation of the sentence was $\forall x(Fx\supset\neg\forall y(Ry\supset Mxy))$, but my logic textbook translated it as $\neg\exists x(Fx\wedge\exists y(Ry\wedge Mxy))$.
As far as I know, no philosophy student admires any rotten lecturer means the same as every philosophy student doesn't admire every rotten lecturer. But, the textbook's author seems to understand it as every philosophy student doesn't admire some rotten lecturer. How do I wrap my mind around this?

A: I realized that no philosophy student admires every rotten lecturer cannot possibly mean the same thing as no philosopher student admires any rotten lecturer. It is the same thing as no philosopher student admires some rotten lecturer.

A: The trip-up is that the usage of "any" when inside a negated clause refers to "some" rather than "every".
Hence "No F admires any R" translates as "there does not exists an F that admires an R."
$$\neg\exists x~\Big(F(x) \wedge \exists y~\big(R(y)\wedge M(x,y)\big)\Big)$$
Which is equivalent to $$\forall x~\Big(F(x)\to ~\forall y~\big(R(y)\big)\to \neg M(x,y)\big)\Big)$$
Or in PNF: $$\forall x~\forall y~\Big(\big(F(x)\wedge R(y)\big) \to \neg M(x,y)\Big)$$


text:
Q: Load big text (a lot of lines) file to listBox How load big text file (12150001 lines) to listBox?
Application is not responsible.
My code:
string fileName = @"C:\Users\xxx\Documents\xxx.txt";
listBoxXYZ.DataSource =  File.ReadAllLines(fileName);

Or:
                    using (System.IO.StreamReader sr = System.IO.File.OpenText(fileName))
                {
                    List<string> _list = new List<string>();

                    String input;
                    while ((input = sr.ReadLine()) != null)
                    {
                        _list.Add(input.ToString());
                    }
                    listBoxXYZ.DataSource = _list;
                    sr.Close();
                }

A: The ListBox component is just not designed to handle that amount of data.
Beside, you will also have a huge amount of memory used, just for the listbox.
Also the user probably won't be able to do anything with a listbox of that size.
I think you should reconsider your usecase and look for a better component, perhaps with lazy loading as well.


text:
Q: Is it possible for a function to be in $L^p$ for only one $p$? I'm wondering if it's possible for a function to be an $L^p$ space for only one value of $p \in [1,\infty)$ (on either a bounded domain or an unbounded domain).
One can use interpolation to show that if a function is in two $L^p$ spaces, (e.g. $p_1$ and $p_2$,with $p_1 \leq p_2$ then it is in all $p_1\leq p \leq p_2$).
Moreover, if we're on a bounded domain, we also have the relatively standard result that if $f \in L^{p_1}$ for some $p_1 \in [1,\infty)$, then it is in $L^p$ for every $p\leq p_1$ (which can be shown using Hölder's inequality).
Thus, I think that the question can be reduced to unbounded domains if we consider the question for any $p>1$.
Intuitively, a function on an unbounded domain is inside an $L^p$ space if it decrease quickly enough toward infinity. This makes it seem like we might be able to multiply the function by a slightly larger exponent. At the same time, doing this might cause the function to blow up near zero. That's not precise/rigorous at all though.
So I'm wondering if it is possible to either construct an example or prove that this can't be true.

A: Robert's and joriki's examples are of course nice and explicit, but you can get examples on any subset of $\mathbb{R}^n$ with infinite measure. Here's how:
Take a function $f$ that is in $L^p$ but not in $L^q$ for $q \gt p$ (on the unit ball $B$ around zero, say). Now take a sequence $x = (x_n)$ that is in $\ell^p$ but not in $\ell^q$ for $q \lt p$ (there are standard examples for both of these things). Now take disjoint balls $B_n$ of volume $1$ (disjoint from $B$) and consider $g = f + \sum x_n \cdot [B_n]$ where $[B_n]$ denotes the characteristic function of $B_n$. Obviously, $\|g\|_{q}^q = \|f\|_{q}^q + \|x\|_{q}^{q}$ is in $L^q$ if and only if $q = p$. If $q \lt p$ then $\|x\|_q = \infty$ and if $q \gt p$ then $\|f\|_{q}^q = \infty$.
I leave it to you to make that explicit and to modify it when your domain is not all of $\mathbb{R}^n$.

A: Since $1/x$ is the border case in both directions, the most promising candidate would be a modified version of $1/x$ that just converges but won't converge if you nudge it ever so slightly. We have
$$\int_2^\infty \frac1{x\log^2x}\mathrm dx=\left[-\frac1{\log x}\right]_2^\infty=\frac1{\log2}\;,$$
whereas
$$\int_2^\infty \left(\frac1{x\log^2x}\right)^p\mathrm dx$$
with $p<1$ diverges. If we stitch this function together with its inverse to get convergence at $0$, we get an integral
$$\int_2^\infty \frac1{x^{1/p}\log^2(x^{1/p})}\mathrm dx=\frac1{p^2}\int_2^\infty \frac1{x^{1/p}\log^2x}\mathrm dx\;,$$
which again diverges for $p>1$, so we only have convergence on both sides if $p=1$.

A: Try $$f(x) = \frac{1}{x^{1/p} (\ln(x)^2+1)} \qquad \text{on} \qquad (0, \infty)$$

A: Consider a real monomial: $x^\alpha$
Now poles give a restriction of the form $\alpha>\alpha_0$
while decay rates give a restriction of the form $\alpha<\alpha_0$.
This can be used to glue a desired example, e.g. if
$$f(x):=x^{\alpha_0}\chi_{[-1,1]}+x^{\alpha_\infty}\chi_{(-\infty,-1)\cup(1,\infty)}$$
then the integrability is restricted to
$$-\frac{1}{\alpha_0}<p<-\frac{1}{\alpha_\infty}$$
Unfortunately this technique only restricts up to a neighborhood like $p=7\pm\varepsilon$.


text:
Q: Distribution of 4 distinct objects among 10 people Suppose I want to distribute $4$ different prizes among $10$ students. In how many ways can I do so?
One method goes like this: for each prize, I have $10$ choices. Hence, by the Fundamental Principle of Counting, the answer comes out to be $10\cdot 10\cdot 10\cdot 10= {10^4}$.
I see that this solution is quite efficient and pleasing but I want to explore the other possible consistent ways of solving the problem.
EDIT: The $4$ prizes can go independently to any of the $10$ students, i.e. one has to count all the possible distributions of the prizes, among those $10$ students.
One method that I tried is to consider the cases of distribution of the prizes, which are: all $4$ go to a single student$;$ $3$ go to one student and $1$ goes to another$;$ $2$ prizes go to a student and the rest $2$ prizes go to another student. Now, I tried to find the number of ways in which each case is possible. For e.g. if all $4$ go to a single student of the $10$ students, it possible in only $10$ ways. Thus, after finding the total number of ways in which all the mentioned $3$ cases can occur, we can just add the numbers to get the required answer. I may be wrong with such a method and if so, I'd appreciate if you point it out for me and also discuss an alternative solution.


text:
Q: Why do browsers always ask to update Java? I have all my browsers asking to update Java, for example, if this link open http://download.oracle.com/otndocs/products/javafx/2/samples/Ensemble/index.html
If I agree to update, this does not help.
Is this common market situation? Or this is my system glitch?

A: All of your browsers are asking to update Java because your Java has updates available.
Those updates close security holes that allow a remote website to infect your computer with viruses, that is why your browser specifically is reminding you that you need to perform the update.
Find what editions of java you have installed and either uninstall them if you don't need them or get the latest versions from the Java website.

A: You receive an alert to update Java because either:

*

*Java is outdated,

*An update wasn't installed properly, thus Java remains outdated, or

*It is a malware faking a Java update request.

Also note that usually the update alert comes not from the browser, but from Java itself, via a taskbar icon similar to this one:

It is possible that in some sites, the Java application requires some specific version of Java to be running, but in this case it would be the site, rather than the browser, alerting of an outdated Java version.

A: The issue we routinely see is that websites using the browser java plug-ins do not necessarily support the latest versions.  Unfortunately the incremental updates actual change the behavior of the Java engine (for better or worst).  3rd party developers then need time to develop updates to adapt to the new behavior and may only include it in future enhancements of their product.
If a end-user follows the on-screen recommendation to install the latest version, these websites break.  It then becomes an IT issue to remove the update and re-install the compatible version.  IT administrators should have a direct path for eliminating the "Install Now" pop-up as distribution is usually controlled with AD Group Policy or some other distribution software.


text:
Q: How to create new test report directory with timestamp every time I run a test and keep the old test reports using scalatest and sbt I am using scalatest to run some tests. Now every time I run a test the test results get stored in target/test-reports overwriting the previous test results. I want to store the results in a new folder with timestamp in the folder name. Like in target/test-reports/dd-mm-yy-hhmmss folder and keep the old results intact. How to get the time stamp in build.sbt and use it to make the folder name.
Currently my build.sbt looks like this :
testOptions in Test ++= Seq(Tests.Argument(TestFrameworks.ScalaTest, "-o"), Tests.Argument(TestFrameworks.ScalaTest, "-h", "target/test-reports"))

Please suggest how to get the timestamp and use it in folder name.

A: Try
libraryDependencies += "org.pegdown" % "pegdown" % "1.6.0",
testOptions in Test ++= Seq(
  Tests.Argument(TestFrameworks.ScalaTest, "-o"),
  Tests.Argument(TestFrameworks.ScalaTest, "-h", s"target/test-reports-$testDirTimestamp")
)

def testDirTimestamp = {
  import java.time.LocalDateTime
  import java.time.format.DateTimeFormatter
  LocalDateTime.now.format(DateTimeFormatter.ofPattern("yyyy-MM-ddHHmmss"))
}

which after executing sbt test should create reports under
target/test-reports-2019-07-02074159

A: I have figured it out. We can use variables in buld.sbt and use it to construct the directory name.
val format = new SimpleDateFormat("dd-MM-yy-hhmmss")
val timeStamp : String = format.format(Calendar.getInstance().getTime())
val resultDirectory : String = "target/test-reports/"+timeStamp

testOptions in Test ++= Seq(Tests.Argument(TestFrameworks.ScalaTest, "-o"), Tests.Argument(TestFrameworks.ScalaTest, "-h", resultDirectory))
libraryDependencies +=  "org.pegdown" % "pegdown" % "1.6.0" % "test"

I tried this earlier but did not work. The reason is every time you change the build.sbt file you need to reload the sbt shell, which I did not earlier.


text:
Q: Are p-boxes for discrete sample spaces meaningful? The Wikipedia article about p-boxes only talks about cumulative probability density functions, which are meaningful for continuous sample spaces. https://en.wikipedia.org/wiki/Probability_box
Just out of curiosity, is it possible, and meaningful, to define p-boxes for discrete sample spaces? What axioms should they fulfil? Some quick google searches for "discrete p-box" and variants thereof did not turn up any results.
Take a three-element sample space $\{0,1,2\}$ for example. We can define a probability mass function (pmf) on it, like $\{0 \mapsto 0.5, 1 \mapsto 0.5, 2 \mapsto 0\}$, where 0 has probability 0.5, 1 has probability 0.5, and 2 has probability 0. Another one would be $\{0 \mapsto 0, 1 \mapsto 0.5, 2 \mapsto 0.5\}$.
My attempt at defining p-boxes on this would be to allow intervals for the probabilities, with the intention that it specifies all pmf's whose values lie in these intervals.
For example a p-box on the three-element set could be $\{0 \mapsto [0,0.5], 1 \mapsto [0,0.5], 2 \mapsto [0,0.5]\}$. This specifies all pmf's whose values lie between 0 and 0.5, like the two concrete ones above.
Not all of those would be meaningful, for example $\{0 \mapsto [0,0.2], 1 \mapsto [0,0.2], 2,[0 \mapsto 0.2]\}$ does not include any valid pmf, because no possible sum adds up to 1.
Another one that is not meaningful would be $\{0 \mapsto [0,\frac{1}{3}], 1 \mapsto [0,\frac{1}{3}], 2 \mapsto [0, \frac{1}{3}]\}$, because the lower bounds could never be used.
It seems that if one were to specify p-boxes in this way, there is some constraint between the upper and lower bounds.
Are p-boxes on discrete sample spaces meaningful? Are they described in some area of probability theory?

A: There is no such thing as a "cumulative probability density function". You seem to get confused between the notions of (i) the (cumulative) probability distribution function, (ii) the probability density function, and (iii) the probability mass function. I suggest you read an introductory textbook on probability or statistics, or just the corresponding Wikipedia articles.
Concerning now p-boxes specifically: The Wikipedia article linked in your post defines a p-box in terms of a cumulative probability distribution function, which in turn is defined for arbitrary real-valued random variables -- discrete, continuous, and neither discrete nor continuous. So, there is no reason to worry about p-boxes in the discrete case.
As for the usefulness/meaningfulness of p-boxes, even the Wikipedia article linked in your post has some criticisms  of the notion of a p-box. I have never before encountered this notion, and I don't believe it could be really useful.


text:
Q: Mongodb error on docker I've a dockerfile and a docker-compose
When I try to run docker-compose this happens

Does someone know how to fix it?
Edit 1
dockerfile
FROM node

RUN apt-get update && apt-get install -y --no-install-recommends build-essential \
 && apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927 \
 && echo "deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-3.2.list \
 && apt-get update \
 && apt-get install -y mongodb-org

RUN useradd --user-group --create-home --shell /bin/false app &&\
  npm install --global npm

ENV HOME=/home/app

COPY package.json $HOME/library/
RUN chown -R app:app $HOME/*

USER root
WORKDIR $HOME/library
RUN npm install --silent --progress=false
COPY . $HOME/library
RUN chown -R app:app $HOME/*
RUN npm install --build-from-source bcrypt

CMD ["npm", "start"]

docker-compose
version: '2'
services:
  db:
    image: mongo
    command: "mongod"
    ports:
      - "27018:27018"
  library:
    build:
      context: .
      dockerfile: Dockerfile
    command: node_modules/.bin/nodemon --exec npm start
    environment:
      NODE_ENV: development
    ports:
      - 3000:3000
    volumes:
      - .:/home/app/library
      - /home/app/library/node_modules
    links:
      - db

Edit 2
Running docker ps -a here
First container docker log here
Second container docker log here
Edit 3
mongoose.connect(config.database);

That's how I am connecting the database on server.js

A: Your Docker Compose file has the MongoDB Ports as 27018=>27018 but the error from your node application is saying it is trying to connect to 127.0.0.1:27017.
Because of how Docker's networking works (which is all kinds of awesome) you should change the port to be 27017 not 27018 in your Compose file & update the MongoDB connection string in your Node app to db:27017.
You shouldn't use 127.0.0.1 within Docker as it expects that whatever you are connecting to is running on within the same container.


text:
Q: Inverse trigonometry integration The magnitude of ans is correct but the sign is negative. Which is incorrect. But the procedure seem to be correct.

A: The problem lies in your choice of trig identity.
Cosine is an even function, so $\cos(\frac{\pi}{2}-x)$=$\cos(x-\frac{\pi}{2})$
The problem with your "cancelation" is that $y=\frac{\pi}{2}-x$ and $y=x-\frac{\pi}{2}$ are not the same graph. On interval $[0,1]$ one is above the axis and one below. That explains your answer off by a negative. So the best thing is to graph the original function first as to determine what trig identity should be used to rewrite the sine.

A: I think this is because of the property of cos to  absorb negative sign of angle.
If you write $\sin x = \cos(\frac π2 - x)$
You got $\frac π2 - \frac12$

A: The problem is the range of arccosine, which is between $0$ and $\pi$.  Therefore, $\cos^{-1}(\cos x)\ne x$ if $x$ is negative.


text:
Q: Catalog product flat reindex issue: errno: 121 Duplicate key on write or update (Magento 1.9.3.8) When I try to reindex catalog_product_flat from command line I get following error.
Reindex finished with error message "SQLSTATE[HY000]: General error: 1005 Can't create tablemagento_db.#sql-4f16_e84(errno: 121 "Duplicate key on write or update")". catalog_product_flat
I tried to truncate all catalog_product_flat tables and rerun it, same result. How can I fix this?

A: SET FOREIGN_KEY_CHECKS=0;
TRUNCATE TABLE catalog_product_flat_1;
TRUNCATE TABLE catalog_product_flat_2;
TRUNCATE TABLE catalog_product_flat_3;
TRUNCATE TABLE catalog_product_flat_4;
TRUNCATE TABLE catalog_product_flat_5;
TRUNCATE TABLE catalog_product_flat_6;
SET FOREIGN_KEY_CHECKS=1;


text:
Q: USA Today-like iPad Multipage Column Layout I'm trying to achieve a layout like this: http://www.ipadinsight.com/wp-content/uploads/2010/07/LakersWin.jpg to be a multi-page multi-column layout working on one body of text. Any ideas? I think that CSS can handle the multi-layout question, but not the paging. Any help would be greatly appreciated. Thank you.

A: You can achieve this by using css property like webkit-column-count, css example below.
div
{
    -moz-column-count:3; /* Firefox */
    -webkit-column-count:3; /* Safari and Chrome */
    column-count:3;
}

Demo is here http://jsfiddle.net/Bqjcc/

A: How about a grid system?
I prefer the 1140 css grid: http://cssgrid.net/
The 960 grid is also popular: http://960.gs/


text:
Q: How to save a model with SharedPreferences? I've got class to add some variables inside it.
I've created an object from it.
Then i've added  some value to it.
The problem now is, i don't know how to add it inside.
SharedPreferences
i want to edit the code so i can add it without problems.
// class : MainActivity
     public class MainActivity extends AppCompatActivity {

         Times times;

         public static Context context;
         @Override
         protected void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.activity_main);
             this.context = context;

             times = new Times(5,30);

             // setInt(times);
         }

         public final static String PREFS_NAME = "appname_prefs";

         public static void setInt(String key, int value) {
             SharedPreferences sharedPref = context.getSharedPreferences(PREFS_NAME ,0);
             SharedPreferences.Editor editor = sharedPref.edit();
             editor.putInt(key, value);
             editor.apply();
         }

         public static int getInt(String key) {
             SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, context.MODE_PRIVATE);
             return prefs.getInt(key , 0);
         }
     }

    // class Times:

    public class Times{

        int Houre;
        int Minute;

        public Times(int houre, int minute){
            Houre = houre;
            Minute = minute;
        }

        public void setHoure(int houre){
            Houre = houre;
        }

        public void setMinute(int minute){
            Minute = minute;
        }

        public int getHoure(){
            return Houre;
        }

        public int getMinute(){
            return Minute;
        }

    }

A: Just add editor.commit(); delete editor.apply();
you can read explanation on shared prefs here
https://www.tutorialspoint.com/android/android_shared_preferences.htm

A: Ohad is correct. SharedPreferences only store primitive types like Int and String. In this case you would have to store each value as its own SharedPreference.
If your data is more complex than what SharedPreferences can handle, consider storing it in a Room database.


text:
Q: simple modal pop up not working in ie 10.0? I'm using simple modal JQUERY plug-in for having pop ups in my MVC 4 website, its works fine with CHROME and FIREFOX but not in internet explorer v10.0, If I opened the site in IE it throws below java script error and modal popup not appearing
Unhandled exception at line 16, column 133 in http://localhost:55939/Scripts/jquery.simplemodal.1.4.4.min.js
0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'removeExpression'

In layout page I'm rendering the below scripts

Below is my Login.cshtml page

    @using (Html.BeginForm())
    {

Sign in to your Account

            @Html.LabelFor(m => m.Username, new { @class = "inlabel" })
            @Html.TextBoxFor(m => m.Username, new { @class = "infield" })

            @Html.LabelFor(m => m.Password, new { @class = "inlabel" })
            @Html.PasswordFor(m => m.Password, new { @class = "infield" })

                    @Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")

            @Html.ActionLink("Forgot your password?", "ForgotPassword")
            <input type="submit" value="Sign In" class="submitButton" />

    }

I'm not sure if there is any compatibility issue with simple modal and jquery plugins any help would be much appreciated.
Many Thanks

A: See the answer by Noah Lehmann-Haupt in this question: Simple Modal, jQuery 1.8.0 and IE9
You'll need to edit a line of the jquery.simplemodal
 // (Line 239) $.support.boxModel is undefined if checked earlier
 //browser.ieQuirks = browser.msie && !$.support.boxModel;
 browser.ieQuirks = browser.msie && (document.compatMode === "BackCompat");

This problem has re-occurred for jQuery 1.10.1


text:
Q: Solving $(D^5-D)y = 8\sin x$ using operator methods This question is similar to this link but here it involves $\sin x$ and it creates a problem. I tried writing $\sin x = \Im (e^{ix})$ but that doesnt help:
$$(D^5-D) y = 8\Im (e^{ix})$$
Now $(D^5-D)$ has factor $D=i$ so we need to factor that out and apply it on right side:
$$(D-1)(D+i)(D+1)D y=\frac{1}{D-i}(\Im(e^{ix}))\\
\implies y = \frac{8}{(i-1)(i+1)(2i)(i)}\Im(e^{ix}\int e^{ix} e^{-ix} dx)$$
which gives $y_p = 2x\sin x$. Another method would have been assuming $y_p = x(A\cos x + B\sin x)$ but that too would have been lengthy
Is the method in this answer correct, because it is using complex numbers loosely. Is this operator method?

A: You can use the same method suggested in 1. Let us find a solution $y$ of the equation
$$
(D^5-D)[y]=8e^{ix}
$$ first. Write $T=D^5-D$. For any $r\in\Bbb C$, it holds that
$$
T[e^{rx}]=D^5[e^{rx}]-D[e^{rx}]=(r^5-r)e^{rx}.
$$ Plugging $r=i$ into the equation does not give the solution because $i^5-i=0$. Now, by differentiating both sides with respect to $r$, we get
$$
\frac{\partial}{\partial r}T[e^{rx}]=T[\frac{\partial}{\partial r}e^{rx}]=T[xe^{rx}]=\frac{\partial}{\partial r}\left((r^5-r)e^{rx}\right)=(5r^4-1)e^{rx}+(r^5-r)xe^{rx}.
$$
Plugging $r=i$ into the expression, we get
$$
T[xe^{ix}]=(5i^4-1)e^{ix}+(i^5-i)xe^{ix}=4e^{ix}.
$$ This shows $T[2xe^{ix}]=8e^{ix}$. By separating real and imaginary parts, we get
$$
T[2x\cos x]=8\cos x,\quad T[2x\sin x]=8\sin x.
$$ This allows us a particular solution $y(x) =2x\sin x$ satisfying $T[y]=8\sin x$.


text:
Q: Not able to debug source code while running unit test cases angular v9 I am using angular v9.
I am able to debug unit test cases in browser using ng test command.
However, some source code methods i need to debug in order to inspect why unit test cases are failing, for that i am trying to add breakpoint, but not able to add them where as some source code method i am able to debug.
any idea?

A: There's a thread regarding to [debug tests in ng test].(Debug Tests in NG Test)
Note: Assuming that you are using Google Chrome as a test browser.


text:
Q: If i have two checkboxes yes or no how can i handle those two If I have Two Check Boxes one is Yes another is No ,if i check on yes, no automatically uncheck(vise versa)
and saved into database (1 for yes 0 for no)

A: using jquery u can make like this
    <input type="checkbox" class="radio" value="1" name="fooby[1][]" />
    <input type="checkbox" class="radio" value="2" name="fooby[1][]" />

<script>
       $("input:checkbox").click(function(){
            var group = "input:checkbox[name='"+$(this).attr("name")+"']";
            $(group).prop("checked",false);
            $(this).prop("checked",true);
        });
</script>

http://jsfiddle.net/m5EuS/1/ fiddle


text:
Q: Django локализация и пути Подскажите плиз, делаю сайт на двух языках. По умолчанию django для каждого языка подставляет корневой путь /ru/ или /en/
А как сделать чтобы для языка по умолчанию (ru) адреса выводились от корня /, а для английского через /en/ ?

A: Решено!
Необходимо добавить в i18n_patterns дополнительный параметр prefix_default_language=False. В итоге код корневого urls выглядит как показано ниже
urlpatterns = [
    url(r'^admin/', admin.site.urls),
]

urlpatterns += i18n_patterns(

    url(r'^$', home_page, name='home_page'),
    # ...

    prefix_default_language=False,
)


text:
Q: Can I map class to int and use it as primary key? I want to use purpose-specific id types (e.g. PersonId for Person class). It requires me to map my custom class (PersonId) to an int and use it as primary key
public class PersonId
{
    int Id;
}

public class Person
{
    PersonId Id;
    // ...
}

Can I map this classes in EF?

A: Putting a class as the primary key isn't possible. With Entity Framework primary keys must be a primitive type or a byte[].
If you want to do something like that for something else than primary key you could make the PersonId class a Complex type.
[ComplexType]
public class PersonId
{
    int Id;
}

or with the fluent API
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.ComplexType<PersonId>();
}

but you won't be able to use that Id as the primary key of your entity


text: Q: Second product image on category page I'm trying to display second image of a product in a category page on hover. I managed to get images by $_product->getMediaGalleryImages() but I have problems with resizing them to category_page_grid or category_page_list size. My question is: how can I resize those images to default category page image size or maybe is there a way to get second image with the same method as default image by $productImage = $block->getImage($_product, $imageDisplayArea)?


text:
Q: Flutter setState not updating string variable I am adding a file to firebase storage. After obtaining the firebase URL of the image, I use setState to set it equal to another string( fileUrl) and then add it to the Firestore database. The problem is it's not updating to the firebase URL and the String fileUrl still has its initialized value. This is the way I use to add the file and add it to the Firestore database, I'm not sure how to fix it.
First I select a file:
    ...
    String fileUrl = 'temp';
    ...

    Future uploadFile() async {
    if (file == null) return Container();

    final fileName = basename(file!.path);
    final destination = 'files/$fileName';

    task = FirebaseApi.uploadFile(destination, file!);

    if (task == null) return;

    final shot = await task!.whenComplete(() {});
    final urlDownload = await shot.ref.getDownloadURL();

    print('Download-Link: $urlDownload'); // This prints out the correct url

    setState(() {
      fileUrl = urlDownload.toString();
    });
    }

Then I upload to firebase database :
    void postToFirebase(school, String fileName) {

    print('fileUrl') ; //But when i check it here it still prints out 'temp'

    FirebaseFirestore.instance
        .collection("collection_name")
        .doc(doc_name)
        .collection("collection_name")
        .add({
      "attachmentUrl": fileUrl,
      "attachment_name": fileName,
    })

Then my Button (on pressed )
    onPressed: () async {
    uploadFile();
    postToFirebase(school, fileName);
    }

Not sure how to fix it. Any help will be much appreciated, thank you

A: The fileUrl field was updated in uploadFile method in an async way. So you are not guaranteed the field will be updated before the following method is called, which is the postToFirebase.
If you want to make it work sequentially, you can use promise/future to tune the process. New a promise, and complete it in the setState callback, and thus make uploadFile method return a future depended on the completion of the promise in setState callback method. And then chain the  postToFirebase with the former one using future's then API.
Code example here:
  String fileUrl = "";

  Future updateFile() {
    Completer completer =  Completer();
    setState(() {
      fileUrl = "new";
      completer.complete();
    });
    return completer.future;
  }

  void postToFireBase() {
    // use the fileUrl updated here
  }

  void text() {
    updateFile().then((value) => postToFireBase());
  }


text:
Q: Are constexpr evaluated on target platform? I wonder if, for example, evaluated compiled on a little endian platform will return true on a big endian target platform.
constexpr bool is_little_endian()
{
    int num = 1;
    return (1 == *(char *)&num);
}

In other words, are constexpr evaluated as if on the target?
EDIT: This example isn't correct, but the question is still active.

A: First off: If you compile code for a given target, then the compiler will generate code for that target. This, of course, includes expressions that are evaluated at compile-time - otherwise every cross compilation that involved such expressions would be broken.
However, just marking a function as constexpr does not guarantee that it is evaluated at compile-time. In particular, your sample function cannot (according to the standard) be evaluated at compile-time, so it is orthogonal to the primary question.
As remarked in the comments, you can't really find out endianness at compile-time without querying the compiler directly. The compiler has to know (because it has to generate code) and any reasonable compiler will provide a way for you to query this information (at compile-time).

A: This is not a valid constexpr function as it has reinterpret_cast baked into it. This makes the whole question moot.
And the reason why this is not valid constexpr function is outlined here: https://en.cppreference.com/w/cpp/language/constexpr. In particular, constexpr function should satisfy, among others, following criteria:

...there exists at least one set of argument values such that an
  invocation of the function could be an evaluated subexpression of a
  core constant expression

reinterpret_cast can never be a part of core constant expression.

A: Yes they are. If you have a C++20 compiler available (probably -std=c++2a) you can try to compile this for platforms with different endianess and see that it behaves correctly.
#include <bit>
#include <iostream>

constexpr bool are_all_scalar_types_little_endian() {
  return std::endian::native == std::endian::little;
}

constexpr bool are_all_scalar_types_big_endian() {
  return std::endian::native == std::endian::big;
}

int main() {
  std::cout << std::boolalpha
    << "little: " << are_all_scalar_types_little_endian() << '\n'
    << "big   : " << are_all_scalar_types_big_endian() << '\n'
    << "mixed : " <<
        (are_all_scalar_types_little_endian()==are_all_scalar_types_big_endian()) << '\n';
}


text:
Q: Testing API's with certificates I'm somewhat inexperienced with API's. I've been screwing around and somehow managed to get them working.
My question is relating to an API that was working before. It is a POST, with a non-variable URL (i.e. not https://url/call?id={id}), and with a JSON body request.
The call is secured with a certificate that was generated using openssl. The certificate has since expired, and following the steps exactly as detailed in the API documentation. I have tested the files, with the developers of the API on a screen share, on Postman using the pem, key and pfx files as Postman specifies.
But our system needs a CER file, that is generated from the pfx file by our Platform's specialists - and that is the only part where I have no interaction with any of the files.
On Postman the call is successful, but when the CER file is generated and installed, it doesn't work.
Is there another app similar to Postman, but where I can use the CER file as generated by our Platform, or perhaps generate my own CER file, test it and install and then use.
Thank you

A: Pfx or Key files contains private key that is required to sign API request but CER file does not contain private key.
For any more details, please share the API specifications so the mechanism to achieve requirement can be devised.


text:
Q: using the right query to perform the proper field targeting I have a table with data like this:

The 6s and 2s you see correspond to userIDs in a users table.
My goal is that with a single query I can target the 6s or 2s.
I will try to be specific. Suppose I target user_Ids with 6, with a query like the one you will see below is that I get as a result 2 rows, at which both rows you can find 6:
                select  appointments.Bookfrom,appointments.Bookedfor
                from appointments,users
                where users.email='email'
                and (appointments.Bookfrom=users.user_ID
                or appointments.Bookedfor=users.user_ID);

WHat I want is to get the 6ths in a single row...meaning getting back only one row in which each column has the 6 in it.
SO far I can achieve that with 2 select statements but I cannot do it with just one.Here is one of these statements that will give me what I want but for one column:
                select  appointments.Bookedfor
                from appointments,users
                where users.email='papageorgiou40@hotmail.com'
                and users.user_ID=appointments.Bookedfor;

The result of the above is this:

I hope I was clear.

A: I think the following does the job, it compares the two fields, and it's better to use JOINS for this:
SELECT * FROM appointments INNER JOIN users user_editor ON appointments.bookeditor = user_editor.user_ID INNER JOIN users user_from ON appointments.bookfrom = user_from.user_ID WHERE STRCMP(bookfrom, bookeditor) = 1


text:
Q: How can I reinstall all R packages from the superuser to the user? I'm using R in Ubuntu. I've realised that I have packages installed in both /usr/local/lib/R/site-library/ and /home/sparhawk/R/x86_64-pc-linux-gnu-library/3.0/. I'd prefer them all in my user directory.
How can I move all the (non-base) packages to the user directory? I'm happy to reinstall R and/or the packages if necessary.
I've also tried sudo apt-get purge r-base, but this didn't touch the root directory listed above.

A: Use the destdir option with install.packages to specify the location of the packages to be installed.

install.packages("RCpp,destdir="~/RPackages", CRAN="http://cran.r-project.org")

A: Uninstall R and packages
First I purged the Ubuntu package
$ sudo apt-get purge r-recommended
$ sudo apt-get --purge autoremove
...
dpkg: warning: while removing r-base-core, directory '/usr/lib/R/library' not empty so not removed

As above, one directory was not removed, so
$ rm -r /usr/lib/R /tmp

The package directories at /usr/local/lib/R/site-library/ and ~/R/x86_64-pc-linux-gnu-library/ were still present, so I removed them.
$ mv /usr/local/lib/R/ /tmp
$ mv ~/R/ /tmp/R-user

Reinstall R and packages
sudo apt-get install r-recommended

Run R from a user account (I used RStudio). Install packages manually.
At one point, I got the warning.
Warning message:
installed directory not writable, cannot update packages 'Matrix'

So rather than run R as superuser, I attempted to install another version in the user directories. I think I have both versions installed, but R seems to pick the newer version.
> update.packages()
Matrix :
 Version 1.0-14 installed in /usr/lib/R/library
 Version 1.1-0 available at http://cran.rstudio.com
Update (y/N/c)?  y
Warning in install.packages(update[instlib == l, "Package"], l, contriburl = contriburl,  :
  'lib = "/usr/lib/R/library"' is not writable
Would you like to use a personal library instead?  (y/n) y
...
> update.packages()
Warning: package 'Matrix' in library '/usr/lib/R/library' will not be updated
> packageVersion('Matrix')
[1] '1.1.0'

However, despite R seemingly picking the latest version, I still get warning messages about being unable to upgrade packages.
> biocLite("limma")
Warning message:
installed directory not writable, cannot update packages 'Matrix'


text:
Q: angular js http get basic auth Hi. At the beginning I have an auth page will just return a json code without doing any auth and then I tried the following code but without the basic auth line. It did work, but then once I added basic auth required on auth page access and I use the below code, then it didn't work. The console log test return status empty string.
When I used postman in chrome and it worked if I included the header auth. I can see the return json code. What's wrong with my code below? Thanks.
angular.module('demoApp')
  .controller('MyrouteCtrl', function ($scope, $http) {

    $http.defaults.headers.common.Authorization = 'Basic mybase64code';
    var output = $http.get('http://tmydomain.com:1338/auth/').
    then(function(response) {
            var status = response;
    });
    console.log("test", status );
  });

A: You should have console.log inside the response handler, e.g.
var output = $http.get('http://tmydomain.com:1338/auth/', [headers: [Authorization: 'Basic mybase64code']]).
then(function(response) {
        var status = response;
        console.log("test", status );
        return response.data;
});


text:
Q: Not throwing exception while passing wrong date in javascript I was trying to check if a date(in MM/dd/yyyy format) is a valid date in javascript. But while passing a wrong date, it is not able to distinguish.
I was using the below logic to check if it is a valid date or not.
var dt = document.forms["registerForm"]["dateOfBirth"].value;
    try{
        var d = new Date(dt);
        alert(d);
    }catch(err){
        alert("not a valid date");
        return false;
    }

while the dateOfBirth is "02/47/2016" it is not going to the exception block, rather it is interpreting "02/47/2016" as Fri Mar 18 2016 00:00:00 GMT+0530 (IST). But when i tried with "02/03/2016" it is interpreting correctly as Wed Feb 03 2016 00:00:00 GMT+0530 (IST).

A: Enforce some structure when users enter the date in the form, e.g. MM/DD/YYYY.  If you don't you may end up with a date such as 02/10/2016 which could validly be Feb 10th or Oct 2nd depending on the country.
Past that, unless you have to be lean, use moment.js for validation, e.g.
alert(moment("02/10/2016", 'MM/DD/YYYY',true).isValid()); //true

A: The Date constructor gets the day value and just adds that number of days, minus 1, to the first of the month, which explains the resulting date you get.
Using a library like momentjs makes life much easier when it comes to dealing with dates, but if you want to do this without additional library, then you could use the function below. If the Date constructor returns a date object, this function will format that date back to a string, comparing it with the original input. If they don't match, the function will return undefined, just like when an exception occurs. If they match, the date object is returned:

function getDate(d) {
    function formatDate(d) {
        return [d.getMonth() + 1, d.getDate(), d.getFullYear()]
               .map( n => (n < 10 ? '0' : '') + n ).join('/');
    }
    try {
        var d = new Date(dt);
        if (formatDate(d) != dt) return; // invalid
        return d;
    }
    catch(err){}
}

var dt = '02/47/2016';
console.log(dt, getDate(dt) !== undefined);
var dt = '02/03/2016';
console.log(dt, getDate(dt) !== undefined);


text:
Q: Accessing Azure Active directory users and roles As Azure REST APIs helps to retrieve the users and corresponding roles information at subscription level.
I would like to know that I have manually created a few users and assigned them different roles in Azure Active directory and i want to access those information from azure active directory through REST API calls or in a programmatic way.
How can I access that information at azure active directory level to retrieve the user list ? is there any API calls available ? what about GRAPH API on this scenario and how it can be used ?
Please input your suggestions. Thanks All !

A: Yes, you can do this via the REST API.
There are two APIs available:

*

*Azure Active Directory Graph API - graph.windows.net (old)

*Microsoft Graph graph.microsoft.com (new).

You should go with the new graph.microsoft.com API (check whether the new API covers all your requirements).
See Working with users in Microsoft Graph

A: You can use Microsoft Graph to list all users: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list
https://graph.microsoft.com/v1.0/users/

You can give it a try with the Graph Explorer at https://developer.microsoft.com/en-us/graph/graph-explorer
You will need an access token to call Microsoft Graph, more information about obtaining an access token can be found here: https://developer.microsoft.com/en-us/graph/docs/concepts/auth_overview

A: You could use the Azure AD Graph API to retrieve users list and corresponding roles by using GET https://graph.windows.net/myorganization/users?api-version=1.6. For the details, please read here.


text:
Q: Vim plugins overwrite line numbers After upgrading vim plugins.
It appears that some Plugins (Ace, Gitgutter, Coc) overwrite the line numbers. The following screenshot shows the problem at line 20. A '+' has overwritten the line number instead of being placed just before it.
Do you have any idea or fix about what could cause this issue ?
Sorry the question is probably not really clear. The goal is to get help pinpointing the shared component that could be responsible for the incorrect display.

A: I also had this issue by copy-pasting coc-nvim config.
The problem was caused by this part of the code
...
if has("nvim-0.5.0") || has("patch-8.1.1564")
  " Recently vim can merge signcolumn and number column into one
  set signcolumn=number
else
  set signcolumn=yes
endif
...

I just replaced it with
...
if has("nvim-0.5.0") || has("patch-8.1.1564")
  " Recently vim can merge signcolumn and number column into one
  set signcolumn=auto
else
  set signcolumn=auto
endif
...

And everything started to work as expected

A:
Do you have any idea or fix about what could cause this issue ?

You said it yourself:

It appears that some Plugins (Ace, Gitgutter, Coc) overwrite the line numbers.

*

*Figure out what plugin is causing the issue.

*Look for clues in its documentation.

*If you can't find anything or nothing works, use its issue tracker.


text:
Q: How to homogenize components size in a JTable? I have a JTable with two columns. The first one contains a custom component (bargraph) with three components inside it:  JLabel lMinLabel, Graph lGraph and JLabel lMaxLabel. Here is what I have:

Here is what I want:

The values label can have different sizes in the different rows, which modify the size of the bargraph. I want the bargraph to have the same size for all JTable rows.
I tryed to put the label in panels, and set a minimum size to these panels (with a fixed value).
Here is my code:
package test;

import java.awt.Component;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

public class JTableExample extends JFrame {

    public JTableExample() {
        super("JTable Example");

        DefaultTableModel dm = new DefaultTableModel();
        dm.setDataVector(new Object[][] { { new BarGraph(0, 10, 25, 27, 75, 90,100), "foo" },
            { new BarGraph(100, 1000, 2500, 5600, 7500, 9000,10000), "bar" } },
                new Object[] { "Graph", "String" });

        JTable table = new JTable(dm);
        table.getColumn("Graph").setCellRenderer(new Renderer());
        JScrollPane scroll = new JScrollPane(table);
        getContentPane().add(scroll);
        setSize(800, 100);
        setVisible(true);
    }

    public static void main(String[] args) {
        JTableExample frame = new JTableExample();
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

class Renderer implements TableCellRenderer {
    public Renderer() {}
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
            int row, int column) {
        return (Component) value;
    }
}

The bargraph class where I try to set the standard size:
package test;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class BarGraph extends JComponent {

    private final double preWarningMax;
    private final double preWarningMin;
    private final double valueMax;
    private final double valueMin;
    private final double warningMax;
    private final double warningMin;
    private double value;

    public BarGraph(double pValueMin, double pWarningMin, double pPreWarningMin, double pValue, double pPreWarningMax,
            double pWarningMax, double pValueMax) {
        super();
        valueMin = pValueMin;
        warningMin = pWarningMin;
        preWarningMin = pPreWarningMin;
        value = pValue;
        preWarningMax = pPreWarningMin;
        warningMax = pWarningMax;
        valueMax = pValueMax;
        this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));

        JPanel lMinPanel = new JPanel();
        JLabel lMinValue = new JLabel(Double.toString(valueMin));
        lMinPanel.add(lMinValue);

        Graph lGraph = new Graph();

        JPanel lMaxPanel = new JPanel();
        JLabel lMaxValue = new JLabel(Double.toString(valueMax));
        lMaxPanel.add(lMaxValue);

        add(lMinPanel);
        add(lGraph);
        add(lMaxPanel);

        lMinPanel.setMinimumSize(new Dimension(15, 5));
        lMaxPanel.setMinimumSize(new Dimension(15, 5));
    }

    private class Graph extends JComponent {

        @Override
        protected void paintComponent(Graphics pGraphics) {
            ...
        }
    }
}

What is the best way to homogenize the bargraph size betweens the JTable rows ?

A: JPanel lMinPanel = new JPanel();
JLabel lMinValue = new JLabel(Double.toString(valueMin));
lMinPanel.add(lMinValue);

Why are you creating an extra panel to hold each JLabel?
Notice how the text is below the top of the cell. That is because the default FlowLayout of the panel adds 5 pixels around all edges of the panel.
Get rid of the panel and just add the JLabel directly to panel with the BoxLayout.

The bargraph class where I try to set the standard size:

    lMinPanel.setMinimumSize(new Dimension(15, 5));
    lMaxPanel.setMinimumSize(new Dimension(15, 5));

The problem is the BoxLayout respects the "maximum" size. So all components will grow to fill the space available.
Instead, I think you want to set the maximum size. So using my first suggestion the basic code should be something like:
lMinValue.setMaximumSize( new Dimension(50, lminValue.getPreferredSize().height) );

You would also set this for the lMaxValue.
Then you add lMinValue/lMaxValue to the component.
You would leave the max size of the chart panel alone, so it should then grow to take all the space after the 100 pixels have been allocated to the two labels.
Note, this assumes the maximum size of the bar chart is greater than its preferred size.


text:
Q: AC voltage gets mixed with DC I am using ATS (automatic start) for my generator. Its programmable IC goes out of work after 2 or 3 days and I have replaced 3 ATS card. My card supplier says that you are somehow getting AC voltage (220V) mixed with DC voltage (12V) which is causing this problem? I want to know if there can be some problem if AC voltage wire is connected directly with DC wire?
I know this is a dumb question but I don't know anything about circuits.

A: Get a Digital Multi Meter set to measure DC volts, check that you are getting 12 volts DC, then try switching the meter to AC.  If you see a Voltage there, then you have AC superimposed on your DC line.  Unshielded runs of cable can have AC induced onto them if they are near AC lines.  Also, poorly designed power supplies can cause this also.  Without knowing what device you are talking about, or how the ATS card is supplied, it is going to be hard to troubleshoot.  If things are failing, it could also be from over-voltage.  If the power supply IC is a linear and settable type, the components used to set the output could be out of spec and causing the regulator to provide more than the required 12v.  This could cause overheating and failure.  If the bypass caps on the regulator are missing it could send the regulator into oscillation which is also bad and can cause failure of ICs.


text:
Q: Force LSTM Keras to use time series dependencies I have two time series A and B:
A: 1,2,3,1,2,3,3,3,1,2,3,3,3
B: 0,0,1,0,0,1,1,1,0,0,1,1,1

This simple training set says that signal B is correlated to A. In fact each time A is equal to 3, at the same time stamp, in B, the value is 1.
I introduced the example above just to explain my problem. When I forecast data by using LSTM with Keras, I want the model understands this kind of dependencies from series.
Now I use this configuration:
model.add(keras.layers.LSTM(hidden_nodes, activation='sigmoid', input_dim=num_features, input_length=window, consume_less="mem"))
model.add(keras.layers.Dense(num_features, activation='sigmoid'))

optimizer = keras.optimizers.SGD(lr=learning_rate, decay=1e-6, momentum=0.9, nesterov=True)

But I see LSTM forecasts value without apparently use dependences between time series. If I make a prediction with a window of 5, in order to forecast the next point:
A: [1,2,3,1,2]
B: [0,0,1,0,0]

I expect that LSTM gives me value 3 for A and 1 for B, because the training set below says that.
The problem is that my net seems use the signals without give the right weight to signals dependencies.

A: You should have only one series with two features.
If A and B are lists (not numpy arrays):
fullSeq = np.array(A + B)
#this shape is (lenA + lenB,)

fullSeq = fullSeq.reshape((2,len(A)))
fullSeq = fullSeq.swapaxes(0,1).reshape((1,len(A),2))

#make sure that the resulting array is something like [[[1,0],[2,0],[3,1],...]]

Now you have a single sequence with num_features=2. A and B get totally dependent now.


text:
Q: How we can fit table data in ckEditor body...? How we can fit table data in the ckEditor body...?
Actually, I am using https://ckeditor.com/ckeditor-5/online-builder/ online-builder CKEditor in my project with table but table table going outside the body of CKEditor as shown below second image


text:
Q: Excel sheet as return value for a WCF service? Is it possible?
Would you advise a better way?
Do you know an example?

A: You can easily do this. Set the Content-Type header equal to application/vnd.ms-excel and then set a Content-Disposition to something similar to this: Content-Disposition: attachment; filename="filename_here.xls" and then return your Excel data.


text:
Q: How to avoid unnecessary Firestore reads with Cache I have a list of trips data (Large Sets) ordered by date.
Existing Behaviour
I store all the trips data into SqlLite Db. For every new data added, I used to get a fcm notification and I synced only the new added data using last updated time concept. This way when ever an cx opens the app, he will always read the data from my DB, Hence saving read and network operations.
How could i achieve the same with Firestore?
Few problems to consider:

*

*Firestore get() always tries to get the data first from SERVER, even if i add CACHE to my query, how can i synced only the updated document

*In my Recyler View I want the data to be order by a field date not by lut(last-modified-time)

*With FireStore Snapshot Listener i can't query such a large record set.

A: you can just add the source of the data to be retrived

firestore.collection("yourCollection").get({source:"cache"})

A:
Firestore get() always tries to get the data first from SERVER, even if I add CACHE to my query, how can I sync only the updated document?

According to the official documentation regarding enable offline data:

For Android and iOS, offline persistence is enabled by default.

So to use offline persistence, you don't need to make ("add") any changes to your code in order to be able to use and access Cloud Firestore data.
Also according to the official documentation regarding Query's get() method:

By default, get() attempts to provide up-to-date data when possible by waiting for data from the server, but it may return cached data or fail if you are offline and the server cannot be reached. This behavior can be altered via the Source parameter.

So this is normal behavior. Starting with 2018-06-13 (16.0.0 SDK) is now possible to specify the source from which we want to get data. We can achieve this with the help of the DocumentReference.get(Source source) and Query.get(Source source) methods.
As you can see, we can now pass as an argument to the DocumentReference or to the Query the source so we can force the retrieval of data from the server only, cache only or attempt server and fall back to the cache.
So something like this is now possible:
yourDocRef.get(Source.SERVER).addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
    @Override
    public void onSuccess(DocumentSnapshot documentSnapshot) {
        //Get data from the documentSnapshot object
    }
});

In this case, we force the data to be retrieved from the server only. If you want to force the data to be retrieved from the cache only, you should pass as an argument to the get() method, Source.CACHE. More informations here. I also wrote an article that can help understand more clear the concept:

*

*How to drastically reduce the number of reads when no documents are changed in Firestore?
If you want to get only updated documents, you can view changes between snapshots. An example from the official documentation would be:
db.collection("cities")
    .whereEqualTo("state", "CA")
    .addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(@Nullable QuerySnapshot snapshots,
                @Nullable FirebaseFirestoreException e) {
        if (e != null) {
            Log.w(TAG, "listen:error", e);
            return;
        }

        for (DocumentChange dc : snapshots.getDocumentChanges()) {
            switch (dc.getType()) {
            case ADDED:
                Log.d(TAG, "New city: " + dc.getDocument().getData());
                break;
            case MODIFIED:
                Log.d(TAG, "Modified city: " + dc.getDocument().getData());
                break;
            case REMOVED:
                Log.d(TAG, "Removed city: " + dc.getDocument().getData());
                break;
            }
        }

        }
    });

See the switch statement for every particular case? The second case will help you get only the updated data.

In my Recyler View I want the data to be order by a field date not by lut(last-modified-time)

In this case you should create a query that allow you order the results by a specific date property. Assuming you have a database structure that looks like this:
Firestore-root
   |
   --- items (collection)
        |
        --- itemId (document)
             |
             --- date: Oct 08, 2018 at 6:16:58 PM UTC+3
             |
             --- //other properties

The query like will help you achieve this:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionRefference itemsRef = rootRef.collection("items");
Query query = itemsRef.orderBy("date", Query.Direction.ASCENDING);

This is also a recommended way on which you can add a timestamp to a Cloud Firestore database.

With FireStore Snapshot Listener i can't query such a large record set.

Oh, yes you can. According this answer, Firebase can effectively loop through billions items. This answer is for Firebase realtime database but same principles apply to Cloud Firestore.

A: I think you should use this package for that case:
firestore_cache
The only way to use it is to add one more document named as "status" inside the collection you want to get data from. For example, you want to get data from User collection, then you need to add document "status" ["User/status"] with a field: "updatedAt" and value which is written like this:
updatedAt: admin.firestore.FieldValue.serverTimestamp()
So every time we want to add, update or delete data in current collection, we must update that field above. Otherwise, your app won't update the data automatically. Read the documentation very well.


text:
Q: Is it true that Lebesgue's differentiation theorem follows from Lebesgue's density theorem? Let $(X,d)$ be a separable complete metric space and $\mu$ a probability measure on the Borel subsets of $(X,d)$. Suppose that the Lebesgue's density theorem holds, i.e. that for each Borel set $A$ of $(X,d)$ it holds that
$$\lim_{r\to0^+}\frac{\mu(A\cap\bar{B}_r(x))}{\mu(\bar{B}_r(x))}=1$$
for $\mu$-almost all $x\in A\cap\operatorname{supp}(\mu)$, where $\operatorname{supp}(\mu)=\{x\in X : \forall r>0, \mu(\bar{B}_r(x))>0\}$.

Question: is it true that Lebesgue's differentiation theorem holds in $(X,d,\mu)$, i.e. that for each $f\in L^1(\mu)$,  $$\lim_{r\to0^+}\frac{1}{\mu(\bar{B}_r(x))}\int_{\bar{B}_r(x)}f\operatorname{d}\mu=f(x)$$
  for $\mu$-almost all $x\in \operatorname{supp}(\mu)$?

I tried to approximate $f$ in $L^1(\mu)$ by a simple function $g$, since it is easy to show that for $g$ simple the theorem holds, so
\begin{align*}
&\left|\frac{1}{\mu(\bar{B}_r(x))}\int_{\bar{B}_r(x)}f\operatorname{d}\mu-f(x)\right| \le \frac{1}{\mu(\bar{B}_r(x))}\int_{\bar{B}_r(x)}|f-g|\operatorname{d}\mu \\
& \quad\quad\quad\quad + \left|\frac{1}{\mu(\bar{B}_r(x))}\int_{\bar{B}_r(x)}g\operatorname{d}\mu-g(x)\right|+|g(x)-f(x)|,
\end{align*}
and then the middle term tends to zero for $\mu$-almost all $x\in\operatorname{supp}(\mu)$. Also Tchebychev allows us to treat the term $|f(x)-g(x)|$. But when trying to estimate the first term it seems that we need a maximal function estimate in terms of $L^1(\mu)$ norm. Now, if we work in $\mathbb{R}^d$ we can rely on Besicovitch covering theorem, but in our context this theorem doesn't hold in general. So I'm wondering if there is any other way to attack this problem without assuming any extra hypothesis... Any ideas?


text:
Q: When does RTCIceConnectionState.closed get fired From Mozilla doc it says

"closed": The ICE agent for this RTCPeerConnection has shut down and is
no longer handling requests.

When or how does a RTCPeerConnection gets shut down

A: This state will in general not fire. The only way to reach it is to call the close() method on the RTCPeerConnection and calling close will not fire events. Try this:
const pc = new RTCPeerConnection();
pc.close();
pc.iceConnectionState;


text:
Q: Phonegap add plugin fails (errno 34) */plugin.xml When I add a plugin to a 3.0.0 phonegap project with an android platform, I have an error eventhough a bunch of files for the plugin are added. In addition to that error when I add it, the Android manifest never gets updated with the right authorizations.
$ cordova plugin ls

No plugins added. 'Use cordova plugin add <plugin>'.

$ sudo cordova plugin add "http://git-wip-us.apache.org/repos/asf/cordova-plugin-media-capture.git"

{ [Error: ENOENT, no such file or directory '/tmp/plugman-tmp1375200648427/*/plugin.xml']

  errno: 34,

  code: 'ENOENT',

  path: '/tmp/plugman-tmp1375200648427/*/plugin.xml',

  syscall: 'open' }

$ cordova plugin ls

[ 'org.apache.cordova.core.media-capture' ]

A: I was having the same problem with the Connection plugin. Once I changed from "cordova plugin add" to "phonegap local plugin add", it worked fine.
$ phonegap local plugin add http://git-wip-us.apache.org/repos/asf/cordova-plugin-media-capture.git

A: I had the same problem, after some debugging and testing I finally solved the problem:

*

*Open
C:\Users\<user>\AppData\Roaming\npm\node_modules\cordova\node_modules\plugman\src\util\plugins.js.

*Find var cmd = util.format('git clone "%s" "%s"', plugin_git_url,
path.basename(tmp_dir)); (line 42 ATM)

*Replace it with var cmd = util.format('git clone "%s"
"%s"', plugin_git_url, tmp_dir);.
This will make git clone clone to the absolute tmp path instead of the relative.

A: I received a similar error.  I resolved the issue by removing the media-capture plugin, installing the file plugin, then reinstalling the media-capture plugin
cordova plugin rm  org.apache.cordova.media-capture
cordova plugin add org.apache.cordova.file
cordova plugin add org.apache.cordova.media-capture

Maybe media-capture is dependent on the file plugin.

A: I was also facing the same error :
Suppose if you want to add camera plugin then instead of giving:
cordova plugin add cordova-plugin-camera
use
phonegap plugin add cordova-plugin-camera
and then it will work fine

A: It turns out i had something really strange with my proxy. Possibly some data compression on the fly which made the data corrupt. Tethering from the phone solved the issue, after completely uninstalling cordova.


text:
Q: Moment Generating Function of Y f(x,y)=8xy       for 0

What will be the MGF of Y?
Do I need to insert the marginal density function for Y in the formula for MGF?
Also, what will be the limits? Will it be from x to 1 or from 0 to 1?

A: From the question "Also, what will be the limits? Will it be from x to 1 or from 0 to 1?" I will assume that the proper joint density is
$$
f_{X,Y}(x,y) = 8xy\cdot\mathsf 1_{0<x<y<1}.
$$
To find the moment-generating function of $Y$, we first need to determine its marginal distribution. To do this, we integrate over all possible values of $X$:
$$
f_Y(y) = \int_0^y8xy\ \mathsf dx = 4y^3\cdot\mathsf 1_{(0,1)}(y).
$$
Next we compute the expectation
$$
\mathbb E[e^{tY}] = \int_0^1 e^{ty} 4y^3\ \mathsf dy = \frac{4 e^t (t ((t-3) t+6)-6)+24}{t^4}
$$
(this requires some repeated integration by parts, which I have omitted for brevity.


text:
Q: Why is CMake designed so that it removes runtime path when installing I built my shared library(I use a lib calculating the fibonacci number for example) myself and want to use it in my another c++ project built by CMake
Let's say the shared library and headers located in /path/to/my/lib, the shared library libfib.so is in /path/to/my/lib/lib and the header fib.h is in /path/to/my/lib/include and my own project located in /path/to/my/project
Here is my original CMakeLists.txt:
cmake_minimum_required(VERSION 3.2)
project(learn-lib)
set(CMAKE_CXX_FLAGS "-std=c++11 ${CMAKE_CXX_FLAGS}")
set(FIB_INCLUDE "${FIB_PREFIX}/include")
set(FIB_LIB "${FIB_PREFIX}/lib")
set(EXE mybin)
include_directories(${FIB_INCLUDE})
link_directories(${FIB_LIB})
add_executable(${EXE} main.cpp)
target_link_libraries(${EXE} fib)
install(TARGETS ${EXE} RUNTIME DESTINATION bin)

And I use this script to build and install my project:
mkdir -p build_dir
cd build_dir
cmake -DFIB_PREFIX=/path/to/my/lib \
      -DCMAKE_INSTALL_PREFIX=/path/to/my/project \
      ..
make
make install
cd ..

Now, after running the install script, I got two executables, one in build_dir, one in the install location path/to/my/project/bin, when running the program in build_dir, everything is fine, but when running the installed program, I get:

./bin/mybin: error while loading shared libraries: libfib.so: cannot open shared object file: No such file or directory

After some searching on google and stackoverflow, I knew it seems that CMake removed the runtime search path that is tied to the executable when building. I now know two ways to get it around:

*

*Add the library path where libfib.so locates to the environment variable LD_LIBRARY_PATH

*Add set_target_properties(${EXE} PROPERTIES INSTALL_RPATH_USE_LINK_PATH TRUE) into my CMakeLists.txt
So, my questions are:

*

*Why is CMake designed so? When installing, why would it remove runtime path from executables instead of just copying the built executables to the install destination or whatever keeping the link path for the installed program?

*Which way is the best practice(or is there a best practice) to eliminate this problem? To set the environment or to add set_target_properties(...) into CMakeLists.txt ?

A: You may want to look into CMake's RPATH handling settings
This quote in particular seems relevant to your predicament:

By default if you don't change any RPATH related settings, CMake will link the executables and shared libraries with full RPATH to all used libraries in the build tree. When installing, it will clear the RPATH of these targets so they are installed with an empty RPATH.

You can set the RPATH that is set for installed binaries using the CMAKE_INSTALL_RPATH variable, for example:
SET(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib")

and you can also disable the RPATH stripping during installation:
SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)

A: I just want to answer question 1. The why this is done. Alex already posted a solution how to change this behaviour.
The reason is that when you build it you really want to use the libraries the build script saw on your machine. If you build a whole stack of libraries for your app you want no mistake that they aren't picked by the library. Therefore it makes sense to use the full rpath to the library. Also you never move your application around between compilation and when it's debugged and run.
But when installed the usual case in the unix world was to use the shared /usr/lib and /usr/local/lib directories. They are usually picked up (unless LD_LIBRARY_PATH is used) and thats normally what you want.
As you see by my wording, all this is a mess because it includes so many implicit decisions how you organize your build and your deployment. It is one of the reasons why the term 'DLL hell' once only popular on Windows moved over to Unix when it became more widely used. There is no technical solution because its not a technical problem (that part is solved). Its an organizational problem and CMake has to decide about the one flavour it supports on a platform by default. And IMHO they have choosen wisely.


text:
Q: Batch file to copy and rename .pdf files I have a set of files, generated daily, called e.g.
01234fileA.pdf
01234SecondFile.pdf
01234Final.pdf

that I need to copy to a separate directory. The numbers at the front of the file name indicate the run number producing the files, and so will A) match one another and B) always be five characters. Then I need to map the remainder of the file names to static, but different, file names:
fileA.pdf -> A_File.pdf
SecondFile.pdf -> File_Number_Two.pdf
Final.pdf -> Grand_Finale.pdf

I'm thinking that I want a for loop to cruise through the .pdf files in the folder and select the max of the leading numbers. Then I would want to take the remainder of the file name and individually map each (there are only six) to its destination. Seems like a simple enough batch process but I am hung up.
Any help is appreciated!

A: @ECHO OFF
SETLOCAL
:: Set source and destination directories (can be same...)
SET sourcedir=c:\sourcedir
SET destdir=c:\destdir
FOR /f "delims=" %%i IN ('dir /b /a-d "%sourcedir%\*.pdf" ') DO CALL :moveme "%%i"
GOTO :EOF

:moveme
SET destd=%~1
SET destf=%destd:~5%
SET destd=%destd:~0,5%
IF /i "%destf%"=="filea.pdf" SET destf=A_File.pdf
IF /i "%destf%"=="Secondfile.pdf" SET destf=File_Number_Two.pdf
IF /i "%destf%"=="Final.pdf" SET destf=Grand_Finale.pdf
ECHO MD "%destdir%\%destd%" 2>NUL
ECHO COPY /B "%sourcedir%\%~1" "%destdir%\%destd%\%destf%"
GOTO :eof

This should do what you've asked. All you need do is alter the source directory setting and the destination directory (which would be the parent of the subdirectories to be created)
Each filename matching the mask is processed by the :moveme routine. This sets the destination filename destf to all-but-the-first-5 characters, and directory to the first 5 characters of the name supplied.
Since you say there is a restricted list of name-transformations you want, all you need to do is follow the bouncing ball for the remaining three. The /i makes the comparison case-insensitive.
Finally, the directory is created - the 2>nul will suppress the 'directory already exists' message, and the file copied to the new name.
Note that these last two operations are merely ECHOed to the console - you'd need to remove the ECHO keyword after you've verified that the command works correctly.
It may be a good idea to add >nul (note : >nul, not 2>nul) to the end of the COPY command. >nul here suppresses the '1 file copied' message; 2>nul would suppress any error messages...
And the moveme routine was so named because I subconciously expected to MOVE rather than COPY the files. COPY /B would make a COPY of the file (duh) but leave the original in the source directory. Replaceing COPY /B with MOVE would transfer the file from source to the destination.


text:
Q: Probability of getting "tails-tails" for the first time.

A fair coin is tossed until the coin lands "tails-tails" (i.e. a tails followed by a tails) for the first time. Let $X$ counts the number of tosses required. Find the probability of the event $X=n.$  What will be the expectation of $X$?

I think this problem has to be solved by recursion but I find difficulty to solve this. Any suggestions regarding this will be highly appreciated.
Thank you very much for your valuable time.
EDIT $:$  If got "tails-tails" for the first time in $n$ steps. Then the first two steps will be either $HH$ or $HT$ or $TH.$ If the first two tosses will yield either $HH$ or $TH$ then we follow the previous step. If it yields $HT$ in the first two steps then the next two steps will be either $HH$ or $HT$ and we go on like that.
We know that $\Bbb E(X) = \Bbb E(X \mid A) \Bbb P(A) + \Bbb E(X \mid A^c) \Bbb P(A^c).$
So in this case we can write $\Bbb E(X) = \Bbb E(X \mid H) \Bbb P(H) + \Bbb E(X \mid T) \Bbb P (T).$
Now $$\Bbb E(X \mid H) = \Bbb E(X) + 1, \Bbb P(H) = \frac 1 2.$$ What is $\Bbb E(X \mid T)$? $$\Bbb E(X \mid T) = \Bbb E((X  \mid T) \mid TH) \Bbb P (TH \mid T) + \Bbb E((X \mid T) \mid TT) \Bbb P(TT \mid T).$$ Now $$\Bbb E((X  \mid T) \mid TH) = 1 + \Bbb E(X \mid H) = 2 + \Bbb E(X).$$ and $$\Bbb E((X \mid T) \mid TT) = 2.$$ Also $$\Bbb P(TH \mid T) = \Bbb P(TT \mid T) = \frac 1 2.$$ So we get $$\Bbb E (X \mid T) = \frac 1 2 \Bbb E(X) + 2.$$ Putting all these together we get $\Bbb E(X) = 6.$
Where have I done mistake? Would you please check it?

A: Hints:
Let $g_n$ be the number of sequences of length $n$ made up of $H$ and $T$ (heads and tails) that contain no two consecutive tails. Then the sequence you want is such a sequence (but of length $n - 2$) followed by $TT$. Assume you know the value of $g_n$ in general. In terms of $g_{n - 3}$, what is the desired probability?
Now, to compute $g_n$, consider how we can obtain a such a sequence of length $n$ from a similar sequence of smaller length. Suppose you're given a sequence of length $n - 1$ that contains no $TT$ (two consecutive tails). Then definitely we can add an $H$ to the end of this sequence to get a valid sequence of length $n$? How many such sequences are there (in terms of the unknown $g_k$)? Does this not count all valid sequences ending in $H$?
So that leaves valid sequences of length $n$ ending in $T$. How shall we get such a sequence? Well, if the last term is $T$, then certainly the term before that must be $H$ (for otherwise we would have $TT$ at the end). So what we want is a valid sequence of length $n - 1$ that ends in $H$. How many such sequences are there (again in terms of the unknown $g_k$)?
Adding the above two should give a recurrence relation for $g_n$. The base cases are $g_0 = ???$ and $g_1 = ???$.
You can also easily convert this into a recurrence relation for the desired probability itself.

Full Solution:
The recurrence relation for $g_n$, the number of $H$-$T$ sequences of length $n$ that contain no $TT$ (consecutive tails)$ is
$$g_n = g_{n - 1} + g_{n - 2};\ g_0 = 1,\ g_1 = 2.$$
A sequence of length $n$ that ends in $TT$ and has no two consecutive tails before that is of the form $G_{n-3}HTT$, where $G_{n-3}$ is a sequence of length $n - 3$ with no consecutive tails. The probability of a sequence of $n$ tosses ending in $TT$ at the last two tosses for the first time is therefore
\begin{align*}
p_n & = \dfrac{g_{n-3}}{2^n}\\
& = \dfrac{g_{n-4} + g_{n-5}}{2^n}\\
& = \dfrac {p_{n-1}} 2 + \dfrac {p_{n-2}} 4
\end{align*}
with base cases $p_2 = \dfrac 1 4$, $p_3 = \dfrac 1 8$.
Then the expected number of tosses is $\sum\limits_{n = 2}^\infty n\, p_n$. To compute this using the recurrence relation that we already have for $p_n$,
\begin{align*}
n p_n &= \dfrac n 2 p_{n - 1} + \dfrac n 4 p_{n - 2} \\
&= \dfrac {1} 2 (n - 1) p_{n - 1} + \dfrac 1 2 p_{n-1}  + \dfrac{1} 4 (n - 2)p_{n - 2} + \dfrac 2 4 p_{n-2}
\end{align*}
Now, we sum this up from $n = 4$ to $\infty$. Note that $\sum p_n = 1$. Thus,
\begin{align*}
\mathbb E[X] - 3 p_3 - 2 p_2 &= \dfrac 1 2 (\mathbb E[X] - 2 p_2) + \dfrac 1 2 (1 - p_2) + \dfrac 1 4 \mathbb E[X] + \dfrac 1 2 \implies\\
\mathbb E[X] &= 6.
\end{align*}

A: Let $h(n)$ denote the number of sequences of length $n$ that end with $H$ and don't contain $TT$. Since $h(n) = h(n-1)+h(n-2)$ and the base cases of $h(n)$ are $h(1) = 1$ and $h(2) = 2$, this is the Fibonacci sequence, $$h(n) = \frac{({\frac{1+\sqrt{5}}{2}})^{n+1}-{(\frac{1-\sqrt{5}}{2}})^{n+1}}{\sqrt{5}}$$
On another track,
$$\Bbb P(X = n) = \frac{h(n-2)}{2^{n}}$$. Plugging the explicit formula of $h(n)$ into the above probability and simplifying finds that $$\Bbb P(X = n) = \frac{({\frac{1+\sqrt{5}}{4}})^{n-1}-{(\frac{1-\sqrt{5}}{4}})^{n-1}}{2\sqrt{5}}$$ Using two infinite arithmetico-geometric sums, the expected value is found to be 6. Note: the expected value could also be found by Ned's method in an earlier comment of $E = \frac{1}{2}*(E+1)+\frac{1}{4}*(E+2)+\frac{1}{4}*2$. Solving for $E$ finds that $E = 6$.


text:
Q: Content Query WebPart Error while executing web part: System.NullReferenceException: I am trying to add the following content by query webpart programatically but I have the error below
#region Last updated documents
                            ContentByQueryWebPart cqwp = new ContentByQueryWebPart();
                            cqwp.ContentTypeBeginsWithId = "0x0101008E49C3D400044AB3A2F1DD14073E74F6001D06D12572244BE3A11AAEE3ED60F576";
                            cqwp.WebUrl = SPContext.Current.Web.ServerRelativeUrl;
                            cqwp.Title = "Last Updated Documents";
                            string query = @"<OrderBy> "+
                                                "<FieldRef Name='Modified'  Ascending='FALSE'/> "+
                                            "</OrderBy>";
                            cqwp.QueryOverride = query;
                            cqwp.ItemLimit = 10;
                            cqwp.ListsOverride =  "<Lists ServerTemplate='101'/>";
                            cqwp.WebsOverride = "<Webs Recursive='False' />";

                            cqwp.MainXslLink = SPUtility.ConcatUrls(SPContext.Current.Web.ServerRelativeUrl, "/Style Library/XSL Style Sheets/ContentQueryMain.xsl");
                            cqwp.HeaderXslLink = SPUtility.ConcatUrls(SPContext.Current.Web.ServerRelativeUrl, "/Style Library/XSL Style Sheets/Header.xsl");
                            cqwp.ItemXslLink = SPUtility.ConcatUrls(SPContext.Current.Web.ServerRelativeUrl, "/Style Library/XSL Style Sheets/ItemStyle.xsl");

                            cqwp.ViewFieldsOverride = @"<ViewFields> " +
                                                            "<FieldRef Name='DocIcon'/>"+
                                                            "<FieldRef Name='FileLeafRef' />" +
                                                            "<FieldRef Name='ContentType'/> " +
                                                            "<FieldRef Name='Modified'/> " +
                                                            "<FieldRef Name='Editor'/> " +
                                                        "</ViewFields>";

                            mgrPageManager.AddWebPart(cqwp, "Footer", 0);
                            mgrPageManager.SaveChanges(cqwp);
                        #endregion

Error while executing web part: System.NullReferenceException: Object reference not set to an instance of an object.
 at Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart.AddViewFieldsFromOverride()
 at Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart.buildCrossListQueryInfo()
 at Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart.IssueQuery()
 at Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart.GetXPathNavigator(String viewPath)
 at Microsoft.SharePoint.WebPartPages.DataFormWebPart.PrepareAndPerformTransform(Boolean bDeferExecuteTransform)

A: A wild, or not so wild, guess:
Your <FieldRef Name='Modified By' Nullable='True' Type='Text'/> could be the cause of the problem. SharePoints internal column names do not ever contain blanks.
I think the internal or static name is actually Editor
EDIT:
Per MSDN the correct format for this parameter is:
"Title,Text;ID,Counter;Editor,User"

So, Column name, Type;


text:
Q: Gridview Footer Not an Instance I'm trying to get an Automatic ID filler for a gridview footer text box, but every time I run I get the "Not Referred Instance of an object" meaning the method isn't finding the Text box, Right?
But I have the same text box in other method and is working correctly, what its wrong?
Below is the code sample of GridView
   <asp:GridView ID="GridView1" runat="server" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black" AutoGenerateColumns="False" ShowFooter="True">
            <Columns>
                <asp:TemplateField HeaderText="ID UNIDAD">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ID_UNIDAD") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtAddID" runat="server" ></asp:TextBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lbl_ID" runat="server" Text='<%# Bind("ID_UNIDAD") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="UNIDAD">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("NOMBRE") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtNombre" runat="server" ></asp:TextBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lbl_Nombre" runat="server" Text='<%# Bind("NOMBRE") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                   <asp:TemplateField HeaderText="FRACCIONES">
                    <EditItemTemplate>
                        <asp:CheckBox ID="TextBox3" runat="server" Checked='<%# Bind("FRACCIONES") %>'></asp:CheckBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:CheckBox ID="chkFraccion" runat="server" ></asp:CheckBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:CheckBox ID="lbl_Fraccion" runat="server" Checked='<%# Bind("FRACCIONES") %>' ></asp:CheckBox>
                    </ItemTemplate>
                </asp:TemplateField>
                   <asp:TemplateField HeaderText="CLAVE SAT">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("CLAVE_SAT") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtClave" runat="server" ></asp:TextBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lbl_Clave" runat="server" Text='<%# Bind("CLAVE_SAT") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <FooterTemplate>
                        <asp:ImageButton ID="Agregar" runat="server" ImageUrl="~/assets/iconos/add.ico" OnClick="Agregar_Click" />
                    </FooterTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#CCCCCC" />
            <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
            <RowStyle BackColor="White" />
            <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F1F1F1" />
            <SortedAscendingHeaderStyle BackColor="#808080" />
            <SortedDescendingCellStyle BackColor="#CAC9C9" />
            <SortedDescendingHeaderStyle BackColor="#383838" />
        </asp:GridView>

Below is the code sample for binding the grid in code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.HtmlControls;
using System.Windows.Input;

public partial class Default2 : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Integral Database"].ToString());
    string query;
    string countid = " ";
    SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["Integral Database"].ToString());
    string connStrr = ConfigurationManager.ConnectionStrings["Integral Database"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)

            llenagrid();
        IncrementoID();
    }

    public void llenagrid()
    {
      DataTable table = new DataTable();
      using (SqlConnection conn = new SqlConnection(connStrr))
      {
          string sql = "SELECT id_unidad, nombre, fracciones, clave_sat from unidades";
            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {
                using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
                {
                    ad.Fill(table);
                }
           }
       }
      IncrementoID();
  GridView1.DataSource = table;
  GridView1.DataBind();
    }

    protected void Agregar_Click(object sender, ImageClickEventArgs e)
    {
        connStr.Open();
        GridViewRow row = GridView1.FooterRow;
        TextBox txtNombre = (TextBox)row.FindControl("txtNombre");
        string str = "select count(nombre) from unidades where nombre like '"+txtNombre.Text+ "'";
        SqlCommand com = new SqlCommand(str,connStr);
        int count = Convert.ToInt32(com.ExecuteScalar());
        connStr.Close();
        if (count > 0)
        {
            string script = "alert('Este Nombre ya Existe.','Atención');";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "testScript", script, true);
        }
        else
        {
            connStr.Open();
            TextBox txtID = (TextBox)row.FindControl("txtAddID");
            CheckBox chkFracc = (CheckBox)row.FindControl("chkFraccion");
            TextBox txtClave = (TextBox)row.FindControl("txtClave");
            string ID = txtID.Text;
            string Nombre = txtNombre.Text;
            bool Fracc = chkFracc.Checked;
            string clave = txtClave.Text;
            string query2 = "Insert into unidades values('" + ID + "','" + Nombre + "','" + Fracc + "','" + clave + "')";
            SqlCommand cmd2 = new SqlCommand(query2, connStr);
            cmd2.ExecuteNonQuery();
            connStr.Close();
            llenagrid();
            IncrementoID();
        }

     }

    public void IncrementoID()
    {
        //query = "select Count(id_unidad) from unidades";
        //con.Open();
        //SqlCommand cmd = new SqlCommand(query, con);
        //string cid = cmd.ExecuteScalar().ToString();
        //con.Close();
        //TextBox ID = (TextBox)GridView1.FooterRow.FindControl("txtAddID");
        //ID.Text = countid + (int.Parse(cid) + 1);
        //ID.ReadOnly = true;

        con.Open();
        SqlCommand cmd = new SqlCommand("select MAX (CAST( ID_UNIDAD as INT)) from unidades",con);
        SqlDataReader rd = cmd.ExecuteReader();
        TextBox txtID = ((TextBox)GridView1.FooterRow.FindControl("txtAddID"));
        if (rd.Read())
        {
            string Value = rd[0].ToString();
            if (Value == "")
            {

                txtID.Text = "1";
            }
            else
            {
                txtID.Text = rd[0].ToString();
                txtID.Text = (Convert.ToInt64(txtID.Text) + 1).ToString();
            }
        }
        con.Close();
    }

    }

As you can see, in the insert method it finds the gridview textbox (txtAddID) and when I try to use the same exact syntax in the IncrementoID Method it doesn't work.

A: Here is the problem in the method llenagrid(), before binding GridView you are trying to access the control that are in Gridview (inside method IncrementoID), So it's giving error as Not Referred Instance of an object means the Object you are trying to access is not yet referenced. Below code sample can help you out:
public void llenagrid()
  {
          DataTable table = new DataTable();
          using (SqlConnection conn = new SqlConnection(connStrr))
          {
              string sql = "SELECT id_unidad, nombre, fracciones, clave_sat from unidades";
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
                    {
                        ad.Fill(table);
                    }
               }
           }
      //IncrementoID(); // Remove the function call from here
      GridView1.DataSource = table;
      GridView1.DataBind();
      IncrementoID();  // Call the function after GridView got binded.
   }


text:
Q: Disable GRUB boot manager from Windows 8 I decided to get rid of the Fedora installation on my hard drive by deleting the partitions and extending my windows partition. To repair the boot loader I used a Windows recovery disc and command prompt and ran bootrec.exe /fixmbr. My problem is that the GRUB bootloader still persists giving me the option to boot into my non-existent Fedora partition. Any ideas on removing it?
Update: Removing Fedora using EasyBCD fixed the problem.

A: It seems like that's something that you should be able to accomplish using EasyBCD (free for non-commercial use) to modify the bootloader. According to this post looking to do a similar thing, writing a new MBR using EasyBCD worked in Windows 7, so the equivalent thing should work today.