text:
Q: FLRW metric, universe expansion, and the energy-momentum relationship This is a follow-up to a previous question of mine.
I am getting myself confused by some basic things in cosmology, so I hope whoever reading this is patient.
The Euclidean FLRW metric is given by
$$ ds^{2} = -dx^{0} + a(t)^{2}\Big((dx^{1})^{2} + (dx^{2})^{2} + (dx^{3})^{2}\Big) $$
where $a(t)$ is strictly increasing with time $t$ and $x^{0} = ct$.
It describes the expansion of the universe, and it can be used as a rough first approximation of the universe.
In this metric, the $4$-momentum of a particle of mass $m$ (zero or nonzero) is
$$ p^{\mu} = \Big(\frac{E}{c},\; \vec{p}\Big)\quad\text{ and }\quad g_{\mu\nu}p^{\mu}p^{\nu} = -m^{2}c^{2}. $$
This gives us
$$ -\frac{E^{2}}{c^{2}} + a^{2}\vec{p}\,^{2} = -m^{2}c^{2} $$
and thus
$$ E^{2} = a^{2}\vec{p}\,^{2}c^{2} + m^{2}c^{4}. $$
This is almost the usual energy-momentum relationship but with a scale factor $a(t)$.
By convention, we take $a(t_{0}) = 1$ for the present time $t_{0}$ of the universe. This way, $a(t) < 1$ for $t<t_{0}$. But this leaves me confused here.

*

*If the scale factor was smaller in the past, how can we say any of our understanding of particle physics (based off of special relativity) holds valid for the past?

*How can we just set $a(t_{0})$ equal to $1$? Wouldn't this affect the dynamics and kinematics?

*I suspect the answer to both questions above is that the value of $a(t)$ is a convention that makes no difference to particle physics. This doesn't seem apparent to me. Clearly the relationship between $E$, $p$, and $m$ are different for different values of $a(t)$. How can we get the same dynamics like this? Is there any proof of this fact?

A: Ok, I think my misunderstanding comes down to a subtle failure to distinguish between vector coefficients vs the vectors themselves. When you change the coordinate systems, the coefficients of 4-vectors change as well. This can lead to some confusion if you are not careful. There are a number of equivalent ways of explaining this properly.
Take any point $x_{0} = (x^{0}_{0}, x^{1}_{0}, x^{2}_{0}, x^{3}_{0})$ and let $t_{0}$ be the time of the point. Without loss of generality, apply a translation of coordinates so that $x_{0} = (0, 0, 0, 0)$. The coordinates need to be rescaled so that the metric is pointwise Minkowski at point $x_{0}$. The resulting coordinates will be the coordinates for which the usual special relativity formulas hold approximately well local to an observer near $x_{0}$. To do this, define
$$ y^{0} = x^{0} \qquad\text{ and }\qquad y^{i} = a(t_{0}) x^{i}. $$
Note that $a(t_{0})$ is a constant, because $t_{0}$ is constant—it is the fixed time at $x_{0}$. Some simple algebraic manipulations show that in these new rescaled coordinates, we have
$$ ds^{2} = -(dy^{0})^{2} + \frac{a(t)}{a(t_{0})}\Big( (dy^{1})^{2} + (dy^{2})^{2} + (dy^{3})^{2} \Big). $$
Let $p^{\mu} = (E/c, \vec{p})$ be the 4-momentum in the $x$-coordinates, and let $\underline{p}^{\mu} = (\underline{E}/c, \underline{\vec{p}})$ be the 4-momentum in the $y$-coordinates.
By the contravariance of the coefficients
$$ \underline{p}^{\mu} = \frac{\partial y^{\mu}}{\partial x^{\nu}}p^{\nu}, $$
we have
$$\underline{p}^{0} = p^{0} \qquad\text{ and }\qquad \underline{p}^{i} = a(t_{0})p^{i}. $$
From this we see that at point $x_{0}$, the equation
$$ E^{2} = a(t_{0})^{2}\vec{p}\,^{2}c^{2} + m^{2}c^{4} $$
that I wrote in my OP transforms into
$$ \underline{E}^{2} = \underline{\vec{p}}\,^{2}c^{2} + m^{2}c^{4} $$
exactly as it is in special relativity.


text:
Q: I'm getting a NullReferenceException inside MessageHeaderManager.GetHeader when receiving a message with NserviceBus host I'm using NServiceBus 3 and when I receive a message I'm getting this error from the receiving endpoint.:
NServiceBus.Unicast.Transport.Transactional.TransactionalTransport [(null)] <(null)> - Failed raising 'transport message received' event for message with ID=97d0f2fa-6227-439b-ad37-a304bd2af000\10428
System.NullReferenceException: Object reference not set to an instance of an object.
   at NServiceBus.MessageHeaders.MessageHeaderManager.GetHeader(Object message, String key)
   at NServiceBus.MessageHeaders.Bootstrapper.<Run>b__0(Object msg, String key)
   at NServiceBus.ExtensionMethods.GetHeader(Object msg, String key)
   at NServiceBus.ExtensionMethods.GetOriginatingSiteHeader(Object msg)
   at NServiceBus.Gateway.HeaderManagement.GatewayHeaderManager.MutateIncoming(Object message)
   at NServiceBus.Unicast.UnicastBus.<>c__DisplayClass25.<ApplyIncomingMessageMutatorsTo>b__24(IMutateIncomingMessages m)
   at System.Collections.Generic.List`1.ForEach(Action`1 action)
   at NServiceBus.Unicast.UnicastBus.ApplyIncomingMessageMutatorsTo(IBuilder builder, Object originalMessage)
   at NServiceBus.Unicast.UnicastBus.<>c__DisplayClass22.<HandleMessage>b__21(Object msg)
   at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
   at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at NServiceBus.Unicast.UnicastBus.HandleMessage(IBuilder builder, TransportMessage m)
   at NServiceBus.Unicast.UnicastBus.HandleTransportMessage(IBuilder childBuilder, TransportMessage msg)
   at NServiceBus.Unicast.UnicastBus.TransportMessageReceived(Object sender, TransportMessageReceivedEventArgs e)
   at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
   at NServiceBus.Unicast.Transport.Transactional.TransactionalTransport.OnTransportMessageReceived(TransportMessage msg)

The message itself looks like this:
public interface ILinkPersonMessage : IBaseMessage
{
    int PersonId { get; set; }
    List<int> UnitIds { get; set; }
}

public interface IBaseMessage
{
    int UserId { get; set; }
}

In the sending class I'm doing this:
var message = bus.CreateInstance<ILinkPersonMessage>();
message.UserId = currentUser.UserId;
message.PersonId = personId;
message.UnitIds = selectedUnits;

bus.Send(message);

Update:
I'm looking through the NServiceBus code, and this is the method that's throwing the error:
    public string GetHeader(object message, string key)
    {
        if (message == ExtensionMethods.CurrentMessageBeingHandled)
            if (bus.CurrentMessageContext.Headers.ContainsKey(key))
                return bus.CurrentMessageContext.Headers[key];
            else
                return null;

        if (messageHeaders == null)
            return null;

        if (!messageHeaders.ContainsKey(message))
            return null;

        if (messageHeaders[message].ContainsKey(key))
            return messageHeaders[message][key];

        return null;
    }

From looking at that code, this could only be happening if bus.CurrentMessageContext or bus.CurrentMessageContext.Headers are null, or if messageHeaders[message] existed, but contained a null value.  Unfortunately I haven't been able to figure out yet which one of these scenarios is more likely (or even possible)
Update 2
So using QueueExplorer I've pulled the headers out:
<?xml version="1.0"?>
<ArrayOfHeaderInfo xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <HeaderInfo>
        <Key>NServiceBus.Version</Key>
        <Value>3.0.3</Value>
    </HeaderInfo>
    <HeaderInfo>
        <Key>NServiceBus.TimeSent</Key>
        <Value>2012-05-08 06:57:15:691208 Z</Value>
    </HeaderInfo>
    <HeaderInfo>
        <Key>NServiceBus.EnclosedMessageTypes</Key>
        <Value>Namespace.Service.ILinkPersonMessage __impl, NServiceBus.Unicast.Transport__impl, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null;Namespace.Service.ILinkPersonMessage, Namespace.Service, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</Value>
    </HeaderInfo>
    <HeaderInfo>
        <Key>WinIdName</Key>
        <Value>*{myusername}*</Value>
    </HeaderInfo>
    <HeaderInfo>
        <Key>CorrId</Key>
    </HeaderInfo>
</ArrayOfHeaderInfo>

Update 3
This is the fluent config that now works:
Configure.With()
.DefiningEventsAs(t => t.Namespace != null && t.Namespace.StartsWith("Events"))
.DefiningCommandsAs(t => t.Namespace != null && t.Namespace.StartsWith("Messages"))
.CastleWindsorBuilder(container)
.XmlSerializer()
.MsmqTransport()
.IsTransactional(true)
.IsolationLevel(IsolationLevel.ReadUncommitted)
.UnicastBus()
.RavenSagaPersister()
.RavenSubscriptionStorage()
.UseRavenTimeoutPersister()
.RunTimeoutManager()
.ForInstallationOn<NServiceBus.Installation.Environments.Windows>().Install();

(I've trimmed all the namespaces)

A: Does this happen on the first message after sending process startup, or just subsequent ones?
Are you configuring your sending bus more than once? (NServiceBus.Configure?)

A: We've recently fixed some bugs around the header management so it could be that that's what you were running into. Please try upgrading to 3.0.4 and see if that resolves your issues.

A: The same thing happened to me, the problem was that i forgot to setup the xmlserialization when configuring the service bus
var configBus = NServiceBus.Configure.With()
.DefaultBuilder()
.MsmqSubscriptionStorage()
.XmlSerializer() // <== This line here
.MsmqTransport()
    .IsTransactional(true)
    .PurgeOnStartup(false)
.UnicastBus()
.ImpersonateSender(true);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retrofit cancel() & check if request was delivered to server How can I be sure that calling cancel() on the Retrofit cause request is not delivered to the server?
Currently I know, that calling cancel on the Retrofit will invoke onFailure branch of the callback. And then I can check if the cause of the failure is because call was cancelled.
https://futurestud.io/tutorials/retrofit-2-cancel-requests
But can I be somehow sure, that request didn't arrive to the server?

A: Code snippet from here
new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            Log.d(TAG, "request success");
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            if (call.isCanceled()) {
                Log.e(TAG, "request was cancelled");
            }
            else {
                Log.e(TAG, "other larger issue, i.e. no network connection?");
            }

        }
    };

According to that this will raise in case call was canceled, as it say
// something happened, for example: user clicked cancel button
call.cancel();
If you call call.cancel() let's say later it means you already got a response from the server, therefore you won't get to onFailure point where call.isCanceled() is being checked :)

If you cancel the request, Retrofit will classify this as a failed request and thus call the onFailure() callback in your request declaration. This callback is also used when there is no Internet connection or something went wrong on the network level. From the app perspective, these errors are quite a bit different.


text:
Q: Match n amount of words separated by commas after base text I would like to match an infinite amount of words separated by commas and whitespaces.
Is there a better solution than just repeating the search parameter?
Sample:
"2_i Art des Problems:\s*(.[^,\s]+)[,]\s*(.[^,\s]+)[,]\s*(.[^,\s]+)"

2_i Art des Problems: Elektrisch, Schweißausrüstung, Burgenland

View on regex101: https://regex101.com/r/yP7PPO/1
Full code for this operation:
With Reg1
.Pattern = "2_i Art des Problems:+\s*([^\r\n]*\S)"
.Global = False
End With
If Reg1.Test(olMail.Body) Then
    Set M1 = Reg1.Execute(olMail.Body)
End If
For Each M In M1
    With xExcelApp
        Select Case M.SubMatches
            Case Software
                Range("D6").Value = 1
            Case Mechanisch
                Range("E6").Value = 1
            Case Elektrisch
                Range("F6").Value = 1
            Case Roboter
                Range("G6").Value = 1
            Case Schweißausrüstung
                Range("H6").Value = 1
            Case Anwendung
                Range("I6").Value = 1
            Case Ersatzteil
                Range("J6").Value = 1
            Case Else
                Range("K6").Value = 1
        End Select
    End With
Next M

A: Does it really need to be a RegEx?
I think this is over complicating things as this can easily be solved with Split():
Option Explicit

Public Sub Example()
    Const TestString As String = "2_i Art des Problems: Elektrisch, Schweißausrüstung, Burgenland"
    Const ConstantPart As String = "2_i Art des Problems: "

    If Left$(TestString, Len(ConstantPart)) = ConstantPart Then
        Dim Parts() As String
        Parts = Split(Mid$(TestString, Len(ConstantPart) + 1), ", ")

        Dim Part As Variant
        For Each Part In Parts
            Debug.Print Part
        Next Part
    End If
End Sub

Output is:
Elektrisch
Schweißausrüstung
Burgenland

A: If you realy need to use regexp than use global flag and e.g. this regexp
(.[^,\s]+)(,|$)

Explanation here
        With regEx
        .Global = True

Use .SubMatches to get capturing groups values
EDIT:
according to one of comment "Then you still need to Trim the matches because they will include the spaces. – Pᴇʜ 1 min ago"
you can still use regexp
.([^,\s]+)(,|$)

check


text:
Q: Show that $A^{(x,y)}$ is countable. Question: Let $A$ be a countable set $A^{(x,y)}$ the set of all functions from $(x,y)$ to $A$. Show that $A^{(x,y)}$ is countable.
My attempt:
By proposition 7.1.2iii, $\mid B \mid^{\mid A \mid}$ is the cardinality of the set of functions from $A$ into $B$ . Also, by definition 6.6.1, A function $f$ from a set $X$ to a set $Y$ is a subset of $ X \times Y$ with the following property:
$(\forall x \in x)( \exists! y \in Y)[(x,y) \in f]$
The set $X$ is the domain of $f$ and the set $Y$ is the codomain of $F$. For each $x \in X$ the unique calue $y$ such that $(x,y) \in f$ is denoted by $f(x) $ and is called the image of $x$.
Suppose that $x = f(x)$ and $y=f(y)$. Then each function $(x,y) \rightarrow A$ is a subset $[([f(x)_1,f(y)_1],a_1,[f(x)_2,f(y)_2],a_2...[f(x)_m,f(y)_m],a_m$ where each element $a_i=f(x_i),f(y_i)$. The function $f$ is uniquely determined by the list $a_1,a_2,...a_m$.
Conversely, there is a one to one correspondence to $ A \times A$. We can count the required set of functions by counting the sets of lists $a_1,a_2,...a_m$. As there are exactly $A$ options for each $a_i$, the cardinality of the set of these lists is $ \mid A \mid \cdot \mid A \mid.... \mid A \mid$ (m factors)
giving $A^m = A^{(x,y)}$
Is this correct? If not, then how do I improve on this proof?
Edit:
Second attempt. For $ \mid A \mid ^x]$
Suppose that $ x =[x_1,x_2,...x_m]$. Each function $f: X \rightarrow A$ is a subset of $ X \times A$ of the form $(x_1,a_1)(x_2,a_2),...,(x_m,a_m)$ where each element $a_i=f(x_i)$. The function $f$ is uniquely determined by the list $a_1,a_2,...a_m$. Conversely, each such list determines a unique function from $X$ to $A$ . This bijection (between lists and functions) implies that we can count the required set of lists $a_1,a_2,...a_m$ as there are exactly $ \mid A \mid$ options for each term $a_1$ the cardinality of the set of these lists is  $ \mid A \mid \cdot \mid A \mid.... \mid A \mid$ (m factors)
giving $A^m = A^{x}$
Similarly, for $\mid A \mid ^y$
Suppose that $ y =[y_1,y_2,...y_m]$. Each function $f: Y \rightarrow A$ is a subset of $ Y \times A$ of the form $(y_1,a_1)(y_2,a_2),...,(y_m,a_m)$ where each element $a_i=f(y_i)$. The function $f$ is uniquely determined by the list $a_1,a_2,...a_m$. Conversely, each such list determines a unique function from $Y$ to $A$ . This bijection (between lists and functions) implies that we can count the required set of lists $a_1,a_2,...a_m$ as there are exactly $ \mid A \mid$ options for each term $a_1$ the cardinality of the set of these lists is  $ \mid A \mid \cdot \mid A \mid.... \mid A \mid$ (m factors)
giving $A^m = A^{y}$

A: I got a little confused reading some of the later stuff in your proof... but I did get that you say for functions from $A$ to $B$ the cardinality is $$|B|^{|A|}$$ So in this case the cardinality is $$|A|^2$$ since there are two elements in $(x,y)$. You just have to show that the product of two countable sets is countable.
EDIT: Ok let's start a new area since this is getting messy.
We have: $A$ is a countable set.
What are $x,y$ and $(x,y)$. What is $m$ and what is $A^m$? I'm getting confused because I'm not clear on what everything represents here.
EDIT2: I think I understand the hint. So you want to list of all possible functions from the SET $$\{x,y\}$$ to the countable set $A$. For each function, you need to make exactly 2 choices: where does $x$ get sent, and where does $y$ get sent? That means that picking a function is equivalent to picking a pair of elements from the set $A$. So the set of functions is in correspondence with the set of pairs of elements from $A$, which is just the set $$A\times A$$
EDIT3: Let's make it concrete. Let $$A=\{1,2,3\}$$ Then the possible functions are:

*

*$f(x)=1,f(y)=1$

*$f(x)=1,f(y)=2$

*$f(x)=1,f(y)=3$

*$f(x)=2,f(y)=1$

.
.
.

*

*$f(x)=3,f(y)=3$

Each function is like a possible pair from $A\times A$:

*

*1,1

*1,2

*1,3

*2,1

.
.
.

*

*3,3

A: Use your proposition 7.1.2iii (but note that it is wrong as stated.  There are $|A|^{|B|}$ function from $B$ to $A$, not $B$ into $A$):
$$|A^{\{x,y\}}| = |A|^{|\{x,y\}|} = |A|^2$$.
At this point, you want to use an enumeration argument.  Construct a "table" of values in $A\times A$ and traverse it, just like you would for the rationals.


text:
Q: Spreading text in table over multiple rows I have a problem when placing two  tables side by side using minipage, the tables are bigger than half a pagewidth however they could be reduced in size if I place the text 'Leading Tail' in two rows except I have no idea how to do this.
\begin{minipage}{0.5\textwidth}

        \begin{tabular}{ll|lll}
            &                   & \multicolumn{3}{c}{\textbf{Trailing Radius}} \\
            &                   & \textbf{R68}  & \textbf{R34}  & \textbf{R17} \\ \hline
            \multirow{3}{*}{\textbf{Leading Tail}} & \textbf{No Tail}  & 0.389         & 0.404         & 0.426        \\
            & \textbf{6° Tail}  & 0.416         & 0.425         & 0.439        \\
            & \textbf{12° Tail} & 0.379         & 0.394         & 0.415        \\ \hline
        \end{tabular}
\end{minipage}%
\begin{minipage}{0.5\textwidth}

    \begin{tabular}{ll|lll}
        &                   & \multicolumn{3}{c}{\textbf{Trailing Radius}} \\
        &                   & \textbf{R68}  & \textbf{R34}  & \textbf{R17} \\ \hline
        \multirow{3}{*}{\textbf{Leading Tail}} & \textbf{No Tail}  & 0.389         & 0.404         & 0.426        \\
        & \textbf{6° Tail}  & 0.416         & 0.425         & 0.439        \\
        & \textbf{12° Tail} & 0.379         & 0.394         & 0.415        \\ \hline
    \end{tabular}
\end{minipage}

A: i would set your table on the following way:

or

for the first case the document example is:
\documentclass{article}
\usepackage{array, booktabs, multirow}

\begin{document}
\begin{center}
    \begin{tabular}[t]{>{\bfseries}p{9ex} lll}
    \toprule
            & \multicolumn{3}{c}{\textbf{Trailing Radius}} \\
    \cmidrule(lr){2-4}
\multirow{-2}{=}{Leading\\ Tail}
            & \textbf{R68}  & \textbf{R34}  & \textbf{R17} \\
    \hline
No Tail     & 0.389         & 0.404         & 0.426        \\
6° Tail     & 0.416         & 0.425         & 0.439        \\
12° Tail    & 0.379         & 0.394         & 0.415        \\
    \bottomrule
    \end{tabular}\hfill
    \begin{tabular}[t]{>{\bfseries}p{9ex} lll}
    \toprule
            & \multicolumn{3}{c}{\textbf{Trailing Radius}} \\
    \cmidrule(lr){2-4}
\multirow{-2}{=}{Leading\\ Tail}
            & \textbf{R68}  & \textbf{R34}  & \textbf{R17} \\
    \hline
No Tail     & 0.389         & 0.404         & 0.426        \\
6° Tail     & 0.416         & 0.425         & 0.439        \\
12° Tail    & 0.379         & 0.394         & 0.415        \\
    \bottomrule
    \end{tabular}
\end{center}
\end{document}

for the second case you need onla replace \hfill between tables with %.

A: You could use the \multirowcell command from the makecell package as shown in the following example.
\documentclass{article}
\usepackage{multirow}
\usepackage{makecell}
\begin{document}

\begin{minipage}{0.5\textwidth}
 \begin{tabular}{ll|lll}
    &                   & \multicolumn{3}{c}{\textbf{Trailing Radius}} \\
    &                   & \textbf{R68}  & \textbf{R34}  & \textbf{R17} \\ \hline
    \textbf{\multirowcell{3}[0pt][l]{Leading \\ Tail}} & \textbf{No Tail}  & 0.389       & 0.404       & 0.426        \\
    & \textbf{6° Tail}  & 0.416         & 0.425         & 0.439        \\
    & \textbf{12° Tail} & 0.379         & 0.394         & 0.415        \\ \hline
 \end{tabular}
\end{minipage}%
\begin{minipage}{0.5\textwidth}
 \begin{tabular}{ll|lll}
    &                   & \multicolumn{3}{c}{\textbf{Trailing Radius}} \\
    &                   & \textbf{R68}  & \textbf{R34}  & \textbf{R17} \\ \hline
    \textbf{\multirowcell{3}[0pt][l]{Leading \\ Tail}} & \textbf{No Tail}  & 0.389       & 0.404       & 0.426        \\
    & \textbf{6° Tail}  & 0.416         & 0.425         & 0.439        \\
    & \textbf{12° Tail} & 0.379         & 0.394         & 0.415        \\ \hline
 \end{tabular}
\end{minipage}
\end{document}

Please keep in mind that since you didn't provide the documentclass you are using, nor information about the margin sizes, the tables still do not fit within the textwidth in the above MWE.

A: I would suggest a slightly different design using booktabs and only multirow.
\documentclass{article}
\usepackage{multirow,booktabs}
\usepackage[margin=1in]{geometry}
\begin{document}
    \begin{minipage}{0.5\textwidth}
        \begin{tabular}{@{}l lll@{}}
            \multirow{2}{*}[-2pt]{\textbf{Leading Tail}} & \multicolumn{3}{c}{\textbf{Trailing Radius}} \\ \cmidrule(l){2-4}
                                                         & \textbf{R68} & \textbf{R34} & \textbf{R17}   \\ \toprule
            No Tail                                      & 0.389        & 0.404        & 0.426          \\
            6° Tail                                      & 0.416        & 0.425        & 0.439          \\
            12° Tail                                     & 0.379        & 0.394        & 0.415          \\ \bottomrule
        \end{tabular}
    \end{minipage}%
    \begin{minipage}{0.5\textwidth}
        \begin{tabular}{@{}l lll@{}}
            \multirow{2}{*}[-2pt]{\textbf{Leading Tail}} & \multicolumn{3}{c}{\textbf{Trailing Radius}} \\ \cmidrule(l){2-4}
                                                         & \textbf{R68} & \textbf{R34} & \textbf{R17}   \\ \toprule
            No Tail                                      & 0.389        & 0.404        & 0.426          \\
            6° Tail                                      & 0.416        & 0.425        & 0.439          \\
            12° Tail                                     & 0.379        & 0.394        & 0.415          \\ \bottomrule
        \end{tabular}
    \end{minipage}
\end{document}


text:
Q: Ejabberd / Rails "getaddrinfo: nodename nor servname provided, or not known" I get the error
SocketError in UsersController#create
getaddrinfo: nodename nor servname provided, or not known

When i try to crate an account in my rails app. I think that the issue relates either to ejabberd or action mailer. How can I find out more about where this error comes from?
Here is def create in my users_controller
 def create
    @user = User.new(params[:user])
    if @user.save!
      clear_current_session
      MailAgent.registration_confirmation(@user).deliver
      flash[:notice] = 'Please activate your account by clicking on the link sent to you by email.'
      redirect_to new_user_url
    else
      flash.now[:error] = 'Please fix the listed errors'
      render 'new'
    end
  end

Here is the full error
Started GET "/" for 127.0.0.1 at 2011-08-02 10:18:33 +1000
  Processing by PagesController#home as HTML
Redirected to http://localhost:3000/users/new
Completed 302 Found in 0ms

Started GET "/users/new" for 127.0.0.1 at 2011-08-02 10:18:33 +1000
  Processing by UsersController#new as HTML
Rendered users/_signup_form.html.erb (6.5ms)
Rendered layouts/_login_links.html.erb (23.3ms)
Rendered layouts/_error_messages.html.erb (0.3ms)
Rendered users/new.html.erb within layouts/application (33.7ms)
Completed 200 OK in 36ms (Views: 35.6ms | ActiveRecord: 0.2ms)

Started POST "/users" for 127.0.0.1 at 2011-08-02 10:18:49 +1000
  Processing by UsersController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"0JgPvOiu18OjD6TmpUrxDGtPiTUBlw0W78HqtdV/brc=", "user"=>{"name"=>"test", "email"=>"[FILTERED]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign Up"}
  [1m[36mSQL (0.1ms)[0m  [1mBEGIN[0m
  [1m[35mUser Load (0.1ms)[0m  SELECT `users`.`id` FROM `users` WHERE (LOWER(`users`.`email`) = LOWER("[FILTERED]")) LIMIT 1
  [1m[36mUser Load (0.1ms)[0m  [1mSELECT `users`.`id` FROM `users` WHERE (`users`.`persistence_token` = BINARY '61b972eee6ed6eb2341b08d92640b08e6379b8743a4df5aa73a233151a6d5629896470e00e108d0f08d20814fb67d8') LIMIT 1[0m
  [1m[35mSQL (1.7ms)[0m  describe `users`
  [1m[36mAREL (0.2ms)[0m  [1mINSERT INTO `users` (`name`, `email`, `crypted_password`, `password_salt`, `persistence_token`, `perishable_token`, `login_count`, `last_login_at`, `created_at`, `updated_at`, `activated`) VALUES ('test', "[FILTERED]", '37712237698ea6db7f044f9408adee9d1fe02447bdb1b92c34b71d2ca35795dd04af1528aa73b6e7db5b11f', 'JnajFzu5luNXbeU', '61b972ec6e0ee6ed6eb08e6379b8743a448ced73ddf5aa73a233151a6d56298e53a996470e00e108d0f08d20814f9c461185f0b67d8', 'bIPlmXIFPjJDHzt', 1, NULL, '2011-08-02 00:18:49', '2011-08-02 00:18:49', 0)[0m
  [1m[35mJabberCredential Load (0.1ms)[0m  SELECT `jabber_credentials`.* FROM `jabber_credentials` WHERE (`jabber_credentials`.user_id = 12) LIMIT 1
  [1m[36mJabberCredential Load (0.1ms)[0m  [1mSELECT `jabber_credentials`.`id` FROM `jabber_credentials` WHERE (`jabber_credentials`.`jabber_id` = BINARY '12_test_72') LIMIT 1[0m
  [1m[35mSQL (1.3ms)[0m  describe `jabber_credentials`
  [1m[36mAREL (0.1ms)[0m  [1mINSERT INTO `jabber_credentials` (`jabber_id`, `jabber_password`, `user_id`, `created_at`, `updated_at`) VALUES ('12_test_72', '123456', 12, '2011-08-02 00:18:49', '2011-08-02 00:18:49')[0m
  [1m[35mSQL (0.5ms)[0m  ROLLBACK
Completed   in 32093ms

SocketError (getaddrinfo: nodename nor servname provided, or not known):
  lib/xmpp_client.rb:14:in `initialize'
  app/models/user.rb:27:in `new'
  app/models/user.rb:27:in `register_jabber'
  app/models/user_observer.rb:7:in `after_create'
  app/controllers/users_controller.rb:11:in `create'

Rendered /Users/fred/.rvm/gems/ruby-1.9.2-p180/gems/actionpack-3.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.erb (0.6ms)
Rendered /Users/fred/.rvm/gems/ruby-1.9.2-p180/gems/actionpack-3.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (2.4ms)
Rendered /Users/fred/.rvm/gems/ruby-1.9.2-p180/gems/actionpack-3.0.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (4.8ms)

A: Check your log file, whenever an exception is thrown it outputs the stack trace. Lines closest to the top are more relevant than those lower down. Many of the lines will be "false errors" meaning they are not the problem, but fail because of the problem. It takes some guess-work and a healthy dose of experience to figure out which one is relevant.
Please include the stack trace and maybe we can help you further.


text:
Q: How to Insert Data in CakePHP with APIController? I have a Function Order in Apicontroller.php, I 've made a note column, but why it does not want the record column store database to the Order, I am very confused to find where the data insert process in CakePHP, but to send the email had been a success, there is my code :
public function Order()
{
    $status                                     =   false;
    $message                                        =   ERR_04;
    $code                                           =   "04";

    $request["Order"]["service_id"]             =   empty($_REQUEST["service_id"]) ? "" : $_REQUEST["service_id"];
    $request["Order"]["user_id"]                    =   empty($_REQUEST["user_id"]) ? "" : $_REQUEST["user_id"];
    $request["Order"]["fullname"]                   =   empty($_REQUEST["fullname"]) ? "" : $_REQUEST["fullname"];
    $request["Order"]["email"]                      =   empty($_REQUEST["email"]) ? "" : $_REQUEST["email"];
    $request["Order"]["phone"]                      =   empty($_REQUEST["phone"]) ? "" : $_REQUEST["phone"];

    $request["Order"]["gender"]                     =   empty($_REQUEST["gender"]) ? "" : $_REQUEST["gender"];
    $request["Order"]["address"]                    =   empty($_REQUEST["address"]) ? "" : $_REQUEST["address"];
    $request["Order"]["lt"]                         =   empty($_REQUEST["lt"]) ? "0" : $_REQUEST["lt"];
    $request["Order"]["unit"]                       =   empty($_REQUEST["unit"]) ? "0" : $_REQUEST["unit"];

    $request["Order"]["city_id"]                    =   empty($_REQUEST["city_id"]) ? "" : $_REQUEST["city_id"];
    $request["Order"]["district_id"]                =   empty($_REQUEST["district_id"]) ? "" : $_REQUEST["district_id"];

    $request["Order"]["village_id"]                 =   empty($_REQUEST["village_id"]) ? "" : $_REQUEST["village_id"];
    $request["Order"]["date_order"]                 =   empty($_REQUEST["date_order"]) ? "" : $_REQUEST["date_order"];
    $request["Order"]["time_order"]                 =   empty($_REQUEST["time_order"]) ? "" : $_REQUEST["time_order"];
    $request["Order"]["time_finish"]                =   empty($_REQUEST["time_finish"]) ? "" : $_REQUEST["time_finish"];
    $request["Order"]["building_id"]                =   empty($_REQUEST["building_id"]) ? "" : $_REQUEST["building_id"];

// "Note" Variable Cannot Save in Database
    $request["Order"]["note"]                   =   empty($_REQUEST["note"]) ? "" : $_REQUEST["note"];

// I Don't Know Why
    $request["Order"]["total_maid"]                 =   empty($_REQUEST["total_maid"]) ? "1" : $_REQUEST["total_maid"];
    $request["Order"]["total_shift"]                =   empty($_REQUEST["total_shift"]) ? "1" : $_REQUEST["total_shift"];
    $request["Order"]["different_gender"]           =   empty($_REQUEST["different_gender"]) ? "0" : $_REQUEST["different_gender"];

    $request["Order"]["price"]                      =   empty($_REQUEST["price"]) ? "0" : $_REQUEST["price"];

    $request["Order"]["total"]                      =   $request["Order"]["total_maid"] * $request["Order"]["total_shift"] * $request["Order"]["price"];

    $request["Order"]["duration"]                   =   empty($_REQUEST["duration"]) ? "0" : $_REQUEST["duration"];

    $timeCoonvert                                   =   strtotime($request["Order"]["date_order"]." ".$request["Order"]["time_order"].":00");
    $request["Order"]["expired_order"]              =   date("Y-m-d H:i:s",mktime(date("H")+5,date("i"),date("s"),date("m"),date("d"),date("Y")));

    $this->loadModel('Order');
    $this->Order->ValidateCheckout();
    $this->Order->set($request);

    $error                                          =   $this->Order->InvalidFields();
    if(empty($error))
    {
        $status     =   true;
        $message    =   ERR_00;
        $code       =   "00";
        $save       =   $this->Order->save($request,array("validate"=>false));
        $ID         =   $this->Order->getLastInsertId();

        $this->Order->BindAll(false);
        $data       =   $this->Order->find('first',array(
                            'conditions'    =>  array(
                                'Order.id'  =>  $ID
                            )
                        ));
        $different_gender   =   ($request["Order"]["different_gender"] == "1") ? "Ya" : "Tidak";
        /****************** EMAIL NOTIFICATION ************************/
        $search     =   array(
                            '[web_url]',
                            '[logo_url]',
                            '[cms_url]',
                            '[order_id]',
                            '[fullname]',
                            '[phone]',
                            '[address]',
                            '[email]',
                            '[date_order]',
                            '[time_order]',
                            '[total_maid]',
                            '[different_gender]',
                            '[total_shift]',
                            '[bank]',
                            '[total]'
                        );

        $replace    =   array(
                            $this->settings["web_url"],
                            $this->settings["logo_url"],
                            $this->settings["cms_url"],
                            $data["Order"]["order_id_display"],
                            ucwords(strtolower($data["Order"]["fullname"])),
                            $data["Order"]["phone"],
                            $data["Order"]["address"]."
".ucfirst($data["Village"]["name"])."
".ucfirst($data["District"]["name"])."
".ucfirst($data["City"]["name"]),
                            $request["Order"]["email"],
                            date("d M Y",strtotime($data["Order"]["date_order"])),
                            substr($data["Order"]["time_order"],0,-3),
                            $data["Order"]["total_maid"],
                            $different_gender,
                            $data["Order"]["total_shift"],
                            str_replace("\n","
",$this->settings['bank_payment']),
                            "Rp ".number_format($data["Order"]["total"],0,null,",")
                        );
        $this->Action->EmailSend('order', trim($request['Order']['email']), $search, $replace,array(),array(),"Order",$ID,"");
        $this->Action->EmailSend('order', "customer@gomaid.co.id", $search, $replace,array(),array(),"Order",$ID,"");
        /****************** EMAIL NOTIFICATION ************************/
    }
    else
    {
        $status     =   false;
        foreach($error as $k => $v)
        {
            $message    =   $v[0];
            break;
        }
        $code       =   "03";
        $data       =   null;
    }

    $out            =   array("status"=>$status,"message"=>$message,"data"=>$data,"code"=>$code,"request"=>$_REQUEST,"files"=>$_FILES);
    $json           =   json_encode($out);
    echo $json;
    pr($out);
}

This is my email receive ....
http://prntscr.com/a05oq9
But this is my table Orders still empty in note field ....
http://prntscr.com/a05pa5
Any have solution? i'm very stuck, i'm newbie inn CakePHP, please help me... im using Eclipse code Android to send data in web with CakePHP to database.

A: For sake of other people who might face this problem these are follow-up steps :

*

*Clear app/tmp/cache/model/* all the files.

*Set debug mode to 2.

*Make your app/tmp directory writable.

Note: Any alteration to the database schema will require to follow the steps 1 or 2 for cakePHP to detect changes made.


text:
Q: ImportError: No module named base I'm trying to implement PageObject pattern for my first Login test. While running it I'm receiving the following error:
>> py.test -v test_login.py
============================= test session starts ==============================
platform linux2 -- Python 2.7.3 -- pytest-2.3.4
plugins: xdist
collected 0 items / 1 errors

==================================== ERRORS ====================================
____________________ ERROR collecting test_login_logout.py _____________________
test_login_logout.py:10: in <module>
>   from ui.pages import LoginPage
../pages/__init__.py:1: in <module>
>   from loginPage import LoginPage
../pages/loginPage.py:3: in <module>
>   from base import BasePage
E   ImportError: No module named base

Here is the pythonpath:

Pythonpath: PYTHONPATH="${PYTHONPATH}:/usr/lib/python2.7/"

export PYTHONPATH

As far as it's one of my first tests a lot of code was copy-pasted, maybe there's something wrong with it but I'd can't get it. Will be very pleased with any suggestions on this point.
Also below is the structure and content of my so-called PageObject implementation:

*

*ui

*

*base

*

*__ init __ .py

*basePage.py

*configs.py

*wrapper.py

*pages

*

*__ init __ .py

*loginPage.py

*tests

*

*__ init __ .py

*test_login.py

*__ init __ .py

ui/__ init __ .py:

__author__ = 'testuser'

ui/base/__ init __ .py:

from wrapper import SeleniumWrapper
from basePage import BasePage

selenium_driver = SeleniumWrapper()

ui/base/basePage.py:

class BasePage(object):

    def __init__(self, driver):
        self.driver = driver

    def get_current_url(self):
        return str(self.driver.current_url)

ui/base/configs.py:

import os

try:
    os.environ["HOST"]
    HOST = os.environ["HOST"]
except KeyError:
    os.environ["HOST"] = 'http://www.website.com'
    HOST = str(os.environ["HOST"])
PORT = ''
BASE_URL_US = '%s:%s/en/' % (HOST, PORT)
EMAIL = 'test.user@gmail.com'
PASSWORD = 'secret'

ui/base/wrapper.py:

from selenium import webdriver
import configs

class SeleniumWrapper:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(SeleniumWrapper, cls).__new__(cls, *args, **kwargs)
        return cls._instance

    def connect(self, host=configs.BASE_URL_US):
        self.driver = webdriver.Firefox()

        self.base_url = host
        return self.driver

ui/pages/__ init __ .py:

from loginPage import LoginPage

ui/pages/loginPage.py:

from base import BasePage

class LoginPage(object):

    login_page_link = '.log-in>a'
    email_field_locator = 'email'
    password_field_locator = 'password'
    login_button_locator = 'submit'

    def __init__(self, driver, base_url):
        self.driver = driver
        self.driver.get(base_url)

    def login_action(self, email, password):
        login_page = self.driver.find_element_by_css_selector(self.login_page_link)
        email_element = self.driver.find_element_by_id(self.email_field_locator)
        password_element = self.driver.find_element_by_id(self.password_field_locator)
        login_button = self.driver.find_element_by_id(self.login_button_locator)
        login_page.click()
        email_element.send_keys(email)
        password_element.send_keys(password)
        login_button.click()

ui/tests/__ init __ .py:

__author__ = 'testuser'

ui/tests/test_login.py:

import sys
import os
import pytest

if __name__ == '__main__':
    sys.path.append(os.path.dirname(__file__) + '/../')
from ui.base import selenium_driver
from ui.pages import LoginPage
from ui.base import configs

@pytest.mark.ui
class TestLoginLogout(object):

    @classmethod
    def setup_class(cls):
        cls.verificationErrors = []
        cls.driver = selenium_driver.connect()
        cls.driver.implicitly_wait(10)
        cls.base_url = selenium_driver.base_url
        cls.email = configs.EMAIL
        cls.password = configs.PASSWORD

    @classmethod
    def teardown_class(cls):
        cls.driver.quit()
        assert cls.verificationErrors == []

    def test_login_positive(self):
        welcome_page = LoginPage(self.driver, self.base_url)
        login_page = welcome_page.login_action(self.email, self.password)
        # assert 'property' in login_page.get_current_url()

if __name__ == '__main__':
    pytest.main([__file__, "-s"])

A: Your base module is located in the ui module. Hence line:
from base import BasePage

should be:
from ui.base import BasePage

A: I was just a beginner when this error struck. So, what I did was:
from models.post import Post

A: i was just a beginner when this error struck what i did was
instead of:
from models.post import Post

i did the following after installing post as package:
from post import Post

it worked for me


text:
Q: Why is .compare returning 1? I understand that for strings y and x, and x.compare(y) is equal to 0, then both strings are equal. When I input an equal string for x using getline(cin,x), I'm getting 1 returned instead of 0. Why is this happening? Should I just account for x.compare(y) == 1 meaning that they are equal?
I have tried making k==0 in my if statement, but it's not returning 0. I feel like getline() is adding additional data to the string, causing compare() to return 1 instead of 0.
Here's my code:
int main(void) {
    string x;
    string y = "Hello World";
    getline(cin,x);
    int k = x.compare(y);
    cout << k;
    if (k==0) {
        cout << "Hi";
    }
    return 0;
}

A: int string::compare (const string& str) const
Returns:

*

*0 : if both strings are equal.

*A value < 0 : if *this is shorter than str or, first character that
doesn't match is smaller than str.

*A value > 0 : if *this is longer than str or, first character that
doesn't match is greater


text:
Q: Is it possible to call RichTextValueBuilder.setTextStyle( ) multiple times programmatically? I got this these values.

And I want to have this result.

So I made the following test code and tried it to the first cell.
function test2() {
  const ss = SpreadsheetApp.getActive();
  const sheet = ss.getSheetByName("richText3");
  const range1 = sheet.getRange("A1");
  const text1 = range1.getValue();
  Logger.log(text1);
  const re = new RegExp(/\([ a-zA-Z\/']*\)\?/dg);
  const redBold = SpreadsheetApp.newTextStyle().setBold(true).setForegroundColor('red').build();
  let array;
  while ((array = re.exec(text1)) !== null) {
    const [start, end] = array.indices[0];
    const richTxtValBlder = SpreadsheetApp.newRichTextValue()
        .setText(text1)
        .setTextStyle(start, end, redBold)
        .build();
    range1.setRichTextValue(richTxtValBlder);
  }
}

After first try, I got this result.

I checked the Reference Document again and I found this comment.

setText(text) : Sets the text for this value and clears any existing text style.
When creating a new Rich Text value, this should be called before setTextStyle()

I found that I should call .setText() once and call .setTextStyle() multiple times.
But the problem is .setTextStyle() should be called programmatically according to the number of patterns in each cell and I cannot find how to do it programmatically.
Each cell may have 0 to 10 patterns and I don't want to make 10 different richTExtValueBuilder which only differ in the number of .setTextStyle() calls.
Do you have any different ideas ?

A: Modification points:

*

*In your script, only cell "A1" is used, and also the 1st match is used. I thought that this might be the reason for your issue.

*In order to achieve your goal, I retrieve the values from column "A". And also, I use matchAll instead of exec.

When these points are reflected in your script, how about the following modification?
Modified script:
function test2() {
  const ss = SpreadsheetApp.getActive();
  const sheet = ss.getSheetByName("richText3");
  const range1 = sheet.getRange("A1:A" + sheet.getLastRow());
  const re = new RegExp(/\([ a-zA-Z\/']*\)\?/g);
  const redBold = SpreadsheetApp.newTextStyle().setBold(true).setForegroundColor('red').build();
  const richTextValues = range1.getRichTextValues();
  const res = richTextValues.map(([a]) => {
    const array = [...a.getText().matchAll(re)];
    if (array) {
      const temp = a.copy();
      array.forEach(a => temp.setTextStyle(a.index, a.index + a[0].length, redBold));
      return [temp.build()];
    }
    return [a];
  });
  range1.setRichTextValues(res);
}

Testing:
When this script is run, the following result is obtained.
From:

To:

References:

*

*map()

*setRichTextValues(values)

A: It looks like you need to call .setText() once, .setTextStyle() multiple times, and .build() once, e.g. change your while loop. Untested code:
    let richTxtValBlder = SpreadsheetApp.newRichTextValue().setText(text1);
    while ((array = re.exec(text1)) !== null) {
        const [start, end] = array.indices[0];
        richTxtValBlder = richTxtValBlder.setTextStyle(start, end, redBold);
    }
    richTxtValBlder = richTxtValBlder.build();
    range1.setRichTextValue(richTxtValBlder);


text:
Q: Why is writing to my NAS in small chunks so slow? I just discovered that the bottleneck of a Python script was writing a text file unbuffered line by line to our QNAP NAS. See attached Python snippet. Is this necessarily so slow or is there something wrong with our QNAP/network setup?
# local SSD: 2 seconds
with open(r'C:\Daten\numbers.txt', 'w') as f:

# local SSD with buffering: 2 seconds
with open(r'C:\Daten\numbers.txt', 'w', buffering=2**20) as f:

# Share on QNAP NAS: ### 36 ... 61 seconds! ###
with open(r'I:\numbers.txt', 'w') as f:

# Share on QNAP NAS with buffering: 2 ... 3 seconds
with open(r'I:\numbers.txt', 'w', buffering=2**20) as f:
    for i in range(1000000):
        print(i, file=f)

A: Any small I/O is going to be expensive compared to larger transfer.
In this case, the situation is worsened by:

*

*using unbuffered I/O

*sending data down to the network rather than a fast local bus

*using a remote filesystem protocol (ie: CIFS or NFS).

While you can somewhat improve performance by fine-tuning the NFS/CIFS/SMB server behavior, I strongly suggest you to avoid generic unbuffered I/O in favor of buffered I/O + explicit flush points (if required by your application).


text:
Q: How call a superclass implementation of a method that takes a variable number of arguments as in [UIAlertView initWithTitle...]? The OS X Developer Library shows how to create a method that takes a variable number of args in the following technical article: http://developer.apple.com/library/mac/#qa/qa1405/_index.html.
I'm trying to figure out if it's possible to subclass an existing implementation of method that takes variable args and call the superclass implementation.
Using UIActionSheet as an example look at the code below. Calling the superclass initWithTitle method only passes the first 'otherButtonTitle'. I don't know how to pass the remaining strings contained in the variable argument list.
// MyActionSheet.m

- (id)initWithTitle:(NSString *)title
           delegate:(id < UIActionSheetDelegate >)delegate
  cancelButtonTitle:(NSString *)cancelButtonTitle
destructiveButtonTitle:(NSString *)destructiveButtonTitle
otherButtonTitles:(NSString *)otherButtonTitles, ...
{
    // this calls the superclass initWithTitle: method but does not
    // pass NIL terminated list of strings
    self = [super initWithTitle:title
                       delegate:delegate
              cancelButtonTitle:cancelButtonTitle
         destructiveButtonTitle:destructiveButtonTitle
              otherButtonTitles:otherButtonTitles, nil];
    if (self) {
        // custom initialization
    }
    return self;
}

I can get the args using va_list, va_start, va_end but don't know how to pass them to the superclass method.
In case anyone is tempted to tell me that I can do this a different way (e.g. don't pass along the variable args but use va_list, va_start, va_end to create an array of strings and call addButtonWithTitle: multiple times, I know I can do that. I used UIActionSheet as an example. There are other cases where the ability to subclass a method with variable args would be useful and I'd like to learn how to do exactly what I've asked if it is possible.
thanks!

A: A number of classes in Cocoa have methods that take variable numbers of arguments. In most cases, these classes will also have an equivalent method that takes a va_list. It's only possible to do what you're suggesting if the class you're using provides one of those methods. For instance, +[NSString stringWithFormat:...] takes a variable number of arguments. Cocoa provides -[NSString initWithFormat:arguments:] where the arguments parameter is a va_list. This allows you to do the following:
- (void)setContentsWithFormat:(NSString *)formatString, ... {
    [contents autorelease];

    va_list args;
    va_start(args, formatString);
    contents = [[NSString alloc] initWithFormat:formatString arguments:args];
    va_end(args);
}

The va_list parameter allows us to pass our own variable argument list to the Cocoa method so that the Cocoa method can handle the arguments.
However, since UIAlertView doesn't provide a va_list API, the cleanest way is probably to make repeated calls to addButtonWithTitle:

A: You can't. Objective-C's variable arguments support is effectively that of C, and as you may already know there is no (portable) way to correctly set up the stack to call to a variadic function.
If the designer of the superclass was on the ball, there will be a parallel function that takes a va_list or NSArray argument that you can call instead. If not, you're usually out of luck.
In this particular case, you could call the superclass's constructor with nil for all the buttons, and then use addButtonWithTitle:, cancelButtonIndex, and so on to setup the buttons "manually".

A: If you can't do it the proper way, you can always do this:
id arg1 = ...; // nil or 1st arg
id arg2 = ...; // nil or 2nd arg
id arg3 = ...; // nil or 3rd arg
id arg4 = ...; // nil or 4th arg
// etc.

self = [super initWithTitle:title
                   delegate:delegate
          cancelButtonTitle:cancelButtonTitle
     destructiveButtonTitle:destructiveButtonTitle
          otherButtonTitles:arg1,arg2,arg3,arg4,/*etc*/ nil];

ugly as hell, but it will work.


text:
Q: Unable to write "undefined" file in grunt plugin I'm new to writing grunt plugins and I'm running into a problem when I'm trying to run it:
Running "inject_css:dev" (inject_css) task
Warning: Unable to write "undefined" file (Error code: undefined). Use --force to continue.

My plugin looks like:
'use strict';

module.exports = function(grunt) {
  grunt.registerMultiTask('inject_css', 'Allows you to inject CSS into HTML files as part of the build process.', function() {
    var src = grunt.file.expand(this.data.src);
    var text = '';

    if (src) {
        src.forEach(function (script) {
            text += grunt.file.read(script);
        });
    } else {
        grunt.log.error('Please specify a file to inject into the html.');
        return;
    }

    this.files.forEach(function (file) {
        grunt.file.write(file.dest, grunt.file.read(file.src).replace('<!-- inject -->', '<style type="text/css">' + text + '</style>'));
        grunt.log.ok('File injected'.blue + ' into ' + file.dest);
    });
  });
};

And when trying to call it in my gruntfile I'm using the following config:
inject_css: {
  dev: {
    files:{
      'static/test/test.html': 'test.html'
    },
    src: 'static/less/form.less'
  }
}

Any ideas what I'm doing wrong?

A: Looking at the warning, I'm guessing it is thrown there :
grunt.file.write(file.dest, grunt.file.read(file.src).replace('<!-- inject -->', '<style type="text/css">' + text + '</style>'));

Which would mean file.dest is undefined.
And looking at your code, it seems normal cause you go with a foreach over this.files which do not contain any dest property.
Basically, I think you forgot to expand this.dest and this should do the trick :
var expandedFiles = grunt.file.expand(this.data.files);
expandedFiles.forEach(function (file) {
    grunt.file.write(file.dest, grunt.file.read(file.src).replace('<!-- inject -->', '<style type="text/css">' + text + '</style>'));
    grunt.log.ok('File injected'.blue + ' into ' + file.dest);
});

As i couldn't really try it, it's just a guess, let me know if it works fine.

A: Have you tried
inject_css: {
  dev: {
    .....
    src: ['static/less/form.less']
  }
}


text:
Q: h5py chunking structured structured numpy arrays I'm getting data from sensors and storing it in HDF5 files using h5py.
The sensordata comes in as a bytes object, I use numpy to convert it into a structured array. Then I write the structured array into the HDF5 file. This all works as intended.
Now I want to read the data back from the HDF5 file and I'm only interested in some parts of it. For example if I only want to read one column. The problem is that directly writing the structured numpy array to the HDF5 file writes all the data as a single block, for example with shape (10,). The default chunksize is set to (256,). This means I read 256 rows and all columns of data for each chunk. However, this gets really slow when the number of columns increases.
Is there a way to modify the data or change the chunking parameters so I can read a single column of data instead of a whole block in each chunk?
A minimal example of what I'm using is shown below:
import h5py
import ctypes
import numpy as np

class SensorStruct(ctypes.Structure):
    _pack_ = 4
    _fields_ = [('tc_time',ctypes.c_int64),
                ('pc_time',ctypes.c_double),
                ('nSample', ctypes.c_ushort),
                ('fMean', ctypes.c_float),
                ('fLowerbound', ctypes.c_float),
                ('fUpperbound', ctypes.c_float)]

def CreateFile(filename):
    #Create a new HDF5 file
    with h5py.File(filename, 'w', libver='latest') as f:
        f.swmr_mode = True

def AddDataset(filename, dsetname, struct):
    #Add a dataset to an existing HDF5 file
    with h5py.File(filename, 'r+', libver='latest', swmr=True) as f:
        f.create_dataset(dsetname,
                         dtype = struct,
                         shape = (0,), #Shape will update each time data is added
                         maxshape = (60480000,),
                         chunks = True, #Need to modify this somehow
                         compression = 'gzip')

def WriteData(filename, data):
    #Append an existing dataset with new data
    with h5py.File(filename, 'r+', libver='latest', swmr=True) as f:
        dset = f[dsetname]

        length = dset.shape[0]
        maxlength = dset.maxshape[0]

        newlength = length + len(data)
        if newlength < maxlength:
            dset.resize((newlength,))
            dset[length:newlength] = data

filename = 'TESTFILE.h5'
dsetname = 'Sensor1'
struct_dt = np.dtype(SensorStruct)

#Rawdata comes in from a sensor every few seconds, returns as bytes object
rawdata1 = b"\x15\xcd[\x07\x00\x00\x00\x00 x\x81BA\x02\xd7A\x00\x00\x00\x00'u\x1fA\xf4Q\x01AbY?A\x16\xcd[\x07\x00\x00\x00\x00 x\x81BA\x02\xd7A\x01\x00\x00\x00\x1c\xe4&A[\x85\x0bA\x97\x96=A\x17\xcd[\x07\x00\x00\x00\x00 x\x81BA\x02\xd7A\x02\x00\x00\x00\xf6\x8b\x02A\xe5\xd5\xd5@\xc1Y\x1bA\x18\xcd[\x07\x00\x00\x00\x00 x\x81BA\x02\xd7A\x03\x00\x00\x00 \xec9A?W\x17A\xd0vRA\x19\xcd[\x07\x00\x00\x00\x00 x\x81BA\x02\xd7A\x04\x00\x00\x00\xf2\t/A\x83U\x19A\r&[A\x1a\xcd[\x07\x00\x00\x00\x00 x\x81BA\x02\xd7A\x05\x00\x00\x00s\x8a\x18A\xb0\x19\x04A\xc6\xb51A\x1b\xcd[\x07\x00\x00\x00\x00 x\x81BA\x02\xd7A\x06\x00\x00\x00P\xb6>A6\xc5 A)erA\x1c\xcd[\x07\x00\x00\x00\x00 x\x81BA\x02\xd7A\x07\x00\x00\x00\xe5e\x11A\x17\x9c\xff@^\xbf5A\x1d\xcd[\x07\x00\x00\x00\x00 x\x81BA\x02\xd7A\x08\x00\x00\x00*\xbe\x19At\xd5\x04AN\x919A\x1e\xcd[\x07\x00\x00\x00\x00 x\x81BA\x02\xd7A\t\x00\x00\x00\xa2* A(-\x03AE\xedFA"
rawdata2 = b'\x1f\xcd[\x07\x00\x00\x00\x00 x\x01EA\x02\xd7A\n\x00\x00\x00\xb6\x89&A\xd7\x8f\x07A\xe9\x00SA \xcd[\x07\x00\x00\x00\x00 x\x01EA\x02\xd7A\x0b\x00\x00\x00\x91I\xfd@*\\\xdc@<\x17!A!\xcd[\x07\x00\x00\x00\x00 x\x01EA\x02\xd7A\x0c\x00\x00\x00,q\x12A\x81\x1f\xfa@\x81\xfe(A"\xcd[\x07\x00\x00\x00\x00 x\x01EA\x02\xd7A\r\x00\x00\x00\x04@\x1cA\x03p\x05A\x05\xb03A#\xcd[\x07\x00\x00\x00\x00 x\x01EA\x02\xd7A\x0e\x00\x00\x00\xad\x89:A8h#A\xab\x88SA$\xcd[\x07\x00\x00\x00\x00 x\x01EA\x02\xd7A\x0f\x00\x00\x00I\x0f\xf5@\x15\xaa\xca@Rk\x0cA%\xcd[\x07\x00\x00\x00\x00 x\x01EA\x02\xd7A\x10\x00\x00\x00\xab\xeb\x1dA\x86 \x05A\x1807A&\xcd[\x07\x00\x00\x00\x00 x\x01EA\x02\xd7A\x11\x00\x00\x00Q\xda3A\xdc\xa6\x1cAT)ZA\'\xcd[\x07\x00\x00\x00\x00 x\x01EA\x02\xd7A\x12\x00\x00\x00U\xb3=A\xae\xcb\x1aA\xebmQA(\xcd[\x07\x00\x00\x00\x00 x\x01EA\x02\xd7A\x13\x00\x00\x00\x8f\x82\x0cA\x11\x15\xf3@$]&A'
data1 = np.frombuffer(rawdata1, dtype=SensorStruct)
data2 = np.frombuffer(rawdata2, dtype=SensorStruct)

CreateFile(filename)
AddDataset(filename, dsetname, SensorStruct)
WriteData(filename, data1)
WriteData(filename, data2)

Here I'm trying to read a single column of data:
import time
t0 = time.time()

with h5py.File(filename, 'r', libver='latest', swmr=True) as f:
    dset = f[dsetname]

    #Optimize chunking so I can read one column
    #My real dataset contains hundreds of columns and milions of rows
    #So this minimal example may look slightly trivial
    print('Chunksize: {}'.format(dset.chunks))
    t = dset['pc_time']

print('Reading the time column took {} seconds'.format(time.time()-t0))

A: In [551]: dt = np.dtype([('a',int),('b','uint8'),('c','float32'),('d','float64')])
In [552]: x = np.ones(10, dt)
In [553]: x.dtype
Out[553]: dtype([('a', '<i8'), ('b', 'u1'), ('c', '<f4'), ('d', '<f8')])
In [554]: x.itemsize
Out[554]: 21
In [555]: x.__array_interface__
Out[555]:
{'data': (40185408, False),
 'strides': None,
 'descr': [('a', '<i8'), ('b', '|u1'), ('c', '<f4'), ('d', '<f8')],
 'typestr': '|V21',
 'shape': (10,),
 'version': 3}

Each record this array takes up 21 bytes, 'V21'.
In [557]: f = h5py.File('vtype.h5','w')
In [558]: ds = f.create_dataset('data', data=x)
In [559]: ds
Out[559]: <HDF5 dataset "data": shape (10,), type "|V21">
In [560]: ds.dtype
Out[560]: dtype([('a', '<i8'), ('b', 'u1'), ('c', '<f4'), ('d', '<f8')])

In h5dump this dataset displays as
  DATATYPE  H5T_COMPOUND {
     H5T_STD_I64LE "a";
     H5T_STD_U8LE "b";
     H5T_IEEE_F32LE "c";
     H5T_IEEE_F64LE "d";
  }

The docs on chunking show a chunking tuple with the same number of elements as the array's shape.
http://docs.h5py.org/en/stable/high/dataset.html#chunked-storage
Here I created a 1d array, so chunking, if specified, only applies to that dimension, not to the Compound datatype.
For numpy arrays, accessing a single field of a structured array is relatively fast, comparable to accessing a column of a 2d array, or a stand along 1d array.  It is a view.
But loading from a h5 dataset is a copy.  With this small example, loading ds[:] is faster than ds['a'].  And ds[:n]['a'] is faster than ds['a'][:n].
I don't have a sense of how these timings compare with column access of a simple 2d array.  And I don't know if the timings depend on the size of the dtype.


text:
Q: Can't get Ubuntu 16.04 to boot after installing I am trying to install Ubuntu on my old desktop. The first hard drive will hold Ubuntu, and a second hard drive holds Windows 10 on it currently. Booting into Windows 10 works fine if I select it from the BIOS.  I install Ubuntu with a Live USB created with Universal USB Installer 1.9.6.6. The live version of Ubuntu loads up and works fine. I install using the shortcut on the Live Ubuntu desktop and then I am unable to get a boot to the desktop environment. After throwing myself at it for hours today I am at wits end on trying to sort this.
Notes on the Process:
Boot LiveUSB
Install Ubuntu 16.04.1 LTS -- Shortcut
English
Download Updates & Install 3rd part software
Erase Ubuntu 16.04.1 LTS and reinstall -- Install Now
    Pop Up Warning
        Partition tables of the following devices are changed: SCSI1(0,0,0)(sda)
        Following partitions are going to be formatted:
            partition #1 of SCSI1(0,0,0)(sda) as ext4
            partition #5 of SCSI1(0,0,0)(sda) as swap
        continue
Time Zone - NY
Keyboard Layout -English (US) - English(US)
Set User & Password - require password to log in -- continue
Install Process Begins
Install finishes - Restart Now
    Options for Setup (f2) and Boot Options (f12)
Burgundy blank Screen (NOT GRUB)
    Appears unresponsive, no blinking cursor
        tried (ctrl+alt+f1) (alt+f7) (f6) (alt+tab)
    Maintains Burgundy screen throughout
    ~5 minutes later, screen is still burgundy and unresponsive
    ~15 minutes no changes; force power off by holding down power button
Power On
    Options for Setup (f2) and Boot Options (f12)
GNU GRUB version 2.02^beta2-36ubuntu3.1
    Ubuntu
    Advanced options for Ubuntu
    Memory test (memtest86+)
    Memory test (memtest86+, serial console 115200)
Enter to boot into Ubuntu (top option)
black screen blinking cursor
    Unresponsive (after all while moves to next step)
Screen: Gave up waiting for root device. Common problems:
 -Boot args (cat /proc/cmdline)
   -Check rootdelay= (did the system wait long enough?)
   -Check root= (did the system wait for the right device?)
  -Missing modules (cat /proc/modules; ls /dev)
 ALERT UUID=(numbers) does not exist. Dropping to a shell!
  Busybox v1.22.1 (Ubuntu 1:1.22.0-15ubuntu1) built-in shell (ash)
  Enter 'help' for a list of built-in commands.
  (initramfs)_  (blinking cursor, but does not take any keyboard input)
Power Off by holding down power button

I've tried a few other things as well such as adding nomodeset to the launch options via grub, radeon.modeset=0, thinking of ways to brutally destroy the machine, running boot-repair through the live version.
Broke hyperlinks with spaces due to lacking reputation to post more than two links.
Images:
initramfs unresponsive:

initramfs unresponsive:

http://i.imgur.com/5lhF0US.jpg (GRUB2)
Logs from two DIFFERENT boot-repairs:
https://paste2.org/YdHyFhM4
https://paste2.org/Zsxc2X66
Edit: http://imgur.com/a/Mq33Y (link to album of images)

A: After a lengthy discussion and troubleshooting in the comments, it was decided that a Ubuntu reinstall from DVD would solve the problem. Cheers, Al


text:
Q: Как исправить ошибку аутентификации при отправки email в .Net core?
На фото мой код, который я почти содрал с этой статьи (https://metanit.com/sharp/aspnet5/21.1.php). При вызове метода происходит ошибка аутентификации, но почта и пароль были внимательно проверены, при вводе я не ошибся. В коментах статьи сказано поменять настройки в аккаунте гугла, ssl(true/false) я это сделал, но безуспешно. Кто знает чем проблема? Так же в аккаунте гугла появились сообщения "Попытка входа заблокирована".


text:
Q: why does applicationWillTerminate: delegate does not fire on minimize? - (void)applicationWillTerminate:(UIApplication *)application {
[InAppPurchaseManager closeStore];
[[InAppPurchaseManager sharedDownloadManager] saveReceipts];
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"ISPARSERLOCKED"];
}

I am working on ios 5 ...i would like to know if there are situations that will not fire the above method on minimize.
Thanks

A: By minimize I assume you mean another app becoming the active app. That almost never causes termination in iOS anymore. You may never get applicationWillTerminate in iOS. For detecting when you become inactive look at -(void)applicationWillResignActive:(UIApplication *)application and -(void)applicationDidBecomeActive:(UIApplication *)application, both are app delegate methods.


text:
Q: Django How to pass signals in Abstract User model for create any custom model? I have an Abstract user model. Where I have three type of user and I also have three custom model for three user. I want to pass signals in my Abstract user model for create my custom model. I have an custom model which name is MyAuthors. If I already have any user in my Abstract user model and save him as author but don't have any objects in MyAuthors model then it will create an objects in MyAuthors model for this user. I tried this code but didn't create user objects in MyAuthors model.
class UserManagement(AbstractUser):
      is_blog_author = models.BooleanField(default=False)
      is_subscriber = models.BooleanField(default=False)
      is_customer = models.BooleanField(default=False)

class MyAuthors(models.Model):
      user = models.OneToOneField(UserManagement, on_delete=models.CASCADE, primary_key=True)
      is_blog_author = models.BooleanField(default=False)

@receiver(post_save,sender=settings.AUTH_USER_MODEL)
def user_objetcs(sender,instance,created,**kwargs):
    if created:
       author = MyAuthors.objects.filter(user=instance) #here I am checking does user have or not any profile in MyAuthors model.

       if not author: #if user don't have any objects in MyAuthors model then it will create
          MyAuthors.objects.create(user=instance,is_blog_author=instance.is_blog_author)


text:
Q: programmatically scrolling a TreeViewer in SWT I have two TreeViewer components. The horizontal scroll bars have to be synchronized. I have tried with setSelection and setTopItem methods but both have no effect to other tree. only the ScrollBar is moved but not the tree .
final ScrollBar rightScrollBar = tree_1.getHorizontalBar();
rightScrollBar.addListener(SWT.Selection, new Listener() {
        @Override
        public void handleEvent(Event event) {
             //       tree.setSelection(tree_1.getSelection());
        }
    });

Any idea Please ?

A: Unfortunately programmatic horizontal scrolling is not possible. In fact, scrolling in general by using the ScrollBar objects isn't possible at all. The method setTopItem(TreeItem item) that you mentioned is only for vertical scrolling which isn't what you're looking, right? But for vertical scrolling that method should work.


text:
Q: Memory is not cleared after destroying EGL context which shares data with other context I'm working on 3d model viewer for android. When I open model, non-VR view (RenderView) which extends GLSurfaceView loads. Here is context factory which I use in setEGLContextFactory() method in this view (log calls and error checks are ommited):
public static class ContextFactory implements GLSurfaceView.EGLContextFactory {
    private static int EGL_CONTEXT_CLIENT_VERSION = 0x3098;

    public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig) {
        int[] attrib_list = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE };
        EGLContext context = egl.eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT,
                attrib_list);

        //Reference is need to use this context as share_context parameter.
        RenderView.context = context;
        return context;
    }

    public void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context) {
        egl.eglDestroyContext(display, context);
    }
}

Next I press 'VR' button and view which extends CardboardView (which extends GLSurfaceView) loads. Here it's context factory:
public static class ContextFactory implements GLSurfaceView.EGLContextFactory {
    private static int EGL_CONTEXT_CLIENT_VERSION = 0x3098;

    public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig) {
        int[] attrib_list = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE };
        EGLContext newContext = egl.eglCreateContext(display, eglConfig, RenderView.context, attrib_list);
        return newContext;
    }

    public void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context) {
        egl.eglDestroyContext(display, context);
    }
}

As you can see it uses RenderView context as share_context parameter in eglCreateContext() method. I also setPreserveEGLContextOnPause(true) on non-VR view so context isn't lost after i switch to VR mode.
Next i press 'Back" button and we return to non-VR view (RenderView).
All EGLCOntextFactory methods work fine and get called when needed. VR context gets properly destroyed when i switch back to non-VR mode but memory it consumes is not get cleared.
Now i go to VR mode again and another context is created which consume memory. I go back to non-VR mode, VR context get destroyed but memory is not get cleared again. So each time I switch to VR mode more and more memory get consumed (about 17 MB per switch).
Memory is totaly cleared (it doesn't matter how much VR contexts were created) only afted non-VR context (which shares data with VR contexts) is destroyed (when i close non-VR view and go to model picking screen).
So the question is why context memory isn't cleared after destruction if context is 'based' on another context and only clears after 'base' context is destroyed? And is there way to resolve this problem by means of GL methods?


text:
Q: I want to get "0.8" from my string using PHP I have a string
$string = "2.5 lakh videos views 0.8";

Now I want to get "0.8" from above string using PHP.

A: To get the last 3 characters:
$string = "2.5 lakh videos views 0.8";
$valSubstr = substr($string, -3);
echo $valSubstr;

To get the last "part" of the sentence. (this way you don't have to care about the count of characters in your number)
$string = "2.5 lakh videos views 0.8";
$partsString = explode(' ', $string);
$valExplode = $partsString[count($partsString) - 1];
echo $valExplode;

Both methods are bad, because you can only hope your data is in the format you expect it to be. But if your data is always in the format you showed, it would work. You can add a regex to check for unwanted characters like a trailing ".".

A: You can use php function substr() like this substr($string,-3);.


text:
Q: Find a row based on a cell value, copy only part of the row in to a new sheet and the rest of the row into the next row of the new sheet I have a file that has 5 transaction codes ("IPL","ISL","IMO","IIC","CAPO").
I need my macro to find the first 4 transaction codes in column dc of worksheets("sort area"), if it locates it, then take the contents of DE-FN and copy values to a new sheet.
for the last transaction code, i need the macro to find the transaction code in dc, and if it's there take the contents of the row but only the subsequent 8 columns (DE-DL) copy paste values in to worksheet("flat file") and then take the next 8 columns (DM-DS) from the original sheet ("sort area") and copy values in worksheet("flat file") but the following row
for the first part of the macro, i have it separated in to two parts, where i am copying the contents of the entire row, pasting values in to a new sheet, and then sorting the contents and deleting unneeded columns in the new sheet.
I'm struggling because my code is skipping some rows that contain IPL and i don't know why.
i have no idea how to do the last part, CAPO.
Part A (this takes the IPL transaction code and moves it to the new sheet ("flat file"):
Sub IPLFlat()

    Dim xRg As Range
    Dim xCell As Range
    Dim xRRg1 As Range
    Dim xRRg2 As Range
    Dim I As Long
    Dim J As Long
    Dim K As Long
    Dim xC1 As Long
    Dim xFNum As Long
    Dim xDShName As String
    Dim xRShName As String

    xDShName = "sort area"
    xRShName = "flat file"
    I = Worksheets(xDShName).UsedRange.Rows.Count
    J = Worksheets(xRShName).UsedRange.Rows.Count
    xC1 = Worksheets(xDShName).UsedRange.Columns.Count

    If J = 1 Then
    If Application.WorksheetFunction.CountA(Worksheets(xRShName).UsedRange) = 0 Then J = 0
    End If

    Set xRg = Worksheets(xDShName).Range("DC2:DC" & I)

    On Error Resume Next
    Application.ScreenUpdating = False

    For K = 1 To xRg.Count
    If CStr(xRg(K).Value) = "IPL" Then
    Set xRRg1 = xRg(K).EntireRow
    Set xRRg2 = Worksheets(xRShName).Range("A" & J + 1).EntireRow

    xRRg2.Value = xRRg1.Value

    If CStr(xRg(K).Value) = "IPL" Then
    K = K + 1
    End If
    J = J + 1
    End If
    Next
    Application.ScreenUpdating = True

    'Sort Flatfile tab
    Worksheets("flat file").Activate
    With ActiveSheet.Sort
         .SortFields.Add Key:=Range("DF1"), Order:=xlAscending
              .SetRange Range("A1", Range("FG" & Rows.Count).End(xlUp))
         .Header = xlNo
         .Apply
    End With
    Columns("A:DD").EntireColumn.Delete

A: Here is a solution:
Sub stackOverflow()
    Dim sortSheet As Worksheet, flatSheet As Worksheet, newSheet As Worksheet
    Set sortSheet = ThisWorkbook.Sheets("sort area")
    Set flatSheet = ThisWorkbook.Sheets("flat file")
    Dim rCount As Long, fCount As Long
    rCount = sortSheet.Cells(sortSheet.Rows.Count, 1).End(xlUp).Row
    For i = 2 To rCount
        Select Case sortSheet.Cells(i, 107).Value
        Case "IPL", "ISL", "IMO", "IIC"
            Set newSheet = ThisWorkbook.Sheets.Add
            sortSheet.Range(sortSheet.Cells(i, 109), sortSheet.Cells(i, 170)).Copy 'de->109 fn->170
            newSheet.Paste
        Case "CAPO"
            With flatSheet
                fCount = .Cells(.Rows.Count, 1).End(xlUp).Row
                sortSheet.Range(sortSheet.Cells(i, 109), sortSheet.Cells(i, 116)).Copy 'de->109 dl->116
                .Range(.Cells((fCount + 1), 1), .Cells((fCount + 1), 8).PasteSpecial Paste:xlPasteValues
                sortSheet.Range(sortSheet.Cells(i, 117), sortSheet.Cells(i, 123)).Copy 'dm->117 ds->123
                .Range(.Cells((fCount + 2), 1), .Cells((fCount + 2), 6).PasteSpecial Paste:xlPasteValues
            End With
        End Select
    Next i
End Sub

I hope I understood your problem correctly and that this helps,
Cheers


text:
Q: Detecting iOS UI events in programmatically created controls I want to have a text input (UITextField) which I create in the main View Controller react to the user's input (specifically when they tap the keyboard's "return" key), but I can't find any way to do this.
I understand that the "usual" way to do this is to create the control in Interface Builder and use that to connect events on the control to exposed IBAction methods, but I want to do this without Interface Builder.
Alternatively
I can create the control in Interface Builder and have its events connected normally, but how do I then get ahold of the object to control it (I just want to be able to hide/show it and perhaps reposition in) from my code?
Again I can't find a way to do this
Either route would work for me - I really don't care how I create the UITextField.
TIA
Mike Peat

A: You could add an observer to the notification center like this:
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyPressed:) name: UITextFieldTextDidChangeNotification object: nil];

and implement the corresponding method:
-(void) keyPressed: (NSNotification*) notification
{
  NSLog([[notification object]text]);
}

A: You need to set up a delegate for the TextField.
textField.delegate = self;

The delegate has certain methodes that reacts to actions with the textField.
You can react to the UserInput with the delegate methode:
- (void)textFieldDidEndEditing:(UITextField *)textField

It is called after the DoneKey (or whatever key you use to end the editing) is pressed
Hope this is what you are looking for


text:
Q: When did we start talking about "going viral"? I am trying to determine when the phrase "going viral" was first used.  Similarly, when did the phrases "viral video" and "viral marketing" get their start?  I have looked online at various sites, but none really address this question (other than saying "recently").

A: It looks like the phrase started being used in print in about 1999 or 2000. And viral video seems to date from 2004.

A: Going viral
I found no earlier example than the one in Callithumpian's comment from  July 31, 2000 by Seth Godin for Fast Company:

Have the idea behind your online experience go viral, bringing you a large chunk of the group that you're targeting without your having to spend a fortune advertising your new service.

"go viral" OR "went viral" OR "gone viral" OR "going viral"
Viral video
The earliest I found is from 21 March 2003 in an article by MediaWeek titled:

Splinter Cell for the PS2 launches with viral video

In 2002, search engine Lycos had set up a Viral Chart for people to upload the viral attachments that people spread via email. When promoting the chart in May 2002, they referred to viral videos:

Sign up to the Viral Chart vTeam and become part of a select group
  spreading the word about Lycos' brilliant new Viral Chart - it's THE
  place on the web to find the coolest, funniest, most outrageous viral
  games, pictures, videos and more!

Here's an archive of the Lycos Viral Chart.
Viral marketing
I found nothing earlier than the 1989 Barrie noted from the OED, in PC User:

The staff almost unanimously voted with their feet as long waiting lists developed for use of the Macintoshes... 'It's viral marketing. You get one or two in and they spread throughout the company.'

A: We, an advertising strategy team at Chiat/Day Los Angeles( Now TBWA) developed the word viral marketing in 1994/5 when launching the first PlayStation for Sony.  It came partly out of the notion that our target of gamers, especially younger people were huge marketing cynics and rejected things pushed at them. Sony had no credibility with this target at the time to make video games. Our insight was people seek things that elude them , especially among the gamer community constantly trying to discover a way through.  So we did a 'stealth' campaign to go after influencers/opinion leaders, we took about a million dollars and created street teams and layered an intricate web of info. and intrigue, everything from club hand stamps to urinal cakes with game code on them, insiders picked up on it, found how to use it in trials of the game and it took off. It fueled the rest of our ad campaign (MTV VMAs, gamer mags) and within 6 months PlayStation was #1 in category- Sony's most successful launch in History.

A: The Oxford English Dictionary's earliest  citation for the use of viral in the sense of 'involving the rapid spread of information' is dated 1989. The earliest citation actually including the verb go is as late as 2004:

Their petition also went viral, gathering half a million signatures in
  a few weeks.

A: The Larry Sanders Show s04e07 (1995)
http://m.imdb.com/title/tt0625359/
The idea of a video itself, spreading like a virus because of public interest, may have inadvertantly been paraphrased when Rip Torn's character compares Hank's sex-tape to the ebola virus.
Quote: "That tape you copied is crawling around town like the f***ing ebola virus."
"I only made one copy"
"And then sent it into the world like the f***ing ebola virus"
~1:08 https://www.google.ca/url?sa=t&source=web&rct=j&url=https://m.youtube.com/watch%3Fv%3DMIzPVGn8Xes&ved=0ahUKEwitlL2b4c3TAhVNVWMKHUJ1BGgQo7QBCBwwAA&usg=AFQjCNEL-REAjwHAC1aMVY7W4YoBVRnHvQ

A: I'm not sure if Malcolm Gladwell borrowed the concept or originated it. But in his book the Tipping Point [published in 2000], he compared something reaching a tipping point as being spread like a virus. If he didn't originate the term, he was likely responsible for make it "go viral" and increase it's common usage.

A: I used the concept and the term viral and went viral in and about my novel Triangulation, which I wrote in 1988 and was published in January of 1990.  It is features an epidemiologist working on HIV who is also the victim of a practical joke that gets out of control and "infects" much of the city of Baltimore.  Jack Stephens


text:
Q: Find maximum value or upper bound of $|z_{1}-z_{2}|^2+|z_{2}-z_{3}|^2+|z_{3}-z_{1}|^2$ If $|z_{1}|=2,|z_{2}|=3,|z_{3}|=4$,then find maximum value of $|z_{1}-z_{2}|^2+|z_{2}-z_{3}|^2+|z_{3}-z_{1}|^2$.
My attempt:I considered 3 circles having centre origin and radii as $2,3,4$. Then I tried invoking the triangle inequality $|z_{1}-z_{2}|\leq|z_{1}|+|z_{2}|$ where equality occurs if origin,$z_{1},z_{2}$ are collinear with origin lying between $z_{1}$ and $z_{2}$. This means that $z_{1}$ and $z_{2}$ lie lie on a common diameter with origin lying between $z_{1}$ and $z_{2}$ and thus maximum value of $|z_{1}-z_{2}|$ will be $2+3=5$.
If I apply the same reasoning to $|z_{2}-z_{3}|$, I get $3+4=7$.
So now I have
$|z_{1}-z_{2}|^2+|z_{2}-z_{3}|^2+|z_{3}-z_{1}|^2$.
$\leq 5^2+7^2+|z_{3}-z_{1}|^2$.
Not able to proceed from here bcoz if I apply the same logic it will put $z_{1}$ and $z_{3}$ on different sides of origin due to which $z_{1}$ and $z_{2}$ will lie on same side of origin wich is in contradiction to the very first assumption that origin,$z_{1},z_{2}$ are collinear with origin lying between $z_{1}$ and $z_{2}$.


text:
Q: Merge collection operations Look at the code below:
val a = List(1,2,3,4,5)
a.filter(_ >= 3).map(_ * 9).drop(1).take(2)

My understanding is that it this iterates through the list once for each operation, generating code similar to this:
for(i <- a) {
    // filter
}
for (i <- afiltered) {
   // map
}
for (i <- afilteredandmapped) {
   // drop
}
..etc

Is there anyway to combine these operations, having chaining operations that only iterates once through the list? Generating such as below:
for (i <- a) {
    // filter
    // map
    // drop
    // take
}

A: Scala 2.8 collections introduced the notion of a Views, which are a lazy counterpart to the strict collections. It allows you to avoid the intermediate allocation of collections when applying multiple transformations on them.
You use them via calling .view on the collection, and when you want to materialize them you can do it via .force or toList/.toSeq:
val result = a
              .view
              .filter(_ >= 3)
              .map(_ * 9)
              .drop(1)
              .take(2)
              .force

A: Scala collections are eagerly evaluated. The simplest and most reliable way to prevent creation of intermediate collections is to apply the transformations to an iterator instead of to the collection itself:
val a = List(1,2,3,4,5)
a.filter(_ >= 3).map(_ * 9).drop(1).take(2)

Creates 3 intermediate lists in addition to the result
val a = List(1,2,3,4,5)
a.iterator.filter(_ >= 3).map(_ * 9).drop(1).take(2).toList

Creates only the result list.
This is very similar to the solution by Yuval Itzachow. But views are a bit more complex since they attempt to preserve the type of the collection (there is a corresponding view for each collection), so the iterator approach is preferable if you don't mind stating what you want the result to be toList vs. force.

A: You can combine the filter and map in a collect
val a = List(1,2,3,4,5)
a.collect {case x if x >= 3 => x * 9}.drop(1).take(2)

if you want the drop and take to be lazy, you'll need views, iterators or streams. A stream version, since other answers cover iterators and views;
val xs = a.toStream
xs.filter{x=>println("filtering " + x); x >= 3}
  .map{x=>println("mapping " + x); x * 9}
  .drop(1)
  .take(2)
  .toList
//> filtering 1
//| filtering 2
//| filtering 3
//| mapping 3
//| filtering 4
//| mapping 4
//| filtering 5
//| mapping5
//| res1: List[Int] = List(36, 45)

A: For Comprehension are made for these cases where the operations are combined on your behalf and an efficient code is generated for you.
(for (x <- a if x >= 3 ) yield (x * 9)).drop(1).take(2)

In fact, for comprehension is translated to the combination of withFilter and map/flatmap.
The withFilter was specifically designed when working with chains of methods to enable lazy evaluation. A filter takes a collection and produce a new collection on the spot. However, withFilter does nothing and passes the data unfiltered through to the next operation. Hence if the next operation is a map the result is realized and the whole filter + map combination is evaluated together.


text:
Q: Getting "InternalServerError" while using Mongo with Node js I am new to Node js programming. Trying to write a simple user create using.. code along with the stack track is given below. Appreciate any help as to what is causing this..
users-add.mjs:
'use strict';

const util = require('util');
const restify = require('restify-clients');
console.log("starting...");
var client = restify.createJsonClient({url: 'http://localhost:'+process.env.PORT,  version: '*'});

console.log("starting...2  ");
client.basicAuth('them', 'D4ED43C0-8BD6-4FE2-B358-7C0E230D11EF');
client.post('/create-user', { username: "me", password: "w0rd", provider: "local",
  familyName: "GUD", givenName: "RG", middleName: "Ud", emails: [], photos: []},
  (err, req, res, obj) => {
  console.log("starting...4  ");
    if(err) {
      console.log("starting...5");
      console.error(err.stack);
    }
    else {
      console.log("starting...6");
      console.log('Created ' + util.inspect(obj));
    }
});
console.log("starting...3  ");

Here is the error I'm getting.. Surprisingly the server side code is able to insert the record into MongoDB, and yet I get this error..
InternalServerError: {}
    at Object.createHttpErr (/Users/raviguduru/node-web-dev/chapter8/users/node_modules/restify-clients/lib/helpers/errors.js:91:26)
    at ClientRequest.onResponse (/Users/raviguduru/node-web-dev/chapter8/users/node_modules/restify-clients/lib/HttpClient.js:309:26)
    at Object.onceWrapper (events.js:300:26)
    at ClientRequest.emit (events.js:210:5)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:583:27)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:115:17)
    at Socket.socketOnData (_http_client.js:456:22)
    at Socket.emit (events.js:210:5)
    at addChunk (_stream_readable.js:309:12)
    at readableAddChunk (_stream_readable.js:290:11)

Pls help.

A: This problem is solved now.. The internal server error comes when we have MongoDBClient calls not wrapped in try/catch blocks. After I included try/catch blocks, they went away.


text:
Q: MS Excel - count number of different days for a given month and year il a list of dates In MS Excel, I've a list of different dates in a column
I'd like to count the number of different days (day month year) in the list for a given year and month
I'd like to have a formula and not using a pivot table
Sample

I found a partial solution
=sumprod(1/count.if(A1:A4;A1:A5))
=sumprod(1/count.if(A6:A17;A6:A17))
But here I've to define the start and end of the month in the selection it doesn't work for the whole column (A:A) or when months are mixed

A: This Array Formula will work:
=COUNT(IF(MONTH(A1:A100)=2,IF(YEAR(A1:A100)=2016,1,0)))

make sure to press Ctrl + Shift + Enter when exiting cell edit mode.

A: Use this simple formula and change the range for your application :
=SUM(IF(FREQUENCY(A2:A10;A2:A10)>0,1;1;0))

*

*The frequency will count how many time a single date occurs

*the IF will change the frequency into 1 each frequency

*The SUM will sum all your IFs and count how many different date you have

Hope it answered your question,
if you need more info : office has some info about it


text:
Q: Collate three or more consecutive terms in a column with bash I ask help to solve a problem I tried to figure out myself with no success. Shortly, I need to process very large tabular data files with structure:
14       R
16       I
21       B
22       C
23       Q
24       E
33       R
34       L
41       K
62       F
63       F
64       M
88       B

and so on... What I trying to do on these sorted ascending data is to collate items in the second column corresponding to chunks of three or more consecutive terms in the first column. So, the expected output from the above data should be:
21-24    BCQE
82-64    FFM

The piece of code I ended up so far is:
prev=0
val=$(prev + 1)
while read -r n a ; do
    if [[ ${n} == ${val} ]]
        t="$( "$a" + ( "$(a - 1)" ) )"  ; then
        echo "$t"
    fi
    prev=$n
done < table

But does not work.

A: Using awk:
$ awk 'function out() { if (start != "") { if (start == prev) printf("%s\t%s\n", prev, string); else printf("%s-%s\t%s\n", start, prev, string) } } $1 != prev + 1 { out(); start = $1; string = "" } { prev = $1; string = string $2 } END { out() }' file
14      R
16      I
21-24   BCQE
33-34   RL
41      K
62-64   FFM
88      B

The awk program:
function out() {
    if (start != "") {
        if (start == prev)
            printf("%s\t%s\n", prev, string)
        else
            printf("%s-%s\t%s\n", start, prev, string)
    }
}

$1 != prev + 1 { out(); start = $1; string = "" }

{ prev = $1; string = string $2 }

END { out() }

This program keeps track of the previous number from the 1st column in prev, and the concatenation of the 2nd column in string.  When the previous 1st column is one less than the current 1st column, all that happens is that prev and string are updated.
When there's a "gap" in the numbering, out() is called to output the collected data together with the interval recorded.  The function is also called at the end of the input.
A word-for-word equivalent thing for an sh shell:
out () {
    if [ -n "$start" ]; then
        if [ "$start" = "$prev" ]; then
            printf '%s\t%s\n' "$prev" "$string"
        else
            printf '%s-%s\t%s\n' "$start" "$prev" "$string"
        fi
    fi
}

while read -r num str; do
    if [ "$num" -ne "$(( prev + 1 ))" ]; then
        out
        start=$num
        string=""
    fi

    prev=$num
    string=$string$str
done <file

out

I just noticed this would combine even when there's only two lines following each other numerically.  I might correct this later, but I'll leave it here for now.

A: An awk solution:
awk '{if(p+1==$1){c+=1}else{ if(c>1){printf "%s-%s %s\n", b, p, s;} c=0;s=""}} c==1{b=p} {p=$1;s=s$2}' file

This time a bit more readable with explanations:
awk '{
  if(p+1==$1){
    c+=1 # increment the counter if the value is consecutive
  } else {
    if(c>1){
      # print the begin and end values with the concatenated string
      printf "%s-%s %s\n", b, p, s;
    }
    c=0 # reset the counter
    s="" # reset the string to print
  }
}
c==1{b=p} # set the begin value
{p=$1;s=s$2} # set the previous variable and the string for the next loop
' file

Tested with GNU awk and mawk

A: As noted elsewhere, bash is probably not the best tool for the job, it's probably easier to do this in Perl or awk. Even so:
#! /bin/bash

print() {
# "${array[*]}" joins the elements with the first characters of IFS as separator
# so we set IFS to the empty string so that the elements are simply concatenated
    local IFS=
    if (( end - start > 1 ))    # more than two consecutive numbers, concatenate
    then
        printf "%s-%s\t%s\n" "$start" "$end" "${chars[*]}"
    elif (( start == end ))                     # single number, nothing special
    then
        printf "%s\t%s\n" "$start" "${chars[0]}"
    elif (( end - start == 1 ))      # two consecutive numbers, print separately
    then
        printf "%s\t%s\n" "$start" "${chars[0]}" "$end" "${chars[1]}"
    fi
}

# An initial read
read -r n a
chars=( "$a" )
start=$n
end=$n

while read -r n a
do
    if (( n - end == 1 ))  # consecutive numbers, store for printing
    then
        chars+=( "$a" )
        end=$n
        continue           # move to next line
    fi
    print                  # Break in numbers, print stored set
    chars=( "$a" )         # reset variables
    start=$n
    end=$n
done

print                      # print last set

If you don't want the other rows, you can remove the elif blocks in the print function.
Example output:
14  R
16  I
21-24   BCQE
33  R
34  L
41  K
62-64   FFM
88  B


text:
Q: Is there a Tangent Vector that will Trace the Position Vector? My calculus book featured several graphing problems that involved drawing the position vector and the tangent vector at a certain point on the graph of a vector equation.  Trying to trace several of these in my head, I realized that it seems like the tangent vector will trace the position vector at (at least) one point.
Is this always true (true at all), and how would one find such such a point?

A: The tangent vector, based at the position vector, will point in the direction in which the curve is progressing. If it actually points along the path that the position vector traces out (that is the curve in question) then the curve is a line. Or, at a minimum, is is locally close to a line. Generally, the curve does not follow the tangent line. In fact, the tendency of the curve to lifts off that line is measured by the curvature. Then the tendency of the curve to lift of the plane which contains the "osculating" circle (infinitesimal plane of motion) is measured by non-trivial torsion.
You should read on the Frenet Frame (T,N,B). It will reveal all these mysteries and much more.


text:
Q: Start X in Debian Wheezy I have been trying for several hours to get to the desktop in Wheezy (amd64 and i386) on Virtualbox but when I execute: startx i just get a slightly different looking prompt.
Do I have to do something before I can access X?
Contents of /var/log/installer/syslog : http://pastebin.com/5ZwpbFxR
service gdm3 start
service gdm start
service kde start

All result in unrecognized service error messages

A: Try apt-get install task-gnome-desktop. From your logs, the DM/DE was not installed, although Desktop task was selected. This is probably a bug.
Is there any reason you are using testing version of Debian? That's why it's called testing -- because nothing is quite working yet the way it should.


text:
Q: Counter/Timer ICs? EDIT: Just to be clear this is not intended to be a "shopping" question. I am looking for the right technique to construct a very fast counter.
=====
I am looking for a counter/timer IC with the following capabilities:

*

*> 10MHz max count rate

*≥ 32 bit depth (preferably >40 bit)

*preferably, a built-in preset or compare function

I will use it to count a succession of events, and give an interrupt when the count reaches a specified value. The interrupt has to occur very fast, before the next event (so less than 100ns), which is why I'm using discrete logic instead of a microcontroller.
Right now I am prototyping with 4-bit counters like the 74LVC161. However I end up having to cascade at least 8 of them, which approaches their propagation delay limits (I calculate a max frequency of 11MHz).
Is there a better solution to this problem? I am willing to try using a CPLD/FPGA to make a huge synchronous counter, but I have no experience and don't know how many gates/logic units are required. What is the best approach?

A: A fast processor (e.g. Cortex M3 @ 64MHz) has a ~16ns clock cycle and will respond to an interrupt well within 100ns. Much faster if it has nothing else to do and you just run a 'look at counter value' loop.
(You probably need to combine a SW counter as well as a hardware one to have more then 32 bits)
For a very fast >40 bit counter you can use an FPGA.
As to how much code/gates you need depends on what action you want to perform. My guess is even the smallest one will suffice.
You will need to learn an HDL language like Verilog and go through the learning curve with the tool set. The tool will also tell you if the design fits in the chosen FPGA. But in the end, if your 'actions' are not too complex, it is very likely to be able to do what you want.

A: If I understand you correctly (counting pulses and emitting pulse at certain number of pulses) you actually don't need really fast micro controller (20 MHz should be enough) as most support external source for timers clock and chaining multiple timers with last timer outputting directly on output pin.
If this is your case your micro controller will only need to setup registers and enter infinite loop (or sleep), without any need for interrupt or code execution in micro controller.
On newer micro controllers you wont even need to more then one timer as they are usually 32 bit with addition of 16 bit prescaler, which is useful if you want to count numbers multiple of 2^N.

A: This can easily be done in an FPGA but I don't think you need anything that complex for what you describe.

*

*With the 4-bit ICs you already have, you have a terminal count (TC) output. If you feed that to the Count enable input (CEP) of the next counter you synchronize the counters.  It should be possible to design a very wide counter.

*To achieve a low and synchronized delay after the event, set the target value that you wish to compare with to the value that occurs 1 cycle before the event occurs, then delay the result 1 cycle with a flip-flop.
To make the comparator simple my own preference is to design a down-counter which is loaded with the target value on (p)reset. When the counter reaches 0 it is done. Optionally add a flip/flop to synchronize the comparator output, and either design the counter to test for 1, or subtract 1 from the preset.

*

*You can do something similar with the ICs you have. Just choose the preset/load value as ( Max. Counter Value - target period ) then the last TC output will be active for one cycle when you have finished the count.

Just to digress a bit, a shift register is often considered one of the fastest counters you can make since there are no comparators or adders. However, since you need one latch (or flip-flop) per counter value, this is not what you want for a >= 32 bit counter.

A: Even a small FPGA will do this with ease. You can get an eval board for Xilinx, Lattice etc. and have at it. Pick and HDL (VHDL and Verilog are the popular ones), and you should be able to download sufficient tools for this project at no cost.
Some CPLDs might be able to do it too, but with an FPGA you probably won't have to worry about resources because you'll not be using much of the available resources.
The combination of an FPGA and processor will solve many problems where one or the other is a poor fit.