Q:

How to create personal JavaScript library and framework?

As a developer, I would like to create my own JavaScript library and framework. In terms of architecture and features, what kinds of aspects should I take into consideration?

A:

First off, you need to know what you want your library to do. From there on, you need to be able to know how to do what you are trying to build. For example if you are trying to make a gaming library, you better know your equations and be good with things such as Canvas and WebGL. I've created a library before for methods for Strings, Array, Objects etc. I got it done, but sadly I never finished the documentation.
Anyways, I basically started out with creating a "JavaScript class". Which would look something like (doing a jQuery like library example):
var DOM = function (selector) {
  if (typeof selector == "string") {
        selector = document.querySelectorAll(selector);
  }
  this.animate = function (prop, times, callbacks) {
      var el = selector;
      var animate = function (element, props, time, callback) {
          callback = callback || function () {};
          time = time || 1000;
          var timers = {}, // store the different interval timers so that they can be cancelled
          calls = 0, // numbers of times the call would have been called
          nprops = 0; // number of properties
          for (var prop in props) {
              (function (prop) {
                  var edit = prop == "scrollTop" ? element : element.style;
                  var stepCounter = [],
                      customStep = props[prop],
                      curr = edit[prop],
                      lastStepPercent = curr == "" ? (prop == "opacity" ? 1 : 0) : curr,
                      measure = prop == "scrollTop" || prop == "opacity" ? "" : "px",
                      stepper = function () {
                          edit[prop] = stepCounter[0] + measure;
                          stepCounter.shift();
                      };
                  if (props[prop].constructor == Number) customStep = [props[prop]];
                  for (var step = 0, len = customStep.length; step < len; step++) {
                      var from = parseInt(lastStepPercent),
                          to = parseInt(customStep[step]),
                          small = to < from,
                          numOfSteps = small ? from - to : to - from, // get current number of frames
                          multi = 30 * Math.round(parseInt(time) / 1000),
                          by = numOfSteps / (25 + multi) * len; // the stepper number

                      if (from == to) {
                          break;
                      }
                      for (var i = from; small ? i >= to : i <= to; i += small ? -by : by) {
                          stepCounter.push(i);
                      }
                      stepCounter.push(to);
                      lastStepPercent = customStep[step];
                  }
                  stepper();
                  timers[element + prop] = setInterval(function () {
                      stepper();
                      if (stepCounter.length == 0) {
                          clearInterval(timers[element + prop]);

                          calls++;
                          if (calls == nprops) {
                              callback.call(element);
                          }
                      }
                  }, time / stepCounter.length);
                  nprops++;
              })(prop);
          }
      };
      for (var i = 0; i < el.length; i++) {
          animate(el[i], prop, times, callbacks);
      };
      return new DOM(selector); // re-initiate "JavaScript class" for chaining
  }
  this.click = function (fun) {
      var el = selector;
      for (var i = 0, len = el.length; i < len; i++) {
        el[i].onclick = fun.bind(el);
      }
  }
};

Setup the variable for your library:
var $ = function (selector) {
    return new DOM(selector);
};

NOTE I used a separate function to do the "class" just because I think $ should be kept basic and just an init function.
You could use this setup like:
$("#click-me").click(function(){
    $(this).animate({
            "opacity": 0
        }, 1000);
    });
});

EXAMPLE (JSFiddle)
This should give a little idea about how jQuery's syntax work. Of course, libraries don't necessarily have to be that complex. A library is just a collection of functions that make your life as a developer easier. Even a setup like the following could in the end be considered a library once you have a full collection of functions:
$ = {};
$.animate = function (selector, prop, times, callbacks) {
   var el = document.querySelectorAll(selector);
   var animate = function (element, props, time, callback) {
       callback = callback || function () {};
       time = time || 1000;
       var timers = {}, // store the different interval timers so that they can be cancelled
       calls = 0, // numbers of times the call would have been called
       nprops = 0; // number of properties
       for (var prop in props) {
           (function (prop) {
               var edit = prop == "scrollTop" ? element : element.style;
               var stepCounter = [],
                   customStep = props[prop],
                   curr = edit[prop],
                   lastStepPercent = curr == "" ? (prop == "opacity" ? 1 : 0) : curr,
                   measure = prop == "scrollTop" || prop == "opacity" ? "" : "px",
                   stepper = function () {
                       edit[prop] = stepCounter[0] + measure;
                       stepCounter.shift();
                   };
               if (props[prop].constructor == Number) customStep = [props[prop]];
               for (var step = 0, len = customStep.length; step < len; step++) {
                   var from = parseInt(lastStepPercent),
                       to = parseInt(customStep[step]),
                       small = to < from,
                       numOfSteps = small ? from - to : to - from, // get current number of frames
                       multi = 30 * Math.round(parseInt(time) / 1000),
                       by = numOfSteps / (25 + multi) * len; // the stepper number

                   if (from == to) {
                       break;
                   }
                   for (var i = from; small ? i >= to : i <= to; i += small ? -by : by) {
                       stepCounter.push(i);
                   }
                   stepCounter.push(to);
                   lastStepPercent = customStep[step];
               }
               stepper();
               timers[element + prop] = setInterval(function () {
                   stepper();
                   if (stepCounter.length == 0) {
                       clearInterval(timers[element + prop]);

                       calls++;
                       if (calls == nprops) {
                           callback.call(element);
                       }
                   }
               }, time / stepCounter.length);
               nprops++;
           })(prop);
       }
   };
   for (var i = 0; i < el.length; i++) {
       animate(el[i], prop, times, callbacks)
   };
}
$.animate("#id", {
    width: 0
}, 1000);

I used this relatively complex function just to note that a library can be a lot of work if you are attempting on developing something difficult. Anyways, You need to be able to be experienced with pretty advanced programming in JavaScript. In the end, it's not hard, as long as you know what you are trying to do and you have some logical experience in JavaScript. Of course i'm not an expert at JavaScript and there might be better architecture for a library, but I hope this helped.


Q:

Creating Persistent Drive Labels With UDEV Using /dev/disk/by-path

I have a new BackBlaze Pod (BackBlaze Pod 2.0).
It has 45 3TB drives and they when I first set it up they were labeled /dev/sda through /dev/sdz and /dev/sdaa through /dev/sdas.
I used mdadm to setup three really big 15 drive RAID6 arrays.
However, since first setup a few weeks ago I had a couple of the hard drives fail on me.  I've replaced them but now the arrays are complaining because they can't find the missing drives.  When I list the the disks...
ls -l /dev/sd*

I see that
/dev/sda
/dev/sdf
/dev/sdk
/dev/sdp

no longer appear and now there are 4 new ones...
/dev/sdau
/dev/sdav
/dev/sdaw
/dev/sdax

I also just found that I can do this...
ls -l /dev/disk/by-path/
total 0
lrwxrwxrwx 1 root root 10 Sep 19 18:08 pci-0000:02:04.0-scsi-0:0:0:0 -> ../../sdau
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-0:1:0:0 -> ../../sdb
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-0:2:0:0 -> ../../sdc
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-0:3:0:0 -> ../../sdd
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-0:4:0:0 -> ../../sde
lrwxrwxrwx 1 root root 10 Sep 19 18:08 pci-0000:02:04.0-scsi-2:0:0:0 -> ../../sdae
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-2:1:0:0 -> ../../sdg
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-2:2:0:0 -> ../../sdh
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-2:3:0:0 -> ../../sdi
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-2:4:0:0 -> ../../sdj
lrwxrwxrwx 1 root root 10 Sep 19 18:08 pci-0000:02:04.0-scsi-3:0:0:0 -> ../../sdav
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-3:1:0:0 -> ../../sdl
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-3:2:0:0 -> ../../sdm
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-3:3:0:0 -> ../../sdn
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:02:04.0-scsi-3:4:0:0 -> ../../sdo
lrwxrwxrwx 1 root root 10 Sep 19 18:08 pci-0000:04:04.0-scsi-0:0:0:0 -> ../../sdax
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:04:04.0-scsi-0:1:0:0 -> ../../sdq
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:04:04.0-scsi-0:2:0:0 -> ../../sdr
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:04:04.0-scsi-0:3:0:0 -> ../../sds
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:04:04.0-scsi-0:4:0:0 -> ../../sdt
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:04:04.0-scsi-2:0:0:0 -> ../../sdu
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:04:04.0-scsi-2:1:0:0 -> ../../sdv
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:04:04.0-scsi-2:2:0:0 -> ../../sdw
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:04:04.0-scsi-2:3:0:0 -> ../../sdx
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:04:04.0-scsi-2:4:0:0 -> ../../sdy
lrwxrwxrwx 1 root root  9 Sep 19 18:08 pci-0000:04:04.0-scsi-3:0:0:0 -> ../../sdz

I didn't list them all....you can see the problem above.  They're sorted by scsi id here but sda is missing...replaced by sdau...etc...
So obviously the arrays are complaining.  Is it possible to get Linux to reread the drive labels in the correct order or am I screwed?
My initial design with 15 drive arrays is not ideal.  With 3TB drives the rebuild times were taking 3 or 4 days....maybe more.  I'm scrapping the whole design and I think I am going to go with 6 x 7 RAID5 disk arrays and 3 hot spares to make the arrays a bit easier to manage and shorten the rebuild times.  But I'd like to clean up the drive labels so they aren't out of order.  I haven't figured out how to do this yet.
Does anyone know how to get this straightened out?
Thanks,
Matt

A:

My Solution
I'm not sure it's the best solution, and I'm still interested in other answers, but here's what I did.
I could not figure out how to force it to map based on the SCSI path (e.g. pci-0000:02:04.0-scsi-0:0:0:0).  So instead I am mapping based on the UUID, which is the drive models and serial numbers.  I just have to remember that when I swap drives I have to update the UDEV entries.

Finding the UUIDs
Used entries from the following commands to identify the current drive names, what SCSI PATH they were mapped to, and what their UUIDs were.
# ls -l /dev/disk/by-path
# /lib/udev/scsi-id -gu /dev/sdX

Created UDEV entries
I put entries like this into a new file I called /etc/udev/rules.d/59-persistent-disk.rules.  There are three rows of Three backplanes each so I did something like this.
# ROW 1 BACKPLANE 1
KERNEL=="sd*", SUBSYSTEM=="block", PROGRAM=="/lib/udev/scsi_id --whitelisted --replace-whitespace /dev/$name", RESULT=="1ATA_WDC_WD30EFRX-68AX9N0_WD-WMC1T0076306", SYMLINK+="pci24scsi00"
KERNEL=="sd*", SUBSYSTEM=="block", PROGRAM=="/lib/udev/scsi_id --whitelisted --replace-whitespace /dev/$name", RESULT=="1ATA_WDC_WD30EFRX-68AX9N0_WD-WMC1T0073437", SYMLINK+="pci24scsi01"
KERNEL=="sd*", SUBSYSTEM=="block", PROGRAM=="/lib/udev/scsi_id --whitelisted --replace-whitespace /dev/$name", RESULT=="1ATA_WDC_WD30EFRX-68AX9N0_WD-WMC1T0073085", SYMLINK+="pci24scsi02"
KERNEL=="sd*", SUBSYSTEM=="block", PROGRAM=="/lib/udev/scsi_id --whitelisted --replace-whitespace /dev/$name", RESULT=="1ATA_WDC_WD30EFRX-68AX9N0_WD-WMC1T0072374", SYMLINK+="pci24scsi03"
KERNEL=="sd*", SUBSYSTEM=="block", PROGRAM=="/lib/udev/scsi_id --whitelisted --replace-whitespace /dev/$name", RESULT=="1ATA_WDC_WD30EFRX-68AX9N0_WD-WMC1T0071564", SYMLINK+="pci24scsi04"

# ROW 1 BACKPLANE 2
KERNEL=="sd*", SUBSYSTEM=="block", PROGRAM=="/lib/udev/scsi_id --whitelisted --replace-whitespace /dev/$name", RESULT=="1ATA_WDC_WD30EFRX-68AX9N0_WD-WMC1T0077571", SYMLINK+="pci24scsi20"
KERNEL=="sd*", SUBSYSTEM=="block", PROGRAM=="/lib/udev/scsi_id --whitelisted --replace-whitespace /dev/$name", RESULT=="1ATA_WDC_WD30EFRX-68AX9N0_WD-WMC1T0077346", SYMLINK+="pci24scsi21"
KERNEL=="sd*", SUBSYSTEM=="block", PROGRAM=="/lib/udev/scsi_id --whitelisted --replace-whitespace /dev/$name", RESULT=="1ATA_WDC_WD30EFRX-68AX9N0_WD-WMC1T0074773", SYMLINK+="pci24scsi22"
KERNEL=="sd*", SUBSYSTEM=="block", PROGRAM=="/lib/udev/scsi_id --whitelisted --replace-whitespace /dev/$name", RESULT=="1ATA_WDC_WD30EFRX-68AX9N0_WD-WMC1T0071238", SYMLINK+="pci24scsi23"
KERNEL=="sd*", SUBSYSTEM=="block", PROGRAM=="/lib/udev/scsi_id --whitelisted --replace-whitespace /dev/$name", RESULT=="1ATA_WDC_WD30EFRX-68AX9N0_WD-WMC1T0076264", SYMLINK+="pci24scsi24"
.......etc

Creating the Arrays
Now that I have persistent device names I created five 9 drive arrays (RAID5 with one spare) as follows.  I used 1 drive per backplane in each array so I could lose an entire backplane (or even two) and the arrays would stay running.  Performance may suffer for doing it this way, but I bought this for archiving and offsite backups so performance isn't the primary concern.
mdadm --create --verbose /dev/md0 --level=5 --raid-devices=8 --spare-devices=1 /dev/pci24scsi00 /dev/pci24scsi20 /dev/pci24scsi30 /dev/pci44scsi00 /dev/pci44scsi20 /dev/pci44scsi30 /dev/pci64scsi00 /dev/pci64scsi20 /dev/pci64scsi30
mdadm --create --verbose /dev/md1 --level=5 --raid-devices=8 --spare-devices=1 /dev/pci24scsi01 /dev/pci24scsi21 /dev/pci24scsi31 /dev/pci44scsi01 /dev/pci44scsi21 /dev/pci44scsi31 /dev/pci64scsi01 /dev/pci64scsi21 /dev/pci64scsi31
mdadm --create --verbose /dev/md2 --level=5 --raid-devices=8 --spare-devices=1 /dev/pci24scsi02 /dev/pci24scsi22 /dev/pci24scsi32 /dev/pci44scsi02 /dev/pci44scsi22 /dev/pci44scsi32 /dev/pci64scsi02 /dev/pci64scsi22 /dev/pci64scsi32
mdadm --create --verbose /dev/md3 --level=5 --raid-devices=8 --spare-devices=1 /dev/pci24scsi03 /dev/pci24scsi23 /dev/pci24scsi33 /dev/pci44scsi03 /dev/pci44scsi23 /dev/pci44scsi33 /dev/pci64scsi03 /dev/pci64scsi23 /dev/pci64scsi33
mdadm --create --verbose /dev/md4 --level=5 --raid-devices=8 --spare-devices=1 /dev/pci24scsi04 /dev/pci24scsi24 /dev/pci24scsi34 /dev/pci44scsi04 /dev/pci44scsi24 /dev/pci44scsi34 /dev/pci64scsi04 /dev/pci64scsi24 /dev/pci64scsi34

Using LVM to Create VGs and LVs
These were my LVM steps to create the volumes so they could be iSCSI mounted remotely.
PVCREATE
pvcreate /dev/md0
pvcreate /dev/md1
pvcreate /dev/md2
pvcreate /dev/md3
pvcreate /dev/md4

VGCREATE
vgcreate VgArr0 /dev/md0
vgcreate VgArr1 /dev/md1
vgcreate VgArr2 /dev/md2
vgcreate VgArr3 /dev/md3
vgcreate VgArr4 /dev/md4
vgcreate VgArr5 /dev/md5

LVCREATE for iSCSI
Create the LVs but do not format or mount the volumes. They get formatted/mounted remotely
lvcreate -L100%FREE VgArr0 -n LvISCSI0

iSCSI
Edit the /etc/iet/ietd.conf and /etc/iet/initiators.conf
Map the iSCSI LUNs remotely on the other host


Q:

Is it correct to say "These terms are less using in nowadays"?

I presented 4 groups of biological terms, while just 2 of them are used in nowadays, and the 2 other groups are less. So when I refer to the other 2 groups, can I say about them the following sentence? (For me it sounds a little weird and that's why I'm asking this question)

"These terms are less using in nowadays"

A:

These terms are less using in nowadays.

This is not idiomatic English.

are using is an active form of the verb use, and implies that the subject (terms, in this example) performs the action. What you want is the passive form: BE + past participle.

These terms are less used

nowadays is an adverb, not a noun, so it cannot stand as the object of a preposition like in. It means in these days all by itself.

These terms are less used nowadays.

Adverbs and short adverbial phrases of frequency (often, very rarely, usually) are usually placed where you have placed less, after the first auxiliary verb. But comparatives (more, less) are usually placed after the lexical (main) verb and its complements.

These terms are used less nowadays.
  People use these terms less nowadays.

This is because less and more often introduce longer comparative constructions with than which would make the syntactic core harder to parse if placed in the ordinary position.

∗ These terms are less than they were ten years ago used nowadays.
okThese terms are used less nowadays than they were ten years ago.

A:

The passive participial construction is formed nowadays with is|are|was|were being plus the past participle
...are being used...
Blood-letting was being used to lower fever as late as the mid-19th century. It was discredited in the late 19th century and is not being used nowadays.


Q:

back up my ubuntu partition for quick restore

I have recently set up my laptop for my ubuntu environment. Now that it's the way that I want it, I want to back it up so if something happens, I can wipe the hard drive, re-install Ubuntu from the original CD, then restore from backup to put everything back the way it is.
So here's the list of folders in my root directory of my hard drive.
bin    dev   initrd.img      lib32       media  proc  sbin     sys  var
boot   etc   initrd.img.old  lib64       mnt    root  selinux  tmp  vmlinuz
cdrom  home  lib             lost+found  opt    run   srv      usr  vmlinuz.old

I'm thinking the things I need to backup are:
bin
boot
etc
home
initrd.img
lib
lib32
lib64
opt--this is where I install my development tools like eclipse and tomcat
sbin
usr
vmlinuz

Anything else?

A:

Clonezilla does a great job... http://clonezilla.org/


Q:

Is there a way to verify a valid path / file name?

Is there a way to verify a valid path / file name?  The file name is known as it is given to the customer.  It is unknown where the .exe and other file are placed.

A:

To check whether a file exists at a specified path, use System.IO.File.Exists(string path):
if (File.Exists(pathFileName))
{
    ...
}
else
{
    ...
}

To check whether a path or file name is valid (I.E. contains no illegal characters) use System.IO.Path.GetInvalidPathChars() or System.IO.Path.GetInvalidFileNameChars():
if (Path.GetInvalidFileNameChars().Any(c => pathFileName.Contains(c)))
{
    ...
}


Q:

How can I convert string into date?

I have two strings:
date1 = 3-5-2014;
date2 = 4-2-2010;
I have to convert them in date and then compare them. I want the same format of date as in strings i.e., dd-mm-yyyy. How it can be done?

A:

NSString *string=@"03-05-2014";
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [dateFormatter dateFromString:string];

enjoy...


Q:

Dvorak keyboard layout on stock Android

I just updated my Nexus 7 to Jelly-Bean 4.2, and it has the swipe keyboard which is awesome. I want to keep this feature of the stock android keyboard, but with the Dvorak keyboard layout. Is this possible?
I'm NOT looking for a replacement. I like the built in keyboard, I just am wondering if it's possible to change the stock keyboard layout.
Also, if it's easy to switch between Dvorak and qwerty that's preferable :-)

A:

This is supported in stock android.
Settings -> Languages & Input -> Android Keyboard (Settings icon) -> Advanced settings -> Custom input styles -> Add style -> Set Language & Layout
Then to activate this style, go back to the keyboard settings and go to the input languages and uncheck "use system language" then check the languages you want. :-)

A:

I believe it is possible. Choose the layout from SETTINGS > LANGUAGE AND INPUT and the settings button on the side of the ANdroid keyboard.
You might also try long-pressing the SPACE bar on the keyboard.
This page does mention that Jelly Bean has in-built support for DVORAK.


Q:

Adding header to an ascii catalogue

I would like to add a header to an ascii file using bash script. What is the shortest way to do it without making temporary text file?

A:

You can try this way
sed '1 i\Header' FileName

Example:
seq 5 | sed '1 i\\tHeader'

Output:
    Header
1
2
3
4
5


Q:

Finding residential buildings with overpass-turbo?

I am looking to find all residential buildings with overpass-turbo.eu.
I am trying to use the following query:
way
  ["building"~"residential|house|terrace|detached|apartments"]
  ({{bbox}});
(._;>;);
out;

However, not many residential buildings are found in this way.
Which tags should be used to find the buildings through overpass-turbo, which may be multi-use but also residential (residential and commercial, or residential and retail...)?

A:

Not all buildings have a corresponding typology tag. Many are just tagged with building=yes (currently 81% of all buildings). Some might have an additional building:use=residential tag.
Remember that the OSM database is primarily populated by volunteers. Some are too "lazy" to enter the building topologies, others just don't know or care about it. Feel free to improve the situation by contributing to OSM.


Q:

Glossy and no reflection - only shadow

Hi. I have square and ball. Square is Glossy BSDF material, and ball is only ball. I have no reflection in square and it is problem. I want reflection effect.

A:

Looks like amount of light bounces for Glossy rays in your scene under the Light Paths rollout is set to 0 and looks like this:

This will make Cycles not to take into account rays which bounced from camera to the surface with only Glossy shader (e.g. plane supposed to be the floor also has glossy added to material nodes but it's mixed with Diffuse shader and Fresnel as the factor, so blackish reflection will be visible under certain angle).
Increase bounces to something more than 0, 8 by default and glossy reflections should appear.

Another possibility - Clamp Indirect under Sampling rollout is set to something really slow, like 0.0001. Then any reflections in the scene will be also black.

These values depend on the scene but generally you don't want them to be less than 1.


Q:

Is commutativity needed in the proof of division algorithm?

I found that my 2 textbooks and other answers state this theorem for commutative ring:

From textbook Algebra by Saunders MacLane and Garrett Birkhoff.

From textbook Analysis 1 by Herbert Amann and Joachim Escher.

In this answer, @Bill Dubuque also states for commutative ring.

For polynomials over any commutative coefficient ring, the high-school polynomial long division algorithm works to divide with remainder by any monic polynomial...

In this answer, @Bill Dubuque also states for commutative ring.

Yes, your intuition correct: the Polynomial Factor Theorem works over any commutative ring since we can always divide (with remainder) by a polynomial that is monic i.e. lead coef $=1$ (or any unit = invertible element). Ditto for the equivalent Polynomial Remainder Theorem - see below.

I have re-read the proofs in my 2 textbooks and can not found where the commutativity is used. As such, is commutativity needed in the proof of division algorithm?

A:

If $K$ is noncommutative there's a bit of ambiguity in what you mean by $K[x]$; if you mean that $x$ is central, then I suppose the argument goes through fine, but I'm not aware of any applications of it.
Note that it does not follow that polynomials over $K[x]$ have unique factorization. As an explicit example, if $K = \mathbb{H}$ is the quaternions, then the polynomial $x^2 + 1$ admits inequivalent factorizations
$$x^2 + 1 = (x + i)(x - i) = (x + j)(x - j) = (x + k)(x - k).$$
The problem is that because we need $x$ to be central, we can't substitute any non-central element for $x$! So the usual argument where we substitute a root no longer applies.


Q:

Compare XPATH attributes

Why does my code not work? I basically have to check if the person is mentioned in "abgebildet" (so i the compared emails but it does not work for some reason)
socialnetwork/personen/person[@email = person/photos/photo/abgebildet/@personemail]/@vorname

XML:
<socialnetwork>
<personen>
    <person email="H.Mueller@yahoo.com" vorname="Hannah" nachname="Müller" geburtsdatum="1991-02-02">
        <photos>
            <photo url="http://www.flickr.com/myphoto/H.Mueller/147.jpg" titel="Photo Number 147" beschreibung="This is a very nice picture taken by H.Mueller@yahoo.com">
                <abgebildet personemail="F.Kaiser@yahoo.com"/>
                <abgebildet personemail="Laura.Heinrich@gmail.com"/>
                <abgebildet personemail="Lucas.Bergmann@sms.at"/>
                <abgebildet personemail="M.Krause@sms.at"/>
                <abgebildet personemail="Neele.Schmitt@yahoo.com"/>
                <abgebildet personemail="P.Winkler@gmx.net"/>
                <abgebildet personemail="S.Hofmann@live.at"/>
                <abgebildet personemail="S.Sommer@gmx.net"/>
            </photo>

A:

Update your XML to include a possible match, because as @JackFleeting comments, no @personemail matches @email.
Update your XML to include a @vorname, because it has no such attribute currently, or drop @vorname from your XPath.
Change your predicate from
person[@email = person/photos/photo/abgebildet/@personemail]

to
person[@email = photos/photo/abgebildet/@personemail]

because the current node is already a person element within the predicate.


Q:

What's the difference between mixture and admixture?

In French the translation is the same but I wonder why in English you have two words for this ? I think that's because there is a slight difference between these two words but I don't get what it is !

A:

You now find a lot of people using admixture as a synonym of mixture; it is so widespread that this cannot be regarded as an error.
But the classic use of admixture is narrower: the prefix ad- (Latin = “to, toward”) implies that a new component or ingredient is brought “to” an original substance and mixed “into” it. We might for instance speak of the classic Manhattan cocktail as

rye whiskey with an admixture of vermouth and bitters.


Q:

How can I create spectograms from .wav files in python for audio classification problem

I want to use spectrograms for audio files classification with CNN. The problem is that my audio files have different lengths (between 2 seconds and 17 seconds) and when I generate the spectograms. they all have the same size which means that the spectrum is widen for the shorter audio files. How can I generate the spectograms so that the signal is not altered?
I tried using the matplotlib.pyplot library for creating the spectrograms but all the images are 640 x 480.
This is the code I used
import matplotlib.pyplot as plt
from scipy.io import wavfile

samplingFrequency, signalData = wavfile.read('dia0_utt0.wav')

plt.title('Spectrogram')

plt.specgram(signalData,Fs=samplingFrequency,NFFT=512)

plt.xlabel('Time')

plt.ylabel('Frequency')

plt.savefig('fig11.png')

I don't know how to obtain spectrograms of variable dimensions based on their length, or to have them of same dimensions but filling the rest until the max length with no information.
For example, if I have a 3 seconds file and the max length is 17 seconds then generate the spectrogram for 3 seconds and fill the rest of the spectrogram with no noise to make it of 17 seconds.

A:

You can use the matplotlib.pyplot.xlim and matplotlib.pyplot.ylim functions to set the limits of both your axes.
[EDITED] In the example below, I load a 3 seconds long wav file of the Cantina Band song downloaded from this website:
import matplotlib.pyplot as plt
from scipy.io import wavfile

samplingFrequency, signalData = wavfile.read('C:/Users/Sheldon/Desktop/WAVEEXAMPLE/CantinaBand3.wav')

plt.title('Spectrogram')
Pxx, freqs, bins, im = plt.specgram(signalData,Fs=samplingFrequency,NFFT=512)
plt.xlabel('Time')
plt.ylabel('Frequency')
plt.xlim(left=0,right=17)

plt.savefig('C:/Users/Sheldon/Desktop/WAVEEXAMPLE/fig11.png')

This script yields the following image:

Had I not specified plt.xlim(left=0, right=17), the output figure would have ranged between 0 and 3 seconds:


Q:

htaccess get code and redirect with php

Ex:
If we entered these url (Like This site)
http://stackoverflow.com/questions/10139779/ or http://stackoverflow.com/questions/10139779
Its automatically redirect to this url http://stackoverflow.com/questions/10139779/handling-get-with-htaccess
I want to get this code (10139779) from url and redirect to full url. Someone go to full url how to get this code (10139779)
Edit :
I created htaccess file like this.
<Files .htaccess>
order allow,deny
</Files>

Options +FollowSymLinks
RewriteEngine On

RewriteRule ^(\w+)$ ./load.php?code=$1

Now i want to give video title to url after video id  Like this www.example.com/16056/video-title
load.php

<?php
echo $_GET['code'];

//I can get video title from php then how to give to url it?
?>

I can get code this from www.example.com/16566 but i can't get code this from this url www.example.com/16566/video-title
after id / link was doesnt work. how to fixed it

A:

Send out a location header for the correct URL. (load.php:)
<?php
    header('Location: /videos/'.$_GET['code'].'/'.getTheVideoTitle($_GET['code']));
?>

There is nothing you can do in .htaccess to get the video title, so php must do it.
Also, for .htaccess:
RewriteRule ^(\w+)$ ./load.php?code=$1

Should be:
RewriteRule ^(\w+)/*$ ./load.php?code=$1

This makes it match slash(s) after the URL. If you also want it to match the title after the URL, make it:
RewriteRule ^(\w+) ./load.php?code=$1


Q:

Is $U+V$ equivalent to $U \cup V$?

$U$ und $V$ are subspaces of a $R^n$
Is $U+V$ equivalent to $U \cup V$?
Additional question:
If I compare basis' instead of subspaces it would be correct? There is a basis(U+V), that is equivalent to a basis($U \cup V$)
?

A:

Note that in general $U \cup V$ isn't a subspace: If there are $u \in U \setminus V$ and $v \in V \setminus U$ then $u+v \not\in U \cup V$. Hence $U \cup V$ is a subspace iff $U \subseteq V$ or $ V \subseteq U$.
$U+V$ is by definition the smallest subspace containing $U$ and $V$, that is $U+V = {\rm span}\, (U \cup V)$.


Q:

Dropdown menu items displayed to the right and not down

I need help with my CSS. I have the following menu:

.h-menu .menu-item .dropdown-content a { display: none;}
.h-menu .menu-item:hover .dropdown-content a {
    display: block;
}

.h-menu .menu-item a {
  display:block;
  float: left;
    text-decoration: none;
  margin: 1em;
}

      Menu Item 1

      Menu Item 2

        Sub-item 1
        Sub-item 2
        Sub-item 3

      Menu item 3

What happens is when I hover over the second menu item, the sub items are displayed to the right and not down. How can I fix it?
Also I want to use CSS to alight the menu to the right. Can someone please help?

A:

Make the main menu inline block elements. Then remove the float on the "a" tag.
See example below.
or just remove the float attribute from the a tag and put it on the menu divs

.h-menu {
text-align: right;
}

.menu-item {
  display: inline-block;
  vertical-align: top;
  border: 1px red solid;/**Remove for debbugging purposes**/
}

.h-menu .menu-item .dropdown-content a { display: none;}
.h-menu .menu-item:hover .dropdown-content a {
    display: block;
}

.h-menu .menu-item a {
  display:block;
  /**float: left**/
  text-decoration: none;
  margin: 1em;
}

      Menu Item 1

      Menu Item 2

        Sub-item 1
        Sub-item 2
        Sub-item 3

      Menu item 3


Q:

You need me. What am I?

I am usually roseate,
But not always.
I am sometimes inconsiderate;
But you need me.
I protect my jewel
That sometimes moves
Because without it;
I cannot confess,
To my lover;
All the love I have prepared.
After I confess;
I part,
And I love.

(This is my first riddle, so it might be easy or a bit off. If it is, please tell me how to improve it!)

A:

Are you ...

Lips?

I am usually roseate,
But not always.

Lips are usually pink/rosy, but may be colored with lipstick

I am sometimes inconsiderate;

A cruel expression

But you need me.

Necessary for proper eating and speaking

I protect my jewel
That sometimes moves

The jewel is the tongue

Because without it; I cannot confess,
To my lover;
All the love I have prepared.

You can't confess your love without a tongue :(

After I confess;
I part,
And I love.

Lips parting for a kiss

A:

Not sure, but I like this answer anyway:

An eggshell

...
I am usually roseate,
But not always.

Eggshells are usually pinkish in colour, (the typical chicken egg), but other birds lay different coloured eggs.

I am sometimes inconsiderate;
But you need me.

Without the eggshell, the bird/reptile inside would die

I protect my jewel
That sometimes moves

The yolk is the golden jewel, and occasionally when fertilised it moves as it becomes an embryo

Because without it; I cannot confess,
To my lover;
All the love I have prepared.

The eggshell allows the embryo to mature

After I confess;
I part,
And I love.

When it confesses it breaks apart releasing the egg or the yolk to the world.

not sure but I like that idea :)

A:

As OP has already accepted an answer and it fits perfect, just adding an alternate answer to this.
Is it

Rose

I am usually roseate,
But not always.

The flower rose is in rose color as the name implies but also can be seen in colors other than rose.

I am sometimes inconsiderate;
But you need me.

Rose prickles can hurt you while plucking rose, still you may need it.

I protect my jewel
That sometimes moves

Refers to the stigma of rose which plays major role in reproduction and it is inside the petals protection.

Because without it; I cannot confess,
To my lover;

Normally nobody use rose or any other flowers without it's stigma because without that the flower won't have it's natural beauty.

All the love I have prepared.
After I confess;
I part,
And I love.

cutting the rose from it's stem and giving it to the love.


Q:

HTML version of LibGDX game doesn't show any logging

I am having trouble getting a html version of my programme to appear.
I am using LibGDX 1.3.1 and running in Java it works fine.
I uploaded the game here:
http://www.darkflame.co.uk/MeshExplorer/index.html
The libgdx loading bar appears and finishes - and in Chromes network tag I can see assets loading.
However, nothing appears other then the rectangle of the expected game size.
Most confusingly for me though, I dont see any crashes or logs from my code.
That is, there is nothing after "SoundManager 2 loaded (OK) "
Given that the first lines of my main core class are:
   game=this;
   font = new BitmapFont();
   batch = new SpriteBatch();

   Gdx.app.log(logstag, "loading..");

I expected at least to see "loading.."
I even added some gwt logs to html launcher
 public class HtmlLauncher extends GwtApplication {
   static Logger Log = Logger.getLogger("HtmlLauncher");

    @Override
    public GwtApplicationConfiguration getConfig () {
       Log.info("GwtApplicationConfiguration");
      System.out.print("GwtApplicationConfiguration");
            return new GwtApplicationConfiguration(640, 480);
    }

    @Override
    public ApplicationListener getApplicationListener () {
          Log.info("test, returning class ME() ");
          System.out.print("test, returning class ME() ");
            return new ME();
    }

}

again, nothing.
I am at a lose how to disorganize this problem further.
It just seems like libgdx isn't even attempting to run my code.

A:

The default logging level in the html target is LOG_ERROR. You would not see any Gdx.app.log messages unless you set the logging level to LOG_INFO.
Calling Gdx.app.setLogLevel(LOG_INFO) in your getConfig or getApplicationListener methods should do the trick.


Q:

Get a list of outlook shared contacts using vb.net

I'm writing a program and i need to get the list of my shared contacts from my outlook. I wrote a code that returns a list of my contacts (not the shared).
how can I get the shared contacts?
this is my code:
Private Sub GetListOfContacts(cmb As ComboBox)
    Dim OutlookApp As Outlook.Application = New Outlook.Application()
    Dim contactItemsList As List(Of Outlook.ContactItem) = Nothing
    Dim folderItems As Outlook.Items = Nothing
    Dim folderSuggestedContacts As Outlook.MAPIFolder = Nothing
    Dim ns As Outlook.NameSpace = Nothing
    Dim folderContacts As Outlook.MAPIFolder = Nothing
    Dim itemObj As Object = Nothing
    Dim contact As Outlook.ContactItem

    Try
        contactItemsList = New List(Of Outlook.ContactItem)()
        ns = OutlookApp.GetNamespace("MAPI")
        'getting items from the Contacts folder in Outlook
        folderContacts = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts)
        folderItems = folderContacts.Items
        For i As Integer = 1 To folderItems.Count
            itemObj = folderItems(i)
            If (TypeOf (itemObj) Is Outlook.ContactItem) Then
                contact = itemObj
                cmb.Items.Add(contact.FullName)
            Else
                Marshal.ReleaseComObject(itemObj)
            End If
        Next

    Catch ex As Exception

Thanks!

A:

Use Namespace.GetSharedDefaultFolder and pass the Recipient object retrieved from Namespace.CreateRecipient.
Dim recip as Outlook.Recipient
...
recip = ns.CreateRecipient("SomeExchangeUserName")
folderContacts = ns.GetSharedDefaultFolder(recip, Outlook.OlDefaultFolders.olFolderContacts)


Q:

AngularJS : watching an expression consisting of variable and function

everyone! Thanks in advance!
I have the following problem: I want to watch an input field's attribute, which at the same time is my directive's name, to focus and select the value when
a) the area the input field is in was activated or when
b) and error from the server occured.
Here the code of the input field:
<input type="email"
    data-focus-and-select="areas.contactInformationEditEmail || hasServerErrorsEmail()" />

Here the code of the controller function:
$scope.hasServerErrorsEmail = function() {
    return !!($scope.notifications.errors.email.empty ||
            $scope.notifications.errors.email.invalid ||
            $scope.notifications.errors.email.illegal ||
            $scope.notifications.errors.email.blacklisted ||
            $scope.notifications.errors.email.conflict);
};

If an server error occurred, one of these notification errors is set to true.
Here the code of the directive:
angular.module('myApp.directive').directive('focusAndSelect', function() {
    'use strict';
    return {
        scope: { focusAndSelect: '=' },
        link: function(scope, element) {
            scope.$watch('focusAndSelect', function(newValue) {
                if (newValue && !element.hasClass('ng-hide')) {
                    element[0].focus();
                    element[0].setSelectionRange(0, element[0].value.length);
                }
            });
        }
    };
});

There are three scenarios:
1) The "focus and select" works when I change the form into editable mode, so that areas.contactInformationEditEmail is set to true.
2) The "focus and select" won't work when I receive an server error. The input field is not focused and selected.
3) But when I remove the areas.contactInformationEditEmail from the expression areas.contactInformationEditEmail || hasServerErrorsEmail(), the "focus and select" works for the error receiving input field.
I have no idea. Is it maybe a problem to watch and variable and and function call at once?
Thanks for your help.

A:

when you use '=' in the isolated scope of the directive it binds to a property in the parent scope, it's not possible to bind to an evaluated expression.
try this instead:
<input type="email"
    data-focus-and-select="{{areas.contactInformationEditEmail || hasServerErrorsEmail()}}" />

and your directive:
angular.module('myApp.directive').directive('focusAndSelect', function() {
    'use strict';
    return {
        scope: { focusAndSelect: '=' },
        link: function(scope, element) {
            scope.$watch('focusAndSelect', function(newValue) {
                if (newValue && !element.hasClass('ng-hide') && scope.$eval(newValue)) {
                    element[0].focus();
                    element[0].setSelectionRange(0, element[0].value.length);
                }
            });
        }
    };
});

you need the $eval because the value will be a String and you want to get it's boolean value.
here's a simplified jsfiddle to demonstrate it.


Q:

Same "controller as" name in angular js directive breaks function in parent controller

I've a controller with some items for ng-repeat and each item should get a random color so I use ng-style with a function in that controller called randColor(...).
app.controller('TestController', function() {
    var vm = this;

    vm.items = [ { name: 'item 1' } , { name: 'item 2'} ];

    vm.randColor = function (item) {
        if (!item) {
            return 'red';
        }
        else if (!item.color)
        {
            var color = 'rgb('
                + _.random(0, 255) + ','
                + _.random(0, 255) + ','
                + _.random(0, 255) + ')';
            item.color = color;
        }

        return item.color;
    };
});

I'm using the "controller as" syntax for this and I usually always use vm as the short name of my controllers. I've never had a problem with doing so, even when naming "sub"-controllers the same way.
But now I've tried to do the same thing with a directive and suddenly my randColor(...) function stopped working.
Here is a plunker of my problem.
HTML:

Without Directive (controllerAs: 'vm')

{{ item.name }}

{{ vm.title }}

Test Directive Alternative (controllerAs: 'directiveVM')

{{ item.name }}

            <test-directive-alt></test-directive-alt>

Test Directive (controllerAs: 'vm')

{{ item.name }}

            <test-directive></test-directive>

JS:
app.controller('TestDirectiveController', function() {
    var vm = this;

    vm.title = 'test';
});

app.directive('testDirective', function() {
        return {
            restrict: 'EA',
            controller: 'TestDirectiveController',
            controllerAs: 'vm',
            bindToController: true,
            template: '
{{ vm.title }}
'
        };
    });

app.directive('testDirectiveAlt', function() {
        return {
            restrict: 'EA',
            controller: 'TestDirectiveController',
            controllerAs: 'directiveVM',
            bindToController: true,
            template: '
{{ directiveVM.title }}
'
        };
    });

Output:

I know I could just use a different name for the controller as in my example, but why does this happen in the first place?
And is there a way to get it working with the same name?

A:

The problem you're facing seems to be related to the fact that the directive is being executed on the same scope as the scope where the controller is defined as vm.
What you need to do is to create a new scope scope: {} within the directive.
app.directive('testDirective', function() {
        return {
            restrict: 'EA',
            scope: {},
            controller: 'TestDirectiveController',
            controllerAs: 'vm',
            bindToController: true,
            template: '
{{ vm.title }}
'
        };
    });

With that, the controllerAs should create a new vm attribute in the directive scope.


Q:

Date.getTime() gives two different values for same timestamp

I have two variables. weekStartDate and startDate. they both hold essentially the same timestamp:
this.startDate  Date {Mon Mar 26 2012 00:00:00 GMT+0530 (IST)}
this.weekStartDate   Date {Mon Mar 26 2012 00:00:00 GMT+0530 (IST)}

the problem is: when I try to getTime(), they show a slightly different value:
this.startDate.getTime()    1332700200000
this.weekStartDate.getTime()    1332700200506

how can i fix this?

A:

The difference is 506 milliseconds. The number of milliseconds isn’t displayed when you call toString() on a Date object, so anything more precise than seconds will go unnoticed unless you compare the numeric value.
To reset the milliseconds to 0, use:
this.weekStartDate.setMilliseconds(0);


Q:

Accessibility of JavaScript on small screen mobile devices?

Im working on a mobile optimised site. Im using media queries to detect the screen size and the majority of the content is still shown just formated differently.
The site has some JavaScript reliant interactive tools. What if any are the accessibility concerns for using JavaScript with mobile devices?
On desktop, non JavaScript users see a static list of the same information the interactive tool uses. I was thinking of the same solution for the mobile version but I guess im interested in more general answers for other situations as Ive not ready anything about accessibility and JavaScript specific to mobile.
Thanks

A:

I would say the same rules apply wouldn't they? Some users may have js turned off, you never know.
Mobile or not, it's still on the web and needs to work regardless of js.


Q:

Wpf shared image memory

I want to optimize the memory usage in my WPF app.
I want to load from the disk an jpg image and show it with its real size.
And then I want to show 5 cropped square section of the original image loaded from the disk.
(No resize is applied on any image).
I want to do all this by loading the original image once and sharing that data among the image controls, in such a way that no memory is wasted and all controls fetch data from the same memory location.
I tried by using a memory stream object but in the end due to some convertions between bitmap and bitmapimage I ended up copying the data.

A:

I found an interesting way to crop an image from a BitmapImage here that I think will solve your problem. Doing it this way, you can display all of your images just using a single BitmapImage
In your xaml your full resolution image would just be a regular image element, but your cropped images would be a rectangle element using an image brush with a specific viewbox. Just define the rectangle with the height and width of the cropped image that you want, and then the viewbox is defined as "x y width height" (in my example it is "10 20 100 200") and remember that x starts at 0 for left and is positive moving right, and y starts at 0 for the top and is positive moving down.
    <Image Source="{Binding Image}"></Image>
    <Rectangle Height="200" Width="100">
        <Rectangle.Fill>
            <ImageBrush ViewboxUnits="Absolute" Viewbox="10,20,100,200" ImageSource="{Binding Image}"></ImageBrush>
        </Rectangle.Fill>
    </Rectangle>

Note that the binding for the Image and the ImageBrush are the same, so you only need to define Image once, and it is used across both elements.


Q:

Why was Edward immune to papercut and not Jasper?

How could Edward attend a human school (where paper cuts; and other skin damage from fights and sports is an absolutely everyday activity); if a small papercut with a single drop of blood on Bella drove Jasper totally insane with bloodlust?
For that matter, why did Edward not try to go for Bella the same way Jasper did; and protected her instead?

I took the little package, rolling my eyes at Edward while I stuck my finger under the edge of the paper and jerked it under the tape.
"Shoot," I muttered when the paper sliced my finger; I pulled it out to examine the damage. A single drop of blood oozed from the tiny cut.
It all happened very quickly then.
"No!" Edward roared.
He threw himself at me, flinging me back across the table. It fell, as I did, scattering the cake and the presents, the flowers and the plates. I landed in the mess of shattered crystal.
Jasper slammed into Edward, and the sound was like the crash of boulders in a rock slide.
There was another noise, a grisly snarling that seemed to be coming from deep in Jasper's chest. Jasper tried to shove past Edward, snapping his teeth just inches from Edward's face.
Emmett grabbed Jasper from behind in the next second, locking him into his massive steel grip, but Jasper struggled on, his wild, empty eyes focused only on me.
(Twilight: New Moon)

Canon answers only please.

A:

The simple answer would be that Jasper was a savage vampire very unlike Edward & the other Cullens.(The details about Jasper's past are covered in Book 3)
Not long ago (maybe 10 years) Jasper was a member of a gang that hunted people for satisfying their thirsts. Edward on the other hand was a Cullen for 100 years. He did kill people in his early vampire life but Carlisle reformed him into a vegetarian way of vampire life. And besides, Edward, after a later realisation, didn't want to be a monster.
Edward could control his thirst for human blood because he didn't want to drink human blood. He didn't want to be a monster. He could wilfully restrain himself just like Carlisle & others.
But Jasper had a different upbringing as a vampire. He hunted people until very recently & was part of the Cullen family after Alice found him. Jasper was "trying" to reform.
To answer the question about why Edward didn't react like Jasper & lunged at Bella, instead came in between the two is because
his love for Bella was much more intense than his thirst for Bella's blood.
Remember also that Edwards thirst for any other
human's blood is far weaker than his thirst for Bella's blood. This is clearly explained in Book 1.
Edward grew accustomed to remain between humans ie school but the moment Bella walked into class, the scent from her was too much for him to control himself
& he takes off away from town with the determination to never return. But his curiosity & connection with Bella brings him back to town.
In the climax of Book 1 when he has to draw out poisoned blood from Bella's body, he indeed finds the will to eventually stop & save Bella
rather than killing her by drinking her blood.
So love wins over lust.
It's long time since I've read the books, the details are a little hazy, but it's all in the books


Q:

How to execute HTTP request to daemon's *.bin endpoint like http://localhost/getblocks.bin

I am studying the wallet code and I found that it executes http://localhost/getblocks.bin request to the monero daemon. However when I try to execute this request in a browser (using GET method) it returns 404. I was just trying to see what the output looks like.
I am able to call all the other endpoints just *.bin gives me trouble.
What is so special about them? How I am supposed to build my HTTP request in order to succeed?

A:

Firstly, all of the .bin methods are binary methods (as the suffix alludes to). The input and output parameters are binary, serialized objects as defined in this file
These methods are generally for more specialized use cases. In almost all normal use cases, the JSON methods should suffice.
For getblocks.bin, there is some documentation here which details the input and output parameters.


Q:

Speed up my interactive matplotlib figure

I am loading a jpeg figure (large: 1300x2000) into matplotlib, drawing a grid of 50x50 squares over it and clicking on each square to color code it. However, I notice that the program lags far behind my clicks and takes up to 30 seconds to catch up if i quick about 50 squares at a reasonable speed. I am wondering if someone might be able to speed up. Below is my script which is ready to go if you copy/paste it (and have scipy,numpy, matplotlib, pillow, and tkinter)
Any advice will be welcome. I am a medical scientist so please forgive me if the code is not well explained:
import matplotlib
import matplotlib.pyplot as plt
import tkinter
import tkinter.filedialog
from matplotlib.figure import  Figure
import math, sys
import numpy as np
import scipy.io as sio
from PIL import Image
from numpy import arange, sin, pi
#from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
#matplotlib.matplotlib_fname()
import os, re

global stridesize, classnumber,x, im,fn, plt, fig, mask

classnumber = 1

def onmove(eve):
    global x,im, plt
    print(eve.ydata)
    print(eve.button)
    if (eve.ydata !=None) and (eve.xdata !=None):
        if eve.button==1:
            print(eve.button)
            xcoord = int(eve.xdata)
            ycoord = int(eve.ydata)
            startX = math.floor(xcoord/stridesize)*stridesize
            startY = math.floor(ycoord/stridesize)*stridesize
           # print(eve.xdata, int(eve.ydata), stridesize)
            if(classnumber==1):
                mask[startY:startY+stridesize,startX:startX+stridesize,:]=np.array([255,0,0])
            if(classnumber==2):
                mask[startY:startY+stridesize,startX:startX+stridesize,:]=np.array([0,255,0])
            if(classnumber==3):
                mask[startY:startY+stridesize,startX:startX+stridesize,:]=np.array([0,0,255])
            if(classnumber==4):
                mask[startY:startY+stridesize,startX:startX+stridesize,:]=np.array([255,0,255])
            if(classnumber==5):
                mask[startY:startY+stridesize,startX:startX+stridesize,:]=np.array([255,255,0])
            if(classnumber==6):
                mask[startY:startY+stridesize,startX:startX+stridesize,:]=np.array([0,255,255])
            if(classnumber==7):
                mask[startY:startY+stridesize,startX:startX+stridesize,:]=np.array([100,255,50])

        if eve.button==3:
            xcoord = int(eve.xdata)
            ycoord = int(eve.ydata)
            startX = math.floor(xcoord/stridesize)*stridesize
            startY = math.floor(ycoord/stridesize)*stridesize
            print(eve.xdata, int(eve.ydata), stridesize)
            mask[startY:startY+stridesize,startX:startX+stridesize,:]=np.array([0,0,0])
        im.set_data(mask)
        fig.canvas.draw()

def onclick(event):

    if (event.ydata !=None) and (event.xdata !=None):
        global x, im, fig
        if event.button==1:
            xcoord = int(event.xdata)
            ycoord = int(event.ydata)
            startX = math.floor(xcoord/stridesize)*stridesize
            startY = math.floor(ycoord/stridesize)*stridesize
            print(event.xdata, int(event.ydata), stridesize)
            if(classnumber==1):
                mask[startY:startY+stridesize,startX:startX+stridesize,:]=np.array([255,0,0])
            if(classnumber==2):
                mask[startY:startY+stridesize,startX:startX+stridesize,:]=np.array([0,255,0])
            if(classnumber==3):
                mask[startY:startY+stridesize,startX:startX+stridesize,:]=np.array([0,0,255])
            if(classnumber==4):
                mask[startY:startY+stridesize,startX:startX+stridesize,:]=np.array([255,0,255])
            if(classnumber==5):
                mask[startY:startY+stridesize,startX:startX+stridesize,:]=np.array([255,255,0])
            if(classnumber==6):
                mask[startY:startY+stridesize,startX:startX+stridesize,:]=np.array([0,255,255])
            if(classnumber==7):
                mask[startY:startY+stridesize,startX:startX+stridesize,:]=np.array([100,255,50])
            im.set_data(mask)

        if event.button==3:
            xcoord = int(event.xdata)
            ycoord = int(event.ydata)
            startX = math.floor(xcoord/stridesize)*stridesize
            startY = math.floor(ycoord/stridesize)*stridesize
            print(event.xdata, int(event.ydata), stridesize)
            mask[startY:startY+stridesize,startX:startX+stridesize,:]=np.array([0,0,0])
            im.set_data(mask)
        fig.canvas.draw()

def onpress(event):
    global classnumber, mask
    if (event.key == 'e'):
       print("YO")
       mask[:,:,:]=0;
       im.set_data(mask)
       fig.canvas.draw()

    if (event.key=='s'):
        savemask(fn)
    if (event.key=='r'):
        plt.figure();
        plt.imshow(mask);
        plt.show();
    if int(event.key) > 0 and int(event.key) <9 :
       classnumber = int(event.key)
       print(classnumber)

def onrelease(event):
    print(event.button)
 #   im.set_data(mask)

def savemask(fn):
    # matrixname =os.path.basename(filename)
    # matrixname = re.sub(r'\.jpg','',matrixname)
    pre, ext = os.path.splitext(fn)
    savename_default = os.path.basename(pre)
    options = {}
    options['defaultextension'] = ''
    options['filetypes'] = [('mat files', '.mat')]
    options['initialdir'] = ''
    options['initialfile'] = savename_default
    options['title'] = 'Save file'

    f = tkinter.filedialog.asksaveasfile(**options)
    if f is None: # asksaveasfile return `None` if aadialog closed with "cancel".
        return
    name = f.name
    sio.savemat(name,{'mask':mask},do_compression=True)
    f.close()

root = tkinter.Tk()
root.withdraw()

options = {}

options['defaultextension'] = '.jpg'

options['filetypes'] = [('Jpeg', '.jpg')]

options['initialdir'] = 'C:\\'
options['initialfile']= ''
options['parent'] = root

options['title'] = 'This is a title'

fn= tkinter.filedialog.askopenfilename(**options)

img = Image.open(fn)
x = np.asarray(img)
x.setflags(write=1)
#masksize= (x.shape[0],x.shape[1],4)
mask= np.zeros(x.shape,'uint8')
#mask[:,:,3]=0.2
fig = plt.figure()
fig.suptitle(r'Key codes: 1 = Tumour, 2 = stroma-hypocellular, 3=stroma cellular (inflammatory)' '\n4 = proteinaceous, 5= red cells, 6,7: anyother,''\nRight click: clear square''\n r:  review mask, e: erase mask, o : open mask image, s : save mask image;')

im=plt.imshow(x)
im=plt.imshow(mask,alpha=.25)
ax = plt.gca();

stridesize = 50;

plt.rcParams['keymap.save']=''
ax.set_yticks(np.arange(0, x.shape[0], stridesize));
ax.set_xticks(np.arange(0, x.shape[1], stridesize));

cid = fig.canvas.mpl_connect('button_press_event', onclick)
cod = fig.canvas.mpl_connect('key_press_event', onpress)
#cdd = fig.canvas.mpl_connect('motion_notify_event', onmove)
cdr = fig.canvas.mpl_connect('button_release_event', onrelease)

plt.grid(b=True, which='both', color='black',linestyle='-')
#
plt.show()

plt.ion()

A:

First, I would recommend avoiding the use of global variables at all cost. You can replace it by using a class instead. Find bellow a fully working summarized version of what your code intends to do:
import numpy as np

import matplotlib
matplotlib.use('Qt4Agg')

from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap

class ColorCode(object):

    def __init__(self, block_size=(50,50), colors=['red', 'green', 'blue'], alpha=0.3):
        self.by, self.bx = block_size # block size
        self.selected = 0 # selected color
        self.colors = colors
        self.cmap = ListedColormap(colors) # color map for labels
        self.mask = None # annotation mask
        self.alpha = alpha
        # Plots
        self.fig = plt.figure()
        self.ax = self.fig.gca()
        # Events
        self.fig.canvas.mpl_connect('button_press_event', self.on_click)
        self.fig.canvas.mpl_connect('key_press_event', self.on_key)

    def color_code(self, img):
        self.imshape = img.shape[:2]
        self.mask = np.full(img.shape[:2], -1, np.int32) # masked labels
        self.ax.imshow(img) # show image
        self.ax.imshow(np.ma.masked_where(self.mask < 0, self.mask), cmap=self.cmap,
                       alpha=self.alpha, vmin=0, vmax=len(self.colors)) # show mask
        # Run
        plt.show(block=True)
        return self.mask

    def on_click(self, event):
        if not event.inaxes or self.mask is None:
            return
        # Get corresponding coordinates
        py, px = int(event.ydata), int(event.xdata)
        cy, cx = py//self.by, px//self.bx # grid coordinates
        ymin = cy * self.by
        ymax = min((cy+1) * self.by, self.imshape[0])
        xmin = cx * self.bx
        xmax = min((cx+1) * self.bx, self.imshape[1])
        # Update mask
        if event.button == 1:
            self.mask[ymin:ymax, xmin:xmax] = self.selected
        elif event.button == 3:
            self.mask[ymin:ymax, xmin:xmax] = -1
        # Update figure
        self.ax.images[1].set_data(np.ma.masked_where(self.mask < 0, self.mask))
        self.fig.canvas.draw_idle()

    def on_key(self, event):
        ikey = int(event.key)
        if 0 <= ikey < len(self.colors):
            self.selected = ikey

The key differences with your code are:

It doesn't use global variables, instead, it uses class-variables. Making it safer to run and easier to extend/modify.
Instead of colouring a 3-dimensional mask for your annotations, annotations are saved as a 2-dimensional mask, where every pixel has a value in the range [1, len(colors)] indicating to which colour it belongs. Colours are then added to the plot by using ListedColormap to set a custom colormap for your plot.
It draws the image and overlays on top of it a segmentation mask. Initially the mask is filled with -1, meaning it has no label. By using a numpy's masked array you can mask where mask < 0 to not show that in the plot, making the plot transparent where mask < 0 and coloured otherwise.
List of possible colours are provided as a parameter to the class. It will allow you to select a colour from 0 to len(colors) with a maximum of 10 colors (as it is currently binded to numbers in the keyboard).
fig.canvas.draw_idle is much better than fig.canvas.draw. The latter blocks the program until it finishes drawing.
As everything is into a class, code looks much cleaner.

You can call the code as:
>>> random_image = np.random.randn(1000,2000, 3)
>>> result = ColorCode().color_code(random_image)

and result will contain the labelling mask where each pixel has a number indicating with witch color it has been tagged (-1 if none). Last, other parameters can be passed to ColorCode's constructor, such as block_size=(100,100) for different block size, alpha=0.5 for less opacity in the mask (or None as alpha=1).
Hope it works for you, or that at least you can grab some ideas from it.


Q:

Monodevelop's text editor

There are several articles that instruct how to use avalonedit of sharpdevelop (avalonedit is the editor of sharpdevelop). Is there any article out there that explains how to use monodevelop's text editor?  Also, what's the name of that editor; does it have a name?  Thanks.

A:

A while ago the previous text editor was replaced by Mono.TextEditor. There's not much documentation on it, or articles about it, but you could look at how it is integrated into MonoDevelop.


Q:

RGB to norm rgb transformation. Vectorizing

I'm writing a piece of code that has to transform from an RGB image to an rgb normalized space. I've got it working with a for format but it runs too slow and I need to evaluate lots of images. I'm trying to vectorize the full function in order to faster it. What I have for the moment is the following:
     R = im(:,:,1);
     G = im(:,:,2);
     B = im(:,:,3);

     r=reshape(R,[],1);
     g=reshape(G,[],1);
     b=reshape(B,[],1);

     clear R G B;

     VNormalizedRed = r(:)/(r(:)+g(:)+b(:));
     VNormalizedGreen = g(:)/(r(:)+g(:)+b(:));
     VNormalizedBlue = b(:)/(r(:)+g(:)+b(:));

     NormalizedRed = reshape(VNormalizedRed,height,width);
     NormalizedGreen = reshape(VNormalizedGreen,height,width);
     NormalizedBlue = reshape(VNormalizedBlue,height,width);

The main problem is that when it arrives at VNormalizedRed = r(:)/(r(:)+g(:)+b(:)); it displays an out of memory error (wich is really strange because i just have freed three vectors of the same size). Were is the error? (solved)
Its possible to do the same process in a more efficiently way?
Edit:
After using Martin sugestions I found the reshape function was not necessary, being able to do the same with a simple code:
     R = im(:,:,1);
     G = im(:,:,2);
     B = im(:,:,3);

     NormalizedRed = R(:,:)./sqrt(R(:,:).^2+G(:,:).^2+B(:,:).^2);
     NormalizedGreen = G(:,:)./sqrt(R(:,:).^2+G(:,:).^2+B(:,:).^2);
     NormalizedBlue = B(:,:)./sqrt(R(:,:).^2+G(:,:).^2+B(:,:).^2);

     norm(:,:,1) = NormalizedRed(:,:);
     norm(:,:,2) = NormalizedGreen(:,:);
     norm(:,:,3) = NormalizedBlue(:,:);

A:

I believe you want
VNormalizedRed = r(:)./(r(:)+g(:)+b(:));

Note the dot in front of the /, which specifies an element-by-element divide. Without the dot, you're solving a system of equations -- which is likely not what you want to do. This probably also explains why you're seeing the high memory consumption.


Q:

java.lang.reflect.invocationtargetexception in android

I am getting a problem , my xml file is as follow
<ImageView
    android:id="@+id/edt_order"
    android:layout_width="50dp"
    android:layout_height="match_parent"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/separator_bottom"
    android:background="#fff"
    android:clickable="true"
    android:onClick="clickHandler"
    android:src="@drawable/edit_button" />

<ImageView
    android:id="@+id/save_change_order_id"
    android:layout_width="100dp"
    android:layout_height="match_parent"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/separator_bottom"
    android:background="#fff"
    android:clickable="true"
    android:visibility="gone"
    android:onClick="clickHandler"
    android:src="@drawable/save_button" />

Actually this is part of xml that define customize alert-dialog. I want that when I click on first ImageView(android:id="@+id/edt_order") , then its visibility become Invisible and in place of this ImageView setvisible a another ImageView(android:id="@+id/save_change_order_id")
For this I write down below code in java file:
public void clickHandler(View v) {

    if (v.getId() == R.id.edt_order) {
        System.out.println(" edit buton click");
        System.out.println("Click my Order");
        img_v_save_change_order_var.setVisibility(ImageView.VISIBLE);
        img_btn_edit_order_var.setVisibility(ImageView.INVISIBLE);
        int jcount = 0;
        // save_change_order_id
        jcount = countjournals();
        System.out.println("jcount = " + jcount);

        if (jcount < 1) {
            alertShow();
        } else {
            intiliazeOrderListDialog();
        }
    }
}

But I am getting a exception as follow:
 01-09 06:12:14.550: D/AndroidRuntime(1981): Shutting down VM
 01-09 06:12:14.550: W/dalvikvm(1981): threadid=1: thread exiting with uncaught exception (group=0xb3ab3b90)
 01-09 06:12:14.730: E/AndroidRuntime(1981): FATAL EXCEPTION: main
 01-09 06:12:14.730: E/AndroidRuntime(1981): Process: com.example.demoekot, PID: 1981
 01-09 06:12:14.730: E/AndroidRuntime(1981): java.lang.IllegalStateException: Could not execute method of the activity
 01-09 06:12:14.730: E/AndroidRuntime(1981):    at android.view.View$1.onClick(View.java:3814)
 01-09 06:12:14.730: E/AndroidRuntime(1981):    at android.view.View.performClick(View.java:4424)
 01-09 06:12:14.730: E/AndroidRuntime(1981):    at android.view.View$PerformClick.run(View.java:18383)
 01-09 06:12:14.730: E/AndroidRuntime(1981):    at android.os.Handler.handleCallback(Handler.java:733)
 01-09 06:12:14.730: E/AndroidRuntime(1981):    at android.os.Handler.dispatchMessage(Handler.java:95)
 01-09 06:12:14.730: E/AndroidRuntime(1981):    at android.os.Looper.loop(Looper.java:137)
 01-09 06:12:14.730: E/AndroidRuntime(1981):    at android.app.ActivityThread.main(ActivityThread.java:4998)
 01-09 06:12:14.730: E/AndroidRuntime(1981):    at java.lang.reflect.Method.invokeNative(Native Method)
 01-09 06:12:14.730: E/AndroidRuntime(1981):    at java.lang.reflect.Method.invoke(Method.java:515)
 01-09 06:12:14.730: E/AndroidRuntime(1981):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
 01-09 06:12:14.730: E/AndroidRuntime(1981):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
 01-09 06:12:14.730: E/AndroidRuntime(1981):    at dalvik.system.NativeStart.main(Native Method)
 01-09 06:12:14.730: E/AndroidRuntime(1981): Caused by: java.lang.reflect.InvocationTargetException
 01-09 06:12:14.730: E/AndroidRuntime(1981):    at java.lang.reflect.Method.invokeNative(Native Method)
 01-09 06:12:14.730: E/AndroidRuntime(1981):    at java.lang.reflect.Method.invoke(Method.java:515)
 01-09 06:12:14.730: E/AndroidRuntime(1981):    at android.view.View$1.onClick(View.java:3809)
 01-09 06:12:14.730: E/AndroidRuntime(1981):    ... 11 more
 01-09 06:12:14.730: E/AndroidRuntime(1981): Caused by: java.lang.NullPointerException
 01-09 06:12:14.730: E/AndroidRuntime(1981):    at com.example.demoekot.MainScreen.clickHandler(MainScreen.java:428)
 01-09 06:12:14.730: E/AndroidRuntime(1981):    ... 14 more

Why I am getting this exception?

A:

I think it is problem of declaration of image in your main class.


Q:

Exuberant Ctags: undocumented extension fields

I'm looking at the tags file that Exuberant Ctags generated for my ruby project, and reading the documentation for the Tag File Format:
tag_name<TAB>file_name<TAB>ex_cmd;"<TAB>extension_fields

My tags file has lots of lines like:
MyThing<TAB>lib/my_thing.rb<TAB>/^class MyThing$/;"<TAB>c

It's just my burning curiosity, but I can't find any explanation of what the trailing <TAB>c extension field indicates.

A:

After downloading the ctags source (and indexing it with ctags), I see in ruby.c that the extension fields are pretty simple:
/*
*   DATA DEFINITIONS
*/
static kindOption RubyKinds [] = {
    { TRUE, 'c', "class",  "classes" },
    { TRUE, 'f', "method", "methods" },
    { TRUE, 'm', "module", "modules" },
    { TRUE, 'F', "singleton method", "singleton methods" }
};


Q:

Removing the "d" object from ASP.Net web service json output

I have some javascript code that processes json output from asp.net web services built with framework 2.0. Now I need to support data returned from framework 3.5 web services.
My javascript code assumes a list of objects as return value, which works fine in 2.0. However In framework 3.5, the list is wrapped in a "d" object. Is there any way I can remove the "d" wrapper and just return the list?
I would prefer to fix this onthe server side

A:

You can't configure 3.5+ services not to return the .d.  It's good that it's there too, because it protects from a tricky JSON hijacking scenario that exists when the outer JSON entity is an array.
ASP.NET AJAX's client-side proxies automatically hide the .d from you.  If it's getting in your way, I'm assuming you're using something like jQuery to call the service?  You can normalize the .d in jQuery by using its DataFilter callback, for example.

A:

Here is a way around that
    [WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public void Status()
    {
        MyObject myObject = new MyObject(); // your object here
        var json = Newtonsoft.Json.JsonConvert.SerializeObject(myObject);

        HttpContext.Current.Response.Write(json);
    }


Q:

Php Redirect to a webpage (html)

I've seen the use of header in the php to redirect to a page.
I've used the method in the code below and the a redirect error as given below the code.
I need to know what went wrong with the code.
Here is the code (php) :
<?php
/**
 * Created by PhpStorm.
 * User: Priyabrata
 * Date: 3/18/14
 * Time: 8:58 PM
 */

function connect_to_db($uid, $pass){
    $con=mysqli_connect("localhost", "root", "12345", "MyDB");
    if (mysqli_connect_errno()){
        echo "Failed to establish link!!";
    }else{
        echo mysqli_connect_error();
    }
    $result=mysqli_query($con, "SELECT `pwd` from `login_table` where `uid` = "."'".$uid."'");
    if (!$result){
        echo "Error!!";
        exit();
    }
    while($xx = mysqli_fetch_array($result)){
        if ($xx['pwd'] == hash("MD5", $pass)){
            header("location:../Html/Login-Existing-Users1_success.htm");
            exit();
        }else{
            echo "Invalid Login Credentials!!";
            exit();
        }
    }
    mysqli_close($con);
}

function validate_credentials(){
    if ((isset($_POST["username"]))&&(isset($_POST["password"]))){
        $uid = $_POST["username"];
        $pwd = $_POST["password"];
        if (($uid == "")||($pwd == "")){
            echo "Please enter User name and password";
        }else{
            //Check user name and password
            connect_to_db($uid, $pwd);
        }
    }else{
        echo "Please enter User name and password";
    }
}

validate_credentials();

Here is the error I get, instead of a redirect when uploaded to the server:
Warning: Cannot modify header information - headers already sent by (output started at /home/opticfhb/public_html/helpvssupport.net/login.php:19) in /home/opticfhb/public_html/helpvssupport.net/login.php on line 27

Additional Info : This works perfectly in my local machine and creates the problem in the server.

A:

You can't call header() after you've already echoed any output. HTTP requests contain header information and data. Any output is part of the data, and data comes after all the headers have already been sent.
PHP has a function called headers_sent to check whether or not the headers have already been sent or not. You might consider writing a function that issues the Location header if they haven't been, or echo out some simple redirect HTML if they have -- perhaps by including this tag in the <head>:
<meta http-equiv="refresh" content="0;http://www.website.com/redirect/url" />


Q:

When doing 3D rotations my angle flips 180 degrees

I'm implementing 3D rotations for a set of 3D circles. To do that I'm using the parametric equation as described in http://demonstrations.wolfram.com/ParametricEquationOfACircleIn3D/.
It works as expected, but I can't figure out how to mitigate one issue. That is every $180$ degrees my circle flips.
I calculate the normal vector for every circle using $arctan()$. It's value starts from $-0$ then goes to $-\frac{\Pi}{2}$. But then it goes to $\frac{\Pi}{2}$ and decrements down to $-\frac{\Pi}{2}$. And the cycle continues.
How do I make this a continuous progression?
I need this to stop my vertices from flipping.

A:

If you are using atan() function, replace it by atan2(). atan2() is always favorable than atan(). Please note that atan2() takes two arguments: y value and x value.


Q:

Html Attribute not populating from HttpContext.Items

My problem seems fairly simple, and I feel like I'm missing something extremely obvious; but I'm unable to determine why the Nonce attribute on the script elements aren't populating and remaining empty strings instead.
I decided to use the Items collection inside the HttpContext to store the nonce because, from what I can tell, it is per request.
Startup.Configure(IApplicationBuilder app, IHostingEnvironment env)
...
app.Use(async (context, next) => { //CSP
    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
    byte[] nonceBytes = new byte[32];
    rng.GetBytes(nonceBytes);
    string nonce = Convert.ToBase64String(nonceBytes);
    context.Items.Add("ScriptNonce", nonce);
    context.Response.Headers.Add("Content-Security-Policy", string.Format(
        "default-src 'none'; " +
        "script-src 'self' 'unsafe-eval' 'nonce-{0}'; " +
        "style-src 'self'; " +
        "img-src 'self' data: https:; " +
        "base-uri 'self'; " +
        "upgrade-insecure-requests; " +
        "object-src 'none'; ", nonce));
    await next();
});
...

View
...
@section Scripts {
    <script src="~/lib/jquery-ajax-unobtrusive/jquery.unobtrusive-ajax.min.js" nonce="@Context.Items["ScriptNonce"]"></script>
    <script src="~/js/Views/Admin/users_index.min.js" nonce="@Context.Items["ScriptNonce"]"></script>
}

Result:
The Nonce is generated, it exists in HttpContext.Items, does not populate.

This seems really simple and I'm really confused on why the attributes are not populating.
I'm a bit new to web development so any tips in ASP.Net Core 2 would be greatly appreciated, if anything stands out to you.
Answer: First Comment;
The nonce was there the entire time, chrome was hiding it.

A:

Answer: First Comment;
The nonce was there the entire time, chrome was hiding it.


Q:

You really know who are we!

Exquisite as much as others we have our own land,
United by our name divided we stand!
When problems visit, and things just stop,
You know
where to find us, we stay on top!
We have our place in each heaven,
Our reign starts at $2^4$ multiply by Seven!

Hint#1

 Friend

Hint#2

 There is a tag "anagram" for a reason. You might get some help out of it.

Hint#3

 Anagram can be applicable to any of the above quoted blocks

Hint#4

 Let me tell you how many we are. We can be regrouped into two. Yes this rocks!

A:

Could it be

 emergency telephone numbers?

My reasoning:

 I will begin from the end ---- 2^4 * 7 = 112, which is one of the most commonly used emergency telephone numbers.
United by name being their classification, but divided in that there is a different number used in various locations around the world.
When problems visit would then refer to the emergencies needed to warrant the use of the emergency telephone number.
We have our place in each heaven could simply mean that there is a working emergency telephone number no matter where you go on Earth (which I can't really vouch for truth, necessarily, but I'd like to think so).
 The concept of anagrams and lateral thinking would combine to suggest a numerical anagram, wherein some regions use 119 and 911 as their distinct emergency telephone numbers, which are anagrams of each other.

A:

The answer is ->

 Function Keys

Exquisite as much as others we have our own land,

 They have there place on every keyboard

United by our name divided we stand!

 They are called function keys. They are placed divided most of the times in groups.

When problems visit, and things just stop,
You know where to find us, we stay on top!

 Function keys are used most of times for booting up or stopping hanged programs. Off-course they are placed on the top.

We have our place in each heaven,

 They have there place on every brand of keyboards.

Our reign starts at $2^4$ multiply by Seven!

 ASCII Key Code of F1 is 112.

Hint

 Friend. Anagram of Friend is "Friden" which first added them on their keyboards Flexowriter

Another Hint

 Let me tell you how many we are. We can be regrouped into two. Yes this rocks! Here "Yes this rocks" has 12 letters. There are 12 function keys.


Q:

Cannot send email from CiviCRM after upgrade to 4.7.21 (Joomla 3.7.3)

After upgrading CiviCRM to 4.7.21 (on Joomla 3.7.3), no emails get sent from CiviCRM (transactional or from CiviMailing). In System Settings >> Outbound Email (SMTP/Sendmail) when I click on "Save and Send Test Email" the page keeps reloading for about a minute, and then results in 500 error ("This page isn't working").
This worked perfectly before the upgrade.
Also, I no longer see file packages/Net/SMTP.php (I re-ran the CiviCRM install just in case) which used to send email via SMTP ... is this now handled by another file in another directory?
Thank you so much for any pointers.

A:

As Mark said this is a known regression and we are looking at an expedited release. However as i can feel even a release this coming US Wednesday may be a bit late.
What i would advise you to do is to if you cannot wait make a patch to the file vendor/pear/net_smtp/Net/SMTP.php along the lines of https://github.com/civicrm/civicrm-core/pull/10622/files. The relevant block of code will be around ~line 600 of that particular file.
Otherwise wait until 4.7.22 comes out which will be very soon. In regards to why this may not affect all users, it only affects users if they need to authenticate to the SMTP server over TLS


Q:

What was the location of Andreas Tanis exile?

In Underworld Evolution, Selene and Michael travel to seek out Andreas Tanis, who is living in exile.
According to the Underworld wiki, Tanis is spending his exile in a monastery described as a "mountain abode"

For his trouble, he is exiled by Selene, Viktor's personal replacement
  for Sonja, to an abandoned monastery.
Once a place of worship, this abandoned mountain abode serves a
  different purpose to the Coven in the late 17th Century. On the orders
  of Vampire Elder Viktor, it is turned into a place of exile for
  Vampire Andreas Tanis.

Is there an in-universe explanation on where this monastery is geographically located?

A:

There is no in-universe map of where the monastery is located, aside from being in the Hungarian region. As Evolution takes place minutes after Underworld, and the events shown are on the scale of a few days, that means it's a night or two's car ride from Budapest, where Underworld takes place (and was filmed). After visiting Tanis, Selena and Michael drive back to Budapest to visit great grand pa Corvinus on his boat on the Danube river.
Assuming 4 hour drive time, that places it any country of the Danubian region.

Out of Universe, it's a sound stage in Vancouver.


Q:

creating a data base for staff time table?

i wana create a database  for staff timetable!!
my attributes are,
StaffTimeTable - TimetableID(pk),StaffID,periods,day.

per day a school has 8 periods(where a staff need to attend) one staff can have only one timetableID.
My problem is how can i create a database with one timetableid for 5days!!
an exmaple
TimeTableID    StaffID  Day     period1 p2 p3     p4  p5   p6   p7   p8

stt001         st001  Monday  maths      physics

My Question is How can i insert the Tuesday TimeTable(for the same time table id) ??
If answered its most appreciable !! :)

A:

you should make a few tables for this.
SEE IT IN ACTION!
SETUP:
CREATE TABLE periods (
   id int,
   period varchar(55)
);

this table would look something like this
id       period
1        'maths'
2        'physics'
3        'english'
... etc

you should also have a table for the days like so
CREATE TABLE day_of_week (
    id int,
    day varchar(55)
);

this would look something like this.
id             day
1              'Sunday'
2              'Monday'
3              'Tuesday'
4              'Wednesday'
.... etc.

you should have a staff table like so
CREATE TABLE staff (
    id int,
    staff_name varchar(55)
);

this table would look something like this.
id            staff_name
1             Mary
2             John
..... etc

NOW you need to have a connecting table.
CREATE TABLE StaffTimeTable (
    id int, -- this is the pk
    staffID int,
    periodID int,
    dayID int
);

NOTE:
each of these id's are the foreign key to the primary keys in your other tables...
also all of the primary key id's should be auto incremented.
COMBINE IT ALL
SELECT t.id, s.staff_name, d.day_name, p.period
FROM StaffTimeTable t
JOIN staff s on s.id = t.staffID
JOIN day_of_week d on d.id =  t.dayID
JOIN periods p on p.id = t.periodID
ORDER BY t.id;


Q:

How to improve the sidenav animation performance angular material

I have made a sidenav using angular-material's md-sidenav and below is the screenshot of it. When i try click on the button for sidenav the animations pretty lagging. I have used on an image on the top bar and the rest just text with font-awesome icons. What could i be possibly doing bad that it is slow. The animations are even worse when i view it on mobile.
Screenshot of sidenav :

Here is the code of sidenav :
<md-sidenav class="boxme-sidenav" layout="column" hide-gt-sm class="md-sidenav-left md-whiteframe-z2" md-component-id="left">

    <md-list style="background-color:#00B0FF;color:white;z-index:10;">
        <md-list-item class="md-2-line sidenav-list" layout-padding>
            <md-button href="" layout-align="space-around center">

              Dashboard
            </md-button>
        </md-list-item>
        <md-list-item class="md-2-line sidenav-list" layout-padding layout-align="start center">
            <md-button href="">

              My Stuff
            </md-button>
        </md-list-item>
        <md-list-item class="md-2-line sidenav-list" layout-padding layout-align="start center">
            <md-button href="">

              Order History
            </md-button>
        </md-list-item>
        <md-list-item class="md-2-line sidenav-list" layout-padding layout-align="start center">
            <md-button href="">

              Billing
            </md-button>
        </md-list-item>
        <md-divider></md-divider>
        <md-subheader style="background-color:#00B0FF;color:white;">Manage the items</md-subheader>
        <md-list-item class="md-2-line sidenav-list" layout-padding layout-align="start center">
          <md-button href=""> Pickup my stuff</md-button>
        </md-list-item>
        <md-list-item class="md-2-line sidenav-list" layout-padding layout-align="start center">
          <md-button href=""> Deliver my stuff</md-button>
        </md-list-item>
    </md-list>
</md-sidenav>

Note :
After a while the performance and animations of sidenav get real lagging on the web.

A:

It may not be right solution for your case, but disabling backdrop and adding 1 tweak made transition performance acceptable for me (even on phone)
.md-sidenav-backdrop {
    opacity: 0 !important;
}

md-sidenav.md-closed-add,
md-sidenav.md-closed-remove {
    -webkit-transition: all .4s cubic-bezier(0.25, .8, .25, 1) !important;
    transition: all .4s cubic-bezier(0.25, .8, .25, 1) !important;
}

A:

I decided to just remove the animation as follows:
I looked through the AngularMaterial CSS file and removed all references to animations. KA-BOOM!
/**
* fix md-sidenav lag by removing animation
**/

.md-sidenav-backdrop {
    opacity: 0 !important;
}

md-sidenav.md-closed-add,
md-sidenav.md-closed-remove,
md-sidenav.md-closed-add.md-closed-add-active,
md-sidenav.md-closed-remove.md-closed-remove-active,
md-sidenav.md-locked-open-remove-active,
md-sidenav.md-closed.md-locked-open-add-active

{
    -webkit-transition: none !important;
    transition: none !important;
}

---- edit ----
Also update to the latest version of AngularMaterial there seems to be an overall improvement in v1.0.0-rc4 compared to prior releases.


Q:

Could the industrial revolution pre-date the age of discovery?

It is the early 1800s.  Some guy has just figured out a way to burn coal to heat water and produce power.  His cohorts are beginning to ask the "what if" questions that will lead to trains, automated saw mills, and paddle-wheel river boats.
However, all of this is happening in a Europe-Asia-Africa that remains blissfully unaware that there are these whole other continents just the around the planet.  Despite having plenty high-quality sailing ships designed for long-distance commerce and military might, despite all the astronomical evidence regarding the size and shape of the Earth, despite ample opportunity to do so, no one has yet been bothered to make the effort.
Can history happen in this order?  Why?  What kept these alt-Europeans from crossing the Atlantic?

A:

Yes as the ancient Greeks invented a type of steam engine but they never figured out that it could be put to practical use.  Had the ancient Greeks figured out the practical use for the steam engine then the industrial revolution could have started in the former Macedonian Empire.

A:

No, not really. It would require major changes of geography and if you go that way, you might as well remove the Americas. If you used a relatively large island remote from other land as the replacement, you might be able to salvage the discovery part. It would essentially be something like taking Australia at its latitude in the south (not en route between Europe and Asia) and moving it east so that it is remote from other lands. The longitude of the Americas would be good enough.
Obviously you would be free to change everything except general size and location. The continent would probably be uninhabited or inhabited by descendant of some Polynesians with really bad luck, followed by some incredibly good luck enabling survival.
In the interest of giving a proper answer, there are three major issues:
Trade between Mediterranean and India.
Both the route around Africa and through the Middle East would at times be unavailable to some European nation due to political reasons. That is what IIRC along with some bad math motivated the Columbus Expedition.
And even if you assume the route around Africa remains always open, Brazil is simply too close for nobody to find it by accident if lots of traffic went between Europe and Cape of Good Hope. And industrialization doesn't really make sense without expanding trade. What else could use the volume production it supplies?
As noted in comments, creating open straits of Suez would help. As would simply expanding the distance between Africa and South America.
Iceland, Greenland, Newfoundland, Fish!
The gaps that need to be crossed are too close up north not to be discovered by competent navigators, if they have reasons to sail around. Industrialization, creates an expansion of economy and population, which creates vastly expanded demand for fish. Which means lots of ships with crews of solid seamanship sailing around the Northern Atlantic looking for new places to fish. Discovery would be inevitable. In fact I think the consensus is that North America was discovered several times by various peoples of the North-Western Europe. They just didn't really do anything with that discovery except some fishing and hunting.
Even if they assumed no land exists to the west they would still be looking for new fisheries in the Atlantic. And study the sea currents to find them too. It would be fairly obvious that something is affecting the flow of currents. And that whatever that was would come with lots of rich fisheries.
You might be able to argue that before the demand for fish expanded they wouldn't really care enough to do anything about reports of land to the West. Especially if you remove Iceland and Greenland so the gap to navigate becomes wider. Then you could justify an expedition to find new Atlantic fisheries based on the odd paths of the ocean currents in roughly the time frame you want.
The Bering straits
AFAIK you can still cross from Asia to America without leaving the sight of land. Any major expeditions by Europeans or the advanced Asian nations to map the coasts of North-Eastern Asia would find America for sure. You might explain this by noting that none of the Asian nations was really trade oriented enough to look within the correct time frame. You would also need to explain away the Russians. That would require a major rewrite of the history of Eastern Europe so Russians do not expand to Siberia.


Q:

Android Studio Instant Run is not enabled?

Instant Run is a new feature introduced for reduce time for run and debug app.
I have all the required configuration for enabling Instant run, but it is not enabled on Android Studio. Here is my configuration below.
1. Android Studio 2.1
2. 'com.android.tools.build:gradle:2.1.0'
3. minSdkVersion 15
4. Settings->Build, Execution, Deployment > Instant Run = "Enable Instant Run..."
5. Run ->device is  Android version 4.4.4

Then Instant Run is NOT enabled.
But when I am Run->on device Android Version 5.1.1, Instant Run is enabled.
Please suggest, if some other configuration I missed to enable Instant run for Android 4.4.4 device.

A:

When you are running for the first time Instant Run is not required as the apk will be installed for the first time in the selected device. From the second time onward if you choose the same device to deploy your changes then instant run will be automatically enabled from Android studio 2.0 and Gradle version 2.0.
Please Note: You are required to run in debug mode.
For more Clear understanding you may visit this link


Q:

Strange C# compiler behavior when choosing overload that looks like a bug/missing feature

I have recently found an interesting behavior of C# compiler. Imagine an interface like this:
public interface ILogger
{
   void Info(string operation, string details = null);
   void Info(string operation, object details = null);
}

Now if we do
logger.Info("Create")

The compiler will complain that he does not know which overload to chose (Ambiguous invocation...). Seems logical, but when you try to do this:
logger.Info("Create", null)

It will suddenly have no troubles figuring out that null is a string. Moreover it seems that the behavior of finding the right overload has changed with time and I had found a bug in an old code that worked before and stopped working because compiler decided to use another overload.
So I am really wondering why does C# not generate the same error in the second case as it does in the first. Seems very logical to do this, but instead it tries and resolves it to random overload.
P.S. I don't think that it's good to provide such ambiguous interfaces and do not recommend that, but legacy is legacy and has to be maintained :)

A:

There was a breaking change introduced in C# 6 that made the overload resolution better. Here it is with the list of features:

Improved overload resolution
There are a number of small improvements to overload resolution, which will likely result in more things just working the way you’d expect them to. The improvements all relate to “betterness” – the way the compiler decides which of two overloads is better for a given argument.
One place where you might notice this (or rather stop noticing a problem!) is when choosing between overloads taking nullable value types. Another is when passing method groups (as opposed to lambdas) to overloads expecting delegates. The details aren’t worth expanding on here – just wanted to let you know!

but instead it tries and resolves it to random overload.

No, C# doesn't pick overloads randomly, that case is the ambiguous call error. C# picks the better method. Refer to section 7.5.3.2 Better function member in the C# specs:

7.5.3.2 Better function member
Otherwise, if MP has more specific parameter types than MQ, then MP is better than MQ. Let {R1, R2, …, RN} and {S1, S2, …, SN} represent the uninstantiated and unexpanded parameter types of MP and MQ. MP’s parameter types are more specific than MQ’s if, for each parameter, RX is not less specific than SX, and, for at least one parameter, RX is more specific than SX:

Given that string is more specific than object and there is an implicit cast between null and string, then the mystery is solved.


Q:

How do I make folders Forbidden to view in Magento

Example:  http://www.acuity-sports.com/skin/
I want this to be what they see below instead of my tree:
Forbidden
You don't have permission to access /skin on this server.

A:

Take a look @ how to prevent directory access and show forbidden error in php
Add a .htaccess file with
# disable directory browsing
Options -Indexes


Q:

Would there be a race condition when multiple Actors access/call Object class methods in Scala?

In Scala singletons are created using Object classes and when serval Akka actors call methods in particular Object, would race condition occur ?

A:

If the object holds state, then yes. It will require proper synchronization guards


Q:

maintaining aspect ratio on launch screen

I expect there's a simple answer here. If so, sorry and thanks.
I'm trying to make my launch screen for all the different iPad and iPhone sizes. On the launch storyboard I have two UIViews, one full size for the background (backView) and one in the shape of a square (squareView). I'm trying to keep the square from stretching (i.e. I'm trying to maintain a 1:1 aspect ratio) and make it 0.75 the width of whatever device the app runs on. I know that there will be varying amounts of space below, but how can I keep the square from distorting when I switch devices?
I've been researching the constraints and diddling with them for hours. I expect someone will tell me it's easy, just do ... what?

A:

First, I've centered my rect horizontally and vertically

Then I've set the rect's width to x0.75 of his superview

For the final step I'm setting his ratio to 1:1

That's it! Final result:


Q:

Creating Activities in a Snapshot View in ClearCase

I would like to create an activity for my ClearCase snapshot view, but you cannot ct setview to a snapshot and when I try to just ct mkactivity I get the following error:

my_snapshot> ct mkact
Create activity with automatically generated name?  [yes] y
[27204] mkact_pre -- trigger firing
Stream feature 'MkactForbidden' does not allow creation of activities.
cleartool: Warning: Trigger "UTS_mkact_pre" has refused to let mkactivity proceed.
cleartool: Error: Unable to create activity.

Can you create activities in ClearCase snapshot views? Or are you restricted to creating activities in dynamic views?

A:

First, cleartool setview is only for dynamic view (see "Python and ClearCase setview", for instance, for more).
mkact can create activity in any view, dynamic or snapshot, but in your case, a pre-op trigger on the mkact operation prevents you to create it.
You could try and set an existing activity: you might have to unselect the current one (ct setact -none) first.
But mainly you need to check with your ClearCase admin why this trigger prevents you to make any activity, which in effects prevents you to checkout or rebase or deliver in this stream.