get index from multiple list in C#

Question: I have this list in my program
private static List<User> us = new List<User>();
public string fNames, lNames, pWs, uNames;
public int uIds;

this is how I add the data to the list
 us.Add(new User { uIds = uId, fNames = fName, lNames = lName, pWs = password, uNames = uName+uId });

i need to get index of us.uNames in us list when input is same with uName
 Console.Write("Username : ");
 string uName = Console.ReadLine();

 int j = us[uNames].IndexOf(uName);

Comment: Where do you ever populate the list `us`?
Comment: A) indexing a collection `[...]` takes an integer, you're giving it `uNames`, which is a string. B) After indexing `us`, you would receive a `User` object, which most likely doesn't have a `.IndexOf()` method.
Comment: Very confusing what you trying to do (ideally you'd show example data and expected result). I think you are looking to find index of object in a list by property - and picked duplicate based on my understanding. If that is not the case please [edit] the question to clarify why FindIndex is not what you are looking for and show data along with desired  output.
Answer: Do you want to do this? I mean find the index of item where uNames is equal to the given value?
var index = us.FindIndex(c => c.uNames == uName);

get index from multiple list in C#


Let $a,b \in Z^+$, let $c = {ab}/{\gcd(a,b)}$

Question: Let $a,b \in Z^+$, let $c = {ab}/{\gcd(a,b)}$ Show that:
i) If $a\mid d$ and $b\mid d$ then $c\mid d$
ii) $c=\min\{d \in Z^+ \text{ such that }a\mid d \wedge b\mid d\}$
Comment: If $a\vert d$, then there exists an $x\in\Bbb Z$ such that $ax=d$. If $b\vert d$, then there exists a $y\in\Bbb Z$ such that $by=d$. Then, what's $ab$? What's the greatest common divisor of $a$ and $b$? The second part is telling you that $c$ is the lowest common multiple.
Comment: algebraically $ab = d^2/xy$. I've tried subbing that into the second part of the equation but now i'm stuck
Answer: Let $a' = \frac a{\gcd(a,b)}$ and $b' = \frac b{\gcd(a,b)}$.
Claim 1:  $\gcd(a',b')=1$.
Proof:  $K=\gcd(a,b)\gcd(a',b')$ is a common divisor of $a$ and $b$ so $K\le \gcd(a,b)$ so $\gcd(a',b') = 1$.
Claim 2:  If $\gcd(m,n) = 1$ and $m|nk$ then $m|k$.
Pf: Intuitively $m$ and $n$ have no factors in common so the only factors $m$ has in common with $nk$ are factors of $k$.  You can do this formally with prime powers dividing $m$ must all divide $k$ as they can't divide $n$.  Or we can do it with Bezout's Lemma:  there are $a,b$ so that $am+bn=1$ so $mj=nk$ so $bmj=bnk=k-amk$ so $m(bj-ak)=k$ and $m|k$.
....
So now... we just do it.
$a = a'\gcd(a,b)$ and $b=b'\gcd(a,b)$ and
$a|d$ means there is an $m$ so that $am = d$ and $b|d$ means there is a $n$ so that $bn = d$.
So $a'\gcd(a,b)m = b'\gcd(a,b)n = d$.  So $a'm = b'n = \frac {d}{\gcd(a,b)}$ and $\gcd(a,b)|d$.
$a'm = b'n$ so $a'|b'n$ but $\gcd(a',b') =1$ so $a'|n$ and, likewise, $b'|m$.
SO let $m = b'm'$ and $n = a'n'$ and we have:
$d = ab'm' = ba'n'$.  Where $ab' = a\frac b{\gcd(a,b)}=\frac {ab}{\gcd(a,b)} = b\frac a{\gcd(a,b)} = ba'$.  So $c = \frac {ab}{\gcd(a,b)}= a'b=b'a$.
So $d = cm'=cn'$ and $c|d$ (and $n'=m'$ by the way).
....
ii) If $a|d$ and $b|d$ then $a=a'\gcd(a,b)$ and $b=b'\gcd(a,b)$ so $a'|d$ and $b'|d$ and $\gcd(a,b)|d$.
So the least common multiple of $a', b', \gcd(a,b)$ divides $d$. and least common multiple of $a',b'\gcd(a,b) = a'b'\gcd(a,b) =c$.


android - EditText length filter not working as it should

Question: First I have to say I have read similar questions and answers here on SO and this question is basically a duplicate of this question and many others but the answers given to those questions doesn't work like the way i want it.
The problem:
Setting length filter on my EditText programmatically like this:
editText.setFilters(new InputFilter[]{new LengthFilter(10)} );

The only thing it does is hide the text that go over the limit in the EditText. It still shows the long (unlimited) text in suggestion box and i have to delete (backspace) for each letter that go over before being able to delete what is shown in the EditText.
Suggested Solutions:

Setting InputType to textFilter.
Programmatically I did this:
editText.setInputType( InputType.TYPE_TEXT_VARIATION_FILTER );

It hides suggestions but the unlimited text is still present and i still have to use backspace to delete letters that shouldn't be present.
Setting InputType to textNoSuggestions|textVisiblePassword.
Programmatically I did this (had to add TYPE_CLASS_TEXT too otherwise it wouldn't work):
editText.setInputType( InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD );

This one does work but the problem is it stops "gesture typing" and it changes the font to monospace.

Better Solutions?
As you can see these two methods don't actually work without additional problems. Is there any other way of doing this that I missed. Should I just use a TextWatcher if I want to keep gesture typing and suggestions?
Answer: I ended up using a TextWatcher instead. I'm not sure if it is the best way to do this but it does work with suggestions and it doesn't turn off gesture typing or change the font style. Here's how I did it (I'm quite new to android so if this needs improvement feel free to let me know).
I added an example in the comments to clarify what is going on.
Make these global variables:
private boolean mWatcherIsBlocked = false;
private String mBeforeChange;
private String mFilteredString;
private int mCursorPosition = 0;

Then create the TextWatcher and add it to your EditText
final int maxLength = 10; // desired length limit

/**
 * lets say our EditText is showing "abcdefgh". We select "cdef" from it and
 * paste a new text "ijklmnop" in the middle. What we should get according to
 * our maxLength is this:
 * (1) "ab" (0th up to the letter from before_change_text we were selecting) +
 * (2) "ijklmn" (part of the text we pasted minus the number of letters the whole
 *      after_change_text goes over the 10 letter limit) +
 * (3) "gh" (last part of before_change_text that wasn't selected)
 *
 * so the new text has to be "abijkmngh"
 */

TextWatcher textWatcher = new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // get before_change_text if textWatcher isn't blocked
        if (!mWatcherIsBlocked) mBeforeChange = s.toString();
    }
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (!mWatcherIsBlocked){
            // get after_change_text if textWatcher isn't blocked
            String after = s.toString();
            // if after_change_text's length is bigger than the limit
            if (after.length() > maxLength) {
                // see how much it goes over the limit
                int over = after.length() - maxLength;
                // add parts (1) and (2) like our example above
                String st = mBeforeChange.substring(0, start) + // (1)
                            after.substring(start, start + count - over); // (2)
                // get where the cursor position should be after pasting (
                // = after the last letter we could paste = length of (1) + (2) )
                mCursorPosition = st.length();
                // now add part (3) of our text to the first two
                st += mBeforeChange.substring(
                          mBeforeChange.length() - (maxLength - st.length()),
                          mBeforeChange.length());
                // now assign this new text to a global variable
                mFilteredString = st;
            } else {
                // if after_change_text hasn't gone over the limit assign it
                // directly to our global variable
                mFilteredString = s.toString();
            }
        }
    }
    @Override
    public void afterTextChanged(Editable s) {
        // if filtered text is not the same as unfiltered text
        // or textWatcher is not blocked
        if (!mFilteredString.equals(s.toString()) && !mWatcherIsBlocked) {
            // block textWatcher to avoid infinite loops created by setText
            // (this might not work as I well as I think!)
            mWatcherIsBlocked = true;
            // set new text to our EditText
            editText.setText(mFilteredString);
            // set its cursor position
            editText.setSelection(mCursorPosition);
            // unblock the textWatcher
            mWatcherIsBlocked = false;
        }
    }
};

// add the TextWatcher to our EditText
editText.addTextChangedListener(textWatcher);


Create matlab array with same values for several sections

Question: I want to create an array of length Ns(Ns+1) and I need the first Ns elements to be 0, the next Ns elements to be 1, ..., the last Ns to be Ns.
I am well aware that there are plenty of ways to do this with for-loops, which I want to avoid for this particular task. I am looking for a way to do this using matlab functions and notions of vectorization.
For example, I had a similar array that I wanted to populate with 0, 1, 2, ..., Ns, 0, 1, 2, ..., Ns, 0, 1, 2, ... and I accomplished that with
my_array = repmat(0:Ns, 1, Ns+1);

Is there a similar approach to be taken to achieve my purpose?
One thing I thought I could do would be to create a matrix like
0 0 0 ... 0
1 1 1 ... 1
... ... ...
Ns Ns .. Ns

and then concatenating the lines; I would know how to create the matrix but not how to concatenate the lines into an array.
Are there any other ways? Suggestions of commands are also acceptable!
Thanks.
Answer: You could do it with repmat, but it's straightforward with repelem:
my_array = repelem(0:Ns, Ns);

Answer: Here's another way:
result = ceil(-1+1/Ns:1/Ns:Ns);

Or, for a general array:
data = [4 1 2 5];
Ns = 3;
result = data(ceil(1/Ns:1/Ns:numel(data)));

which gives
result =
     4     4     4     1     1     1     2     2     2     5     5     5

This can be done even without ceil, exploiting implicit rounding in colon indices (not documented; more fun than practical):
data = [4 1 2 5];
Ns = 3;
result = data(.5:1/Ns:numel(data)+.5-1/Ns);

Answer: The reshape command may be relevant
>> Ns = 3;
>> a = repmat(0:Ns, Ns, 1)
a =
 0     1     2     3
 0     1     2     3
 0     1     2     3

>> b = reshape(a, 1, [])
b =
 0     0     0     1     1     1     2     2     2     3     3     3


How to Properly Escape Nested Special Characters

Question: I need to save below example sentences as a file called demo.sh.
#!/usr/bin/env bash
xmessage This is "first sentence"
xmessage This is 'second sentence'
xmessage This is {third sentence}

The code I use in C is below:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    system("sudo bash -c 'printf \"#!/usr/bin/env bash\n\" > /usr/share/applications/demo.sh'");
    return 0;
}

I can write the first sentence of the above 4 sentences OK into the file. But the other sentences contain special characters like single quotes, double quotes and line ending character. And this gets very difficult to escape because sudo command needs to have two nested section which I tried to wrap by ' and " separately.
How can I escape the sentences and write out to the file? It would be great to have some function because actually the file is more than 4 sentences and have many special characters.
As a note, I know I could use I/O functions of C, I want to write the file by a single system command which use sudo, printf and one line string.
Comment: Using the `system` is effectively the same as entering those commands in a terminal, any reason for not doing it that way?
Comment: During testing program could not write to `/usr/share/applications/` location because it belongs to `root`. I saw using `sudo bash -c` way is working in Terminal. So I wanted to port the Terminal way into C program. For simple sentences it went great but whenever the sentence contained special characters, it got terribly complex.
Comment: This is not porting it to C, this is merely executing the same bash commands through a C program
Comment: I may have used wrong terminology but you are right. I am writing a file by Terminal command in C.
Answer: I dont thing that its the best way, but you can use one char[] variable for system command and sprintf() function to split and write command in this variable
here is an example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char command[128];

    /* Generate string */
    sprintf(command, "sudo bash -c %s %s bash\n > /usr/share/applications/demo.sh'",
        "'printf", "#!/usr/bin/env");

    system(command);
    return 0;
}

Comment: Thanks for the tip. I modified your code but whenever I go to second line, it looks horrible. I had to use 3 backslashes for the second sentence double quote escaping. `sprintf(command, "sudo bash -c %s %s > /usr/share/applications/demo.sh'",
        "'printf", "\"#!/usr/bin/env\\nxmessage This is \\\"first sentence\\\"\"");`
Comment: I am not sure why it is needed 3 backslashes.


Cannot install phablet-tools, has no installation candidate

Question: Whenever I run the following command
$ sudo apt-get install phablet-tools android-tools-adb android-tools-fastboot

my terminal shows this
$ sudo apt-get install phablet-tools android-tools-adb android-tools-fastboot
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package phablet-tools is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
However the following packages replace it:
  repo

E: Package 'phablet-tools' has no installation candidate

Comment: Please [edit] your question and add your Ubuntu version. `phablet-tool` is [available only for 14.04 LTS and 16.04 LTS](https://packages.ubuntu.com/search?suite=all&section=all&arch=any&keywords=phablet-tools&searchon=names).
Answer: The package was removed from the archive after Canonical dropped support of phones and the unity 8 stack.
If you are on either Ubuntu 14.04 or Ubuntu 16.04, the phablet-tools package is in the universe repository, so you must make sure it is enabled in Software Properties before you'll be able to install it.


Why can't I feed or breed animals in Minecraft: Xbox 360 Edition?

Question: I have wheat in my hand even if they look directly at the animals they still won't follow me. Also, there is no button at the bottom that says feed. Why?
Answer: Minecraft for Xbox 360 is based on an older version of Minecraft1, and because of this, breeding is not available in it.
Note 1: specifically, Beta 1.6 with some additional backported features. Breeding was introduced in Beta 1.9.
Comment: Oh, that stinks :( but thanks for letting me know :)
Comment: Not to worry. As of now, they are working to get the Adventure Update and pistons added into the game. The XBox version has reached 1 million+ downloads, so it'll be no surprise if they put their full attention on that game.
Answer: Minecraft for the Xbox 360 (MCX360) is a ported version of a much older version of the game - 1.6. Because of this, we don't get many of the newer features like breeding sheep and enchanting.
Don't worry, though, they have announced they will be updating MCX360 to Beta 1.7.3, which means we can get Pistons! And I'm sure they will continue to update MCX360 to later versions of Minecraft when they can.
Comment: Here is a related announcement: [Minecraft Xbox 360 Patch 1.7.3 Release Date 'Within 10 Days'](http://www.nowgamer.com/news/1464385/minecraft_xbox_360_patch_173_release_date_within_10_days.html)


inputs of 2 separate predict() return the same set of fitted values

Question: Confession: I attempted to ask this question yesterday, but used a sample, congruent dataset which resembles the my "real" data in hopes this would be more convenient for readers here. One issue was resolved, but another remains that appears immutable.
My objective is creating a linear model of two predicted vectors: "yC.hat", and "yT.hat" which are meant to project average effects for unique observed values of pri2000v as a function of the average poverty level "I(avgpoverty^2) under control (treatment = 0) and treatment (treatment = 1) conditions.
While I appear to have no issues running the regression itself, the inputs of my data argument have no effect on predict(), and only the object itself affects the output. As a result, treatment = 0 and treatment = 1 in the data argument result in the same fitted values. In fact, I can plug in ANY value into the data argument and it makes do difference. So I suspect my failure to understand issue starts here.
Here is my code:
q6rega <- lm(pri2000v ~ treatment + I(log(pobtot1994)) + I(avgpoverty^2)
   #interactions
   + treatment:avgpoverty + treatment:I(avgpoverty^2), data = pga)

## predicted PRI support under the Treatment condition
q6.yT.hat <- predict(q6rega,
data = data.frame(I(avgpoverty^2) = 9:25, treatment = 1))
## predicted PRI support rate under the Control condition
q6.yC.hat <- predict(q6rega,
data = data.frame(I(avgpoverty^2) = 9:25, treatment = 0))

q6.yC.hat == q6.yT.hat

TRUE[417]

dput(pga has been posted on my github, if needed
EDIT: There were a few things wrong with my code above, but not specifying pobtot1994 somehow resulted in R treating it as newdata being omitted. Since I'm fairly new to statistics, I confused fitted values with the prediction output that I was actually trying to achieve. I would have expected that an unexpected input is to produce an error instead.
Answer: I'm surprised  you are able to run a prediction when it is lacking the required variable (pobtot1994) for your model in the new data frame for prediction.
Anyway, you would need to create a new data frame with the three variables in untransformed form used in the model. Since you are interested to compare the fitted values of avgpoverty 3 to 5 for treatment 1 and 0, you need to force the third variable pobtot1994 as a constant. I use the mean of pobtot9994 here for simplicity.
newdat <- expand.grid(avgpoverty=3:5, treatment=factor(c(0,1)), pobtot1994=mean(pga$pobtot1994))

  avgpoverty treatment pobtot1994
1          3         0   2037.384
2          4         0   2037.384
3          5         0   2037.384
4          3         1   2037.384
5          4         1   2037.384
6          5         1   2037.384

The prediction will show you the different values for the two conditions.
newdat$fitted <- predict(q6rega, newdata=newdat)

  avgpoverty treatment pobtot1994   fitted
1          3         0   2037.384 38.86817
2          4         0   2037.384 50.77476
3          5         0   2037.384 55.67832
4          3         1   2037.384 51.55077
5          4         1   2037.384 49.03148
6          5         1   2037.384 59.73910


Regular Outlet Tripped, Now Various Outlets Are Dead

Question: Recently, I purchased a new small appliance and when I plugged it in, it did not work.  After using an extension cord, I used another outlet and figured out that the original outlet was at fault.  As I removed the outlet plate before going to switch the breaker off, the outlet suddenly sparked.
After the spark, I noticed that the GFCI outlet in my kitchen was not resetting and thus not working.  I then noticed that a few outlets around the house, along with a couple of light switches stopped working.  I checked all breakers both main and the sub, and none had tripped, but reset them anyway.
As I thought the issue may be the faulty GFCI in the kitchen, I was about to replace it and when I checked to see if there's activity, the meter showed nothing.  This may sound like a ridiculous question, but could a GFCI that is not hot when connected work properly after it is connected?  If this isn't the issue, could it possibly be a circuit gone bad or a fuse (even though none had tripped and all were reset)?  Any input is greatly appreciated.  Thanks in advance!
Comment: There are a few questions you need to answer before we can help you resolve your problem. First did you plug your small appliance in the kitchen? Second when you unplugged your appliance was it on or off ? Third did the outlet spark or did the cord arc when you pulled it out? Forth are all of the outlets not working on the same circuit? Finally are you sure all of your breakers are on and not in the tripped position? Please answer as many of these questions as you can since it will help us identify the problem.
Comment: Thanks for answering.  The small appliance was technically plugged into the kitchen (I have a small divider wall that divides the main kitchen from a "nook" area" but that wall was built by myself and was initially an open kitchen floor-plan.  When I unplugged the appliance, it was in the off position.  All I saw when it occurred was a fairly decent sized spark.  I assume it was from the outlet itself but on second thought, possible from the cord itself.  2 of the 3 outlets are not working (1 is the GFCI).  After reading you response I went ahead again to make sure no circuit was tripped. Than
Answer: Another backstab casualty
We get these all the time.
First, the arc flash when you opened up the first box had a simple reason: the receptacle shifted position, and the "hot" screws on the side of the receptacle hit the grounded metal box.  Possibly contributing was the screws being all the way out in their highest position, because the screws were not used to attach the wires.  This surge was massive, in the hundreds of amps, and it caused the root problem.
The root problem is most likely one we've seen before: "backstab" connections in receptacles upstream of the incident socket.  Backstabs are intended for high production assembly of house wiring e.g. In developments.  The "electrician" jabs the wires in a hole, and the hole grabs the wire. However, these make "point" contact with the wire in just 2 places, quite unlike the long edge contact you get on a side screw.  As such, they are very vulnerable to "failing open" under heavy load, even when loaded only with ordinary household loads such as a 12A heater.
This is made much worse when a wire is pried out of a backstab, and the hole reused; extracting the first wire weakens the spring.  It is, after all, only 1 of 4 springs in a 60 cent socket.  I've seen backstabs designed to make edge contact, but they respond badly to side strain on the wire, and it's hard to avoid that when shoving wires into the junction box.
The upshot is, I bet you will find a lot of backstabs in this house.  If you knew the circuit layout, you could focus on the first failed outlet and the one before.
Twist/pull the wires out of the backstabs, don't cut them because a) it's a waste of precious wire length, and b) you can then inspect the wires for evidence of arcing. Move them to the side screws, and torque firmly (Code now calls for a torque screwdriver).  Also run down all the side screws.  Bonus points for wrapping the outlet a few turns of electrical tape to cover all the screws.  Don't back screws all the way off, that wrecks the receptacle.
Comment: Harper--thanks for the input and after rereading your instructions ( to make sure I have it all down), I am going to test it out tomorrow.  I'll move the wires to the side screws and see what happens.  I've always been a sucker for bonus points since I was in grade school, so I'll definitely be wrapping electrical tape; easy task for some point :)  Thanks again!


How to whitelist people without restarting the server?

Question: I have a server and I want to be able to add people to my whitelist from inside the server so that I dont have to restart the server though when I type in what I have to:
<code>/whitelist add username_of_person_to_add
</code>
It just says that I dont have permission even though I am a level in the OP.json file
I have tried changing the level that I am an OP though it hasn't helped
Comment: You need to add yourself as op from the server console or ops.txt (I think) before you can use commands like `/whitelist`
Comment: Are you using any permissions plugins or vanilla Minecraft? Some more detail about your server setup would be very helpful and assist in getting the question answered.
Answer: One thing you can do is type in console is
"whitelist add username"
If you can not do that,
http://dev.bukkit.org/bukkit-plugins/permissionsex/
Create a group,
<code>  Admin:
    default: false
    build: true
    permissions:
    - '*'
</code>
If you create a group set it to false If you want only certain people to have it or true if anyone can have it.
In console type "pex user add [USERNAME] group add Admin"
If you do not have that try /reload
Answer: I managed to do it with the same code though in the gui


how can i get objc_property_t type

Question: i can get objc_property_t property name by property_getName(property)
unsigned int outCount;

objc_property_t *properties = class_copyPropertyList([model class], &outCount);

for (int i = 0; i < outCount; i++) {

    objc_property_t property = properties[i];

    NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];

}

but how can i get the type about property like CGFloat or NSString or NSInteger....
Answer: Using the objc_property_t, you need to call property_getAttributes() and then the property type is at the front of a rather cryptic string - to see some code that parses the result of that, see this answer:
property type or class using reflection

how can i get objc_property_t type


Bluetooth Mouse Pairs and Connects But Doesn't Do Anything

Question: Is there way to achieve a better experience with the Bluetooth driver or an alternative driver?
You can see what I did, updated the firmware. Mouse works fine in Windows still. Now in Ubuntu, I forget the mouse, re-pair, it shows both paired and connected, and registers no clicks nor movement.
It's not like Logitech MX Anywhere 2 mouse pairs but doesn't do anything because it shows Type = Mouse.
01/29/17
The plot thickens:
I got a brand new USB mouse. One of the buttons controls volume, so I know it's connected and somewhat working. However, it doesn't click nor point. In xsetpointer -l | grep Pointer, it has XExtensionPointer next to it, and it's showing up in the list of devices. Maybe this helps diagnose the problem?
Comment: Does the mouse show in the battery indicator?  May be bug 1098959, Bluetooth Battery Indicator Interferes with Bluetooth Mouse Moves.
Comment: The mouse does show in the battery indicator. The mouse has always shown in the battery indicator, and worked. It is only after updating firmware that mouse doesn't work in Ubuntu 16.10, and it still works and always worked on the same machine/bluetooth device in Windows. Is there any way to specifically test whether that bug is the problem? I don't really see anything specific about that bug. Like, how do I know whether the battery indicator is interfering with mouse moves, or if the battery indicator is existing and NOT interfering with mouse moves?
Answer: In a terminal, run sudo hcidump and see if moving the mouse produces output (even if the cursor does not move).  If it does, add yourself to the bug #1098959 (question "does this affect me?" in upper left corner).
Try the suggested solutions, reboot with Bluetooth off, kill the powerd process, start Bluetooth, run without a battery in laptop to suppress the title bar battery notification (may be some power options to set too).
And finally if all else fails, just change your mouse.  Only some mice have this problem.  My generic BT mouse had the problem, but a Microsoft Sculpt Comfort does not (and it does not display any mouse battery in the indicator either).
Comment: The mouse does not produce output by moving it around and clicking. It does do some lines of input when the mouse connects/disconnects.

I ordered a wired mouse out of frustration. But this is really poor user experience. Something Ubuntu really needs to tackle to make Ubuntu worth using. Bluetooth connected devices are essential to users' personal  computing experiences.


Is it possible to have multiple pointcuts with different arguments in Spring AOP?

Question: I have single advice method with multiple pointcuts. Is it possible to have different arguments?
   @Around("execution(* com.admin.web.controller.*.*.*(javax.servlet.http.HttpServletRequest,com.admin.model.PortalRequestTransaction)) && args(request,portalRequestTransaction)"
        + " || execution(* com.admin.web.controller.BaselineImporterController.*(javax.servlet.http.HttpServletRequest,..)) && args(request)")
public Object auditAround(ProceedingJoinPoint joinPoint, HttpServletRequest request,
                          PortalRequestTransaction portalRequestTransaction) throws Throwable { // some code here }

For example, Is it possible to the first pointcut to have 2 arguments and for the second one to have only one argument and second one passed as null?
If this is not possible, what is the best solution?
Comment: You may use [JoinPoint.getArgs()](https://www.eclipse.org/aspectj/doc/released/runtime-api/org/aspectj/lang/JoinPoint.html#getArgs()) to get the method arguments as an object array.
Answer: One way to achieve this is using JoinPoint.getArgs() to get the method arguments as an object array. This involves reflection.
A sample code to achieve this would be as follows
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class TestAspect {

    @Pointcut("execution(* com.admin.web.controller.*.*.*(javax.servlet.http.HttpServletRequest,com.admin.model.PortalRequestTransaction))")
    public void requestNTransaction() {}

    @Pointcut("execution(* com.admin.web.controller.BaselineImporterController.*(javax.servlet.http.HttpServletRequest,..))")
    public void requestAsFirstArg() {}

    @Around("requestNTransaction() || requestAsFirstArg()")
    public Object auditAround(ProceedingJoinPoint pjp) throws Throwable {
        // get the signature of the method to be adviced
        System.out.println(pjp.getSignature());
        Object[] args = pjp.getArgs();
        for(Object arg:args) {
            // use reflection to identify and process the arguments
            System.out.println(arg.getClass());
        }
        return pjp.proceed();
    }

}

Note:

Individual methods serving as Pointcut signature . Spring documentation
ProceedingJoinPoint for @Around advice type
Comment: This answer is correct insofar as it is a functional workaround. The actual explanation for why argument binding like this does not work is that it would be **ambiguous**: If both conditions in `||` would match, which value should be selected for binding? If you would compile this with the AspectJ compiler (not just use Spring AOP), you would see a compile error: `ambiguous binding of parameter(s) ... across '||' in pointcut`. Spring AOP uses AspectJ pointcut matching, but does not compile aspects, so you only notice during runtime that is simply does not work.
Comment: The answer is this point "Individual methods serving as Pointcut signature " so we can start searching for another approach. I wanted to avoid looping throw arguments by adding another @Around method and both of them calls common method with it's parameter.
Answer: Yes, it is possible to have multiple point-cuts in your advice, and it's done with this generic syntax:
@AdviceType("execution(point-cut1) || execution(point-cut2) || execution(point-cut3)")
public void foo(){}

Note, that @AdviceType and point-cutX are conceptual names, and you should change them respectively with your advice and pointcut[s].
Comment: Thanks Giogri, Yes I can have multiple point-cuts but i'm asking about passing different agrs, each point-cut has different args.
Comment: You want to have an optional method parameters?
Comment: Yes, for the first point-cut I want to pass 2 arguments and for the second point-cut I want to pass only one argument.
Comment: Then this is not about AOP, but rather about Java. What about defining the method with a superset of parameters and mark optional parameters as nullable? you'll just need to manually check what you have received and what not, in your method.
Comment: As it's about Java, I solved it by adding another @Around method and both of them calls common method with it's parameter.


Could not find RubyGem railties

Question: I try to create new app with "rails new" command however getting this error:
'report_activate_error': Could not find RubyGem railties (>= 0) (Gem::LoadError)
 from /usr/lib/ruby/vendor_ruby/1.8/rubygems.rb:244:in 'activate_dep'
 from /usr/lib/ruby/vendor_ruby/1.8/rubygems.rb:236:in `activate'
 from /usr/lib/ruby/vendor_ruby/1.8/rubygems.rb:1307:in `gem'
 from /usr/local/bin/rails:18

Any idea why?
by the way I am working on Ubuntu
gem list

*** LOCAL GEMS ***

it is empty but I installed rails just before
Comment: Can you please run the following in terminal and output it here?

gem list
Comment: Well I'd try `gem install rails` and see where that gets you first.
Comment: You installed ruby from ubuntu repo? Might be you try install gems into /usr without sudo, and get errors. I recommend to you install RVM.
Comment: It looks like you're operating on an empty list of gems. You'll need to install Rails before trying to use it.
Comment: I installed rails and ruby with RVM however there was an early ruby installation and I delete it after RVM installation. In addition I execute gem install rails and it install all the gemss needed but I think system cannot find the necessary gem or rails
Answer: I have encountered the issue before.The solution is :
you must use comand gem install rails, not sudo gem install rails.
Answer: I encountered the same problem and found the following solution Here which was mentioned here. Hope it helps
After you installed RVM and after you set the default Ruby version in RVM, you need to re-install all ruby gems, e.g.
gem install rails
you need to install those gems as the user, not as root.
Because from now on RVM will keep track of all installed gems by the ruby version which was used to install them!
Answer: You need to install RVM (I don't know it is the best solution but it works) then use such rails commands like rvmsudo rails new or such. I use rails and ruby command with including rvm or rvmsudo phase and all of them start to work.
Answer: Do you have multiple Ruby installations on your system? Maybe you have installed some package (like Heroku with full installation) and you are using the 'new' Ruby installation. I have uninstalled the last Ruby and everything seems to be fine.
Edit: Not everything is fine... yet. Under Windows you will have to edit Heroku.bat (in your Program Files/Heroku path) and change the path to Ruby installation folder.
Answer: Install rvm and try it again to install rails
RVM provides a very great way to manage your gems in Gemsets
for multible ruby installations.
On the offizial rvm site is a installation tutorial
http://beginrescueend.com/

Could not find RubyGem railties


My GitHub webpage isn't available on the web

Question: My GitHub page (https://visheshbons.github.io/cv/) isn't opening properly. All I get is this:

I tried deleting the repository and remaking it so it would come but it just gave me error 404 anyway.
Can you please give me some solutions?
Thanks.
My problems are solved for HTML code, but my CSS isn't there. Image-without-css
Thanks! My problem is solved!
Answer: You have to publish your website, from your repository settings, go to "Pages"

Then choose your branch and your root folder

then click on "Save" and wait for couple of minutes for your website to be published, then refresh the page to see your URL like this:
Comment: Check this "https://github.com/Visheshbons/cv/deployments/activity_log?environment=github-pages", it means that your website was deployed 3min ago. Now refresh your page, if you still see a 404 try doing a "hard reload" with Cmd+Shift+R
Comment: My CSS isn't available
Comment: The path for your CSS is wrong, it should be `CSS/styles.css` instead of `css/styles.css` (Use inspect element to see the result, and compare it to what you have in the repository)
Comment: Thanks, Fcmam5! you fixed my problem!


How to identify the ultimate parent from a nested table structure using python?

Question: I have the following table:

My question is: how do I programmatically identify the ultimate parent?
Here are the rules explained through an example:

the id 5.0's parent is 51.0. The id 51.0 has no parent. Therefore, the id 5.0's ultimate parent is 51.0.
the id 6.0's parent is 1.0. The id 1.0's parent is 10.0. The id 10.0 has no parent. Therefore, the id 6.0's ultimate parent is 10.0.
the id 2.0 has no parent. Therefore, the ultimate parent_id for 2.0 is 2.0

There are no duplicates in the id field and I don't know beforehand how many levels of nesting there could be in the id structure.
Here is the code for this example:
import pandas as pd
import numpy as np

original_df = pd.DataFrame({'id': pd.Series([5., 6, 2, 51, 1, 70, 10])
              ,'parent_id': pd.Series([51, 1, np.nan, np.nan, 10, np.nan, np.nan])})
original_df['ultimate_parent_id'] = ''
original_df

Here is what the final table should look like:

Here is the code for generating that file.
final_df = pd.DataFrame({'id': pd.Series([5., 6, 2, 51, 1, 70, 10])
              ,'parent_id': pd.Series([51, 1, np.nan, np.nan, 10, np.nan, np.nan])})
final_df['ultimate_parent_id'] = pd.Series([51., 10, 2, 51, 10, 70, 10])
final_df

If possible, I would be very interested both in solutions that use a while loop as well as solutions that utilized vectorized operations.
Comment: This task is inherently sequential (not vectorizable). Pandas is a bad tool for such job. If you know the maximal path-to-parent length N and have enough memory space, you can probably join the dataframe to itself N times.
Comment: @DYZ Pandas is just the format that the data happens to be in to start and end with. **I'd definitely be open to a solution that relies on a different data structure** as long as it could be converted back to into a 2-dimensional table structure afterwards.
Comment: For example:  `original_df.to_dict()` would turn it into a dictionary format. It's fine to make the solution starting point this dictionary: `{'id': {0: 5.0, 1: 6.0, 2: 2.0, 3: 51.0, 4: 1.0, 5: 70.0, 6: 10.0},
 'parent_id': {0: 51.0, 1: 1.0, 2: nan, 3: nan, 4: 10.0, 5: nan, 6: nan}}`
Answer: In the same vein as @Vaishali's answer, here is a version that uses Python looping over the major operations, but uses np / pd operations within the dataframe:
import pandas as pd
import numpy as np

df = pd.DataFrame(
        { 'id': pd.Series([5., 6, 2, 51, 1, 70, 10]),
        'parent_id': pd.Series([51, 1, np.nan, np.nan, 10, 51, np.nan])
        }
    )

def find_ultimate_parents(df):
    # Make a copy of df, using 'id' as the index so we can lookup parent ids
    df2 = df.set_index(df['id'])
    df2['nextpar'] = df2['parent_id']

    # Next-parent-2 not null - fake it for now
    np2nn = df2['nextpar'].notnull()

    while np2nn.any():
        # Lookup df2[parent-id], since the index is now by id. Get the
        # parent-id (of the parent-id), put that value in nextpar2.
        # So basically, if row B.nextpar has A, nextpar2 has (parent-of-A), or Nan.

        # Set na_action='ignore' so any Nan doesn't bother looking up, just copies
        # the Nan to the next generation.
        df2['nextpar2'] = df2['nextpar'].map(df2['parent_id'], na_action='ignore')

        # Re-evaluate who is a Nan in the nextpar2 column.
        np2nn = df2['nextpar2'].notnull()

        # Only update nextpar from nextpar2 if nextpar2 is not a Nan. Thus, stop
        # at the root.
        df2.loc[np2nn, 'nextpar'] = df2[np2nn]['nextpar2']

    # At this point, we've run out of parents to look up. df2['nextpar'] has
    # the "ultimate" parents.

    return df2['nextpar']

df['ultimate_parent_id'] = find_ultimate_parents(df)
print(df)

The loop guard checks np2nn.any() which is a vector op on a boolean Series. Each pass through the loop looks up the "next parent", so the number of passes through the loop will be the maximum depth of any child-parent chain. The worst case in O(N), for a list like 1->2->3->4->...->n. The best case is 0, for a list with no parents.
The loop does a .map with na_action='ignore' to simply propagate Nan values. This is O(fast-N) times the cost of the index lookup, which should be O(1).
With the nextpar2 field computed, the loop re-computes np2nn using a simple .notnull() which again is O(fast-N).
Finally, the nextpar field is updated from nextpar2, which again should be O(fast-N).
Thus, worst-case performance is O(slow-N * fast-N), which is N², but it's a Pandas-N², not a Python-N². Average-case should be O(slow-m * fast-N) where m is the average-case maximum tree depth, and best case is O(fast-N) for 1 fast pass through the rows.
Answer: Here is one solution with use of map and combine_first. First create a dictionary from the df values for mapping. Now use map on parent_id to map those values first and then use map again to map values to id. Combine_first will ensure that values mapped from parent_id gets precedence. Final combine_first to fill out NaN values with id.
d = final_df.dropna().set_index('id').to_dict()
final_df['ultimate_parent_id'] =
final_df['parent_id'].map(d['parent_id'])\
.combine_first(final_df['id'].map(d['parent_id']))\
.combine_first(final_df['id'])

You get
    id      parent_id   ultimate_parent_id
0   5.0     51.0        51.0
1   6.0     1.0         10.0
2   2.0     NaN         2.0
3   51.0    NaN         51.0
4   1.0     10.0        10.0
5   70.0    NaN         70.0
6   10.0    NaN         10.0

Comment: @Vaishali, thank you for your answer. DYZ is correct, I'm looking for a solution that works with an arbitrary (previously unknown) tree height.
Comment: @josiah, I see your point. It can be done with a loop but Pandas answers with loops are rarely optimum. May be Pandas is bad tool for this as DYZ mentioned
Comment: @Vaishali I am definitely open to a solution that does not rely on Pandas.
Answer: Let's first cleanup the DataFrame and get rid of the nans. A negative number is a good replacement:
original_df = original_df.fillna(-1).astype(int)

Convert the DataFrame into a dictionary:
d = original_df.set_index('id').to_dict()['parent_id']
#{1: 10, 2: -1, 51: -1, 5: 51, 6: 1, 10: -1, 70: -1}

Now, you need a recursive function to translate an ID into the ultimate parent ID:
def translate(x):
    return x if d[x] == -1 else translate(d[x])

Apply the recursive function to each dictionary key, collect the results into another DataFrame:
ultimate = pd.DataFrame(pd.Series({x: translate(x) for x in d.keys()}),
                 columns=('ultimate_parent_id', ))

Combine the result with the original DataFrame:
original_df.merge(ultimate, left_on='id', right_index=True)

#   id  parent_id  ultimate_parent_id
#0   5         51                  51
#1   6          1                  10
#2   2         -1                   2
#3  51         -1                  51
#4   1         10                  10
#5  70         -1                  70
#6  10         -1                  10

Answer: Adding to @adhast's answer, the last line the function(find_ultimate_parents(df)) should be
return df2['nextpar'].values

df2 is using df['id'] as an index so doesn't correspond to df's index.
Below is the complete script.
import pandas as pd
import numpy as np

df = pd.DataFrame(
    { 'id': pd.Series([5., 6, 2, 51, 1, 70, 10]),
    'parent_id': pd.Series([51, 1, np.nan, np.nan, 10, 51, np.nan])
    }
)

def find_ultimate_parents(df):
    # Make a copy of df, using 'id' as the index so we can lookup parent ids
    df2 = df.set_index(df['id'])
    df2['nextpar'] = df2['parent_id']

    # Next-parent-2 not null - fake it for now
    np2nn = df2['nextpar'].notnull()

    while np2nn.any():
        # Lookup df2[parent-id], since the index is now by id. Get the
        # parent-id (of the parent-id), put that value in nextpar2.
        # So basically, if row B.nextpar has A, nextpar2 has (parent-of-A), or Nan.

        # Set na_action='ignore' so any Nan doesn't bother looking up, just copies
        # the Nan to the next generation.
        df2['nextpar2'] = df2['nextpar'].map(df2['parent_id'], na_action='ignore')

        # Re-evaluate who is a Nan in the nextpar2 column.
        np2nn = df2['nextpar2'].notnull()

        # Only update nextpar from nextpar2 if nextpar2 is not a Nan. Thus, stop
        # at the root.
        df2.loc[np2nn, 'nextpar'] = df2[np2nn]['nextpar2']

    # At this point, we've run out of parents to look up. df2['nextpar'] has
    # the "ultimate" parents.

    return df2['nextpar'].values

df['ultimate_parent_id'] = find_ultimate_parents(df)
print(df)


How to find the unknown number while only LCM is given

Question: Find the smallest value of $n$ such that the lcm of $n$ and $15$ is $45$.
I have searched many ways to solve but could not find a step wise method to teach the students, please help.
Answer: I would present the following as a systematic approach
$$
\eqalign{
  & {\rm lcm}(15,n) = 45 = {{15 \cdot n} \over {\gcd (15,n)}}\quad  \Rightarrow \quad n = 3\gcd (3 \cdot 5,n)\quad  \Rightarrow   \cr
  &  \Rightarrow \quad \min (n) = 3\min \left( {3,5,15} \right) = 9 \cr}
$$
Answer: $n$ must be a divisor of $45$, however $n$ and $15$ must not be each other's divisor. Divisors of $45$:
$$1,3,5,9,15,45.$$
Note that $3,5,15$ are divisors of $15$. So $n$ can be $9$ or $45$. Therefore the smallest $n$ is $9$.
Answer: $15=3\times 5$ and $45=3^2\times 5$. Your number $n=3^2=9$.
Answer: Hint:   $\,n \mid 45 = 3^2 \cdot 5\,$ so $\,n=3^a \cdot 5^b\,$ with $\,0 \le a \le 2\,$ and $\,0 \le b \le 1\,$. Find the smallest $\,a,b\,$ such that $\,45 = \operatorname{lcm}(15,n) = \operatorname{lcm}(3 \cdot 5, 3^a \cdot 5^b) = 3^{\max(1, a)}\cdot 5^{\max(1,b)}\,$.
Answer: We know that the Highest Common Factor is $45$, and that one of the numbers is $15$, and the other number is $n$
GCD=$\frac{45}{15}=3$.
L.C.M × H.C.F = $15\cdot n$
$3 ×  45 = 15 × n $
$\frac{3 × 45}{15} = n$
$9 = n$
Comment: LCM=45/15 ? Also, please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference?noredirect=1&lq=1)


Swift 2 programmatically setting title of dynamic tableview cell to upper left hand corner

Question: I set the height of the cell with:
<code>override func tableView(tableView: UITableView,heightForRowAtIndexPath indexPath: NSIndexPath)-> CGFloat {}
</code>
I'm looking to position the title in the top.  Currently, the title of the cell sits in the middle, and as the cell gets larger, this looks more and more awkward as shown below.

Does anyone have ideas about how I could get the title to stay in the top left of the cell, no matter how big it stretches?
Thank you!
Comment: How are you adding the `UILabel`? In code or Interface Builder? Are you using constraints? If code, show the relevant pieces.
Answer: Go to your storyboard->Editor->EmbededIn->Navigation Controller
this will add additional view before your main view at storyBoard
you can add Title and it will be always in top
If you are using label inside the cell as a title put it in the top left corner and press command,alt,shift ,= all in same time will do the constraints directly
Comment: I think you are misinterpreting his question. He wants to know how he can get the text in the colored views to be at the top of those views. Your answer does not address this.
Comment: If you are using label inside the cell as a title put it in the top left corner and press command,alt,shift ,= all in same time will do the constraints directly
Comment: That didn't work.  I already have a title in there, with stuff linked to it.  I need to make sure the title I have doesn't dilute when the cell grows.


How to save animation fabricjs in a video file?

Question: I have animated objects on the canvas.
Can I save the animation, for example in the GIF or MP4?
As an option to do save the animation frame by frame in the image using Fabric on Node.js Then merge pictures with ffmpeg
Answer: Interesting question, although off-top and to broad and I would expect it to be closed (and a complete answer is not possible) You best bet would be to try and build something and ask for help when you get stuck.
fabric.js objects on a canvas are rendered to the canvas which is effectively a image and with animation, this image is just updated constantly...
you could try and take snapshots of the canvas and collate those on the server to try and create a gif or video
I have also just found this: How to save canvas animation as gif or webm?
which might help
Comment: Thank. In the last link there is a very interesting library ccapture.js
Answer: You can try MediaRecorder API like this

        var srcImg = "demo.png";
        var canvas = new fabric.Canvas('c');
        var canvas_to_capture = $('canvas#c')[0];
        var fps = 30, mediaRecorder;

        function create_stream(){
                var canvasStream = canvas_to_capture.captureStream(fps);
                //create media recorder from the MediaStream object
                mediaRecorder = new MediaRecorder(canvasStream);
                var chunks = [];
                mediaRecorder.ondataavailable = function(e) {
                    chunks.push(e.data);
                };
                //create dynamic video tag to
                mediaRecorder.onstop = function(e) {
                    var blob = new Blob(chunks, { 'type' : 'video/mp4' });
                    chunks = [];
                    var videoURL = URL.createObjectURL(blob);
                    var tag = document.createElement('a');
                    tag.href = videoURL;
                    tag.download = 'sample.mp4';
                    document.body.appendChild(tag);
                    tag.click();
                    document.body.removeChild(tag);
                };
                //build the data chunk
                mediaRecorder.ondataavailable = function(e) {
                    chunks.push(e.data);
                };
                //start recording
                mediaRecorder.start();

        }

        function roll(){
            create_stream();
            fabric.Image.fromURL(srcImg, function (oImg) {
                canvas.add(oImg);
                oImg.set('left',0);
                oImg.set('top', 100);
                oImg.scale(.25);
                canvas.renderAll();

                // and then, we can animate the image
                oImg.animate('left', 200, {
                    onChange: canvas.renderAll.bind(canvas),
                    onComplete: function(){
                        mediaRecorder.stop();
                    },
                });
            });
        }

    <canvas id="c" width="300" height="300"></canvas>
    <button onclick="roll()">Get</button>


Are there items that when sold to merchants, will stay in their inventory forever (aside from Dragon Claws)?

Question: This answer in the question, "Can you rebuy things from fences if they don't sell that item in skyrim?" states that:

Unique items (e.g. Dragon Claws) remain in the inventory of the storekeepers indefinitely. However items such as armour, whilst they will remain for a day or so, are liable to be lost permanently when the storekeeper's merchandise chest resets.

Aside from Dragon Claws, are there other "unique" items which will stay in a merchant's inventory forever? What determines if an item is considered "unique"?
I would like to know as I regularly sell items I don't need to merchants, so they can be "deleted" in the game when the merchants have their inventory reset. I am not sure which items will indeed be removed with a merchant inventory reset.
Answer: I've had several items stay far, far, longer than a day in a vendor's shop before. I am not sure if they stay indefinitely, though they seem to take a lot of time to go away.
The UESP wiki lists two distinct types of permanent items:
Type 1 - Permanent (fully)

Keep their RefID number, when dropped into the world
Do not lose any of their persistent traits when dropped into the world

Type 2 - Permanent (until dropped)

May keep or lose their RefID number, when dropped into the world
Lose any or all of their persistent traits when first dropped into the world.

List of permanent items
The following items were found to be fully permanent:

Aetherial Crown [DG]
Ebony Blade
The Gauldur Amulet
Zephyr [DG]

The following items were found to be permanent until dropped (or placed on a weapon plaque):

Calcelmo's Ring
Declaration of War [DB]
Eduj
Emerald Dragon Claw
Halldir's Staff - the one you get from Halldir's ash pile, not the one which drops near it
Ironhand Gauntlets - looted from Hajvarr Iron-Hand
Iron Dragon Claw
Journals of Ralys Sedaris [DB] - all volumes
Klimmek's Supplies
Letter from a Friend - all instances
Okin
Ruby Dragon Claw
Saerek's Skull Key - only if you do not use it to awaken Otar the Mad (awaken him with shout or rune spell instead)
Staff of Hag's Wrath
The Aetherium Wars [DG] - only the first copy, obtained before or during associated quest
Torsten's Skull Key - only if you do not use it to awaken Otar the Mad (awaken him with shout or rune spell instead)
Whiterun guard's armor, shield, helmet, gloves and boots - looted from Mirmulnir

Note: Permanent weapons may fail to prevent corpses from disappearing, although they will remain in respawning containers.
Comment: Which items are those?
Comment: Well the weird thing for me was that it seemed to be mostly regular armor that took a while to fade. I know it was mine because I always tempered it and enchanted it before I sold it. I did however find a list of items that should work anyway, see answer.


How to shortcut (nmap) windo command expression?

Question: For closing all quickfix windows, I use the following vim command expression:
:windo if &buftype == 'quickfix' || &buftype == 'locationlist' | lclose | endif

Whenever I try to shortcut it like:
nmap <S-q> :let @a = "%:windo if &buftype == 'quickfix' || &buftype == 'locationlist' | lclose | endif"

by using nmap in my init.vim, I got an error:

E749: empty buffer
E488: Trailing characters

How to solve that?
Answer: Explanation
The | is a command separator; unfortunately (this is a common pitfall), it also ends any :map command, and the remainder is interpreted immediately, instead of being part of the mapping.
:help map-bar lists three different solutions; the most common is using the special <Bar> notation instead of |.
Your mapping
nmap <S-q> :let @a = "%:windo if &buftype == 'quickfix' <Bar><Bar> &buftype == 'locationlist' <Bar> lclose <Bar> endif"

Is the %:windo a typo? The % is suspicious.
The mapping is missing the trailing <CR>; it will linger until you press <Enter> yourself. Is that intended?
Why do you assign the commands to register a instead of executing it?
You should use :noremap; it makes the mapping immune to remapping and recursion.
'buftype' is always quickfix, also for location lists; you can drop the second branch in the test.

noremap <S-q> :windo if &buftype == 'quickfix' <Bar> lclose <Bar> endif<CR>

Comment: Great! I found another nitpick: `buftype` cannot contain `locationlist`; you can remove the check for that. If that solves the problem, please accept the answer by clicking on the outlined checkmark next to it.
Comment: Thanks, it works. Now I changed it to: noremap  :windo if &buftype == 'quickfix'  &buftype == 'locationlist'  lclose  endif
Comment: I would use `:cclose` & `:lcose` instead of using `:windo`. e.g. `nnoremap  z z:ccloselclose`


Swipe actions buttons locations for long rows

Question: I am working on a project where I am implementing a swipe menu option for some additional actions. Everything works fine when the height of rows is relatively small and the user is in the middle of the row. But when the height increases, specially when it covers the whole page and the user has scrolled half way, it kind of breaks the design. Here are the screenshots for both actions.
[The image at the top shows the menu when the user is in the middle of the row. The second image show when he has scrolled half way][2]

My questions is, is there a way to move the actions button down with the page when the user scrolls so they are always visible?
NOTE: I am using the mgswipeTableCell lib.
Comment: NO, But if you can scroll your cell to top and set the buttons in swipe cell as top of it in stead of doing it in centre.
Comment: @Sourav The swipe buttons are always centered no matter what. I want them to be contextual to the visible area of the cell on the screen.
Comment: you change in mgSwipeCell for your convenient frame of swipe button .
Answer: As you can see in the official project there are 3 available demo, each demo have a custom UITableViewCell cell based on MGSwipeTableCell methods. It can't be simple if you don't have convenience with UITableViewCell subclassing. You can try to following MGSwipeTableCell project instructions.
What do you want is to make cell labels with more than 2 or 3 lines and with the buttons vertical center aligned.
The demo who is near your needs is Mail Demo
Comment: Thanks man. Let me see what I can come up with. I will keep the progress posted here. Thanks again for the help.
Comment: That's not the problem. Everything is vertically aligned and works fine for a text the size of the Mail Demo project. The issue is with larger text, say with 20 lines. If the user scrolls up and then swipes, the labels will move up. I also tried adding more text to the mail project but cannot seem to increase the height of the cells.
Comment: There is not issue here, it's just a matter to customize your cell, speaking about Mail Demo what about this property _mailMessage.scrollEnabled = NO; ? Have you try to change it?
Comment: Did you click on the link I have posted? The first image is when the user scrolls up. I have tried that. It just hides the text in your cell, which is something I don't want.
Comment: I've just see your images. What do you want is not included in MGSwipeTableCell proj. You must intercept the MGSwipeTableCell scrolling delegates and center the buttons .IMHO what do you want is unconfortable: you have a vertical swiping table + vertical scrolling inside cell. Seems the same happened with today extensions vertical scrolling and table scrolling extension: it's deprecated. From Apple note: Avoid putting a scroll view inside a Today widget. It's difficult for users to scroll within a widget without inadvertently scrolling the Today view.
Comment: No. My view is very similar to what the Mail app has. No scrolling inside the cells, etc. Some cells have large text some have small two lines. When the text is many lines users have to read half of it at the top and then scroll to get to the bottom. Now when he is at the bottom of the screen, the swipe menu will have moved to the top, which misplaces the icons.
Comment: With the scroll disable you must respect the containerView cell height. In fact, inside the source code, you can view at the end of swipe animations, buttons reallined with center of the containerView cell. I dont know your code, if you use autolayout or not, if your constraints are aligned or not, in your xib design or your programmatic construction you have to respect your containerView height.
Comment: I use autolayouts and my code is very similar to what I have posted in my other answer. I just create a simple array and use that as my buttons. I couldnt find the code you are referring to in your comment. Can you please post it in your answer?
Comment: Sure, you can find all the swipe animation methods inside the source code project at the MGSwipeTableCell.m module. During the mail demo the message texts respect the 2 lines as you see, Why dont your project respect this limitation? I've tested a message with the long Lorem Ipsum text, the message show me always 2 rows. Check your code..
Comment: I dont want to show two lines. I want to show all the lines.
Comment: What I try to explain to you :) is that the source code is maded to work only with 2 message lines, if you want to increase these restrinction, you must rebuild your cell from XIB with a custom cell, or from code (from code it's very hard) but, surely, you can use maildemo code to starting your customizations..as I write in my answer.


Why can't I connect a dimmer in line with an outdoor security light?

Question: I have an outdoor security floodlight (with motion sensor and photocell) that I'd like to be able to dim.
The user manual says to not connect it to a dimmer, but doesn't explain why.
What is the reason for this?
Is it a fire hazard, or will it simply prevent the motion sensor from working if I dim the light too low?
Comment: Can you replace the bulbs, or fixture, with ones that have lower lumen levels?
Comment: you can simply get a smart bulb that can be dimmed itself.
Comment: Dimmers do weird things with the power running through them.  With a regular incandescent lamp (or LED lamps designed to tolerate dimmers) the current is "averaged" so that the choppiness of the incoming juice is smoothed.  But anything containing electronics (and which isn't designed to be dimmer-tolerant) will be, at the very least, confused by the chopped-up incoming power, and may actually be damaged by it.
Comment: Can you move the photocell/motion sensor somewhere else in the circuit? How do you want the dimmer's manual switching to interact with the photocell/motion sensor turning the light ON/OFF?
Comment: Just replace the 100w bulb with a 60w bulb (old money) or a 1000 lumen bulb with a 500 lumen bulb (new currency). Skip the dimmer entirely.
Answer: Generally, schemes where you want to control a light 2 ways at once, do not work.  The two methods end up in contention/conflict with each other.
The motion sensor and photocell units need 24x7 power. They do not work on reduced power, partial power or the wacky waveform you get out of a triac dimmer, which is made only for lights. Since you are using a single light+motion sensor+photocell unit, you can't separate out and dim only the light, unless the internal arrangement of the unit allows you to do so, which is pretty rare these days.
Modern motion sensor+photocell+LED units generally have a single power supply on board that makes 12V, both for the motion sensor and the light.  (12V motion sensors are ~$10, 120V motion sensors are ~$20 due to the need for an internal power conversion and a higher safety rating switch).  If you could access the internals of the unit, it's certainly easy to get a PWM dimmer for ~12V LEDs, that could go between the sensor and the LED.  The cheapies have a physical knob that will stay where you put it.
Honestly, your best option - though it'll be a little complex - is to do exactly that with discrete components.  The photocell is generally part of the motion sensor, and so you don't need 2 components there.
So you have a 12V power supply... then a 12V motion sensor... then a 12V PWM dimmer... then 12V LED lights of your choice, which are readily available.
It'd be possible to do that same thing in 120V, however choosing a dimmer would be a challenge.  Most dimmers these days do not like being downline of a switch, and will do undesirable things like reset themselves to full brightness etc.
Answer: The light only takes one power feed and all the attached electronics, I.E. Sensors, require full voltage.
Your product would have to be compatible with a low voltage dimmer system (purple and gray wires if present)
Comment: "*The light only takes one power feed*" Can you explain that, is someone suggesting more than one power feed? Answers are better, and more likely to get up votes, if there is comprehensive explanation for the advise being given.
Comment: Don't most DC circuits, such as the electronics that control the motion sensor logic, require 5 volts to operate? Why would the manufacturer require all 120V to flow through?
Comment: @Phillip - They may, but they derive that lower voltage from the incoming 120V AC.  If you "chop" the 120V input with a dimmer, the small/simple power supply that powers the motion detector electronics probably won't work.
Answer: The motion sensor and photocell require a certain input voltage to operate. If that voltage is lowered by a dimmer switch, the switching won't take place and your light won't turn on.
I have security lights that have an input range of 95 to 125 volts so I have installed dimmers and can dim the lights a small amount but if I dim them too much, nothing works. I've also installed low wattage bulbs to increase the dimming effect. You might want to check your voltage ratings and experiment with a cheap dimmer.
Answer: Is this a solution?:

Power the photocell with straight power from electrical source
Connect photocell to dimmer as you would for lights ( Now the power is in the dimmer)

Power will be sent at dusk and power will be cut off at dawn at the dimmer instead of lights

The dimmer will send the voltage received from photocell as desired to your lights as
you adjust it
Comment: you answered with how, but the original question is why


boost.asio. The possibility to expect the completion of any object in queue is necessary

Question: In asio:: io_service I insert objects. asio:: io_service::run() runs in several threads.
The possibility to expect the completion of any object in queue is necessary.
For example:
<code>template <typename T>
struct handler {
   void operator()() {
      ....
   }
   T get() const {...}
};

asio::io_service ios;
ios.post(handler());
</code>

How I can refer to the object in queue?
How can I pause the main program loop, untill handler::operator() is executed?

Thanks.
Comment: The liveworkspace code is helpful but I'm not entirely clear on the scenario.  Do you know which handler you will be calling get() on prior to posting the handler to io_service?  Also, when you call get() on one handler do all handlers that are running need to finish or just the one that get() is being called on?  Is there some data dependency between all of the handlers that are running concurrently? Thx
Comment: I don't really understand what you are asking. Can you post compilable code instead of pseudo code? Is 'the object in queue' an instance of `struct handler`?
Comment: It is required, by the calling of handlet::get() to suspend the calling loop until handlet is executed.
Comment: @niXman - It sounds like you want one handler to execute at a time.  Is this correct?
Comment: No.
I need the handlers to be executed as usual until I call the method get() of any of them. But when I call get(), the calling thread should stop until the operator() of this object is executed.
Comment: Could you give us a bigger picture? What behavior are you trying to achieve? Rather than a vague `handler` object, describe what its purpose is.
Comment: In the operator() of the handler some calculations are executed. The result of calculation I get using the method get(). I need, at the calling of the method get(), the calling loop to be frozen until the operator() of this object is executed. But if I do not call get(), then this handler is executed as usual. There's no waiting of its processing then. code: http://liveworkspace.org/code/c601a9bf6226fe7e85fc9ba07c8dc933
Comment: it sounds like your various `handler` objects have dependencies with one another?  Otherwise, why would you need to stop the `io_service` reactor queue?
Comment: It is not known for any handlers will need to call get().
Handlers do not depend on each other.
Answer: Here's what I know so far:
1. Several handlers are executing on several threads.
2. Handlers run independently of each other.  There is no synchronization needed between threads for data/race conditions.
3. Get can be called on anyone handler. When called the handler should stop calculating and let another thread call handler::get().
This really seems more like a multi-threading / concurrency question then a boost::asio question.  At the moment I do not see a need to use an io_service.  It seems like several threads could just be started without an io_service and some synchronization could be used between the threads.
The thread calling Handler::get() needs to wait until the io_service thread running operator() completes its calculation before it can return.
Consider using a condition variable.  The handler::get() method can wait until the condition is met (i.e. operator() finishes its calculation).  The io_service thread that runs operator() would notify the main thread through the condition variable.
An example of one thread notifying another thread via a condition variable is here.
Comment: I know that this can be implemented using a condition variable,
but suggested that this possibility should provide asio::io_service and its members/type_members.

Thank you.


Realtek Wifi Adapter: Super High Ping on Internet-Connected software (Discord, TF2, Portal 2, etc.)

Question: I have an HP Laptop with Kubuntu 16.10 dual-booting alongside Windows 10.
I just updated it from 16.04, and suddenly TF2, Discord, Portal 2, and other programs are experiencing fluctuating ping, from decent (20-50ms range) to downright horrible (430-500ms). I have tried updating the kernel to 4.10.5 (the latest stable release), but after rebooting it didn't do a single thing.
I have a Realtek RTL8188EE Wireless Network Adapter as my Wifi card.
When I ping my router:`
evan@evan-computer-a:~$ ping 192.168.0.1
PING 192.168.0.1 (192.168.0.1) 56(84) bytes of data.
64 bytes from 192.168.0.1: icmp_seq=1 ttl=64 time=2.09 ms
64 bytes from 192.168.0.1: icmp_seq=2 ttl=64 time=5.61 ms
64 bytes from 192.168.0.1: icmp_seq=3 ttl=64 time=3.61 ms
64 bytes from 192.168.0.1: icmp_seq=4 ttl=64 time=4.06 ms
64 bytes from 192.168.0.1: icmp_seq=5 ttl=64 time=3.95 ms
64 bytes from 192.168.0.1: icmp_seq=6 ttl=64 time=4.34 ms
64 bytes from 192.168.0.1: icmp_seq=7 ttl=64 time=2.97 ms
64 bytes from 192.168.0.1: icmp_seq=8 ttl=64 time=6.61 ms
64 bytes from 192.168.0.1: icmp_seq=9 ttl=64 time=4.63 ms
64 bytes from 192.168.0.1: icmp_seq=10 ttl=64 time=2.72 ms
64 bytes from 192.168.0.1: icmp_seq=11 ttl=64 time=4.01 ms
64 bytes from 192.168.0.1: icmp_seq=12 ttl=64 time=2.75 ms
64 bytes from 192.168.0.1: icmp_seq=13 ttl=64 time=2.92 ms
64 bytes from 192.168.0.1: icmp_seq=14 ttl=64 time=6.31 ms
64 bytes from 192.168.0.1: icmp_seq=15 ttl=64 time=4.75 ms
64 bytes from 192.168.0.1: icmp_seq=16 ttl=64 time=2.72 ms
64 bytes from 192.168.0.1: icmp_seq=17 ttl=64 time=3.80 ms
64 bytes from 192.168.0.1: icmp_seq=18 ttl=64 time=3.81 ms
64 bytes from 192.168.0.1: icmp_seq=19 ttl=64 time=2.40 ms
64 bytes from 192.168.0.1: icmp_seq=20 ttl=64 time=6.69 ms
^C
--- 192.168.0.1 ping statistics ---
20 packets transmitted, 20 received, 0% packet loss, time 19032ms
rtt min/avg/max/mdev = 2.097/4.042/6.694/1.352 ms

When I ping Google:
evan@evan-computer-a:~$ ping www.google.com
PING www.google.com (18.104.22.168) 56(84) bytes of data.
64 bytes from yv-in-f106.1e100.net (22.214.171.124): icmp_seq=1 ttl=45 time=28.9 ms
64 bytes from yv-in-f106.1e100.net (126.96.36.199): icmp_seq=2 ttl=45 time=23.4 ms
64 bytes from yv-in-f106.1e100.net (184.108.40.206): icmp_seq=3 ttl=45 time=25.1 ms
64 bytes from yv-in-f106.1e100.net (184.108.40.206): icmp_seq=4 ttl=45 time=23.6 ms
64 bytes from yv-in-f106.1e100.net (220.127.116.11): icmp_seq=5 ttl=45 time=31.7 ms
64 bytes from yv-in-f106.1e100.net (184.108.40.206): icmp_seq=6 ttl=45 time=104 ms
64 bytes from yv-in-f106.1e100.net (126.96.36.199): icmp_seq=7 ttl=45 time=26.8 ms
64 bytes from yv-in-f106.1e100.net (126.96.36.199): icmp_seq=8 ttl=45 time=33.7 ms
64 bytes from yv-in-f106.1e100.net (22.214.171.124): icmp_seq=9 ttl=45 time=31.8 ms
64 bytes from yv-in-f106.1e100.net (22.214.171.124): icmp_seq=10 ttl=45 time=24.1 ms
64 bytes from yv-in-f106.1e100.net (184.108.40.206): icmp_seq=11 ttl=45 time=22.6 ms
64 bytes from yv-in-f106.1e100.net (22.214.171.124): icmp_seq=12 ttl=45 time=22.5 ms
64 bytes from yv-in-f106.1e100.net (188.8.131.52): icmp_seq=13 ttl=45 time=180 ms
64 bytes from yv-in-f106.1e100.net (220.127.116.11): icmp_seq=14 ttl=45 time=27.6 ms
64 bytes from yv-in-f106.1e100.net (184.108.40.206): icmp_seq=15 ttl=45 time=25.5 ms
64 bytes from yv-in-f106.1e100.net (22.214.171.124): icmp_seq=16 ttl=45 time=24.7 ms
64 bytes from yv-in-f106.1e100.net (18.104.22.168): icmp_seq=17 ttl=45 time=22.4 ms
64 bytes from yv-in-f106.1e100.net (22.214.171.124): icmp_seq=18 ttl=45 time=37.5 ms
64 bytes from yv-in-f106.1e100.net (220.127.116.11): icmp_seq=19 ttl=45 time=40.3 ms
64 bytes from yv-in-f106.1e100.net (184.108.40.206): icmp_seq=20 ttl=45 time=27.5 ms
^C
--- www.google.com ping statistics ---
20 packets transmitted, 20 received, 0% packet loss, time 19031ms
rtt min/avg/max/mdev = 22.430/39.290/180.588/36.788 ms

As you can see, there is no packet loss on both of them, and the ping is completely fine, except on a few places in the Google ping.
I have tried looking at many other sites to fix the problem, none has worked. Laptop power management is off (my laptop is connected directly to power anyways - there isn't a battery in it). The kernel is the most up-to-date as it can be (without being unstable). I have absolutely no idea why my ping on TF2, Discord, and other programs is so high and fluctuating so much.
Answer: This is how I fixed my ping:
sudo apt-get install build-essential linux-headers-generic git dkms
git clone http://github.com/lwfinger/rtlwifi_new.git
cd ~/rtlwifi_new
make
sudo modprobe -rv rtl8188ee
sudo make install
sudo modprobe -v rtl8188ee

The first modprobe command will disconnect your computer to the internet, and the second will reconnect it. After I completed the commands, I rebooted my system and everything was fixed & working fine.
This will also work for most other Realtek adapters, all you do is put your model in place of "rtl8188ee". (The files that were downloaded have those other models included as well.)


RichFaces  doesn't rerender on first try

Question: I'm using JSF 1.2 with RichFaces 3.3.3 (big company project - no options to update yet) and I have a problem with rerendering some fields with <a4j:support> tag.
I have a table, and a summary row, which displays values calculated in backing bean. The summary row cells should auto update after every change in the other rows, so on every cell which triggers an update, i've got a valueChangeListener which calls "recalculation" method on the bean and a <a4j:support reRender="[corresponding_summary_cell]" (...) /> The problem is when I first load the page with a table the rerendering doesn't work. Ajax request is called, but returns some kind of an "empty" response. Only when I reload the view (by clicking a link to the page for example) the requests start to work as intended, an correctly update corresponding summary cells.
The kind-of-empty response contents fragment:

  <meta name="Ajax-Update-Ids" content="" />
  <input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="j_id11" autocomplete="off" />
  <meta id="Ajax-Response" name="Ajax-Response" content="true" />
  <meta name="Ajax-Update-Ids" content="" />

    <input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="j_id11" autocomplete="off" />

  <meta id="Ajax-Response" name="Ajax-Response" content="true" />

The cell which triggers a calculation example:
<customNamespace:moneyValue value="#{someAttribute}" id="field1" valueChangeListener="#{controller.calculateSums}">
   <a4j:support event="onchange" reRender="Form-Table-Cost1Sum"/>
</customNamespace:moneyValue>

The rows in the table are added dybnamically, but it's only the first time (added first row to an empty table) which gives the problem, next rows work ok. I also tried re-rendering whole form - nothing changed.
TL;DR:
Got a table cell with  which should ajax-update another row, works only after reload, first time gives response like reRender attribute was empty.
Answer: Try adding one instance of your component above the table, with attribute rendered="false".
This will make sure JSF has loaded whatever is needed to process the tags.

RichFaces  doesn't rerender on first try


What effect do the 'Hungryiness' and 'thirst4Dew' stats have?

Question: Disclaimer: (Yes, this is a real game)

In the Montage parody game (GAME OF THE YEAR: 420BLAZEIT vs. xxXilluminatiXxx [wow/10 #rekt edition] Montage Parody The Game) the stats shown in the top right of the screenshot below seem to tick up as you move around, and can be reset to 0 by picking up the Doritos bags & Dew cans respectively. Picking up these items also restores health.
But I haven't seen any effect (negative or otherwise) from the stats alone.
Do they have an effect in-game?
Comment: I also considered `[gameoftheyear-420blazeit]` for the tag, but opted for the safer option
Comment: @Anto - lol. Only the most dank MLG Montage video game ever created.
Comment: What the hell is this...
Answer: I decompiled the game source code, and it shows that if your hunger (or thirst) "points" are at 100, it applies 5 "starve" (or thirst) damage every 3 seconds. These can both apply at the same time.
<code>public float starveInterval = 3f;
public float starveAmt = -5f;

if (lastHungerTime + hungerInterval < Time.time)
    UpdateHunger(1f);

if (hungerPoints == maxHungerPoints && lastStarveTime + starveInterval < Time.time && hitPoints > 0.0)
{
    HealPlayer(starveAmt);
    (Instantiate(painFadeObj) as GameObject).GetComponent<PainFade>().FadeIn(PainColor, painTexture, 0.75f);
    if (hitPoints < 1.0)
        SendMessage("Die");
    timeLastDamaged = Time.time; lastStarveTime = Time.time;
}
</code>
Comment: Despite it saying "HealPlayer", it's actually passing through a negative amount - `starveAmt` - which applies negative "healing" - damage.


Error creating task using Asana API

Question: we have been using the ASANA API about 4 month, but today we started get an error trying to create task in Asana:
5:15:48,208 ERROR [stderr] (pool-13-thread-1) Exception in thread "pool-13-thread-1" com.sun.jersey.api.client.ClientHandlerException: org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "num_hearts" (Class net.joelinn.asana.tasks.Task), not marked as ignorable
05:15:48,210 ERROR [stderr] (pool-13-thread-1)  at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@6eae04be; line: 1, column: 296] (through reference chain: net.joelinn.asana.tasks.Task["num_hearts"])

the error happens on client.createTask() call, see the code below:
protected void createProjectTasks(Project template, AsanaDetails asanaDetails, Long createdProjectId) {
    try {
        String asanaWorkspaceName = asanaDetails.getWorkspaceName();
        Asana asana = new Asana(asanaDetails.getApiKey());

        Tasks tasks = asana.projects().getTasks(template.id);
        Workspace workspace = getWorkspace(asana, asanaWorkspaceName);

        if (workspace == null) {
            throw new AsanaException("Asana workspace with name " + asanaWorkspaceName + " is not found");
        }
        if (tasks == null) {
            return;
        }

        Collections.reverse(tasks);

        TasksClient client = asana.tasks();
        for (Task task : tasks) {
            TaskRequestBuilder taskRequestBuilder = new TaskRequestBuilder();
            if (StringUtils.isNotBlank(task.name)) {
                taskRequestBuilder.name(task.name);
                taskRequestBuilder.completed(false);
                taskRequestBuilder.addProject(createdProjectId);
                taskRequestBuilder.workspace(workspace.id);
                client.createTask(taskRequestBuilder);
            }
        }
    } catch (ApiException e) {
        throw new AsanaException(e.getMessage());
    }
}

I checked the Task class, the are no field there annotated with "num_hearts", so, I'm a bit confused what got broken here, we haven't made any code changes for about a month...
and here is the api version:
    <dependency>
        <groupId>net.joelinn</groupId>
        <artifactId>asana</artifactId>
        <version>0.5.4</version>
    </dependency>

Any thoughts?
Thanks in advance
Answer: We're happy to have released support in the API for hearts in both tasks and stories. These include the new fields, "hearted", "hearts", and "num_hearts". You can read more about this in our documentation.
Unfortunately, your client threw an error because it reached a new field (num_hearts) which it did not recognize. Since the client appears to be open source, you might want to send them a pull request to add support for the new hearts attributes. Alternatively, it may be worth to generalize the client so it does not throw an error when we add new fields in the future. In order to keep the API up-to-date with product developments, we will from time to time add fields and endpoints. You can rely on existing fields not going away, but it's bad to rely on no new fields being added.

Error creating task using Asana API


Error when trying to access variable inside a for loop

Question: I've got some code below that loops through a XML document to grab certain information. I want to grab 3 bits of information and place them in variables. As the code shows i have declared the variables before the loop, then after the loop i try to use the variables it mentions that they are unassigned.
I also think having 3 loops probably isn't the best way to do this but couldn't find another way to get all three bits of information.
Heres the code;
private void findDetails(String school)
    {
        XElement root = XElement.Load("proxies.xml");

        IEnumerable<XElement> proxydetails = from el in root.Elements("item") where (string)el.Element("schoolname") == school select el;

        String SchoolAddress1, Port, Enabled = "";

        foreach (XElement el in proxydetails)
        {
            SchoolAddress1 = (string)el.Element("schooladdress");
        }
        foreach (XElement el in proxydetails)
        {
             Port = (string)el.Element("schoolport");

        }
        foreach (XElement el in proxydetails)
        {
             Enabled = (string)el.Element("schoolenabled");

        }

        MessageBox.Show(SchoolAddress1);
        }

I've just checked what data is returned in proxydetails and it is the following;
<item>
<schoolname>Primary School</schoolname>
<schooladdress>proxy</schooladdress>
  <schoolport>80</schoolport>
  <schoolenabled>1</schoolenabled>
  </item>

Here is the updated code that now works;
private void findDetails(String school)
        {
            XElement root = XElement.Load("proxies.xml");

            IEnumerable<XElement> ProxyDetails = from el in root.Elements("item") where (string)el.Element("schoolname") == school select el;

            String schoolAddress1 = "";
            String port = "";
            String enabled = "";

            foreach (XElement el in ProxyDetails)
            {
                schoolAddress1 = (string)el.Element("schooladdress");
                port = (string)el.Element("schoolport");
                enabled = (string)el.Element("schoolenabled");
            }

             MessageBox.Show(schoolAddress1);
            }

Comment: are you sure proxydetails having data? + You actually do not require 3 loops!
Comment: Sounds like you are having nothing in the proxydetails and the loops do not occure at all. Run it in debug mode and tell us that is the item count in the enumerator before entering the first loop.
Comment: 1. You are looping and assigning new values to the same variable repeatedly. Only the last value read will be remembered therefore. 2. You don't need three separate loops. 3. The variables are assigned on declaration, so where are you getting an error and what error is it? 4. If `proxydetails` is an empty list, the loops won't be run, so `SchoolAddress1` etc will all be "" still. 5. Please fix your casing: the method should use *PascalCase*, the variables should use `camelCase`. You are just making it hard for others to read you code by not following those conventions.
Comment: i've just added what was contained in proxydetails
Comment: I'm getting the following error even before i run the app. Use of unassigned local variable 'SchoolAddress1' on the messagebox line near the bottom
Comment: Compiler is telling you that if proxydetails will be empty, `SchoolAddress1` will not have any value (because you declared it without initializing it), try declaring it like this `String SchoolAddress1 = "", Port = "", Enabled = "";`
Comment: var schooldetails = proxydetails.Select(x=> new { schoolAddress1 = x.schooladdress, Port = x.schoolport, Enabled = x.schoolenabled}); Then MessageBox.Show(schooldetails.schoolAddress1);
Answer: The line:
String SchoolAddress1, Port, Enabled = "";

is equivalent to:
String SchoolAddress1;
String Port;
String Enabled = "";

If you want to initialise them all, you need to it like:
String SchoolAddress1 = "";
String Port = "";
String Enabled = "";

As the compiler cannot know whether proxydetails will contain anything, it cannot know if SchoolAddress1 will be assigned a value in the loop. So it plays safe and warns that the variable may be undefined at the point you try to read it.
Comment: this was the answer, I've also altered the naming conventions of variables and methods and also removed the redundant for loops. to help others i'll post the updated code.
Answer: try below code:-
private void findDetails(string school)
    {
        var root = XElement.Load("proxies.xml");

        IEnumerable<XElement> proxydetails = from el in root.Elements("item") where (string)el.Element("schoolname") == school select el;

        var schoolAddress1 = string.empty;
        var port = string.empty;
        var enabled = string.empty;

        var result = proxydetails.Select(x => new { schoolAddress1 = x.schooladdress, port = x.schoolport, enabled = x.schoolenabled}).ToLost();

         MessageBox.Show(result[0].schoolAddress1);
        }

Because in your code "" was assigned only to Port;
+ follow code conventions for better programming.
Answer: Init you string with string.Empty value:
String SchoolAddress1, Port, Enabled = "";

should be
String SchoolAddress1 = string.Empty, Port = string.Empty, Enabled = string.Empty;

Also, merge the foreach loops into one:
foreach (XElement el in proxydetails)
{
    SchoolAddress1 = (string)el.Element("schooladdress");
    Port = (string)el.Element("schoolport");
    Enabled = (string)el.Element("schoolenabled");
}


How can I create better looking charts than those generated by Core Plot?

Question: I'm looking for good library for iphone to draw charts (pie chart, bar chart). I've tested Core plot, which was recommended by many people, but I think the generated charts look poor.
I saw example of good-looking charts in that application:

Anyone knows what library was used there? Or what library can help me achieve similar, nice look?
Comment: Dont confuse the chart with the surroundings. You can put a gradient behind any view.  Core-Plot is capable of things like this.
Comment: Core Plot is highly customizable.  Both of those charts can be made (and possibly were) using that framework.  Just because the default charts in the sample applications weren't to your liking doesn't mean that's all you can do with the framework.  Look through the highly customized charts in some of the applications using the framework, for example: http://code.google.com/p/core-plot/wiki/AppsUsingCorePlot
Comment: another example of nice bar chart: http://a1.phobos.apple.com/us/r1000/015/Purple/ca/2b/5d/mzl.fxjzjxtb.320x480-75.jpg
Comment: I used Core-Plot in one of my apps, and it was easy enough to use, but I have to agree that it isn't the prettiest.
Answer: I would use CorePlot, but since you dont like it…
In one project I used the Google Chart api.  Nearly everything is customizable, the only downside is that you have to be connected the internet to fetch the image.  Depending on your use case, it might be appealing.
You can also checkout the huge list of responses to this similar question: Is there a good charting library for iPhone?


Speed and travel time

Question: If at speed 0 it takes an infinite amount of time to arrive at a destination, and at speed 100 it takes 86400 seconds to arrive at the destination, how do I calculate the amount of time it takes to arrive at the destination at any given speed? Thanks!
Comment: `at speed 0 it takes an infinite amount of time to arrive at a destination` No, at speed $\,0\,$ you are standing still and will *never* arrive at any destination other than the point where you were to begin with. How is that relevant to the rest of the question, anyway?
Comment: I am just stating the limits of the problem. Sheesh!
Comment: No Sir. First of all, the units of speed aren't given. Second, by your knowledge, it takes an infinite amount of time to go any non-zero distance with speed zero, so that is a nearly useless statement. Nevertheless, at least the answer below is correct, so you can accept that and close this question.
Answer: You can calculate the distance from the formula $v=d/t$, yielding $d=vt$. Now for any velocity $v_1$ you have $v_1=d/t_1$ or $t_1=d/v_1$. You can write this as $$t_1=\frac{v}{v_1}t$$
Answer: Speed times time equals distance.  You have what you need to compute the distance, then if you divide by a different speed you get the time at that speed.

Speed and travel time


Django comments reverse relationship

Question: When using django.contrib.comments is there anyway to add the reverse relationship to a model that has comments?
For example:
post = Post.objects.all()[0]
comments = post.comments.all()

Answer: Yes, you should be able to do:
from django.contrib.contenttypes import generic
class Post(models.Model):
    ...
    comments = generic.GenericRelation(Comments)

per the Django docs on reverse generic relations
Comment: In Django 1.3, I had to use the following: `comments = generic.GenericRelation(Comments, object_id_field='object_pk')`. Apparently `BaseCommentAbstractModel` uses what is now a non-standard name for its `object_id_field`?
Answer: I came up with another way to do this (why? Because I wasn't aware of any other way to do that time). It relies on having an abstract model class from which all models in the system are derived. The abstract model itself has a method, comments, defined which when called returns a QuerySet of all the comment objects associated with the corresponding concrete object. I implemented it thus:
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.comments.models import Comment

class AbstractModel(models.Model):

    def comments(self):
        """Return all comment objects for the instance."""
        ct = ContentType.objects.get(model=self.__class__.__name__)
        return Comment.objects.filter(content_type=ct,
                                    object_pk=self.id)

    class Meta:
        abstract = True

Django comments reverse relationship


Javascript dot operator

Question: I am a javascript noob so i dont understand why in the code below the author uses Avengers.cast instead of just Avengers?
var myApp = angular.module('myApp', []);
    myApp.factory('Avengers', function() {
        var Avengers = {};
        Avengers.cast = [{
            name: "Robert Downey Jr.",
            character: "Tony Stark / Iron Man"
        }];
        return Avengers;
    })

function AvengersCtrl($scope, Avengers) {
    $scope.avengers = Avengers;
}

Comment: apparently design decision - the Avengers object will probably have more properties in the future than just the cast
Comment: He is setting a property `cast` on the object `Avengers`. It can be accessed using the same notation.
Comment: @lethal-guitar: Well there's also the question of why set it on the property instead of the variable...
Answer:     var Avengers = {};

This means: create a new object and refer to it by the variable Avengers
    Avengers.cast = [{
        name: "Robert Downey Jr.",
        character: "Tony Stark / Iron Man"
    }];

This means: the object just created now has a property called cast. This is an Array and contains exactly one object (with two properties with String values).
Comment: So why declare var Avengers = {}; and Avengers.cast when the code seems to work just the same when i delete the var Avengers = {}; line and change Avengers.cast to Avengers? Thank you so much for your answer!
Answer: In your code, cast property of Avengers is set to specific object. Let say, initially Avengers has no value. In factory section, Avengers became
Avengers.cast = [{
    name: "Robert Downey Jr.",
    character: "Tony Stark / Iron Man"
}];

You can use this somewhere in your code like console.log(Avengers.cast). Following example for the function;
myApp.factory('Avengers', function() {
    return {
        helloWorld: function() {
            return "Hello, World!"
        }
    };
});

You can use Avengers.helloWorld() somewhere in your code.
As summary, you can create objects with angular.js factory and set property for that object also create functions in that object. Refer here  for more details
Answer: To answer your specific question: there is more than one way to pass information around.
The author could have made the Avengers service just the array instead of an object with the array.
So the choice was somewhat arbitrary, as you seem to be picking up on.
That said if the author is planning on extending the Avengers service with more properties, then that is why an object with the array was chosen.
Although if you're just going to do that you should check out constant - maybe it would be more appropriate than factory.

Javascript dot operator