text:
Q: DRF exception 'NotAuthenticated' raising 500 Internal Server Error in place of 401/403 I have a Django middleware where I verify a firebase IDToken.
from rest_framework import exceptions

def process_request(request):
    ...
    try:
        decoded_token = auth.verify_id_token(id_token)
        uid = decoded_token['uid']
    except:
        raise exceptions.NotAuthenticated(detail='not authenticated')

When the verification fails, auth raises an exception, which is caught by the try except block. But instead of raising 401/403 error, 500 Internal Server Error is raised by NotAuthenticated.
Is it because of some working of DRF Exceptions that this is happening ?

A: DRF handles sending status code 401 or 403 depending on the exception that got raised (NotAuthenticated, PermissionDenied) from your view.
But since you are working with a middleware, DRF is already out of the picture. Any exceptions that you raise which are not caught or handled by default will be considered as a server error, hence giving you a 500.
If you want your middleware to return a 401 or 403, you can use django's HttpResponse or HttpResponseForbidden like so:
from django.http.response import HttpResponse, HttpResponseForbidden

class MyMiddlware:
    def process_request(request):
        try:
            decoded_token = auth.verify_id_token(id_token)
            uid = decoded_token['uid']
        except Exception:
            return HttpResponseForbidden('not authenticated')
       # or return HttpResponse('not authenticated', status=401)


text:
Q: Chromium Browser (Linux Chrome) unable to display WebGL I am running Chrome (chromium-browser on Linux Mint).
Version 22.0.1229.94 Built on Ubuntu 12.10, running on LinuxMint 14 (161065)
I can't seem to get webGL enabled on it, it has worked previously.
chrome://gpu shows "WebGL has been disabled, either via about:flags or command line."
So I have checked chrome://version/gpu
Which shows: Command Line    /usr/lib/chromium-browser/chromium-browser --disable-new-tab-first-run --enable-user-scripts --flag-switches-begin --enable-accelerated-filters --disable-accelerated-2d-canvas --disable-gpu-vsync --disable-threaded-animation --disable-webgl --js-flags=--harmony --enable-nacl --enable-experimental-extension-apis --force-compositing-mode --ignore-gpu-blacklist --flag-switches-end
Which implies its getting disabled in the commandline. chrome://flags doesn't have webgl disabled.
/etc/chromium-browser/default only has CHROMIUM_FLAGS="--disable-new-tab-first-run --enable-user-scripts"
I have also tried running chrome direct via /usr/bin/chromium-browser
I can't see how this is getting disabled in the commandline. Is there something else I should change to enable it ?

A: Only way I've managed to fix it, was to do a rm -Rf /home/(username)/.config/chromium. Removing the Default directory inside it wasn't enough. WebGL is now enabled as default, without any further changes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Covert jQuery to javascript This is my code please covert my jQuery into javascript.
Convert in javascript
$(".wrapper td li>span").text(function () {
        return $(this).text().replace(".", "");
    });

A: Using querySelectorAll and textContent

document.querySelectorAll('span').forEach(function(el) {
  el.textContent = el.textContent.replace(/\./g, '')
});
1. abc

2. def

A: Finally I got a proper answer to convert jQuery to JavaScript with and issues on enterprise mode of internet explorer
var spans=document.body.querySelectorAll('.wrapper td li>span')
for (i = 0; i < spans.length; i++) {
spans[i].innerText = spans[i].innerText.replace(/\./g, '')
}


text:
Q: Php json_encode returning Unicode and latin characters After encoding by json_encode in PHP, I want pretty json and want to remove Unicode and latin character from the string or JSON. I want this for api, needed clean response.
Below is the unicoded json after json_encode.
E.g.
\u003Cb\u003EInformation about \u003Ci\u003E\u0027Sachin Tendulkar\u0027\u003C\/i\u003E\u003C\/b\u003E\u003Cbr\u003ESachin Ramesh Tendulkar \u003Ci\u003E (\/\u02ccs\u0259t\u0283\u026an t\u025bn\u02c8du\u02d0lk\u0259r\/; born 24 April 1973) \u003C\/i\u003E is a former Indian cricketer and captain, widely regarded to be one of the greatest cricketers of all time and by many as the greatest batsman of all time. He took up cricket at the age of eleven, made his Test debut on 15 November 1989 against Pakistan in Karachi at the age of sixteen, and went on to represent Mumbai domestically and India internationally for close to twenty-four years. He is the only player to have scored one hundred international centuries, the first batsman to score a double century in a One Day International, holds the record for most number of runs in both ODI and Test cricket, the only player to complete more than 30,000 runs in international cricket.\u003Cbr\u003E\u003Cbr\u003E\u003Cb\u003E\u003C\/b\u003E \u003Cbr\u003E\u003Cb\u003EPersonal information\u003C\/b\u003E \u003Cbr\u003E\u003Cb\u003EFull name:\u003C\/b\u003E Sachin Ramesh Tendulkar\u003Cbr\u003E\u003Cb\u003EBorn:\u003C\/b\u003E (1973-04-24) 24 April 1973 (age\u00a042) Mumbai, Maharashtra, India\u003Cbr\u003E\u003Cb\u003ENickname:\u003C\/b\u003E Tendlya, Bombay Bomber, Little Master, Master Blaster \u003Cbr\u003E\u003Cb\u003EHeight:\u003C\/b\u003E 5\u00a0ft 5\u00a0in (165\u00a0cm)\u003Cbr\u003E\u003Cb\u003EBatting style:\u003C\/b\u003E Right-handed\u003Cbr\u003E\u003Cb\u003EBowling style:\u003C\/b\u003E Right-arm medium, leg break, off break\u003Cbr\u003E\u003Cb\u003ERole:\u003C\/b\u003E Batsman\u003Cbr\u003E\u003Cb\u003E\u003C\/b\u003E \u003Cbr\u003E\u003Cb\u003EInternational information\u003C\/b\u003E \u003Cbr\u003E\u003Cb\u003ENational side:\u003C\/b\u003E India\u003Cbr\u003E\u003Cb\u003ETest debut (cap\u00a0187):\u003C\/b\u003E 15 November 1989\u00a0v\u00a0Pakistan\u003Cbr\u003E\u003Cb\u003ELast Test:\u003C\/b\u003E 14 November 2013\u00a0v\u00a0West Indies\u003Cbr\u003E\u003Cb\u003EODI debut (cap\u00a074):\u003C\/b\u003E 18 December 1989\u00a0v\u00a0Pakistan\u003Cbr\u003E\u003Cb\u003ELast ODI:\u003C\/b\u003E 18 March 2012\u00a0v\u00a0Pakistan\u003Cbr\u003E\u003Cb\u003EODI shirt no.:\u003C\/b\u003E 10\u003Cbr\u003E\u003Cb\u003EOnly T20I (cap\u00a011):\u003C\/b\u003E 1 December 2006\u00a0v\u00a0South Africa\u003Cbr\u003E\u003Cb\u003E\u003C\/b\u003E \u003Cbr\u003E\u003Cb\u003EDomestic team information\u003C\/b\u003E \u003Cbr\u003E\u003Cb\u003E1988:\u003C\/b\u003E Cricket Club of India\u003Cbr\u003E\u003Cb\u003E1988\u20132013:\u003C\/b\u003E Mumbai\u003Cbr\u003E\u003Cb\u003E1992:\u003C\/b\u003E Yorkshire\u003Cbr\u003E\u003Cb\u003E2008\u20132013:\u003C\/b\u003E Mumbai Indians\u003Cbr\u003E\u003Cb\u003E2014:\u003C\/b\u003E Marylebone Cricket Club\u003Cbr\u003E\u003Cb\u003E\u003C\/b\u003E \u003Cbr\u003E\u003Cb\u003ECareer statistics\u003C\/b\u003E \u003Cbr\u003E\u003Cb\u003ECompetition \/ Test \/ ODI \/ FC \/ LA Matches:\u003C\/b\u003E 200 \/ 463 \/ 310 \/ 551\u003Cbr\u003E\u003Cb\u003ERuns scored:\u003C\/b\u003E 15,921 \/ 18,426 \/ 25,396 \/ 21,999\u003Cbr\u003E\u003Cb\u003EBatting average:\u003C\/b\u003E 53.78 \/ 44.83 \/ 57.84 \/ 45.54\u003Cbr\u003E\u003Cb\u003E100s\/50s:\u003C\/b\u003E 51\/68 \/ 49\/96 \/ 81\/116 \/ 60\/114\u003Cbr\u003E\u003Cb\u003ETop score:\u003C\/b\u003E 248* \/ 200* \/ 248* \/ 200*\u003Cbr\u003E\u003Cb\u003EBalls bowled:\u003C\/b\u003E 4,240 \/ 8,054 \/ 7,605 \/ 10,230\u003Cbr\u003E\u003Cb\u003EWickets:\u003C\/b\u003E 46 \/ 154 \/ 71 \/ 201\u003Cbr\u003E\u003Cb\u003EBowling average:\u003C\/b\u003E 54.17 \/ 44.48 \/ 61.74 \/ 42.17\u003Cbr\u003E\u003Cb\u003E5 wickets in innings:\u003C\/b\u003E 0 \/ 2 \/ 0 \/ 2\u003Cbr\u003E\u003Cb\u003E10 wickets in match:\u003C\/b\u003E 0 \/ n\/a \/ 0 \/ n\/a\u003Cbr\u003E\u003Cb\u003EBest bowling:\u003C\/b\u003E 3\/10 \/ 5\/32 \/ 3\/10 \/ 5\/32\u003Cbr\u003E\u003Cb\u003ECatches\/stumpings:\u003C\/b\u003E 115\/\u2013 \/ 140\/\u2013 \/ 186\/\u2013 \/ 175\/\u2013"

Output should be:
Information about 'Sachin Tendulkar'
Sachin Ramesh Tendulkar (/ˌsətʃɪn tɛnˈduːlkər/; born 24 April 1973) is a former Indian cricketer and captain, widely regarded to be one of the greatest cricketers of all time and by many as the greatest batsman of all time. He took up cricket at the age of eleven, made his Test debut on 15 November 1989 against Pakistan in Karachi at the age of sixteen, and went on to represent Mumbai domestically and India internationally for close to twenty-four years. He is the only player to have scored one hundred international centuries, the first batsman to score a double century in a One Day International, holds the record for most number of runs in both ODI and Test cricket, the only player to complete more than 30,000 runs in international cricket.

Personal information
Full name: Sachin Ramesh Tendulkar
Born: (1973-04-24) 24 April 1973 (age 42) Mumbai, Maharashtra, India
Nickname: Tendlya, Bombay Bomber, Little Master, Master Blaster
Height: 5 ft 5 in (165 cm)
Batting style: Right-handed
Bowling style: Right-arm medium, leg break, off break
Role: Batsman

International information
National side: India
Test debut (cap 187): 15 November 1989 v Pakistan
Last Test: 14 November 2013 v West Indies
ODI debut (cap 74): 18 December 1989 v Pakistan
Last ODI: 18 March 2012 v Pakistan
ODI shirt no.: 10
Only T20I (cap 11): 1 December 2006 v South Africa

Domestic team information
1988: Cricket Club of India
1988–2013: Mumbai
1992: Yorkshire
2008–2013: Mumbai Indians
2014: Marylebone Cricket Club

Career statistics
Competition / Test / ODI / FC / LA Matches: 200 / 463 / 310 / 551
Runs scored: 15,921 / 18,426 / 25,396 / 21,999
Batting average: 53.78 / 44.83 / 57.84 / 45.54
100s/50s: 51/68 / 49/96 / 81/116 / 60/114
Top score: 248* / 200* / 248* / 200*
Balls bowled: 4,240 / 8,054 / 7,605 / 10,230
Wickets: 46 / 154 / 71 / 201
Bowling average: 54.17 / 44.48 / 61.74 / 42.17
5 wickets in innings: 0 / 2 / 0 / 2
10 wickets in match: 0 / n/a / 0 / n/a
Best bowling: 3/10 / 5/32 / 3/10 / 5/32
Catches/stumpings: 115/– / 140/– / 186/– / 175/–"

A: You have to translate the embedded unicode escape sequences back to their corresponding characters.
$data = "\u003Cb\u003EInformation about \u003Ci\u003E\u0027Sachin Tendulkar\u0027\u003C\/i\u003E\u003C\/b\u003E\u003Cbr\u003ESachin Ramesh Tendulkar \u003Ci\u003E (\/\u02ccs\u0259t\u0283\u026an t\u025bn\u02c8du\u02d0lk\u0259r\/; born 24 April 1973) \u003C\/i\u003E is a former Indian cricketer and captain, widely regarded to be one of the greatest cricketers of all time and by many as the greatest batsman of all time. He took up cricket at the age of eleven, made his Test debut on 15 November 1989 against Pakistan in Karachi at the age of sixteen, and went on to represent Mumbai domestically and India internationally for close to twenty-four years. He is the only player to have scored one hundred international centuries, the first batsman to score a double century in a One Day International, holds the record for most number of runs in both ODI and Test cricket, the only player to complete more than 30,000 runs in international cricket.\u003Cbr\u003E\u003Cbr\u003E\u003Cb\u003E\u003C\/b\u003E \u003Cbr\u003E\u003Cb\u003EPersonal information\u003C\/b\u003E \u003Cbr\u003E\u003Cb\u003EFull name:\u003C\/b\u003E Sachin Ramesh Tendulkar\u003Cbr\u003E\u003Cb\u003EBorn:\u003C\/b\u003E (1973-04-24) 24 April 1973 (age\u00a042) Mumbai, Maharashtra, India\u003Cbr\u003E\u003Cb\u003ENickname:\u003C\/b\u003E Tendlya, Bombay Bomber, Little Master, Master Blaster \u003Cbr\u003E\u003Cb\u003EHeight:\u003C\/b\u003E 5\u00a0ft 5\u00a0in (165\u00a0cm)\u003Cbr\u003E\u003Cb\u003EBatting style:\u003C\/b\u003E Right-handed\u003Cbr\u003E\u003Cb\u003EBowling style:\u003C\/b\u003E Right-arm medium, leg break, off break\u003Cbr\u003E\u003Cb\u003ERole:\u003C\/b\u003E Batsman\u003Cbr\u003E\u003Cb\u003E\u003C\/b\u003E \u003Cbr\u003E\u003Cb\u003EInternational information\u003C\/b\u003E \u003Cbr\u003E\u003Cb\u003ENational side:\u003C\/b\u003E India\u003Cbr\u003E\u003Cb\u003ETest debut (cap\u00a0187):\u003C\/b\u003E 15 November 1989\u00a0v\u00a0Pakistan\u003Cbr\u003E\u003Cb\u003ELast Test:\u003C\/b\u003E 14 November 2013\u00a0v\u00a0West Indies\u003Cbr\u003E\u003Cb\u003EODI debut (cap\u00a074):\u003C\/b\u003E 18 December 1989\u00a0v\u00a0Pakistan\u003Cbr\u003E\u003Cb\u003ELast ODI:\u003C\/b\u003E 18 March 2012\u00a0v\u00a0Pakistan\u003Cbr\u003E\u003Cb\u003EODI shirt no.:\u003C\/b\u003E 10\u003Cbr\u003E\u003Cb\u003EOnly T20I (cap\u00a011):\u003C\/b\u003E 1 December 2006\u00a0v\u00a0South Africa\u003Cbr\u003E\u003Cb\u003E\u003C\/b\u003E \u003Cbr\u003E\u003Cb\u003EDomestic team information\u003C\/b\u003E \u003Cbr\u003E\u003Cb\u003E1988:\u003C\/b\u003E Cricket Club of India\u003Cbr\u003E\u003Cb\u003E1988\u20132013:\u003C\/b\u003E Mumbai\u003Cbr\u003E\u003Cb\u003E1992:\u003C\/b\u003E Yorkshire\u003Cbr\u003E\u003Cb\u003E2008\u20132013:\u003C\/b\u003E Mumbai Indians\u003Cbr\u003E\u003Cb\u003E2014:\u003C\/b\u003E Marylebone Cricket Club\u003Cbr\u003E\u003Cb\u003E\u003C\/b\u003E \u003Cbr\u003E\u003Cb\u003ECareer statistics\u003C\/b\u003E \u003Cbr\u003E\u003Cb\u003ECompetition \/ Test \/ ODI \/ FC \/ LA Matches:\u003C\/b\u003E 200 \/ 463 \/ 310 \/ 551\u003Cbr\u003E\u003Cb\u003ERuns scored:\u003C\/b\u003E 15,921 \/ 18,426 \/ 25,396 \/ 21,999\u003Cbr\u003E\u003Cb\u003EBatting average:\u003C\/b\u003E 53.78 \/ 44.83 \/ 57.84 \/ 45.54\u003Cbr\u003E\u003Cb\u003E100s\/50s:\u003C\/b\u003E 51\/68 \/ 49\/96 \/ 81\/116 \/ 60\/114\u003Cbr\u003E\u003Cb\u003ETop score:\u003C\/b\u003E 248* \/ 200* \/ 248* \/ 200*\u003Cbr\u003E\u003Cb\u003EBalls bowled:\u003C\/b\u003E 4,240 \/ 8,054 \/ 7,605 \/ 10,230\u003Cbr\u003E\u003Cb\u003EWickets:\u003C\/b\u003E 46 \/ 154 \/ 71 \/ 201\u003Cbr\u003E\u003Cb\u003EBowling average:\u003C\/b\u003E 54.17 \/ 44.48 \/ 61.74 \/ 42.17\u003Cbr\u003E\u003Cb\u003E5 wickets in innings:\u003C\/b\u003E 0 \/ 2 \/ 0 \/ 2\u003Cbr\u003E\u003Cb\u003E10 wickets in match:\u003C\/b\u003E 0 \/ n\/a \/ 0 \/ n\/a\u003Cbr\u003E\u003Cb\u003EBest bowling:\u003C\/b\u003E 3\/10 \/ 5\/32 \/ 3\/10 \/ 5\/32\u003Cbr\u003E\u003Cb\u003ECatches\/stumpings:\u003C\/b\u003E 115\/\u2013 \/ 140\/\u2013 \/ 186\/\u2013 \/ 175\/\u2013";

$output = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) {
  return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
}, $data);

echo $output;

This will ouput a nicely formatted html version of your data.
To see the above code in actio visit php sandbox: http://sandbox.onlinephpfunctions.com/code/11db868791beff697efca2f538e3f35a7480764e


text:
Q: CSS IE6 case - inner div doesn't fit in 100% I have one big container (div) and one header div inside of it. It should fit the container in 100% of its width. And it does, everywhere instead of IE6 (it does even in IE7).
HTML code:

            Fdsfdsf:
            fdjsklf

            dfdsfdsf:
            vcxvcx

            FDSfjdsklf
            FDsjfkdsj

And CSS:
* {
    margin:                 0;
    padding:                0;
}
html {
    font:                   62.5% verdana, geneva, sans-serif;
    line-height:            1.125em;
    background-color:       silver;
    text-align:             center;
}
body {
    background-color:       white;
    width:                  79%;
    min-width:              1024px;
    max-width:              1920px;
    margin:                 3% auto;
    text-align:             left;
}
header {
    padding:                1em;
    border-bottom:          1px solid silver;
    text-align:             center;
}
header table {
    margin:                 0 auto;
}
header table tr {
    font-size:              0.8em;
}
header table .first-row {
    font-size:              1em;
}
header table th {
    font-weight:            normal;
    padding:                0 10px 0 0;
    text-align:             right;
}
header table .first-row th {
    font-weight:            bold;
}
header table .first-row td, header table .first-row th {
    border-bottom:          1px dotted silver;
}

Sorry for the length of the code. To check the header size I added bottom margin. It fits the left side of the outer container perfectly. And as the header doesn't have width set in the file it should fit the outer div also to the right. However there exist a gap on the right side. The end of the border is a little bit (about 20px) distanced from the right side, so it's too short.
Can you see the problem? I tried everything, the only thing that works is setting width: 100% in the header. However because of the padding it is too long in other browsers...

A: If adding 100% to the header works, you can use:
header {
    padding:                1em;
    border-bottom:          1px solid silver;
    text-align:             center;
    width:                  100%;
    box-sizing:             border-box; /* that's the magic */
}

Padding will be included in the total lenght in later browsers thanks to the power of box-sizing.

As they're already pointing out in the comments, unless you live in China you can probably ignore IE7 and below.


text:
Q: Is it possible to use an extender on a calculation? I have a custom binding I'm using to format percent numbers.
ko.bindingHandlers.textPercent = {
    //init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
    //    //init logic
    //},
    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var val = parseFloat(ko.utils.unwrapObservable(valueAccessor()));
        if ($.isNumeric(val)) {
            $(element).text((val * 100).toFixed(2))+"%";
        }
        else {
            $(element).text("#Error");
        }
    }
}

usage:

It works ok but I'd like to be able to use varying number of fixed digits, so I made an extender:
ko.extenders.percent = function (target, precision) {
    var result = ko.computed({
        read: function () {
            return (target()*100).toFixed(precision)+"%";
        },
        write: function (newValue) {
            target(parseFloat(newValue) / 100);
        }
    });
    return result;
};

usage:

Problem is it doesn't work with the inline calculation.
Suggestions?
http://jsfiddle.net/eRapL/4/

A: You must wrap your expression with ko.observable()
Example:
text extend percent:

Look at: http://jsfiddle.net/c7Qx7/1/


text:
Q: Equalizer bar for muted audio I am trying to create an audio equalizer through the guidance of this tutorial.
This works fine until you mute the audio through the controls(as shown in the image). Muting it also stops the equalizer bars.
How would I go about implementing the equalizer bars so that the bars don't stop even when the audio is muted?

let canvas,
  ctx,
  source,
  context,
  analyser,
  fbc_array,
  bar_count,
  bar_pos,
  bar_width,
  bar_height;

let audio = new Audio();

audio.src = "test.mp3";
audio.controls = true; // Show audio controls so we can pause and play at will
audio.loop = true;
audio.autoplay = true;

window.addEventListener(
  "load", // only executes after loading page fully
  function() {
    document.getElementById("audio").appendChild(audio); // putting the audio element inside the another HTML element

    audio.onplay = function() {
      if (typeof(context) === "undefined") {
        context = new AudioContext();
        analyser = context.createAnalyser();
        canvas = document.getElementById("canvas");
        ctx = canvas.getContext("2d"); // returns a drawing context
        source = context.createMediaElementSource(audio); // creates an audio object which can be manipulated

        canvas.width = window.innerWidth * 0.80;
        canvas.height = window.innerHeight * 0.60;

        source.connect(analyser);
        analyser.connect(context.destination); // connect the analyzer and the context(which is used to draw)
      }

      FrameLooper(); // will handle all the animation and output
    };
  },
  false
);

function FrameLooper() {
  window.requestAnimationFrame(FrameLooper);

  fbc_array = new Uint8Array(analyser.frequencyBinCount); // array for containing frequencies
  bar_count = window.innerWidth / 2;

  analyser.getByteFrequencyData(fbc_array);

  ctx.clearRect(0, 0, canvas.width, canvas.height); // clear old visual data
  ctx.fillStyle = "#ffffff"; // fill it with white

  /* For repainting */
  for (let i = 0; i < bar_count; i++) {
    bar_pos = i;
    bar_width = 1;
    bar_height = -(fbc_array[i] / 2);

    ctx.fillRect(bar_pos, canvas.height, bar_width, bar_height);
  }
}
body {
  background: black;
  padding: 0px;
  margin: 0px;
}

div#player {
  width: 80vw;
  height: 60vh;
  background: black;
  margin: 20vh auto 0px auto;
  display: block;
}
<!DOCTYPE html>

  <link rel="stylesheet" href="styles.css">
  <title>Equalizer bar</title>

    <canvas id="canvas"></canvas>


text:
Q: Hit detection algorithm not working, unsure why not. (Javascript/Processing.js) I'm new to programming games (and programming in general). I have previously made a "Flappy Bird" clone and a few others and I used the hit detection algorithm as provided by the Mozilla Developer Network here.
I am now trying to recreate "Pong" but, for whatever reason, its not working in my current code and I'm completely clueless as to why not. I want the ball to hit the "paddle" and then go back the way it came, but right now it ghosts through the paddle.
I'm using the Processing.js library but it should be apparent to anyone (familiar with it or not) what my code is trying to achieve. The draw() function gets called frequently by processing.js.
The code in action (but not working as expected) can be found here
var PADDLE_WIDTH = 10;
var PADDLE_HEIGHT = 75;
var PADDLE_X = 10;

var Player = function(y) {
    this.x = PADDLE_X;
    this.y = mouseY;
    this.score = 0;
    this.width = PADDLE_WIDTH;
    this.height = PADDLE_HEIGHT;
};

Player.prototype.drawPlayer = function() {
    rect(10,mouseY, this.width, this.height);

};

var Ball = function(x,y) {
    this.x = x;
    this.y = y;
    this.speed = 4;
    this.width = 10;
    this.height = 10;
};

Ball.prototype.drawBall = function() {
    rect(this.x, this.y, this.width, this.height);

};

Ball.prototype.onHit = function() {
    if(this.y <= 0 || this.y >= height) {
        this.speed *= -1;
    } else if(this.x <= 0 || this.x >= width){
        this.speed *= -1;
        // HIT DETECTION UNDERNEATH
    } else if (player.x < this.x + this.width &&
   player.x + player.width > this.x &&
   player.y < this.y + this.height &&
   player.height + player.y > this.y){
       this.speed *= -1;
   }

};

var player = new Player();
var ball = new Ball(width/2, height/2);

draw = function() {

    background(0);
    fill(250, 250, 250);
    ball.x -= ball.speed;

    player.drawPlayer();
    ball.drawBall();
    ball.onHit();

};

A: In the drawPlayer method you draw player in the (10, mouseY) point, but never update y property of player. It always remains equal to 0. I would recommend you to add update method, which will change player's state and change draw method to render player purely on its state. Something like
Player.prototype.updatePlayer = function() {
    this.y = mouseY;
};

Player.prototype.drawPlayer = function() {
    rect(this.x , this.y, this.width, this.height);
};

draw = function() {
    // ...
    player.updatePlayer();
    player.drawPlayer();
    ball.drawBall();
    // ...
};

A: In drawPlayer you can add the line this.y = mouseY
Player.prototype.drawPlayer = function() {
    rect(10,mouseY, this.width, this.height);
    this.y = mouseY;
};

Fiddle: http://jsfiddle.net/z0acb8gy/


text:
Q: Determining CDF and PDF of a function on x I am trying to learn probability and have gotten to the points of transformations. I am now quite confused. While I understand what CDF and PDF are, I have no idea why changing the value of X to a function on X should drastically alter these, or how I should go about determining them. This is the problem statement I'm trying to figure out:
X is a continuous random variable.  Find the CDF and PDF of $Y=X^2$ in the expression of CDF FX of X and PDF fX of X.
How do I proceed here, especially since no actual function is given and no distribution specified?

A: Here's an extreme example of why composing a function with a random variable alters the distribution.
Consider the uniform random variable $X\sim U\{-1,1\}$.
That is, $\mathbb{P}(X=-1)=\mathbb{P}(X=1)=1/2$.
Now, let $f$ be a function which maps everything to zero.
That is, $f(x)=0$.
Note that $\mathbb{P}(f(X)=0)=1$, yielding a point mass distribution.

If $X$ is a continuous random variable,
$$
\Phi_{X}(x)\equiv\mathbb{P}(X\leq x)=\int_{-\infty}^{\infty}\varphi_{X}(x)dx
$$
where $\Phi_{X}$ and $\varphi_{X}$ are the CDF and PDF of $X$.
The CDF of $Y\equiv X^{2}$ is given by
\begin{multline*}
\Phi_{Y}(y)\equiv\mathbb{P}(Y\leq y)=\mathbb{P}(X^{2}\leq y)
=\mathbb{P}(\left|X\right|\leq\sqrt{y})
=\mathbb{P}(-\sqrt{y}\leq X\leq\sqrt{y})\\
=\mathbb{P}(X\leq\sqrt{y})-\mathbb{P}(X\leq-\sqrt{y})
=\Phi_{X}(\sqrt{y})-\Phi_{X}(-\sqrt{y})
\end{multline*}
To get the PDF from the CDF, just differentiate:
$$
\varphi_{Y}(y)=\Phi_{Y}^{\prime}(y)=\frac{1}{2\sqrt{y}}\left(\varphi_{X}(\sqrt{y})+\varphi_{X}(-\sqrt{y})\right).
$$
Since $\varphi_X$ was not specified, this is as far as you can simplify.


text:
Q: finding $\mathcal{F}$ or classes in $\mathcal{F}$ Let $\mathcal{F}$ be the set of functions (sequences, if you like) $f:\mathbb{Z}_{\geq0}\rightarrow\mathbb{Z}$ such that
(a) $f(0)$ is odd, and
(b) $2^{n+1}\,\vert\,(\Delta^nf)(x)$ for all $n\geq1$ and all $x\in\mathbb{Z}_{\geq0}$. Here
$$(\Delta f)(x):=(Sf)(x)-f(x):=f(x+1)-f(x).$$
Examples. The Fibonacci sequence $F(x)=F_x\not\in\mathcal{F}$ but it is a cute exercise $F(6x+1)\in\mathcal{F}$. The polynomial $f(x)=(2x+1)^2\in\mathcal{F}$.
For the motivation on this subject and some sequences $f$ belonging to $\mathcal{F}$, see this paper.

Questions.
(1) Which class/family of polynomials are in $\mathcal{F}$?
(2) Which family of familiar or combinatorial sequences are in $\mathcal{F}$?
(3) Anything else?

Your suggested class doesn't have to be the most general.
We will just keep a catalogue here.

A: I think I have an answer for (1).
Let $P(x)=\sum_k\alpha_kx^k$ be a polynomial. Then, we can express $P$ in the binomial basis $\{\binom{x}m\}_m$ in the manner
$$P(x)=\sum_m\beta_m\binom{x}m.$$
Now, $P(x)$ is integer-valued iff each $\beta_m\in\mathbb{Z}$. The criterion (1) and (2) enforce the conditions:
$$\text{$\beta_0$ is odd} \qquad \text{and} \qquad 2^{m+1}\,\vert\, \beta_m.$$
To complete the argument, it suffices to observe that $\beta_m=(\Delta^mP)(0)$ and for Condition (b) use
$$\Delta\binom{x}m=\binom{x}{m-1}.$$
Therefore, we know exactly which polynomials belong to $\mathcal{F}$. Let's denote this collection by $\mathcal{F}_P\subset\mathcal{F}$.


text:
Q: Keep an html browser full screen on mac I'm getting frustratingly stuck on a quite simple problem. I run an html slideshow. I need it to be full screen (no toolbar, no topbar) at every moment.
In the background, a lot is getting done however. I got an app (Canon EOS Utility) that is regularly activated by applescript. Here is my problem : activating this program automatically quits the full screen mode (or presentation mode) in the browser. How can I stop this?
The full screen mode seems to be part of OS X (Mission Control) - it behaves the same way with every browser.
I tried Afloat 2.0 but this doesn't hide the toolbar and topbar.
Have a clue to solve this?
BTW I'm using Max/MSP for background process, if anything can be done with that.
Thanks !
M

A: Finally, I've solved my problem by not solving it !
The "EOS Utility" software, which was triggered by applescript, needed to be "activated" to work. That caused fullscreen to quit.
I've found this jem : gphoto2 (http://photolifetoys.blogspot.ca/2012/08/control-your-camera-with-gphoto2-via.html)
It can be used to tether a whole bunch of cameras via command lines. This, of course, doesn't change the OS display.
So the full screen stays… !
This is good enough for now, for me… Just replying for the record, if it can help anyone !


text:
Q: What's the difference between "menage" and "family"? I was wondering if these two words "menage" and "family" had any differences in use.
According to OED, "menage" means "the members of a household", but their example sentences make "menage" and "family" appear interchangeable. For example, "You'll find your ... square tables, some even set for three for ménages of the same size...".
Are they truly interchangeable or are they differently nuanced?

A: There certainly is a difference... ménage would sound and feel antiquated or (overly) formal to most people.
Furthermore, there is a subtle difference in meaning. A family implies that the members are a group of people related by blood, and they can still be a family if they don't share a house. A ménage refers rather to a household, which in many cases would be a family, but it doesn't have to be the same. A priest living with his housekeeper (once a common arrangement!) could be considered a ménage of two, but it's not his family.
Similarly, a couple of students that share accommodations could be considered a ménage, but not a family.
And finally, ménage is used in the expression ménage à trois, which can lead to unwanted connotations when you mean a household!


text:
Q: Increasing distance between Earth and Moon I have a problem where a planet's rate of rotation is decreasing due to tidal effects of the moon. I know that the angular momentum of the system will be conserved. So, in order to conserve that the moon will recede away from the planet.
$$ L = mvr = m\omega r^2.$$
I'm not sure how to convert/translate this loss in angular momentum of the planet to the rate of recession of the moon.

A: Whether the Earth slows down or speeds up isn't something you can just decide from basic logic. It is a mathematical question whose answer depends on the relative phase relationship of the driving force (the moon) and he driven object (the tide). If the frequency of the driving force is less than the natural frequency of the tides, the tidal bulge will lag and the effect will be to speed up the earth and pull the moon down into a lower orbit. (The lower orbit is actually faster, but the angular momentum goes down because the radius changes more than the velocity.) If the frequency of the driving force is greater than the natural frequency of the tides, the bulge will lead the moon and the effect will be to slow the earth down and drive the moon into a higher orbit. (The higher orbit will actually be slower, but the anuglar momentum goes up because of the radius.)
It is an experimental fact that the driving frequency of the moon (one rotation every 24 hours) is greater than the natural frequency of the tidal bulge (circe the earth in 2 or 3 days, or a wave velocity of several hundred mph). So the earth slows down and the moon gets farther away.
I analyze this in a series of blog posts starting here: How the Tides Slow Down The Moon

A: The key is, as you indicate, in the conservation of angular momentum.
First comment on the cause : the tides
the effect of tides (flows) causes a slowdown in the angular velocity of the Earth, that is to say, the Earth slows down by the tidal effects caused by the Moon ( the sun also causes but is much lower).
What happens? Let us consider the isolated system Earth-Moon

*

*The total angular momentum must be conserved.

*The angular velocity of the Earth decreases because of the effects of the tide, the period of rotation is increasing. That is to say, the angular momentum of the Earth decreases

*As a result, if the angular momentum of the Earth decreases, the angular momentum of the Moon has to increase to the total angular momentum is maintained, is the only option.

*Therefore, to increase the angular momentum of the moon, the orbit of the moon becomes higher, so, gradually, moon's orbit becomes larger= more eccentric = the distance increases with the Earth

Let me make you an approach.
Of the dynamics of the circular movement
$$  G \frac {M_e M_m}{d^2} = M_m w^2 d $$   where $w = \sqrt {G \frac{M_e}{d^3}}$
$M_e$ and $M_m$ are the mass of the Earth and Moon respectively.
Now, we consider the isolated system Earth-Moon, the total momentum $L$ must be conserved over the time, this is :
$$ L = L_e + L_m = L'_e + L'_m = L' $$
The moment of inertia of a sphere of mass m and radius R with respect to the axis of rotation that passes through its center is $2M_eR^2/5$ (obviously, for simplicity, we are considering that the earth is spherical), and the moment of inertia of a particle of mass m that is far d of the axis of rotation is $M_m d^2$
Another consideration, mass of the Earth is considerably greater than the mass of the Moon and that the distance between its centers is much greater than any of its rays, so we can consider the moon as a particle of mass $M_m = 8.99\times 10^{22} kg $ which describes a circular orbit of radius d around the Earth.
The last consideration, also for simplicity, we've considered the axis of rotation of the Earth perpendicular to the plane of the Moon's orbit.
Also, you know about the Earth : $M_e = 5.98 \times 10^{24} kg $ , $R_e = 6.37 \times 10^6 m$
After all these considerations and introduction, we have that :
$$ \frac 25 M_e R^2 \Omega + M_m d^2 w = \frac 25 M_e R^2 \Omega_1 + M_m d_1^2 w_1^2 $$
I have to leave now, anyway hope you understand my explanation. If you need, I can continue with the derivation but I think you'll be able to do that.


text:
Q: Can FluentMigrator output one SQL file per migration? I want to know if I can have one SQL file per migration.
We are trying to use it with RoundhousE, but RoundhousE will stop if a SQL file already ran is ever altered.
Any ideas?

A: I solved this issue by forking FM and adding a DirectoryAnnouncer that then outputs one file per migration (named after the migration #).


text:
Q: Program checking to see if a users number is stored in the array in c++ I wrote this code to check to see whether or not a positive integer the user enters is stored in the array of the program, and then displays the result to the user. I am very new to C++ and am having some difficulties. Can someone please help me.
#include <iostream> //needed for access to cin and cout

using namespace std;

int main (void)
{
    int LS (int [], int);

    int ll=10;
    int l[ll]= {30, 2, 13, 9, 25, 17, 89, 32, 73, 69};
    int i=0;
    int it=0;
    int result=0;

    cout << " Welcome User, this program allows you to enter a number"<<endl
         << " and see if it is stored in our database."<<endl;

    cout << " Please enter number :  ";
    cin >> it;

    result = LS (l[ll], it);

    if (result==0)
    {
        cout << " The number" << it << " you entered was not found in our database. " << endl;
    }

    if (result==1)
    {
        cout << " The number" << it << " you entered has been found in our database. " << endl;
    }

    return 0;
}

int LS (int l[int ll], int it) //function to search for "it"
{

    int i=0, f=0;

    if (l[i]==it)
    {
        f=1;
        i++;
    }

    if (i==ll)
    {
        return f;
    }
}

A: #include <iostream> //needed for access to cin and cout

using namespace std;

int main (void)
{
int LS (int [], int);
int ll=10;
int l[ll]= {30, 2, 13, 9, 25, 17, 89, 32, 73, 69};
int i=0;
int it=0;
int result=0;

cout << " Welcome User, this program allows you to enter a number"<<endl
  << " and see if it is stored in our database."<<endl;

cout << " Please enter number :  ";
cin >> it;

result = LS (l[ll], it);
if (result==0){
 cout << " The number" << it << " you entered was not found in our database. " << endl;
}

if (result==1)
{
 cout << " The number" << it << " you entered has been found in our database. " << endl;
}

 return 0;
}

int LS (int l[int ll], int it) //function to search for "it"{
  int i=0;
  while (l[i]!=it and i<11){
     i++;
  }
if (i==ll)
   return 0;
return 1;
}

This code works because if an element is found then while loop will break and hence i value will be less than 11

A: You are missing a loop to iterate through all the values in the array
#include <iostream> //needed for access to cin and cout

using namespace std;

int main (void)
{
 int LS (int [], int);

 int ll=10;
 int l[ll]= {30, 2, 13, 9, 25, 17, 89, 32, 73, 69};
 int i=0;
 int it=0;
 int result=0;

 cout << " Welcome User, this program allows you to enter a number"<<endl<< " and see if it is stored in our database."<<endl;

 cout << " Please enter number :  ";
 cin >> it;

 result = LS (l, it);

 if (result==0)
 {
   cout << " The number" << it << " you entered was not found in our database. " << endl;
 }

 if (result==1)
 {
  cout << " The number" << it << " you entered has been found in our database. " << endl;
 }

  return 0;
}

int LS (int l[10], int it) //function to search for "it"
{

 int i=0, f=0;
 for(i=0;i<10;++i) {
 if (l[i]==it)
 {
   f=1;
   return f;
 }
  return f;
 }
}

A: Many changes to have a better code:

*

*Use boolean to return true/false statements

*Use more explicit function/variable names

*Do your for loop correctly!

*...
#define ARRAY_SIZE 10
bool findItem( int item, int* items, size_t count )
{
    for ( size_t i = 0; i != count; ++i )
    {
        if ( items[i] == item )
            return true;
    }
    return false;
}

int main (void)
{
    int l[ARRAY_SIZE] = {30, 2, 13, 9, 25, 17, 89, 32, 73, 69};

    cout << " Welcome User, this program allows you to enter a number"<<endl<< " and see if it is stored in our database."<<endl;

    cout << " Please enter number :  ";
    int toFind;
    cin >> toFind;

    if ( !findItem( toFind, l, ARRAY_SIZE ) )
    {
        cout << " The number" << toFind << " you entered was not found in our database. " << endl;
    }
    else
    {
        cout << " The number" << toFind << " you entered has been found in our database. " << endl;
    }

    return 0;
}

A: I found some issues here.
1) We need to provide the function declarations outside of all the functions. So int LS(int [], int) should be outside of main. Function decleration is suggesting the C++ compiler that function LS will take 2 arguments a) an integer array b) one integer
2) Function can not determine number of elements in the array automatically. So we need to send the number of elements in the array to function LS. So function declaration should be changed as below.
int LS (int [], int, int);

2nd parameter is number of elements in the array.
3) Only 10 elements are placed inside the array. So no need to keep the array size as 11 in main()
 int l[ll]= {30, 2, 13, 9, 25, 17, 89, 32, 73, 69};

4) Finally your function is missing the logic of looping through the array.
So Find below program which is modified version of yours.
#include <iostream> //needed for access to cin and cout

using namespace std;

int LS(int [], int, int);

int main (void)
{
    int ll=10;
    int l[l0]= {30, 2, 13, 9, 25, 17, 89, 32, 73, 69};
    int i=0;
    int it=0;
    int result=0;

    cout << " Welcome User, this program allows you to enter a number"<<endl
    << " and see if it is stored in our database."<<endl;

    cout << " Please enter number :  ";
    cin >> it;

    result = LS (l, 10, it);

    if (result==0)
    {
        cout << " The number" << it << " you entered was not found in our database. " << endl;
    }

    if (result==1)
    {
        cout << " The number" << it << " you entered has been found in our database. " << endl;
    }

    return 0;
}

int LS(int L[], int n, int it)
{
    for(int i = 0; i < n; i++)
    {
        if (l[i]==it)
        {
            return 1;
        }
    }

    return 0;
}

A: First of all, you should know that you extremely complicate your life. Just use std::find, which works perfectly fine with arrays, and be done with it! Here's how you would write the program using normal standard C++11:
#include <iostream> // for std::cout and std::cin
#include <algorithm> // for std::find
#include <iterator> // for std::begin and std::end

int main()
{
    int const numbers[] = {30, 2, 13, 9, 25, 17, 89, 32, 73, 69 };

    std::cout << " Welcome User, this program allows you to enter a number\n"
                 " and see if it is stored in our database.\n";

    std::cout << " Please enter number :  ";
    int input;
    std::cin >> input;

    if (std::cin)
    {
        if (std::find(std::begin(numbers), std::end(numbers), input) == std::end(numbers))
        {
            std::cout << " The number " << input << " you entered was not found in our database.\n";
        }
        else
        {
            std::cout << " The number " << input << " you entered has been found in our database.\n";
        }
    }
    else
    {
        // invalid input...
    }
}

(In fact, the only C++11-specific feature used here is std::begin / std::end.)

Yet you are probably interested in knowing what went wrong with your original code.
The first problem with it is that it usually won't even compile.
 int ll=10;
 int l[ll]= {30, 2, 13, 9, 25, 17, 89, 32, 73, 69};

This is using a GCC-specific compiler extension. In portable standard C++, the array size must be known at compile time, and ll is only known at run time.
Fortunately, you don't even have to specify the size anyway. This is one of the few good things about raw arrays in C++:
 int l[] = {30, 2, 13, 9, 25, 17, 89, 32, 73, 69};

The next problem:
 int LS (int l[int ll], int it) //function to search for "it"

Proprietary compiler extensions aside, this should probably be:
 int LS (int l[], int size, int it)

When you pass an array to a function like this, any size information is lost, so an extra size parameter is needed. Calling the function then looks like this:
result = LS (l, sizeof(l) / sizeof(int), it);

And finally, in your LS function, you are not iterating over your array but just compare one single element. Here is a possible modification of your original code:
int LS (int l[], int size, int it)
{
  int i=0, f=0;

  while (i < size)
  {
    if (l[i]==it)
    {
      f=1;
    }
    i++;
  }

  return f;
}

It still has quite a few problems, but it's a start.

Moral of the story:

*

*Use functions from <algorithm>. They also work with arrays.

*Use std::vector and std::array whenever you can. You should almost never see raw arrays in modern C++ code.

*One of the few good features of raw arrays is the fact that the compiler counts the elements automatically at the point of declaration.


text:
Q: 2D games programming coordinates in C I'm making my way through some ncurses tutorials as I want to improve some of my C programming skills. I'm at a point where the tutorial is emulating a simple tennis game.
What confuses me is this:
* think of posX as relating to rows, the bottom of the screen will be at
maximum Y value, so subtract 2, to set the racket near the bottom */
p.posX = SCREEN_HEIGHT - 2;

/* think of posY as relating to a column, the middle of the screen will be
at the middle of the screen_width, divided by 2, to set racket at center */
p.posY = SCREEN_WIDTH / 2;

and say, the racket is moved left by the user:
void moveRacketLeft() {
if (p.posY - 2 > 0) { // ensure racket is still on screen
    mvprintw(p.posX, p.posY-1, "   ");  // if true, it will print an empty space, deleting the racket
    p.posY --;    // remember to decrement, as we are going to the left
    }

}
What confuses me about this, is that the X and Y positions have seem to be reversed and I don't know how to logically 'get it'.
Is there some kind of grey area between conventional coordinates in C programming and the use of the ncurses library? Or is the tutorial making a mistake?
Many thanks

A: The x and y coordinates in curses are as you expect: x is the horizontal coordinate, corresponding to columns. y is the vertical coordinate, cooresponding to rows.
But in curses, these coordinates are usually given in the order y, x. For example, the prototype to mfprintw mentioned in your code snippet is:
int mvprintw(int y, int x, const char *fmt, ...);

And there are even functions (or macros. rather) that have yx in their name, e.g. getyx.
I imagine that this notation was chosen, because it reflects the way that two-dimensional arrays are addressed in C: array[row][col].


text:
Q: Insert a variable in the middle of the string but keep the single quotes (C#) How to insert a variable to a piece of string with keeping single quotes as a part of the string.
CODE:
var textMessage = "myText"; //local variable storing text to be injected to string

this is what I have tried but it did't work:
"//div[contains(@id,'msgError') and contains(text(),'+textMessage+')]" //string where textMessage should be insterted

OUTPUT should be like this:
"//div[contains(@id,'msgError') and contains(text(),'myText')]" //Output

A: You can use string.Format like this:
string.Format("//div[contains(@id,'msgError') and contains(text(),'{0}')]", textMessage)

you can specify more parameters to put in string.

A: "//div[contains(@id,'msgError') and contains(text(),'+textMessage+')]"

That's a single string literal in C# syntax, everything except special characters will be in the string as is. In order for textMessage to evaluate to its value, you have to add it as an expression:
"//div[contains(@id,'msgError') and contains(text(),'" + textMessage + "')]"

Now the result will be the concatenation of the first string literal, plus textMessage variable's value, plus the last string literal.
As a sidenote, concatenating strings like this is usually frowned upon, it's better to use string.Format.

A: You're close.  The textMessage has to be outside the string:
"//div[contains(@id,'msgError') and contains(text(),'" + textMessage + "')]"

In your solution, textMessage and the two plus characters are just part of the literal string.

A: In addition to the string.Format(string, object...) solutions already mentioned I just want to point out that in C# 6.0 you can use the new string interpolation feature:
const string queenType = "lizard";
var message = $"I am the {queenType} queen!";

It works similarly to string.Format(string, object...), but I think it's a bit more readable.

A: For basic string templating in C#, string.Format is your friend.
var textMessage = "myText";
var template = "//div[contains(@id,'msgError') and contains(text(),'{0}')]";
var output = string.Format(template, textMessage);

A: i whould use the string.Format where you can use placeholders "{x}" in the string. these placeholders you can add as meny as you need to the string provided that you swift the x with the matching index in the paramiters after.
in your example
war textmessage = "myText";
string.Format("This is formated to end with {0}",textmessage);

this whould write This is formated to end with myText.
you can build on this by adding more parameters.
var name1 = "Emil";
var name2 = "Rachel";
string.Format("{1} and {0} are friends",name1,name2);

the index as you se does not have to be 0 1 2 but can be shifted around to suit your needs.
hope this helps :)


text:
Q: First time with apport Today, when I turned on the laptop to update Ubuntu, I got an error "System program problem detected" after logging in. I thought it was an bug, so I updated the computer and restarted it, but the the error continued to appear.
Them, it asked for my password and I saw that the program was called "apport" (I think). After typing my password, I saw that the error was about the linux gnu time indicator, so I sent the file to Canonical (I think).
In the folder /var/crash, there is this file:
_usr_lib_x86_64-linux-gnu_indicator-datetime_indicator-datetime-service.112

(there are 3 different extensions for the same file, .crash, .upload, uploaded).
After that, I restarted my computer and the error stopped appearing,
So, since it is my first time with the program, I would like to know if this program is actually legit, and if my computer is alright.
EDIT: I would like to know too if it's possible to see the error window again, to see if I'm correct about the error being from apport.
Thank you guys for helping me, also sorry if there was another post like this.

A: Apport is the tool that Ubuntu uses to report such errors; think of it like Ubuntu's version of Windows' error reporting. Yes, it is perfectly legit. As far as the problem re-occuring -- maybe, maybe not. Hard to say really. It may simply have been a one-time incident.


text:
Q: SQL Server: Combine multiple rows into one with no overlap but new columns I have a Table "Details" like this:
    ID         |        BookID         |        Genre
    _____________________________________________________
    1          |         12            |         AB
    1          |         05            |         AC
    2          |         12            |         AB
    2          |         08            |         BB

Is there any way to combine the rows in this format:
    ID  | BookID1 | Genre1  | BookID2 | Genre2
    _____________________________________________________
    1   | 12      | AB      | 05      |   AC
    2   | 12      | AB      | 08      |   BB

I need to do it in such a format to add the respective columns to a stored procedure.
I generally would love to include some code or attempts but I'm clueless at this moment.
Not a Duplicate of the below:
T-SQL dynamic pivot
1st difference im not using tsql
2nd difference is the structure of the table which can't be applied to mine.
My values are not going to be column headers instead they are gonna generate new columns such as :
    ID  | BookID1 | Genre1  | BookID2 | Genre2  | BookID3 | Genre3  | BookID4 | Genre4
    1   | 05      | Horror  | 12      | Horror  | 03      | Drama   |         |
    2   | 05      | Horror  | 15      | Advent  | 03      | Drama   | 112     | RomCom

3rd Im not able to grasp the structure since I have zero knowledge of pivot tables

A: Try a dynamic sql query
CREATE TABLE #BookGenreMapping
(
   Id int,
   BookId int,
   Genre varchar(20)
)

INSERT INTO #BookGenreMapping VALUES (1,12,'AB'),(1,05,'AC'),(2,12,'AB'),(2,08,'BC'),(2,09,'BCD')
DECLARE @HeaderAll nvarchar(max)
DECLARE @ColumnPivotBookId nvarchar(max)
DECLARE @ColumnPivotGenre nvarchar(max)

;WITH temp AS
(
   SELECT *,
   CONCAT('BookID' ,row_number() OVER(PARTITION BY bgm.Id ORDER BY bgm.BookId)) AS BookGroupId,
   CONCAT('BookGroupGenre' ,row_number() OVER(PARTITION BY bgm.Id ORDER BY bgm.BookId)) AS BookGroupGenre
   FROM #BookGenreMapping bgm
),
temp1 AS
(
   SELECT DISTINCT t.BookGroupId, t.BookGroupGenre FROM temp t
)
SELECT @HeaderAll = STUFF((SELECT CONCAT(',',t.BookGroupId, ',', t.BookGroupGenre) FROM temp1 t FOR XML PATH('')), 1,1,''),
     @ColumnPivotBookId =  STUFF((SELECT CONCAT(',',t.BookGroupId) FROM temp1 t FOR XML PATH('')), 1,1,''),
     @ColumnPivotGenre =  STUFF((SELECT CONCAT(',', t.BookGroupGenre) FROM temp1 t FOR XML PATH('')), 1,1,'')

--SELECT @HeaderAll, @ColumnPivotBookId, @ColumnPivotGenre

DECLARE @query nvarchar(max) = CONCAT(
      ';WITH temp AS
      (
         SELECT *,
         CONCAT(''','BookID',''' ,row_number() OVER(PARTITION BY bgm.Id ORDER BY bgm.BookId)) AS BookGroupId,
         CONCAT(''','BookGroupGenre',''' ,row_number() OVER(PARTITION BY bgm.Id ORDER BY bgm.BookId)) AS BookGroupGenre
         FROM #BookGenreMapping bgm
      )
      SELECT pt1.Id, ',@HeaderAll,' FROM
      (
          SELECT Id, ',@ColumnPivotBookId,' FROM
          (
            SELECT t.Id, t.BookId, t.BookGroupId FROM temp t
          ) src
          PIVOT
          (
            MIN(BookId) FOR BookGroupId IN (',@ColumnPivotBookId,')
          ) pvt
       ) pt1
       INNER JOIN
       (
          SELECT Id, ',@ColumnPivotGenre,' FROM
          (
            SELECT t.Id, t.Genre, t.BookGroupGenre FROM temp t
          ) src
          PIVOT
          (
            MIN(Genre) FOR BookGroupGenre IN (',@ColumnPivotGenre,')
          ) pvt
       ) pt2 ON pt1.Id = pt2.Id'
       )

PRINT @query
exec(@query)

DROP TABLE #BookGenreMapping

A: For all those with a case similar to mine.
The below link is a huge help :
https://community.spiceworks.com/topic/973727-sql-how-to-convert-multiple-rows-into-single-rows-with-more-columns


text:
Q: How to remove Google Drive Ubuntu? I made my biggest mistake of my life and installed google drive on Ubuntu. Now I cannot uninstall it anymore.
- I uninstalled the google drive package:
sudo apt-get remove grive-tools
sudo apt-add-repository --remove ppa:thefanclub/grive-tools

*

*I deleted the all the accounts under Online Accounts

*I unmounted the drive

But it still appears in the file explorer and when I click on it, it automatically revives and sysncs the files back again:

I want to remove it forever and never ever see it again!


text:
Q: Installing packages with Anaconda on Fedora 27 I can't seem to install any packages with the conda package manager on Fedora 27, specifically, I'm trying to install pytorch. I've tried installing it using conda install pytorch torchvision -c pytorch but it says I don't have permission, and when I try source activate my_root like EVERY INTERNET SOURCE tells me to do, it just errors because source doesn't even do the right thing.
I also tried building it from source but it gives the error that yaml is not installed, and I can't install it with conda for the same reason: source activate my_root is a total scam.
I can't find anything else that is remotely close to functional. How do I perform the basic task of installing a package from the internet?


text:
Q: How do you return a list of the current project folders and files of your current project in QtCreator? I think Qt must have this, because QtCreator has a list on its sidebar:

Ideally I am just looking for a Qt function that will just return this list.
Thanks.

A: You can list the files in a given directory with QDir::entryList().  QDir has a number of other methods that may be useful for you as well.


text:
Q: Recursive SQL relation query I am stuck on one SQL Query, any one could help me?,
Following is my table [LEVEL]
With columns
Id int, Name Varchar(50), ObjectId Int, ParentId Int, LevelId int

Following are the records:
INSERT INTO [LEVEL] (Name,ObjectId,ParentId,LevelId) VALUES('Test',1,NULL,1);
INSERT INTO [LEVEL] (Name,ObjectId,ParentId,LevelId) VALUES('3rdItem',2,1,2);
INSERT INTO [LEVEL] (Name,ObjectId,ParentId,LevelId) VALUES('1stItem',3,2,3);
INSERT INTO [LEVEL] (Name,ObjectId,ParentId,LevelId) VALUES('ehs',4,3,4);
INSERT INTO [LEVEL] (Name,ObjectId,ParentId,LevelId) VALUES('2ndItem',5,3,4);
INSERT INTO [LEVEL] (Name,ObjectId,ParentId,LevelId) VALUES('test tom',6,3,4);
INSERT INTO [LEVEL] (Name,ObjectId,ParentId,LevelId) VALUES('waterweg23',7,3,4);
INSERT INTO [LEVEL] (Name,ObjectId,ParentId,LevelId) VALUES('ehs',4,2,1);

I need to get the objects with parents having max Level Id.
Here record "ehs" has 2 parents i.e. (3 & 2) it should show for ehs with parent 3 only, as Object 3 has highest level id than 2.
So I want to get all the records with Parent having max levelId
Can anyone help me??

A: If you want recursive one, try this:
with cte as (
    select L.Name, L.ObjectId, L.LevelID, L.ParentId, LP.LevelId as ParentLevelId
    from [LEVEL] as L
        left outer join [LEVEL] as LP on LP.ObjectID = L.ParentId
    union all
    select L.Name, L.ObjectId, L.LevelID, c.ParentId, c.ParentLevelId
    from [LEVEL] as L
        inner join cte as c on c.ObjectId = L.ParentId
), cte2 as (
    select
        Name, ObjectID, ParentId, LevelId, ParentLevelId,
        row_number() over(partition by Name, ObjectID order by ParentLevelId desc) as row_num
    from cte
)
select
    Name, ObjectID, LevelId, ParentId, ParentLevelId
from cte2
where row_num = 1
order by name asc

sql fiddle

A: Try this.
DECLARE @LEVEL TABLE (Id int, Name Varchar(50), ObjectId Int, ParentId Int, LevelId int)

INSERT INTO @LEVEL (Name,ObjectId,ParentId,LevelId) VALUES('Test',1,NULL,1);
INSERT INTO @LEVEL (Name,ObjectId,ParentId,LevelId) VALUES('3rdItem',2,1,2);
INSERT INTO @LEVEL (Name,ObjectId,ParentId,LevelId) VALUES('1stItem',3,2,3);
INSERT INTO @LEVEL (Name,ObjectId,ParentId,LevelId) VALUES('ehs',4,3,4);
INSERT INTO @LEVEL (Name,ObjectId,ParentId,LevelId) VALUES('2ndItem',5,3,4);
INSERT INTO @LEVEL (Name,ObjectId,ParentId,LevelId) VALUES('test tom',6,3,4);
INSERT INTO @LEVEL (Name,ObjectId,ParentId,LevelId) VALUES('waterweg23',7,3,4);
INSERT INTO @LEVEL (Name,ObjectId,ParentId,LevelId) VALUES('ehs',4,2,1);

SELECT
    l.ID,
    l.Name,
    l.ObjectID,
    l.ParentID,
    l.LevelID
FROM
    @LEVEL AS l INNER JOIN (
                        SELECT
                            ObjectID,
                            MAX(LevelID) AS LevelID
                        FROM
                            @LEVEL
                        GROUP BY
                            ObjectID
                        ) AS s
                    ON
                        l.ObjectID = s.ObjectID
                            AND
                        l.LevelID = s.LevelID
ORDER BY
    l.ObjectID


text:
Q: What might be preventing the HomeAsUp icon being displayed I've been working on an app with multiple ActionBar activities, and from the outset the HomeAsUp button has been visible and working on all of the activities selected from the MainActivity. Today I noticed that it is no longer there - but I can't figure out what I have changed that would affect it.
The most significant change in recent days is that I migrated the project from Eclipse to Android Studio because I was having problems with Eclipse frequently corrupting my project files and requiring a complete reinstall.
This is a sample of the code in the main activity which creates the new activities:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
  Intent intent=null;
  int id = item.getItemId();
  switch (id) {
    case R.id.action_list:
      intent = new Intent(this, StudyListActivity.class);
      break;
    // etc
  }

  if (intent != null) {
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    return true;
  }
  return super.onOptionsItemSelected(item);
}

Here is the declaration of the intent in the manifest
<activity
  android:name="com.example.app.StudyListActivity"
  android:label="@string/activity_list"

  android:parentActivityName="com.example.app.MainActivity" >
    <meta-data
      android:name="android.support.PARENT_ACTIVITY"
      android:value="com.example.app.MainActivity" />
</activity>

since it stopped working I have also tried putting
getSupportActionBar().setHomeButtonEnabled(true);

in the onCreate method of the called activity (as per Display back button on action bar) but that makes no difference.
So I'm wondering if there is anything that got stripped out in my migration from eclipse which is preventing it showing (or something else I could have changed which might inadvertently have disabled it)

A: you should enable it via setDisplayOptions
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME);

A: You could also try
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

In the activity you want the HomeAsUp icon in


text:
Q: unable to get vuex store getters data in vuejs using jest I am trying to test the getters method of vuex store using jest. But getting undefined as result.
Below is the code I am using,
storeConfigurations.ts
---------------------
const state = {
    update: false
}

const getters = {

  [types.GET_UPDATE_VALUE]: (state: { update: any }) => {
        return state.update;
    }

}

types.ts
--------
export const GET_UPDATE_VALUE = 'GET/update'

trying to test the store getters method inside updatedValue() method and got undefined as result.
update.vue
===========

  <div class="updateCss">
      <customList :items="updatedValue"></customList>
    </div>

export default class UpdateTest extends Vue {

get updatedValue() {

const updatedValue = this.$store.getters[
      types.GET_UPDATE_VALUE
    ];
}

update.spec.ts
==============

import Vuex from 'vuex'
import storeConfigurations from '@/store/modules/storeDetails'
const localVue = createLocalVue()
localVue.use(Vuex)

 describe('Update Component TestSuite', () => {

 beforeEach(() => {
    let store
    let updateWrapper
     store = new Vuex.Store({
      modules: {
        storeConfigurations: {
          state: { update:false},
          getters: {
            updatedValue: jest.fn()

         }
      }
      }
    })

     updateWrapper = shallowMount(UpdateTest , {
      store,
      localVue

 }

Here I am trying to get the updatedvalue from store, but I am getting undefined while mocking store.

A: Problem got solved by giving getters with state variables inside modules.


text:
Q: fabric.api execute stuck in loop Please find the my fabfile.py content below. You may like to change the list of env.hosts to check for yourself.
Kindly note that direct call to chk_* methods would get execute but then also execute against unintended hosts for e.g. chk_kafka also execute against zookeeper group of nodes.
Any help is appreciated. Thanks for bearing with me.
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
    auto ssh
"""
import os
from fabric.colors import *
from fabric.api import *
from fabric.context_managers import *
from fabric.contrib.console import confirm

env.user = 'centos'
env.password = 'centos'

env.hosts = [
                '10.41.121.78',
                '10.41.121.79',
                '10.41.121.80',
                '10.41.121.81',
                '10.41.121.82',
                '10.41.121.83',
                '10.41.121.84',
                '10.41.121.85'
            ]

clusters = env.hosts

env.hostnames = dict([h, 'gt-%d' % (i + 1)] for i, h in enumerate(clusters))

env.roledefs = {
    'clusters' : clusters,
    'kafka' : clusters[0:5],
    'zookeeper' : clusters[5:8]
}

@task
def status(op=None):
    if op=='zookeeper':
        execute(chk_zk)
    elif op == 'kafka':
        execute(chk_kafka)
    else:
        execute(chk_all)

@roles('zookeeper')
def chk_zk():
    run('jps')

@roles('kafka')
def chk_kafka():
    run('jps')

@roles('clusters')
def chk_all():
    run('jps')

A: adding @runs_once annotation to the method 'status' solved the problem for me.

A: The problem is that you are setting env.hosts explicitly. This is the list of hosts that Fabric will execute tasks on. Usually it would be set via the -H (--hosts) command line option if you wanted to select specific hosts to execute on. In your setup, it is most sensible to leave env.hosts out completely, as you are executing mosts tasks on hosts of specific roles via the @roles decorator.
I'm not sure whether your solution works exactly as intended. @runs_once will cause the status task to only execute once per fab run, which effectively means it will run on only one machine, whichever that is, instead of running once for every machine and subsequently triggering the chk_* tasks multiple times. I would expect the other tasks to then still be run on all machines mentioned in env.hosts, regardless of the roles given via @roles.
TL;DR: Remove env.hosts and keep @runs_once on the status task, and you should be fine.


text:
Q: MathJax.Hub.getAllJax returns empty array My html:
{{question_display}}
Javascript code:
var math = MathJax.Hub.getAllJax("questiondisplay")

On doing this math is an empty array []
However, on doing $('#questiondisplay') I get: []
Can anyone please explain what I'm doing wrong with MathJax ?


text:
Q: htmlentities - How do I keep my form safe in PHP? I have a small contact form that requires a subject, a name, an email, and a message. All these fields are sanitized with:
function sanitize($string){
    return htmlentities($string, ENT_QUOTES, 'UTF-8');
}

I send the email using the mail() function from PHP, and I use the subject field as the email title/subject. The problem is that in subject I have a single quote:
I'd like to explore

But after I sanitize it I get the email in the inbox, but that single quote is sanitized and appears like this:
I'd like to explore

How do I keep my form safe, but at the same time how do I get my subject of the email to be with the single quote not with that 'd-thing?

A: You store data using your sanitize function and if you want to display the data, you need to "desanitize" to the original format.
$str = 'I'd like to explore';

echo html_entity_decode($str, ENT_QUOTES, 'UTF-8');

To be strict, storing any data is not a security risk. However the process how the data is stored can cause security issues. Using HTML entities is usually done for storing data in databases and use it later on. But a better way to store that data is by using prepared statements which makes this completely unnecessary.
The question really is, for what storage you are sanitizing.

A: htmlentities is used when you want to print user-generated content as HTML on your own site. User-generated content could contain HTML-breaking symbols, so it replaces characters with HTML entities. (A wrong ' could terminate a string or if a troll inserts </div>, you entire layout of your website would break.)
That '-thing is a ' and is, from the perspective of any html-rendering-engine, an apostrophe and will be displayed as such. You can find a list of these entities online.
The reverse of that process is html_entity_decode, in order to get plain text out of it again.
In regards to your use case of keeping your form safe: htmlentities is the not the right tool for this.
If you want to send that email with plain text, keep it as plain text. It's true that you should not trust user-generated content and behavior, yet you then should safeguard against database insertion issues (prepared statements) and preventing POST-repetition on the form itself in order to not spam people.
Yet there is no inherent harm in treating user input as raw text and sending that content as raw text. (If you want to to send an HTML email with user-generated content, then htmlentities will come in handy for that as well.)

A: Sanitization is done within a context. In other words you should know what you are "sanitizing" against: SQL injection, html script attacks or what not. With this in mind, the correct approach is to deal with each problem separately: sanitize for the SQL injection when storing in the db, but store the data as close to the "original" as you can. This means the data in the db will be "desanitized". Then, depending on what you intend to do with the data, you process it accordingly: sending in an email? Just dump the content. Showing on the web page? html_entities it.
Note that the question of "optimization" in the sense of not having to process with a sanitizer every time you output content is different. It has to be dealt with separately, if at all needed.
This has proven itself a sound approach for me over years.


text:
Q: Using Salesforce Landing page checkbox values to populate a SFDC field I have an ExactTarget Landing Page form that is currently inserting a Lead into SFDC when submitted. The form has 3 checkbox options that (if possible) I'm trying to concatenate and insert into the 'Description'(textarea) field in SFDC.
Here is the code I have now:
var @_SFtype, @_SFobjid, @checkbox1, @checkbox2, @checkbox3, @Description

SET @checkbox1 = RequestParameter("checkbox1")
SET @checkbox2 = RequestParameter("checkbox2")
SET @checkbox3 = RequestParameter("checkbox3")
SET @Description = Concat(@checkbox1, @checkbox2, @checkbox3)

SET @_SFobjid = CreateSalesforceObject
("Lead",13,"Company",RequestParameter("Company"),
"LastName",RequestParameter("LastName"),
"Status",RequestParameter("Status"),
"FirstName",RequestParameter("FirstName"),
"Job_Title__c",RequestParameter("Job_Title__c"),
"Email",RequestParameter("Email"),
"Phone",RequestParameter("Phone"),
"Street",RequestParameter("Street"),
"City",RequestParameter("City"),
"StateCode",RequestParameter("StateCode"),
"PostalCode",RequestParameter("PostalCode"),
"Description",RequestParameter("Description"),
"LeadSource",RequestParameter("LeadSource"))

if "Lead" == "Contact" then
    SET @_SFtype = "Contact"
endif

if "Lead" == "Lead" then
    SET @_SFtype = "Lead"
endif

I can see when the form posts that it's sending the checkbox values individually and not passing a 'Description' value, but I'm not sure what I'm missing with the script.
SOLVED
Instead of:
"Description",RequestParameter("Description"),
This worked:
"Description",@Description,


text:
Q: JavaScript Promises and Function Return Differences What is the difference between the following two functions as far as promises are concerned?
var service = {
    someFunction: function() {
        return $http.get('url').then(function (response) {
            return response;
        });
    },
    someFunction2: function() {
        return $http.get('url');
    }
};

A: The second returns a promise so that the calling function (not shown in your code) can do something with it.
The first one does exactly the same thing, but it also uses the promise to define a function that will run then the response comes back. That function does (effectively) nothing, since when the HTTP response arrives, it returns to the calling function (then) which doesn't care about the response.

A: There is no difference - the identity function in the first example is not needed but doesn't cause any observable difference to outside.


text:
Q: C Program to print first and last n lines in a file, what am I doing wrong? I am new to programming in general. Please note that this is for homework.
I am using a txt file with a-z in lowercase.
I use the command ./a.out test.txt to run the program, then enter a number.
my code:
#include <stdio.h>

static void cat(FILE *fp, int num) {
    int count = 0;
    char buffer[4096];

    while (fgets(buffer, sizeof(buffer), fp) != 0) {
        if (count == num)
            break;
        else
            count++;
        fputs(buffer, stdout);
    }
}

int main(int argc, char *argv[]) {
    int num, count = 0;
    long length;
    char buffer[4096];

    FILE *fp;
    fp = fopen(argv[1], "r");
    if (fp == NULL) {
        printf("Can't open this file\n");
        return 0;
    }

    scanf("%d", &num);
    cat(fp, num);
    printf("...\n");

    fseek(fp, 0, SEEK_END);
    length = ftell(fp);
    fseek(fp, (length - 2), SEEK_SET);
    printf("1\n");
    while (fgets(buffer, sizeof(buffer), fp) != 0) {
        fputs(buffer, stdout);
    }
    if (ftell(fp) == '\n') {
        count++;
        length = ftell(fp);
        fseek(fp, (length - 4), SEEK_SET);
        printf("2\n");
        while (fgets(buffer, sizeof(buffer), fp) != 0) {
            fputs(buffer, stdout);
        }
    } else {  //<------ missing opening brace
        length = ftell(fp);
        fseek(fp, (length - 2), SEEK_SET);
        printf("3\n");
        while (fgets(buffer,s izeof(buffer), fp) != 0) {
            fputs(buffer, stdout);
        }
        if (count == num) {
            printf("4\n");
            while (fgets(buffer, sizeof(buffer), fp) != 0) {
                fputs(buffer, stdout);
        }
    }

    fclose(fp);
    return 0;
}

Please Help!

A: I reformatted your code to improve readability.  There is a missing { where I indicated.  As posted, the code does not compile.
Your program should be able to print the first n lines, but your method cannot work for the last n lines.
Allocate an array of n buffers:
char (*array)[4096] = calloc(4096, num);

For each line read, move the buffers and copy the line at the last position:
memmove(array[0], array[1], sizeof(array[0] * (num - 1));
strcpy(array[num - 1], buffer);

There are more efficient methods but you should be able to implement this simple method.
When you reach the end of file, print the non empty lines from the array.
EDIT:
Here is a complete version that uses an array of num+1 buffers.  It reads the whole file, printing the first num lines as they are read, and keeping the last num lines in the array at all times, cycling the position at which it read the next line over num+1 buffers.
At the end of file, if the file has at more than num lines, extra lines must be printed, potentially separated by a -------- if lines are skipped in the middle of the file. The last num lines or less are printed: pos is computed to find the proper buffer modulo num+1 and the lines are printed until the last.
Here is the code:
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    int num, pos, count;
    FILE *fp;
    char (*array)[4096];  /* pointer to an array of buffers */

    if (argc < 2) {
        printf("Usage headtail filename [number]\n");
        return 1;
    }
    fp = fopen(argv[1], "r");
    if (fp == NULL) {
        printf("Cannot open file %s\n", argv[1]);
        return 1;
    }
    if (argc > 2) {
        /* get the number from the command line if 2 args were given */
        if (sscanf(argv[2], "%d", &num) != 1) {
            num = -1;
        }
    } else {
        /* otherwise read from standard input */
        if (scanf("%d", &num) != 1) {
            num = -1;
        }
    }
    if (num < 0) {
        printf("Invalid number\n");  /* negative or non numeric */
        return 1;
    }

    /* allocate space for num+1 buffers */
    array = malloc(4096 * (num + 1));

    for (count = pos = 0; fgets(array[pos], 4096, fp) != NULL; count++) {
        /* printing the first num lines */
        if (count < num)
            fputs(array[pos], stdout);
        /* cycle buffers for num lines + 1 extra buffer */
        if (++pos >= num + 1)
            pos = 0;
    }
    if (count > num) {
        /* more lines to print */
        pos = count - num;
        if (pos > num) {
            /* print place holder for missing lines */
            printf("...\n");
        } else {
            /* print from the last line printed */
            pos = num;
        }
        for (; pos < count; pos++) {
            fputs(array[pos % (num + 1)], stdout);
        }
    }
    fclose(fp);
    return 0;
}

A: 1) You should check if the file size is less than size of buffer.
2) If you intend to read the file for n lines in chunks of data at a time, read it one line at a time. probably using fscanf. This way you can keep track of how many lines you've read/printed. Also this helps to know whether your file has enough lines at all.


text:
Q: Is it possible to setup a router to access local computers available on RJ45 which is connected to WAN port I have a router which has 4 LAN and a WAN ports. I use PPPoE to connect internet. Earlier i used to connect internet via my Laptop. Since I started using router, i could not see local computers (reason is obvious) my laptop is connected through LAN port of router and not to actual ISP LAN cable. WAN has internet IP not local network IP.
Is it possible to connect local computers (without switch) so that I can use IPmessanger with my friends ? if yes how?
Please advice

A: Configure your router accordingly. The idea behind a (home) router is that you have a device which lets your share the WAN connection between multiple other devices and router traffic accordingly. You connect your ISPs cable to the WAN port and every computer that should be part of the network to one of the available LAN ports.
Every computer gets some kind of internal address like 192.169.100.X usually automatically assigned using DHCP. That DHCP configuration also supplies additional information e.g. that your router should be the default gateway for those computers. That was traffic that isn't meant for the internal network gets send to the router and the router forwards it to your ISP.
If you can not ping or otherwise reach the other computers that are part of your LAN (assuming they're all connected to the LAN ports of the router) you need to check the configuration for isolation options. This depends on the model of the router so without knowing which model of router it is you're on your own on that.


text:
Q: Postgresql constraints SARG Are SQL Server style SARGs relevant to PostgreSQL queries in general and more specifically on table constraints?
I have a parent table with many inherited children, partitioned by a date column.
Would it be better to change the constraints from
CHECK (date_part('year', end_of_dt)::integer = 2016)

to
CHECK (end_of_dt between '2016-01-01 0:00:00' and '2016-12-31 23:59:59.999')

A: We can easily test this.. but first, stop using date_part. Instead, use extract. It's the same thing with slightly different syntax, but it's standardized.
Testing it
Let's create a table with all the second TIMESTAMPS for the year.
CREATE TEMPORARY TABLE foo AS (
  SELECT to_timestamp(x) AS ts
  FROM generate_series(
    extract(EPOCH FROM '2016-01-01'::timestamp)::int,
    extract(EPOCH FROM '2017-01-01'::timestamp)::int
  ) AS t(x)
);

Then we can implement your check in a WHERE condition to get a basic idea of speed. BTW, there are a ton more seconds in a year than I first though. There are 31,622,401 seconds in a year. It takes 1093 MB to load this sample data.
took, 12.6, 10.8, 11.0 seconds.
SELECT count(*) FROM foo
WHERE extract(YEAR FROM ts) = 2016;

took, 6.1, 6.3, 6.2 seconds
SELECT * FROM foo
WHERE ts BETWEEN '2016-01-01 0:00:00' AND '2016-12-31 23:59:59.999';

Conclusion
Yes, the second is roughly 2x as fast in three trial runs. For the purposes of creating a check constraint, you should use the latter.
Addendum
PostgreSQL has the ability to add functional indexes, however an index on date_part() is not possible
CREATE INDEX onyear ON foo (date_part('year',ts));
ERROR:  functions in index expression must be marked IMMUTABLE

I assume this is because the result of datetime functions comes back in the client's timezone. Either way, this makes it even more advantageous to use the timestamp ranges. One easy to get more speed if need be would be with materialized views though..
CREATE MATERIALIZED VIEW matviewfoo AS
SELECT
  extract(YEAR FROM ts)::smallint AS year,
  ts
FROM foo;
CREATE INDEX yearidx ON matviewfoo (year);
VACUUM FULL matviewfoo;

Now you can
SELECT count(*) FROM matviewfoo WHERE year = 2016;

And, you're down to 4.1 seconds

A: Here's what I've found empirically
CREATE TABLE accounts (
    account_id INT PRIMARY KEY
    ,eod DATE
    );

CREATE TABLE accounts_p2015 (LIKE accounts INCLUDING ALL) INHERITS (accounts);
CREATE TABLE accounts_p2016 (LIKE accounts INCLUDING ALL) INHERITS (accounts);
CREATE TABLE accounts_p2017 (LIKE accounts INCLUDING ALL) INHERITS (accounts);

So the question becomes performance of these constraints:
ALTER TABLE accounts_p2015 ADD CONSTRAINT chk_eod CHECK (EXTRACT(YEAR FROM eod) = 2015);
ALTER TABLE accounts_p2016 ADD CONSTRAINT chk_eod CHECK (EXTRACT(YEAR FROM eod) = 2016);
ALTER TABLE accounts_p2017 ADD CONSTRAINT chk_eod CHECK (EXTRACT(YEAR FROM eod) = 2017);

vs
ALTER TABLE accounts_p2015 ADD CONSTRAINT chk_eod CHECK ( eod BETWEEN '2015-01-01' AND '2015-12-31');
ALTER TABLE accounts_p2016 ADD CONSTRAINT chk_eod CHECK (eod BETWEEN '2016-01-01' AND '2016-12-31');
ALTER TABLE accounts_p2017 ADD CONSTRAINT chk_eod CHECK (eod BETWEEN '2017-01-01' AND '2017-12-31');

The first constraints (not SARGable) looks like it hits all child tables:
EXPLAIN SELECT * FROM accounts WHERE eod = '2016-11-11';
                            QUERY PLAN
----------------------------------------------------------------------
Append  (cost=0.00..114.75 rows=34 width=8)
->  Seq Scan on accounts  (cost=0.00..0.00 rows=1 width=8)
        Filter: (eod = '2016-11-11'::date)
->  Seq Scan on accounts_p2015  (cost=0.00..38.25 rows=11 width=8)
        Filter: (eod = '2016-11-11'::date)
->  Seq Scan on accounts_p2016  (cost=0.00..38.25 rows=11 width=8)
        Filter: (eod = '2016-11-11'::date)
->  Seq Scan on accounts_p2017  (cost=0.00..38.25 rows=11 width=8)
        Filter: (eod = '2016-11-11'::date)
(9 rows)

And the second (SARGable) only hits the relevant child table:
EXPLAIN
SELECT *
FROM accounts
WHERE eod = '2016-11-11';
                            QUERY PLAN
----------------------------------------------------------------------
Append  (cost=0.00..38.25 rows=12 width=8)
->  Seq Scan on accounts  (cost=0.00..0.00 rows=1 width=8)
        Filter: (eod = '2016-11-11'::date)
->  Seq Scan on accounts_p2016  (cost=0.00..38.25 rows=11 width=8)
        Filter: (eod = '2016-11-11'::date)
(5 rows)

So I guess SARGs are relevant to PostgreSQL query and constraint optimization.
SQLFiddle


text:
Q: Efficient substring Search in DynamoDB This is the context of my situation:

*

*I have a huge DB in dynamoDB with 250.000 items. (Example) table

*I want to be able to "substring search" through 3 attributes, getting the list of all items that match the substrings.

*The attributes i want to be able to search can have the same value among different items.

*My hash key is an id (the only attribute that really differentiates the items).

*I'm using react native as a client

*My schema has these "query types" queries
Where I am:

*

*I first tried querying with the listCaballos query adding the user input as a filter to the query, and using the nextToken recursively to go over the whole table (without using secondary indexes), but it took 6 minutes to go through the table and return the items.

*I know secondary indexes help to partition and then order the items through chosen keys (which makes it fast), buuuut I read that that forces the user to make an exact search (not a substring kind of search), and that's not what I need.

*I've heard Elastic Search might help.
Any suggestions?
Thanks!

A: This is not efficient in DynamoDB. Although you can create secondary indexes to search 'begins_with', substring ('contains') capability is there only for filters which are not efficient in a large data set (Since DynamoDB will use IOPS to query all and then apply the filter).
This kind of a requirement, it is efficient to index the database using another service like AWS ElasticSearch or CloudSearch so that you can apply the query on top of that service and configure continuous indexing.
Getting Started

*

*Searching DynamoDB Data with Amazon CloudSearch

*Combining DynamoDB and Amazon Elasticsearch with Lambda

*Indexing Amazon DynamoDB Content with Amazon Elasticsearch Service Using AWS Lambda

A: You will not be able to use secondary indexes to help create a (reasonable) generalized substring search.
There are many ways to solve your problem. Here, I present a few of them, and this is by no means exhaustive.
DynamoDB -> CloudSearch
CloudSearch can provide general search functionality for your data. Basically, you can connect a lambda function to the DynamoDB stream from your table. That lambda function can keep your CloudSearch domain up to date. Here is an overview of this process.
CloudSearch
You could forgo DynamoDB and store this data in CloudSearch. That eliminates the need for the lambda function and means your data is only stored in one place. However, you need to tolerate a higher time to consistency because CloudSearch doesn't have strongly consistent reads like DynamoDB.
RDS
You could just use a SQL database of some sort. Most of them support a full text search. You can even use AWS Aurora Serverless if you don't want to manage database instances.


text:
Q: Error: While trying to resolve module `react-native-fbads` I am inserting Facebook ads in my react native app. I have installed react-native-fbsdk-next and set up that. I got no issues with this.
Now I have installed react-native-fbads as per the documentation, but I am getting this error:
Error: While trying to resolve module `react-native-fbads` from file `Component File`, the package `PATH/node_modules/react-native-fbads/package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`PATH/node_modules/react-native-fbads/dist/lib/index.js`. Indeed, none of these files exist:

Can anyone help me with this issue? I have tried adding this in metro.config.js
resolver: {
    sourceExts: ['jsx', 'js', 'ts', 'tsx', 'cjs'],
},

A: go to package.json file of nodemodules/react native fbads and then package. Json and change the main value to the src/index. Js or index.ts


text:
Q: change the host header after the backend server responds I have a proxy setup to receive a client request for www.example.com from external.example.com (www.example.com is a tab on external.example.com) . the proxy recieves the request and sends to www.example2.com to the backend server with multiple websites with host headers. now when www.example2.com responds with path and query strings ex : https://www.example2.com/results . I want this intercepted by the proxy and have the proxy change just the header to http://www.example.com without going into a loop and display results . I have tried proxy_set-header host and proxy_redirect and both fail. below is my config :
    server {
    listen 80;
    listen [::]:80;

   server_name www.example.com;

    #root /var/www/www.example.com;
    #index index.html;

   location / {
   proxy_pass http://www.example2.com;
  proxy_set_header Host http://www.example.com;
  OR
  Proxy_redirect https://www.example2.com$1 http://www.example.com
              }
           }

A: I was doing a proxy_pass to a URL which was behind an aws elb . The elb was stripping out the set host header commands and proxy redirects . IO changed it to a prticular instance and it started working as expected. thanks for your help @nbari


text:
Q: Compiling perl-tk with xft support on Mac OSX Snow Leopard I am trying to compile perl-tk with XFT support on a Mac OS X 10.6.8, but running into some problems.
The first is that running

perl Makefile.PL XFT=1

yields the following output (in summary the freetype.h header cannot be found, and the XFT argument is not recognized):
macmini:Tk-804.030 sjurisic$ perl Makefile.PL XFT=1
perl is installed in /usr/local/ActivePerl-5.8/lib okay
PPM for perl5.008009
Test Compiling config/perlrx.c
Test Compiling config/pmop.c
Test Compiling config/pregcomp2.c
Test Compiling config/regexp511.c
Test Compiling config/signedchar.c
Test Compiling config/Ksprintf.c
Test Compiling config/svtrv.c
Test Compiling config/tod.c
Test Compiling -DTIMEOFDAY_TZ config/tod.c
TZ gettimeofday()
Using -L/usr/X11R6/lib to find /usr/X11R6/lib/libX11.dylib
Using -I/usr/X11R6/include to find /usr/X11R6/include/X11/Xlib.h
Cannot find freetype.h include file
WARNING: DISTVNAME is not a known parameter.
'DISTVNAME' is not a known MakeMaker parameter name.
'XFT' is not a known MakeMaker parameter name.

A: You can try to adjust myConfig in the Perl/Tk distribution to add additional search paths for the freetype includes. This would be the line
my $ftinc = Ift("/usr/include","/usr/local/include",$X11INC||());

where you can add "/usr/X11/include".
If the libXft.so does not live in /usr/local/lib or any other standard library path, then you probably need to adjust the my $ftlib = definition a few lines below, too.
Regardless if you're successful or not, this is worth a ticket in https://rt.cpan.org/Ticket/Create.html?Queue=Tk
BTW, in Tk 804.031 XFT=1 is set by default, so you don't have to specify it anymore in the perl Makefile.PL call. And the warning about 'XFT' is not a known MakeMaker parameter name. is just a MakeMaker artifact and may be ignored.


text:
Q: Sharepoint 2010 - Suggestion Board I am using Sharepoint Foundation 2010, and I'm looking to create a discussion board for employees, where they can submit "suggestions".
I would for the employees that post a suggestion to be anonymous (or only see their post - which I know is a feature in SP)
However, I would also like to give certain people the ability to view all the suggestions and reply accordingly - and for the employee to be able to see that response.
Is this possible? I'm sure it's been done before.
Thanks

A: The discussion board is not very advanced in 2010 version, they have improved it in 2013. The discussion board does not permit out of the box anonymity.
The only feature that allows to be anonymous is the survey (although the site owner can switch it off anytime and see the names of users), which is not made to discuss other people's replies. They could, but it is not easy to navigate among replies of other people and one would not have a place to comment.
Per experience (and I am not talking about technical things but basic human nature) one thing is to request feedback on more important policies of the company, which for many employees is considered risky (we all know how the employer might treat a personal opinion not in line with his own), another thing is to receive feedback on the use and ways of sharepoint which does not necessarily mean critique towards the employer and should be considered mere improvement to current hardware/software/policies.
I would not architect something more complicated since the signal you are sending out is that merely talking about sharepoint and its use inside the company is something dirty and something to be careful with. This sends out a negative message that might get in the way of your user adoption strategies.
If the business culture is so bad that anyone would feel ashamed to post an idea for fearing to be judged as silly or ignorant, use anonymous surveys. If the culture is more relaxed and allows participation, free of prejudice, then use the message board, which has the advantage that keeps everything transparent.


text:
Q: Avoid failure of confint.merMod on weighted models in lme4 when data object modified in calling frame I'm facing a problem when using lme4 glmer function with weights, where if the data object passed to glmer is modified, some functions such as confint no longer work on the model. Here is an example:
library(lme4)

set.seed(1)
n <- 1000
df <- data.frame(
  y=rbinom(n,1,.5),
  w=runif(n,0,1)*.1+.95,
  g=as.integer(round(runif(n,0,4)))
)
m <- glmer(cbind(y,1-y)~(1|g),data=df,weights=w,family=binomial())
confint(m)
df$w <- df$w*2
confint(m)

The 2nd call to confint gives this error:
Computing profile confidence intervals ...
Error in profile.merMod(object, which = parm, signames = oldNames, ...) :
  Profiling over both the residual variance and
fixed effects is not numerically consistent with
profiling over the fixed effects only

It seems this has something to do with the profile function, as that function doesn't work after modifying the data frame.
The following seems to work to remove the dependency on the data object, but I am a bit uneasy not knowing if there might ever be bad side effects:
glmer2 <- function(...){
  cl <- match.call()
  df <- eval.parent(cl$data)
  cl[1] <- call("glmer")
  cl$data <- as.name("df")
  eval(cl)
}
m <- glmer2(cbind(y,1-y)~(1|g),data=df,weights=w,family=binomial())
confint(m)
df$w <- df$w*2
confint(m)

(results of confint don't change)
The reason I need something like this is that I am creating a series of models, and need to re-compute the weights between each one, and it would be quite messy to keep all of the data objects.
Why do model functions seem to rely on the data object still being present and unchanged in the calling environment? And is there a better way to solve this issue?
(R version 3.6.3 (2020-02-29), x86_64-redhat-linux-gnu, lme4_1.1-21)


text:
Q: Run javascript inside HTML component in Adobe AIR Flex 4? I have the following component in an AIR application from Flex 4:
<mx:HTML id="viewObject"
         x="10" y="42" width="634" height="313"
         location="http;//localhost:8080/mypage.php" />

Now I want to run a javascript when the page loads but the javascript isn't inside the target page. I want to run the following javascript:
javascript:alert('Hello world.');

I tried approaching it by setting the location property again to the javascript after the page has loaded like below.
<s:Button x="10" y="10" label="Button">
    <s:click>
        <![CDATA[
        viewObject.location = "javascript:alert('hello world');";
        ]]>
    </s:click>
</s:Button>

Unfortunately for me, that doesn't seem to work. Can anybody help me out with this problem?

A: That's because location is like using the address bar.  What you need to do is something like this:
htmlComponent.htmlLoader.window.alert('hello world');

I think that should work.


text:
Q: ReactJS setState conflicts with getDerivedStateFromProps I am trying to follow the design pattern in https://github.com/reactjs/rfcs/issues/26 (see replies by bvaughn) and create ReactJS editable form, that reads data from the server, show then in the form fields, allows the use to edit values and then save those data back in database.
I have some essential code:
const mapStateToProps = state => {
    return {
        invoice: state.invoice,
        invoiceReady: state.invoiceReady,
    };
};

 static getDerivedStateFromProps(nextProps, prevState) {
        if (nextProps.match.params.id !== prevState.id) {
            return update(
                prevState, {
                    ['id']: {$set: nextProps.match.params.id},
                    ['invoiceReady']: {$set: false}
                });
        } else {
            return update(
                prevState, {
                    ['invoice']: {$set: nextProps.invoice},
                    ['invoiceReady']: {$set: nextProps.invoiceReady}
                });
        }
    }

 handleChange(event) {
        const state = update(
            this.state, {
                invoice: {
                    [event.target.id]: {$set: event.target.value}
                }
            }
        );
        this.setState(state);
    }

componentDidMount() {
        this.requestInvoice();
    }

componentDidUpdate(prevProps, prevState) {
        if (!this.state.invoiceReady) {
            this.requestInvoice();
        }
    }

and my JSX code contains editable fields like:
                        <input
                            type="text"
                            className="form-control"
                            id="invoiceDate"
                            value={this.state.invoice.invoiceDate}
                            onChange={this.handleChange}
                        />

So - according to the mentioned pattern I am initiating the request to the server by requestInvoice, some other components handle this action and receives and saves the invoice into the Redux store and that is why those data are automatically written into the props.invoice variable and I am further writing props.invoice into this.state.invoice by getDerivedStateFromProps for further local processing of the invoice data. During the work with the form the handleChange events are raised and with the help of immutability-helper (update function) the updated fields are written into new state and setState is called.
My problem is that during the setState call the React is calling getDerivedStateFromProps and so the props.invoice overwrites any changes that are coming from the user and that ar processed into handleChange:setState function.
So - how to solve this problem: the conflict between setState and getDerivedStateFromProps?
Several options may be:

*

*my design can be flawed. E.g. maybe I should not try to move props.invoice into this.state.invoice (why not?)? But from the other side it would be nice to save invoice into this.state and be sure that all the changes are applied to the this.state.invoice during the editing of the invoice.

*mybe I should prevent execution of getDerivedStateFromProps during setState?

Maybe some other design pattern or code is more suitable for my ReactJS form?
I am using ReactJ 16.x

A: If you are decided to use react-redux for component state management, then you should avoid to manage the that component internal state using setState as its controlled by redux store.
Otherwise it will causes such issue and lots of if-else you may need to handle it.
considering your scenario,
During handleChange instead calling setState,better to dispatch an action to update the state in redux store and then via connect it will reflect to your component in the same way you calling API.
handleChange(event) {
        const stateData = invoice: {
                    [event.target.id]: {$set: event.target.value}
                };
        this.props.callDispatch({'UPDATE_SOME_DATA',stateData})
    }

Only thing need to take care, make sure reducers update only required passed properties data and leave other data intact updated by API dispatch action process.

A: I have arrived at the following solution - with the help of this.state.stateUpdate variable - and I consider this as the answer to my question (please comment if this is not sound and neat solution, I can accept other answer as well if that works):
 const mapStateToProps = state => {
        return {
            invoice: state.invoice,
            invoiceReady: state.invoiceReady,
            stateUpdate: false
        };
    };

     static getDerivedStateFromProps(nextProps, prevState) {
            if (prevState.stateUpdate) {
              return update(
                prevState, {
                    stateUpdate: {$set: false}
                }
              )
            }
            if (nextProps.match.params.id !== prevState.id) {
                return update(
                    prevState, {
                        ['id']: {$set: nextProps.match.params.id},
                        ['invoiceReady']: {$set: false}
                    });
            } else {
                return update(
                    prevState, {
                        ['invoice']: {$set: nextProps.invoice},
                        ['invoiceReady']: {$set: nextProps.invoiceReady}
                    });
            }
        }

     handleChange(event) {
            const state = update(
                this.state, {
                    invoice: {
                        [event.target.id]: {$set: event.target.value}
                    },
                    stateUpdate: {$set: true}
                }
            );
            this.setState(state);
        }

    componentDidMount() {
            this.requestInvoice();
        }

    componentDidUpdate(prevProps, prevState) {
            if (!this.state.invoiceReady) {
                this.requestInvoice();
            }
        }