Is there an equivalent to o--p in Vim?

Question: When I yank a whole line and press p, Vim creates a new line to put the yanked text, because of the newline characters. But if I yank part of a line is there a way to put that yanked text in a new line? I currently do o ESC p. Is this the only way?
Answer: Here's your answer from Vim help:
<code>:[line]pu[t] [x]        Put the text [from register x] after [line] (default
                        current line).  This always works |linewise|, thus
                        this command can be used to put a yanked block as new
                        lines.
                        The cursor is left on the first non-blank in the last
                        new line.
                        The register can also be '=' followed by an optional
                        expression.  The expression continues until the end of
                        the command.  You need to escape the '|' and '"'
                        characters to prevent them from terminating the
                        command.  Example: >
                                :put ='path' . \",/test\"
<                       If there is no expression after '=', Vim uses the
                        previous expression.  You can see it with ":dis =".

:[line]pu[t]! [x]       Put the text [from register x] before [line] (default
                        current line).
</code>
But colon-p-u-enter is more keystrokes anyway =/
Comment: Good answer, this could certainly be bound to another key sequence to cut down the keystrokes if it was used frequently.
Comment: Even though it is more keystrokes, it saves going in and out of insert mode, which usually at least has the appearance of saving time (you don't have to reach for ESC).
Answer: Theres o(c-r)0 as you can always paste from registers while your in insert mode but thats only if you want to remain in insert mode after the paste

Is there an equivalent to o--p in Vim?


Writing into an XML file and only saving changes at the end

Question: I have an XML file which I need to write to. I can successfully do so already using the following:
//Code to open the File
public void Open(string FileName, string FilePath)
    {
        try
        {
            XmlDoc = new XmlDocument();
            XmlDoc.PreserveWhitespace = true;
            XmlnsManager = new XmlNamespaceManager(mXmlDoc.NameTable);
            XmlnsManager.AddNamespace("", "urn:xmldata-schema");

            FileStream = new FileStream(@Path.Combine(FilePath, FileName),
                FileMode.Open, FileAccess.ReadWrite);

            XmlDoc.Load(FileStream);

        }
        catch (Exception inException)
        {
            MessageBox.Show(inException.ToString());
        }
    }

   //Code to write to the file
   public void SetValueByElementName(string Name, string Value)
   {
        try
        {
            XmlNode node = XmlDoc.SelectSingleNode("//" + inElementID, XmlnsManager);
            node.InnerText = Value;

        }
        catch (Exception inException)
        {
            MessageBox.Show(inException.ToString());
        }
    }

//Code to save the file
public void Save()
    {

        try
        {
            XmlDoc.Save(@Path.Combine(XmlFilePath, XmlFileName));
            IsFileModified = false;
        }
        catch (Exception inException)
        {
            MessageBox.Show(inException.ToString());
        }
    }

However, the implementation of this class, is that every time I need to write something into the XML file, I have to save it. Now, I was told that I have to change this, and what should happen is that I have to save it only once which is at the end when reading/writing is done. How can I achieve this?
EDIT:
I forgot to add this: One thing I don't quite understand is that the implementation requires to close the file stream immediately.
 //Code to close stream
 private void CloseStream()
    {
        try
        {
            FileStream.Close();
        }
        catch (Exception inException)
        {
            MessageBox.Show(inException.ToString());
        }
    }

The flow is as follows:

OpenFile (then immediately close it)
CloseFile
SetFirstElementValueByElementId (change something in the xml file).
SaveFile (has to be called everytime I make changes, otherwise they won't reflect on the file).
Comment: I don't understand your problem. Why not save an instance of the XMLfile? then you will be able to change everything at running time, and save at the end? can you add some more info?
Answer: Just separate the lifecycle into three parts:

Load the XML file (I would recommend using LINQ to XML instead of the old XmlDocument API, but whatever you need to do...)
Perform all the modifications you need to
Save it at the end

You haven't really explained what's happening in the middle step, but there are two potential options:

Either you can let the rest of your code know about the XML directly
You can hide the XML within another class - so you'd have an XmlDocument or XDocument as a member variable in the class, and the calling code would look something like:
Foo foo = Foo.Load("test.xml");
// Whatever you need here...
foreach (var data in someSource)
{
    foo.UpdateWithData(data);
}
foo.Save("test.xml");

That way the only class that needs to understand the structure of your XML file is Foo. (You'd rename it to something more appropriate, of course.)
Answer: You could simply copy contents of the FileStream into MemoryStream and use it until you want to save the file to the disk.
The link below explains how to do it.
Save and load to Memory Stream


Deriving the analytical expression for time distribution of second consecutive event in Poisson process

Question: I am tying to model a Poisson process in MATLAB using the exponentially decaying distribution which is the time distribution for the elapsed time for the next event after any given event.
In MATLAB, I sampled from an exponential distribution multiple times and created a histogram of the sampled values. With enough samples, this of course, gets you back the original exponential distribution. I also tried to find the time distribution of the second event (the one after the 'next') - I sampled the first time value and when I sampled again , I added this new value to the first time value. Here are the curves. How do I arrive at an analytical expression for the second consecutive event after any given event?
Answer: The pdf of a sum of two independent exponential(1) random variables is the convolution of the individual pdfs, meaning:
$$f_{X+Y}(x)=\int_{-\infty}^\infty e^{-(x-y)} e^{-y} 1_{x-y>0} 1_{y>0} dy = \begin{cases} 0 & x<0 \\ \int_0^x e^{-x} dy = xe^{-x} & x \geq 0 \end{cases}.$$
In general for a sum of $n+1$ iid exponential($\lambda$) random variables, you obtain a Gamma distribution (or more specifically an Erlang distribution) with pdf $\lambda^{n+1} x^n e^{-\lambda x}/n!$.


Why do most coaches save key defensive resources till the end of the game?

Question: This question could be asked of a number of sports, but the example I'm using comes from football.
Yesterday, during the wild card round, the New Orleans Saints called a time out early in the second quarter, to give their defense a chance to recuperate, after the Philadelphia Eagles had driven to the "red zone."
The results fully justified the move. The next two plays resulted in defensive sacks for long yards that prevented a touchdown, and drove the Eagles to the edge of field goal range. The Eagles kicked and missed a field goal that might have represented a victory had the made it (the final score was 26-24, Saints).
Apparently this is unusual. Why is that?  My understanding is that most coaches like to save key defensive resources (e.g. time outs in football, or closers in baseball) for the end of the game. Are some coaches now starting to move their key resources at "critical times" (e.g. time outs earlier in the game)?
Comment: "The results fully justified the move." This is [selection bias](http://en.wikipedia.org/wiki/Selection_bias) - just because it happened to work this time, doesn't mean it was a good idea.
Comment: Who is this unusual to? You mention that "apparently this is unusual." Also, "key defensive resource" to describe a time-out (understand the baseball aspect) is misleading, in my opinion.
Answer: Nothing's changed.  The ideal is still to save your timeouts to the end in case you need to be able to control the clock late in a half.
But these coaches aren't doing anything different.  The key word in the sentence above is "ideal"--it's not uncommon to be able to accomplish that, but it's also not uncommon not to be able to.  Avoiding a delay-of-game penalty or changing out of an obviously bad play call in the here and now may, depending on the situation, be more important than saving them for later--and this is nothing new.  These coaches still would have preferred to be able to save their timeouts for later; it's just that the way things played out didn't really make that possible.
Comment: "Avoiding a delay-of-game penalty or changing out of an obviously bad play call ... **may** ... be more important than saving them for late." This did not hold true for the 2013 Wild Card matchup between the Kansas City Chiefs at the Indianapolis Colts. With the play clock running out on two plays, on [2nd and 8 and 3rd and 7](http://espn.go.com/nfl/playbyplay?gameId=340104011.=4) with around 7 minutes left in the 4th quarter, the Chiefs used two time-outs. I challenge that 40 seconds are more valuable than -5 yards...and you address this by stating the "ideal" is to save time-outs.
Comment: The word "may" is key here.
Answer:
Why do most coaches save [time outs] till the end of the game?

To stop the clock for the possibility of getting the ball back and the opportunity to score, if necessary.
An example is from a 2013 wild card game with the Kansas City Chiefs at the Indianapolis Colts. The Chiefs turned the ball over in downs with around 1:55 left, and the Colts ran out the clock to clinch the win. Had the Chiefs had one timeout, they may have been able to get the ball back for the opportunity to score.

Are some coaches now starting to move their [time-outs] at "critical times" (e.g. time outs earlier in the game)?

This is where I challenge the statement, "These coaches still would have preferred to be able to save their timeouts for later."
The circumstance you present involves the Philadelphia Eagles offense and the New Orleans Saints defense. You also state that the Saints took a time-out to give their defense a chance to recuperate. This very well may be the case, but I have a different perspective.
The Eagles offense is a college-style, fast-paced offense implemented by head coach Chip Kelly. This article goes into the reasons why NFL offenses are "picking up the pace." The following reasons apply:

A faster pace leads to more plays and scoring opportunities.
No-huddle offense limits defensive substitutions.

You address #2 in that the Saints took a time-out to give their defense a chance to recuperate. However, to address #1, coaches may be using their [time-outs] at "critical times" (e.g. time outs earlier in the game) to disrupt the rhythm of a fast-paced offense and to limit and/or disrupt plays and scoring opportunities.
One thing to note here is momentum. To disrupt the rhythm of a fast-paced offense is to disrupt momentum. I'm sure that not all three time-outs in a given half will be used for this purpose (as some are used to avoid delay-of-game penalties and other unforeseen circumstances)...but a strategically placed time-out during the middle of a rhythmic, fast-paced offensive drive may keep points off the scoreboard.
Comment: I think you are right.  I would only add that, after the two minute warning on first down, the offense can run out the entire clock unless the defense calls timeouts.  Even before the two minute warning, the offense can take away huge chunks of time.  Some forget this--that defensive timeouts save *a lot* more time compared to offensive timeouts.
Answer: I'll answer using baseball, with which I am more familiar.
The short answer is that the end of the game is the most critical time period, all other things being equal. In baseball, that means the ninth inning is the most crucial, then the eighth (starting from the beginning of the inning). That's why the best reliever "closes" the game in the ninth inning, and the second best plays "setup" man in the eighth. The worst relievers are placed in the "middle" innings, in the gap between the starter and setup man.
What defies this conventional wisdom is that critical points sometimes occur earlier in the game. Say a tired starter puts allows two runners on base with no outs in the sixth inning, and needs to be relieved. Under these circumstances, this particular sixth inning is more critical than the beginning of the ninth inning normally is. There is now a school of thought (still very much a minority) that believes that your best reliever should be brought in at this point of the game, rather than the ninth inning because recent events (the last two batters) have made this juncture "high leverage."
In the football example, the defending team judged correctly that using the time out in the "red zone" could save at least the difference between a touchdown and a field goal, and in fact, as it turned out, the field goal itself. Even though the last two minutes of a football game are usually the most crucial (and when time outs are most likely to be used), the red zone situation turned out to be more critical than "the last two minutes" usually are.


How to add Charts LineChartView to Coccoa view

Question: I am an old time Windows Visual Studio programmer trying to learn programming on the MAC with Xcode 10.  I am trying to build a test program which uses Daniel Gindi's Charts.
I start by creating a Coccoa Mac OS project called "test" and save it as workspace called "Mytest". I close the 'test' project and open the "Mytest" workspace.
After downloading the current version(3.2.0) of Charts on GitHub and unzip it to the desktop, I open Charts directory and find Charts.xcodeproj.  I drag that file into the workspace just above test.  Next I click on test and find the "Embedded Binaries" section and click on the "+", select the "Charts.frameworkMacOS" and click Add.
Command B to build and get a Succeeded message.
I then select main.storyboard, then view under ViewController.  I am able to add both a button and a text field to the view from the Objects Library.
This is where I am stuck.  How to I add a LineChartView object?  It is not in selection list.
This is probably very obvious to many but being new to this environment it has me stumped and frustrated.
Thank you in advance for your help!
Answer: Your expectation is just wrong, that's all. Xcode has no provision for injecting additional view types into the Object library. It knows nothing of LineChartView as far as the library is concerned.
However, it does know that there is an NSView subclass called LineChartView. So, just drag in a plain vanilla NSView and use the Identity inspector to turn that view into a LineChartView.
Comment: The same answer is also in this tutorial: https://medium.com/@OsianSmith/creating-a-line-chart-in-swift-3-and-ios-10-2f647c95392e Might still be useful to study.
Comment: Thank You for your help... Off to the next problem. ;)


Grails URLMapping to Response Codes doesn't work if the request is POST

Question: I am a little crazy about this.
At first, my mapping is like below
<code>"500"(view:'/error/exception')
</code>
But, then we found, if the exception is throw in Spring Security code, the error page is not correct. By looking the source code, I change the mapping from view to action
<code>"500"(controller: "error", action: "exception")
</code>
and, in the action I will send a redirect request to another action which will render view. Seems everything work.
However, today I found if the request which cause exception is GET, it works, if it is a POST, then nothing rendered, it just return 404 to browser.
Could anybody tell me how to walkaround it?
Answer: Found a walkaround.
Config mapping as:
<code>"500"(view:'/error/exception')
</code>
In the view,  write an redirect
<code><% response.sendRedirect("/xxx/error/exception") %>
</code>
Then , render view in the ErrorControl, exception action.
Waiting for better solution.


Find the pointwise limit and determine if convergence is uniform

Question:
Find the pointwise limit of $f_n(x)=nx^n(1-x^n)$ and determine if the convergence is uniform.

Solution
For $x=1$
$$\lim_{n\to\infty}(nx^n(1-x^n))\to 0$$
For $0\le x<1$
$$\lim_{n\to\infty}(nx^n(1-x^n))\to0$$
as $x^n\to0$ as $n\to\infty$.
Thus the pointwise limit of $f_n(x)$ is $f(x)=0$.
Determine if the convergence is uniform:
We use,
$$\sup\vert f_n(x)-f(x)\vert<\epsilon$$
$$\sup\vert nx^n(1-x^n)-0\vert$$
$$\sup\vert nx^n(1-x^n)\vert$$
$$\sup \vert nx^n-nx^{2n}\vert$$
We want too find the largest possible value of this function, we take the derivative set to $0$.
$$\frac{d}{dx}(nx^n-nx^{2n})=0$$
$$n^2x^{n-1}-2n^2x^{2n-1}=0$$
$$x^{n-1}-2x^{2n-1}=0$$
$$x^{n-1}(1-2x^{n})=0$$
We can then find the trivial solution $x^{n-1}=0$ and the solution,
$$x=\sqrt[n]{\frac{1}{2}}$$
Is this a correct solution? Or have I made an error?
As $n\to\infty$, $\sqrt[n]{\frac{1}{2}\to1$, which is obviously not the largest value.
Answer: Your pointwise limit is O.K.
Furthermore: $f_n(\sqrt[n]{\frac{1}{2}})=\frac{n}{4}$ for all $n$. This shows that the convergence is not uniform.
Comment: Thank you, I used $x^n=\sqrt[n]{\frac{1}{2}}$ not $x$.
Answer: It is always interesting to plot graphical representations concretizing algebraic/analytic proofs. Here it is for the 8 first curves with coordinates of maximum (red stars)
$$(\sqrt[n]{\frac12}, \ \frac{n}{4}).$$


A range-restriction of a function?

Question: Let $f:A \longrightarrow B$ be a function. What do we call the function (if it has a name !) $f:A \longrightarrow C$ where $C\subset B$. A "range-restriction of $f$"?
Comment: This is very book/author dependent. While most books don't name such a thing, one that does (Topology and Groupoids) just calls it a restriction and writes $f\mid A,C$.
Comment: Depending on your definition of function, if $f$ is a function $A \to B$ such that $f(a) \in C$ for all $a \in A$, then $f$ itself is already a function $A \to C$.
Comment: A closely related question that asks about changing both is [here](https://math.stackexchange.com/q/2232277/26369)
Answer: It may not even be a function.  If there is some $a \in A$ that gets mapped to a point in $B \setminus C$ it isn't a function any more.  You can start with  the set of points that have image in $C$.  This is often denoted $f^{-1}(C)$ even though $f$ may not have an inverse.  You might call that $A'$ and then you can talk about $f$ restricted to $A'$, which we write $f_{\big|A'}$.
Answer: It really depends on who is talking what the restricted range function would be. Many authors omit this altogether. For instance $f:\mathbb{R} \to \mathbb{R}$ defined by $f(x)=\sin(x)$. Many authors will define it as above but many will just haphazardly define the co-domain to be whatever they want (on-the-fly). But formally $g:\mathbb{R} \to [-1,1]$ defined by $g(x)=\sin x$ is a defferent function than $f$.
I don't think there is a single standard notation for this besides using the arrow between the domain and codomain.
Answer: If you are working in a part of mathematics where things are phrased in categorical terms, you could call such a function a lift of $f$ by the inclusion map $C\rightarrow B$.
If you are not working in such a field, you're probably best off just saying "range restriction" and explaining what you mean. Possibly, you're working in a field where the codomain of a function isn't even that relevant, and you can just say that $f$ is already a function $A\rightarrow C$ if $f(a)\in C$ for all $a\in A$.

It's worth naming the opposite process: If you have a function $g:A\rightarrow C$, you can expand its range to $B$ by composing $g$ with the inclusion map $i:C\rightarrow B$ to get a function $i\circ g:A\rightarrow B$. You are trying to describe the opposite process.
That is, if you start with a function $f:A\rightarrow B$, you are trying to find a function $g:A\rightarrow C$ such that $f=i\circ g$. This is relationship can be described by saying that $g$ is a lift of $f$ through $i$ (or, if the existence of such a $g$ is all you care about, that $f$ factors through $i$).
That said, the word "lift" might give the wrong idea because it has pretty heavy connotations about either being a process to derive something interesting from a commutative diagram or being a process to "undo" some sort of quotient. If you're not in a field where these things are relevant (or where people talk about inclusion maps for other reasons), being more plainly spoken is advisable.

A range-restriction of a function?


If React Component Library needs React as a peer dependency, how can I make Preact using it?

Question: Suppose I have a React Component library called myLibrary.
myLibrary has exported a <Hello /> Component:
import React from 'react';

function Hello() {
  return
World

}

And myLibrary's package.json specific React as a peer dependency.
Which means it doesn't install React when I npm install it in my other project.
How can I use myLibrary in my preact project without installing React?
In my preact project:
yarn add myLibrary
// main.js
/** @jsx h */
import { Hello } from 'myLibrary';
import { h, render } from 'preact';

render(<Hello />, document.body);

How can I make it all happen without installing React?
Comment: Are you aliasing react to `preact/compat` anywhere?
Comment: No, I think I should do that.
Comment: @JosephWang did you ever end up solving this issue?
Comment: @elethan I think preact-compat is the solution
Answer: This is what preact-compat is for! You'll want to implement per the readme here: https://github.com/developit/preact-compat


How to delete a particular child in firebase real time (Angular 7)

Question: I have been stuck in trying to delete a particular child in my firebase real time database by a button click. A paginator is available with the list of the child i intend to delete on request.
Below is how far i have gone.I have tried all possible tutorial online but none seems to work.Either it deletes the entire parent node or it shows a successful message but nothing worked.

    <mat-form-field fxFlex="60%">
        <input matInput type="text" (keyup)="doFilter($event.target.value)" placeholder="Filter">
    </mat-form-field>

    <ng-container matColumnDef="key">
         Action

            Approve |
            Delete

    </ng-container>
    <ng-container matColumnDef="name">
         Name
         {{element.name}}
    </ng-container>

    <ng-container matColumnDef="phone">
         PhoneNumber
         {{element.phone}}
    </ng-container>

    <ng-container matColumnDef="cartype">
         Car Type
         {{element.cartype}}
    </ng-container>

    <ng-container matColumnDef="destination">
         Destination
         {{element.destination}}
    </ng-container>

    <ng-container matColumnDef="date">
         Date
         {{element.date | date: 'dd/MM/yyyy'}}
    </ng-container>

    <ng-container matColumnDef="time">
         Time
         {{element.time}}
    </ng-container>
    <ng-container matColumnDef="location">
         Your Location
         {{element.location}}
    </ng-container>

    <ng-container matColumnDef="numberOfPersons">
         No of Persons
         {{element.numberOfPersons}}
    </ng-container>

    <ng-container matColumnDef="price">
         Trip Price
         {{element.price}}
    </ng-container>

<mat-paginator [pageSize]="6" [pageSizeOptions]="[2, 4, 6, 10, 20]">
</mat-paginator>

Ts
delete(key) {
  this.ph.scheduledRideSingle.remove(key).then(() => {
    alert('Success');
  });
}

Ph.ts
[![constructor() {
       this.scheduledRideSingle = firebase.database().ref(`userProfile/ScheduledRides`);

     }

  public scheduledRideSingle: any;

Answer: You need to use remove():

remove
Removes the data at this Database location.
Any data at child locations will also be deleted.

https://firebase.google.com/docs/reference/js/firebase.database.Reference#remove
For example:
var adaRef = firebase.database().ref('users/ada');
adaRef.remove()
  .then(function() {
    console.log("Remove succeeded.")
  })
  .catch(function(error) {
    console.log("Remove failed: " + error.message)
  });

If you want to delete a particular node then do:
firebase.database.ref("userProfile/ScheduledRides").child(key).remove();

Comment: this solved it `delete(uid) {
  firebase.database().ref(`/userProfile/${uid}/ScheduledRides`).remove().then(() => {
alert('Successfully Deleted');
  });
}`
Comment: thanks. Will try out and give  feedback. However i have updated my question please check it out.
Comment: Okay I saw the image, in ur database u have `userProfile` node and under it you have an ID, you need to access that ID to be able to delete ScheduledRides
Comment: `firebase.database.ref("userProfile").child(uid). child("ScheduledRides").remove();`
Comment: Yeah it did. Thanks
Comment: correct, you need to traverse the database from up to down, to be able to delete the node
Comment: Yeah, Thanks putting me through though


Como converter TIMESTAMP/DATETIME em GregorianCalendar?

Question: Como faço para converter um TIMESTAMP ou DATETIME do MySQL em um GregorianCalendar do Java? Ou uma ideia melhor?
Na classe, o campo dataCadastro é do tipo GregorianCalendar. Estou gravando no banco no tipo TIMESTAMPdd-MM-yyyy 00:00:00.
Agora quero fazer o contrário, pegar do banco e gerar o GregorianCalendar para compor o objeto.
A ideia é manter os dados completos da data de cadastro do usuário!
Como fazer?
Answer: Timestamp ts = seuTimeStamp;
GregorianCalendar c = new GregorianCalendar();
c.setTime(ts);

ou, se for o Date
Date d = seuDate;
GregorianCalendar c = new GregorianCalendar();
c.setTime(d);

Comment: da mesma forma... só que ao inves de usar o getInstance.. você faz um new GregorianCalendar( )
Comment: GregorianCalendar. Não Calendar!

Como faz?


VBA to print to access tables

Question: I am building a library database and i have a working script to probe a web database using the ISBN number and return data about the book. I have successfully made the data print to the immediate window using debug.print and then the specific property of the object. I am now wanting to print the data retrieved straight in to the database.
here is my code for the ISBN search:
Option Compare Database
    Dim BookTitle As String
    Dim BookTitleLong As String
    Dim BookAuthorsText As String
    Dim BookPublisherText As String
    Dim BookSummary As String
    Dim BookNotes As String
    Dim accessKey As String

Private Sub Class_Initialize()
    'Your isbnDB access key'
    accessKey = "xxxxxx" 'Working access key here
End Sub
Property Get Title() As String
    Title = BookTitle
End Property
Property Get TitleLong() As String
    TitleLong = BookTitleLong
End Property
Property Get AuthorsText() As String
    AuthorsText = BookAuthorsText
End Property
Property Get PublisherText() As String
    PublisherText = BookPublisherText
End Property
Property Get Summary() As String
    Summary = BookSummary
End Property
Property Get Notes() As String
    Notes = BookNotes
End Property

Public Function Lookup(ISBN As String) As Boolean
    Lookup = False
    Dim xmlhttp
    Set xmlhttp = CreateObject("MSXML2.xmlhttp")
    xmlhttp.Open "GET", "https://isbndb.com/api/books.xml?access_key=" & accessKey & "&results=texts&index1=isbn&value1=" & ISBN, False
    xmlhttp.send
    'Debug.Print "Response: " & xmlhttp.responseXML.XML'
    Dim xmldoc
    Set xmldoc = CreateObject("Microsoft.XMLDOM")
    xmldoc.async = False
    'Note: the ResponseXml property parses the server's response, responsetext doesn't
    xmldoc.loadXML (xmlhttp.responseXML.XML)
    If (xmldoc.selectSingleNode("//BookList").getAttribute("total_results") = 0) Then
        MsgBox "Invalid ISBN or not in database"
        Exit Function
    End If
    If (xmldoc.selectSingleNode("//BookList").getAttribute("total_results") > 1) Then
        MsgBox "Caution, got more than one result!"
        Exit Function
    End If
    BookTitle = xmldoc.selectSingleNode("//BookData/Title").Text
    BookTitleLong = xmldoc.selectSingleNode("//BookData/TitleLong").Text
    BookAuthorsText = xmldoc.selectSingleNode("//BookData/AuthorsText").Text
    BookPublisherText = xmldoc.selectSingleNode("//BookData/PublisherText").Text
    BookNotes = xmldoc.selectSingleNode("//BookData/Notes").Text
    BookSummary = xmldoc.selectSingleNode("//BookData/Summary").Text
    Lookup = True
End Function

and here is the code i have used to print to the immediate window
Public Function t()
    Dim book
    Set book = New ISBN
    book.Lookup ("0007102968")
    Debug.Print book.Title
    Debug.Print book.PublisherText
    Debug.Print book.AuthorsText
    Debug.Print book.TitleLong
    Debug.Print book.Summary
    Debug.Print book.Notes

End Function

this is all based off this question asked a few years back:
ISBN -> bookdata Lookup to fill in a database
i would also like to be able to input the ISBN through a form if anyone can help with that :)
Comment: So... you want to know how to write an `INSERT` statement? Or is there any reason that won't do? Really, this is basic stuff, and you should read in how to store things in a database yourself, and make a good-faith attempt. Then you can ask questions if things don't work as expected.
Comment: Well, we're not an "I can't code so please code for me for free" site. We are willing to help, but only if you put in the work and make a good-faith attempt yourself. There are numerous resources on how to execute queries. Read about them, and specifically calling queries from VBA (because that's where your variables reside), and using parameters.
Comment: hi thanks for the pointer, I'm completely new to this. i have tried running this:

      `StrSQL = "INSERT INTO Table1 (Title) VALUES (book.Title)"`

but instead of inserting the object property `book.Title` it brings up a text box for me to fill it in manually
Comment: Don't enclose variable references within quotes and concatenate instead. Text field parameters need apostrophe delimiters. Try:`StrSQL = "INSERT INTO Table1 (Title) VALUES ('" & book.Title & "')"`
Comment: @ErikvonAsmuth i appreciate what you are saying but i have been trying to fix this alone for the last day and a half and i haven't asked you to write any code for me i simply asked for some pointers on where to go next.
Comment: @June7 thanks for the help, i see what you mean about not calling the variables in the quotes but i have not seen any success with your revision to my SQL commant
Comment: @SamBrown The main problem is that you're not sharing your attempts, and why they haven't worked, in your question, nor are you sharing any table structure. A simple google on `Access VBA Insert Table` will result in [this question](https://stackoverflow.com/questions/25044447/how-to-insert-values-into-the-database-table-using-vba-in-ms-access), which looks perfectly valid for your use case.
Comment: Furthermore, your original question contained your private isbnDB access key. Please change that key, since it's private (not to be shared publicly on the internet).
Comment: @ErikvonAsmuth i found the article you have linked following the reference to you made to `INSERT` statements but am still struggling. thank you for the help
Comment: What does 'not seen any success' mean, what happens - error message, wrong results, nothing? You haven't shown how you use the constructed SQL string. Edit your question with this information. Are you able to perform the INSERT with an Access query object using static parameter?
Answer: You can try the following approach.
First of all, create a user-defined data type to store the book data:
Public Type Book
    ISBN As String
    Title As String
    TitleLong As String
    AuthorsText As String
    PublisherText As String
    Summary As String
    Notes As String
End Type

Then create an insert query and pass the book values as parameters. Let's name the query qryAdd.
PARAMETERS prmISBN Text (255),
           prmTitle Text (255),
           prmPublisherText Text (255),
           prmAuthorsText Text (255),
           prmTitleLong Text (255),
           prmSummary LongText,
           prmNotes LongText;

INSERT INTO T ( ISBN, Title, PublisherText, AuthorsText, TitleLong, Summary, Notes )
SELECT prmISBN AS ISBN,
       prmTitle AS Title,
       prmPublisherText AS PublisherText,
       prmAuthorsText AS AuthorsText,
       prmTitleLong AS TitleLong,
       prmSummary AS Summary,
       prmNotes AS Notes;

'Change T to the name of your table and update the field names.

Lastly, the function to call the insert query where we pass the book to be inserted.
Public Function InsertToDatabase(b As Book) As Boolean
    With CurrentDb().QueryDefs("qryAdd")
        .Parameters("[prmISBN]").Value = b.ISBN
        .Parameters("[prmTitle]").Value = b.Title
        .Parameters("[prmTitleLong]").Value = b.TitleLong
        .Parameters("[prmPublisherText]").Value = b.PublisherText
        .Parameters("[prmAuthorsText]").Value = b.AuthorsText
        .Parameters("[prmSummary]").Value = b.Summary
        .Parameters("[prmNotes]").Value = b.Notes
        .Execute dbFailOnError
    End With

    'all good
    InsertToDatabase = True
End Function

To test it:
Sub Test()
    Dim b As Book
        b.ISBN = "aaa"
        b.Title = "bbb"
        b.TitleLong = "ccc"
        b.PublisherText = "ddd"
        b.AuthorsText = "eee"
        b.Summary = "fff"
        b.Notes = "ggg"

    If InsertToDatabase(b) Then MsgBox "Done!"
End Sub

VBA to print to access tables


SIGABRT error Thread 0 crashed iOS

Question: Iam new to iOS and have developed an app. The issue is the app works fine when I use it but on the client side it crashes with the following log:-
<code>Incident Identifier: 74AEF6C5-98CE-45D3-A7F3-67D54FD66D4D
CrashReporter Key:   TODO
Hardware Model:      iPhone5,2
Process:         MobileiOS [246]
Path:            /var/mobile/Containers/Bundle/Application/F9FF0CF3-DC56-428C-8CB0-40C31A3B4434/MobileiOS.app/MobileiOS
Identifier:      com.mjapps.MobileXam
Version:         1.0 (1.0)
Code Type:       ARM
Parent Process:  ??? [1]

Date/Time:       2016-03-29 08:26:57 +0000
OS Version:      iPhone OS 9.2.1 (13D15)
Report Version:  104

Exception Type:  SIGABRT
Exception Codes: #0 at 0x20e51c84
Crashed Thread:  0

Thread 0 Crashed:
0   libsystem_kernel.dylib              0x20e51c84 __pthread_kill (in libsystem_kernel.dylib) + 8
1   libsystem_c.dylib                   0x20de80c5 abort (in libsystem_c.dylib) + 109
2   MobileiOS                     0x00ac8fc0 0x31000 + 11108288
3   MobileiOS                     0x00a03fdd 0x31000 + 10301405
4   MobileiOS                     0x00a035dd 0x31000 + 10298845
5   MobileiOS                     0x00a027b3 0x31000 + 10295219
6   MobileiOS                     0x009fc45b 0x31000 + 10269787
7   MobileiOS                     0x003de9bc 0x31000 + 3856828
8   MobileiOS                     0x000b8c64 0x31000 + 556132
9   MobileiOS                     0x0008a7bc 0x31000 + 366524
10  MobileiOS                     0x0008b028 0x31000 + 368680
11  MobileiOS                     0x003ab754 0x31000 + 3647316
12  MobileiOS                     0x00a0ce87 0x31000 + 10337927
13  MobileiOS                     0x00a5ce85 0x31000 + 10665605
14  MobileiOS                     0x009a64cd 0x31000 + 9917645
15  MobileiOS                     0x009ab415 0x31000 + 9937941
16  UIKit                               0x256960c9 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] (in UIKit) + 673
17  UIKit                               0x25696209 -[UITableView _createPreparedCellForGlobalRow:willDisplay:] (in UIKit) + 69
18  UIKit                               0x2568596d -[UITableView _updateVisibleCellsNow:isRecursive:] (in UIKit) + 2269
19  UIKit                               0x2569aa47 -[UITableView _performWithCachedTraitCollection:] (in UIKit) + 79
20  UIKit                               0x2543c16f -[UITableView layoutSubviews] (in UIKit) + 179
21  UIKit                               0x2534da83 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] (in UIKit) + 715
22  QuartzCore                          0x23429ad5 -[CALayer layoutSublayers] (in QuartzCore) + 129
23  QuartzCore                          0x234251d1 CA::Layer::layout_if_needed(CA::Transaction*) (in QuartzCore) + 353
24  QuartzCore                          0x23425061 CA::Layer::layout_and_display_if_needed(CA::Transaction*) (in QuartzCore) + 17
25  QuartzCore                          0x23424581 CA::Context::commit_transaction(CA::Transaction*) (in QuartzCore) + 369
26  QuartzCore                          0x23424233 CA::Transaction::commit() (in QuartzCore) + 615
27  QuartzCore                          0x2341d9ef CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) (in QuartzCore) + 139
28  CoreFoundation                      0x2117cb21 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ (in CoreFoundation) + 21
29  CoreFoundation                      0x2117ae17 __CFRunLoopDoObservers (in CoreFoundation) + 283
30  CoreFoundation                      0x2117b255 __CFRunLoopRun (in CoreFoundation) + 973
31  CoreFoundation                      0x210cdbb9 CFRunLoopRunSpecific (in CoreFoundation) + 517
32  CoreFoundation                      0x210cd9ad CFRunLoopRunInMode (in CoreFoundation) + 109
33  GraphicsServices                    0x22347af9 GSEventRunModal (in GraphicsServices) + 161
34  UIKit                               0x253b9fb5 UIApplicationMain (in UIKit) + 145
35  MobileiOS                     0x00124568 0x31000 + 996712
36  MobileiOS                     0x000beab4 0x31000 + 580276
37  MobileiOS                     0x000bea74 0x31000 + 580212
38  MobileiOS                     0x000708e0 0x31000 + 260320
39  MobileiOS                     0x003ab754 0x31000 + 3647316
40  MobileiOS                     0x00a0ce87 0x31000 + 10337927
41  MobileiOS                     0x00a5ce85 0x31000 + 10665605
42  MobileiOS                     0x00a6054b 0x31000 + 10679627
43  MobileiOS                     0x00adbe88 0x31000 + 11185800
44  MobileiOS                     0x009b300d 0x31000 + 9969677
45  libdyld.dylib                       0x20d80873 start (in libdyld.dylib) + 3
</code>
The client does not want to give us a test user hence I cannot debug it. Any guidance where this might be failing would help me in on the right path. Any help is appreciated.
Comment: You have to symbolicate the crash report.
Comment: As @trojanfoe said, you will need to symbolicate this crash report to gather any relevant information from it - as it stands all you have is memory addresses. Guide here: http://jmillerdev.net/symbolicating-ios-crash-files-xamarin-ios/
Comment: It's here: `0x00ac8fc0`.
Comment: @trojanfoe Thanks for the quick reply. I cannot really understand what this is. Could you please explain further
Comment: @trojanfoe Iam using Xamarin so Iam really not able to figure out this. This is my first attempt at ios programming.
Comment: @BytesGuy thanks for the link. But It says I need to debug it locally to synbolicate it. But I cant do that since it only crashes at the client side
Comment: If you produce the app bundle and you have the crash report then you have everything you need.
Comment: @trojanfoe the crash report has to be from the device on which the app crashed right?
Comment: Not really.  At the end of the day as long as you have the crash address and access to the `.dsym` "file" for the correct version of the app, then you can use `atos` to get the source code location of the crash.
Comment: @trojanfoe how can you say where exactly the error could be. I mean you said its at `0x00ac8f0` how could you point out that?
Answer: For completeness, I'll add an answer here for my blog post that was linked in the comments above by BytesGuy.
You need the .app that you built which is running on the client device. You also need a .dSYM that matches this .app. It's unlikely you have this unless you specifically kept it from when you built the .app file. If you still have it sitting in your bin/Release|Debug folder - use that. If not, you'll have to build a new .app and .dSYM. Keep both this time somewhere.
The client needs to use this new version of the .app file and produce the crash again. Now that you kept the .app and .dSYM that matches it, you can symbolicate any new crash reports which come in using the techniques in my blog.
Comment: Thanks for the answer. I tried doing it and I could manage to symbolicate it. I get `extra_method_info_offsets ` as the error. Do you know what this could mean?

SIGABRT error Thread 0 crashed iOS


What happens to Webform data when a component is deleted? Can I change a component type?

Question: I inherited a complicated Webform with several hundred submissions. One of the components was a Textfield used to capture the email address of the form submitter. For some reason this is a Textfield and not an E-mail field which prevents me from using the E-mail address to send a confirmation email.
If I were to delete the textfield email component what would happen to all the data? I'm assuming it would be erased.
Is there any way to change the type of a form component while still preserving the data?
Update: I am using Drupal 7 and Webform 3.19
Comment: Are you using the [Webform module](https://drupal.org/project/webform) for Drupal 6 or Drupal 7?
Comment: Drupal 7. Sorry should have mentioned that.
Comment: In Drupal 7,  there is a place to change the field name in the database. But I'm not sure how to do it
Answer: When a Webform component is deleted, the submitted data for that component are deleted.  The data for the form's other components are preserved.  I've confirmed these by querying the webform_submitted_data MySQL table on Webform 7.x-3.23.
As user calebtr indicated, there's a "Private" checkbox for each component that can be used as an ersatz delete-but-save-the-data feature, except that logged-in users with the privilege to read results will still see the component on the form (not only in the results).  These fields could be hidden using a stylesheet or custom template, potentially after corralling them into a private fieldset.
The Webform UI does not allow the changing of component type.  I see this information stored in webform_component.fieldset, so you could probably modify it there.  You'd also want to update the component settings in the "extra" column.
Answer: Consider if you really need the data structure intact or not, or if you just need the data preserved. Are you using the webform data in a view? Is anyone dependent on the automated 'Analysis' that Webform provides?
If you only need to send confirmation emails for new submissions, then add the new field with the same labeling, a different key and the correct type, and then suppress the original field by marking it as 'Private' in the field settings.
Private fields are shown to users who have access to results, so this may not work for your use case.
Alternatively, use the Node Clone module to clone the webform and change that field without either losing data or having to re-key everything.
Answer: If the field you delete is unique to a content type, then the field is gone from the database (that includes it's data). If you delete a shared field from, the field is removed from that content type along with the data unique to the content type.
If you find that you need to keep the data associated with the field but you need a different type of field for the data, you need to plan ahead.

Create the new field.
Devise a way to migrate the data from the old field to the new field.
Delete the old field.

A good solution might be to use Feeds module (to import to fields) and Views Data Export Module (to export fields to the spreadsheet). The procedure would be:
Setup a view that lists all of your textfield values and displays all of the fields you want to migrate. Then data export and choose CSV format.
Use feeds to import the data to D7. Just map each exported field to your preferred field.
on the other hand you might want to read this tutorial too
Comment: Will Feeds import Webform data?
Comment: Follow up to MPD: Are Webform components considered fields? Webform does not allow you to define your own component types except through custom modules so I would assume Webform components are all shared fields?
Comment: Kevin I'm not sure but I think yea, you could try it anyway, and in case feeds didnt work out you can try webform import http://drupal.org/project/webform_import


android.content.res.Resources$NotFoundException: Resource ID #0x0 Android error

Question: I am Creating an ArrayAdapter's Super class in which I am binding the data I receive from the object and put them into the TextViews.
The code is not any complicated and I have double checked the ids of all the TextViews in my XML.
And I have checked all the other questions with the same title.
None of them seem to work in this case.
Attaching my code below.
public class EarthquakeAdapter extends ArrayAdapter<Earthquake>
    {
        public EarthquakeAdapter(Context context, int resource) {
            super(context, resource);
        }
        public EarthquakeAdapter(Activity activity, ArrayList<Earthquake> Earthquakes)
        {
            super(activity,0, (List<Earthquake>) Earthquakes);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            super.getView(position, convertView, parent);
            View ListItemView = convertView;
            if(ListItemView == null)
            {
                ListItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.earthquake_list_item, parent, false);
            }

            Earthquake currentItem = getItem(position);

            TextView magnitude = (TextView)
            ListItemView.findViewById(R.id.magnitude);
            //Double m = ;
            magnitude.setText(""+currentItem.getmMag());

            TextView location = (TextView) ListItemView.findViewById(R.id.Location);
            location.setText(currentItem.getmLocation());

            TextView date = (TextView) ListItemView.findViewById(R.id.date);
            date.setText(currentItem.getmDate());

            return ListItemView;
        }

and then there is the xml file.
    <?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:id="@+id/list_view_container">

    <TextView
        android:id="@+id/magnitude"
        android:layout_width="0dp"
        android:layout_height="60dp"
        android:layout_weight="1"
        tools:text="7.6"/>
    <TextView
        android:id="@+id/Location"
        android:layout_width="0dp"
        android:layout_height="60dp"
        android:layout_weight="1"
        tools:text="San Fransisco"/>
    <TextView
        android:id="@+id/date"
        android:layout_width="0dp"
        android:layout_height="60dp"
        android:layout_weight="1"
        tools:text="Date"/>

</LinearLayout>

This is my Earthquake Class.
public class Earthquake
     {
        private double mMag;
        private String mLocation;
        private String mDate;

        public Earthquake(double Mag, String Location, String Date){
            mMag = Mag;
            mLocation = Location;
            mDate = Date;
        }

        public String getmDate() {
            return mDate;
        }

        public double getmMag() {
            return mMag;
        }

        public String getmLocation() {

            return mLocation;
        }
    }

and This is the Error LOG.
06-11 20:38:36.570 9359-9359/com.example.android.quakereport W/ResourceType: No package identifier when getting value for resource number 0x00000000 06-11 20:38:36.571 9359-9359/com.example.android.quakereport D/AndroidRuntime: Shutting down VM 06-11 20:38:36.581 9359-9359/com.example.android.quakereport E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.quakereport, PID: 9359
   android.content.res.Resources$NotFoundException: Resource ID #0x0
       at android.content.res.Resources.getValue(Resources.java:1369)
       at android.content.res.MiuiResources.getValue(MiuiResources.java:145)
       at android.content.res.Resources.loadXmlResourceParser(Resources.java:2824)
       at android.content.res.Resources.getLayout(Resources.java:1183)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:425)
       at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:378)
       at android.widget.ArrayAdapter.getView(ArrayAdapter.java:369)
       at com.example.android.quakereport.EarthquakeAdapter.getView(EarthquakeAdapter.java:28)
       at android.widget.AbsListView.obtainView(AbsListView.java:2346)
       at android.widget.ListView.makeAndAddView(ListView.java:1876)
       at android.widget.ListView.fillDown(ListView.java:702)
       at android.widget.ListView.fillFromTop(ListView.java:763)
       at android.widget.ListView.layoutChildren(ListView.java:1685)
       at android.widget.AbsListView.onLayout(AbsListView.java:2148)
       at android.view.View.layout(View.java:16653)
       at android.view.ViewGroup.layout(ViewGroup.java:5438)
       at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
       at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
       at android.view.View.layout(View.java:16653)
       at android.view.ViewGroup.layout(ViewGroup.java:5438)
       at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:435)
       at android.view.View.layout(View.java:16653)
       at android.view.ViewGroup.layout(ViewGroup.java:5438)
       at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
       at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
       at android.view.View.layout(View.java:16653)
       at android.view.ViewGroup.layout(ViewGroup.java:5438)
       at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
       at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)
       at android.widget.LinearLayout.onLayout(LinearLayout.java:1495)
       at android.view.View.layout(View.java:16653)
       at android.view.ViewGroup.layout(ViewGroup.java:5438)
       at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
       at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
       at com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:2680)
       at android.view.View.layout(View.java:16653)
       at android.view.ViewGroup.layout(ViewGroup.java:5438)
       at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2198)
       at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1958)
       at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1134)
       at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6045)
       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:860)
       at android.view.Choreographer.doCallbacks(Choreographer.java:672)
       at android.view.Choreographer.doFrame(Choreographer.java:608)
       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:846)
       at android.os.Handler.handleCallback(Handler.java:739)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:148)
       at android.app.ActivityThread.main(ActivityThread.java:5441)
       at java.lang.reflect.Method.invoke(Native Method)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)

Comment: Please show us your Earthquake class and the logcat as well
Comment: I am unable to understand where are you setting values in Earthquake class to the variables mMag,mLocation,mDate? I think you need to set values while calling constructor
Comment: @AkhilSaraswat It's an arraylist passed to the constructor...
Comment: Remove the `super` call in `getView()`. You've passed an invalid layout resource ID in the three-argument constructor - which is leading to that Exception when `ArrayAdapter` tries to inflate it - and you're not using the `super` return anyway, since you're inflating the layout yourself.
Comment: @MikeM. Your comment helped. It'ss not showing any errors. thankyou. :D

And thanks everyone for helping. :)
Answer: The problem is in the getView() method of EarthquakeAdapter class
the statement super.getView() was causing some issue. I removed it and its working fine now.
Refer to the comment of @MikeM in the question itself.

Remove the super call in getView(). You've passed an invalid layout resource ID in the three-argument constructor - which is leading to that Exception when ArrayAdapter tries to inflate it - and you're not using the super return anyway, since you're inflating the layout yourself
Answer: I think you need to fix your constructors. You only need one.
public class EarthquakeAdapter extends ArrayAdapter<Earthquake> {
    public EarthquakeAdapter(Context context, ArrayList<Earthquake> earthquakes) {
        super(context, 0, earthquakes);
    }

And you should not need to call super.getView
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final Earthquake earthquake = getItem(position);

        View v = convertView;
        if(v == null) {
            v = LayoutInflater.from(getContext()).inflate(
                R.layout.earthquake_list_item, parent, false);
        }

        return v;
    }

Otherwise, you need to determine what is happening at line 28 and what is zero valued there.
You may follow this example to define custom adapter
You may need to clean and rebuild the project to regenerate your resources.
Comment: Actually, it was the statement with super.getView() call.
I deleted it. Its now working. Thank you. :)
Comment: Yeah I thought you meant the super constructor
Answer: Try this
 Earthquake currentItem = new Earthquake(3.33,"someplace","05-05-05")
     currentItem=getItem(position);

in place of
 Earthquake currentItem = get(position);        `//getItem(position);`

if it work you need to set values of the variables declared in Earthquake class
This might solve your problem
Declare member variables
Context ctx;
ArrayList<Earthquake> Earthquake;
    public EarthquakeAdapter(Activity activity, ArrayList<Earthquake> Earthquakes)
            {
               super(activity,0, (List<Earthquake>) Earthquakes);
               Ctx=activity;
               Earthquake=this.Earthquake;
            }

now where you are doing Earthquake currentItem = getItem(position);
do this
Earthquake currentItem=Earthquake.get(position);     `//getItem(position);`

basically you are not passing values received by EarthquakeAdapter.
Also check in this
    public Object getItem(int position) {
            return Earthquake.get(position);
        }
public int getCount() {
        return Earthquake.size();
    }
public long getItemId(int position) {
        return position;
    }

If this does not work show the code where you are setting the ArrayList<Earthquake> and calling adapter public EarthquakeAdapter(Activity activity, ArrayList<Earthquake> Earthquakes)
Comment: How does making a `new Earthquake` solve the problem?
Comment: If it doesn't solve but helps, you should post it as a comment. Not an answer
Comment: but getItem(int) is not a method of Earthquake class. How can call it through an object of it?
Comment: apologies my mistake
Comment: It will not solve your problem but if it works then the array list is not parsing properly to the constructor otherwise I might be wrong so kindly check that
Comment: i'll be careful next time
Comment: You realize this is [the wrong way](https://medium.com/@Sudhagar/android-array-adapters-what-most-of-the-tutorials-don-t-tell-you-90f898fb54a2) to write adapter anyway?


Database and Application on same physical server but on virtual machines

Question: Is it good practice to have the database of an application on the same physical server as the application but separated by a virtual machine?
Answer: It seems reasonable enough as long as there is enough resource - for the database server, be especially careful not to overcommit memory or CPU, and ensure that memory doesn't use the balloon driver.
Comment: Ignore memory and CPU ;) THe most likely overload candidate is IO - "the server has 2 dsics" instead of 20 ;)
Comment: Hi TomTom, how do you know?
Comment: Databases are disc IO intensive, but when virtualising we mitigate this by throwing memory at the problem.
Answer: "Good Practice" - personally I don't like running production DBs in VMs but if you want to do that then actually running them on the same host would be great as your virtual networking between the two would be FAR quicker than any regular physical networking available.


Problems with this stack implementation

Question: where is the mistake?
My code here:
 typedef struct _box
    {
        char *dados;
        struct _box * proximo;
    } Box;

    typedef struct _pilha
    {
        Box * topo;
    }Stack;

void Push(Stack *p, char * algo)
{
    Box *caixa;
    if (!p)
    {
        exit(1);
    }

    caixa = (Box *) calloc(1, sizeof(Box));
    caixa->dados = algo;
    caixa->proximo = p->topo;
    p->topo = caixa;
}

char * Pop(Stack *p)
{
    Box *novo_topo;
    char * dados;
    if (!p)
    {
        exit(1);
    }

    if (p->topo==NULL)
        return NULL;

    novo_topo = p->topo->proximo;

    dados = p->topo->dados;

    free(p->topo);
    p->topo = novo_topo;

    return dados;
}

void StackDestroy(Stack *p)
{
    char * c;
    if (!p)
    {
        exit(1);
    }
    c = NULL;
    while ((c = Pop(p)) != NULL)
    {
        free(c);
    }
    free(p);
}

int main()
{
int conjunto = 1;
char p[30], * v;
int flag = 0;

Stack *pilha = (Stack *) calloc(1, sizeof(Stack));

FILE* arquivoIN = fopen("L1Q3.in","r");
FILE* arquivoOUT = fopen("L1Q3.out","w");

if (arquivoIN == NULL)
{
    printf("Erro na leitura do arquivo!\n\n");
    exit(1);
}

fprintf(arquivoOUT,"Conjunto #%d\n",conjunto);

while (fscanf(arquivoIN,"%s", p) != EOF )
{
    if (pilha->topo == NULL && flag != 0)
    {
        conjunto++;
        fprintf(arquivoOUT,"\nConjunto #%d\n",conjunto);
    }

    if(strcmp(p, "return") != 0)
    {
        Push(pilha, p);
    }

    else
    {
        v = Pop(pilha);

        if(v != NULL)
        {
            fprintf(arquivoOUT, "%s\n", v);
        }
    }
    flag = 1;
}

StackDestroy(pilha);

return 0;

}
The Pop function returns the string value read from file.
But is not correct and i don't know why.
Comment: Although someone might be able to spot a problem, you have a higher chance of getting an answer if you include some details like what exactly is "not correct" about your program, what failure you are seeing, what you have tried to fix it, and so on.
Answer: You're not allocating any storage for the strings pointed to by dados - you're just re-using one string buffer (p) and passing that around, so all your stack elements just point to this one string.
Comment: Yes, exactly.  The `Box` objects that you're storing in the stack contain `char *` pointers -- they don't actually contain the strings themselves.  So, you create a `Box` pushed onto the stack, and it points to where `p` is, and then you change `p` in reading the next value, and since the `Box` already on the stack is still pointing to `p`, it's now pointing at the changed value.
Comment: Oh my god!
thank you very much!
=D

I have had spent many time with this problem, must be the lack of caffeine =)

Problems with this stack implementation


Self-signed certificate is not "trusted" by default?

Question: Self-signed certificate is not "trusted" by default? How can I make it trusted?
I used this tutorial for generate my .crt and .key - https://www.digitalocean.com/community/articles/how-to-create-a-ssl-certificate-on-nginx-for-ubuntu-12-04/
Comment: Just exactly like you'd trust me if I certify that I'm Elvis...
Answer:
Self-signed certificate is not "trusted" by default?

Obviously. Who would be trusted? A self-signed vertificate is self-contained ad as such does not have a master authority that is registere as trusted.

How can I make it trusted?

Have you tried reading the documentation? WHich is sort of the requirement to ask qustions here (professional capacity, minimum knowledge).
I found this on google:
https://help.ubuntu.com/12.04/serverguide/certificates-and-security.html
THat has a lot of interesting topics.
And this:
http://ubuntuforums.org/showthread.php?t=1914563
The title matches (Install self-signed cert like in Windows Trusted Root CA).
the general profesional advice is to - install a CA if you need it, or get a trusted certificate if that is too much work.

Self-signed certificate is not “trusted” by default?


jQuery: keeping references to jQuery object during application runtime

Question: I've got a question about treating references to jQuery objects.
Let suppose in my app I have a DOM element DIV with ID=some_widget, it is supposed to live during all the application runtime and be used quite often in the code.
1) So if I keep a reference to it in a global var during application runtime:
var someWidget = $("#some_widget")

it will create jquery objects once, but will consume memory during application run, but when I use someWidget it wont create jquery object again, so this can speed up the process.
2) if I will alway use the call of $("#some_widget") in the code, it won't consume memory constantly, but every time I use $. it will take time jQuery to construct the object.
Am I right? What approach is more sufficient?
Can keeping the references to many object end up with memory leak?
what does it depend on, what do you think?
Answer: Yes, you can cache your jQuery object by declaring it in a variable. This is in fact considered a best practice for re-used objects.
Answer: My understanding (although still a jQuery novice myself) is that the saving by caching the jQuery object comes from the fact that the DOM is not traversed each time you call the selector. So, for example, if you call $("#some_widget") multiple times in your code, jQuery will traverse the DOM each time to find the element with that ID. If you cache it once in the variable, then you can call jQuery methods on it the same as you would with the selector, but the DOM traversal is not required. I have done this in my code with realized performance improvements. I am not aware of any issues with memory leaks using the caching method, and much of my reading on the topic recommends caching as a best practice.
One other aside that can be helpful if you do this is adding a naming convention to cache variables of this type. For example, prepending a $ to the variable:
var $someWidget = $("#some_widget");

Some people don't like this, but I have found it useful when visually tracking which variables I can use jQuery functions on.
Comment: I'm one of those people; the extra $ makes it quite clear to me that I'm dealing with a cached jQuery object. I use it to make $this variables all the time (from $(this)).
Answer: Yes, you are correct. Only thing I would like to add is
var query_result = $("some_selector") is actually caching your query results into a variable for a later use. If the result of the query happens to be a widget, then that is being cached. Obvious advantage will be that when you are using this cached query, jQuery won't have to query the DOM again to build up results for you. But the disadvantage will be that the cached results are like a snapshot of the DOM at the instant when query was executed. So if at a later stage the dom has been manipulated, executing the $("previous_selector") will return something different than cached query_result and it might not be what you are expecting.
Not entirely sure about memory leaks, have seen lot of programmers use this caching technique and is recommended too.
Comment: Thanks for your replay. But what do you mean "if at a later stage the dom has been manipulated, executing the $("previous_selector") will return something different", what different it can return if its a widget? example?
Comment: You are just considering it from a widget point of view.
For example lets say your DOM is like this at page load:
`Item 1Item 2`. Now you cached all list items `var li_list = $(".foo li")`. Right now you you have 2 "li" cached in `li_list`.

Later you manipulated you DOM and it became something like this:
`Item 1Item 2Item 3`, if you were to run query again 'var new_list  = $(".foo li")' the variable `new_list` will have 3 li items, where as original `li_list` has just two.

I hope this explains it.
Comment: Yes if "widget" is an array of jq objects, it wont be dynamically updated. But if you get only on DOM element as widget (as in my example DIV) you will probably won't find such manipulation for this object that could lead to some problems in terms of what you described, no?
Comment: Yes, you are correct. In that case you don't have to worry about this sort of a problem.


Drupal 7 form missing from $form object during Ajax callback function

Question: I'm using this example code to create a 'add another field' to my custom Form. The form itself is quite big and showing a full example here isn't possible.
The problem I'm having is that when I hit my callback button to 'add another field' the $form variable is missing most of the form I wish to utilise. My form is an admin area only form, but using the above example works fine in my implementation as POC.
The form utilises vertical_tabs but I have also tried without. I have a lot of validation around this form and in essence it's being built of a yaml file but I can't work out why the form elements are missing during the ajax callback. $form_state contains all the values submitted by the form including the missing data from $form.
I had assumptions that #tree was the issue but, I have this set to TRUE from the start.
Answer: Just incase anybody wants to know the issue was I was trying to obtain a value from arg() and this was different for the ajax callback funtion. So in my hook_form function I set the following:
  // This is needed for the ajax callback
  if (arg(1) != 'ajax') {
    // We need to set the variable before we load the form.
    $form_state['value'] = arg(3);
    $key = arg(3);
  }
  else {
    // Ajax callback can now reference correct key.
    $key = $form_state['value'];
  }

This allowed me to obtain the correct value during the ajax callback function.
Comment: Yes, for most Ajax calls, they hit `system/ajax` path, so checking `arg()` won't result in much.


Improper integral of $\frac{x}{e^x-1}$

Question: This integral came up in an exercise on the estimation of the specific heat of a 1-D solid and is probably a standard integral, possibly one that can be solved by contour integration:
\begin{equation}
\int_0^{+\infty} \frac{x}{e^x-1} dx
\end{equation}
I have some rudimentary knowledge of contour integrals, but I can't come up with a proper path, also because of the many singularities along the imaginary axis. Any suggestion?
Answer: Make a change or variables, $e^{-x}=u$, and write the integral as
$$\int_0^\infty \frac{x e^{-x}}{1 - e^{-x}}dx$$
Now substituting gives
$$-\int_0^1 \frac{\log u}{1 - u}du $$
This is a known integral that evaluates to $\dfrac{\pi^2}{6}$.
If you want to prove it, you can use the dilogarithm. Let $1-u=x$, so that
$$-\int_0^1 \frac{\log(1 - x)}{x}dx$$
Now, since we're working on $(0,1)$ it is legitimate to use
$$\frac{{ - \log \left( {1 - x} \right)}}{x} = \sum_{n = 1}^\infty  {\frac{{{x^{n - 1}}}}{n}} $$
Integrating termwise gives
$$\int_0^t \frac{-\log(1 - x)}{x} dx = \sum_{n = 1}^\infty \frac{t^n}{n^2}  = \mathrm{Li}_2 (t)$$
Evaluating at $t=1$ gives
$$ -\int_0^1 \frac{\log(1 - x)}{x} dx = \sum_{n = 1}^\infty \frac{1}{n^2}  = \frac{\pi^2}{6}$$
Answer: Any text book which dicusses the Riemann Zeta function will likely have this.
We have for $\Re(z) \gt 1$, that
$$ \zeta(z) \Gamma(z) = \int_{0}^{\infty} \frac{t^{z-1}}{e^t - 1} \text{d}t$$
Your integral is therefore
$$\zeta(2)\Gamma(2) = \frac{\pi^2}{6}$$
For an online discussion, see this: http://www.math.utah.edu/~milicic/zeta.pdf
Comment: I pimped your `Re` symbol.
Comment: @PeterT.off: Thanks!

Improper integral of $\frac{x}{e^x-1}$


How to load data into an ArrayList after it's finished loading

Question: How to load data into an ArrayList after it's finished loading ?
I am facing the same issue. Log : D/DB: []
https://www.reddit.com/r/Firebase/comments/d1dyd4/androidfirebase_how_to_load_data_into_an/
How can I fix this. Thank you in advance.
db.collection("fastmode")
    .get()
    .addOnCompleteListener(new OnCompleteListener < QuerySnapshot > () {
        @Override
        public void onComplete(@NonNull Task < QuerySnapshot > task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot documentSnapshot: task.getResult()) {
                    String question = documentSnapshot.getString("question");
                    String answer = documentSnapshot.getString("answer");

                    Log.d("DB", question);
                    Log.d("DB", answer);
                    questions.add(question);
                }
            }
        }
    });

Log.d("DB", String.valueOf(questions));
Intent in = new Intent(getApplicationContext(), FastMode.class);
startActivity( in );

Answer: If you run your current code in a debugger and set some breakpoints, you'll see that Log.d("DB", String.valueOf(questions)) runs before any of the questions.add(question). This is because data is loaded from Firestore (and most modern cloud APIs) asynchronously.
All code that needs access to the data from the database needs to be inside the onComplete block. So something like:
db.collection("fastmode")
    .get()
    .addOnCompleteListener(new OnCompleteListener < QuerySnapshot > () {
        @Override
        public void onComplete(@NonNull Task < QuerySnapshot > task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot documentSnapshot: task.getResult()) {
                    String question = documentSnapshot.getString("question");
                    String answer = documentSnapshot.getString("answer");

                    Log.d("DB", question);
                    Log.d("DB", answer);
                    questions.add(question);
                }
                Log.d("DB", String.valueOf(questions));
                Intent in = new Intent(getApplicationContext(), FastMode.class);
                startActivity( in );
            }
        }
    });

Also see:

How to check a certain data already exists in firestore or not
Firebase Firestore get data from collection


Como simplificar o processo de verificar um determinado valor?

Question: Por exemplo, quando eu preciso verificar alguns determinados valores, eu crio um "método", semelhante a esse:
public function verificaString($campo)
{
    if (isset($_POST[$campo]) && (!empty($_POST[$campo]) && (is_string($_POST[$campo])))):
        (string)$var = filter_var(trim($_POST[$campo]), FILTER_SANITIZE_STRING);
        return $var;
    else:
        $var = 'Indisponível';
        return $var;
    endif;
}

Agora pensando nessa parte mais especificamente:

if (isset($_POST[$campo]) && (!empty($_POST[$campo])

Não existe uma maneira de simplificar esse processo?
Toda vez que eu preciso verificar se uma variável está setada e ela tiver um valor diferente de nulo, eu tenho que fazer exatamente isso? Não tem como simplificar esse procedimento?
Answer: Utilizar isset e utilizar !empty (no seu caso) é redundante, pois empty faz exatamente o contrário do isset (basicamente ele é !isset($var);) com a adição do comando de negação da variável. Ou seja:
empty($var); // true

é igual a:
!isset($var) || !$var; // true

O resultado de empty será o mesmo que !isset e negação (acima demonstrada). Ou seja, você pode adicionar na sua condição que seja apenas !empty.
Já no seu método, você pode utilizar early returns e remover o if/else do seu método o que deixará ele com uma melhor leitura e uma menor complexidade ciclomática:
public function verificaString($campo)
{
    if (empty($_POST[$campo]) || !is_string($_POST[$campo]))
    {
        return 'Indisponível';
    }

    return filter_var(trim($_POST[$campo]), FILTER_SANITIZE_STRING);
}

Perceba a inversão da instrução if que está validando se o valor, na superglobal $_POST, é vazia ou diferente de string. Caso for verdadeiro, retorna que é indisponível.
O else, não se faz mais necessário, pois, o return interrompe a execução do código. Caso o código não cair no if, pode ser realizado a sanitização da string.
Agora, saber se o método é útil ou não (simplificar a existência do método) é algo que não posso afirmar com tão pouco trechos de código.
Comment: Por favor, reveja o seu último código, parece que o retorno da função `is_string` está sendo passado como parâmetro de `empty` junto com o valor de `$_POST`.
Comment: O isset é diferente do empty. O empty verifica se não existe e não tem valor. O isset verifica se existe.
Comment: @lucascarvalho o `empty` é um construtor de linguagem e faz exatamente o que foi dito na resposta, como é citado também na documentação. Portanto é possível omitir o `isset` se utilizado o `empty`, sim.
Comment: O [isset()](http://php.net/manual/en/function.isset.php) verifica se uma variável está/foi **setada e não é nula**. Já o [empty()](http://php.net/empty) verifica se ela **está vazia**.
Comment: É exatamente como você disse @GabrielHeming. O empty com isset da maneira usada é uma redundância. Basta utilizar o empty que já é suficiente.
Comment: @AndersonCarlosWoss corrigdo, valeu pela informação
Comment: @LucasCarvalho leia novamente o que eu escrevi, o empty é o contrário do isset + a negação da variável. Veja o link: https://stackoverflow.com/questions/4559925/why-check-both-isset-and-empty ou o próprio manual
Comment: @UzumakiArtanis Havia faltado uma negação no `empty`, mas a definição escrita ainda está correta. Veja os comentários acima.
Comment: Sim, está certo :) Só estou dizendo que não é a mesma coisa. Podem fazer as mesmas coisas, mas não são as mesmas coisas.
Comment: @LucasCarvalho Em nenhum momento foi dito que são a mesma coisa. Apenas que estão redundantes no código.
Answer: Não sei se é exatamente isso que você procura mas vou arriscar uma maneira mais limpa e linda de verificar se suas variáveis via post estão sendo passadas:
Ex:
$nome = filter_input(INPUT_POST, 'nome', FILTER_SANITIZE_SPECIAL_CHARS);

Valor da requisitada variável em caso de sucesso, FALSE se o filtro falhar, ou NULL se o parâmetro variable_name é um variável não definida. Se a flag FILTER_NULL_ON_FAILURE é usada, ela retorna FALSE se a variável não é definida e NULL se o filtro falhar.
Para mais informações segue o manual do php, abraços e bons estudos garoto!!!
Answer: Utilizando o filter_input:
filter_input(INPUT_POST, $campo, FILTER_SANITIZE_STRING)

Há uma lista de constantes pré-definidas para os filtros.
Você pode então simplicar um pouco e reduzir a tua função junto do operador ternário:
public function verificaString($campo)
{
    return trim(filter_input(INPUT_POST, $campo, FILTER_SANITIZE_STRING)) ?:  'Indisponível';
}


Continuous stopping time property

Question:
Let $S,T$ be continuous stopping time with respect to filtration $\mathcal{G}_t$. If $\Lambda\in \mathcal{G}_{S\lor T}$, then $\Omega\cap \{S\leq T\}\in \mathcal{G}_T$

This problem is from Diffusion Markov Process and Martingale. Here is what I try...
$\Lambda\in \mathcal{G}_{S\lor T}$ iff $\Lambda\cap \{S\leq t\} \cap \{T\leq t\}\in \mathcal{G}_t$.
$\Lambda\cap \{S\leq T\}\in \mathcal{G}_{ T}$ iff $\Lambda\cap \{S\leq T\} \cap \{T\leq t\}\in \mathcal{G}_t$
So I try to write $S\leq T$ as $\{S\leq r\}\cap \{r\leq T\}$ where $r\in \mathbb{R}$. But from here I don't know how to preceed.
Does anyone have any idea?
Thankes in advance
Answer: I think I have figured out myself..
Let $A\in \mathcal{F}_{S\lor T}$. we have
\begin{align*}
A\cap \{S\leq T\}\cap \{T\leq t\} = [A\cap \{S\leq t\}\cap \{T\leq t\}]\cap [\{S\leq T\}\cap \{T\leq t\}]
\end{align*}
The first part is in $\mathcal{F}_T$. We know that
\begin{align*}
\{S>T\}\cap \{T\leq t\}=\cup_{q\in \mathbb{Q}^+\cap [0,t]}(\{S>q\}\cap \{T\leq q\}\cap \{T\leq t\})
\end{align*}
The RHS is in $\mathcal{F}_T$. Since $(T\leq t)\in \mathcal{F}_t$, we get $\{S\leq T\}\cap \{T\leq t\}\in \mathcal{F}_t$.

Continuous stopping time property


Logging into Drupal 7 site with headless browser: why would it fail?

Question: NOTE: I've heavily revised the wording of my question to focus more clearly on the problem.  There's a ton of really really useful information in the answers below, but not all of it applies to solving the problem of logging in with a headless browser.  (Feel free to view the edit history for more details, as well as a more verbose version of the same info.)
I'm using a headless WebKit browser (from CasperJS to log into my Drupal 7 site, and it is failing for unknown reasons.  I first used the Ruby version of the Mechanize library and got identical results: access denied even after filling out and submitting the log in form.  I'm pretty sure the problem has to do with Drupal, and some failure on my part to jump through some hoop (that is probably there to prevent spambots and such from submitting to Drupal-based sites).
Since my script loads the log-in form before submitting it, AFAIK it should work just like a normal user logging in.  I've looked through the methods mentioned in the answers that details Drupal's form-submission process, but I'm not seeing what would cause my problem.
This question seems to provide clues, though it is D6 and using curl.  That person is passing field_source, form_token, form_build_id, and form_id as fields.  In my form I only see form_build_id and form_id. Should I be passing all those fields, even though they don't seem to be present in the login form?  Drupal seems to look for form_token, but it's not present on my login form.  What's up with that?
NOTE: Someone will undoubtedly ask why I'm using these tools when there must be better ways with such-and-such a Drupal module, and the short answer is just that I chose to use tools I'm most familiar with.   If you have good module suggestions please leave comments (with implementation details if possible) as I'd love to hear the suggestions, but I'd still appreciate an answer to this question as it is asked.  Thanks.
Comment: Can you also explain why you're trying to login to the site this way?
Comment: Since I needed to scrape the old site for content (it couldn't be easily exported in any clean way, as the site was in IBM Domino and the body text was using Notes Rich Text fields, which are a PITA), it seemed easiest to have the scraping script also do a POST to the new site.  Since an HTTP Post uses the normal user interface, I could side-step all the normal issues that come up for migrations.
Comment: Given that Cyrve, the experts on Drupal migrations, say they're always painful, and that Googling turns up things like  http://www.lullabot.com/articles/drupal-data-imports-migrate-and-table-wizard, which gives a method that *won't work* with D7, it seemed like I was avoiding a whole mess of pain.  If not for the log-in issue, it would have been super easy.
Comment: In the end I used Feeds to import CSV data.
Answer:
Is there some security feature built into Drupal to prevent
  submissions by scripts?

Yes, there is.
In order to prevent automated form submission by bots etc.. During form build Drupal generates a token, based on session id, and a unique id, for form cache. These are used during form validation.
See:

drupal_prepare_form
drupal_get_token
drupal_validate_form
form_get_cache

In order to successfully submit the form, you would need to retrieve it and then submit it using the same token and form_build_id values.
However, there are other ways to submit forms programmatically, such as
drupal_form_submit
As well as purely code based methods to log a user in.
e.g, in a very simple form:
// Load a user account and assign to global $user
global $user;
$account = user_load(1, TRUE); // Root user
$user = $account; // This "logs" the user in
drupal_session_regenerate();
// Invoke login event
$edit = NULL;
user_module_invoke('login', $edit, $user);

Comment: `form_build_id` is used as the cache key when getting/setting the form in cache. The form token, based on the user session id, is used to validate the user has access to submit that form.
Comment: Isn't the 'form_build_id' field that token?
Comment: So both CasperJS and Mechanize are basically headless browsers, so anything that works in a normal browser (with the exception of JS in Mechanize) should work, AFAIK.  (It's not like just using `curl` or something to do an HTTP POST.) Do you know any reason they wouldn't be treated by Drupal the same way as (for instance) Chrome?  CasperJS uses WebKit just like Safari and Chrome.  It actually renders the page and everything if you want, can give you screenshots: the whole 9 yards.
Comment: What is the actual error message that occurs with your current method?
Comment: It's just a regular access denied response, the same as what a regular user would get if they weren't logged in.  After submitting the login form with username and password I navigate to /admin and that's when I get it.  I made CasperJS take screenshots and it's just a normal access denied screen, as far as I can see.
Answer:
Is there some security feature built into Drupal to prevent submissions by scripts?

Yes, there are. First off, a script that is not bootstrapping Drupal cannot submit a form that has not requested to a Drupal site. Drupal explicitly check that condition is verified, and that task is done from drupal_validate_form(), which contains the following code.
  // If the session token was set by drupal_prepare_form(), ensure that it
  // matches the current user's session.
  if (isset($form['#token'])) {
    if (!drupal_valid_token($form_state['values']['form_token'], $form['#token'])) {
      $path = current_path();
      $query = drupal_get_query_parameters();
      $url = url($path, array('query' => $query));

      // Setting this error will cause the form to fail validation.
      form_set_error('form_token', t('The form has become outdated. Copy any unsaved work in the form below and then reload this page.', array('@link' => $url)));
    }
  }

_form_validate() then verifies there is a correspondence between the values submitted and the form elements contained in the form requested to Drupal. If there isn't an exact correspondence, the submission fails.
  if (isset($elements['#maxlength']) && drupal_strlen($elements['#value']) > $elements['#maxlength']) {
    form_error($elements, $t('!name cannot be longer than %max characters but is currently %length characters long.', array('!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title'], '%max' => $elements['#maxlength'], '%length' => drupal_strlen($elements['#value']))));
  }

        if (!isset($options[$v])) {
          form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
          watchdog('form', 'Illegal choice %choice in !name element.', array('%choice' => $v, '!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
        }

   elseif (!isset($options[$elements['#value']])) {
      form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
      watchdog('form', 'Illegal choice %choice in %name element.', array('%choice' => $elements['#value'], '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
    }

Is there some other reason scripts would fail to log into Drupal on a page where a user in a normal browser would have no problem?

As you are asking for a headless browser, the form submission could be successful if:

The browser requests the login form
It inject JavaScript code that fills out the necessary fields, and submit the form back to Drupal

The condition necessary for the operation to work is that the browser is able to keep the session open. In fact, the token used to validate the form is obtained from drupal_get_token(), which contains the following code.
  return drupal_hmac_base64($value, session_id() . drupal_get_private_key() . drupal_get_hash_salt());

The function used to validate the token is drupal_valid_token().
function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
  global $user;
  return (($skip_anonymous && $user->uid == 0) || ($token == drupal_get_token($value)));
}

As side note, to create content is not necessary to log in as a specific user: Just bootstrap Drupal, build a node object, and call node_save().
For example, the following code put in a file in the same directory containing the index.php Drupal comes with would create a node. (The code is for Drupal 7, but a similar code can be written for Drupal 6.)
  define('DRUPAL_ROOT', getcwd());
  require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

  $node = new stdClass();
  $node->title = $node_title;
  $node->type = $node_type;

  // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().
  node_object_prepare($node);

  $node->language = LANGUAGE_NONE;
  $node->uid = $user_id;
  $node->status = 1;
  $node->promote = 0;

  // Comments are disabled; change it to COMMENT_NODE_OPEN to enable them.
  $node->comment = COMMENT_NODE_CLOSED;

  $node = node_submit($node);
  node_save($node);

Using this code, Drupal would create a node.
If the code is used for a publicaly available site, and you want to avoid everybody runs the file (let's suppose the file is migration.php), you can use the following code.
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if (!isset($_GET['cron_key']) || variable_get('migration_key', 'drupal') != $_GET['cron_key']) {
  watchdog('migration', 'Migration could not run because an invalid key was used.', array(), WATCHDOG_NOTICE);
  drupal_access_denied();
}
elseif (variable_get('maintenance_mode', 0)) {
  watchdog('Migration', 'Migration could not run because the site is in maintenance mode.', array(), WATCHDOG_NOTICE);
  drupal_access_denied();
}
else {
  $node = new stdClass();
  $node->title = $node_title;
  $node->type = $node_type;

  // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().
  node_object_prepare($node);

  $node->language = LANGUAGE_NONE;
  $node->uid = $user_id;
  $node->status = 1;
  $node->promote = 0;

  // Comments are disabled; change it to COMMENT_NODE_OPEN to enable them.
  $node->comment = COMMENT_NODE_CLOSED;

  $node = node_submit($node);
  node_save($node);
}

The Drupal variable migration_cron should be initialized with variable_set('migration_key', drupal_get_token('update'));. The script would be then called as http://example.com/migration.php?migration_key=XYX, where XYZ is the value saved in the Drupal variable migration_key. As drupal_get_token() returns a different value each time the function is called, external attachers could not get the value to use to run the script.
The code I shown creates just a node, but using similar code would be possible to migrate content. The code would execute a loop to create a node for each entry loaded from a file, an external database, or returned from a drupal_http_request() call to an external site (among other methods). In any case, it is not necessary to first log in to create a node, if the PHP code first bootstrap code.
If you can use Drush, that would probably be a better way to programmatically create content.
As alternative, there are many modules to migrate content. As far as I recall, also the Feeds module is used to migrate content to Drupal.
Answer: Try this with CasperJs:
Need CasperJs and PhantomJs on your system PATH
#filename testCasper.js

var _adminUser = '';
var _adminPass = '';
var _baseUrl = 'local.drupal.dev';

casper.test.begin('Basic BDD: login as Admin and test behavior of interface.', 3, function suite(test) {

casper.start(_baseUrl , function() {
    test.assertTitle("drupalLocal.dev", "homepage title is ok");
    test.assertExists('form#user-login-form', "user login form is found");
    this.fill('form#user-login-form', {
        name: _adminUser,
        pass: _adminPass
    }, true);
});

casper.then(function() {
    test.assertTextExists('Log out', 'User is logged in');
    console.log('location is ' + this.getCurrentUrl());
});

casper.run(function() {
    test.done();
    phantom.exit();
});
});

run with:
`casperjs test testCasper.js`


Cannot create a process in a COM object from an asp site

Question: I'm updating an old process that already exists, which works as follows:
The user submits a form which runs the following asp (simplified, names changed):
    <%
    set rb = Server.CreateObject("RecordBuilder.SomeObject")
    rb.Calculate()
    rb.StartProcess()
    %>

The RecordBuilder.SomeObject was an old VB6 DLL, I don't have VB6, so I converted it to VB.NeT 4.0
The call to Calculate() works as expected, the call to StartProcess() fails.
StartProcess() is the following:
Public Function StartProcess()
    Try
        strProcess = "Starting process"
        Dim proc = New Process()
        proc.StartInfo.RedirectStandardOutput = True
        proc.StartInfo.UseShellExecute = False
        proc.StartInfo.CreateNoWindow = True
        proc.StartInfo.FileName = "d:\App\RecordProcessor.exe"

        Dim procHandle = proc.Start()
        strProcess = "Started process"
    Catch ex As Exception
        Err.Raise(vbObjectError + 9999, "RecordBuilder.SomeObject", strProcess & " failed: " & ex.Message & "
Stack Trace:
" & ex.StackTrace)
    End Try
End Function

This fails with the call to proc.Start(), however if I copy the test ASP to a .vbs file it will work as expected.
I have changed the permissions on d:\App\RecordProcessor.exe to grant execute permission to the group Everyone.
Comment: What exception do you get thrown?
Comment: Got it working.  I regenerated my Strong Name Key from within Visual Studio instead of via "sn -k".  In addition, if RedirectStandardOutput, UseShellExecute, and CreateNoWindow are not all set correctly, it tries to run the application in a Window and fails with access denied.
Answer: Check that the website's anonymous user account has the requisite permissions on the d:\app folder and any other folders that it may be touching.
One thing I notice that's missing is proc.WaitForExit() after your proc.Start().
You probably want that so you can capture errors from the process itself as well:
Dim stdError As New String
Try
    strProcess = "Starting process"
    Dim proc = New Process()
    proc.StartInfo.RedirectStandardOutput = True
    proc.StartInfo.RedirectStandardError = True
    proc.StartInfo.UseShellExecute = False
    proc.StartInfo.CreateNoWindow = True
    proc.StartInfo.FileName = "d:\App\RecordProcessor.exe"

    Dim procHandle = proc.Start()
    strProcess = "Started process"

    proc.WaitForExit()

    stdError = proc.StandardError.ReadToEnd()
    If stdError.Length > 0 Then
       '' So long since I did VB so next line might need tweaked
       Err.Raise(vbObjectError, "Caught StdError", stdError)
    End If
Catch ex As Exception
    Err.Raise(vbObjectError + 9999, "RecordBuilder.SomeObject", strProcess & _
         " failed: "  & ex.Message & "
Stack Trace:
" & ex.StackTrace)
End Try

Comment: Thanks, I have given the whole D:\app folder read & execute permission for the "Everyone" group.  I am using proc.WaitForExit() in my actual method, but I'm using a test method to troubleshoot the proc.Start call.  It throws an Exception on the proc.Start() call, so there would be nothing to read from StandardError
Comment: @user - what exception is thrown?


Apply htaccess rewrite-rule on rewritten URL

Question: Is it possible to apply a .htaccess rewrite-rule on an already rewritten URL?
Example:
I want to resize my pictures with timthumb.php (most recent version, so there should be no security flaw any more). But the URL should look fine, therefore I created this rewrite-rule:
RewriteRule ^rz/(.*)x(.*)/r/(.*) /themes/Nerdtalk/timthumb.php?src=$3&h=$2&w=$1&q=80

This rule is working fine, but before starting timthumb.php which may re-direct to a cached file, I want Apache to check, if the file exists and let Apache redirect to the cached file, so timthumb.php won't be started.
Therefore I created this ruleset:
RewriteCond %{SCRIPT_FILENAME} timthumb.php
RewriteCond %{QUERY_STRING} src=(.*)\.(png|jpe?g)&h=([0-9]+)&w=([0-9]+)&q=([0-9]+)
RewriteCond %{DOCUMENT_ROOT}/cache/%1-%4-%3-1-%5.%2 -f
RewriteRule ^.* /cache/%1-%4-%3-1-%5.%2 [L]

Can an already rewritten URL be rewritten a second time?
Is the second part correct?
If there is a possibility to merge these two rulesets, can you please tell me how?
Answer:
Can an already rewritten URL be rewritten a second time?

Yes. When rewrite occurs (rule with the [L] flag or end of htaccess), mod_rewrite goes to next iteration and starts matching all rules again from start. That's why you need to build your rules with rewrite loop in mind (especially if you use this sort of pattern ^(.*)$ for matching).
If you write a rule without [L] flag, then rewrite continues on the same iteration, so any rules placed below current may rewrite URL again to a completely different.

Is the second part correct?

I would say Yes (although not checking on the actual Apache). I'm just not sure about first rewrite condition (just never used %{SCRIPT_FILENAME} myself so unsure how exactly it works) -- I would use %{REQUEST_URI} timthumb\.php$ or something like that.
The only thing that I would add is ? at rewrite target to get rid of newly created (1 rule above) query string: RewriteRule ^.* /cache/%1-%4-%3-1-%5.%2? [L]. But it should work fine as is now.

If there is a possibility to merge these two rulesets, can you please
  tell me how?

Place them one after another in the same order you have here. You cannot make it a single rule as 2nd rule will only work if thumbnail is already cached.
If it will not work straight away (as Apache's variables (%{SCRIPT_FILENAME}, %{QUERY_STRING} etc) may not have proper values straight away) try adding [L] flag to first rewrite rule -- it will force next iteration which populates those variables with proper values for sure, and, depending on the rest of your rules that you may have before this one, it will reach 2nd ruleset where 2nd rewrite will occur.
If you want -- you can rewrite it completely to check and serve cached file straight away (if present) and then (if still nothing) rewrite image to be processed by timthumb.php, but that will do exactly the same job as aforementioned rules, just a bit differently.
Comment: Thanks for your detailed explanation. But isn't it faster to let Apache process the check of file-existence instead of starting a PHP-script every time?
Comment: @Phil What are you talking about? I think you are confused how all this works. Please describe your understanding of the above mentioned rules.
Comment: The first rule rewrites a URL like /rz/714x357/r/screen.jpg to /themes/Nerdtalk/timthumb.php?src=screen.jpg&h=357&w=714&q=80.
Comment: Second rule checks:
- if the requested scriptname equals timthumb.php
- if the query string of requested URL matches src=(.*)\.(png|jpe?g)&h=([0-9]+)&w=([0-9]+)&q=([0-9]+)
- if a file exists on DOCUMENT_ROOT/cache/%1-%4-%3-1-%5.%2 (for better unterstanding: DOCUMENT_ROOT/cache/screen-714-357-1-80.jpg)
And if all these Conditions are true, then the URL gets rewritten and the rewriting will aborted then ([L]).

The reason for the whole thing is, that in my understanding Apache should do the work of checking, whether a cached file exists or not, much faster than a PHP-script.
Comment: Yes -- you are correct & that is exactly how it will work with these 2 rules (executed 1 after another): Apache-invoked check is faster than PHP as you have no PHP overhead (PHP needs to be initialised, parse PHP script (if no code-caching involved) and then execute it. It can make some difference on very busy / shared hosting servers.
Comment: One thing that you still have to keep in mind: `[L]` does not necessary mean _"rewriting will aborted"_ -- instead think that `[L]` means end of iteration and that there always be another iteration after this (useful link: http://stackoverflow.com/questions/6797998/rewriterule-last-l-flag-not-working ). If you build your rules properly then no need to worry about other iterations/rewrite loop. These rules alone will not be caught in rewrite loop.
Comment: And I am on a shared host - I'm glad, that my understanding of the code was correct. I played around a bit and tried some (hopefully) optimized RegExp in the conditions, additionally I moved the check, if a cached file exists before the first rewrite. I will post this (working) ruleset later this day.
Comment: @Phil There is no REAL need to "move the check, if a cached file exists before the first rewrite" -- the difference will be invisible for you, even under heavy load (well .. 0.00001s diff or smaller), unless you reduce number of matches/regex complexity (even then the difference will be extremely small under the load -- it's only single rule, not 30-40 of them).
Answer: Can an already rewritten URL be rewritten a second time?
Yes, it can. It's default behaviour and if you would want to change it, you could use flags like [L]:
http://httpd.apache.org/docs/current/rewrite/flags.html
Is the second part correct?
I'm not sure if you can use %1 etc. in RewriteCond directive
If there is a possibility to merge these two rulesets, can you please tell me how?
I would put cache in the same folder as your original url: ^rz/(.)x(.)/r/
If it exists - just serve it, if not - use php