Q:

Is momentary physical access dangerous?

I’m asking the question with these conditions:

The device (computer or mobile phone) is in a running state.
“Momentary” refers to a reasonably short period of time, such as 5 to 10 seconds.
The system may not be in a “locked” state (e.g. showing a lock screen asking for a password). However, the active session doesn’t have superuser privilege (the usual case for a mobile phone).

What can a hacker do to gain further access to the system?

A:

That all depends on the system, the attacker, and the level of preparation they had. If they have unlimited preparation, they could do effectively anything that they could do with an unlimited access window. Even if they do not have in-depth knowledge of the specific system, it would not be difficult to very quickly inject malicious code that allows for subsequent remote access. They could:

Connect a PCMCIA or PCIe card and dump memory or inject code.
Splice a hardware keylogger in between the keyboard's PS/2 or USB cable.
Quickly download and execute malicious code, or modify existing code.
Access sensitive files and save them (e.g. with a camera or USB flash drive).
Physically destroy the computer (e.g. with a hammer or a power surge over USB).
Simply grab the system and pawn it off for a quick buck.

Time for a story. I once had a target who I would be in close proximity to for a brief period. My goal was to gain persistence on their laptop to exfiltrate sensitive documents. I knew I had only a few seconds every time they went out of sight, so I couldn't just grab their laptop and take my time. I obviously also could not steal it. Luckily, I came prepared. I had a programmable USB device that I plugged in. As soon as it was plugged in, it simulated keyboard input to open PowerShell and execute a few commands to download a payload I had set up earlier. The scenario went like this:

I waited until this person had left to get something for me in another room.
I leaned over on the table where the laptop was and surreptitiously plugged in the device.
I waited a few seconds to be safe, unplugged it, and tried to keep a straight face.
After they gave me what I asked for, I thanked them and left.
When I got home, I got on my computer and connected to their machine.

It was not difficult, did not take an extensive period of preparation, and was moderately stealthy. I could have made it even more stealthy if I used something that looked like a cell phone so I could claim I was just charging the device and didn't see any other USB ports around. The moral is that you can do a lot with just a few seconds of access, so you must never underestimate the risk.
So how do you protect against these threats? You need to develop a threat model. Figure out who your adversary is, what assets of yours they are after, and what their resources are. If you don't want your mother to see your porn when you're at her house, you probably don't need to worry about exploits abusing corrupt EDID in a VGA or HDMI cable. If you are holding extremely valuable company secrets in a highly competitive industry (robotics, epoxy, etc) and are going to a high-risk country like France or China, you absolutely need to worry about sophisticated attacks, because industrial espionage (aka the more illicit side of "corporate intelligence") is rampant. Stay with your computer at all times in adversarial situations. Lock it if you are going out of its line of sight, and bring it with you or physically secure it in a safe if you are going to be away for a longer period.

A:

I think you're also missing that there's other malicious things to be done beyond hacking. There are USB devices that can literally fry a computer. So even if they don't gain access or install dangerous software, a "few seconds" could cause thousands of dollars in damage, not to mention downtime to repair the affected systems.

A:

I can think of one way to prolong the physical access.

USB drives can be so tiny that the entire electronic portion fits under the contacts, and the tab is just so you can pull it out. You may modify one by cutting the tab off to fit stealthily inside a slot, so that the owner might not notice something's there right away. And by the time they do, who knows when or where someone may have inserted it? How often do you check your USB ports? :p
Also, many laptops have that plastic placeholder SD card to keep the lint and dust out. Do you check that often too?

And thirdly, with this stealthy approach, you may be able to manufacture a USB cable which includes a controller which acts as a normal charge/data cable but can become a man-in-the-middle for any connected devices. Or use an already existing "USB flash drive in a cable" accessory like this one:


Q:

Minimize noise on electromagnet using audio frequencies

I have an electromagnet (coil with about 500 uH inductance and 0.8 Ohm resistance) that I want to drive at 4 kHz with about 3 Amps of current.  I want to achieve this with minimum noise and power at any frequency other than 4 kHz.
I am using a waveform generator (Stanford Research Systems DS345) to generate a 4 kHz sine wave (unbalanced signal), which is then sent to an audio amplifier (Crown xls 402).  The output of the amplifier is a balanced signal connected to the coil.  In parallel with the coil I have two zener diodes for flyback to prevent damage to the amplifier in the event of a power failure.
In order to minimize noise coming from the waveform generator or the amplifier, which of the following is optimal?  The most critical noise frequencies that I must minimize are those at low frequencies (< 4kHz and in particular those less than 200 Hz) and those over 4 MHz.
(i) Maximize the voltage coming from the waveform generator (10 V peak to peak).  Then set the gain on the amplifier to get desired output current
(ii) Set gain on amplifier to maximum, and then set the waveform amplitude to get desired output current
(iii) Something else entirely

A:

You might be missing a trick here - try series resonating the inductor with a capacitor of precisely 3.18 uF. With the 500uH coil (and series resistance of 0.8 ohms), you'll get a voltage magnification across the coil of about 15:1.
In other words, you apply a 1V RMS sine wave at 4kHz and you get 15V RMS sinewave across the coil. There's another benefit too - it's a fairly tight filter and rejects distortion/noise from the amplifier that's driving it. Your amplifier needs to be able to drive a small load resistance because now all the load the amp will see is the losses in the inductor i.e. the 0.8 ohms but, if the amp's minimum load is 2 ohms then insert an extra 1.2 ohms in series - the magnification will only be about 6.3 now but still pretty reasonable.

simulate this circuit – Schematic created using CircuitLab
Resonant frequency is \$\dfrac{1}{2\pi\sqrt{LC}} = \dfrac{1}{2\pi\sqrt{500\mu\cdot 3.18\mu}} = 3991.4 Hz.
\$


Q:

Setting a class variable with a private method

Say, we have a class that has internal state, implemented as a private variable and a method to determine that state. What is the oop-way to set the variable with a method:
class Car
{
..
private:
float speed_;
float calculate_optimal_speed();
..}

Is it better to make a function calculate_optimal_speed(), which returns the varible speed_ within its body or a void set_speed() method?
Say, we have a big method control_the_car().
What is preferred and will create less problem in the further development of the code:
float calculate_optimal_speed();
control_the_car()
{
..
speed_ = calculate_optimal_speed();
}

or
void set_optimal_speed();
control_the_car();
{
..
set_optimal_speed();
}

On one hand, implementing set_optimal_speed() allows to change the type of speed_ variable with less modifications of the code. On the other hand, returning a value allows to re-use the function if I need it again. Is there a rule of thumb here?

A:

Is there a rule of thumb here?

Yes: write the simplest implementation that covers your needs. If you need something different later, refactor.
This means you should probably use the set_optimal_speed(); implementation, unless you have speeds to calculate that do not need to be set in the private state of the class (if you do, make a function that returns the speed, then implement set_optimal_speed(); in terms of this function).


Q:

Prove that no finite abelian group is divisible.

A nontrivial abelian group $G$ is called divisible if for each $a \in G$ and each nonzero integer $k$ there exists an element $x \in G$ such that $x^k=a$. Prove that no finite abelian group is divisible.
I came across a prove that goes like this:
Let $G$ be a finite divisible abelian group. Then for each positive integer $k$ there is $x_k \in G$ such that $x_k^k = 1$. Note we may assume $x_k$ is minimal with respect to this property; i.e. the order of $x_k$ is $k$. Therefore, $G$ contains an element of every positive order and these must be distinct. Contradiction.
How can we assume $x_k$ has order $k$? If $G$ is finite of order $n$, then we must have $ord(x)|n$ for each $x \in G$. If $n<k$ then there is no $x\in G$ with order $k$. Right? Or did I go wrong somewhere?

A:

Here is my proof by contradiction.
Since $G$ is non trivial, exists an element $a\in G\setminus\{1\}$. For this element and $k=|G|$, exists and $x\in G$ such that $x^{|G|}=a$, but since $G$ is finite, $x^{|G|}=1$. This implies that a=1.

A:

For any finite abelian group there is at least one integer $n$ such that $nG=1$. But for a divisible group, $kG=G$ for any $k$. Can you figure out how to find such $n$?

A:

Three steps (alternative to Pedro Tamaroff's nice answer) for a slightly more general result.

A quotient of a divisible group is divisible (the proof is very simple).
A finitely generated abelian group is a direct sum of cyclic groups (main theorem on finitely generated abelian groups).
No cyclic group is divisible (just a verification).


Q:

Cyclic Dependencies

Are cyclic dependencies a common thing in games dev? I ask as I keep getting into situation where I'm using and have been told more than once that they should be avoided.
I am wondering if this is just a what people say as a general rule of thumb in the software development business. and that the nature of game programming produces such dependencies.
// Foo
#include <Bar.hpp>
class Foo {
    bar& m_bar;
};

and
// Bar
class Foo;
class Bar {
    Foo* m_foo;
};

I do this alot in Ruby, but dynamic languages are more forgiving in this instance, where as static ones, not so much.

A:

Since you're using indirect addressing (pointers or references), and you don't need to know the contents of the other object at declaration time (only at implementation time) this will work just fine in most languages. Obviously it falls apart when you have one object containing another (because to know the size of the containing object, you have to know the full details of the contained object).
All of that is just semantics though, the fact that you can do such a thing is not a reason why you should. The problem that you'll face is that you are essentially tightly binding those two classes together. You can't have a Foo without a Bar, nor a Bar without a Foo. So you can't re-use Foo elsewhere without also dragging Bar along as well, and that may just not be appropriate. So if the only reason Foo needs to know about Bar is for one little thing, that might even be optional, that's a massive pain.
For example, if you have a character instance which knows about an navigation state structure to run its navigation logic, but in turn, the navigation state needs a back pointer to the character instance so it can get, say, its position. The navigation logic might also be applicable to vehicles, but you can't use it, because navigation is assuming that it's hooked to a character.
A much better approach to this is to understand what the back-pointers are being used for, and define an interface which can be used instead. Instead of having a Character* pointer, the navigation state has an IPositionable pointer (and Character implements IPositionable somehow). Now the navigation logic doesn't care how it is used, and can be re-used for characters, vehicles, anything. Better yet, the navigation logic could be split out into its own library / module, because it now has no awareness of anything above its own level - it's nice and self-contained.
Game development is not special in this regard. If you are producing many such tight circular dependencies like this, it is because your structures are poorly designed. This is a normal software engineering problem, and all of the same guidances apply.


Q:

powershell regex issue with powershell 2 vs. powershell 5 end of line anchor

Given the following code:
$inputString = "`r`n#cmakedefine BREAK_THE_CODE`r`n"
$match = '(?m)^(.*?)#cmakedefine(.*?)$'
$replace = 'hello $1#undef$2 goodbye '
$retVal = $inputString -replace $match,$replace -join "`r`n"
Write-Host $retVal

Powershell 5 produces the following (expected) output:
hello #undef BREAK_THE_CODE goodbye

Powershell 2 produces the following (unexpected) output:
 goodbye def BREAK_THE_CODE

Anyone know why?  Or have a workaround.  I'm fine with using [regex::] if it buys me more consistency.  I need both versions to produce the same results.  For what it's worth, hello and goodbye are going to end up being /* and */ but I'm trying to avoid confusing the issue with anything that could be interpreted as a special character.
EDIT: Matt's answer below is detailing that both Powershell versions are producing the same output, [CR][LF]hello #undef BREAK_THE_CODE[CR] goodbye [LF]
and the apparent difference between the versions is actually ISE vs. not ISE and Write-Host.  So the root problem is here is that my regex was just broken, although I still don't know why that is.
I ended up with:
$match = "(?m)^(.*?)#cmakedefine([^\r\n]*)"
$replace = '/* $1#undef$2 */'

As a little sidebar, the help for the VS 2015 IDE (which almost definitely uses the same regex engine) lists \r?$ as the proper end of line anchor:
https://msdn.microsoft.com/en-us/library/2k3te2cs.aspx
That anchor could be made to work by capturing the \r portion of it, which I initially did, but I prefered Wiktor's solution below.

A:

This does not have anything to do with regex or PS Version but with how Write-Host is dealing with that lonely carriage return in the middle of the string. I can also reproduce this in PowerShell 2.0 and 5.0 but not ISE since it is a different environment. You can reduce your findings to this statement.
write-host "Hello Matt`rBagel"

It should print "Hello Matt Bagel" but instead prints "Bagel Matt" the carriage return resets the host cursorposition and then continues typing. So it did print Hello Matt but then overwrote "Hello" with "Bagel".
Wikipedias definition of CR will help explain that this is  status by design when the control character is by itself.

A carriage return, sometimes known as a cartridge return and often shortened to CR,  or return, is a control character or mechanism used to reset a device's position to the beginning of a line of text.

You would not see this if you just use Write-Output or just $retVal on the command line. Removing the lonely CR would also fix this.
write-host ("Hello Matt`rBagel" -replace "`r(?<!`n)")

The reason you have this issue is that it appears your (.*?)$ is anchored on "`n" so the capture group is consuming the carriage return. If this is something you are seeing in your real data then you would need to account for it somehow.

A:

The problem with your '(?m)^(.*?)#cmakedefine(.*?)$' pattern is that the . symbol matches any char but an LF (a newline only), and (?m) modifier makes the $ anchor match right before the LF, after a possible CR. That means, the CR symbol is present at the end of Capturing group 2.
Look at your string:
<CR><LF>
#cmakedefine BREAK_THE_CODE<CR><LF>
|------------- MATCH ---------|
||          |-----Group2------|

Group 1 value is empty, Group 2 contains  BREAK_THE_CODE. So, the CR becomes "lonely" as Matt explains.
Here is a possible fix, replace the last lazy dot pattern with [^\r\n]* that matches 0 or more chars other than CR and LF (and $ becomes redundant then):
$match = '(?m)^(.*?)#cmakedefine([^\r\n]*)'
$replace = 'hello $1#undef$2 goodbye '

Here is a regex demo (unfortunately, all the values in the table there are trimmed from whitespace, but it must work well now.)


Q:

Obtain value from href with name using jquery

Is it possible to pass values to jquery if an a href has a name? I have posted my code which I think illustartes the point. In php, I would use a switch statement, but I am novice to jQuery, so could use some help. For example, if a user clicks on the link with the name of billing, I need to capture that value and process in jquery. Thanks
html

Billing

Report Error

A:

$('.greybox a').on('click',function(){
   if(this.name === 'billing'){
      // billing clicked
   }
});


Q:

Segmentation Fault in C++ most probably in strtok operation

I was writing a postfix evaluation program which could handle multiple digits. Therefore I first read the inputs to a character array, and split them to array of (character array). Whenever I run my program, it gives a segmentation error (g++ on Ubuntu 13.10)
Here's my function to split
int split(char str[], char *ret[]){
    int c=0;
    char * pch;
    pch = strtok (str," ");
    while (pch != NULL)
    {
        //printf ("%s\n",pch);
        strcpy(ret[c], pch); c++;
        //cout<<ret[c];
        pch = strtok (NULL, " ");
    }
    return c;
}

And part of my main()
char* s;
s =  new char[200];
cout<<"Enter Postfix Expression:\n > ";
cin.getline(s,200);
char* st[200];
//int size=3;
int size = split(s, st); // < Is what I'm passing correct?

I could not understand why the segfault occurred. Any suggestions?
EDIT: Thanks to yugnum for the answer. The following did the trick
...
ret[c] = new char[strlen(pch)];
strcpy(ret[c], pch); c++;
...

A:

char* st[200];
int size = split(s, st);

int split(char str[], char *ret[]){
  ...
  strcpy(ret[c], pch);
  ...
}

this is what is wrong, you just pass bunch of uninitialized pointers to strcpy while it requires pointer that points to valid allocated memory.


Q:

Make a tweet from Java application

I need help to post a tweet from an Java application, I already made some work, reagarding the authorization part.
I made a connection to the Twitter authorization and been routed to the page on Twitter where you grant the application access to Twitter.
But now I want to make a connection and to be able to post a tweet from my user account. How do I go about this?
I've looked in to some guide's but they all give me different answers and are a bit confusing...

A:

Why don't you use Twitter Java libraries, such as Twitter4J ?


Q:

Occaisonal black screen on boot AMD A8-4500M laptop

Half of the time when I turn on my laptop I get a black screen.CTRL+ALT+F1 also shows a black screen.I have to put my laptop to sleep and back on to get the screen to work.When my screen is not black I see a message before boot for about a second relating to the radeon driver and then it boots correctly
I am running default drivers with kernel 4.4 installed. The laptop is a HP Pavilion g7 2269wm
Output of dmesg | grep -i radeon when screen is NOT black
[    0.194197] smpboot: CPU0: AMD A8-4500M APU with Radeon(tm) HD Graphics (family: 0x15, model: 0x10, stepping: 0x1)
[    6.062500] [drm] radeon kernel modesetting enabled.
[    6.080879] fb: switching to radeondrmfb from EFI VGA
[    6.082067] radeon 0000:00:01.0: VRAM: 512M 0x0000000000000000 - 0x000000001FFFFFFF (512M used)
[    6.082075] radeon 0000:00:01.0: GTT: 1024M 0x0000000020000000 - 0x000000005FFFFFFF
[    6.082382] [drm] radeon: 512M of VRAM memory ready
[    6.082385] [drm] radeon: 1024M of GTT memory ready.
[    6.082865] [drm] radeon: dpm initialized
[    6.083172] radeon 0000:00:01.0: Direct firmware load for radeon/TAHITI_vce.bin failed with error -2
[    6.083181] radeon 0000:00:01.0: radeon_vce: Can't load firmware "radeon/TAHITI_vce.bin"
[    6.091893] radeon 0000:00:01.0: WB enabled
[    6.091897] radeon 0000:00:01.0: fence driver on ring 0 use gpu addr 0x0000000020000c00 and cpu addr 0xffff8800355c0c00
[    6.092713] radeon 0000:00:01.0: fence driver on ring 5 use gpu addr 0x0000000000075a18 and cpu addr 0xffffc90001835a18
[    6.092717] radeon 0000:00:01.0: VCE init error (-22).
[    6.092723] radeon 0000:00:01.0: fence driver on ring 1 use gpu addr 0x0000000020000c04 and cpu addr 0xffff8800355c0c04
[    6.092726] radeon 0000:00:01.0: fence driver on ring 2 use gpu addr 0x0000000020000c08 and cpu addr 0xffff8800355c0c08
[    6.092729] radeon 0000:00:01.0: fence driver on ring 3 use gpu addr 0x0000000020000c0c and cpu addr 0xffff8800355c0c0c
[    6.092732] radeon 0000:00:01.0: fence driver on ring 4 use gpu addr 0x0000000020000c10 and cpu addr 0xffff8800355c0c10
[    6.092739] radeon 0000:00:01.0: radeon: MSI limited to 32-bit
[    6.092910] radeon 0000:00:01.0: radeon: using MSI.
[    6.093191] [drm] radeon: irq initialized.
[    7.275570] [drm:vce_v1_0_start [radeon]] *ERROR* VCE not responding, trying to reset the ECPU!!!
[    8.295553] [drm:vce_v1_0_start [radeon]] *ERROR* VCE not responding, trying to reset the ECPU!!!
[    9.315552] [drm:vce_v1_0_start [radeon]] *ERROR* VCE not responding, trying to reset the ECPU!!!
[   10.335549] [drm:vce_v1_0_start [radeon]] *ERROR* VCE not responding, trying to reset the ECPU!!!
[   11.355546] [drm:vce_v1_0_start [radeon]] *ERROR* VCE not responding, trying to reset the ECPU!!!
[   12.375543] [drm:vce_v1_0_start [radeon]] *ERROR* VCE not responding, trying to reset the ECPU!!!
[   13.395541] [drm:vce_v1_0_start [radeon]] *ERROR* VCE not responding, trying to reset the ECPU!!!
[   14.415540] [drm:vce_v1_0_start [radeon]] *ERROR* VCE not responding, trying to reset the ECPU!!!
[   15.435537] [drm:vce_v1_0_start [radeon]] *ERROR* VCE not responding, trying to reset the ECPU!!!
[   16.455535] [drm:vce_v1_0_start [radeon]] *ERROR* VCE not responding, trying to reset the ECPU!!!
[   16.475537] [drm:vce_v1_0_start [radeon]] *ERROR* VCE not responding, giving up!!!
[   16.475607] [drm:cayman_startup [radeon]] *ERROR* radeon: failed initializing VCE (-1).
[   16.521446] [drm] radeon atom DIG backlight initialized
[   16.521450] [drm] Radeon Display Connectors
[   17.333968] fbcon: radeondrmfb (fb0) is primary device
[   18.239239] radeon 0000:00:01.0: fb0: radeondrmfb frame buffer device
[   18.306279] [drm] Initialized radeon 2.43.0 20080528 for 0000:00:01.0 on minor 0

I have tried nomodeset . It works but causes the laptop to be slow and heat up

A:

My laptop is UEFI so I use rEFInd.The problem was that rEFInd was loading GRUB which caused some issues.I made rEFInd directly boot elementary OS (using EFI Stub) without GRUB and the problem went away.I could also use secure boot now


Q:

How can i compare set of selected box values with another set of selected box values?

I have the form with selected boxes like below.

i need to group the first two select boxes "Select Session" and "Select Time", i need to allow select unique sessions and time for each pair of dropdowns. If i selected one session and time in one drop down and again i selected the same session and time in the below dropodwns that time i have to pop up the error message like "Same session and time Already Selected".
How can i do this?.. the HTML code is

You can enroll in one or more sessions:

            Select Session:
            <select id="first" name="first" class="tx_bx" value="">
                <option value="">- Select -</option>
                <option value="">Session #1: Tues May 31st - Fri June 10th (1-5:30PM)</option>
<option value="">Session #2: Tues June 14th - Fri June 24th (9-2:00PM)</option>
<option value="">Session #3: Tues June 28th - Fri July 8th (9-2:00PM)</option>
<option value="">Session #4: Tues July 12th - Fri July 22nd (9-2:00PM)</option>
<option value="">Session #5: Tues July 26th - Fri Aug 5th (9-2:00PM)</option>
<option value="">Session #6: Tues Aug 9th - Fri Aug 19th (9-2:00PM)</option>

            </select>

            Select Time:
            <select id="first" name="first" class="tx_bx" value="">
                <option value="">- Select -</option>
                <option value="">#1 only: 1pm</option>
<option value="">#1 only: 1:30pm</option>
<option value="">#1 only: 2pm</option>
<option value="">#1 only: 2:30pm</option>
<option value="">#1 only: 3:30pm</option>
<option value="">#1 only: 4pm</option>
<option value="">#1 only: 4:30 pm</option>
<option value="">#1 only: 5:00pm</option>
<option value="">9am</option>
<option value="">9:30am</option>
<option value="">10 am</option>
<option value="">10:30am</option>
<option value="">11 am</option>
<option value="">11:30am</option>
<option value="">12:30 pm</option>
<option value="">1:00pm</option><option value="">1:30pm</option>
            </select>

            Select Session:
            <select id="second" name="second" class="tx_bx" value="">
                <option value="">- Select -</option>
                <option value="">Session #1: Tues May 31st - Fri June 10th (1-5:30PM)</option>
<option value="">Session #2: Tues June 14th - Fri June 24th (9-2:00PM)</option>
<option value="">Session #3: Tues June 28th - Fri July 8th (9-2:00PM)</option>
<option value="">Session #4: Tues July 12th - Fri July 22nd (9-2:00PM)</option>
<option value="">Session #5: Tues July 26th - Fri Aug 5th (9-2:00PM)</option>
<option value="">Session #6: Tues Aug 9th - Fri Aug 19th (9-2:00PM)</option>

            </select>

            Select Time:
            <select id="second" name="second" class="tx_bx" value="">
                <option value="">- Select -</option>
                <option value="">#1 only: 1pm</option>
<option value="">#1 only: 1:30pm</option>
<option value="">#1 only: 2pm</option>
<option value="">#1 only: 2:30pm</option>
<option value="">#1 only: 3:30pm</option>
<option value="">#1 only: 4pm</option>
<option value="">#1 only: 4:30 pm</option>
<option value="">#1 only: 5:00pm</option>
<option value="">9am</option>
<option value="">9:30am</option>
<option value="">10 am</option>
<option value="">10:30am</option>
<option value="">11 am</option>
<option value="">11:30am</option>
<option value="">12:30 pm</option>
<option value="">1:00pm</option><option value="">1:30pm</option>
            </select>

            Select Session:
            <select id="third" name="third" class="tx_bx" value="">
                <option value="">- Select -</option>
                <option value="">Session #1: Tues May 31st - Fri June 10th (1-5:30PM)</option>
<option value="">Session #2: Tues June 14th - Fri June 24th (9-2:00PM)</option>
<option value="">Session #3: Tues June 28th - Fri July 8th (9-2:00PM)</option>
<option value="">Session #4: Tues July 12th - Fri July 22nd (9-2:00PM)</option>
<option value="">Session #5: Tues July 26th - Fri Aug 5th (9-2:00PM)</option>
<option value="">Session #6: Tues Aug 9th - Fri Aug 19th (9-2:00PM)</option>

            </select>

            Select Time:
            <select id="third" name="third" class="tx_bx" value="">
                <option value="">- Select -</option>
                <option value="">#1 only: 1pm</option>
<option value="">#1 only: 1:30pm</option>
<option value="">#1 only: 2pm</option>
<option value="">#1 only: 2:30pm</option>
<option value="">#1 only: 3:30pm</option>
<option value="">#1 only: 4pm</option>
<option value="">#1 only: 4:30 pm</option>
<option value="">#1 only: 5:00pm</option>
<option value="">9am</option>
<option value="">9:30am</option>
<option value="">10 am</option>
<option value="">10:30am</option>
<option value="">11 am</option>
<option value="">11:30am</option>
<option value="">12:30 pm</option>
<option value="">1:00pm</option><option value="">1:30pm</option>
            </select>

A:

I have written the code for this one. it's working. Find below the structure.
HTML Structure is,

You can enroll in one or more sessions:

            Select Session:
            <select id="country" name="country" class="tx_bx" value="">
                <option value="">- Select -</option>
                <option value="">Session #1: Tues May 31st - Fri June 10th (1-5:30PM)</option>
<option value="">Session #2: Tues June 14th - Fri June 24th (9-2:00PM)</option>
<option value="">Session #3: Tues June 28th - Fri July 8th (9-2:00PM)</option>
<option value="">Session #4: Tues July 12th - Fri July 22nd (9-2:00PM)</option>
<option value="">Session #5: Tues July 26th - Fri Aug 5th (9-2:00PM)</option>
<option value="">Session #6: Tues Aug 9th - Fri Aug 19th (9-2:00PM)</option>

            </select>

            Select Time:
            <select id="country" name="country" class="tx_bx" value="">
                <option value="">- Select -</option>
                <option value="">#1 only: 1pm</option>
<option value="">#1 only: 1:30pm</option>
<option value="">#1 only: 2pm</option>
<option value="">#1 only: 2:30pm</option>
<option value="">#1 only: 3:30pm</option>
<option value="">#1 only: 4pm</option>
<option value="">#1 only: 4:30 pm</option>
<option value="">#1 only: 5:00pm</option>
<option value="">9am</option>
<option value="">9:30am</option>
<option value="">10 am</option>
<option value="">10:30am</option>
<option value="">11 am</option>
<option value="">11:30am</option>
<option value="">12:30 pm</option>
<option value="">1:00pm</option><option value="">1:30pm</option>

           </select>

            Select Session:
            <select id="country" name="country" class="tx_bx" value="">
                <option value="">- Select -</option>
                <option value="">Session #1: Tues May 31st - Fri June 10th (1-5:30PM)</option>
<option value="">Session #2: Tues June 14th - Fri June 24th (9-2:00PM)</option>
<option value="">Session #3: Tues June 28th - Fri July 8th (9-2:00PM)</option>
<option value="">Session #4: Tues July 12th - Fri July 22nd (9-2:00PM)</option>
<option value="">Session #5: Tues July 26th - Fri Aug 5th (9-2:00PM)</option>
<option value="">Session #6: Tues Aug 9th - Fri Aug 19th (9-2:00PM)</option>

            </select>

            Select Time:
            <select id="country" name="country" class="tx_bx" value="">
                <option value="">- Select -</option>
                <option value="">#1 only: 1pm</option>
<option value="">#1 only: 1:30pm</option>
<option value="">#1 only: 2pm</option>
<option value="">#1 only: 2:30pm</option>
<option value="">#1 only: 3:30pm</option>
<option value="">#1 only: 4pm</option>
<option value="">#1 only: 4:30 pm</option>
<option value="">#1 only: 5:00pm</option>
<option value="">9am</option>
<option value="">9:30am</option>
<option value="">10 am</option>
<option value="">10:30am</option>
<option value="">11 am</option>
<option value="">11:30am</option>
<option value="">12:30 pm</option>
<option value="">1:00pm</option><option value="">1:30pm</option>
            </select>

            Select Session:
            <select id="country" name="country" class="tx_bx" value="">
                <option value="">- Select -</option>
                <option value="">Session #1: Tues May 31st - Fri June 10th (1-5:30PM)</option>
<option value="">Session #2: Tues June 14th - Fri June 24th (9-2:00PM)</option>
<option value="">Session #3: Tues June 28th - Fri July 8th (9-2:00PM)</option>
<option value="">Session #4: Tues July 12th - Fri July 22nd (9-2:00PM)</option>
<option value="">Session #5: Tues July 26th - Fri Aug 5th (9-2:00PM)</option>
<option value="">Session #6: Tues Aug 9th - Fri Aug 19th (9-2:00PM)</option>

            </select>

            Select Time:
            <select id="country" name="country" class="tx_bx" value="">
                <option value="">- Select -</option>
                <option value="">#1 only: 1pm</option>
<option value="">#1 only: 1:30pm</option>
<option value="">#1 only: 2pm</option>
<option value="">#1 only: 2:30pm</option>
<option value="">#1 only: 3:30pm</option>
<option value="">#1 only: 4pm</option>
<option value="">#1 only: 4:30 pm</option>
<option value="">#1 only: 5:00pm</option>
<option value="">9am</option>
<option value="">9:30am</option>
<option value="">10 am</option>
<option value="">10:30am</option>
<option value="">11 am</option>
<option value="">11:30am</option>
<option value="">12:30 pm</option>
<option value="">1:00pm</option><option value="">1:30pm</option>
            </select>

And the script is,


Q:

find contours in image where object and background have nearly same color

How could you perform efficiently edge detection when the object in the image and background have nearly same color?
I tried with the code below but it doesn't give what I want:
import cv2
import matplotlib.pyplot as plt
image = cv2.imread("image1.JPG")

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.bilateralFilter(gray, 11, 17, 17)
edged = cv2.Canny(gray, 10, 150)
edged = cv2.dilate(edged, None, iterations=1)
edged = cv2.erode(edged, None, iterations=1)

plt.imshow(edged)
plt.show()

image1
edges1

A:

You shouldn't convert the image to grayscale using COLOR_BGR2GRAY, that's losing the color data. What you want to do is to find the color space that gives you the best edge detection results. There are 3 color spaces you can try and probably one would work fine for your application, HSV, YCrCb, and LAB.
Here is the result of canny edge detection on the second component of the LAB image.

lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
a_component = lab[:,:,1]
edged = cv2.Canny(a_component, 10, 50)


Q:

AngularJS insert invalid HTML

I have an app that requires HTML to be pieced together from different APIs. Rather than getting into specifics there, let me just say that we have tried getting away from that many times but in the end the best answer always end up being what we currently have. Hopefully that changes someday but for now it's working great.
Currently, the HTML is parsed together as a string server-side using NodeJS and sent across the wire as complete HTML to be rendered. I'm in the process of adopting AngularJS, and while I'm loving it I am stuck on this issue-- how can I use Angular templating to insert invalid HTML at times?
The server will return three JSON fields: leadingHTML, trailingHTML, and copy. The copy field is always valid HTML, but leadingHTML and trailingHTML can sometimes return invalid HTML. When all three are added together, valid HTML results.
Let me illustrate:
leadingHTML='
';
copy = '
I love AngularJS
';
trailingHTML='
';

As you can see, if you add those together you will get the valid HTML that is required to be displayed. It's pretty easy to make the fields trustworthy HTML in Angular:
for (i in data.results){
    data.results[i].copy=$sce.trustAsHtml(data.results[i].copy);
    data.results[i].leadingHTML =$sce.trustAsHtml(data.results[i].leadingHTML );
    data.results[i].trailingHTML =$sce.trustAsHtml(data.results[i].trailingHTML );
}

And then render the copy in my view:

But I need a way that does what this looks like it would do, but the leadingHTML and trailingHTML scope variables get render as strings:

{{ i.leadingHTML }}

{{ i.trailingHTML }}

Is the best answer here to build the template via javascript? Would that even work?

A:

Are you able to pre-process your data so that you do have valid HTML?
var item;
for (i in data.results){
    item = data.results[i];
    item.content = $sce.trustAsHtml(item.leadingHTML + item.copy + item.trailingHTML);
}

Then you can just bind to the combined content in the view:

Edit:
Yes, this will allow you to embed expressions in your HTML content.
In fact, you will need to be careful that you aren't opening yourself up to security exploits in the trusted HTML content (see the example at the bottom of the page for the $sce service).
Using $sce.trustAsHtml in this way is roughly equivalent to loading a directive's templateUrl from your site, so the security considerations around that are probably the same. See the "How does it work?" and
"Impact on loading templates".


Q:

Using Visual Studio as a Task-Focused IDE

Are there patterns or libraries or any official Microsoft SDK for using Visual Studio as a specifically Task-Focused UI?
For example, both Revolution R (IDE for the R language) and SQL 2012 (and I think SQL 2008 and possibly 2005) use Visual Studio as the underlying IDE framework.
Is there an officially supported SDK and/or examples/samples for doing this type of thing?
I am building a language Parser for an existing language - whose only available IDE is INSANELY expensive - using Irony (and eventually will generate a Language Service as well).
Any direct or indirect suggestions/answers are appreciated.

A:

You might want to have a look at Visual Studio Shell.  The Visual Studio 2012 Shell (Isolated) provides a foundation on which you can build your own custom-branded tools environment.
Visual Studio Shell is part of the Visual Studio SDK.  A redistributable runtime is provided.
See also http://studioshell.codeplex.com/


Q:

Search nested array for certain criteria

I have a report document that has an images array in it.  Inside each image is a thumbnails array that track the thumbnails I have generated for the image.
{
  "_id" : ObjectId("536021ba9b319f5195000004"),
  "images": [{
    "name": "some_image.jpg",
    "width": 1200,
    "height": 1200,
    "thumbnails": [{
      "name": "some_image_150.jpg",
      "size": 150
    }]
  }]
}

Now lets say I want to generate the following thumbnail sizes:
[150, 320, 800]

Is there a way that I can query the reports collection and get back all reports that do not have all the proper thumbnails generated?  I.E. in the example above, the query would return the example document as it has an image that does not contain all the proper attachments.
Best case would be to only get images where all thumbs are not generated, ie if a report has 2 images and one image has all the thumbnails and another image does not it would be nice to just get the image that needs thumbnails.
I have tried messing around with aggregation to unwind the images array, such that I can match against things.  However I am running in a problem with trying to match the numbers in my array [150, 320, 800] to the documents in thumbnails.
EDIT:
I also need to determine if a thumb should not be created.  I.E. if my original image is 350x350, then I should not create a 800x800 thumbnail.  so even though 800 is in my thumbnail set I need to only take values from that thumbnail set that are less than the original images width and height.

A:

I believe following should work fine for your scenario:
db.mycollection.find( {"images.thumbnails.size": {$not: {"$all": [150, 320, 800]}}  })

This should give you any document that does not has one or more of those thumbnail sizes.

A:

You would want to be working on a negative case of the $all operator combined with $not:
db.collection.find({
    "images.thumbnails.size": {
        "$not": { "$all": [ 150, 320, 800 ] }
    }
})

Possibly in versions prior to MongoDB 2.6 you might need to adapt this due to a change in the logic for $all but the same thing is constructed using $and:
db.collection.find({
    "$and": [
        { "$ne": { "images.thumbnail.size": 150 } },
        { "$ne": { "images.thumbnail.size": 320 } },
        { "$ne": { "images.thumbnail.size": 800 } }
    ]
})

Noting of course that these statements are matching "documents" and not the elements of your "images" array, to actually filter those you would need to apply this to aggregate:
db.collection.aggregate([
    // Match the documents meeting the conditions
    { "$match": {
        "images.thumbnails.size": {
            "$not": { "$all": [ 150, 320, 800 ] }
        }
    }},

    // Unwind the images array
    { "$unwind": "$images" },

    // Filter out any array elements that do not match
    { "$match": {
        "images.thumbnails.size": {
            "$not": { "$all": [ 150, 320, 800 ] }
        }
    }},

    // Optional: Projection re-shaping
    { "$project": {
        "_id": {
            "_id": "$_id",
            "images": {
                "name": "$images.name",
                "width": "$images.width",
                "height": "$images.height"
            }
        },
        "thumbs": "$images.thumbnails"
    }},

    // Optional: unwind the thumbnails
    { "$unwind": "$thumbs" },

    // Optional: group back only the sizes
    { "$group": {
        "_id": "$_id",
        "thumbs": { "$push": "$thumbs.size" }
    }},

    // Optional: Project with the difference on the set
    { "$project": {
        "_id": "$_id._id",
        "images": {
            "name": "$_id.images.name",
            "width": "$_id.images.width",
            "height": "$_id.images.height",
            "missingThumbs": { "$setDifference": [
                 [ 150, 320, 800 ],
                 "$thumbs"
            ]}
        }
    }},

    // Restore the images array
    { "$group": {
        "_id": "$_id",
        "images": { "$push": "$images" }
    }}

])

So this uses $setDifference to take this a little further and tell you which of the "thumbnail sizes" you were testing for did not exist. The stage is optional as that operator is only available from MongoDB 2.6 and upwards, so otherwise just remove the stages marked as "Optional:" to allow this to filter the "images" array entries.
You also could do the "difference" matching in versions prior to 2.6 but it is a fair bit more involved, but you may want to try and work that part out.

As for your full generation edit here would be the full listing:
db.collection.aggregate([
    // Match the documents meeting the conditions
    { "$match": {
        "images.thumbnails.size": {
            "$not": { "$all": [ 150, 320, 800 ] }
        }
    }},

    // Unwind the images array
    { "$unwind": "$images" },

    // Filter out any array elements that do not match
    { "$match": {
        "images.thumbnails.size": {
            "$not": { "$all": [ 150, 320, 800 ] }
        }
    }},

    // Projection re-shaping
    { "$project": {
        "_id": {
            "_id": "$_id",
            "images": {
                "name": "$images.name",
                "width": "$images.width",
                "height": "$images.height"
            }
        },
        "thumbs": "$images.thumbnails"
    }},

    // unwind the thumbnails
    { "$unwind": "$thumbs" },

    // group back only the sizes
    { "$group": {
        "_id": "$_id",
        "thumbs": { "$push": "$thumbs.size" }
    }},

    // Project missingThumbs
    { "$project": {
        "missingThumbs": { "$setDifference": [
             [ 150, 320, 800 ],
             "$thumbs"
        ]}
    }},

    // Unwind the missing thumbs
    { "$unwind": "$missingThumbs" },

    // Project a size test
    { "$project": {
        "missingThumbs": 1,
        "larger": { "$gte": [
            "$_id.images.width",
            "$missingThumbs"
        ]}
    }},

    // Match the size test
    { "$match": { "larger": true }},

    // Group back the missing thumbs
    { "$group": {
        "_id": "$_id",
        "missingThumbs": { "$push": "$missingThumbs" }
    }},

    // Project the images entry
    { "$project": {
        "_id": "$_id._id",
        "images": {
            "name": "$_id.images.name",
            "width": "$_id.images.width",
            "height": "$_id.images.height",
            "missingThumbs": "$missingThumbs"
        }
    }},

    // Restore the images array
    { "$group": {
        "_id": "$_id",
        "images": { "$push": "$images" }
    }}

])

Nothing optional in here as you would clearly be using the features to detect the thumbnails you don't already have. The additional steps are there to compare the size of the missing thumb against the size of the image. Anything not detected as "larger" would be excluded.


Q:

How to choose the right potentiometer for dimming a LED

I have a reading lamp from IKEA. It has a bright LED. Too bright for my taste. So I inspected it and it is composed of a DC power supply unit that outputs 7V and a maximum of 3W. The LED unit is saying 1.5W.
My college memories tell me that this means that the LED is doing 214 mA at an equivalent of 32.7 ohms.
I am thinking to dim the LED using a potentiometer but I need to understand what resistance range should the right potentiometer have. If I choose a wide range the usable range within will be too short and I would have a hard time setting the desired light, choosing it too narrow it will not dim enough. I guess. Please correct any assumption that I make if needed.
Furthermore I remember that current vs light given by a LED is heavily non-linear. That means that if I manage to cut the current in half the light will not be half but probably 1/4 or even 1/5. If I'm not wrong again.
Considering that I would choose a potentiometer with a maximum resistance of the same equivalent resistance of the LED would that be a good choice for me?
I am aware this question might require editing and please provide comments that would help me pen the question better.

A:

Furthermore I remember that current vs light given by a LED is heavily
  non-linear. That means that if I manage to cut the current in half the
  light will not be half but probably 1/4 or even 1/5. If I'm not wrong
  again.

It is actually directly linear to the current (once you factor heat variation), but what is not linear is the eye response to light intensity.
The driver might not drive the LED in DC mode but perhaps in PWM mode. PWM mode allows to increase the power output of the LED, as it is flashing faster than the eye response, if you have a duty cycle of 20%, you can power the LED at 5 times higher for the same "load" (with abstraction to losses) and the eye will perceive a much brighter light as it only sees the "on" state.
If you want to DIM the IKEA LED, you need first to understand the driver schematics.
Adding a potentiometer before the driver won't work.
Putting a  potentiometer within the LED strip it will probably overheat as potentiometer are not designed to dissipate power. Also the driver will regulate the current, so increasing the impedance probably won't work.


Q:

What difference between URL paths in Flask?

What difference between URL paths:
@app.route('/projects')

@app.route('/projects/')

What does mean slash in the end of route path? In witch cases to use it?
If I understood correctly it is used for absolute and relative path to server files? Right?

A:

This is called trailing slash.
For general trailing slash,

https://www.google.com/example/ -> It's a directory.

Firtst, Server checks if the directory exists.
Second, If it exists, server checks default file, such as index.html

https://www.google.com/example -> It's a file.

Firtst, Server checks if the file exists.
Second, if not, check the directory with that name.

Therefore, if you specify a trailing slash when requesting a directory resource, there is a small gain in page response speed because you can skip file checking.
In Flask

@app.route('/projects')

call to /projects/  -> return 404.
(Werkzeug interprets as an explicit rule, so it's not match a trailing slash.)
call to /projects  -> return 200

@app.route('/projects/')

call to /projects/  -> return 200
call to /projects  -> return 302
(Werkzeug will redirect if the url doesn't have it)

This article will be helpful.


Q:

How did Perkins find out that the time of Harry's trial had changed?

Harry and Mr Weasley only find out about the change in the time of Harry's hearing because of Perkins, who works in Mr Weasley's office. Their conversation gives the impression that it was pure coincidence that Harry and Mr Weasley came in early and that Perkins was able to find them.

"Ah, Harry, this is Perkins.”
  A stooped, timid-looking old wizard with fluffy white hair had just entered the room, panting.
  “Oh Arthur!” he said desperately, without looking at Harry. “Thank goodness, I didn’t know what to do for the best, whether to wait here for you or not, I’ve just sent an owl to your home but you’ve obviously missed it - an urgent message came ten minutes ago -”
  “I know about the regurgitating toilet,” said Mr. Weasley.
  “No, no, it’s not the toilet, it’s the Potter boy’s hearing - they’ve changed the time and venue - it starts at eight o’clock now and it’s down in old Courtroom Ten."
  “Down in old - but they told me - Merlin’s beard -”
  Mr. Weasley looked at his watch, let out a yelp, and leapt from his chair.
  “Quick, Harry, we should have been there five minutes ago!”
(Order of the Phoenix, Chapter 7, The Ministry of Magic).

What isn't clear is how Perkins might've found out about the change in time and location. The only communication seems to have been from the Wizengamot to Harry by owl.

“Sorry,” said Harry nervously. “I-I didn’t know the time had changed.”
  “That is not the Wizengamot’s fault,” said the voice. “An owl was sent to you this morning. Take your seat.”
(Order of the Phoenix, Chapter 8, The Hearing).

Considering that the whole point of the exercise of moving the hearing was to try and get Harry to miss his trial and be expelled automatically it seems strange that Perkins would be privy to this information. I'd have thought that the true trial time would be closely guarded secret within the Ministry.
Perkins clearly didn't see the owl that was sent to Grimmauld Place. So how could he have possibly known about the change in time and location?

A:

I think you may have misconstrued the order of events slightly. The Ministry moved the trial and a letter was sent by owl to Mr Weasley at impossibly short notice so that there would be plausible deniability that they'd tried to get hold of him.
At the same time it would appear that a member of the Wizengamot (or A.N. Other MoM official) who was loyal to Dumbledore contacted Perkins in order to try to get hold of Mr Weasley. This was separate to the owl/s and was probably an unauthorised action.

As to the identity of the mole, my money is on Madam Bones. In addition to showing an obvious desire to give Harry a fair hearing she was the first to call for a vote to acquit him and personally lead the faction that voted in his favour. Although she wasn't a fully paid-up member of the Order of the Phoenix, she was definitely part of the anti-Voldemort tendency and connected to the Order through her deceased brother, a former member.

A:

Forgive me, but surely the answer is in the question?

'Oh Arthur!' he said desperately, without looking at Harry. 'Thank goodness, I didn't know what to do for the best, whether to wait here for you or not, I've just sent an owl to your home but you've obviously missed it - an urgent message came ten minutes ago -'

Perkins is Arthur's colleague in the Ministry, they share an office. Clearly the message was sent to The Misuse of Muggle Artefacts Office, where Perkins was, before Mr Weasley arrived with Harry, in addition to the owl being sent to Harry. I don't think there's any need to assume leaks or moles.
In fact, I disagree with you about the intention behind changing the location. I think the intention was to wrong-foot Dumbledore so that Harry would have to go in alone, rather than to cause Harry to miss it altogether. After all, when Arthur arrives many of the employees are still there and bustling around and Perkins was clearly in before Arthur and Harry, so the Ministry was clearly up and running, it's not like they've moved the hearing unreasonably early, they moved it from 09:00 to 08:00.
Now that may seem like a wholly unreasonable thing to do, to move it forward an hour at short notice, but it should be remembered that Harry and Arthur left Grimmauld Place early in order to take Muggle public transport and make a good impression. I don't think there's anything to indicate that they sent the letter too late for a wizard - with their floo powder and their Knight bus and so on - to turn up on time, merely that Harry and Arthur missed it for reasons the Ministry wouldn't necessarily have been anticipating.
Instead, I think what happened is that a letter was sent to Harry's place of residence - presumably Privet Drive - but of course Harry wasn't there, he was at Grimmauld Place, a secret hideout that the Ministry wouldn't know about. So it's likely that that was why he never received the letter. But the Ministry wouldn't have known anything about that. That is why I think messages seemed to arrive unreasonably late, rather than because the Ministry had actually waited until impossibly late to inform Harry.
Then Harry arrives at the Ministry with Mr Weasley and then Harry and Arthur took their time getting up to the office, believing they had an hour to spare, and Arthur paused to talk to Kingsley and so on. Now, according to Perkins, the message arrived ten minutes earlier. According to him it's been moved to 08:00 and according to Arthur, when he gets the message, they should have been there 5 minutes ago, meaning that the message arrived at the Misuse of Muggle Artefacts office 5 minutes before the hearing was due to the start. What I think happened is that, with five minutes to go, and Harry still not there, a second message was sent to the Misuse of Muggle Artefacts Office, perhaps using one of the paper aeroplane memos. The Ministry would have known that Arthur was accompanying Harry, because he told them as much using the phone in the visitor's entrance (the disused phone box).
But call me a Ministry apologist if you will ... :P


Q:

How could this solution to an easy probability problem be considered wrong?

I was asked to re-check an exam my brother just got back. His solution to the following problem was marked as false by his teacher:

A user sits in front of a computer with a keyboard with 26 keys for the lower-case letters (a, b, c, ...z) and randomly hits the keys. What is the probability he types the word "passwort"?

The solution my brother gave:

The word "passwort" has 8 letters. Therefore the probability to type it is $\frac{1}{26}^8 = 4.788E-12$

Which is also the solution I would have come up with. So is this solution wrong, and why is it wrong?

A:

This is the answer I would give, except I would stop at $\frac 1{26^8}$.  Maybe your teacher wants to consider he might press a different number of keys than $8$.  Maybe your teacher objects to the equal sign when they are not equal (though they are close).  Ask your teacher why it is wrong.


Q:

Flatten nested array with key value pairs in Javascript

Given an array like this:
[
    { id: 1, emailAddresses: ["bill@test.com", "bob@test.com"] },
    { id: 2, emailAddresses: ["sarah@test.com" },
    { id: 3, emailAddresses: ["jane@test.com", "laura@test.com", "paul@test.com"]
]

How could I use Javascript to reduce this to an array like this:
[
    { id: 1, emailAddress: "bill@test.com" },
    { id: 1, emailAddress: "bob@test.com" },
    { id: 2, emailAddress: "sarah@test.com" },
    { id: 3, emailAddress: "jane@test.com" },
    { id: 3, emailAddress: "laura@test.com" },
    { id: 3, emailAddress: "paul@test.com" }
 ]

I've read about the functions reduce, flat, map and so on and read lots of the questions on SO about using them but I can't find anything that's asking quite the same as this and I can't get my head around using those functions to do it.

A:

You could use flatMap

const input = [
    { id: 1, emailAddresses: ["bill@test.com", "bob@test.com"] },
    { id: 2, emailAddresses: ["sarah@test.com"] },
    { id: 3, emailAddresses: ["jane@test.com", "laura@test.com", "paul@test.com"] }
]

const output = input.flatMap(o =>
    o.emailAddresses.map(e => ({ id: o.id, emailAddress: e }) )
)

console.log(output)

If flatMap is not supported, you could use a nested for...of loop:

const input = [{id:1,emailAddresses:["bill@test.com","bob@test.com"]},{id:2,emailAddresses:["sarah@test.com"]},{id:3,emailAddresses:["jane@test.com","laura@test.com","paul@test.com"]}];
const output = []

for (const { id, emailAddresses } of input)
  for (const emailAddress of emailAddresses)
    output.push({ id, emailAddress })

console.log(output)


Q:

Subsonic 3 - What is the difference between these approaches?

This method works fine:
Person p = new Person(3);
p.Name = "Bob";
p.Update();

However if I have an IQueryable foreign key collection the below fails
var foreignItems = Person.Find(x => x.ID == 3)
foreach(Person p in foreignItems)
{
  p.Name = "Bob";
  p.Update(); /*THROWS EXCEPTION */
}

Exception is thrown in Repository Update as it executes a query from BuildUpdateQuery such as - UPDATE PERSON WHERE ID = {0} which is wrong syntax!

A:

This looks like a bug, you should report it to github (the new host for SubSonic source).
In the meantime does calling p.Save() may work around the issue.


Q:

How to avoid crash when key doesnt exist in array?

Im having a lot of difficulty with arrays in PHP. They require me to write a lot of codes such as isset(), empty(), array_key_exist(); And I really dont want to deal with these. If the key doesnt exist just handle it as a null.
$arr = [
   'location' => 'Paris'
]

$arr['country'] // boom crash. How to walkaround this?

Any suggestions?
EDIT
I dont want to use any if condition. No isset(), array_key_exist, exceptions, etc. I just want them to be null if the key doesn't exist? Is this possible in PHP? The application is very abstract and data may vary on each request.

A:

My own function inspired from deceze. Works perfectly.
/**
 * Fill array with null on nonexistent keys
 *
 * @param array $arg
 * @param array $possible_keys
 */
function fillNull(array $arg, array $possible_keys){
    foreach($possible_keys as $key){
        $result[$key] = empty( $arg[$key] ) ? null : $arg[$key];
    }
    return $result;
}


Q:

Duplicate rows in multi-table MySQL query

We have three tables, "cameras", "cameratypes", and "locations".
Here are each with sample data.
locations(location_id, user_id, contact1)
select * from locations;
+-------------+---------+--------------------+
| location_id | user_id | contact1           |
+-------------+---------+--------------------+
|          38 |      96 | Joe Blow           |
|          42 |      96 | Joe Blow           |
|          45 |     105 | Francis McLucky    |
|          50 |     113 | Ogre L'Bosch       |
|          53 |     113 | Ogre L'Bosch       |
+-------------+---------+--------------------+

cameratypes(cameratype_id, title)
select * from cameratypes;
+---------------+----------------+
| cameratype_id | title          |
+---------------+----------------+
|             1 | Pan Tilt Zoom  |
|             2 | Fixed          |
|             3 | Mobile         |
+---------------+----------------+

cameras(camera_id, cameratype_id, location_id, user_id)
select * from cameras
+-----------+---------------+-------------+---------+
| camera_id | cameratype_id | location_id | user_id |
+-----------+---------------+-------------+---------+
|      4633 |             3 |          38 |      96 |
|      4637 |             3 |          38 |      96 |
|      4644 |             1 |          38 |      96 |
|      4962 |             1 |          45 |     105 |
|      4667 |             2 |          45 |     105 |
|      4681 |             2 |          50 |     113 |
|      4689 |             2 |          50 |     113 |
|      4684 |             2 |          50 |     113 |
|      4682 |             3 |          50 |     113 |
|      4691 |             2 |          53 |     113 |
+-----------+---------------+-------------+---------+

I am trying to join the tables into a report, where the output is a list of cameras, with the owner's name and camera type.
Yet, when I run my query, I get this result (which is basically multiplying the number of cameras for user 113 (he has five) by the number of camera locations he has (which is two).
My query is:
SELECT
    loc.contact1 AS 'Camera Owner Name',
    loc.location_id AS 'Location ID',
    cam.camera_id AS 'Camera ID',
    camtype.title AS 'Camera Type'
FROM engine4_securonet_cameras AS cam
LEFT JOIN engine4_securonet_locations AS loc ON cam.user_id = loc.user_id
JOIN engine4_securonet_cameratypes AS camtype ON cam.cameratype_id = camtype.cameratype_id
WHERE loc.user_id = 113
ORDER BY cam.camera_id;

The result of the query is:
+-------------------+-------------+-----------+--------+
| Camera Owner Name | Location ID | Camera ID | Type   |
+-------------------+-------------+-----------+--------+
| Alexis Neve       |          50 |      4681 | Fixed  |
| Alexis Neve       |          53 |      4681 | Fixed  |
| Alexis Neve       |          50 |      4682 | Mobile |
| Alexis Neve       |          53 |      4682 | Mobile |
| Alexis Neve       |          50 |      4684 | Fixed  |
| Alexis Neve       |          53 |      4684 | Fixed  |
| Alexis Neve       |          50 |      4689 | Fixed  |
| Alexis Neve       |          53 |      4689 | Fixed  |
| Alexis Neve       |          50 |      4691 | Fixed  |
| Alexis Neve       |          53 |      4691 | Fixed  |
+-------------------+-------------+-----------+--------+
10 rows in set (0.00 sec)

How can I eliminate this duplication? Thanks so much in advance!

A:

You were joining all locations that an owner was associated to, not only the camera's location.
SELECT
  loc.contact1 as Owner,
  loc.location_id as "Location Id",
  cam.camera_id AS "Camera ID",
  camtype.title AS "Camera Type"
FROM cameras AS cam

LEFT JOIN locations AS loc
       ON loc.location_id = cam.location_id
      AND cam.user_id = loc.user_id

JOIN cameratypes AS camtype
  ON cam.cameratype_id = camtype.cameratype_id

WHERE loc.user_id = 113
ORDER BY cam.camera_id;


Q:

What is the proper way to play A-Flat scales on piano?

Consider four cases:

A-flat major
A-flat (natural) minor
A-flat melodic minor
A-flat harmonic minor

I start them with the third finger on the A-flat key (both hands), but I have no idea how a professional pianist would do it.  Help!

A:

There's nothing wrong with starting on the third finger.  I would think most people would be taught it that way, because then it's consistent with the fingering you would use as you go up an octave (i.e., if you start on A♭4 you should play A♭5 with the third finger).
Some pianists might start with the second finger on the right hand, however.  The inconsistency is initially difficult to manage mentally, but it allows you to start with your stronger index finger.

A:

For Ab Major: Start with the third finger on the right hand, third finger on the left.  Play the C with your thumb, then cross over for the Db.
Ab minor: This has the same key signature as B Major, so you can use the same fingering.

A:

I think what helps instead of memorizing where each individual finger should go, is to memorize the "imprint" of your hand on the keyboard. For Ab major for instance, this would be thumb, index and middle on C, Db and Eb resp. and then thumb, index, middle and ring on F, G, Ab, and Bb resp. That is for the right hand, for the left hand, middle, index and thumb on Ab, Bb and C resp. and ring, middle, index and thumb on Db, Eb, F and G resp. Then, you can start on whatever finger you like, you just have to see that you fall back to that pattern somehow.


Q:

'size' vs 'ls -l' to get the size of an executable file

For the same file, I think the output of ls -l xxx is always greater than or equal to the output of size xxx.
But when I type ls -l /bin/ls the output is:
 -rwxr-xr-x 1 root root 104508  1月 14  2015 /bin/ls

For size /bin/ls, the output is:

   text    data     bss     dec     hex filename
 101298     976    3104  105378   19ba2 /bin/ls

Why is ls showing less than size? 104508 < 105378

A:

ls -l is telling you the size of the file, while the size command tells you the size of the executable image stored in the file -- how much memory it will require when loaded.  Some segments (such as .bss) are zero-initialized rather than requiring data in the file to initialize them, so the the file may well be smaller than the executable image as a result.


Q:

Change text color if last image in banner is active

html:

details

I use bxslider and I want if last image is active a#selected will have a class .select is this possible
sample: http://jsfiddle.net/NXzcx/83/
js
$('.bxslider').bxSlider({
  auto: true,
  infiniteLoop: false,
  hideControlOnEnd: true,
});

$(document).ready(function(){
                if (slider.active.index == 0){
                $('#selected').addClass("select");
            }

            });

A:

Add onAfterSlide callback to the bxSlider.
$('.bxslider').bxSlider({
    auto: true,
    infiniteLoop: false,
    hideControlOnEnd: true,
    onAfterSlide: function (currentSlide) {
        if(currentSlide == $('.bxslider').children('li.pager').length -1) {
            $('#selected').addClass("select");
        } else {
            $('#selected').removeClass("select");
        }
    }
});

DEMO


Q:

Maven resolver at Jenkins job with Arquillian tests (Issue when creating WAR by ShrinkWrap)

I'm trying to do a little modular project that uses Arquillian tests remotely launched on WildFly 8.1.0 server. Everything is wirking, but only when i launch tests from my IDE. When Jenkins tries to do the same, it fails with error:
SEVERE [domain.testframework.logic.UserPersistTest] : org.jboss.shrinkwrap.resolver.api.Invokable$InvocationException: Unable to invoke onlyOne([Ljava.lang.Class;@5d79653) on object org.jboss.shrinkwrap.resolver.spi.loader.ServiceRegistry with parameters [Ljava.lang.Object;@cce2624
    at org.jboss.shrinkwrap.resolver.api.Invokable.invokeMethod(Invokable.java:108) [shrinkwrap-resolver-api-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.api.ResolverSystemFactory.createFromUserView(ResolverSystemFactory.java:91) [shrinkwrap-resolver-api-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.api.ResolverSystemFactory.createFromUserView(ResolverSystemFactory.java:53) [shrinkwrap-resolver-api-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.api.Resolvers.use(Resolvers.java:68) [shrinkwrap-resolver-api-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.api.maven.Maven.resolver(Maven.java:36) [shrinkwrap-resolver-api-maven-2.1.1.jar:2.1.1]
    at domain.testframework.logic.UserPersistTest.createDeployment(UserPersistTest.java:61) [:]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_13]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_13]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_13]
    at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_13]
    at org.jboss.arquillian.container.test.impl.client.deployment.AnnotationDeploymentScenarioGenerator.invoke(AnnotationDeploymentScenarioGenerator.java:177) [arquillian-container-test-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.container.test.impl.client.deployment.AnnotationDeploymentScenarioGenerator.generateDeployment(AnnotationDeploymentScenarioGenerator.java:103) [arquillian-container-test-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.container.test.impl.client.deployment.AnnotationDeploymentScenarioGenerator.generate(AnnotationDeploymentScenarioGenerator.java:64) [arquillian-container-test-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.container.test.impl.client.deployment.DeploymentGenerator.generateDeployment(DeploymentGenerator.java:79) [arquillian-container-test-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_13]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_13]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_13]
    at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_13]
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:145) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:116) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.core.impl.EventImpl.fire(EventImpl.java:67) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.container.test.impl.client.ContainerEventController.execute(ContainerEventController.java:100) [arquillian-container-test-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_13]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_13]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_13]
    at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_13]
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.test.impl.TestContextHandler.createClassContext(TestContextHandler.java:84) [arquillian-test-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_13]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_13]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_13]
    at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_13]
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.test.impl.TestContextHandler.createSuiteContext(TestContextHandler.java:65) [arquillian-test-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_13]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_13]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_13]
    at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_13]
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:145) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:116) [arquillian-core-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.test.impl.EventTestRunnerAdaptor.beforeClass(EventTestRunnerAdaptor.java:80) [arquillian-test-impl-base-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.junit.Arquillian$2.evaluate(Arquillian.java:190) [arquillian-junit-core-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:345) [arquillian-junit-core-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.junit.Arquillian.access$200(Arquillian.java:49) [arquillian-junit-core-1.1.5.Final.jar:1.1.5.Final]
    at org.jboss.arquillian.junit.Arquillian$3.evaluate(Arquillian.java:207) [arquillian-junit-core-1.1.5.Final.jar:1.1.5.Final]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309) [junit-4.11.jar:]
    at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:155) [arquillian-junit-core-1.1.5.Final.jar:1.1.5.Final]
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:264) [surefire-junit4-2.17.jar:2.17]
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153) [surefire-junit4-2.17.jar:2.17]
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:124) [surefire-junit4-2.17.jar:2.17]
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:200) [surefire-booter-2.17.jar:2.17]
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:153) [surefire-booter-2.17.jar:2.17]
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103) [surefire-booter-2.17.jar:2.17]
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_13]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_13]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_13]
    at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_13]
    at org.jboss.shrinkwrap.resolver.api.Invokable.invokeMethod(Invokable.java:100) [shrinkwrap-resolver-api-2.1.1.jar:2.1.1]
    ... 60 more
Caused by: java.lang.RuntimeException: Could not create new service instance
    at org.jboss.shrinkwrap.resolver.spi.loader.SpiServiceLoader.createInstance(SpiServiceLoader.java:248) [shrinkwrap-resolver-spi-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.spi.loader.SpiServiceLoader.createInstances(SpiServiceLoader.java:208) [shrinkwrap-resolver-spi-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.spi.loader.SpiServiceLoader.all(SpiServiceLoader.java:79) [shrinkwrap-resolver-spi-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.spi.loader.SpiServiceLoader.onlyOne(SpiServiceLoader.java:85) [shrinkwrap-resolver-spi-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.spi.loader.ServiceRegistry.onlyOne(ServiceRegistry.java:117) [shrinkwrap-resolver-spi-2.1.1.jar:2.1.1]
    ... 65 more
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) [rt.jar:1.7.0_13]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) [rt.jar:1.7.0_13]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) [rt.jar:1.7.0_13]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525) [rt.jar:1.7.0_13]
    at org.jboss.shrinkwrap.resolver.spi.loader.SpiServiceLoader.createInstance(SpiServiceLoader.java:244) [shrinkwrap-resolver-spi-2.1.1.jar:2.1.1]
    ... 69 more
Caused by: org.jboss.shrinkwrap.resolver.api.InvalidConfigurationFileException: Unable to get security configuration from /root/.m2/settings-security.xml. Please define path to the settings-security.xml file via -Dorg.apache.maven.security-settings, or put it the the default location defined by Maven.
    at org.jboss.shrinkwrap.resolver.impl.maven.internal.decrypt.MavenSecurityDispatcher.getMaster(MavenSecurityDispatcher.java:171) [shrinkwrap-resolver-impl-maven-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.impl.maven.internal.decrypt.MavenSecurityDispatcher.decrypt(MavenSecurityDispatcher.java:96) [shrinkwrap-resolver-impl-maven-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.impl.maven.internal.decrypt.MavenSettingsDecrypter.decrypt(MavenSettingsDecrypter.java:92) [shrinkwrap-resolver-impl-maven-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.impl.maven.internal.decrypt.MavenSettingsDecrypter.decrypt(MavenSettingsDecrypter.java:60) [shrinkwrap-resolver-impl-maven-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.impl.maven.bootstrap.MavenSettingsBuilder.decryptPasswords(MavenSettingsBuilder.java:223) [shrinkwrap-resolver-impl-maven-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.impl.maven.bootstrap.MavenSettingsBuilder.buildSettings(MavenSettingsBuilder.java:186) [shrinkwrap-resolver-impl-maven-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.impl.maven.bootstrap.MavenSettingsBuilder.buildDefaultSettings(MavenSettingsBuilder.java:113) [shrinkwrap-resolver-impl-maven-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.impl.maven.MavenWorkingSessionImpl.<init>(MavenWorkingSessionImpl.java:136) [shrinkwrap-resolver-impl-maven-2.1.1.jar:2.1.1]
    at org.jboss.shrinkwrap.resolver.impl.maven.MavenResolverSystemImpl.<init>(MavenResolverSystemImpl.java:44) [shrinkwrap-resolver-impl-maven-2.1.1.jar:2.1.1]
    ... 74 more

@Deployment method
@Deployment
    public static WebArchive createDeployment() {
        File pom = new File("pom.xml");
        LOG.info("---->>" + pom);

        File[] libs = null;
        try {
            libs = Maven.resolver().loadPomFromFile(pom)
                    .importRuntimeDependencies().resolve().withTransitivity().asFile();
        } catch (Throwable exception) {
            LOG.log(Level.SEVERE, "", exception);
        }
        LOG.info("LIBS RESOLVED: " + libs.length);
        for (File lib : libs) {
            System.out.println(lib);
        }
        WebArchive archive = ShrinkWrap.create(WebArchive.class, "ShrinkWrap-arquillian-test.war")
                .addAsWebInfResource("web.xml")
                .addClass(User.class)
                .addAsResource("test-persistence.xml", "META-INF/persistence.xml")
                .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
                .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");

        for (File lib : libs) {
            if (!lib.toString().contains("test-framework-data")) {
                archive.addAsLibrary(lib);
            }
        }
    }

any idea why this is happening?
my parent POM
<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>domain</groupId>
    <artifactId>test-framework-parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>
    <modules>
        <module>test-framework-web</module>
        <module>test-framework-logic</module>
        <module>test-framework-data</module>
        <module>test-framework-ear</module>
    </modules>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java-version>1.7</java-version>
        <!--Wersje pluginów-->
        <ejb-plugin-version>2.3</ejb-plugin-version>
        <war-plugin-version>2.4</war-plugin-version>
        <ear-plugin-version>2.9</ear-plugin-version>
        <compiler-plugin-version>3.1</compiler-plugin-version>
        <maven-dependency-plugin-version>2.8</maven-dependency-plugin-version>
        <!--Wersje zależności-->
        <javaee-api-version>7.0</javaee-api-version>
        <shrinkwrap.bom-version>2.1.1</shrinkwrap.bom-version>
        <postgreslq.version>9.1-901-1.jdbc4</postgreslq.version>
        <!--Wersja EJB-->
        <ejb-spec-version>3.2</ejb-spec-version>
        <!--Wersje środowiska testowego-->
        <surefire-plugin-version>2.17</surefire-plugin-version>
        <junit-version>4.11</junit-version>
        <arquillian-version>1.1.5.Final</arquillian-version>
        <wildfly-version>8.1.0.Final</wildfly-version>
        <arquillian-wildfly-version>8.1.0.Final</arquillian-wildfly-version>
        <arquillian-transaction-version>1.0.1.Final</arquillian-transaction-version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>javax</groupId>
                <artifactId>javaee-api</artifactId>
                <version>${javaee-api-version}</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit-version}</version>
            </dependency>
            <dependency>
                <groupId>org.jboss.shrinkwrap.resolver</groupId>
                <artifactId>shrinkwrap-resolver-bom</artifactId>
                <version>${shrinkwrap.bom-version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.jboss.shrinkwrap.resolver</groupId>
                <artifactId>shrinkwrap-resolver-depchain</artifactId>
                <version>${shrinkwrap.bom-version}</version>
                <type>pom</type>
            </dependency>
            <dependency>
                <groupId>org.jboss.arquillian.extension</groupId>
                <artifactId>arquillian-transaction-bom</artifactId>
                <version>${arquillian-transaction-version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.wildfly</groupId>
                <artifactId>wildfly-arquillian-container-remote</artifactId>
                <version>8.1.0.Final</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.jboss.arquillian</groupId>
                <artifactId>arquillian-bom</artifactId>
                <version>${arquillian-version}</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>

            <dependency>
                <groupId>postgresql</groupId>
                <artifactId>postgresql</artifactId>
                <version>${postgreslq.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-ear-plugin</artifactId>
                    <version>${ear-plugin-version}</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <version>${maven-dependency-plugin-version}</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>${surefire-plugin-version}</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>${compiler-plugin-version}</version>
                    <configuration>
                        <source>${java-version}</source>
                        <target>${java-version}</target>
                        <encoding>${project.build.sourceEncoding}</encoding>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-ejb-plugin</artifactId>
                    <version>${ejb-plugin-version}</version>
                    <configuration>
                        <ejbVersion>${ejb-spec-version}</ejbVersion>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>${war-plugin-version}</version>
                    <configuration>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                        <packagingExcludes>WEB-INF/lib/*.jar</packagingExcludes>
                        <archive>
                            <manifest>
                                <addClasspath>true</addClasspath>
                                <classpathPrefix>lib/</classpathPrefix>
                            </manifest>
                        </archive>
                        <webResources>
                            <resource>
                                <filtering>true</filtering>
                                <directory>src/main/webapp</directory>
                                <includes>
                                    <include>**/web.xml</include>
                                </includes>
                            </resource>
                        </webResources>
                    </configuration>
                </plugin>

            </plugins>
        </pluginManagement>
    </build>
    <name>test-framework</name>
</project>

A:

Solution to this problem was a bit trivial.
Problem was with the settings.xml for maven repository. I have local repository with credentials like <password>{123}abc</password>.
Maven.resolver() requires modification to <password>\{123\}abc</password> otherwise it will look for file 'settings-security.xml'. I've modified local copy of this file, however on server it was not changed.


Q:

HTML5 Geolocation Not Waiting for user Input

I am trying to create a web app that will prompt the user to allow the use of his location. I am using the following function.
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            function(position){
                return("@" + position.coords.latitude + "," + position.coords.longitude);
            }
        );
    } else {
        return("Unknown");
    }
}

My issue is that the function returns "undefined" before the user is even prompted to allow for location tracking. Does anyone know how I could modify this code to wait until after the user chooses? Also I can't seem to see what is throwing the undefined error.

A:

Promises is a simple answer for this kind of issue. navigator.geolocation.getCurrentPosition is an asynchronous call - that means that you call the method and pass it a callback function, whenever the location is retrieved then your callback function will be called with the result value (location). Depending on the asynchronous function you're calling, it could take 1ms for your callback function to be called or 1 hour, all you know is that whenever the value is available, it will "notify" you.
In the case of your getLocation function, you either return nothing at all or you return the string Unknown. Notice that returning a result from the callback function(position){ has nothing to do with returning on getLocation. A very simple solution (without using Promises) is to simply give a callback to your getLocation function, so it would look like something like this:
function getLocation(callback) {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            function(position){
                callback("@" + position.coords.latitude + "," + position.coords.longitude)
            }
        );
    } else {
      return "Unknown";
    }
}

getLocation(function(res) { /* do something with the result */ });

As I mentioned before, another way of fixing this is to use Promises. Either use native ES6 promises or go for a widely used library like Bluebird (my favourite). With promises, the code would look something like this: (I recommend you to have a read about it since Javascript is all about asynchronous methods, so you should have a good grasp on these kind of issues)
function getLocation(callback) {
    var promise = new Promise(function(resolve, reject) {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                function(position){
                    resolve("@" + position.coords.latitude + "," + position.coords.longitude)
                }
            );
        } else {
          reject("Unknown");
        }
    });

    return promise;
}

var locationPromise = getLocation();
locationPromise
      .then(function(loc) { console.log(loc); })
      .catch(function(err) { console.log("No location"); });


Q:

Running multiple T4 Templates with a single click

I have some 6 T4 templates spread through my solution in different projects, is it possible to run them all with a single click or do I necessarily need to go through them one by one?

A:

Does the "Transform All Templates" button in the toolbar of Solution Explorer do what you need?
Oleg
Visual Studio 2012+ is now in Build -> Transform All T4 Templates


Q:

null detection for double method

I'm employing a private lib. One of the objects has a method that delivers either a double or a null.
How could I perform:
if (object.method != null) {
    // do some numeric operations with the returned value
}

Additional details:
library = org.apache.commons.collections4.map
class = LRUmap
method = get

My code is:
public class ExampleNode extends GeneralNode {
    private LRUMap<Integer, Double> cache;

    public ExampleNode() {
        this.setCache(new LRUMap<Integer,Double>(100));
    }

    public void setCache(LRUMap<Integer, Double> lruMap) {
        this.cache = lruMap;
    }

    public double getDatumCacheDebug(int llave){
        return this.cache.get((Object)llave,false);
    }
}

And then I call:
//outside ExampleNode
    if ( actualNode.getDatumCacheDebug(k) != null ) {

Eclipse Neon3 says: "The operator != is undefined for the argument type(s) double,null."

A:

The signature of the library method is:
public V get(Object key,
    boolean updateToMRU)

in class LRUMap<K,V>
The returned value is a Double, and therefore could be null, but it is being unboxed to double before the null test:
public double getDatumCacheDebug(int llave){
    return this.cache.get((Object)llave,false);
}

I suggest changing the signature of this method to return Double instead of double, so that the information about whether the result was null is preserved and can be tested. Otherwise, it will throw NullPointerException if get returns null.


Q:

How to give horizontal gradient color to button in ios

How to give horizontal gradient color to button in ios?
I am trying to give button gradient color blue in horizontal direction, but not getting output properly.

A:

You can try the below code:
{
    UIColor *transBgColor = [UIColor colorWithWhite:1.0 alpha:0.0];
    UIColor *black = [UIColor blackColor];
    CAGradientLayer *maskLayer = [CAGradientLayer layer];
    maskLayer.opacity = 0.8;
    maskLayer.colors = [NSArray arrayWithObjects:(id)black.CGColor,
    (id)transBgColor.CGColor, (id)transBgColor.CGColor, (id)black.CGColor, nil];

    // Horizontal - commenting these two lines will make the gradient vertical
    maskLayer.startPoint = CGPointMake(0.0, 0.5);
    maskLayer.endPoint = CGPointMake(1.0, 0.5);

    NSNumber *gradTopStart = [NSNumber numberWithFloat:0.0];
    NSNumber *gradTopEnd = [NSNumber numberWithFloat:0.4];
    NSNumber *gradBottomStart = [NSNumber numberWithFloat:0.6];
    NSNumber *gradBottomEnd = [NSNumber numberWithFloat:1.0];
    maskLayer.locations = @[gradTopStart, gradTopEnd, gradBottomStart, gradBottomEnd];

    maskLayer.bounds = container.bounds;
    maskLayer.anchorPoint = CGPointZero;
    [container.layer addSublayer:maskLayer];
}


Q:

5V LDO blowing up only when testing current draw

I have a circuit to power some 5-volt logic from a +24VDC source. It has some basic reverse-polarity protection and uses a TI 5VDC LDO.

It all works great during normal operation however, when I use my FLUKE multimeter in amp mode to test the current draw like so:

The LDO blows up immediately. Smoke, sparks, a bright light, all of it.
Anyone know what's going on?
Thanks

A:

I think people are distracted by the PMOS, but the real reason is a voltage spike when the 24V is connected, due to inductance of the wiring that is even higher when the multimeter is connected, vastly exceeding the max voltage of the LDO.  I assume you are using a ceramic capacitor at the LDO input,  which is a reason someone may be experiencing this problem for the first time -- it wouldn't happen with an electrolytic cap, as I'll explain.
Forget the transistor for now and model the circuit like this, with a source that has some resistance and inductance in the wiring (R1, L1).  Also model the capacitor as having a very low ESR (R2):

simulate this circuit – Schematic created using CircuitLab
Simulate this and you'll see that the RLC circuit rings, peaking at about 42V when the 24V turns on:

Now try the same thing after changing R2 from 10 mΩ (which could be a typical ESR for a multilayer ceramic capacitor) to 1 Ω (which could be a typical ESR for an electrolytic capacitor) and the peak will be much lower, about 27V:

The added resistance in series with the cap significantly dampens the oscillation, keeping the input voltage well with range of the LDO.  Yay!  So the simple solution is to add an additional 1 Ω resistor between your 1 uF capacitor and GND to account for the low ESR of the cap.
You should be able to observe this behavior in the real circuit pretty easily with an oscilloscope.  Remove the LDO (to avoid blowing it up) and watch the voltage across the capacitor when you first attach the 24V.  You can tweak the value of the added resistor as necessary to ensure the peak never goes above the LDO's limit.
Alternately, the ringing will never exceed twice the input voltage regardless of any of the parasitic values, so you could switch to a LDO that has a >48V input limit and you'd always be safe.

A:

I agree with VillageTech in incriminating the PMOS. It has a capacitive load in the source and an inductive load in the drain (your mutlimeter wires), add a bit of parasitic inductive/capacitive coupling and you get a colpitts oscillator.
However, since your supply is 24V and you're using a LDO to make 5V at 80mA, I wonder why you need to use a PMOS to make a quasi-ideal low dropout diode...
If you implement your reverse polarity protection with a dumb old diode, dropping 0.6V, the LDO will still have 18.4V headroom instead of 19V!
So I'd say just get rid of the PMOS and replace with a diode.
If the PMOS provides reverse polarity protection for other stuff on the 24V rail that you didn't mention in your question, then of course don't remove the PMOS, but instead add a cap on the 24VDC input. Preferably an electrolytic with a bit of ESR, like a 10-100µF general purpose cap, to damp transients or resonances due to cable inductance and low-ESR caps in the power supply. A low-ESR ceramic cap may produce ringing due to this.

A:

I'm suspicious that you may have insufficient capacitance on the output of the LDO. Personally, I think it unlikely the MOSFET is involved in this, the body diode severely limits what mischief it can get up to.
If the LDO is hovering on the edge of instability, a small change to the input could push it over the edge. If you're using a very small (physically) capacitor, the capacitance under bias may be much less than even the nominal 1.5uF you've shown. And you're under the recommended minimum 2.2uF even with the nominal value.

But that may not be the main thing wrong. Consider the massive power dissipation for such a tiny device, as Andy points out. If I read the suffix code correctly you have an SOT-23-5 device, which has a datasheet (possibly optimistic, depending on the footprint) junction-to-ambient thermal resistance of 212°C/W meaning at room temperature the junction is heading for 350°C. FAR too high for a silicon chip. Now,  it's supposed to shut down gracefully under thermal overload (at a very high die temperature), but that's not a good thing to provoke and with such a high input voltage it may well be dying as a result.


Q:

CSS acting weird

i have the following css code:
.tag {
    display: inline;
    font-size: 10px;
    padding: 5px;
    color: #FFF;
    background-color: #444;
}

.tag:hover {
    font-size: 10px;
    padding: 5px;
    color: #FFF;
    background-color: #666;
}

aside from the background color, and one having the display:inline, there is no difference, correct? Well when the .tag div comes into existance, it has white text but no background color. it also has a 12pt font size and no padding. however, it looks perfectly the way its supposed to when I hover over it. Can anyone tell me why its doing this?

A:

there will be no different if you only have these 2 classes in your css file/scriptlet.
but it will be different if you have more than 2 and mixed with other classes as well.
your .tag might be overidden by other class
I'd debug it using firefox + firebug. This tool will show you which css class/properties is voeridden

A:

Use !important


Q:

Problems with Passenger + Nginx: Failed to connect to a master node. Rails config error?

We're not sure if this is something not configured properly in our Rails setting, but we're seeing this error in our nginx error logs get repeated: Exception PhusionPassenger::UnknownError in PhusionPassenger::Rack::ApplicationSpawner (Failed to connect to a master node at x.objectrocket.com:10804 ...
Here's a gist with more from the error log: https://gist.github.com/panabee/a291526f4dcf4cd434d9
How do we stop these errors?
We're on Rails 3.2.12.

A:

This error means the ObjectRocket mongo server is refusing or timing out your connections. Contact them with the specific logs to work out why they refuse the connection.
Also, try setting your timeouts lower to avoid hanging connections for your clients:
MongoMapper.connection = Mongo::Connection.new(host, 27017, :connect_timeout => 1, :op_timeout => 1)

This sets the connect and read timeouts. There's a :timeout option as well: it's related to connection pooling, not connecting to the server.
Neither :op_timeout nor :connect_timeout have a default value. Verify their settings by reading MongoMapper.connection.connect_timeout.
If you're using the 1.8.0 mongo gem version or later, you may want to replace the deprecated Mongo::Connection class with Mongo::MongoClient.