text:
Q: how to use cookies to prevent a jquery popup to after click action hello this is my first time asking a question on here, hope im not asking for too much, i created a lightbox type pop up that starts after 20 seconds, for my site, but i dont want the popup to keep reappearing if i continue browsing(session cookie), i have tried creating cookies but it seems that i am not doing it correctly. if you can help i would appreciate it very much thank you.
window.setTimeout(function () {

    $('.popupbox').ready(function () {
        $('.backdrop, .box').animate({
            'opacity': '.50'
        }, 300, 'linear');
        $('.box').animate({
            'opacity': '1.00'
        }, 300, 'linear');
        $('.backdrop, .box').css('display', 'block');
    });

    $('.close').click(function () {
        close_pop();
    });

    $('.backdrop').click(function () {
        close_pop();
    });
}, 20000);

if (!readCookie('hide')) {
    $('.popupbox').show();
}

function close_pop() {
    $('.backdrop, .box').animate({
        'opacity': '0'
    }, 300, 'linear', function () {
        $('.backdrop, .box').css('display', 'none');
    });

    $.cookie('hide', true, 1, {
        path: '/'
    });
    return false;
}

A: The below code will display a div after 20 seconds if the user clicks inside the div or on close the div will hide and won't show again unless they lose their cookies, even on reload.
Special Note: Unfortunately jquery.cookie.js plugin doesn't have a CDN so I inline included it below...please don't do this in production include it using normal script includes.
DEMO: jQuery jsFiddle
HTML

        Hello World I am a popup.
        <input type="button" class="close" value="Close" />

JS
$(function () {
    if (!$.cookie('hide')) {
        window.setTimeout(function () {
            $('.popupbox').show();
            $('.popupbox').ready(function () {
                $('.backdrop, .box').animate({
                    'opacity': '.50'
                }, 300, 'linear');
                $('.box').animate({
                    'opacity': '1.00'
                }, 300, 'linear');
                $('.backdrop, .box').css('display', 'block');
            });

            $('.close').click(function () {
                close_pop();
            });

            $('.backdrop').click(function () {
                close_pop();
            });
        }, 20000);
    }
});

function close_pop() {
    $('.backdrop, .box').animate({
        'opacity': '0'
    }, 300, 'linear', function () {
        $('.backdrop, .box').css('display', 'none');
    });

    $.cookie('hide', true);
    return false;
}

/*!
 * jQuery Cookie Plugin v1.3.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2013 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as anonymous module.
        define(['jquery'], factory);
    } else {
        // Browser globals.
        factory(jQuery);
    }
}(function ($) {

    var pluses = /\+/g;

    function raw(s) {
        return s;
    }

    function decoded(s) {
        return decodeURIComponent(s.replace(pluses, ' '));
    }

    function converted(s) {
        if (s.indexOf('"') === 0) {
            // This is a quoted cookie as according to RFC2068, unescape
            s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
        }
        try {
            return config.json ? JSON.parse(s) : s;
        } catch (er) {}
    }

    var config = $.cookie = function (key, value, options) {

        // write
        if (value !== undefined) {
            options = $.extend({}, config.defaults, options);

            if (typeof options.expires === 'number') {
                var days = options.expires,
                    t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            value = config.json ? JSON.stringify(value) : String(value);

            return (document.cookie = [
            config.raw ? key : encodeURIComponent(key),
                '=',
            config.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''].join(''));
        }

        // read
        var decode = config.raw ? raw : decoded;
        var cookies = document.cookie.split('; ');
        var result = key ? undefined : {};
        for (var i = 0, l = cookies.length; i < l; i++) {
            var parts = cookies[i].split('=');
            var name = decode(parts.shift());
            var cookie = decode(parts.join('='));

            if (key && key === name) {
                result = converted(cookie);
                break;
            }

            if (!key) {
                result[name] = converted(cookie);
            }
        }

        return result;
    };

    config.defaults = {};

    $.removeCookie = function (key, options) {
        if ($.cookie(key) !== undefined) {
            // Must not alter options, thus extending a fresh object...
            $.cookie(key, '', $.extend({}, options, {
                expires: -1
            }));
            return true;
        }
        return false;
    };

}));

DEMO: JavaScript jsFiddle
HTML

        Hello World I am a popup.
        <input type="button" class="close" value="Close" onclick="close_pop()" />

JS
function close_pop() {
    $('.backdrop, .box').animate({
        'opacity': '0'
    }, 300, 'linear', function () {
        $('.backdrop, .box').css('display', 'none');
    });

    setCookie('hide', true, 365);
    return false;
}

function getCookie(c_name) {
    var c_value = document.cookie;
    var c_start = c_value.indexOf(" " + c_name + "=");
    if (c_start == -1) {
        c_start = c_value.indexOf(c_name + "=");
    }
    if (c_start == -1) {
        c_value = null;
    } else {
        c_start = c_value.indexOf("=", c_start) + 1;
        var c_end = c_value.indexOf(";", c_start);
        if (c_end == -1) {
            c_end = c_value.length;
        }
        c_value = unescape(c_value.substring(c_start, c_end));
    }
    return c_value;
}

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

window.onload=function () {
    if (!getCookie('hide')) {
        window.setTimeout(function () {
            $('.popupbox').show();
            $('.popupbox').ready(function () {
                $('.backdrop, .box').animate({
                    'opacity': '.50'
                }, 300, 'linear');
                $('.box').animate({
                    'opacity': '1.00'
                }, 300, 'linear');
                $('.backdrop, .box').css('display', 'block');
            });

            $('.close').click(function () {
                close_pop();
            });

            $('.backdrop').click(function () {
                close_pop();
            });
            //change 1000 to 20000 for 20 seconds
        }, 1000);
    }
}


text:
Q: MySQL : Connect locally using Java I have a MySQL database and a java application using it thru JDBC. I want to distribute the application. I copied the DB to my application folder. I also have myconnectionj jar file included in the project.
How to create the url/connectionString to connect to the database along with the application instead of using server ? I want to connect like we do for Access files. We can distribute it with the application easily and use it. How to achieve the same with MySQL DB without using server.

A: I don't know if MySQL can provide that flexibility. But exist other Databases which enable to you store the data in a file and port it across to clients. You can ckeck the following:

*

*Derby DB

*HSQL DB

*SQL Lite

A: I'm not sure if there is a mysql-wrapper for such tests. AFAIK you need a running server.
If you need portability you should check file-databases like: H2, HyperSQL or SQLLite.

redpajama_set_name: RedPajamaStackExchange


text:
Q: java : shift distance for int restricted to 31 bits Any idea why shift distance for int in java is restricted to 31 bits (5 lower bits of the right hand operand)?
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.19
x >>> n

I could see a similar question java Bit operations >>> shift but nobody pointed the right answer

A: The shift distance is restricted to 31 bits because a Java int has 32 bits. Shifting an int number by more than 32 bits would produce the same value (either 0 or 0xFFFFFFFF, depending on the initial value and the shift operation you use).

A: It's a design decision, but it seems a bit unfortunate at least for some use cases. First some terminology: let's call the approach of defining as zero all shifts amounts larger than the number of bits in the shifted word the saturating approach, and the Java approach of using only the bottom 5 (or 6 for long) bits to define the shift amount as the mod approach.
You can look at the problem by listing the useful shift values. Those are shift amounts that result in unique output values1. If you take >>>, the interesting values are 0 though 32 inclusive. 0 results in an unchanged value, and 32 results in 0. Shifting by more than 32 would again produce the same result as 32, sure - but java doesn't even let you shift by 32: it stops at 31! A shift by 32 will, perhaps unexpectedly, leave your value unchanged.
In many uses of >>> a shift by 32 is not possible, or the Java behavior works. In other cases, however, the natural result is 32, and you must special case zero.
As to why they would choose that design? Well, it probably helped that the common PC hardware at the time (x86, just like today) implements shifts in exactly that way (using only the last 5 bits for 32-bit shifts, and the last 6 for 64-bits). So the shifts can be directly mapped to hardware without any special cases, conditional moves or branches2.
Furthermore, for hardware that doesn't implement those semantics by default, it is easy to get the Java semantics by a simple mask: shiftAmount & 0x1F. That's going to be fast on all hardware. The reverse mapping - implementing saturating shifts on hardware that doesn't support it is more complex: you may need a costly compare and branch, some bit twiddling hacks or predicated moves to handle the > 31 case.
Finally, the mod approach is quite natural for many algorithms. For example, if you are implementing a bitmap structure, addressable per-bit, a good implementation may be to have an array of integers, with each integer representing 32 bits. Internally to index into the Nth bit, you would break N down into two parts - the high 27 bits would find the word in the array the bit is in, and the low 5 bits would pick the bit out of the word. To pick the bit out of the word (e.g., to move it to the LSB), you might do:
int val = (word >>> (index & 0x1F)) & 1

That sets val to 1 if the bit was set, 0 otherwise. However, because of the way the Java >>> operator was specified, you don't need the & 0x1F part at all, because it is already implied in the mod definition! So you can omit it, and indeed the JDK's BitSet uses exactly that trick.

1 Granted, any value without a 1 in the MSB may not produce unique values under >>>, once all the 1s get shifted off, so let's just talk about any value with a leading one.
2 For what it's worth, I checked ARM and the semantics are even weirder: for variable shifts, the bottom eight bits of the shift amount is used. So the shift is a weird hybrid - it is effectively a saturating shift once you exceed 31, but only up to 255, at which point it loops around and suddenly has non-zero values for the next 31 values, etc.


text:
Q: Calculate integral $ \int_{0}^{\infty}\frac{1 - at^{2}}{(1 + bt^{2})^{3}} \cos(nt)dt $ How to calculate the following
definite integral containing cosine and rational function of polynomial
$$
\int_{0}^{\infty}\frac{\left(1 - at^{2}\right)\cos\left(nt\right)}{\left(1 + bt^{2}\right)^{3}}\,{\rm d}t\ ?
$$
Here $a, b$ and $n$ are positive constants, greater than $1$.

A: HINT:
Note that
$$\int_0^\infty \frac{(1-at^2)\cos(nt)}{(1+bt^2)^3}\,dt=\frac12 \text{Re}\left(\int_{-\infty}^\infty \frac{(1-ax^2)e^{inx}}{(1+bx^2)^3}\,dx\right)$$
Move to the complex plane, close the contour in the upper-half plane, and apply the residue theorem.  Note that the pole at $i/\sqrt b$ is of third order.

A: Rewrite the integral as
$$I =\int_0^{\infty} \frac{(1-at^2)\cos(nt)}{(1+bt^2)^3}dt
=\frac1{b^3}\int_0^{\infty} \frac{\cos(n t)}{(\frac1b +t^2)^3}dt
-\frac a{b^3}\int_0^{\infty} \frac{t^2\cos(n t)}{(\frac1b +t^2)^3}dt \tag1
$$
and note that
$$J(p,q)=\int_{0}^{\infty} \frac{\cos(p t)}{q+ t^2} dt
=\frac{\pi e^{-p\sqrt{q}}}{2\sqrt{q}}$$
obtained via $J_p''(p,q)=qJ(p,q)
$, along with $J(0,q) = \frac{\pi}{2\sqrt{q}}$ and $J_p'(0,q)= -\frac\pi2$. Then, evaluate the two integrals in (1) as follows
$$\int_0^{\infty} \frac{\cos(n t)}{(\frac1b+t^2)^3}dt
= \frac12 \frac{\partial^2 J(p,q)}{\partial q^2}\bigg|_{q=\frac1b,p=n}
=\frac{\pi}{16}e^{-\frac n{b^{1/2}}}b^{3/2}(n^2+3n b^{1/2}+3b)
$$
$$\int_0^{\infty} \frac{t^2\cos(n t)}{(\frac1b+t^2)^3}dt
= -\frac12 \frac{\partial^2\partial^2 J(p,q)}{\partial p^2\partial q^2}\bigg|_{q=\frac1b,p=n}
=-\frac{\pi}{16}e^{-\frac n{b^{1/2}}}b^{1/2}(n^2-n b^{1/2}-b)
$$
As a result
$$ I =\frac{\pi}{16}e^{-\frac n{b^{1/2}}}
\left[ \frac{n^2}{b^{3/2}}\left(1+\frac ab\right)+\left(\frac nb+\frac1{b^{1/2}}\right)\left(3-\frac ab\right)\right]
$$


text:
Q: Figuring out how much torque dc motor will need to run at a certain speed. (E-skateboard project) Suppose I want to purchase a DC motor online, how can i determine how much torque my motor will need to run at a certain speed? I.e. 15mph
This is for my electric skateboard project and the load on top of the board will be 140 lbs.
Really having a hard time figuring this out and was hoping someone can share their knowledge.

A: Get a friend to tow you behind a car while you ride a conventional skateboard. Use some type of spring scale to measure how hard the tow rope is pulling you. That force, multiplied by the radius of the skateboard wheel, is the required wheel torque. If your skateboard uses a drive-belt, then the motor torque will be different than the wheel torque. The rope should be long enough that you are not in the slipstream of the car. I suggest you take measurements at several speeds and also while going up and down a few hills. Make sure you record both speed and force. The speed component will allow you to calculate power as well as torque.

A: I don't know if the same is true for skate boards but for bicycles you can find online calculators like these; Cycling calculator.  I would think at 15mph the rolling friction and wind resistance would be similar.  For me this calculator says 160lbs of me and 20lbs of bicycle take 110 Watts.  In this case, I'm the motor and putting out about 100rpm at the crank.  Your motor will turn a lot faster.  It turns out on the mechanical side the power a motor puts out is equal to the motor speed in rad/sec times the torque in Nm.  Now if you search for small motors like this you might come up with these;Maxon 150W Motors  You need to know your battery voltage.  If you pick one of the 48V motors and run it on the fast side, to get good efficiency, say 7000rpm.  This is about 700rad/s.  So this motor would be at 110W/700rad/s = 0.15Nm.  If you picked a different motor that was most efficient at 3500 rpm your torque would double to put out the 110 Watts needed.  See?

A: Torque is about acceleration, not about speed. The higher the torque, the faster you speed up. To calculate the actual acceleration, you need the impulse required, which is governed by the load to accelerate.
In contrary, the top speed is limited by the driving power your whole arrangement needs and has. The motor torque goes into that equation but not the impulse and thus, not the load on top of the board (because it isn't accelerated any more).
Instead, losses get important. Most influencing losses come from

*

*the wheels on the ground (but then: more loss there leads to higher possible acceleration – no slippage)

*the loss of the gear (but then: a worm gear may be much smaller)

*and head wind (don't laugh: wear a cape and see the difference, plus: wind losses go up with \$v^2\$)

You have to find out these losses first to calculate the top speed possible. To make a rough guess, for the wind shape of a single person riding a vehicle at 15mph, you need about 1kW mechanical power. That's what mopeds have.

A: What makes you think you can build one cheaper than buying one engineered with over 10 man years of R&D and low cost materials in China?  I say this, not to discourage your thinking, but to encourage you to learn how write a better list of requirements. Cost, performance, functions accessories. Not just weight and speed.  There is a lot more to Engineering than Grade 12 Physics.

This picture is worth about $850 with charger and remote control.
Rated at 3300W with 35 kph but not sure for how long as this would get very hot.

A: This may help you get started. Don't expect a detailed design service.

*

*design spec:

*

*4 wheel skate board 65mm wheels , 65kg load plus motor+bat

*desired speed 35 km/h on smooth level road. let's use 36kph=10m/s

\$ E_k=\frac{1}{2}mv^2=(65+15kg)100/2=4kW-s=4kJ\$

*

*Thus for 1/3 Hp~=750/3=250W

*However HP = T*RPM which peaks around 80-85% ideally so using an average of 1/3 for the area under a triangular rising HP you have an avg Hp of 1/9th Hp or 750W/hp/9= 83W mechanical power so time to full speed is 4000Ws/83W=48 seconds so you see, leg power is faster.

*Next motor rating is Torque in kV/RPM with D=65mm wheels with a circumference of 204mm = 0.2m and a velocity, v = 10m/s

*for RPM= v/(Pi*D)*60 =10/(3.14*65)*60*1000mm/m = 3000 RPM

So you are looking for a 1/3Hp pancake brush DC motor with 3000 RPM no load. then choose Wh batt size and voltage from different assumptions for standard voltages in this type and size then pick lowest kV/RPM avail to get highest string of series voltage.

The max loaded speed is where F=T/r or friction=torque/radius of wheel. (edited typo.

Think of it like picking your favorite gear in a 10 speed bike. But you can only pick one gear, so it a compromise of acceleration and speed.

*

*Don't expect much acceleration as  a=F/m where 140lbs(65kg) is a lot more than friction at 15mph (35kph). Expect to use leg power to start and stop fast and don't expect much torque going up hill unless you choose a 2 speed motor with dual winding options

A good fit for HP ends up having loaded speed at 80% of no loss speed so max speed is 19mph or 44 kph.

*

*Then make sure your Zbat or battery ESR is much lower than DCR of motor for battery load regulation like <<10%DCR pref <2%. Use the highest voltage motor and series/parallel array voltage that is practical.

background info

*

*Direct current (DC) motor design
motor parameters (brush dc motor)

*\$ v  \$= input voltage to the motor (volts)

*\$ rm\$ = motor resistance (ohms) or DCR in

*\$lm \$= motor inductance (henrys)

*\$ kb\$ = back emf constant (volt·s/rad)

*\$  kt \$= torque constant (N·m/a)

*\$ jm \$= rotor inertia (kg m²)

*\$ bm\$ = mechanical damping (linear model of friction: bm * dth)
load parameters

*\$  jl \$=  load inertia (1000 times the rotor)

*\$ bl\$ =  load damping (friction)

*\$ k \$=  spring constant for motor shaft to load

*\$   b \$=  spring damping for motor shaft to load
Variables

*\$  i  \$   =  motor electric current (amperes)

*\$  dth_m\$ =  rotor angular velocity sometimes called omega (radians/sec)

*\$  th_m \$ =  rotor angle, theta (radians)

*\$   dth_l \$=  wheel angular velocity (rad/s)

*\$ th_l \$ =  wheel angle (radians)
Equations

*

*\$ lm*i - v = -rm*i -    kb *th_m \$

*\$jm*dth_m =  kt*i - (bm+b)*th_m - k*th_m +     b *th_l + k*th_l\$

*\$jl*dth_l =             b *th_m + k*th_m - (b+bl)*th_l - k*th_l\$

*\$dth_m = th_m\$

*\$dth_l = th_l \$


text:
Q: Filter my NSArray of NSDictionaries using several UIControls I have an NSArray of NSDictionarys (the dictionaries contain several key value pairs).  On my story board I have several UISegmentedControls and during their selected events I'm filtering out my array of dictionaries (works lovely).  I'm storing the selected state and values of these SegmentedControls inside instance variables so I can tell if they were previously selected or being selected for the first time.
The problem I'm having is trying to filter this Array of Dictionaries using multiple predicates created by each UISegmentControl.  For example if I click SegmentControl 1 it filters the array accordingly, If I click SegmentControl 2 it takes the current result and filters those.  However if I choose another value from SegmentControl 1 it returns nothing, because all those values had been originally filtered out.  This is accentuated even more by the fact that I have 5 of these Segments and I need to make sure it can filter my unfiltered set that's generated on my viewDidLoad (my unfiltered data comes from a JSON source and is stored once when the app loads to prevent it pulling from JSON source multiple times).
I'm having a terrible time trying to solve this filter issue.  I'm not sure if it's because my brain is mush from looking at this all day or if it is my novice ability with objc (I've got a lot of oop program experience, but this is my first objective c app). I thought about originally making a function/method that accepts the unfiltered array, and all the selected filter values to return the filtered data but I can't wrap my head around what would happen if some of the filter fields were nil.  What is the best way to approach this?  Here is some code:
@interface ViewController ()
{
    //Checks for UISegments
    Boolean isSegment1Selected;
    Boolean isSegment2Selected;
    Boolean isSegment3Selected;
    Boolean isSegment4Selected;

    //Instance FilterValues
    NSString *segment1Value;
    NSString *segment2Value;
    NSString *segment3Value;
    NSString *segment4Value;

    //Create arrays for dictionaries
    NSMutableArray *myArrayOfDictionaries;
    NSMutableArray *unfilteredArrayOfDictionaries;
    NSMutableArray *filteredArrayOfDictionaries;
}
@end

On my viewDidLoad() I'm filling myArrayOfDictionaries with the data from my JSON source.
I have IBOutlet events for each UISegmentView I'm using to filter.  I'll show you one since they are all pretty much the same minus their names:
/// UISegmentedControl Filters ///
- (IBAction)segment1:(UISegmentedControl *)sender {
    //    NSLog(isSegment1Selected ? @"YES" : @"NO");

    //Haven't used this if/else yet but guessing it will be part of the solution
    if (segment1Value == nil)
    {
        NSLog(@"Nothing");
    }
    else
    {
        NSLog(@"Something");
    }

    //Grab value of SegmentControl into instance variable and strip additional characters not needed from the end
    segment1Value = [[sender titleForSegmentAtIndex:sender.selectedSegmentIndex] substringToIndex:[sender titleForSegmentAtIndex:sender.selectedSegmentIndex].length -1 ];

    //Create predicate filter with key and value
    NSPredicate *predicateForSegment1 = [NSPredicate predicateWithFormat:@"(%K == %@)", segment1_key, segment1Value];

    //Check if filteredArray already has objects
    if ([filteredArrayOfDictionaries count] == 0)
    {
        //If filteredArray is empty, fill it with the filtered data using predicate from selected Segmented index control.  Then clear the array and copy filtered array to filtered array
        filteredArrayOfDictionaries = [[unfilteredArrayOfDictionaries filteredArrayUsingPredicate:predicateForSegment1] mutableCopy];

    }
    else
    {

        //If filtered array is full, empty it first then fill it with new filtered values.
        NSArray *tmpArray = [[NSArray alloc] initWithArray:filteredArrayOfDictionaries];
        [filteredArrayOfDictionaries removeAllObjects];
        filteredArrayOfDictionaries = [[tmpArray filteredArrayUsingPredicate:predicateForImpellerDiameter] mutableCopy];

    }

    [myArrayOfDictionaries removeAllObjects];
    [myArrayOfDictionaries addObjectsFromArray:filteredArrayOfDictionaries];
    [tableData reloadData];

}

All of my UISegmentControls look like this.  I started writing a function to call in each SegmentControl event to return the filtered array but I'm not sure if that is the best way either.  Here's what I have so far, I'm not sure if I should pass in Predicates or just Strings.
- (NSArray*)filteredResults:(NSArray*)unfilteredArray forSegment1:(NSPredicate*)segment1 forSegment2:(NSPredicate*)segment2 forSegment3:(NSPredicate*)segment3 forSegment4:(NSPredicate*)segment4;

Am I going about this the right way?  It all has become really confusing.  I know that when I select Segment1 and then Segment2, it filters correctly.  But as soon as I change the value of a segment already selected it returns nothing because the Segments values have already been filtered out by the first selection.  Is it possible to compare my filtered and my unfiltered array when a segment control has been previously selected?  I really hope this makes sense.  Thank you for looking and reading.

A: This is a perfect example of how the MVC paradigm can quickly become a "Massive View Controller" architecture.
Your View Controller is now burdened with the responsibility of maintaining 5 separate data sources and managing the state between them. Poor guy!
What you should contemplate doing is implementing aggregated data sources and specifically in your case a segmented data source. This allows you to abstract all your data source logic into a model object where it belongs.
A segmented data source is responsible for managing child data sources as well as vending the appropriate selected data source. This type of design makes it significantly easier to change your code to include more arrays or remove arrays as you see fit.
The singular responsibility principle is your friend and abstraction should be very attractive as you notice your code exhibiting signs of code smell.
Want more to go on? Then I highly recommend watching this years WWDC talk on advanced collection view layouts, they discuss exactly how you can reduce your View Controller complexity and build reusable data sources. See this blog post for all the links

A: You need to rebuild the filtered array each time one of the segments changes.  I would use something like this
@interface ViewController ()
{
    //Create arrays for dictionaries
    @property (strong,nonatomic) NSMutableArray *myArrayOfDictionaries;
    @property (strong,nonatomic) NSMutableArray *filteredArrayOfDictionaries;

    //Array for storage of predicates
    @property (strong,nonatomic) NSMutableArray *predicates;
    @property (strong,nonatomic) NSArray *predicateKeys;
}
@end

-(void) viewDidLoad {
     [super viewDidLoad];

     self.predicateKeys=@[@"key1",@"key2",@"key3",@"key4",@"key4"];
     self.predicates=[NSMutableArray new];
     for (int i=0;i<self.predicateKeys.count;i++) {
         [self.predicates addObject:[NSNull null]];
     }
     [self setupFilteredArray];
}

//  Set the tag for each segmented controller to it's "number" - 0 to 5 and set this method as the action handler for all of the segmented controls

- (IBAction)segmentChanged:(UISegmentedControl *)sender {
      NSInteger segmentNumber=sender.tag;
//Grab value of SegmentControl into instance variable and strip additional characters not needed from the end
    segmentValue = [[sender titleForSegmentAtIndex:sender.selectedSegmentIndex] substringToIndex:[sender titleForSegmentAtIndex:sender.selectedSegmentIndex].length -1 ];

    if ([segmentValue isEqualToString:@""]) {
        [self.predicates replaceObjectAtIndex:segmentNumber withObject:[NSNull null]];
    }
    else {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%K == %@)",self.predicateKeys[segmentNumber], segmentValue];
        [self.predicates replaceObjectAtIndex:segmentNumber withObject:predicate];
    }

    [self setupFilteredArray];
}

-(void) setupFilteredArray {
    NSArray *tempArray=[NSArray arrayWithArray:self.myArrayOfDictionaries];
    for (int i=0;i<self.predicates.count;i++) {
        if (!([self.predicates[i] isEqual:[NSNull null]])) {
            NSPredicate *predicate=(NSPredicate *)self.predicates[i];
            tempArray=[tempArray filteredArrayUsingPredicate:predicate];
        }
    }

    self.filteredArray=tempArray;
}


text:
Q: String Comparison Using Inequalities in Excel Can someone provide a reference to how excel compares strings using inequality operators in Excel? I have found some unexpected behavior:
In the below examples, the first two columns are strings, column C is of the expression =A2<B2, the third column is the expected behavior, and the final column is whether the expected behavior matches the actual.
Comparison  Benchmark   Is A < B?   Expected    Pass?
Q1 2009     Q4 2012       TRUE      TRUE        TRUE
Q2 2009     Q4 2012       TRUE      TRUE        TRUE
Q3 2009     Q4 2012       TRUE      TRUE        TRUE
Q4 2009     Q4 2012       TRUE      TRUE        TRUE
Q1 2010     Q4 2012       TRUE      TRUE        TRUE
Q2 2010     Q4 2012       TRUE      TRUE        TRUE
Q3 2010     Q4 2012       TRUE      TRUE        TRUE
Q4 2010     Q4 2012       TRUE      TRUE        TRUE
Q1 2011     Q4 2012       TRUE      TRUE        TRUE
Q2 2011     Q4 2012       TRUE      TRUE        TRUE
Q3 2011     Q4 2012       TRUE      TRUE        TRUE
Q4 2011     Q4 2012       TRUE      TRUE        TRUE
Q1 2012     Q4 2012       TRUE      TRUE        TRUE
Q2 2012     Q4 2012       TRUE      TRUE        TRUE
Q3 2012     Q4 2012       TRUE      TRUE        TRUE
Q4 2012     Q4 2012       FALSE     FALSE       TRUE
Q1 2013     Q4 2012       TRUE      FALSE       FALSE
Q2 2013     Q4 2012       TRUE      FALSE       FALSE
Q3 2013     Q4 2012       TRUE      FALSE       FALSE
Q4 2013     Q4 2012       FALSE     FALSE       TRUE
Q1 2014     Q4 2012       TRUE      FALSE       FALSE
Q2 2014     Q4 2012       TRUE      FALSE       FALSE
Q3 2014     Q4 2012       TRUE      FALSE       FALSE

For dates before the benchmark, it seems like Excel compares the whole string, whereas after the benchmark date, Excel only compares the string until it finds a single character less than the analogous character in the comparison.

A: What Excel does here is it compares the two strings character by character left to right until it finds a mismatch, and then the string with higher value character becomes the greater string.  This is the standard method to compare strings -- it's used in pretty much all programming languages, databases and other software packages.
So, for example, for the first line the comparison would go like this:
Comparison  Benchmark   Outcome
    Q           Q        Equal
    1           4        Benchmark is greater - done comparing
 [space]     [space]     Ignored
    2           2        Ignored
    0           0        Ignored
    0           1        Ignored
    9           2        Ignored

For the fourth line it would be:
Comparison  Benchmark   Outcome
    Q           Q        Equal
    4           4        Equal
 [space]     [space]     Equal
    2           2        Equal
    0           0        Equal
    0           1        Benchmark is greater - done comparing
    9           2        Ignored

And for the last line it would be:
Comparison  Benchmark   Outcome
    Q           Q        Equal
    3           4        Benchmark is greater - done comparing
 [space]     [space]     Ignored
    2           2        Ignored
    0           0        Ignored
    1           1        Ignored
    4           2        Ignored


text:
Q: Java class namespace? so I've recently started learning java but I'm having a little problem:
OrcMage.health -= 80;

but if you saw all of my code, you'd see that I use the OrcMage class a lot, and I still have a lot to go. Would it be possible to create something like a namespace so I could type health -= 80;instead?

A: Declare health as static then use
import static OrcMage.health;


text:
Q: Mach Number after Normal Shock Is there any way that someone can give me more of a conceptual explanation for the fact that the Mach number downstream of a normal shock must be less than or equal to 1?  I understand the mathematical reasons and how to show this is indeed true, but not exactly why.  I understand why it must be less than the Mach number upstream of the shock, but what is the reason it HAS to be less than or equal to one?
Thanks

A: The short answer is that sound waves travel at the speed of sound.  Since the sound speed increases downstream of a shock and the flow speed decreases, this results in a Mach number less than one.
The physical reason is that without a piston, the flow of a fluid cannot exceed its communication speed due to dissipative effects.  You can see my response here that explains this in more detail.
I will answer in more detail later, but my 8 month old daughter is demanding attention.
Updates
Suppose one were to create a region of homogeneous fluid flow with a uniform bulk flow speed.  The bulk flow speed could be larger than the speed of sound in that medium and nothing would be wrong with that.  There would be no shock waves or violations of laws, unless one inserted an obstacle into the medium.  The obstacle would then act as a piston or driver, that would obstruct and deflect the flow.  If the bulk flow speed exceeds the speed of sound, then a shock wave would form if sufficient energy dissipation existed.  I explain the need for energy dissipation here and wrote a response that explains energy dissipation (i.e., irreversibility) in more detail here.
You can also think in terms of traffic jams.  Imagine there is a highway/road where all the cars are moving with the same speed.  Now you insert a bunch of crazy drivers that try to move at twice that speed.  The crazy drivers would immediately run into the slower drivers and, ignoring damage done to the cars, would start to exchange energy/momentum with the slower cars (analogous to a binary particle collisions).  There would be a pile up of cars at the interaction region (analogous to a shock ramp).  Assume that we continually insert crazy drivers.  Eventually, the average speed of traffic on the road would increase slightly at the interaction region and behind it (i.e., direction from which the crazy drivers are coming, called the downstream region).  However, a larger increase would occur in the range of speeds of all the different drivers from all the collisions (analogous to increasing the heat/temperature).  This interaction region would move up the road faster than the slower drivers, thus expanding the downstream region and advancing the ramp region up the road.
If we were to ride in a helicopter and follow the ramp region (i.e., like transforming into the shock rest frame), it would appear as if the slower drivers were moving towards the ramp faster than their speed relative to the road.  The "mess" downstream would appear to be moving away from the ramp region at a slightly slower rate due to the increased collision rate and scattering of cars.
The point is, sound waves propagate at the sound speed because that is roughly the average thermal speed of the molecules in a gas (though in space, this gets more complicated as I discussed here).  To move faster than the average speed of the particles is to incur more collisions with those slower particles, thus lowering the net speed (on average) of this hypothetical faster particle.  So downstream of a shock, the Mach number is generally less than one because the forces involved act to keep the flow from moving faster than the average.


text:
Q: Vips - add text on top of image, after resize in Ruby I'm using Vips to resize images via Shrine, hoping it's possible to use the Vips library to merge a layer of text on top of the image.
ImageProcessing::Vips.source(image).resize_to_fill!(width, height)

This code works great, how can I add a layer of text after resize_to_fill?
The goal is to write 'Hello world' in white text, with a CSS text-shadow in the center of the image.
I've tried writing something like this, but I'm only getting errors so far:
Vips\Image::text('Hello world!', ['font' => 'sans 120', 'width' => $image->width - 100]);

A: Your example looks like PHP -- in Ruby you'd write something like:
text = Vips::Image.text 'Hello world!', font: 'sans 120', width: image.width - 100

I made a demo for you:
#!/usr/bin/ruby

require "vips"

image = Vips::Image.new_from_file ARGV[0], access: :sequential

text_colour = [255, 128, 128]
shadow_colour = [128, 255, 128]
h_shadow = 2
v_shadow = 5
blur_radius = 10

# position to render the top-left of the text
text_left = 100
text_top = 200

# render some text ... this will make a one-band uchar image, with 0
# for black, 255 for white and intermediate values for anti-aliasing
text_mask = Vips::Image.text "Hello world!", dpi: 300

# we need to enlarge the text mask before we blur so that the soft edges
# don't get clipped
shadow_mask = text_mask.embed(blur_radius, blur_radius,
                              text_mask.width + 2 * blur_radius,
                              text_mask.height + 2 * blur_radius)

# gaussblur() takes sigma as a parameter -- approximate as radius / 2
shadow_mask = shadow_mask.gaussblur(blur_radius / 2) if blur_radius > 0.1

# make an RGB image the size of the text mask with each pixel set to the
# constant, then attach the text mask as the alpha
rgb = text_mask.new_from_image(text_colour).copy(interpretation: "srgb")
text = rgb.bandjoin(text_mask)

rgb = shadow_mask.new_from_image(shadow_colour).copy(interpretation: "srgb")
shadow = rgb.bandjoin(shadow_mask)

# composite the three layers together
image = image.composite([shadow, text], "over",
                        x: [text_left + h_shadow, text_left],
                        y: [text_top + v_shadow, text_top])

image.write_to_file ARGV[1]

Run like this:
$ ./try319.rb ~/pics/PNG_transparency_demonstration_1.png x.png

To make:


text:
Q: set proportional to different property ex, width:10%height does it work in CSS to set a property by proportion to another property ?
i know that i can do this with java-script, but i would be nice if this is possible with CSS.
for example : width:10 % height;
if not is there any other good way to do it.
thanks for you help.

A: Using Nenad's comment I built a fiddle https://jsfiddle.net/bv5fLrth/20/
Re-size it vertically to see the width change size.
#someDiv {
  width: calc(100vh*0.1);
  height: 200px;
  background-color: blue;
}


text:
Q: Как открыть локальную страницу в Mozila Firefox В папке с профилем лежит html страничка как ее открить, тоесть в адресной строке нужно написать команду на подобее path но как она в фаерфокс пишется то?
ВОПРОС РЕШЕН
Сам я вопрос решил, но тут я не корректно написал его. Посколько удалить я его не могу пишу вот такое сообщение.

A: Несколько способов открыть локальный файл в Firefox:

*

*правой кнопкой по файлу "Открыть с помощью Firefox";

*в самом Firefox "Файл -> Открыть файл";

*прописать в адресной строке путь к файлу: file:///home/path/to/file;

*из консоли:

*

*открыть в новом окне: firefox --new-window file.txt

*открыть в новой вкладке: firefox --new-tab file.txt


text:
Q: Issue about logical output from MEX function in MATLAB Why is the output always 1 from my MEX function although it was expected to be 0?
I wrote the following MEX source code shown below
#include "mex.h"

void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
  bool *x,*y;

  /* Create matrix for the return argument. */
  plhs[0] = mxCreateLogicalMatrix(1,1);

  /* Assign pointers to each input and output. */
  x = mxGetLogicals(prhs[0]); //input
  y = mxGetLogicals(plhs[0]); //output

  /* Calculations. */
  if (*x == 0) *y = 1;
  else *y = 0;
}

and the following appears:
y = test(5)

y =

     1

A: I'd like to point you to the documentation of mxGetLogicals.  Part of the documentation says:

Returns
Pointer to the first logical element in the mxArray. The result is unspecified if the mxArray is not a logical array.

What you are passing is a double precision number, not a logical.  By doing this, you will get undefined behaviour. As such, there are three ways you can resolve this error:

*

*Pass an actual logical value to the function.

*Leave everything as is, but change what you are returning.  Instead of *y = 1 and *y = 0, change this to true and false respectively, but the input has to be double.

*You basically must change any reference to logical / bool to double.  Specifically, change mxGetLogicals to mxGetPr so you can get a pointer to a double precision real array.  You'll also need to change mxCreateLogicalMatrix to mxCreateDoubleMatrix and you'll have to change your pointers from bool to double.

Option #1 - Passing a logical value to the function:
You simply need to do:
y = test(false);

or:
y = test(true);

Running this with these changes gives me the following:
>> y = test(false)

y =

     1

>> y = test(true)

y =

     0

Option #2 - Input type is double, output type is bool:
These changes are what you need to make:
#include "mex.h"

void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
  double *x;
  bool *y; // Change

  /* Create matrix for the return argument. */
  plhs[0] = mxCreateLogicalMatrix(1,1);

  /* Assign pointers to each input and output. */
  x = mxGetPr(prhs[0]); //input - Change
  y = mxGetLogicals(plhs[0]); //output

  /* Calculations. */
  if (*x == 0) *y = true; // Change
  else *y = false;
}

Running this code with the above changes gives me:
>> y = test(0)

y =

     1

>> y = test(5)

y =

     0

Option #3 - Change bool behaviour to double:
#include "mex.h"

void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
  double *x,*y; // Change

  /* Create matrix for the return argument. */
  plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL); // Change

  /* Assign pointers to each input and output. */
  x = mxGetPr(prhs[0]); //input - Change
  y = mxGetPr(plhs[0]); //output - Change

  /* Calculations. */
  if (*x == 0) *y = 1;
  else *y = 0;
}

Running this code with the above changes gives me:
>> y = test(0)

y =

     1

>> y = test(5)

y =

     0


text:
Q: bullet doesn't bounce in pygame In the "def Update" section.
According to the place where the four blocks,which are tagged, are placed. The bullet just goes past the screen or stays inside the screen blinking (because it changes its x,y to -x,-y all the time)
Bullet doesn't bounce unlike in other programs I've made. I think the problem is in the position of those four blocks. Can you tell me where to fix?
class Bullet(pygame.sprite.Sprite):
    def __init__(self,centerx,centery,c):
        ...

    def update(self):
        a= pygame.time.get_ticks()
        self.b.append(a)

        #point and shoot
        if self.point == 1:
            self.yspeed = -10
            self.xspeed = 0
        if self.point == 2:
            self.yspeed = 10
            self.xspeed = 0
        if self.point == 3:
            self.yspeed = 0
            self.xspeed = -10
        if self.point == 4:
            self.yspeed = 0
            self.xspeed = 10

        #bounce
        if self.rect.right>=WIDTH or self.rect.left<=0:
            self.xspeed = -self.xspeed
        if self.rect.top<=0 or self.rect.bottom>=HEIGHT:
            self.yspeed = -self.yspeed

        #kill after 5 sec
        if (a-self.b[0])>=5000:
            del self.b[:]
            self.kill()

        #move according to speed
        self.rect.centerx += self.xspeed
        self.rect.centery += self.yspeed

my full code here - for you to try
import pygame
import random
from os import path

WIDTH = 800
HEIGHT = 600
FPS = 60

BLACK = (0,0,0)
WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255,0,0)
light_BLUE = (0,255,255)

pygame.init()
pygame.mixer.init()
screen= pygame.display.set_mode((WIDTH,HEIGHT))
clock = pygame.time.Clock()

class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((30,30))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.center = (WIDTH/2,HEIGHT/2)
        self.speed = 0
        self.y_speed = 0

    def update(self):
        self.speed = 0
        self.y_speed = 0
        keystate = pygame.key.get_pressed()
        if keystate[pygame.K_LEFT]:
            self.speed = -3
        if keystate[pygame.K_RIGHT]:
            self.speed = 3
        if keystate[pygame.K_UP]:
            self.y_speed = -3
        if keystate[pygame.K_DOWN]:
            self.y_speed = 3
        self.rect.x+=self.speed
        self.rect.y+=self.y_speed

class Gun(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((10,10))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.center = (WIDTH/2,HEIGHT/2)
        self.a = 0
        self.b = 0
        self.c = 0

    def update(self,player_Cposition):
        keystate = pygame.key.get_pressed()
        if keystate[pygame.K_UP]:
            self.a = player_Cposition[0]
            self.b = player_Cposition[1]-2*self.rect.height
            self.c = 1
        if keystate[pygame.K_DOWN]:
            self.a = player_Cposition[0]
            self.b = player_Cposition[1]+2*self.rect.height
            self.c = 2
        if keystate[pygame.K_LEFT]:
            self.a = player_Cposition[0]-2*self.rect.width
            self.b = player_Cposition[1]
            self.c = 3
        if keystate[pygame.K_RIGHT]:
            self.a = player_Cposition[0]+2*self.rect.width
            self.b = player_Cposition[1]
            self.c = 4
        self.rect.center = [self.a,self.b]

    def shoot(self,x,y,c):
        bullet = Bullet(x,y,c)
        all_sprites.add(bullet)

class Bullet(pygame.sprite.Sprite):
    def __init__(self,centerx,centery,c):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((8,8))
        self.image.fill(light_BLUE)
        self.rect = self.image.get_rect()
        self.rect.center = [centerx,centery]
        self.point = c
        self.xspeed = 0
        self.yspeed = 0
        self.b = []

    def update(self):
        a= pygame.time.get_ticks()
        self.b.append(a)
        #point and shoot
        if self.point == 1:
            self.yspeed = -10
            self.xspeed = 0
        if self.point == 2:
            self.yspeed = 10
            self.xspeed = 0
        if self.point == 3:
            self.yspeed = 0
            self.xspeed = -10
        if self.point == 4:
            self.yspeed = 0
            self.xspeed = 10

        #bounce
        if self.rect.right>=WIDTH or self.rect.left<=0:
            self.xspeed = -self.xspeed
        if self.rect.top<=0 or self.rect.bottom>=HEIGHT:
            self.yspeed = -self.yspeed

        #kill after 5 sec
        if (a-self.b[0])>=5000:
            del self.b[:]
            self.kill()

        #move according to speed
        self.rect.centerx += self.xspeed
        self.rect.centery += self.yspeed

all_sprites = pygame.sprite.Group()
player = Player()
gun = Gun()
all_sprites.add(player)
gun_sprites = pygame.sprite.Group()
gun_sprites.add(gun)

running = True
while running:
    #event
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                gun.shoot(gun.a,gun.b,gun.c)
    #update
    all_sprites.update()
    gun_sprites.update(player.rect.center)
    #draw
    screen.fill(BLACK)
    all_sprites.draw(screen)
    gun_sprites.draw(screen)
    pygame.display.update()
    #clock
    clock.tick(FPS)
pygame.quit()

A: You are changing bullet speed in two places in your Bullet update function, one workaround
could be:
# bounce
    if self.rect.right >= WIDTH or self.rect.left <= 0:
        self.xspeed = -self.xspeed
        self.point = 0
    if self.rect.top <= 0 or self.rect.bottom >= HEIGHT:
        self.yspeed = -self.yspeed
        self.point = 0


text:
Q: Proof attempt of exercise 3.2, Ch. III Hartshorne I try to prove that if a Noetherian scheme $X$ has each irreducible component affine, then $X$ is affine. Here's my attempted proof:
Choose an irreducible component $i:Y \to X$ and a quasi-coherent sheaf $\mathcal{F}$ on $X$. If $U = X\setminus Y$, $j:U\to X$, then we have the short exact sequence $0 \to \mathcal{F}_U \to \mathcal{F} \to \mathcal{F}_Y \to 0$, where $\mathcal{F}_U = j_!(\mathcal F|_U)$ and $\mathcal{F}_Y = i_*(\mathcal F|_Y)$. By taking the long exact sequence in cohomology we get the surjective maps
\begin{align}
H^p(X,\mathcal{F}_U) \to H^p(X,\mathcal{F}) \to H^p(X,\mathcal{F}_Y) = 0,
\end{align}
where the last group is $0$ since $Y$ is affine and $\mathcal{F}_Y$ is quasi-coherent. Hence it is enough to prove that $H^p(X,\mathcal{F}_U) = 0$ (then apply Serre's criterion for affineness). Now I want to use the fact that $\mathcal{F}_U$ is a quasi-coherent sheaf on $\overline{U}$, which has less irreducible components than $X$, and to use some induction on the number of irreducible components to get that $H^p(X,\mathcal{F}_U)  = 0$.
My question is how I make rigorous this last fact. More precisely, how do I show that $H^p(\overline{U},\mathcal{F}_U|_\overline{U})  = H^p(X,\mathcal{F}_U)$?

A: Here are the two statements we'll need.

For any closed immersion $f:X\to Y$ and any sheaf $\mathcal{F}$ on $Y$ supported on $X$, the natural morphism of $\mathcal{O}_Y$-modules $\mathcal{F}\to f_*f^*\mathcal{F}$ is an isomorphism.

This can be proven by checking on stalks.

For any $\mathcal{O}_X$ module $\mathcal{G}$, we have $H^p(X,\mathcal{G})=H^p(Y,f_*\mathcal{G})$.

This is a direct consequence of closed immersions being affine and is an exercise earlier in Hartshorne.
Now we apply the facts. Write $k:\overline{U}\to X$ for the closed immersion. Then $\mathcal{F}_U|_{\overline{U}}=k^*\mathcal{F}_U$, so $$H^p(\overline{U},\mathcal{F}_U|_{\overline{U}}) = H^p(\overline{U},k^*\mathcal{F}_U)=H^p(X,k_*k^*\mathcal{F}_U)= H^p(X,\mathcal{F}_U)$$ per the statements in the previous paragraph.
For a more conventional solution (I'm not even sure Hartshorne ever defines $f_!$ in the text), consider the following:
Let $X=\bigcup_{1\leq i \leq n} X_i$ be a decomposition in to irreducible components with $\mathcal{I}_i$ the ideal sheaf of $X_i$. Let $I$ be a coherent ideal sheaf on $X$. Then we may form the filtration $$I\supset I\cdot \mathcal{I}_1 \supset I\cdot \mathcal{I}_1\cdot\mathcal{I}_2 \supset \cdots \supset I\cdot \mathcal{I}_1\cdots\mathcal{I}_n$$ where we rename the terms $I_0\supset I_1\supset\cdots I_n$ for ease of notation. The final term is zero by assumption that $X$ is reduced, and each subquotient $I_j/I_{j+1}$ is a coherent sheaf supported on $X_{j+1}$ which implies $H^1(X_{j+1},I_j/I_{j+1})=H^1(X,I_j/I_{j+1})$ (this uses the same fact you're asking about, proven above). After taking the cohomology of $$ 0\to I_{j+1}\to I_{j} \to I_j/I_{j+1} \to 0$$ we see that $0=H^1(X,I_n)=H^1(X,I_{n-1})=\cdots=H^1(X,I_0)=0$ and we have the desired claim.


text:
Q: How does internet explorer gets its favorites? Looks like there are two ways for Internet Explorer to keep its favorites list: in "Windows/Favorites" folder and in registry "HKCU/Software/Microsoft/Internet Explorer/Main/FavouritesEntries".
The information there seems duplicated. I would like to know, how does internet explorer builds his favorites list? He prefers registry settings or folder settings? And how does it handle the situation, when registry list does not match folder list?
Thank you!

A: I think "HKCU/Software/Microsoft/Internet Explorer/Main/FavouritesEntries" location has default IE bookmarks and user bookmarks are stored in Windows/Favorites folder. So IE would use combination of both this list to build favorites when IE is loaded.

A: It also takes contents from the folders specified in "Favorites" key in these registry locations:
HKEY_CURRENT_USER\Software\Microsoft\Windows\Current Version\Explorer\Shell folders
HKEY_CURRENT_USER\Software\Microsoft\Windows\Current Version\Explorer\User Shell folders
HKEY_USERS\.default\Software\Microsoft\Windows\Current Version\Explorer\Shell folders
HKEY_USERS\.default\Software\Microsoft\Windows\Current Version\Explorer\User Shell folders


text:
Q: How to pick all elements but the one i hover in jquery I want to make all divs in a .html file disappear while the mouse is hovering on a certain div. In other words, is there anything like the $(this), but instead of this for all other divs that?
Thank you in advance.

A: Try
var div_all = $('div'); //refers to all div
div_all.hover(function () {
    div_all.not(this).hide(); //hide all div's but not current one
    $(this).show(); //$(this) refers to current div and show current div
}, function () {
    div_all.hide(); //hide all divs
});

div_all.not(this) refers to all divs except the one which is hovered.

References

this keyword
.not()
.hover()

A: $('div').hover(
    function(){ $('div').not(this).hide(); },
    function(){ $('div').show(); }
);


text:
Q: Advantages of using pixel tracking mechanism versus regular HTTP GET API call for client side tracking Pixel tracking method seems to be gaining traction recently especially in the field of marketing and analytics.
For client side tracking internally (tracking system is not opened to be used by public), what are the advantages of using pixel to track (downloading a 1 pixel image and passing all params that we are interested in tracking in the image url) versus regular old http get call and passing the get parameter in a message queue to be processed later.


text:
Q: Is there a simple interpretation of the eigenvectors of a graph (visualizable?)? I want to understand eigenvectors obtain from graphs (adjacency matrices) in an analogous way as they are interpreted from principal component analysis of a set of images, which is easy:Eigenfaces Wiki. From the wiki page we see that each row in the matrix is an image and the eigenvector a reference image:

Each image is treated as one vector, simply by concatenating the rows of pixels in the original image, resulting in a single row with r × c elements. For this implementation, it is assumed that all images of the training set are stored in a single matrix T, where each row of the matrix is an image.
  Subtract the mean. The average image a has to be calculated and then subtracted from each original image in T.
  Calculate the eigenvectors and eigenvalues of the covariance matrix S. Each eigenvector has the same dimensionality (number of components) as the original images, and thus can itself be seen as an image. The eigenvectors of this covariance matrix are therefore called eigenfaces.

Can we then say that the adjacency matrix is a set of row networks with outgoing edges, and that the eigenvector is another network as well? I am looking for a tangible interpretation of eigenvector of the graph's adjacency matrix in a similar fashion of eigenfaces. (something that could also be visualized easily?)


text:
Q: I could not createsuperuser for django I want to create super user.
 I used the command prompt to create super user.
When I write this code
Python manage.py createsuperuser

I get this error
Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\ysr\Desktop\Blog\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "C:\Users\ysr\Desktop\Blog\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\ysr\Desktop\Blog\venv\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\ysr\Desktop\Blog\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 59, in execute
    return super().execute(*args, **options)
  File "C:\Users\ysr\Desktop\Blog\venv\lib\site-packages\django\core\management\base.py", line 353, in execute
    output = self.handle(*args, **options)
  File "C:\Users\ysr\Desktop\Blog\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 112, in handle
    username = self.get_input_data(self.username_field, input_msg, default_username)
  File "C:\Users\ysr\Desktop\Blog\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 193, in get_input_data
    raw_value = input(message)
  File "C:\Users\ysr\Desktop\Blog\venv\lib\encodings\cp437.py", line 12, in encode
    return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character '\u0131' in position 6: character maps to <undefined>

I am using pycharm2018.3.1x64
Please help me.

A: This is a "UnicodeEncodeError". Please try the character encoding 'utf-8' in your database field definition and related code parts.

A: if u need to write some text on other languages (not English I mean) in your documents.
this thing at top of your file can help u.
even if your text is commented
#-*- coding: utf-8 -*-


text:
Q: Why create custom init when ivars/properties can be set from outside the instance? I'm reading an Objective-C book and I have a question that the book doesn't seem to really answer.
Let's say I have two custom-made classes.
The first class is called ClassA. It has both the .h and .m files of course. The second class is called ClassB. It also has both .h and .m files.
Somewhere in the code, 'ClassA' has this method:
-(IBAction)displaySomeText:(id)sender {
    ClassB *myNumber = [[ClassB  alloc]init];

    NSString *numberString = [myNumber storedNumberAsString];
    // storedNumberAsString is just a method that returns a string object that holds
    // myVariable.

    [textView insertText:numberString];
    //textView is a object  I created that just displays some text on screen.

    [myNumber release];
}

The book tells me that ClassB should have a method:
-(id)init {
    [super init]; //I know why this is done, the book explains it well.
    myVariable = 42; // I created this variable already in the ClassB .h file
    return self;
}

Now, when in the Interface Builder I click the buttons I connected, etc. It works, the number displayed is 42.
My question is, why do I have to create an -(id)init method for ClassB, if I can do the following in ClassA's method:
-(IBAction)displaySomeText:(id)sender {
    ClassB *myNumber = [[ClassB alloc]init];
    myNumber.myVariable = 42; //I just do this to skip the -(id)init method.

    NSString *numberString = [myNumber storedNumberAsString];
    [textView insertText:numberString];
    [myNumber release];
}

Doing this, it still displays the same value: 42. I can change it to whatever I like. So why not just use the init inherited from NSObject and just do the simple way myNumber.myVariable = 42?

A: Suppose that the value of the instance variable were something more complicated than an integer. Suppose it involved reading a string from a file, or getting some information over the network, or just doing some arithmetic. In that case, it wouldn't make sense to have ClassA be responsible for setting that value correctly. That would break the encapsulation that makes it useful to have separate classes in the first place.
In this extremely simple case, you're quite right, there may be no reason to have a custom initializer for ClassB, but in general, a class should itself be responsible for its state being set up correctly. Foisting that responsibility off on other classes means that those others need to know about the internals of the first, meaning the two may be too tightly coupled.
In some cases, the value of the ivar might be a piece of information that is known only to ClassA, or needs to be calculated based on such a piece of information. Then you should create a custom initializer for ClassB which receives that value, e.g., - (id) initWithInteger: This would become the "designated initializer", and you would then override -[ClassB init] to call it with some reasonable default value.

A: If instances of ClassB do not have to have anything initialized (other than to nil/zero), you do not need to create an explicit init method for ClassB.  In this case the question is whether setting myVariable to 42 is ClassB's answer to life, the universe, and everything, or whether myVariable is just a field in ClassB that could be set to any value.
That is, the issue is conceptual, not of physical significance.  If conceptually the value 42 "belongs" to ClassB, then there should be an init method for ClassB that sets it.  If that specific value has more meaning to ClassA than to ClassB then some method of ClassA should set it.  If you do it "wrong" the code still works fine, but your design is slightly less elegant, slightly less extendable, slightly less robust.

A: This is kind of a tricky issue. I was "brought up" to think that after a constructor (initializer) runs, the object should be ready to go. You should be able to safely call any method on it. Therefore, you need to set up any instance variables in the constructor for which 0 is not a valid value. I like to set them up if they have 0 values anyway, just for sanity, because I never want to bother to know the minute details of every language I work with, like whether they initialize instance variables to 0 automatically.
However, there are some arguments for not initializing some variables.

*

*The initialization is complex, like loading a file or getting data from the network. You want to keep open the possibility of creating an instance and waiting until you're ready to do heavy weight operations.

*There are quite a lot of instance variables that are configurable. Your options are to make a constructor with umpteen arguments, or make a constructor with no or a few arguments, and let the caller decide which values should be set to non-default values by property setters.

*You need to set up a whole object graph before you can meaningfully initialize a value. That is, initializing the value might have side effects that depend on other related objects. The best solution is to construct each object, then use property setters to set the relationships between objects, then use property setters to initialize attribute values.


text:
Q: Scan and print full names in a list (C language) I want to create a C program that can read 'n' number of full names from keyboard input and print them. I tried to use fgets(), but couldn't figure out how to scan multiple entries, so I ended up writing the code below.
The issue is, it takes the names as input and just prints garbage values.
#include <stdio.h>
#include <conio.h>
#include <string.h>

int main()
{
    int n,i;
    char name[64][64],sur[15][15],a[3];

    printf("How many names? ");
    scanf("%d",&n);
    printf("\nEnter names:\n");

    for(i=0;i<n;i++)
    {
        scanf("%s%s",name[i],sur[i]);
    }

    for(i=0;i<n;i++)
    {
        a[3]=' ';
        strcat(name[i],a);
        strcat(name[i],sur[i]);
    }

    printf("\nThe names are:\n");
    for(i=0;i<n;i++)
    {
        printf("%s",name[i]);
    }
    getch();

    return 0;
}

A: @16tons addresses the most obvious issue, but there are lurking memory problems. The scanf and strcat calls are vulnerable to buffer overflows. They will not limit themselves to just the allocated memory.
for(i=0;i<n;i++)
{
    scanf("%s%s",name[i],sur[i]);
}

This will try to put any number of input characters into name[i] and sur[i] which can only hold strings of 63 and 14 characters respectively. That means Hubert Wolfeschlegelsteinhausenbergerdorff will cause name[i] to contain "Hubert\0" and sur[i] will contain "Wolfeschlegelst" (no null byte) and the rest will spill over into adjacent memory causing problems. Because of the lack of a null byte, trying to use sur[i] as a string will result in reading whatever garbage is after it.
Same with strcat.
for(i=0;i<n;i++)
{
    a[0]=' ';
    a[1]='\0';
    strcat(name[i],a);
    strcat(name[i],sur[i]);
}

If name[i] is already full, adding to the end of it will overflow its buffer scribbling over adjacent memory and causing weird problems.
How many names? 3

Enter names:
Hubert Wolfeschlegelsteinhausenbergerdorff
Hubert Wolfeschlegelsteinhausenbergerdorff
Hubert Wolfeschlegelsteinhausenbergerdorff

The names are:
Hubert WolfeschlegelstWolfeschlegelstWolfeschlegelsteinhausenbergerdorff WolfeschlegelstWolfeschlegelsteinhausenbergerdorff
gerdorff WolfeschlegelstWolfeschlegelsteinhausenbergerdorff
Hubert Wolfeschlegelsteinhausenbergerdorff

To avoid this, scanf must be limited to the buffer size. When using strcat, the string being added to must have sufficient space to accept the new characters.
Since you're using name[i] to store both the first name and then the full name, it's important that you limit the size of the first name to leave space for the last time. Since sur[i] can have 14 characters, and name[i] can have 63, that's 63 - 14 or 49. Don't forget the space! 48.
for(i=0;i<n;i++)
{
    scanf("%48s%14s",name[i],sur[i]);
}

This ensures that scanf will read no more than 48 characters into name[i] (using 49 bytes because of the null byte) and no more than 14 into sur[i] (using 15).
Now your strcats are safe. We know for sure name[i] has the space to accept a space and sur[i] on the end. 48 (max chars already in name[i]) + 1 (the space) + 14 (max in sur[i]) + 1 (null byte) = 64.
While your technique saves some memory, it's much safer to have separate given and surname variables which are concatenated into a fresh name variable. Then all you need to do is add up the sizes of given, surname, and the space to know how big name should be. The limits on scanf are simply the size of the buffers. No needing to remember that one variable has to keep some extra space around, nor having to redo all those calculations (or more likely forget to redo them) if surname gets bigger.
For your particular purposes, the strcats are unnecessary. printf can do it safer.
printf("\nThe names are:\n");
for(i=0;i<n;i++)
{
    printf("%s %s\n",name[i], sur[i]);
}

It's safer, easier, and faster to print a bunch of variables to a stream than to concatenate them together and then print them.

A: As mentioned in the comment, use a[0] as space and make a[1] null. Code below works.
int main()
{
    int n,i;
    char name[64][64],sur[15][15],a[3];

    printf("How many names? ");
    scanf("%d",&n);
    printf("\nEnter names:\n");

    for(i=0;i<n;i++)
    {
        scanf("%s%s",name[i],sur[i]);
    }

    for(i=0;i<n;i++)
    {
        a[0]=' ';
        a[1]='\0';
        strcat(name[i],a);
        strcat(name[i],sur[i]);
    }

    printf("\nThe names are:\n");
    for(i=0;i<n;i++)
    {
        printf("%s\n",name[i]);
    }
    getch();

    return 0;
}


text:
Q: Perl: How to get all grouped patterns I have the following code.
Here I am matching the vowels characters words:
if ( /(a)+/ and /(e)+/ and /(i)+/ and /(o)+/ and /(u)+/ )
{
print "$1#$2#$3#$4#$5\n";
$number++;
}

I am trying to get the all matched patterns using grouping, but I am getting only the last expression pattern, which means the fifth expression of the if condition. Here I know that it is giving only one pattern because last pattern matching in if condition.  I want to get all matched patterns, however.  Can anyone help me out of this problem?

A: It is not quite clear what you want to do. Here are some thoughts.
Are you trying to count the number of vowels? In which case, tr will do the job:
    my $count = tr/aeiou// ;
    printf("string:%-20s count:%d\n" , $_ , $count ) ;

output :
    string:book                 count:2
    string:stackoverflow        count:4

Or extract the vowels
    my @array = / ( [aeiou] ) /xg  ;
    print Dumper \@array ;

Output from "stackoverflow question"
    $VAR1 = [
              'a',
              'o',
              'e',
              'o',
              'u',
              'e',
              'i',
              'o'
            ];

Or extract sequences of  vowels
    my @array = / ( [aeiou]+ ) /xg  ;
    print Dumper \@array ;

Output from "stackoverflow question"
    $VAR1 = [
              'a',
              'o',
              'e',
              'o',
              'ue',
              'io'
            ];

A: You could use
sub match_all {
  my($s,@patterns) = @_;

  my @matches = grep @$_ >= 1,
                map [$s =~ /$_/g] => @patterns;

  wantarray ? @matches : \@matches;
}

to create an array of non-empty matches.
For example:
my $string = "aaa e iiii oo uuuuu aa";
my @matches = match_all $string, map qr/$_+/ => qw/ a e i o u /;

if (@matches == 5) {
  print "[", join("][", @$_), "]\n"
    for @matches;
}
else {
  my $es = @matches == 1 ? "" : "es";
  print scalar(@matches), " match$es\n";
}

Output:
[aaa][aa]
[e]
[iiii]
[oo]
[uuuuu]
An input of, say, "aaa iiii oo uuuuu aa" produces
4 matches

A: *

*You have 5 patterns with one matching group () each. Not 1 pattern with 5 groups.

*(a)+ looks for a string containing a, aa, aaa, aaaa etc. The match will be multiple a's, not the word containing the group of a-s.

*Your if( ...) is true if $_ contains one or more of 'a','e','i','o','u'.


text:
Q: vectorized shuffling per row in pandas I want to shuffle the columns of a pandas data frame.
However, the default method (sample) shuffles all the columns in the same way.
How can I efficiently shuffle the columns of each row differently?
import pandas as pd

df = pd.DataFrame({'foo':[1,4,7],'bar':[2,5,8],'baz':[3,6,9],})
display(df)
df.sample(frac=1, axis=1)

Certainly, an apply based solution would work - but this would not be vectorized and thus slow.

Is there a fast (and ideally vectorized) way to sample differently for each row?

A: Let us try with np.random.rand and argsort to generate shuffled indices
i = np.random.rand(*df.shape).argsort(1)
df.values[:] = np.take_along_axis(df.to_numpy(), i, axis=1)

print(df)

   foo  bar  baz
0    3    1    2
1    4    5    6
2    7    9    8

A: You can try this solution:
def shuffle_columns_per_row(df):
    arr = df.values
    x, y = arr.shape
    rows = np.indices((x,y))[0]
    cols = [np.random.permutation(y) for _ in range(x)]
    return pd.DataFrame(arr[rows, cols], columns=df.columns)

| foo | bar | baz |
|-----|-----|-----|
| 3   | 2   | 1   |
| 5   | 6   | 4   |
| 9   | 7   | 8   |

A: A quick check gives the benchmark:
%%timeit
df.sample(frac=1, axis=1)
# 1000 loops, best of 5: 288 µs per loop

With apply, as you said, we get:
%%timeit
idx = np.random.choice([0, 1, 2], size=(3,), replace=False)
df.apply(lambda x: x.iloc[idx], axis=1)
# 1000 loops, best of 5: 1.47 ms per loop -> ~3700 times slower

We could rather use iloc:
%%timeit
idx = np.random.choice([0, 1, 2], size=(3,), replace=False)
df.iloc[:, idx]
# 1000 loops, best of 5: 398 µs per loop -> ~1.4 times slower

If you could live with a roughly 1.4 times decrease in speed, I think the iloc version would work.


text:
Q: How to Configure cisco router using POWERSHELL SSH.net? Good, this is the code I'm using:
function escribe_log($dispositivo, $log, $comando){
$Fichero_Log = "C:\Modificacion_routers.log"
$texto = $dispositivo
    $texto >> $Fichero_Log
    $texto = $log
    $texto >> $Fichero_Log
    $texto = $comando
    $texto >> $Fichero_Log
}

##PROGRAMA PRINCIPAL##
Import-Module SSH-Sessions

$ficheroIPS = "C:\ipsdispositivos.txt"
$ficheroComandos = "c:\comandos.txt"

$dispositivos = Get-Content $ficheroIPS
$comandos = Get-Content $ficheroComandos

foreach ($dispositivo in $dispositivos) {
    New-SshSession -ComputerName $dispositivo -Username USUARIO -password PASSWORD
    foreach ($comando in $comandos) {
        $SshResults = Invoke-SshCommand -ComputerName $dispositivo -Command $comando
        escribe_log $dispositivo $SshResults $comando
        Start-Sleep -s 1
    }
    $comandos = Get-Content $ficheroComandos
}

Remove-sshSession -RemoveAll

Works perfectly to launch "sh" show commands, my problem is that when I launch a command automatically disconnects the session, then command is not possible to launch a "conf t" to enter configuration mode and then launch configuration commands.
Do you know if this library is possible to configure a router?
if that is not possible,
would they know me any alternative to configure the router using script?

SOLVED:
FUNCTION FOR CHANGES TO SSH ROUTER/SWITCH WITH POWERSHELL
Function set-SSH($devices, $ssh){
    function ReadStream($reader)
    {
        $line = $reader.ReadLine();
        while ($line -ne $null)
        {
            $line
            $line = $reader.ReadLine()
        }
    }

    function WriteStream($cmd, $writer, $stream)
    {
        $writer.WriteLine($cmd)
        while ($stream.Length -eq 0)
        {
            start-sleep -milliseconds 1000
        }
    }

    $stream = $ssh.CreateShellStream("dumb", 80, 24, 800, 600, 1024)

            $reader = new-object System.IO.StreamReader($stream)
            $writer = new-object System.IO.StreamWriter($stream)
            $writer.AutoFlush = $true

            while ($stream.Length -eq 0)
            {
                start-sleep -milliseconds 500
            }
            ReadStream $reader

            foreach ($command in $commands) {

                WriteStream $command $writer $stream
                ReadStream $reader
                Write-Host $reader
                start-sleep -milliseconds 500
            }

            $stream.Dispose()
            $ssh.Disconnect()
            $ssh.Dispose()

}

There are three variables to initialize $commands, $ssh, $devices
    #Example of file commands.txt...
    #sh conf
    #conf t
    #int f0/1
    #description Modify via powershell
    #exit
    #exit
    #wr
    #...
    $fileCommands= ".\commands.txt"
    $commands= Get-Content $fileCommands
    #Example of file devices.csv...
    #10.10.10.10;SWITCH01
    #10.10.10.11;SWITCH02
    #10.10.10.12;SWITCH03
    #...
    $devices = Import-Csv -path ".\devices.csv" -header 'ip','hostname' -delimiter ';'
    $port = 22
    $ssh = new-object Renci.SshNet.SshClient($devices[0].ip, $port, $user, $password)
    Try{
            $ssh.Connect()
            Start-Sleep -s 1
            set-SSH $commands $ssh
    }catch{
    }


text:
Q: Why is Account Owner not always shown when merging accounts? We're doing some account cleanups on our org by merging duplicate accounts.  These accounts have different Account Owners.  On the merge page, where you get to reconcile fields, sometimes the Account Owner field appears and sometimes it doesn't.
Does anyone know (or can point me to documentation) the logic around why it wouldn't always display on the merge page so I can choose who owns the merged record?
Screenshot 1 - two records, different owners, owner field shown

Screenshot 2 - two records, different owners, owner field not not shown

A: Reason behind that Master record contains Organization Owner which you want to keep.
Where as in the non master it should not have because it is getting merged with Master record who will own the record which has been defined as Organization Owner.
And, non master account will move into recycle bin.


text:
Q: Include stack template into another one I know that I can export values of some stacks via Cross Stack References. I also know that it's possible to reuse some code using Nested Stacks.
How can I have a template routing-server.yml and ws-server.yml and import (OR compose them in) env-staging.yml?

A: Look at the reference architecture of the awslabs/ecs-refarch-cloudformation Github repository, it uses nested stacks.
Resources:

VPC:
    Type: AWS::CloudFormation::Stack
    Properties:
        TemplateURL: https://s3.amazonaws.com/ecs-refarch-cloudformation/infrastructure/vpc.yaml
        Parameters:
            EnvironmentName:    !Ref AWS::StackName
            VpcCIDR:            10.180.0.0/16
            PublicSubnet1CIDR:  10.180.8.0/21
            PublicSubnet2CIDR:  10.180.16.0/21
            PrivateSubnet1CIDR: 10.180.24.0/21
            PrivateSubnet2CIDR: 10.180.32.0/21

https://github.com/awslabs/ecs-refarch-cloudformation


text:
Q: Thumbnail Grid shows up in reverse order I have a wordpress site that uses a thumbnail grid (9 posts, 3 posts wide, responsive ) the featured image on each post creates the grid.
My code that controls the grid is
<?php
/**
 * controls main grid images
 */
?>

<article id="post-<?php the_ID(); ?>" <?php post_class('col-md-4 col-sm-4 pbox '); ?>>

<a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?>

<?php the_category(', '); ?>

    <?php
        $thumb = get_post_thumbnail_id();
        $img_url = wp_get_attachment_url( $thumb,'full' ); //get full URL to image (use "large" or "medium" if the images too big)
        $image = aq_resize( $img_url, 750, 560, true ); //resize & crop the image
    ?>

    <?php if($image) : ?>
    <a href="<?php the_permalink(); ?>"> <img class="img-responsive" src="<?php echo $image ?>"/>
    <?php endif; ?>

It creates a grid but it shows up in the reverse order (9 to 1, instead of 1 to 9) This wouldn't be a huge deal but I have 'next' and 'previous' buttons which don't co-ordinate to the post.
Ex. on my first post the 'previous' button shows up cause it thinks its on the 9th post, etc.
the back/next menu is created with the following
function web2feel_content_nav( $nav_id ) {
global $wp_query, $post;

// Don't print empty markup on single pages if there's nowhere to navigate.
if ( is_single() ) {
    $previous = ( is_attachment() ) ? get_post( $post->post_parent ) : get_adjacent_post( false, '', true );
    $next = get_adjacent_post( false, '', false );

    if ( ! $next && ! $previous )
        return;
}

// Don't print empty markup in archives if there's only one page.
if ( $wp_query->max_num_pages < 2 && ( is_home() || is_archive() || is_search() ) )
    return;

$nav_class = ( is_single() ) ? 'post-navigation' : 'paging-navigation';

?>
<nav role="navigation" id="<?php echo esc_attr( $nav_id ); ?>" class="<?php echo $nav_class; ?> row">

<?php _e( 'Post navigation', 'web2feel' ); ?>

<?php if ( is_single() ) : // navigation links for single posts ?>

    <?php previous_post_link( '
%link
', '' . _x( '←', 'Previous post link', 'web2feel' ) . ' %title' ); ?>
    <?php next_post_link( '
%link
', '%title ' . _x( '→', 'Next post link', 'web2feel' ) . '' ); ?>

<?php elseif ( $wp_query->max_num_pages > 1 && ( is_home() || is_archive() || is_search() ) ) : // navigation links for home, archive, and search pages ?>

    <?php if ( get_next_posts_link() ) : ?>

<?php next_posts_link( __( '← Older posts', 'web2feel' ) ); ?>

    <?php endif; ?>

    <?php if ( get_previous_posts_link() ) : ?>

<?php previous_posts_link( __( 'Newer posts →', 'web2feel' ) ); ?>

    <?php endif; ?>

<?php endif; ?>

<?php
}


text:
Q: GCM is not working on Nexus 7 it is on Samsung Galaxy S3 So i have implemented GCM into my app with help of the AndroidHive tutorial.
The push messages used to work on both of my devices Samsung Galaxy S3 and Nexus 7. But now the push notifications only work on my samsung galaxy s3 and it gives an error to my Nexus 7. My nexus 7 does not want to register anymore. when i attempt to register my Nexus 7 i get this:
    01-01 07:46:33.396: V/GCMBroadcastReceiver(10980): onReceive: com.google.android.c2dm.intent.REGISTRATION
01-01 07:46:33.396: V/GCMBroadcastReceiver(10980): GCM IntentService class: com.toviehd.remake.GCMIntentService
01-01 07:46:33.396: V/GCMBaseIntentService(10980): Acquiring wakelock
01-01 07:46:33.426: V/GCMBaseIntentService(10980): Intent service name: GCMIntentService-725930664821-1
01-01 07:46:33.426: E/GCMRegistrar(10980): internal error: retry receiver class not set yet
01-01 07:46:33.426: V/GCMRegistrar(10980): Registering receiver
01-01 07:46:33.436: D/GCMBaseIntentService(10980): handleRegistration: registrationId = null, error = SERVICE_NOT_AVAILABLE, unregistered = null
01-01 07:46:33.436: D/GCMBaseIntentService(10980): Registration error: SERVICE_NOT_AVAILABLE
01-01 07:46:33.436: I/GCMIntentService(10980): Received recoverable error: SERVICE_NOT_AVAILABLE
01-01 07:46:33.446: D/GCMBaseIntentService(10980): Scheduling registration retry, backoff = 1573 (3000)
01-01 07:46:33.466: V/GCMBaseIntentService(10980): Releasing wakelock
01-01 07:46:34.796: D/dalvikvm(10980): GC_CONCURRENT freed 212K, 5% free 8010K/8376K, paused 1ms+3ms, total 20ms
01-01 07:46:34.976: D/dalvikvm(10980): GC_CONCURRENT freed 273K, 6% free 8159K/8592K, paused 3ms+3ms, total 24ms
01-01 07:46:35.026: V/GCMBroadcastReceiver(10980): onReceive: com.google.android.gcm.intent.RETRY
01-01 07:46:35.026: V/GCMBroadcastReceiver(10980): GCM IntentService class: com.toviehd.remake.GCMIntentService
01-01 07:46:35.026: V/GCMBaseIntentService(10980): Acquiring wakelock
01-01 07:46:35.036: V/GCMBaseIntentService(10980): Intent service name: GCMIntentService-725930664821-2
01-01 07:46:35.036: V/GCMRegistrar(10980): Registering app com.toviehd.remake of senders 725930664821
01-01 07:46:35.046: V/GCMBaseIntentService(10980): Releasing wakelock
01-01 07:46:35.146: V/GCMBroadcastReceiver(10980): onReceive: com.google.android.c2dm.intent.REGISTRATION
01-01 07:46:35.146: V/GCMBroadcastReceiver(10980): GCM IntentService class: com.toviehd.remake.GCMIntentService
01-01 07:46:35.146: V/GCMBaseIntentService(10980): Acquiring wakelock
01-01 07:46:35.176: V/GCMBaseIntentService(10980): Intent service name: GCMIntentService-725930664821-3
01-01 07:46:35.176: D/GCMBaseIntentService(10980): handleRegistration: registrationId = null, error = SERVICE_NOT_AVAILABLE, unregistered = null
01-01 07:46:35.176: D/GCMBaseIntentService(10980): Registration error: SERVICE_NOT_AVAILABLE
01-01 07:46:35.176: I/GCMIntentService(10980): Received recoverable error: SERVICE_NOT_AVAILABLE
01-01 07:46:35.186: D/GCMBaseIntentService(10980): Scheduling registration retry, backoff = 5157 (6000)
01-01 07:46:35.196: V/GCMBaseIntentService(10980): Releasing wakelock
01-01 07:46:35.996: D/dalvikvm(10980): GC_CONCURRENT freed 359K, 6% free 8220K/8736K, paused 3ms+4ms, total 22ms
01-01 07:46:36.116: D/dalvikvm(10980): GC_CONCURRENT freed 332K, 7% free 8332K/8868K, paused 3ms+3ms, total 24ms
01-01 07:46:40.346: V/GCMBroadcastReceiver(10980): onReceive: com.google.android.gcm.intent.RETRY
01-01 07:46:40.346: V/GCMBroadcastReceiver(10980): GCM IntentService class: com.toviehd.remake.GCMIntentService
01-01 07:46:40.346: V/GCMBaseIntentService(10980): Acquiring wakelock
01-01 07:46:40.356: V/GCMBaseIntentService(10980): Intent service name: GCMIntentService-725930664821-4
01-01 07:46:40.356: V/GCMRegistrar(10980): Registering app com.toviehd.remake of senders 725930664821
01-01 07:46:40.366: V/GCMBaseIntentService(10980): Releasing wakelock
01-01 07:46:40.466: V/GCMBroadcastReceiver(10980): onReceive: com.google.android.c2dm.intent.REGISTRATION
01-01 07:46:40.466: V/GCMBroadcastReceiver(10980): GCM IntentService class: com.toviehd.remake.GCMIntentService
01-01 07:46:40.466: V/GCMBaseIntentService(10980): Acquiring wakelock
01-01 07:46:40.476: V/GCMBaseIntentService(10980): Intent service name: GCMIntentService-725930664821-5
01-01 07:46:40.486: D/GCMBaseIntentService(10980): handleRegistration: registrationId = null, error = SERVICE_NOT_AVAILABLE, unregistered = null
01-01 07:46:40.486: D/GCMBaseIntentService(10980): Registration error: SERVICE_NOT_AVAILABLE
01-01 07:46:40.486: I/GCMIntentService(10980): Received recoverable error: SERVICE_NOT_AVAILABLE
01-01 07:46:40.486: D/GCMBaseIntentService(10980): Scheduling registration retry, backoff = 8885 (12000)
01-01 07:46:40.496: V/GCMBaseIntentService(10980): Releasing wakelock

I really do not know what i did to break this... Any help would be greatly appreciated

A: It had to with a Date Time setting. The Date on the tablet was in the past. I think GCM can't sync into the past or something. I reset the Time on the tablet and it works again!!


text:
Q: Is there any empirical relation between hardness and density? Inspired from: Why is diamond not the most dense substance?
The answer says that there is no general relation between hardness and density but we do have a connection between packing/bonding of atoms which ultimately determines the density of the substance.
However, hardness might have a slight correlation with density as most metals are hard and quite dense (except obvious exception: Mercury and Gold). From here:

hardness is roughly correlative with density. In addition, several pairs of polymorphs show the same trend: the more dense mineral is the harder mineral. This relationship makes some sense, in that closer packing of atoms would give greater density and would allow shorter bond lengths, which allows greater hardness.

Is there any empirical relationship/formula that can correlate various hardness constants of a material and density?

A: There is no such correlation function; here is why. I will restrict my answer to common engineering materials from which useful objects could be fashioned, where hardness would be a useful attribute. This excludes metals that catch fire spontaneously in air, since it would be injudicious to make cars and airplanes out of them.
Hardness is a measure of how difficult it is to indent a material. Indentive deformation requires slippage between adjacent layers of atoms which is facilitated by nondirectional bonding between those atoms- as in the case of metallic bonding. Resistance to indentation requires either the interatomic bonds be directional (as in the case of covalently bonded atoms, as for instance in ceramics) or that interatomic slippage mechanisms be pinned down or inhibited by the microstructure of that material (as for example in the case of the iron-carbon system).
This is an extremely complicated business where the hardness mechanisms in different materials have completely different root causes, making any sort of universal correlative "hardness function" essentially impossible- especially with respect to density, as density itself is not correlated to interatomic bonding mechanisms, alloying effects, microstructure, and ductility mechanisms.

A: Niels Nielsen is obviously an expert on condensed matter physics, but I find his answer a little unsatisfying because it merely asserts that there are many confounding variables. That doesn't mean that there is no correlation, or that we can't find an empirical rule relating hardness and density if we control for all the other variables.
If you look at the alkali metals, they all have BCC structure, and their density increases as you go down the periodic table (except for potassium). Their hardness decreases. That is, lithium is both the lowest in density and the hardest. So I think this establishes that such a relation does exist sometimes, if you control for lots of other variables. However, it seems unlikely that this relation is in any way universal. For instance, I think the trend for various types of wood would be that denser woods are harder.

A: So you gave a link, but there are two other relevant links in the same book: 2 and 3. All the links are for minerals, rather than for materials in general. It turns out that there is a better correlation between hardness and normalized density:

the observed density is divided by the average atomic weight of the
constituent atoms (and thus by formula weight divided by the number of
atoms in the formula


text:
Q: Passing command-line arguments to an emscripten-generated application When a C program is compiled with Emscripten, there is an HTML page generated that will display the results of the program.  I was wondering how you could pass command line arguments to the application.  For instance, with the original C program it's ./bfs 32 1.

A: I was able to pass command line arguments by adding a line to the generated .html file. Not sure if this is the correct solution but it worked.
There's a var Module declared. simply add the following line underneath: arguments: ['32', '1'],