Set the same image for UICollectionViewCell and UIView

Question: am getting color from my image with this extension
 extension UIImage {
func getPixelColor(pos: CGPoint) -> UIColor {

    let pixelData = self.cgImage!.dataProvider!.data
    let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)

    let pixelInfo: Int = ((Int(self.size.width) * Int(pos.y)) + Int(pos.x)) * 4

    let r = CGFloat(data[pixelInfo]) / CGFloat(255.0)
    let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0)
    let b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0)
    let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0)

    return UIColor(red: r, green: g, blue: b, alpha: a)
}
}

and am setting this in cellForItemAt indexPath:
  let img = cell.movieImage.image?.getPixelColor(pos: CGPoint(x: 10, y: 10))
  cell.backgroundColor = img
  view.backgroundColor = img

but the backgroundColorof the cell does not match the view's backgroundColor
EDIT: Added demo image
https://s30.postimg.org/gshw3u829/demo.gif
Comment: There is different types of colors like RGB, CYMK, etc, So, it happen that your color type is different among so it didnt match color. Check the color type of return from image and your cells background image. If its not the problem then match the RGB values of both image
Comment: The color is getting applied the color type is ok but the color on `view.backgroundColor` is different from  the cell color `cell.backgroundColor = img`
Comment: did you have your demo ? If you could send me to my mail or give me link of dropbox from where i can download and check
Comment: I edited the question there's a demo now
Comment: Can you send me demo at email@example.com, So I can see your issue ?
Comment: I told you to send demo of coding not the gif image. send me xcode project please
Answer: Instead of setting background Color of tableCell, try setting color of contentView
cell.contentView.backgroundColor = img

Comment: I think that wouldn't creating issue like you can directly set background color of cell
Comment: color of contentView overrides backgroundColor of cell, and all the views are. added on contentView
Comment: There's a demo..the cell background color doesn't match the view background when scrolling


mount --bind /dev sometimes "kills" tty until unmounted

Question: I have a script that uses sudo mount --bind /dev other/dev and then later uses sudo umount other/dev to unmount. After some random number of runs, we can somehow enter an odd state where the main tty stops existing, and the whole desktop environment starts malfunctioning (new applications won't start, or they crash, and firefox can't redraw pages and they freeze, etc...) and tty in my terminal says not a tty, and the terminal fails to open new instances. I'm not using ssh or any other remote functions, so the loss of the tty for my local terminal is absurd.
The only way to fix it is to reboot or to enter a different tty with CTRL+ALT+F1 or similar, log in, and force other/dev to unmount (normal asking says it is busy). After this the tty is magically revived and everything works again. I'm only actually mounting dev to get another /dev/null, so an easier workaround probably exists for me, but this is still very strange!
Is there some explanation for this odd behavior?
I'm on 18.04.2 LTS.
Comment: You can make a character device like `/dev/null` using `mknod` as decribed here: [How to create /dev/null?](https://unix.stackexchange.com/questions/27279/how-to-create-dev-null). This appears to be an [XY problem](https://meta.stackexchange.com/a/66378).
Comment: @steeldriver, That is what I've done. I mainly wanted to post this because it was so bizarre that I wanted it out on the internet somewhere in case anyone experiences something similar. It is possibly harder to side step in other scenarios.
Answer: If the propagation type of /dev is shared, then mount and unmount operations will be copied from /dev/ to other/dev and vice-versa, unmounting other/dev will therefore unmount from /dev everything that was mounted after the bind mount.
To solve this set the propagation type of other/dev before unmounting it:
mount --make-rprivate other/dev


cant remove, reinstall or anything of that sort for linux-firmware /lib/firmware/intel/sof-tplg

Question: some tries and errors, the thing is this is also a vps, i would just like to switch to linux-image-virtual or what ever its called anyway, but i would also just like to be able to upgrade my software atm
<code>sudo apt upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following packages will be REMOVED:
  linux-firmware
The following NEW packages will be installed:
  distro-info libevdev2 libimobiledevice6 libplist3 libupower-glib3 libusbmuxd6
  linux-headers-5.4.0-73 linux-headers-5.4.0-73-generic upower usbmuxd
The following packages will be upgraded:
  alsa-ucm-conf apport erlang-asn1 erlang-base erlang-crypto erlang-dev erlang-diameter
  erlang-edoc erlang-eldap erlang-erl-docgen erlang-eunit erlang-ic erlang-inets erlang-inviso
  erlang-mnesia erlang-nox erlang-odbc erlang-os-mon erlang-parsetools erlang-percept
  erlang-public-key erlang-runtime-tools erlang-snmp erlang-ssh erlang-ssl erlang-syntax-tools
  erlang-tools erlang-xmerl intel-microcode libasound2 libasound2-data libmysqlclient21
  libnetplan0 libpq5 libunbound8 libxmlb1 linux-headers-generic linux-libc-dev netplan.io
  open-iscsi postgresql-13 postgresql-client-13 postgresql-client-common postgresql-common
  python3-apport python3-problem-report python3-update-manager python3-yaml thermald tmux
  ubuntu-advantage-tools update-manager-core
52 upgraded, 10 newly installed, 1 to remove and 0 not upgraded.
43 not fully installed or removed.
Need to get 0 B/61.4 MB of archives.
After this operation, 467 MB disk space will be freed.
Do you want to continue? [Y/n]
Extracting templates from packages: 100%
Preconfiguring packages ...
(Reading database ... 137369 files and directories currently installed.)
Removing linux-firmware (1.187.10) ...
dpkg: error processing package linux-firmware (--remove):
 unable to securely remove '/lib/firmware/intel/sof-tplg/sof-tgl-rt711-rt1308.tplg.dpkg-new': Bad message
dpkg: too many errors, stopping
Errors were encountered while processing:
 linux-firmware
Processing was halted because there were too many errors.
E: Sub-process /usr/bin/dpkg returned an error code (1)

sudo apt -f install
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages will be REMOVED:
  linux-firmware
0 upgraded, 0 newly installed, 1 to remove and 52 not upgraded.
43 not fully installed or removed.
After this operation, 559 MB disk space will be freed.
Do you want to continue? [Y/n]
(Reading database ... 137369 files and directories currently installed.)
Removing linux-firmware (1.187.10) ...
dpkg: error processing package linux-firmware (--remove):
 unable to securely remove '/lib/firmware/intel/sof-tplg/sof-tgl-rt711-rt1308.tplg.dpkg-new': Bad message
dpkg: too many errors, stopping
Errors were encountered while processing:
 linux-firmware
Processing was halted because there were too many errors.
E: Sub-process /usr/bin/dpkg returned an error code (1)

sudo apt --fix-missing reinstall
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages will be REMOVED:
  linux-firmware
0 upgraded, 0 newly installed, 1 to remove and 52 not upgraded.
43 not fully installed or removed.
After this operation, 559 MB disk space will be freed.
Do you want to continue? [Y/n]
(Reading database ... 137369 files and directories currently installed.)
Removing linux-firmware (1.187.10) ...
dpkg: error processing package linux-firmware (--remove):
 unable to securely remove '/lib/firmware/intel/sof-tplg/sof-tgl-rt711-rt1308.tplg.dpkg-new': Bad message
dpkg: too many errors, stopping
Errors were encountered while processing:
 linux-firmware
Processing was halted because there were too many errors.
E: Sub-process /usr/bin/dpkg returned an error code (1)

sudo dpkg -i --force-overwrite /var/cache/apt/archives/linux-firmware_1.187.12_all.deb
Selecting previously unselected package linux-firmware.
(Reading database ... 137370 files and directories currently installed.)
Preparing to unpack .../linux-firmware_1.187.12_all.deb ...
Unpacking linux-firmware (1.187.12) over (1.187.10) ...
dpkg: error processing archive /var/cache/apt/archives/linux-firmware_1.187.12_all.deb (--install):
 unable to stat './lib/firmware/intel/sof-tplg/sof-apl-asrc-wm8804.tplg' (which I was about to install): Bad message
dpkg-deb: error: paste subprocess was killed by signal (Broken pipe)
Errors were encountered while processing:
 /var/cache/apt/archives/linux-firmware_1.187.12_all.deb
</code>
Comment: so nobody can help me on this ehh
Answer: The issue was the filesystem was corrupted
Fixed it by booting from ubuntu install cd and doing fsck, surprised their busy box doesnt contain fsck and cryptsetup


What is the best way to check and retrieve the first item of a collection?

Question: I understand this is somewhat trivial but...
What the best way to get the reference the first item of a collection if any exist? Assume the collection contains items of a reference-type.
Code Sample 1:
if (collection.Any())
{
    var firstItem = collection.First();
    // add logic here
}

The above sample has two separate calls on the collection starting an iteration which complete as soon as the first is detected.
Code Sample 2:
var firstItem = collection.FirstOrDefault();
if (firstItem != null)
{
    // add logic here
}

The above sample only has a single call on the collection but introduces a variable that is unnecessarily in a wider scope.
Is there a best-practices related to this scenario? Is there a better solution?
Comment: Have you taken into account that `null` might be the first element in a collection?
Comment: If you really need the most fast code, you can take examples from answers, compile and open assemblies with ILDasm. You will see what is the most expensive.
Comment: I don't consider it that trivial - #1 has a race-condition and #2 doesn't work on every possible `` (as you noted), so anything that helps people avoid these pitfalls is worthwhile.
Answer: I prefer the second example because it's more effecient in the general case.  It's possible that this collection is combination of many different delay evaluated LINQ queries such that even getting the first element requires a non-trivial amount of work.
Imagine for example that this collection is build from the following LINQ query
var collection = originalList.OrderBy(someComparingFunc);

Getting just the first element out of collection requires a full sort of the contents of originalList.  This full sort will occur each time the elements of collection are evaluated.
The first sample causes the potentially expensive collection to be evaluated twice: via the Any and First method.  The second sample only evaluates the collection once and hence I would choose it over the first.
Answer: You could create an extension method like this:
public static bool TryGetFirst<T>(this IEnumerable<T> seq, out T value)
{
    foreach (T elem in seq)
    {
        value = elem;
        return true;
    }
    value = default(T);
    return false;
}

Then you would use it like this:
int firstItem;
if (collection.TryGetFirst(out firstItem))
{
    // do something here
}

Comment: That's exactly what `FirstOrDefault` does (edit: except this handles value types as well. Good suggestion - I wonder why they didn't build this in?)
Comment: @Zooba,  it also handles IEnumerables that contain null (or default) values
Answer: The second doesn't work on non-nullable value types (Edit: as you assumed - missed that the first time) and doesn't really have an alternative besides the first, which has a race-condition. There are two alternatives which are both suitable - selecting one or the other depends on how frequently you will get an empty sequence.
If it's a common or expected case where you get an empty enumeration, using a foreach loop is relatively neat:
foreach (var firstItem in collection)
{
    // add logic here
    break;
}

or if you really don't want the break in there (which is understandable):
foreach (var firstItem in collection.Take(1))
{
    // add logic here
}

If it is relatively unusual for it to be empty then a try/catch block should give the best performance (since exceptions are only expensive if they are actually raised - an unraised exception is practically free):
try
{
    var firstItem = collection.First();
    // add logic here
}
catch (InvalidOperationException) { }

A third option is to use an enumerator directly, though this should be identical to the foreach version and is slightly less clear:
using (var e = collection.GetEnumerator())
{
    if (e.MoveNext())
    {
        var firstItem = e.Current;
        // add logic here
    }
}

Comment: version 2 assumes that the collection has implemented the extension method First()
Comment: @tkeE2036 Version 2 assumes the collection implements `IEnumerable` and that `System.Linq` has been imported. Based on the question, these are good assumptions.
Comment: "Version 2" in the earlier comments is now the third (`try/catch`), because I added another `foreach` approach.
Answer: Sometimes I use this pattern:
foreach (var firstItem in collection) {
    // add logic here
    break;
}

It initiates only one iteration (so it's better than Code Sample 1) and the scope of the variable firstItem is limited inside the brackets (so it's better than Code Sample 2).
Comment: I think this is the worst approach because it sacrifices clear intent (IMO the most important quality of code) for the less relevant improvement in variable scope (which with "short enough" methods may not matter at all) and the even less important expected speed increase (totally irrelevant unless it's in the inner loop of a CPU-bound thread).
Comment: IMO, this is plain wrong!  If you see a loop when reading code it implies we expect to more often than not have more than one item in a collection. If the question is taken as  read it implies test and retrieve JUST the first item from a collection.
Comment: I am personally not a fan of this because it reduces readability of the code in the sense that someone reading this will see a foreach and assume that you are iterating over multiple elements. If your logic gets complex, a new person reading your code may miss the one line break; statement.
Comment: @Mitch Wheat. Sometimes it actually increases readability. I use this pattern when reading deep nested optional XML elements and I found that it reduces the amount of code significantly.
Comment: +1 for producing an identical code example to me :) (and doing it first, but I didn't see until I'd finished my own answer)
Comment: @linepogl: "Sometimes it actually increases readability." - No it doesn't. I see loop, I think multiple iterations.
Answer: Or, as an extension to the solution from Gabe, make it use a lambda so you can drop the if:
public static class EnumerableExtensions
{
    public static bool TryGetFirst<T>(this IEnumerable<T> seq, Action<T> action)
    {
        foreach (T elem in seq)
        {
            if (action != null)
            {
                action(elem);
            }

            return true;
        }

        return false;
    }
}

And use it like:
     List<int> ints = new List<int> { 1, 2, 3, 4, 5 };

     ints.TryGetFirst<int>(x => Console.WriteLine(x));

Comment: I thought about this solution, but it's a bit slower, so I didn't use it.
Comment: Absolutely true, but the question is how often is the code used? It is important to differentiate between theoretical performance hits and real life performance hits. Also, instead of the lambda can you directly use an existing method too. It is good to see so many examples on this question though, options I hadn't think of yet!
Answer: Since all generic Collections (ie: of type System.Collections.ObjectModel) have the Count member my preferred way of doing this is as follows:
Item item = null;
if(collection.Count > 0)
{
    item = collection[0];
}

This is safe is since all Collections will have both the Count and Item property. Its also very straight forward and easy for any other programmers reading your code to understand what your intent is.
Comment: My understanding is that the 'Count' property potentially iterates the entire collection to retrieve the value. I'm not sure if this is true, but if so, then I imagine this is a fairly inefficient way to check if any exist. The linq method .Any() will return true if the first record exists without iterating the entire collection.
Comment: As I commented on a similar answer that appears to have been deleted, this assumes that `collection` is actually a collection and not just an `IEnumerable`. All generic collections implement `IEnumerable`, so any solution that works and is clear for that will also work for any collection. The increased generality also lets you replace an `IList` with an `IEnumerable` without changing any code.
Answer: Just did simple test on primitive type, and looks like your code sample #2 is fastest in this case (updated):
[TestFixture] public class SandboxTesting {
  #region Setup/Teardown
  [SetUp] public void SetUp() {
    _iterations = 10000000;
  }
  [TearDown] public void TearDown() {}
  #endregion
  private int _iterations;
  private void SetCollectionSize(int size) {
    _collection = new Collection<int?>();
    for(int i = 0; i < size; i++)
      _collection.Add(i);
  }
  private Collection<int?> _collection;
  private void AnyFirst() {
    if(_collection.Any()) {
      int? firstItem = _collection.First();
      var x = firstItem;
    }
  }
  private void NullCheck() {
    int? firstItem = _collection.FirstOrDefault();
    if (firstItem != null) {
      var x = firstItem;
    }
  }
  private void ForLoop() {
    foreach(int firstItem in _collection) {
      var x = firstItem;
      break;
    }
  }
  private void TryGetFirst() {
    int? firstItem;
    if (_collection.TryGetFirst(out firstItem)) {
      var x = firstItem;
    }
  }
  private TimeSpan AverageTimeMethodExecutes(Action func) {
    // clean up
    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();

    // warm up
    func();

    var watch = Stopwatch.StartNew();
    for (int i = 0; i < _iterations; i++) {
      func();
    }
    watch.Stop();
    return new TimeSpan(watch.ElapsedTicks/_iterations);
  }
  [Test] public void TimeAnyFirstWithEmptySet() {
    SetCollectionSize(0);

    TimeSpan averageTime = AverageTimeMethodExecutes(AnyFirst);

    Console.WriteLine("Took an avg of {0} secs on empty set", avgTime);
  }
  [Test] public void TimeAnyFirstWithLotsOfData() {
    SetCollectionSize(1000000);

    TimeSpan avgTime = AverageTimeMethodExecutes(AnyFirst);

    Console.WriteLine("Took an avg of {0} secs on non-empty set", avgTime);
  }
  [Test] public void TimeForLoopWithEmptySet() {
    SetCollectionSize(0);

    TimeSpan avgTime = AverageTimeMethodExecutes(ForLoop);

    Console.WriteLine("Took an avg of {0} secs on empty set", avgTime);
  }
  [Test] public void TimeForLoopWithLotsOfData() {
    SetCollectionSize(1000000);

    TimeSpan avgTime = AverageTimeMethodExecutes(ForLoop);

    Console.WriteLine("Took an avg of {0} secs on non-empty set", avgTime);
  }
  [Test] public void TimeNullCheckWithEmptySet() {
    SetCollectionSize(0);

    TimeSpan avgTime = AverageTimeMethodExecutes(NullCheck);

    Console.WriteLine("Took an avg of {0} secs on empty set", avgTime);
  }
  [Test] public void TimeNullCheckWithLotsOfData() {
    SetCollectionSize(1000000);

    TimeSpan avgTime = AverageTimeMethodExecutes(NullCheck);

    Console.WriteLine("Took an avg of {0} secs on non-empty set", avgTime);
  }
  [Test] public void TimeTryGetFirstWithEmptySet() {
    SetCollectionSize(0);

    TimeSpan avgTime = AverageTimeMethodExecutes(TryGetFirst);

    Console.WriteLine("Took an avg of {0} secs on empty set", avgTime);
  }
  [Test] public void TimeTryGetFirstWithLotsOfData() {
    SetCollectionSize(1000000);

    TimeSpan averageTime = AverageTimeMethodExecutes(TryGetFirst);

    Console.WriteLine("Took an avg of {0} secs on non-empty set", avgTime);
  }
}
public static class Extensions {
  public static bool TryGetFirst<T>(this IEnumerable<T> seq, out T value) {
    foreach(T elem in seq) {
      value = elem;
      return true;
    }
    value = default(T);
    return false;
  }
}

AnyFirst
 NonEmpty: 00:00:00.0000262 seconds
 EmptySet: 00:00:00.0000174 seconds
ForLoop
NonEmpty: 00:00:00.0000158 seconds
EmptySet: 00:00:00.0000151 seconds
NullCheck
NonEmpty: 00:00:00.0000088 seconds
EmptySet: 00:00:00.0000064 seconds
TryGetFirst
NonEmpty: 00:00:00.0000177 seconds
EmptySet: 00:00:00.0000172 seconds
Comment: @Zooba, yes, I agree, this was just initial testing I did before left work. I want to average over a lot of runs, different test cases (empty set), and test with JaredPar's order example. I will try and update soon.
Comment: You'll need to run each of `AnyFirst()`, `NullCheck()` and `ForLoop()` a lot more than once to get reasonable results. You'll also want to compare the performance against an empty sequence, as well as a non-empty sequence.


I found a mistake in old pushed commit. How can I change it and apply to later commits?

Question: I have the following history:
0---1---2---HEAD

And I found that commit 0 have an error. Now I want to fix it and apply this fix to commits 1, 2 and HEAD.
What is the best way to do it?
Comment: You can rebase, but why don't you fix the code and make a new commit?
Comment: The [`--fixup` and `--autosquash`](http://fle.github.io/git-tip-keep-your-branch-clean-with-fixup-and-autosquash.html) features may come in handy here. Be aware of the [consequences of history rewriting](https://git-scm.com/book/ch3-6.html#_rebase_peril), though.
Comment: Have the changes been pushed to a remote repository yet? If so, just commit.
Comment: @MarounMaroun, @coredump I'm writing some programming tutorial and the idea was to add features to the program. I.e. commit `0` have a base functionality, commit `2` adds a new feature. And I wanted the user to be able to checkout needed commit, that's it. But I found a bug in the very first (base) commit that was pushed already.
Answer: Create a new branch from 0, apply your fixes, and rebase the old branch onto the new one. You can then use rebase -i to squash the fix into 0.
More recent git versions support --fixup commits, so you can just create one with the fixes, then do rebase -i --autosquash and resolve the conflicts.
Note that you shouldn't change history if the branch has already been pushed, and definitely not without agreement of other developers using the same branch.
Comment: Thank you. Can I ask you to explain in detail why do we need to rebase twice? Maybe with a diagram before-after?
Comment: This would have been a better solution
http://fle.github.io/git-tip-keep-your-branch-clean-with-fixup-and-autosquash.html


Generating regex-based string with RandExp

Question: I need to generate a string based on regex which would result random letters and numbers, 4 dashes at random places in 36-character string.
Example:
123A5678-01B3C5F7-901R345-789F1-3456
I've figured out a regex that seems to validate given string well:
(?=.{36}$)([0-9A-Z]+-){4}([0-9A-Z])+
...but using the same for generating string in RandExp ends  up in a mess. It generates 36-character string and adds 5 random-length groups:
new RandExp(/(?=.{36}$)([0-9A-Z]+-){4}([0-9A-Z])+/).gen()
M78QMOC6OGIF5OAJAJCG68CQWJGT5FX43CTKZ9CS9GXWLEKUKZMG602U5HPR4CEKO7OIX45CMLB7DS5RHZBI8KE8HGO9ET6OWS9A-PQSHN9E36KIMW328A1L0BHXCFOJVCD2ZT11-KD03XTZ375WP7CR7YSF4CTSX-0FBJ3MZ4RNDLA5UZOHI5QWVY66PTUDDRCG-OH4F688VM1
Should I just settle for fixed-width groups for my string using something like:
([0-9A-Z]{6}-){4}[0-9A-Z]{8}
... or is there any way I could improve the original regex?
Comment: What does 'generate a string based on regex' mean? Regexen don't generate strings. Take a look at [ask]. Include your code, preferably in a [MCVE].
Comment: @pvg Indeed, regex doesn't create. But he's using [randexp](https://github.com/fent/randexp.js).
Comment: [Randexp](https://github.com/fent/randexp.js) is a JS library that can generate strings matching a certain regexp.
Answer: It seems impossible to use a whole string length restricting lookahead with Randexp. I also tried with your pattern, and it generates a string with n chars of any type, like $>Qa MG4XT@#j{3#&[+V4=^"VQLI*|b%bp~@ (1).
It is even more strange when you apply anchors, new RandExp(/^(?=.{36}$)(?:[0-9A-Z]+-){4}[0-9A-Z]+$/) will also produce some ~30 chars of various types at the start of the string. It might be related to the fact that $ is not used at the final pattern position, and is ignored (see Bad Regular Expressions). It looks like a bug to me.
Removing the lookahead and adding ^ start-of-string anchor at the start and $ end-of-string anchor at the end makes it generate somewhat better strings (2). However, you might really want to only use fixed length groups (3).

document.body.innerHTML = "(1) " + new RandExp(/(?=.{36}$)([0-9A-Z]+-){4}([0-9A-Z])+/).gen();
document.body.innerHTML += "

(2) " + new RandExp(/^(?:[0-9A-Z]+-){4}[0-9A-Z]+$/).gen();
document.body.innerHTML += "

(3) " + new RandExp(/^(?:[0-9A-Z]{6}-){4}[0-9A-Z]{8}$/).gen();

You may then try to work around that problem by using /^(?:[0-9A-Z]{6,8}-){4}[0-9A-Z]{6,8}$/ regex in a loop and only return a result if the string is 36 chars long:

var rdx = new RandExp(/^(?:[0-9A-Z]{6,8}-){4}[0-9A-Z]{6,8}$/);
var res = rdx.gen();
while (res.length !== 36) {
    res = rdx.gen();
}
document.body.innerHTML = res;

Comment: Thanks for the really constructive answer, it confirmed my doubts that look-aheads just won't well for generation. I've decided to keep the complex regex for validation but use the simpler fixed-width regex when generating a string.
Comment: Having [written a very similar library to this myself](https://github.com/tom-lord/regexp-examples), I can say: Look-aheads are not supported by the library because they're "not *really* **regular** expressions". Supporting them would require using a totally different algorithm, and it may not even be 100% possible. In order to achieve what OP originally wanted, I'd recommend e.g. combining `RandExp` with some additional logic -- e.g. generate a 36-char string and only *then* substitute 4 random characters with `-`.
Comment: @TomLord: Yes, there must be some additional logic. I suggested a quick workaround at the bottom of the answer. It's a pity it is not mentioned in the library readme that it is not fully JS regex compatible.
Comment: Also, for anyone wondering, approximately `18.54%` of the time, the above code **will** randomly generate a string of length 36.


How to combine output of Conv1D with output of Conv2D in keras

Question: I want to add a scalar value to the output of a Conv2D operation in the following way:
num_filters = 16
num_targets = 10
input_conv = layers.Conv2D(num_filters, (3, 3), activation='relu', padding='same')(input_img)
target_conv = layers.Conv1D(num_filters, num_targets, use_bias=False, activation='linear')(label)
# TODO: add output target_conv to input_conv along each of the filter dimensions
# this is like adding a scalar value for each of the filter dimensions

The input_conv output is of shape (None, 28, 28, 16) and the target_conv is of shape (None, 1, 16), where 28 x 28 corresponds to the image dimensions and 16 is the number of filters. For each filter (each of the 16 dimensions), I want to add the corresponding target_conv value as a scalar. So imagine we are just looking at the output of the first filter for input_conv and target_conv, that gives us shapes (None, 28, 28, 1) and (None, 1, 1). I want to add the output of target_conv to the output of input_conv which would still output (None, 28, 28, 1) for the first filter, and this would then happen for each filter dimension to output (None, 28, 28, 16).
However, I am not sure how to implement this?
Answer: All you need to do is simply add one dimensionality to the target_conv output in order to have it in 4D. This enables you to make a simple sum between the two outputs
num_filters = 16

input_img = Input((28,28,1))
label = Input((10,1))
input_conv = Conv2D(num_filters, (3, 3),
                    activation='relu', padding='same')(input_img) # (None,28,28,num_filters)
target_conv = Conv1D(num_filters, 10,
                     use_bias=False, activation='linear')(label) # (None,1,num_filters)

target_conv = Reshape((1,1,num_filters))(target_conv) # (None,1,1,num_filters)
sum_filter = Add()([input_conv,target_conv]) # (None,28,28,num_filters)

m = Model([input_img,label], sum_filter)
m.summary()

Comment: Thanks @Marco Cerliani! Appreciate your help. Turns out I didn't actually need the reshape to make things work in this example. I just forgot to feed both the input image and label as inputs to the model which of course caused issues. However, I think reshaping is probably good practice so I included that in my code.


SEO viewport meta tag

Question: I'm interested what is the purpose of this meta tag?
<code><meta name="viewport" content="width=device-width, initial-scale=1">
</code>
Comment: Its for responsive webdesign read here https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag
Answer: It is not for SEO, it just an instruction how to render the page on mobile devices. You can read more about it here:
https://developer.mozilla.org/en/docs/Mozilla/Mobile/Viewport_meta_tag

SEO viewport meta tag


Do you know any PHP script or library to export/import dumps of MySQL databases?

Question: I don't have shell access so can't use the mysqldump command
Also the use of sentences like SELECT * INTO OUTFILE are restricted
SOLVED: I've found several PHP scripts/libraries/classes in google code.
Comment: I would almost guarantee that a PHP lib is going be a wrapper for `mysqldump`
Comment: What exactly is your question here? Do you want to write such a library and you need some help with it? Or do you want an already existing one for your project? What are all the tasks this library has to be able to do? Should it export all at once or only one DB at a time, etc.?
Answer: Than a SELECT * FROM and afterwards a file_put_contents()
Otherwise explain why not doing one of the following!
What do you want the output to look like? If it should look like a regular dump file, that good luck in writing your own PHP to mysql dump file converter.
Comment: Only reason I can guess is lack of shell access


Background of h1 should overlap image

Question: currently I'm having some issues with Css on a small website.
I want to display a image, and have a text (h1), which overlaps half of the image. But I also want the text to be in a white box. corrently I"ve solved this which the background-tag, but the image is overlapping the h1-background.
|~~~~~~~~~~~~~~~~~~
| image            |
|            ______|____________________________
|           | This is the Text, with background |
|            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|                  |
|~~~~~~~~~~~~~~~~~~

I hope, you understand, what I want to do... I'm thankful for every advice!
Comment: Could you provide a jsFiddle or similar to reproduce your problem? Thanks
Comment: Please include your HTML and CSS code.
Comment: http://learnlayout.com
Answer: You could change the box element with the h1 to a position absolute, choose a position you're happy with and have a div container around all elements that is a position relative to keep everything intact for responsiveness.

Example Text

Just change the stylings to your perfences.
Answer: You can put position: absolute; top: 100px; and left: 100px; in css on your h1 tag.
Answer: I made a simple example of how it could work
Html

This is the H1 text

CSS
img{
   float:left;
}
h1{
  float:left;
  margin-left:-20px;
  background:white;
}

Fiddle Link: https://jsfiddle.net/1b4kx9vd/
Comment: this was the thing I needed. Now I'm just adjusting it for mobile sites! Thanks a lot!

Background of h1 should overlap image


Can I upgrade a wubi 10.04 install using a 11.04 install image

Question: I want to eventually update 10.04 to 11.04 on several computers using a USB.  I would like to try it first on a non-essential computer, but the most likely candidate is a test box I run a wubi install on.
Should this work?
Do I boot from the USB like I normally would, or is there another procedure?
Should this emulate the results I would expect when upgrading a normal install?
Comment: When updating you either have to go from LTS to LTS or do every release upgrade in between. So in other words, you'll first have to upgrade your installs to 10.10, then upgrade to 11.04.
Comment: Ward, this is an honest personal question, why did you comment and not answer? If this is the case, it (the answer) should have the chance to pull in a few up votes and maybe get accepted?  This happens fairly often and I never really understand why.
Comment: I didn't feel like it completely answered your question, the main focus of your question was about Wubi where I don't really have a clue about.
Comment: Thanks I appreciate that, I just always feel that information this useful, though it may not get accepted, should be more prominent and gain the votes it deserves, since starting at 8.10, I had never noticed that before.
Answer: You can only upgrade a Wubi install while booted into that install, so either using update manager, or from the alternate desktop CD image (cdromupgrade).
You cannot do it from Windows or by booting an Ubuntu CD/USB.
You can only upgrade to 11.04 from 10.10 - so you'd first need to upgrade from 10.04 to 10.10, but note that there are some problems with the wubi upgrade to 10.10 (bug 653134 and bug 610898). These have been fixed for 11.04, but until the fix is backported to 10.10 you will likely suffer booting problems. You can find a solution for these problems here: Wubi megathread
With any upgrade I recommend backing up beforehand. With Wubi you can just copy the virtual disks (usually just the root.disk) in Windows beforehand. It's a good idea to copy C:\wubildr as well.
Comment: Great links, I often use Wubi on a short term basis (weeks or months) on work computers and these will definitely come in handy.


Exercise 16 from chapter 3 of Stein & Shakarchi's complex analysis

Question: Suppose $f$ and $g$ are holomorphic in a region containing the disc $|z| \le 1$.
Suppose that $f$ has a simple zero at $z=0$ and vanishes nowhere else in $|z| \le 1$.
Let $f_\epsilon (z) = f(z)+\epsilon g(z)$.
Show that if $\epsilon$ is sufficiently small, then
(a) $f_\epsilon (z)$ has a unique zero in $|z| \le 1$, and
(b) if $z_\epsilon$ is this zero, the mapping $\epsilon \mapsto z_\epsilon$ is continuous.
I already solved (a) by applying Rouche's theorem, but (b) is such a nuisance to me.
I first tried the classical $\epsilon - \delta$ method, but it didn't work.
However, I couldn't find any other ways to prove the continuity.
Since $f$ has a simple zero at $z=0$, I found that $f(z)=zh(z)$ for some $h(z)$ that is holomorphic and non-zero in the unit disc and $z_\epsilon h(z_\epsilon) = -\epsilon g(z_\epsilon)$.
Am I on the right track? I don't know how to proceed from this.
Answer: $f$ has no zeros on the boundary of the unit circle $\Bbb D$, therefore
$$
  \varepsilon_0 = \frac{ \min \{ |f(z)| : |z| = 1 \}}{1 + \max \{ |g(z)| : |z| = 1 \} } \, .
$$
is strictly positive.
Then for $0 \le \varepsilon \le \varepsilon_0$ and $|z| = 1$,
$$
 | (f(z) + \varepsilon g(z)) - f(z) | = \varepsilon |g(z)| < |f(z)|
$$
and it follows from Rouché's theorem that $f(z) + \varepsilon g(z)$ and
$f(z)$ have the same number of zeros in $\Bbb D$. Since $f$ has exactly
one (simple) zero, it follows that $f(z) + \varepsilon g(z)$ also
has exactly one zero $z_\varepsilon$ in the unit disk.
The solution $z_\varepsilon$ of  $f(z) + \varepsilon g(z) = 0$
can be represented as
$$
 z_\varepsilon = \frac{1}{2 \pi i} \int_{\partial \Bbb D}
  \frac{z (f'(z) + \varepsilon g'(z))}{f(z) + \varepsilon g(z)} \, dz
$$
(Proof: For fixed $\varepsilon$, $f(z) + \varepsilon g(z) =
(z - z_\varepsilon)h(z)$ where $h$ is holomorphic and not zero
in $\Bbb D$. Then
$$
 \frac{z (f'(z) + \varepsilon g'(z))}{f(z) + \varepsilon g(z)}
 = z \frac{h'(z)}{h(z)} + 1 + \frac{z_\varepsilon}{z_\varepsilon - z}
$$
and that has exactly one (simple) pole in $\Bbb D$, with residue $z_\varepsilon$.)
Since the integrand is continuous as a function of
 $(z, \varepsilon) \in \partial \Bbb D \times [0, \varepsilon_0]$
it follows that the integral is a continuous function of $\varepsilon $.
(It is even an analytic function of $\varepsilon $ if we consider
complex $\varepsilon $ with $|\varepsilon| < \varepsilon_0 $.)

An alternative proof would be to apply the implicit function theorem
to $F(\varepsilon, z) = f(z) + \varepsilon g(z)$, viewed as a function
from $\Bbb R \times \Bbb R^2 \to \Bbb R^2$.
Writing $f(z) = u(x, y) + i v(x,y)$, the derivative of $F$
with respect to $(x, y)$  at $(0, (0, 0))$ is
$$
 \begin{pmatrix}
    u_x(0, 0) & u_y(0, 0) \\
    v_x(0, 0) & v_y(0, 0)
 \end{pmatrix} =
  \begin{pmatrix}
    u_x(0, 0) & u_y(0, 0) \\
    -u_y(0, 0) & u_x(0, 0)
 \end{pmatrix}
$$
which is invertible because its determinant
$$
   u_x(0, 0)^2 + u_y(0, 0)^2 = |f'(0)|^2
$$
is not zero.
Comment: Could you explain specifically the derivation of $z_\epsilon$ expressed by line integral in the first proof? I don't know why the residue of the integrand is $z_\epsilon$.
Comment: Thank you so much. I finally understood fully and solved this tricky stuff.
Comment: @bellcircle: See updated answer.
Comment: I'm afraid I'm making you bothered, but could you give me a proof that $f(z)+\epsilon g(z)$ has a simple zero at $z_\epsilon$?
Comment: @bellcircle: It follows from Rouché that $f(z) + \varepsilon g(z)$ has exactly one zero in the unit disk. We just *name* that zero $z_\varepsilon$.


EF 4.1 Code first - Many to Many - State unchanged

Question: I have a many to many relationship, see my scenario explained here before continuing reading:
EF 4.1 Code First: Many to Many
Ok, now I can add the entries to the respective tables by doing the solution proposed by Slauma (see below) but I do not want to insert any entry to one of the tables (table B) as it has fixed entries (readonly). so how to achieve it? I mark it as unchanged but it is not working.
I do the following:
A a = new A() { PropertyA1 = something_1,
            PropertyA2 = something_2,
            PropertyA3 = something_3 };
a.Bs = new List();

foreach (.....)
{
  B b = new B() { ..... }
  a.Bs.Add(b);
}

context.A.Add(a);

// Below loop is not working
foreach (var entry in context.ChangeTracker.Entries()
        .Where(e => e.State == EntityState.Added && e.Entity is SomeEntity))
{
        entry.State = EntityState.Unchanged;
}

context.SaveChanges();

If I remove previous foreach, information is added correctly to tables A and link table C, but also in B and I do no want info to be added in B.
Any ideas?
Answer: Where you do
B b = new B() { ..... }

you must in stead fetch an existing B from the database and add that to a.Bs.


Difference between 'git pull origin develop --rebase' and 'git pull --rebase origin develop'

Question: I couldn't find a difference but could there be one?
Between:

option A: git pull origin develop --rebase
option B: git pull --rebase origin develop

Git docs state :
git pull [<options>] [<repository> [<refspec>…]]

So you would think of option B being the correct one, but than..

why does option A also works
and is there maybe an order by which the options are handled?
Comment: No, the position of options is irrelevant in git. Just beware of `--` in some commands, because everything after it is considered filepaths. `git show --name-only abcd1234 -- path/to/file.txt` will not be equivalent to `git show abcd1234 -- path/to/file.txt --name-only`
Comment: @MRedant I'm quite surprised by your comment, since I did not propose *any* answer nor solution in my first comment. I was merely pointing out that *no option* should be put after `--` which is the symbol for "everything past this are filepaths". And here you do *not* use `--` in your command, sorry if I somehow added confusion. Also, I have no clue why you got that my comment prompted you towards what you call "option A".
Comment: There is no difference AFAIK.  As to _why_, Git syntax is often very lax, that's why.
Comment: @MRedant No. If you want to prevent unexpected mistakes, prefer option B like it is described in the documentation. It is a shared convention between most of the unix command line tools...
Comment: @RomainValeri .. sorry for the confusion.. I was refering to the 'No' in your first comment and the other interesting background-info you provided.
Comment: @RomainValeri aha, so we'd prefer option A than
Comment: thx @RomainValeri if you post this as an answer I can mark it as a solution
Answer: There are competing theories on how rigid one should be with placement of options vs arguments.  POSIX utility guidelines prescribe what you called Option B.  Git, however, tries to be quite flexible about option placement, even when there are optional or required positional arguments.
These are the general rules for Git options:

Options placed between git and the sub-command verb, such as git --no-replace-objects log, are handled by the Git front end (the git program itself).  The front end transforms these into environment variable settings, which means that there's always an environment variable you could set instead.  For instance:
 git --git-dir=<path> ...

and
 GIT_DIR=<path> git ...

do the same thing.
Options placed after the sub-command verb are handled by the sub-command.

Single-letter options, such as -v, are preceded by a single hyphen, and can be grouped together.  Multi-letter options, such as --name-status, are preceded by a double hyphen.  Hence in git diff, there is a -c option ("combined diffs") but also a --cc option ("dense combined diffs"); the single-c option takes a single dash and the double-c option takes a double dash.

Anything starting with a hyphen is an option, anywhere, except after a double-hyphen.

The git filter-branch command breaks the last rule a bit because it has to parse its own options, then pass some options to git rev-list.  So with filter-branch, you run:
git filter-branch <filter-options> -- <rev-list-options>

and the <rev-list-options> itself can have options, then a second stand-alone double hyphen --, then path names.1
This all adds up to what you called Option A.  But note that if you write your commands with Option B in mind, they all work under Option A.

and is there maybe an order by which the options are handled?

There were, in the past, for some Git sub-commands, some places where order was particularly important.  That's fixed now but you will see this remark in the git checkout-index documentation:

The order of the flags used to matter, but not anymore.

In general, however, options are processed in the order they appear, and often, a repeated option will overwrite a previous one.  For instance:
git --git-dir=/tmp --git-dir=.git status

uses .git as the Git directory, not /tmp.

1By can here, I mean is physically able to.  You shouldn't actually use this capacity with git filter-branch as it is a form of aiming a gun at your own foot.


How to handle empty array response in iOS swift using alamofire

Question: I am using alamofire for service integration. its giving an empty reponse as [] sometimes only. in that time app is crashing because of empty array response. How to handle that response in swift iOS.
Here is my code:
    let headers = ["Authorization" : "Bearer "+token,
                   "Content-Type": "application/json"]

Alamofire.request("http://sos.partnersbuddy.in/api/friend_request/received", method: .get, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
            // print("Request  (response.request)")
        print("RESPONSE \(String(describing: response.result.value))")
        print("RESPONSE \(response.result)")
        print("RESPONSE \(response)")

            var respVO:[RequestResvo] = Mapper<RequestResvo>().mapArray(JSONArray: response.result.value as! [[String : Any]])

            print(respVO)

            self.postID = respVO[0].id!

            if let result = response.result.value {
                let JSON = result as! NSArray
                print(JSON.value(forKey: "user"))

                let res = JSON.value(forKey: "user")
                let respVo = Mapper<SubRequestVo>().mapArray(JSONArray: res as! [[String : Any]])

                for (index, element) in (respVo.enumerated()) {
                    print(index)

                    self.nameArr.append(element.first_name!)
                    self.numberArr.append(element.mobile!)

                    print("nameArr\(self.nameArr)")
                    print("numberArr\(self.numberArr)")

                    DispatchQueue.main.async {
                        // update your UI and model objects here

                        self.mytableView.reloadData()
                        // SKActivityIndicator.dismiss()
                    }
                }
            }
    }

How to handle this empty response in that time app is crashing because of empty array response. How to handle that response in swift iOS.
Answer: You can try print response as string:
Add it at the end of your request, like this:
Alamofire.request(url, method: .get, encoding: JSONEncoding.default, headers: headers)
.responseJSON { response in

}.responseString { response in
    print(response)
}

Answer: Looking at your code, I would do something like this:
Alamofire.request("http://sos.partnersbuddy.in/api/friend_request/received", method: .get, encoding: JSONEncoding.default, headers: headers).responseJSON { response in

        switch response.result {
        case .success(let json):
            guard let array = json as? [[String : Any]] else {
                // Handle error: your json response is not a [[String : Any]] as you were expecting
            }

            if array.count == 0 {
                // Handle empty array response
            }

            var respVO:[RequestResvo] = Mapper<RequestResvo>().mapArray(JSONArray: response.result.value as! [[String : Any]])

            print(respVO)

            self.postID = respVO[0].id!

            if let result = response.result.value {
                let JSON = result as! NSArray
                print(JSON.value(forKey: "user"))

                let res = JSON.value(forKey: "user")
                let respVo = Mapper<SubRequestVo>().mapArray(JSONArray: res as! [[String : Any]])

                for (index, element) in (respVo.enumerated()) {
                    print(index)

                    self.nameArr.append(element.first_name!)
                    self.numberArr.append(element.mobile!)

                    print("nameArr\(self.nameArr)")
                    print("numberArr\(self.numberArr)")

                    DispatchQueue.main.async {
                        // update your UI and model objects here

                        self.mytableView.reloadData()
                        // SKActivityIndicator.dismiss()
                    }
                }
            }
        case .failure(let error):
            // Handle response error
            print(error)
        }
    }

This let you handle both response result and the empty array case.
Giving more information about your response json format, would be better to write down more precise code that fit your problem.
Answer: I got an empty json from alamofire response with nil status code and failure because of sending the URL with spaces. If you got something similar, make sure to use the url with allowed characters:
var urlString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)


Brownian motion property on interval

Question: Say $B$ is a Brownian motion. Knowing that for some constant $a\gt0$
$$P(\sup_{[0,n]} |B|\leq 1) \leq e^{-{an}}$$
how can I deduce that
$$P\left(\sup_{[0,1]} |B| \leq \frac{1}{n}\right)\leq e^{-{an^2}}$$
Answer: First, rewriting the inequality for $n' \equiv n^2$, we have that $$ \mathbb P(\sup_{[0,n^2]} |B|\leq 1) \leq e^{-{an^2}} \tag1$$
Now, if $(B_t)_{t\ge0}$ is a Brownian Motion, then $W \equiv \left(nB_{t/n^2}\right)_{t\ge0}$ is also a Brownian Motion for all $n >0$. Therefore, applying inequality $(1)$ to the process $W$, we get :
$$\begin{align}\mathbb P(\sup_{[0,n^2]} |W|\leq 1) &= \mathbb P(\sup_{t\in[0,n^2]} n|B_{t/n^2}|\leq 1)\\
&=\mathbb P\left(\sup_{t\in[0,n^2]} |B_{t/n^2}|\leq \frac1 n\right)\\
&=\mathbb P\left(\sup_{s\in[0,1]} |B_{s}|\leq \frac1 n\right) \\
&\le e^{-{an^2}} \end{align} $$

Brownian motion property on interval


Aggregate function in R

Question: I am newbie to R and hence struggling to figure out on how to retrive the complete list of fields / columns from the data frame with in aggregate function.
For example, I have a data frame df with 200+ fields. Now, I would like to group the data frame on a particular field df.a and then order by another field df.b. However, in the output data frame, I want each of the rows containing all the 200+ fields instead of only df.a and df.b fields.
Please help me understand how to achieve this.
Comment: Welcome to StackOverflow! Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you.
Comment: [R Grouping functions: sapply vs. lapply vs. apply. vs. tapply vs. by vs. aggregate](http://stackoverflow.com/questions/3505701), [Aggregate multiple variables simultaneously](http://stackoverflow.com/questions/9723208), [How to sum a variable by group?](http://stackoverflow.com/q/1660124)
Answer: You could write your own function but it would probably be best if you use an already written, debugged and performance-tuned function. The package dplyr is excellent for these sort of things.
I find myself often writing lines like:
df %>% group_by(a) %>% arrange(b) %>% summarise(total = sum(b))

Where df is my dataframe, group_by is the function to group your rows by a specific column (or set of columns) and arrange is the function to reorder your rows by a column (or set of columns). summarise is a way to perform aggregations and produce summaries of data. %>% is the 'pipe' operator used to feed the result of the expression on the left as the first argument to the function on the right instead of writing multiple nested calls that are hard to read or creating intermediate one-off variables.
Hope this helps or gives you some better ideas.
Comment: Thanks Kliron for the answer. This is what I was looking for. However, just wondering how I can perform count on a particular column using dplyr.
Comment: Look at the edited post. You can use summarise to produce aggregates/summaries of your data. If you want a specific answer to a specific problem please give a simple example data frame and a desired output in your question above.

Aggregate function in R


Exclude permission denied messages from find

Question: In bash, I can redirect stderr using 2>&1 with the find command and pipe it to grep to remove any Permission denied messages. How do I do this in csh? I am getting the error message Ambiguous output redirect. I have already tried the syntax at this question, and it gives me the error described.
Comment: possible duplicate of [How to redirect stdout and stderr from csh script](http://stackoverflow.com/questions/1849358/how-to-redirect-stdout-and-stderr-from-csh-script)
Comment: also possible duplicate of http://stackoverflow.com/questions/9426440/stderr-redirection-methods
Comment: @Ben: Second link does not answer my question, nor is the answer having to do with find. And first link does not have to do with find nor does it only redirect stderr.
Comment: Both of them answer your question.
Comment: This isn't possible without writing to a file then grepping it:  http://stackoverflow.com/questions/13720246/redirect-stderr-to-stdout-in-c-shell
Answer: Theoretically you can use "! -executable -prune -o ..." to enter only accessible directories.
Answer: Per the link that @swdev posted in a comment above, the only way to do this by sending it to a file and then using grep on that file when you are in csh.


Can we use Jetty8.x with Java 1.8?

Question: I am developing an eclipse RCP application with Eclipse Juno (4.2.2) that comes with Jetty 8.1.3. I have bundled the product with Java SDK 1.8. The RCP application runs fine but Help -> Help Contents gives below error. (Note that this works fine if I try with java 1.7)
Does Jetty 8.x works with Java 8? If yes, could you please provide instructions on how to make it work with Java SDK 1.8?
<code>HTTP ERROR: 500
Problem accessing /help/index.jsp. Reason:

PWC6033: Error in Javac compilation for JSP

PWC6199: Generated servlet error:
The type java.io.ObjectInputStream cannot be resolved. It is indirectly
referenced from required .class files
----------------------------------------------------------------------------
Powered by Jetty://
</code>
Thanks in advance.
Answer: No. You need Java 1.6 for Jetty8.
If you want to use Java 1.8, you need to upgrade to Jetty9.3 or higher.

Can we use Jetty8.x with Java 1.8?


How does the WAR suit ability Shield Wall work?

Question: Any soldier who has a WAR suit (tier 3 heavy weapon armor) equipped gains a "Shield Wall" ability, allowing them to act as high cover for other soldiers (something like one of the MEC Trooper abilities from XCOM: Enemy Within).
The game doesn't really explain well how this ability affects both the soldier who deploys the shield, and any soldiers who then take cover behind the shield.

Is the soldier deploying the shield immune to damage, or do they still take damage as normal?
Can the soldier deploying the shield still take advantage of any environmental cover while also activating the shield? For example, can a WAR suit soldier crouch behind low cover, deploy the shield, and still take advantage of the low cover?
Does activating the shield give the WAR suit soldier a defensive bonus that stacks with whatever cover that he is using?
Answer: The effect of Shield Wall is: you become high cover.
That's it. You don't get any sort of defense bonus, you don't get damage resistance, nothing else. On the bright side, it doesn't appear to prevent you from taking cover, either. The net effect is that you're a regular soldier in every way, except that wherever you're standing happens to count as a high cover tile.
Comment: As it currently exists, I find Shield Wall to be underwhelming, or even dangerous, especially on higher levels of difficulty. It's not like the old MEC troopers who were durable and survivable enough to stand out in the open, because they couldn't take cover anyways.
Comment: Yeah, it's extremely underwhelming. If armor functioned like it did in XCOM:EU, where armor damage didn't send you to the med bay, it would at least be feasible. Right now it's just a very situational "your soldier is already in acceptable cover and it would be nice if there was even more cover".
Comment: @ChrisHayes: The idea of having a damage soaker is not to keep everyone out of the medbay, but rather to have the damage soakers go to the medbay instead of the glass cannons. For such a strategy, you need several damage soakers so you can rotate them for needed missions.
Answer: The purpose of the shield wall is to provide full cover where none exists. The soldier that casts it turns into that heavy cover, but as a side-effect that soldier receives no bonuses. The benefit of using it is to, say, move up to a soldier that is now being flanked and give him some hard cover. Kinda like in the last game with Alloy SHIVs. You could move one up to a soldier standing, and it would provide them with hard cover.
The uses of the shield wall are still very...limited. I think it can have some good uses if the right combination of buffs are applied by your other squadmates, but that's a lot of spent moves that might work better for a different strategy.
Basically, let's say you deploy it in a no man's land of cover and want to move someone else up, say a Sharpshooter, to get in some sweet pistol kills. But you don't want to leave them flapping in the wind and open to flanks, who wants to do that? So you use the shield wall and move someone up into that no man's land.
However, once you do that, then that soldier is flanked. Even though you can now move someone up behind them and they will have full cover, your shield-wall soldier is considered flanked (they're standing in the open). This renders the full-cover benefit to the soldier behind them worthless, because the aliens will prioritize shooting the now flanked soldier in their sights over everything else.
It still seems to me that it might have some interesting things with it, such as a grenadier with blast padding. That gives you 3 or 4 armor pips I think, which is very tanky. Combine that with a very high dodge PCS, and aid protocol, and you'll have a virtually untouchable wall of hard cover that can move. Still, I'd rather spend moves with my specialists elsewhere, like overwatching with guardian, hacking, or using combat protocol. And use my Grenadier for more useful things like Salvo.
Comment: A lot of enemies can shred armor, so your 3-4 armor WAR suit soldier isn't as tanky as you think. Plus on higher difficulties, getting critically hit is especially brutal, and can often result in instant death in 1 or 2 hits, so leaving a soldier flanked out in the open is basically a death sentence.
Comment: "The benefit of using it is to, say, move up to a soldier that is now being flanked and give him some hard cover." - This would effectively only swap one flanked soldier against another while additionally providing a good OeE target. I can only imagine VERY rare cases where this might help-
Comment: I agree it's underwhelming. But might be useful on a Ranger with the Untouchable buff (to rush in a second soldier).
Answer: The Shieldwall appears to absorb no damage whatsoever. My guy took full damage from all angles and she was even flanked meaning there could be some gain from cover as well.


How do I see what streaming accounts are already tied to my PS4?

Question: Playstation recently updated their OS and I'm having trouble finding what broadcasting accounts (such as Twitch or YouTube) I've already added to my PS4's broadcasting settings.
Is there a new menu that allows me to see the Twitch or YouTube usernames that are currently tied to the console?
I believe there is a way through the PS4 App, but I'm looking for a menu directly on the console.
Comment: Are you talking about like Netflix/Hulu/YouTube/CrunchyRoll type subscriptions or is this specifically about streaming accounts?
Comment: @Vemonus - Specifically broadcasting accounts such as Twitch.  I'll edit the question to clarify. Thanks!
Comment: Is it in a different place than the account's linked subscriptions?
Comment: Yes, there is a "Broadcasting Settings" menu that houses streaming accounts in the "Settings" of the PS4 OS.
Comment: ah, I don't stream so I wasn't aware of a difference. Though I could've sworn the Twitch and YouTube subs were listed next to my streaming accounts like Hulu/Netflix/CrunchyRoll... will definitely take a look when I get home today and get back to you if no one else does in the meantime!
Answer: Yes, there is a way to see all accounts for services that you've linked to your PSN account. Each user on the console is able to link accounts to services as they choose, so you aren't limited to one account per console per service. However, each user can only see their own account links. To see these linked accounts, here are some directions.
From your home screen, go to your Settings:

Then, go to "PlayStation Network/Account Management":

From there, go to "Link with Other Services":

Once there, you'll see a list of a bunch of services you either have or are able to link with your PSN account. The ones you have linked are marked with a check mark:

If you click on a service that you've linked to your PSN account, it will display the account you've linked for that service. For example, YouTube will tell you the name and email of the account you've linked to your PSN account.
Comment: You sir are a rock star!  I've confirmed this as the solution.


TestFlight Issue With Invitation

Question: I have successfully invited my internal testers to test my 2nd build, and they have both received the invite email. The problem is that when they click on the invite, when they are taken into TestFlight they get a message saying the app is not available. If you have any experience with this or know how to fix this please let me know. I think the pictures below will be very helpful in finding my problem.
Comment: Could you have possibly turned off beta testing somehow after you sent the invites?  Could you try turning beta testing on and off again?
Comment: @milesper that did the trick! Please post your comment as an answer so I can accept it as an answer and give you reputation.
Answer: Make sure beta testing is turned on, or try turning it off and on again.
Comment: Is the user opening the email in mail and clicking the link from there?
Comment: Yep, the user did open the email and click on that link.
Comment: Are they internal or external?
Answer: The user must click on the invite on their device using the Apple mail app. They cannot use Gmail, for example, to successfully make the build appear in Apple's TestFlight app.

TestFlight Issue With Invitation


14.04 won't update

Question: I haven't used this system for a while, so when I went to update it I started getting error messages such as this:
E:Line 1 too long in source list /etc/apt/sources.list.d/medibuntu.list.
E:The list of sources could not be read.
E:The package lists or status file could not be parsed or opened.

I'm way out of my depth here, please help.
Edit: The result of head -n 1 /etc/apt/sources.list.d/medibuntu.list
<!DOCTYPE html><meta charset=utf-8><title>medibuntu.org -&nbspThis website is for sale! -&nbspmedibuntu Resources and Information.</title><meta http-equiv="refresh" content="0; url=http://www.medibuntu.org/sources.list.d/trusty.list/?gtnjs=1"><meta name=GOOGLEBOT content="index, follow, all"><meta name=robots content="index, follow, all"><meta name=viewport content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0"><meta name=description content=This website is for sale! medibuntu.org is your first and best source for all of the information you're looking for. From general topics to more of what you would expect to find here, medibuntu.org has it all. We hope you find what you are searching for!><link href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYxIDY0LjE0MDk0OSwgMjAxMC8xMi8wNy0xMDo1NzowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNS4xIFdpbmRvd3MiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6MzRFNEQ3NkJEMjRGMTFFMTk4RjA4NDhFNTEwRTcyMkIiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6MzRFNEQ3NkNEMjRGMTFFMTk4RjA4NDhFNTEwRTcyMkIiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDozNEU0RDc2OUQyNEYxMUUxOThGMDg0OEU1MTBFNzIyQiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDozNEU0RDc2QUQyNEYxMUUxOThGMDg0OEU1MTBFNzIyQiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PukMAkAAAAEsUExURcbf8uXx+vb6/eXx+Q5FtN/t+Ofz+rbX7uTr9+Tq9y5fvlh+y7rY7+n0+lJ6yS1evt7l9Sxdvr/b8L3a8BRLtpev31mAy+v0+k13yLLD59Hm9PT5/c3Z8LXG6Oby+pXG5aG54vX3/Git2LvZ79bg8vr8/vP4/Mjh8+Pw+Ofy+sPd8cfj9G2P0cDc783k9Ex2x6DK5xlOuCBUumWJztDm9DZkwLTF6Ojt92yP0s7a8OPq9m6Y1d3l9cHP7OLp9kNvxNPo9Wes2DNhwJSv3uDt+Ovw+cDP6yNVuurv+Nbf8pjI5aDL56G44rTL6h1RuWaJz9bp9tDo9u31+oWi2TZlwMfg8E16yd7t99Hc8Vl+ysri897l9JCq3FB5yPL1++/2/MLQ7HGb1j9sw////2AvJ1QAAADsSURBVHjaRM9ZMwNREAXgnpvLZKOENsQSJrTlIjHEEhQZS2JJxljHmoT+//9B37w4j19Xna4DzKzGDbHKLN+MdZlB4GNJ8fV9AbH1W7ew7g6zn9ORt/uM8wJkBOs7eHai/P05Bnp0S8ynBQz2qk9v0jEbTyjpKWZRI0Z9hqlV29u9ynQmR6PAY7g0NYH+efvzYDHAQ4bExBY0Bi3E7BHDkGkI+MXN7+ncV1pKU1AhIiYbudgvx957c+t2YW2k1ugJUKmqdXs7DGdiN5+yW+hV4K4cVhI37wzGdX4u0skL9FYcRw2ANh74P38CDABMCjqJfzUcfQAAAABJRU5ErkJggg==" type=image/png rel="shortcut icon">

14.04 won't update


ArcGIS js API - possible to get data map points from an external web service?

Question: I'm very new to ArcGIS and I'm currently exploring the js API. I haven't seen documentation for this but can i use a json datasource (returned from an ajax call) as the data items/points for my map? Can anyone point me to an example?
Answer: If you don't have any Map Service (ArcGIS, WMS, KML, etc) but just a list of geometries fetched from somewhere else you must use a GraphicsLayer. You can use the default GraphicsLayer of the map or add another GraphicsLayer.
for each geometry:
<code>map.graphics.add(new Graphic(geometry, symbol));
</code>
Comment: thank you so much! I struggled a little creating the graphic from a json object but i got it working!


ora-02287 Sequence number not allowed

Question: I am trying to run the following query to fill a table with the proper values. I have ran the select statement alone, without the price_s and the created_by, creation_date, last_updated_by, and last_update_date, and it pulls everything that I need. When I add those values, it gives errors, I have gotten through some of them, but I am stuck on this one ORA-02287: Sequence number not allowed here, I have looked everywhere and cannot find what I am doing wrong. It is probably some simple answer, but I just cannot see it right now.
Here is the code:
CREATE SEQUENCE price_s START WITH 1001;

INSERT INTO price (price_id, item_id, price_type, active_flag, start_date, end_date, amount, created_by, creation_date, last_updated_by, last_update_date)
SELECT price_s.nextval, i.item_id,
active_flag,
cl.common_lookup_id,TRUNC (i.release_date),
CASE
WHEN (TRUNC (SYSDATE) - TRUNC (i.release_date)) < 31 AND active_flag = 'N' THEN NULL
WHEN (TRUNC (SYSDATE) - TRUNC (i.release_date)) > 30 AND active_flag = 'N' THEN TRUNC (i.release_date) + 30
END AS END_DATE,
CASE
WHEN (TRUNC (SYSDATE) - TRUNC (i.release_date)) < 31 AND active_flag = 'Y' THEN
CASE
WHEN rental_days = 1 THEN '3'
WHEN rental_days = 3 THEN '10'
WHEN rental_days = 5 THEN '15'
END
WHEN (TRUNC (SYSDATE) - TRUNC (i.release_date)) > 30 AND active_flag = 'N' THEN
CASE
WHEN rental_days = 1 THEN '3'
WHEN rental_days = 3 THEN '10'
WHEN rental_days = 5 THEN '15'
END
WHEN (TRUNC (SYSDATE) - TRUNC (i.release_date)) > 30 AND active_flag = 'Y' THEN
CASE
WHEN rental_days = 1 THEN '1'
WHEN rental_days = 3 THEN '3'
WHEN rental_days = 5 THEN '5'
END
END AS AMOUNT,
1,SYSDATE,1,SYSDATE
FROM     item i CROSS JOIN
    (SELECT 'Y' AS active_flag FROM dual
     UNION ALL
     SELECT 'N' AS active_flag FROM dual) af CROSS JOIN
    (SELECT '1' AS rental_days FROM dual
     UNION ALL
     SELECT '3' AS rental_days FROM dual
     UNION ALL
     SELECT '5' AS rental_days FROM dual) dr INNER JOIN
     common_lookup cl ON dr.rental_days = SUBSTR(cl.common_lookup_type,1,1)
WHERE NOT ((TRUNC (SYSDATE) - TRUNC (i.release_date)) <= 31 AND active_flag = 'N')
AND NOT cl.common_lookup_table = 'RENTAL_ITEM'
ORDER BY 1, 2, 3;

Any ideas on what I am doing wrong?
Comment: Perhaps you have a trigger on `price`.
Comment: I can insert using `INSERT INTO price VALUES` and creates one row.
Comment: Your `order by` is superfluous because of the way that sequence numbers work.
Comment: Thank you, I posted the answer same time as you, THANK YOU so much though for answering.
Answer: Well I figured out what was wrong with my statement. I knew it was simple I just could not see it at the time. I forgot to take out the
ORDER BY 1, 2, 3; it was messing everything up, sorry to take up anyone's time.
Comment: You should accept your answer.  You have a reasonable question and answer to it.
Comment: It says I have to wait 2 days

ora-02287 Sequence number not allowed


Ganged Circuit Breaker has strange ganging configuration. 40-[30-30]-40

Question: I have a scenario where the Circuit Breakers for a Dryer and a Range are intertwined in the CB panel. In the picture below 17 and 20 are ganged together with that wild ganging clip. 18 and 19 both 30amps are ganged together normally.

Is this kind of ganging of breakers with in code ?
Why would anyone do this ?
Why wouldn't they just connect this normally 17 & 18 and then 19 & 20?

EDIT 7-11-2018
Based on write ups and comments etc.. I  felt it better to edit my post rather than to go through each write-up/comment.
Please don't read anything into the numbering of spaces, I was told the previous homeowner did that numbering.

17 & 20 Range........40 Amp Range.
18 & 19 Dryer..........30 Amp Dryer.
1 & 2, 3 & 4.............60 Amp Heater.
5 & 6, 7 & 8.............30 Amp Air Conditioner.
21 & 22, 23 & 24.....30 Amp Water Heater.

I know each pole is 120V circuit. I know that you gang them in a 240V circuit (L1,L2) - in a residence in USA you don't normally get 220V Single Phase (HI-Leg or Stinger Leg - of course they all sting if you ask me).
So each pole Odd/Even slot - A & B Phase if you will (L1, L2). Normally Odd (1, 3, 5 etc) is L1 and Even (2,4,6 etc) is L2 (of course I don't think code states which is L1 and which is L2). That way when you place a 240V breaker in; it takes up the Odd Slot {120V - L1} and the Even Slot {120V - L2} for 240V. This might be panel dependent but that is the jist of getting 240V from L1 and L2.
As for the breaker in question I do believe it is a Quad as some have linked to. Which basically sounds like 2 Double Stuffs in one unit , in order to fit the number of breakers that are needed. Seems to me the Builder did not size the panel correctly and just Stuffed away.
Comment: Likely [this](https://www.homedepot.com/p/206632159) breaker.  It should be noted there are more restrictions on usage than standard double stuff breakers, they don't fit every space in every Siemens panel.
Comment: Can you give us a closeup of the breaker in question? I can't read the labeling off it well enough to tell if it's an independent trip or a common trip quadplex...)
Comment: Lots of electricians tend to forget that it was not that long ago the was a strict limit to the number of slots, by using tandem or double stuff breakers this provided more branch circuits. In the past the handle ties were all that was needed, today a common trip mechanism is required. Code allows this of it was legal when the wiring was done you are not required to update the panel.
Comment: What does that 60A breaker turn off/control?
Answer: This is a bit backwards, but OK as long as the breakers have a common trip mechanism inside them
Normally, you'd see this configuration as a 30-40-40-30, but either way, this is a quadplex breaker, where the outside half-poles are ganged together to form 1 240V circuit while the inside half-poles are ganged together to form the other 240V circuit.  You wouldn't get anything good out of the other configuration, as the two upper half-poles connect to the same bus stab (i.e. are on the same leg), and likewise with the two lower half-poles.  The crazy-looking handle-tie (what you call a "ganging clip") is manufacturer-supplied, and normal for this type of quadplex breaker -- it allows the handles to be operated together when you operate them by hand.  Common trip is handled by an internal mechanism, however.
As to why someone would do this? They simply ran out of panel space -- this is also evidenced by the large quantity of double-stuff breakers in the panel.  (This is why putting in a panel that barely fits is penny-wise and pound-foolish, especially for the main panel in a building.)  It's OK by Code as long as the panel is labeled and listed to accept double-stuff breakers in those two slots -- check your panel labeling for details.
Comment: Your comments and questions were right on and as I read more on the Quad - I came to realize that is exactly what it is. Then I also came to realize the builder of this home was CHEAPER than CHEAP. While it passed code, he had to "improvise" in order to get things to work out with the panel in Question. Not only that there was not a single space left for additional circuits - you would think the next panel size up wouldn't have broken the ability to sell the home!
Answer: Because you haven't numberd braker spaces - you've numbered half spaces.  Each space only has one pole, so a breaker that only  takes one space (i.e. 17-18) can only access 120V.
Your 240V breakers need two poles.
See this discussion of how poles work.
That is actually a 16 space breaker panel.  That is far too small for a modern home.  They lean very heavily on the double-stuff breaker "crutch" but that is not allowed anymore: most circuits today require AFCI and/or GFCI and/or whatever they come up with next. Far and away the easiest and least awkward way to do that is xFCI+breaker combo devices, and none of those will fit in a half space.  They can't be double-stuffed.
A better panel size choice is 30-space, but even there you'd already be out of spaces on day one... This is why we recommend a 40+ space panel.
Comment: But if you don't have >$2k for a new panel installed, could you use GFCI and AFCI receptacles strategically placed?
Comment: @JimStewart -- you could, yes -- this is sometimes done when an obsolete but reliable panel is still giving good service
Answer: To go right to your point, in simplified language and using your numbering system, #17 and #18 are on the same leg (0 V difference); same with #19 and #20. To get a pair of 2-pole 240 V circuits this type of breaker pairs #17 and #20 for the 40 A circuit and #18 and #19 for the 30 A circuit.
The visible physical links between #17 and #20 and between #18 and #19 insure that if you manually switch the breaker both breakers will be switched. These are 2-pole breakers powering a single 240 V circuit and you want either both on or both off.
In addition, according to @Tyson (comment) each pair of this model of linked breakers is "common trip", meaning there is an electrical connection inside which causes the other breaker of the pair to trip even if the over-current in only in one of the pair. (This could happen if only one leg was shorted to neutral or to gnd.) There are breaker pairs which have a physical link that are not common trip. These are used for a different purpose than powering a single 240 V circuit.
EDIT I was under the impression this was a split bus panel, but not so.
Comment: I actually am kinda doubting that it's split buss -- we don't have enough to go on.  Also, it is only *mixed-voltage* (120/240V together) circuits that need common trip.
Comment: @ThreePhaseEel Ken could settle it by seeing the effect of switching off the 60 A breaker. The 60 A size is what is used to feed the bottom in my split phase panel and in the other current split phase panel from Seattle.
Comment: @ThreePhaseEel you are correct It is not a split buss - the 60AMP is for the heater (at least that is how it is labeled on the door). The breaker in question is the odd ball - I am thinking it is a Quad as others have stated (I never saw one before)
.
Comment: So is there a main breaker/disconnection means elsewhere? in a box outside under the meter? What is the manufacturer and age of this panel?
Comment: The current pic of the panel is cropped. What is above and below in the panel? Is there a 150 A main breaker in this panel? Where is this and what type of residence?


If I have an nVidia graphics card on Linux, do I need Mesa or FreeGLUT or anything like that?

Question: The wiki says the following about using OpenGL on Linux:

Most Linux distributions rely on the Mesa3D project to provide their OpenGL implementation

But it also says:

OpenGL is included in drivers, so you'll have to make sure drivers are properly installed if you want to enjoy programs using OpenGL. Open source drivers actually make use of Mesa's OpenGL implementation.

So I am a little confused:
If I have an nVidia graphics card and install the nVidia drivers, do I need to install Mesa?
What if I have the card but do not install nVidia's drivers?
What, exactly, is meant by "implementation" in this context?
Answer: The Mesa3D project is a software implementation of OpenGL; that is, an implementation that does all the rendering on the CPU with no GPU involvement at all. It's designed in two layers: a backend which renders each frame from some internal state, and a frontend which implements the OpenGL API and sets up the state for the backend to use. Most OpenGL implementations have a similar two-layer architecture, so that the same backend can be used by an OpenGL frontend, an OpenCL frontend, a Direct3D frontend, etc.
The open-source NVidia drivers (and most open-source drivers) use Mesa's frontend to provide the OpenGL API and a backend specific to that GPU. The OpenGL API is quite complicated to implement, so it makes sense for vendors to share an existing front-end in this way. However, closed-source drivers do not use Mesa's frontend and have their own closed-source frontend.
If you install and use a closed-source GPU driver, it will include its own libgl, which doesn't use Mesa at all. You don't need to install anything else to run OpenGL applications. (You might need an extra "-dev" package to get the header files needed to compile OpenGL applications.)
If you install and use an open-source GPU driver, it will use Mesa, but the packages in your distribution should have the dependencies set up correctly, so that if an external Mesa package is needed, it will be installed automatically.
Either way, you shouldn't have to worry about whether the OpenGL implementation you're using is based on Mesa or not.


Tools to help figure performance improvement with http 2.0 over http 1

Question: Are they any tools to help me figure out performance improvement I will be get with HTTP 2.0 versus HTTP 1
Or any other guidance on how I would go about doing paper calculation.
Typically I have noticed that the tools would eliminate SSL connect time because of socket reuse.
I have looked at one tool - http://http2.loadimpact.com/entry/
Answer: I recently found http://www.webpagetest.org/.
You can choose the browser that runs the test, and if you choose a browser that does not support HTTP/2 such as IE10 and one that does such as Chrome, you will get a comparison between HTTP/1.1 and HTTP/2.
Comment: Thank you, very useful tool to analyze other aspects of browser behavior. I like the location testing


DHCPD and Appamor

Question: I running ubuntu 22.04 on raspberry pi, with fixed IPv4 address. On the server a isc-dhcp-server is running. (i know isc-dhcp-server is outdated an not in service anymore).
While starting appamor denying dhcpd operation:
apparmor="DENIED" operation="open" profile="/usr/sbin/dhcpd" name="/proc/sys/net/ipv4/ip_local_port_range"

That's not a problem, because of fixed IPv4 address, but why and how can i prevent this failed operation?
Answer: to prevent the message:
sudo nano /etc/apparmor.d/usr.sbin.dhcpd

@{PROC}/sys/net/ipv4/ip_local_port_range r,

DHCPD and Appamor


Skip deserialization of an element and get whole content as a string while xml parsing in java

Question: I have a XML like below:
<content>

Node: Some information

</content>

When deserializing this XML, I want to get the content inside p tag as a string.
For example, if I have a java class like below:
@Data
class Content {
  TextInParagraph p;
}

@Data
class TextInParagraph {
  String text;
}

I should have value of text as "Node: Some information".
Is there a way I can do above using JAXB or Jackson XML parser?
I tried deserializing above in Jackson, but I am getting below exception:
Expected END_ELEMENT, got event of type 1
java.io.IOException: Expected END_ELEMENT, got event of type 1

Comment: See JSON [documentation](https://www.baeldung.com/jackson-deserialization), Did you try something like `new ObjectMapper().readValue(json, Content.class);`?
Comment: I tried something like above, but I am getting error: "Expected END_ELEMENT, got event of type 1".
Comment: Can you change this `XML` and use `CDATA` to store `HTML` code inside `content`  or `p` node?
Comment: No, I am getting this from another service, so can't edit.
Answer: Sadly, this is not possible with jackson-dataformat-xml.
With JAXB however you can solve this by using a DomHandler
@XmlRootElement(name = "content")
@XmlAccessorType(XmlAccessType.FIELD)
public class Content {

    @XmlAnyElement(InnerXmlHandler.class)
    private String p;
}

DomHandler
import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.annotation.DomHandler;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.StringReader;
import java.io.StringWriter;

public class InnerXmlHandler implements DomHandler<String, StreamResult> {

    private static final String START_TAG = "
";
    private static final String END_TAG = "
";

    private StringWriter xmlWriter = new StringWriter();

    public StreamResult createUnmarshaller(ValidationEventHandler errorHandler) {
        return new StreamResult(xmlWriter);
    }

    public String getElement(StreamResult rt) {
        String xml = rt.getWriter().toString();
        int beginIndex = xml.indexOf(START_TAG) + START_TAG.length();
        int endIndex = xml.lastIndexOf(END_TAG);
        return xml.substring(beginIndex, endIndex);
    }

    public Source marshal(String n, ValidationEventHandler errorHandler) {
        try {
            String xml = START_TAG + n.trim() + END_TAG;
            StringReader xmlReader = new StringReader(xml);
            return new StreamSource(xmlReader);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

This works with the sample you provided, but even works with nested
 tags like:
<content>

 This is some

list

 and
nested paragraph

</content>

However, this works only when the inner HTML/XML is valid. The following will not work and throw an exception like The element type "ul" must be terminated by the matching end-tag "
".
<content>

 This is some
invalid xml

</content>

This is because of JAXBs internals which traverses all inner elements although the dom handler is provided.


What does the "eye" control in picture in picture mode do?

Question: In tabletop simulator there is a "picture in picture" tool.
One of the controls is an "eye" icon, but I have no idea what it actually does.
Does anyone know what this control does?
Answer: In the latest update they have added tooltip text to the control.
This is what it says in both states of the control:

So it would appear that it edits the pip view to simulate either a player or a spectator perspective.  (not really sure when that feature would be very helpful, but at least now we know does the control does.)


Any efficient way to solve this fixed-rank problem?

Question: My problem can be listed as follows:
$$\begin{array}{ll} \text{minimize} & f(X)\\ \text{subject to} & \mbox{rank} (X) = 3\end{array}$$
Is there some efficient algorithm to solve this problem? High complexity is affordable for high performance. Thank you in advance.
Comment: Maybe state the whole problem? What is f?
Comment: such as $f=|Y - BX|_F^2$, where Y and B is known matrix
Answer: The constraint $\mbox{rank}(X)=3$ is a non-convex constraint, so your optimization problem is in general non-convex.
One common approach to dealing with this is reparameterize the rank-3 matrix $X$ as
$X=VV^{T}$
where $V$ is an $n$ by $3$ matrix.  When you do this, you'll get rid of the nonconvex constraint, but you'll probably create a situation in which the new function of $V$ is nonconvex.
There are also methods that work directly with the rank constraint to find a local minimum solution.  Look for research on optimization on manifolds.
Comment: Thank you for your kind response. I have tried to use the manopt to solve this problem, however, in my problem the $X$ is a complex matrix, while it seems the manifold tools propsoed by manopt can only work for real matrix.
Comment: According to its documentation, the MATLAB package manopt supports a Stiefel manifold on complex matrices.