text:
Q: Draw chart based on dropdown selection in backbone I am trying to draw a chart when the user selects a different option in a dropdown by using Backbone.js, Highchart and handlebars. I have used collection to store JSON values and used toJSON function to display all the values in dropdown and to draw a chart. Everything is working perfectly like drawing Chart and display values in dropdown.
Now i am trying to draw first two values(two bars) only while page load. After that the first value/bar will be a constant it needs not to draw a chart and second bar charts have to be drawn based on the dropdown selection. For example if the user select Edvin need to draw chart for the Edvin user and so on.
To achieve, i have used "select" backbone event. I am calling "tableModified" function when the dropdown value is changed. Then i am checking if the value is matched with collection value again i am calling "modifyTableValue" function. The above "tableModified" function is getting fired when i change any values in dropdown and also i can see the selected dropdown valued in console.
Here i am trying to display first two bar charts after that need to draw a chart based on selection in the dropdown.
Here is my backbone JS code

Could any one please tell me how to proceed further or give some suggestion in order to accomplish it?
Thanks in advance!


text:
Q: How to make Windows Bootable-Installable from existing Installed Windows Does anyone have idea about making Windows 8.1 Bootable-Installable from existing Installed Windows.
I need this because many of the times, I need to reinstall the windows as my system is faulty and get crashes. So I can make a installable-bootable USB Pen Drive from the existing installed windows (with all software and drivers etc), then it would be very much helpful for me. Then I will not have to install the drivers and other my required software, after each time I install the Windows.
Is there any way to do so?

A: Basically what you need is a imaging or cloning software. There are many having their own pros and cons. They are initially used to make rescue disks. Same you can use to make iso image for your need. Some of them are Macrium Reflect, Magic Iso , Ultra Iso , Ghost Drive etc.

A: System Image Backup
If you don't want to use a 3rd party imaging tool you can use Windows' own built-in System Image Backup. It's hidden from Start Search, so to access it go to File History. It's at the bottom left corner of the window:

To create a system image you'll need an NTFS formatted storage device. Most people use an external HDD to store the backup image onto but you could use DVDs of course:

When recovering from the system image you'll need either a Win8.x bootable USB stick or a  System Repair Disc** which you'll be asked to create when making the image. Go to Troubleshoot>Advanced Options>System Image Recovery and just choose the system image you want to recover!

Sources here and here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where is form data handled?? (Django) I have read a lot of tuts and documentation on form creation and handling in Django but I still am confused on certain aspects of the implementation. Specifically, I cannot understand where I should handle the data sent by the form. Is it on the view that is using the form template or is it on another view?
For example, assume an index template with a single form:
*index.html*
{% load url from future %}
<form action="{% url 'Directories:_results'%}" method="post">
Name: <input type="text" name="txtField" />
<input type="submit" name="submit" />
</form>

So now for my view i have two versions:
#1 version (1 view): The same view displays and handles the form
def index(request):
    if request.method == 'POST': # If the form has been submitted...
        form = dbForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            field = form.cleaned_data['txtField']
            #doSomething
    else:
        form = dbForm() #unbound form
     return render(request, 'Directories/index.html', {'form': form})

#2 version (2 views): One view to display the form and one view to handle the form data
#the view that creates the form (unbound)
def index(request):
    form = dbForm()
    return render(request, 'Directories/index.html', {'form':form})

#the view that handles the data sent during form submission in the index template.
def results(request):
    if request.method == 'POST':
        form = dbForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            field = form.cleaned_data['txtField']
            #doSomething
     else:
         form = dbForm() #unbound form
     return render(request, 'Directories/index.html', {'form': form})

and here is my urls.py:
from django.conf.urls import patterns, url
from Directories import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='_index'),
    url(r'^results$', views.results, name='_results'),)

As you can see data handling is performed differently in each version and as a result I want to know if any of these is wrong and if both are correct then which one is considered the best practice.

A: Generally a form will post to the same view it is being displayed on.
You can simplify the view logic like so:
def index(request):
    form = dbForm(data=request.POST or None)
    if form.is_valid(): # All validation rules pass
        field = form.cleaned_data['txtField']
        #doSomething
        return redirect(success_url)
    return render(request, 'Directories/index.html', {'form': form})

Note that it is usually good if you redirect after a successful form post, even if you redirect back to the same view. This prevents the user from being prompted to 'resend form data' if they refresh the page.
You should look at the docs for rendering a form in the template:
https://docs.djangoproject.com/en/dev/topics/forms/#looping-over-the-form-s-fields
If you don't render the field errors, for example, the user will never know what the problem was.
An example of a form that would post to a different view is if say your base template has a 'search' form which appears on every page. When you post this form you don't want to come back to the current view, you want to go to the 'search results' view.

A: Generally, one view corresponds to one url. Also, same url should show the form and accept the submitted form. With this logic, your first approach is better. One view shows and accepts the form.
However, there are cases where view to show form is different than the one accepts it. For example, a page that has multiple forms. Each form can be submitted to different view. But a different view can be implemented to handle that url and show such forms.

A: There's nothing wrong with either, it depends on what you want to do. By default forms send the data to the same request but you can send the data to a different view if that's more convenient
For most cases it's usually simpler to use the same view. Using two views is good if you're using an external tool\app\whatever or if you want tighten your security (having the second view only accept requests with post data for example etc.), but will require extra steps (error handling, succesful redirect)

A: The first thing to understand is that the view that processes the form is usually also the one that shows the form in the first place -- because it has to show the form again in case of errors.
In your template, you build the form HTML entirely by hand. That's unusual, because in case of errors (usually a required field that wasn't filled in) you want to render the form again, with all the values already entered present, and with a nice error message. Django's form rendering ( {{ form.as_p }} and the like) do that for you, you don't get it if you write the HTML by hand like this. In fact your view misses an else: clause on the is_valid(), leading it to
So usually the view does both, except for the second thing to understand: after a successful POST, you always redirect to a succes page, or possibly to the same page (which will show an empty form again). Mostly so the user can't accidentally re-submit the form with the refresh button then.
So your 1st is typical, except that you also need to finish with returning a ResponseRedirect in the is_valid() case, and should render more of the form in your template. No need for a second view.


text:
Q: I need to compare different image values after they've been clicked I have not been able to find any good questions regarding my predicament. I am trying to count/check how many times a specific item is clicked via an actionListener but am unsure of how to use an actionListener/EventHandler to document the click. This is being done in JavaFX.Pardon the potentially noobish question.
        correctUrl = getCorrectUrl(); //Correct image for set
        wrongUrl = getWrongUrl();
        initialPos(); //everything is placed into default.

       imageOne.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
           imageOne.setOnMouseClicked((MouseEvent e) -> {
               imageOne = flipToCard(imageOne, 1);
           });
            returnCardOne();
            System.out.println("Tile pressed ");
            event.consume();
        });

The ultimate goal of the code is to notice two images have been clicked and then check to see if their URL == each-other.

A: If the URLs are equal, the Images should be equal. So why not compare Images? This little app demos what you are trying to achieve. Comments in the code.

Main:

import java.util.ArrayList;
import java.util.List;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 *
 * @author Sedrick
 */
public class JavaFXApplication51 extends Application {

    @Override
    public void start(Stage primaryStage) {
        List<ImageViewTile> imageViews = new ArrayList();
        List<ImageViewTile> cardsBeingMatched = new ArrayList();//Used to keep up with the current two cards that are pressed inorder to deteremine if they are a match
        Image initialImage = new Image(getClass().getResourceAsStream("cardBack_blue1.png"));
        Image ace = new Image(getClass().getResourceAsStream("cardSpadesA.png"));
        Image king = new Image(getClass().getResourceAsStream("cardSpadesK.png"));
        imageViews.add(new ImageViewTile(initialImage, ace));
        imageViews.add(new ImageViewTile(initialImage, king));
        imageViews.add(new ImageViewTile(initialImage, ace));
        imageViews.add(new ImageViewTile(initialImage, king));

        for(ImageViewTile view : imageViews)
        {
            //Set ImageViews' onMouseClicked handler
            view.setOnMouseClicked(event->{

                if(!view.isShowing())//If card face value is not showing
                {
                    view.showFrontImage();//show it.
                    cardsBeingMatched.add(view);//Add card being clicked to list so it can be compared against the next card
                    if(cardsBeingMatched.size() == 2)//Once two cards are in the list, see if they are equal.
                    {
                        if(cardsBeingMatched.get(0).getImage().equals(cardsBeingMatched.get(1).getImage()))//If cards are equal a match is found
                        {
                            System.out.println("Match");
                            cardsBeingMatched.clear();//clear the list to prepare to compare the next two cards that are clicked
                        }
                        else//If cards are not equal
                        {
                            System.out.println("No match");
                            //wait half a second and flip cards back over
                            Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(.5), (event1) -> {
                                System.out.println(".5 seconds need to pass before another mouse click!");
                            }));
                            timeline.setCycleCount(1);
                            timeline.play();
                            timeline.setOnFinished(event1->{
                                cardsBeingMatched.get(0).showBackImage();
                                cardsBeingMatched.get(1).showBackImage();
                                cardsBeingMatched.clear();//clear the list to prepare to compare the next two cards that are clicked
                            });
                        }
                    }
                }
            });
        }

        GridPane root = new GridPane();
        for(int i = 0; i < imageViews.size(); i++)
        {
            root.add(imageViews.get(i), i % 2, i  / 2);//Add ImageViews to the GridPane
        }

        Scene scene = new Scene(root, 280, 380);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

ImageViewTitle Class:

import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

/**
 *
 * @author Sedrick
 */
public final class ImageViewTile extends  ImageView{
    private boolean showing;
    private final Image backImage;
    private final Image frontImage;

    public ImageViewTile(Image backImage, Image frontImage) {
        this.backImage = backImage;
        this.frontImage = frontImage;

        this.setImage(backImage);
        showing = false;
    }

    public void showBackImage()
    {
        this.setImage(backImage);
        showing = false;
    }

    public void showFrontImage()
    {
        this.setImage(frontImage);
        showing = true;
    }

    public boolean isShowing()
    {
        return showing;
    }
}

I created this class to help me keep up with the ImageView's different states.


text:
Q: Errors after installing flat remix gnome theme using terminal I am beginner in Ubuntu and I decided to try out flat remix gnome theme but I faced a very big problem while using the terminal commands which are as following:
sudo add-apt-repository ppa:daniruiz/flat-remix
sudo apt-get update
sudo apt-get install flat-remix-gnome

But after applying the first two with no problems in the third command I start facing these codes every time I try installing any package:
Unpacking android-sdk-platform-tools-common (27.0.0+10~18.04.2) ...
Setting up android-liblog (1:8.1.0+r23-5~18.04) ...
Setting up flat-remix-gnome (20191117) ...
/var/lib/dpkg/info/flat-remix-gnome.postinst: 4: /var/lib/dpkg/info/flat-remix-gnome.postinst: make: not found
dpkg: error processing package flat-remix-gnome (--configure):
 installed flat-remix-gnome package post-installation script subprocess returned error exit status 127
Setting up android-libboringssl (8.1.0+r23-2~18.04) ...
Setting up android-sdk-platform-tools-common (27.0.0+10~18.04.2) ...
Setting up android-libcrypto-utils (1:8.1.0+r23-5~18.04) ...
Setting up android-libbase (1:8.1.0+r23-5~18.04) ...
Setting up android-libcutils (1:8.1.0+r23-5~18.04) ...
Setting up android-libadb (1:8.1.0+r23-5~18.04) ...
Setting up adb (1:8.1.0+r23-5~18.04) ...
Processing triggers for man-db (2.8.3-2ubuntu0.1) ...
Processing triggers for libc-bin (2.27-3ubuntu1) ...
Errors were encountered while processing:
 flat-remix-gnome
E: Sub-process /usr/bin/dpkg returned an error code (1)

and I tried to remove the package but it gives same error and I tried re-installing the package and this appear>>>
moutasim@moutasim-Aspire-A515-51G:~$ sudo apt-get install flat-remix-gnome
[sudo] password for moutasim:
Reading package lists... Done
Building dependency tree
Reading state information... Done
flat-remix-gnome is already the newest version (20191117).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
1 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Do you want to continue? [Y/n] y
Setting up flat-remix-gnome (20191117) ...
/var/lib/dpkg/info/flat-remix-gnome.postinst: 4: /var/lib/dpkg/info/flat-remix-gnome.postinst: make: not found
dpkg: error processing package flat-remix-gnome (--configure):
 installed flat-remix-gnome package post-installation script subprocess returned error exit status 127
Errors were encountered while processing:
 flat-remix-gnome
E: Sub-process /usr/bin/dpkg returned an error code (1)

Please help guys cause this is my second time reinstalling Ubuntu please help

A: I solved this problem
Into file /var/lib/dpkg/info/flat-remix-gnome.postinst has a command make and package is not installed: make: not found
I started Ubuntu with recovery mode and installed the package make, after reboot this problem has been solved


text:
Q: Linux Mint: Error! Your kernel headers for kernel 4.4.0-38-generic cannot be found After several attempts to fix the issue by myself I've decided to post here, basically everytime I'm running an upgrade I received this error message:
fabrizio@fabrix ~ $ sudo apt-get upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
3 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.

Do you want to continue? [Y/n] y
Setting up initramfs-tools (0.125) ...
update-initramfs: deferring update (trigger activated)
Setting up linux-image-4.4.0-38-generic (4.4.0-38.57) ...
Running depmod.
update-initramfs: deferring update (hook will be called later)
The link /initrd.img is a dangling linkto /boot/initrd.img-4.4.0-38-generic
vmlinuz(/boot/vmlinuz-4.4.0-38-generic
) points to /boot/vmlinuz-4.4.0-38-generic
 (/boot/vmlinuz-4.4.0-38-generic) -- doing nothing at /var/lib/dpkg/info/linux-image-4.4.0-38-generic.postinst line 491.
Examining /etc/kernel/postinst.d.
run-parts: executing /etc/kernel/postinst.d/apt-auto-removal 4.4.0-38-generic /boot/vmlinuz-4.4.0-38-generic
run-parts: executing /etc/kernel/postinst.d/dkms 4.4.0-38-generic /boot/vmlinuz-4.4.0-38-generic
Error! echo
Your kernel headers for kernel 4.4.0-38-generic cannot be found at
/lib/modules/4.4.0-38-generic/build or /lib/modules/4.4.0-38-generic/source.
Error! echo
Your kernel headers for kernel 4.4.0-38-generic cannot be found at
/lib/modules/4.4.0-38-generic/build or /lib/modules/4.4.0-38-generic/source.
run-parts: executing /etc/kernel/postinst.d/initramfs-tools 4.4.0-38-generic /boot/vmlinuz-4.4.0-38-generic
update-initramfs: Generating /boot/initrd.img-4.4.0-38-generic
E: busybox or busybox-static, version 1:1.22.0-17~ or later, is required but not installed
update-initramfs: failed for /boot/initrd.img-4.4.0-38-generic with 1.
run-parts: /etc/kernel/postinst.d/initramfs-tools exited with return code 1
Failed to process /etc/kernel/postinst.d at /var/lib/dpkg/info/linux-image-4.4.0-38-generic.postinst line 1052.
dpkg: error processing package linux-image-4.4.0-38-generic (--configure):
 subprocess installed post-installation script returned error exit status 2
dpkg: dependency problems prevent configuration of linux-image-extra-4.4.0-38-generic:
 linux-image-extra-4.4.0-38-generic depends on linux-image-4.4.0-38-generic; however:
  Package linux-image-4.4.0-38-generic is not configured yet.

dpkg: error processing package linux-image-extra-4.4.0-38-generic (--configure):
 dependency problems - leaving unconfigured
Processing triggers for initramfs-tools (0.125) ...
update-initramfs: Generating /boot/initrd.img-4.4.0-21-generic
E: busybox or busybox-static, version 1:1.22.0-17~ or later, is required but not installed
update-initramfs: failed for /boot/initrd.img-4.4.0-21-generic with 1.
dpkg: error processing package initramfs-tools (--configure):
 subprocess installed post-installation script returned error exit status 1
Errors were encountered while processing:
 linux-image-4.4.0-38-generic
 linux-image-extra-4.4.0-38-generic
 initramfs-tools
E: Sub-process /usr/bin/dpkg returned an error code (1)

I tried to look for similar error and I tried to remove the kernel, to upgrade initramfs and other operations without success, can you point me to right direction?
fabrizio@fabrix ~ $ df -h
Filesystem      Size  Used Avail Use% Mounted on
udev            3.7G     0  3.7G   0% /dev
tmpfs           759M  9.5M  750M   2% /run
/dev/sda1       286G   25G  248G   9% /
tmpfs           3.8G  9.0M  3.7G   1% /dev/shm
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
tmpfs           3.8G     0  3.8G   0% /sys/fs/cgroup
cgmfs           100K     0  100K   0% /run/cgmanager/fs
tmpfs           759M   32K  759M   1% /run/user/1000
fabrizio@fabrix ~ $ df -i
Filesystem       Inodes  IUsed    IFree IUse% Mounted on
udev             965757    531   965226    1% /dev
tmpfs            970893    813   970080    1% /run
/dev/sda1      19038208 500395 18537813    3% /
tmpfs            970893     30   970863    1% /dev/shm
tmpfs            970893      6   970887    1% /run/lock
tmpfs            970893     18   970875    1% /sys/fs/cgroup
cgmfs            970893     14   970879    1% /run/cgmanager/fs
tmpfs            970893     20   970873    1% /run/user/1000
fabrizio@fabrix ~ $ sudo apt-get install busybox busybox-static
Reading package lists... Done
Building dependency tree
Reading state information... Done
busybox-static is already the newest version (1:1.22.0-19ubuntu2).
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 busybox : Conflicts: busybox-static but 1:1.22.0-19ubuntu2 is to be installed
 busybox-static : Conflicts: busybox
E: Unable to correct problems, you have held broken packages.

A: try
sudo apt-get install linux-headers-4.4.0-38-generic
sudo apt-get -f install

see if that solves the problem :)


text:
Q: SCardListReaders in js-ctypes giving 0x6 error continuing the previous question:
Error while calling SCardListReaders in js-ctypes
the code was amended as follows:
Cu.import('resource://gre/modules/ctypes.jsm');

var is64bit = ctypes.voidptr_t.size == 4 ? false : true;
var ifdef_UNICODE = true;

var TYPES = {
ABI: is64bit ? ctypes.default_abi : ctypes.winapi_abi,
CALLBACK_ABI: is64bit ? ctypes.default_abi : ctypes.stdcall_cabi,

CHAR: ctypes.char,
DWORD: ctypes.uint32_t,
LONG: ctypes.long,
LPCVOID: ctypes.voidptr_t,
ULONG_PTR: is64bit ? ctypes.uint64_t : ctypes.unsigned_long,
WCHAR: ctypes.jschar
};

// advanced types - based on simple types
TYPES.LPSTR = TYPES.CHAR.ptr;
TYPES.LPCSTR = TYPES.CHAR.ptr;
TYPES.LPDWORD = TYPES.DWORD.ptr;
TYPES.LPCWSTR = TYPES.WCHAR.ptr;
TYPES.LPWSTR = TYPES.WCHAR.ptr;
TYPES.SCARDCONTEXT = TYPES.ULONG_PTR;

// advanced advanced types - based on advanced types
TYPES.LPCTSTR = ifdef_UNICODE ? TYPES.LPCWSTR : TYPES.LPCSTR;
TYPES.LPTSTR = ifdef_UNICODE ? TYPES.LPWSTR : TYPES.LPSTR;
TYPES.PSCARDCONTEXT = TYPES.SCARDCONTEXT.ptr;
TYPES.LPSCARDCONTEXT = TYPES.SCARDCONTEXT.ptr;

var CONST = {
    SCARD_AUTOALLOCATE: TYPES.DWORD('0xffffffff'),
    SCARD_SCOPE_SYSTEM: 2,
    SCARD_SCOPE_USER: 0,
    SCARD_S_SUCCESS: 0
};

var cardLib = ctypes.open('Winscard');
var SCardEstablishContext = cardLib.declare('SCardEstablishContext', TYPES.ABI, TYPES.DWORD, TYPES.DWORD, TYPES.LPCVOID, TYPES.LPCVOID, TYPES.LPSCARDCONTEXT);
var SCardListReaders = cardLib.declare(ifdef_UNICODE ? 'SCardListReadersW' : 'SCardListReadersA', TYPES.ABI, TYPES.LONG, TYPES.LPSCARDCONTEXT, TYPES.LPCTSTR, TYPES.LPTSTR, TYPES.LPDWORD);
var SCardFreeMemory = cardLib.declare('SCardFreeMemory', TYPES.ABI, TYPES.LONG, TYPES.SCARDCONTEXT, TYPES.LPCVOID);
var SCardReleaseContext = cardLib.declare('SCardReleaseContext', TYPES.ABI, TYPES.LONG, TYPES.SCARDCONTEXT);

// types, consts, and functions declarations complete, now lets use it
try {
    var hSC = TYPES.SCARDCONTEXT();
    var rez_SCEC = SCardEstablishContext(CONST.SCARD_SCOPE_USER, null, null, hSC.address());
    if (rez_SCEC.toString() != CONST.SCARD_S_SUCCESS.toString()) {
        console.error('failed to establish context! error code was: ' + rez_SCEC + ' in other terms it is: 0x' + rez_SCEC.toString(16) + ' you can look up this error value here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa374738%28v=vs.85%29.aspx#smart_card_return_values');
        throw new Error('failed to establish context!');
    }

    try {
        var reader_count = TYPES.DWORD();
        var reader_names = TYPES.LPTSTR.targetType(0);
        var rez_SCLR = SCardListReaders(hSC.address(), null, null, reader_count.address());
        console.log('rez_SCLR:', rez_SCLR, rez_SCLR.toString());
        if (rez_SCLR.toString() != CONST.SCARD_S_SUCCESS.toString()) {
            console.error('failed to get list of readers! error code was: ' + rez_SCLR + ' in other terms it is: 0x' + rez_SCLR.toString(16) + ' you can look up this error value here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa374738%28v=vs.85%29.aspx#smart_card_return_values');
            throw new Error('failed to get list of readers!');
        }
throw ('done');
        var rez_free = SCardFreeMemory(hSC, reader_names);
        console.log('rez_free:', rez_free, rez_free.toString());
        if (rez_release.toString() != CONST.SCARD_S_SUCCESS.toString()) {
            console.error('failed to free the multi-string that lists the card readers! error code was: ' + rez_release + ' in other terms it is: 0x' + rez_release.toString(16) + ' you can look up this error value here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa374738%28v=vs.85%29.aspx#smart_card_return_values');
            throw new Error('failed to free the multi-string that lists the card readers!');
        }
    } finally {
        var rez_release = SCardReleaseContext(hSC);
        console.log('rez_release:', rez_release, rez_release.toString());
        if (rez_release.toString() != CONST.SCARD_S_SUCCESS.toString()) {
            console.error('failed to release context! error code was: ' + rez_release + ' in other terms it is: 0x' + rez_release.toString(16) + ' you can look up this error value here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa374738%28v=vs.85%29.aspx#smart_card_return_values');
            throw new Error('failed to release context!');
        }
    }

} finally {
    cardLib.close();
    console.log('cardLib closed');
}

However it also has the following error:
"failed to get list of readers! error code was: 6 in other terms it is: 0x6"
Exception: Error: failed to get list of readers!
@Scratchpad/2:61:1
WCA_evalWithDebugger@resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/devtools/server/actors/webconsole.js:1185:16
WCA_onEvaluateJS@resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/devtools/server/actors/webconsole.js:797:20
WCA_onEvaluateJSAsync@resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/devtools/server/actors/webconsole.js:768:20
DSC_onPacket@resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/devtools/server/main.js:1456:15
LocalDebuggerTransport.prototype.send/<@resource://gre/modules/devtools/dbg-client.jsm -> resource://gre/modules/devtools/transport/transport.js:561:11
makeInfallible/<@resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/devtools/DevToolsUtils.js:82:14
makeInfallible/<@resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/devtools/DevToolsUtils.js:82:14

A: It turns out the hSC passed to SCardListReaders was wrong.
SCardListReaders(hSC.address(),

Should be:
SCardListReaders(hSC,


text:
Q: Set temporary directory: open_mfdataset xarray, dask(?), python I am opening multiple files with xarray.open_mfdataset and storing them again as one dataset. As I am doing so, my temporary directory runs out of memory.
How do I change the path to the temporary directory?
My code looks something like:
    import xarray as xr

    with xr.open_mfdataset( my_list_of_filepaths ) as in_data:

        out_data = some_data_manipulation( in_data )

        out_data.to_netcdf( out_filepath )

I have tried:
    import dask
    import xarray as xr

    with dask.config.set({'temporary_directory': 'path_to_temp_dir'}):

        with xr.open_mfdataset( my_list_of_filepaths ) as in_data:

            out_data = some_data_manipulation( in_data )

            out_data.to_netcdf( out_filepath )

and setting the environment variables TMPDIR, TEMP and TMP to my desired temporary directory without success.
Thank you!

A: xr.open_mfdataset( my_list_of_filepaths )

I believe you must pass at least chunks={} to the above call in order for dask to be invoked. You can check whether an array in your returned dataset is wrapping a Dask array or a normal one by checking its data attribute:
ds = xr.open_...
ds.my_variable.data

will either show concrete values (arrays of numbers) or dask.array.Array(...).


text:
Q: Polymorphic functions and type inference in SML Consider this function in Standard ML.
fun times_until_zero(f, x) =
  if x = 0 then 0
  else 1 + times_until_zero(f, f x)

REPL shows that times_until_zero has type (int -> int) * int -> int. But why isn't the type ('a -> int) * int -> int? All I can see from the function definition is that x has to be int and f has to take an argument which is at least as general as int and f has to return int. I tested it together with a function binding fun g x = 0 (so g has type 'a -> int)  and times_until_zero(g, 10) returned 1 just fine.

A: If times_until_zero had the type you suggest, then a caller would be allowed to do the following:
times_until_zero (string_to_int, 10)

where string_to_int : string -> int parses a string into an integer. Clearly, the call to f would not be type-correct anymore.
The subtlety here is where 'a is quantified, i.e., who gets to choose an instantiation. In the ML type system, the quantifier is always implicitly placed at the outermost position. That is, the type
('a -> int) * int -> int

actually means
forall 'a. (('a -> int) * int -> int)

Consequently, the caller of the function gets to pick a type for 'a.
For your example to be type-correct, you'd need the type
(forall 'a. ('a -> int)) * int -> int

With this the callee, i.e., your function, gets to pick a type for 'a, and can in fact pick a different one every time it calls f. On the flip-side, applying string_to_int would no longer be type-correct, since that function does not have the necessary polymorphic type.
However, types like the above with inner quantifiers (called higher-rank polymorphism) are not supported in plain ML, simply because type inference for them is not decidable in general.


text:
Q: Why aren't we sure that photons and gravitons are massless? In particle data group's (PDG) The Review of Particle Physics (2016) page number 29, the mass of the photon is given to be $<1\times10^{-18}eV$ and that of graviton as $<6\times10^{-32}eV$.

*

*In case those limits are experimental upper bounds, what makes them give theoretical value for gluons and experimental limits for photon and graviton?

*Why aren't we sure that photon's mass is zero, even though we are sure that gluons mass is zero (as given in it)?

*In case they have mass, why do we think graviton may have lesser mass that of the photon even though they both are carriers of forces of similar range?


text:
Q: Converting string to double in fluent-nhibernate mapping I have a sql table with a string column that could contain null, empty string or a double value.
I want to map this column to a C# property that is a double, defaulting to zero when the column is null or empty.
Can I do this with a fluent-nhibernate mapping?
I tried this:
Map(p => p.doubleProperty).CustomSqlType("varchar(20)").CustomType("double").Default("0");

and variations on this theme but I always get an error that the conversion failed.

A: For now I've gone with a custom type which allows me to use
      Map(p=>p.doubleProperty).CustomType<DoubleString>();

Which will do for my current needs.
I'll leave the question open for now in case someone comes up with an easier solution.
Code for the DoubleString type is below.
public class DoubleString : IUserType
{
    public new bool Equals(object x, object y)
    {
        if (ReferenceEquals(x, y))
        {
            return true;
        }
        if (x == null || y == null)
        {
            return false;
        }
        return x.Equals(y);
    }

    public int GetHashCode(object x)
    {
        return x.GetHashCode();
    }

    public object NullSafeGet(IDataReader rs, string[] names, object owner)
    {
        var valueToGet = NHibernateUtil.String.NullSafeGet(rs, names[0]) as string;
        double returnValue = 0.0;
        double.TryParse(valueToGet, out returnValue);
        return returnValue;
    }

    public void NullSafeSet(IDbCommand cmd, object value, int index)
    {
        object valueToSet = ((double)value).ToString();
        NHibernateUtil.String.NullSafeSet(cmd, valueToSet, index);
    }

    public object DeepCopy(object value)
    {
        return value;
    }

    public object Replace(object original, object target, object owner)
    {
        return original;
    }

    public object Assemble(object cached, object owner)
    {
        return DeepCopy(cached);
    }

    public object Disassemble(object value)
    {
        return DeepCopy(value);
    }

    public SqlType[] SqlTypes
    {
        get
        {
            return new[] { new SqlType(DbType.String) };
        }
    }

    public Type ReturnedType
    {
        get { return typeof(double); }
    }

    public bool IsMutable
    {
        get { return true; }
    }
}

A: I would just map this to a string and in your entity have a property that is a double that does the conversion.  Seems easier and cleaner than doing it in the mapping.
Maybe something like this:
public double Price
{
    get
    {
        double price = -1.0;
        Double.TryParse(stringProperty, out price);
        return price;
    }
    set { stringProperty = value.ToString(); }
}

A: I solved kind of the same problem using two Properties which both referred to the same private variable. In my example the database contains a varchar which is NOT USED or ACTUAL, i therefor wanted a bool in my application.
    private bool _myBool= true;

    public virtual bool MyBool{ get { return _myBool; } set { _myBool= value; } }

    public virtual string MyString
    {
        get { return _myBool ? "ACTUAL" : "NOT USED"; }
        set { _myBool= value.Equals("NOT USED"); }
    }
}


text:
Q: zip iterator with openmp won't go parallel I am trying to use a zip iterator (from either boost or thrust library) with openmp.  My goal is to have a for_each loop that will process things in parallel through openmp.
Using the example from the boost documentation:
#pragma omp parallel for
std::for_each(
    boost::make_zip_iterator(
    boost::make_tuple(beg1, beg2)
),
    boost::make_zip_iterator(
    boost::make_tuple(end1, end2)
),
    zip_func()
);

However, this doesn't appear to run in parallel.
Suggestions?

A: I am not an expert in OpenMP. I think that, to use a pragma omp for, OpenMP waits a complete for construction, for instance:
#pragma omp parallel for
{
for (i = 0; i < N; i++)

Besides, I think that std:for_each is implemented using OpenMP.
See http://gcc.gnu.org/onlinedocs/libstdc++/manual/parallel_mode.html

A: What you have to do is either use omp parallel for followed by a a for loop, use gcc __gnu_parallel::for_each as was previously suggested or explicitly partition your iteration range (notice the absence of for in the pragma):
#pragma omp parallel
{
int tid = omp_get_thread_num();
int n   = omp_get_num_threads();
auto nbeg1, nbeg2, nend1, nend2  = ... // create n chunks of work, each thread takes one chunk
std::for_each(
  boost::make_zip_iterator(boost::make_tuple(nbeg1, nbeg2)),
  boost::make_zip_iterator(boost::make_tuple(nend1, nend2)),
  zip_func() );
}


text:
Q: What tools exist for monitoring the CPU and memory utilization of Firefox? Firefox appears to using too much memory and cpu even when it is idle
What tools exist for monitoring the CPU and memory utilization of Firefox?
I am thinking of an equivalent of Sysinternals Process Explorer for Firefox or something like top or htop, on a page, script and addon basis. More technically oriented, something I can see and hand over to the script designers or Mozilla and say "see what this doing to my browsing experience!!"

A: You might want to consider using System Monitor:

Provides CPU usage and memory usage graphs on the toolbar.

A: It seems like Mozilla themselves is looking for such a tool.
The comments on that blog post lead to a few approaches to the problem:

*

*Memory Profiler

*XUL Profiler

*FireBug also contains profiling features

A: Go to More > Task Manager or typing about:performance in the address bar


text:
Q: How to unpack binary formatted dates in python? In a database export file i have a column with dates which are stored in binary format.
I'm trying to unpack dates in the file so that "\x07\xdb\x0c\x01" becomes "01-12-2011" again.
I know how the hexadecimal values corresspond to their decimal counterpart,
0x07DB = 2011
0x0C = 12
0x01 = 01

But how to properly unpack these formatted dates?

A: Use the struct module to unpack these values to a tuple of integers:
import struct
year, month, day = struct.unpack('>HBB', "\x07\xdb\x0c\x01")

The >HBB format specifier tells struct to expect 3 values in little endian format, one unsigned short (a 2 byte value, read as an integer) and to unsigned chars (1 byte values, read as integers).
You could then pass these to datetime.date() to create a date object if you want:
from datetime import date
import struct

somedate = date(*struct.unpack('>HBB', "\x07\xdb\x0c\x01"))

Demo:
>>> import struct
>>> from datetime import date
>>> date(*struct.unpack('>HBB', "\x07\xdb\x0c\x01"))
datetime.date(2011, 12, 1)

or you could use string formatting:
>>> '{2:02d}-{1:02d}-{0}'.format(*struct.unpack('>HBB', "\x07\xdb\x0c\x01"))
'01-12-2011'

to create a string representing that date.


text:
Q: CSS - Customising and arranging Flexsiders buttons Im so new to web design, CSS and html5 but im trying to learn. I reacently downloaded "FLEXSIDER" but i cant figure out how to arrange the buttons how i want. Any help would be so much appreciated. Here is an image of what im trying to achive:

Here is the html:

And this is the CSS I'm Using:
/* =================  Banner Start ================= */
.bannerFrame {
background:#f7f7f7 /*rgba(210,210,210,1)*/;
border-top:1px solid #ccc;
border-bottom:1px solid #ccc;
padding:25px 0 15px 0;
min-height:300px;
}
.bannerBg img {
height: 487.5px;
margin: auto;
overflow: auto;
position: absolute;
width: 932.5px;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
.bannerBg{
background:/*#00AEEF*/ rgba(0, 174, 239, 0.5);
border:15px solid #fff;
height:487.5px;
min-height:487.5px;
margin:0px auto 0px auto;
/*outline:2px solid rgba(200,200,200,0.5);*/
position: relative;
text-align:center;
width:932.5px;
/* Box Shadows */
box-shadow: 0px 0px 7px rgba(0,0,0,0.1);
-moz-box-shadow: 0px 0px 7px rgba(0,0,0,0.1);
-webkit-box-shadow: 0px 0px 7px rgba(0,0,0,0.1);
}
.bannerBgShadow {
background:url(../images/elements/bannerShadow.png) no-repeat;
display:block;
height:20px;
margin-left: auto;
margin-right: auto;
margin-top:0px;
width:1100px;
}
/* =================  Banner End ================= */

.cdplayer ul {
color:#999;
font-family:"Arial Black", Gadget, sans-serif;
font-size:14px;
letter-spacing:1px;
text-align:center;
}
.cdplayer li {
display: inline-block;
padding: 5px 20px 0 0;
}
.cdplayer li a {
color: #999;
text-decoration: none;
}
.cdplayer li a:hover {
color: #00AEEF;
text-decoration: none;
}
.cdplayer li a span.revPlayBtn {
background:url(images/icons/rewIcon.svg) no-repeat;
display:block;
height:41px;
margin-left: auto;
margin-right: auto;
padding: 0 0 5px 0;
width:41px;
}
.cdplayer li a:hover span.revPlayBtn {
background:url(images/icons/rewIconHover.svg) no-repeat;
}
.cdplayer li a span.playBtn {
background:url(images/icons/playIcon.svg) no-repeat;
display:block;
height:41px;
margin-left: auto;
margin-right: auto;
padding: 0 0 5px 0;
width:41px;
}
.cdplayer li a:hover span.playBtn {
background:url(images/icons/pauseIconHover.svg) no-repeat;
}
.cdplayer li a span.fwBtn {
background:url(images/icons/ffIcon.svg) no-repeat;
display:block;
height:41px;
margin-left: auto;
margin-right: auto;
padding: 0 0 5px 0;
width:41px;
}
.cdplayer li a:hover span.fwBtn {
background:url(images/icons/ffIconHover.svg) no-repeat;
}
.cdplayer li a span.stopBtn {
background:url(images/icons/stopIcon.svg) no-repeat;
display:block;
height:41px;
margin-left: auto;
margin-right: auto;
padding: 0 0 5px 0;
width:41px;
}
.cdplayer li a:hover span.stopBtn {
background:url(images/icons/stopIconHover.svg) no-repeat;
}
.cdplayer li:nth-child(2) {
padding-right: 10px;
}
.cdplayer li:nth-child(3) {
padding-left: 10px;
}


text:
Q: Signal m2m_changed never triggered class Lab(Model):
  pass

class School(Model):
  labs = ManyToManyField(Lab, related_name='schools')

def m2m_changed_labs(*args, **kwargs):
  pass

m2m_changed.connect(m2m_changed_labs, sender=Lab.schools)

The m2m_changed signal is never triggered, therefore the m2m_changed_labs function is never called. I want the m2m_changed_labs function to be called each time a school is added to or removed from a lab.

A: Have you tried sender=School.labs.through?
and with your receiver method like this:
def m2m_changed_labs(sender, **kwargs):  # notice sender instead of *args
    print "signal received"

That's the sender used in the example from the docs.


text:
Q: Take top X total items in a round robin from multiple arrays with Ramda I have an array of arrays and want to write a function that returns the top x number of items, by taking items from each array in order.
Here is an example of what I'm after:
    const input = [
      ["1a", "2a", "3a", "4a", "5a"],
      ["1b", "2b", "3b", "4b", "5b"],
      ["1c", "2c", "3c", "4c", "5c"],
      ["1d", "2d", "3d", "4d", "5d"]
    ];

    const takeRoundRobin = count => arr => {
      // implementation here
    };

    const actual = takeRoundRobin(5)(input);

    const expected = [
      "1a", "1b", "1c", "1d", "2a"
    ];

I saw a suggestion to a Scala question that solved this using zip but in Ramda you can only pass 2 lists to zip.

A: Here, Ramda's transpose can be your base.  Add a dollop of unnest, a dash of take, and you get this:

const {take, unnest, transpose} = R

const takeRoundRobin = (n) => (vals) => take(n, unnest(transpose(vals)))

const input = [
  ['1a', '2a', '3a', '4a', '5a'],
  ['1b', '2b', '3b', '4b', '5b'],
  ['1c', '2c', '3c', '4c', '5c'],
  ['1d', '2d', '3d', '4d', '5d']
]

console.log(takeRoundRobin(5)(input))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

Note also that this can handle arrays of varying lengths:

If you want to be able to wrap around to the beginning and continue taking values, you could replace take with a recursiveTake like this:

const {take, unnest, transpose, concat } = R

//recursive take
const recursiveTake = (n) => (vals) => {
  const recur = (n,vals,result) =>
    (n<=0)
      ? result
      : recur(n-vals.length,vals,result.concat(take(n,vals)))
  return recur(n,vals,[]);
};

const takeRoundRobin = (n) => (vals) =>
  recursiveTake(n)(unnest(transpose(vals)));

const input = [
  ['1a', '2a', '3a', '4a'],
  ['1b'],
  ['1c', '2c', '3c', '4c', '5c'],
  ['1d', '2d']
]

console.log(takeRoundRobin(14)(input))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

Another version of that function, without the explicit recursion would look like:
const takeCyclic = (n) => (vals) => take(
  n,
  unnest(times(always(vals), Math.ceil(n / (vals.length || 1))))
)

A: Here's one way you can do it using recursion –
const None =
  Symbol ()

const roundRobin = ([ a = None, ...rest ]) =>
  // base: no `a`
  a === None
    ? []
  // inductive: some `a`
  : isEmpty (a)
    ? roundRobin (rest)
  // inductive: some non-empty `a`
  : [ head (a), ...roundRobin ([ ...rest, tail (a) ]) ]

It works in a variety of cases –
const data =
  [ [ 1 , 4 , 7 , 9 ]
  , [ 2 , 5 ]
  , [ 3 , 6 , 8 , 10 , 11 , 12 ]
  ]

console.log (roundRobin (data))
// => [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 ]

console.log (roundRobin ([ [ 1 , 2 , 3 ] ]))
// => [ 1 , 2 , 3 ]

console.log (roundRobin ([]))
// => []

Free variables are defined using prefix notation which is more familiar with functional style –
const isEmpty = xs =>
  xs.length === 0

const head = xs =>
  xs [0]

const tail = xs =>
  xs .slice (1)

Verify it works in your browser below –

const None =
  Symbol ()

const roundRobin = ([ a = None, ...rest ]) =>
  a === None
    ? []
  : isEmpty (a)
    ? roundRobin (rest)
  : [ head (a), ...roundRobin ([ ...rest, tail (a) ]) ]

const isEmpty = xs =>
  xs.length === 0

const head = xs =>
  xs [0]

const tail = xs =>
  xs .slice (1)

const data =
  [ [ 1 , 4 , 7 , 9 ]
  , [ 2 , 5 ]
  , [ 3 , 6 , 8 , 10 , 11 , 12 ]
  ]

console.log (roundRobin (data))
// => [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 ]

console.log (roundRobin ([ [ 1 , 2 , 3 ] ]))
// => [ 1 , 2 , 3 ]

console.log (roundRobin ([]))
// => []

Here's another way using a secondary parameter with default assignment –
const roundRobin = ([ a = None, ...rest ], acc = []) =>
  // no `a`
  a === None
    ? acc
  // some `a`
  : isEmpty (a)
    ? roundRobin (rest, acc)
  // some non-empty `a`
  : roundRobin
      ( append (rest, tail (a))
      , append (acc, head (a))
      )

const append = (xs, x) =>
  xs .concat ([ x ])

A: To demonstrate what you may have seen as the implementation in other languages, the applicative instance for a ZipList can be used to transpose the array, where a ZipList applies the functions contained in the ZipList in a pair-wise manner with the corresponding ZipList of values unlike the standard permutative version of ap for lists.
const ZipList = xs => ({
  getZipList: xs,
  map: f => ZipList(R.map(f, xs)),
  ap: other => ZipList(R.zipWith(R.applyTo, other.getZipList, xs))
})

ZipList.of = x => ZipList(new Proxy([], {
  get: (target, prop) =>
    prop == 'length' ? Infinity : /\d+/.test(prop) ? x : target[prop]
}))

This has an interesting requirement which is somewhat clunky to represent in JS, where the of function to produce a "pure" value needs to produce a ZipList containing a repeating list of the "pure" value, implemented here using a Proxy instance of an array.
The transpose can then be formed via:
xs => R.unnest(R.traverse(ZipList.of, ZipList, xs).getZipList)

After all of this, we have just reinvented R.transpose as per the answer from @scott-sauyet.
It is nevertheless an interesting implementation to be aware of.
(full example below)

const ZipList = xs => ({
  getZipList: xs,
  map: f => ZipList(R.map(f, xs)),
  ap: other => ZipList(R.zipWith(R.applyTo, other.getZipList, xs))
})

ZipList.of = x => ZipList(new Proxy([], {
  get: (target, prop) =>
    prop == 'length' ? Infinity : /\d+/.test(prop) ? x : target[prop]
}))

const fn = xs => R.unnest(R.traverse(ZipList.of, ZipList, xs).getZipList)

const input = [
  ["1a", "2a", "3a", "4a", "5a"],
  ["1b", "2b", "3b", "4b", "5b"],
  ["1c", "2c", "3c", "4c", "5c"],
  ["1d", "2d", "3d", "4d", "5d"]
];

const expected = [
  "1a", "1b", "1c", "1d", "2a"
];

const actual = R.take(5, fn(input))

console.log(R.equals(expected, actual))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

A: Not sure what Ramda functions to use to address this particular problem but here is an answer not using Ramda that'll only work if all arrays are the same length:

const input = [
  ['1a', '2a', '3a', '4a', '5a'],
  ['1b', '2b', '3b', '4b', '5b'],
  ['1c', '2c', '3c', '4c', '5c'],
  ['1d', '2d', '3d', '4d', '5d'],
];

const takeRoundRobin = (count) => (arr) => {
  const recur = (arr, current, count, result) =>
    (current === count)
      ? result
      : recur(
        arr,
        current + 1,
        count,
        result.concat(
          arr
            [current % arr.length]//x value
            [//y value
              Math.floor(current / arr.length) %
                (arr.length + 1)
            ],
        ),
      );
  return recur(arr, 0, count, []);
};

console.log(takeRoundRobin(22)(input));


text:
Q: v-else not displaying any content I am currently learning about Vue.js and I found some strange behaviour about which I can't find anything in Internet.
For some reason DIV with v-else doesn't display any content I put inside.
I tried to learn why is that happening and all I found was that it is not advised to use v-for and v-if for same element (which I do not from what I understand).
When I remove v-else everything works perfectly. I put example of my code below (I think it is pretty self-explanatory, but if I am mistaken please say so and I will post more information). Thanks in advance for all the help!
 <template>

{{ error }}

{{ post.title }}

         #{{ tag }}

{{ post.body }}

        <Spinner />

    </template>

As requested here is my getPost method:
import { ref } from "vue";

const getPost = (id) => {
  const post = ref({});
  const error = ref(null);

  const load = async () => {
    try {
      //simulate delay
      await new Promise((resolve) => setTimeout(resolve, 1000));

      let data = await fetch("http://localhost:3000/posts/" + id);
      if (!data.ok) throw Error("Sorry, no data available");
      post.value = await data.json();
    } catch (err) {
      error.value = err.message;
    }
  };

  return { post, error, load };
};

export default getPost;

And here is how it looks in json-server:
{
  "posts": [
    {
      "id": 1,
      "title": "Welcome to my blog",
      "body": "Dolor proident consectetur veniam magna Lorem enim laboris cupidatat dolor do commodo officia veniam occaecat. Et incididunt in pariatur commodo fugiat elit eiusmod proident duis proident magna laborum occaecat minim. Ex eu sint cillum proident ea Lorem nulla consequat incididunt tempor reprehenderit laborum sit. Enim nulla sint sunt nulla deserunt officia occaecat sunt velit qui in aliquip. Non nulla et mollit esse ad qui mollit id.",
      "tags": ["webdev", "coding", "news"]
    },
    {
      "id": 2,
      "title": "Top 5 CSS tips",
      "body": "Et incididunt in pariatur commodo fugiat elit eiusmod proident duis proident magna laborum occaecat minim. Ex eu sint cillum proident ea Lorem nulla consequat incididunt tempor reprehenderit laborum sit. Enim nulla sint sunt nulla deserunt officia occaecat sunt velit qui in aliquip. Non nulla et mollit esse ad qui mollit id.",
      "tags": ["webdev", "coding", "css"]
    }
  ]
}

A: If the post is object you need to check it differently:

let post = {}
console.log(post) // returns empy object - true
console.log(Object.keys(post).length) // returns 0 - false

post = null
console.log(post && Object.keys(post).length) // returns null - false


text:
Q: SqlCacheDependency & custom table change We are using a third party who's own implementation of caching has very poor performance rates when we measure making requests via their API and their database.  Their database (Sql Sever 2005 - running in compatiablity mode - so thinking it is actaully a 2000 db) uses the same principals that SqlCacheDependency does in the sense it has a table with two columns

*

*tablename

*changeCount

and the triggers on the tables which update this custom table which logs the change count.
We are thinking of throwing away the third party caching and implementing our own solution.  using SqlCacheDependency with Asp.NET 3.5
Rather than going through the process of enabling the tables etc which creates the automated AspNet_SqlCacheTablesForChangeNotification with all the associated sp's, trigger etc, I would rather use the already existing data structure.
So my question is, is it possible to have SqlCacheDependency riged up so that rather than looking at the AspNet_SqlCacheTablesForChangeNotification and associated stored procs that it looks at the custom tables which are already defined in the db?

A: You could simply create those stored procedures with those name, but alter their implementation to work with your own data structure. I'm not sure you can tell the SqlCacheDependency what stored procedures to use, but because we do know what ones it wants to use, you could do a little slight of hand.


text:
Q: The affine algebra $\Gamma(V)$ is finite-dimensional iff $V$ is finite Proposition. Let $k$ be an algebraically closed field. Then $V\subseteq k^n$ is finite if and only if $\Gamma(V)$ is a finite-dimensional $k$-vector space (where $\Gamma(V)=k[x_1,\dots,x_n]/I(V)$ is the affine $k$-algebra of polynomial functions on $V$)
For the "$\Rightarrow$" implication, with $V=\{u_1,\dots,u_r\}$, I know about the proof with the map
$$\begin{align}
\varphi:k[x_1,\dots,x_n] & \longrightarrow k^r\\
F & \longmapsto \varphi(F)=(F(u_1),\dots,F(u_r))
\end{align}$$
whose kernel is $I(V)$ and ... but the first "proof" I came up with is setting
$$I(V)=I(\{u_1\}\cup\dots\cup\{u_r\})=I(u_1)\cap\dots\cap I(u_r)$$
with all $I(u_i)$ maximal by the Nullstellensatz, then
$$\Gamma(V)=k[x_1,\dots,x_n]/I(V)=$$
$$=k[x_1,\dots,x_n]/(I(u_1)\cap\dots\cap I(u_r))\hookrightarrow$$
$$\hookrightarrow k[x_1,\dots,x_n]/I(u_1)\times\dots\times k[x_1,\dots,x_n]/I(u_r)=k^r$$
Here i use that $k[\dots]$ over a maximal ideal is a field and can be considered an extension of $k$ of at most countable degree (which makes it equal to $k$ as it is algebraically closed).
Is this proof correct? In essecence it looks the same but i find it more "geometrical" (dont know why).
Also, why can't we say that $\Gamma(V)$ is $r$-dimensional? What can happen so that it has lower dimension? If we translate/scale the whole set $V$ nothing should change as we can translate/scale the polynomials. Also, relative positions of the point shouldn't matter because in $I(V)$ there are polynomials of arbitrarily high degree that can adjust/interpolate (in some vague sense) the position of the points (the closer two of them are the higher the degree).
Thanks!


text:
Q: Hibernate get List from database In the following code I am trying to get a List of Products which contains all the products in the database:
public List<Products> getAllProducts() throws Exception{
    try{
     List<Products> products ;
    org.hibernate.Transaction tx = session.beginTransaction();
    products = session.createSQLQuery("SELECT * FROM Products").list();
    if(products.size() > 0)
    {
        return products;
    }
    return null;
    }
    catch(Exception e)
    {
        throw e;
    }
}

however this exception is thrown:
[Ljava.lang.Object; cannot be cast to mediatek.Products

A: Your answer not only adds a cast, but switches from SQL to HQL.  Since your 2nd query is in HQL, Hibernate is able to use mapping information to know what class to return.  This is the preferred way to do things in Hibernate, but if you had to use SQL for some reason you could achieve the same thing with:
(List<Products>)session.createSQLQuery("SELECT * FROM Products").addEntity(Products.class).list();

A: List<Products> list = session.createCriteria(Products.class).list();

This will give you all the records of products table from database

A: In Hibernate 5 the session.createCriteria methods are deprecated.
You will need to use a CriteriaBuilder and query from there to get a generic list of Products instead of just List.
Imports
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;

Code
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Products> criteria = builder.createQuery(Products.class);
criteria.from(Products.class);
List<Products> products = session.createQuery(criteria).getResultList();

A: Forgot to type cast the query. it is working now.
List<Products> products  = (List<Products>) session.createQuery("from Products").list();

A: For example you have code:
Session session = getSessionFactory().openSession();
Transaction transaction = null;
try {
SQLQuery sqlQuery = session.createSQLQuery("SELECT * FROM schema.yourtable WHERE param = :param");
            sqlQuery.setString("param", "someParam");

And if your next step will be:
List list = sqlQuery.list();

You will receive list with Rows. You can see your Entity.class parameters in debug, but cat cast to List with your Entities:
List<Entity> list = (List<Entity>) sqlQuery.list();

In this point will be ClassCastException!

And if you need received List with your Entities you must add entity type to sql query:
List<Entity> list = (List<Entity>)sqlQuery.addEntity(Entity.class).list();

That's all. I hope someone will help.

A: if you using sql query, you should add this line at the last of the query to get the list you want:
.setResultTransformer(Transformers.aliasToBean(testDTO.class)).list();


text:
Q: Transpose select results with Oracle my question is, with some background:
I have to generate some sql queries based on the table metadata (column format), and the result is something like:
TABLENAME1|COL1
TABLENAME1|COL2
TABLENAME2|COL1
TABLENAME2|COL2
TABLENAME2|COL3
TABLENAME3|COL1
TABLENAME4|COL1
TABLENAME4|COL2
... /*some other 1800 rows */

(Yeah, it's ordered.)
What I need is to transpose this data, based on the first column, so the expected output would be:
TABLENAME1|COL1|COL2|NULL
TABLENAME2|COL1|COL2|COL3
TABLENAME3|COL1|NULL|NULL
TABLENAME4|COL1|COL2|NULL
/* less then 1800 rows ;-) */

Is it possible using Oracle SQL?
Thanks in advance!

A: If you want to generate the query for each call or use a hardcoded max-column-count, then you can do something like that:
WITH tab AS
(
  SELECT table_name, column_name FROM user_tab_cols WHERE column_id <= 4
) -- user_tab_cols used to provide test data, use your table instead
SELECT MAX(c1) c1,
       MAX(c2) c2,
       MAX(c3) c3,
       MAX(c4) c4
  FROM (SELECT table_name,
               DECODE( column_id, 1, column_name ) c1,
               DECODE( column_id, 2, column_name ) c2,
               DECODE( column_id, 3, column_name ) c3,
               DECODE( column_id, 4, column_name ) c4
          FROM ( SELECT table_name,
                        column_name,
                        ROW_NUMBER() OVER ( PARTITION BY table_name ORDER BY column_name ) column_id
                   FROM tab
               )
       )
 GROUP BY table_name
 ORDER BY table_name

If it is sufficient to get it in that form
TABLENAME1|COL1,COL2
TABLENAME2|COL1,COL2,COL3

have a look at Tom Kyte's stragg.

A: The keyword that you're looking for is pivot.  Here's an example of its use.  The syntax appears generally the same as MSSQL, and since I don't know the url for Oracle's documentation I'll toss up the MSDN link and hope that someone that knows more about Oracle's page layout than me will edit it to point to their documentation.
EDIT: Oracle documentation, search for pivot enough times and you'll get to the details.


text:
Q: Css order property doesn't update when set by Jquery When updating an element's order property after it is on the dom rendered like so, the html elements fail to reorder.
$(".test").css('order', '0');

Is this a known issue?
Edit: Yes, the container has the following css properties:
display: flex;
flex-direction: column;
overflow-y: overlay;
overflow-x: hidden;
position: relative;

Edit: error demonstrated in fiddle https://jsfiddle.net/me6g30ur/
My code:
$(".update").on("click", function() {
    for (var i = 0; i < $(".child").length; i++) {
      $(".child").css("order", Math.floor(Math.random * 100));
    }

  });

A: Two things wrong with your code (from your fiddle)

*

*Math.random is a function so you need to do Math.random()

*You need to choose the child element to update. You can use :eq(index) selector for that
Final code: https://jsfiddle.net/me6g30ur/3/
  $(".update").on("click", function() {
    for (var i = 0; i < $(".child").length; i++) {
        var order = Math.floor(Math.random() * 100);
      $(".child:eq(" + i + ")").css("order", order);
    }

  });

Side note:
Might be better to use jquery's .each loop instead of a for loop which would lead to less querying.
Then inside the loop you can do this.style.order = Math.floor(Math.random() * 100);


text:
Q: workflows to update data in IMIS enterprise cloud I am new to IMIS which is an Engagement management system with membership handling inbuilt. I need some inputs about the business process automation in IMIS. I see IMIS does not allow creating stored procedures to clients using IMIS cloud hosting. This seems to be a concern as every business has simple to complex processes and many processes updates data too. I am surprised to see that IMIS does not have a proper workflow builder (GUI based) where one can select as if some Business object is updated/created or have some value X then "update" some other business object/data i.e update the database table with specific values.
Best example if I want to use a custom Membership numbers (autonumbers) then I cannot do that. I cannot update table data via IMIS "process automation". IMIS "process builder"  offers very limited functionality. It do allows calling stored procedure via it but what is the use of it as we cannot create a stored procedure in IMIS. IMIS does allow calling 3rd party REST api via process automation too for particular trigger. With in IMIS there is no way to add custom code handling or custom process handling or a UI based workflow with if/else (a BPM which is available in Salesforce, Zoho and other CRM).
SO I want to know if there is any IMIS consultant here then please guide me how do you suggest handling complex business process automations ? I know IMIS allows REST API but that means I need to write a custom code to handle the process automation and it also means I need to do it outside of IMIS cloud. I just need a confirmation that business process need to be handled via customization outside IMIS through an external system. The external system will get data from IMIS, make the data changes and push it back to IMIS via API. I can build it but before doing so I am trying to make sure I am not missing something which is inside in IMIS (99% sure it cannot be done inside IMIS)
I also believe IMIS does not have webhooks as well as there is no menu to configure the same in IMIS. Please guide on this.
Please do not point me back to "process automation" menu or feature of IMIS as I am aware of it and its limitation too. I have explained its limitation above after checking with the IMIS support desk.

A: Nope, you can't do complex workflows in iMIS cloud (yet, as of July 2022). No web hooks either. Both of these requirements can be covered with a cloud based RPA solution.


text:
Q: IE support for multiple Angular ng-class expressions I have a code sample below where i check for file extension and accordingly set the icon for uploaded file. As there is support for multiple files, i have set icon for each of them and based on extension i apply related class with ng-class attribute. Its not working in IE11. I checked with single expression to confirm and it worked. Is there a workaround to this?
<i flex ng-class="{
          'icon-pdf': (fileDetails['extention'].search('pdf') != -1),
          'icon-word': (fileDetails['extention'].search('doc') != -1),
          'icon-ppt': (fileDetails['extention'].search('ppt') != -1),
          'icon-xls': (fileDetails['extention'].search('xlsx') != -1),
          'icon-html': (fileDetails['extention'].search('html') != -1),
          'icon-jpg': (fileDetails['extention'].search('jpg') != -1),
                        'icon-jpg': (fileDetails['extention'].search('png') != -1),
          'icon-wit': (fileDetails['extention'].search('txt') != -1)}"
>

A: I haven't read about this bug before but you could create a function that returns the proper class instead of having multiple ng-class attributes like so:
In your template:

And in your controller:
function getIconClass(search) {
    if(search('pdf') != -1)
        return 'icon-pdf';
    if(search('doc') != -1)
        return 'icon-word';
    if(search('ppt') != -1)
        return 'icon-ppt';
    if(search('xlsx') != -1)
        return 'icon-xls';
    if(search('html') != -1)
        return 'icon-html';
    if(search('jpg') != -1 || search('png') != -1)
        return 'icon-jpg';
    if(search('txt') != -1)
        return 'icon-wit';
}

A: I found out a way of doing it, using ng-class ternary operator besides Martijn's way (which is cleaner). Posting it for sake of expanding knowledge.
<i flex ng-class="
    fileDetails['extention'].search('pdf') != -1? 'icon-pdf':
    fileDetails['extention'].search('doc') != -1 ? 'icon-word':
    fileDetails['extention'].search('ppt') != -1? 'icon-ppt':
    fileDetails['extention'].search('xlsx') != -1? 'icon-xls':
    fileDetails['extention'].search('html') != -1? 'icon-html':
    fileDetails['extention'].search('jpg') != -1? 'icon-jpg':
    fileDetails['extention'].search('png') != -1? 'icon-jpg':
    fileDetails['extention'].search('txt') != -1? 'icon-wit': 'icon-html' ">


text:
Q: Installation error when running code with activity-alias I have used activity alias to show multiple app icons as per condition. The code is working fine but when I run the code in debug mode via usb directly it gives the below installation error :
Error while executing: am start -n "com.****.****/com.****.****.splashscreen.SplashScreen" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.****.****/.splashscreen.SplashScreenpinkathon }
Error type 3
Error: Activity class {com.****.****/com.****.****.splashscreen.SplashScreenpinkathon} does not exist.

Error while Launching activity

A: I had the same issue-- Android Studio's default launch option when debugging is "Default Activity," which picks the Activity or activity-alias based on your AndroidManifest.xml. If your app disables the default activity-alias, the next time you launch debugger won't be able to launch.
My work around for this was to change the Android Studio Run/Debug configurations to pick the Activity that the aliases target:
Run -> Edit Configurations -> Launch Options -> Change "Launch" to "Specified Activity", specify the target activity in "Activity"


text:
Q: Firebase authentication in ReactJS project - user null inside onAuthStateChanged I'm tearing my hair out trying to setup email/password authentication through firebase.
I've got my firebase configuration setup like so
// Firebase App (the core Firebase SDK) is always required and must be listed first
import firebase from "firebase/app";
//authenticaion module
import "firebase/auth";

// Add the Firebase products that you want to use
import "firebase/firestore";

var firebaseConfig = {
 // I've got my api key and other info copied from the console in here
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

export const db = firebase.firestore();
export const app = firebase.auth();

I've got a sign-in form created that calls the following function:
import { app } from "../firebase/firebaseConfig";

  const createAccount = () => {
    app
      .createUserWithEmailAndPassword(email, password)
      .then((user) => {
        console.log("user created");
        console.dir(user);
      })
      .catch((error) => {
        console.log("something went wrong");
      });
  };

First problem: I'm not seeing the "user created" message, even though I can see the user being created in the Firebase Authentication console. I'm also not seeing the "something went wrong" message that would indicate an exception occurred.
Second problem: I'm trying to do a re-direct when the user signs in. To do this, I've setup a listener on the Firebase auth object as suggested in the docs:
firebase.auth().onAuthStateChanged((user) => {
  console.log("Inside listener");
  console.dir(user);
});

The problem is, I'm seeing the console message so the function is triggering but 'user' is always null in here even though the user is being created.
Firebase version: 8.2.1
Can anyone see what I'm missing here?

A: It is normal that in an auth state listener your callback first gets called with null, as that is typically the initial user authentication state as the page is loaded.
Firebase tries to automatically restore the user's authentication state, but this may take some time. Only once the state is restored will it again call your auth state listener with the then active user account.

A: I found a solution in case anyone runs into a similar issue - the button that was triggering the submit was inside a html form and I was not calling event.preventDefault() and so the page was re-rendering and I believe this was causing the auth callback to work incorrectly. Working code -
  const createAccount = (event) => {
    event.preventDefault();
    app
      .createUserWithEmailAndPassword(email, password)
      .then((user) => {
        console.log("user created");
        console.dir(user);
      })
      .catch((error) => {
        console.log("something went wrong");
      });
  };


text: Q: How to add friends to my roster in node xmpp? I want to add friends to my Spark roster.With this client i'm connected to node-xmpp server.How i should do this?I've saw events like client.on('connect)  or `client.on('stanza') .Is there a way to do this in this mode ?I think an event is executed when a a friend is added


text:
Q: Google play store like interface using recycler view My assignment is to create an interface much same like Google Play Store.There will a Category name followed by 3 or 4 cards (horizontal) followed by More button. Then again next category.
I already had implemented this using nesting the horizontal listview inside Vertical listview.
I know, I can achieve this by using the Recycler view with LinearLayoutManager with horizontal orientation. Using this I'll be having one only row.
My question is how do I add 2nd, 3rd row to this?
Should I use again nested Recycler view?
Are there some better options?

A: Dont use nested listviews (you cant scroll horizontally in play store).
Consider the following options:

*

*You can use a simple LinearLayoutManager and make different view types. For the with 3 cards horizontally use a GridLayout or LinearLayout with same weights. The problem here is, that you have to consider the indexes of your underlying data list used in the adapter

*Write your own LayoutManager for RecyclerView

*Use TwoWay View which is based on RecyclerView and offers a Spannable Grid Layout manager, which seems to be what you are looking for.

A: If you inspect the layout of the Google Play app, they do not use a listview/recyclerview for the horizontal cards. I'm pretty sure that is just a linearlayout (horizontal) within a vertical listview / recyclerview.
If you insist on using a horizontal recyclerview for each row, then having a nested recyclerview would be your best option. You can specify a RecycledViewPool so that all the nested recyclerviews share the same pool instead of creating their own.

A: You may like to do it as one vertical RecyclerView (Main recycler) and for every section you can inflate a horizontal RecyclerView as well (Section recycler) as this blog answer mention:
Also, consider using:

*

*A cache layer for Bitmaps for persistent access through your other store screens

*A lazy load method for your category/section images

*A place holder before showing new items


text:
Q: How do you punctuate around parentheses? Which of these punctuation examples is more correct?

*

*On December 7, 1941, ("a date which will live in infamy") Japan bombed Pearl Harbor.

*On December 7, 1941 ("a date which will live in infamy"), Japan bombed Pearl Harbor.

*On December 7, 1941, ("a date which will live in infamy"), Japan bombed Pearl Harbor.

Edit: A little background on my question may be in order. According to most, if not all, online references I could find, a comma is required after the year when writing a date in the above American style. For example, from Wikipedia: "most style manuals, including The Chicago Manual of Style and the AP Stylebook, recommend that the year be treated as a parenthetical, requiring a second comma after it." See also, Chicago Manual of Style Online, the Language Portal of the Canadian Government, and Wikipedia's own style guide.
I couldn't find a reference for how to punctuate serial parentheticals.

A: There's no need for a second comma in On December 7, 1941 Japan bombed Pearl Harbor, so there's no need for one when you insert the words in brackets. You can write On December 7, 1941 ("a date which will live in infamy") Japan bombed Pearl Harbor.

A: Of your three options, I consider the first best, as the second option seems to associate your quote with just the year, and the third option's final comma seems entirely unnecessary, as the parentheses are jarring enough for the reader to not need another comma!
May I ask why you think the parentheses are necessary? The sentence would be better if you simply omit them, and perhaps rephrase:
Japan bombed Pearl Harbor December 7, 1941, "a date which will live in infamy."
"A date which will live in infamy," Japan bombed Pearl Harbor December 7, 1941.
Japan bombed Pearl Harbor on "a date which will live in infamy," December 7, 1941.

Also, I did not modify the quoted text, but note the which should be that.

A: In the original sentence, there are two commas required after "December 7, 1941" (or more accurately, there are two reasons for the single comma). You get one comma because you would write "On December 7, Japan bombed Pearl Harbor". You get another for the date: "December 7, 1941," where the year is set off by commas. Normally, these two commas would be coalesced into one, but the parenthetical statement actually belongs between the two commas, so you need the third option.
If you would write:

On December 7 Japan bombed Pearl Harbor,

(which is acceptable, although I'd include the comma), you don't need the comma after the parenthesis. If you would write

December 7, 1941 was the day that Japan bombed Pearl Harbor,

without the second comma (again acceptable, although I believe most style guides will tell you to include the comma), you don't need the comma before the parenthesis.


text:
Q: (Prolog) the first solution from the list that satisfies the goal I need to find the first element on the list which satisfies a user provided goal. I mean something like maplist/2 but which succeeds when the goal can be applied to at least one element. include/3 would be an option but I'm after a more optimal solution that can stop after finding the first element.
I think the interface could look like:
first(:Goal, List, First)

and it should be semidet in the SWI-Prolog sense.
It's fairly easy to code it but I'd prefer an existing rule. Is there a relevant rule in the "standard" libraries; I'm using SWI-Prolog.
Cheers,
  Jacek

A: I don't think there's a standard predicate that does this. But as you say, it would be very easy to code. I would probably write something like this, which has a pattern like the member/2 predicate:
includes_item(Goal, [X|_], X) :-
    call(Goal, X).
includes_item(Goal, [_|T], X) :-
    includes_item(Goal, T, X).

As @false indicates in the comments, this in fact can be more clearly written using member/2:

includes_item(Goal, List, Item) :-
    member(Item, List),
    call(Goal, Item).

includes_item(:Goal, List, Item) succeeds for each Item in List that satisfies :Goal. For example:
3 ?- includes_item('>'(3), [1,2,3,-2, 4, 5], X).
X = 1 ;
X = 2 ;
X = -2 ;
false.

You can then use once/1 to obtain only the first item without a choice point:
first(Goal, List, Item) :-
    once(includes_item(Goal, List, Item)).

And now you get:
4 ?- first('>'(3), [1,2,3,-2, 4, 5], X).
X = 1.

5 ?-


text:
Q: JVM crash on Tesseract.getWords API invocation running with ubuntu docker image I am trying to extract words from image using tess4j. When I invoke getWords API then JVM crashes in some case.
Following are the versions for relevant packages/software

*

*Java version: 11

*Tomcat version: 8.5

*Relevant java dependencies
<dependency>
    <groupId>net.sourceforge.tess4j</groupId>
    <artifactId>tess4j</artifactId>
    <version>4.3.1</version>
</dependency>
<dependency>
    <groupId>org.bytedeco.javacpp-presets</groupId>
    <artifactId>tesseract-platform</artifactId>
    <version>4.0.0-1.4.4</version>
</dependency>

Followings are my observation

*

*If I run the same setup on my fedora (version 29) desktop it works fine.

*If I run inside docker with the same setup but with the base image as ubuntu:18.04, then on extraction of words from image JVM crashes.

*Please note that env TESSDATA_PREFIX is set appropriately. Also I tried by setting LC_ALL=C  but no luck if I run with docker image.

Crash report from catalina.out
contains_unichar_id(unichar_id):Error:Assert failed:in file ../ccutil/unicharset.h, line 513
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007f1fe7aa369b, pid=40, tid=89
#
# JRE version: Java(TM) SE Runtime Environment (11.0.2+9) (build 11.0.2+9-LTS)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (11.0.2+9-LTS, mixed mode, tiered, compressed oops, g1 gc, linux-amd64)
# Problematic frame:
# C  [libtesseract.so.4+0x25969b]  ERRCODE::error(char const*, TessErrorLogCode, char const*, ...) const+0x16b
#
# Core dump will be written. Default location: Core dumps may be processed with "/usr/lib/systemd/systemd-coredump %P %u %g %s %t %c %h %e" (or dumping to /app/identity-service/core.40)
#
# An error report file with more information is saved as:
# /app/identity-service/hs_err_pid40.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.

One of thread the had problem from thread dump
Current thread (0x00007f210015a800):  JavaThread "fb5c080c-25bb-494a-8e6d-1df6df91c188" daemon [_thread_in_native, id=89, stack(0x00007f206e7d2000,0x00007f206e8d3000)]

Stack: [0x00007f206e7d2000,0x00007f206e8d3000],  sp=0x00007f206e8cdbb0,  free space=1006k
Native frames: (J=compiled Java code, A=aot compiled Java code, j=interpreted, Vv=VM code, C=native code)
C  [libtesseract.so.4+0x25969b]  ERRCODE::error(char const*, TessErrorLogCode, char const*, ...) const+0x16b

Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
j  com.sun.jna.Native.invokeInt(Lcom/sun/jna/Function;JI[Ljava/lang/Object;)I+0
j  com.sun.jna.Function.invoke([Ljava/lang/Object;Ljava/lang/Class;ZI)Ljava/lang/Object;+211
j  com.sun.jna.Function.invoke(Ljava/lang/reflect/Method;[Ljava/lang/Class;Ljava/lang/Class;[Ljava/lang/Object;Ljava/util/Map;)Ljava/lang/Object;+271
j  com.sun.jna.Library$Handler.invoke(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;+344
j  com.sun.proxy.$Proxy25.TessBaseAPIRecognize(Lnet/sourceforge/tess4j/ITessAPI$TessBaseAPI;Lnet/sourceforge/tess4j/ITessAPI$ETEXT_DESC;)I+20
j  net.sourceforge.tess4j.Tesseract.getWords(Ljava/awt/image/BufferedImage;I)Ljava/util/List;+31

Can you please help?

A: Update:
This turned out to be memory issue


text:
Q: Where can I add "already" in "I am going to have gone to bed by the time you come home"?
I am going to have gone to bed by the time you come home

Where can I add "already" in this question?

A: You could add it after "am", but your sentence sounds very unidiomatic.
This would be likelier:
"I will already have gone to bed by the time you get home."

A: You could place "already" after "am", or before "gone to bed" or after "gone to bed".
I'd probably rephrase to avoid the future perfect:

I'll already be in bed by the time you get home.


text:
Q: How center the chapter* titles I want center the title "Preface" and "Abstract" only. I do not want to centralize all the chapters. I can not and I should not delete any bookstore, I need all the libraries.
\documentclass{book}
\usepackage[left=3cm, right=2cm, top=2cm, bottom=2cm]{geometry}
\usepackage{lipsum}
\usepackage{lscape}
\usepackage[utf8]{inputenc}

\usepackage[spanish,es-tabla]{babel}

\usepackage[table]{xcolor}

\usepackage{sectsty}
\sectionfont{\fontsize{12pt}{14.4pt}\selectfont\sffamily\bfseries}
\subsectionfont{\fontsize{11.5pt}{13.8pt}\selectfont\sffamily\bfseries}
\subsubsectionfont{\normalsize\sffamily\bfseries}

\begin{document}

\chapter*{\centering Preface}

Some text
\chapter*{\centering Abstract}

\chapter{Introduction}
\chapter{Body}
\chapter{Conclusion}

\end{document}

A: Set the title inside a \makebox[\linewidth]; this naturally centres it. It would not have any impact on headers or the ToC since these elements don't end up there.

\documentclass{book}

\usepackage{lipsum}

\begin{document}

\chapter*{\makebox[\linewidth]{Preface}}
\lipsum[1]

\chapter*{\makebox[\linewidth]{Abstract}}
\lipsum[2]

\chapter{Introduction}
\chapter{Body}
\chapter{Conclusion}

\end{document}

A: Fast solution
You could set a manual space
\chapter*{\hspace{.4\textwidth}Preface}

which puts the title almost in the middle of the page
Reasoned solution
Otherwise you could think of measuring the length of your title and make the thing more precise with the package calc
%PREAMBLE
\usepackage{calc}

\newlength\mylen
\newcommand\chaplen[1]{
    \setlength\mylen{(\textwidth-\widthof{\Huge\bfseries #1})/2}
}

%... BEGIN DOCUMENT

\chaplen{Preface}
\chapter*{\hspace*{\mylen}Preface}

\chaplen{OTHER}
\chapter*{\hspace*{\mylen}OTHER}

FUll code:
\documentclass{book}
\usepackage[left=3cm, right=2cm, top=2cm, bottom=2cm]{geometry}
\usepackage{lipsum}
\usepackage{lscape}
\usepackage[utf8]{inputenc}

\usepackage[spanish,es-tabla]{babel}

\usepackage[table]{xcolor}

\usepackage{sectsty}
\sectionfont{\fontsize{12pt}{14.4pt}\selectfont\sffamily\bfseries}
\subsectionfont{\fontsize{11.5pt}{13.8pt}\selectfont\sffamily\bfseries}
\subsubsectionfont{\normalsize\sffamily\bfseries}

\usepackage{calc}

\newlength\mylen
\newcommand\chaplen[1]{
    \setlength\mylen{(\textwidth-\widthof{\Huge\bfseries #1})/2}
    }

\begin{document}

\chaplen{Preface}
\chapter*{\hspace*{\mylen}Preface}

Some text
\chaplen{Abstract}
\chapter*{\hspace*{\mylen}Abstract}

\chapter{Introduction}
\chapter{Body}
\chapter{Conclusion}

\end{document}

A: Using the tools from sectsty:
\documentclass{book}
\usepackage[left=3cm, right=2cm, vmargin=2cm]{geometry}
\usepackage{lipsum}
\usepackage{lscape}
\usepackage[utf8]{inputenc}

\usepackage[spanish,es-tabla]{babel}

\usepackage[table]{xcolor}

\usepackage{sectsty}
\sectionfont{\fontsize{12pt}{14.4pt}\selectfont\sffamily\bfseries}
\subsectionfont{\fontsize{11.5pt}{13.8pt}\selectfont\sffamily\bfseries}
\subsubsectionfont{\normalsize\sffamily\bfseries}

\begin{document}

\chapterfont{\huge\bfseries\centering}
\chapter*{\centering Preface}

Some text
\chapter*{\centering Abstract}

\chapterfont{\huge\bfseries\raggedright}
\chapter{Introduction}
\chapter{Body}
\chapter{Conclusion}

\end{document}


text:
Q: Ideas for an algorithm to randomly place interrelated nodes I apologise for the title, I realise it isn't especially descriptive. I'll try to describe my problem in greater detail.
I have a set of "nodes", for sake of example we'll title them A, B, C, D, and E. These nodes are unique from one another in the sense that they have are "related" to each other, though only to specific nodes. In my real implantation, there could be thousands of nodes and I would like to develop an algorithm which could place them appropriately, regardless of their quantity.
We'll pretend the associations are as follows:
A: B, D

B: A, C, D

C: E

D: A, B

E: C

This format means that A is related to B and D, etc.
My goal is to display these relationships on a 2D plane by drawing each node as a circle, and drawing a line between them. I would like to display them in a "web" type fashion, meaning that the nodes do not overlap whatsoever, and the distance between related nodes is minimized. I would like for the diagram to suggest that by starting at A, for instance, one could travel next to B, then to C, and finally to E.
In a case such as B's, where it itself is related to C while C is not related to B, there does not have to be a distinction to suggest that. That is to say, showing that A:B and B:A can be the same as saying that B:C, despite C is not related to B.
I hope I have made myself clear in what I would like to accomplish. I don't think I'll have very much trouble coding the actual algorithm, I just for the life of me can't think of a way logical way to approach the problem.
Any suggestions at all are greatly appreciated, I don't need pseudocode or step by step instructions, just some advice from some more seasoned programmers who may be able to look at the problem from a different perspective.
Thanks!

A: Try searching for "force directed graph drawing".
The basic idea is as follows:

*

*Initialize node positions randomly (putting them with equal distances on a circle turned out to be good)

*Apply Forces between the nodes:

*

*Nodes push off each other

*if they are related, they are additionally pulled towards each other

*Repeat step 2 until you have a nice layout.

There is a live example at http://getspringy.com/


text:
Q: Spark Categorical Data Encoding Is there a function in Spark to do Categorical data encoding.
Ex:
Var1,Var2,Var3
1,2,a
2,3,b
3,2,c

To
var1,var2,var3
1,2,0
2,3,1
3,2,2

a -> 0, b->1, c->2

A: Use this function for Categorical data encoding.
python
def get_mapping(rdd, idx):
    return rdd.map(lambda x: x[idx]).distinct().zipWithIndex().collectAsMap()

Scala
val categories = rdd.map(r => r(2)).distinct.collect.zipWithIndex.toMap

A: Python - PySpark 2.0.0 +
df = pd.read_csv("file.csv",keep_default_na=False)
df = spark.createDataFrame(df)
types =  df1.dtypes
arity = {}
i=0
for c,t in types:
    if(t == 'string'):
        arity[i] = len(df1.select(c).distinct().collect())
        print arity[i],i,c
    i+=1

This arity dictionary can act as your input to categoricalFeaturesInfo


text:
Q: Cannot restore data from pg_dump due to blank strings being treated as nonexistant data I have a database currently on a PostgreSQL 9.3.9 server that I am backing up with pgdump in the simplest possible fashion, eg pg_dump orb > mar_9_2018.db.
One of those tables (linktags) has the following definition:
CREATE TABLE linktags (
    linktagid integer NOT NULL,
    linkid integer,
    tagval character varying(1000)
);

When attempting to restore the database on PostgreSQL 11.2 via
cat mar_9_2018.db | docker exec -i pg-docker psql -U postgres
(docker container restore) the table returns empty because of the following error -
ERROR:  missing data for column "tagval"
CONTEXT:  COPY linktags, line 737: "1185    9325"
 setval

I checked the db file and found that there are missing tabs where I would expect some sort of information, and clearly the restore process does as well.

I also verified that the value in the database is a blank string.
So -

*

*Is there an idiomatic method to backup and restore a postgres database I am missing?

*Is my version old enough that this version of pg_dump should have some special considerations?
Am I just restoring this wrong?

Edit:
I did some further research and found that I was incorrect in the original checking of NULLs, it was instead blank strings that are causing the issue.
If I make an example table with null strings and then blank strings, I can see the NULLs get a newline but the blank does not

A: pg_dump has an option to use INSERT instead of COPY
pg_dump -d db_name --inserts

as the manual warns, it might make restoration slow (and much larger dump file). Even in case of some inconsistencies tables will be filled with valid rows.
Another problem is with empty tables, pg_dump generates empty copy statement like:
COPY config (key, value) FROM stdin;
\.

in this case you'll be getting errors on reimport like:
 ERROR:  invalid input syntax for type smallint: "  "
CONTEXT:  COPY config, line 1, column group: "  "

which doesn't happen with --insert option (no insert statement is generated).


text:
Q: How to measure ISR execution time? I am on linux kernel 2.6.32.
I am facing an issue in which one of the two ISR (serial and ethernet) are taking more time (hundreds of microseconds) on several occasion/under some scenarios which I don't know. I would like to get the time difference every time the ISR executes.
What would be the best way (least expensive in terms of overhead involved). I don't see ARM architecture has some TSC register (read_tsc api) which would give me direct access to time as it offers on some other architecture.
So Idea is
1) The moment ISR is invoked measure time
2) the moment ISR is complete measure the time.
3) get the difference of 1 and 2 store it in some variable.
4) Keep doing the steps 1 to 2 and when the value received in the step 3 is greater than the past value overwrite it (keep/preserve value with maximum latency).
When the issue happens (some abrupt condition print the value) or array of last 10 value).
I need to do in kernel driver so let me know what would be the least expensive way.

A: OMAP3 has Cortex-A8 core. That does have Performance Monitor Unit (PMU). Cycle Count (CCNT) would correspond to x86 TSC, except probably you have to enable it counting before you read. Good info in BeagleBoard post.
In 2.6.32.55 I see arch/arm/oprofile/op_model_v7.c gives full access and control. My need was bare-metal, I used ARM example code that was simple and worked for me.
It would also be possible to use an OMAP3 GPT, but that would be more work, e.g. to get its clock input set up from PRCM.


text:
Q: find the minimum of $A=\frac{x^3}{3y+1}+\frac{y^3}{3z+1}+\frac{z^3}{3x+1}$ with $x^3+y^3+z^3=3$ With $x,y,z \ge 0, x^3+y^3+z^3=3$: find the minimum of $A=\dfrac{x^3}{3y+1}+\dfrac{y^3}{3z+1}+\dfrac{z^3}{3x+1}$
My attempts: $A=\dfrac{x^6}{3yx^3+x^3}+\dfrac{y^6}{3zy^3+y^3}+\dfrac{z^6}{3xz^3+z^3} \ge \dfrac{(x^3+y^3+z^3)^2}{3(yx^3+zy^3+xz^3)+x^3+y^3+z^3}=\dfrac{3}{yx^3+zy^3+xz^3+1}$ and I don't know what to do next (I think my approach is not right)

A: The key observation is the term $3x,3y,3z$ at the denominators. This suggests the application of the AM-GM inequality somehow. Indeed, by AM-GM inequality: for $a \ge 0 \implies a^3 + 2 = a^3 + 1 +1 \ge 3a\implies a^3+ 3 \ge 3a+1$. Using this fact for $a = x, y, z$ in the denominators of $A$. Thus: $A \ge \dfrac{x^3}{y^3+3} + \dfrac{y^3}{z^3+3}+\dfrac{z^3}{x^3+3}$. Now let $m = x^3, n = y^3, p = z^3 \implies A \ge \dfrac{m}{n+3}+\dfrac{n}{p+3}+\dfrac{p}{m+3}$, with $m+n+p=3$ and $m,n,p \ge 0$. Using Cauchy-Schwarz inequality twice: $\displaystyle \sum_{\text{cyclic}}\dfrac{m}{n+3} = \displaystyle \sum_{\text{cyclic}}\dfrac{m^2}{mn+3m}\ge \dfrac{3(m+n+p)^2}{3(mn+np+pm)+9(m+n+p)}\ge \dfrac{3\cdot3^2}{(m+n+p)^2+9\cdot 3}=\dfrac{27}{9+27}=\dfrac{27}{36}= \dfrac{3}{4}$. Equality occurs in the original inequality when $m = n = p = 1 \implies x = y = z = 1$.

A: @SuzuHirose's use of standard Lagrange methods indeed finds an extremum.  Here's a color-coded plot of the target function on the cubic surface to show that:

The minima occur when $x = y = z = 1$, etc., as seen in the figure, where blue is small.

A: Note: The following answer is incorrect, see comments. I don't have a correct version yet. However since the other answer mentions this, I've marked it as community wiki and made it visible.
Let
$$
L
=
\lambda (x^3+y^3+z^3-3)+{x^3\over 3y+1}+{y^3\over 3z+1} +{z^3\over 3x+1}\\
$$
Differentiating with respect to $\lambda, x, y$, and $z$ gives
$$
{\partial L\over\partial\lambda}=x^3+y^3+z^3-3
$$
and three symmetric equations of the form
$$
{\partial L\over\partial x}=3x^2(\lambda+{1\over 3y+1})
$$
Setting $\partial L/\partial\lambda=\partial L/\partial x=...=0$ gives $\lambda=-1/(3y+1)=-1/(3z+1)=-1/(3x+1)$,  so $x=y=z$ and since $x^3+y^3+z^3=3$, $x=y=z=1$.


text:
Q: How to identify a unique identifier of a duplicate records? I have duplicate records in a table. I need to be able to identify only one unique identifier so I can delete it from the table.
The only way I know there are a duplicate is from columns subject and description so if there are at least 2 of the same subject and the same description, I need to delete one and leave one.
So I was able to get a list of the duplicate records but I am not able to get the unique identifier to be able to delete it.
This is what I have done to identify the duplicate records.
SELECT
    p.accountid, p.subject, p.description, count(*) AS total
FROM
    activities AS p
WHERE
    (p.StateCode = 1) AND p.createdon >= getdate()-6
GROUP BY
    p.accountid, p.subject, p.description
HAVING
    count(*) > 1
ORDER BY
    p.accountid

There is a column record_id which holds the unique identifier for each record. But if I added record_id to my select statement then I get no results because it is impossible to have a duplicate unique identifiers
How can I get the record_id using SQL Server?
NOTE: the record_id is not an integer it is something like "D32B275B-0B2F-4FF6-8089-00000FDA9E8E"
Thanks

A: One nice feature that I like about SQL Server is the use of CTEs with update and delete statements.
You are looking for duplicate records and presumably want to keep either the lowest or highest record_id.  You can get the count and the id to keep using a CTE and window functions:
with todelete as (
    SELECT p.accountid, p.subject, p.description,
           COUNT(*) over (partition by p.accountid, p.subject, p.description) as total,
           MIN(record_id) over (partition by p.accountid, p.subject, p.description) as IdToKeep
    FROM activities AS p
    WHERE (p.StateCode = 1) AND p.createdon >= getdate()-6
   )
delete from todelete
    where total > 1 and record_id <> IdToKeep;

The final where clause just uses the logic to select the right rows to delete.
I should add, if you just want the list that would be deleted, you can use the similar query:
with todelete as (
    SELECT p.accountid, p.subject, p.description,
           COUNT(*) over (partition by p.accountid, p.subject, p.description) as total,
           MIN(record_id) over (partition by p.accountid, p.subject, p.description) as IdToKeep
    FROM activities AS p
    WHERE (p.StateCode = 1) AND p.createdon >= getdate()-6
   )
select *
from todelete
 where total > 1 and record_id <> IdToKeep;

The over function indicates that a function is being used as a window function.  This idea is simple.  Count(*) over returns the count for all records with the same values for the fields in the partition clause.  It is a lot like the aggregation function, except you get the value on every row.  This class of functions is quite powerful, and I'd recommend that you learn more about them.

A: Perhaps something like this?
SELECT max(p.record_id), p.accountid, p.subject, p.description, count(*) AS total
FROM activities AS p
WHERE (p.StateCode = 1) AND p.createdon >= getdate()-6
GROUP BY p.accountid, p.subject, p.description
HAVING count(*) > 1
ORDER BY p.accountid

A: Seems to me you need to do an inner query first, then join against the larger table to get what you want.
SELECT ALL
    *
FROM (SELECT p.accountid
  FROM activities AS p
  WHERE p.statecode = 1 AND p.createdon >= getdate()-6
  GROUP BY p.accountid
  HAVING count(*) > 1) AS x
JOIN activities AS a ON x.accountid = a.accountid
ORDER BY p.accountid

A: Try this:
;with recordsToDelete as (
SELECT
     recordId
    ,Row_Number() OVER(partition p.subject, p.description) as rowNum
FROM activities AS p
)

select
*
from recordsToDelete
where rowNum > 1

If that looks correct, you can replace the select with:
delete from recordsToDelete
    where rowNum > 1


text:
Q: What am I doing wrong here? WordPress database error I'm just trying to insert values into custom table of wordpress and it throws me this error
WordPress database error:
[You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to use near
'( post_id, site_id, u_id, is_present )
VALUES ( 989, 139, '1' at line 2]
INSERT INTO ( post_id, site_id, u_id, is_present ) VALUES ( 989, 139, '10822456', 'false' )

I'm using prepare query to Protect Queries Against SQL Injection Attacks.
Here is my code
$wpdb->query($wpdb->prepare(
"
    INSERT INTO $wpdb->wp_plugs
    ( post_id, site_id, u_id, is_present )
    VALUES ( %d, %d, %d, %s )
",
    $post_id,
    $site->ID,
    $u_id,
    'false'
) );