set textbox with current date onload when using xdsoft datetimepicker

Question: i have a textbox with xdsoft datetimepicker jquery plugin. Here is the code.
<asp:TextBox class="spacial_text calendar" ID="txtDate" runat="server"></asp:TextBox>

i want to load the current date to textbox txtDate while loading the page.
i tried
$('#txtDate').val(new date());
setDate: new Date() //inside datetimepicker function- but not working

onGenerate: function (ct) {
                    jQuery(this).val(new Date());
                } //not working

any way to set current date to textbox on load???
Comment: this may help you http://stackoverflow.com/questions/6646376/jquery-date-picker-default-date
Comment: Try `new Date().toString()`
Answer: According to the documentation the value option will be used if set and ignore the input's value. To get the current date in the format you want I would use (d.getUTCFullYear())+'/'+(d.getUTCMonth()+1)+'/'+(d.getUTCDate()).
$(document).ready(function () {
    var d = new Date(),
        date = (d.getUTCFullYear())+'/'+(d.getUTCMonth()+1)+'/'+(d.getUTCDate());

    $('#txtDate').datetimepicker({
        mask: true,
        timepicker: false,
        format: 'Y/m/d',
        value: date
    });
});

Comment: yeah this works. but i have to set mask: false. if mask is true, this is not working. But its ok, i dont want mask.... thank you @Adam Merrifield
Answer: The best method you can choose for html
  $('#txtCourseExpiryDate').datetimepicker({
                                    format: 'd/M/Y',
                                    timepicker: false,
                                    value: new Date()
                                });

If you are using the same in the aspp.net then please use the below
  $('#<% =txtCourseExpiryDate.ClientID %>').datetimepicker({
                                    format: 'd/M/Y',
                                    timepicker: false,
                                    value: new Date()
                                });

Output:
Answer: Try the code Below
$("#txtDate").datepicker( "setDate" , "10/11/2014" );

Answer: Another way:
$("#txtDate").datetimepicker({ value: new Date().toDateString() });


Additional notes that are being played besides picked ones

Question: I was experimenting with sound analysis lately and from what I see when I plot spectral data of an audio file is that apart from notes that were actually plucked there are some other notes with quite high local amplitude.
For example I have a sample where D major chord is played with some nasty distortion. After looking onto the spectral plot I can observe a note D, F# and A as expected. But as I go higher some other notes have higher amplitude than threshold, one of those is E.
So, the question is: is it a normal thing that when I play D major the note E could be observed on a spectral plot but not heard or that's just error during recording ?
Additional info:

that is not a DC component
audio is in high quality, therefore there are almost no background noise
the note E has some harmonics further in spectrum
Comment: I think the major distortion is what you're seeing. Distortion is just extra frequencies added on top. It's not surprising that some of those frequencies would combine harmonically to create the impression of additional notes.
Comment: It all depends where on the fretboard the notes are, which string, how you pluck, where you pluck, which pickups you are using, what distortion, what eq, etc...
Comment: @ToddWilcox then why a similar behaviour cannot be observed with combination of notes with lesser frequency ? I mean, the intervals and relation between those notes are kind of the same, except for the higher amplitude.
Comment: the question was answered [link](http://dsp.stackexchange.com/questions/31151/spectral-plot-shows-more-notes-than-there-really-should-be/31152#31152) . thanks to all who participated.
Comment: Cross posting the same question on multiple SE sites is discouraged. http://meta.stackexchange.com/questions/64068/is-cross-posting-a-question-on-multiple-stack-exchange-sites-permitted-if-the-qu
Answer: Most natural instruments will produce a tone which contains frequencies that are near-multiples of the tone; for some instruments such as the clarinet most such frequencies will be near odd multiples (3x, 5x, 7x, etc.) while other instruments will produce a mixture of even and odd multiples.
For any two frequencies x and y which are present in a signal, harmonic distortion may add additional frequencies Nx+My for any two integers M and N (generally the larger M and N, the less of that frequency will generally be present).  For most kinds of chord using equal temperament, this produces a very nasty sound because a major third has a frequency ratio of about 5.04:4, meaning that a distorted version of the chord will contain significant content at frequencies like 4(5.04)-4(4), i.e. 4.16, or 6(4)-4(5.04), i.e. 3.84, thus yielding a blurry mess.  Power chords have frequencies concentrated in 2x/3x/4x ratios and multiples thereof, meaning most of the harmonic content will be concentrated at multiples of a frequency an octave below the bottom note.
Depending upon the nature of the distortion, it might be possible to do spectral analysis by applying Foorier transforms only to the portions of the source waveforms which don't appear to be distorted, computing how the exclusion of other parts of the waveform would affect the results, and then reversing those effects, but the reliability of that approach would depend upon the nature of the distortion involved and the original frequency content.
Answer: The other notes are not being PLAYED.  But the sound of an instrument depends on several things - largely the characteristics of the initial attack of the note, but also the less complex waveform of the sustained note.  (You might be surprised at the effect of splicing the attack of one instrument onto the sustain of another, and which makes most difference.  A whole system of "hybrid synthesis" with a sampled attack and synthesised sustain exploits this.)
Sometimes an upper harmonic of a note can feature strongly in a spectral analysis.  Your ear, having locked into the pitch of the note's attack may not hear it as strongly as the microphone and computer does.   This is what's happening here I think.


Why is omreport storage vdisk controller=0 inconsistant output across servers

Question: I wrote a script fetching the RAID configuration of the latest VirtualDisk.
On one server I get :
# omreport storage vdisk controller=0 -fmt ssv | awk '-F;' '/^ID/{print}/Virtual\s*Disk\s*[0-9]+;/{line=$0;value=$7}END{print line;print value}'
ID;Status;Name;State;Hot Spare Policy violated;Encrypted;Layout;Size;T10 Protection Information Status;Associated Fluid Cache State ;Device Name;Bus Protocol;Media;Read Policy;Write Policy;Cache Policy;Stripe Element Size;Disk Cache Policy
14;Ok;VirtualDisk16;Ready;Not Applicable;No;RAID-0;7,451.50 GB (8000987201536 bytes);No;Not Applicable;/dev/sdo;SAS;HDD;No Read Ahead;Write Through;Not Applicable;64 KB;Unchanged
RAID-0
#

On another server, I get :
# omreport storage vdisk controller=0 -fmt ssv | awk '-F;' '/^ID/{print}/Virtual\s*Disk\s*[0-9]+;/{line=$0;value=$7}END{print line;print value}'
ID;Status;Name;State;Hot Spare Policy violated;Virtual Disk Bad Blocks;Encrypted;Layout;Size;T10 Protection Information Status;Associated Fluid Cache State ;Device Name;Bus Protocol;Media;Read Policy;Write Policy;Cache Policy;Stripe Element Size;Disk Cache Policy
16;Ok;Virtual Disk 16;Ready;Not Applicable;No;No;RAID-0;3,725.50 GB (4000225165312 bytes);No;Not Applicable;/dev/sdp;SAS;HDD;Read Ahead;Force Write Back;Not Applicable;64 KB;Disabled
No
#

The difference between these two servers is the PERC H730 Mini firmware version :
According to omreport system version, the first has PERC H730 Mini v25.5.2.0001 and the second PERC H730 Mini v25.5.0.0018.
Answer: It probably depends on different omreport or firmware versions. In general, be careful tailoring your script for very specific output, as any small change can break your parsing.


Eliminating vocal vibrato

Question: I am currently working on microtonality (I'm talking about JND pitch differences), and I want to know if solfege would be a possible way of learning this. The only requirement is vibrato smaller that the JND (which means it is totally inaudible). So my question is - how to minimize vibrato? Is it possible to sing with no vibrato (or vibrato smaller that JND)? If yes, what does it require (added force, tension)?
A few extra notes: I am an intermediate singer, and the smallest step in the scale I'm working on (205edo) is 5.85 cents (~JND) - which means the vibrato needs to be smaller than that.
Comment: One doesn't *have* to sing with vibrato. Most good singers can govern it, from none to plenty (too much?), so singing 'straight' maybe needs working on. It requires control. Or have I missed the point?
Comment: I hadn't come across the *edo* acronym before. edo = equal divisions of the octave
Comment: I'm a moderately advanced singer, and I think it would be extremely difficult to moderate ones pitch anywhere nearly as accurately as +/- 3 cents.
Comment: Straight Tone still has vibrato, it's just very small, around 10 cents if I'm not mistaken, at least when we're talking about the average choir. My question refers to whether one can improve straight tone to the point that the vibrato isn't audible.
Comment: I suspect that with an average choir, the vib that is heard is due to beats. An individual should be able to sing straight, and the perceived vib could easily be a fluctuation in tone rather than pitch. A tuner would verify or rubbish this.
Comment: ^vote with a note: Please spell out JND . . . just noticeable difference?
Answer: European solfege is more geared to western musical styles and I'm thinking might be more of a hindrance than a help.  Microtonality doesn't require straight tone, as it's required of good choral singers when singing a cappella and without accompaniment if pure untempered tuning is desired.  That being said, straightening out the vibrato as much as possible will help.  Increasing airflow and focusing on making the sound from air as opposed to making from your throat will help in this.  Increased pressure is often the cause of vibrato, and increasing your vocal pressure may not have your desired effect.  It might be interesting to note that many examples of microtuning come from non-western musical styles.  Many of these diverse styles of singing are devoid of the wide vibrato found in "the western classically trained voice".  Pitch is a funny thing when it comes to the human ear.  We're not so good at determining pitch when the tone is pure and clean (like a sine wave) - so singing microtones in the style of a young choirboy might not demonstrate pitch difference to the listener as much as a singer with a slightly nasal straight tone.  There's just more acoustic information in the more colourful tone than in the pure tone.  Adding some nasality to your sound may assist you in hearing your own tiny pitch changes.
A trained choir can accomplish a sound that is audibly devoid of vibrato, so yes, it's possible.
All THAT being said, vibrato is fluctuation of F0, the fundamental.  The centre point of the fluctuation is the perceived fundamental.  So as long as the vibrato is minimal and even, microtones are definitely perceivable, even with vibrato.  It really depends on the style of music you're using the microtones for....

Eliminating vocal vibrato


Compute the line integral of $x^2 + y^2$ on curve $|x|+|y|=1$

Question:
Compute the integral
$$\int_{\gamma} f(x,y)ds$$
where $\gamma=\{|x|+|y|=1\}$ and $f(x,y)=x^2+y^2$

Note, we have not covered any major theorems on evaluating line integrals, which has been presented is to parametrize the curve then integrate with respect to the parameter(roughly speaking). However, I have no idea how to paramatrize the curve. My intuition tells me we should probably split the curve into four cases, but then the derivative of the parametrizations will be zero? So how would I proceed? Input would be much appreciated!
Comment: @BobDobbs yes I get that, but what should the $\gamma$'s be?
Comment: @William These are not parametrizations. A parametrization is a (differentiable) map $\gamma: [a,b] \to \mathbb{R}^2$.
Comment: $\gamma=\gamma_1+\gamma_2+\gamma_3+\gamma_4$
Comment: "but then the derivative of the parametrizations will be zero?" - This should not happen. Can you provide your parametrizations?
Comment: @Klaus I was thinking $x=-1,x=1,y=-1,y=1$, but I'm not quite sure about this.
Answer: The curve is made of 4 lines in the 4 Quadrants.
Each line has the same value of the required Integral , because of the Squaring & the Modulus , which will convert all Negatives to Positives.
Explaining that Observation : With $(+a,+b)$ on the curve , we will get $(-a,+b) , (+a,-b) , (-a,-b)$ on the curve.  Squaring , we always get $+a^2+b^2$ in all the 4 Quadrants.
Taking first Quadrant , we can use the line $U=1-V$ matching the 2 Corners & the mid-Point.
Now we can Integrate over this line & take 4 times.
Comment: Thank you! Made it much clearer, (I drew a regular square which was my point of confusion) :)
Comment: Nice to know that it was useful !
Answer: $\gamma=\gamma_1+\gamma_2+\gamma_3+\gamma_4$ is the obvious sum of line segments: 1) $\gamma_{1}$ joins $(1,0)$ and $(0,1)$. 2) $\gamma_{2}$ joins $(0,1)$ and $(-1,0)$. 3) $\gamma_{3}$ joins $(-1,0)$ and $(0,-1)$. 4) 2) $\gamma_{4}$ joins $(0,-1)$ and $(1,0)$.
Then, $I=\int_{\gamma}(x^2+y^2)ds=\sum_{i=1}^4I_{i}$ where $I_i=\int_{\gamma_{i}}(x^2+y^2)ds$.
(1) Parametrization of $\gamma_1$: $x=t$, $y=1-t$, $0\leq t\leq 1$. Then $dx=dt$, $dy=-dt$, $ds=\sqrt{dx^2+dy^2}=\sqrt{2}dt$. Hence, $I_1=\int_0^1(t^2+(1-t)^2)\sqrt{2}dt=\sqrt{2}\int_0^1(2t^2-2t+1)dt=\frac{2\sqrt{2}}{3}.$
(2) Parametrization of $\gamma_2$: $x=t$, $y=t+1$, $-1\leq t\leq 0$. Then $dx=dt$, $dy=dt$, $ds=\sqrt{dx^2+dy^2}=\sqrt{2}dt$. Hence, $I_1=\int_{-1}^0(t^2+(1+t)^2)\sqrt{2}dt=\sqrt{2}\int_{-1}^0(2t^2+2t+1)dt=\frac{2\sqrt{2}}{3}.$
Here, we noticed that the orientation is not important.(Why?) Let's dicuss this. It is confusing. We could choose a counter-clockwise orientation of $\gamma_2$: $x=-t$, $y=1-t$, $0\leq t\leq 1$. Then $dx=-dt$, $dy=-dt$, $ds=\sqrt{dx^2+dy^2}=\sqrt{2}dt$. Hence, $I_1=\int_{0}^1((-t)^2+(1-t)^2)\sqrt{2}dt=\sqrt{2}\int_{0}^1(2t^2-2t+1)dt=\frac{2\sqrt{2}}{3}.$ Same result.
It seems that (3) and (4) computations will give the same result: $\frac{2\sqrt{2}}{3}$. Therefore, $I=4(\frac{2\sqrt{2}}{3})=\frac{8\sqrt{2}}{3}$.
Comment: I hope they give the same number.
Comment: Thank you very much for the extensive answer!


Openssl upgrade from source

Question: I have upgraded the openssl version on my server to the latest version of openssl but the libraries that the reverse proxy server is using is pointing to .
  strings /usr/lib64/libssl.so.10 | grep "^OpenSSL "

  OpenSSL 1.0.1e-fips 11 Feb 2013

Where as when i type command
openssl version
it shows
   [root@newreverseproxy openssl-1.0.2]# openssl version
   OpenSSL 1.0.2 22 Jan 2015

I need my reverse proxy server nginx to use the up to date version of OpenSSL would really appreciate if some one could help me up with it .
Comment: Don't run an unregistered version of RH; use CentOS instead, then you won't have an access-to-patches problem.  Also, *why* do you need your nginx to run against the latest OpenSSL?
Answer: the 'problem' is that your ngnix is linked against a particular verion of libssl (libssl.so.10) ... your newly compiled libssl has a different version. Run
ldd `which openssl`

to see which version it is ...
In order for ngnix to use the new version of libssl you have to recompile ngnix as well.
Another option you have is to compile openssl-1.0.1l.tar.gz, which is the latest version of the 1.0.1 line of the software. The resulting libssl will be compatible with 1.0.1e and can be readily used by your existing ngnix binary.
If you are replacing libssl with a newer version, note that this is a rather 'risky' business since many applications use libssl, so better be sure that it works, or many programs may fail to even start.
A nice way to just replace libssl for ngnix, is to install the new libssl into an alternate directroy and then start ngnix with the environment variable LD_LIBRARY_PATH pointing to the new directory. Just make sure the newly compiled library is called exactly the same as the one you find when running ldd on ngnix
export LD_LIBRARY_PATH=/usr/local/new-libssl/lib
ngnix -whatever-options-you-want

Comment: Tried doing it as well still same.
Comment: added a bit more detail
Answer: As well as Tobi's suggestion about openssl versions, you may not be installing the libraries into the correct locations.  If you just run "./configure; make; make install" it will install into /usr/local/lib by default, for example. Even if you set the prefix properly, you might still be installing into /usr/lib/ rather than /usr/lib64, and ldconfig might not be set up properly
However, your distribution almost certainly has updated libraries available that do not involve compilation. Hand-compiling openssl now more or less commits you to hand-compiling it from now on, so this is really a last-resort method. No offence intended here, but if you're having problems getting this to work, it's not the right approach, at least not on a server you care about.
If you are running RedHat, CentOS, Fedora or any other distro that uses .rpm packages, try running 'sudo yum update'. If you are running debian, ubuntu, mint or any other distro that uses .deb packages, try running 'sudo apt-get update; sudo apt-get dist-upgrade'. If you need more help here, try googling for how to update your distro - there are heaps of people posting articles on how to upgrade various linux distributions for GHOST or Heartbleed or poodle, so one of those will have instructions you can use.
Comment: Agreed , But the irony is that that system is not registered to RHN also no RHN repo is available not sure how to workaround from it.

Openssl upgrade from source


hook to alter custom blocks?

Question: I am having a problem with my custom blocks rendering, and I want to programmatically manipulate the blocks to troubleshoot the issue.
I used this question to add this hook to my module:
function mymodule_block_view_alter(array &$build, Drupal\Core\Block\BlockPluginInterface $block) {
  drupal_set_message($block->getBaseId());
}

However, when I navigate to my site, I see only the base ids of system blocks:
- page_title_block
- system_main_block
- help_block
- local_tasks_block

My site's header and footer are made of custom blocks, so I should be seeing their ids.
How can I programmatically access my custom blocks?
Edit this is my actual code:
$ cat my_block_hooks.module
<?php

function my_block_hooks_block_view_alter(array &$build, Drupal\Core\Block\BlockPluginInterface $block) {
  drupal_set_message(__FUNCTION__ . "() id: " . $block->getBaseId() );
}

And here's a screenshot:

You can see that all the system blocks show up, but my custom block does not.
This is the custom block as I have it set up:

And here I have it placed in the layout:

And of course, I've cleared the cache many times to get to this point.
What am I doing wrong?
Comment: Any news on this?
Answer: The type of entity you are dealing with defines the hook you need to implement; in this case it is NOT block but rather block_content, as provided by the "Custom Block" core module.
N.B.: It is generally good practice to use more specific hooks when possible, as it will have a general effect on your code's performance, i.e. your hook implementation will be called less times if it is more specific. In your case, instead of going through all blocks available on any page during page loading, you are going through only custom blocks (block_content entities).
In order to get your hook_ENTITY_TYPE_view()/hook_ENTITY_TYPE_view_alter() implementation to work, you need to replace ENTITY_TYPE with block_content. That should give you the following code (which I tested and works):
use Drupal\block_content\Entity\BlockContent;
...
function my_block_hooks_block_content_view_alter(array &$build, BlockContent $custom_block) {
  drupal_set_message(__FUNCTION__ . "() id: " . $custom_block->id() );
}

And the visual result:

Good luck!
Answer: You're using the built-in custom block which ships with Drupal.
In your code your getting the baseId which is in your case block_content and it is shown in your screenshot actually.
I think you need to use $block->id() instead.
Answer: You can use getPluginId to get the id of the block:
function my_block_hooks_block_view_alter(array &$build, Drupal\Core\Block\BlockPluginInterface $block) {
  drupal_set_message(__FUNCTION__ . "() id: " . $block->getPluginId());
}

here is the result:
Answer: Yes, you should be seeing the IDs of your custom blocks. Here are some things you can try:

Make sure you actually have the custom block nicely defined and placed on your Manage blocks page.
Make sure your custom block is actually visible on the page? Return some temporary output like "foo" from your custom block plugin and make sure that the "foo" is visible on the page.
Try removing cache for your block temporarily by adding $build['#cache']['max-age'] = 0; to your block's output.
Drush drush cr or clear cache and see if your custom block is visible.
Check the visibility rules for your custom block in block configuration. Try removing all visibility rules temporarily and see if the block shows up.
If you've implemented any block access rules, try disabling them to see if your block becomes visible.
Multiple blocks can have the same Base ID. Try doing $block->getPluginId() or $block->id(). In your case, it should give you an item like block_content:UUID where UUID is the unique ID of the custom block you created in your custom block library.

The ID of your block not showing up is basically sounds like your block is not being displayed on the page.
Comment: I've updated my question to address some of the questions you've raised. It's on a new Drupal 8.6.3 clean install, do I don't have any custom visiblity rules (other than what would have come out of the box). Hopefully you can help spot my mistake : )
Comment: Also check that it is  placed in the currently active (default) theme. Sometimes when you have multiple active ones, it might be placed in block set of a non-default one.
Comment: The item `block_content` corresponds to your custom block. Since you're dealing with custom content blocks, the base ID for all blocks created in the custom block library will be `block_content`. So use `$block->getPluginId()` to get the unique block ID. It will be something like `block_content:UUID`.
Comment: Also, it seems like you're new to Drupal. It will be great if you could say the exact problem you're facing while rendering the blocks. Maybe there is an easier solution?
Answer: use Drupal\block_content\Entity\BlockContent;

//...

function my_block_hooks_block_content_view_alter(array &$build, BlockContent $custom_block) {
  drupal_set_message(__FUNCTION__ . "() id: " . $custom_block->id() );
}

You will get your block id here, based on that set condition and override that specific block output.
use Drupal\block_content\Entity\BlockContent;

// ...

function my_block_hooks_block_content_view_alter(array &$build, BlockContent $custom_block) {
    if($custom_block->id() == 5){
       $build['content']['#markup'] = Markup::create('Your text');
    }
}

Answer: I am going to take a wild guess, but have you tried clearing the cache? Custom blocks normally do not contain dynamic data and as such can be heavily cached. This causes the block output to be rendered without your hook getting called.
In the configuration menu go to development > performance and hit the 'Clear all caches' button. Then go back to the page with your blocks and see if it made a change. Alternatively you can install the devel module to clear the cache from each page directly.

hook to alter custom blocks?


Differences between eq and compressor in single wave forms

Question: I mean when you use a single sound, for example a sample kick. Why should i use a compressor when i could use an eq easily? So i would just easily decrease or increase the frequency i want. Do they do the same thing?
Answer: They do not do the same thing.
Compressor: when the sound gets above a threshold, its volume is reduced in a set ratio (3:1 means for every 3 dB increase in the input signal you get 1 dB increase in the output).
This is helpful for reducing the dynamic range of an instrument.
Equalizer: reduces/amplifies all sounds (regardless of their level) by a set amount (e.g. -3 dB) instead of a ratio.
This is helpful for changing the frequency characteristics of an instrument, but does nothing to reduce the dynamic range.
A kickdrum does not produce "a single sound", it produces a broad frequency spectrum, so you'd have to set up a very broad filter on your EQ. You might as well reduce the input gain instead.
Answer: A compressor's typical use case is to narrow the spread between the loudest parts of the sound across all frequencies while an eq is designed to enhance/reduce the levels of certain frequency ranges.
If you have a fairly narrow band of frequencies to work with, you'd achieve the same effect from adjusting the right eq band as a compressor. The difference between the two becomes more apparent when you working with a wider band of frequencies (e.g. a piano playing at different octaves).
Comment: Thank u very much. But i wonder why people mostly  use compressor on a narrow frqs like sample kick or snare. Its easier to use eq. Isnt it?
Comment: @user64789 It boils down to what I'm trying to accomplish. I use eq for certain things and compressors for other things. Sometimes even both at the same time.
Answer: I would typically utilize EQ to affect the tonal aspect of a given track or instrument, whereas I use compressors to affect the dynamics and sometimes to increase the sustain of a track or instrument. These are two different characteristics of sound by themselves and I often use them together to achieve results I cannot achieve without combining them together.
When I first learned to use these toys, I studied everything I could get my hands on to understand what they did and how they functioned, but until I spent many hours playing with them and listening to the results, my initial understanding of their capabilities was incomplete. Book learning is only the beginning, be prepared to spend time getting to know the "feel" of what these devices can do. Welcome to this site.
Comment: A compressor can also "tighten up" transients in a signal. That's IMO the main reason to use it on kick drum.
Comment: @leftaroundabout- I would include that effect in the dynamics part of the answer, but it's good that you pointed that out. Thanks.
Answer: Bro , compressor and eq are  two different things
Eq affects the tone of a sound ( how dull it is or how bright it is ) etc .
Compressor controls the volume difference between the loudest and the quitest part of your sample by reducing the volume of sample once it crosses a certain volume level
compressor on a kick drum can be used to increase kick's transient ( that means that the initial part of your kick drum is low in volume and the part which comes later is louder in volume ) by using slow attack time and suitable release time or you can even tame down that transient ( if it is too much  in volumes and hurting your ears  ) by using fast attack time and suitable release time
You can use eq to balance kick drum's tonal aspects
Summary is - that compressor reduces the difference between quitest and loudest parts of you sample
Eq changes tone of sound
Comment: Bro, why do you start your answers off with "Bro"?
Comment: Haha it's my habit


Same related products throughout the website - Magento

Question: I have a Ecommerce website having lots of products. When I am going to choose related product for one specific product it's automatically showing in all products as related product.
How can I fix this?
I need to have different related products in different products.
Answer: It will show the products related to the search criteria in that grid(first time it will show all the products) and you have to choose the products which are related to that specific product from that list by click the checkbox given there and click save button to get that list as your related products


How to retrieve the object posted to web api end point when exception occurs?

Question: I have a Web Api End point and Exception handler. When something goes wrong i want to find out what was posted to the endpoint. How do i achieve this?
<code>//In my controller
[Route("send/postmodel")]
[HttpPost]
public IHttpActionResult PostModel(MyModel model)
{
    //Exception occured
}

//My Exception Handler
public class ApiExceptionHandler : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        //How do i retrive the object here
    }
}
</code>
I have tried looking in HttpRequestMessage and HttpRequestContext inside ExceptionHandlerContext but no luck.
Comment: Do you want to get `model` value or get raw request data?
Answer: You Can use DelegatingHandler to Log Each request and response you send and receive which will help you too log your Exception.
Code Snippet
<code> public class ApiLogHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var apiLogEntry = CreateApiLogEntryWithRequestData(request);

        if (request.Content != null)
        {
            request.Content.ReadAsStringAsync()
               .ContinueWith(task =>
               {
                   apiLogEntry.RequestContentBody = task.Result;
               }, cancellationToken);
        }

        return base.SendAsync(request, cancellationToken)
            .ContinueWith(task =>
            {
                var response = task.Result;

                // Update the API log entry with response info
                apiLogEntry.ResponseStatusCode = (int)response.StatusCode;
                apiLogEntry.ResponseTimestamp = DateTime.Now;

                if (response.Content != null)
                {
                    apiLogEntry.ResponseContentBody = response.Content.ReadAsStringAsync().Result;
                    apiLogEntry.ResponseContentType = response.Content.Headers.ContentType.MediaType;
                    apiLogEntry.ResponseHeaders = SerializeHeaders(response.Content.Headers);
                }

                // TODO: Save the API log entry to the database
                InsertAPILog(apiLogEntry);

                return response;
            }, cancellationToken);
    }

    private ApiLogEntry CreateApiLogEntryWithRequestData(HttpRequestMessage request)
    {
        var context = ((HttpContextBase)request.Properties["MS_HttpContext"]);
        var routeData = request.GetRouteData();

        return new ApiLogEntry
        {
            Application = "[Logging]",
            User = context.User.Identity.Name,
            Machine = Environment.MachineName,
            RequestContentType = context.Request.ContentType,
            RequestRouteTemplate = routeData.Route.RouteTemplate,
            RequestRouteData = SerializeRouteData(routeData),
            RequestIpAddress = context.Request.UserHostAddress,
            RequestMethod = request.Method.Method,
            RequestHeaders = SerializeHeaders(request.Headers),
            RequestTimestamp = DateTime.Now,
            RequestUri = request.RequestUri.ToString()
        };
    }

    private string SerializeRouteData(IHttpRouteData routeData)
    {
        return JsonConvert.SerializeObject(routeData, Formatting.Indented);
    }

    private string SerializeHeaders(HttpHeaders headers)
    {
        var dict = new Dictionary<string, string>();

        foreach (var item in headers.ToList())
        {
            if (item.Value != null)
            {
                var header = String.Empty;
                foreach (var value in item.Value)
                {
                    header += value + " ";
                }

                // Trim the trailing space and add item to the dictionary
                header = header.TrimEnd(" ".ToCharArray());
                dict.Add(item.Key, header);
            }
        }

        return JsonConvert.SerializeObject(dict, Formatting.Indented);
    }

    private void InsertAPILog(ApiLogEntry apiLogEntry)
    {
        try
        {
            using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["API_Logging"].ToString()))
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("API_LoggingRequest", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Application", apiLogEntry.Application);
                cmd.Parameters.AddWithValue("@User", apiLogEntry.User);
                cmd.Parameters.AddWithValue("@Machine", apiLogEntry.Machine);
                cmd.Parameters.AddWithValue("@RequestIpAddress", apiLogEntry.RequestIpAddress);
                cmd.Parameters.AddWithValue("@RequestContentType", apiLogEntry.RequestContentType);
                cmd.Parameters.AddWithValue("@RequestContentBody", apiLogEntry.RequestContentBody);
                cmd.Parameters.AddWithValue("@RequestUri", apiLogEntry.RequestUri);
                cmd.Parameters.AddWithValue("@RequestMethod", apiLogEntry.RequestMethod);
                cmd.Parameters.AddWithValue("@RequestRouteTemplate", apiLogEntry.RequestRouteTemplate);
                cmd.Parameters.AddWithValue("@RequestRouteData", apiLogEntry.RequestRouteData);
                cmd.Parameters.AddWithValue("@RequestHeaders", apiLogEntry.RequestHeaders);
                cmd.Parameters.AddWithValue("@RequestTimestamp", apiLogEntry.RequestTimestamp);
                cmd.Parameters.AddWithValue("@ResponseContentType", apiLogEntry.ResponseContentBody);
                cmd.Parameters.AddWithValue("@ResponseContentBody", apiLogEntry.ResponseContentBody);
                cmd.Parameters.AddWithValue("@ResponseStatusCode", apiLogEntry.ResponseStatusCode);
                cmd.Parameters.AddWithValue("@ResponseHeaders", apiLogEntry.ResponseHeaders);
                cmd.Parameters.AddWithValue("@ResponseTimestamp", apiLogEntry.ResponseTimestamp);
                cmd.ExecuteNonQuery();
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

}
</code>


Hope for any help with this delta function question

Question: I don't know how to show X is a vector space and what does "onto" mean......
Let X be the collection of functions u in $C^\infty(R^2)$ that vanish outside a ball(Each u has its own ball) and $Z = R^2$. Define the gradient of the delta function:
$\iint_{R^2}\nabla\delta(x)u(x)dx = -\nabla\ u(0)$.  Show that $\nabla\delta : X \to Z $ is a linear operator. Is $\nabla\delta$ onto?
Answer: The linearity of the operator is due to the linearity of the gradient:
$$\int_{\mathbb{R}^2} \nabla \delta(x) (\alpha u(x)+\beta v(y)) \ dx=-\nabla(\alpha u(0)+\beta v(0))= -\alpha\nabla u(0)-\beta\nabla v(0) $$
Therefore if $F(u)=\int_{\mathbb{R}^2} \nabla \delta(x)u(x) dx$ we have $F(\alpha u + \beta v)= \alpha  F(u)+\beta F(v)$.
Now, if you want to show that the operator is surjective (onto) you have to ask yourself the following question: For every $(a,b)$ in $\mathbb{R}^2$ Can I find a $C^\infty$ function $u(x)$ such that $-\nabla u(0)=(a,b)$? Take $u(x,y)=ax+by$ (except in a ball) for example.


Why is std::type_info polymorphic?

Question: Is there a reason why std::type_info is specified to be polymorphic? The destructor is specified to be virtual (and there's a comment to the effect of "so that it's polymorphic" in The Design and Evolution of C++). I can't really see a compelling reason why. I don't have any specific use case, I was just wondering if there ever was a rationale or story behind it.

Here's some ideas that I've come up with and rejected:

It's an extensibility point - implementations might define subclasses, and programs might then try to dynamic_cast a std::type_info to another, implementation-defined derived type. This is possibly the reason, but it seems that it's just as easy for implementations to add an implementation-defined member, which could possibly be virtual. Programs wishing to test for these extensions would necessarily be non-portable anyway.
It's to ensure that derived types are destroyed properly when deleteing a base pointer. But there are no standard derived types, users can't define useful derived types, because type_info has no standard public constructors, and so deleteing a type_info pointer is never both legal and portable. And the derived types aren't useful because they can't be constructed - the only use I know for such non-constructible derived types is in the implementation of things like the is_polymorphic type trait.
It leaves open the possibility of metaclasses with customized types - each real polymorphic class A would get a derived "metaclass" A__type_info, which derives from type_info. Perhaps such derived classes could expose members that call new A with various constructor arguments in a type-safe way, and things like that. But making type_info polymorphic itself actually makes such an idea basically impossible to implement, because you'd have to have metaclasses for your metaclasses, ad infinitum, which is a problem if all the type_info objects have static storage duration. Maybe barring this is the reason for making it polymorphic.
There's some use for applying RTTI features (other than dynamic_cast) to std::type_info itself, or someone thought that it was cute, or embarrassing if type_info wasn't polymorphic. But given that there's no standard derived type, and no other classes in the standard hierarchy which one might reasonably try cross-cast to, the question is: what? Is there a use for expressions such as typeid(std::type_info) == typeid(typeid(A))?
It's because implementers will create their own private derived type (as I believe GCC does). But, why bother specifying it? Even if the destructor wasn't specified as virtual and an implementer decided that it should be, surely that implementation could declare it virtual, because it doesn't change the set of allowed operations on type_info, so a portable program wouldn't be able to tell the difference.
It's something to do with compilers with partially compatible ABIs coexisting, possibly as a result of dynamic linking. Perhaps implementers could recognize their own type_info subclass (as opposed to one originating from another vendor) in a portable way if type_info was guaranteed to be virtual.

The last one is the most plausible to me at the moment, but it's pretty weak.
Answer: The C++ standard says that typeid returns an object of type type_info, OR AN IMPLEMENTATION-DEFINED subclass thereof. So... I guess this is pretty much the answer. So I don't see why you reject your points 1 and 2.
Paragraph 5.2.8 Clause 1 of the current C++ standard reads:

The result of a typeid expression is an
  lvalue of static type const
  std::type_info (18.5.1) and dynamic
  type const std::type_info or const
  name where name is an
  implementation-defined class derived
  from std::type_info which preserves
  the behavior described in 22.214.171.124)
  The lifetime of the object referred to
  by the lvalue extends to the end of
  the program. Whether or not the
  destructor is called for the type_info
  object at the end of the program is
  unspecified.

Which in turn means that one could write the following code is legal and fine:
const type_info& x = typeid(expr); which may require that type_info be polymorphic
Comment: Yes, I get that, but I can't see anything portable that you can do with the information that it's a subclass, or not. It seems like all portable, valid programs now would still be valid if it weren't polymorphic. Making it so that you couldn't necessarily detect subclasses (by making type_info not polymorphic) shouldn't change anything for portable programs, as far as I can see, and shouldn't make non-portable extensions any harder to create. Can you think of a counter-example, of something made possible by this spec?
Comment: Thanks - but I still don't understand why that last expression requires `type_info` to be polymorphic. All the useful functions on `type_info`, like `operator==`, `before`, `name`, etc. aren't specified as virtual. So if an implementation needs virtual dispatch on those functions, then I suppose it can declare them virtual, or delegate to virtual implementation functions, and if it doesn't, then it doesn't need to make them virtual. Is there something I'm missing?
Comment: @Matthieu M.: definitely, you can, but such a cast would be implementation-specific. There are lots of ways an extension like that could be provided without mandating that `std::type_info` is polymorphic in all cases.
Comment: If you are returned a derived class, you can up-cast it (`dynamic_cast` / `static_cast`) and provide MORE methods.
Answer: I assume it's there for the convenience of implementers. It allows them to define extended type_info classes, and delete them through pointers to type_info at program exit, without having to build in special compiler magic to call the correct destructor, or otherwise jump through hoops.

surely that implementation could
  declare it virtual, because it doesn't
  change the set of allowed operations
  on type_info, so a portable program
  wouldn't be able to tell the
  difference.

I don't think that's true. Consider the following:
#include <typeinfo>

struct A {
    int x;
};

struct B {
    int x;
};

int main() {
    const A *a1 = dynamic_cast<const A*>(&typeid(int));
    B b;
    const A *a2 = dynamic_cast<const A*>(&b);
}

Whether it's reasonable or not, the first dynamic cast is allowed (and evaluates to a null pointer), whereas the second dynamic cast is not allowed. So, if type_info was defined in the standard to have the default non-virtual destructor, but an implementation added a virtual destructor, then a portable program could tell the difference[*].
Seems simpler to me to put the virtual destructor in the standard, than to either:
a) put a note in the standard that, although the class definition implies that type_info has no virtual functions, it is permitted to have a virtual destructor.
b) determine the set of programs which can distinguish whether type_info is polymorphic or not, and ban them all. They may not be very useful or productive programs, I don't know, but to ban them you have to come up with some standard language that describes the specific exception you're making to the normal rules.
Therefore I think that the standard has to either mandate the virtual destructor, or ban it. Making it optional is too complex (or perhaps I should say, I think it would be judged unnecessarily complex. Complexity never stopped the standards committee in areas where it was considered worthwhile...)
If it was banned, though, then an implementation could:

add a virtual destructor to some derived class of type_info
derive all of its typeinfo objects from that class
use that internally as the polymorphic base class for everything

that would solve the situation I described at the top of the post, but the static type of a typeid expression would still be const std::type_info, so it would be difficult for implementations to define extensions where programs can dynamic_cast to various targets to see what kind of type_info object they have in a particular case. Perhaps the standard hoped to allow that, although an implementation could always offer a variant of typeid with a different static type, or guarantee that a static_cast to a certain extension class will work, and then let the program dynamic_cast from there.
In summary, as far as I know the virtual destructor is potentially useful to implementers, and removing it doesn't gain anyone anything other than that we wouldn't be spending time wondering why it's there ;-)
[*] Actually, I haven't demonstrated that. I've demonstrated that an illegal program would, all else being equal, compile. But an implementation could perhaps work around that by ensuring that all isn't equal, and that it doesn't compile. Boost's is_polymorphic isn't portable, so while it's possible for a program to test that a class is polymorphic, that should be, there may be no way for a conforming program to test that a class isn't polymorphic, that shouldn't be. I think though that even if it's impossible, proving that, in order to remove one line from the standard, is quite a lot of effort.
Answer:
3/ It leaves open the possibility of metaclasses with customized types - each real polymorphic class A would get a derived "metaclass" A__type_info, which derives from type_info. Perhaps such derived classes could expose members that call new A with various constructor arguments in a type-safe way, and things like that. But making type_info polymorphic itself actually makes such an idea basically impossible to implement, because you'd have to have metaclasses for your metaclasses, ad infinitum, which is a problem if all the type_info objects have static storage duration. Maybe barring this is the reason for making it polymorphic.

Clever...
Anyway, I disagree with this reasoning: such implementation could easily rule-out meta classes for types derived from type_info, including type_info itself.
Answer: About the simplest "global" id you can have in C++ is a class name,and typeinfo provides a way to compare such id's for equality. But the design is so awkward and limited that you then need to wrap typeinfo in some wrapper class, e.g. to be able to put instances in collections. Andrei Alexandrescu did that in his "Modern C++ Design" and I think that that typeinfo wrapper is part of the Loki library; there's probably one also in Boost; and it's pretty easy to roll your own, e.g. see my own wrapper.
But even for such a wrapper there's not in general any need for a virtual destructor in typeinfo.
The question is therefore not so much "huh, why is there a virtual destructor" but rather, as I see it, "huh, why is the design so backward, awkward and not directly usable"? And I'd put that down to the standardization process. For example, iostreams are not exactly examples of superb design, either; not something to emulate.
Comment: I sort-of have an answer to "huh, why is the design so backward, awkward and not directly usable?". It's basically because Bjarne Stroustrup (a) wanted to discourage people from relying on RTTI too much, and (b) got lots of requests for all sorts of RTTI-related features, some of which violated C++'s type safety. He thought it would be a lot of trouble to satisfy everyone's requests, as well as being potentially high-overhead and technically dubious, so it was easiest to just provide a bare-bones feature that people could build on according to their needs.

Why is std::type_info polymorphic?


distributed system programming with php

Question: I'm doing a system for a hospital in my country as the final year project of my degree, my supervisor specially asked me to use php and mysql for this. i don't have any experience with distributed systems and php programming, can any one help me out to build my base and improove my knowledge stating some sites, books to refer to overcome this matter.
regards,
rangana.
Comment: Distributed? PHP? HOSPITAL? I see a lot of people die in the future.
Comment: @LukeN The fact that PHP is a (sometimes too) permissive language and has a great semi-professional following does not mean it is not possible to develop highly secure, stable, professional software in it. (I still laughed about your 1st comment :). If the word "distributed" is anything serious, though, the standard run-off-the-mill PHP tutorial isn't going to cut it.
Comment: PHP has gotten a really bad reputation. It's insecure and really easy to introduce mistakes that are hard to find with. If you google for PHP tutorials, you will find tons of ressource on PHP itself, as it's immensly popular because it's so easy (the consequence of that is what you can read in my second sentence.). Most tutorials cover MySQL too, because PHP has support for MySQL built in.
Comment: don't know buddy, i don't know how these things cope up with each other but, only thing i know is, he asked me to refer about distributed systems, and do it using php and mysql??? please clear me on this matter???
Comment: @rangana I think your supervisor needs to clarify what exactly they mean by "distributed".
Comment: Is the "supervisor" in charge of the hospital or your degree program?
Comment: @Pekka Of course it is possible to write high secure and reliable software with PHP, but so is it with assembler and brainf*ck :) I just think I'll never understand what's going on in the average "supervisor's" head. They never seem to know what they're talking about ;)
Comment: @LukeN I see what you mean but I have to disagree. PHP 5 and - among other things - QA tools like PHPUnit and other notable tools by Sebastian Bergmann (http://sebastian-bergmann.de/software/) make it possible to work with PHP in a very, very high-level way. The fact that PHP doesn't enforce that way from the start is both its charm and its curse - you can still see its templating language roots there, no doubt. Still, PHP is fine if handled correctly. You just shouldn't *learn programming* with PHP alone IMO.
Answer: I'm guessing you want something like this
Answer: You might want to consider the literature on the following topic:

3 Tier Application Architectures (or N-tier in general)

Tiers in general would be the DataStore (an RDBMs usually), the Business Logic Layer and the Presentation Layer.
Each layer can be examined and analyzed thoroughly, depending on your needs and solutions such as Load Balancing, Workload Distribution (in a sometimes clustered environment), Database Clustering/Replication/Splitting, might be needed.
Good luck with your project.
Comment: thank you very much for your valuable comments and suggestions guys, i highly appreciate it, thanks again...!

distributed system programming with php


What values of $j$ makes the congruence solvable when $a \leq b$?

Question: What values of $j$ makes the congruence solvable when $a \leq b.$?
$$0 \equiv xp^{s}j + yp^t\pmod{p^a} $$ where $x,y$ are not divisible by $p.$ and $s,a$ are any integers and $a \leq b.$
Since the given congruence above is equivalent to $xp^{a+s−b}j + yp^t = u p^b $ for some $u$; and then I have to divide both sides by $p^m$ where $m= \operatorname{min} \{s,t,a\}$, then my answer for the question what values of $j$ that makes this congruence solvable is as follows:
If $m=a$
Then the equation is satisfied for all $j$.
If $m\ne a, t = m$
Then $x p ^{s-t}j + y = u p^{a-t}$ and since $p$ is not a factor of $y$ then there are no solutions.
If $m\ne a, t \ne m$
Then $xj + yp^{t-s} = u p^{a-s}$ and since $p$ is not a factor of $x$ there are no solutions.
Is my solution correct?
I have followed exactly the same procedure given to me in the solution here:
what values of $j$ makes this congruence solvable?
Answer: You seem to have the right idea and there are lots of correct deductions, but there are errors:-
The equation on line 4 should be $$xp^sj + yp^t = u p^a.$$
The $m=a$ case is handled correctly.
In the second case, there can be solutions when $s=t$.
In the final case, your equation $xj + yp^{t-s} = u p^{a-s}$ is correct but there may be solutions when $j$ is divisible by $p$. For example, when $a=t$ and $j=Jp^{a-s}$, the equation becomes $xJ+y=u$ and so there are infinitely many solutions for $x$ and $y$.
Let's deal with one such case which you didn't consider:-
If $m=s=t$, $m\ne a$
Then $$xj + y = u p^{a-m}.$$
For any $j$ not divisible by $p$ we can therefore choose $y=up^{a-m}-xj$.
Comment: Yes to the second of the above queries. For the final case, I have added the explanation into the answer. I hope that helps.
Comment: Yes that's right because $y$ would have to be divisible by $p$ in that case.
Comment: Why , in the second case , there can be solutions when $s=t$? could you clarify please?
Comment: I think the answer of my previous comment is the case $m=s=t, m\neq a $ you are considering at the end of your solution ..... am I correct?
Comment: Why in the final case there may be solutions when $j$ is divisible by $p,$ could you please explain that in details?
Comment: Here is another question (more general to my previous 2 questions) just in case you want to answer it. https://math.stackexchange.com/questions/3988796/for-what-values-of-l-and-j-simultaneously-is-the-following-congruence-solv
Comment: For the second case, if $j$ is divisible by $p$ there will be no solution ..... correct?


Android BufferedWriter : Empty File Saved.

Question: I am facing a problem and unable to identify it. The case is, I have an activity from which I am saving a JSON file to the storage on some button click. There are times when the file is an empty file(0 KB). So, most of the times it work as expected but this 0 KB file created a headache. There is no exception at all.
Thanks in advance!
BufferedWriter bw = null;

try {
    File file = new File(path);
    if (!file.exists()) {
        file.createNewFile();
    }
    bw = new BufferedWriter(new FileWriter(file, false));
    bw.write(content);

} catch (Exception e) {
    Logger.e(mContext,"Write To File",e.toString());
}
finally {
    try {
        if (bw != null) {
           bw.close();
        }
    }catch (Exception e)
    {
        Logger.e(mContext,"Write To File",e.toString());
    }
}

Comment: please verify that "content" variable isn't empty in those cases add:
    Logger.d(mContext,"content",content);
check the logcat when the file is empty
Comment: @Khaledvic : No there is no place where i am writing into the same file.
Comment: Have you stepped through the code with a debugger?
Comment: Yes, but the problem is, one in 1000 times it happens. I had wrote a test case to test this function but couldn't replicate the issue.
Comment: are you using the exact file else where in your application? maybe somewhere you open the file for writing and truncate the file
Comment: I have a doubt that when the file is being written and suddenly the user forcefully closes the application  then in this case Can the file be empty?
Comment: @AnkitSingh I think it's extremely unlikely to force close the application in the middle of the short block of code above
Answer: I had the same issue. Solved it that way:
fw = new FileWriter(file, false);
bw = new BufferedWriter(fw);
...
bw.flush();
bw.close();
fw.close();


How do I convert nested python lists to c structures?

Question: Ive been given a "json parser" python module that parses json files and returns a list of structures from the json file. Ive been asked to write a python module that takes this list and converts it into a ".h" file filled with c structures. My problem is that the json files can contain many nested lists (meaning nested lists within nested lists etc. etc.) and i just cant seem to get the right code to access these.
Also every element of these lists has a key-value pair called "position" and i want to be able to sort the structures after this key-value pair and create a ".h" file with the sorted structures but im not sure if my code will do the trick.
My idea was to create a for loop that goes through the list and if it finds another list within that list checks this nested list for more nested lists etc. Im fairly new to python, could i solve this problem with a recursive function? If so, how?
method to go through the lists (only works for nested lists in the first list)
def test(liste):
        for inner_l in liste:
            for item in inner_l:
                print(item)

my sort function
def takeFourth(elem):
        return elem[3]

neueListe = neueListe + x.sort(key=takeFourth)

expected results, final .h file should look like this:
struct SubStructOfSubStruct
{
    int MyInteger;
};

struct ThirdSubStructType
{
    float MyFloatValue;
    double MyDoubleValue;
    struct SubStructOfSubStructType SubStructOfSubStruct;
};

struct SubStructType
{
    float MyFloatValue;
    double MyDoubleValue;
};

struct SecondSubStructType
{
    int MyInteger;
};

struct Toplevel
{
    struct ThirdSubStructType ThirdSubStruct;
    struct SubStructType SubStruct;
    char MyString[10];
    boolean MyBoolValue;
    double MyDoubleValue;
    float MyFloatValue;
    int MyInteger;
    struct SecondSubStructType SecondSubStruct;
};

This is where im at, this is the list that the parser returns that i want to go through and create structures of:
(the last value in the lists is the "position" value that i want to sort after)
[['SubStructOfSubStructType ', [['Integer', 'MyInteger', 33, 0]]],
['ThirdSubStructType ', [['TreeNode', 'SubStructOfSubStructType', 'SubStructOfSubStruct', 2], ['Double', 'MyDoubleValue', 100, 0], ['Float', 'MyFloatValue', 22, 1]]],
['SecondSubStructType', [['Integer', 'MyInteger', 333, 0]]],
['SubStructType', [['Double', 'MyDoubleValue', 1000, 0], ['Float', 'MyFloatValue', 222, 1]]],
['Toplevel', [['TreeNode', 'ThirdSubStructType', 'ThirdSubStruct', 7], ['Float', 'MyFloatValue', 2, 1], ['Boolean', 'MyBoolValue', False, 2], ['Double', 'MyDoubleValue', 10, 0], ['Integer', 'MyInteger', 3, 3], ['TreeNode', 'SecondSubStructType', 'SecondSubStruct', 6], ['String', 'MyString', 'Leer', 4], ['TreeNode', 'SubStructType','SubStruct',5]]]]

Answer: For recursive list processing, you need to identify whether what you are looking at is a list or a leaf:
def test(liste):
    if isinstance(liste,list):
        for inner_l in liste:
            test(inner_l)
    else:
        print('item: {}'.format(liste))

Since you want to be able to locate structs and treat them as a unit, it might help to have helper functions to identify stuff you're looking for. You can use the same technique to look for a pattern of a label followed by a single list of members:
def is_struct(liste):
    return not isinstance(liste[0],list) and isinstance(liste[1],list) and len(liste) == 2

Then you can put them together:
def test(liste):
    if isinstance(liste,list):
        if is_struct(liste):
            print('struct {}'.format(liste[0]))
            for item in liste[1]:
                print('  var: {}'.format(item))
        else:
            for inner_l in liste:
                test(inner_l)
    else:
        print('unexpected: {}'.format(liste))

This technique should handle arbitrarily nested list structures. You could extend it to handle C-style nested structs.
Comment: thank you so much for you answer :) it really helped! im so close to my expected results. Do you perhaps have an idea on how i could implement a sorting algorithm that sorts the structs and their inner elements after their "position" value (last element in list) and then print it out without the values, so i get the expected results above?
Comment: also could u explain this part here: "return not isinstance(liste[0],list) and isinstance(liste[1],list) and len(liste) == 2". i understand that it returns True if liste does not contain a sublist but i dont understand why it only looks at liste[0], liste[1] and checks if len(liste) == 2
Comment: We need to tell whether a list is a struct, or just another list we need to recurse into. A C struct should always have a pattern: it is a list that contains exactly two elements, the first is a name, and the second is a list of members. Liste[0] verifies that the first item is a name not a list, liste[1] must be a list not a name, and len(liste) must be exactly two.
Comment: You already developed the basic means of sorting inner elements. You probably want to use "sorted(liste[1], key=takeFourth)". For sorting the structs by name, I'd be inclined to place each completed struct into a new list and sort that. It would be complicated to try and do it in the recursive algorithm.


mysql jdbc not batching queries even after rewriteBatchedStatements = true

Question: I've been reading all over the internet + stackoverflow on why jdbc batch update is so slow. Looks like the proper fix is to set rewriteBatchedStatements = true in the connection string.  But I cant seem to get it to work for me.
I am using springboot and spring-jdbc
Ive set rewriteBatchedStatements = true in my  application.properties
spring.datasource.url=jdbc:mysql://RDS_URL.us-west-2.rds.amazonaws.com/DATABASE?rewriteBatchedStatements=true

I have also set a breakpoint to verify that the ?rewriteBatchedStatements=true is reflected in code
I have general_log set to true and when watching the logs I see that the inserts are not being properly batched
This is what my sql string looks like
private static String INSERT_USER_TO_GROUP_SQL = "INSERT INTO users (groupId, phoneNumber, accountId, source) VALUES(?, ?, ?, ?)";

The lines in the logs all look like this
45 Query   INSERT INTO users (groupId, phoneNumber, accountId, source) VALUES('49', '99999999999', '123', 'web')
My java code to do the batch insert is
executor.submit(() -> {
  jdbcTemplate.batchUpdate(INSERT_USER_TO_GROUP_SQL, new BatchPreparedStatementSetter() {

    @Override
    public void setValues(PreparedStatement ps, int i) throws SQLException {
      Subscriber subscriber = subscribers.get(i);
      ps.setString(1, subscriberGroup.getGroupId());
      ps.setString(2, subscriber.getPhoneNumber());
      ps.setString(3, accountId);
      ps.setString(4, subscriberGroup.getSource());
    }

    @Override
    public int getBatchSize() {
      return subscribers.size();
    }

  }); // end BatchPreparedStatementSetter lambda class
}); // end thread

Here is a snippet from the method batchUpdate looks like this, as you can see it calls addBatch(), then finally executeBatch()
for (int i = 0; i < batchSize; i++) {
    pss.setValues(ps, i);
    if (ipss != null && ipss.isBatchExhausted(i)) {
        break;
    }
    ps.addBatch();
}
return ps.executeBatch();

Here is the table i am inserting into
CREATE TABLE `users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `phoneNumber` varchar(20) DEFAULT NULL,
  `groupId` varchar(11) DEFAULT NULL,
  `source` varchar(30) DEFAULT NULL,
  `accountId` varchar(50) DEFAULT NULL,
  `deleted` int(1) DEFAULT '0',
  `timestamp` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `phoneNumber` (`phoneNumber`,`groupId`,`accountId`)
) ENGINE=InnoDB AUTO_INCREMENT=21677 DEFAULT CHARSET=latin1;

ALSO I have even tried not relying on jdbc.batchUpdate() and doing it myself. With still no luck
    Connection connection = jdbcTemplate.getDataSource().getConnection();
    connection.setAutoCommit(false);
    PreparedStatement preparedStatement =
    connection.prepareStatement(INSERT_USER_TO_GROUP_SQL);

    preparedStatement.setString(1, "1");
    preparedStatement.setString(2, "2");
    preparedStatement.setString(3, "3");
    preparedStatement.setString(4, "4");
    preparedStatement.addBatch();

    preparedStatement.setString(1, "11");
    preparedStatement.setString(2, "22");
    preparedStatement.setString(3, "33");
    preparedStatement.setString(4, "44");
    preparedStatement.addBatch();

    preparedStatement.executeBatch();
    connection.commit();

ALSO I tried to rule out issues with prepared statements so I tried just hard coding queries. Still no luck.
Connection connection = jdbcTemplate.getDataSource().getConnection();
Statement statement = connection.createStatement();
statement.addBatch("INSERT INTO users (groupId, phoneNumber, accountId, source) VALUES('1', '2', '3', '4')");
statement.addBatch("INSERT INTO users (groupId, phoneNumber, accountId, source) VALUES('11', '22', '33', '44')");
statement.executeBatch();

This is the version of jdbc in my pom
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
    <version>1.5.2.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>4.3.6.RELEASE</version>
</dependency>

Im expecting this parameter to speed up the insert and for the logs to show a properly batched insert statement. Most SO articles show people just setting rewritebatchedstatements = true in the url and it works.
Comment: Thanks for that. I edited the title as i'm not really concerned about the particular query performance, it should be quick as it's just an insert, and I dont think this is a typical, "why is my query slow" question
Im more interested in why the rewritebatchedstatements = true isnt being respected and properly batching the inserts. Ive added the table structure and autocommit and its currently turned to on
Comment: Please read this, especially the section on query performance. http://meta.stackoverflow.com/a/271056/  Then please [edit] your question to provide more information.  In the meantime, please figure out whether you have autocommit turned on, or whether you are wrapping multiple `INSERT` statements in `BEGIN TRANSACTION` / `COMMIT` blocks in your SQL.
Comment: Where's your code that uses the `addBatch()` and `executeBatch()` methods? The performance gain from a rewrite comes from using a batch to do a multirow insert, and thereby cuttting down on the number of implicit `COMMIT` operations performed by the database server.  Are you calling `addBatch()` a whole mess of times before you call `executeBatch()`?   https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#addBatch(java.lang.String)
Comment: Yes I am. Ive added a snippet of the implementation of jdbcTemplate.batchUpdate() which I am using in my first example, that method calls addBatch() and executeBatch(). Also Ive added another snippet of what I've tried, where I call addBatch() and executeBatch() explicitly without using the built in JdbcTemplate method batchUpdate()
Answer: For others having the issue of jdbcTemplate connection url not honoring rewriteBatchedStatements = true Check your mysql-connector-java version in your pom.xml
At the time of writing this question I had
<dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.9</version>
</dependency>

Since my batch writes were happening one by one it appears that version 5.1.9 doesn't support batch updates, and falls back as noted in the spring docs

batchUpdate() -- Will fall back to separate updates on a single Statement if the JDBC driver does not support batch updates.

Bumping this to version 5.1.18 gave me proper batch updates, verified in mysql general log.
Also a bug I ran into which might save others some time. In version 5.1.23, when you configure the db url to include profileSQL=true which I imagine most do, there's a bug with the driver and profileSQL.


Is the normed space of bounded convergent sequences closed?

Question: Suppose we have the normed space of bounded real sequences with the uniform norm. Is the subset consisting of convergent sequences closed?
Comment: Yes, it is.  Where did you get stuck in trying to prove it?
Comment: Try showing instead that $x$ is Cauchy.
Comment: All you really need is that there exists $y \in X$ with $\|y-x\|_{\infty} < \epsilon$, or perhaps $\epsilon /3$, and $y$ convergent/Cauchy.
Comment: Fix $\epsilon > 0$.  You have to find an $N$ such that... something something... holds for $x$.  But you can choose an $N$ such that... something something... holds for $y$.  And you know that for any $k$, $|x^k - y^k| < \epsilon/3$ or something...
Comment: Let's call the subset $X$. Suppose $\{x_n\}$ is a convergent sequence in $X$ with limit $x$. So I am trying to show that $x$ is convergent. I have no idea what to do from here...
Comment: Well, I know that for all $\epsilon > 0$, there exists $N \in \mathbb{N}$ such that $ n > N $ implies $||x_n - x||_\infty < \epsilon $ so $sup_k |x^k_n - x^k| < \epsilon$. But how does that help in showing that $x$ is Cauchy?
Comment: And I have such a $y$. Just pick any of the $x_n$. But how does that show $x$ is Cauchy?
Comment: May not be too hard to show the complement, containing unbounded divergent sequences is open.
Comment: Thanks, Nate! I have it. =)
Answer: Let $S=\{0,1,1/2,1/3,1/4,\cdots\}$. Then $S$ is a compact set in the relative topology of $[0,1]$; hence $C(S)$ is a Banach space under the usual sup norm.
Every $f \in C(S)$ defines a convergent sequence $\{ x_{n}\}_{n=1}^{\infty}$ by $x_{n}=f(1/n)$ with $\lim_{n} x_{n}=f(0)$. Conversely, if $\{ x_{n} \}$ is a convergent sequence, then $f(1/n)=x_{n}$, $f(0)=\lim_{n}x_{n}$ defines $f \in C(S)$. The norm of $f \in C(S)$ is the same as $\sup_{n} |x_{n}|$.


Testing Script - Find open MySQL Ports and check Database

Question: following Problem:
I want to Check all Open MySQL Ports in a network and give myself a list of them.

After this i want to check if i can get access to the MySQL database from the open ports.

It Would be just a security check script to avoid other people getting access to the databases.
Bash/perl/Powershell... maybe someone can give me a hint?
Answer: You can use NMAP for all port scanning tasks.
EDIT:
Lets asssume an example: mysql-vuln-cve2012-2122(This vulnerability tries to access the MySql server through open ports by bypassing authentication, if possible, also dumps the MySQL usernames and password hashes.)
Pre-requisite: You need the 'Vulns' library to be installed separately. Please read the documentation, to know more about how to install and other details, since it would be too tedious to explain it here.
mysql-vuln-cve2012-2122.pass
MySQL password. Default: nmapFTW.

mysql-vuln-cve2012-2122.user
MySQL username. Default: root.

mysql-vuln-cve2012-2122.iterations
Connection retries. Default: 1500.

mysql-vuln-cve2012-2122.socket_timeout
Socket timeout. Default: 5s.

Please leave the password blank to check for non-password vulnerabilities.
Command to run:
nmap -p3306 --script mysql-vuln-cve2012-2122 <target>

Here  is your MySql instance
This will give an output, something like this:
PORT     STATE SERVICE REASON
3306/tcp open  mysql   syn-ack
mysql-vuln-cve2012-2122:
VULNERABLE:
Authentication bypass in MySQL servers.
State: VULNERABLE
 IDs:  CVE:CVE-2012-2122
  Description:
    When a user connects to MariaDB/MySQL, a token (SHA
    over a password and a random scramble string) is calculated and
compared
    with the expected value. Because of incorrect casting, it might've
    happened that the token and the expected value were considered
equal,
    even if the memcmp() returned a non-zero value. In this case
   MySQL/MariaDB would think that the password is correct, even while
it is
    not.  Because the protocol uses random strings, the probability of
    hitting this bug is about 1/256.
    Which means, if one knows a user name to connect (and "root"
almost
    always exists), she can connect using *any* password by repeating
    connection attempts. ~300 attempts takes only a fraction of
second, so
    basically account password protection is as good as nonexistent.

  Disclosure date: 2012-06-9
  Extra information:
  Server granted access at iteration #204
  root:*9CFBBC772F3F6C106020035386DA5BBBF1249A11
  debian-sys-maint:*BDA9386EE35F7F326239844C185B01E3912749BF
  phpmyadmin:*9CFBBC772F3F6C106020035386DA5BBBF1249A11

For more and detailed info, please refer the above link.
The NMAP tools will not only help you in getting the list of port related vulnerabilities. It can also be used to search for other vulnerabilities like MySql injection,DDOS, brute force vulnerabilities and lot more. Though you need to download separate libraries for those.
Comment: This is a bit short for an answer. It's not really a comment either though. I suggest you [edit] and include some examples, even if it's just a quote of the doc synopsis, and an explanation of why it's a useful tool.


VBA - Excel : Vlookup crashes my program when no match found

Question: In my program, the user types a Zip Code and gets as an output information related to the Zip Code (province, city, district). To do this, I use the Vlookup function.
So, the user :

Types a Zip code in the main sheet
The program search in a database (in another sheet) in which Zip Code are associated to City, Province, District.
When there is a match, it sends the result to the main pages, so the user can get a city, province, district just by typing the Zip Code. Quite simple process.

I use this code to do so :
If Range("J9").Value <> "N/A" Then 'if there is actually a zip code entered by the user (if not, it will be "N/A")
cityZip = Application.WorksheetFunction.VLookup(sMain.Range("J9").Value,
                 sZipCodes.Range("B2:E864"), 3, False)
barangayZip = Application.WorksheetFunction.VLookup(sMain.Range("J9").Value,
                 sZipCodes.Range("B2:E864"), 2, False)
provinceZip = Application.WorksheetFunction.VLookup(sMain.Range("J9").Value,
                 sZipCodes.Range("B2:E864"), 4, False)
sMain.Range("J7").Value = provinceZip
sMain.Range("J13").Value = cityZip
sMain.Range("J16").Value = barangayZip
Else
End If

It works perfectly when there is a Zip Code which is in my database. But if not, it crashes the execution of the program and I have an error message (like "execution error '1004', unable to read the Vlookup ...).
How to modify my code to just say that if there is no match, then it should just do nothing? I don't know how to introduce this request in a Vlookup function.
Thanks in advance !
EDIT : here is my new code, after following Tim Williams suggestion :
'Using Zip Code
If Range("J9").Value <> "N/A" Then
provinceZip = Application.Lookup(sMain.Range("J9").Value, sZipCodes.Range("B2:E907"), 4, False)

If IsError(provinceZip) = False Then
cityZip = Application.Lookup(sMain.Range("J9").Value, sZipCodes.Range("B2:E907"), 3, False)
barangayZip = Application.Lookup(sMain.Range("J9").Value, sZipCodes.Range("B2:E907"), 2, False)

sMain.Range("J7").Value = provinceZip
sMain.Range("J13").Value = cityZip
sMain.Range("J16").Value = barangayZip
Else
'do nothing
End If

End If

My error is on this line :
provinceZip = Application.Lookup(sMain.Range("J9").Value, sZipCodes.Range("B2:E907"), 4, False)

=> Error 1004, invalid number of arguments
Comment: Drop the `.WorkSheetFunction` and just use `Application.Lookup`.  Then you  can test the return value using `IsError()` on the first lookup
Comment: Your error is because you've switched from `VLOOKUP` to `LOOKUP` in your code.
Comment: @Tim is right. However, why not just put the `VLOOKUP` formulas in cells J7, J13 and J16 directly? You could also make J9 a data validation dropdown whose source range is your list of zip codes. That way users could only choose valid zip codes and you could avoid (possibly) unneeded coding.
Comment: @TimWilliams : thank you! I found more details here (http://www.cpearson.com/excel/callingworksheetfunctionsinvba.aspx ) and tried to follow their example, but I still have a problem, different one this time (but still error 1004), when I try to run my program... I'm gonna edit my code with more details.
Comment: @DougGlancy thanks for the suggestions but the user doesn't actually type the zip code, I just avoided giving unnecessary details. To sum up, the zip code is automatically found in an address, sent to "J9" but can sometimes by mistaken for something else (a street number, a unit number, etc.) so there must be an error handling part!
Comment: Indeed! Perfect, works well now! Thank you Doug and Tim !
Answer: You should read up on VBA error handling. A source such as http://www.cpearson.com/excel/errorhandling.htm might help. That said, try the following code.
You want something like:
Public Function SafeVlookup(lookup_value, table_array, _
                        col_index, range_lookup, error_value) As Variant
    On Error Resume Next
    Err.Clear
    return_value = Application.WorksheetFunction.VLookup(lookup_value, _
                                table_array, col_index, range_lookup)
    If Err <> 0 Then
      return_value = error_value
    End If

    SafeVlookup = return_value
    On Error GoTo 0
End Function

In your code you might call it like:
cityZip = SafeVlookup(sMain.Range("J9").Value, sZipCodes.Range("B2:E864"), 3, _
                   False, "")

The last parameter is the default value to return if the vlookup failed. So in this example it'd return an empty string.
Answer: I usually wrap the vlookup() with an iferror() which contains the default value.
The syntax would be as follows:
iferror(vlookup(....), <default value when lookup fails>)

You can also do something like this:
Dim result as variant
result = Application.vlookup(......)
If IsError(result) Then
  ' What to do if an error occurs
Else
  ' what you would normally do
End if

Answer: You changed from Vlookup to Lookup, which has less arguments. Using only 2 arguments, you should be fine: provinceZip = Application.Lookup(sMain.Range("J9").Value, sZipCodes.Range("B2:E907") )
Answer: SafeVlookup is a good function.
I am still learning VB.
I changed like this and it works for me.
     Function SafeVlookup(lookup_value, _
                    range_lookup, col_index, error_value) As Variant
     .....
     return_value = Application.WorksheetFunction.vlookup(lookup_value, _
                    range_lookup, col_index, error_value)
     ....
     End Function

Hope I can use it like this.
Comment: This won't work at all. You can't change the arguments of the built-in `VLOOKUP` formula. You are using an `error_value` in the last VLOOKUP argument to determine if vlookup is looking for an exact match or not. Why not use the solution as @andASM provided it?


Unusual text inserted in the SQL

Question: I am getting some unusual text which is getting added to my queries in views. I am referring to the part setting view_name.
SELECT users.name AS users_name, users.uid AS uid, 'cardinality_user_test:page' AS view_name
FROM
{users} users
LEFT JOIN {node} node_users ON (SELECT nodeINNER.nid AS nidINNER, ':default' AS view_name
FROM
{node} node INNER LEFT JOIN {users} users_nodeINNER ON nodeINNER.uid = users_nodeINNER.uid
WHERE (( (users_nodeINNER.uid = users.uid ) ))
ORDER BY nodeINNER.nid DESC
LIMIT 1 OFFSET 0) = node_users.nid
LIMIT 10 OFFSET 0

This additional SQL is creating an error:

SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 2 column(s)

What is causing that text to be added in Drupal 7?
Answer: That extra field is added from the Views module itself, in particular its views_plugin_query_default::add_signature() method, which is described as:

Add a signature to the query, if such a thing is feasible.
  This signature is something that can be used when perusing query logs to discern where particular queries might be coming from.

If you look at its code, it is setting the view_name field.
function add_signature(&$view) {
  $view->query->add_field(NULL, "'" . $view->name . ':' . $view->current_display . "'", 'view_name');
}

Comment: Thank you. From your answer I realised I had ticked "Add Views signature to all SQL queries" in the Advanced Views Settings which was causing an error in some of my views.
Comment: Yes, I should add that in the answer. Understanding which setting is causing that view's behavior is not immediate.

Unusual text inserted in the SQL


CLT for identically distributed but NOT independent random variables

Question: The random variables are not
IID; in fact they are identically distributed but NOT independent. Can
you give me a reference for CLT under this type of set-up?
Comment: Can you tell us about the kind of dependence?Just one example:  https://projecteuclid.org/euclid.aop/1176992260
Answer: Little can be said about what happens here in general. For example, suppose $X_k=(-1)^{k-1}X_1$, where $X_1$ has any symmetric distribution. Then $\sum_{k=1}^nX_1$ is $0$ ($X_1$) when $n$ is even (odd).
Answer: If variables in the sequence that are far away from each other are sufficiently close to independent, roughly the same results hold.
For example, if the sequence is stationary with pairwise correlations $\rho_k$, the limit of the scaled sum is Gaussian with variance
$$
\sigma^2+2\sum_{n>1}\rho_n.
$$
Obviously this can only be true if the sum above exists, i.e., if correlations decay sufficiently quickly.
Formalizations of this are called "Ergodic CLT" and you can pick an exposition at your desired level from a Google search.


SQL Server (2012 Enterprise) Browser service failing

Question: SQL Server (2012 Enterprise) Browser service failing
I have a problem as described below:
I have an instance of SQL Server 2012 Enterprise (thanks to MSDN) for local development on my PC.
I try to start SQL server Browser Service from SQL Server Configuration Manager and it takes a long time to fail, then fails with:

The request failed or the service did not respond in a timely fashion.
  Consult the event log or other applicable error logs for details.

I checked event logs and found these errors in this order (all within the same 1-second time frame):

The SQL Server Browser service port is unavailable for listening, or
  invalid.
The SQL Server Browser service was unable to establish SQL instance
  and connectivity discovery.
The SQL Server Browser is enabling SQL instance and connectivity
  discovery support.
The SQL Server Browser service was unable to establish Analysis
  Services discovery.
The SQL Server Browser service has started.
The SQL Server Browser service has shutdown.

I checked firewall rules and both port 1433 (TCP) and 1434 (UDP) are wide open, just as well - the programs and service binary had been "allowed through windows firewall".
I started the "Analysis Services" service by hand and it works fine. Browser still won't start.
Some History:
Installed SQL 2008 R2 express advanced
Installed SQL2012 Express advanced
Uninstalled SQL 2008 R2 express advanced
Installed 2012 SSDT and lots of features with Express install
Installed a unique instance of SQL 2012 Enterprise with all features
Uninstalled SSDT and reinstalled SSDT with Enterprise (solved a different problem)
Uninstalled SQL 2012 Express
Uninstalled SQL 2012 Enterprise
Removed anything with "SQL" in the name from Control panel > "Programs and features"
Installed SQL 2012 Enterprise without Analysis services (This is where I noticed SQL Browser service was failing to start even on the install)
Added the feature of Analysis Services (and everything else) via the installer (Browser continued to fail to start on the install)
========================
Other interesting facts:
opening a command window with administrator and trying to run sqlbrowser.exe manually yielded:

Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft
  Corporation.  All rights reserved.
C:\Windows\system32>cd C:\Program Files (x86)\Microsoft SQL
  Server\90\Shared
C:\Program Files (x86)\Microsoft SQL Server\90\Shared>sqlbrowser.exe -c
  SQLBrowser: starting up in console mode  SQLBrowser: starting up SSRP redirection service
  SQLBrowser: failed starting SSRP redirection services -- shutting down.
  SQLBrowser: starting up OLAP redirection service
  SQLBrowser: Stopping the OLAP redirector
C:\Program Files (x86)\Microsoft SQL Server\90\Shared>

As I try to repair the install it errors out saying

The following error has occurred:
Service 'SQLBrowser' start request failed.
Click 'Retry' to retry the failed action, or click 'Cancel' to cancel
  this action and continue setup.
For help, click:
  http://go.microsoft.com/fwlink?LinkID=20476&ProdName=Microsoft%20SQL%20Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=11.0.2100.60&EvtType=0x4F9BEA51%25400xD3BEBD98%25401211%25401

Clicking retry fails every time. When clicking cancel I get:

The following error has occurred:
SQL Server Browser configuration for feature
  'SQL_Browser_Redist_SqlBrowser_Cpu32' was cancelled by user after a
  previous installation failure. The last attempted step: Starting the
  SQL Server Browser service 'SQLBrowser', and waiting for up to '900'
  seconds for the process to complete. .
For help, click:
  http://go.microsoft.com/fwlink?LinkID=20476&ProdName=Microsoft%20SQL%20Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=11.0.2100.60&EvtType=0x4F9BEA51%25400xD3BEBD98%25401211%25401

When I go to uninstall the SQL Browser from "Programs and Features", it complains:

Error opening installation log file. Verify that the specified log
  file location exists and is writable.

Is there any way I can fix this short of re-imaging my computer and reinstalling from scratch?
A possible approach would be to somehow really uninstall everything and delete all files related to SQL... is that a good idea, and how do I do that?
Answer: I learned that installing Enterprise Edition locally is a bad idea... thus I tried:

removing everything related to SQL server with "programs and features"
deleteing all files related to SQL server from Program files (and Program files (x86))
Installing SQL 2012 Express

SQL Browser service still failed to start, thus failed to install.
I found this article which led me to believe I had an interfereing proxy of some kind... sure enough! I removed Covenant Eyes (a content filtering service) from my computer, and tried to reinstall SQL Server Express and the browser service installed correctly. Still a handful of other things failed to install (Database Engine Services, Full-Text and Semantic Extractions for Search, SQL Server Replication, Reporting Services - Native), but the browser service is working!
If you are having this issue as well, check for interference from filters/proxies/virus scanners/etc..
UPDATE:
I got the other 4 things (that failed to install) working by going to "Programs and Features" > removing just those features and reinstalling them. I ran into these helpfuls questions along the way:
https://stackoverflow.com/questions/2979425/sql-server-installation-what-is-the-installation-media-folder
If you get the error

Rule "Reporting Services Catalog Database File Existence" failed

or

Rule "Reporting Services Catalog Temporary Database File Existence"
  failed

Go to C:\Program Files\Microsoft SQL Server\MSSQL<version#>.<instance_name>\MSSQL\DATA and delete the report server files.

ReportServer.mdf
ReportServer_log.LDF
ReportServerTempDB.mdf
ReportServerTempDB_log.LDF.

http://www.sqlcoffee.com/Troubleshooting028.htm


(BackboneJS) Executar uma View após retorno do servidor

Question: Na minha aplicação eu tenho 2 Views.
Uma delas está enviando os dados para o servidor quando o cliente clica no submit.
A outra precisa esperar essa resposta e executar para trabalhar com os dados 'atualizados'.
Como eu faria tal coisa?
Comment: Quando a primera view é submetida você faz uma requisição ajax? Não da para fazer a ação da segunda view no callback dessa requisição?
Answer: O jeito mais fácil seria utilizar os recursos nativos da collection do backbone.

Substituir o input type submit por um input type button (ou uma div) para não ter que ficar cancelando o comportamento default do elemento HTML.

Opção 1:

Realizar a inserção (POST) via collection.

Na view 1 criar um model com os valores que seriam submetidos pelo form.
Adicionar o model criado à collection com 'create' para assim adicionar e realizar o request para o server enviando o novo model (backbone-collection-create).

Na view 2 utilizar uma nova collection apontando para a mesma url, e escutar o evento de add para adicionar o novo item inserido na collection (server) utilizando o 'fetch' com a opção de remove como false caso não queira que toda a collection seja atuzalizada: (backbone-collection-fetch)
collection.fetch({remove: false});

Opção 2:

Na view 1 realizar a inserção (POST) via JSON (ou JSONP no caso de cross domain);
Na view 2:

Escutar o evento de add da mesma forma do exemplo acima.
Ou realizar um trigger (backbone-trigger) da view 1 para a view 2 passando o novo model e adicionar manualmente na view (escutar na view 1 o evento disparado pelo trigger e realizar um 'append' do HTML com os dados dos novo model que foram passados via trigger).


Proving Properties of Boolean Algebras $(x+y) + (y\cdot x') = x+y$

Question: I'm trying to justify the following simplification:
$(x + y) + (y \cdot x') = x + y$
The solution that was provided to me is as follows:
$
= (x + y) + (y \cdot x') - (LHS)\\
= x + y \cdot (1 + x')\\
= x + y \cdot (1)\\
= x + y\\
$
I'm a little confused on the jump from steps 1 to 2, and what rule was applied and then also the switch from a disjunction to a conjunction.
Is anyone able to provide some insight into the reasoning?
Comment: I want to apologize for the unfriendly comment you received from another user below your most recent question.  I flagged the comment, and the comment was deleted.  I encourage you to undelete the post; I will upvote it.  It is clear you put effort into writing the post, and it deserves to be attended to.
Answer: That step actually combines three steps. In order, they are associativity of disjunction, conjunctive identity, and distributivity of conjunction over disjunction:
$$\begin{align*}
(x+y)+(y\cdot x')&=x+\big(y+(y\cdot x')\big)\\
&=x+\big((y\cdot 1)+(y\cdot x')\big)\\
&=x+\big(y\cdot(1+x')\big)
\end{align*}$$
Then it just completes the calculation within the parentheses.
Comment: Awesome, thank you so much for the quick and clear explanation.
Comment: @confundido: You're very welcome.


Comportamentos inesperados com operações básicas no JavaScript

Question: Gostaria de saber o motivo dos comportamentos, a meu ver estranhos, do JavaScript em subtraçôes com números reais:

1.74 - 1.7
// retorna: 0.040000000000000036

Explico melhor a questão: gostaria de saber o porquê desta característica e se existe alguma forma de fazer a operação já à evitando. Não pergunto como arredondar ou formatar o resultado.
Sou novo em JS e no Stack, favor não me apedrejar, obrigado.
Comment: Bem-vindo ao site, espero que não tenha se sentido apedrejado. A marcação de duplicata não é nada contra sua pergunta. A ideia desse recurso aqui é criar uma teia de conteúdos relacionados para ajudar as pessoas a encontrar as respostas. Leia os conteúdos linkados no box amarelo do topo, veja se resolvem sua dúvida.
Answer: Para nós parece tão fácil esse cálculo e o resultado exato de 0.4, mas em JavaScript, todos os números são números de ponto flutuante do padrão IEEE 754. Devido à natureza binária de sua codificação, alguns números decimais não podem ser representados com precisão perfeita. Isso é análogo como o exemplo da fração 1/3 que não pode ser representada com precisão com um número decimal com um número finito de dígitos. Quando atingir o limite do seu armazenamento, você precisará arredondar o último dígito para cima ou para baixo.
Seu primeiro pensamento pode ser tentar arredondar para a segunda casa decimal. Infelizmente, as funções de arredondamento internas do JavaScript são arredondadas apenas para o número inteiro mais próximo.
Porém para seu caso e semelhantes onde o valor desejado é inteiro mais próximo poderia ser utilizado sim e recomendo o toFixed(2)
resultado.toFixed(2);

Não recomendo, mas:
Ainda sem usar outro framework ou plugin para calculos, existe uma maneira um pouco mais precisa utilizando números apenas inteiros, como no exemplo seria multiplicar por 100 os valores então teria: 174 - 170, porém muda a perspectiva de representação do valor, onde os decimais percentem aos ultimos 2 digitos do próprio inteiro, ainda nesse cálculo se fizer o resultado / 100 obterá o resultado desejado: 0.4
Obs. Funcionou para esse caso e muitos outros.
Mas claro, isso não pode ser 100% garantido pois a divisão e multiplicações podem resultar em valores inexatos.


Determin the determination coefficient R square

Question: I have the following question and I couldn't figure out how to solve it.
The given is the following:

The model is: Yi = B0 + B1 Xi + Ei
I have the following dependent variables 2, 4 and 8 (3 observations)

After estimating the model by OLS, we know that the summation of the estimated (y hat) squared is = 80.
how can I calculate R square with the above given
the answer is supposed to be .7857
Any help?
I added the exact question:
Comment: You need to apply several formulas for variances and $R^2$ as well as know how the mean of $\hat Y_i$ is related to the mean of $Y_i.$  At what step do you need help?
Comment: @whuber can you list the steps please, I'm stuck on how to calculate R-square without having the independent variables listed.
Comment: If this is homework, you need the `self-study` tag along with the others: `regression` etc.
Answer: Because this problem is most instructive when you work out the answer yourself, I will suggest a logical sequence of attack but not provide a complete answer.
Begin at the end: you want to find $R^2,$ which is defined as a ratio of variances.  The numerator is the variance of the predicted values $\hat y_i$ while the denominator is the variance of the response values $y_i.$
Although the problem does not specify any variances, it does gives us the sum of squares of the $\hat y_i$ and the individual $y_i.$  Obviously you can compute any property you need from the $y_i,$ which are $(2,4,8).$  You need the variance and most computations of the variance first obtain the mean, so you might as well compute these two statistics right away.
That leaves you with a conundrum: how to find the variance of the $\hat y_i$ when all you have is their sum of squares?  There must be some connection between properties of the $\hat y_i$ and properties of the $y_i.$  That's the key: apart from exercising your skills in algebra, this problem invites you to think about any necessary relationships between the predicted values and the original responses in an ordinary least squares regression (which includes a constant term: this is crucial).
If you cannot think of any relationship, take this opportunity to review your textbook and notes for relationships.  Focus on the one missing piece: since you have the sum of squares of the $\hat y_i,$ all you need in order to find their variance is their mean (and, of course, their count): how is the mean of the predicted values related to the original responses?
The rest is arithmetic.


Visualization of combinations of options

Question: I'm working on some code profiling/optimization and I'm trying to find a way to visualize the result (a scalar -- the performance). I can specify a pretty big variety of options, some of which may be used together, some of which may not. For example, if I have options A, B, C, D, and E, I may have a result for A, A+B, A+C, A+B+C, D, D+B, D+B+C+E, ... etc etc.
To visualize it, I could just have a lookup table somewhere that maps a case name/integer to a combination of options and do a standard categorical scatter plot. But I don't like the idea of having to look up in a table the difference between Case 32 and Case 12.
What is an intuitive way to visualize the result as a function of the various combinations?
Answer: Bertin graphs can be used to visualize the information (figure from a book as shown in an answer on gis.stackexchange):  .
Each row would represent a set of options, and each column a particular option (A, B, C, etc...). Each option present for given set of option will be marked in the matrix.
Then you can either plot results on the side (e.g., as a bar plot with one bar per row), or as vertically stacked figures if more than one result to display (one such figure per set of options). Reordering the rows and columns of the matrix is something you'll likely want to explore in order to highlight patterns of interest.