Q: Dual monitor setup, why does NVidia 340 Prime only detect one monitor? I'm using:

*

*Alienware M14xR2 laptop running Ubuntu 14.04

*2 * DELL U2412M monitors attached via HDMI and Mini Display Port

*Optimus graphics (Intel + nVidia GeForce GT 650M) running with nvidea-340 and nvidia-prime, with Prime setup in nvidia-settings GUI to use the NVidia GPU

*built-in laptop monitor disabled

Unfortunately, the monitors only work successfully in the default mirrored setup - I have the following issues trying to get a dual external screen extended desktop to work:

*

*nvidia-settings GUI can only see one monitor on the X Server Display Config page. System Display GUI can see both displays but can only mirror the displays successfully. By fiddling with Display GUI and ARandR, I temporarily managed to get an extended desktop working, but NVidia GUI still only sees one of the monitors and if I try to reboot with 2 monitors attached, the GUI is totally glitched and unusable after login.

*During boot, the system just uses the left monitor (via HDMI i/f) for display, so I presume this is treated as the primary display. However, after boot, it appears the system switches to using the Display Port for the primary display and the system will not let me have the Ubuntu launcher only on the left (HDMI) display. The only options that work are for having the launcher on both or just on the right (Display Port) monitor. I tried to forcefully fix the issue with the primary monitor incorrectly being set to the right monitor by changing the primary monitor switch in ~/.config/monitors.xml, however this does not work and causes both monitors to appear at strange resolutions and glitch badly with uncoordinated mouse input.

Running  /usr/lib/nvidia-340/bin/nvidia-xconfig --query-gpu-info gives
Number of GPUs: 1

GPU #0:
  Name      : GeForce GT 650M
  UUID      : GPU-...
  PCI BusID : PCI:1:0:0

  Number of Display Devices: 1

  Display Device 0 (DFP-0):
      EDID Name             : DELL U2412M
      Minimum HorizSync     : 30.000 kHz
      Maximum HorizSync     : 83.000 kHz
      Minimum VertRefresh   : 50 Hz
      Maximum VertRefresh   : 61 Hz
      Maximum PixelClock    : 170.000 MHz
      Maximum Width         : 1920 pixels
      Maximum Height        : 1200 pixels
      Preferred Width       : 1920 pixels
      Preferred Height      : 1200 pixels
      Preferred VertRefresh : 60 Hz
      Physical Width        : 520 mm
      Physical Height       : 320 mm

Running xrandr --query gives
Screen 0: minimum 8 x 8, current 3120 x 1920, maximum 16384 x 16384
DP-0 connected primary 1200x1920+1920+0 left (normal left inverted right x axis y axis) 518mm x 324mm
   1920x1200      60.0*+
   ...
DP-1 disconnected (normal left inverted right x axis y axis)
LVDS1 connected
   1600x900       60.0 +   40.0
   ...
DP1 disconnected
DP2 disconnected
HDMI1 connected 1920x1200+0+0 518mm x 324mm
   1920x1200      60.0*+
   ...
HDMI2 disconnected
VGA1 disconnected
VIRTUAL1 disconnected

Running lspci | grep VGA gives

00:02.0 VGA compatible controller: Intel Corporation 3rd Gen Core processor Graphics Controller (rev 09)
  01:00.0 VGA compatible controller: NVIDIA Corporation GK107M [GeForce GT 650M] (rev a1)

My xorg.conf is almost empty but I believe 14.04 automatically detects those settings.

A: Post-installation and removal Nvidia, I noticed a strange(and a good one at that) behavior. And that its that the GUI  response in the second monitor has become much improved.
And I also noticed that the xorg.conf has a different setting, pasting it for your reference,
jpvel@jpvel-M11xR3:~/Downloads$ sudo cat /etc/X11/xorg.conf.04192015

Section "ServerLayout"
    Identifier "layout"
    Screen 0 "nvidia"
    Inactive "intel"
EndSection

Section "Device"
    Identifier "intel"
    Driver "intel"
    BusID "PCI:0@0:2:0"
    Option "AccelMethod" "SNA"
EndSection

Section "Screen"
    Identifier "intel"
    Device "intel"
EndSection

Section "Device"
    Identifier "nvidia"
    Driver "nvidia"
    BusID "PCI:1@0:0:0"
    Option "ConstrainCursor" "off"
EndSection

Section "Screen"
    Identifier "nvidia"
    Device "nvidia"
    Option "AllowEmptyInitialConfiguration" "on"
    Option "IgnoreDisplayDevices" "CRT"
EndSection

I suspect that the existing nouveau driver seems to start honoring the configuration and appropriately instruct the graphics card to send the output to the external monitor. As
For those souls who tried using the DVI port or HDMI to VGA adapter, let me forwarn you, it does not work. As neutrino pointed out, the HDMI port is welded with Nvidia card in Alienware laptops
Edit from 2nd answer:
I went for the reinstallation and again tried using the latest Nvidia drivers from ppa:xorg-edgers/ppa for Nvidia-340, it ended up mucking the UI. So I decided to uninstall and live with the existing setup.
However, with the fresh installation, I am able to work with a dual monitor setup that is not perfect, but usable. I mirrored the displays and ensured that the intel's graphics driver could do the rendering(but it is lousy though I admit)

A: It seems that due to the unconventional way Dell wired up the 3 display ports, the Nvidia GFX and the on-board Intel GFX in the Alienware M14xR2, you cannot use HDMI and MDP for the external monitors. It is also not possible to disable the Intel GFX in bios as Dell wired up the Nvidia card to pass through the Intel card!
Using the HDMI and VGA ports for the monitors solves this issue and allows the use of an external dual monitor setup on Ubuntu 14.10 without mirroring.
However, at the time of writing, the Nvidia 340 and 346 series of drivers are not working for this dual monitor setup and will only work properly using just one monitor. Only Nvidia 331 series seems to support this dual setup (or Nouveau - but that driver shows a very noisy picture on the second monitor and its 3D acceleration does not work properly either). Bugs, bugs, bugs!


Q: Three.JS - AudioAnalyser() not working with audio source as Stream type in Safari I'm developing a streaming radio in 3D using Three.JS, I'm sending music as a PeerConnection to my clients attaching a THREE.AudioAnalyser() to display 3D bars that move according to frequencies.
Sound is working great in all platforms, but THREE.AudioAnalyser() with an input source of stream type only works on Chrome, Safari is not working at all :frowning:
var listener = new THREE.AudioListener();
var audio = new THREE.Audio( listener );
audio.setMediaStreamSource( stream );
audioAnalyser = new THREE.AudioAnalyser( audio, 128 );

function loop(){
    console.log(audioAnalyser.getFrequencyData());
}

The console.log() of the loop() function should contain an Array of Integers, on Chrome is all good, Safari logs [0,0,0,0,0,0,0,0]
What could be causing this issue? It seems to work everywhere but not on Safari, and also it only seems to fail when the source is a stream.

A: Not 100% sure, but you might want to connect the output of the AnalyserNode to the destination node.  You may want to stick a GainNode with a gain of 0 in between, just in case you don't really want the audio from the AnalyserNode to be played out.


Q: Remove unused source code files using eclipse/ Flash builder 4.6 i have a project having lots of file, around 4500 file in all Project. i separated it in 40 library project.Now my problem is that it taking too much time to Compile. so i increase a memory of Flash builder. This gives me little improvement to compile. i am sure that i have too much file which is not used in my project. so now i want to remove it by plug of Flash Builder / Eclipse. Because it is too much headache process to see that "xyz.as/mxml" file is used in any other file or if it is used in Other file say "abx.as/mxml" then again i have a question that "abx.as/mxml" is useful file or used in any other file. so you have any idea or hint please give me. Thanks in advance...

A: One thing you can try is to use the size-report of your flex compilation : flex compiler options
This way you will have an idea of which classes are really used in your libraries and therefore wich ones aren't because the flex compiler only link to classes you really need in your compiled swf.
This not ideal but it can avoid a lot of manual process pain.

A: Add this param to your compiler:
-link-report output.xml

this information will help you.

A: I'm not sure if it would work for flash-builder, but for Java there is the UCDetector.


Q: 1d numpy array with enough elements not resizing as expected I just started working with numpy arrays in conjunction with panda dataframes, and I am working on a practice project, but have hit a bit of a problem. I have a panda dataframe which I pass the rows of to a function to do some work on it. The function takes in two different arrays one labeled best and worst and then creates a new vector to compare sums against. From there it will return either the current array that the pandas.apply has passed or it will return the new vector based on which sum() is the lowest. This creates a new python array which needs to be a matrix of 20x5 at the end. The function works fine, but the returned dataframe needs to be converted to a python array of size (20 x 5) for further work, which when np.array() is called, it converts it into an array of size (20,). I figured just using .reshape(20,5) would work since it has enough elements to work with, but it does not, it just fails on run. Any help is appreciated as I can't find anything that's helping me understand why this is happening.
(the error, as many could guess by reading above, is: "cannot reshape array of size 20 into shape (20,5)" )
code except from my program that shows it (can run on it's own):
import numpy as np
import pandas as pd

rng = np.random.default_rng(seed=22)
df = pd.DataFrame(rng.random((20,5)))

def new_vectors(current, best, worst):
    #convert current to numpy array
    current = current.to_numpy()

    #construct a new vector to check
    new = np.add(current, np.subtract((rng.random()*(np.subtract(best, np.absolute(current)))), ((rng.random()*(np.subtract(worst, np.absolute(current)))))))

    #get the new sum for the new and old vectors
    summed = current.sum()
    newsummed = new.sum()

    #return the smallest one
    return np.add(((newsummed < summed)*(new)), ((newsummed > summed)*(current))).flatten()

z = np.array(df.apply(new_vectors, args=(df.iloc[0].to_numpy(), df.iloc[11].to_numpy()), axis=1))
z.reshape(20,5) #I know reshape() creates a copy, just here to show it doesn't work regardless

A: You can do the reshape manually.

*

*Delete z.reshape(20,5). This is not going to work with an array of arrays.

*After applying the function, use this instead:
# Create a empty matrix with desired size
 matrix = np.zeros(shape=(20,5))
 # Iterate over z and assign each array to a row in the numpy matrix.
 for i,arr in enumerate(z):
      matrix[i] = arr

If you don't know the desired size for the matrix. Create the matrix as matrix = np.zeros(shape=df.shape).
All the code used:
import numpy as np
import pandas as pd

rng = np.random.default_rng(seed=22)
df = pd.DataFrame(rng.random((20,5)))

def new_vectors(current, best, worst):
    #convert current to numpy array
    current = current.to_numpy()

    #construct a new vector to check
    new = np.add(current, np.subtract((rng.random()*(np.subtract(best, np.absolute(current)))), ((rng.random()*(np.subtract(worst, np.absolute(current)))))))

    #get the new sum for the new and old vectors
    summed = current.sum()
    newsummed = new.sum()

    #return the smallest one
    return np.add(((newsummed < summed)*(new)), ((newsummed > summed)*(current))).flatten()

z = np.array(df.apply(new_vectors, args=(df.iloc[0].to_numpy(), df.iloc[11].to_numpy()), axis=1))

matrix = np.zeros(shape=df.shape)

for i,arr in enumerate(z):
     matrix[i] = arr

A: Your original dataframe - with reduced length for display purposes:
In [628]: df = pd.DataFrame(rng.random((4,5)))
In [629]: df
Out[629]:
          0         1         2         3         4
0  0.891169  0.134904  0.515261  0.975586  0.150426
1  0.834185  0.671914  0.072134  0.170696  0.923737
2  0.065445  0.356001  0.034787  0.257711  0.213964
3  0.790341  0.080620  0.111369  0.542423  0.199517

The next frame:
In [631]: df1=df.apply(new_vectors, args=(df.iloc[0].to_numpy(), df.iloc[3].to_numpy()), axis=1)
In [632]: df1
Out[632]:
0    [0.891168725430691, 0.13490384333565053, 0.515...
1    [0.834184861872087, 0.6719141503303373, 0.0721...
2    [0.065444520313796, 0.35600115939269394, 0.034...
3    [0.7903408924058509, 0.08061955595765169, 0.11...
dtype: object

Note that it has 1 column, that contains arrays.  Make an array from it:
In [633]: df1.to_numpy()
Out[633]:
array([array([0.89116873, 0.13490384, 0.51526113, 0.97558562, 0.15042584]),
       array([0.83418486, 0.67191415, 0.07213404, 0.17069617, 0.92373724]),
       array([0.06544452, 0.35600116, 0.03478695, 0.25771129, 0.21396367]),
       array([0.79034089, 0.08061956, 0.1113691 , 0.54242262, 0.19951741])],
      dtype=object)

That is (4,) object dtype.  That dtype is important.  Even though the elements all have 5 elements themselves, reshape does not work across that "object" boundary.  We can't reshape it to (4,5).
But we can concatenate those arrays:
In [636]: np.vstack(df1.to_numpy())
Out[636]:
array([[0.89116873, 0.13490384, 0.51526113, 0.97558562, 0.15042584],
       [0.83418486, 0.67191415, 0.07213404, 0.17069617, 0.92373724],
       [0.06544452, 0.35600116, 0.03478695, 0.25771129, 0.21396367],
       [0.79034089, 0.08061956, 0.1113691 , 0.54242262, 0.19951741]])


Q: Sort a string property that is in a List(of class) In my database project, the user should have a search function.
The search results are saved in a List(of Class_Post). This list should now be sorted alphabetically.
I would like to add that I could already have used:
sorted.Sort(Function(x, y) x.compareto(y))
But the FxCopAnalyzer complained that the sorting could differ due to regional settings, so I now want to use String.Compare (x, y, StringComparison.Ordinal).
The property to be sorted is Class_Post.Ueberschrift. The error is at line 11 (sorted.sort(comparison)): Overload resolution failed because no accessible "Sort" can be called with these arguments:
"Public Overloads Sub Sort (comparer As IComparer (Of Class_Post))": "Option Strict On" does not allow implicit conversions from "Comparison (Of String)" to "IComparer (Of Class_Post)".
Dim sorted As List(Of Class_Post) = Ergebnisse.ToList()

        Select Case Suchmoeglichkeit
            Case Sortiermoeglichkeiten.Alphabetisch ' alphabetical (a String)

                Dim comparison As Comparison(Of String) =
                        Function(x, y)
                            Dim rslt As Integer = x.Length.CompareTo(y.Length)
                            Return rslt
                        End Function
                sorted.Sort(comparison)

            Case Sortiermoeglichkeiten.Erstellzeit 'Creation Time (a Date)
                sorted.Sort(Function(x, y) x.Erstelldatum_dieses_Posts.CompareTo(y.Erstelldatum_dieses_Posts))
            Case Else
                Exit Select
        End Select

        Return sorted

A: You don't want a Comparison(Of String) but a Comparison(Of Class_Post) and you want to compare the Ueberschrift.
Case Sortiermoeglichkeiten.Alphabetisch ' alphabetical (a String)
        Dim comparison As Comparison(Of Class_Post) =
                Function(x, y)
                    Dim rslt As Integer = StringComparer.Ordinal.Compare(x.Ueberschrift, y.Ueberschrift)
                    Return rslt
                End Function
        sorted.Sort(comparison)

A ListOf(Of Class_Post) can just be sorted with a Comparison(Of Class_Post).
Another approach which is easier to read and to maintain is LINQ:
Select Case Suchmoeglichkeit
    Case Sortiermoeglichkeiten.Alphabetisch ' alphabetical (a String)
        Return Ergebnisse.OrderBy(Function(x) x.Ueberschrift).ToList()
    Case Sortiermoeglichkeiten.Erstellzeit 'Creation Time (a Date)
        Return Ergebnisse.OrderBy(Function(x) x.Erstelldatum_dieses_Posts).ToList()
    Case Else
        Exit Select
End Select


Q: Algorithm for Background subtraction I am trying to implement a simple background subtraction method for the detection of moving objects in a particular scene. The objective is to kind of segment out a particular motion out of a video to use it in another video.
The algorithm i am following is:
1. Take the first 25frames from the video and average them to get a background model.
2. Find the standard deviation of those 25frames and store the values in another image.
3. Now i am calculating the absolute difference between each frame and average background model pixel wise.
The output i am getting is kind of a transparent motion being highlighted in white (the absolute differencing is resulting in the transparency i think). I want to know whether my approach is right or not considering that i will be doing a segmentation upon this output as next step? And also i am getting no idea as to how to use the standard deviation image. Any help will be appreciated.
Please let me know if this is not the type of question that i should post in stack overflow. In that case any reference or links to other sites will be helpful.

A: You should take a look at that blog. http://mateuszstankiewicz.eu/?p=189
You will find a start of Answer. Moreover I think there is a specific module for video analysis in Opencv.

A: You said it looks like transparent.
This is what you saw right?→ See YouTube Video - Background Subtraction (approximate median)

The reason is you use the median value of all frames to create the background.
What you saw in white in your video is the difference of your foreground(average image) and your background. Actually, median filtered background subtraction method is simple, but it's not a robust method.
You can try another background subtraction method like Gaussian Mixture Models(GMMs), Codebook, SOBS-Self-organization background subtraction and ViBe background subtraction method.
See YouTube Video - Background Subtraction using Gaussian Mixture Models (GMMs)

A: Try these papers:

*

*Improved adaptive Gaussian mixture model for background subtraction

*Efficient Adaptive Density Estimapion per Image Pixel for the Task of Background Subtraction


Q: Configure all Devise controllers to use a different layout? I have a Rails app which application layout is used to render an AngularJS app.  However, I would like that all the Devise controllers use another layout. I don't need Angular in there.
How can I tell Devise to use a different layout for all its controllers?

A: You probably should review this entry: How To: Create custom layouts.
More or less, you can set it via ApplicationController:
class ApplicationController < ActionController::Base
  layout :layout_by_resource

  protected

  def layout_by_resource
    if devise_controller?
      "layout_name_for_devise"
    else
      "application"
    end
  end
end

Or via configuration (config/application.rb):
config.to_prepare do
  Devise::SessionsController.layout "devise"
  Devise::RegistrationsController.layout proc{ |controller| user_signed_in? ? "application" : "devise" }
  Devise::ConfirmationsController.layout "devise"
  Devise::UnlocksController.layout "devise"
  Devise::PasswordsController.layout "devise"
end


Q: Оставить только строку заданной длины в файле в php Как оставить только строку заданной длины в файле?
$replaced=preg_replace("(\b((\S{0,8}))\b)", "",$replaced );

A: С помощью регулярного выражения
$str = "333 4444 55555 666666";
preg_match_all("/(\b\S{5}\b)/", $str, $matches);
var_dump( $matches );

результат

array(2) {                                                                                [0] =>                                                                                array(1) {                                                                                [0] =>                                                                                string(5) "55555"                                                                                }                                                                                [1] =>                                                                                array(1) {                                                                                [0] =>                                                                                string(5) "55555"                                                                                }
}

Без регулярного выражения
$str = "333 4444 55555 666666";
$words = explode(" ", $str);
foreach( $words as $word ) {
    if ( mb_strlen( $word ) == 5 ) {
        echo $word."\n";
    }
}

Хотя зачем я тут все это пишу, опять же набегут тролли, наставят минусов без объяснения причин...


Q: Image data transfer on drag and draw on canvas I am uploading an image from PC. Then I read the file with file reader and display image by creating an img tag. Then I drag the image from the img tag into the canvas and draw it onto canvas. I'm using dragstart and onDrop events. I use datatransfer.setdata() and  datatransfer.getdata() for the functionality. But on drop, the image drawn on canvas is not as original. It is a zoomed version. I don't know why is this happening!
Here is my code:
<!DOCTYPE HTML>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Drag Demo</title>
<link href="copy.css" rel="stylesheet" type="text/css" />

<canvas id = "canvas" style = "position:relative;width:1000px;height:1000px;top:0px;left:200px; border:2px  solid black;" ondrop="dropIt(event);" ondragover="event.preventDefault();"> </canvas>

    <input type="file" id="fileElem" accept="image/*" style="display:none" >

Select some files

A: With canvas there are 2 'size' settings:
Through CSS you'll set the DISPLAY size, so to set the PHYSICAL size of the canvas, you MUST use its attributes. So NO CSS/Style.
Think about it this way: you create a IMAGE with physical size: (let's say) 400px*400px.
Then just as a normal image (jpg,png,gif) that has a physical size, you can still choose to change the DISPLAYED size and thus aspect-ratio: like 800px*600px. Even % is normally supported.
Hope this explains clearly WHY this happened and why your solution in your comment is also the correct solution!!


Q: Argument 2 passed to Controller method must be in instance of Request, none given I'm trying to pass 2 dates from one view to another, in my controller, but I get the following error:
Argument 2 passed to App\Http\Controllers\GuestController::reservationToGuest() must be an instance of Illuminate\Http\Request, none given
This is my first view (the view having the date):
<form action="{{ route('create_guest') }}">
    {{ csrf_field() }}
    <input type="hidden" value="2016-08-26" name="dateOne">
    <input type="hidden" value="2016-08-28" name="dateTwo">
    <button class="btn btn-block btn-success">Proceed To Check In</button>
</form>

(dateOne and dateTwo are the dates which I want in the second view)
routes.php
Route::get('/guest_page/create/{idreservation?}',[
    'uses' => 'GuestController@reservationToGuest',
    'as' => 'create_guest'
]);

reservationToGuest in GuestController
public function reservationToGuest($idreservation = null, Request $request){
    if($idreservation === null){
        return view('guest_page_create', ['idreservation' => 0, 'page_title' => 'Guest Check In', 'check_in_date' => $request['dateOne']]);

    } else{ //else clause works just fine and the dates from the database are inserted into the view
        $details = DB::table('reservation')
            ->where('idreservation', $idreservation)
            ->get();

        return view('guest_page_create', ['idreservation' => $idreservation, 'details' => $details, 'page_title' => 'Guest Check In']);
    }
}

And in view 'guest_page_create'
<label for="datemask">Check In Date</label>
<input type="date" class="form-control" id="datemask" name="datemask" value="{{ $check_in_date }}">

A: You shouldn't pass optional parameters before required ones. Try this:
public function reservationToGuest(Request $request, $idreservation = null)
{
    // ...
}


Q: iOS 14 large titles not working properly when navigating between views Large titles disappear after navigating back and forth within the app. The large title is enabled but when navigating back, it becomes small again. This only happened when updating to iOS 14.


Q: Controlled database insert I have created a script that uses PDO database functions to pull in data from an external feed and insert it into a database, which some days could amount to hundreds of entries.. the page hangs until it's done and there is no real control over it, if there is an error I don't know about it until the page has loaded.
Is there a way to have a controlled insert, so that it will insert X amount, then pause a few seconds and then continue on until it is complete?
During its insert it also executes other queries so it can get quite heavy.
I'm not quite sure what I am looking so have struggled to find help on Google.

A: I would recommend you to use background tasks for that. Pausing your PHP script will not help you in speeding up page loading. Apache (or nginx or any other web-server) sends whole HTTP packet back to browser only when PHP script is completed.
You can use some functions related to output stream and if web-server supports chunked transfer then you can see progress while your page is loading. But for this purpose many developers use AJAX-queries. One query for one chunk of data. And store position of chunk in a session.
But as I wrote at first the better way would be using background tasks and workers. There are many ways of implementation this approach. You can use some specialized services like RabbitMQ, Gearman or something like that. And you can just write your own console application that you will start and check by cron-task.


Q: Node.js get actual memory usage as a percent I have used "os" http://nodejs.org/api/os.html#os_os To attempt to calculate some system stats for use in an app.
However I notice that it cannot actually calculate the memory properly, because it leaves out the cache and buffers witch is needed to properly calculate a single readable percentage. Without it the memory will almost always be 90%+ with most high performance servers (based on my testing).
I would need to calculate it like so:
(CURRENT_MEMORY-CACHED_MEMORY-BUFFER_MEMORY)*100/TOTAL_MEMORY
This should get me a more accurate % of memory being used by the system. But the os module and most other node.js modules I have seen only get me total and current memory.
Is there any way to do this in node.js? I can use Linux but I do not know the ins and outs of the system to know where to look to figure this out on my own (file to read to get this information, like top/htop).

A: Based on Determining free memory on Linux, Free memory = free + buffers + cache.
Following example includes values derived from node os methods for comparison (which are useless)
var spawn = require("child_process").spawn;
var prc = spawn("free", []);
var os = require("os");

prc.stdout.setEncoding("utf8");
prc.stdout.on("data", function (data) {
    var lines = data.toString().split(/\n/g),
        line = lines[1].split(/\s+/),
        total = parseInt(line[1], 10),
        free = parseInt(line[3], 10),
        buffers = parseInt(line[5], 10),
        cached = parseInt(line[6], 10),
        actualFree = free + buffers + cached,
        memory = {
            total: total,
            used: parseInt(line[2], 10),
            free: free,
            shared: parseInt(line[4], 10),
            buffers: buffers,
            cached: cached,
            actualFree: actualFree,
            percentUsed: parseFloat(((1 - (actualFree / total)) * 100).toFixed(2)),
            comparePercentUsed: ((1 - (os.freemem() / os.totalmem())) * 100).toFixed(2)
        };
    console.log("memory", memory);
});

prc.on("error", function (error) {
    console.log("[ERROR] Free memory process", error);
});

Thanks to leorex.
Check for process.platform === "linux"

A: From reading the documentation, I am afraid that you do not have any native solution. However, you can always call 'free' from command line directly. I put together the following code based on
Is it possible to execute an external program from within node.js?
var spawn = require('child_process').spawn;
var prc = spawn('free',  []);

prc.stdout.setEncoding('utf8');
prc.stdout.on('data', function (data) {
  var str = data.toString()
  var lines = str.split(/\n/g);
  for(var i = 0; i < lines.length; i++) {
     lines[i] = lines[i].split(/\s+/);
  }
  console.log('your real memory usage is', lines[2][3]);
});

prc.on('close', function (code) {
    console.log('process exit code ' + code);
});


Q: Serving express static files not working with bundle from webpack :( so I have a node/express app that serves back a bundle.js bundled by webpack.
I've been banging my head at this issue for close to 4 nights and I don't know anymore.
I'm getting the Uncaught SyntaxError: Unexpected token < error as the express static middleware is not catching the request and treating it.
webpack.config.js:
output: {
   path: BUILD_DIR,
   filename: 'bundle.js',
   // https://github.com/webpack/webpack-dev-middleware/issues/205
   // DO NOT leave publicPath out -- it'll cause errors if we do
   publicPath: '/',
},

express middleware:
var serveStatic = require('serve-static')
app.use(serveStatic(
   path.join(__dirname, 'statics'),
))
app.use('/dist', express.static('dist'));
app.use('/statics', express.static('statics'));\

index.html:
    <script src="bundle.js" type="text/javascript"></script>


Q: Calculating posterior of difference given posterior of two means I am using R and MCMCpack to do a Bayesian analysis of some data that I have.  I have generated posterior distributions (postDist) on the means of some parameters (y1,y2,y3) using MCMCregress (postDist <- MCMCRegress( x ~ y + z ,...)).
Now, I would like to take those posterior distributions on the means and generate a posterior distribution on the difference between the means.  Is that a reasonable thing to do in a Bayesian analysis, and if so, how do you do it (either in theory or in R)?

A: First, the method and theory, in brief: The goal is to approximate the target distribution $p(\theta|D)$  where $\theta$ is a vector parameter and $D$ is observed data, given some prior distribution $p(\theta)$. At each stage of the MCMC chain, the sampling algorithm proposes a new parameter vector $\theta$. (This process varies depending on the flavor of algorithm, and the proposal distribution.) Given a proposed $\theta$, it then computes the product $p(D|\theta_{proposed})p(\theta_{proposed})$, which by Bayes rule is proportional to the posterior distribution $p(\theta|D)$. It accepts the proposal with probability $max(\frac{p(\theta_{proposed})}{p(\theta_{current})},1)$. If a number of requirements are met, this chain will produce a representative sample from the posterior distribution. (In brief, it requires a proposal process that adequately covers the posterior distribution, proper burn-in, and convergence.)
If those requirements are met, one can view the MCMC sample as an approximation to the posterior. Each individual sample value is one sampled vector of values for $\theta$; likewise, differencing two sampled parameters over the entire sample produces an approximated distribution of the difference between the two parameters. (I'm not familiar with MCMCPack, but I gather from your code and comment that postDist[,"y2"] and postDist[,"y2"] are vectors of samples from the posterior, so this should work.) This is one benefit of MCMC methods: If the parameters covary, then solving for their sum or difference analytically depends on knowing their joint distribution.
By the by, I began learning Bayesian methods with Kruschke's Doing Bayesian Data Analysis, and I highly recommend his chapters explaining MCMC algorithms. It's a very approachable, intuitive treatment.


Q: javascript -I can't understand, why are the first two functions returning 'undefined' but the third one returns the desired value?
Addy(int c) : function to add all the digits of the number and repeat the sum only if it is a single digit. Else, repeat the process
  till it is a single number.

first function :
function addy(c) {
  c = parseInt(c);
  console.log('Recieved Number '+c);
  var sum;
  var nas = c.toString().split(''); // nas --> Number As String.
  console.log('Digits present in Number: '+nas);
  for (var i = 0; i < nas.length; i++) {
    sum = sum + parseInt(nas[i]);
  }
  console.log('Sum is: '+sum);
  if(sum < 9) {
    console.log(typeof sum);
    console.log('value of sum is: '+ sum);
    return sum;
  }
  console.log('Value Still not single digit.');
  addy(sum);
}

Algorithm(that I used in the first function.):

*

*Convert the given number to string.

*Get all the digits present in the numbers by using the split method on the string that has just been created from the number.

*Loop through all the digits, and add to sum.

*If the sum is single digit, then return and if it is not then repeat the process till the sum is single digit.
Second function :
  function addy(c){
     var s=0;
     while(c!==0)
     {
       s = s + parseInt(c%10);

       c = parseInt(c/10);
     }
     if(s>9)
     {
       s = addy(s);
     }
     else if(s<9)
     {
       return s;
     }
   }

Third function :
 (which actually works and is identical to the second function)
   function addy(num)
   {
    var sum = 0;

    while (num > 0)
   {
      sum += parseInt(num % 10);

      num = parseInt(num / 10);
   }
   if (sum > 9)
   {
      sum = addy(sum);
   }
     return sum;
   }

I want to know the reason why the first two functions are returning "undefined" instead of returning a single digit number.

A: First of all, your third function is not identical to your second function.
First function
Fixed code:

function addy(c) {
  c = parseInt(c);
  var sum = 0; // <------- THIS LINE
  var nas = c.toString().split('');
  for (var i = 0; i < nas.length; i++) {
    sum = sum + parseInt(nas[i]);
  }
  if(sum < 9) {
    return sum;
  }
  addy(sum);
}
console.log(addy(123));

Your original code has a line:
var sum;  // sum is undefined

Therefore, when the execution reaches this line:
sum = sum + parseInt(nas[i]);

sum will become NaN because that translate to:
undefined = undefined + parseInt(nas[i]);

To make it work, you simply need to initialise the value of sum:
var sum = 0;   // Give sum a default value;

Second function
Fixed code:

function addy(c){
  var s=0;
  while(c!==0)
  {
   s = s + parseInt(c%10);
   c = parseInt(c/10);
  }
  if(s>9)
  {
   s = addy(s);
   return s;     // <----- THIS LINE
  }
  else
  {
   return s;
  }
}
console.log(addy(1234));

In original code:
if(s>9)
{
  s = addy(s);
}
else
{
  return s;
}

Nothing is being returned if s > 9. Therefore you get undefined.
To make it work, you simply need to add a return line:
if (s > 9){
    s = addy(s);
    return s;    // <--- THIS LINE
} else {
    return s;
}


Q: Suggested Post and Taxonomy structure I am trying to work out the most sensible way to structure a new site. I would like to have continents, countries and articles. Articles will be the normal post type but I am unsure of the best way to setup the continents and countries.
I have played with setting up two new post types continent and country and have added a meta box to allow the country to associate itself with a continent. The URL structure is also what I want: /custom/continent/country
The trouble is how to efficiently associate posts to a country so that they can be queried at the continent and country level.
The other option I am trying is to setup two taxonomies, which is easier in terms of categorising the posts, but makes URL rewriting a pain. I'd also want to limit the post to being tagged with multiple continents and countries.
The posts will just use a regular permalink structure for now.
UPDATE: I am looking for a solution that does not use plugins please. I can already create custom post types or custom taxonomies.

A: CPTUI and add_rewrite_endpoint will help you get the desired things.
[Update] From my comment-
You need pairs for rewrite rule /base/1 or base/1/base2/2 using wordpress rewriting... and the way you want will not be that easy depending on wordpress. If you have fixed /custom/continent/country structure then add HTACCESS of your own as site/1/2/3 to yield  site/?continent=1&country=2&article=3. This will create global variable in wordpress environment to be queried anytime... :) Hope this helps.


Q: Return to where the user was, after log out I know how to direct logged out user to a particular page or a URL, like:
<a href="<?php echo wp_logout_url( home_url() ); ?>">Log out

But if I want the user to redirect to the URL where he/she just was, what can I do?
Though I'm not knowledgeable about wp_get_referer(), but I tried:
<?php $redirect_to = wp_get_referer() ? wp_get_referer() : home_url(); ?>
<a href="<?php echo wp_logout_url( $redirect_to ); ?>">Log out

and
<?php $redirect_to = $_SERVER['HTTP_REFERER'] ? $_SERVER['HTTP_REFERER'] : home_url(); ?>
<a href="<?php echo wp_logout_url( $redirect_to ); ?>">Log out

with no luck. :(
It's always taking me to the home_url().

A: You get the current path with remove_query_arg( '' ). Combine it with site_url(), and you have the full current request URI:
$url = untrailingslashit( site_url() );
$url .= remove_query_arg( '' );

Be aware that remove_query_arg() doesn’t return a sanitized value, so you have to use esc_url() if you want to print it to a page. Otherwise, someone could inject malicious code into your site in an URL parameter.
wp_get_referer() is for form submissions, it looks for a request parameter _wp_http_referer and is not relevant in your case.


Q: lxpanel launch bar icons are broken I'm using lxpanel on my Ubuntu 14.04 laptop and facing this issue. Trouble is that the launchbar on the panel isn't displaying icons for some apps (or rather, the icons being displayed are generic white ones with a red cross-mark in between).

As you can see in the above image, the third icon for the geany app is problematic and isn't displayed and the same happens if I put firefox in the launchbar. However, all other icons seem to be displayed properly. Also, its noteworthy that issue with geany/firefox icons is only in the launchbar, in the taskbar and the main menu, it is displayed properly. I've also ensured that geany icons exist in the /usr/share/icons folder. I've also tried changing the gtk themes using lxappearance, but it didn't do any good. Can someone help me with this?
EDIT
When I right-click on the icons and go to the launch-bar settings, I can see a selector dialog like this from where I chose geany/firefox, but I see no way to change the icon:

A: I successfully changed the icon as follows (I'll use Iceweasel for my example):
1.Check your home folder for the LXpanel configuration at ~/.config/lxpanel/LXDE/panels/panel for a block specifying the launchbar:
Plugin {
  type=launchbar
  Config {
    Button {
      id=/usr/share/applications/lxterminal.desktop
    }
    Button {
      id=/usr/share/applications/iceweasel.desktop
    }
    Button {
      id=menu://applications/Internet/icedove.desktop
    }
  }
}

2.We found where the iceweasel.desktop config file is located. Now we look at said file /usr/share/applications/iceweasel.desktop for the Icon line:
grep Icon /usr/share/applications/iceweasel.desktop
Icon=icewesael

3.We change it to our new icon (as root) e.g. the icedove icon using a full path entry, so now the line reads:
Icon=/usr/share/icons/hicolor/128x128/apps/icedove.png

4.Restart the panel
lxpanelctl restart

Now you just need to figure out where your specific missing icon is.


Q: JavaScript regular expression to remove comma in number comma number "12,56,7abc,fgh" ===> "12567abc,fgh"
"1,245abc,1a" ===> "1245abc,1a"
"1,2,3,4,5abc" ===> "12345abc"

How to remove comma in (number),(number) format?
For the test
const array = ["12,56,7abc,fgh", "1,245abc,1a", "1,2,3,4,5abc"]
const answer = ["12567abc,fgh", "1245abc,1a", "12345abc"]

function formatter(string){
   // here
   return // string.replace('', '') ??
}

array.map((el, i) => {
   const formatted = formatter(el)
   if(answer[i] === formatted){
      console.log('Success. formatted: ', formatted)
   } else {
     console.log('Failed. formatted: ', formatted)
   }
})

A: str.replace(/(?<=\d),(?=\d)/g, '')

(?<=\d): lookbehind - a digit
(?=\d) : lookahead - a digit


Q: Initialize multiple jQuery sliders programatically, each with a different onChange function I'll try and keep this straightforward. I am using jQuery sliders and trying to initialize them all at once using an array:
sliders.push(new slider('paletteControl','pSlider',0,255,100,sliderChange()));

function slider (context, id, min, max, defaultvalue, changeFunc) {
    this.context = context;
    this.id = id;
    this.min = min;
    this.max = max;
    this.defaultvalue = defaultvalue;
    this.changeFunc = changeFunc;

}
Where context is the ID of its intended parent div and changeFunc is the function I want it to call on change.
My Init function loops through this array and appends the markup according to the context, and then tries to init each jquery slider like so:
$(id).slider({
      range: "min",
      min: sliders[i].min,
      max: sliders[i].max,
      value: sliders[i].defaultvalue,
      create: function() {
        handle.text( $( this ).slider( "value" ) );
      },
      change: function() {
          sliders[i].changeFunc();
      }
 });

The min, max, and value inits work fine, presumably since they happen exactly once, during the init, but the change function fails pretty miserably, again presumably because it's simply trying to look up sliders[i] on each change (i being a long dead iterator by that point).
My question is - how can I programatically init a bunch of jquery sliders, each with a different onChange function? Without doing them manually, that is.
EDIT: Got some great help from Ramon de Paula Marques below, though in the end I had to do it a different way altogether because I was unable to pass a value to the function. What I ended up doing, for better or worse, was creating a wrapper function that simply looked up the proper change function once called based on the id of the slider that called it.
function parcelSliderFunction(caller, value)
{
   for (var x = 0; x < sliders.length; x++)
    {
        if(sliders[x].id == caller) {
            sliders[x].callback(value);
            return;
        }
    }

    console.log("id " + caller + " not found, you done screwed up.");
    return;

}

I should probably use a dictionary for this.

A: First you have to remove parentheses of the function as parameter, in this line
sliders.push(new slider('paletteControl','pSlider',0,255,100,sliderChange()));

It becomes
sliders.push(new slider('paletteControl','pSlider',0,255,100,sliderChange));

Then you get the change function like this (without parentheses)
$(id).slider({
      range: "min",
      min: sliders[i].min,
      max: sliders[i].max,
      value: sliders[i].defaultvalue,
      create: function() {
        handle.text( $( this ).slider( "value" ) );
      },
      change: sliders[i].changeFunc
 });

OR
$(id).slider({
      range: "min",
      min: sliders[i].min,
      max: sliders[i].max,
      value: sliders[i].defaultvalue,
      create: function() {
        handle.text( $( this ).slider( "value" ) );
      }
 });

$( id ).on( "slidechange", function( event, ui ) {} );

A: You may call the changeFunc using window[value.changeFunc] as shown below
function newSlider(context, id, min, max, defaultvalue, changeFunc) {
    this.context = context;
    this.id = id;
    this.min = min;
    this.max = max;
    this.defaultvalue = defaultvalue;
    this.changeFunc = changeFunc;
}

function func1() {
    $('#output').append("func1
");
}

function func2() {
    $('#output').append("func2
");
}

function func3() {
    $('#output').append("func3
");
}

var sliders = [];
sliders.push(new newSlider('paletteControl', 'pSlider1', 0, 255, 100, "func1"));
sliders.push(new newSlider('paletteControl', 'pSlider2', 0, 255, 200, "func2"));
sliders.push(new newSlider('paletteControl', 'pSlider3', 0, 255, 70, "func3"));

$.each(sliders, function(index, value) {
    $("#" + value.id).slider({
        range: "min",
        min: value.min,
        max: value.max,
        value: value.defaultvalue,
        change: window[value.changeFunc]
    });
});

Working code: https://plnkr.co/edit/nwjOrnwoI7NU3MY8jXYl?p=preview


Q: How to fit multiline text inside a TextView using a custom font? I'm using API 10.
I am stuck with this for days. I searched stackoverflow and tried a ton of classes.
I wanted to fit a multiline text inside my TextView bounds with the default font. I used the class below and it worked wonders, and not only one one device, but on all devices. Exactly the same. The code is this, I found it in stackoverflow:
/**
 * This class builds a new android Widget named AutoFitText which can be used instead of a TextView
 * to have the text font size in it automatically fit to match the screen width. Credits go largely
 * to Dunni, gjpc, gregm and speedplane from Stackoverflow, method has been (style-) optimized and
 * rewritten to match android coding standards and our MBC. This version upgrades the original
 * "AutoFitTextView" to now also be adaptable to height and to accept the different TextView types
 * (Button, TextClock etc.)
 *
 * @author pheuschk
 * @createDate: 18.04.2013
 */
@SuppressWarnings("unused")
public class AutoFitText extends TextView {

    /** Global min and max for text size. Remember: values are in pixels! */
    private final int MIN_TEXT_SIZE = 10;
    private final int MAX_TEXT_SIZE = 400;

    /** Flag for singleLine */
    private boolean mSingleLine = false;

    /**
     * A dummy {@link TextView} to test the text size without actually showing anything to the user
     */
    private TextView mTestView;

    /**
     * A dummy {@link Paint} to test the text size without actually showing anything to the user
     */
    private Paint mTestPaint;

    /**
     * Scaling factor for fonts. It's a method of calculating independently (!) from the actual
     * density of the screen that is used so users have the same experience on different devices. We
     * will use DisplayMetrics in the Constructor to get the value of the factor and then calculate
     * SP from pixel values
     */
    private final float mScaledDensityFactor;

    /**
     * Defines how close we want to be to the factual size of the Text-field. Lower values mean
     * higher precision but also exponentially higher computing cost (more loop runs)
     */
    private final float mThreshold = 0.5f;

    /**
     * Constructor for call without attributes --> invoke constructor with AttributeSet null
     *
     * @param context
     */
    public AutoFitText(Context context) {
        this(context, null);
    }

    public AutoFitText(Context context, AttributeSet attrs) {
        super(context, attrs);

        mScaledDensityFactor = context.getResources().getDisplayMetrics().scaledDensity;
        mTestView = new TextView(context);

        mTestPaint = new Paint();
        mTestPaint.set(this.getPaint());

        this.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @SuppressWarnings("deprecation")
            @Override
            public void onGlobalLayout() {
                // make an initial call to onSizeChanged to make sure that refitText is triggered
                onSizeChanged(AutoFitText.this.getWidth(), AutoFitText.this.getHeight(), 0, 0);
                // Remove the LayoutListener immediately so we don't run into an infinite loop
                AutoFitText.this.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });
    }

    /**
     * Main method of this widget. Resizes the font so the specified text fits in the text box
     * assuming the text box has the specified width. This is done via a dummy text view that is
     * refit until it matches the real target width and height up to a certain threshold factor
     *
     * @param targetFieldWidth
     *            The width that the TextView currently has and wants filled
     * @param targetFieldHeight
     *            The width that the TextView currently has and wants filled
     */
    private void refitText(String text, int targetFieldWidth, int targetFieldHeight) {

        // Variables need to be visible outside the loops for later use. Remember size is in pixels
        float lowerTextSize = MIN_TEXT_SIZE;
        float upperTextSize = MAX_TEXT_SIZE;

        // Force the text to wrap. In principle this is not necessary since the dummy TextView
        // already does this for us but in rare cases adding this line can prevent flickering
        this.setMaxWidth(targetFieldWidth);

        // Padding should not be an issue since we never define it programmatically in this app
        // but just to to be sure we cut it off here
        targetFieldWidth = targetFieldWidth - this.getPaddingLeft() - this.getPaddingRight();
        targetFieldHeight = targetFieldHeight - this.getPaddingTop() - this.getPaddingBottom();

        // Initialize the dummy with some params (that are largely ignored anyway, but this is
        // mandatory to not get a NullPointerException)
        mTestView.setLayoutParams(new LayoutParams(targetFieldWidth, targetFieldHeight));

        // maxWidth is crucial! Otherwise the text would never line wrap but blow up the width
        mTestView.setMaxWidth(targetFieldWidth);

        if (mSingleLine) {
            // the user requested a single line. This is very easy to do since we primarily need to
            // respect the width, don't have to break, don't have to measure...

            /*************************** Converging algorithm 1 ***********************************/
            for (float testSize; (upperTextSize - lowerTextSize) > mThreshold;) {

                // Go to the mean value...
                testSize = (upperTextSize + lowerTextSize) / 2;

                mTestView.setTextSize(TypedValue.COMPLEX_UNIT_SP, testSize / mScaledDensityFactor);
                mTestView.setText(text);
                mTestView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);

                if (mTestView.getMeasuredWidth() >= targetFieldWidth) {
                    upperTextSize = testSize; // Font is too big, decrease upperSize
                }
                else {
                    lowerTextSize = testSize; // Font is too small, increase lowerSize
                }
            }
            /**************************************************************************************/

            // In rare cases with very little letters and width > height we have vertical overlap!
            mTestView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);

            if (mTestView.getMeasuredHeight() > targetFieldHeight) {
                upperTextSize = lowerTextSize;
                lowerTextSize = MIN_TEXT_SIZE;

                /*************************** Converging algorithm 1.5 *****************************/
                for (float testSize; (upperTextSize - lowerTextSize) > mThreshold;) {

                    // Go to the mean value...
                    testSize = (upperTextSize + lowerTextSize) / 2;

                    mTestView.setTextSize(TypedValue.COMPLEX_UNIT_SP, testSize
                            / mScaledDensityFactor);
                    mTestView.setText(text);
                    mTestView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);

                    if (mTestView.getMeasuredHeight() >= targetFieldHeight) {
                        upperTextSize = testSize; // Font is too big, decrease upperSize
                    }
                    else {
                        lowerTextSize = testSize; // Font is too small, increase lowerSize
                    }
                }
                /**********************************************************************************/
            }
        }
        else {

            /*********************** Converging algorithm 2 ***************************************/
            // Upper and lower size converge over time. As soon as they're close enough the loop
            // stops
            // TODO probe the algorithm for cost (ATM possibly O(n^2)) and optimize if possible
            for (float testSize; (upperTextSize - lowerTextSize) > mThreshold;) {

                // Go to the mean value...
                testSize = (upperTextSize + lowerTextSize) / 2;

                // ... inflate the dummy TextView by setting a scaled textSize and the text...
                mTestView.setTextSize(TypedValue.COMPLEX_UNIT_SP, testSize / mScaledDensityFactor);
                mTestView.setText(text);

                // ... call measure to find the current values that the text WANTS to occupy
                mTestView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
                int tempHeight = mTestView.getMeasuredHeight();
                // int tempWidth = mTestView.getMeasuredWidth();

                // LOG.debug("Measured: " + tempWidth + "x" + tempHeight);
                // LOG.debug("TextSize: " + testSize / mScaledDensityFactor);

                // ... decide whether those values are appropriate.
                if (tempHeight >= targetFieldHeight) {
                    upperTextSize = testSize; // Font is too big, decrease upperSize
                }
                else {
                    lowerTextSize = testSize; // Font is too small, increase lowerSize
                }
            }
            /**************************************************************************************/

            // It is possible that a single word is wider than the box. The Android system would
            // wrap this for us. But if you want to decide fo yourself where exactly to break or to
            // add a hyphen or something than you're going to want to implement something like this:
            mTestPaint.setTextSize(lowerTextSize);
            List<String> words = new ArrayList<String>();

            for (String s : text.split(" ")) {
                Log.i("tag", "Word: " + s);
                words.add(s);
            }
            for (String word : words) {
                if (mTestPaint.measureText(word) >= targetFieldWidth) {
                    List<String> pieces = new ArrayList<String>();
                    // pieces = breakWord(word, mTestPaint.measureText(word), targetFieldWidth);

                    // Add code to handle the pieces here...
                }
            }
        }

        /**
         * We are now at most the value of threshold away from the actual size. To rather undershoot
         * than overshoot use the lower value. To match different screens convert to SP first. See
         * {@link http://developer.android.com/guide/topics/resources/more-resources.html#Dimension}
         * for more details
         */
        this.setTextSize(TypedValue.COMPLEX_UNIT_SP, lowerTextSize / mScaledDensityFactor);
        return;
    }

    /**
     * This method receives a call upon a change in text content of the TextView. Unfortunately it
     * is also called - among others - upon text size change which means that we MUST NEVER CALL
     * {@link #refitText(String)} from this method! Doing so would result in an endless loop that
     * would ultimately result in a stack overflow and termination of the application
     *
     * So for the time being this method does absolutely nothing. If you want to notify the view of
     * a changed text call {@link #setText(CharSequence)}
     */
    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        // Super implementation is also intentionally empty so for now we do absolutely nothing here
        super.onTextChanged(text, start, lengthBefore, lengthAfter);
    }

    @Override
    protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
        if (width != oldWidth && height != oldHeight) {
            refitText(this.getText().toString(), width, height);
        }
    }

    /**
     * This method is guaranteed to be called by {@link TextView#setText(CharSequence)} immediately.
     * Therefore we can safely add our modifications here and then have the parent class resume its
     * work. So if text has changed you should always call {@link TextView#setText(CharSequence)} or
     * {@link TextView#setText(CharSequence, BufferType)} if you know whether the {@link BufferType}
     * is normal, editable or spannable. Note: the method will default to {@link BufferType#NORMAL}
     * if you don't pass an argument.
     */
    @Override
    public void setText(CharSequence text, BufferType type) {

        int targetFieldWidth = this.getWidth();
        int targetFieldHeight = this.getHeight();

        if (targetFieldWidth <= 0 || targetFieldHeight <= 0 || text.equals("")) {
            // Log.v("tag", "Some values are empty, AutoFitText was not able to construct properly");
        }
        else {
            refitText(text.toString(), targetFieldWidth, targetFieldHeight);
        }
        super.setText(text, type);
    }

    /**
     * TODO add sensibility for {@link #setMaxLines(int)} invocations
     */
    @Override
    public void setMaxLines(int maxLines) {
        // TODO Implement support for this. This could be relatively easy. The idea would probably
        // be to manipulate the targetHeight in the refitText-method and then have the algorithm do
        // its job business as usual. Nonetheless, remember the height will have to be lowered
        // dynamically as the font size shrinks so it won't be a walk in the park still
        if (maxLines == 1) {
            this.setSingleLine(true);
        }
        else {
            throw new UnsupportedOperationException(
                    "MaxLines != 1 are not implemented in AutoFitText yet, use TextView instead");
        }
    }

    @Override
    public void setSingleLine(boolean singleLine) {
        // save the requested value in an instance variable to be able to decide later
        mSingleLine = singleLine;
        super.setSingleLine(singleLine);
    }
}

The text shrunk as needed so that it fit the TextView bounds.
But now I want to use a custom font. I imported my custom font and everything went wrong. As you can see in the image below it doesn't fit anymore. The text doesn't shrink to fit.

So, does anyone have an idea how to handle this? Have you faced a similar problem with custom fonts?
Please someone with enough reputation, enable my image.

A: You need also to set the current fontface to the testTextView. This solved my problem.
private void refitText(String text, int targetFieldWidth, int targetFieldHeight) {

        //
        // Bla bla bla codes
        //

        //
        // THIS IS THE FIX
        // Put the current typeface of textview to the test-textview
        mTestView.setTypeface(getTypeface());

        // Initialize the dummy with some params (that are largely ignored anyway, but this is
        // mandatory to not get a NullPointerException)
        mTestView.setLayoutParams(new LayoutParams(targetFieldWidth, targetFieldHeight));

        // maxWidth is crucial! Otherwise the text would never line wrap but blow up the width
        mTestView.setMaxWidth(targetFieldWidth);

        if (mSingleLine) {


Q: ggplot2 polygon world map centred with limits gives funny edges Using the below code I generate a map centred on Washington DC.  solution based on  kohske's solution here.  I have changed geom_path to geom_polygon as I want to colour the countries.
All is well and good until I want add the scale_x_continuous (commented so you can see that there's no problem when it is left out), this makes Antarctica and China look very strange, i guess because the polygons have been trimmed?

Is there a known workaround for this?  Help is appreciated.
library(maps)
library(maptools)
library(ggplot2)

home_country_longitude <- -77.03

mp1 <- fortify(map(fill=TRUE, plot=FALSE))
mp2 <- mp1

mp2$long <- mp2$long + 360
mp2$group <- mp2$group + max(mp2$group) + 1

mp <- rbind(mp1, mp2)

if(home_country_longitude < 0){
  mp$long <- mp$long - (360 + home_country_longitude)
} else {
  mp$long <- mp$long + home_country_longitude
}

ggplot() +
  geom_polygon(aes(x = long, y = lat, group = group), data = mp) +
  #scale_x_continuous(limits = c(-180, 180)) +
  theme(panel.background = element_rect(fill = "#090D2A"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank())

A: Use coord_map, like this. Full explanation here.
ggplot() +
  geom_polygon(aes(x = long, y = lat, group = group), data = mp) +
  coord_map(xlim = c(-180, 180)) +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank())


Q: How to check the variables of an Object are Empty or NULL in JAVA? How to check variables of Objects are empty or NULL in JAVA?
Employee employee = repository.getEmployee(id).orElseGet(null);
if (employee == null) {
   employee = new Employee();
   employee.id(1);
   employee.name("Thirumal");
   employee.mobile("+91-8973-697-871");
   repository.save(employee);
}

Instead of NULL, I  am trying to create an object new Employee()
Employee employee = repository.getEmployee(id).orElseGet(new Employee());
if (employee.isEmpty()) { //--------- How to do ????????
   employee = new Employee();
   employee.id(1);
   employee.name("Thirumal");
   employee.mobile("+91-8973-697-871");
   repository.save(employee);
}

How to check the member of objects are empty/NULL?

A: Just add that isEmpty method to Employee class and implement it there, or use a null object pattern instead of doing new Employee().
As to what you are actually trying to do in your code, I suggest to do it like that instead:
Employee employee = repository.getEmployee(id).orElseGet(() -> {
   Employee emp = new Employee();
   emp.id(1);
   emp.name("Thirumal");
   emp.mobile("+91-8973-697-871");
   return repository.save(emp);
});


Q: How can I open the Install Voices settings page in Objective C (iOS) I would like my custom made app to be able to open the iOS native settings page, specifically the settings for installing new voices to your device.
How can I do this in Objective C?
I saw you can use UIApplicationOpenSettingsURLString to open the settings, but I need to go to the specific install voices settings page for the current language of the user which looks like this:

This page is found under: Settings -> Accessibility -> Spoken Content -> Voices -> (Your Language)
Getting to the Voices page, where the user has to select the language is fine too.
I guess I could try using the open() objective C function in order to open a custom URI scheme, but I need to know which URI scheme I need exactly...
EDIT: This is what I'm currently trying to do:
    NSString *voiceSettings = @"prefs:root=ACCESSIBILITY&path=SPEECH_TITLE#QuickSpeakAccents";
    NSString *cleanQuery = [voiceSettings stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString: [NSString stringWithFormat:cleanQuery]] options:@{} completionHandler:nil];

However it fails with:
Failed to open URL prefs:root=ACCESSIBILITY&path=SPEECH_TITLE#QuickSpeakAccents: Error Domain=NSOSStatusErrorDomain Code=-10814 "(null)" UserInfo={_LSLine=229, _LSFunction=-[_LSDOpenClient openURL:options:completionHandler:]}

am I missing something here?

A: UIApplicationOpenSettingsURLString is the only supported way of opening the built-in Settings.app. Any other method is a hack and runs the risk of review rejection because of private API usage.
See e.g. Is it considered a private API to use App-prefs:root?


Q: Cannot implicity convert type object to system.data.datatable Hi I'm trying to do the following but it throws the error title. As I can fix?
Thanks!!!
public static object conectar(string query)
{
    DataTable Tabla = new DataTable();
    SqlConnection connection = BaseDatos1.getConexion();
    SqlDataAdapter Da = new SqlDataAdapter();
    DataSet Ds = new DataSet();
    Da = new SqlDataAdapter(query, connection);
    Da.FillSchema(Tabla, SchemaType.Source);
    Da.FillLoadOption = LoadOption.PreserveChanges;
    Da.Fill(Tabla);
    BaseDatos1.closeConnection();
    return Tabla;
}

public static string Verificar()
{
    bool functionReturnValue ;
    DataTable Dt1;
    DataTable Dt2;
    DataTable Dt3;
    int j;
    int k;
    int DigitoVerificador;
    int Acum;
    string A;
    string tablas = "";
    string[] table = new string[6];
    string registro = "";
    bool errorEnTablaActual;
    int reg = 0;
    try {
        functionReturnValue = true;
        //Verifico en Base Seguridad
        **Dt1 = conectar("select Tabla from DigitoVerificador");**

A: You get the error because the conectar method returns an object, which you then assign to Dt1, which is a DataTable, and so you get the message that the value cannot be implicitly converted..
You can explicitly cast the return value to a DataTable, as the conectar method never returns null:
Dt1 = (DataTable)conectar("select Tabla from DigitoVerificador");

Alternatively, and probably better, you would change the return type of conectar to DataTable.


Q: Series from highcharts not showing up This is my first time using Highcharts and I'm struggling with a little problem that doesn't let me go further in my work.
I have a database in MySQL and I'm trying to show some infomation on a graph using Highcharts.
The problem is that even after several try, I'm still not being able to show my series and I can't see why.
Here's my code :
data.php
<?php
try
{
    $bdd = new PDO('mysql:host=localhost;dbname=name', 'root', '');
}
catch (Exception $e)
{
        die('Erreur : ' . $e->getMessage());
}

$sql=<<<SQL
        SELECT DATE, Traf_BH_TCH_Erl, Trafic_HR_BH, Block_BH_TCH
        FROM 182_d_all
        WHERE BCF='TIMNAY'
SQL;
$reponse = $bdd->query($sql);

$bln = array();
$rows = array();
$bln['name'] = 'Date';
$rows['name'] = 'Traf_BH_TCH_Erl';

while($donnee=$reponse->fetch()){
    $bln['data'][] = $donnee['DATE'];
    $rows['data'][] = $donnee['Traf_BH_TCH_Erl'];
    }
$rslt = array();
array_push($rslt, $bln);
array_push($rslt, $rows);
print json_encode($rslt, JSON_NUMERIC_CHECK);

$reponse->closeCursor();
?>

line.php
<?php
$cakeDescription = "Highcharts Pie Chart";
?>
<!DOCTYPE HTML>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title><?php echo $cakeDescription ?></title>
        <link href="webroot/css/cake.generic.css" type="text/css" rel="stylesheet">

The problem is that all the values of the series are equal to zero.
I don't understand why it's all blank instead of showing values?
Thank you for your answers!
EDIT :
The JSON looks something like :

[{"name":"Date","data":["\n5/6/2015 00:00:00","\n17/6/2015 00:00:0","\n15/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n26/6/2015 00:00:0","\n18/6/2015 00:00:0","\n18/6/2015 00:00:0","\n16/6/2015 00:00:0","\n7/6/2015 00:00:00","\n9/6/2015 00:00:00","\n3/6/2015 00:00:00","\n11/6/2015 00:00:0","\n9/6/2015 00:00:00","\n11/6/2015 00:00:0","\n20/6/2015 00:00:0","\n7/6/2015 00:00:00","\n24/6/2015 00:00:0","\n9/6/2015 00:00:00","\n22/6/2015 00:00:0","\n26/6/2015 00:00:0","\n26/6/2015 00:00:0","\n17/6/2015 00:00:0","\n17/6/2015 00:00:0","\n16/6/2015 00:00:0","\n16/6/2015 00:00:0","\n24/6/2015 00:00:0","\n22/6/2015 00:00:0","\n24/6/2015 00:00:0","\n22/6/2015 00:00:0","\n3/6/2015 00:00:00","\n20/6/2015 00:00:0","\n20/6/2015 00:00:0","\n3/6/2015 00:00:00","\n7/6/2015 00:00:00","\n28/6/2015 00:00:0","\n25/6/2015 00:00:0","\n25/6/2015 00:00:0","\n25/6/2015 00:00:0","\n5/6/2015 00:00:00","\n5/6/2015 00:00:00","\n28/6/2015 00:00:0","\n28/6/2015 00:00:0","\n15/6/2015 00:00:0","\n15/6/2015 00:00:0","\n23/6/2015 00:00:0","\n21/6/2015 00:00:0","\n19/6/2015 00:00:0","\n19/6/2015 00:00:0","\n19/6/2015 00:00:0","\n30/6/2015 00:00:0","\n30/6/2015 00:00:0","\n28/5/2015 00:00:0","\n18/6/2015 00:00:0","\n1/7/2015 00:00:00","\n1/7/2015 00:00:00","\n1/7/2015 00:00:00","\n8/6/2015 00:00:00","\n8/6/2015 00:00:00","\n8/6/2015 00:00:00","\n4/6/2015 00:00:00","\n4/6/2015 00:00:00","\n4/6/2015 00:00:00","\n28/5/2015 00:00:0","\n28/5/2015 00:00:0","\n29/5/2015 00:00:0","\n29/5/2015 00:00:0","\n29/5/2015 00:00:0","\n31/5/2015 00:00:0","\n6/6/2015 00:00:00","\n6/6/2015 00:00:00","\n6/6/2015 00:00:00","\n30/5/2015 00:00:0","\n30/5/2015 00:00:0","\n21/6/2015 00:00:0","\n21/6/2015 00:00:0","\n10/6/2015 00:00:0","\n10/6/2015 00:00:0","\n10/6/2015 00:00:0","\n23/6/2015 00:00:0","\n23/6/2015 00:00:0","\n29/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n27/6/2015 00:00:0","\n29/6/2015 00:00:0","\n29/6/2015 00:00:0","\n27/6/2015 00:00:0","\n27/6/2015 00:00:0","\n30/5/2015 00:00:0","\n30/6/2015 00:00:0","\n1/6/2015 00:00:00","\n1/6/2015 00:00:00","\n1/6/2015 00:00:00","\n31/5/2015 00:00:0","\n31/5/2015 00:00:0","\n2/6/2015 00:00:00","\n2/6/2015 00:00:00","\n2/6/2015 00:00:00","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n11/6/2015 00:00:0","\n12/6/2015 00:00:0","\n12/6/2015 00:00:0","\n12/6/2015 00:00:0","\n12/6/2015 00:00:0","\n12/6/2015 00:00:0","\n12/6/2015 00:00:0"]},{"name":"Traf_BH_TCH_Erl","data":["14,49","17,47","12,96","13,10","13,10","12,03","5,59","10,33","3,68","10,42","14,92","12,82","14,49","11,93","12,03","11,47","5,59","11,09","12,29","10,31","5,63","10,15","9,82","4,56","15,58","8,52","12,77","7,56","10,18","11,23","3,36","4,08","11,96","9,97","3,98","5,69","4,97","13,49","8,55","7,88","4,17","12,25","5,81","8,69","4,72","12,01","5,59","11,58","9,77","9,69","8,47","2,89","9,61","3,24","12,71","8,27","12,36","10,42","3,67","14,21","13,59","4,92","15,37","13,56","4,44","11,41","7,39","14,90","11,77","6,63","11,02","12,68","11,48","5,19","12,37","5,84","8,26","3,87","12,71","11,79","5,37","8,94","3,27","9,82","13,10","12,03","5,59","11,31","9,06","3,65","10,13","4,06","9,11","9,79","11,71","11,57","5,46","9,37","4,59","13,62","13,33","5,34","13,10","12,03","5,59","13,10","12,03","5,59","13,10","12,03","5,59","10,59","10,00","4,77","10,59","10,00","4,77"]}]

A: There is a lot going on here...
A few changes I did to get a functional example from your data:

*

*You must create a 'data' field inside 'series':
series: [{
    data: []
}]

*You must set the 'data' attribute from 'series[0]' and pass the data field from your JSON:
options.series[0].data = text[1].data;

*You must use numbers as y coordinate data, so you should use dot as decimal separator and do not use quotes:
{"name":"Traf_BH_TCH_Erl","data":[11.23,3.36,4.08,11.96,9.97]}

*You are not using X axis with date format properly, but you can search for that after you get your first Highcharts working. ;)
Functional example: JSFiddle


Q: Generating a PHP array tree structure from dynamic data set I have a history with having tree issues and I've done a lot of research on the topic.  I think maybe I'm using the wrong hammer on this nail.
I am trying to create a tree hierarchy data set from an array, but not just one that has defined parent-child relationships.  It's pretty much comparing one array in the data set to another, and then combining what is the same, and branching the differences into a new array.
The reasoning behind this is for searching against the data sets later (such as ACL) which are expected to be large, and to return this format through API calls.
Coming from a PHP and MySQL query, I return an array that looks like this (the key value pairs could be anything, this is just a generalization):
$testArray = array(
    array('group' => 'Group1','group_id' => '1','portal' => 'Portal1','portal_id' => '1','role' => 'Role1','role_id'  => '1','permission' => 'Permission1','permission_id' => '1'),
    array('group' => 'Group1','group_id' => '1','portal' => 'Portal1','portal_id' => '1','role' => 'Role1','role_id'  => '1','permission' => 'Permission2','permission_id' => '2'),
    array('group' => 'Group1','group_id' => '1','portal' => 'Portal2','portal_id' => '2','role' => 'Role1','role_id'  => '1','permission' => 'Permission3','permission_id' => '3'),
    array('group' => 'Group1','group_id' => '1','portal' => 'Portal2','portal_id' => '2','role' => 'Role2','role_id'  => '2','permission' => 'Permission1','permission_id' => '1'),
    array('group' => 'Group2','group_id' => '2','portal' => 'Portal1','portal_id' => '1','role' => 'Role3','role_id'  => '3','permission' => 'Permission1','permission_id' => '1'),
    array('group' => 'Group2','group_id' => '2','portal' => 'Portal1','portal_id' => '1','role' => 'Role3','role_id'  => '3','permission' => 'Permission2','permission_id' => '2')
);

Pseudo Output After:
            (Group_Name = Group1, Group_ID = 1)
(Portal_Name = Portal1, Portal_id = 1) (Portal_Name = Portal2, Portal_id = 2)
(Role,RoleID)                        (Role,RoleID)
(Permission,Permission_id)           (Permission,Permission_id)

Here's the WIP function.  It's a little all over the place ATM, but this is where my head is at:
//List of keyList to compare against
if(is_array($testArray[0])) {
    $keyList = array_keys($testArray[0]);
}

function buildTree(&$data, $keyList) {
    $branch = array();
    $tree = array();

    foreach($keyList as $k => &$keyName) {

        //Each row in the data set is an array
        foreach($data as $rowKey => &$rowArraySet) {
            //If the branch key exists, and matches
            if(isset($rowArraySet[$keyName]) && isset($keyList[$keyName]) &&
                isset($branch[$keyList[$keyName]][$rowArraySet[$keyName]])) {

                if(isset($data[1+$rowKey]) &&
                    $rowArraySet[$keyName] == $data[1+$rowKey][$keyName]) {
                    $branch[$keyName][$rowArraySet[$keyName]] = array_diff($rowArraySet, $rowArraySet[$keyName]);
                    unset($data[$rowKey]);
                }

            }
            //If the branch does not exist, and matches next array record
            else if(isset($data[1+$rowKey]) &&
                    $rowArraySet[$keyName] == $data[1+$rowKey][$keyName]) {
                $branch[$keyName] = array();
                $branch[$keyName][$rowArraySet[$keyName]] = array_diff($rowArraySet, array($keyName => $rowArraySet[$keyName]));
                unset($data[$rowKey]);
            }
            //Create new branch key (no match)
            else if(isset($rowArraySet[$keyName])) {
                $branch[$keyName] = array();
                $branch[$keyName][$rowArraySet[$keyName]] = array_diff($rowArraySet, array($keyName => $rowArraySet[$keyName]));
                unset($data[$rowKey]);
            }
            echo $rowKey;
        }
        //Remove keyName from checking
        unset($keyList[$k]);

        //Compare branch
        //$tree[] = buildTree($branch, &$keyList);

        //echo '<pre>';
        //var_dump($branch);
        //die;
    }

    return $tree;
}

Yes, I know there's a little place in hell for programmers and undocumented code.  My thinking goes like this:

*

*Capture Keys from the first array in the set (this is the parent - child like relationship, at least the order to check against)

*Use the keys to compare each array to eachother in the set (if exists/set etc)

*Matching values create a new branch and move the array over, combining them

*Check the next set, and check to see if the keys exist in the branch

*Recursively sort the branch once complete

*Return branch to tree array and output tree

As always, any guidance is appreciated.  I feel like I'm close to figuring this out, I just can't wrap my head around it.  Thank you.
Edit per recommendations.


Q: How to get return code from spark-submit? I am trying to execute a spark job using an ssh connection on a remote location.
There have been instances where the job failed but the scheduler marked it as "success" so i want to check the return code of spark-submit so i could forcefully fail it.
Below is the code I'm using
def execute_XXXX():
    f = open('linux.pem','r')
    s = f.read()
    keyfile = StringIO.StringIO(s)
    mykey = paramiko.RSAKey.from_private_key(keyfile)
    sshcon   = paramiko.SSHClient()
    sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    sshcon.connect('XXX.XXX.XXX.XXX', username='XXX', pkey=mykey)
    stdin, stderr, stdout= sshcon.exec_command('spark-submit XXX.py')

    logger.info("XXX ------>"+str(stdout.readlines()))
    logger.info("Error--------->"+str(stderr.readlines()))

How do I get the return code for the spark-submit job so I can forcefully fail the task.
Or could you suggest an alternate solution.
Thanks, Chetan

A: So this is how I solved the issue i was facing. A simple 1 line code was enough.
def execute_XXXX():
    f = open('linux.pem','r')
    s = f.read()
    keyfile = StringIO.StringIO(s)
    mykey = paramiko.RSAKey.from_private_key(keyfile)
    sshcon   = paramiko.SSHClient()
    sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    sshcon.connect('XXX.XXX.XXX.XXX', username='XXX', pkey=mykey)
    stdin, stderr, stdout= sshcon.exec_command('spark-submit XXX.py')
    if (stdout.channel.recv_exit_status())!= 0:
         logger.info("XXX ------>"+str(stdout.readlines()))
         logger.info("Error--------->"+str(stderr.readlines()))
         sys.exit(1)

A: You need to implement a sparkListener. More information to which can be found on the below link.
How to implement custom job listener/tracker in Spark?


Q: Хотел закинуть телеграм бота на сервер и выходит такая ошибка Traceback (most recent call last):
File "main.py", line 4, in
from telebot import types
File "/usr/local/lib/python3.4/dist-packages/telebot/types.py", line 149
self.chat: Chat = chat
Как пофиксить?


Q: Excel SUMIF variations I'm trying to make a SUMIF function like this one
=SUMIF(OUT!$G$22:$G$70;'2018'!$B4;OUT!$J$22:$J$70)
But i would like instead of giving the name of the sheet OUT, i want the excel to read de name of the sheet from an other cell like i show on the img.
I tried =SUMIF(CELL("contents";E2)!$G$22:$G$70;'2018'!$B4;CELL("contents";E2)!$J$22:$J$70)
but still not working. Anyone knows how to do it?
Excel image

A: You need INDIRECT:
=SUMIF(INDIRECT("'"&E2&"'!G22:G70");'2018'!$B4;INDIRECT("'"&E2&"'!J22:J70"))

Note that since the ranges are literal text strings, you don't need to make them absolute since they won't adjust if you copy/fill anyway.


Q: What determines if a scrollbar has color in Firefox? TLDR; I've encountered interesting behaviour in Firefox. For example, it automatically styles the scrollbar limegreen, but not lightgreen. Why does it render one, but not the other?

While answering another question I found that this renders a limegreen colored scroll bar in Firefox 72 latest on Windows 10:

div {
  background-color: limegreen;
  max-height: 5em;
  overflow-y: scroll;
}

Hi!
Hi!
Hi!
Hi!
Hi!
Hi!
Hi!
Hi!
Hi!
Hi!

Like this:

But that Firefox refuses to render a lightgreen colored scroll bar:

div {
  background-color: lightgreen;
  max-height: 5em;
  overflow-y: scroll;
}

Hi!
Hi!
Hi!
Hi!
Hi!
Hi!
Hi!
Hi!
Hi!
Hi!

See this:

What causes this behavior, and how can I predict it?
PS. Chrome 80 shows both scrollbars in the default style.
PS. There are questions on how to actively change scrollbar color in Firefox, but I'm not (right now) interested in pragmatic advice on "how to change scrollbar color", but instead I'm asking and trying to understand when and why it happens automatically, and only for some background colors.

A:

div {
  background-color: lightgreen;
  max-height: 5em;
  overflow-y: scroll;
  scrollbar-color: lightgreen lightgreen;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Using scrollbar-color works (more info here). I think color detection is just really buggy - sometimes one color works with scrollbar-color and applies to both parts of the scrollbar and sometimes you need to repeat it twice. I just think it's a poorly implemented part of the HTML spec. Doesn't have great browser support though so make sure it's not required as part of your interface.


Q: checkbox select submit post call I need to make a post call when a checkbox is selected in table. The row information should need to be passed when I select the checkbox of the particular row which I am selecting.
Right now I am bale to get the selected table row information, only thing is I am not able to submit information to backend.
Note: I dont want to make a ajax call.I need the page get reload once again.
Code:

${flashMessage}
<form method="post"
    action="/InformationManagement/mrps/getDepositSearch"
    class="searchCriteria">

        Select the Search Column Name <select class="dropmenu"
            name="searchCondition">
            <option value="NONE">--- Select ---</option>

            <c:forEach items="${searchAllContents.searchContent}" var="record">
                <%-- <c:if test="${searchAllContents.searchContent} ==''">
        <option value="${record.key}" selected>${record.value}</option>
        </c:if> --%>
                <c:choose>
                    <c:when test="${record.key=='DPST_NUM'}">

                        <option value="${record.key}" selected>${record.value}</option>
                        <option value="DPST_DTE">Deposit Date</option>
                    </c:when>
                    <c:when test="${record.key=='DPST_DTE'}">
                        <option value="DPST_NUM">Deposit Number</option>
                        <option value="${record.key}" selected>${record.value}</option>

                    </c:when>
                    <c:otherwise>

                        <option value="DPST_NUM">Deposit Number</option>

                        <option value="DPST_DTE">Deposit Date</option>

                    </c:otherwise>
                </c:choose>
            </c:forEach>

        </select> Search <input type="text" id="searchText" name="searchText"
            value="${searchText}" />

        <input type="submit" class="submit" />

   </form>

   <form name="test" id= "testid" action="Controller" method="post">

   Deposit Date
   Deposit Number
  Deposit Status

  <c:forEach items="${depositDetails}" var="depositDetails">

  <input type="checkbox" class = "chcktbl" />
   ${depositDetails.DPST_DTE}
  ${depositDetails.DPST_NUM}
   ${depositDetails.PMT_STS}

</c:forEach>

    </form>


Q: Why do we extend JpaRepository Interface and not implements it TestRepository ***extends*** JpaRespotiroy<Test,Long>
JpaRepository is an interface. Why do we extend it and not implement it as we know in Java? As far as I know, interfaces are implemented, not extended.
Can somebody explain to me please?

A: I assume your code looks like
interface TestRepository extends JpaRepository<Test, Long>

So TestRepository is an interface and interfaces can extend other interfaces not implement interfaces.
The TestRepository will be implemented from Spring Data JPA during runtime based on the SimpleJpaRepository
https://github.com/spring-projects/spring-data-jpa/blob/master/src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java

A: In Java

*

*Class extends Class
   class Test Extends Thread

*interface Extend interface
    public interface TestI extends Runtime

*class implements interface
  public class Test implements Runnable


Q: How to handle API requests with Record Limits using R I do not have any code to share, but am looking for advice on the best way to handle API record limits. I am pulling data for a restful api service and the record limit is 1000 records. The data goes back about three years. I am using HTTR package in R to use a GET request with multiple parameters.
I want to be able to pull as much data into memory that R can handle which in my experience is around 2 million records. Loops do not seem ideal. I managed to create a list of date ranges (about 30 day range) which when created into a dataframe leaves me with about 40 dataframes where about half are still reaching a record limit of 1000 rows. The date ranges do not overlap. The only thing I can think of is to make the query small enough so that the data pulled back is not reaching or exceeding the record limit and to then do a rbind on all the data.
Is there any workarounds for querying restful api's that have these record limits. If not, then my approach may be to query small enough date ranges and loop the GET request until it has queried all date ranges in my list and cache the files. Then perhaps query from the cached files. Is there a better approach?