Potentially cancel all other submit handlers after my own

Question: I've unshifted my own submit handler to the #submit handler of a node form. I already have a validation handler, so I can't execute my cancelling submit handler there.
Maybe this makes more sense:

my validation
all other validation
my submit handler, which potentially kills the submit process to form_state[rebuild] => TRUE and try again
all other submit handlers

Is that possible? I can cancel submission if I put my submit logic in a validation, but that's too soon. It should only run when all validation passes.
Comment: This sounds like an interesting question, but I can't quite follow what you are trying to accomplish?  Can you provide a little background as to what you need to do?
Answer: Ensure that your implementation of hook_form_alter() is the last one to be called. Your implementation of hook_form_alter() can then unshift one validation function and push a second validation function. The second validation function would then have complete information about whether other validation functions objected to saving the node (by calling form_get_errors()).
You can ensure that your your implementation of hook_form_alter() is the last one to be called by implementing hook_module_implements_alter()
Comment: DUH! Two validation functions! OMG I suck. My module has a high weight, so it'll be last. Thanks man.


How does size of test set affect the performance of a model?

Question: My data set is divided into 80:20 train and test...i have performed 10 fold cross validation on the train data set and tested the 20 % dataset on each iteration ( so that test set is not touched while training). Finally i get the scores by averaging the scores in each iterations.
I have been trying classification on a 7 class problem. I have 8 sensors generated data .(8features). Every time the classifier misclassifies the last class. I tried decreasing the number of classes, still the last class got miss classified.
 Finally i started decreasing the test set to increase training. I got good results (90%accuracy) when test data is only 8%.
Is any other way around or any scope of increasing scores without further decreasing the size of the test set?
 following are the snipets of the two cases
Comment: How does the distribution of your classes look? Have you examined the class distributions in the entire sample and then in such smaller subsamples?
Comment: The classes are distributed almost equally, plus-minus one or two raws between the subsamples
Comment: How is the accuracy in both cases per class? It could of course be that due to a smaller training partition resulting from a bigger test partition, the fitted model generalizes worse than with a bigger training partition, but this depends strongly on the problem and the sample size we're talking about. On the other hand, it might as well be that your smaller test sets merely present a more 'accomodating' sample for your model. This is something we cannot really answer without speculation. You could investigate both angles and report what you find, maybe then the picture gets clearer.
Comment: i have added a confusion matrix and some scores as an image. Regarding your view on training and test partitions, i will check and surely report. thanks
Answer: Generally speaking, with more training data, the model will learn the underlying distribution of the real data better. Since a larger training set in your case improves the performance of on training and test set, you should get more data if you can. The performance on the test set might not be that reliable if your test set is small. In other words, your performance might be different if you change to another test set. That is one of the reasons that you perform cross validation. I suggest you also take a look at the CV accuracy.
You should also take a look at the class distribution in your training and test set. If there are only a few data points for the last class, the classifier will not able to learn well. You can upsample the minority class to make the classifier work better.
Answer: You have a pretty small dataset from the start. You need to consider 2 considerations:

You want to maximize the training set since it increases the model's chance to learn a real result that generalizes.
You want to maximize the test set since the bigger it is, the better it represents the model's ability to generalize.
for example, in the extreme case of 1 sample in the test set, it obviously doesn't represent the model's performance out of sample.

I personally don't like going below 20% in small datasets, but it depends on the problem domain and your experience with the domain and data.
I would check how the data is split into train and test sets. because what might happen is that the train set is from a different distribution than the test set.
For example let's assume your sensors measure temperature,
if you split by time, and your 80% are data from January-October, and the test is from November-December, then class 8 might occur in the train set when the temperature is above 20 degrees, but in the test set it's only below 20 degrees.
Now that you add Nov. to the train set by decreasing the test set to 8%, you shift the training distribution to include samples where class 8 occurs below 20 degrees,  thereby improving your accuracy on the test data.
So my guess is there's some kind of shift in the features representing the problematic class between test and train. You can look into data drift for further information.


Xcode 5 Error will never go away

Question: - (IBAction)buttonPressed {
  count++;

  scoreLabel.text = [NSString stringWithFormat:@"Score\n%i", count];
}

Following off a beginners ios tutorial. He uses xcode and doesn't recieve this error. I receive the error just after (IBAction)buttonPressed saying i need to put in a ; but it doesn't have a ; and when I do put a ; in it doesn't do anything! Please help!!
Comment: Please add the exact error message to your question. Also, how and where is `count` declared?
Comment: The error message is "Expected ';' after method prototype."
And count is declared up above. Count is declared as
NSInteger count;
Answer: The error is because the method is declared in the interface, not the implementation.
Here is what you want:
In the .h file
@interface YourClassNameHere : SuperClassNameHere {
    int count;
}
@property (weak, nonatomic) IBOutlet UILabel *scoreLabel;
@end

In the .m file
@implementation YourClassNameHere
- (IBAction)buttonPressed {
    count++;
    self.scoreLabel.text = [NSString stringWithFormat:@"Score\n%i", count];
}
@end

The IBOutlet property scoreLabel needs to be connected to the UILabel.
Comment: While tutorials are nice it is best to start with a good foundation knowledge of the "C" and Objective-C languages. There are books and even Apple supplies good documentation on Objective-C.
Comment: Its in ViewController.h There is no implementation
Comment: Methods have to be in the `@implementation` not in the `@interface`, that is the problem. The implementation should be in a .m file.
Comment: Found out I have to start everything all over again. Thanks misleading tutorials...

Xcode 5 Error will never go away


How to find difference between two arrays in PHP?

Question: Here is array 1:
Array ( [ABC01] => 10.123.456.78
        [ABC02] => 10.123.456.79
        [ABC03] => 10.123.456.80
        [ZYX99] => 10.123.456.81
      )

Here is array 2:
Array ( [0] => ABC01
        [1] => ABC02
        [2] => ABC03
      )

I'm trying to find the difference between these two arrays and return the following (as you can see, the host name and then the corresponding ip address of an item not found in array 2):
Array ( [ZYX99] => 10.123.456.81)

I've been looking through the different PHP array functions and am overwhelmed by the amount of them: http://www.w3schools.com/php/php_ref_array.asp
Comment: http://stackoverflow.com/questions/10077840/difference-between-two-arrays
Answer: This should work for you:
(Here I just used array_diff_key() to get the difference of the keys. The second array I flipped with array_flip() so to change the values to keys)
<?php

    $arr1 = array(
            "ABC01" => "10.123.456.78",
            "ABC02" => "10.123.456.79",
            "ABC03" => "10.123.456.80",
            "ZYX99" => "10.123.456.81"
    );

    $arr2 = array("ABC01", "ABC02", "ABC03");

    $result = array_diff_key ($arr1, array_flip($arr2));
    print_r($result);

?>

Output:
Array ( [ZYX99] => 10.123.456.81 )

Comment: Thanks for this! Unfortunately, this is not outputting the host name,just the ip (Array ([0] => 10.123.456.78). I'll look into it further.


Linear independence of matrices $I, A, A^2$

Question: I want to prove that $I,A,A^2\:$matrices $\in M_{2\times 2}$ are $\textit {linearly independent}$.
I consider the following matrices and their "corresponding" vectors:
$I=\begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}\to (1,0,0,1)$
$A=\begin{pmatrix} a & b \\ c & d \end{pmatrix}\to (a,b,c,d)$
$A^2=\begin{pmatrix} a^2+ b c & ab+db \\ ac+dc & d^2+bc\end{pmatrix}\to (a^2+bc, ab+db, ac+dc,d^2+bc)$
What I am trying to do, is to prove that these vectors are $\textit{linearly independent}$.
For that direction, I want to prove that (at least) one $3\times 3$ determinant is $\neq 0$.
It seems that all $3\times 3$ determinants $\left( e.g. \begin{vmatrix} 1 & 0 & 0\\ a & b & c\\ a^2+bc & ab+db & ac+dc\end{vmatrix} \right)$ are equal to zero! What am I really missing?
Comment: As it seems, there must be a typo in the exercise! Question: Does my way of thinking prove just the opposite?
Comment: Did it occur to you that in (a2+bc,ab+db,ac+dc,d2+bc) (ab+db)c=(ac+dc)b ?
Answer: The thing you're trying to prove is not true. Consider the case $A = I$.
More generally, if $A$ is any $2 \times 2$ matrix, then you can compute its characteristic polynomial, $c(x)$, the determinant of $A - xI$. That will be some quadratic polynomial in $x$, like
$$
3x^2 - 22 x^1 + 8x^0.
$$
It turns out that if you plug in $A$ for $x$ , and treat the $A^0$ as $I$, you'll get a $2 \times 2$ matrix...that's the zero matrix! That's called the Cayley-Hamilton theorem.
As an example:
$$
A = \begin{bmatrix}1 & 3 \\ -1 & 1 \end{bmatrix} \\
A- xI = \begin{bmatrix}1-x & 3 \\ -1 & 1-x \end{bmatrix} \\
c(x) = det(A - xI) = (1-x)^2 + 3 = x^2 -2x + 4
$$
Now plug $A$ into $c$ to get
$$
c(A) = A^2 - 2A + 4I \\
 = \begin{bmatrix} -2 & 6 \\ -2 & -2 \end{bmatrix} -  \begin{bmatrix}2 & 6 \\ -2 & 2 \end{bmatrix}  +  \begin{bmatrix}4 & 0 \\ 0 & 4 \end{bmatrix} \\
= \begin{bmatrix}0 & 0 \\ 0 & 0 \end{bmatrix}
$$
Comment: Or the case of any projection matrix $A$ (so $A^2=A$).
Comment: Or in the case of a general $2 \times 2$ matrix: $A^2 - (a+d)A + (ad-bc)I = 0$.
Answer: First of all your matrix is a root of its characteristic polynomial . The bad news is that its square is linear dependant from its lower order terms. The good news is that the algebra generated by this matrix (if its characteristic polynomial is irreducible which it's mostly is) is the splitting field of its roots.


Find at least one first order differential equation from general solution

Question: How can I find at least one first order differential equation when the solution for it is $y = x^4$?
Thanks for your help :)
Answer: Most basic equation would be simply $ \frac {dy}{dx}$ = 4$x^3$
with initial condition that y(0)=0
You can get infinite solutions by introducing some constant terms or some specific f(x), and restricting them with specific initial conditions.
For eg. take $$ \frac {dy}{dx}  = 4x^3+k$$ (where k is some constant)
So, $$dy=(4x^3+k)dx$$
integrating both sides,
$$y=x^4+kx+c$$
Now, use y(0)=0
How about taking $$ \frac{dy}{dx} = (4x^3 + px^q + r)?$$
$$y=x^4+ \frac {px^{q+1}}{q+1}+rx+c$$
Again, y(0)=0
Comment: Can you find more?
Comment: edited...just keep changing k and you get infinite solutions


Changing the default method parameters IntelliJ creates

Question: I'd like to change the default generated parameters by IntelliJ when I ask it to automatically create a method.
For example if I write the following (it's just an example, this question isn't about using List instead of ArrayList), before the method generate() is created:
generate( new ArrayList<String>{}, 42 );

and ask IntelliJ to create the method, it creates this:
private void generate( ArrayList<String> strings, int i ) {
}

But I'd like to have this instead:
private void generate(
    @NotNull final ArrayList<String> strings,
    final int i
) {
}

In other words I'd like:

every primitive to be preceded by the final keyword
every non primitive to be preceded by the final keyword
every non primitive to be preceded by the @NotNull annotation
(ideally) every parameter to go on its own line

How can I do this?
Answer: Go into the settings and have a look at the code formatting for most of this.
I'm not sure about the @NotNull or final choices.
UPDATE: I think @NotNull annotation will show up if you tell IntelliJ that you want JDK 6 or higher language features.  This means that you have to compile with JDK 6 or higher, of course.
The rest should be under code style settings.  Or file or method templates.
Comment: thanks, I did find a *"Make generated parameters final"* option in *Settings* / *Code Generation*.  Still looking for the rest : )


Question About Compact Space in Topology

Question: I am really confused about below questions. Actually, I did some inferences but I am not sure. Thank you
(i) Show that T = {A ⊂ R | 1 ∉ A } ∪ {$\mathbb{R}$} is a topology on $\mathbb{R}$ and show that the space ($\mathbb{R}$, t) is a compact space according to this topology.
Thank you for now.
Comment: An open cover of $T$ must contain an open set $U$ such that $1\in U$, so…
Comment: I didn't exactly undestand what you mean...
Comment: You should add to your question what you have tried so far and where you're stuck at. Working exercises is a good way to learn mathematics and simply providing a full solution wouldn't help you. You need to (1) prove that $T$ is a topology; (2) prove that any open cover of $\mathbb{R}$ by sets in $T$ has a finite subcover.
Answer: Let $\mathcal{U}$ be an open cover for $\Bbb R$ in this topology. In particular there is an $U \in \mathcal{U}$ such that $1 \in U$.
By the definition of the topology $\mathcal{T}$ the only open set that contains $1$ is $\Bbb R$ itself. So $U = \Bbb R$ and so $\{U\}$ is a (very) finite subcover of $\mathcal{U}$. So the space is compact : every open cover has a finite subcover (always the same boring one in this trivial case).
Answer: Let $T=\{A\subseteq\mathbb R:1\notin  A\}\cup \{\mathbb R\}$ be a topology on $\mathbb R$. First we show that it's indeed a topology.
(i) Observe that $\emptyset,\mathbb R \in T$ (because $1\notin \emptyset\implies \emptyset\in\{A\subseteq\mathbb R:1\notin  A\}$).
(ii) Let $\mathcal A=\{A_i\}_{i\in I}$ be a family of open sets in $T$. Since $\forall i\in I$, $A_i\in T\implies 1\notin A_i\forall i\in I$.
Therefore we can state that $1\notin \underset{A_i\in\mathcal A}{\bigcup}A_i\implies \underset{A_i\in\mathcal A}{\bigcup}A_i\in T$.
(iii) If we now consider $A_1,A_2\in\mathcal A\implies 1\notin A_1,A_2\implies 1\notin A_1\cap A_2\implies A_1\cap A_2\in T$, hence $T$ defines a topology on $\mathbb R$.
Let $\mathcal F$ be a family of open sets that covers $\mathbb R$, then $1$ will be neccesairily in $\mathcal F$, so $\mathcal F$ must contain all the real line.
In other words, if $1\in \mathcal F$, then $\exists A\in\mathcal F:1\in A$, but the unique open set that contains the point $\{1\}$ is $\mathbb R\implies A=\mathbb R$. Since $\mathcal F$ was a generic family of open sets that covers $X=(\mathbb R,T)$, it follows that $X$ is compact because we can always find the open sub-cover $\{A\}$.
Comment: Thank you for instructive solutions. But I have really some essential information deficiencies about this topic. I would be very grateful if you could explain the final part.
Comment: Ok I edited my answer. Let me know... :-)


How to stop notification panel from hiding?

Question: I want to make a notification with buttons. But after click on button- notification panel is hiding. What shall I do?
I'm using this code to create my notification:
public class MyNotification extends Notification {
private Context ctx;
private NotificationManager mNotificationManager;

public MyNotification (Context ctx, int layaut_id) {
    super();
    this.ctx = ctx;
    String ns = Context.NOTIFICATION_SERVICE;

    mNotificationManager = (NotificationManager) ctx.getSystemService(ns);
    CharSequence tickerText = "Shortcuts";
    long when = System.currentTimeMillis();

    Notification.Builder builder = new Notification.Builder(ctx);
    Notification notification = builder.getNotification();
    notification.when = when;
    notification.tickerText = tickerText;
    notification.icon = R.drawable.ic_launcher;

    RemoteViews contentView = new RemoteViews(ctx.getPackageName(), layaut_id);

    //set button listners
    setListeners(contentView);

    notification.contentView = contentView;
    notification.flags |= Notification.FLAG_NO_CLEAR;
    CharSequence contentTitle = "From Shortcuts";
    mNotificationManager.notify(1387, notification);

}

Answer: Probably your notification is autocancelled when you click on it.
To disable this add:
builder.setAutoCancel(false);

Answer: Use setOnClickPendingIntent() on buttons' views.
setOnClickPendingIntent


Recommendation for a MIDI controller keyboard with 88 keys and piano-weighted action

Question: I'd like to buy a keyboard instrument with a piano touch, 88 keys, and a midi output, and otherwise extremely minimal features (no built-in speakers or sound synthesis, etc.).
I'm hoping this will allow me to experiment with different sounds over the lifetime of the keyboard rather than being locked in with the sounds that are normally built in to a digital piano. By moving the sound production out of the keyboard, I expect it would also be lighter and easier to transport (several smaller components instead of one large keyboard).
Are there keyboards like this available? How would I go about finding a keyboard with these features? Are there any good resources relevant to midi and keyboards to help me learn more?
Comment: The answer is the same as the one you asked before. You need to go to a music store and test out the keyboards and see what you like and what options are available. Then if you really want you can try to find the one with all the features you desire online, but it may not be what you want.
Comment: I feel that this question is different because that question asked if such a keyboard is a good idea, whereas this question asks if such a keyboard is available and how to go about finding such a keyboard.
Answer: It is possible that you are making a couple of incorrect assumptions. Let's check it out.
First, you said "I'm hoping this will allow me to experiment with different sounds over the lifetime of the keyboard rather than being locked in with the sounds that are normally built in to a digital piano."
Having built-in sounds will not restrict you. Most stage pianos can work with either internal sounds or with external sounds using MIDI. The external sounds can be a hardware synthesizer module or a soft synth running on a computer.
In that regard a keyboard with internal sounds is more flexible than a keyboard without sounds.
You said that "By moving the sound production out of the keyboard, I expect it would also be lighter and easier to transport (several smaller components instead of one large keyboard)."
The heavy part of the keyboard is the piano action. A true 88 key hammer action may weigh 40 -60 lbs. That is heavy.
The built-in sounds are just a circuit board that adds no weight. But if you carry a separate sound module or a laptop you are adding both weight and several cables to the mix.
In many cases you will be better off with a keyboard that has sounds in it. When you are in your studio, you can use a computer for the sounds but when you are transporting the keyboard you can use the internal sounds and save a lot of hassle.
As far as speakers are concerned, you also have the opportunity to bypass them in the studio and use them on the road. I have a keyboard which has speakers in it. They are fine for a small room and casual use. When I am playing in other venues I hook up external speakers as I do in my studio.
Decent speakers can be quite heavy. In the studio I use near field monitors. When I am gigging I use a heavy duty amp and speakers that in sum add about 100 lbs.
However, when I play at a friends house or informally, I use a keyboard with built-in speakers. At first I didn't want them but now I am glad that I have them.I can just pop the keyboard into the trunk and go. Much easier.
If you are not a very experienced pianist and don't require the nuances of a fully-weighted piano action, there have recently been a number of excellent keyboards that have excellent touch without a fully-weighted action. These keyboards weight around 20 lbs so are really portable. Casio and Yamaha make keyboards like this and they are worth a look. Check out the reviews in Electronic Musician and Keyboard magazines.
Wheat Williams suggests you need a "a three-pedal foot controller with half-pedal action." This is nice to have but you may be fine with a single damper pedal. That's a lot lighter and unless you use the other two pedals (I rarely do) it's just fine. You will find there are some nice ones that look and function like acoustic piano pedals and others that are just foot switches. I strongly recommend the former. Make certain that the pedal matches the keyboard you select. Yamaha uses different polarity from other keyboard manufacturers so look at the specs carefully. Some pedals have switchable polarity.
So think about how you will use the keyboard. If you never take it with you, you don't need internal sounds or integral speakers. But if you do, you many want to consider them. Keyboards and MIDI are flexible and you can use or ignore internal sounds and speakers as the situation dictates.
Answer: You want a MIDI controller keyboard, interfaced to a computer, and running virtual instrument software on the computer.
First you need a MIDI controller keyboard with 88 keys and piano-weighted action, and a three-pedal foot controller with half-pedal action.
There are many on the market, by many manufacturers. Here is a list of some models for sale at Sweetwater.com in the US.
Then you need several other components:

A suitably fast computer
A fast external hard drive
An external audio interface
High-quality stereo speakers with built-in amplifiers and
possibly a subwoofer
Suitable virtual instrument piano software
Suitable virtual instrument software for making other kinds of instrument sounds, such as those of other acoustic instruments and of synthesizer sounds

See this answer:
https://music.stackexchange.com/questions/12576/recommendation-for-a-computer-based-virtual-instrument-for-an-acoustic-piano-sou
Since, by going this route, you will need to purchase several components, you must visit local music stores and learn about what they sell.
On this site, we are not equipped to give you numerous recommendations on so many different components, such as the vast array of virtual instrument software, hardware audio interfaces, hard drives, speakers and amplifiers, etc. This site, as its title suggests, is for questions about learning to play instruments, and learning about making music. If you need extensive recommendations for numerous components of a digital music-making system, you should look to other sites.
Comment: I will try to stay more focused on the intended topic of this site from now on.
Answer: The same question was pondering me for almost 6 months until I have made my final purchase decision.
At the end it came down to deciding between the three models:

Roland A-88
Kawai VPC-1
Akai MPK-88

My requirements were as follows:

Should not be as minimal as possible, but wanted pitch/bend and at least a knob/slider for volume control.
Budget considerations (< 1k Euro).
Good build quality.

At the end, I have bought the Roland A-88. Why? The Kawai was too minimalistic and above 1000 Euro. The Akai was too overloaded with controls for my taste. I know myself ... I would not practice my piano routines but rather playing around with all those pads, sliders and knobs.
That would have been enough to decide basically, but the most important is to get a feel for the key action before you buy anything. I could only test the Roland in a shop and loved it the very first moment. This is very subjective no one can give you a recommendation for.


Probability of winning sweep stakes, put all coupons in one box or split them between boxes?

Question: Taken from : here
A mall has sweep stakes where they give you a coupon for every X dollars you spend (amount is not important). You fill the coupon with your contact details and put it in the box. Every two weeks, they draw 10 coupons, give their owners prizes, and discard the rest of the coupons.
Now, thanks to some very big purchase we made, we have about 300 coupons (going to hurt when filling them). To get the highest probability of winning, should we put all the coupons at once, or split them evenly between the three remaining draws?
Comment: Yes, I posted there earlier today, but realized the people at Yahoo! answers aren't as brilliant as people here.
Answer: Let's assume that in each box there are n other tickets besides yours. So if you put them all in the first box and 10 tickets are drawn your chance of winning something is
$$q = 1 - \prod_{k=1}^{10} \left( 1 - \frac{300}{n+301-k} \right).$$
Now if you split them, 100 each amongst three boxes (where, again, each box has n other tickets), your chance of winning something is
$$p = 1 - \prod_{k=1}^{10} \left( 1 - \frac{100}{n+101-k} \right)^3 .$$
Now p>q, but only slightly, for large n.
For example, with n=10000, $$p \approx 0.258176 \textrm{ and } q \approx 0.256004$$
So you're slightly better off if you split them up into three lots of 100. However, this assumes that the number of other tickets placed in the box every two weeks remains constant.
Note that the difference between p and q decreases with increasing n.


What does "factor out" an ideal mean?

Question: I am studying this article. In proving Theorem 2.14—

Let $R$ be an $\alpha$-ring and $S=R[x,\alpha]$. Then $S$ is $\alpha$-Jacobson if and only if $R$ is $\alpha$-Jacobson

—the author says that:

. . . we can factor out $(P \cap R)S $, which is contained in $P$, and assume that $P \cap R = 0$

(where $P$ is an $\alpha$-prime ideal of $S$).
I don't understand what this "factor out" means. Any help would be great.
Comment: See [this answer.](https://math.stackexchange.com/a/3716/242)
Comment: @BillDubuque, I read your answer. I didn't understand the following : "For example, in many ring theoretic problems involving an ideal I, one can reduce to the case I=P prime, then reduce to R/P, **thus reducing to the case when the ring is a domain**."  How can we reduce to the case when R is a domain?
Answer: It means to consider the quotient. When you do $P/(P\cap R)$, now $P\cap R$ is the zero of the quotient.
Comment: I edited the question, its $(P \cap R)S$ rather than $P \cap R$. I read what Bill commented but I still don't see why we can only considerer the case $P \cap R = 0$. In another article, the author justifies by the isormophism $S/(P \cap R)S \cong R/(P \cap R) [x,\alpha]$, but I still don't see it. Can you explain more, please?

What does “factor out” an ideal mean?


Windows Server 2016 Standard License for VMS & RDS CAL

Question: We are a small business with two HP Servers(HPE ProLiant DL380) virtualized with ESXi, containing 7 VMs of Windows Server OS(2016).
As per Hardware documentation, each server has single processor with 10 cores each. So that should make 20 Cores total.
I did search about Microsoft Licensing and it says core based can have two licenses if 16 Core licenses are purchased.
Can anyone help me about

How many Windows Server 2016 STD Licenses should I purchase to
accommodate 7 VMs.
If I purchase 1 Remote Desktop Device CALs for
each of VM's (Total:7), multiple users in the domain can RDP login to
the server?

Edit: The confusion here is only with Core Based Licensing from Microsoft.
Comment: Buy licenses to cover 20 cores and you should be fine.
Comment: @Overmind Purchasing 20 Core Licenses will permit me to add 7 vm's each having Win Server 2016?
Comment: I detailed everything in an answer.
Answer: For the Datacenter version, you get an unlimited number of VMs so the equation is simple: Number of Processors in the Host x Number of Cores Per Processor (minimum of 8)=  Number of Core Licenses Needed (minimum of 16). In your case, you have 2 servers.
So your grand total is 1 CPU x10 cores = 10 licenses x 2 servers = 2 10-core licenses.
But there's one more problem: if you have less than 16 cores, you need to license your server as if you had 16 cores. So practically, you need 2 licenses for 16 cores each.
In the standard edition, there's also the VM limitation which complicates things. You are limited to 2 VMs per physical server, which in your case is bad.


Find a way to uniquely determine a point $x_{\sigma} \in X,$ given an element $\sigma \in \mathcal{L}$

Question: Here is my previous question Investigating the relationship between $X$ and the inverse limit $\mathcal{L}$ of the tower.
And now I want to Find a way to uniquely determine a point $x_{\sigma} \in X,$ given an element $\sigma \in \mathcal{L}.$ This defines a function $f:\mathcal{L} \rightarrow X.$
Could anyone help me in doing so please?
Answer: As I said in my answer, we can define it by $\{x_\sigma\} = \bigcap_n \sigma_n$.
The map is 1-1 because if $\sigma \neq \sigma'$, then for some $n$ we have $\sigma_n \neq \sigma'_n$ and as these are from the same $\mathcal{A}_n$, which is a partition, $\sigma_n \cap \sigma'_n = \emptyset$ which implies $x_\sigma \neq x_{\sigma'}$.
The map is also onto, as each $x$ occurs in a unique $\sigma_n \in \mathcal{A}_n$ and then the $\sigma$, so defined, has $x_\sigma=x$ by definition.
The last function also gives the inverse $g: X \to \mathcal{L}$:
$g(x)=\sigma$ defined by: $\sigma_n$ is the unique member of $\mathcal{A}_n$ that contains $x$.
Comment: And how can I show that the 2 functions are inverses of each other?
Comment: I know that I should show that $f \circ g = id_{X}$ and $g \circ f = id_{\mathcal{L}}$ but how?


Atualizar página ajax mvc core

Question: Preciso fechar um modal, e atualizar a página, estou fazendo desta forma:
 function closeModal() {
        $('#myModal').modal('hide');
        location.reload();
    }

Porém, na primeira vez não funciona, e depois funciona normal, alguém sabe o porque ? Ou algum outro código que possa atualizar, as informações do modal, são inclusas por uma função AJAX, que funciona, preciso apenas atualizar depois de fechar o modal.
 Gravar Item

Eu salvo a função e depois fecho o modal. O que está ocorrendo que possa estar acontecendo esse comportamento estranho.
Edit, código:
Por exemplo esta é a função para salvar:

function SalvarItens() {
    var idItem = $("#idItem").val();

    if (idItem == 0) {
        var dataInicio = $("#txtHoraInicio").val();
        var dataFim = $("#txtHoraFim").val();
        var tipoLimite = $("#txtTipoLimite").val();
        var limiteAcessos = $("#txtLimiteAcessos").val();
        var cbSeg = $('#cbSeg').prop('checked');
        var cbTer = $('#cbTer').prop('checked');
        var cbQua = $('#cbQua').prop('checked');
        var cbQui = $('#cbQui').prop('checked');
        var cbSex = $('#cbSex').prop('checked');
        var cbSab = $('#cbSab').prop('checked');
        var cbDom = $('#cbDom').prop('checked');
        var cbFer = $('#cbFer').prop('checked');
        var idHorario = $("#idHorario").val();
        var url = "/HorariosItens/SalvarItens";

        $.ajax({
            url: url
            , data: { HoraInicio: dataInicio, HoraFim: dataFim, Seg: cbSeg, Ter: cbTer, Qua: cbQua, Qui: cbQui, Sex: cbSex, Sab: cbSab, Dom: cbDom, Fer: cbFer, Tipolimite: tipoLimite, Limiteacessos: limiteAcessos, HorarioId: idHorario }
            , type: "POST"
            , datatype: "html"
            , success: function (data) {
                if (data.resultado > 0) {
                    ListarItens(idHorario);
                }
            }
        });
    } else {
        var dataInicio = $("#txtHoraInicio").val();
        var dataFim = $("#txtHoraFim").val();
        var tipoLimite = $("#txtTipoLimite").val();
        var limiteAcessos = $("#txtLimiteAcessos").val();
        var cbSeg = $('#cbSeg').prop('checked');
        var cbTer = $('#cbTer').prop('checked');
        var cbQua = $('#cbQua').prop('checked');
        var cbQui = $('#cbQui').prop('checked');
        var cbSex = $('#cbSex').prop('checked');
        var cbSab = $('#cbSab').prop('checked');
        var cbDom = $('#cbDom').prop('checked');
        var cbFer = $('#cbFer').prop('checked');
        var idHorario = $("#idHorario").val();

        var url = "/HorariosItens/EditarItem";

        $.ajax({
            url: url
            , data: { HoraInicio: dataInicio, HoraFim: dataFim, Seg: cbSeg, Ter: cbTer, Qua: cbQua, Qui: cbQui, Sex: cbSex, Sab: cbSab, Dom: cbDom, Fer: cbFer, Tipolimite: tipoLimite, Limiteacessos: limiteAcessos, HorarioId: idHorario, ItemId: idItem }
            , type: "POST"
            , datatype: "html"
            , success: function (data) {
                if (data.resultado > 0) {
                    ListarItens(idHorario);
                }
            }
        });
    }

}

Este é o ListarItens:

function ListarItens(idHorario) {

    var url = "/HorarioItem/Create";

    $.ajax({
        url: url
        , type: "GET"
        , data: { id: idHorario }
        , datatype: "html"
        , success: function (data) {
            var divItens = $("#divItens");
            divItens.empty();
            divItens.show();
            divItens.html(data);
            $("#idItem").val("0");
            $("#idHorario").val(idHorario);
            //$('#myModal').modal('hide');

        }
    });
}

Este é o código que salva:

  public ActionResult EditarItem(string HoraInicio, string HoraFim, bool Seg, bool Ter, bool Qua, bool Qui, bool Sex, bool Sab, bool Dom, bool Fer, int Tipolimite, int Limiteacessos, int HorarioId, int ItemId)
        {
            var item = new HorariosItens()
            {
                HoraFim = HoraFim,
                HoraInicio = HoraInicio,
                Seg = Seg,
                Ter = Ter,
                Qua = Qua,
                Qui = Qui,
                Sex = Sex,
                Sab = Sab,
                Dom = Dom,
                Fer = Fer,
                Tipolimite = Tipolimite,
                Limiteacessos = Limiteacessos,
                HorarioId = HorarioId,
                Id = ItemId
            };

            try
            {
                _context.Entry(item).State = EntityState.Modified;
                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return Json(new { Resultado = item.Id });
        }

Ele inclui, edita, e exclui, ele apenas tem horas que não atualiza, e tem horas que atualiza.
Edit HTML:

div class="form-group">
<input type="button" value="Incluir Itens" onclick="abreModal();" class="btn btn-info btn-sm" />

<form method="post" id="createform">

  @if (Model.Message != null) {

    <button type="button" class="close" data-dismiss="alert" aria-label="close">
                ×
            </button> @Model.Message

  }
  <input type="hidden" asp-for="HorariosVM.Horarios.Id" />

            @Html.DisplayNameFor(model => model.HorariosItens[0].HoraInicio)

            @Html.DisplayNameFor(model => model.HorariosItens[0].HoraFim)

            @Html.DisplayNameFor(model => model.HorariosItens[0].Seg)

            @Html.DisplayNameFor(model => model.HorariosItens[0].Ter)

            @Html.DisplayNameFor(model => model.HorariosItens[0].Qua)

            @Html.DisplayNameFor(model => model.HorariosItens[0].Qui)

            @Html.DisplayNameFor(model => model.HorariosItens[0].Sex)

            @Html.DisplayNameFor(model => model.HorariosItens[0].Sab)

            @Html.DisplayNameFor(model => model.HorariosItens[0].Dom)

            @Html.DisplayNameFor(model => model.HorariosItens[0].Fer)

            @Html.DisplayNameFor(model => model.HorariosItens[0].Tipolimite)

            @Html.DisplayNameFor(model => model.HorariosItens[0].Limiteacessos)

        @foreach (var item in Model.HorariosItens) {

            @Html.DisplayFor(modelItem => item.HoraInicio)

            @Html.DisplayFor(modelItem => item.HoraFim)

            @Html.DisplayFor(modelItem => item.Seg)

            @Html.DisplayFor(modelItem => item.Ter)

            @Html.DisplayFor(modelItem => item.Qua)

            @Html.DisplayFor(modelItem => item.Qui)

            @Html.DisplayFor(modelItem => item.Sex)

            @Html.DisplayFor(modelItem => item.Sab)

            @Html.DisplayFor(modelItem => item.Dom)

            @Html.DisplayFor(modelItem => item.Fer)

            @Html.DisplayFor(modelItem => item.Tipolimite)

            @Html.DisplayFor(modelItem => item.Limiteacessos)

            Alterar
            Excluir @*
            Editar
            <button asp-page-handler="Delete" asp-route-id="@item.Id" class="btn btn-danger btn-sm">Excluir</button>*@

        }

                      Hora Inicio
                      <input type="time" class="form-control" id="txtHoraInicio" />

                      Hora Fim
                      <input type="time" class="form-control" id="txtHoraFim" />

                      Tipo Limite
                      <input id="txtTipoLimite" class="form-control" type="text" />

                      Limite de Acesso
                      <input id="txtLimiteAcessos" type="text" class="form-control" />

                        <input type="checkbox" id="cbSeg" />

                      Segunda

                        <input type="checkbox" id="cbTer" />

                      Terça

                        <input type="checkbox" id="cbQua" />

                      Quarta

                        <input type="checkbox" id="cbQui" />

                      Quinta

                        <input type="checkbox" id="cbSex" />

                      Sexta

                        <input type="checkbox" id="cbSab" />

                      Sabado

                        <input type="checkbox" id="cbDom" />

                      Domingo

                        <input type="checkbox" id="cbFer" />

                      Feriado

                Gravar Item
                Fechar

</form>

O Create ele atualiza, porém ele não deixa mais fazer nenhuma função.
Comment: Você quer atualizar a página e o que você espera com isso? O modal fecha? O que acontece depois que passa no  location.reload(); Alguma saída no console do navegador?
Comment: Eu preciso que ao fechar o modal, atualize a tabela, o modal fecha, porém nem sempre atualiza a tabela.
Comment: E poque ao fechar o modal você não chama um ajax para persistir os dados na tabela? Não faz sentido você fechar um modal, dá refresh na página e ele inserir dados na tabela.
Comment: no ajax, ele chama a função pra alterar/editar/excluir os dados, e ele faz isso, somente não atualiza.
Comment: Então seu problema está certamente no c#. Por fim você chama o  SaveChanges(); ?
Comment: Estou depurando o código, o problema está nas funções ajax, pelo jeito, o problema que mesmo informando no console.log(data.resultado) ele está certo, não tem motivos pra ele não entrar no sucess de data.resultado.
Comment: @NetinhoSantos acontece que geralmente na primeira vez ele não entra no sucess da função, vc sabe me dizer pq isso acontece ? Depurando o código mesmo sendo feito com sucesso, ele não entra e por isso não atualiza a página conforme tem q atualizar.
Comment: Poste o seu código ajax.
Comment: @NetinhoSantos editei com os códigos.
Comment: Pode ser um problema de concorrência onclick="SalvarItens(); closeModal();" você está chamando duas funções no click do botão e isso não garante que ele esconda a modal e recarregue a página depois da submissão no método SalvarItens().
Comment: Mas como eu posso fechar então o modal, sem dar este problema ?
Comment: Realmente eu fiz o teste, exclui, altera e edita sem problemas, porém preciso fechar o modal, que no caso se eu tiro o closeModal() eu só consigo incluir uma vez, e o alterar, ele altera, mas tenho que fechar o modal, pra ele atualizar.
Answer: Altere a sequencia de chamadas para organizar a execução dos comandos na ordem que deseja. E esqueça o reload da página porque isso não faz nenhum sentido nesse contexto.
No botão de fechar invoque apenas o closeModal()
Gravar Item

Na closeModal() chame o SalvarItens()
function closeModal() {
   SalvarItens();
}

E na ListarItens() dê um dispose em sua modal
function ListarItens(idHorario) {
    $('#myModal').modal('dispose');
    var url = "/HorarioItem/Create";

    $.ajax({
        url: url
        , type: "GET"
        , data: { id: idHorario }
        , datatype: "html"
        , success: function (data) {
            var divItens = $("#divItens");
            divItens.empty();
            divItens.show();
            divItens.html(data);
            $("#idItem").val("0");
            $("#idHorario").val(idHorario);
        }
    });
}

Comment: No form de edit dessa forma funcionou, porém no create não deu certo, ele abre o modal, ele inclui, atualiza, porém fica como se o modal tivesse aberto, até criei as funções novamente, e coloquei outro nome, para separar do edit, e do create.
Comment: Ainda não consegui entender por que você quer recarregar a página
Comment: Na vdd eu n preciso recarregar a página, eu preciso atualizar a tabela no create, e isso não ta acontecendo.No edit eu recarrego a página, que foi a melhor maneira que encontrei, agora no create, eu não estou conseguindo, ele fica como se o modal n fosse fechado, porém ele inclui no banco.
Comment: Inclua o html de sua view na pergunta
Comment: Atualizei a pergunta com o HTML. Lembrando que trabalho com PageRazor e .net core
Comment: Tentei dessa forma que você editou, porém não funcionou.
Comment: Com o dispose ele me retorna o seguinte erro: Uncaught TypeError: data[option] is not a function
    at HTMLDivElement.eval
Comment: pode ser questão de versão e deixando com o hide?
Answer: Pelo que entendi, deseja salvar/editar um item e que a lista seja atualiza, abaixo segue um exemplo de como pode fazer:
No exemplo, após salvar/editar é carregada novamente a lista.
Não sei ao certo como está a arquitetura do seu projeto, então provavelmente terá que fazer ajustes.
O código todo do exemplo está disponível nesse repositório
Quanto a fechar o modal e o fundo ficar cinza, quando o modal é aperto ele adiciona uma classe no body. Achei essa resposta no SO que pede para fazer assim para fecha-lo
$('#your-modal-id').modal('hide');
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();

View Index:
@{
    ViewData["Title"] = "Setores";
}

Setores

<button type="button" class="btn btn-add-new" onclick="carregaCreate()" data-toggle="modal" data-target="#myModal">Criar novo setor</button>

@section scripts{

}

View _Create:
@model ProjetoBase.ViewModel.Setor.CreateSetorViewModel

    <button type="button" class="close" data-dismiss="modal" aria-label="Close"></button>

Adicionar setor

        <form id="formCreate">

                        <input asp-for="Nome" class="form-control" />

                        <input asp-for="Sigla" class="form-control" />

                                <input type='checkbox' checked asp-for="IsAtivo" />

        </form>

    <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
    <input type="button" id="btnCreate" value="Adicionar" onclick="createSetor()" class="btn btn-default" />

View _Lista:
@model IEnumerable<ProjetoBase.ViewModel.Setor.ViewSetorViewModel>

@if (Model.Count() <= 0)
{
    Não há setores cadastrados
}
else
{

                    @Html.DisplayNameFor(model => model.IsAtivo)

                    @Html.DisplayNameFor(model => model.Nome)

                    @Html.DisplayNameFor(model => model.Sigla)

                    Editar

            @foreach (var item in Model)
            {

                        @if (item.IsAtivo)
                        {

                        }
                        else
                        {

                        }

                        @Html.DisplayFor(modelItem => item.Nome)

                        @Html.DisplayFor(modelItem => item.Sigla)

            }

}

View _Update:
@model ProjetoBase.ViewModel.Setor.UpdateSetorViewModel

    <button type="button" class="close" data-dismiss="modal" aria-label="Close"></button>

        <form id="formUpdate">
            <input asp-for="SetorId" type="hidden" />

                        <input asp-for="Nome" class="form-control" />

                        <input asp-for="Sigla" class="form-control" />

                                <input type='checkbox' asp-for="IsAtivo" />

        </form>

    <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
    <input type="button" id="btnUpdate" value="Atualizar" onclick="updateSetor()" class="btn btn-default" />

Index javaScript:
$(document).ready(function () {
    lista()
});

function createSetor() {
    var objeto = $("#formCreate").serialize();
    $.ajax({
        url: "/Setores/Create",
        type: "POST",
        data: objeto,
        datatype: "json",
        success: function (data) {

            if (data.MensagemSucesso != undefined) {
                notificaSucesso(data.MensagemSucesso)
                $("#corpoModal").html("");

                $('#myModal').modal('hide')
                lista();
            } else {
                notificaFalha(data.MensagemErro)
            }

        }
    });
}

function updateSetor() {
    var objeto = $("#formCreate").serialize();
    $.ajax({
        url: "/Setores/Update",
        type: "POST",
        data: objeto,
        datatype: "json",
        success: function (data) {

            if (data.MensagemSucesso != undefined) {
                notificaSucesso(data.MensagemSucesso)
                $("#corpoModal").html("");

                $('#myModal').modal('hide')
                lista();
            } else {
                notificaFalha(data.MensagemErro)
            }

        }
    });
}

function carregaCreate() {
    $("#corpoModal").load("Setores/CarregaCreate");
}

function carregaUpdate(id) {
    $("#corpoModal").load("Setores/CarregaUpdate/" + id);
}

function lista() {
    $("#lista").load("setores/lista", function () {
    });
}

Controller:
public class SetoresController : Controller
{
    private readonly ISetorService _setorService;
    public SetoresController(ISetorService setorService)
    {
        _setorService = setorService;
    }

    [HttpGet]
    public IActionResult Index() => View();

    [HttpGet]
    public IActionResult CarregaCreate() => PartialView("_Create");

    [HttpPost]
    public IActionResult Create(CreateSetorViewModel viewModel)
    {
        if (!ModelState.IsValid)
            return Json(new { MensagemErro = ModelState.DisplayErros() });

        Setor setor = Mapper.Map<Setor>(viewModel);

        List<StatusValidacaoEnum> status = _setorService.ValidaSetor(setor);

        if (status.Count > 0)
            return Json(new { MensagemErro = status.DisplayDescriptionsToViewModel() });

        if (_setorService.Insert(setor))
            return Json(new { MensagemSucesso = "Setor incluso com sucesso" });
        else
            return Json(new { MensagemErro = "Erro ao adicionar setor" });
    }

    [HttpGet]
    public IActionResult CarregaUpdate(int id)
    {
        Setor setor = _setorService.SelectById(id);

        if (setor == null)
            return PartialView("_Create");

        UpdateSetorViewModel viewModel = Mapper.Map<UpdateSetorViewModel>(setor);

        return PartialView("_Update", viewModel);
    }

    [HttpPost]
    public IActionResult Update(UpdateSetorViewModel viewModel)
    {
        if (!ModelState.IsValid)
            return Json(new { MensagemErro = ModelState.DisplayErros() });

        Setor setor = Mapper.Map<Setor>(viewModel);

        List<StatusValidacaoEnum> status = _setorService.ValidaSetor(setor);

        if (status.Count > 0)
            return Json(new { MensagemErro = status.DisplayDescriptionsToViewModel() });

        if (_setorService.Update(setor))
            return Json(new { MensagemSucesso = "Setor atualizado com sucesso" });
        else
            return Json(new { MensagemErro = "Erro ao atualizar setor" });
    }

    [HttpGet]
    public IActionResult Lista()
    {
        List<ViewSetorViewModel> viewModels = Mapper.Map<List<ViewSetorViewModel>>(_setorService.Select());
        return PartialView("_Lista", viewModels);
    }
}

Comment: Ele atualiza a tabela, porém fica como se n tivesse fechado o modal, vou postar a imagem pra vc ver como que fica.
Comment: @marianac_costa, atualizei a resposta
Comment: O engraçado, é que executando direto no visual, ele dava certo, e fora não, mas após colocar o código pra fechar o modal q vc atualizou a resposta, deu certo, obrigado mais uma vez.

Atualizar página ajax mvc core


Start solr indexing from CI job

Question: We use Solr 6.4.1 and implement several cores for searching. In one of core contain several entities. All steps for refreshing index start manually from UI, including the credentials of the database.
My question is can I reindex solr core with several entities from a remote console? I need create CI job for this.
And the second question is where I can specify custom parameters with database credentials for all cores on the server?
Answer: If the application has some sort of command, you could just trigger the command directly from the CI pipeline, if it's not the case and the indexing/update code is highly coupled to the UI, then you could use DataImportHandler so you configure in Solr (as described in the documentation) the credentials, the queries that Solr needs to execute, etc. And you just trigger the import handler from the CI pipeline, something like:
http://<host>:<port>/solr/<collection_name>/command=delta-import

This will start a delta-import, for some more commands check the Data Import Handler Commands section on the previous link.

Start solr indexing from CI job


JQuery .html() question

Question: I have a menu made with HTML, using a simple UL with lots of LIs. Each item contains a link with class "primary". When a list item (anywhere in a list item - not just the text) is clicked, jquery checks to see if the item contains a link with class "primary", and if so it loads the specified page into a hidden div (which I refer to as temporary, even though its not actually temporary...) and then extracts certain parts of the new page to set as the html for parts of the visible page. For example it takes ".temp .content" and places that in ".content". It basically extracts the html, sets the html of ".temp" to nothing (otherwise the line $(".content").html(newhtml); will set the html of the ".content" within the temporary div) and then sets the html of the original content div to newhtml.
I have a slight problem however. It seems that it sometimes makes the div go blank, sometimes it takes two clicks to load a page and sometimes I can click item 1, then click item 2 and it instantly loads the content from item 1 (i.e. that which is displayed in the content div of the page which is loaded by item 1).
In fact I can make a "chain" - click items 1, 2, 3, 4 and then 1 and 2 again and I see blank, content for items 1, 2, 3, 4 and 1.
Does anyone have any clue as to whats going on here?
Many thanks in advance.
Regards,
Richard
In reply to Peter Ajtai (I have tried to shorten it as much as possible - it is actually much much more complex than this as I have a 3 col layout and a fix to make all 3 columns shaded to the same height - but I think all the essential stuff is here)...
Basic structure of the page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        //jquery includes
        $("li").click(function () {
            var url = $(this).find("a.primary").attr("href");
            if (url != "" && url != null) {
                $(".temp").load(url);
                var newhtml = $(".temp .content").html();
                $(".temp").html("");
                $(".main-col").html(newhtml);
            }
        });

//left menu stuff here, in the following format:

Content Management List

Ranges

Collections

        </wrapper>

Comment: Could you provide the pertinenent HTML and jQuery? It'd be much simpler to debug like that. ----------- One thing you should make sure to do is only load the page into a `div` once. After that simply toggle the visibility of the `div` containing the page.
Comment: Ive added my code to the question...
Answer: I think you should just catch the ajax response in your success handler function and put it where it needs to go the first time around.  Doing multiple DOM inserts for the same content is
a) slow and cumbersome, and
b) probably where your issue is coming from.
Most likely (without seeing your code) you've got some duplicate id on some element somewhere.
If you need to insert content returned from the server into separate locations in the document, consider changing your server response to JSON and put the two HTML strings in different array elements.
UPDATE
From your example it looks like you are just loading content into .main-col if so you could make a new server method that only serves up a view with content that belongs inside main-col, and then do this:
    $("li").click(function () {
        var url = $(this).find("a.primary").attr("href");
        if (url != "" && url != null) {
            $(".main-col").load(url);
        }
    });

Comment: hmm seems I may be getting out of my depth here - I have very limited experience of jQuery... I thought this would be a simple load the page and then change the content of various elements. I suppose I could attach a number into the query string (using $(".temp").load(url+loadcount);, and increment loadcount every time a page is loaded. This could be appended to the ID of each element in the new page - making each ID unique. I dont know how efficient this would be, however. It may solve the issue though.
Comment: This comment is on the update you posted (I didnt realise it was there till now)... grr stupid enter = submit on textarea function... anywho so what you are saying is to tag something onto the query string which the server then reads and thinks (or rather knows) it is a partial page which is required, then sends back just the required information..? Sounds simple enough.
Comment: Exactly.  Or write a new server method for the partial pages.  Then you're only inserting what you need into the DOM.
Comment: Ah cool at least we are thinking along the same lines... I dont know why I never thought of using the query string like that - I mean ive done that before... its so obvious... thanks for the suggestion.

JQuery .html() question


AWS API Gateway, Cognito Identity Pool and REST: can I restrict to specific paths and methods?

Question: I want to implement a blog API - for fun and learning - which allows a user to manage and write/view their own blog posts.  So far I have an API with paths like
/ - GET all posts,
/blog/{id} - GET a specific post or PUT to update a post
/blog/ - POST for a new blog
Using a cognito user pool, a user can sign up, and login and the API Gateway uses an authorizer to allow or deny access (I'm mucking about with Blazor at the same time - there isn't really an interface yet just a bit of cobbled together C# that uses the identity provide API}.
However, any user can see all posts.  I really want something like this:
/{user}/ - GET all posts by user
/{user}/blog/{id} - GET or PUT specific blog post
and so on.
Behind the API gateway are four really simply lambda functions.  So far, with the user pool authorizer I can see the Authorization header but nothing else (the request context and context have no Identity elements that are not null).
I was wondering whether I could use Identity Pool to do the specific user permissions using IAM Roles, but I cant think of what the roles might look like, or whether this seems possible.  I know there are parameters you can embed in roles - you do that for S3 Roles - why not API paths?
Does this sound plausible or would I need to go down the Lambda function to do authorization?  Anyone any examples?  I googled and look through stack overflow, but couldn't see anything specific around this.
Another problem I guess would be getting a nice ID substitution for user here - I collect email and nickname so far - need a nice username rather than a cognito user id, which looks like they're wouldn't play well with a URL?
Thanks.
Comment: Just adding Identity Pool stuff in C# is proving baffling at the moment.  I think I may have bitten off more than I can chew here...
Answer: The answer to my query appears to be in this you tube video, put up by the AWS team late last night (uk time, anyway.)  So far, using C#, I can authenticate myself against the user pool, and get AWS Credentials, but when I attempt to access my API I get "message": "unauthorized", and that's it!
Anyway, onwards and upwards.
You tube video about fine grained access control using cognito identity pools.


HTTP calls behave different locally vs AWS - is it ruby or AWS?

Question: I have a weird problem with an API I'm writing. The API has makes http get requests to other services and times out in certain situations- another service being off/unreachable in most cases.
I'm trying to run the system entirely on AWS, but when running the API on there I get frequent timeouts trying to access services on the same instance. The API is written in ruby+sinatra; I never had problems with its python predecessor. If I curl the url for other services from the AWS instance command line, I never get timeouts. When I run the API locally (other services on AWS), it works fine, every single time.
Initially I thought it might be the http library I was using- net/http, which turned out to be problematic even locally. Switching to open-uri or rest-client fixed all local problems, but when I run on AWS I still get timeouts 20% of the time.
The API is ruby+sinatra using open-uri to do http requests. The other services are either ruby+sinatra or java. I'm running on a 32-bit Amazon Linux small instance, ruby 1.9.3, java 1.6; my local machine is Mac with Snow Leopard with ruby 1.9.3 and java 1.6 as well.
Any ideas or tips to further narrow down what might be happening?

UPDATE: My big sinatra app and little sinatra app behave differently!?
The test version of my sinatra app to call my java service, both running on AWS... works fine.
require 'rubygems'
require 'uri'
require 'open-uri'
require 'sinatra'

set :port, 6969

get '/wtf' do
  xid = params[:xid]
  state = params[:state]
  service_addr = 'http://prod.myserver.com'
  rid = 'xxx'
  json = "{\"state\":\"#{state}\",\"sid\":\"0xac99d8929a89e6c01b56378336dec3a8L\",\"m\":\"set\",\"rid\":\"#{rid}\",\"id\":\"#{xid}\"}"

  paramStr = URI.escape("rid=#{rid}&id=#{xid}&json=#{json}")
  response = open(service_addr+"?"+paramStr)
  status = response.status[0]
  body = response.read

  body
end

The big version, running with Rack + as a better structured sinatra app... fails 20+% of the time!
require 'uri'
require 'open-uri'

class MyApp < Sinatra::Base

  get '/wtf' do
    xid = params[:xid]
    state = params[:state]
    service_addr = 'http://prod.myserver.com'
    rid = 'xxx'
    json = "{\"state\":\"#{state}\",\"sid\":\"0xac99d8929a89e6c01b56378336dec3a8L\",\"m\":\"set\",\"rid\":\"#{rid}\",\"id\":\"#{xid}\"}"

    paramStr = URI.escape("rid=#{rid}&id=#{xid}&json=#{json}")
    response = open(service_addr+"?"+paramStr)
    status = response.status[0]
    body = response.read

    body
  end

end

UPDATE 2: Detailed error readout using mechanize- always a gateway timeout
For the simple version, it works every time (no timeouts). For the complicated version, here are readouts with mechanize when it works, and doesn't.
When it works:
I, [2012-05-22T22:45:53.267464 #11610]  INFO -- : Net::HTTP::Get: /? ### big long get str
D, [2012-05-22T22:45:53.267587 #11610] DEBUG -- : request-header: accept => */*
D, [2012-05-22T22:45:53.267630 #11610] DEBUG -- : request-header: user-agent => Mechanize/2.5.1 Ruby/1.9.3p125 (http://github.com/tenderlove/mechanize/)
D, [2012-05-22T22:45:53.267676 #11610] DEBUG -- : request-header: accept-encoding => gzip,deflate,identity
D, [2012-05-22T22:45:53.267713 #11610] DEBUG -- : request-header: accept-charset => ISO-8859-1,utf-8;q=0.7,*;q=0.7
D, [2012-05-22T22:45:53.267750 #11610] DEBUG -- : request-header: accept-language => en-us,en;q=0.5
D, [2012-05-22T22:45:53.267787 #11610] DEBUG -- : request-header: host => prod.pixieplug.com:9001
I, [2012-05-22T22:45:53.341814 #11610]  INFO -- : status: Net::HTTPOK 1.1 200 OK
D, [2012-05-22T22:45:53.341916 #11610] DEBUG -- : response-header: content-type => application/json;charset=ISO-8859-1
D, [2012-05-22T22:45:53.341962 #11610] DEBUG -- : response-header: transfer-encoding => chunked
D, [2012-05-22T22:45:53.342009 #11610] DEBUG -- : response-header: server => Jetty(8.0.y.z-SNAPSHOT)
D, [2012-05-22T22:45:53.342137 #11610] DEBUG -- : Read 167 bytes (167 total)
126.96.36.199 - - [22/May/2012 22:45:53] "GET /wtf?xid=00:00:00:00:00:17&state=255 HTTP/1.1" 200 167 0.0777

When it doesn't:
I, [2012-05-22T22:46:23.665908 #11610]  INFO -- : Net::HTTP::Get: /?# long list of params
D, [2012-05-22T22:46:23.666014 #11610] DEBUG -- : request-header: accept => */*
D, [2012-05-22T22:46:23.666053 #11610] DEBUG -- : request-header: user-agent => Mechanize/2.5.1 Ruby/1.9.3p125 (http://github.com/tenderlove/mechanize/)
D, [2012-05-22T22:46:23.666090 #11610] DEBUG -- : request-header: accept-encoding => gzip,deflate,identity
D, [2012-05-22T22:46:23.666125 #11610] DEBUG -- : request-header: accept-charset => ISO-8859-1,utf-8;q=0.7,*;q=0.7
D, [2012-05-22T22:46:23.666161 #11610] DEBUG -- : request-header: accept-language => en-us,en;q=0.5
D, [2012-05-22T22:46:23.666233 #11610] DEBUG -- : request-header: host => prod.pixieplug.com:9001
I, [2012-05-22T22:46:28.675045 #11610]  INFO -- : status: Net::HTTPGatewayTimeOut 1.1 504 Gateway Timeout
D, [2012-05-22T22:46:28.675156 #11610] DEBUG -- : response-header: content-type => application/json;charset=ISO-8859-1
D, [2012-05-22T22:46:28.675195 #11610] DEBUG -- : response-header: transfer-encoding => chunked
D, [2012-05-22T22:46:28.675232 #11610] DEBUG -- : response-header: server => Jetty(8.0.y.z-SNAPSHOT)
D, [2012-05-22T22:46:28.675332 #11610] DEBUG -- : Read 48 bytes (48 total)
Mechanize::ResponseCodeError - 504 => Net::HTTPGatewayTimeOut for http://prod.pixieplug.com:9001/?# long list of params  -- unhandled response:
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/mechanize-2.5.1/lib/mechanize/http/agent.rb:304:in `fetch'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/mechanize-2.5.1/lib/mechanize.rb:407:in `get'
    /home/ec2-user/elphi-api/routes/sandbox.rb:15:in `block in <class:MyApp>'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/sinatra-1.3.2/lib/sinatra/base.rb:1212:in `call'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/sinatra-1.3.2/lib/sinatra/base.rb:1212:in `block in compile!'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/sinatra-1.3.2/lib/sinatra/base.rb:785:in `[]'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/sinatra-1.3.2/lib/sinatra/base.rb:785:in `block (3 levels) in route!'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/sinatra-1.3.2/lib/sinatra/base.rb:801:in `route_eval'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/sinatra-1.3.2/lib/sinatra/base.rb:785:in `block (2 levels) in route!'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/sinatra-1.3.2/lib/sinatra/base.rb:822:in `block in process_route'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/sinatra-1.3.2/lib/sinatra/base.rb:820:in `catch'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/sinatra-1.3.2/lib/sinatra/base.rb:820:in `process_route'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/sinatra-1.3.2/lib/sinatra/base.rb:784:in `block in route!'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/sinatra-1.3.2/lib/sinatra/base.rb:783:in `each'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/sinatra-1.3.2/lib/sinatra/base.rb:783:in `route!'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/sinatra-1.3.2/lib/sinatra/base.rb:886:in `dispatch!'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/sinatra-1.3.2/lib/sinatra/base.rb:719:in `block in call!'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/sinatra-1.3.2/lib/sinatra/base.rb:871:in `block in invoke'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/sinatra-1.3.2/lib/sinatra/base.rb:871:in `catch'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/sinatra-1.3.2/lib/sinatra/base.rb:871:in `invoke'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/sinatra-1.3.2/lib/sinatra/base.rb:719:in `call!'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/sinatra-1.3.2/lib/sinatra/base.rb:705:in `call'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/rack-protection-1.2.0/lib/rack/protection/xss_header.rb:22:in `call'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/rack-protection-1.2.0/lib/rack/protection/base.rb:47:in `call'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/rack-protection-1.2.0/lib/rack/protection/base.rb:47:in `call'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/rack-protection-1.2.0/lib/rack/protection/path_traversal.rb:16:in `call'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/rack-protection-1.2.0/lib/rack/protection/json_csrf.rb:17:in `call'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/rack-protection-1.2.0/lib/rack/protection/base.rb:47:in `call'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/rack-protection-1.2.0/lib/rack/protection/xss_header.rb:22:in `call'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/rack-1.4.1/lib/rack/session/abstract/id.rb:205:in `context'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/rack-1.4.1/lib/rack/session/abstract/id.rb:200:in `call'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/rack-1.4.1/lib/rack/logger.rb:15:in `call'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/rack-1.4.1/lib/rack/head.rb:9:in `call'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/rack-1.4.1/lib/rack/methodoverride.rb:21:in `call'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/sinatra-1.3.2/lib/sinatra/showexceptions.rb:21:in `call'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/rack-1.4.1/lib/rack/lint.rb:48:in `_call'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/rack-1.4.1/lib/rack/lint.rb:36:in `call'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/rack-1.4.1/lib/rack/showexceptions.rb:24:in `call'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/rack-1.4.1/lib/rack/commonlogger.rb:20:in `call'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/rack-1.4.1/lib/rack/chunked.rb:43:in `call'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/rack-1.4.1/lib/rack/content_length.rb:14:in `call'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/thin-1.3.1/lib/thin/connection.rb:80:in `block in pre_process'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/thin-1.3.1/lib/thin/connection.rb:78:in `catch'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/thin-1.3.1/lib/thin/connection.rb:78:in `pre_process'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/thin-1.3.1/lib/thin/connection.rb:53:in `process'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/thin-1.3.1/lib/thin/connection.rb:38:in `receive_data'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/eventmachine-0.12.10/lib/eventmachine.rb:256:in `run_machine'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/eventmachine-0.12.10/lib/eventmachine.rb:256:in `run'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/thin-1.3.1/lib/thin/backends/base.rb:61:in `start'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/thin-1.3.1/lib/thin/server.rb:159:in `start'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/rack-1.4.1/lib/rack/handler/thin.rb:13:in `run'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/rack-1.4.1/lib/rack/server.rb:265:in `start'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/rack-1.4.1/lib/rack/server.rb:137:in `start'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/gems/rack-1.4.1/bin/rackup:4:in `<top (required)>'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/bin/rackup:19:in `load'
    /home/ec2-user/.rvm/gems/ruby-1.9.3-p125/bin/rackup:19:in `'
188.8.131.52 - - [22/May/2012 22:46:28] "GET /wtf?xid=00:00:00:00:00:17&state=255 HTTP/1.1" 500 157221 5.1385

Comment: So basically you have 2 sinatra apps trying to communicate with each other locally. My advice is to try to get the problem code as small as possible and post it here.
Comment: The sinatra->java seems to be the problem. when both are on AWS. Sinatra app running on my laptop -> java app on AWS works fine. I will attempt to simplify my code and post it.
Comment: it looks like you might need a slash after service_addr. Also try CGI.escape instead of URI.escape.
Comment: tried former, latter and both, didn't fix the timeout issue. It's interesting that the full sinatra app works fine on my mac but has trouble on the ami.
Comment: How are you running it? With rackup?
Comment: Do you compare 'big long get strs'? Are they identical?
Comment: You can try adding: AGENT.open_timeout, AGENT.read_timeout = 60,60
Comment: Big long str are identical. Adding the agent timeouts doesn't make a difference because the java service times out.
Comment: The current theory is that AWS small instance has too much resource contention going on with 3 separate process I run (2 sinatra apps and one big multithreaded java app). Running on a medium or large instance resolves timeouts, though I have not performed a full on load test to verify this.
Comment: I guess that makes sense but I've run heavy apps on micro instances and never seen that. I never send json data in a query string like that though.
Answer: It's a strange looking request, usually json data goes in a post body not the query string. Let's try using mechanize because it gives lots of debug information when you use a logger and maybe that will help you see where the problem is. Slightly refactored code:
require 'sinatra/base'
require 'mechanize'
require 'logger'
require 'json'

class Myapp < Sinatra::Base

  AGENT = Mechanize.new
  AGENT.log = Logger.new $stdout

  get '/wtf' do
    rid, sid, xid, state = 'xxx', '0xac99d8929a89e6c01b56378336dec3a8L', params[:xid], params[:state]
    service_addr = 'http://prod.myserver.com/'
    json = {'state' => state, 'sid' => sid, 'm' => 'set', 'rid' => rid, 'id' => xid}.to_json
    response = AGENT.get service_addr, {:rid => rid, :id => xid, :json => json}
    response.body
  end

end


Matching users Firestore db model

Question: I am developing a mobile app in flutter to help people connect with DIY experts.
The app will connect people who need advice to people who are expert, then let them chat in 1:1 messaging. As example, person A want advice on plumbing, so the app connect him to person B, who know how to plumbing.
My database model is use Firestore to store user details and FCM tokens. Cloud functions to send notifications to all expert FCM tokens (to notify them when non-expert need help).
Here my model so far:

Firestore: Store 2 groups users: non-expert and expert.
When non-expert in app taps 'I need help!', flag non-expert's field in database 'needhelp' to set to true.
Firebase Cloud function listen to change, and send FCM to all expert FCM tokens in database.
?? When one expert in app tap 'I can help!', create new chat document in db ??
Firestore: Create new Messages document, store messages etc.

My question is step 4: how to match and connect expert and non-expert in new 1:1 chat when expert tap 'I can help' in client app. On tap, should expert client app set new value in document in Firestore? What document? What db model for this?
Similar apps are dating apps e.g. Tinder. Fun question: What would Tinder Firestore look like? :)
Comment: So you basically need a database schema for your app, right?
Comment: Yes basically @AlexMamo. I have watch you youtube videos!! But I no find how to match users at step 4 above.
Comment: You can find answers for all your questions in my tutorials. For a one to one chat app, please see this **[Firestore chat tutorial](https://www.youtube.com/playlist?list=PLn2n4GESV0Ak1HiH0tTPTJXsOEy-5v9qb)**.
Comment: @AlexMamo I have watch all you videos, but not answer my question. You schema work where you always know exactly who you will connect with. In you video: 'Second User' / First Random User' / 'Second Random User'. You schema work for normal chat app because always know who need connect to. However in my app we never know which users we will be connecting before there is match. We don't know who non-expert will connect to. We don't even know if non-expert will find match. So my database model must be different.
Comment: Once you change that property to available, it means that you know the person you are chating with. So basically the whole problem is reduces the schema in my video.
Comment: @alexmamo Good point! So base on you schema you suggest to have: 'users', 'rooms', 'messages' root-level collections. Store users as documents (document name == Firebase auth UID). User fields: chatroom, UID, username and 'needhelp' boolean. My app no need contacts because match for one-time only 1:1 chat. What you think?
Comment: @AlexMamo Second question. You video #4 have 'rooms' and 'messages' root collection. I think my app need only 'messages'. Because user never have more than one chat open in app and only 1:1. After users finish chat they will never look at it again. The next chat will be with different person and no need to view previous chats. You agree?
Comment: First comment, yes, it's a possible database structure.For the first comment, according to your app use-case, yes, you can model with or without it.
Comment: @AlexMamo Thanks! What you think about my second question?
Comment: The second respons was actually for the second question.
Comment: @AlexMamo I have now make most my Firestore db! My final design is have separate collection for non-expert needing help. This collection store document (document name = non-expert UID). Field is the chatroom name (random string). When expert tap 'I can help!' then app retrieve chatID from this document. Then find chat ID in 'rooms' collection and load data. What you think? Thanks for help!
Comment: I think it might work. If you want more informations post a new question regarding that schema.
Comment: Thanks! I have post here: https://stackoverflow.com/q/53746920
Answer: create chat rooms that go like: chatroom1, chatroom2, chatroom 3 .....
if a user wants to join chatroom1 should be empty so he will join this one.
a second user wants to join and founds 1 user in chat room 1 so he joins the room and they start chatting
a third user comes by and finds that chat room 1 is full (2 people in it) so he joins chat room2 and waits for somebody else to join a nd the pattern goes on............

Matching users Firestore db model


Plotting graph in Wolfram Mathmatica?

Question: Which is the function that can plot me the graph K 7, 2 in mathematica? And after that to delete 2 edges??
Thanks for the help.
Comment: Perhaps better to ask at [Mathematica.SE](http://mathematica.stackexchange.com/)...?
Comment: I also recommend to you to propose this question to the Mathematica SE community, however if you do, please specify on what you mean by the $K_{7,2}$ graph.
Comment: Bipartite graph K 7,2
Answer: Wolfram Mathematica has a great help with many examples. Also it does have its own community on StackExchange https://mathematica.stackexchange.com/ . You'd better address questions regarding Mathematica there
<code>G1 = CompleteGraph[{7, 2}];
G2 = EdgeDelete[G1, {1 <-> 8, 2 <-> 8}];
GraphPlot[G1]
GraphPlot[G2]
</code>
Comment: EdgeDelete::graph: A graph object is expected at position 1 in EdgeDelete[Graph[CompleteGraph[{7,2}]],{1<->8,2<->8}]. >>
Comment: GraphPlot::grph: Graph[CompleteGraph[{7,2}]] is not a valid graph. >>
Comment: GraphPlot::grph: EdgeDelete[Graph[CompleteGraph[{7,2}]],{1<->8,2<->8}] is not a valid graph. >>
Comment: I've corrected my answer. Should work in Mathematica 8

Plotting graph in Wolfram Mathmatica?


Do a render foreach loop on a regular field?

Question: I have a regular field with multiple values,
If i do
render( $fields['field1'] )

It prints
Field1_value1
Field1_value2
Field1_value3
etc

Am trying to get it to output like this
[Field1_value1]
[Field1_value2]
[Field1_value3]
etc

To add [ and ] to the output.
I thought of using a foreach loop, but the field array is like such
'#title' => 'xxxx',
'#type' => 'xxxx',
...
'0' => <array>,
'1' => <array>,
'2' => <array>,

How can I get it to loop throught the [0], [1], [2] etc only?
Note: I have no control on how many multiple values the field may have, so I have to loop.

Another solution that worked well for me: Display comma-separated list of taxonomy terms?
You can make use of the power of field.tpl.php.
Answer: $field_values = element_children($fields['field1']);
foreach($field_values as $field_value) { ... }

I was looking for the answer to this too, and ended up hunting through the render() function. It wasn't too far down the chain: drupal_render() calls element_children().

element_children
Identifies the children of an element array, optionally sorted by weight.
The children of a element array are those key/value pairs whose key does not start with a '#'. See drupal_render() for details.
Answer: Why don't you try a regular expression loop after the print? See here.
If you're really experiencing problems with the loop, check out the documentation for preg_replace_callback().


Xamarin.forms - checkbox trigger another checkbox's CheckedChanged event

Question: In my xamarin.forms app, I have a listview with checkboxes for the selection of the individual cell. What I am trying to do is multi select the checkboxes inside the listview by providing a "select all" checkbox outside the listview.The Multiselection works fine. For the "select all" checkbox click and individual checkbox click, I am performing some actions like an API Call. The Problem I am facing is Whenever I Click on the "select all" checkbox, the checkbox changed event of individual checkbox gets triggered.I know its natural But is there any way to prevent it like subscribe or unsubscribe the changed event of individual checkbox or something?

Xaml
<Grid >
        <Grid.RowDefinitions>
        <RowDefinitions Height="Auto"/>
        <RowDefinitions Height="Auto"/>
        </Grid.RowDefinitions>
        <StackLayout Grid.Row="0"  Orientation="Horizontal">

        <CheckBox x:Name="MultiselectCheckbox" ScaleX="0.8" ScaleY="0.8" CheckedChanged="MultiSelectCheckBox_CheckedChanged"  IsChecked="False" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Color="LawnGreen"></CheckBox>
        </StackLayout>
        <ListView
         x:Name="Listview"
         HorizontalOptions="FillAndExpand"
         ItemTapped="DistrictList_ItemTapped"
         VerticalOptions="FillAndExpand" >
                                    <ListView.ItemTemplate >
                                        <DataTemplate >
                                            <ViewCell >
                                                <ViewCell.View>
                                                    <Frame HorizontalOptions="FillAndExpand">
                                                        <StackLayout  Orientation="Horizontal" HorizontalOptions="FillAndExpand">

                                                            <CheckBox CheckedChanged="Single_CheckedChanged" IsChecked="{Binding Selected}" Color="LightBlue" HorizontalOptions="End" >
                                                            </CheckBox>
                                                        </StackLayout>
                                                    </Frame>
                                                </ViewCell.View>
                                            </ViewCell>
                                        </DataTemplate>
                                    </ListView.ItemTemplate>
                                </ListView>
      </Grid>

Multiselect Checkbox checked event
    private  void MultiSelectCheckBox_CheckedChanged(object sender, CheckedChangedEventArgs e)
    {

     if (!e.Value)
        {
         foreach (MyData TS in MyObject)
                    {
                        TS.Selected = false;
                    }
        }

     else{
        foreach (MyData TS in MyObject)
                    {
                        TS.Selected = true;
                    }

                    PerformSomeAction();
         }
    }

Single selection Checkbox changed event
     private void Single_CheckedChanged(object sender, CheckedChangedEventArgs e)
                {

                 if (!e.Value)
                    {
                    }
                 else{
                                PerformSomeAction();
                     }

}

Data Model
 public class MyData : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }

            public string name { get; set; }
            private bool selected;
            public bool Selected
            {

                get
                {
                    return selected;
                }

                set
                {
                    if (value != null)
                    {
                        selected = value;
                        NotifyPropertyChanged("Selected");
                    }
                }
            }
        }

Comment: Can you use a boolean flag (like `fromMultiSelect`) to restrict the single checkbox event?? Will it be enough for your purpose?
Comment: @Nikhileshwar The problem is user have enough freedom to multiselect or single select as they like. So I think keeping a boolean value is not sufficient
Comment: From what I understand what you are doing is making an API call based on selections? So if I select options A, B and C so only that data comes and if that is the case you are doing this wrong what you should be doing is always get all the data and then you rule out whatever is not relevant, Feel free to ask questions if you have any!
Comment: @FreakyAli Thanks for the reply. The Data will receive according to the checkbox item. So I cant fetch the whole data initially.When ever we  click select all, there is an Id corresponds to each item and will pass as list and get the data. If we click any single checkbox again API call with corresponding id will pass and obatin the result
Comment: I can manage these single and multi selection seperatly. Bu if we use these features together then the mentioned issue will happens
Comment: What I am saying is you always have the list of possible options then why are you not getting the whole data that is how you should be handling this in the first place! AFAIK that is the best solution!
Comment: @FreakyAli  I wish.But the API is not under my control. So is there any other workarounds to solve this issue?
Comment: @FreakyAli when user click on select all option, I just dont want the individual checkbox trigger.
Comment: AFAIK there is no direct way to do this you will have to add a boolean and handle this yourself!
Comment: As you are checking the individual CheckBox in the `MultiSelectCheckBox_CheckedChanged ` method why not set a boolean to true there. And check that boolean in the `Single_CheckedChanged ` before `PerformSomeAction ` and set the boolean back to false after the for loop in `MultiSelectCheckBox_CheckedChanged`. I don't think this might cause an issue. Will it??
Answer: Agree with @ Nikhileshwar , you could define some properties to get the different condition .And since you had used MVVM, you would better put all logic handling in your viewmodel .
in xaml
<Grid >
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <StackLayout Grid.Row="0"  Orientation="Horizontal" HeightRequest="40" BackgroundColor="LightPink">

        <CheckBox x:Name="MultiselectCheckbox" ScaleX="0.8" ScaleY="0.8"   IsChecked="{Binding MultiselectCheck}" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Color="Red"></CheckBox>
    </StackLayout>
    <ListView Grid.Row="1"
     x:Name="Listview"
     HorizontalOptions="FillAndExpand"
    ItemsSource="{Binding MyItems}"
     VerticalOptions="FillAndExpand" >
        <ListView.ItemTemplate >
            <DataTemplate >
                <ViewCell >

                        <Frame Padding="0" HeightRequest="40" HorizontalOptions="FillAndExpand">
                            <StackLayout  Orientation="Horizontal" HorizontalOptions="FillAndExpand">

                                <CheckBox  IsChecked="{Binding Selected}" Color="Red" HorizontalOptions="End" >
                                </CheckBox>
                            </StackLayout>
                        </Frame>

                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>

in ViewModel
public class MyViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    bool isMultiselect;
    bool isSingleSelect;
    public ObservableCollection<MyData> MyItems { get; set; }

    private bool multiselectCheck;
    public bool MultiselectCheck
    {

        get
        {
            return multiselectCheck;
        }

        set
        {
            if (multiselectCheck != value)
            {
                multiselectCheck = value;

                if(!isSingleSelect)
                {
                    isMultiselect = true;

                    foreach (MyData data in MyItems)
                    {
                        data.Selected = value;
                    }

                    isMultiselect = false;
                }

                NotifyPropertyChanged("MultiselectCheck");
            }
        }
    }

    public MyViewModel()
    {
        MyItems = new ObservableCollection<MyData>() {

             new MyData(){name="Selection1" },
             new MyData(){name="Selection2" },
             new MyData(){name="Selection3" },

        };

        foreach(MyData data in MyItems)
        {
            data.PropertyChanged += Data_PropertyChanged;
        }
    }


Is it possible to use wildcard mapping in IIS7

Question: I'd like to point user test1.domain.com test2.domain.com etc without manually adding the header binding in IIS7.
Is this possible?
If not automatically can I add the host header programmatically?
Answer: Yes you can.
It is possible to use a wildcard SSL certificate and one single IP.
I can detail how to test this using a self-signed wildcard.
Prerequisites

MakeCert.exe (Which should be part of a visual studio install or downloadable here)
winhttpcertcfg.exe (downloadable here)
APPCMD (Part of Vista / Server 2008 / Windows 7)
'Certificates' snap-in for Personal and Local Computer using MMC

Method
Execute the following command from a command prompt
makecert -r -pe -n CN=*.domain.com -ss my -sr currentuser -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 wildcard.domain.cer

then

From the RUN command or start menu, type MMC
File > Add or Remove Snap-ins - Select Certificates, Click Add, Select My user account, Click Finish
Repeat previous step and select My Computer (then selecting Local Computer)
Click OK
Expand Certificates - Current User > Personal > Certificates
Right click *.domain.com and All Tasks > Export. The PFX file contains both the public and private key for this cert, hence why your asked for a password.
Copy or Move the Certificate from Current User > Personal > Certificates to Local Computer > Trusted Root Certification Authorities > Certificates
Import the PFX into Local Computer > Personal > Certificates (this will be the certificate used by your web services.

Now let's create your web servers

Tidy up your environment :)

Remove existing demo app pools and sites
%windir%\system32\inetsrv\Appcmd delete site "Demo 1"
%windir%\system32\inetsrv\Appcmd delete site "Demo 2"
%windir%\system32\inetsrv\Appcmd delete AppPool "Demo 1 App Pool"
%windir%\system32\inetsrv\Appcmd delete AppPool "Demo 2 Portal App Pool"

Establish SSL Environment

Tell windows that Network Service is allowed access to your wildcard cert. and tell it to bind the cert to port 443 on your IP address
PathToWinHTTPCertCfg\winhttpcertcfg -g -i "wildcard.domain.com.pfx" -c LOCAL_MACHINE\My -a "Network Service" -p MySecretPassword
 netsh http add sslcert ipport=<YOURLOCALIPADDRESS>:443 certhash=<CERTIFICATE THUMBPRINT> appid=

Create App Pools and Sites

This is the code to create app pools and sites
%windir%\system32\inetsrv\Appcmd add site -id:100 -name:"Demo 1" -bindings:http/*:80:YOURLOCALIPADDRESS -physicalPath:<PathToDemo1Source> -logfile.directory:<PathToPutLogFilesIn> -traceFailedRequestsLogging.directory:<PathToPutTraceFiles>
%windir%\system32\inetsrv\Appcmd set app "Demo 1/" -applicationPool:"Demo 1 App Pool"
%windir%\system32\inetsrv\Appcmd set site /site.name:"Demo 1" /+bindings.[protocol='https',bindingInformation='*:443:demo1.domain.com']

%windir%\system32\inetsrv\Appcmd add site -id:200 -name:"Demo 2" -bindings:http/*:80:YOURLOCALIPADDRESS -physicalPath:<PathToDemo2Source> -logfile.directory:<PathToPutLogFilesIn> -traceFailedRequestsLogging.directory:<PathToPutTraceFiles>
%windir%\system32\inetsrv\Appcmd set app "Demo 2/" -applicationPool:"Demo 2 App Pool"
%windir%\system32\inetsrv\Appcmd set site /site.name:"Demo 2" /+bindings.[protocol='https',bindingInformation='*:443:demo2.domain.com']

...and that should be you ;) Enjoy!
Answer: As far as I know there are only two options when it comes to host headers in IIS7.

You set up a host header/type/port/ip for each domain you want it to handle.
You set up no host header but include a type/port/ip on the site you want to handle the multiple domains.

The catch with option #2 is it'll respond to any request on that port and you will be unable to use that same port on another site without a host header.
There may be an ISAPI filter you can load at the server level to intercept the request before it gets to the host header part of the processing but it may be easier to set up a script to handle option #1.
Answer: By setting up a wildcard DNS entry, you can have as many names as you want go to your default website.  Once the user hits that website, if you need it to redirect to another site, have your default.asp file look for the HOST header to determine if it needs to redirect, otherwise, go ahead and load the rest of the site.
References:
Wildcard Host Headers with IIS7
List of HTTP headers
I'm not very good with web development, but this should at least get you started.
Comment: Keep in mind that this method is like method #2 above - you will still need one IP per site.
Comment: From the way that the support doc was written, it sounds like regular host headers will work, but yes, anything that needs a wildcard will need its own ip.