Play video using libVLC from memory in python

Question: I am trying to make use of libVLC python bindings to play files after reading them into memory. I have the following code that reads a valid video file into the memory. I need to now play the video directly from the memory.
<code>import vlc
File1 = open('vid.webm','rb')
Axel  = File1.read()
</code>
Now i need to play the contents in Axel, how can I do this.
Information on how to do this in C, Java etc too can help.
Edit: Understood I will have to use the imem module but can't find any help regarding how to get it done.
Answer: To do this you have to use the imem module of libvlc. This can be really confusing since it is not a publicly documented API right now. However, I followed a couple other posts related to this here and on the VideoLan forums. Below is some example code I got working today in C++ that uses JPEG images loaded into memory to create a video stream. You can follow the similar steps, but you'll just have to change the codec of your data in memory (see imem-codec=RV24 line).
<code>// Local file/media source.
std::string IMEM_SOURCE_FOLDER = "settings/rvideo/samples/bigdog";

class MyImemData
{
public:
    MyImemData() : mFrame(0), mDts(0), mPts(0) {}
    ~MyImemData() {}
    std::vector<cv::Mat> mImages;
    std::size_t mFrame;
    int64_t mDts;
    int64_t mPts;
};

/**
    \brief Callback method triggered by VLC to get image data from
    a custom memory source. This is used to tell VLC where the
    data is and to allocate buffers as needed.

    To set this callback, use the "--imem-get=<memory_address>"
    option, with memory_address the address of this function in memory.

    When using IMEM, be sure to indicate the format for your data
    using "--imem-cat=2" where 2 is video. Other options for categories are
    0 = Unknown,
    1 = Audio,
    2 = Video,
    3 = Subtitle,
    4 = Data

    When creating your media instance, use libvlc_media_new_location and
    set the location to "imem:/" and then play.

    \param[in] data Pointer to user-defined data, this is your data that
    you set by passing the "--imem-data=<memory_address>" option when
    initializing VLC instance.
    \param[in] cookie A user defined string. This works the same way as
    data, but for string. You set it by adding the "--imem-cookie=<your_string>"
    option when you initialize VLC. Use this when multiple VLC instances are
    running.
    \param[out] dts The decode timestamp, value is in microseconds. This value
    is the time when the frame was decoded/generated. For example, 30 fps
    video would be every 33 ms, so values would be 0, 33333, 66666, 99999, etc.
    \param[out] pts The presentation timestamp, value is in microseconds. This
    value tells the receiver when to present the frame. For example, 30 fps
    video would be every 33 ms, so values would be 0, 33333, 66666, 99999, etc.
    \param[out] flags Unused,ignore.
    \param[out] bufferSize Use this to set the size of the buffer in bytes.
    \param[out] buffer Change to point to your encoded frame/audio/video data.
        The codec format of the frame is user defined and set using the
        "--imem-codec=<four_letter>," where 4 letter is the code for your
        codec of your source data.
*/
int MyImemGetCallback (void *data,
                       const char *cookie,
                       int64_t *dts,
                       int64_t *pts,
                       unsigned *flags,
                       size_t * bufferSize,
                       void ** buffer)
{
    MyImemData* imem = (MyImemData*)data;

    if(imem == NULL)
        return 1;
    // Loop...
    if(imem->mFrame >= imem->mImages.size())
    {
        imem->mFrame = 0;
    }
    // Changing this value will impact the playback
    // rate on the receiving end (if they use the dts and pts values).
    int64_t uS = 33333; // 30 fps

    cv::Mat img = imem->mImages[imem->mFrame++];
    *bufferSize = img.rows*img.cols*img.channels();
    *buffer = img.data;
    *dts = *pts = imem->mDts = imem->mPts = imem->mPts + uS;

    return 0;
}

/**
    \brief Callback method triggered by VLC to release memory allocated
    during the GET callback.

    To set this callback, use the "--imem-release=<memory_address>"
    option, with memory_address the address of this function in memory.

    \param[in] data Pointer to user-defined data, this is your data that
    you set by passing the "--imem-data=<memory_address>" option when
    initializing VLC instance.
    \param[in] cookie A user defined string. This works the same way as
    data, but for string. You set it by adding the "--imem-cookie=<your_string>"
    option when you initialize VLC. Use this when multiple VLC instances are
    running.
    \param[int] bufferSize The size of the buffer in bytes.
    \param[out] buffer Pointer to data you allocated or set during the GET
    callback to handle  or delete as needed.
*/
int MyImemReleaseCallback (void *data,
                           const char *cookie,
                           size_t bufferSize,
                           void * buffer)
{
    // Since I did not allocate any new memory, I don't need
    // to delete it here. However, if you did in your get method, you
    // should delete/free it here.
    return 0;
}

/**
    \brief Method to load a series of images to use as raw image data
    for the network stream.

    \param[in] sourceFolder Path to folder containing jpeg or png images.
*/
std::vector<cv::Mat> GetRawImageData(const std::string& sourceFolder)
{
    namespace fs = boost::filesystem;
    std::vector<cv::Mat> result;
    std::vector<std::string> filenames;
    if( fs::exists(sourceFolder) && fs::is_directory(sourceFolder) )
    {
        for(fs::directory_iterator dir(sourceFolder);
            dir != fs::directory_iterator();
            dir++)
        {
            std::string ext = dir->path().extension().string();
            if( fs::is_regular_file( dir->status() ) &&
                (dir->path().extension() == ".jpeg" ||
                 dir->path().extension() == ".png") )
            {
                filenames.push_back(dir->path().string());
            }
        }
    }

    if(filenames.size() > 0)
    {
        // Sort from 0 to N
        std::sort(filenames.begin(), filenames.end());
        std::vector<std::string>::iterator filename;
        for(filename = filenames.begin();
            filename != filenames.end();
            filename++)
        {
            cv::Mat img = cv::imread(*filename);
            result.push_back(img);
        }
    }
    return result;
}

int main(int argc, char* argv[])
{

    // Load images first since we need to know
    // the size of the image data for IMEM
    MyImemData data;
    data.mImages =
        GetRawImageData(IMEM_SOURCE_FOLDER);

    if(data.mImages.size() == 0)
    {
        std::cout << "No images found to render/stream.";
        return 0;
    }

    int w, h, channels;
    w = data.mImages.front().cols;
    h = data.mImages.front().rows;
    channels = data.mImages.front().channels();

    // You must create an instance of the VLC Library
    libvlc_instance_t * vlc;
    // You need a player to play media
    libvlc_media_player_t *mediaPlayer;
    // Media object to play.
    libvlc_media_t *media;

    // Configure options for this instance of VLC (global settings).
    // See VLC command line documentation for options.
    std::vector<const char*> options;
    std::vector<const char*>::iterator option;
    options.push_back("--no-video-title-show");

    char imemDataArg[256];
    sprintf(imemDataArg, "--imem-data=%#p", &data);
    options.push_back(imemDataArg);

    char imemGetArg[256];
    sprintf(imemGetArg, "--imem-get=%#p", MyImemGetCallback);
    options.push_back(imemGetArg);

    char imemReleaseArg[256];
    sprintf(imemReleaseArg, "--imem-release=%#p", MyImemReleaseCallback);
    options.push_back(imemReleaseArg);

    options.push_back("--imem-cookie=\"IMEM\"");
    // Codec of data in memory for IMEM, raw 3 channel RGB images is RV24
    options.push_back("--imem-codec=RV24");
    // Video data.
    options.push_back("--imem-cat=2");

    // If using RAW image data, like RGB24, then you
    // must specify the width, height, and number of channels
    // to IMEM. Other codes may have that information within
    // the data buffer, but RAW will not.
    char imemWidthArg[256];
    sprintf(imemWidthArg, "--imem-width=%d", w);
    options.push_back(imemWidthArg);

    char imemHeightArg[256];
    sprintf(imemHeightArg, "--imem-height=%d", h);
    options.push_back(imemHeightArg);

    char imemChannelsArg[256];
    sprintf(imemChannelsArg, "--imem-channels=%d", channels);
    options.push_back(imemChannelsArg);

    //options.push_back("--verbose=2");

    // Load the VLC engine
    vlc = libvlc_new (int(options.size()), options.data());

    // Create a media item from file
    media = libvlc_media_new_location (vlc, "imem://");

    // Configure any transcoding or streaming
    // options for the media source.
    options.clear();

    // Stream as MPEG2 via RTSP
    //options.push_back(":sout=#transcode{venc=ffmpeg{keyint=1,min-keyint=1,tune=zerolatency,bframes=0,vbv-bufsize=1200}, vcodec=mp2v,vb=800}:rtp{sdp=rtsp://:1234/BigDog}");

    // Stream as MJPEG (Motion JPEG) to http destination. MJPEG encoder
    // does not currently support RTSP
    //options.push_back(":sout=#transcode{vcodec=MJPG,vb=800,scale=1,acodec=none}:duplicate{dst=std{access=http,mux=mpjpeg,noaudio,dst=:1234/BigDog.mjpg}");

    // Convert to H264 and stream via RTSP
    options.push_back(":sout=#transcode{vcodec=h264,venc=x264,vb=0,vbv-bufsize=1200,bframes=0,scale=0,acodec=none}:rtp{sdp=rtsp://:1234/BigDog}");

    // Set media options
    for(option = options.begin(); option != options.end(); option++)
    {
        libvlc_media_add_option(media, *option);
    }

    // Create a media player playing environment
    mediaPlayer = libvlc_media_player_new_from_media (media);

    // No need to keep the media now
    libvlc_media_release (media);

    // play the media_player
    libvlc_media_player_play (mediaPlayer);

    boost::this_thread::sleep(boost::posix_time::milliseconds(60000));

    // Stop playing
    libvlc_media_player_stop (mediaPlayer);

    // Free the media_player
    libvlc_media_player_release (mediaPlayer);
    // Free vlc
    libvlc_release (vlc);

    return 0;
}
</code>
Answer: I know this question is very old, but I was searching for the same thing and it could be still useful.
If you are on Linux you could hack the system this way:
create a tmpfs partition and during your application startup just copy the files to the tmpfs partition.
Now you can load them from there


Is there a way to force postgresql to return repeatitive(duplicate) records for the repetitive ids in "IN" clause?

Question: The query goes like this
SELECT "students"."full_name" FROM "students" WHERE "students"."id" IN (1, 2, 3, 6, 785, 1, 2, 3, 785, 6)

Right now only 5 results are returned.
But I would like to get 10 results in a single query.
How can I do that?
Answer: It's not possible with an IN clause, but you can use a JOIN:
SELECT s.full_name
FROM students s
  JOIN unnest(array[1, 2, 3, 6, 785, 1, 2, 3, 785, 6]) as x(id) on s.id = x.id;

A more standard compliant version would be a values clause
SELECT s.full_name
FROM students s
  JOIN (
     values (1), (2), (3), (6), (785), (1), (2), (3), (785), (6)
  ) as x(id) on s.id = x.id;

Answer: The answer is "No", however, you can do something like that:
SELECT full_name
FROM "students" s
INNER JOIN (VALUES (1), (2), (3), (6), (785), (1), (2), (3), (785), (6)) v (id)
ON s.id = v.id

The sort order will be undetermined though.


How to copy the value of the click through the anchor and add this value through the input and remove?

Question: The code does not work the way I want it to. It is to copy the value of the click through the anchor and add this value through the input and remove. Can you help me? The code is for an interaction feature in the field. I'm creating a form and I'm trying to add this feature. My idea is ...
Explanation of idea and code with pseudo-algorithm
if (click) { remove input }
input. removed { step 1 }
Step 1 :: Now add this  1 anchor

if ( click ) {   if (step1) is 'correct'! {    else (copy text value) .create input   }  createinput 'is'   }   'is'  =  input.add {  ( add text value ) }

now: remove the anchor ^ step2 ^
Step 2 :: Now add this <input></input>
end-script

Translation 1

Remove input and add the anchor.
Add anchor and if (click)... add value of text in (input).
To add the input create a new input and then remove the anchor.

Translation 2
  HTML(Values.txt) is 'Presencial'
  HTML(Values.txt) is'Online'

  take.valueTXT ( Presencial, Online) = Text.content for Value.Input )

  'take.valueTXT' 'is' ( expression )

   '(expression)' 'is'  'rule'

   'rule' is $("#presencial,#online").text($('#inscricao').val(););

Translation 3
$(function()
{
    var find = $("#presencial, #online").text("");
    var add = $("#input").val("");
    var make = find to add;

   $('<input>').addClass('inscricao u-full-width').attr({id: 'inscricao'});

});

Translation 4
function myFunction() {
  var x = document.getElementById("#presencial,#online").innerText;
  var a = $("#inscricao").val();
  a = x;

Translation 5
$("#presencial,#online").text($("#inscricao").val();)

Translation 6
      $("#presencial,#online").click(function() {
       $("#presencial,#online").text( $("#inscricao").val(); )
       $("#presencial,#online").remove();
       $("input").add(); // add input
   });

Translation 7
document.getElementById("#presencial,#online").innerText;.$("#inscricao").val();

Errors, Source-Code
// script 1
$("#inscricao").one("click", function() {
    $('#inscricao').after('
PresencialOnline
');
    jQuery('#inscricao').remove();
});
// script 2
      $("#presencial").click(function() {
                    $("#presencial").val(function(c) {
                        $('#presencial').after('<input class="inscricao u-full-width" id="colegios" type="text" autocomplete="off" required/>');

/* var take = document.querySelector('#presencial').innerHTML; var adicionar = document.querySelector("#presencial").value = take;  */

                        var c = $("#inscricao").text();
                        return c.

                        jQuery('#presencial').remove();

                    });
                });

Reference

https://jsfiddle.net/pedroguilherme/e0b8jrpk/42/
https://jsfiddle.net/pedroguilherme/82Lbfac1/2/

IDEA
 var take = document.querySelector('#presencial').innerHTML; var adicionar = document.querySelector("#presencial").value = take;

Test1

$("#inscricao").one("click", function() {
  $('#inscricao').after('
PresencialOnline
');
  jQuery('#inscricao, #label1').remove();
});

$("#unidades").one("click", function() {
  $('#unidades').after('
RecifeJabatão
');
  jQuery('#unidades,#label2').remove();
});

$("#colegios").one("click", function() {
  $('#colegios').after('
CDF MasterMenino JesusEthos
')
  ;
  jQuery('#colegios,#label3').remove();
});
body {
  padding: 20px;
  font-family: Helvetica;
}

input,
label {
  padding: 10px;
  display: inline;
}

label {
  float: left;
}

a {
  padding: 20px;
  color: black;
  font-size: 16px;
  display: flex;
  margin: 20px;
}

a:hover {
  color: blue;
  font-weight: bolder;
  cursor: pointer;
}

Inscrição
<input id="inscricao">

Unidades
<input id="unidades">

Colégios
<input id="colegios">

Test2!
Source-code work now! enter code here;D
STEPS/ Translation 8!
// $().ready(function(e){}
$("#inscricao").one("click", function() {
    $('#inscricao').after('
PresencialOnline
');
    jQuery('#inscricao').remove();
});

$("#unidades").one("click", function() {
    $('#unidades').after('
RecifeJabatão
');
    jQuery('#unidades').remove();
});

$("#colegios").one("click", function() {
    $('#colegios').after('
CDF MasterMenino JesusEthos
');
    jQuery('#colegios').remove();

});

$("#presencial, #online").click(function() {
  var text = $( this ).text();
  $( "input" ).val( text );
});

$("#recife, #jabatao").click(function() {
  var text = $( this ).text();
  $( "input" ).val( text );
  <input class="nomecompleto u-full-width" id="nome" type="text" autocomplete="off" required>
});

$("#cdfmaster, #meninojesus, #ethos").click(function() {
  var text = $( this ).text();
  $( "input" ).val( text );

});

Steps of Source-Code

If(click) in input... this input: <input class="inscricao u-full-width" id="nome" type="text" autocomplete="off" required>

So... remove input and add anchor....! this anchor: PresencialOnline

If(click) in anchor "if (click) in anchor is each".... So... get value and add in input.<input class="inscricao u-full-width" id="nome" type="text" autocomplete="off" required>

KnowHow

I use   $("#inscricao").one("click", function() { $('#inscricao').after('
PresencialOnline
');jQuery('#inscricao').remove();});

Steps of 1

$("#inscricao").one("click", function() {

Describe: Get input with id and if (click)... one and... replace inscricao with id inscricao....
So example
 $('#inscricao').after('
PresencialOnline
');

jQuery('#inscricao').remove();

So example
 $("#inscricao").one("click", function() { $('#inscricao').after('
PresencialOnline
');jQuery('#inscricao').remove();});
Describe: I add click in input that remove input and add anchor.
Step Source-Code 2
$("#presencial, #online").click(function() {
  var text = $( this ).text();
  $( "input" ).val( text );
});

Describe: If click in anchor... So, add value text in input. 'Value text is value from here Presencial'... So, add value in input is 'Get value text in >Presencial< and add in input'
Problem

How return in input if I remove in Source-Code 1?

Solve!

Add after in anchor! But, How I add?

Problem and Describe

How I return in one input... if click one in anchor?
How Add two variables in one?

Example 1 and 2
$("#inscricao").one("click", function() {
    $('#inscricao').after('
PresencialOnline
');
    jQuery('#inscricao').remove();
$("#presencial, #online").click(function() {
  var text = $( this ).text();
  $( "input" ).val( text );
});
});

Describe: I trying this... But, no work :/
Problem
Describe: I trying one function with this... But, no work :/ Why?
Solve with the simple

Stop writing bad code! Stop being a kiddie script! Lol ... ^^

How?

Read http://api.jquery.com/val/#val-function
Read https://api.jquery.com/click/
Use concept val-function + click function

How?

$( "#multiple" ).val([ "Multiple2", "Multiple3" ]);

Describe: You have used id and get value inside options in select. Sorry, I no understand... and Calm!

So... Add this inside value as value input!

With this... you no remove input and add anchor and add new input and remove anchor!

How!?

I'm not stupid, I do not understand code! ;D

Step of Solve
1. $("#multiple").val(["Multiple2","Multiple3"]);
2. Add values of id #Multiple2, #Multiple3 if click in input!

Source-code
// set id and add ip select
 $("#presencial,#online").click(function() {
       $("#presencial,#online").text( $("#inscricao").val(); )

      // if click in select add value in input
        $("input").add(); // add input
   });

// I tried like this

// If I click in select... So... add value of select in input
$( "#Multiple2, #Multiple3" ).click(function() {
  var text = $( this ).text();
  $( "input" ).val( text );

});

// But, no work... I trying add $(this).prev('input').val("#Multiple2, #Multiple3").click;

Comment: Your first fiddle has a syntax error, check the JavaScript console.
Comment: Please use [Stack Snippets](https://stackoverflow.blog/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) instead of jsfiddle.
Comment: **Add anchor and if (click)... add value of text in (input).** Add the value where?
Comment: How does text get into the input? You can't type into it, because first you have to click on it, and that removes it.
Comment: You're just saying the same thing you wrote in the question. I didn't understand it the first time, I still don't.
Comment: Where should it add the value of the text of the anchor? You can't add it to the input, because you removed the input.
Comment: `new_input.val($(this).text())`
Comment: You have `this.form`, but there's no form in your HTML. The `form` attribute only works on inputs, not anchors.
Answer: You can use the replaceWith() method to replace the anchor with an input. Use $(this).text() to get the value of the new input.
Use event delegation to write the event handler for the anchors, rather than putting onclick attributes in each of them. See Event binding on dynamically created elements?

$(document).on("click", "a", function() {
  $(this).replaceWith($("<input>", {
    value: $(this).text()
  }));
});

$("#inscricao").one("click", function() {
  $('#inscricao, #label1').replaceWith('
PresencialOnline
');
});

$("#unidades").one("click", function() {
  $('#unidades,#label2').replaceWith('
RecifeJabatão
');
});

$("#colegios").one("click", function() {
  $('#colegios, #label3').replaceWith('
CDF MasterEthos
');
});
body {
  padding: 20px;
  font-family: Helvetica;
}

input,
label {
  padding: 10px;
  display: inline;
}

label {
  float: left;
}

a {
  padding: 20px;
  color: black;
  font-size: 16px;
  display: flex;
  margin: 20px;
}

a:hover {
  color: blue;
  font-weight: bolder;
  cursor: pointer;
}

Inscrição
<input id="inscricao">

Unidades
<input id="unidades">

Colégios
<input id="colegios">
Comment: I don't know jsPDF, I can't help you with that.
Comment: Use a class to specify the anchors that should have this special behavior, and change `"a"` to `"a.class"` where `class` is the class name you've chosen.


Can you setup a PS3 without a controller?

Question: I have just bought a used PS3 to use as a streaming media player. I've also bought a PS3 Blu-Ray remote (the one that looks like a TV remote) to use with it.
The PS3 I bought didn't come with a PS3 controller.
I've just powered the PS3 on, and got the setup screen asking me to plug a controller in via USB:

Is there any way to get past this screen without a PS3 controller?
Comment: Also, I've heard about some people having success with using a USB keyboard on that screen. Either way, you'll need *something* to do the setup... You might just want to buy the cheapest used controller you can get your hands on (or borrow one).
Comment: It's been many years since I've done this, but I believe the reason it wants you to plug in the controller is that new controllers need to sync with new systems. Are there any instructions with the remote that say how to sync it?
Comment: I'm not sure about the PS3 media controller but as far as I remember the PS2 one functioned as a controller and you could actually use it in games however dumb it was to do that. So just try that maybe?
Comment: @DangerZone have added picture of screen. The BD remote instructions talk about going to the PS3's XMB menu to pair the remote, which would presumably need me to get past this setup screen. I've got a USB keyboard and tried plugging in and pressing every key - the keyboard is recognised (e.g. Caps lock light goes on and off) but nothing seems to emulate the "P" key that the PS3 wants...
Comment: In that case, your best bet might be to pick up a used one on eBay/Amazon/craigslist. I'd be surprised if you couldn't get one under $15-20 at this point. And besides, you can get some pretty sweet games for cheap on the PS3 and a controller will come in handy ;)
Comment: @awidgery I assume you've already tried pressing the PS key on the remote, just under the directional keys and above select/start? It seems painfully obvious, but you haven't mentioned trying that yet, per Probst's analogy with the PS2 remote.
Comment: @recognizer Yeah I tried that - nothing. But the issue is that I think the remote uses Bluetooth (not IR) to communicate with the PS3 so it will need pairing up for anything to work
Comment: Pretty sure the windows key is the PS button on a keyboard
Comment: @Probst interesting - the windows key is the only one that does anything at all - but all it does is show a "No entry" symbol at the top right of the screen...
Answer: After many helpful suggestions it doesn't look like there's any way you can do this.
I tried:

HDMI-CEC: This isn't enabled on the PS3 by default (confirmed in the menu system when I finally did get in) and no key on my TV remote had any impact on the PS3
USB keyboard: No keys had any effect, except the Windows key, and all this did was show a "no entry" symbol
Using the Bluray remote itself: Doesn't work as it uses Bluetooth to communicate with the PS3 and can't be paired with the PS3 until you're in the PS3's menu system (the BD remote has no mini USB port like a Dualshock controller does which presumably allows the Dualshock to communicate with the PS3 before the Bluetooth pairing happens).

In the end I borrowed a controller from a friend for all of 1 minute - all it took to complete setup, get into the PS3 menu, and pair the BD remote.
Answer: Try doing an HDMI-CEC control, that might be able to get you far enough to be able to pair the remote. I don't know what the PS button would be, but it might be worth a try
Comment: Tried every key on the TV remote for the Sony TV the PS3 is plugged into. None of them seem to have any effect...
Answer: I plugged in a wireless mouse to the usb port and used it to navigate the screen.  Got the controller programmed in a few minutes.  Worked great.
Comment: Can the OP get past the screen he posted an image of using a wireless mouse?


How to calculate the PDF of a multi-lobe BSDF

Question: In PBRT, a BSDF is represented as an array of BxDF lobes. Each lobe sets a bitflag representing what kind of lobe it is. (Specular, Diffuse, Reflection, Transmission, etc.) I'm investigating how PBRT implemented sampling a BSDF for an input direction, wi.
Following standard Monte Carlo sampling, I was expecting the code to randomly sample an appropriate lobe, then set the $pdf = pdf_{picked}/n$ where $n$ is the number of lobes of the appropriate type. However this isn't what PBRT does. My question is why? To go in futher, this is the PBRT function:
Spectrum BSDF::Sample_f(const Vector3f &woWorld, Vector3f *wiWorld,
                        const Point2f &u, Float *pdf, BxDFType type,
                        BxDFType *sampledType) const {
    // Choose which _BxDF_ to sample
    int matchingComps = NumComponents(type);
    if (matchingComps == 0) {
        *pdf = 0;
        if (sampledType)
            *sampledType = BxDFType(0);
        return Spectrum(0);
    }
    int comp = std::min((int)std::floor(u[0] * matchingComps), matchingComps - 1);

    // Get _BxDF_ pointer for chosen component
    BxDF *bxdf = nullptr;
    int count = comp;
    for (int i = 0; i < nBxDFs; ++i)
        if (bxdfs[i]->MatchesFlags(type) && count-- == 0) {
            bxdf = bxdfs[i];
            break;
        }

    // Remap _BxDF_ sample _u_ to $[0,1)^2$
    Point2f uRemapped(std::min(u[0] * matchingComps - comp, OneMinusEpsilon),
                      u[1]);

    // Sample chosen _BxDF_
    Vector3f wi, wo = WorldToLocal(woWorld);
    if (wo.z == 0)
        return 0.;
    *pdf = 0;
    if (sampledType) *sampledType = bxdf->type;
    Spectrum f = bxdf->Sample_f(wo, &wi, uRemapped, pdf, sampledType);

    if (*pdf == 0) {
        if (sampledType) *sampledType = BxDFType(0);
        return 0;
    }
    *wiWorld = LocalToWorld(wi);

    // Compute overall PDF with all matching _BxDF_s
    if (!(bxdf->type & BSDF_SPECULAR) && matchingComps > 1)
        for (int i = 0; i < nBxDFs; ++i)
            if (bxdfs[i] != bxdf && bxdfs[i]->MatchesFlags(type))
                *pdf += bxdfs[i]->Pdf(wo, wi);
    if (matchingComps > 1)
        *pdf /= matchingComps;

    // Compute value of BSDF for sampled direction
    if (!(bxdf->type & BSDF_SPECULAR)) {
        bool reflect = Dot(*wiWorld, ng) * Dot(woWorld, ng) > 0;
        f = 0.;
        for (int i = 0; i < nBxDFs; ++i)
            if (bxdfs[i]->MatchesFlags(type) &&
                ((reflect && (bxdfs[i]->type & BSDF_REFLECTION)) ||
                 (!reflect && (bxdfs[i]->type & BSDF_TRANSMISSION))))
                f += bxdfs[i]->f(wo, wi);
    }

    return f;
}

In pseudo-code, it looks to be doing the following:
// Get the number of lobes that match the ones we asked for
numMatchingLobes = NumComponents(type);

// Early out check
if (numMatchingLobes == 0):
    return

// Randomly pick one of the matching lobes
pickedBxDF = Rand()

// Transform wo from world space to local space
// Then sample the chosen BxDF to get f, pdf, and wi
f, pdf, wi = pickedBxDF.sample_f(woWorld.ToLocal())

// Early out check
if (pdf == 0):
    return

// Transform wi to world space
wiWorld = wi.ToWorld()

// Add all of the pdfs of the matching lobes if the picked BxDF wasn't specular
if pickedBxDF.type not Specular && numMatchingLobes > 1:
    for BxDF in matchingLobes:
        pdf += BxDF.pdf(wi, wo)

// Divide the resulting pdf by the number of matching lobes
pdf /= numMatchingLobes;

// Calculate the combined f if the picked BxDF isn't specular
if pickedBxDF.type not Specular:
    // Reset f to zero
    f = 0

    // Add each BxDF's f, iff it matches reflection / transmission
    reflect = wo and wi on same hemisphere as geoNormal
    for BxDF in matchingLobes:
        // Add the
        if reflect and BxDF.type == Reflection:
            f += BxDF.f(wo, wi)
        elif !reflect and BxDF.type == Transmission:
            f += BxDF.f(wo, wi)

The part I'm not understanding is why it adds the pdf's of all the matching lobes on top of the already calculated pdf. This seems like it would double count the pdf of the picked lobe.
For example, if there are two matching lobes, called A and B. A is picked.
We calculate f, pdf, and wi with A. Then with a for loop, we add the pdf for A and B and divide by 2. Aka:
$$
\frac{A + A + B}{2}
$$
This doesn't seem right. Is PBRT code wrong? Should it be resetting the pdf, similar to the f calculation code below it?
Answer: The summation doesn't include the BxDF that was picked for sampling. Look again at this line:
if (bxdfs[i] != bxdf && bxdfs[i]->MatchesFlags(type))

Here bxdf is the one that was sampled earlier, so when it iterates to that one it skips it.


Wireless n-networks in Ubuntu 13.04 and WICD

Question: I just installed Ubuntu 13.04 on my Lenovo E530 laptop, and found myself having trouble connecting to the company's wireless network which uses the n-standard. I have no trouble connecting to g-networks.
After roaming the forums I found an advice to install the wicd network manager. I did so, following the instructions at Install wcid network manager. After rebooting I was asked to enter my password with the reason that "Wicd needs to access your computer's network cards". But my password was rejected as being incorrect.
After roaming some more I think I found that it wants the root password. But AFAIK the default Ubuntu setup has no such thing. In addition, the failure to give a satisfactory password is responded with a complete freeze of the entire interface, except for the mouse. I had to Alt-Ctrl-F1 out, remove wicd and reboot to be able to ask this question.
Additional info:
$ lspci | egrep -i network
03:00.0 Network controller: Intel Corporation Centrino Wireless-N 2230 (rev c4)

Any help, in particular to my original problem of being unable to connect to an n-network, is highly appreciated.
Comment: It's a bug: https://bugs.launchpad.net/ubuntu/+source/wicd/+bug/1132529  I doubt Wicd will enable you to connect to an N network any easier than Network Manager. Intel products with the iwlwifi driver are indeed tricky. Does your employer also have G available? If you disable N can you connect to G? sudo modprobe -r iwldvm; sudo modprobe -r iwlwifi; sudo modprobe iwlwifi 11n_disable=1
Comment: @chili555: Thanks. I have no trouble connecting to G the way it is now, it's just that I was told that N is more stable, and therefore wanted to make that work. So if `wicd` does not help me with that, I guess I don't need it. Do you know if my problem is due to a bug in the iwlwifi driver then? And if there is any fix/alternative?
Comment: That is a matter of debate. Some card/iwlwifi driver/router combinations, including mine, have no trouble whatever with N speeds. Others are just impossible. Since this is your employers network, you can probably not log on to the settings page of the router and fiddle with settings until it works. Frankly, I find N no more or less stable, but that may be due to the fact that are very few other networks in range at my home. If it were me, I'd disable N permanently, remove Wicd and be done. If you need guidance, post back.
Comment: Ok I will do that. However, when I run the second or third command that you gave, I get the error:`Error: missing module name.
FATAL: Error running remove command for iwlwifi`
Comment: Please try: lsmod | grep iwl. In 13.04, the iwldvm or iwlmvm module needs to be unloaded first. Remove whatever you found. If not iwldvm, then do: sudo modprobe -r iwlmvm; sudo modprobe -r iwlwifi; sudo modprobe iwlwifi 11n_disable=1. If you then connect, we can write a conf file to make it permanent.
Comment: Hm it keeps telling me that the module name is missing, or that the module is not found. If it doesn't hurt to just leave the settings as they are, I think I will just do that? Anyway, thank you for your help. If you make it an answer, I will accept it.
Answer: Please verify that your driver is iwlwifi.
lsmod | grep iwl

If you wish to disable N speeds in order to connect seamlessly, add to one file:
gksudo gedit /etc/modprobe.d/iwlwifi.conf

At the end of the file, add a new line:
options iwlwifi 11n_disable=1

Proofread, save and close gedit. After a reboot, you should be all set. If you are able to connect to home and work networks without any issues, this is not necessary.


How do I easily and inexpensively fix a crack developing in the stone front of my house?

Question: I think the picture says it all.  Is there some type of ready-to-go filler that can be purchased?  Naturally, it would be great to match the color of the mortar some how.  Many thanks]1
Comment: If you don't fix the cause of the crack, it will just crack again. Of course, that's less likely to be quick, inexpensive, and/or easy.
Answer: Your picture IS worth a thousand words! Is the stone a fascia or veneer in front of the bearing wall? Or is the stone the actual foundation for the structure? That's a window sill in the photo? Lastly, how old is the stonework? If it's just a façade of stone you may be able to reason the crack developed from settling. But it would be wise to monitor it. But to repair the gap start by removing loose pieces by hand (specifically that one in the middle). Then check each stone is still fastened and secured in place. Do this by grasping and attempting to move each one (again by hand). The second stone from the top left might come loose. If any are loose get a batch of mortar ready. With a cold chisel Gently chip away the old mortar from the joints on either edge of the crack. The idea is to develop a space along the crack line for fresh mortar. It will be difficult, but try not to loosen any stone. Brush or vacuum  out any dust. You should now have a wider gap running the length of the old crack! With a bucket of water and a sponge moisten the surrounding area. Mix a batch of mortar with enough water so that it will remain in place when troweled into the gap. The ideal tool for this type of work is a 'joint striking tool' and a pointed trowel. Work your way up from the bottom pressing mortar in the gap with the pointed trowel until it is full. Every 6 inches or so switch to the joint striking tool (which is concave in profile) and press the still moistened mortar level with the surrounding original mortar. For best results let the mortar cure out of direct sun light so it doesn't dry to fast. After it has set up for a couple of hours keep it moist for the same reason. The slower it cures the stronger it will be. Mortar straight from the bag and mixed with enough water will usually appear much lighter when cured. Some what silvery to grayish in tone. The mortar in your photo has been wiped with a sponge. Probably to clean any splotches from the stone and/ or for appearances. You can do the same after it sets up in an hour or so.
Comment: Thank you!  Everyone on this site is incredibly knowledgeable and helpful.  I definitely have some decisions to make on what to do (short-term vs long-term, myself vs professional).
Comment: Your welcome. I hope you found the information provided for your answer helpful. If so, as per Stack Exchanges instructions to all new members.."Voting is central to our model of providing quality questions and answers..". So it would help others whom might have a similar question if you  voted for any answer you found helpful.
Comment: Good answer, and great details.  For a little more ambitious DIY'er, this is certainly the way it needs to be done.
Answer: Most mortar is about the same color, so you have a good chance of a close match.  You can purchased premixed mortar repair in a tube for a calking gun like this product:
Quickrete Mortar repair
Comment: Awesome, thanks.  I can appreciate the crack could happen again, but just looking for something to bandaid it before winter. Perfect answer.


What does \D do in Perl regular expressions

Question: In some code I am maintaining, I have found the expression:
$r->{DISPLAY} =~ s/\Device//s;

What surprises me is that it matches both device and Device!
I have not found any mention of \D in the documentation, only \d.
Can someone clarify please...
Comment: I'd call this an "incorrect" use of `\D` rather than an "obfuscated" use... That regex will also match "crevice", "Levice", and even "#evice", not just "device" and "Device".
Comment: It's also useful to know that you run `perldoc perlre` on your command line, or go here: http://perldoc.perl.org/perlre.html.
Comment: You almost certainly want a case-insensitive match (`s/Device//si`) rather than this obfuscated use of `\D`...
Comment: Reading the rest of the code (not shown), it appears that a case sensitive match is needed with "Device". I think the stray "\" is a cut and paste error. Thanks for the help :-)
Answer: \D is the negation of \d, i.e. it matches anything that is not a digit.
Comment: @Roger If you like sepp2k's answer, you should click the checkmark to the left, to signify that this answer answered your question.
Comment: @Roger If you meant to checkmark sepp2k's answer, I believe you made a mistake.. you put the checkmark on my answer.
Comment: @TLP: Don't complain! You did the more helpful answer, got the accept. That's the way the system works.
Answer: In that regex, \D looks like a typo. It works for both d and D, only because it matches any character that is not a digit (0-9).
A more appropriate regex (if the intent is to match "device" or "Device"), is:
s/(d|D)evice// # one way
s/[dD]evice//  # another way

The s option is also a bit odd. From perldoc perlop
s   Treat string as single line. (Make . match a newline)

And there is no such matching going on in that line.
Comment: Yes, I think the '\' was a cut and paste error, as a match with Device was required...
Comment: Strange copy/paste error.. it does not seem to belong there in any context I can think of, except perhaps from a windows path, e.g. "c:\Device"...
Answer: You already have an answer, However, there's documentation in perldoc perlrecharclass about it. See the information about Backslash sequences.
It's also mentioned in perldoc perlrequick and in the regular perldoc perlretut under Using character classes. However, in those two sections, it's rather buried.


Finding vertices of a polytope?

Question: Assume that in 3D we have a polytope defined by the intersection of halfspaces.
A half space is the set of all solutions of a linear inequality $P = N \cdot x + c \leq 0$ Where $N$ is the normal to the half space.
The polytope is thus the boundary of $\cap_{i=0} P_i$ $P_i = N_i \cdot x + c_i \leq 0$.
In 3D all vertices must be intersections of at least 3 planes. i.e. all vertices are a subset of all points such that:
$$P_i = P_j = P_k = 0$$
Which is a trivial 3x3 system that can be easily solved.
However, the total number of points that you get out of this is exponentially larger than the actual number of points on the polytope.
For example in this diagram:

The top plane intersects the other 2 at points which are not vertices of the polytope.
Comment: I am not sure what the figure means here. My understanding is that in this figure, the normals of these planes form linear relationship. Since normal is orthogonal to any given line on that plane, so we know the intersection of two planes defines a line of which the direction can be calculated by the cross product of two normals. Since all three normals are on the same plane (due to linear relationship), the intersection lines will be parallel to each other, so the system has no solution thus no vertex. When these lines are exactly the same, then you will have infinite number of solutions.
Comment: So If I understand correctly, you can check the determinant of the 3x3 system before solving for the vertex. If the determinant is 0 (or its absolute value is extremely small), there won't be a good solution for you.
Comment: @Enigmatisms I perhaps was unclear, you have arbitrarily many of these planes, not just 3 and you are looking for the vertices of the underlying polytope.
Comment: There is no question !
Comment: "is exponentially larger ": it can very well turn out that all points that are the intersection of $d$ hyperplanes are indeed vertices of the polytope !
Answer: (I'm going to use the word "polyhedron" instead of "polytope" because I haven't considered how to generalize it to more dimensions.)

Being constructed of the intersection of half-spaces, the polyhedron must be convex; the interior volume is a region containing none of the planes.

We can classify the intersection points of 3 unequal planes as follows:

There cannot be an intersection point within the polyhedron, because per (1), none of the planes intersect the polyhedron.
If it is on the surface, then it must be a vertex; it cannot lie on an edge or face because if it did, that would contradict the 3 planes defining a point.
If it is outside the polyhedron, then it must not be a vertex.

If an intersection point lies within the outside half of any one of the half-spaces making up the polyhedron, then it cannot be inside or on the surface of the polyhedron per (1), and therefore cannot be a vertex per (2).

If an intersection point does not lie within the outside half of any half-space, then it cannot be inside per (1), so it must be on the surface of the polyhedron, and therefore per (2) must be a vertex.

Therefore, it suffices to discard all intersections which are outside any one of the half-spaces.
This can be seen as applying the separating axis theorem to the points; every plane defines a potential separating axis.
Answer: You can use an incremental approach.
In 3D, it works as follows:

Assume that as some point you have constructed the (possibly open) polytope defined by the $k$ first planes.

Consider the next plane and change the coordinate system so that the equation simplifies to $z=0$.

For every edge of the polytope, check if the endpoints belong to the same half-plane defined by the plane ($z$ sign).

If both have $z>0$, keep the edge; if both have $z<0$, discard the edge; otherwise, compute the intersection point of the edge with the plane and trim the edge. Finally, join the intersection points to form a convex section polygon.

Repeat with the remaining planes.

This method cannot avoid the $O(n^3)$ behavior in the worst case (no method can) but if you are lucky it can keep the number of useless vertex computations to a low value. (At best, $O(nm)$ intersections for $n$ planes and $m$ vertices in the solution.)

Finding vertices of a polytope?


symfony output raw image

Question: in my php code, I get an image in a variable. e.g.:
$src_image=  imagecreatefromjpeg(my_jpeg_path);

I want to output it as an image. So i tried this:
$src_image=  imagecreatefromjpeg(my_jpeg_path);
header('Content-type: image/jpeg');
imgaejpeg($src_image);

But this leads me to an error. the header(..) is assumed a global header and the browser replies:
The image "http://localhost:8081/backend_dev.php/poster/makenew" cannot be displayed because it contains errors.

How do I fix it?
P.S.: I know I can save the image by fwrite and the use image tags but I'll prefer to know whether my method can be made to work.
UPDATE: at this time, I didn't need to see the image itself. I only needed to use the image in another page. in that case doing  worked fine. But later I investigated a little and I ended up learning
Symfony output image """Cannot modify header information - headers already sent by..."""
Answer: This:
imgaejpeg($src_image);

Is spelt wrong, unless that is just a typo here, that will be your problem. If it is just a typo here, then comment out the header line and the imagejpeg line and see if there are any errors being written, as that will cause an error in the jpeg rendering.
Comment: I was gonna discard this as a stupid answer but turns out it wasn't. Thanks. But still It doesn't show as an image. It shows some weird characters in some weird encoding. You know, the way an image file looks in a text editor. Some way around that?
Comment: @prongs It seems like you may have the header line commented out still, make sure it is still there and being executed. Without the header line, it is just plain text and spits out the binary data.

symfony output raw image


How does the wiring in this light hookup?

Question: I'm trying to install this light in my house, but I don't know how the wiring works for it. The light has a switch on the front of it that controls both bulbs and the switch has two black wires coming out of it.
Two of the wires coming from the bulbs were tied together.
Here's a picture of the wiring on the back of the light. Any ideas?
Comment: That light is a fire hazard. Replace the sockets, switch and wiring with modern components.
Comment: Withdrawing my answer. I missed the point about the fixture having a switch. I really can't see enough from this photo to say anything about how that should be working. (The fixture may or may not also want to be rewired as @longneck suggests -- again, I don't think we can see enough from this photo to have a valid opinion. It certainly wants a new sleeve over the socket which is missing one.)
Comment: @longneck What makes this light a fire hazard?
Comment: The switch actually looks ok. But I see scorch marks on the braided wiring and on at least one of the bulb sockets.
Comment: Thanks for the comments, guys. Why is the light a fire hazard? The switch is on the front of the light and connected by the two black wires.

I'm not sure how to hook the wires up to the wall, however, or why the two white wires coming out of each light are bundled together. My assumption is that the two banded together connect to the white wire in the wall and somehow one of the black wires joins with a white wire and that connects to the black wire in the wall, but like I said that's only a guess. Definitely don't want to burn the house down experimenting...
Answer: Time to break out the multi-meter.  You can safely assume the two black wires from the switch are interchangeable.  But the white wires from the lamp sockets are not.  Cut that blog off that connects the two and test each side.  The outer metal ring needs to be the neutral and the center tab the hot.  Use the multi-meter to see which wire has continuance from either the ring or center tab.  Wire both center tabs (of the light socket) to one of the black wires from the switch.
To then wire the light to the wall.  The other black will then be wired to the hot (black) and the two free whites will be wired to the neutral.
Answer: Almost certainly was meant to be wired with hot to the two blacks, which run through the switch, and then the neutral to the two unbound whites.
But a several commenters said there are a number of concerns with what you show:

Scorch marks
A missing insulating sleeve for one of the bulb sockets
No clear ground connection, unless that's what the other two coupled white wires are for, in which case that's unusual.  Not to mention whatever that blob binding the two whites is looks suspicious.


cascaded dropdown prepopulate knockout MVC

Question: I am on the Update details screen and I have a Country and a state dropdown .I want to pre populate State dropdown on the basis of the selected Country.
On the initial page load I do have the selected Country,Country Collection and Selected State all I need is to fetch the State Collection using AJAX.
Country List: <select id="CountryDropdownList" data-bind="options: viewModel.CountryCollection,optionsText:'CountryName',optionsValue:'CountryName',value:viewModel.SelectedCountry"></select>
State List: <select id="StateDropdownList" data-bind="options: viewModel.StateCollection,optionsText:'StateName',optionsValue:'StateName',value:viewModel.SelectedState"></select>

But when I try to fetch the state list through AJAX request the Selected State value gets reset and the first value in the list becomes the default selected value. I am confused, why does KO update my selected State value when I am not changing it at all?
But if I set the Selected State again in AJAX Success callback it works fine
viewModel.SelectedCountry.subscribe(function (newSelectedCountry) {
            alert(newSelectedCountry);

            $.ajax({
                url: 'Home/GetStateList?Country=' + newSelectedCountry,
                success: function (data) {
                    viewModel.StateCollection(ko.mapping.fromJS(data.StateCollection)());
                    viewModel.SelectedState(data.SelectedState);

                }
            })
        });

I am looking for a reason for this strange behavior.
Comment: check you check logging the same thing before ajax call and see the o/p,
Comment: I just checked the value before the AJAX call and it is giving as undefined any idea what is going wrong here?
Comment: can anyway you can setup a fiddle which reproduces your issue . try moving `applyBindings` to `document.ready` code inside  and remove `viewModel.SelectedCountry.valueHasMutated();`  and try it
Comment: If I remove viewModel.SelectedCountry.valueHasMutated() then the subscription is not fired on load this is just to tell ko that this value has changed so fire the subscription
Comment: `viewModel.SelectedCountry.valueHasMutated()` you are calling on observable which is not needed (internally if there is a change it do the same) .
Comment: yes there should not be a need to add this method since we are using observable but the problem is that my ViewModel  initially has the country list so for KO there is no change in the value it is just initial binding so it is not firing the subscription method on it's own . For this reason I added the valueMutated method to make the subscription fire on load.
Comment: provide a jsfiddle which reproduces your issue. Building a view-model based in a string sent by the server is not a good practice. try to avoid this
Comment: Sure I will try to provide a Fiddle but may I ask why is it a bad practice?
Answer: I have tried simplifying the code as directed by you and now I think it might help you to point out the issue.

Comment: I am sorry but I have mentioned in the comments the value of selectedState it is still getting reset  to State0 after the ajax call. Any idea why?


How would I set an objective to 0 in 1.11

Question: How would I set an objective to 0 using the scoreboard command if it is possible?
My command so far is:
<code>/scoreboard objectives
</code>
But when I press tab after that it shows a list of what could be there, saying "add, list, remove, setdisplay" but it doesn't say set.
I know I have done this in one of my other maps but they were in 1.8 and I'm using 1.11 now.
Answer: You are confusing objectives and players. A scoreboard is not a value, or a variable. It cannot store a number. What you really want to do is set the value of a player on the scoreboard.
<code>/scoreboard players set [player] [objective] [value]
</code>
For example:
<code>/scoreboard players set @p locations 1
</code>


How do I fix scratches from sanding drywall?

Question: I've never sanded drywall/spackle before so I don't know what is acceptable or not. I'm remodeling my bathroom and have put down a few layers of spackle. Everything looks good and I just wanted to touch it up with some sanding.
I'm using a 220-grit screen and it's leaving small scratches behind. It looks worse than it did before I  touched it! I'm not pressing particularly hard.
Is this normal? Does primer fill these small gaps? Or should I go get a finer grit? I checked the big box stores online and it seems 220 is the finest they carry, so I'm guessing these scratches are normal.
I was going to sand all the spackle, now I'm thinking I'll just search around for ridges and sand them down, and leave everything else alone.

Click for full size image
Comment: Does primer fill these small gaps?  I would put some primer on a small area that is already sanded to test for suitability.
Comment: FYI the big box stores in my area cary 320 grit, but I really don't think you'd need it for this application.
Answer: Wet Sanding
If you want a smooth surface, you could try wet sanding it.  Purchase a drywall sanding sponge (~$4.00 at any home improvement store), and use that for the final sanding pass.

Fill a bucket with water.
Dunk the sponge in the water, and then wring it out to remove as much excess water as possible.
Using a light circular motion, buff the compound to a smooth finish.

Alternatively, you could purchase this 3M drywall sanding sponge.

In has both medium and fine grade on one sponge, and it can be used wet or dry.  Similarly, use this sponge in a light circular motion.
Personally, when I'm patching drywall I tend to use a damp microfiber cloth for my finish sanding.
Comment: +1 for the damp cloth idea. After sanding, I often just 'buff' it with a damp (not wet) plain ol' car washing sponge. A light touch and a bit of dampness smooths it all out fairly well.
Answer: It is hard to tell from the picture but I am guessing you are using a traditional screen and you are moving the screen back and forth along one of the axes of the screen. If the less than stellar ascii art below is your screen, instead of instead of moving N-S or E-W move the screen NE-SW or NW-SE. Or start with the screen rotated 45 degrees and continue to sand N-S or E-W
<code>+--+--+--+--+--+--+--+
|  |  |  |  |  |  |  |
+--+--+--+--+--+--+--+          N
|  |  |  |  |  |  |  |        W + E
+--+--+--+--+--+--+--+          S
|  |  |  |  |  |  |  |
+--+--+--+--+--+--+--+
</code>
A lot of times primer and paint will fill in these tiny scratches and most people will not notice even if the scratches are not filled in completely. But since it is your house and the scratches bother you go ahead and try the diagonal movements.
Comment: Thanks!! I just finished one pass and after a while I think I ended up doing what you said, but only coincidentally. I'll do another quick pass using your suggestion tomorrow to get rid of anything left behind.


WebView scroll up automatically when scrolling it down little

Question: In web view when I scroll the page little bit down then it scroll up automatically on some pages not all pages but on some pages.Why this happen and what is it solution
Here is xml code
<android.support.design.widget.CoordinatorLayout android:id="@+id/nonVideoLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    >
<android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/swipeContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    >
    <WebView
        android:id="@+id/webView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         />
</android.support.v4.widget.SwipeRefreshLayout>
</android.support.design.widget.CoordinatorLayout>

Here is my code you can check this
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        bindLayout();
        mySwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                webView.reload();
            }
        });
        CookieManager.getInstance().setCookie(url, cookie);
        webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
        ProgressDialogHelper.showProgress(WebViewActivity.this);
        webView.setWebViewClient(new WebViewClient(){

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);

                return true;
            }

            @Override
            public void onPageFinished(WebView view, final String url) {

                mySwipeRefreshLayout.setRefreshing(false);
            }
        });

            webView.loadUrl(url);

    }

Here is my java code I set the cookie also to web view and I set also layer type. I search that everyone says to set layer type then this problem solved but it does not solved.
Comment: put java code, i think its happening because of SwipeRefreshLayout, when you scroll down SwipeRefreshLayout event onRefresh got Fired.
Comment: so how I can overcome this
Comment: I added the code
Comment: webView.getSettings().setLoadWithOverviewMode(true);
any specific reason for using above line?
Comment: no I just copy and paste it from stack overflow
Comment: after removing this the problem is still same
Comment: wait, let me check first
Comment: I even remove the swipe to refresh widget but I get even same
Comment: remove these too
  webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
Answer: try this
final WebSettings settings = mWebView.getSettings();
settings.setDomStorageEnabled(true);
settings.setJavaScriptEnabled(true);
mWebView.setVerticalScrollBarEnabled(false);

Comment: try to remove all of this

    CookieManager.getInstance().setCookie(url, cookie);
        webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
Comment: removing .setLayerType(WebView.LAYER_TYPE_SOFTWARE, null); is okey for everything
Answer: Just remove
webView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);

all others are OK
Answer: try this in AndroidManifest.xml
set android:hardwareAccelerated="true" in the application and activity tag.


How do I make my Django dropdown form show items owned by a user and not all users?

Question: I am having trouble displaying items owned only by specific users, rather than each user getting to see all items in my database. Below is an example of a non-superuser who has access to all items in my database when this user should only have access to the ones they created
image of dropdown menu with all items instead of just some
Below are the Form, View, and Models I have created in attempt to do this.
forms.py
class RoutineForm(forms.ModelForm):
"""creates a form for a routine"""
class Meta:
    model = Routine
    fields = ['workout']
    labels = {'workout': 'Workout'}

Here is the views.py
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect, Http404
from django.urls import reverse
from django.contrib.auth.decorators import login_required
@login_required
def routine(request):
    """display a dropdown of all workouts for a user"""
    if request.method != 'POST':
        form = RoutineForm()
    else:
        form = RoutineForm(data=request.POST)
        if form.is_valid():
            new_routine = form.save(commit=False)
            new_routine.save()
            return redirect('index')
    context = {'workouts':workouts, 'form':form}
    return render(request, 'routine_workouts_app/routine.html', context)

and finally, the models.py file
from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class Workout(models.Model):
    """A workout group the user will use to workout"""
    text = models.CharField(max_length=200) #titles should not be too long
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        """Return a string representation of the model"""
        return self.text

class Routine(models.Model):
    """Shows a routine"""
    workout = models.ForeignKey(Workout, on_delete=models.CASCADE)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return 'this is a routine'

Am I missing some sort of filter? Something Fundamental? I have been able to filter some other views that I have made. For example:
@login_required
def workouts(request):
    """This is the page that will display all the workout groups"""
    workouts = Workout.objects.filter(owner=request.user).order_by('text') #filter by user ownership
    context = {'workouts': workouts}
    return render(request, 'routine_workouts_app/workouts.html', context)

on line 4 of this snippet, I have successfully filtered items that only belong to a specific user. But this is not a form, just a display on an html file. I have tried to put a similar line in the routine view function but it did not work. Any suggestions?
Answer: You can add a parameter to the constructor of the RoutineForm, that will filter the queryset specified to link to a Workout. This thus means that the form looks like:
class RoutineForm(forms.ModelForm):
    """creates a form for a routine"""

    def __init__(self, *args, user=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['workout'].queryset = Workout.objects.filter(owner=user)

    class Meta:
        model = Routine
        fields = ['workout']
        labels = {'workout': 'Workout'}
In the view, we then can construct a Form where we pass the logged in user to the constructor of the form:
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect, Http404
from django.urls import reverse
from django.contrib.auth.decorators import login_required

@login_required
def routine(request):
    """display a dropdown of all workouts for a user"""
    if request.method != 'POST':
        form = RoutineForm(user=request.user)
    else:
        form = RoutineForm(data=request.POST, user=request.user)
        if form.is_valid():
            form.instance.owner = request.user
            new_routine = form.save()
            return redirect('index')
    context = {'workouts':workouts, 'form':form}
    return render(request, 'routine_workouts_app/routine.html', context)
Comment: Thank you, it seems to be working properly now!


How to fix the ClassNotFoundException in Android

Question: I have tried to implement TabHost on android for few days and I am stuck on one error. I deleted my core tabhost code, I still have same error. I think it is my manifest.xml. Base on my error msg, I look up the source manifest but I couldn't find it.
Error
E/AndroidRuntime(32386): Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.FragmentLayout" on path: /system/framework/com.google.android.maps.jar:/data/app/com.sysdisc.mobile.hangmessage-1.apk
Code
public class AA extends FragmentActivity{
private ListView inboxList;
private ListView outboxList;
private ListView listView1;
private ListView listView2;
ProgressDialog dialog;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    dialog = new ProgressDialog(this);
    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    dialog.setMessage(getString(R.string.pleaseWait));
    dialog.setTitle(R.string.loading);
    setContentView(R.layout.message_history_entire_layout);
    }
}

This is my xml
 <?xml version="1.0" encoding="utf-8"?>
<TabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tabHost"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:padding="5dp" >
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />
        <FragmentLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:padding="5dp">
           <ListView android:id="@+id/list1" android:layout_width="fill_parent"
          android:layout_height="wrap_content" android:layout_weight="1">
      </ListView>
        <ListView android:id="@+id/list2" android:layout_width="fill_parent"
                android:layout_height="wrap_content" android:layout_weight="1">
            </ListView>
       </FragmentLayout>
    </LinearLayout>

Answer: Go to your

project properties > Java Build Path > Order and Export >

Make sure com.google.android.maps.jar is selected.
Then clean and rebuild your project.
Comment: So I followed your solution. still have same problem.... should I give you the manifest.xml?
Comment: No it's not a problem with the manifest. Make sure android private libraries is clicked. And any external jar you're using is clicked in Order and Export.
Comment: Also after you selected maps.jar and did a clean did your error message change?
Comment: Yes Yes  I did.
I just found out that the error  indicates setContentView(R.layout.message_history_entire_layout);

on my log : Caused by: android.view.InflateException: Binary XML file line #20: Error inflating class FragmentLayout


How to get the unload result in Packed decimal format if the table column is in INTEGER formmat in the DB2 table?

Question: I have a one query explaind below....,
1.My DB2 table column is in INTEGER format (it has the date value in Julian date format - YYYYDDD)

2. After unload this date into a flat file, the result is in hexa decimal format.(4 bytes occupaid)

3. I have a requirement to compare this date with (Current Julian date+7days) and write the corresponding recods into a File.

4. So, when I am comparing the Hexa decimal Input date with Current Julian date+7days (DATE3P+7), I am getting MAxcc=0 but I am not getting required output.

5. What I identified the problem is that the input date should also be in packed decimal format.

Can anybody please let me know how to convert the table value in Packed decimal while unloading or please suggest alternate way to get it.
Ex:- 1. Unload Julian date (YYYYDDD) [After unload this will be in hexa decimal format].
     2. compare with Current Julian date +7 days.
        SORT FIELDS=COPY
        OUTFIL FILES=1,
               INCLUDE=(1,4,PD,LT,DATE3P+7)
        OUTFIL FILES=2,SAVE
Thanks in Advance, Rajasekhar Jannu.
Answer: Believe these alternate ways, work...

Instead of getting the date in hex type, unload it as date in YYYYDDD
format and the DATE3 will give you the julian date in YYYYDDD. Now
these both are in compatible format to compare and condition.
There are many scalar functions of DB2 to provide Julian date and as
well date in numbers. I believe DIGITS on JULIAN scalar function
would do...
Refer this DB2 Scalar Functions
If you couldnt unload the table in the way described above, another
way would be manipulating the unload file, so that date from hex
format needs to be converted into YYYYDDD numeric format using
DFSORT. Then DATE3 will help u to get one week old data. DFSORT
reference has been already shared.
Comment: Hi Raja anna. I tried with the scalar function DIGITS(Colun name) while unloading. I got the julian date in Digit format. It works fine for my requirement to compare the unload date with currenr date DATE3 in Sort. Thanks for this solution. Earlier I achieved this by converting the unload date to YYYYDDD format and again convert this date into YYYY-MM-DD. after that only I used to compare with current date DATE1.   I reduced 2 steps with your solution. Thanks again.    :-)


Undo accidental check-in with TFS

Question:
Possible Duplicate:
How to rollback in Visual Studio TFS?

I need to undo my check-in in TFS.
How do I go about?
where can i read up on how to do it please?
thanks
Answer: I found plenty of examples, i did not search for it correctly
How to rollback in Visual Studio TFS?
How do I rollback a TFS check-in?
Comment: it might nevertheless be usefull to put the answer here, because people might search for this topic on SO and be dissapointed that you have an answer but didn't share it ;-)
Comment: But if I rollback my changes then they are gone locally. I have accidentally checked in half my work.

Undo accidental check-in with TFS


Is it possible to see the content of game updates on Steam?

Question: I have automatic game updates enabled on Steam, but so far I haven't been able to find an easy way to see exactly what has been updated.
Is there a way to see the details of a game update on Steam, similar to how you would do it on the Apple App Store or on Google Play?
Comment: It depends on the game developer if they make this information public or not. Even on app store or google play you often see details like "various improvements" which tells you nothing. I think steam opted for giving  developers an option of not putting in some bla instead of description when they have nothing to say.
Answer:
Sometimes. It depends on if the game has released information about what has been updated. Some games are really good about it, others are not.
To view where it would be, go to your downloads page (Library > Downloads) and where the download is, you should see a view news link on the right hand side of the page. This takes you to the Steam News page for that game, and is where games would be able to share what has changed with recent updates. If there is a lot of news and you just want the changes, you can filter on the Product Updates category to see only items that notes changes made.

Note some games may use an external site or system for reporting this information, but this is the most centralized place for Steam.
Comment: I would like to add that you can also access that page directly from the game entry in the library itself, on the right side, the link "News" under LINKS. Often, such updates are also on the storefront page of the game itself.
Comment: Also, some developers post the patch notes on in the Steam Forums, but I guess you can count this as an 'external system'.
Comment: @user1301428 if you want to filter specifically to only see updates, you can use the "Product Updates" channel filter on the right hand side.
Comment: I guess this is the best we can get at the moment, although the News section is often filled with all kind of news related to the game but with no mention of recent updates.


awk script not able to change field separator

Question: I have the following script taken from here
#!/usr/bin/awk -f
{
    if ($0 ~ /:/) {
        FS=":";
        $0=$0;
    } else {
        FS=" ";
        $0=$0
    }
    print $3
}

input file
ONE 1 I
TWO 2 II
THREE:3:III
FOUR:4:IV
FIVE:5:V
SIX 6 VI
SEVEN 7 VII

my output
I
II

IV
V

VII

so my question is why is the 3rd field missing for some of the lines?
Comment: `$0=$0` is pointless. It doesn't force parsing line, you should normally use `$1=$1`.  However, it's not going to work in this case either.
Answer: you can set FS to both characters
$ awk -F'[ :]' '{print $3}' file

or
$ awk 'BEGIN{FS="[: ]"} {print $3}' file

you can move the section between the single quotes to a script file, if that's what you want.
Comment: but how do I do that in a script?
Comment: this reply IS a script sample. if it should be inside the quoted source, use BEGIN section like second example but there is no reason for in your sample source
Answer: awk '
{
    # force the FS
    if ($0 ~ /:/) FS=":"
     else FS=" "

    # force awk to retreat the field separation with "new" line content
    #  because this is done at the start of the loop once (so earlier than)
    #  new FS assignation
    $0 = $0

    # print the 3th field
    print $3
}
' YourFile

this is your original script adapted (difference are normaly not the source of your other result) tested on my aix and linux. Both give the 3th value correctly. On which system are you ?
Assuming your sample data structure (no mix of space or ":") you cna try (especialy for mac problem) using both separator at once via a class
awk -F '[: ]' '{ print $3 }' YourFile

Comment: im running the script on mac
Comment: another variant of the script is added in th reply
Answer: In AWK scripts, the record and field separators are used to split the next field.  That's why they're usually set in a BEGIN clause.
If you need to split the current based on the contents of the current field, you'll have to use the split function, e.g.
arr_len = split($0, my_array, /:/);
if (arr_len > 3) {
    print my_array[3]
} else {
    ....
}

I would suggest the following quick reference to help:
Shell Scripting Primer [How AWK-ward]
Comment: maybe u wanna take a look at the link that i have provided, it is possible to change it dynamically.
Comment: See the comment later on that page: "However, this behavior changed in later versions, so the above script no longer works. What happens is that once the FS variable is changed, you have to re-evaluate the fields by using $0=$0:".  So I guess you can technically do it without using `split`, but it doesn't work automatically.  Also, I suspect that the "$0=$0:" syntax may be non-portable, whereas explicit use of `split` is portable.
Comment: are u able to provide a working example? sorry im still learning some of the caveats of awk scripting.
Comment: Done, though there are examples of split in the link above.  :-)


How to use css to change  font size

Question: pre{font-family:cursive;font-style:italic;font-size:xxx-small}

How to change pre font size?
Answer: While the font-size cannot be changed for text directly inside pre tags, you can always wrap that text in another element (a span, for example) and change the font size of that element.
For example (this is inline-styles, but could be put in CSS if you wanted):

Blah blah
Multiple lines and no br's!
Oh yeah!

Comment: I almost didn't try this because I didn't think it could possibly work since the tag is inside the pre tag...but it does work (at least with the outlook html interpreter).  Thanks!
Comment: If you are using `<code></code>`, remember to set `pre code { white-space: pre; }` to preserve line breaks.
Comment: I've found this incredibly helpful when emailing powershell text output to a teams channel (need the preformatted so you don't lose column spacing + need a smaller font) +1
Answer: Your issue is probably due to Courer being used as the default font, if you set Courier New as the preferred font it should be fine.
The following works fine in both Firefox & IE
pre {
   font-family: "courier new", courier, monospace;
   font-size: 11px;
}

Answer: If you only need to change the font size once, you can write

    ...

Comment: In Chrome it did change the font size, but "added" (?) significant spacing in between the lines, more or less nullifying the effect.
Answer: Take a look here:
PRE - preformatted text
HTML  tag

You cannot change font size within a
  PRE element (and you cannot put a PRE
  element inside a FONT  element, for
  example), but the BASEFONT element
  affects preformatted text, too.
Comment: Second link is dead :(
Comment: @Jankapunkt the page changed extension from .asp to .html. :) Thanks for the hint.
Comment: it's always best to post an actual response (even copy/paste) instead of just the link to external resources, because websites and blogs may have a shorter life than stackoverflow
Answer: One solution to fixing font size on pre tags is to use:
pre
{
    white-space: pre-wrap !important;
}

This fixes font sizes on mobile browsers, which cannot accurately determine the width of a pre element.
Source: Font size of pre tag on mobile devices gets too big – a fix
Answer:
Here is the  Demo
I am not quite sure why my browsers (chrome, FF, IE) doesn't agree!
Please let me know if I am missing something.
HTML

Test

css
pre {
    font-size: 100px;
    font-family: "Times New Roman", Times, serif;
    font-style: italic;
}

Chrome

Firefox

IE
Answer: Sorry for digging up an old issue. After searching high and low for "why browsers (specially mobile browsers) renders
 tags text too small and unreadable", I found as suggested here, changing css font-size: to em helps. But the gotcha is em for
 effects size differently on desktop browser then on mobile brower. A clear discrepancy noticeable on android Samsung/Mozilla/Chrome increase in font-size less for the same value of em then desktop browsers. The solution to this dilemma is to use % instead of em.
The css rule pre{font-size:200%;} seems to enlarge
 text more consistently (compare to other texts) on mobile browser as it does on desktop browser.
Answer: I think it can have something to do with the standard fonts supported by different browsers. Try your code in different browsers but remember IE is not W3 compatible.
Answer: I'm not sure if it's the right way to do it, but this worked for me in Firefox:
font: normal 11px Verdana, Arial, sans-serif;

How to use css to change  font size


Install error (--site-dirs) python 2.6 and setuptools

Question: i can't install setuptools on my nas.
i have this error :
LeGrappin> python2.6 setup.py build
running build
running build_py
LeGrappin> python2.6 setup.py install
running install
error: /opt/local/lib/python2.5/site-packages (in --site-dirs) is not on sys.path
LeGrappin>

Any idea ?
Answer: It's warning you that the place it is getting installed to will not be a place where python loads modules from.
To check which directories are, simply start python, then run
import sys; print sys.path

That should give you all directories that do work.  You may have to override the installation prefix as an argument to install.


Javascript onClick pass php string variable

Question: I have this php code snippet and i want to pass string in onclick function. if i just add php variable it will print the string as 3rd argument but sending me error undefined "String Value".
 $mydata_rankings .= "[  \"$captainId\" ,\"$captain_name\", \"$phone\"
 ,\"$email\", \"$points\", \"$rank\", \"Approve\"], ";

The 3rd argument $rank is string first 2 are numbers so no problem.
HTML output:
 Approve

Comment: What is the expected output? `php` runs on the server-side, while `javascipt` runs only on the client-side..
Comment: @Ahmad the onclick function should run. its not running because its a string i think i have to send string with single quotes ?
Comment: Can you show the HTML result of this code?
Comment:  Approve
Comment: `$mydata_rankings .= "[  \"` - what is that supposed to be - poor man's JSON? Don't assemble stuff like this manually - create the proper data structure, and then use `json_encode`!
Comment: @misorude this is not json its a php array with different values...
Comment: No, that is _not_ an array, it is a _string_ value. (And the content of that string appears to be JSON, which again, should not be assembled manually.)
Comment: @misorude any solution with current code ?
Comment: Why? This is absolutely trivial to rewrite using an array and json_encode - and it will be less error prone then, because json_encode will take care of encoding special characters according to JSON syntax, that you might otherwise miss.
Answer: The problem is that the Gold might not be defined.
You may have wanted it to be string, so enclose $rank between single quotes.
onclick='updaterank($captainId,$points,$rank)'

change it to:
onclick='updaterank($captainId,$points,\'$rank\')'

here is the complete code:
$mydata_rankings .= "[  \"$captainId\" ,\"$captain_name\", \"$phone\"
 ,\"$email\", \"$points\", \"$rank\", \"Approve\"], ";

Comment: I have tried '$rank' but it displays $rank as 3rd argument.
Comment: @DanishJamshed I have updated my answer to force `php` to substitute the value of `$rank`
Comment: Thanks Ahmed for your help but for some reasons this isn't working as well. i will share the html generated with your code.
Comment:   this is the html with your code
Comment: where does the `=` appear from? You need to fix the php code to prevent adding more that valid javascript function call. @DanishJamshed
Comment: not sure from where its coming = the variable contains Gold in it


dplyr: comparing values within a variable dependent on another variable

Question: How can I compare values within a variable dependent on another variable with dplyr?
The df is based on choice data (long format) from a survey. It has one variable that indicates a participants id, another that indicates the choice instance and one that indicates which alternative was chosen.
In my data I have the feeling that a lot of people tend to get bored of the task and therefore stick to one alternative for every instance. I would therefore like to identify people who always selected the same option from a certain instance onwards till the end.
Here is an example df:
set.seed(0)
df <- tibble(
    id = rep(1:5,each=12),
    inst = rep(1:12,5),
    alt = sample(1:3, size =60, replace=T),
)

That looks like the following:
   id     inst alt
1   1        1   3
2   1        2   1
3   1        3   2
4   1        4   2
5   1        5   3
6   1        6   1
7   1        7   3
8   1        8   3
9   1        9   2
10  1       10   2
11  1       11   1   <-
12  1       12   1   <-
13  2        1   1
14  2        2   3
...

I would like to create two new variables count and count_alt. The new variable count should indicate how often the same value appeared in alt based on id and inst, only counting values from the end of id. So for participant (id==1) the count variable should be 2, since alternative 1 was chosen in the last two instances (11 & 12). The count_alt would take the value 1 (always the same as inst == 12)
The new df schould look like the following
 id     inst   alt   count   count_alt
1   1        1   3       2           1
2   1        2   1       2           1
3   1        3   2       2           1
4   1        4   2       2           1
5   1        5   3       2           1
6   1        6   1       2           1
7   1        7   3       2           1
8   1        8   3       2           1
9   1        9   2       2           1
10  1       10   2       2           1
11  1       11   1       2           1
12  1       12   1       2           1
...

I would prefer to solve this with dplyr and not with a loop since I want to incooperate it into further data wrangling steps.
Answer: See if that solves it:
library(dplyr)

df %>%
  group_by(id) %>%
  mutate(
    count = cumsum(alt != lag(alt, default = "rndm")),
    count = sum(count == max(count)),
    count_alt = alt[n()]
  )

Output:
   id inst alt count count_alt
1   1    1   3     2         1
2   1    2   1     2         1
3   1    3   2     2         1
4   1    4   2     2         1
5   1    5   3     2         1
6   1    6   1     2         1
7   1    7   3     2         1
8   1    8   3     2         1
9   1    9   2     2         1
10  1   10   2     2         1
11  1   11   1     2         1
12  1   12   1     2         1
13  2    1   1     1         2
14  2    2   3     1         2
15  2    3   2     1         2
16  2    4   3     1         2
17  2    5   2     1         2
18  2    6   3     1         2
19  2    7   3     1         2
20  2    8   2     1         2
21  2    9   3     1         2
22  2   10   3     1         2
23  2   11   1     1         2
24  2   12   2     1         2
25  3    1   1     1         3
26  3    2   1     1         3
27  3    3   2     1         3
28  3    4   1     1         3
29  3    5   2     1         3
30  3    6   3     1         3
31  3    7   2     1         3
32  3    8   2     1         3
33  3    9   2     1         3
34  3   10   2     1         3
35  3   11   1     1         3
36  3   12   3     1         3
37  4    1   3     1         1
38  4    2   3     1         1
39  4    3   1     1         1
40  4    4   3     1         1
41  4    5   2     1         1
42  4    6   3     1         1
43  4    7   2     1         1
44  4    8   3     1         1
45  4    9   2     1         1
46  4   10   2     1         1
47  4   11   3     1         1
48  4   12   1     1         1
49  5    1   2     2         2
50  5    2   3     2         2
51  5    3   3     2         2
52  5    4   2     2         2
53  5    5   3     2         2
54  5    6   2     2         2
55  5    7   1     2         2
56  5    8   1     2         2
57  5    9   1     2         2
58  5   10   1     2         2
59  5   11   2     2         2
60  5   12   2     2         2

Comment: I like the approach, but it mutate(x = cumsum()) does produce the following error: Error in mutate_impl(.data, dots) :
  Not compatible with requested type: [type=character; target=double].


Copying data into array without use of array_agg() in POSTGRESQL

Question: I have read only access to a database in which I would like to aggregate string literals that belong to the same key. The Postgres database is not up to date and array_agg() is not supported, but I need them to be in an array for other purposes. I am currently copying data from that database into a csv file, and then need to copy from the csv file to my new database with array column type.
For example, what I have is:
author ... "BOOK1";"BOOK2";"BOOK3"

which results in
ERROR:  malformed array literal: "BOOK1"
DETAIL:  Array value must start with "{" or dimension information.

When I try to copy it from the csv to my database.
How can I can I get this in an array format without array_agg()?
Comment: You may want to post the expected output
Comment: Try this: https://dbfiddle.uk/?rdbms=postgres_8.4&fiddle=0b299077ebb1e0fbbb5799403db8abaa
Answer: You need to encapsulate the values with { and }` https://www.postgresql.org/docs/9.1/static/arrays.html
a="BOOK1,BOOK2,BOOK3"
print('{'+a+'}')

Comment: do I just need to write a script to manually add brackets to this column? there are about 40k rows so I don't know how efficient that would be
Comment: I do not have much experience with particular data type but documentation tells you to do so. Maybe use pandas do so.


Set a view's textbox (datetime field) to display readonly current datetime

Question: I have a textbox on my view and I'm only looking it to display the current date and time(in readonly..how can this be done?
Currently I have this in the view:

        @Html.EditorFor(model => model.Opened, new { @value = System.DateTime.Now, @readonly = "readonly" })
        @Html.ValidationMessageFor(model => model.Opened)

..And this in the model:
    [Required]
    public DateTime Opened
    {
        get;
        set;
    }

How can this be implemented in MVC?
Thanks,
Answer: I recommend you using a Label. I think it's unusual display dates and time at TextBoxes.
Regards.
Comment: Using `label` is not semantically correct as the  tag defines a label for an  element.
Comment: @StephenMuecke, I don't suggest the HTML label, if not the ASP.NET label ().
Answer: Well, you can do that, but @Angel Manuel Garcia Car's suggest is what you should be doing logically.
Anyways, here is the code. As long as you are creating a textbox, you should be using TextBoxFor.
@Html.TextBoxFor(model => model.Opened, new { @value = DateTime.Now, @readonly="readonly" })

I don't see any point here.


How to improve a scrollable dropdown section issue

Question: I have an issue where the overflow of a scrollable list on a website is cutting off my dropdown menu. The scrollable list has a height constraint because it is in a modal which has a set height and width.
The dropdown has about 11 items so it is fairly big, so any alternatives would have to accommodate for those items.
I have attached an image to help further explain the issue.
Comment: I don't quite catch your meaning. Did you mean that the first model consists of 11 items but because of the below list model it can now only show 4? And you want the first model not to be cut off?
Comment: Yes thats what I mean
Comment: Let us know what this UI screen is and what's in it. What are users supposed to be doing? What is in the scrollable list? What's in the other two sections?
Answer: The scrollable list needs to be above the layer of the modal, by that way it will expand above the modal containing it.

moreover it is not necessary that dropdown should expand below only, you can expand it from above also, as done in example


Does attracting Reapers to a Solar System only affect me?

Question: Scanning too much in a system attracts Reapers which case you. However, does attracting Reapers mean they only care about you or could attracting them to important solar systems actually cause harm to any planets/people in the game?
Basically, does attracting Reapers have any effect beyond the risk of a Game Over if they touch me?
Answer: No, the Reapers are already in control of these systems when you enter - scanning just draws attention to the Normandy.
If you scan too often, they'll pursue you, but they're already tearing it up in the system, so there's no additional risk to others.  If anything, you're distracting them slightly.
Comment: @BenBrocka, no, you do in some cases.  For instance, the Citadel's system is not Reaper controlled (at least as far as I've been in the game).  You can scan to your heart's content in that system and nothing will ever happen.  On the galaxy map, the Reaper controlled systems have a "Reaper" on top of their icons.  If there's no Reaper icon, there's no Reapers.
Comment: K, so I'll never have access to a solar system that isn't Reaper controlled?
Comment: Yeah, I know about the Citadel, but wasn't sure if any other systems would pop up.
Comment: @BenBrocka, I've seen at least a couple more, but to date I haven't found anything in the non-Reaper controlled systems by scanning.  I think the two mechanics go hand-in-hand, although I won't be able to confirm until I test it exhaustively.


Hibernate creates a SQL query

Question: Hibernate creates a SQL query looking for data from a database.table and SQL wants the request to be from [database.table]. how do I get Hibernate to put in the [ ]?
Comment: What do you mean with "SQL wants"? Do you mean "SQL **Server**" wants that format? Because in "*SQL*" `[` and `]` are invalid for object names.
Answer: The need for quoting database identifiers derives from the database used, some do, some don't; it is not SQL per se that "wants" this. So you need to set the correct database dialect then Hibernate will do this automatically if needed. In fact it is one of the benefits of Hibernate that you don't need to care for this differences.

Hibernate creates a SQL query


How can I see all tech tree nodes?

Question: I'd like to work towards some specific parts in the KSP Career/Science tech tree, but I have no idea where they are. Is there some setting in game (perhaps with a mod) or online resource I can use to show me everything to figure out what's where?
Answer: The official tree is on Wiki, under http://wiki.kerbalspaceprogram.com/wiki/Technology_tree - no surprise.
If you are using tree selection modules, then you must either read documentation for a mod, or do it good old way: Just play thorough all that technologies.

How can I see all tech tree nodes?


Selenium WebDriver getText

Question: I have a
0
.
I try to write a test that myDiv has 0 text in it. With WebDriver it is:
String text = webDriver.findElement(By.xpath("//div[@name='myDiv']")).getText();

But in the result I have an empty string. Shouldn't I use getText() for getting a content of a div?
Comment: Related: *[How to gettext() of an element in Selenium Webdriver](https://stackoverflow.com/questions/22087952)*
Answer: I had the same problem; a little digging brought me to this:
https://groups.google.com/forum/#!msg/webdriver/fRb_1QOr3wg/wzUsW3Ll6bgJ
HTMLUnitDriver (and apparently FirefoxDriver) will return empty strings when you try to call WebElement#getText() on elements whose CSS property 'display' is set to 'none'.
Here is my solution:
public void assertContainsText(final By by, final String value) {
    browser.waitTillElementPresent(by);
        Boolean result = new WebDriverWait(getWebDriver(),Browser.DEFAULT_WAIT_TIMEOUT_SECONDS).until(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver arg0) {
                WebElement elem = arg0.findElement(by);
                String text = "";
                if (elem.isDisplayed()) {
                    text = elem.getText();
                } else {
                  //have to use JavaScript because HtmlUnit will return empty string for a hidden element's text
                    text = (String) executeScript("return arguments[0].innerHTML", elem);
                    text = text.replace("

", "\n"); //scary
                }
                return text.contains(value);
            }
        });
        Assert.assertTrue(by.toString() + " contains value ["+value+"]", result);
}

Yes, it's ugly as sin.  And note the text.replace("

") - this is because HTML tags aren't escaped when you pull out the raw data.  The WebDriver will nicely 'unescape' this if you call #getText() on the element.
I've now put in a request to our IT guys to install X-Windows on our CI servers so we can run the FirefoxDriver.  We've had nothing but trouble from the HTMLUnitDriver, and it's incredibly slow to boot.
Answer: I just need use a real browser for my webDriver:
webDriver = new FirefoxDriver();

Then it works.
Maybe it is a JavaScript issue.
Comment: Though it is true that a Chrome or Firefox driver will work, do you know why the HtmlUnitDriver does not?
Answer: It sounds like you are using HTMLUnitDriver. In that case you would need to enable the JavaScript code like below.
HtmlUnitDriver driver = new HtmlUnitDriver();
driver.setJavascriptEnabled(true);

Check out the documentation here.
Comment: yes you are right, but it does not work, I use Qquery fadeIn() for tahte element - but event with setJavascriptEnabled(true) and with setting a wait(xxxx) it does not work.. so I prefer use Real browser instead.
Answer: In Selenium 2, I used this, and it works for me fine.
driver.getPageSource().contains(text);

Answer: You can use getText() even if it doesn't have any content. That should not be the issue.
From your answer, the issue seems to be that you didn't instantiate the FirefoxDriver.
Selenium WebDriver will only interact with visible elements, and therefore the text of an invisible element will always be returned as an empty string.
Answer: You can try using the jsoup library for parsing HTML.
First just load the page content (driver.getPageSource()) to the jsoup document object and use the richness of methods of that excellent library (kudos to the author).
Example:
String pageSource = driver.getPageSource();
Document doc = Jsoup.parse(pageSource);
Elements requestsListRecords = doc.getElementsByTag("table").get(2).getElementsByTag("tr");

Answer: You can also verify the text in the div by:
$browser.is_element_present("//div[@name='myDiv']/.[text()='0']")

Answer: Try this
WebDriver driver = new YourBrowserdirver(); //FirefoxDriver or ChromeDriver etc..
String Text = driver.findElement(By.id("myDiv")).getText();
System.out.println("The text present in myDiv = "+Text);

Selenium WebDriver getText


Screen flickers after installing Ubuntu 22.04

Question: I installed Ubuntu 22.04 with Windows 11 using Dual Boot on a Lenovo computer and when I log in the screen flickers, not being able to interact well with the OS.
The equipment has the following specifications: CPU: Intel i7-11370H 3.3GHz RAM: 16GB GPU: MX450 Display: 16.0" WQXGA Intel iRIS-xe. In Software & Updates I have checked the option: Using X.Org X server-Nouveau display driver from xserver-xorg-video-nouveau (open source).
Answer: It may be possible to remove the screen flickering by installing the proprietary Nvidia graphics drivers. Ubuntu has a built-in ubuntu-drivers program that can decide automatically which proprietary graphics driver to install, and streamlines the installation of Nvidia drivers. Open the terminal and type:
sudo ubuntu-drivers install
sudo reboot

The install option of ubuntu-drivers installs drivers that are appropriate for automatic installation including their dependencies. Don't uninstall the open source Nouveau graphics drivers. Leave them installed as a fallback option in case Ubuntu ever has problems booting.
Comment: The suggestion, given in many other places, to add to GRUB_CMDLINE_LINUX_DEFAULT the value "i915.enable_dc=0 intel_idle.max_cstate=2" failed to solve the problem for me.  What worked was to install appropriate graphics drivers as suggested here.  Thanks.
My setup, if it's helpful to anyone else:
Ubuntu 22.04.3
Kernel 18.104.22.168-generic
CPU Intel i7-10700F (16) @ 4.8GHz
GPU NVIDIA GeForce GT 730
Answer: Without any information about your hardware it's difficult to say, however the first port of call for graphics issues is to ensure there are no additional drivers available - including proprietary ones, which unfortunately are often a necessary evil.
Assuming you have already checked for driver updates using the "Software Updater" application, check the "Additional Drivers" application to see if there are any recommended.
If none are showing, ensure that "Proprietary drivers for devices (restricted)" option is enabled then check again.
In summary:

Open the "Software Updater" application to check for updates
If none found or you still have the issue, then;
Open the "Software & Updates" application, go to the "Ubuntu Software" tab
Enable the "Proprietary drivers for devices (restricted)" option
Run the "Additional Drivers" application to check for any applicable drivers

Failing all that you might need to seek more specific advice by searching for information related to your specific model of laptop.
Comment: Hello, thank you very much for your answer.
The equipment has the following characteristics:
CPU: Intel i7-11370H 3.3GHz
RAM: 16GB
GPU: MX450
Display: 16.0" WQXGA
Intel iRIS-xe

In "Software and updates" I have checked the option:
Using X.Org X server-Nouveau display driver from xserver-xorg-video-nouveau (open source)