How can I commit changes to a theme?

Question: I worked on Omega-7.x-3.0-alpha1 and added some fixes to fluid style sheets in rtl mode.
How can I commit them to the drupal.org repository?
Answer: Unless you are one of the maintainers or have been explicitly granted write access to the repository, you will not be able to push your commits to the "official" branches.
The recommended route to contribute is the following:

Checkout the git repository for the correct branch (instructions here)
Create  patch with your changes (instructions in the above link)
Search for a relevent issue or create a new one in the project's issue tracker on Drupal.org
Submit the patch in the issue
Comment: For more information, see also http://drupal.org/contribute/development and the pages below.
Comment: where is checkout link?
Comment: its the first link: git clone --branch 7.x-3.x http://git.drupal.org/project/omega.git

How can I commit changes to a theme?


Triggering Custom Functionality in Django Admin

Question: I'm new to Django, and Django Admin, so I'm still not 100% with the correct names for things.
I want to add a "Download All" button/link/action to the list view when using the Admin app for a Model. Ideally just like the "Add" button. I tried a custom action, which almost got me there, but it is insisting I select at least one row before it will trigger.
I'm very focused on delivering results fast here - as long as I can explain to my users how to use the app - then job done.
I'm using Django 1.9.
Comment: You would need to override the django admin change_list.html and keep a copy of this in you app/templates/app folder to add an button or link. Than this link should have url and callable to trigger an action. Hope this help
Answer: step1: First override the change_list.html which is at /app/templates/admin/app/change_list.html.(if it's not there create one)
The contents of change_list.html will look like
{% block object-tools %}
    {% if has_add_permission %}

            {% block object-tools-items %}

                    Export Data

                    {% blocktrans with cl.opts.verbose_name as name %}Add {{ name }}{% endblocktrans %}

            {% endblock %}

    {% endif %}
{% endblock %}

step2: In admin.py for this form add get_urls method
def get_urls(self):
    urls = super(classname, self).get_urls() # replace wit your class name
    my_urls = patterns(
        '',
        url(r'^export/$',
            ExportCampaignView.as_view(), name='export'),
    )
    return my_urls + urls

step3: In views.py add this logic to download the file
XLSX_CONTENT_TYPE = ('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

class ExportCampaignView(generic.View):

    def get(self, request, *args, **kwargs):
        xlsx_file = self.create_xlsx()
        response = HttpResponse(xlsx_file, content_type=XLSX_CONTENT_TYPE)
        response['Content-Disposition'] = (
            'attachment; filename=campaign.xlsx')
        return response

    @staticmethod
    def create_xlsx():
        """
        :return tablib.Dataset: Campaign data.
        """
        output = StringIO()
        workbook = xlsxwriter.Workbook(output)
        sheet = workbook.add_worksheet()
        bold_with_bg = workbook.add_format(
            {'bold': True, 'bg_color': 'silver'})
        date_format = workbook.add_format({'num_format': 'dd.mm.YYYY'})

        headers = [
            _(u'col1'), _(u'col2'), _(u'col3'),

        ]

        data = Model.objects.all()

        for row_idx, row in enumerate(data, start=1):
            sheet.write(row_idx, 0, row.col1)
            sheet.write(row_idx, 1, row.col2)
            sheet.write(row_idx, 1, row.col3)

        workbook.close()
        output.seek(0)
        return output

Comment: Nice, just change the grappelli classes (grp-add-link), to the regular django-admin ones, and logic can be in the admin class not the view :)


Alternative Proof: If $(x_n)$ is bounded and diverges, then there exist two subsequences of $(x_n)$ that converge to different limits

Question: I know other proofs of this exist, but how can continue with this proof with $\epsilon$-neighborhoods?
Let $(x_n)$ be bounded but divergent. By the Bolzano–Weierstrass Theorem (BWT), $(x_n)$ contains a convergent subsequence, $(b_n)$.
Let $(b_n)\to L$.
So, $\forall \epsilon \gt0 \exists N \in \mathbb{N}: \forall n \gt N |b_n -L| \lt \epsilon$.
If there exists an $N'$ such that for all $n\gt N' |x_n -L| \lt \epsilon$, then $(x_n)$ converges - a contradiction.
Here is where I am stuck.
Can I say there exist infinitely many points in the sequences outside the $\epsilon$-neighborhood without using the infinite extraction method found in other proofs for this?
Comment: There must be some $\epsilon > 0$ such that the $\epsilon$-neighborhood centered at $L$ excludes infinitely many $x_n$, hence you can construct a subsequence of $x_n$ that stays outside that neighborhood. That subsequence has a convergent sub-subsequence...
Answer: $(x_n)$ converges to $L$ precisely when for all $\epsilon>0$ all but finitely many terms fall inside $B_\epsilon(L)$. For $(x_n)$ to not converge to $L$ it means there is some $\epsilon>0$ such that infinitely many terms of the sequence lie outside $B_\epsilon(L)$. Let us denote this subsequence by $(a_n)$. Now $(a_n)$ is also bounded and has a convergent subsequence $(y_n)$. Since $(y_n)$ is a sequence in the closed set $B_\epsilon(L)^c$, its limit must also be in the set. So it cannot be $L$.

Alternative Proof: If $(x_n)$ is bounded and diverges, then there exist two subsequences of $(x_n)$ that converge to diﬀerent limits


At what point does an Incompletion become a Fumble?

Question: I was watching an American Football game the other day (can't remember which, but it was a re-run of an older game) and there were two incidences:

The ball is snapped to the QB, he performs a fake hand-off to the RB, and fires a short pass over the top to a receiver. He gets about half a yard before he his tackled by a defender, and from the tackle, the ball comes loose. The ruling on the field was that the pass was incomplete.
Similar play. The ball is snapped to the QB, who trows a quick pass to a receiver, who is again tackled within a yard of receiving the ball, and the ball comes loose. However this time the ruling was that it was a fumble (which was recovered by the offensive team).

What is the reasoning behind the two different calls for such similar incidences?
Comment: @PhilipKendall It's close, but I'd say it is a slightly different question that has an almost identical answer.
Comment: Should maybe be cited as related, but not identical question. The other question is more terminological, while this one is more rules.
Comment: possible duplicate of [What is a "football move" in the NFL?](http://sports.stackexchange.com/questions/7392/what-is-a-football-move-in-the-nfl)
Comment: In particular, the answer to that suggested duplicate explains when a pass is considered complete.
Comment: Both questions are about what makes a pass complete. Perhaps a little judicious editing is in order?
Answer: The difference between an "incompletion" and a "completion followed by a fumble" is in the rules for a completion.
A completion has to meet three criteria:

The receiver needs to gain control of the ball.
The receiver needs to have both feet or any other body part (except hands) on the ground inbounds.
The receiver needs to maintain control of the ball long enough to make a "football move."

If any of these three criteria are not met, it is an incompletion.  If all three are met, it is a completion, and if the ball is dropped, a fumble.
From the 2013 Official Playing Rules of the NFL, 8.1.3:

COMPLETED OR INTERCEPTED PASS
Article 3 Completed or Intercepted Pass. A player who makes a catch may advance the ball. A forward pass is complete
  (by the offense) or intercepted (by the defense) if a player, who is inbounds:
(a) secures control of the ball in his hands or arms prior to the ball touching the ground; and
(b) touches the ground inbounds with both feet or with any part of his body other than his hands; and
(c) maintains control of the ball long enough, after (a) and (b) have been fulfilled, to enable him to perform any act
  common to the game (i.e., maintaining control long enough to pitch it, pass it, advance with it, or avoid or ward off an
  opponent, etc.).
Note 1: It is not necessary that he commit such an act, provided that he maintains control of the ball long enough to do so.
Note 2: If a player has control of the ball, a slight movement of the ball will not be considered a loss of possession. He must
  lose control of the ball in order to rule that there has been a loss of possession.
Answer: An incomplete pass cannot be fumbled, so technically speaking an incomplete pass never becomes a fumble. Rather, we have two scenarios:

The pass was incomplete, in which case it is impossible to fumble it (to fumble you have to have possession).
The pass was complete, in which case it is possible to fumble it.

The criteria for completion, or gaining possession of a passed ball, are nicely outlined in Ben Miller's answer. A fumble is simply defined as a loss of possession. From the NFL rules:

FUMBLE
Article 4
  A Fumble is any act, other than a pass or kick, which
  results in loss of player possession. The term Fumble always implies
  possession.

Emphasis added.
Answer: The accepted answer covers the rules.  I will give you what referees look for.

The two feet on the ground are a given.
A football move means the player is attempting to do something.  So if I jumped as high as I could caught the ball with hands over my helmet and then got rocked as I hit the ground.  That is the most obvious example of an incomplete due to no football move.

So there are basically two points of emphasis on the short-term completion.

Does the referee believe the player had intent to move and did the move start?  This could be as little a player twitching in a direction to start a fake.  This can be really hard to tell for receivers receiving a big hit.
Did the player maintain absolute control the entire sequence?  This is actually what is the difference between a complete and incomplete pass especially with replay in place.  All it takes is a ball to squirm a little in the hands and boom, we need ANOTHER two feet on the ground and ANOTHER football move.
Comment: Well "football move" is really defined as the time to make a move, not the actual making of a move. You could stand there, doing nothing, but if it were long enough for you to do something, then that is enough. From the rules: "It is not necessary that he commit such an act, provided that he maintains control of the ball long enough to do so." (http://sports.stackexchange.com/questions/7392/what-is-a-football-move-in-the-nfl).
Comment: @neuronet - that is fine to note that but that literally never happens.  When discussing a close play this might be 1%.
Comment: Yes, I pointed out a corner case that is likely to happen never. :) It's a conceptual point....


"Summing" linear regression models

Question: I would like to combine regression models where each $Y_i$ is a subset of the total $Y$. The independent variable is the same but not from the same sample. Some illustrating example: say I am interested to estimate the tree density in a city, tree density is negatively related to population density. What I have is:
$Y_1=b_1X$    where $X$ is the population density of some cities and $Y_1$ is the tree density of a certain tree species.
$Y_2=b_2X$ is a similar data set for but a different tree species from some other cities.
What I would like to estimate is the total tree density $Y=Y_1+Y_2$.
I think just summing the result of the two models would overestimate the total number of trees because the proportion between the two species varies among cities. In the most extreme case all trees in acity would be from the same species.
The problem seems not so uncommon, so any keywords that would guide some search would be helpful. It would be just fine if I could estimate the prediction bounds of the total tree density of cities with population density $X$, e.g by randomly drawing from a distribution of a weighting parameter that mixes different fractions of $Y_1$ and $Y_2$
Comment: Why not use multilevel model?
Comment: What I have just learned about multilevel models ist that they can be used for impoving the prediction at lower level by incorporating higher level information i.e. as in my case the climate setting of a city. I could not find an example where this direction is reversed which I think is the problem in this example: making predictions from low-level - trees species for a higher level - all trees.
Comment: First of all: it would let you build a single model for all your data instead assuming that every subsample is totally independent of every other one.
Comment: @robbenhundt Multilevel models are frequently used with post-stratification to generate better higher level forecasts.
Comment: Thank you for providing the key word 'post-stratification' which really helps to dive further into the topic.
Answer: It sounds like a mixed effects/hierarchical regression problem. If $Y_{ij}$ is the number of trees of $i$-th kind in $j$-th city, $X_j$ is the population density of $j$-th city, then the basic model you can think of is
$$
Y_{ij} = \mu + \gamma_i + \beta_{j} X_{ij} + \varepsilon_{ij}
$$
so the intercept $\mu$ is the base population, $\gamma_i$ are intercepts for each of the kinds of trees, and $\beta_j$ are (random) slopes for the cities. This basic model can and possibly should be extended, at least to include interactions as you notice that there are cities that differ in the species of trees that grow in them (so you have effects for kinds of trees nested in cities), or to include other covariates not mentioned by you.
Putting everything in a single model would let you not to worry about arbitrary weighting to sum your estimates since the optimal weighting would be estimated by your model.
If you are not familiar with this kind of models you can check the great introductory book:

Gelman, A. & Hill, J. (2006). Data Analysis Using Regression and
  Multilevel/Hierarchical Models. Cambridge.
Comment: Thanks for the reference and the clarification. I guess I am on the right track now.

"Summing" linear regression models


Applescript - Recursively step through directories

Question: I have found similar solutions like this:
property theOpenFile : missing value

tell application "Finder" to set theSel to selection
if theSel is not {} then
    set pathToYourTextFile to (path to desktop folder as string) & "SampleTextFile2.txt"
    set theOpenFile to open for access file (pathToYourTextFile as string) with write permission
    repeat with aItem in theSel
        tell application "Finder" to class of aItem is folder
        if the result then my getFilesIn(aItem) -- aItem is a folder
    end repeat
    close access theOpenFile
end if

on getFilesIn(thisFolder)
    tell application "Finder" to set theseFiles to files of thisFolder as alias list
    repeat with thisFile in theseFiles
        set f to thisFile as string
        set pathLength to length of f
        if pathLength > 255 then my writeToFile(f)
    end repeat
    tell application "Finder" to set theseSubFolders to folders of thisFolder
    repeat with tSubF in theseSubFolders
        my getFilesIn(tSubF) -- call this handler (recursively through this folder)
    end repeat
end getFilesIn

on writeToFile(t)
    write (t & return) to theOpenFile starting at eof
end writeToFile

They all work in with a file reference in alias format. As I understand I cannot change the filename of the original in this case, or delete it, etc. and thats what I want to do.
Am I right ? If yes what else can I do ?
Answer: You can rename and delete files, the Finder can handle alias specifiers
repeat with thisFile in (get theseFiles) -- you need get to capture the reference list
    set f to thisFile as string
    set pathLength to length of f
    if pathLength > 255 then my writeToFile(f)
    tell application "Finder" to set name of thisFile to "foo.txt"
    -- or
    tell application "Finder" to delete thisFile
end repeat

or rather than an alias you can use Finder file specifiers
repeat with thisFile in (get theseFiles)
    set f to thisFile as string
    set pathLength to length of f
    if pathLength > 255 then my writeToFile(f)
    tell application "Finder" to set name of file f to "foo.txt"
    -- or
    tell application "Finder" to delete file f
end repeat


Very basic question about pre-additive category

Question: I am trying to prove whether in a pre-additive category, $0_{Mor(y,z)}\circ f=0_{Mor(x,z)}$ for objects $x,y,z$ and $f\in Mor(x,y)$. Now, by bi-linearity of composition maps $$ 0_{Mor(y,z)}\circ f+ 0_{Mor(y,z)}\circ (-f)= 0_{Mor(y,z)} \circ 0_{Mor(x,y)} $$
Putting $f=0_{Mor(x,y)}\; \;$ we have $\; \; 0_{Mor(y,z)} \circ 0_{Mor(x,y)} =0_{Mor(x,z)}\; \; $and we also get $\; \; 0_{Mor(y,z)}\circ f=-( 0_{Mor(y,z)}\circ (-f))$. But I can't seem to progress any further.
Thanks in advance!
Comment: Bilinearity of composition implies by definition $0\circ f=0$ since the map $-\circ f$ is a homomorphism of groups.
Answer: The answer to your question is basically in asdq's comment, allow me to expand a little.
By bilinearity you have that for $f \in Mor(x,y)$ the mapping
$$
\begin{align*}
-\circ f \colon Mor(y,z) &\to Mor(x,z) \\
x \mapsto x \circ f
\end{align*}
$$
is a group homomorphism, in particular it sends $0_{Mor(y,z)}$ into $0_{Mor(x,z)}$, that is that $0_{Mor(y,z)}\circ f = 0_{Mor(x,z)}$.


LIBXML-RUBY > Xpath context

Question: Context: I'm parsing an XML file using the libxml-ruby gem. I need to query the XML document for a set of nodes using the XPath find method. I then need to process each node individually, querying them once again using the XPath find method.
Issue: When I attempt to query the returned nodes individually, the XPath find method is  querying the entire document rather than just the node:
Code Example:
require 'xml'

string = %{<?xml version="1.0" encoding="iso-8859-1"?>
<bookstore>
  <book>
    <title lang="eng">Harry Potter</title>
    <price>29.99</price>
  </book>
  <book>
    <title lang="eng">Learning XML</title>
    <price>39.95</price>
  </book>
</bookstore>}

xml = XML::Parser.string(string, :encoding => XML::Encoding::ISO_8859_1).parse
books = xml.find("//book")
books.each do |book|
    price = book.find("//price").first.content
    puts price
end

This script returns 29.99 twice. I think this must have something to with setting the XPath context but I have not figured out how to accomplish that yet.
Comment: I'd highly recommend using Nokogiri for your XML parsing. It's the defacto standard for Ruby.
Comment: I actually started out using Nokogiri and ran into the same exact problem. I switched to libxml-ruby hoping that things would be different there but the same issue persists.
Comment: Well... when the problem follows you you know it's not in the library. :-) Been there, done it too many times to remember. Stick with Nokogiri; It rocks.
Answer: The first problem I see is book.find("//price").
//price means "start at the top of the document and look downward. That's most certainly NOT what you want to do. Instead I think you want to look inside book for the first price.
Using Nokogiri, I'd use CSS selectors because they're more easy on the eyes and can usually accomplish the same thing:
require 'nokogiri'

string = %{<?xml version="1.0" encoding="iso-8859-1"?>
<bookstore>
  <book>
    <title lang="eng">Harry Potter</title>
    <price>29.99</price>
  </book>
  <book>
    <title lang="eng">Learning XML</title>
    <price>39.95</price>
  </book>
</bookstore>}

xml = Nokogiri::XML(string)
books = xml.search("book")
books.each do |book|
    price = book.at("price").content
    puts price
end

After running that I get:
29.99
39.95

Comment: Ah, you're right. I was had incorrectly assumed that would cause the query to start at the top of the node, rather than the document. The issue is resolved by simply removing the "//" in front of price. Thanks for your help!
Comment: Correct. That's one of the reasons I prefer CSS. The slashes in XPath make my brain tired.

LIBXML-RUBY > Xpath context


What is the integral homology of the free commutative monoid on a space?

Question: The Dold-Thom construction on a space is its free commutative monoid. Its homotopy groups are isomorphic to the integral homology groups of the original space. What are the integral homology groups of the Dold-Thom construction?
Answer: The Dold-Thom construction of a connected CW-complex $X$ is a product of Eilenberg-Maclane spaces so its homology groups are those of a product of Eilenberg-Maclane space which are determined by a Kunneth formula.
One basic example to see is the Dold Thom construction of a circle which is homotopy equivalent to a circle and also the examples of spheres more generally.
Of course, the Dold-Thom construction which is also called the infinite symmetric product construction $SP^{\infty}$ is a homotopy functor, meaning that we can compute the integral homology of infinite symmetric products of "simpler" spaces if these spaces are homotopy equivalent.
Comment: That's a great answer! Let me remark that Walid is using the fact that a connected topological commutative monoid is weakly equivalent to a product of Eilenberg-Maclane spaces.


Terminal like app in PySide

Question: I am making an application in PySide and I want to add a Console/Terminal like screen, where you have a prompt and you can type commands.  How would I be able to accomplish this.  I am guessing some combination of QPlainTextEdit/QTextEdit for the output and QLineEdit for the actual prompt. Is there a better way to do this?
Answer: You could check out Spyder. They use PyQt (which is similar) and have a terminal. I think you can import their terminal widget, but I haven't played with it.
https://code.google.com/p/spyderlib/
Also, it is my favorite python editor by far!
I've spent a fair deal of time trying to find something like this, but to no avail. Good luck!
Answer: I did this with a custom QPlainTextEdit and custom QLineEdit. I also had an indicator label that would display ">>>" on the terminal to show user input. It needs more work. The best way would be to create your own custom widget based off of a QTextEdit and your own io handler. Below is an example of my execute method with self.input being the QLineEdit and self.view being the QTextEdit. It should get you the general idea.
<code>import io, subprocess, shlex, code, rlcompleter, platform

def execute(self, currentText=None):
    """Execute runs the command given based on the console type.

    If the console type is "both" then execute will run python commands
    unless the user give the input ::os::command or ("::(platform.syste())::command").
    Otherwise the console type will determine the what the input will execute with.

    Args:
        currentText(str): Text to execute. None will run the text from the QLineEdit self.input.
    """
    # Check for given text
    if currentText is None:
        currentText = self.input.text()
        self.input.clear()
        self.view.display(currentText, "input")
    else:
        cmd = re.search("^>>>", currentText) # search for start only
        if cmd is None:
            currentText = ">>>" + currentText
        else:
            self.view.display(currentText, "input")
    # end

    # Variables
    self.completer.clear()
    cmdString = re.sub("^>>>", "", currentText)
    result = None
    displayType = "output"
    run, cmdString = self.getRunType(cmdString)

    try:
        # Check where the output is going
        sys.stdout = self.out = io.StringIO()
        sys.stderr = sys.stdout

        if run == "python": # Run python command
            result = self._runInterpreter(cmdString)
            displayType = "python"

        elif run == "os": # Run os command
            result = self._runSubprocess(cmdString)
            displayType = "os"
    except Exception as err:
        result = str(err)
        displayType = "Error"

        notFoundPython = "NameError:" in result and "is not defined" in result
        notFoundWindows = "returned non-zero exit status" in result
        if notFoundPython or notFoundWindows:
            result = "Command not found"
    finally:
        sys.stdout = self.old_stdout
        sys.stderr = self.old_stdout

        self.display(result, displayType)
# end execute

def getRunType(self, cmdString):
    run = self._consoleType

    # Check the run type
    if self._consoleType == "both":
        if re.search("^::python::", cmdString) is not None:
            cmdString = re.sub("^::[a-z]*::", "", cmdString)
            run = "python"

        elif re.search("^(::os::|::"+platform.system()+"::)", cmdString) is not None:
            cmdString = re.sub("^::[a-z]*::", "", cmdString)
            run = "os"
        else:
            run = "python"
    # end

    return run, cmdString
# end getRunType

def _runInterpreter(self, cmdString, outIO=None, run=None):
    # Check for a proper console type
    if(self._consoleType != "both" and self._consoleType != "python"):
        return

    # Get the IO
    if outIO is None:
        outIO = sys.stdout

    # Run python command

    self.interpreter.push(cmdString)

    # Check outIO
    result = "Unreadable buffer: Check python's sys.stdout"
    if isinstance(outIO, io.StringIO):
        result = outIO.getvalue()
    else:
        if outIO.readable():
            result = str(outIO.readlines())

    # Check for error
    if re.search("^Traceback", result) or re.search("[a-zA-z]*Error:", result):
        raise ValueError(result)

    return result
# end _runInterpreter

def _runSubprocess(self, cmdString, run=None):
    # Check for a proper console type
    if(self._consoleType != "both" and self._consoleType != "os"):
        return

    # Run OS command
    cmd = shlex.split(cmdString)
    result = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT).decode("utf-8")

    # Check for error
    if re.search("^Traceback", result) or re.search("[a-zA-z]*Error:", result):
        raise ValueError(result)

    return result
# end _runSubprocess
</code>

Terminal like app in PySide


How to automate PHP 7 installation on Ubuntu 16.04 in Docker?

Question: I am trying to create a Dockerfile to install PHP 7 on Ubuntu 16.04. This is supposed to fully automate the whole installation process. However, during the installation, it prompts me to select a Geographic area, which completely defeats the purpose.
The directive I am using is:
<code>RUN apt-get update && apt-get install -y php
</code>
And here is the prompt:

How can I automate this? Maybe prepare some predefined values for the prompts in some manner?
Note: I am aware of this image link: https://hub.docker.com/_/php/. Unfortunately, the scripts there are overly complicated for me. I just need something nice and simple.
Thanks!
Comment: What method are you using for the installation?
Comment: running `docker run php` is too complicated? and that's why you want to build your own docker image? okay ...
Comment: No. You misunderstood. I meant the scripts in the Docker file links are too complicated. Follow this link and see for yourself: https://github.com/docker-library/php/blob/85af0c14e3f23689f0851d3164ab3b630e7f016f/7.2/stretch/cli/Dockerfile.
Comment: 200+ lines of Dockerfile for installing PHP is overly complicated, for my task at hand (not going into details here) at the moment.
Comment: Well, I can't reproduce your problem. `apt install -y php` installs php without further questions.
Comment: Hence I said "scripts", not the command.
Comment: Probably due to that we are using different distros.
Comment: I've set up an ubuntu 16.04 for the test. installed all current updates. ran `sudo apt install -y php`. It went through without asking about a geographic location.
Comment: Thanks for your effort, sir. I am not sure why it happened on my machine. Posted a screenshot.
Answer: It turns out tzdata is it. The solution in this link works for me: https://stackoverflow.com/questions/44331836/apt-get-install-tzdata-noninteractive.
Comment: This question even has an example with a docker example: https://stackoverflow.com/questions/8671308/non-interactive-method-for-dpkg-reconfigure-tzdata/47909037#47909037
Comment: If you had posted that you have a problem with tzdata instead of php in the first place we could have solved this a lot easier.
Comment: Yes, you are right :)


Location of libcrt sources in VS2017?

Question: they used to ship sources for the C runtime in previous versions of VS. Would someone perhaps know what would be the default location in VS2017? Do they still ship the code with it?
Answer: Ah.. found it in Visual Studio\2017\Community\VC\Tools\MSVC\14.12.25827\crt
I hope the refactored code is as beautiful as the path is long.

Location of libcrt sources in VS2017?


Excel - Tabelas - Identificando a próxima linha

Question: boa tarde. Essa é minha primeira pergunta por aqui. Desde já, agradeço a quem puder me orientar.
Fiz uma planilha com algumas tabelas (aba "Página Inicial", "Formatar como tabela"). Depois, fiz um VBA para limpar essa tabela e inserir novas informações a partir de um arquivo texto. Eu estava utilizando um recurso que é identificar a linha onde está a tabela através do comando Range("Nome da tabela").row. A partir daí, eu incrementava um contador que ia sempre me dando o número da próxima linha. Vejam abaixo:
<code>    ...
    Application.Goto Reference:="NomeDaTabela"
    PróximaLinhaDaTabela = Range("NomeDaTabela").Row
    For X = 1 To 50 'Simulando os registros de um array
        ActiveSheet.Cells(PróximaLinhaDaTabela, 1) = X
        PróximaLinhaDaTabela = PróximaLinhaDaTabela + 1
    Next
    ...
</code>
Acontece que eu, de fato, não estou "controlando" a próxima linha da tabela "NomeDaTabela". Estou controlando a próxima linha da planilha ("ActiveSheet"). Quando eu tento adicionar uma nova linha na tabela através do comando Range("Nome da tabela).Insert, ele insere uma linha no início da tabela, logo abaixo do cabeçalho. Eu gostaria que ele inserisse ao final, após as outras linhas da tabela que já estejam preenchidas. E que eu conseguisse referenciar essa nova linha para adicionar valores. Se eu tento utilizar o comando Range("NomeDaTabela").Cells(PróximaLinhaDaTabela, Coluna), ele utiliza a posição da tabela mais o número de linhas informado. Ou seja, o comando Range("NomeDaTabela") "sabe" onde está localizada a tabela. Eu é que não sei como referenciar.
Alguém já fez algo do tipo?
Desde já, obrigado.
Answer: Seja bem vindo!
Se estiver procurando como adicionar uma linha em um objeto como uma tabela pré definida o código será algo assim:
<code>Set myNewRow = ActiveWorkbook.Worksheets(1).ListObject(1).ListRows.Add
</code>
Neste caso deve adicionar uma linha abaixo.
Espero ter ajudado!
Referência
Comment: Obrigado, Evert. Era exatamente o que eu estava procurando. Fiz umas pesquisas e já vi que vou ter que alterar meu código pra tratar adequadamente essas tabelas. Eu estava usando "Range", mas acho que devo tratar como "ListObject". Obrigado pela ajuda.


Find out how often OTHER apps crashed on Android

Question: My manager asks if it's possible for an app to learn how many times OTHER apps that are installed on the Android device have crashed.
From what I understand about sandboxing the apps, this shouldn't be possible. Is maybe the Android OS writing somewhere into logs which apps crashed, when, for what reason (e.g. stack trace saved)? If yes, one could parse them (possibly even on a non-rooted phone, if permissions allow).
This should work for just any kinds of other apps, from AndroidMarket or not, and not only those we developed ourselves.
Thanks!
Comment: http://code.google.com/p/alogcat/ look at source ... all you need to do is log parsing ;p
Answer:
My manager asks if it's possible for an app to learn how many times OTHER apps that are installed on the Android device have crashed.

Some apps will allow their stack traces for unhandled exceptions to be written to LogCat, which you can read if you have the READ_LOGS permission. Ideally, few production applications do this, as one can argue that it's a bit of a security issue. Those that have their own mechanism for reporting unhandled exceptions (e.g., ACRA) will not necessarily log their data to LogCat, and you have no way about finding out whether or not they "crashed".
Comment: @iseeall: "How long do the logs in logcat stay?" -- not long. It's a 64KB ring buffer, so older entries get replaced with newer ones. "I'd need a service which keeps parsing LogCat once in a while" -- triggered by `AlarmManager`, yes. "They'd prefer an app which just runs once, and can tell what apps had crashed before this app was installed." -- if it crashed in the last few minutes, that might work. Personally, I don't like apps with `READ_LOGS`, and so expect some push-back from users.
Comment: Thanks! How long do the logs in logcat stay? I mean, it will grow to megabytes after some time and would clog space if kept on the phone forever, won't it? When I view it from Eclipse, it gets cleaned up after maybe 10-20 mins. If so, I'd need a service which keeps parsing LogCat once in a while. Am I thinking over the right lines?
Comment: They'd prefer an app which just runs once, and can tell what apps had crashed before this app was installed. If LogCat gets cleaned up regularly, this wouldn't be possible, right?


How do I change the time format and data format in logstash?

Question: I want to load mysql data using logstash and put it into elasticsearch.
I added the "jdbc:mysql://local:portnumber/test?zeroDateTimeBehavior=convertToNull" option to load the data from mysql.
The time format is changed when getting the value of the date field in mysql.
for example....
date field value : 2017-04-07 08:01:00
logstash value:  2017-04-06T23:01:00.000Z
I want to change the time format to Asia / Seoul (GMT + 9) format.
So I tried the below, but the format does not changes.
date{
         match => ["reg_date","yyyy-MM-dd HH:mm:ss.S"]
         #timezone => "UTC"
         timezone => "Asia/Seoul"
        }
I will change the format to 'yyyy-MM-dd HH: mm: ss.S' using 'ruby code' after changing the time format with 'date filter'.
How do I change the time format?
Answer: Logstash sets the timestamp always to UTC. You should change the timestamp on the presentation layer instead to another timezone.


VB Net Console Loops

Question: How to write a VB net console app using loops for this kind of output:

$$$$$
$$$$
$$$
$$
$

'Declaring the variables
Dim DollarSign As String

DollarSign = "$"

For counter = 5 To 1 Step -1
    Console.WriteLine(DollarSign)
Next

the output shows like this:

$
$
$
$
$

as well this following output:

1$$$$
12$$$
123$$
1234$

I can't figure this out. What's going on here?
Comment: Show your attempts with code
Answer: Dim DollarSign as String = "$"

For counter = 5 To 1 Step -1
    Console.WriteLine(New String(DollarSign, counter))
Next

Answer: Another approach using NESTED for loops:
Dim numRows As Integer = 5
For row As Integer = numRows To 1 Step -1
    For col As Integer = 1 To row
        Console.Write("$")
    Next
    Console.WriteLine()
Next
Console.ReadKey()

Output:
$$$$$
$$$$
$$$
$$
$

Second version:
Dim numRows As Integer = 5
For row As Integer = numRows To 1 Step -1
    For col As Integer = 1 To ((numRows + 1) - row)
        Console.Write(col)
    Next
    For col As Integer = 1 To (row - 1)
        Console.Write("$")
    Next
    Console.WriteLine()
Next
Console.ReadKey()

Output:
1$$$$
12$$$
123$$
1234$
12345

Answer: Right now your code is looping from 5 to 1 and printing the dollar sign once during each iteration.
It sounds like you want the dollar sign to be repeated based on the current index of the loop.
If that's the case then you can create a new string and pass in the dollar sign and the current index:
Dim dollarSign As Char = "$"c
For counter = 5 To 1 Step -1
    Console.WriteLine(New String(dollarSign, counter))
Next

Fiddle: https://dotnetfiddle.net/Ok8NSD
Answer: There are just so many ways to do this:
Dim output = "$$$$$"
Do While output.Length > 0
    Console.WriteLine(output)
    output = output.Substring(1)
Loop

That gives:
$$$$$
$$$$
$$$
$$
$

VB Net Console Loops


Google My Business API return 429 code all time

Question:
{ "error": { "code": 429, "message": "Quota exceeded for quota metric
'Requests' and limit 'Requests per minute' of service
'mybusinessaccountmanagement.googleapis.com' for consumer
'project_number:xxx'.", "errors": [ { "message": "Quota
exceeded for quota metric 'Requests' and limit 'Requests per minute'
of service 'mybusinessaccountmanagement.googleapis.com' for consumer
'project_number:xxx'.", "domain": "global", "reason":
"rateLimitExceeded" } ], "status": "RESOURCE_EXHAUSTED" } }

Why do I receive such a message immediately after logging in?
I haven't had time to use api yet
Comment: apparently you need to send a separate request for access to the api https://docs.google.com/forms/d/1XTQc-QEjsE7YrgstyJxbFDnwmhUhBFFvpNJBw3VzuuE/viewform
Comment: did you find solution? as i faced this error now i checked console and there is 0 request limit for each minute in api quotas. i didn't get how to workaround this
Comment: Any updates? Facing same @Dry7 i have applied for the access to API and got approved still facing this issue
Comment: Did you solve the problem? Does the google team increase your quotas after you filled the form? Thanks for feedback
Answer: I guess you already applied for accesss to GMB API and GMB Account Management API.
You usually get approved for both in less than 2 weeks, but, here comes the answer to your question, now you also need to request an increase for the GMB Account Management API Quota, as this API get approved with a 0 quota.
You can request this from a couple different places. I think I requested mine from the project Quota section in console.cloud.google.com.
You should get your new quota in 1-2 weeks.
It is clear they should update reference docs more in detail.
Comment: Hi, same problem here. I filled the form 2 times, without any reply from the Google team. The form is still valid? Is there a way to contact someone? It's a blocking point to use the API.
Comment: This helped me a lot. Found the form here: https://docs.google.com/forms/d/e/1FAIpQLSdoCw8P5JJsJ-taCH2i8w8B69sGsZfoRhacQOe7FTWArWZ-SQ/viewform?fbzx=2253286086101214471
Comment: I am also facing the issue regarding Google My Business api quota. I submitted the form but did not get any reply after almost 3 weeks.
Comment: thanks this helps alot https://docs.google.com/forms/d/e/1FAIpQLSdoCw8P5JJsJ-taCH2i8w8B69sGsZfoRhacQOe7FTWArWZ-SQ/viewform
Comment: this has never been an issue for me and now all of a sudden i get both cors and 429 errors
Answer: I have finally found an answer! The Google console has a major ux BUG in it. When you don't use the api for a while, it Google will disable the Business API (or it gets disabled after the API update).
HOWEVER, the Google console will still show that your My Business API access is enabled! While in reality it's not! And the button to the google form requesting the access is gone, so you can pull your hairs out, because the other My Business related apis will show you 0 quota, even though the main My Business API will show you non-zero quota and that it's enabled while it's not.
You have to re-request your google my business api here again, even if it shows you that you already have it enabled.
It took us weeks to realize that Google has a bug on their side (and they haven't even bothered to fix it or admit that they have a bug in their panel, they just sid "access is not enabled" when contacting them).
Developing with Google has always been and still is a true hell on earth, very comparable to Facebook developer experience.
Comment: Oh whell, now to find out why i get CORS errors on one business endpoint and not on another, while i use the same OAuth client ...


How to unset field in views conditionally

Question: I'm using hook_views_pre_render() in a module to make sure an image field 'field_field_company_logo' is removed for a certain content type 'job_listing'. I have the following code, which works, but produces warnings:
function hideviewsfields_views_pre_render(&$view) {
  if ( ($view->name == 'job_search') && ($view->current_display == 'job_search_results') ) {
    $result = $view->result;
    foreach ($result as $row) {
      $type = $row->_field_data['nid']['entity']->type;
      if ( $type == 'job_listing' ) {
        unset ( $row->field_field_company_logo );
      }
    }
  }
}

It works, in as much as the correct images are omitted, but I get the following warnings:
Notice: Undefined property: stdClass::$field_field_company_logo in views_handler_field_field->get_items() (line 715 of /public_html/sites/all/modules/views/modules/field/views_handler_field_field.inc).
Warning: Invalid argument supplied for foreach() in views_handler_field->advanced_render() (line 1053 of /public_html/sites/all/modules/views/handlers/views_handler_field.inc).
Notice: Undefined property: stdClass::$field_field_company_logo in views_handler_field_field->get_items() (line 715 of /public_html/sites/all/modules/views/modules/field/views_handler_field_field.inc).
Warning: Invalid argument supplied for foreach() in views_handler_field->advanced_render() (line 1053 of /public_html/sites/all/modules/views/handlers/views_handler_field.inc).

I've seen elsewhere people writing code similar to the following:
unset($view->field[$field_name]);
unset($view->display_handler->handlers['field'][$field_name]);

where the first line seems similar to the unset I am executing, but I believe it was acting upon a different variable (i.e. not $views -- maybe $data?) and I can't find any other reference to the image field within the $view object that can be unset without it removing it altogether from the display.
Comment: Try setting $row->field_field_company_logo to some empty value rather than using unset. Some rows have this value and some don't and I think that is the problem.
Answer: Drill down in the field_field_company_logo field to its ['rendered']['#access'] property and set it's value to FALSE.
Comment: Works like a charm! Thank you! :) Just to clarify, I removed the `unset ( $row->field_field_company_logo );` line and added `$row->field_field_company_logo[0]['rendered']['#access'] = FALSE ;`
Answer: I was trying to hide/unset field in Drupal 8 but the above approach was not working so I used following code to hide/unset field in Views result page (D8),
function hideviewsfields_views_pre_render(ViewExecutable $view) {
  if ($view->id() == 'job_search') {
    foreach ($view->field as $key => $value) {
      if ($key == 'field_company_rating') {
        $value->options['exclude'] = TRUE;
      }
    }
  }
}


Return non-distinct object based on three different fields

Question: Given the following, I would like to be able to pull out the non-distinct values based on two fields: Name and Country.  In this example, I want return the first two in the list.
List<City> cities = new List<City>
{
new City{ Name = "Sydney", Country = "Australia", Galaxy = "Mine"  },
new City{ Name = "Sydney", Country = "Australia", Galaxy = "Yours" },
new City{ Name = "New York", Country = "USA", Galaxy = "Ours"},
new City{ Name = "Paris", Country = "France", Galaxy = "Theirs" },

};

Comment: Specify exactly what do you want? Do you want distinct values of Name and Country fields? Why then _first two in the list_? If you want first two - by what mean to select them? The question is quite ambiguous
Comment: good point, my mistake for not being more clear.  The intended result would yield the first two in the list.  lazyberezovsky gave the the answer I was looking for.
Answer: This query will return non-distinct cities by name and country (i.e. first two in your case):
IEnumerable<City> query =
    cities.GroupBy(c => new { c.Name, c.Country })
          .Where(g => g.Count() > 1)
          .SelectMany(g => g);


Find transformation matrix with respect to a basis of an invariant subspace

Question: Simple question but I've never encountered ones like that.
$T$ is a linear transformation from $\mathbb R^3$ to $\mathbb R^3$ defined by:
$T(v)=Av$ when $A=\begin{pmatrix} 1 & 2 & 2\\6 & 3 & -2\\-3 & 1 & 6\end{pmatrix}$ and $v \in \mathbb R^3$.
Let $U=span\{\begin{pmatrix}1\\0\\0\end{pmatrix},\begin{pmatrix}0\\2\\-1\end{pmatrix}\}$
Let $W = span\{\begin{pmatrix}0\\1\\-1\end{pmatrix}\}$
1) Show that U and W are invariant subspaces (meaning that $Im(U) \subseteq U$ and $Im(W) \subseteq W$). I solved this question
2)I'm stuck here Choose $B_1$ a basis for $U$ and $B_2$ a basis for $W$. Find:
$[T|U]_{B_1}$, $[T|W]_{B_2}$, and $[T]_{B_1 \cup B_2}$
3) Is this the primary decomposition of $T$ to invariant subspaces over $\mathbb R$?
4) Is this the primary decomposition of $T$ to invariant subspaces over $\mathbb Q$?
Clarification about exactly what I'm having difficulties with:
I was taught that the matrix of a transformation with respect to a basis is just the transformation applied to elements of said basis. for example, if $s$ is the standard base then:
$[T]_s = \begin{pmatrix} T(\begin{pmatrix} 1\\0\\0\end{pmatrix},T(\begin{pmatrix} 0\\1\\0\end{pmatrix},T(\begin{pmatrix} 0\\0\\1\end{pmatrix}\end{pmatrix}$ but since $dim(W)=1$ there will be only 1 column in the matrix $[T|W]_{B_2}$ and so it is not a matrix at all...
Answer: You are restricting the transformation $T$ to each of the invariant subspaces, in turn.  For example, $T|_U$ is a linear transformation $U \to U$, so it is represented by a $2 \times 2$ matrix.  You've displayed a pair of linearly independent vectors that span $U$.  Why not let them be your basis $B_1$?  Then, call the matrix for $T|_U$ in this basis $A_1$.
Since $W$ is $1$-dimensional, it is spanned by a single basis vector, so the basis $B_2$ is a singleton set.  The matrix $A_2$ for $T|_W$ in this basis is $1 \times 1$, so it looks like a single number.
Putting this all together, and using $B_1 \cup B_2$ as a basis for $\Bbb{R}^3$, the matrix for $T$ is a block matrix that looks like
$$
\left[
\begin{array}{c|c}
A_1 & \begin{array}{c} 0 \\ 0 \end{array} \\
\hline
\begin{array}{c c} 0 & 0 \end{array} & A_2
\end{array}
\right]
$$
Comment: And is this the primary decomposition to invariant subspaces over $\mathbb R$?


Help: Instance Variables & Properties [iPhone]

Question: In something like this:
<code>@interface Control_FunViewController : UIViewController {
    UITextField *nameField;
    UITextField *numberField;
}
@property (nonatomic, retain) IBOutlet UITextField *nameField;
@property (nonatomic, retain) IBOutlet UITextField *numberField;
</code>
I understand that "UITextField *nameField;" is an instance variable and "@property ..." is a property. But what do these individual things do?
I guess what I'm really asking is how the property is used for example in the implementation file (.m)
Answer: The instance variables are the actual variables, whereas the properties are the equivalent of
<code>- (UITextField *)nameField;
- (void)setNameField:(UITextField *)newTextField;
</code>
and completely optional.  They are also used by the compiler to understand exactly what you want when you @synthesize a variable.  Basically the properties and corresponding @synthesize (or custom implementation) allow OTHER classes access to variables, and are completely optional.  It is in fact generally recommended, as per standard object oriented encapsulation principals, not to use properties unless you specifically intend for them to be used by external classes.  However, you still need Interface Builder to recognize the UITextFields (presumably) which is why we typically put the IBOutlet decorator before the ivar declaration, not the property.


How to find a smallest group generator

Question:
Find the smallest generator for a group $\mathbb{Z}^{*}_{31}.$

It is not said, but I assume that it is about multiplication, because addition would be a trivial one (1 would be a generator).
Comment: We use $^*$ or $^\times$ superscripts to refer to the multiplicative group of units.  See [this wikipedia page](http://en.wikipedia.org/wiki/Multiplicative_group_of_integers_modulo_n), especially the section on generators.
Comment: @williamdemeo: But isn't it that * sign here denotes that this is a group without the $\{0\}$ element?
Comment: Maybe.  How does your book define it?
Comment: @williamdemeo: It is said that it is all about the $\{0\}$ element. None symbol denotes whether it is multiplication or addition. It is always said directly (except this one).
Comment: I suspect they mean the multiplicative group $(\mathbb Z/31\mathbb Z)^{\times}$, in which case the generating set (and your answer) is given in the table at the bottom of the page I mentioned, but I could be wrong. Of course, you should know how to find the smallest generator, or "primitive root" (without refering to this table).  Think about it, and if you are still unsure I'll try to post an answer...
Comment: [This wikipedia page](http://en.wikipedia.org/wiki/Primitive_root_modulo_n#Finding_primitive_roots) explains how to compute the primitive roots, and points out that there is no known general formula, so you just have to compute!
Answer: The $*$ in $\mathbb{Z}^{*}_{31}$ means that you are indeed dealing with the multiplicative group.
I have a feeling you are expected to just compute. Luckily, the computation is relatively short. Start with $2$. Since $2^5\equiv 1\pmod{31}$ (you may be using different notation), $2$ is not a generator: it has order $5$, not $30$.
So now try $3$. If $3$ is not a generator, then the powers of $3$ generate a proper subgroup of our group. Our group has $30$ elements, so the proper subgroups have size $1$, $2$, $3$, $5$, $6$, $10$, or $15$. So we do not need to compute too many powers modulo $31$.
If we find out that $3^{15}\not \equiv 1\pmod{31}$, that will also rule out $1$, $3$, and $5$. We must also rule out $6$ and $10$.
First we rule out $6$. Note that $3^3\equiv -4\pmod{31}$. So $3^6\equiv 16\pmod{31}$. Thus $3^9\equiv -64\equiv -2\pmod{31}$, and therefore $3^{10}\not\equiv 1\pmod{31}$.  That rules out $10$. Since this is homework, I will leave it to you to rule out  $15$.  With a calculator, it is particularly easy, since one need not be afraid of largish numbers.
We end up finding that $3$ is a generator. Since $2$ isn't, $3$ is the smallest one.
Remark: We could just have computed the powers of $3$, reducing modulo $31$. Here is a start: $3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30$. Now it's all over, because we have computed $15$ powers and not reached the identity.  Much more efficient (at least for $31$) than the argument of the main post, which used more in the way of group-theoretic ideas.  However, with substantially larger numbers, the proper approach is a combination of ideas and brute force. By the way, finding a generator, for huge primes, has practical applications.
Comment: Nice explanation +1
Comment: @André Nicolas: Nice, thanks. Only one question. Why we can assume, that "If 3 is not a generator, then the powers of 3 generate a proper subgroup of our group."?
Comment: In any finite group, the powers of any element $a$ form a subgroup of $G$. Quick reminder of proof: Look at $a$, $a^2$, $a^3$, and so on. Since $G$ is finite, these are not all distinct. Suppose $m<n$ and $a^n=a^m$. Then $a^{n-m}$ is the identity, and $a^{n-m-1}$ is the inverse of $a$. So inverse of any power of $a$ is a power of $a$. End. In our case, **proper** subgroup because if it is full group, $3$ is generator. We wanted to rule out all ways $3$ can fail to be generator.  We could just have computed all the powers, seen there are $30$.
Comment: @teodore: I have added a remark that gives a "trivial" way to do the job.  The reason I avoided it in the main post is that problems like this are a good way to learn about some important group-theoretic ideas, so I did not want to write out a completely "no-thinking" solution.
Comment: @AndréNicolas: Thanks a lot. The last thing. Why we can only focus on $30$ divisors (so $k = 1,2,3,5,6,10$ or $15$) while checking whether $3^k \not\equiv 1 \pmod{31}$? Why we don't need to check for example if $ \ 3^7 \not\equiv 1 \pmod{31}$?
Comment: By Lagrange's Theorem, the order of the subgroup generated by $a$ **divides** the order of the full group. The end. Or, if you are familiar with elementary number theory but not yet group theory, the order of an element divides $p-1$. Standard proof: Let $k$ be the smallest positive integer such that $a^k \equiv 1 \pmod p$. If $k$ does not divide $p-1$, then $p-1=kq+r$ where $0<r<k$. But then fairly easily $a^r\equiv 1\pmod{p}$, contradicting choice of $k$ as smallest. Lagrange is better, since you are taking group theory, so should develop a group viewpoint.

How to find a smallest group generator


Calculate coords of a point giving angle and a line

Question: I work in canvas and I want to draw some lines.
I have a first line defined by 2 points P1 (x1,y1) and P2 (x2,y2).
I know how to calculate distance r between these 2 points with formula : sqrt((x2-x1)^2 + (y2-y1)^2) .
My problem is the following. With a defined angle Alpha, I would like to calculate coords of a point P3 (x3,y3) like distances P1P3 = P1P2 = r.
I guess it's a problem with trigonometry or polar coords perhaps but I don't remember these notions and I have some problems to find the solution.
The following image resumes the post and show a representation :

Someone has some ideas about the solution ?
Thanks by advance for your help.
Sylvain
Answer: The basic idea is to rotate the difference vector:
<code>dx := x2 - x1
dy := y2 - y1

dx' := cos alpha * dx - sin alpha * dy
dy' := sin alpha * dx + cos alpha * dy

x3 := x1 + dx'
y3 := x1 + dy'
</code>


Help solving $\int {\frac{8x^4+15x^3+16x^2+22x+4}{x(x+1)^2(x^2+2)}dx}$

Question: $\displaystyle\int {\frac{8x^4+15x^3+16x^2+22x+4}{x(x+1)^2(x^2+2)}\,\mathrm{d}x}$
I used partial fractions, solved $A = 2, C = 3$.

$$\frac{A}{x} + \frac{B}{x+1} + \frac{C}{(x+1)^2} +\frac{(Dx+E)}{(x^2+2)}$$
\begin{align*}
&8x^4+15x^3+16x^2+22x+4\\
&\quad = A(x+1)^2(x^2+2)+B(x)(x+1)(x^2+2)+C(x)(x^2+2)+(Dx+E)(x)(x+1)^2
\end{align*}
Substitute in $x=0$ to get $4=A(1)(2)$, so  $A = 2$
$$6x^4+11x^3+10x^2+14x = B(x)(x+1)(x^2+2)+C(x)(x^2+2)+(Dx+E)(x)(x+1)^2$$
Substitute in $x=-1$ to get
$$6-11+10-14 = C(-1)(1+2)$$
so $-9=-3C$, thus $C=3$.
Leaving me what I have below:

Which brings me to where I am currently stuck.
$$6x^4 +8x^3 +10x^2+8x = B(x)(x+1)(x^2+2) + (Dx + E) (x) (x+1)^2$$
Is the next best move to use substitution to solve for $B$?
Comment: You could just multiply out the polynomials on the left and then match up the coefficients of each term (i.e. the only unknown multiplied by $x^4$ will be D, so D must be 6).  This strategy will always work, although there are usually quicker ways if you use some ingenuity (as it sounds like you are).
Comment: It might be helpful to see your setup for the partial fraction decomposition.
Comment: I meant 'right' instead of left above...
Comment: right, for some reason I forgot to square the x+1 on my paper so I only ended up with Dx^3, now I see that I should have gotten Dx^4 so D must be 6
Comment: Note: after the editing what I said is wrong.
Comment: @Brian:  Actually I multiplied out the right side wrong,  you would still have Bx^4 because I left out the (x-1) that is also multiplies by B.
Comment: @Finzz: Please consider using displayed equations when writing out fractions or long expressions (with `$$...$$`); not only does it mean you don't need to break into a new paragraph, and that they are automatically centered, they also rendered larger and more readable.
Answer: Below I show how the Heaviside cover-up method generalizes to handle nonlinear denominators. With numerator $\rm\:f(x)\ =\ 8x^4+15x^3+16x^2+22x+4\:,\: $ the undetermined partial fraction is
$$\rm\frac{f(x)}{x(x+1)^2(x^2+2)}\ =\ \frac{a}{x}\, + \,\frac{b\, (x+1) + c}{(x+1)^2}\, + \,\frac{d\, x+e}{x^2+2}$$
To find $\,\rm d\,x+e\,$ in the $\rm\: x^2+2\ $ fraction, clear denominators and collect factors of $\rm\: x^2 + 2\: $
$$\rm f(x)\ \ =\ \ x\ (x+1)^2\ (d\, x +\: e)\, +\, (x^2+2)\ g(x)\ ,\quad some\ \ g(x) \in \mathbb Q[x]$$
Evaluating this $\rm\bmod\, x^2 + 2,\ $ i.e.$\:$ iteratively applying the rewrite rule $\rm\ x^2 \to -2\,\ $ yields
$$\rm - 8\, x + 4\ =\: -(4\, d + e)\, x\, +\, 2\, d - 4\, e\ \iff \ d=2,\ e=0 $$
Notice this method amounts to ignoring ("covering") all the undetermined partial fractions having denominator different (i.e. coprime) from the current denominator $\rm\:p(x) = x^2+2\:$ (i.e. having different roots) then evaluating what remains at the roots of $\rm\,p(x)\,$ or,  equivalently,  evaluating it $\rm\bmod p(x).\,$ To avoid computing inverses $\rm\bmod p(x)\:$ we scale to clear denominators before evaluating. This is simply the higher-degree analog of the classical Heaviside method - where covering up and evaluating at $\rm\: x = r\:$ is equivalent to evaluating modulo $\rm\:x-r\:$.
Using the same method we can solve for the numerator of the $\rm\ (x+1)^2\,$ fraction
$$\rm f(x)\  =\  x\, (x^2+2)\, (b\, (x+1) + c)\,  + \, (x+1)^2\ h(x)\ ,\quad some\ \ h(x) \in\mathbb Q[x]$$
Evaluating it mod $\rm\, (x+1)^2,\, $ i.e.  iteratively applying rewrite rule $\rm\, x^2 \to\, -2\ x - 1\, $ yields
$$\rm 3\ x - 6\ =\ (5\, c - 3\, b)\, x\, +\, 2\, c - 3\, b\ \iff\ c = 3,\ b = 4 $$
Comment: Very nice -- I didn't know about this :-)
Comment: More examples (for reference): [1](http://www.math-cs.gordon.edu/courses/ma225/handouts/heavyside.pdf) [2](http://www.iaeng.org/publication/WCE2008/WCE2008_pp978-980.pdf?#page=2)
Comment: @joriki [See here](http://math.stackexchange.com/a/804200/242) for another (simpler) example
Answer: First, I trust you used the correct partial fraction decomposition:
$$\frac{8x^4+15x^3+16x^2+22x+4}{x(x+1)^2(x^2+2)} = \frac{A}{x} + \frac{B}{x+1} + \frac{C}{(x+1)^2} + \frac{Dx+E}{x^2+2}.$$
This leads to
\begin{align*}
&8x^4 + 15x^3 + 16x^2 + 22x + 4\\
&\qquad = A(x+1)^2(x^2+2) + Bx(x+1)(x^2+2) + Cx(x^2+2) + (Dx+E)x(x+1)^2.
\end{align*}
A useful "trick" is to evaluate at the zeros of the linear factors to get some information; I suspect you evaluated at $x=0$ to get $2A = 4$, from which you got $A=2$.
You can then evaluate at $x=-1$ to get $-3C = -9$, which is how you got $C=3$. Looking good.
Then you used that to simplify.
$$2(x^2+2x+1)(x^2+2) +3x(x^2+2) = 2x^4 + 7x^3 + 6x^2 + 14x + 4,$$
which subtracted from $8x^4 + 15x^3 + 16x^2 + 22x + 4$ gave you
$$6x^4 + 8x^3 + 10x^2 + 8x = Bx(x+1)(x^2+2) + (Dx+E)x(x+1)^2.$$
Hmmm... Which is not quite what you have. Did you use the correct decomposition, or did you forget about being careful with that $(x+1)^2$?
Anyway: here's where you go stuck because you are used to being able to solve the partial fractions problems using only the evaluation trick. But when you have irreducible quadratic factors or powers of linear factors (or worse, both), the trick doesn't get you all the way there.
Here, we can factor out $x$ from both sides to get
$$6x^3 + 8x^2 + 10x + 8 = B(x+1)(x^2+2) + (Dx+E)(x+1)^2.$$
(We factored out $x$ from both sides and cancelled; that's how we dropped from fourth power to cube).
Edit.
We can further factor out $x+1$ from both sides:
$$(x+1)(6x^2 + 2x + 8) = (x+1)(B(x^2+2) + (Dx+E)(x+1))$$
to get
$$6x^2 + 2x + 8 = B(x^2+2) + (Dx+E)(x+1).$$
Contrary to your claim before, now that we had all the right terms, we cannot simply conclude that $D=6$, because there are two quadratic terms: $Bx^2$ and $Dx^2$.
You can, however, evaluate at $x=-1$ to get $12 = 3B$, or $B=4$; from this you go to
$$6x^2 + 2x + 8 = 4x^2 + 8 + (Dx+E)(x+1)$$
or
$$2x^2 + 2x = (Dx+E)(x+1).$$
Noting that the constant term on the right is $E$, and $0$ on the left, you get $E=0$. This gives
$$2x(x+1) = Dx(x+1)$$
which, cancelling $x(x+1)$ yields $D=2$.
Alternatively, from $2x^2+2x = (Dx+E)(x+1)$, we can factor the left hand side completely to get
$$2x(x+1) = (Dx+E)(x+1)$$
from which we immediately get $Dx+E = 2x$, so $D=2$ and $E=0$.
So, in summary, $A=2$, $B=4$, $C=3$, $D=2$, $E=0$.
Comment: @Finzz: I factored out $x$, which is how I dropped from fourth power to cube. And no, you cannot deduce that $D=6$ at this point, because if you do things correctly you'll notice that you have **two** terms that involve the highest power of $x$, not a single one: both the $Bx^3$, and the $Dx^3$. I have not divided through by $x-1$.
Comment: @Finzz: Yes, you have two terms with highest term. Look at the edit I just did.
Comment: If you don't factor out the x and multiply out the right side, the only co-efficient to yield $x^4$ would mean D would have to be 6.  because  $6x^4+8x^3+10x^2+8x = Bx^3 +2Bx +Dx^4 + 2Dx^3 + Ex^3 +Ex^2 +Ex$
Comment: @Arturo:  I accidentally skipped the part where you said you factored out the x,  look at my comment again.  EDIT: Nevermind, you would have $Bx^4$ wouldn't you?
Comment: @Arturo:  Awesome!  Thanks once again, and I think you accidentally put an extra dollar sign ($) on one of your lines.
Comment: @Fizz: Rather, I left one out. Thanks.
Comment: @Ross: Thanks for catching the typo; but why did you move the period to outside a displayed equation? Punctutation goes outside in-line formulas, but inside displayed ones: `$blah$.` vs. `$$blah.$$`
Comment: @Arturo:  I didn't intend to move it, though the evidence shows I did.  I just noticed the imbalance in dollar signs because it didn't render and tried to fix it.  I was unaware of the difference in where punctuation goes, but I'll watch it in the future.
Answer: Given what you have, what happens when you set $x = -1$?
Comment: I don't think I can because then the right side would be 0.  EDIT: So would the right side.
Comment: @Finzz: You mean the left side will be zero? Does that give you a value for $B$?
Comment: There is also supposed to be an (x+1) attached (multiplied) to the B, I forgot to add it in, sorry.
Comment: @Finzz: Then do the substitution _after_ dividing by $(x+1)$. Make sure you divide out $x+1$ from the left side before trying to set $x=-1$. The $D,E$ gets cancelled because of $(x+1)^2$, but the $B$ term remains...
Comment: @Moron: What do you mean divide out x+1 from the left side?  Because I would be dividing by 0 after setting x = -1
Comment: @Finz: Can you divide out $x+1$ from $x^2 + 2x + 1$?
Comment: @Finzz: Divide as *polynomials*. Since the polynomial on the left evaluates to $0$ at $x=-1$, that means that it must be a multiple of $x-(-1)$. So factor it out, then cancel it.
Answer: Following your original method from the point where you pose your question, here are a couple of tricks you can use, which were not mentioned in previous answers. (1) Set $x=\varepsilon -1$ and neglect $\varepsilon^2$, to get $B=4$ immediately. (2) Set $x=\mathrm{i}\sqrt2$ and equate real and imaginary parts to find $D$ and$E$ (independently of $B$).
Answer: For kicks, I thought I provide the end result for checking:
${\huge{\displaystyle\int}} \! \dfrac {\rm{8x^4+15x^3+16x^2+22x+4}}{\rm{x(x+1)^{2}(x^2+2)}}~\mathrm{dx}~=~
{\huge{\displaystyle\int}} \! \dfrac {\rm{A}}{\rm{x}}+\dfrac {\rm B}{(\rm x+1)}+\dfrac {\rm C}{(\rm{x+1)^{2}}}+\dfrac {\rm{Dx+E}}{{\rm{(x^2+2)}}}~\mathrm{dx} $
$~~~~~~~~~~~~~~~
\left[ \begin{array}{ccccc}
\rm{a} \\
\rm{b} \\
\rm{c} \\
\rm{d} \\
\rm{e}
\end{array} \right] = \left[ \begin{array}{ccccc}
\rm{2} \\
\rm{4} \\
\rm{3} \\
\rm{2} \\
\rm{0}
\end{array} \right]~~~~~~~~~~\Rightarrow~~~~~~~~~~~~~~
={\huge{\displaystyle\int}} \! \dfrac {\rm 2}{\rm x}+\dfrac {\rm 4}{{\rm{(x+1)}}}+\dfrac {\rm 3}{{\rm{(x+1)^{2}}}}+\dfrac {\rm 2x+0}{{\rm{(x^2+2)}}}~\mathrm{dx}
$
$~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
={\rm{2\ln|x|-4\ln(x+1)+\dfrac {3}{x+1}+\ln(x^2+2)+K}}
$
$~~~~~~~~~~~\Big({\rm{\ln|x^2+2|\equiv \ln(x^2+2)}}~,~\because {\rm{x^2+2\gt 0~~\forall ~x \in \mathbb{R}}}\Big); ~$
via a substitution of the denominator for the last 3 integrals.
Comment: Should this not be $-\frac{3}{x+1}$?


Pass variables from Presentation Layer to Logic Layer

Question: I am stuck when I try to make the Logic Layer update the Presentation Layer since I have initialized GUI variables in the Presentation Layer. Still, after that, I couldn't find a way to reach those variables from the Logic Layer. I don't believe that I should make all variables public to reach them.
I have an example here:

Logic Layer method that updates multiChoicePanel
<code>public void clearDisplay() {
          if (currentlyDisplayedQuestion.getQuestionType() == QuestionType.MULTI_CHOICE) {
              multiChoicePanel.clearDisplay();
          }
         else
          ...
      };
</code>

Presentation Layer where i have declared multiChoicePanel
<code>  private JQEMultiChoiceQuestionScreen multiChoicePanel;
</code>

So the question here is how to pass multiChoicePanel to Logic Layer?
Comment: You shouldn't! Just pass the necessary information to the logic layer
Comment: Yes. For sure! Everything that has to do with the UI belongs to the presentation layer.
Comment: The logic is where you implement the business logic and access the data layer. The logic layer is exposing their functionality through methods but does not access the UI layer
Comment: So, clearDisplay() method should be in the Presentation Layer instead of the Logic Layer?
Comment: Alright, can we say the Logic Layer is responsible for methods that need to use Data Layer and Presentation Layer together?
Comment: Now it makes sense, thank you for the help
Comment: If you have arrived at a solution, please post and accept an Answer to your own Question so this page can be marked as resolved.
Answer: I solved this question by moveing clearDisplay() in the Presentation Layer and make the Logic Layer expose its functionality through methods.


Is referential integrity supported?

Question: Does Drupal 8 support referential integrity? Can I tell Drupal what it should do if a parent row in a content type is deleted? For example:

I could tell Drupal not to allow the deletion of a parent row if it has child rows
I could tell Drupal to delete all child rows that belong to a parent row when that parent row is deleted

By row I mean an item of a content type. For example, if the content type is Book, a row is the data about one book.
Comment: Welcome to Drupal Answers! I must admit I don't understand your question. What rows?
Comment: @leymannx I think they are called "nodes" in Drupal, not sure.
Comment: Are you sure, then please update your question accordingly. Otherwise it would be better to find that out yourself first and then come back and clarify.
Comment: You should simply try it out yourself. What happens when you try to delete a node that's referenced by another node? Does it work? As far as I remember this isn't possible. But I might be wrong. Please just try it out yourself instead of letting us try it out for you.
Answer: No, there's no such feature out of the box.
For D7, there is a module for that, but I haven't see a Drupal 8 version: https://www.drupal.org/project/erri.
We did build something like that ourself based on the entity_usage module, we alter the node delete form and display a warning that shows where the node is used.
Comment: A Drupal 8 module which facilitates the enforcement of entity references is https://www.drupal.org/project/erg. It is abandoned but the approach taken seems solid enough.

Is referential integrity supported?


Upload image to a nodeJs server using react-native

Question: I want to upload an image from react-native (cli without expo) to a node server, i tried using axios with formData filed is not recognised by multer, then i tried with fetch that worked image was stored in server but i get promise rejection on front:
<code>const postDocument = (doc) => {
//i used react-native-document-picker to pick document(doc) i logged it and it works
  const url =`${api}/sendImage`;
  const formData = new FormData();
  const id = uuid.v4()

  formData.append('id',id)
  formData.append('image', doc);
 const options = {
      method: 'POST',
      body: formData,
      headers: {
        Accept: 'application/json',
        'Content-Type': 'multipart/form-data',
      },
  };
  fetch(url, options).then((res)=>{
//getting promise rejection even without code but image is stored in backend
  }).catch(error=>{})
}
</code>
getting this error : [TypeError: Network request failed]
Answer: using rn-fetch-blob (react-native-cli not expo-cli) instead of fetch or axios solved this for me


Moving backwards from fragment

Question:
Fragment InvoiceInfo

public void move_to_another_fragment() {
    Fragment fragment = (Fragment) new ItemFragment();
    FragmentManager fragmentManager = getFragmentManager();
    getActivity().getActionBar().setTitle("Items");
    fragmentManager.beginTransaction()
        .replace(R.id.frame_container, fragment)
        .addToBackStack("invoiceinfo").commit();

}

In the Above fragment Invoice Info I use move_to_another_fragment method to move into Fragment PurchaseOrder it works fine

Fragment PurchaseOrder

FragmentManager fm = getActivity().getFragmentManager();
fm.beginTransaction().addToBackStack("purchase_order");
fm.popBackStack();

This Fragment PurchaseOrder has a button, when the button is clicked it should go back to the previous page(InvoiceInfo fragment).
It also works but when I click a button in invoice frgament I need to go to the PurchaseOrder.
FragmentManager fm = getActivity().getFragmentManager();
fm.beginTransaction().addToBackStack("purchase_order");
fm.popBackStack();

I used the above code inside the InvoiceInfo fragment to do that but it does not work
Answer: Have you tried popBackStackImmediate()?
FragmentManager fm = getActivity().getFragmentManager();
            fm.popBackStackImmediate();

update
  FragmentManager fm = getActivity()
                .getSupportFragmentManager();
        fm.popBackStack ("invoiceinfo", FragmentManager.POP_BACK_STACK_INCLUSIVE);

Comment: not working.i actually i need to get the any fragment reside in the stack instead of taking top one.
Comment: @SupunLakshan edited my answer check if it works for you

Moving backwards from fragment


Using Linear Mixed Models with two fixed factors and a random factor

Question: I am trying to make a Linear Mixed Model with two fixed factors ('ANTS and LABEL') with the ('STATE') as a random factor. Can anyone suggest to me how to proceed with such a model in R or Matlab?
An image of the data file is attached.
Answer: Assuming that RATE is the response then in R the model would be:
RATE ~ ANTS + LABEL + (1|STATE)


Feature selection using deep learning?

Question: I want to calculate the importance of each input feature using deep model.
But I found only one paper about feature selection using deep learning - deep feature selection. They insert a layer of nodes connected to each feature directly, before the first hidden layer.
I heard that deep belief network (DBN) can be also used for this kind of work. But I think, DBN provides only abstractions (clusters) of features like PCA, so though it can reduce the dimension effectively, I wonder that if it is possible to calculate the importance (weight) of each feature.
Is it possible to calcualte the feature importance with DBN?
And are there other known methods for feature selection using deep learning?
Answer: One approach you can take for almost any prediction model is to first train your model and find its accuracy, then for one input add some noise to it and check the accuracy again. Repeat this for each input and observe how the noise worsens the predictions. If an input is important then the extra uncertainty due to the noise will be detrimental.
Remember set the variance of the noise to be proportional to the variance of the input in question.
Of course noise is random and you don't want one input to appear unimportant due to random effects. If you have few training examples then consider repeatedly calculating the change in accuracy for each training example with a new noise added each time.
In response to the comments:
This analysis can also be done by removing a variable entirely but this has some downsides compared to adding noise.

Suppose that one of your inputs is constant, it acts like a bias term so it has some role to play in the prediction but it adds no information. If you removed this input entirely then the prediction would become less accurate because the perceptrons are getting the wrong bias. This makes the input look like it is important for prediction even though it adds no information. Adding noise won't cause this problem. This first point isn't a problem if you have standardized all inputs to have zero mean.
If two inputs are correlated then the the information about one input gives information about the other. A model could be trained well if you used only one of the correlated inputs so you want the analysis to find that one input isn't helpful. If you just removed one of the inputs then, like the first point made, the prediction accuracy would decrease a lot which indicates that it is important. However, adding noise won't cause this problem.
Comment: Hugh, I'm familiar with doing that by removing the feature. What are the advantages of replacing the feature with noise?
Comment: @Huge Thank you for the comment. I agree with you. But what I really wanted to know was how to calculate the importance of each feature with deep learning, or neural network. As they use several feature extractions(hidden layers), it was difficult for me to analyze the feature importance. It is possible to calculate whole weight of each feature, but it seems to be quite complex and time-consuming. The linked paper used a single linear layer and I think that is a good idea. I wanted to know other better methods for analyzing the feature importance on the network.
Comment: @Dan I didn't mean that the feature should be completely replaced with noise, just that some noise should be added. Removing a feature can make unimportant features look important if they have non-zero mean or if they are correlated with other variables. I've edited my answer to explain.
Comment: Thank you for the comment. But in fact I have a number of feature set(inputs) and many of them are correlated. In this case, maybe the computational time will be close to n! as I need to consider the combinations. So I want to apply deep learning-based model which can consider complex feature combinations.
Comment: @z991 in multivariable linear regression the same problem can occur with variables that are not perfectly correlated. Often we introduce each variable one at a time or use all variables and remove them one at a time. There's no way to simply calculate the best combination. If that hasn't been solved for linear regression you won't find a solution for NN's. You could take the same approach and remove variables one at a time and avoid the n! computation.
Comment: I understand Hugh. I had in mind https://en.wikipedia.org/wiki/Feature_selection#Wrapper_Method
Comment: Why would the accuracy drop after removing a redundant variable?
Comment: @broncoAbierto If the whole NN was retrained without that variable then it wouldn't drop, but without retraining then a redundant variable will have some functionality in producing the prediction.
Comment: Oh, ok. I thought you suggested removing the variable from the whole process, including training.
Answer: Maybe check this paper: https://arxiv.org/pdf/1712.08645.pdf
They use dropout to rank features.
... In this work we use the Dropout concept on the input feature layer and optimize the corresponding feature-wise dropout rate. Since each feature is removed stochastically, our method creates a similar effect to feature bagging (Ho, 1995) and manages to rank correlated features better than other non-bagging methods such as LASSO. We compare our method to Random Forest (RF), LASSO,
ElasticNet, Marginal ranking and several techniques to derive importance
in DNN such as Deep Feature Selection and various heuristics...
Answer: Have a look at this post:
https://email@example.com/how-to-use-deep-learning-for-feature-selection-python-keras-24a68bef1e33
and this paper:
https://arxiv.org/pdf/1903.07045.pdf
They present a nice scheme for applying deep models for feature selection.

Feature selection using deep learning?


In the history of Formula 1, when has the fastest qualifier not started the race on pole?

Question: Lewis Hamilton has a 5 place grid penalty for the Chinese Grand Prix this weekend, due to having to change his gearbox.  Harsh, but that's the rule.
He's been on pole for the first two races this season so has a good chance of making it three, if it weren't for the penalty.
My question is, when was the last time that the fastest qualifier didn't start on pole, due to a penalty or some other situation?  I don't think it's ever happened before due to a penalty but am not sure, hence the question.
When was the last time the pole-sitter didn't start the race on pole?  This has definitely happened due to mechanical problems or spinning off the track on the formation lap in the wet, San Marino springs to mind but I can't remember the year or who it was.
There is a reason for the question - the Fantasy F1 game I run gives the pole-sitter bonus points but I am not sure what to do in this kind of situation!
Comment: It will happen today. Michael Schumacher was first in qualifying but was penalized 5 grid places for an incident related to the previous race.
Comment: Funnily enough, yesterday the Spanish Grand Prix had this situation!  Hamilton was disqualified from pole and started from the back of the grid.
Answer: I was so interested in this myself that I wasn't going to stop at anything to get a good answer.  Sadly, small research didn't get me the answers I was after so eventually I spent 14 hours reviewing the reports of every Grand Prix since 1950.  To the date of this answer there have been 864 of them, which is why it took so long.
Grands Prix in which the fastest qualifer didn't start from pole
1955 Indianapolis GP - May 30, 1955
Jack McGrath set the fastest qualifying speed but actually started in grid position 3, on the outside of the track. Jerry Hoyt started in pole as he was one of only two drivers to complete a qualifying event on "Pole Day" due to strong winds and the threat of heavy rain. Hoyt was actually only the eighth fastest in the field and his speed (140.045mph) is the record slowest ranked pole speed.
1994 Monaco GP - May 15, 1994
This was the first GP to follow the deaths of Ayrton Senna and Roland Ratzenberger at the season's previous Grand Prix at San Marino.
Whilst Michael Schumacher did start at pole position and is officially documented as such, grid places 1 and 2 were left unoccupied and painted with the flags of Senna and Ratzenberger's respective nations as a mark of respect.
1996 French GP - June 30, 1996
Michael Schumacher qualified with the fastest lap, earning him pole position for this race.  However, Schumacher's engine failed during the formation lap at Magny Cours and did not take his place on the grid.
1998 Japanese GP - November 1, 1998
Schumacher was involved again here, this time stalling from his hard-earned (one tenth of a second faster) pole position. As a result of this he was sent to the back of the grid. The race started successfully on this, the third, attempt after Jarno Trulli had stalled his car on the first attempt.
2001 Monaco GP - May 27, 2001
David Coulthard was sitting happily in pole position but his McLaren failed to pull away for the formation lap.  His team managed to get him moving eventually but by this time he was resigned to starting from the back of the grid.
2005 US GP - June 19, 2005
This is the one they called "IndyGate".  Jarno Trulli was fastest qualifier and therefore in pole position.  However, due to safety concerns regarding the Michelin tyres, all drivers of vehicles with these tyres retired to the pits during the formation lap.
Only six cars started the race with drivers in grid places 5, 7, 17, 19, 18 & 20.

2005 Italian GP - September 4, 2005
Kimi Räikkönen qualified with the fastest time but was given a 10-place grid penalty for changing his engine. Juan Pablo Montoya took up pole position as a result.
2007 Hungarian GP - September 4, 2005
Fernando Alonso recorded the fastest time in qualifying but a stewards' inquiry before the race adjudged Alonso to have impeded Lewis Hamilton during Q3.  Alonso was subsequently relegated 5 places on the starting grid, moving Hamilton up to pole.
2012 Spanish GP - May 13, 2012
In this event, Lewis Hamilton was excluded from the qualifying results due to having insufficient fuel to return to the pits.  As a result, Hamilton had to start the race from the very back of the grid.
2012 Monaco GP - May 27, 2012
The fastest qualifier at Monaco was Michael Schumacher.  However, Schumacher was carrying a 5-grid penalty from the previous race in Spain for causing an avoidable collision with Bruno Senna, thus moving him back in the grid.
It nearly happened in
1990 Japanese GP
Ayrton Senna had secured pole position but was unhappy that pole was situated on the side of the track which was not on the racing line.  Senna requested that he be moved and the stewards agreed, only for the FISA president to overrule the decision, meaning Senna started in pole at the original location.
And to close, you ask:

There is a reason for the question as the Fantasy F1 game I run gives the pole-sitter bonus points but I am not sure what to do in this kind of situation!

You'll have to decide!  Perhaps give the bonus for fastest qualifier instead of pole position?
You can see my spreadsheet with all the pole positions since 1950 here.
Comment: Excellent, many thanks.  It's quite coincidental that after asking this question it happened in the next two races!  Good suggestion for my Fantasy F1 game too, I will probably use that idea.
Answer: This has happened three more times since Ste's answer:

2021 Monaco Grand Prix

Charles Leclerc took pole position, but crashed at the end of the session. The crash caused damage to his driveshaft that wasn't discovered until he left the garage on Sunday, leaving no time for it to be fixed or replaced, and he did not take part in the race.

2021 Italian Grand Prix

Valtteri Bottas was fastest in qualifying and won the sprint qualifying session, but engine penalties meant he started the actual race at the back of the grid, and Max Verstappen took pole instead.

2022 Belgian Grand Prix

Max Verstappen was the fastest in qualifying by over 0.6s, but had already taken engine penalties and started 14th, with Carlos Sainz Jr. inheriting pole position. Verstappen notably went on to win the race anyway.

Taking the title of the question literally, you could also count the 1997 European Grand Prix. Jacques Villeneuve took provisional pole with a time of 1:21.072, but Michael Schumacher and Heinz-Harald Frentzen both matched Villeneuve's time down to the millisecond. Villeneuve was awarded pole position by virtue of having set his time first, so Schumacher and Frentzen missed out on pole despite being (joint) fastest qualifiers.


React onChange não esta disparando

Question: Eu tenho o seguinte código:
handleChange(event, module) {
    this.state[module][event.target.name] = event.target.value
    this.forceUpdate();
}

render() {
    const handleChange = (event, module) => {
        this.handleChange(event, module);
    }
    return (
        <form ref="steps" action="#" className="wizard-big" id="paymentForm">
            <FormGroup>
                <ControlLabel htmlFor="bank_account_agency">Agência</ControlLabel>
                <FormControl name="bank_account_agency" id="bank_account_agency" type="text" value={this.state.bank.bank_account_agency} onChange={(event) => handleChange(event, "bank")} required />
            </FormGroup>

            <FormGroup>
                <ControlLabel htmlFor="bank_account_number">Conta</ControlLabel>
                <FormControl name="bank_account_number" id="bank_account_number" type="text" value={this.state.bank.bank_account_number} onChange={(event) => handleChange(event, "bank")} required />
            </FormGroup>
        </form>
  );
}

O onChange não é disparado em nenhum input dentro do form, eu testei fora dele e tudo funcionou perfeitamente. Estou utilizando a biblioteca jQuery Steps e creio que seja esse o problema, porém não consigo encontrar o motivo do erro.
Answer: Eu gosto de fazer métodos dentro de uma classe com fat arrows, daí eu nunca preciso de colocar o .bind()
Você pode remover a função dentro do seu render()
Eu coloquei: constructor e umas variáveis dentro do render para poder mostrar o exemplo, e removi os componentes do "Bootstrap" também

//import React from 'react';

class Formulario extends React.Component
{
  constructor(props) {
    super(props);
    this.state = { bank: {} };
  }
  //fat arrow functions não precisam de dar o .bind
  handleChange = (event, module) => {
      this.state[module][event.target.name] = event.target.value;
      this.forceUpdate();
  }

  render() {
      let baa = this.state.bank.bank_account_agency ? this.state.bank.bank_account_agency : null;
      let ban = this.state.bank.bank_account_number ? this.state.bank.bank_account_number : null;
      return (
        <form ref="steps" action="#" className="wizard-big" id="paymentForm">

Bank account agency: { baa }

Bank account number: { ban }

            <input onChange={(event) => this.handleChange(event, "bank")} name={"bank_account_agency"}/>
            <input onChange={(event) => this.handleChange(event, "bank")} name={"bank_account_number"}/>
        </form>
      );
  }
}

ReactDOM.render(<Formulario/>, document.querySelector(".root"));

Answer: Só é possível atualizar o state do React com this.setState você NUNCA deve alterar o this.state diretamente. Pois é com o this.state que o React vai vai saber o que mudou ou não. Você iniciou o componente sem state inicial, logo deve usar this.setState para definir novos valores.

React onChange não esta disparando


Finding which item from list was randomly chosen

Question: I have a Tkinter program choosing a random game for me to play. I set up the list and need my program to see which game is chosen so that it can launch the game from its file location. What I have doesn't work. Can you tell me how to find which game was chosen?
def genRanGame(self):
    game = ['BF4', 'CSGO', 'GTA', 'FC3', 'DB']
    self.game.set(random.choice(game))
    if game == "BF4":
        print ("This is working")
    if game == 'CSGO':
        print ("This is really working")

Comment: Did you mean `if self.game == "BF4"`? `game` is still the list. Could you show a [minimal example](http://stackoverflow.com/help/mcve) that *actually recreates the issue*? *"doesn't work"* isn't a terribly helpful problem description...
Answer: Store the random.choice() result in a variable first:
games = ['BF4', 'CSGO', 'GTA', 'FC3', 'DB']
game_picked = random.choice(games)
self.game.set(game_picked)
if game_picked == "BF4":
    # ...

or retrieve it from the object you set it on; presumably self.game is a Tkinter StringVar() object or similar; it has a .get() method as well as a .set() method, you can use that to read out the random choice you set as well:
games = ['BF4', 'CSGO', 'GTA', 'FC3', 'DB']
self.game.set(random.choice(games))
if self.game.get() == "BF4":
    # ...

The list object (I named it games to better reflect the contents) doesn't change when using random.choice(), so games == 'BF4' is never going to be true; it is still set to that whole list and not to just one choice from the list.


How to run web request (Observable) in `finalize()` or achieve similar behavior?

Question: I want to somehow chain two web requests such that:

Request A (Observable<void>) is always run.
Request B (also Observable<void>) is also always run, after A and even when A completes with errors (like finalize()).
If A errors with EA, I want the whole pipeline to complete with EA.
If A succeeds, but B errors with EB, I want the whole pipeline to complete with EB.

I could also do with the pipeline just succeeding in this case.

If both error, then I want the whole pipeline to complete with EA.

This is the solution I could come up with, but it feels very clumsy:
// Changes different parts of backend state in multiple steps,
// some of which might fail.
const reqA: Observable<void> = this.mutateSystemState();

// Loads & renders the system state, updating the parts that
// could be changed.
const reqB: Observable<void> = this.updateSystemStateDisplay();

const pipeline = reqA.pipe(
    catchError(e => of({ errA: e })),
    mergeMap(resultA => reqB.pipe(
        catchError(e => of({ errB: e })),
        map(resultB => {
            if (resultA instanceof Object) {
                throw resultA.errA;
            } else if (resultB instanceof Object) {
                throw resultB.errB;
            }
        })
    ))
);

Comment: I think it's the best you could write with the given contraints. I'd just improve the narrowing with `resultA && 'errA' in resultA` .
Comment: With TypeScript I could actually improve it to `if (resultA)` since `void` is falsy.
Answer: The materialize operator converts next, error, or completion 'events' into
ObservableNotification objects.
Assuming you want pipeline$ to either error or complete without emitting a value, you can do the following:
const pipeline$ = reqA.pipe(
  materialize(),
  concatMap(a => reqB.pipe(
    materialize(),
    map(
      // Both have executed.
      // Both a & b are ObservableNotification objects
      // Emit a if ErrorNotification
      b => a.kind === 'E' ? a
      // Otherwise emit CompleteNotification if b is a NextNotification
        : b.kind === 'N' ? {kind: 'C'}
      // Otherwise emit b
        : b
    )
  )),
  // At this point, we've got reqA's ErrorNotification, reqB's ErrorNotification or a CompleteNotification.
  // Either way, this observable is closing before the first materialize gets a chance to emit reqA's CompleteNotification
  dematerialize()
);

Comment: Theoretically yes but I admit that I didn't test my theory! I didn't want to worry about whether or not `reqB` might be... or later become... asynchronous. `reqA.pipe(materialize ())` emits either an ErrorNotification or a NextNotification **and** a CompleteNotification, so if you used `mergeMap` then `reqB` would be subcribed to twice, but with `concatMap`, `pipeline` will close before a CompleteNotification from `reqA` is dealt with. That's my theory, anyway. Instead of `concatMap(...)`, we could use `take(1),mergeMap(...)` and get the same result.
Comment: Exactly what I was looking for: an obscure operator that almost does all the work for you :D Gonna try it next week at work and accept the answer if it works.
Comment: Is there a specific reason to use `concatMap()` instead of `mergeMap()` here?
Answer: onErrorResumeNext()
whatever reqA$ error or not, will subscribe reqB$
reqA$.pipe(
  onErrorResumeNext(reqB$)
).subscribe(...);

https://stackblitz.com/edit/rxjs-ps5f1j

const pipeline$ = of(reqA$, reqB$).pipe(
  concatMap(materialize()),
  filter(({kind}) => kind === 'E'), // filter Error
  reduce(identity), // collect then return first value
  dematerialize(),
);

or
const pipeline$ = of(reqA$, reqB$).pipe(
  concatMap(materialize()),
  max(({kind}) => +(kind === 'E')),
  dematerialize(),
);

https://stackblitz.com/edit/rxjs-jnqhjw
Comment: if you comment out `reduce(identity)`, when `reqA$` has error `reqB$` won't be subscribed, https://stackblitz.com/edit/rxjs-3zmvcf
Comment: Nice this works too and also avoids the nesting of `pipe()`. But I'm wondering: can't the `reduce(identity)` be omitted? In case both requests error and the pipeline has multiple error notifications then `dematerialize()` will stop at the first error already.
Comment: By the way, If you wanna behavior like this, just use `concat(reqA$, reqB$)`


cocoa pod install error while want to install afnetworking pod

Question: <code>$ pod install

Updating local specs repositories
Analyzing dependencies

[!] Unable to find the Xcode project
`~/Desktop/TestAfnetwork.xcodeproj` for the target `Pods`.
</code>
When i run install command then i got this issue.Please solve my problem. I have already updated this setup.
Comment: locate your .xcodeproj path in side your project folder and then try using pod install command.
Comment: In my pod file path are:-source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '7.0'
pod 'AFNetworking', '~> 2.5'
xcodeproj '/Users/vallesoft/Desktop/TestAfnetwork.xcodeproj'
Comment: on terminal just write .... cd /Desktop/TestAfnetwork.xcodeproj  path of your project folder where .xcodeproj file is present  and then write pod install
Comment: it gives this,Although my project on desktop :-ValleSofts-Mac-mini:~ vallesoft$ cd /Desktop/TestAfnetwork.xcodeproj
-bash: cd: /Desktop/TestAfnetwork.xcodeproj: No such file or directory
Comment: what is your project folder name ? go setp by step
will you tell me what is your project folder name and confirm that your .xcodeproj file is seen when you click on that folder
Comment: TestAfnetwork....my folder name and after that we just jump to see xcodeproj
Comment: /Users/vallesoft/Desktop/TestAfnetwork..Full path of my folder
Comment: ok so according to your information you need to do cd /Desktop/TestAfnetwork/TestAfnetwork.xcodeproject also if you will add some screen shot then it will be helpful.
Comment: @nik--ValleSofts-Mac-mini:~ vallesoft$ cd /Desktop/TestAfnetwork/TestAfnetwork.xcodeproject
-bash: cd: /Desktop/TestAfnetwork/TestAfnetwork.xcodeproject: No such file or directory
Comment: @Nik-My pod install but in my folder no workspace show to open this..
Comment: it will be good if you add some screenshots so i will know more about it.
Answer: Firstly, you should cd to your path /Users/vallesoft/Desktop/TestAfnetwork by using Terminal.
Secondly, type pod init to create Pod file
Finally, make sure that your Pod file look like this
target 'TestAfnetwork' do
pod 'AFNetworking', '~> 2.6'
end
Good luck


How to convert a Neumann problem into a Dirichlet problem

Question: I'm currently studying Dirichlet and Neumann problems from the Schaum series on Complex analysis, book.
I came across this phrase in the book: It is of interest that a Neumann problem can be stated in terms of an appropriately stated Dirichlet problem
I'm not being able to understand this statement. How exactly do I prove this statement? I've been asked to find a harmonic function in the upper half of the complex plane, and its normal derivative has the value $C$ on the positive $x$ axis and $0$ on the negative $x$ axis.
If this had been a dirichlet problem, I could have easily solved it. However, how do I convert the above neumann problem into a dirichlet problem ?
Answer: Problem: Find a harmonic function $u(x,y)$ in the upper half of the complex plane, and its normal derivative has the value $C$ on the positive $x$ axis and $0$ on the negative $x$ axis.
We consider a Dirichlet problem :
Find a harmonic function $U(x,y)(=u_y(x,y))$ in the upper half of the complex plane satisfying $U(x,0)=C,$ $x>0$ and $U(x,0)=0, $ $x<0$. We can easily find $$
U(x,y)=C-\frac{C}{\pi}\arg z, \quad (\,z=x+iy\,).
$$
Let $f(z)=-v+iu$, where $v$ is the conjugate of $u$, then $f(z)$ is holomorphic and $f^\prime(z)=-v_x+iu_x=u_y+iu_x=U+iu_x$. Since $\operatorname{Re} f^\prime(z)=U,$ we see $f^\prime(z)=C+\frac{iC}{\pi}\log z.$
Then $f(z)=Cz+\frac{iC}{\pi}(z\log z -z)+D.$ Since $u$ is the imaginary part of $f(z)$, we have $$
u(x,y)=Cy+\frac{C}{\pi}(x\log |z| -y\arg z -x).$$
We have neglected a constant.