Receiving sms in android- stopped unexpectedly

Question: Hello friends this is the code i used to receive sms. it receives the sms after receiving it shows receivesms stopped unfortunately. can anyone please help me.
ReceivesmsActivity.java
<code>                      public class ReceivesmsActivity extends Activity {
public TextView info;
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
             setContentView(R.layout.activity_receivesms);

            info = (TextView) findViewById(R.id.info);
     }

public class Receivesms extends BroadcastReceiver{
         @Override public void onReceive(Context context, Intent intent) {
     try{
     Bundle pudsBundle = intent.getExtras();
     Object[] pdus = (Object[]) pudsBundle.get("pdus");
     SmsMessage messages =SmsMessage.createFromPdu((byte[]) pdus[0]);
     info.setText(messages.getMessageBody().toString());
     }catch(Exception e){
     Toast.makeText(context,e.toString(),Toast.LENGTH_LONG).show();
     }
    }
     }
</code>
This is the manifest file for this application
Manifest
<code>                     <activity

        android:name="com.receivesms.ReceivesmsActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
       </intent-filter>
       </activity>

       <receiver android:name=".Receivesms">
         <intent-filter>
             <action android:name="android.provider.Telephony.SMS_RECEIVED" />
         </intent-filter>
       </receiver>
</code>
Comment: post your logcat please
Comment: at first look, it appears that your trying to update the UI with a broadcast receiver. that is not a good idea. u should implement Handler.Callback in your activity. and then use the handler to communicate with the broadcast receiver to update the UI
Comment: i tried without update the ui also it shows like that only @inner_class7
Comment: sorry edit: you must use the BroadcastReceiver to send a message to the Handler to update the UI(previous comment says otherway around). Code posted below
Comment: then can you please post your logcat...  Also i updated how the Handler is instantiated using `ReceivesmsActivity.this`
Comment: i execute in phone not in emulator because it does not receive sms right?
Comment: you should still have a logcat. If in eclipse do Window->show view->other->logcat and additionally please post the entire contents of your manifest file.
Answer: Probably need to do this:
<code>  public class ReceivesmsActivity extends Activity implements Handler.Callback {
    public TextView info;
    public Handler handler;
    private static final int SUCCESS = 0;
    private static final int FAILED  = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_receivesms);

        info = (TextView) findViewById(R.id.info);
        handler = ReceivesmsActivity.this;
 }

   @Override
   public boolean handleMessage(Message message){

           switch(message.what){

           case SUCCESS:
               udpateUI(message);
            break;
           case FAILED:

            // Maybe toast the user that you have not been able to receive or update UI
            break;

        }
        return true;
   }

  // Updates the UI from the Activity, not the Broadcast Receiver
  public void updateUI(Message msg){
    info.setText(((SmsMessage) msg.obj).obtainMessageBody().toString());

  }

  // Since this is a service its not run on the UI thread, so can't update UI
  public class Receivesms extends BroadcastReceiver{
     @Override
    public void onReceive(Context context, Intent intent) {
     try{
            Bundle pudsBundle = intent.getExtras();
            Object[] pdus = (Object[]) pudsBundle.get("pdus");
            SmsMessage messages =SmsMessage.createFromPdu((byte[]) pdus[0]);

             // the idea is get a reference to your activity
             // then send a message back to the Handler to update the UI
             handler.obtainMessage(SUCCESS, messages).sendToTarget();

      }catch(Exception e){
          Toast.makeText(context,e.toString(),Toast.LENGTH_LONG).show();
     }
}
 }
</code>
Comment: Can you try this again? i made some updates, i was handling the Object wrong with the Handler. It should be good now


Finding if a value falls within a range, using bitwise operators in C

Question: So i am working on this method, but am restricted to using ONLY these operators:
<<, >>, !, ~, &, ^, |, +
I need to find if a given int parameter can be represented using 2's complement arithmetic in a given amount of bits.
Here is what I have so far:
int validRange(int val, int bits){
    int minInRange = ~(1<<(bits + ~0 ))+1;   //the smallest 2's comp value possible with this many bits
    int maxInRange = (1<<(bits+~0))+~0;  //largest 2's comp value possible
    ..........
}

This is what I have so far, and all I need to do now is figure out how to tell if minInRange <= val <=maxInRange. I wish I could use the greater than or less than operator, but we are not allowed. What is the bitwise way to check this?
Thanks for any help!
Comment: Do you have to deal with negative values?
Comment: Yup, it's 2' complement. For example: validRange(-4,3) would return 1, while validRange(5,3) would return 0
Comment: Shift the value to the right `while (value && ~value)`. In other words, if you keep shifting the value to the right, it will eventually be 0 (if it started as a positive number) or all 1's (if it started as a negative number). Then you'll need to add 1 to the bit count if is was a negative number.
Comment: I'm not allowed to use loops or conditional statements :/
Comment: Your shifts exhibit undefined behavior when `bits` is equal to the number of bits in an `int` (or greater).  Of course, in that case, the function could trivially return 1.
Comment: I think we are supposed to assume it is, at most, 32 bits
Comment: @Team.Coco assuming that `bits` is at most 32 is not sufficient to avoid UB.  You get UB if it is exactly 32, too (supposing that `int` is not larger than that).  That's a case I would expect to work properly, myself.  It might turn out to work for you regardless, but it cannot be relied upon to do so everywhere or everywhen.
Comment: Are you permitted to use conditional statements?
Comment: Nope. Just those operations listed and variables
Comment: Well, you're using assignment operators (`=`) and `-` in your example code, and those are not on your list.  It seems likely that at least the assignment operator is intended to be allowed, but the omission of `-` might be intentional.  Anyway, that does lead me to ask you to confirm that the relational operators (`==`, `<`, etc.) are indeed forbidden.
Comment: Yea, I just noticed that I have mistakenly used operators I wasn't supposed to. I will correct it.
Answer: Two's complement negative numbers always have a '1' in their high bit.
You can convert from negative to positive (and vice versa) by converting from FF -> 00 -> 01. That is, invert the bits, add 1. (01 -> FE -> FF also works: invert the bits, add 1)
A positive number can be represented if the highest set bit in the number is within your range. (nbits - 1: 7 bits for an 8 bit signed char, etc.)
I'm not sure if your constraints allow you to use arrays. They would speed up some things but can be replaced with loops or if statements.
Anyway, if 1 << (NUM_INT_BITS-1) is set on your input, then it's negative.
Invert, add one.
Now, consider 0. Zero is a constant, and it's always the same no matter how many bits. But if you invert 0, you get "all the bits" which changes by architecture. So, ALL_BITS = ~0.
If you want to know if a positive number can be represented in 2 bits, check to see if any bits greater than or equal to bit 2 are set. Example:
two_bits = 0b00000011
any_other_bits = ~two_bits # Result: 0b11...11100
if positive_number & any_other_bits
    this number is too fat for these bits!

But how do you know what ~two_bits should be? Well, it's "all set bits except the bottom however-many". And you can construct that by starting with "all set bits" and shifting them upwards (aka, "left") however-many places:
any_other_bits = ~0 << 2  # where "2" is the number of bits to check

All together now:
if (val & ((unsigned)INT_MAX + 1))
    val = ~val + 1;

mask = ~0 << bits;
too_wide = val & mask;
return !too_wide;

Comment: From the comments:  "I'm not allowed to use loops or conditional statements :/"
Comment: You must be very careful shifting values of signed type, for a left shift that otherwise would produce a value that is out of range for the type produces undefined behavior.  Inasmuch as you seem to be depending on doing so, you're giving poor advice.  One can work around this by working with an unsigned type; e.g. `0U << bits`, but you still have to be careful not to try to assign an out-of-range value to an `int` variable, too.
Answer: To test if a number can be represented in a N-bit 2s compliment number: Simply test that either

The number bitwise-and'ed with the compliment of a word with the low (N-1) bits set is equal to zero
OR The high InputBitWidth-(N-1) bits of the number are 1s.

 mask=(1<<(bits-1))-1; return ( !(val&mask) | !((val&~mask)^~mask) );
Comment: Not providing code b/c this sounds like homework, and I prefer to encourage at least some thought.
Comment: Thanks! I prefer to not see the code anyways. What do you mean by a word with the low N bits? So like 011 for 3 bit?
Comment: Actually this may not solve the problem, given your example.  `-4` doesn't fit in 3 bits.   Hm.
Comment: Maybe if you "and" it with the low (N-1) bits? So check 100 (-4) with 011, which is the max value. Anding them will get 0. Would this be correct?
Comment: @Team.Coco `-4` is a special case. Consider the bit patterns for `-3` and `-5`.
Comment: -4 2s compliment is `0b11111100`   I guess you could consider that this fits in a signed 3-bit number.    Editing answer.
Comment: What is meant by "high INputBitWidth"?
Comment: `sizeof(int)*8` bits


Is it bad form to prompt people to mark answers as accepted? (During BETA)

Question: I've been looking through the site and I'm very aware of some stats that we're lacking on for the beta to graduate.
There is a large proportion of good answers that have been up voted by the community but not accepted by the op.
Now this doesn't look quite like the typical 'hit and run' style of question - as the OP has gone on to ask other questions too.
So on this note, is it a bad/good idea to perhaps pop a gentle reminder in a comment recommending accepting the answer (if they found it suitable). I think some people either forget to come back and mark it as solved, or are waiting for more/better answers - but even then, I think a reasonable time limit should be applied.
Answer: Unfortunately, the persistence of these "gentle reminders" starts to amount to  systematic (or at least system-wide) harassment — so we generally ask users to forgo the activity completely. The system already prompts the user to accept answers when warranted. But accepting an answer is a completely voluntary activity, and it is up to the user to decide when (and if) an answer should be accepted at all.
If this were only an occasional nudge, we'd probably just leave them as a helpful reminder towards a feature they may simply be unaware of. But as the sites start to fill with them, it becomes unwelcoming as the noise and harassment level of this feature starts to outweigh its benefits. I'd just leave it alone.
Comment: @sonassi Don't forget to mark this as the answer, Ben :-D (if appropriate)
Comment: Never, I'm waiting for a better one to come along ...
Comment: IMO the larger portion of the problematic posts are from those newer to SE/SO. Many here never did use SO, so we are starting with rookie users. I like Robert's answer though... :)
Comment: I'm aware that on a graduated site that it might be an inconvenience/clutter - but whilst the site was in BETA, I did wonder whether we need to just nudge people that little bit to encourage them to stay active to keep the site active. But nevertheless, consider it done.
Comment: @sonassi If anything, this is a *bigger* problem during the beta when the site is smaller and the activity is more concentrate across fewer questions. Graduation, beta; makes no difference.


What is standard way to give LXC public IP address?

Question: I am researching LXC. The thing I was unable to find is how to give a container public IP address?
Suppose we have a server with 5 IP addresses. Then we do 4 containers there and give somehow one address for each of them.
I saw there is "standard" way for LXD, but I found nothing for LXC.
Answer: What I do in LXC is to have the server interface being a bridge, so the server has IP1 set on the bridge, and the four container interfaces becomes part of that bridge. Just configure your container networking to be:
lxc.network.type = veth
lxc.network.flags = up
lxc.network.link = <your server bridge interface>
lxc.network.name = eth0

And then you set your container IP as usual in the container. You can also set the IP in the lxc config if you want:
lxc.network.ipv4 = <IP>/24
lxc.network.ipv4.gateway = <gw IP>

How you do that is up to you. There are also other network types, so please do read up on that.


$AB \neq 0$ but $BA=0$

Question: Do there exists to matrices or objects such that $AB \neq 0$ but $BA=0$?
Another way to ask this question is if there exists objects or matrices $A$ and $B$ such that...
$[A,B]=AB$
where $[ \, , \, ]$ is the commutator $[A,B]=AB-BA.$
If such matrices do not exist, what does that imply about the algebra that the elements are in?
Answer: Noncommutative algebra is filled with examples of this.
For example, take $A=\begin{bmatrix}0&1\\0&0\end{bmatrix}$ and $B=\begin{bmatrix}0&0\\0&1\end{bmatrix}$.
You have $AB\neq 0$ but $BA=0$.
Rings in which $ab=0$ implies $ba=0$ are called reversible rings. That is a particularly strong condition, and is pretty interesting to study. I highly recommend Greg Marks' paper: Reversible and symmetric rings (2002), and P.M. Cohn's paper Reversible rings (1999).
This would imply that $AB=0$ does not necessarily imply $[A,B]=0$.
Comment: Obvious examples of reversible rings include commutative rings and rings without nilpotent elements.
Comment: What can be said about *algebras* where $AB = BA$, for instance over commutative rings?
Comment: @NieldeBeaudrap Well, if you read my comment, you see I mentioned that commutative rings are obviously reversible. They also have the property that $[A,B]=0$ for all $A, B$, too. Algebras are rings, unless you specifically have nonassociative algebras in mind. Do you?
Comment: @rscwieb: Sigh. Yes, obviously, algebras are rings; and obviously an algebra which happens to be commutative satisfy $AB = 0 \iff BA = 0$. I had hoped for something more. Are you telling me that there is nothing more known about when $AB = 0 \iff BA = 0$, for algebras as a particular case of rings? That in this case, the only thing we know about algebras are things which hold for rings in general?
Comment: @NieldeBeaudrap Since this definition only deals with the ring multiplication of the algebra, I can't forsee why having additional algebra structure would make any difference. In fact, I can't think of a single substantial thing where being an algebra makes a difference on a result for rings. But if you have a good example, I would love to hear it :)
Comment: I suppose I had in mind such ideas as taking an existing algebra, for instance, $M_n(\mathbb C)$, and extracting another algebra which would be reversible in this way, e.g. the normal matrices in this case. I imagined perhaps one might be able to characterize constructions of this sort which give rise to reversibility.
Comment: @NieldeBeaudrap If you can get your hands on the papers I mentioned, I'm sure you'll find something useful along these lines :)
Answer: What about $$B = \begin{pmatrix}0 & 1 \\ 0 & 0 \end{pmatrix} $$ and $$A = \begin{pmatrix}1 & 0 \\ 0 & 0 \end{pmatrix}$$
Answer: Sure - here's an example, with matrices taking entries in the field $\mathbb{Z}_{2}$:
$$
\begin{bmatrix}
1 & 1\\
0 & 0\\
\end{bmatrix}
\begin{bmatrix}
1 & 0\\
1 & 0
\end{bmatrix}
=
\begin{bmatrix}
0 & 0\\
0 & 0
\end{bmatrix},
$$
but
$$
\begin{bmatrix}
1 & 0\\
1 & 0\\
\end{bmatrix}
\begin{bmatrix}
1 & 1\\
0 & 0
\end{bmatrix}
=
\begin{bmatrix}
1 & 1\\
1 & 1
\end{bmatrix}.
$$
Answer: As the other answer show: there are uncountably many pairs of matrices $(A,B)$ such that $AB = 0$ while $BA \neq 0$. If you think of square matrices as linear transformations then it is obvious why this should be so: in $AB$, we can think of the product as recording the image of each of the columns of $B$ under the linear transformation $A$, likewise with $BA$.
A nice question to ask is the following: Given a fixed matrix $A \in \text{Mat}_n\mathbb{R},$ what is the following:
$$\widetilde{A} := \{ X \in \text{Mat}_n\mathbb{R} : AX = 0 \ \wedge \ XA \neq 0\} \, ?$$
Clearly, if $X \in \widetilde{A}$ then $\lambda X \in \widetilde{A}$ for all $\lambda \neq 0.$ Interestingly, this space is not a vector space because the zero matrix $0 \notin \widetilde{A}$ and $X,Y \in \widetilde{A}$ does not imply that $X+Y \in \widetilde{A}.$
Comment: @JasonDeVito Quite right! Thanks for that. I've changed it.
Comment: $AX = 0$ iff ${\cal R}(X) \subseteq {\cal N}(A)$ (i.e. the column space of $X$ is contained in the null space of $A$).  So $\tilde{A}$ consists of those $X$ such that ${\cal R}(X) \subseteq {\cal N}(A)$ but not ${\cal R}(A) \subseteq {\cal N}(X)$.
Comment: Any $n \times n$ matrix $A$ whose rank is strictly between $0$ and $n$ has $\tilde{A}$ nonempty: just let $u$ and $v$ be nonzero vectors in ${\cal R}(A)$ and ${\cal N}(A)$ respectively, and take $X = v u^T$.

$AB \neq 0$ but $BA=0$


Javascript JSON Data to HTML Table

Question: I have some code which I'll paste below now. What the code does is read the contents of an XML file and put it into a JSON. Then puts the data from the JSON into a HTML table. All works fine except one thing. When the table is created the first row (after the column headings) always shows up as "undefined" in each cell. I've had a look through this code and cannot find anything that would cause it but I'm not an expert and I'm sure a fresh pair of eyes would help so any ideas?

USA State Information

Please select an area of the USA in the dropdown list below.

<select name="area" onchange="findXML(this.value)">

<?php
//set directory and open it
$xmldir = 'XML';
$dir = opendir($xmldir);

//create array and read through files in directory
$xmlfiles = array();
while ($file = readdir($dir))
{
    //if the first char is not '.' then add to array
    if (substr($file,-1,1) !== ".")
    {
        $xmlfiles[] = $file;
    }
    else
    {
        //do nothing
    }
}

echo '<option value="select">Select</option>';

foreach($xmlfiles as $area){
    echo '<option value="'.$area.'">'.$area.'</option>';
}
echo '</select>';

//close directory
closedir($dir);
?>

Name</>
Number</>
Joined</>
Population</>

Comment: Just a stylistic concern. Why not `tblr.insertCell(0).innerHTML = JSONObject[i].name;`? There is no need for these variables. Also, your `var` statements inside of the `for` loop are logically wrong: they are variables that are either local to the containing function or global to the window! You *cannot* declare variables inside of a `for` loop. To understand more about the javascript code quality, you might start using a tool like [jshint.com](http://jshint.com).
Answer: I think I found the issue:
var JSONObject = [{}];

should be
var JSONObject = [];

The reason this fixes the issue is that you're iterating through the JSONObject array starting at the first index. This is fine, but the way you initialized the array gives the first index an empty object. When you go to get the properties name, number, etc., the empty object won't have them and they'll be returned as undefined.
Comment: I've tried. I've got to wait a few more minutes but will do so when it's available :)
Comment: Thank you SO much! Just tried this and it has solved the problem! Can't believe I didn't notice this before, haha! Thanks again!
Comment: @Kimmy25 If this solved your answer please click the check mark to the left of the post underneath the up/down arrows.
Comment: @Kimmy25 Ah, my apologies! :)
Answer: have you tried:
for (i=1; i!=($length); i++){
It may be your index starts from 1 and not 0
Comment: This will actually fix the issue but it's not the "correct" solution. Arrays are always 0 indexed.

Javascript JSON Data to HTML Table


How to indicate things that you should listen for in Musescore?

Question: Some people have complained about my arrangements being hard to understand when only viewing your part sheet. Because of that, I'd like to somehow indicate that a certain part should not be played, but instead being listened to.
Consider this:

Here I want the lower part to listen for the higher, so I would like to copy those notes. Like this:

But how should I indicate that those note should not be played? One way would be if those notes were considerably smaller, like grace notes, but I have not found a way to create a complete melody with grace notes since you need to attach all grace notes to real notes.
EDIT:
Found a solution, but I hope for better answers. My solution cannot possibly be the most convenient way.
Answer: You're asking for 'cues'.  See example below, borrowed from the Wikipedia item on that topic.  You'll see that the main part retains its full notation, rests and all, the smaller cue notes are labelled with the name of the instrument that plays them.

The more advanced notation programs (Sibelius, Finale) have a 'Paste as cue' function that automatically puts the cues in an otherwise unused Voice, hides the cues in the Full Score, shows them in the Parts, turns off playback etc.   MuseScore can achieve all this, but you'll have to do it manually.
Like this:
Answer: Turned out the solution was pretty simple.
To change the size of the note heads, select the notes and press F8 and the press the button notes. Now check the checkbox "small". Now it looks like this:

In the same inspector you get when pressing F8, where you can change the size of the note heads, you can also simply uncheck a checkbox called play. This will make those notes silent.
Comment: You're nearly there.  But reinstate the (full-size) rests under the cue notes and label then with the voice or instrument they represent.
Comment: @LaurencePayne I tried that, but it looked like a complete mess. If you know how to do it, please add an own answer and provide a picture.
Comment: OK.  I've extended my answer with a MuseScore example.


Connection to two websockets (via vue-socket.io) in one vue/vuex app

Question: so I have a web application using vue with vuex which has a connection to a websocket via vue-socket-io like this:
<code>Vue.use(new VueSocketIO({
  debug: true,
  connection: SocketIO('http://192.168.0.31:5000'),
  vuex: {
    store,
    actionPrefix: 'SOCKET_',
  },
}));

new Vue({
  router,
  store,
  vuetify,
  render: (h) => h(App),
}).$mount('#app');
</code>
My problem is, that besides this websocket, I now need to communicate with yet another server also via websocket. How can I have two websockets with different servers at the same time?
I found a similar question here but I am not sure, if the answer to "just not use vue-socket-io because it won't work" is correct or if there is a way to accomplish this?
In this question the user tried to use two stores which I also don't know if it is a food idea?
Thanks for any hint on how I can solve this problem!
Answer: Apparently with vuex and the way shown above only one websocket can be connected like this. The only way to connect another on was to locally do it in the components.


Combinations - no repetition for mirrors?

Question: My question is, if there is a simple explanation as to why mirrors aren't counted twice with binomials such as it is in the case it's not a mirror?
Here is an example:
Consider the elements {1, 4}. How many different ways can these be added? Clearly the answer is 3:
1 + 4
4 + 4
1 + 1
The answer is not as clear with larger lists though, and I'm having trouble understanding why
Calculating the amount of choices with binomials, I get 2 choices for the first value, 2 choices for the second value, and divide by 2 to avoid double counting:

Clearly it gives the wrong answer. So now to my real question:
Why is not 4 + 4(mirror objects) counted twice, but 1 + 4(non mirror objects) is? is there a simple explanation to this?
Comment: Are you asking why $1+4$ could be seen as distinct from $4+1$ but $4+4$ is seen as the same as $4+4$?
Comment: I guess that's essentially what I'm asking yeah, it makes sense that 1 + 4 and 4 + 1 could be seen as distinct. For some reason it just seemed a bit odd to me, but I guess I've got some flawed thinking going.
Answer: There is only one way to get a $4 + 4$. You must select a $4$ on the first character and $4$ on the second character.
With the $1 + 4$ case, we select a $1$ as the first term and a $4$ on the second term. This is equivalent to selecting a $4$ on the first term and a $1$ on the second term. So there are two distinct permutations $(1, 4), (4, 1)$. We want to denote equivalence. From an algebra standpoint, we are "dividing out" by the Symmetry group $S_{2}$, which is the group of permutations on two elements. Doing this says that $(1, 4) \equiv (4, 1)$. Note that $S_{2}$ has $2! = 2$ elements, so that is why you divide out the quantity by $2$.
Another way to look at this is by enumerating the elements:
$(1, 1)$
$(1, 4)$
$(4, 1)$
$(4, 4)$
So start with $(1, 1)$. When you permute the elements of this tuple, you just get $(1, 1)$ back. The same logic applies to $(4, 4)$. This is why $4 + 4$ and $1 + 1$ are the same.
When you deal with $(1, 4)$ and permute it, you get $(4, 1)$ back.
So if we partition the enumerations where two tuples are equivalent by the same sum, then we have the partitions:
$(1, 1)$
$(4, 4)$
$(1, 4) = (4, 1)$
Notice three partitions, hence your count.
Comment: Thank you for good and quick response, makes perfect sense and I feel like it fixed some stupid way I had of looking at the problem.
Comment: Glad to help! Algebra and graph theory are always nice to haves with combinatorics. They are closely related fields. :-)


Linear Combination of Orthogonal Polynomials

Question: I am currently taking a Numerical Linear Algebra course where orthogonal polynomials is the current topic being discussed.
At some point regarding the aforementioned topic, the author wrote something which i cant seem to figure out why it should be true:
"Any polynomial with degree $m$ can be written as a linear combination of the first (m + 1) orthogonal polynomials $p_{0}, p_{1}, \ldots, p_{m}$"
Where orthogonal polynomials are the ones for which the following relation holds:
\begin{equation}
\left(\mathrm{p}_{\mathrm{k}} \mid \mathrm{p}_{\ell}\right)=0 \quad \mathrm{k} \neq \ell
\end{equation}
where $\mathrm{p}_{\mathrm{k}}(\mathrm{x})=\mathrm{c}_{\mathrm{k}} \mathrm{x}^{\mathrm{k}}+\mathrm{c}_{\mathrm{k}-1} \mathrm{x}^{\mathrm{k}-1}+\ldots+\mathrm{c}_{1} \mathrm{x}+\mathrm{c}_{0}$
and $\left(p_{k} \mid p_{\ell}\right)$ expresses the inner product between polynomials $p_{k}$ and $p_{\ell}$.
Can someone help me? The author did not mention any theorem or proposition for further justifications. I did find some solved examples at Burden & Faires Numerical Analysis book but i guess i am not gonna be fully satisfied until i can prove it or read a full proof.
Thanks in advance!
Answer: A proof uses linear algebra. Orthogonality implies the polynomials in a basis are linearly independent. To see this more clearly, the inner product of a finite sum of orthogonal polynomials $\sum_{k=0}^m a_k p_k$ and a $p_i$ where $0 \leq i \leq m$ is a $c a_i$ for a constant $c$.
Comment: Specific examples are helpful. Choose a basis, say Chebyshev polynomials of the first kind. The order of $T_m(x)$ is $m$ for all $ m \geq 0$. Given a polynomial of degree 5 with constant coefficients from a field, it can be formed from a unique linear combination $\sum_{k=0}^5 a_k T_k(x)$. The coefficients $a_k$ can be found using the inner product for T, discrete or continuous. When $k>5$, $a_k=0$.  If the polynomials were not linearly independent, then one of them $T_n(x)$ would have a non-zero inner product with a $T_l(x)$ where $l \not = n$.  A general proof will be in texts on the topic.
Comment: An example text is "Linear Algebra with Mathematica" by Frank Szabo, Elsevier, 2000. Theorem 8.2 Orthogonal vectors in an inner product space are linearly independent (page 492) and Corollary 8.3 may also be of interest.  The book you mentioned may link orthogonal polynomials and vectors. The Gram-Schmidt process can be applied to polynomials to give orthonormal ones, for example applying it to the monomials gives the Legendre polynomials.
Comment: Interesting! Can you explain it a little bit further, please? I still cant see why it implies the result.
Comment: Can you recommend a good book which contains a full proof? Burden $ Faires does not contain one.
Comment: Just found in Atkinson's numerical analysis book! Also, nice example you gave earlier.


Getting JSON file out in HTML through Azure Storage

Question: I have hooked my Particle photon to a eventhub on Azure where i stream the data through Stream Analytics and then to my Azure Storage. Right now i recieve the temperature as a JSON file in Azure Storage.
Is there any way to do HTTP request or something to the storage account?
This is the JSON file: https://pptlbhstorage.blob.core.windows.net/temperature/0_d1e8a2b709b14461b5ac12265f33020b_1.json
Also, should i make a WepAPI that recieves theese data? so i also can make mobile app and not only webpage?
Comment: You want to get the json file from blob storage via javascript?
Answer: Yes, you may get the files out from the Azure Storage using the official SDKs. For that, you will need the Blob functionality - take a look here.
And, if you want your own implementation, you can use the Azure Storage REST API.
<code> CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("ahrimanstoraccount_AzureStorageConnectionString"));
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference("vhds");
        CloudBlockBlob blockBlob = container.GetBlockBlobReference("yourfilename.txt");

        string path = (@"C:\Temp\yourlocalfilename.txt");
        blockBlob.DownloadToFile(path, FileMode.OpenOrCreate);
</code>
app.config:
<code><appSettings>
 <add key="ahrimanstoraccount_AzureStorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=myAccountName;AccountKey=myAccountKey" />
</appSettings>
</code>
UPD from the comments: the same approach is working for Console and ASP.NET MVC. Azure Storage may be added by 1) Click on the project => Add => Add Connected Service => Azure Storage => Select your storage account. That will install all of needed libraries and valid connection string into your web.config. 2) Once it is done, the browser will open the page where code pieces will be shown
and manually, by going to the Azure Storage page and copying keys/names to the connection string.
Comment: Thanks! i'm quite new to this.. is it possible to show any code examples? im not so used to read documentation, i have tried but always end up doing it wrong
Comment: @yellowborat you use Visual Studio?
Comment: Yes i do use Visual Studio
Comment: @yellowborat ok, 1) Click on the project => Add => Add Connected Service => Azure Storage => Select your storage account. That will install all of needed libraries and valid connection string into your web.config. 2) Once it is done, the browser will open the page where code pieces will be shown
Comment: As i have some samples, i will post it there a few minutes later.
Comment: @yellowborat here you are. Add Connected Service as described above, go to the web.config, grab the connection string name (in the format i used in the answer) and put your filename. You should be all set.
Comment: Thank you! :D When i try to connect to the Azure Storage i get this message: https://gyazo.com/fa2acb1ca6f0cef5baf9899b0c2d5cd0
Comment: Fantastic. What is the project type? ASP.NET, something else?
Comment: Ok. First, Click on your project, "Manage NuGet packages", go to "Browse" => enter "azure storage", once it find the packages WindowsAzure.Storage and Microsoft.WindowsAzure.ConfigurationManager, install both of the packages.
Comment: After that, paste the code i provided to your Main class, and open app.config. Paste the appsettings block here as i changed in the answer.
Comment: I have already downloaded the packages needed for azure storage, i went to the connectionstring to manually add my key and storage name. Isn't that the same also?
Comment: Yes, it is the same. See my answer - just paste your key and name to the connection string.
Comment: I got it working now, so what does the code basically do? It opens up the container, and look for the specified blob name? in my case "jsonFile.json" and then saves it locally ?
Comment: Exactly as you said.
Comment: Thank you! Now if i were to display this json file out in html.. how would i do it? would i create a MVC project and then do the same thing as i did here in the controller?
Comment: Yes, absolutely. Also you may want to try SignalR for real-time stuff as described [here](http://www.mikelanzetta.com/2015/08/real-time-mapping-with-signalr-and-event-hubs/). It uses Event Hubs, but i suspect you use that or the IoT Hub.
Comment: No i am actually using Event Hubs as the Particle Photon already provides their own cloud service. I will look into SignalR! Thank you so much for your help!
Comment: @yellowborat Glad that helps. Please mark the question answered for a future reference.
Comment: All -  this isn't the place for conversation - that's what Chat is for. There is a lot of detail buried in the comments here that should actually be in the answer (as well information such as links to errors, which should be edits to the original question).
Comment: Sorry, but when Stackoverflow constraints me with not opening a chat since i don't have enough points, i didn't have any choice :)


Can $\sin(xy)$ be written in terms of trigonometric functions of only $x$ or $y$?

Question: Can $\sin(xy)$ be written in terms of trigonometric functions of only $x$ or $y$? I am tempted to say yes, because the double- and half-angle formulae exist, and these would be special cases of $\sin(xy)$.
I first looked at the Taylor series,
$$\sin(xy) = \sum_{n=0}^\infty\frac{(-1)^nx^{2n+1}y^{2n+1}}{(2n+1)!} = xy-\frac{x^3y^3}{6}+\frac{x^5y^5}{120}-\cdots$$
but as far as I know, neither $x$ nor $y$ can come out of the sum since they are not constants.
Comment: It might depend on what "in terms of" means (though I am very much inclined to suggest that the answer is "no" regardless). For one thing, it is apparent that for any function $g:\Bbb R^4\to\Bbb R$, the map $g(\sin x,\cos x,\sin y,\cos y)$ is a bi-periodic function $\Bbb R^2\to\Bbb R$, while $\sin(xy)$ is not.
Comment: Half and double or $\sin kx$ are much more different from $xy$
Think to $e^{xy}$ or $\log(xy)$. No way. Forget it :)
Comment: Taylor series give nothing. Try Ryan series.
Comment: @Blue I think you are partially right. This question and its answers are more general, but one answer does explicitly say $$\sin(n x)=\sum_{d=0}^\infty \frac{d\cdot \cos\left(\frac{n-d}{2}\pi\right)\frac{2^dn}{n+d}{{\frac{n+d}2}\choose d}}{n}\cos^{d-1}(x)\sin(x) \ \ \ \ \ \forall |x|\leq\pi$$ However, these answers already have provided different formulae and insight, so I'm not sure.
Answer: If you think at $\sin(xy)$ be expressed as a combination of a FINITE number of  sums and powers of $\sin(x)$ and $\sin(y)$ , the answer is certainly no.
With infinite series, one can imagine a formal answer (more a joke than serious)
Starting from :
$$\sin(xy)=\sum_{k=0}^\infty \frac{(-1)^k x^{2k+1}y^{2k+1}}{(2k+1)!}$$
$$a=\sin(x)\quad\to\quad x=\sin^{-1}(a)=\sum_{n=0}^\infty \frac{\left(\frac{1}{2} \right)_n a^{2n+1}}{(2n+1)n!}=\sum_{n=0}^\infty \frac{\left(\frac{1}{2} \right)_n \sin^{2n+1}(x)}{(2n+1)n!}$$
And similarly
$$y=\sum_{n=0}^\infty \frac{\left(\frac{1}{2} \right)_n \sin^{2n+1}(y)}{(2n+1)n!}$$
$\left(\frac{1}{2} \right)_n$ is the Pochhammer symbol $=\frac{\Gamma(n+\frac{1}{2})}{\Gamma(\frac{1}{2})}$.
Finally, the monster :
$$\sin(xy)=\sum_{k=0}^\infty \frac{(-1)^k \left(\sum_{n=0}^\infty \frac{\left(\frac{1}{2} \right)_n \left(\sin(x)\right)^{2n+1} }{(2n+1)n!} \right)^{2k+1}\left(\sum_{n=0}^\infty \frac{\left(\frac{1}{2} \right)_n \left(\sin(y)\right)^{2n+1} }{(2n+1)n!} \right)^{2k+1}}{(2k+1)!}$$


Merging two data.frames by key column

Question: I have two dataframes. In the first one, I have a KEY/ID column and two variables:
KEY V1 V2
1   10  2
2   20  4
3   30  6
4   40  8
5   50 10

In the second dataframe, I have a KEY/ID column and a third variable
KEY V3
1    5
2   10
3   20

I would like to extract the rows of the first dataframe that are also in the second dataframe by matching them according to the KEY column. I would also like to add the V3 column to final dataset.
KEY V1 V2 V3
1   10  2  5
2   20  4 10
3   30  6 20

This are my attempts by using the subset and the merge function
subset(data1, data1$KEY == data2$KEY)
merge(data1, data2, by.x = "KEY", by.y = "KEY")

None of them does the task.
Any hint would be appreaciated. Thank you!
Answer: merge(data1, data2, by="KEY") should do it!
Answer: If what you want is an inner join, then your attempt should do it. If it doesn't check the formats of Key columns in both the table using class(data1$key).
Apart from these and the merge suggested by Christian, you can use -
library(plyr)
join(data1, data2, by="KEY", type="inner")

or
library(data.table)
setkey(data1, KEY)
setkey(data2, KEY)
data1[,list(data1,data2)]

Comment: Thank you! I wasn't familiar with the plyr package
Answer: You could use a dplyr *_join. Given the sample data, both of the following would give the same result:
library(dplyr)
df_merged <- inner_join(data1, data2, by = 'KEY')
df_merged <- right_join(data1, data2, by = 'KEY')

A inner_join returns all rows from df1 where there are matching values in df2, and all columns from df1 and df2.
A right_join returns all rows from df2, and all columns from df1 and df2.

Merging two data.frames by key column


UICollectionView contentSize.width is wrong

Question: I am running into a very strange situation. I have a UICollectionView in a storyboard and I'm using the standard horizontal flow layout. I have the size of the cell set to 80x80.
However, when I run the app the cells are not stacked horizontally. When I examine collectionView.frame.width, it has the right width (which is the width of the screen). But collectionView.contentSize.width is 80!!
Any idea how I can get the collectionView to use the whole width?
Comment: where you check that width value ?
Answer: When using horizontal flow layout the width of the content view apparently grows with the number of columns filled up with cells.
The content of a collection view that has one column will be less in width than the same collection view with two columns ...

When a minimum content view width is required, property sectionInset left and right values could be set accordingly.
@IBOutlet weak var myLayout: UICollectionViewFlowLayout!
...
override func viewDidLoad() {
   ...
   myLayout.sectionInset = UIEdgeInsets(top: 0, left: 100, bottom: 0, right: 600)
}


Piano Conductor & Accordion Guide

Question: I've been puzzled at why in some of our big band charts, the piano part is labelled "Piano (Conductor) & Accordion Guide". Our keyboardist tried, for a laugh, choosing an accordion patch on his keyboard one time and it sounded terrible. I've never heard of having an accordion in a big band.
(Examples include Stan Butcher's arrangement of Sunny, and Woodchopper's Ball.)
So is this a case of "it doesn't mean what you think it means"?
Why accordion? Did big bands/dance bands at one time sometimes have an accordion instead of a piano?
Update
My question was not so much about the virtues of including an accordion player in a big band, but about whether it was common practice at a certain time to label the piano part thus, and whether it literally meant the pianist could be subbed with an accordion player, or whether it actually indicated something else.
Comment: It's also possible that some big bands had an accordion *in addition to* a piano.
Answer: Average "accordion patches" try to capture the look&feel of a "typical" accordion.  Which lean a bit towards the awful side.
The accordion is really a portable harmonium with much more delicate pressure control (which is one reason harmoniums went out of fashion and accordions not).  An "accordion patch" does not offer this minute continuous control, similar to how solo violin patches rarely crank out anything satisfactory.
Once you exit the folk music scene and take a look at jazz and tango accordionists (the original "Ole guapa!" has been composed and performed by a Dutch accordionist of great acclaim) as well as players specializing on baroque, romantic, classical music as well as a number of Latin American dance and art music, you'll find a lot of brilliant and sensual play.  Nations like Finland, France, Russia have long and active accordion traditions, partly inspiring new classical compositions.
The bandonion has similarities in technique and sound and has become the Tango solo instrument of choice.
With regard to dance bands: many folk dance events make use of small diatonical accordions, and France made the chromatic button accordion large in its use for musette music.  "Musette" is actually the name of a bagpipe, and for purely acoustic bands, the cutting power of an accordion rendered it a suitable replacement with nicer sound and the possibility for polyphonic play.
Accordions are still built for volume, but the use of detuned reed sets (particularly striking in "musette" tuning) with strong beating, very useful for making sound hearable above a brass band, has declined in its aggressiveness since nowadays amplification can be used for maintaining a suitable balance between instrument types.
A musette accordion without accompaniment and in original tuning is sort of an acquired taste.  You really have to take it as the equivalent of bagpipes at home.
Answer: The explanations I could think of:

The composer could have decided that the piano part can be played by an accordion as well to give it a different timbre (Experimenting with the instrument setup)
The charts are sort of universally written so accordion players can participate as well. This way it's the arranger's choice to include an accordion.

And here's the living proof of an accordion in a big band:
Answer: According to the Wikipedia article on accordion music genres, many popular bands of the 1910s and 1920s employed an accordion player, including the Paul Whiteman Orchestra and the Horace Heidt Orchestra (though I'd not heard of the latter before reading the above article).
So it looks like the answer to my question is that accordions were used in dance/swing bands of that era, though they have fallen out of use since. So an arrangement with a Piano and Accordion Guide part probably harks back to that era.
(Incidentally, Stan Butcher was born in 1920, so perhaps it was a publisher with a longer memory who added the accordion label.)

Piano Conductor & Accordion Guide


The apk must be signed with the same certificates as the previous one

Question: I am trying to upgrade my previous version app into the Android market,but it shows an error as "The apk must be signed with the same certificates as the previous one". I am also having previous version apk file.but dont know how to solve this certificate issue..Can someone pls guide me the steps on how to upgrade this new version app?
Answer: You should definitely read this:
http://developer.android.com/guide/publishing/app-signing.html
When you published the app the first time you must have used a certificate - it's mandatory. To upgrade the app you must use the same certificate to sign the upgraded app.
If you lost the certificate, there is no way to perform upgrade. You will need to remove app from market and add a new one. This will not upgrade the app for existing users.
Comment: but how can I extract the previous certificate signed from the previous apk file? I am having previous version apk file
Comment: You cant do that - the apk does not contain the certificate. If it did then other people could extract it and update your app, right?
Comment: Then whats the procedure to upgrade this app?
Comment: @Kanika, You signed your application with a private key. Your apk file only has a public key now. It's impossible to get the private key back from your apk, unless you're the NSA or something. The real question is. What happened to your initial certificate, it should still be on the original computer you developed the app with. Did you switch computers? Did you wipe your drive? If the answer is "no" to both those questions (hopefully it's "No"). What kind of computer do you have? a PC? or a Mac? Also, if a PC what version of Windows/linux are you using?
Comment: yes I switch the computer,and I am using Windows XP.The other person upload the previous version of the app into the Android market,and he has given me the apk file but now i had upgrade it and want to upload my new version into the Android market. but I am not getting how to solve this certificate issue?
Comment: For the last time - NOW PLEASE LISTEM:
Comment: I'll put it simply: IF YOU LOST THE CERTIFICATE YOU CAN NOT UPGRADE THE APP. Period. No way around it. Please stop asking. You will only get the same answer.
Answer: For upgrading any application certificate must be same as before or you can do by installing whole application and again reinstall
Answer: Just use the same keytool that you used for previus app...


Usar bootstrap ou CSS manualmente para responsividade?

Question: Estou com uma duvida em quais situações são mais validas em investir para ter conhecimento em front-end, inclusive tratando-se de responsividade.
Seria mais importante confiar no Bootstrap para deixar seu website responsivo, ou seria mais importante programar toda a responsividade manualmente?
Quais os problemas que podem ser causados quando somente obtém-se o uso do Bootstrap?
Comment: responsividade, obrigado por corrigir, acabei de editar.
Comment: Aprenda display flex e display grid e sejá 100% feliz criando facilmente qualquer site puro em CSS !
Comment: Se você tiver tempo disponível para aprender toda a logica de responsividade do zero em CSS, seria bacana que você mesmo usaria suas próprias soluções.
Agora se você já sabe sabe usar o CSS o básico e quer alguma solução de forma rápida, pode investir no Bootstrap.
Comment: Isto não responde à pergunta. Quando você tiver [reputação](https://pt.stackoverflow.com/help/whats-reputation) suficiente, você vai poder deixar [comentários em qualquer post](https://pt.stackoverflow.com/help/privileges/comment) mas, até lá, escreva apenas resposta que não [dependam de mais informações de quem perguntou](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [Da Revisão](/review/low-quality-posts/245214)
Answer: Cara se você quer controle total não seria prudente você depositar todas as suas fichas em um FrameWork (FW), seja ele qual for, ainda mais o Bootstrap 4 (BS4 é a versão atual).
O BS4 não tem tratamentos avançados para resoluções 4k, nem para display retina, e muito menos para smart watches como o Apple Watche. Então pondere bem o que o cliente quer e o que vc vai fazer para atender o problema. Ou se vc vai gerar outro problema com um site que não vai ficar legal na TV 4K que ele vai usar na loja por exemplo.
O BS 4 também não tem como tratar imagens com srcset, isso na verdade é no HTML, mas mesmo no CSS ele não sugere usar media queries para tratar tamanho de imagens para telas menores ou maiores, ele simplesmente sugere usar width:100% o que é muito superficial perto do poder total dos tratamentos que se tem com CSS puro. https://developer.mozilla.org/pt-BR/docs/Aprender/HTML/Multimedia_and_embedding/Responsive_images
Pontos positivos:
As vantagens do BS 4 é ter um grid em flex, usar medidas em REM e atualmente apresentou uma solução para Tipografia Responsiva, mas nada que você não possa fazer na mão. https://blog.getbootstrap.com/2019/02/11/bootstrap-4-3-0/#introducing-responsive-font-sizes
Independente de tempo para fazer, o valor do orçamento, vc precisa saber andar sem muletas! Resumindo o básico do CSS é indispensável e depender de FrameWork é um grande erro


How to overcome the IllegalAccessError while start up of connector in Kafka

Question: I am writing a connector for Kafka Connect. The error I see during the start up of connector is
java.lang.IllegalAccessError: tried to access field org.apache.kafka.common.config.ConfigTransformer.DEFAULT_PATTERN from class org.apache.kafka.connect.runtime.AbstractHerder

The error seems to happen at https://github.com/apache/kafka/blob/trunk/connect/runtime/src/main/java/org/apache/kafka/connect/runtime/AbstractHerder.java#L449
Do I need to set this DEFAULT.PATTERN manually? Is this not set by default.
I am using the docker image confluentinc/cp-kafka:5.0.1. The version of connect-api I am using in my connector app is org.apache.kafka:connect-api:2.0.0. I am running my set up inside Kubernetes.
Comment: Not that it matters, but Confluent 5.0.1 would be running Kafka 2.0.1 APIs
Answer: The issue was resolved when I changed the image to confluentinc/cp-kafka:5.0.0-2.
I already tried this option before posting the question, but the pod was in a Pending state and was refusing to start. I thought that it could have been an issue with the image. Upon doing some more research later, I came to know that sometimes Kubernetes is unable to allot enough resources and hence pods can stay in Pending state.
I tried the image confluentinc/cp-kafka:5.0.0-2 and it works fine.
Comment: Just to add to the information here, if you are using confluentinc/cp-kafka-connect-base image, using version 5.0.0-1 solved this issue for me.


Como não perder os dados incluídos nas Claims nas revalidações dos Cookies?

Question: Possuo uma aplicação que preciso controlar o acesso dos usuários que são de acordo com o perfíl de cada um. Empresa, Filial.
Na entidade Usuario eu adicionei os campos referentes à essas outras duas entidades e neles estarão as informações que representam cada um e seu perfíl de acesso.
public class Usuario : IdentityUser
{
    public int EmpresaId { get; set; }
    public int? FilialId { get; set; }

    public virtual Empresa Empresa { get; set; }
    public virtual Filial Filial { get; set; }

    public Perfil Perfil { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<Usuario> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

        userIdentity.AddClaim(new Claim(CustomClaimTypes.EMPRESA_ID, EmpresaId.ToString()));
        userIdentity.AddClaim(new Claim(CustomClaimTypes.FILIAL_ID, FilialId?.ToString() ?? ""));
        userIdentity.AddClaim(new Claim(CustomClaimTypes.PERFIL, Perfil.ToString());

        return userIdentity;
    }
}

Para controlar o perfíl dentro da aplicação eu carrego e obtenho as informações nas Claims do usuário, como mostrado no método GenerateUserIdentityAsync.
E então criei uma classe IdentityManager para ajudar a obter tais informações e atualizá-las quando preciso.
public class IdentityManager
{
    public IdentityManager(IIdentity identity)
    {
        Identity = identity as ClaimsIdentity;
    }

    protected ClaimsIdentity Identity { get; set; }

    public int EmpresaId
    {
        get { return GetClaimValue(CustomClaimTypes.EMPRESA_ID); }
        set { SetClaim(CustomClaimTypes.EMPRESA_ID, value.ToString()); }
    }

    public int? FilialId
    {
        get { return GetClaimValue(CustomClaimTypes.FILIAL_ID); }
        set { SetClaim(CustomClaimTypes.FILIAL_ID, value.ToString()); }
    }

    public Perfil Perfil
    {
        get { return (Perfil)Enum.Parse(typeof(Perfil), GetClaimValue(CustomClaimTypes.PERFIL)); }
        set { SetClaim(CustomClaimTypes.PERFIL, value.ToString()); }
    }

    public void Update()
    {
        var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
        authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, Identity);
    }

    private int GetClaimValue(string claimType)
    {
        int id;
        int.TryParse(Identity.FindFirstValue(claimType), out id);
        return id;
    }

    private void SetClaim(string claimType, string value)
    {
        var claim = Identity.FindFirst(claimType);
        if (claim != null) Identity.TryRemoveClaim(claim);
        Identity.AddClaim(new Claim(claimType, value ?? ""));
    }
}

Para atualiar os novos valores das Claims em IPrincipal eu executo authenticationManager.SignIn.
E isso funciona perfeitamente em toda a apliação até que o tempo para validação do cookie, conforme configurado no Identity, zera e a validação é refeita:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        OnValidateIdentity =
            SecurityStampValidator.OnValidateIdentity<AppUserManager, Usuario>(

                TimeSpan.FromMinutes(30), // <-- Revalida os cookies de 30 em 30 minutos

                (manager, user) => user.GenerateUserIdentityAsync(manager))
    }
});

Então, de 30 em 30 minutos os cookies são revalidados/reconstruídos como método GenerateUserIdentityAsync da classe Usuário, conforme também configurado no código acima, perdendo os dados que foram incluídos anteriormente.
A questão é que usuários com perfíl Empresa podem escolher mudar para o perfíl Filial, escolhendo a filial, para poder realizar operações para ela.
Por não ter acesso às informações atuais das claims dentro do método GenerateUserIdentityAsync, não consigo recolocá-los nas Claims.
Minha pergunta é:
Como eu poderia fazer para não perder as informações atuais das Claims nas revalidações dos cookies feitas nos intervalos de 30 minutos (conforme configuração)?
Estou usando o VisualStudio 2015 Community com o .Net 4.6.
Grato!
Answer: O problema dessa revalidação é que você não guarda as informações de sessão em lugar algum. É importante entender que Claims são diferentes de dados de sessão.
Há duas coisas que você pode fazer:

Serializar a lista de Claims e guardar isso dentro de Session;
Usar um servidor chave-valor como o Redis e trazer esses dados da preferência de usuário por lá (também serializando os dados e guardando como uma string única).

Seja qualquer caminho que você escolha pra seguir, antes de definir os Claims, faça uma verificação da existência da string e defina os valores primeiro pela string se isto for possível. Caso contrário, você simplesmente preenche novamente a lista de Claims, como já é feito.
Comment: Fiquei curioso quanto à tabela `AspNetUserClaims` se não dá para armazenar nela. Sinceramente, ainda não vi ela sendo usada. Grato pela resposta!


Query D6 db from D7 module

Question: I want to import a content type data from D6 db to D7.
I have db in settings file like....
<code>    /**
     * Database
     */
    $databases['default']['default'] = array(
      'driver' => 'mysql',
      'database' => 'd7',
      'username' => 'root',
      'password' => 'root',
      'host' => 'localhost',
    );
    $databases['d6']['default'] = array(
      'driver' => 'mysql',
      'database' => 'd6',
      'username' => 'root',
      'password' => 'root',
      'host' => 'localhost',
    );
</code>
I am trying to query nid's from D6 db from D7 module using db_query, but cant use node_load for D6 db then.
<code>    function import_schools() {
      db_set_active($key = 'd6');

      $result = db_query("SELECT nid FROM {node} WHERE type = :type AND nid         = :nid", array(
        ':type' => 'classified',
        ':nid' => '77307',
      ));

      while ($record = $result->fetchAssoc()) {
        print_r($record);
        print_r(node_load($record['nid']));
      }

    }
</code>
How can I chang API from d7 to d6 on fly while switching db using db_set_active.
Comment: You can't bootstrap D6 and D7 in the same request, too many identically named functions
Comment: Drupal's API isn't swappable, if you want to use the D6 API you need to bootstrap a D6 site
Comment: How to switch between bootstraps while file is on D7 root dir.
Answer: If you are looking to Migrate D6 Content (Nodes) to D7 system then you can use Drupal-to-Drupal data migration module.
Project page says

migrate_d2d provides a framework based on the Migrate API for
  migrating content from Drupal 5, Drupal 6, or Drupal 7 sites into the
  Drupal 7 site where it is installed.

Query D6 db from D7 module


fixest and glm iid standard errors for Poisson regression

Question: I am trying to manually compute iid standard errors for Poisson regression via the fixest package. Unfortunately, I fail to match fixest exactly - I am always slightly off.
Here's my implementation:
library(fixest)

base = setNames(iris, c("y", "x1", "x2", "x3", "species"))
base$y_int = as.integer(base$y)

est = fepois(
  y_int ~ x1 + x2 + as.factor(species),
  base,
  se = "iid",
  ssc = ssc(adj = FALSE)
)

glm_est = glm(
  y_int ~ x1 + x2 + as.factor(species),
  base,
  family = "poisson"
)

X = fixest:::model.matrix.fixest(est, type = "rhs")
Y = fixest:::model.matrix.fixest(est, type = "lhs")
weights = est$irls_weights
uhat = fixest:::resid.fixest(est)

XW = sqrt(weights)* X
XWX = crossprod(XW)
N <- nrow(X)
k <- ncol(X)

vcov1 = solve(XWX) * sum(
  weights * fixest:::resid.fixest(
    est, type = "response"
    )^2
  ) / (N-k)
diag(vcov1)

cbind(
  diag(vcov1),
  diag(est$cov.scaled),
  diag(est$cov.iid),
  diag(est$cov.unscaled),
  diag(vcov(est)),
  diag(vcov(glm_est))
)

# [,1]        [,2]        [,3]        [,4]        [,5]        [,6]
# (Intercept)                  0.134124672 0.136024583 0.136024583 0.136024583 0.136024583 0.136024583
# x1                           0.012744117 0.012924641 0.012924641 0.012924641 0.012924641 0.012924641
# x2                           0.007314296 0.007417905 0.007417905 0.007417905 0.007417905 0.007417905
# as.factor(species)versicolor 0.085225170 0.086432407 0.086432407 0.086432407 0.086432407 0.086432407
# as.factor(species)virginica  0.148401944 0.150504097 0.150504097 0.150504097 0.150504097 0.150504097

diag(vcov1) /   diag(est$cov.scaled)
# (Intercept)                           x1                           x2
# 0.9860326                    0.9860326                    0.9860326
# as.factor(species)versicolor  as.factor(species)virginica
# 0.9860326

The fact that all vcov elements are more or less off by a constant factor suggests to me that I am doing something wrong when computing the standard deviation $\hat{\sigma}$
diag(vcov1) /   diag(est$cov.scaled)
# (Intercept)                           x1                           x2
# 0.9860326                    0.9860326                    0.9860326
# as.factor(species)versicolor  as.factor(species)virginica
# 0.9860326                    0.9860326

What am I doing wrong?
Answer: The problem in the question are some mistakes in the computation of the estimate for the variance of the observations.
Poisson model
For a Poisson model we have $Var(y) = E(y)$ and the estimates of the variances are not based on the sum of squared residuals. Instead, it is based on the fitted Y values.
When using the following computations you get the right result
vcov1 = solve(t(X) %*% W %*% X)

That equation for vcov is based on https://en.wikipedia.org/wiki/Weighted_least_squares#Parameter_errors_and_correlation and the matrix for the weights and the matrix for the covariance of the observations cancel each other.
Quasi Poisson model
The equation that you used is related to the estimation of the dispersion parameter like here: https://stats.stackexchange.com/a/590724/
If you compute it like
vcov1 = solve(XWX) * sum(1/est$fitted.values * fixest:::resid.fixest(est, type = "response")^2) / (N-k)

And compare it with glm that uses a quassipoisson model
glm_est = glm(
  y_int ~ x1 + x2 + as.factor(species),
  base,
  family = "quasipoisson"
)

then you get the same result
                                    [,1]
(Intercept)                  0.0048002929
x1                           0.0004561092
x2                           0.0002617771
as.factor(species)versicolor 0.0030501903
as.factor(species)virginica  0.0053112733

And the result is much smaller than the previous case because the Poisson model greatly overestimates the variance of the observations.
Answer: I don't really understand the following small sample adjustment:
sum(weights * fixest:::resid.fixest(est, type = "response")^2) / (N-k)

The default VCOV has no adjustment:
diag(solve(XWX)) /   diag(est$cov.scaled)
#>                  (Intercept)                           x1                           x2
#>                            1                            1                            1
#> as.factor(species)versicolor  as.factor(species)virginica
#>                            1                            1


Can we make a mapping function from "sum operator" to "max operator" or inverse

Question: Suppose we have a knowledge base $K$ :
$$K=\{(\phi_i, \alpha_i) : i=1..n\}$$
Such as:

$\phi_i$ : are propositional formulas (CNF format for example).
$\alpha_i$ : are integers ($\alpha_i \in \mathcal{N})$.

And we have two functions $S$ and $M$, such as for each logical interpretation $\omega$ :

$M(\omega)= max\{\alpha_i : (\phi_i, \alpha_i) \in K, \omega \not\vDash  \phi\}$
$S(\omega)= \sum\{\alpha_i : (\phi_i, \alpha_i) \in K, \omega \not\vDash  \phi\}$

Can we define a function $F$ such that, for each logical interpretation $\omega$:
$$M(\omega)=F(S(\omega))$$
or
$$S(\omega)=F(M(\omega))$$
Can a such function exists? else, can we proof its nonexistence?

Example:
let $K=\{(a \lor b, 6), (\lnot{a} \lor c, 4), (c, 3), (a, 1), (\lnot{b},1))\}$ a knowledge base, consider the interpretation $ab\lnot{c}$, we have :

$M(ab\lnot{c})=4$
$S(ab\lnot{c})=4+3+1=8$
Answer: $S(\omega)=F(M(\omega))$ is not possible, consider $\{(a, 1), (b, 1), (b \vee c, 1)\}$. Then $M(\lnot a \lnot bc) = M(\lnot abc) = 1$, but $S(\lnot a \lnot bc)  \neq S(\lnot abc)$, and $F(1)$ can't possibly equal both values.
Can you provide a similar counterexample for $M(\omega)=F(S(\omega))$?
Comment: @youneszeboudj Yes, that is sufficient to show $F$ can't exist, at least not for arbitrary $\omega$. If $F$ exists it must be a function, and a function can't map the same input to multiple different outputs.
Comment: Thank you for your response!, yes, a similar counter example for $M(\omega)=F(S(\omega))$ is as follow : consider $K=\{  (a \lor b, 4), (a,5), (\lnot{c},9) \}$. Then we have : $S(\lnot{a}\lnot{b}\lnot{c})=S(a\lnot{b}c)=9$, and $M(\lnot{a}\lnot{b}\lnot{c})\ne M(a\lnot{b}c) (5 \ne 9)$, but are those two counter examples are sufficient to prove the non-existence of $F$, can't we exploit the definition of $M$ and $S$?
Comment: orlp right, thanks again


I need to access a derived class member through the base class static variable

Question: I need to access the derived class member variable through Base class variable.
Class A{

};

Class B:public A {
  int data;
};

now I need to do something like this
A *pb = new B()
pb->data = 10;

but the problem is I cannot access the Derived member class wihtout it.
and Yeah I know how to make it work with virtual functions.
Thanks, I really appreciate your help.
Answer: The need points to a faulty design.
But if you really insist writing bad code, you can just cast back to B *.
Comment: Yeah, actually my code doesn't have a situation like this. But was just wondering, if I have to do something like this.... But how come it makes a faulty design, so you mean, all the derived class members need to be initialized/modified only through constructors???? or through virtual functions???
Comment: @howtechstuffworks accessing a derived class member from a parent means something is wrong. Parent is a viable object on its own, and should be able to exist without any derived objects, unless its a pure virtual class. The correct way of doing it would be through virtual functions defined at the parent class level.
Comment: ^ Yeah thats how it works now, its an abstract class with pure virtual function....... But I wonder whats the difference between these two? We are going to change it anyway through virtual fucntions, why not use the same thing to datamember and change it directly..... my members are private, I am talking about an friend class....
Comment: @howtechstuffworks I believe that dynamic dispatch is only available for functions (because, amongst other reasons, there's only a single instance of the function per all the instances of the class in memory).
Comment: ^ @littleadv: Yeah I understand there are certain way of doing things, thats why we follow OOP, but I am trying to find a concrete answer for these situation.... Pardon me, if I was silly...\
Answer: Without virtual functions the only thing you could do is downcast it.  There's a few ways to go about that:

You can use dynamic_cast if you have RTTI enabled AND you have at least one virtual function in the parent class, which will let you check to see if the cast succeeded or not.
static_cast will let you cast to something below you in your inheritance tree, but you lose the ability to check if it succeeded.
You could also throw caution to the wind completely and use a C-style cast.
Comment: without virtual functions, dynamic_cast isn't available.
Comment: ^ Makes sense...... I was wondering,if we have something like virtual variables or something, which would make lives easier........ But dynamic cast is handy..... Thanks
Comment: ^ yeah..... I use virtual destructor.... Good catch.... Once again....  I didnt run into this kinda situation(yet), just let my imagination bird fly... I am sorry, if I am silly....
Comment: You should tag using @ when replying to someone. I didn't know you edited the answer. By pure luck I came back to this thread to change the vote.
Answer: Short answer: You cannot. Because your compiler does not know what pb is. it could be of type A. However, you an use dynamic_cast, which returns a B pointer or NULL if that is not possible.
A *pa = new B();
B *pb = dynamic_cast(pa);
if (pb) {
    pb->data = 10;
}
else {
    ...
}

Anyhow, if you need to do that it probably means that you should revise your design as upcasting is not a good idea. Sometimes though, you just cannot avoid it. E.g. when using external libraries and such.


How to fairly do tip pooling with uneven proportions of contributions?

Question: Imagine a restaurant where the servers each have shifts of the same length and pool the same proportion of their tips (e.g. 50%).
It's easy to calculate how much each server should receive from the pool at the end of the shift.  You divide the pool by the number of contributors, and they each get the same amount.
My question is whether it's possible to fairly pool tips when the servers have shifts of different lengths and where each server gets to elect ahead of time what proportion of tips to pool, from 0% to 100%.
For instance, you might have a pool like this:
<code>| Server      | Shift (hrs) | Total tips | % pooled |
| ----------- | ----------- | ---------- | -------- |
| Alice       | 4           | $80        | 50%      |
| Bob         | 8           | $100       | 25%      |
| Charlie     | 8           | $120       | 50%      |
| Diane       | 6           | $80        | 25%      |
</code>
Is there some way to weight each server's contribution based on shift length and proportion of tips pooled and come up with a distribution method that allows each contributor to receive a weighted-average payout?
(For context, I'm trying to work out a payment model for an app that allows workers to do tip pooling, and I'd like to determine whether they can specify what proportion of their tips to pool, or whether it has to be a static percentage.)
Answer: So the sole purpose of the pool is to redistribute tip money among the servers? If you are taking any money out for other purposes, such as tipping other staff who are vital to the restaurant's operation but don't get the chance to graft the customers themselves, then I would certainly recommend that all servers be required to submit the same percentage of their tips. Anything else would be unfair.
But if the pooled money is only redistributed to the servers, then consider the following:
Assign to each server a "stake", which is the percentage of their tips that they contribute, times the hours that they worked. Sum all the stakes to get the total stake. The amount of the pooled tips that each server receives is the ratio of their stake to the total stake.
In your example, let me add another column for the stakes:
<code>| Server      | Shift (hrs) | Total tips | % pooled | Contribution | Stake          |
| ----------- | ----------- | ---------- | -------- | ------------ | -------------- |
| Alice       | 4           | $80        | 50%      | $40          | 50% x 4 = 2    |
| Bob         | 8           | $100       | 25%      | $25          | 25% x 8 = 2    |
| Charlie     | 8           | $120       | 50%      | $60          | 50% x 8 = 4    |
| Diane       | 6           | $80        | 25%      | $20          | 25% x 6 = 1.5  |
| ----------- | ----------- | ---------- | -------- | ------------ | -------------- |
| Total       |             |            |          | $145         |           9.5  |
</code>
Now $\dfrac {\$145}{9.5} \approx \$15.26$, so the servers receive:
<code>| Server      | Stake | Return                |
| ----------- | ----- | --------------------- |
| Alice       | 2     | 2   x $15.26 = $30.52 |
| Bob         | 2     | 2   x $15.26 = $30.52 |
| Charlie     | 4     | 4   x $15.26 = $61.04 |
| Diane       | 1.5   | 1.5 x $15.26 = $22.39 |
</code>
The total is $\$144.47$. You can toss the remaining $53¢$ to the bellhop ;-). Or maybe just save it for tomorrow's pool. (And it is up to you whether you want to round to cents or dollars, or whatever.)
To consider it's fairness, note that Alice contributed the same percentage as Charlie, but worked only half the hours, so she gets only half the pay-out he does. And Bob worked the same number of hours as Charlie, but only contributes half the percentage, so he also only gets half the pay-out as Charlie. So in both cases, the proportion works out.
Now it might seem unfair that Alice loses money on the deal while everyone else gains. But no matter how this is done, it is a zero-sum game. Someone has to lose for anyone else to win. The only reason for participating is because the another day Alice might be the one collecting few tips, so she pays in now in hopes of future benefit. Overall, the idea is to even out the fluctuations, so that everyone has a dependable flow of income.
However, if someone regularly out-performs others, they have no incentive to participate. If Alice is attentive to her customers while Bob spends most of his time in the back goofing off, then Alice will be the loser every time, and is just subsidizing Bob's laziness with her hard work. So she would be wiser to keep her money to herself.


How do I generate a Azure table authorization token to use in my javascript file

Question: I want to make calls to my Azure storage table from my Javascript file.
Requirements -
1. no time expiration in the key.
2. Only read access
I don't want a SAS token because it is time based, so I need to generate a access key or something I can pass into the JS API with this limited read only access.
But working within my Azure dashboard, I can't seem to figure it out. Under my tables, I can see my access keys and connection strings. I can also generate a access policy for my table with just read permission.
Not sure how to combine the two...
Comment: SAS token has no limit on expiry time, e.g you can set end date as 3000-11-13. Is this acceptable?
Comment: Ya that will probably work. In my c# code where I create the SAS token, I tried leaving out the expiry time altogether. Meaning, I didn't set any value for that property, but the client side rejected it saying  something along the lines of authentication failed or format was not correct. So I guess I have to add it, even though it will be something like 3000-11-13
Comment: Correct, expiry time is required for generating a valid sas token.
Comment: So you decide to use SAS token eventually? If so, I think it is feasible in fact. Although it is not really permanent.
Comment: Hi Joy. What do you mean not permanent?
Comment: I mean the very far expiry time != absolute permanent, like 3000-11-13, actually it is not permanent. But it is enough for us to use it, no necessary to care about it. I will add it to my reply, if it is acceptable, you could mark it as answer.
Answer: If the solution need to meet the two requirements, I think it is impossible to do that.
The access policy just provides an additional level of control over service-level SAS on the server side and it is also time based, it will expiry.
If your case is for Blob and Queue storage, you can use RBAC to meet your requirements, register an AD App, add it as a Reader role in the Access Control (IAM) of the container or queue, and generate the access token with the AD App. Even so, the access token will also expiry, but the permission of the AD App to the Blob or Queue will not expiry, you just need to generate the token again with your code when necessary. If you want to absolute permanent, I think you could just use storage key nowadays.
For the Table storage, the RBAC is not supported currently, I found a feedback here, you could vote it. May be it will be supported in the future, until then, you could refer to the steps above, the logic should be similar.
Edit:
The above answer is for the requirement of absolute permanent( no time expiration in the key as you said), if you can accept the very far expiry time, like @Jerry mentioned, just specific the expiry time of a far time, like 3000-11-13, I think it will work fine.


When is $99^{(n+1)}$>$100^n$?

Question: Using logarithms, it doesn't seem all too hard to figure out that $99^{(n+1)}$>$100^n$ when n<457.21 approximately.  How does one figure out when $99^{(n+1)}$>$100^n$ without using a single logarithm?
Comment: [related/duplicate](http://math.stackexchange.com/q/103431/19341) for $n=99$?
Comment: The exact question you are asking is for which $n$ is $99> \left(1+\frac{1}{99}\right)^n$.  This occurs precisely when $\frac{\log 99}{\log\left(1+\frac{1}{99}\right)}>n$.  Presumably you can prove the inequality to the nearest integer (457) using inequalities based on the exponential, but this will likely just be a taylor expansion at some point "removing" the logarithm which is implicitly there. It is very likely that any other solution will just be hiding the logarithms in some way, since to even express the cut off point we need to use logarithms or equivalents.
Comment: Related, yes. Inspired by, quite possibly. Duplicate, no.
Comment: Presumably, you're not looking for "by using a calculator or computer to graph or to make a table of values."
Answer: $99^{n+1}>(99+1)^n={n\choose0}99^n+{n\choose1}99^{n-1}+{n\choose2}99^{n-2}$
$1>\frac{1}{99}+\frac{n\choose1}{99^2}+\frac{n\choose2}{99^3}+...$
Upper bounds for n can be derived from the first couple of terms. For example, $1>\frac{1}{99}+\frac{n}{99^2}+\frac{n^2-n}{2.99^3}$ is a quadratic which solves as $x<1294.9$
Comment: @DougSpoonwood Divide both sides by $99^{n+1}$
Comment: I don't see how the second line (1>...) comes into play here.
Answer: We can rewrite $99^{n+1} < 100^n$ as $99(99)^n < (99 + 1)^{n}$ and so $99 < (1 + \frac{1}{99})^n$.  Rewrite the right-hand side as $((1 + \frac{1}{99})^{99})^{n/99}$. The quantity inside is a bit less than $e$ (actually, the convergence is sort of slow!).  Taking a log (but just one!) we find that $e^{4.6} > 100$.  So when $n \geq 456$, the inequality holds. (Or almost holds, since I am underestimating $e$.)
Comment: I admit I did use the plural form of "logarithm", but I meant to ask how the problem can get solved without using a single logarithm.

When is $99^{(n+1)}$>$100^n$?


What limits are there on the number of reverse ssh tunnels?

Question: We have 100+ embedded boards that we need to talk to occasionally.
We've found the best way to do this reliably (there are some strange internet connections out there) is to have the boards open a few reverse ssh tunnels to our server.
Currently each board opens three tunnels, for a total of around 300. The tunnels are inactive most of the time .
Are there any performance implications of this?  Assuming we don't run out of ports or file descriptors, what is most likely to trip us up?
Edit: I'm primarily concerned with having several hundred inactive clients connected at once.  Only a few of the tunnels will be in active use at any one time.
Comment: I'm curious about the need to open 3 tunnels per machine. Care to enlighten me?
Comment: One tunnel is for ssh, the other two are for services running on the clients that we need to connect to.  Currently we pull, rather than push data.
Comment: Just curious because I'd like to do the same - are you using some special software to manage all of this? Or do you open these tunnels manually?
Comment: Nothing very special, mainly bash scripts and monit.
Answer: The limit on active SSH connections is 65,534 minus the number of TCP ports in use on your system -- If we want to be conservative let's just say 60,000 (or for most practical purposes "Unlimited"). You may bump up against other system resource limits however, depending on the machine you're connecting to.
That said you might want to economize on the number of tunnels (do you really need three connections per board?), and if you don't always need the connections up you might want to have the remote site initiate them only when needed.
Comment: It's the other system resource limits I'm interested in.  What might they be?
Comment: It's impossible to enumerate every system resource that can be exhausted - This is like asking for an exhaustive list of why a computer won't boot (the hardware fault tree alone would be a book). A few of them in rough order of likely exhaustion: max number of logins per user (if set), max number of logged-in users system-wide, max number of open filehandles, RAM, network bandwidth, CPU
Comment: I know - but first on the list are things like 'Is it plugged in?'  I didn't know about any logged-in user limit, so if I check that's ok I think we'll be good for a while.  Thanks.
Answer: TL;DR: memory. Rest is okay (for hundreds of tunnels).

Assuming we don't run out of ports or file descriptors,
  what is most likely to trip us up?

I think it is safe enough to answer: memory.
A quick experiment shows 4.6 megabytes of actual memory consumed per incoming connection. Part of it may be shared, a real experiment would tell. Fix: add swap space.
Also, 86 megabytes of addressing space which is quite big.  It's very probably shared, or a 32-bit server would have addressing space exhaustion before 50 connections. Fix: use a 64-bit OS.

Assuming we don't run out of ports or file descriptors,

Does this assumption hold true?

At the range of hundreds, ports won't be a problem, unless your server is also a high traffic server for something else.
File descriptors might get exhausted. A quick experiment shows 21 file descriptors consumed per incoming ssh connection, not counting a shell. The limit on file descriptors can be tuned system-wide, so it should not be a real blocker.

(Experiments done on a 64-bit Debian server.)
Answer: There are also systems that create the reverse tunnel on demand, when you need to connect to a particular remote computer. These include AWS IoT Secure Tunelling and open-source software that I wrote for the same purpose. These eliminate the concerns of having too many reverse tunnels simultaneously open.
My system uses MQTT connections (more specifically, AWS IoT Core, which is a secure MQTT broker with security policy for each client) to tell remote computers to open a reverse SSH tunnel to a proxy using a random port on the proxy. Once the tunnel is open, the remote computer reports back to your laptop/desktop the port number, and the software now establishes a tunnel through the proxy all the way to the remote computer; you do not need to log in to the proxy. Scalability is constrained by the number of active SSH connections to remote computers, not by the total number of remote computers that you can connect to.


Cloning entities

Question: i have 3 different entities build with help of EntityApi module. They connected with each other with ID column  in tables.
<code>Entity - "Purchase"
Entity - "Catalog" has 'purchase_id' column in table
Entity - "Product" has 'catalog_id' column in its table.
</code>
What is the way to clone in one click some already active "Purchase" with all catalogs and product which it ccontains?
Answer: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Entity.php/function/Entity%3A%3AcreateDuplicate/8.2.x
Check that out. You can use it by doing something like:
<code>// Load the entity you want.
$entity = \Drupal::entityTypeManager()
 ->getStorage('my_entity')
 ->load('1');

// Copy it.
$duplicate = $entity->createDuplicate();
$duplicate->save();
</code>
Answer: I believe node_clone can clone entities and their fields for you. There is an API to call it programmatically, or if you have Admin pages created for your entity I believe you can make a "save and clone" or "clone" button show up there.
Comment: Both not good for me. Lets say i have in purchase 3 catalogs with 100 products in each. Clone one by one manually not the way to do it. I would like to have script which will do it automaticcaly.
Comment: what? node_clone clones the 1 entity and any sub-data as well.  If you want to script it write a small php script (I did not small Module) and run that script via Drush. Or, make a module and use like views_bulk_operations module and node_clone. If you're cloning *anything* node_clone is the way to go. Good luck finding another approach ...
Comment: Thank you i will check node_clone more thoughrely may be i missed  something.

Cloning entities


Legder Nano S can't effective authorization

Question: I use ledger nano S for https://wallet.betanet.near.org/, and the ledger nano S successful configuration. after I delete all key from my account and just keep 1 Full Access Key(create by ledger nano S).
Now I can't add other fullaccess key. Whatever method is used.when I did: near login --useLedgerKey. the web verify page will show:
An error occurred while approving this action. Please try again!
When I did add Seed Phrase enable, on the [Enter the following word from your recovery phrase to complete the setup process.] page, When I confirm it in the Ledger it will show:

An error occurred while setting up seed phrase recovery. Please try again!

Actually , my ledger still will show confirm info:

DANGER: This gives full access to a device other than Ledger

when I make a transaction  push √ button. it still show the error:

An error occurred while approving this action. Please try again!

I think it's a bug, when use just keep 1 access key form ledger nano S.
enter image description here
enter image description here
my account : catcatcat.test
Comment: I'm struggling to understand what you're asking. Might you consider rephrasing?
Answer: This is probably an error on the NEAR Wallet side. If you don't mind me asking, what is your account ID? I can better understand what is happening by viewing the chain activity associated with this.
Comment: catcatcat.test.
For "an error on the NEAR Wallet side" I think so. because I use near cli
 by ledger nano is correct.
Answer: Unfortunately it takes time to get new app version published in Ledger Live (even in Developer Mode). First version that got published (1.0.0) has the bug with adding full access keys.
As far as I know this bug is fixed in latest version available here:
https://github.com/LedgerHQ/app-near/pull/2
Best shot for now is to try compiling it from source following instructions in README:
https://github.com/LedgerHQ/app-near/blob/6a8d3263896fdf65ac06961c6e7ed6a9912d5480/README.md
Comment: @NIUNIU 932d214 isn't latest commit, it is still v1.0.0 so expected to have the same issue. Check https://github.com/LedgerHQ/app-near/commits/master – Ledger has merged latest changes. Ledger Live update coming soon.


User Registration Module for Drupal

Question: Drupal uses email for user registration purpose. Instead of the out-of-box Drupal user registration that requires user to specify a username and email address, I want a full-fledged user registration form ( with captcha, user profile etc, like yahoo or gmail registration) for my website.
Is there a module that does that?
Answer: There are a couple of options for this.
To get profile fields the most common solution is the profile module included in Drupal core. Go to Administer > Site building > Modules and enable it under core-optional.  Then you can configure the Profile module at Administer > User settings > Profile and in the settings you can say whether the fields will show during registration or not.
To get a captcha during registration you will need one of a couple of modules:
I prefer HCaptcha because it works very well and even can earn you some money, but it sends your content to an external site to do some verification.
There is also Captcha which provides integration with other options.
Comment: Blech. Not really. Content profile is a bunch of overhead. If core profile works well for the user's needs (which it does in this case) then it is much simpler than content profile. "Content profile creates nodes" but Nodes are not always better!
Comment: Using the content profile module is a better choice instead of the standard profile module. The content profile creates nodes.
Answer: The typical choice for this is to use a combination of content_profile to create the user profile as a node, content_profile_registration, a component of content_profile, to create such a profile at registration using such a full-fledged node edit form, and possibly auto_assign_role if you have multiple types of users with distinct profile types.
For the captcha part, Mollom is an interesting service, as Greggles suggested, but you might also want to consider reCaptcha, which is good too at even doubles as a public service.
Answer: It would appear that the recommended process now is creating fields. From the Drupal site:

The Profile module is deprecated in Drupal 7. It is kept around only
  to provide an upgrade path for Drupal 6 sites that used it. Use of the
  Profile2 module or creating fields directly on the user entity is
  recommended in Drupal 7.
Answer: ReCaptcha for sure.
You can also have the simple core profile fields show up in registration if you want to stay lean. Though this often requires you to theme user_profile.tpl.php if you want that page public.
PS: The Email Registration module may be of user, as well as LoginToboggan.
Answer: With regards "full-fledged user registration form", you can go to Admin >> Use Management >> Profiles then create/customize your fields and make sure that you tick the "Visible in user registration form" option.
Answer: If I edit user_profile.tpl.php then I can easily maintain registration part as I want.
<?php
   // Validate the username:
   if (user_access('change own username') || user_access('administer users') || arg(1) == 'register') {
     if ($error = user_validate_name($edit['name'])) {
       form_set_error('name', $error);
     }
     else if (db_num_rows(db_query("SELECT uid FROM {users} WHERE uid != %d AND LOWER(name) = LOWER('%s')", $uid, $edit['name'])) > 0) {
       form_set_error('name', t('The name %name is already taken.', array('%name' => $edit['name'])));
     }
     else if (drupal_is_denied('user', $edit['name'])) {
       form_set_error('name', t('The name %name has been denied access.', array('%name' => $edit['name'])));
     }
   }
?>

User Registration Module for Drupal