text:
Q: c++ qt qabstracttablemodel subclass chrashes when underlying qmap is updated i am having great trouble with the update of a custom qabstracttablemodel.
i want to have a tableview that shows the prices of several stocks. i get the prices from a local server i control. this setup is for testing purposes. the pricing information is received in a worker thread.
i have subclassed the qabstracttablemodel in the following way:
PriceModel.h:
class PriceModel : public QAbstractTableModel {
    Q_OBJECT
public:
    PriceModel( QObject* parent = 0 );

    void setPriceMap( const QMap<QString, ITick*> &curTickMap );
    int rowCount( const QModelIndex &parent ) const;
    int columnCount( const QModelIndex &parent ) const;
    QVariant data( const QModelIndex &index, int role ) const;
    QVariant headerData( int section, Qt::Orientation orientation, int role ) const;
private:
    QMap<QString, ITick*> currentTicks;
    QString stockAt( int offset ) const;
};

PriceModel.cpp
#include "PriceModel.h"

PriceModel::PriceModel( QObject* parent ) : QAbstractTableModel( parent ) {
}

int PriceModel::rowCount( const QModelIndex& parent ) const {
    return this->currentTicks.count();
}

int PriceModel::columnCount( const QModelIndex& parent ) const {
    return 4;
}

QString PriceModel::stockAt( int offset ) const {
    return ( currentTicks.begin() + offset ).key();
}

QVariant PriceModel::data( const QModelIndex& index, int role ) const {
    if ( !index.isValid() ) {
        return QVariant();
    }
    if ( role == Qt::TextAlignmentRole ) {
        return int( Qt::AlignRight | Qt::AlignVCenter );
    } else if ( role == Qt::DisplayRole ) {
        QString stock = stockAt( index.row() );
        int i = index.column();
        switch ( i ) {
            case 0 : return currentTicks.value( instrument )->getTime().toString( "hh:mm:ss:zzz" );
            case 1 : return currentTicks.value( instrument )->getBid();
            case 2 : return currentTicks.value( instrument )->getAsk();
            case 3 : return currentTicks.value( instrument )->getBidVolume();
            case 4 : return currentTicks.value( instrument )->getAskVolume();
        }
    }
    return QVariant();
}

QVariant PriceModel::headerData( int section, Qt::Orientation orientation, int role )  const {
    if ( role != Qt::DisplayRole ) {
        return QVariant();
    }
    if ( orientation == Qt::Horizontal ) {
        switch ( section ) {
            case 0 : return QString( "Time" );
            case 1 : return QString( "Bid" );
            case 2 : return QString( "Ask" );
            case 3 : return QString( "Bid Volume" );
            case 4 : return QString( "Ask Volume" );
        }
    } else {
        return instrumentAt( section )->getCurrencyPairWithDelimiter();
    }
    return QVariant();
}

void PriceModel::setTickMap( const QMap<QString,ITick*>& curTickMap ) {
    beginResetModel();
    this->currentTicks = curTickMap;
    endResetModel();
}

the model populates the tableview when i call the setTickMap( qmap<...> ) method and all the different stocks are shown just as expected. ( initializing the data in my model is working fine )
the problem arises when i want to call the setTickMap( qmap<...> ) method again. the application crashes and i do not understand why nor do i get a significant error message - namely a segvault.
on a crash in debug configuration netbeans opens a tab named "Disassemlby" with following content:
QMetaObject::activate(QObject*, QMetaObject const*, int, void**)+50: add    %ebx,%r15d
QMetaObject::activate(QObject*, QMetaObject const*, int, void**)+85: testb $0x4,0x20(%rax)
QMetaObject::activate(QObject*, QMetaObject const*, int, void**)+89: jne 0x7ffff63f4df8 <QMetaObject::activate(QObject*, QMetaObject const*, int, void**)+536>
QMetaObject::activate(QObject*, QMetaObject const*, int, void**)+102: add    0x6c(%rsp),%ebx
QMetaObject::activate(QObject*, QMetaObject const*, int, void**)+118: mov    %ebx,0x2c(%rsp)
QMetaObject::activate(QObject*, QMetaObject const*, int, void**)+106: movq   $0x0,0x40(%rsp)
QMetaObject::activate(QObject*, QMetaObject const*, int, void**)+95: mov    0x31c19a(%rip),%rdx        # 0x7ffff6710de0
QMetaObject::activate(QObject*, QMetaObject const*, int, void**)+115: mov    (%rdx),%rax
QMetaObject::activate(QObject*, QMetaObject const*, int, void**)+122: test   %rax,%rax
QMetaObject::activate(QObject*, QMetaObject const*, int, void**)+125: je     0x7ffff63f4c72 <QMetaObject::activate(QObject*, QMetaObject const*, int, void**)+146>
QMetaObject::activate(QObject*, QMetaObject const*, int, void**)+127: lea    0x40(%rsp),%rdx
QMetaObject::activate(QObject*, QMetaObject const*, int, void**)+132: test   %r13,%r13
QMetaObject::activate(QObject*, QMetaObject const*, int, void**)+135: mov    %ebx,%esi
QMetaObject::activate(QObject*, QMetaObject const*, int, void**)+137: mov    %r12,%rdi
QMetaObject::activate(QObject*, QMetaObject const*, int, void**)+140: cmovne %r13,%rdx
QMetaObject::activate(QObject*, QMetaObject const*, int, void**)+144: callq  *%rax

i sandwiched the map assignment in the beginResetModel() methods but that does not seem to work as i just get a crashing application. odly enough this works at the first call of the setter method. this makes me assume that it is a quite stupid mistake. i think as the first call works fine we can rule out that it has something to do with inter-thread-communication problems.
this model is not supposed to be edited by the user through the GUI and i am aware that i could have used the tablewidget to just display the data but i am not sure if there is going to be another view that will share this models information. the map with the current prices is not going to be very big ( 25 items tops ) so i am not uncomfortable to reset the model on every new price coming in.
thanks in advance and i hope someone can help me with this
micropor

A: Considering that you are displaying real time tickdata I'd recommend approaching the data storage.  Since you are only displaying 5 items from the tick you might want to consider something other then a QMap may be arrays since your universe might be fairly standardized during the trading day.
Also I would have to assume that the code is multi-threaded and the curTickMap may change during the setTickMap as it is likely that you are not doing the model reset on every tick.
And as webclectic pointed out the code you have posted is unlikely to compile.

A: Wow my stupidity knows no bounds...
I fixed the problem and it had nothing to do with the tickmodel itself. The codesamples provided work just fine. I was apparently just too stupid to make sure the correct modelpointer is used.
This is sufficient:
void PriceModel::setTickMap( const QMap<QString,ITick*>& curTickMap ) {
    this->currentTicks = curTickMap;
    reset();
}


text:
Q: Selecting Dimension goes to column label instead of row in Excel ( SSAS ) selecting a dimension attribute for SSAS  excel  is going to column label instead of row label on pivot table . It used to work correct before i added an new attribute to the dimension.  Can someone tell me what property should i change to default it to row label?

A: Open the Dimension in BIDS. In the Dimension properties, change Type to something other than Time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Issue extracting "mentions" from Twitter data using regex I am trying to extract the mentions in a Tweet from Twitter i.e. @Google or @Apple.
This is my code so far to extract the mentions from a column and then create another column with the mentions.
df_bdtu['mentions'] = df_bdtu['tweet_text'].str.findall('(?:^|\s)[@ @]{1}([^\s#<>[\]|{}]+)')

It works mostly but I am facing some issues with some edge cases for example take this Tweet:
Check out @Dreams_n_Songs and give them a follow! I can't recommend their hoodies enough!Shop now  …

The mentions stored in the mentions column below which is incorrect as it includes the emoji for some reason.
['Dreams_n_Songs', '…']

Another issue is when there is a . before the mentions such as this example:
.@ChelseaFC, @FCBayern, @VfL_Wolfsburg and more are among the latest names to be confirmed at -…

The mentions that are produced do not include the first mention.
[FCBayern,, VfL_Wolfsburg]

How would I fix the regex for this?

A: You can use
[@@]([^][\s#<>|{}]+)

See the regex demo. So, remove (?:\s|^) that requires either start of string or a whitespace at the start of a match, and you need to remove a literal space from the [@ @] character class.
In Pandas code, you can use it like this:
df_bdtu['mentions'] = df_bdtu['tweet_text'].str.findall(r'[@@]([^][\s#<>|{}]+)')

Mind the r'...' raw string literal notation.


text:
Q: Any suggestions on Infopath form library and form template deployment in SharePoint2010 I need to deploy a Infopath form library with custom form template to SharePoint2010 ,once we save the form to the form library it will kick off a custom workflow(very similar to the built-in approval workflow).I woulk like to know any recommendations or gotha for deployment and subsequent uprade for form template or form library in the future.

A: One thing you might want to consider for future form upgrades is using Content Types for you form revisions.  When you publish a revised form template, your existing forms will top working if fields are removed from it, for example.  However, publishing your templates as new content types will allow the older templates to live on when people open an older form.


text:
Q: An object with the same key already exists in the ObjectStateManager I have a scenario that could not find the solution for it and need some help
How can I achieve this,
I'd like to get current record for the client modify it and instead of update I'd like to add the new record to table for historical change information
    client c = new client();
    using (DBEntities db = new DBEntities())
    {
        // get current records in the client table for client
        IQueryable<client> co = from p in db.client where p.CUS_NUMBER == scd.cus_number && p.isCurrent == true select p;

        c = co.First();

        //update email and and address
        c.EMAIL = Helper.CleanInput("mymail@mm.com");
        c.ADDRESS = Helper.CleanInput("123 Sheppard");

        //instead of updating current record I'd like to add new record to the table to keep historical changes
        db.AddToclient(c);
        db.SaveChanges();
        //I get error that
        //An object with the same key already exists in the ObjectStateManager.
        //The existing object is in the Modified state. An object can only be added to
        //the ObjectStateManager again if it is in the added state.

Complete error

An object with the same key already exists in the ObjectStateManager. The existing object is in the Modified state. An object can only be added to the ObjectStateManager again if it is in the added state.

A: remove this code   db.AddToclient(c); ,rest all is fine,You are already accessing the object by its reference so no need to add it again.It'll get modified when you call savechanges()
or use cloning if you want to add new object c = co.First().Clone();

A: The reason db.AddToclient(c); gives the error is because this object is being tracked by the object context, by possibly being in the database.
The best way to accomplish what you are trying to do is something like the following:
var newClient = new client()
{
    EMAIL = Helper.CleanInput("mymail@mm.com"),
    ADDRESS = Helper.CleanInput("123 Sheppard"),
};

db.AddToclient(newClient);
db.SaveChanges();

A: It's look like you are adding same row to database and error is coming due to  addition of same row again having same primary key which DB will not allow.
Try to add new row and make another table that keeps Historical information of old row and a reference as foreign key. You can add a boolean field that keep information regarding deletion let It is IsDeleted.
Hope It will Help
Thanks

A: In Entity Framework, all objects retrieved from database by default are tracked by ObjectContext instance. Entity Framework internally maps all objects being tracked by his Key. This pattern is called Identity Map. This means that there will be only one instance of an entity per key. So, you don't need to call Add again, since the entity is already on EF map. You just need call SaveChanges to persist modified entities.
In your case you are:
1 - Creating a new instance of EF ObjectContext;
2 - Retrieving entities in your LINQ query;
3 - Changing values of properties of the retrieved entity;
4 - Adding again to the ObjContext; //error!
5 - Calling SaveChanges()
Step 4 is not necessary because the ObjectContext already knows about the retrieved objects.


text:
Q: Why does Gulp.js throw a Bus Error: 10 with gulp.watch? I keep getting a Bus error: 10 with gulp.watch() after a watched file changes.
Why does the Bus error happen with a valid gulpfile?
Here is my gulpfile:
var gulp = require('gulp');
var minifycss = require('gulp-minify-css');

gulp.task('css', function() {
  return gulp.src('css/*.css')
    .pipe(minifycss())
    .pipe(gulp.dest('css/min'));
});

gulp.task('default', function() {
  gulp.watch('css/*.css', ['css']);
});

A: I also was getting this error, then realized I had a circular dependency in my sass imports.

A: I solved my problem from information in a similar question on Stack Overflow, GruntJS "bus error grunt watch".
There was a common issue with OS X Mavericks, and Node.js versions < v0.10.21. I was running v0.10.20.
I upgraded node, and now gulp.watch() is working fine.


text:
Q: Mapping from "int" to corresponding permutation value? I ran across this question this morning.
Basically that question is about data which has to create permutations for 6 values; each one ranging from 1 to 38.
So, first permutation would be
1 1 1 1 1 1      [ permutation 1 ]
1 1 1 1 1 2      [ permutation 2 ]
1 1 1 1 1 3...   [ permutation 3 ]

to end much later with
38 38 38 38 38 38 [ permutation 38^^6 ]

The output is simply created by 6 nested loops, each counting from 1 to 38; and within the inner-most loop, you print the 6 loop counters.
Now I am wondering about the math behind that; and out of curiosity: what would be the "function" that

*

*computes the "permutation index", given a any permutation 1 2 3 4 5 6

*Probably more interesting: that takes an "index", such as 102382; and tells me the corresponding permutation output

Any idea anybody?

A: It works exactly like a change of base (binar, octal or hex).
The first one question simply:
 1*38^6 + 2*38^5 + 3*38^4 + 4*38^3 +...+6*38^0
The second one reversed:
102382 mod 38... recursively
UPDATE
Let us assume we want change 10 to base 2:
10/2=5 remainder(modulus)  **0**
5/2=2 remainder           **1**
2/2=1 remainder           **0**
1/2=0 remainder           **1**

backwards is  1010
general gave a M to change in base B, just divide M by B ,  and the remainder are going to be the digit in the new base


text:
Q: How to use kubernetes service account with golang? Actually, I use kubernetes service accounts mostly with NodeJS, and this works fine, but I have this one service made in Go and I can't seem to make it work with service accounts (I know that the service account is correctly configured because I tested it with a pod).
I'm using this lib https://github.com/aws/aws-sdk-go
Up till now I tried this:
  sess := session.Must(session.NewSession())

  creds := stscreds.NewCredentials(sess, os.Getenv("AWS_ROLE_ARN"))

  svc := s3.New(sess, &aws.Config{Credentials: creds})

And also this (just in case):
  region := os.Getenv("AMAZON_REGION")
  sess := session.Must(session.NewSession(&aws.Config{Region: &region}))

  svc := s3.New(sess)

for the first case I got the following error:
AccessDenied: User: arn:aws:sts::xxxxxxxx:assumed-role/staging-worker-node/i-0xxxxxxxxx is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::xxxxxxxx:role/EKSServiceAccount-app

and for the second case, I got a generic permission error.
I read the docs and tried a few things more (that may not be relevant here), but I can't see to make it work, maybe because I don't have much experience with golang.

A: There are a few things you can try to get your Go service to work with service accounts on Kubernetes:
Verify that your Go service is properly configured to use the Kubernetes service account. This can be done by checking that the service account is correctly mounted as a volume in the pod definition and that the service is able to read the credentials from the volume.
Make sure that the AWS SDK for Go you are using (https://github.com/aws/aws-sdk-go) is configured to use the correct credentials. The SDK supports several methods for providing credentials, including environment variables, shared credentials file, and IAM roles.
You can try using the k8s.io/client-go library instead of the AWS SDK for Go, this will help you to use the Kubernetes service account to authenticate with the Kubernetes API and obtain the required credentials for the AWS SDK.
If you are using the Kubernetes service account to authenticate with an external service such as AWS, you may also need to configure an IAM role that allows the service account to access the necessary resources.
Double check that your Go service is correctly using the Kubernetes service account token and is passing it along as an authentication token to the AWS SDK.
You can also try to use the k8s.io/client-go library to get the secret and use it in your go code.


text:
Q: How do Wordpress Plugins Update Themselves? I am quite curious how people go about updating wordpress plugins. I have seen in the past a link to click on the dashboard to update a plugin. What goes on behinds the scenes?

A: It just downloads the latest package from the wordpress.org or the developers site and extracts it into the existing folder, which is why you should not edit plugin files because your work will be erased if you ever update.


text:
Q: Center USA cities on iOS app Based on a city name, like San Diego, we need to center map on that city in the iOS application.
We thought on using top left coordinates and botton right coordinates for each city, however this cannot be automated.
Another solution was taking the center of the city based on data from Google Maps, however we need to define a zoom for each
city that must depend on it's boundaries.
What approaches can you think? How can we define the zoom for the second approach?
Thanks

A: Have you tried using the viewport JSON output of the Google Geocoding API? It contains the northeast and southwest coordinates that you can pass into fitBounds.


text:
Q: Get First line in Summernote i can't get the first line of text using Summernote WYSIWYG Editor, i try using this code but not work. Always return all lines.
var t = $('.editor').code();
tmp = t.split("<br>");
var firstLine = tmp[0];
console.log(firstLine)

how could you do this?
Thx.


text:
Q: Prove this sequence of recursively defined sets converges to the natural numbers Consider the sequence of sets $\{\phi_k\}_{k=0}^{\infty}$ recursively defined by the relation
$$\phi_k=\left\{ \frac{a_{k-1}-2^q}{3} \in\Bbb{N} : a_{k-1}\in\phi_{k-1},\  q\in\Bbb{N},\ 2^{q+1} \mid a_{k-1}\right\}$$
And we take $\phi_0=\{2^q: q\in\Bbb{N}\}$. I wish to prove that the sequence $\{\phi_k\}$ converges to $\Bbb{N}\setminus\{0\}$ in the sense that
$$\forall_{n\in\Bbb{N}\setminus\{0\}}\ \exists_{K}\text{ s.t. } \forall_{k\ge K} n\in\phi_k \ \ \ \text{ and }\ \ \ \ \phi_k\subseteq\Bbb{N}\setminus\{0\} $$
It's not terribly difficult to show that $\phi_0\subseteq\phi_1\subseteq\phi_2\subseteq\ldots\subseteq\phi_k$ (multiply the explicit equation for elements of $ \phi_k $ below by 3), so it suffices to show
$$\forall_{n\in\Bbb{N}\setminus\{0\}}\ \exists_{k}\text{ s.t. } n\in\phi_k$$
(note that $\phi_k\subseteq\Bbb{N}$ and does not contain $0$ by construction). As an example of how things proceed, one can show with a bit of direct calculation that $\phi_1=\left\{\frac{2^{q_0}-2^{q_1}}{3}\in\Bbb{N}: q_0>q_1\in\Bbb{N}\right\}$ consists of all natural numbers with representation in base 4 given by 111...1100...000 or 222...2200...000 where there may be any number of 1's,2's, or 0's in the string (so long as it is nonzero).
More explicitly, the elements of $\phi_k$ are precisely the set of integer solutions to the equation
$$3^k*x=2^{q_0}-3^0*2^{q_1}-3^1*2^{q_2}-...3^{k-1}*2^{q_{k}}$$
For some choice of $q_0>q_1>q_2...>q_{k}\ge 0$ (to see how the recursion relation falls out of this equation, consider the equation modulo $ 3^{k-1}$). For example, $10=2*4^1+2*4^0 = 22$ in base 4, so $10\in\phi_1$, and we can write $3^1*10=2^5-3^0*2^1$. Similarly, $21=111$ in base 4, and $3^1*21=2^6-3^0*2^0$
I'm not terribly familiar with results of set theory regarding treatment or convergence of recursive sequences, so I'd also appreciate any pointers in the way of applicable theorems.

EDIT 1:
I'll add updates that I feel are elucidating as I develop them. Advice and insights on progress are welcome.
The set $\phi_k$ is characterized by a base set $B_k$ of odd numbers such that
$$\phi_k=\left\{ 2^qb_k: b_k\in B_k, q\in \Bbb{N}\right\}$$
And the sets $B_k$ satisfy the recursion relation
$$B_k=\left\{\frac{2^qb_{k-1}-1}{3}\in\Bbb{N}:b_{k-1}\in B_{k-1}, q>0\in\Bbb{N}\right\}$$
The desired proof reduces to showing that the sequence $\{B_k\}$ converges (in the same sense as above) to the set of positive odd numbers, where $B_0=\{1\}$. This formulation is particularly useful in that we can immediately see how any $b_{k-1}\in B_{k-1}$ determines the elements of $B_k$:
If $b_{k-1} \not\equiv 0 \pmod3$ (otherwise, $b_{k-1}$ generates no elements in $B_k)$, it determines a sequence ${\{\psi_p(b_{k-1})\}_{p=0}^{\infty}}\subseteq B_k$ with
$$\psi_0=
\begin{cases}
\frac{2b_{k-1}-1}{3}, & b_{k-1} \equiv 2 \pmod3 \\
\frac{4b_{k-1}-1}{3}, & b_{k-1} \equiv 1 \pmod3 \\
\end{cases}$$
and satisfying the recurrence relation (to see where this comes from, see the recursion relation of $B_k$)
$$\psi_p=4\psi_{p-1}+1 $$
and thus $$\psi_p=4^p\psi_0+4^{p-1}+4^{p-2}+\ldots 4+1$$
and so $\psi_p$, in base 4, is the string $\psi_0$ concatenated with p 1's. Finally, we construct $B_k$ as
$$B_k=\mathop{\bigcup}_{b\in B_{k-1}} \{\psi_p(b)\}_{p=0}^{\infty}$$
where $\{\psi_p(b)\}=\emptyset$ if $b \equiv 0 \pmod3$.
We can immediately see from this (and that $\psi_0(1)=1$) that $B_1$ is the set of natural numbers with base 4 representation 111...111 where there are any nonzero number of 1's in the string, in agreement with the above conclusion.
With some direct calculation using the elements of $B_1$, one finds that $B_2$ is the set of natural numbers with base 4 representation 1301301...301301111...111 or 3203203...203203111...111, the strings 301 or 203 are repeated any number of times, and there are any number of 1's appended on to the end, and thus $\phi_2$ is the set of natural numbers that are $2^q$ times these elements of $B_2$.
Though the calculations seem more natural in base 4, the results are much more interesting in base 2. The elements of $B_1$ in base 2 are 101010...10101, while the elements of $B_2$ are 111000111000...11100011010101...0101 or 111000111000...1110001010101...0101 (the difference being the number of 1's between the switch from the 111000111000... repetition to the 01010101... repetition, either of which may occur any number of times). The entirety of $\phi_2$, then, is given by these numbers with any number of $0$s on the end.
As an example, $1110001101_2 = 909_{10}$, so $909\in\phi_2$, and $3^2*909=2^{13}-3^0*2^{3}-3^1*2^0$, so 909 is indeed a solution to the explicit equation for the elements of $\phi_2$.
(After some further investigation, the apparent symmetry of results in base 2 does not seem to generalize past $B_2$.)

EDIT 2:
To generalize the results of the previous edit on the form of $B_2$, we consider a sequence of elements of $B_{k-1}$, call it $\{\Psi_p\}_{p=0}^\infty\subseteq B_{k-1}$, that satisfies a recursion relation
$$\Psi_p=4^q\Psi_{p-1}+c \text{  for some  } q,c\in\Bbb{N}$$
and thus
$$\Psi_p=4^{jq}\Psi_{p-j}+c*(4^{(j-1)q}+4^{(j-2)q}+ \ldots +4^q+1) \text{ for } 0< j \leq p$$
We wish to consider how this might give rise to a sequence of elements in $B_k$. We evaluate
$$\psi_0(\Psi_p)=
\begin{cases}
\frac{2\Psi_p-1}{3}, & \Psi_p \equiv 2 \pmod3 \\
\frac{4\Psi_p-1}{3}, & \Psi_p \equiv 1 \pmod3 \\
\end{cases}=
\begin{cases}
\frac{2*[4^{3q}\Psi_{p-3}+c*(4^{2q}+4^q+1)]-1}{3}\\
\frac{4*[4^{3q}\Psi_{p-3}+c*(4^{2q}+4^q+1)]-1}{3}\\
\end{cases}=
\begin{cases}
\frac{4^{3q}*(2\Psi_{p-3}-1)+4^{3q}+2c*(4^{2q}+4^q+1)-1}{3}\\
\frac{4^{3q}*(4\Psi_{p-3}-1)+4^{3q}+4c*(4^{2q}+4^q+1)-1}{3}\\
\end{cases}\\=
\begin{cases}
4^{3q}\psi_0(\Psi_{p-3})+\frac{4^{3q}+2c*(4^{2q}+4^q+1)-1}{3}\\
4^{3q}\psi_0(\Psi_{p-3})+\frac{4^{3q}+4c*(4^{2q}+4^q+1)-1}{3}\\
\end{cases}$$
Note that we relate $\psi_0(\Psi_p) \text{ to } \psi_0(\Psi_{p-3})$ to ensure that the numerator in the result is divisible by 3. In addition, $\Psi_p \equiv \Psi_{p-3} \pmod 3$, so we may relate $\psi_0(\Psi_{p-3}) \text{ to } \psi_0(\Psi_{p-6})$ in the same way, and so on, and thus the above result establishes a recurrence relation for a sequence of elements of $B_k$. What's more, this relation is of the same form as that for $\{\Psi_p\}$, with $q\rightarrow 3q$ and a new $c$, so discussion of these sequences is relevant for all $\phi_k$. If $c\not\equiv0\pmod3$, then $\exists_p$ s.t. $\Psi_p\equiv1\pmod3$ AND $\exists_p$ s.t. $\Psi_p\equiv2\pmod3$, and so the sequence $\{\Psi_p\}$ in $B_{k-1}$ bifurcates into two distinct sequences in $B_{k}$. If $c\equiv0\pmod3$, then we have $\Psi_p\equiv\Psi_{p-1}\pmod3$, and $\{\Psi_p\}$ gives rise to a single sequence in $B_k$ (or none at all, if $\Psi_p\equiv0\pmod3$) with recurrence relation
$$ \psi_0(\Psi_p)=
\begin{cases}
4^q\psi_0(\Psi_{p-1})+\frac{4^q+2c-1}{3}, & \Psi_0 \equiv 2 \pmod3 \\
4^q\psi_0(\Psi_{p-1})+\frac{4^q+4c-1}{3}, & \Psi_0 \equiv 1 \pmod3 \\
\end{cases}$$
Each element in these sequences in $B_k$ serves as an initial value for another sequence $\{\psi_p(b)\}$ (as defined in Edit 1) for some $b\in B_{k-1}$.
To see the use of these results, consider the case of going from $B_1$ to $B_2$: the elements of $B_1$ are a sequence $\{\Psi_p\}$ with a relation defined by $q=1$ and $c=1$, so there are two sequences of elements of $B_2$; one with $q=3$ and $c=35_{10}=203_4$, and one with $q=3$ and $c=49_{10}=301_4$, as found previously.


text:
Q: Push notification for Android app with Sharepoint 2013 I need to write an Android 6+ App with push notification about activities/resources updated in Sharepoint 2013. Polling is not a viable option...
I would like to know if there is some kind of Sharepoint's service the handle push notification and the way to connect it to android apps or otherwise the best way to achieve this (Sharepoint that connect to CloudFire maybe?)... My app should be native.
Thank you very much indeed...


text:
Q: Android: SQLite Database in android for multiple users I've read that the best database to use is SQLite in android. I haven't done a lot of android development.
My goal is to create an app that has a database in which multiple users can access to. If user 1 and user 2 post content, they both store the content in a database which both users have access to that information. Can someone explain how this could be achieved or provide an example. I've searched SQLite but I'm afraid these are only local database (am I correct in saying this)?

A: If you want to have a database of that sort its is recommended to use MySQL database or something similar.Using some APIs you can connect to it.
There are lot of examples with MySQL and Php which you can make use of which i think would be the best in your case rather than SQLite .

A: Android sqlite db is a local database residing in the phone's memory. If you want to have a commonly synched DB for your users who are using your app from different phones, then you need to ideally have a cloud based database which is accessible to any authorised users of your app. You can consider using google app engine for hosting a cloud database and google cloud endpoints for accessing the data through apis.

A: Yes you are correct. Sqlite database is used just as local database. In this case you need web database. Like benilMathew said, you can use MySQL but you should definitely check this:

https://parse.com

No need to make server side code (in php etc.), easy to use API for Android (also for iOS, WinMobile...) and everything is well documented. I am using it and it satisfies all my requirements.

A: The best and most easiest option is to use LAMP. PHP can be used to access a MySQL database and you can use Web Services, like SOAP or even JSON, to consume the data contained in the database or interact with the MySQL instance. The advantage of using Web Services like this is that it is relatively simple to implement and use in comparison to using a Web Browser App in the Android App itself. Remember, the SQLite database within each user's Android device can be used to temporarily store data until it is ready to be uploaded to the remote MySQL database and in this way an SQLite database could still be quite useful in any Android/Mobile Application.
A tutorial is shown at this site: http://www.helloandroid.com/tutorials/connecting-mysql-database


text:
Q: Python - Create a new sublist between two elements in an ordered list Given two elements in an ordered list, I want to make a  new list consisting of everything between (and including) those elements.
The problem comes if the second point comes before the first point in the list.
right is my existing sorted list of objects. rt is the beginning boundary and rb is the end boundary.
new_right = right[right.index(rt): right.index(rb) + 1]
This snippet works except in the case
right = [a, rb, c, rt, d, e]
where I get [rt, d, e] instead of the wrapped [rt, d, e, a, rb]
Is there a way to do this without creating a complicated method? Some other people's problems were solved by list comprehension. Looking into it, I was able to come up with
begin = right.index(rt)
end = right.index(rb)
if end > begin:
    new_right = right[begin: end + 1]
else:
    new_right = [right[i % r_len] for i in range(begin, r_len + end + 1)]

Which looks pretty ugly to me, but it seems to hold up to my tests.
Is there a better way to do this?
EDIT:
There were two working solutions to this.
rbegin = right.index(rt)
rend = right.index(rb)
if rend >= rbegin:
    new_right = right[rbegin: rend + 1]
else:
    new_right = [right[i % r_len] for i in range(rbegin, r_len + rend + 1)]

Which is obscenely complicated compared to:
if rend > rbegin:
    new_right = right[rbegin: rend + 1]
else:
    new_right = right[rbegin:] + right[:rend + 1]

A: Would simply flipping the slice match your tests like so:
begin = right.index(rt)
end = right.index(rb)
if end > begin:
    new_right = right[begin: end + 1]
else:
    new_right = right[end: begin + 1]

A: Maybe this?
new_right = right[begin: end + 1] if end > begin else right[begin:] + right[:end + 1]

A: You can add the trailing and leading slices instead of using a comprehension.  Using your code structure:
begin = right.index(rt)
end = right.index(rb)
if end > begin:
    new_right = right[begin: end + 1]
else:
    new_right = right[begin:] + right[:end + 1]


text:
Q: Routing problems to certain domains with PPTPD VPN setup We've been struggling with some kind of network/routing issue with a PPTPD based VPN where the clients can't access certain internet domains/ips through the VPN. As an example, the user can browse hxxp://google.com, but not hxxp://microsoft.com.
The setup is as follows:
Client (same problem on Windows and Android, haven't tested others) (ip: x.x.x.x) -> Internet -> (y.y.y.y) dd-wrt router (192.168.1.1) -> Ubuntu Server 10.10 running PPTPD (192.168.1.125).
eirik@woserv:~$ cat /etc/pptpd.conf | grep -v '#'
option /etc/ppp/pptpd-options
logwtmp
localip 192.168.1.125
remoteip 192.168.1.230-240

eirik@woserv:~$ cat /etc/ppp/pptpd-options | grep -v '#'
name pptpd
refuse-pap
refuse-chap
refuse-mschap
require-mschap-v2
require-mppe-128
ms-dns 192.168.1.1
proxyarp
nodefaultroute
debug
lock
auth
nobsdcomp
noipx
mtu 1490
mru 1490

iptable rules (in /etc/rc.local) and verified is loaded using iptables -L
#!/bin/sh

# Flush all rules

iptables -F

iptables -X

iptables -Z

# Allow all VPN stuff

iptables -A INPUT -p tcp --dport 1723 -j ACCEPT

iptables -A INPUT -p 47 -j ACCEPT

iptables -A OUTPUT -p tcp --sport 1723 -j ACCEPT

iptables -A OUTPUT -p 47 -j ACCEPT

iptables -A FORWARD -i ppp+ -o eth0 -s 192.168.1.0/24 -m state --state NEW -j ACCEPT

iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT

iptables -A POSTROUTING -t nat -o eth0 -j MASQUERADE

exit 0

We've enabled PPTP, IPSEC and L2TP passthrough on the dd-wrt router (under Security -> VPN Passthrough). Also, we've port forwarded 1723 and 47 to 192.168.1.125.
The VPN connection in Windows is setup with "Use default gateway on remote network" on IPv4 and uses MS-CHAP v2. If the clients access hxxp://www.whatismyip.com/ the correct VPN ip is reported (y.y.y.y) and not their normal internet IP, x.x.x.x.
So far we've identified the following problem domains:
microsoft.com
support.microsoft.com
no.yahoo.com
answers.yahoo.com
nrk.no
imgur.com

(And while working on describing this problem, I discovered that I could not load http://w.pastebin.ca/pb-g.gz.js when I tried to access hxxp://pastebin.ca via the VPN)
If the clients try to open these web pages when they are using the VPN, they get a timeout (Google Chrome Dev Tools under Networking says "Pending" for the requests until they timeout). Sometimes Chrome says the error is "Error 101 (net::ERR_CONNECTION_RESET): The connection was reset.". Other services (besides http/https 80/443 also fail).
Most other sites work, like hxxp://google.com and hxxp://bing.com. The problems are consistent among many different windows and android clients from various locations. There are no proxies involved. Disabling Windows firewall and any anti-virus software does nothing.
tracert from the clients gives various results for the different domains, but they seem somewhat consistent between no VPN and VPN, here are some examples.
If I fire up lynx http://microsoft.com directly on the Linux server running PPTPD it loads up fine. Same with the other sites ...
Any ideas?
(sorry for the jsfiddle with the tracert links, could not post that many links here as a new user on ServerFault)

A: Since you changed the default MTU, this may be the cause.  Try adding the following rule to your firewall, adjust as necessary:
iptables -I FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS  --clamp-mss-to-pmtu

EDIT: changed the rule to insert itself as first in the chain.

A: Multiple Issues

*

*/etc/ppp/pptpd-options
nodefaultroute

But Windows is setup with "Use default gateway on remote network". The above option should be removed.

*Same network on both side of NAT
iptables -A POSTROUTING -t nat -o eth0 -j MASQUERADE

PPTP server has LAN IP of 192.168.1.125, PPTP clients are assigned 192.168.1.230-240, same 192.168.1.0/24 on both side of the NAT. Not sure it really works, partially works, but looks problematic.
Additionally, PPTP server is already inside the LAN, DD-WRT router is doing out going NAT already. NAT on PPTP server is not necessary. Remove the above rule.

*Check /proc/sys/net/ipv4/ip_forward
cat /proc/sys/net/ipv4/ip_forward should return 1. If not, add following as 2nd lines of rc.local
echo 1 > /proc/sys/net/ipv4/ip_forward

*Check PPTP Client Network
Check PPTP client local/LAN IP not using 192.168.1.0/24. They have to be changed or VPN routing may not work.


text:
Q: Android - Publish/Test apk with expansion files - How it does work? I'm still a Android student and I have develop an application which has more than 100Mb and therefore I need to use expansion files.
I have read thousands of documents, but I am very confused.
There are many mp3 files I need to compact in that kind of 'expansion file', in order to upload only apk code and not the entire app+mp3 files.
I think if I generate a file '.obb' with all those mp3 ones, I would go over 50MB requrired by Google Play.
I know this '.obb' file must be in scard/Android/obb folder of my device, too.
Currently my code get the 'int' resource from a mp3 file to manipulate it is like this:

intMyResource=R.raw.name_of_my_music_file;

But, currently, as I told, the path of the files is 'R.raw'.
My question: How is the best method to replace

intMyResource=R.raw.name_of_my_music_file;

to the actual path/name where my '.obb' file is?
Thank you all.
Mauro

A: You should create expansion file with this zip command:
zip -r -9 -n ".mp3" main-expansion-file.zip *

Use -n option is critical to don't compress media files, because if media files are compressed you cannot use it in your android application.
Change name zip to 'main.VERSIONCODE.YOURPACKAGENAME.obb and copy  this .obb file in scard/Android/obb folder device.
Read files of zip expansion files is easy work with Google ZipFile Library (available in pathAndroidSDK/extras/google/play_apk_expansion/zip_file)
Replace R.raw.name_music_file by call of this method:
public static AssetFileDescriptor getFileDescriptor(Context ctx, String path) {
        AssetFileDescriptor descriptor = null;
        try {
            ZipResourceFile zip = APKExpansionSupport.getAPKExpansionZipFile(ctx, 1, -1);
            descriptor = zip.getAssetFileDescriptor(path);
        } catch (IOException e) {
            Log.e("APKExpansionSupport", "ERROR: " + e.getMessage(), e);
            e.printStackTrace();
        }
        return descriptor;
    }

Example code to play music from expansion file with MediaPlayer:
    AssetFileDescriptor descriptor = null;
            try {
                descriptor = getFileDescriptor(this, "name_music_file.mp3"));
                MediaPlayer reproductor = new MediaPlayer();
                reproductor.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
                reproductor.setOnCompletionListener(this);
                reproductor.prepare();
                reproductor.start();

            } catch (Exception e) {
                Log.e("Play mp3", "ERROR: " + e.getMessage(), e);
            } finally {
                if (descriptor != null)
                    try{descriptor.close();} catch (IOException e) {}
            }

Hope this help you!


text:
Q: I want to put db tables in same database. How? My iOS program download [A.sqlite3] file in server.
My iOS have already [b.sqlite3] file in local
I want to Join A.sqlite3's table with b.sqlite3's table in local iOS.
But, because of table's database is different, I have problem joining tables.
How do I put tables in same db?

A: You can use the sqlite ATTACH syntax. Assuming you had a table A in database A.sqlite3 and a table B in database B.sqlite3, from the command line, the steps would be:
$ sqlite3 A.sqlite3
sqlite> ATTACH 'B.sqlite3' AS dbB;
sqlite> SELECT a.*,dbB.b.* FROM a,dbB.b WHERE (a.id = dbB.b.id);

The ATTACH gives the additional database file a prefix which you can use in your sql statements.
On an iPhone app, you open your A.sqlite3 database as before, then pass the sql ATTACH command to the sqlite library like you pass your other sql commands, and remember to give the full pathname as the first argument to the ATTACH.


text:
Q: Unable to add reference to BouncyCastle after NuGet import I am trying to link to the BouncyCastle library in my ASP.NET MVC 5 application.  I right clicked on my project, and went to the NuGet Packages.  I installed BouncyCastle and I now see it in my references as BouncyCastle.Crypto.  I want to use this package, so just like anything else I am trying:
using Org.BouncyCastle.Crypto

When I do this, I get an error that The type or namespace 'Org' could not be found.  If I try using BouncyCastle.Crypto I get the same error, except this time for the type or namespace BouncyCastle.
If I grep for BouncyCastle, I can see it in my packages:
packages/BouncyCastle.1.7.0/lib/Net40-Client/crypto.xml:        <member name="T:Org.BouncyCastle.OpenSsl.PemReader">

One thing that I notice, however, is that it comes up as Net40-Client.  Is this an issue?  Was it built using a client profile?  If so, it seems similar to this issue.  However, I am not sure how to actually change this profile if this is the case, since it is a pre-built library.

A: Are you sure you are using the using in the same project where the DLL has been added as a reference?
Edit 1: I just tried that and it is working for me. Please verify if you are using it in relevant project.

A: I was having the same issue.  Eventually I noticed that BouncyCastle.Crypto.dll (which was in the correct project's bin folder) wanted me to right click on it and select "Include in Project".  This was the fix I needed to succssfully reference the bouncy castle classes =^.^=

A: right click the project click unload then reload.
you should then see BouncyCastle in the references folder in the project.


text:
Q: How to export all filtered records kartik-v/yii2-export in GridView? I am using the extension kartik-v / yii2-export, (Apparently it is the only one there is to export). I have the following inconvenience:
I only exported the first page of the dataprovider.
I would like to filter the data in the grid, and export the filtered data, even if they have several pages. Is this possible?

A: If i am correct it is a default feature in kartik export :
use kartik\export\ExportMenu;
$gridColumns = [
    ['class' => 'yii\grid\SerialColumn'],
    'id',
    'name',
    'color',
    'publish_date',
    'status',
    ['class' => 'yii\grid\ActionColumn'],
];

// Renders a export dropdown menu
echo ExportMenu::widget([
    'dataProvider' => $dataProvider,
    'columns' => $gridColumns
]);

// You can choose to render your own GridView separately
echo \kartik\grid\GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => $gridColumns
]);

Data provider for the export and grid should be same it will work

A: In controller create new dataProvider with different name
 $dataProvider = new SqlDataProvider([
           'sql' => $data,
            'pagination' => [
                'pageSize' => 20,
            ],
            // 'sort' => [
            //     'attributes' => [
            //           ......
            //     ],
            // ],
        ]);
        $dataExport = new SqlDataProvider([
           'sql' => $data,
            'pagination' => [
                'pageSize' => $count_your_data,
            ],
            // 'sort' => [
            //     'attributes' => [
            //           ......
            //     ],
            // ],
        ]);

And in view change this
// Renders a export dropdown menu
echo ExportMenu::widget([
    'dataProvider' => $dataExport,
    'columns' => $gridColumns
]);

A: I Solved this; by setting the property  'batchSize'  from the Export Widget, the same value the property 'pageSize' from DataProvider. It Works !


text:
Q: How to reuse a .Net assembly from a pure C application I have a legacy application written in C , and i would like to gradually move some code to c#. But before being able to rewrite everything i will need to have just few components writen in c# first that are going to be used from C.

A: I assume your C# class is a static class. You need to create an interop layer in C++/CLI before you can use it in pure C. Create a C++/CLI class to wrap your C# class. Once that is done use the export function to export the specific C functions. C++/CLI will manage the interop on your behalf. The rule of thumb is if you class/function has any CLI it WILL BE CLI. So your extern functions should only return native datatypes.
extern "C" __declspec( dllexport ) int MyFunc(long parm1);

Here is an article to help you get started. It converts C++ to C# but the process is reversed in your case. CodeProject Unfortunately there is no convenient reverse PInvoke for pure C.
Unfortunately I have never gone from C# to C. It sounds like an interesting project. Good luck!
Ok If you have not figured it out yet i have a quick sample for you.
C# CSLibrary.Math.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSLibrary
{
    static public class Math
    {
        static public int Add(int a, int b)
        {
            int c = a + b;
            return c;
        }
    }
}

Cpp/C++ Project CPPCLibrary.h (Compiled with C++/CLI Option with project dependencies)
#pragma once

using namespace System;

extern "C" __declspec( dllexport ) int MathAdd(int a, int b)
{
    return CSLibrary::Math::Add(a, b);
}

C Project CTest.c (Compiled as C Code)
#include "stdafx.h"
#pragma comment(lib, "../Debug/CPPCLILibrary.lib")

extern __declspec( dllimport ) int MathAdd(int a, int b);

int _tmain(int argc, _TCHAR* argv[])
{
    int answer = MathAdd(10, 32);
    _tprintf(_T("%d\n"), answer);
    return 0;
}

All files are in the same solution but different projects. I have confirmed this has worked. I hope this helps anyone who comes across it.
Cheers!

A: If the code is pure C, you might be able to put it into a visual C++ assembly project without too much difficulty. From there, you would have access to a regular .net api.


text:
Q: GD commands display raw image text instead of an image Hey i was trying to learn the GD library and i can't get my code to work, it displays raw image text instead of the actual PNG i want to display. I have Png Support enabled in the GD section by the way.
Code is very simple:
<?php
$picture = imagecreatefrompng("test.png");
imagepng($picture);
?>
but the result comes down to something like this:
�PNG  IHDR���.�b    pHYs���+ IDATx� etc.

A: You have to tell the Browser, that it is image data.
Add
header("Content-type:image/png");

So it should be:
<?php
    header("Content-type:image/png");
    $picture = imagecreatefrompng("test.png");
    imagepng($picture);
?>

For more information and other image type you can look here PHP, display image with Header()


text:
Q: Choosing the sign of determinant when taking a square root
Calculate the determinant $$\det(A)=\begin{vmatrix}a&b&c&d\\ \:\:\:-b&a&d&-c\\ \:\:\:-c&-d&a&b\\ \:\:\:-d&c&-b&a\end{vmatrix}$$

I found that $$\det(A)\det(A^T)=\det(A)^2=(a^2+b^2+c^2+d^2)^4$$
From this we get
$$\det(A) = \pm (a^2+b^2+c^2+d^2)^2$$
Now, how to choose the sign? Any help is appreciated.

A: Here is one quick way: Use the standard cofactor formula for the determinant. Expand only what you need. What is the sign of $a^4$?

A: Evaluate it at $A=I$ gives you the sign.


text:
Q: git cherry-pick and rebase fails I have the following commits in the history of my topic branch:
(git lola shortcut described here)
jochen@autolaptop4:~/projects/infoodle$ git lola
*   0c61616 (refs/stash) WIP on receipt_preview_sprint_to_finish: 3678770 progress
|\
| * 332dc8a index on receipt_preview_sprint_to_finish: 3678770 progress
|/
* 3678770 (HEAD -> receipt_preview_sprint_to_finish, origin/receipt_preview, receipt_preview, integration) progress
*   ed2ca95 Merge branch 'receipt_preview' of bitbucket.org:richinnz/infoodle-web into receipt_preview
|\
| * 0743777 preview stuff
| * 03a2279 be able to ahndle both rebatable and non-rebatable
| * 1ff3d6c better sample number for preview of receipts
| * 0a0f3ed handle missing {tax receipt} replacement
| * 0ce35c9 remove language files, should not be in git
| * 5cc2b61 identify first key of transaction detail correctly to get data out of transaction record
| * def1132 sort out preview spinner
| * 5622f85 typo when pasting code from master
* | 30ef79c (origin/receipt_search, receipt_search) merge transactiontranslator back into receiptconfigurator
* | 367685c progress transferring sql into configurator
* |   84c71b1 Merge remote-tracking branch 'origin/receipt_search' into receipt_search
|\ \
| * | 149e5f0 Progress on receipt screen search/ sort/ detail
* | | e927458 processing receiptstodo query into receiptList class, process SQL where parts into ReceiptConfigurator
* | | 80c7c06 list loaded from ajax complete
* | | 99b6ed8 only use global.min when not in debug mode
* | | bf15181 rename
* | | 43fd17a re-indent
* | | 57e38a0 re-indent
* | | c4e7588 save work
| |/
|/|
* | 867c918 remove confusing commented out stuff
* | fec8c04 text tweak in phpdoc
|/
* 75a78ce fix mismatch of function parameter typing after merge

Basically I have accidentally merged origin/receipt_search and we had a change of plan in regards to getting this feature branch finished.
I want to start now with commit 75a78ce (at bottom) and apply
0743777 preview stuff
03a2279 be able to ahndle both rebatable and non-rebatable
1ff3d6c better sample number for preview of receipts
0a0f3ed handle missing {tax receipt} replacement
0ce35c9 remove language files, should not be in git
5cc2b61 identify first key of transaction detail correctly to get data out of transaction record
def1132 sort out preview spinner
867c918 remove confusing commented out stuff
fec8c04 text tweak in phpdoc

in reverse order onto a new branch.
1) I have tried git cherry-pick:
git checkout 75a78ce
git checkout -b receipt_preview_sprint_to_finish
git cherry-pick fec8c04..0743777

This fails when applying the second commit:
On branch receipt_preview_sprint_to_finish
You are currently cherry-picking commit 867c918.
  (fix conflicts and run "git cherry-pick --continue")
  (use "git cherry-pick --abort" to cancel the cherry-pick operation)

Unmerged paths:
  (use "git add <file>..." to mark resolution)

        both modified:   code/classes/class.receipting.php

I don't understand why there would be a conflict.
2) Then I tried rebase:
git branch -f integration 0743777
git rebase --onto receipt_preview_sprint_to_finish fec8c04~1 integration

    First, rewinding head to replay your work on top of it...
    Fast-forwarded integration to receipt_preview_sprint_to_finish.
    jochen@autolaptop4:~/projects/infoodle$ git log
    commit 3678770d92b2fd00797d2cda2875c090fc701a1e
    Author: Jochen Daum <jd@automatem.co.nz>
    Date:   Thu Mar 23 10:48:42 2017 +1300

        progress

    commit ed2ca95096690c4c419ef491ad65c3c5020120e5
    Merge: 30ef79c 0743777
    Author: Jochen Daum <jd@automatem.co.nz>
    Date:   Thu Mar 23 08:26:23 2017 +1300

        Merge branch 'receipt_preview' of bitbucket.org:richinnz/infoodle-web into receipt_preview

        # Conflicts:
        #   code/ajax/accountcode_functions.php
        #   code/ajax/subinclude/person.php
        #   code/styles/ennz/admin_donationreceipts.tpl.php
        #   code/styles/ennz/header.tpl

But these 2 commits I specifically did not want.
What am I doing wrong?

A: The problem with the git cherry-pick is simple:

I want to start now with commit 75a78ce (at bottom) and apply [commits starting with, and including, fec8c04, so I ran]
git cherry-pick fec8c04..0743777

The notation X..Y in Git means "all commits reachable from Y, excluding all commits reachable from X".  This excludes X itself.  It's reminiscent of half-open intervals in maths, where [3..5] means 3, 4, and 5 but (3,5] means 4 and 5 only, or [3, 5) means 3 and 4 only.  (These are written other ways, such as ]3, 5] in some notations, and commits are not really linear this way—we're actually doing set subtraction, rather than intervals—but the idea here is to act as a reminder that X..Y never includes commit X itself.)
Hence, what you need is:
git cherry-pick 75a78ce..0743777

or:
git cherry-pick fec8c04^..0743777

to include commit fec8c04.
Worthy of note as well is that this is not quite right:

git checkout 75a78ce
git branch -b receipt_preview_sprint_to_finish

The second command should be git checkout -b, not git branch -b.  But git branch -b would give you an error so I guess you actually used git checkout -b. :-)
(The git rebase method is not going to work well as it will select far too many commits to copy into a linear sequence.)


text:
Q: How to add hyperlink in column field of dash Datatable I wanted to add Hyperlink to the first column CR-number, so it should be clickable, on clicking it will redirect to the link.
below is the code snippet of it.
html.Div(
        className = "row",
        children = [
            dash_table.DataTable(
                id='datatable-cr-list',
                columns=[
                    {"name": i, "id": i} for i in cr_columns_to_display
                ],
                filter_action = "native",
                sort_action = "native",
                style_cell_conditional=[
                        {'if': {'column_id': 'Title'},
                        'textAlign': 'left',
                        'overflow': 'hidden',
                        'textOverflow': 'ellipsis',
                        'width': '60%',
                        'whiteSpace': 'normal'
                        }
                ],
                style_data_conditional=[
                    {
                        'if': {'row_index': 'odd'},
                        'backgroundColor': 'rgb(230, 242, 255)'
                    }
                ],
                style_header={
                    'backgroundColor': 'rgb(153, 204, 255)',
                    'fontWeight': 'bold'
                },
                export_format="csv",
            )
        ]
    ),

here is the image of the table, where I wanted to add a hyperlink to the first column. Do we have any feature to add a hyperlink to the dash?

A: I fix with adding hyperlink to first column with below method and add "presentation": 'markdown' in the Layout for Table field
def f(row):
    return "[{0}](<link of redirection>{0})".format(row["CR_Number"])
if open_cr_count > 0:
    df_fa_direct_open["CR_Number"] = df_fa_direct_open.apply(f, axis=1)


text:
Q: Is there a way to get the order of attributes/fields in an instance? For the purposes of a generic-style TableModel it would be nice to be able to get the attributes of an object. It is apparently possible to get the field names and values using reflection. However, is there a way to get these according to the order of declaration? If not, do you know of a workaround that could be used in the above example? I've been thinking along the lines of initializing the TableModel with an ordered list.

A: Have you considered to create an annotation for the fields? The annotation could describe the column index of the field, and the column name.

A: Create out own annotation:
@interface Order {
  int value();
}

and then annotate your fields
@Order(1) String field1;
@Order(2) String field2;
...

Then you can use reflection
Field[] flds = MyClass.getFields();
flds[0].getAnnotation(Order.class)
etc
...


text:
Q: White font with black border in XAML as the title says, I would like to have a black font with a white border
in my TextBox.
How could it be achieved?
Cheers.

A: It's possible to convert text into geometry objects with advanced formatting like outlines and fills for individual letters - you can find out more about how to do that here.
Having said that, I'm not sure that this is possible inside a TextBox. It may be for read-only text (TextBlock) only.
Edit
This blog post shows some advanced font rendering techniques inside a TextBox. It may be handy for you.

A: What I always do for that is set the font color to white and set a DropShadow effect on the text.
Next, play around with depth, angle (set to 0 or something) and blur and you should be able to get what you want.

A: Check out Blacklight controls @ http://blacklight.codeplex.com/. In particular look at the sample on http://mightymeaty.members.winisp.net/blacklight.silverlight/ | Visual Controls | TEXT | Stroke Text Block (Alpha).

A: A full class and example using Geometries:
http://blogs.msdn.com/b/wpfsdk/archive/2006/12/24/using-text-as-a-decorative-graphic.aspx


text:
Q: Replacing File Server Running Server 2003 with Server 2008 - Permissions Copy? I currently have a file and print server running Windows Server 2003.
I would like to replace the OS hard drive with a new one, running server 2008 R2.
Currently, all the files are stored on two other hard drives on the same server.
When I replace the current OS hard drive, I assume that all the current permissions on all the folders will be lost.
Is there a way to preserve those sharing/security permissions, so I can "seamlessly" upgrade the server?

A: Robocopy has the ability to preserve ACLs during file transfer.
robocopy source dest /MIR

A: Is this file server a domain member, or is it a standalone server in a workgroup? NTFS file permissions use SIDs (security identifiers) to reference users and groups.
In a workgroup environment, the SIDs are defined on the fileserver itself, as part of the local users and groups configured on that server. If you are wiping out the boot disk and installing a new operating system entirely, then the permissions will reference SIDs that no longer exist, so you'll need to reset all of the permissions. But if you're just doing an upgrade, that won't affect the local users and groups so the permissions will remain intact.
In a domain environment, the SIDs for domain users are defined on the domain controllers. So even if you wipe out the boot drive and reinstall a new operating system, the files on your data drive are still using the same SIDs, and they are still defined by your domain controllers, so the permissions are totally perserved.


text:
Q: How to check if a value exists in an array and get the next value? I have an Array let x = ["", "comp", "myval", "view", "1"].
I want to check first whether or not the value "comp" exists in the array, and if it does then get the very next value. Any idea?

A:   let x = ["", "comp", "myval", "view", "1"];
  if (x.indexOf(yourVal) >= 0) {

   let nextValue = x[x.indexOf(yourVal) + 1];

  } else {
   // doesn't exist.
  }

Note : you won't get next values if your values is last value of array.

A: You can do like this
var x=["","comp","myval","view","1"],
    l=-1!==x.indexOf("comp")?x[x.indexOf("comp")+1]:"no value";
console.log(l);

A: You could use a function and return undefined if no next value.

function getNext(value, array) {
    var p = array.indexOf(value) + 1;
    if (p) {
        return array[p];
    }
}

let x = ["", "comp", "myval", "view", "1"]

console.log(getNext('comp', x));
console.log(getNext('foo', x));

A: let x = ["", "comp", "myval", "view", "1"]

let nextIndex = x.indexOf('comp') > -1 ? x.indexOf('comp') + 1 : -1;

basically, check if "comp" exists in x, if true i.e > -1 then it returns indexOf("comp") + 1  which is the next item else returns -1

A: An alternate can be to have first element as undefined and then fetch index of search value and return array[index + 1].
Since first element is undefined, for any non matching case, index would return -1, which will fetch first element in array.
This approach involves creating new array and using if(index) return array[index] would be better, still this is just an alternate approach of how you can achieve this.

function getNext(value, array) {
  var a = [undefined].concat(array)
  var p = a.indexOf(value) + 1;
  return a[p];
}

let x = ["", "comp", "myval", "view", "1"]

console.log(getNext('comp', x));
console.log(getNext('foo', x));


text:
Q: Encrypted disk kernel warning - initramfs image won't boot After an upgrade to 14.10 on my netbook, I can only manage to boot with the old kernel remaining from the previous 14.04 installation.
For the most recent kernels, I get this warning when they are being updated (i.e. when update-initramfs is invoked:
WARNING: Option hash missing in crypttab for target sda5_crypt, assuming ripemd160.
         If this is wrong, this initramfs image will not boot.
         Please read /usr/share/doc/cryptsetup/README.initramfs.gz and add
         the correct hash option to your /etc/crytpttab.
cryptsetup: WARNING: target sda5_crypt uses a key file, skipped.

And indeed the kernel does not boot. Essentially, it drops to an initramfs shell after issuing this error:
ALERT!  /dev/mapper/ubuntu--vg-root does not exist.  Dropping to a shell!

What is strange is that /etc/crypttab looks exactly the same (save for the UUID) as in my main computer, where it boots without trouble. Also the old kernel on the netbook manages to boot using the same /etc/crypttab the other kernels are failing to boot with.
$ cat /etc/crypttab
sda5_crypt UUID=#long string here# none luks

Another thing I've noticed: when I boot in recovery mode from the old kernel, on issuing a sudo reboot, I also get this warning:
/scripts/local-top/cryptroot: line 1: can't open /dev/mapper/ubuntu--vg-root: no such file

Any ideas on how to bring back the 14.10 kernel to life?


text:
Q: How to refresh an activity when a child activity (theme:dialog) is closed? I have an activity A and when a user clicks on a button, a dialog appears(which is an Activity B with dialog theme), there he can click on a button and after that dialog disapper and user returns to the activity A . How can I refresh the activity A's UI so the users do not have to go back to the home and open again the activity A?
I appreciate any help that you can provide.

A: Use startActivityForResult() - setResult() - onActivityResult() pattern.

A: Have a look on the ActivityLifecycle:

When the activity A is showing up to the user again, the onResume() method is called. So do your updating stuff inside this method and your data is refreshed every time the activity is showing up again.


text:
Q: How to avoid loosing focus on click of anchor tag? I have an input type text element and anchor element, Now I don't want to loose focus on click of that anchor tag if the focus is already on input text element. I have tried following but it does not work.
HTML:
<input type = 'text' value='click here first' />
do nothing

jQuery code:
$('#nothing').bind('click', function(e){
    e.preventDefault();
})

Above does not work for me. Can somebody tell me what is missing here?

A: The anchor will always loose focus when clicking something else, the way to get around it is by resetting the focus to the input:
var active = null;

$('#nothing').on({
    mousedown: function() {
        active = document.activeElement;
    },
    mouseup: function() {
        if (active) active.focus();
    },
    click: function(e) {
        e.preventDefault();
    }
});

FIDDLE

A: I have faced similar problem try using 'mousedown' instead of click event.
Here is the DEMO
<input type = 'text' value='click here first' />
clicking this does not loose the focus from input field!

$('#nothing').bind('mousedown', function(e){
    e.preventDefault();
})


text:
Q: Whiptail Gauge: Variable in loop not being set Am new to bash and whiptail so excuse the ignorance.
When assigning a var in the for loop, the new value of 20 is never set when using a Whiptail dialog.  Any suggestions why ?
andy="10"
{
    for ((i = 0 ; i <= 100 ; i+=50)); do
        andy="20"
        echo $i
        sleep 1
    done
 } | whiptail --gauge "Please wait" 5 50 0
# }
echo "My val $andy

A: A command inside a pipeline (that is, a series of commands separated by |) is always executed in a subshell, which means that each command has its own variable environment. The same is true of the commands inside the compound command (…), but not the compound command {…}, which can normally be used for grouping without creating a subshell.
In bash or zsh, you can solve this problem using process substitution instead of a pipeline. For example:
andy="10"
for ((i=0 ; i <= 100 ; i+=50)); do
        andy="20"
        echo $i
        sleep 1
done > >(whiptail --gauge "Please wait" 6 50 0)
echo "My val $andy

>(whiptail ...) will cause a subshell to be created to execute whiptail; the entire expression will be substituted by the name of this subshell's standard input (in linux, it will be something like /dev/fd/63, but it could be a FIFO on other OSs). > >(...) causes standard output to be redirected to the subshell's standard input; the first > is just a normal stdout redirect.

A: The statements inside {} are not ordinarily executed in a sub-shell. However, when you add a pipe (|) to it, they seem to be executed in a sub-shell.
If you remove the pipe to whiptail, you will see the update value of andy.


text:
Q: Is there a way to defer firing jquery.ajax call to allow further modifying its settings by other functions? I'm constructing a jquery.ui widget, which needs to call a backend service via ajax. However, not all settings are available when invoking the $.post() in that particular widget, i.e. the post needs to be passed to other functions by the _trigger() signal, and use other cooperating widgets to complete all the settings, only then it can be sent to the backend.
It's something like this:
$.widget('widget1', {
   drilldown: function(){
       var pseudocode_variable = $.post('backend_service', _incomplete_settings, callback);
       this._trigger('request_drilldown', event, [pseudocode_variable]);
   },
   ...
});

$.widget('widget2', {...complete_ajaxsettings_here, then fire...});

I've looked up in the jquery documentation, but didn't get anywhere. Could someone more informed give a direction whether such idea is implementable? Thanks.


text:
Q: please guide me to solve? show
\begin{Vmatrix}
   1 & -(x_{1}+x_{2})&x_{1}x_{2}&0\\
   0 &1 &-(x_{1}+x_{2})&x_{1}x_{2}\\
   0&x_{1}+x_{2}-(y_{1}+y_{2})&y_{1}y_{2}-x_{1}x_{2} &0\\
   0 &1 &-(y_{1}+y_{2})&y_{1}y_{2}
\end{Vmatrix}
=$(x_{1}-y_{1})(x_{1}-y_{2})(x_{2}-y_{1})(x_{2}-y_{2})$

A: Develop along the first column  we obtain
$$\Delta=\begin{Vmatrix}
   \\
   1 &-(x_{1}+x_{2})&x_{1}x_{2}\\
   x_{1}+x_{2}-(y_{1}+y_{2})&y_{1}y_{2}-x_{1}x_{2} &0\\
   1 &-(y_{1}+y_{2})&y_{1}y_{2}
\end{Vmatrix}$$
If we don't want to do the calculus notice $\Delta=\Delta(x_1,x_2,y_1,y_2)$ is a polynomial of four variables and with leading coefficient $1$ and it vanishes if $x_i=y_j,\; i=1,2;\; j=1,2$, Can we conclude?


text:
Q: Audio file to text file python I want to convert an audio(ex: ".mp3") file to text file. I have tried different approaches like pyspeech and speech recognition, But i didn't get any answer. Is there any other way to do this..? Any help would be appreciated !

A: Did you try https://pypi.python.org/pypi/SpeechRecognition/ ? That sounds like exactly what you want.
I also found the CMU Sphinx project via this blog. It has Python bindings too (as mentioned in the article).
The other item I found was Google's Speech to Text API. You might want to check that out too. Here's a decent tutorial on this subject:

*

*http://codeabitwiser.com/2014/09/python-google-speech-api/

A: import speech_recognition as sr
print(sr.__version__)
r = sr.Recognizer()

file_audio = sr.AudioFile('file_audio.wav')

with file_audio as source:
   audio_text = r.record(source)

print(type(audio_text))
print(r.recognize_google(audio_text))

A: way 1: convet audio file to bytes (0,1) with https://github.com/jiaaro/pydub or by f = open("test.mp3", "rb") first16bytes = f.read(16)
way 2: audio to speech convertors.eg.-convert to english or other language with pip libraries like SpeechRecognition pydub. (but i think you don't asked for this)
way 3: convert mp3 to Json. If anyone did this, then please share.


text:
Q: Ошибка при попытке скомпилировать что-то с boost::stacktrace Решил попробовать boost::stacktrace и воспроизвёл простейший пример из документации boost. Использую qt-creator 4.8, Cmake 3.10, GCC 7.3, boost 1.69.0.
Код:
#include <boost/stacktrace.hpp>
#include <iostream>

void Foo() {
    std::cout << boost::stacktrace::stacktrace() << std::flush << std::endl;
}

int main() {
    Foo();
    return 0;
}

Cmake скрипт:
cmake_minimum_required(VERSION 3.10)
project(fast_test_3)
add_definitions(-DBUILD_TYPE_="${CMAKE_BUILD_TYPE}")
add_definitions(-DPROJECT_NAME_="${PROJECT_NAME}")

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

set(CMAKE_CXX_FLAGS                 "${CMAKE_CXX_FLAGS} -Wall -pthread ") #
set(CMAKE_CXX_FLAGS_DEBUG           "${CMAKE_CXX_FLAGS} -Wall -pthread -g -DDREAL_DEBUG -DDREAL_TRACE -fno-inline")
set(CMAKE_CXX_FLAGS_MINSIZEREL      "${CMAKE_CXX_FLAGS} -Wall -pthread -Os -DNDEBUG")
set(CMAKE_CXX_FLAGS_RELEASE         "${CMAKE_CXX_FLAGS} -Wall -pthread -O3 -DNDEBUG")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO  "${CMAKE_CXX_FLAGS} -Wall -pthread -O2 -g")

set (Boost_USE_STATIC_LIBS ON)
set (Boost_USE_MULTITHREADED OFF)
find_package(Boost REQUIRED system)
include_directories (SYSTEM ${Boost_INCLUDE_DIR})
link_directories(${Boost_LIBRARIES})

add_executable(${PROJECT_NAME} "main.cpp")

target_link_libraries(${PROJECT_NAME} ${Boost_LIBRARIES})

Во время компиляции компилятор выдаёт четыре ошибки:

*

*/.../main.cpp.o:-1: In function `boost::stacktrace::detail::to_string[abi:cxx11](boost::stacktrace::frame const*, unsigned long)':

*/.../main.cpp:-1: error: undefined reference to `dladdr'

*/.../main.cpp:-1: error: undefined reference to `dladdr'

*:-1: error: collect2: error: ld returned 1 exit status
На сколько я знаю boost::stacktrace это хэдеронли библиотека и я не могу понять в чём вообще заключается проблема?
UPD:
Вовремя дискусии возник вопрос, действительно ли эта библиотека хэдеронли? Предоставляю ссылку на место в документации где оговаривается этот момент.

A: Убив кучу времени, я решил эту проблему. В общем как оказалось для сборки чего-то с boost::stacktrace на GNU требуется библиотека DL (спасибо @VTT за подсказку). Но что бы CMake всё нормально собрал необходимо добавить в target_link_libraries переменную ${CMAKE_DL_LIBS} (при этом наличие или отсутствие флага компиляции -ldl не на что не влияет, не знаю почему). Конечный скрипт выглядит так:
cmake_minimum_required(VERSION 3.10)
project(fast_test_3)
add_definitions(-DBUILD_TYPE_="${CMAKE_BUILD_TYPE}")
add_definitions(-DPROJECT_NAME_="${PROJECT_NAME}")

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

set(CMAKE_CXX_FLAGS                 "${CMAKE_CXX_FLAGS} -Wall -pthread ") #
set(CMAKE_CXX_FLAGS_DEBUG           "${CMAKE_CXX_FLAGS} -Wall -pthread -g -DDREAL_DEBUG -DDREAL_TRACE -fno-inline")
set(CMAKE_CXX_FLAGS_MINSIZEREL      "${CMAKE_CXX_FLAGS} -Wall -pthread -Os -DNDEBUG")
set(CMAKE_CXX_FLAGS_RELEASE         "${CMAKE_CXX_FLAGS} -Wall -pthread -O3 -DNDEBUG")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO  "${CMAKE_CXX_FLAGS} -Wall -pthread -O2 -g")

set (Boost_USE_STATIC_LIBS ON)
set (Boost_USE_MULTITHREADED OFF)
find_package(Boost REQUIRED system)
include_directories (SYSTEM ${Boost_INCLUDE_DIR})
link_directories(${Boost_LIBRARIES})

add_executable(${PROJECT_NAME} "main.cpp")

target_link_libraries(${PROJECT_NAME} ${Boost_LIBRARIES} ${CMAKE_DL_LIBS})


text:
Q: Pattern matching checking for type of tuple I am trying to use Scala's pattern matching feature to check for the type of the first parameter, and to accept any arbitrary type for the second parameter- though I'm not sure syntactically how this works in Scala as I am fairly new, and I cannot find anything as to how tuples work with one another in Scala as it relates to pattern matching and case statements.
My initial attempt:
case foo => (eval(e1, e2), eval(e1, e2)) match
{
    case (S(e1), _) => (bar(e1, e2) + bar(e1, e2))
    case _ => ???
}

Wherein, this should, in this case, check that the first argument is a string, and accept the second to be whatever, and then do whatever bar wants.
Further, I have seen examples like so:
case (_: String, _: Int) => ???

however, I am unclear as to how you reference these parameters in your right hand statement.
What is the proper method of referencing these _ parameters in a statement?

A: You use : to enfore the type. Below the example. You can refer to any value using a variable and without explicitly declaring type.
Scala REPL
scala> :paste
// Entering paste mode (ctrl-D to finish)

("Java", 1) match {
  case (str: String, v) => println(s"value: $v")
  case _ => println("something")
}

// Exiting paste mode, now interpreting.

value: 1


text:
Q: generalize python script to run on all files in a directory I have the following python script:
with open('ein.csv', 'r') as istr:
    with open('aus.csv', 'w') as ostr:
        for line in istr:
            line = line.rstrip('\n') + ',1'
            print(line, file=ostr)

how could this be generalized to run on all the files in a directory and output a seperate file for each one?
maybe have a function like this:
for phyle in list_files(.):
    with open(phyle, 'r') as istr:
        with open('ausput_xyz.csv', 'w') as ostr:
            for line in istr:
                line = line.rstrip('\n') + ',1'
                print(line, file=ostr)

def list_files(path):
    # returns a list of names (with extension, without full path) of all files
    # in folder path
    files = []
    for name in os.listdir(path):
        if os.path.isfile(os.path.join(path, name)):
            files.append(name)
    return files

A: Just put the code in a function and call it:
def process(infilename):
    outfilename = os.path.splitext(infilename)[0] + "-out.csv"
    with open(infilename, 'r') as istr:
        with open(outfilename, 'w') as ostr:
            for line in istr:
                line = line.rstrip('\n') + ',1'
                print(line, file=ostr)

def process_files(path):
    for name in os.listdir(path):
        if os.path.isfile(os.path.join(path, name)):
            process(name)

In a directory with input files "abc.csv", "xyz.csv" this code will create output files named "abc-out.csv" and "xyz-out.csv".
Note that os.listdir(path) is called just once during the execution, so the list of files to process will not include the newly created output files.

A: First off, as a more pythonic way for dealing with csv files you better to use csv module and use with statement for opening the files which will close the file object automatically at the end of the block. And use os.walk() function to iterate over the files and directories of a specific path:
import csv
import os

for path_name, dirs, files in os.walk('relative_path'):
    for file_name in files:
        with open(file_name) as inp,open('{}.csv'.format(file_name),'wb') as out:
             spamwriter = csv.writer(out, delimiter=',')
             for line in inp:
                 spamwriter.writerow(line) # or line.split() with a specific delimiter

Note that if your script is not in a same path with your files directory you can add the path to the leading of your file name while you want to open them.
with open(path_name+'/'+file_name),...


text:
Q: Mac Terminal Strange Behaviour (no newline when hitting enter, no visible text ) I'm on Mac OS X 10.11.3 My terminal looks like this:
[Fabian@MacBook-Pro] >
[Fabian@MacBook-Pro] > pyspark
Python 2.7.11 (default, Jan 29 2016, 17:48:19)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
16/03/17 10:08:22 WARN NativeCodeLoader: Unable to load native-hadoop library     for your platform... using builtin-java classes where applicable
Welcome to

      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /__ / .__/\_,_/_/ /_/\_\   version 1.6.1
      /_/

Using Python version 2.7.11 (default, Jan 29 2016 17:48:19)
SparkContext available as sc, HiveContext available as sqlContext.
>>> print 'hello'
>>> hello

>>> quit()
>>> [Fabian@MacBook-Pro] > [Fabian@MacBook-Pro] > [Fabian@MacBook-Pro] > [Fabian@MacBook-Pro] > -bash:     printsf: command not found

in the first line I press enter, and as you see, the prompt starts at another line, then I launch pyspark, do something and quit, then when I return to the prompt I press enter and as you can see, the prompt doesn't appear in a newline! I actually type and nothing is printed to the screen, however the commands are executed as you can see
 -bash:     printsf: command not found

my .bash_profile (located in /Users/Fabian folder) looks like this
# Setting PATH for Python 3.4
# The orginal version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.4/bin:${PATH}"
export PATH
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export PYTHONPATH=$PYTHONPATH:/Users/Fabian/Library/Python

##
# Your previous /Users/Fabian/.bash_profile file was backed up as /Users/Fabian/.bash_profile.macports-saved_2016-02-07_at_11:26:24
##

# MacPorts Installer addition on 2016-02-07_at_11:26:24: adding an appropriate PATH variable for use with MacPorts.
export PATH="/opt/local/bin:/opt/local/sbin:$PATH"
# Finished adapting your PATH environment variable for use with MacPorts.

export JAVA_HOME=$(/usr/libexec/java_home)
export PATH=$PATH:/Users/Fabian/apache-maven-3.3.9/bin
export PS1="[\u@\h] > "
export PATH=$PATH:/Users/Fabian/spark-1.6.1-bin-hadoop2.6/bin

How Can I fix this behavior??
Thanks!

A: As noted in comments (and as described by OP), the expected newline after each message was lost.  That is because the application changed the terminal I/O modes dealing with carriage-return / line-feed, e.g.,

*

*pressing Enter (which is a carriage return) was not translated into a newline (actually a line-feed), and

*newlines sent from the computer were not translated into carriage return / line-feed.

However, on "any" keyboard, you can type a newline by pressing controlJ.  The usual fixes apply pressing controlJ first to get a prompt, and completing the command with pressing controlJ):

*

*stty sane (resets the terminal driver)

*reset (resets the terminal driver as well as asking the terminal to reset itself).

A: This can be caused by an escape character that when printed to the terminal causes it to go nuts.
It usually helps if you close this terminal window and open a new one. Maybe pyspark is using some escape codes (for color or design) and then forgets to revert its changes.
You can try running pyspark with a terminal type of dumb instead of xterm-256color. This can be done via the $TERM Environment Variable. Try doing echo $TERM before running pyspark.

A: I had the same problem with python 2.7.12 installed with macport. This might have been a coincidence, because I've tried many things, but "sudo port install py27-readline" fixed the problem for me.


text:
Q: Open full Image from gridview in new Activity I tried to make general gridview and categorical gridview , from categorical gridview try to open clicked image in new activity .
THE PROBLEM IS WHEN click item in categorical gridview it doesn't open the new Activity
second gridview "categorical ":
     holder.tv = (TextView) row.findViewById(R.id.textView1);
        holder.img = (ImageView) row.findViewById(R.id.imageView1);

        holder.tv.setText(Bresult[position]);
        holder.img.setImageResource(BimageId[position]);

        if (row == null) {
            row = new ImageView(Bcontext);
        }
        row.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Bcontext, BActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (position==0){
                    intent.putExtra("imageID", position);
                    Bcontext.startActivity(intent);
                }
                Toast.makeText(Bcontext, "You Clicked " + Bresult[position], Toast.LENGTH_LONG).show();

            }
        });

        return row;
    }
}

And this the New Activity should image appear there :
    Intent intent = getIntent();
    BCustomAdapter imageAdapter = new BirthCustomAdapter(this);
    Bundle bdl = getIntent().getExtras();
    int index = bdl.getInt("imageID");
    ImageView image = (ImageView) findViewById(R.id.img_view);
    image.setImageResource(index);
}

A:         Intent intent = new Intent(Bcontext, BActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (position==0){
            intent.putExtra("imageID", position);
            Bcontext.startActivity(intent);
        }

Your startActivity() is inside the if statement, so your activity will only be started if position == 0.
Perhaps you really meant this:
        Intent intent = new Intent(Bcontext, BActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (position==0){
            intent.putExtra("imageID", position);
        }
        Bcontext.startActivity(intent);


text:
Q: What is the purpose of creating aliases in JavaScript? What does this JavaScript statement do? I have seen a couple of JavaScript libraries that have this syntax at the beginning of the file. What does this statement mean, what is the value of getClass after this statement is run, and why is this needed? Also, what is the purpose of the semicolon at the beginning?
;(function (window) {
  // Convenience aliases.
  var getClass = {}.toString, isProperty, forEach, undef;

   // remaining function goes here
}

A:
what is the value of getClass after this statement is run,

The same as {}.toString.

and why is this needed?

It isn't. The comment says it is a convenience alias.

Also, what is the purpose of the semicolon at the beginning?

So that if the script is concatenated with another script, and the previous script fails to include a ; after its last statement, it won't cause an error.

A: In ECMAScript 5, objects have an internal [[Class]] property, which according to 8.6.2 can only be accessed through Object.prototype.toString:

The value of a [[Class]] internal property is used internally to
  distinguish different kinds of objects. Note that this specification
  does not provide any means for a program to access that value except
  through Object.prototype.toString (see 15.2.4.2).

And {}.toString is a shortcut to that Object.prototype.toString.
For example, getClass can be used to test if an object is an Arguments object:
getClass.call(obj) === "[object Arguments]"


text:
Q: HTML5 Canvas in Magento I am new to magento i want to know .In my project i want some customized product view in product view page.  But i am not getting any idea on this .Please let me know the possibility for using HTML5 canvas in magento 1.6.
Thanks in advance,

A: Yes it is possible, you can edit the template file catalog/product/view/media.phtml which is where the product image is.


text:
Q: ffmpeg null filter when configuring (no such filter 'eq') I configure ffmpeg to compile it an Android gcc (among others) like that:
./configure --disable-filters --enable-filter=atrim,trim,eq

And this is the preview:
Enabled filters:
aformat          anull            atrim            format           null             trim

Obviously the eq filter is missing and in it's place it's the null enabled filter. As expected the eq filter is also missing from the executable binary and if we try use the eq filter it will return:
 No such filter: 'eq', Error reinitializing filters!, Failed to inject frame into filter network:
 Invalid argument, Error while processing the decoded data for stream #0:0, Conversion failed!

Full configuration:
--prefix=/path/to/x86
--enable-static --disable-shared
--enable-small
--enable-cross-compile
--target-os=linux
--arch=x86
--sysroot=/path/to/sysroot
--cross-prefix=/path/to/i686-linux-android-
--enable-pic
--disable-ffplay
--disable-ffprobe
--disable-ffserver
--disable-doc
--disable-filters
--enable-filter=atrim,trim,eq
--disable-asm
--disable-debug
--extra-cflags=-I/path/to/usr/include -O3 -Wno-deprecated-declarations -fpie -pie -Wl,-z,relro,-z,now -march=i686 -m32 -mtune=intel -mssse3 -mfpmath=sse
--extra-ldflags=-L/path/to/usr/lib -fpie -pie

A: The eq filter requires FFmpeg to be compiled under the GPL license, so add --enable-gpl.


text:
Q: rails active record has_many custom query is it possible to have an active record has_many associations, but i have a specific condition.
class Team < AR
  has_many :matches, query: 'team1 == ID or team2 == ID'
end

class Match < AR
  attr_accessible :team1, :team2
end

A: Here's a potential solution:
class Team < AR
  def matches
    Match.where("team1 = ? or team2 = ?", id, id) # or: { team1: id, team2: id }
  end
end

A: You can use finder_sql but it will be deprecated in Rails 4 and I'm not sure if there's a new way to do this:
class Team < AR
  has_many :matches, finder_sql: proc { "SELECT * FROM matches WHERE (matches.team1 = #{id} or matches.team2 = #{id})" }
end

Another solution:
class Team < AR
  has_many :matches_as_team1, class_name: "Match", foreign_key: "team1"
  has_many :matches_as_team2, class_name: "Match", foreign_key: "team2"
  def matches
    matches_as_team1 | matches_as_team2
  end
end

In this solution, the result of Team#matches is an array, not a Relation, so you won't be able to do things like team.matches.limit(10).

A: I would prefer keeping your association as normal and apply query later on with where condition.
class Team < AR
  has_many :matches

  scope :team_details, lambda {|id1,id2| matches.where("team1 = ? OR team2 = ?",id1,id2)}
end

team (object of Team)
Then call
team.team_details(id1,id2)


text:
Q: Hop count - what will happen in this simple case Consider ABCD
router A wants to send to D
It keeps hop count 3
What will be the HOP COUNT when the packet reaches D
Will it be zero or one?

A: B will decrement it from 3 to 2, and C will decrement it from 2 to 1. Therefore it will be 1 when it reaches D.

A: D will forward it.  The node on the receiving end, say E, will drop it if it can't process it.

A: If I understand the question correctly, a ping is being sent from router A with a TTL of 3.  In that case it will not reach D. (I could be wrong, but it depends on how the router OS defines traversing)
a       b       c       d
3   2   2   1   1 not forwarded by c

If a were a PC then
a       b       c           d
3   3   3   2   2   1       1

edit - To determine how Router A defines "traversing" ping Router B from A with a TTL of 1.  My home routers do not correctly decrement the TTL so I can't test here.


text:
Q: Strange Message body bytes size for rabbitmq I'm using rabbitmq and facing some heap space problems on java client. Normally theses messages are quite small on size, but sometimes I fall in this situation that with only 2K messages the Message body bytes is over 8.8GB.  In my tests I already let this exactly same queue with 200K messages and the message body bytes is not bigger than 200MB.

another scenario, same queue same kind of message but totally different pattern

Anyone can help me understand what can makes this message get bigger than normal?


text:
Q: Volley POST request android I am not sure i should use which type of content to POST to the api because I am very new to this developing world.
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        button = (Button)findViewById(R.id.reg_btn_sign_up);
        btnCancel = (Button)findViewById(R.id.reg_button_cancel);
        Email = (EditText)findViewById(R.id.reg_email);
        Name = (EditText)findViewById(R.id.reg_name);
        Pass = (EditText)findViewById(R.id.reg_pass);
        ConPass = (EditText)findViewById(R.id.reg_confirm_pass);

    button.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            email = Email.getText().toString();
            name = Name.getText().toString();
            password = Pass.getText().toString();
            conPass = ConPass.getText().toString();

            JSONObject jsonBody = new JSONObject();
            try {
                jsonBody.put("username", email);
                jsonBody.put("password", password);
                jsonBody.put("name", name);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            final String mRequestBody = jsonBody.toString();

            StringRequest stringRequest = new StringRequest(Request.Method.POST, reg_url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONArray jsonArray = new JSONArray(response);
                        JSONObject jsonObject = jsonArray.getJSONObject(0);
                        String status = jsonObject.getString("status");
                        String result = jsonObject.getString("result");
                        builder.setTitle("Server Response...");
                        builder.setMessage(result);
                    } catch (JSONException e){
                            e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            })

            {
                @Override
                public byte[] getBody() throws AuthFailureError {

                    try {
                        return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                        return null;
                    }

                }

                @Override
                public String getBodyContentType() {
                    return "application/json; charset=utf-8";
                }
            };

            MySingleton.getmInstance(RegisterActivity.this).addRequestQueue(stringRequest);

        }
    });

}

}

This is the log I get in logcat:

W/System.err: org.json.JSONException: Value
  {"status":0,"result":"Access restricted"} of type org.json.JSONObject
  cannot be converted to JSONArray

I do it correctly in POSTMAN but I failed to get the result I want in android.
API added in command.

A: try this
  public void login(final String user, final String pass) {
        Log.e("Constant.KEY_URL", String.valueOf(Constant.KEY_URL));
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.KEY_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                     //you will get your response in log
                        Log.e("response", response);

                        if (user.equals("") || pass.equals("")) {

                            Toast.makeText(getApplicationContext(), "username or password is empty", Toast.LENGTH_LONG).show();
                        } else if (!response.equals("empty")) {
                            Log.e("isempty", "yes");

                            try {
                                JSONArray array = new JSONArray(response);
                                for (int i = 0; i < array.length(); i++) {
                                    JSONArray array1 = array.getJSONObject(i).getJSONArray("data");
                                    for (int j = 0; j < array1.length(); j++) {

                                        startActivity(intent);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        } else {
                            Log.e("isempty", "else");
                            Toast.makeText(getApplicationContext(), "Username or password is incorrect", Toast.LENGTH_LONG).show();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), "username or password is empty", Toast.LENGTH_LONG).show();
                        //  Toast.makeText(getApplicationContext(), "Invalid username or password", Toast.LENGTH_SHORT).show();
                        Log.e("Error", "msg==>" + error);
                    }
                }) {

            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> reqMap = new LinkedHashMap<>();
                reqMap.put("username", user);
                reqMap.put("password", pass);
                reqMap.put("method", "login");

                Log.e("request","login" + reqMap);

                return reqMap;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 30, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        if (requestQueue == null) {
            requestQueue = Volley.newRequestQueue(getApplicationContext());
        }
        requestQueue.add(stringRequest);
        stringRequest.setTag("TAG");

    }

call this login method on your button click event

    btnlogin.setOnClickListener(new View.OnClickListener()

    {
        @Override
        public void onClick(View view) {
            user = editusername.getText().toString().trim();
            pass = editpassword.getText().toString().trim();

           login(user, pass);
        }

    });

I'm assuming that you are doing sign up function using volley request response..Relate to my code which i have used for login purpose,you can change it according to your needs..Hope it helps

A: The response you are getting is JSONObject and not JSONArray
try following code in onResponse method:
try {
                    JSONObject jsonObject = new JSONObject (response);
                    String status = jsonObject.getString("status");
                    String result = jsonObject.getString("result");
                    builder.setTitle("Server Response...");
                    builder.setMessage(result);
                } catch (JSONException e){
                        e.printStackTrace();
                }

A: Your are trying to parse an array from your response but you are getting an JSONObject.
So first change this line when you get the response
JSONObject jsonObject = new JSONObject(response);

and check the status
if(jsonObject.getString("status").equalsIgnoreCase("0")){
   // show error message or whatever
}else if(jsonObject.getString("status").equalsIgnoreCase("1")){
   // then parse your array if response has it
}

A: Use this
JSONObject jsonObject = new JSONObject (response.toString());

Instead of
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);


text:
Q: Lightbox2 2.6 shows images very tight I'm using that library to show some pictures but when I open one of them the picture is very tight and smaller.
The code:
<a href="<?php echo $productThumb; ?>-1.jpg" rel="lightbox"><img src="<?php echo $productThumb; ?>-1.jpg" alt=""/>

The PHP variables contains the path to the image.
I tried using the older rel="lightbox" and the new data-lightbox

A: You might want to look here, where it was first adressed: https://github.com/lokesh/lightbox2/issues/69, specifically this.
So try adding this to your style sheet:
.lb-image{
max-width: inherit;
}

A: try echoing the url to the big image in the A element, and the url to the thumbnail in the IMG element


text:
Q: Changing part of a composite-id I have a class, BillMedicine, which is many-to-many table for Bill and Medicine.
The BillMedicine mapping file is:
<class name="BillMedicine" table="Bill_Medicine">
    <composite-id>
        <key-many-to-one name="Bill" class="Bill" column="BillID" />
        <key-many-to-one name="Medicine" class="Medicine" column="MedicineID" />
    </composite-id>
    <version name="LastModifiedOn" column="LastModifiedOn" type="DateTime"
             access="field.pascalcase-underscore" />
    <property name="Quantity" column="QuantityPurchased" />
</class>

When I create a new BillMedicine and update the quantity my unit test succeeds. However if I uncomment the line that updates the medicine, I got the exception NHibernate.StaleObjectStateException: Row was updated or deleted by another transaction
BillMedicineRepository target = new BillMedicineRepository();
BillMedicine billMedicine =
    new BillMedicine { Bill = _bill, Medicine = _medicine1, Quantity = 1 };
target.AddBillMedicine(billMedicine);

//billMedicine.Medicine = _medicine2;
billMedicine.Quantity = 2;
target.UpdateBillMedicine(billMedicine); // Exception if I update the medicine

I have checked the SQL shown by NHibernate and it is not updating the medicine
UPDATE Bill_Medicine SET LastModifiedOn = @p0, QuantityPurchased = @p1
WHERE BillID = @p2 AND MedicineID = @p3 AND LastModifiedOn = @p4;

Edit:
My Questions:
1- Why updating the quantity only is working but updating the medicine is throwing exception?
2- Is it possible to make Nhibernate update the medicine property? If yes, how? If no, can someone suggest a workaround?

A: NHibernate does not allow changing the primary key.
Possible workarounds:

*

*Create a new instance with the new medicine and delete the old one

*Use an HQL update to change the Medicine. Keep in mind that the in-memory state won't match the DB unless you Evict the instance and load it again.

A: I think you should create another object, because i have a deja-vu here. Your trying to

*

*create an object with the key B1 M1

*save it

*keeping the same object and same
reference, changing the key to B1 M2

*
updating the new object (with an old
reference)

I'd recommend either flushing your session between the save and the update, or using a transaction for each of the operations (flushing should be enough though, i recommend the transaction only because it's a good practice :) ). I have the feeling you're trying to update an object that hasn't been inserted yet


text:
Q: Syncing issues using GameKit I am trying to make a simple two player snake game that uses gameKit to send movement information back and forth. I start the game out with the server sending a command to start the game. Once the game starts a timer fires every .5 seconds that moves the snakes. No matter what I do I end up with the timers on the two iPhones firing at different times. Does anyone have any suggestion or advice for a solid way of synching the information between the devices?
Thanks in advance for your help!

A: What I finally went with was to have one device do all the number crunching and send the other device information on where its snake (it was a snake game) should be instead of having both devices calculate where there snakes should be and sending that info to the other device. That way led to syncing issues 100% of the time.

A: A quick search for network game synchronization techniques yielded plenty of results...  Each game is unique, I imagine you could adapt some of the techniques from these articles to help:

*

*http://www.mine-control.com/zack/timesync/timesync.html

*http://www.softlookup.com/tutorial/games/ch17.asp

*http://www.flipcode.com/archives/Network_Game_Programming-Issue_07_I_bent_my_Wookie.shtml
There were even a few IEEE articles if you have access to them.