text:
Q: Save Flot Chart as PDF I am trying to save entire flot (Pie/Bar)Chart to PDF. I am using jQuery/FLOT to draw a Pie and Bar Chart.
I have the code for downloading the flot chart as PDF but I have three charts in one page and the problem is once I click download they printed in the page and in the same time I got them in different PDF separately.
My question is it possible to have them all in one pdf and without printing them in the page.
Any idea ?
Thank you.
Here is my code:

  Download as PDF

  var _canvas = null;

   $(function() {
   $.plot($("#container"), [ { label: 'Test', data: [[0, 0], [1, 9]] } ], { yaxis: { max: 1 } });
   $("#toPdf").on("click", function(e) {
    e.preventDefault();

        html2canvas($("#container").get(0), {
            onrendered: function(canvas) {
                document.body.appendChild(canvas);

                var imgData = canvas.toDataURL('image/png');
                console.log('Report Image URL: '+imgData);
                var doc = new jsPDF('landscape');

                doc.addImage(imgData, 'PNG', 10, 10, 190, 95);
                doc.save('testingPDF.pdf');
            }
        });
         });
      });

A: Have you tried removing the canvas once the work is done?
$(function() {
    $.plot($("#container"), [ { label: 'Test', data: [[0, 0], [1, 9]] } ], { yaxis: { max: 1 } });
    $("#toPdf").on("click", function(e) {
    e.preventDefault();

        html2canvas($("#container").get(0), {
            onrendered: function(canvas) {
                document.body.appendChild(canvas);

                var imgData = canvas.toDataURL('image/png');
                console.log('Report Image URL: '+imgData);
                var doc = new jsPDF('landscape');

                doc.addImage(imgData, 'PNG', 10, 10, 190, 95);
                doc.save('testingPDF.pdf');
                document.body.removeChild(canvas); //  newly added line
            }
        });
    });
});

UPDATE
Check out this new fiddle (you wanted something link this right?)
HTML

Generate to pdf

CODE
var _canvas = null;

$(function () {
    $.plot($(".container1"), [{
        label: 'Testing1',
        data: [
            [0, 0],
            [1, 9]
        ]
    }], {
        yaxis: {
            max: 1
        }
    });
    $.plot($(".container2"), [{
        label: 'Testing2',
        data: [
            [0, 0],
            [1, 9]
        ]
    }], {
        yaxis: {
            max: 1
        }
    });
    $.plot($(".container3"), [{
        label: 'Testing3',
        data: [
            [0, 0],
            [1, 9]
        ]
    }], {
        yaxis: {
            max: 1
        }
    });

    window.allcanvas = [];

    $("#toPdf").on("click", function (e) {
        e.preventDefault();
        var allcontainers = $('[class^="container"]');
        allcontainers.each(function (index, elem) {
            html2canvas($(elem).get(0), {
                onrendered: function (canvas) {
                    window.allcanvas.push(canvas);
                    if(allcontainers.length == allcanvas.length){
                        finalpdf();
                    }
                }
            });
        });
    });
    finalpdf = function(){
        var doc = new jsPDF('landscape');
        for(var i = 0; i<allcanvas.length;i++){
            var imgData = allcanvas[i].toDataURL('image/jpeg');
            doc.addImage(imgData, 'JPEG', 10, 10, 190, 95);
            if(i != allcanvas.length-1)
                doc.addPage();
        }
        doc.save('testingPDF.pdf');
    };
});


text:
Q: I need to convert PDDocument to File Object I am trying to split a pdf document through org.apache.pdfbox.multipdf.Splitter and need to perform certain file operations on this single page PDDocument,
How can I convert PDDocument to File Object in java?

A: Very simple. I am using 1.8.16
    try {
        PDDocument document = PDDocument.load(new File(filename));

        // do what ever you want
        document.save(newfilename);

    } catch (IOException | BadSecurityHandlerException | CryptographyException e) {
        e.printStackTrace();
    }
    finally {
        if(document != null )
            try {
                document.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //return tmpFile != null ? tmpFile.getAbsolutePath() : null;
        return tmpFilename;
    }

A: with Apache commons
   InputStream is = null
    try {
     PDDocument document = PDDocument.load(filePath);
     File targetFile = new File("nameoffile.pdf");
     PDStream ps = new PDStream(document);
     is = ps.createInputStream();
     FileUtils.copyInputStreamToFile(is, targetFile);
    } catch (IOException io) {} finally {
     if (is != null)
      IOUtils.closeQuietly(is);
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Touchpad requires you to press really hard on MacBook 2.1 On my white MacBook 2.1 I have to press to my finger really hard to the touchpad to even move the mouse pointer. I did not have to do that when I had OSX installed on it.
Any ideas?

A: A lot of people with Macbook varieties have installed alternate drivers for the trackpad so they can modify them to their hearts' content.  In my case, I installed xf86-input-mtrack driver.  To install it, at the terminal type:
sudo apt-get install xserver-xorg-input-mtrack

Put in password as usual when prompted.
Now you need to actually switch from the old driver (called "multitouch") to this one.  You will need to put some entries in /etc/X11/xorg.conf
sudo nano /etc/X11/xorg.conf

Put in:
    Section "InputClass"
        MatchIsTouchpad          "on"
        Identifier               "Touchpads"
        Driver                   "mtrack"
    EndSection

This is the bare minimum you need in the conf file.  You will undoubtedly want to now experiment and tweak it until the driver gets to the Goldilocks "just right" stage.
Here is the readme by the author of the driver:  https://github.com/BlueDragonX/xf86-input-mtrack/blob/master/README.md
It explains the different options.  Here's an example, using my conf:
     Section "InputClass"
          MatchIsTouchpad    "on"
          Identifier         "Touchpads"
          Driver             "mtrack"
          Option             "Sensitivity"           ".67"
          Option             "TapButton1"            "0"
          Option             "TapButton2"            "0"
          Option             "TapButton3"            "0"
          Option             "ScrollDistance"        "100"
          Option             "FingerHigh"            "8"
          Option             "FingerLow"             "8"
      EndSection

I don't like any of the tapping business, so I turned them off.  FingerHigh is what you are most interested in.  Default value is 5.  It defines the minimum pressure the touchpad will recognize as a touch.  As you can see, I found it very sensitive, so I set it to 8.
Now reboot.  If all goes well, you've fixed your problem.  It's that easy (or at least, it should be -- knock on wood).
Finally, a discussion thread started by the driver author is here:  http://ubuntuforums.org/showthread.php?t=1730361
A fair amount of the info in there is outdated, not applicable, or in some cases wrong (some examples of the xorg.conf files mistakenly have "multitouch" where "mtrack" should be).  But the initial post is worth reading as it explains the author created dispad to work with the driver, for those who accidentally touch trackpad a lot while typing.  I don't have that problem, so I didn't install dispad, but maybe you will need it.


text:
Q: How do I fill a c# observable collection with strings with a callback that was called by an unmanaged DLL? My app needs to display strings of data, and those strings come from unmanaged X.dll, which delivers each line through a callback function.
I've created this pipeline to deal with X.dll in c#:
Xapp
  -> X-csharp.dll   // c#, managed front end to X-api.dll
     -> X-api.dll   // Shim to expose the pieces of X.dll needed
        -> X.dll    // Original dll

I don't want to repeat exactly how it works since that's been done many times, but if I need to say more than __declspec(dllexport), internal static class NativeMethods, DllImport, etc.,
let me know and I'll write it up.
Regarding flow, Xapp does an init call that gets down to X.dll, followed by an open call, and then a getData call that includes a callback declared a lot like this:
public delegate void dataCBfunc(IntPtr entry, IntPtr arg);

My static callback function includes the conversion
string line = Marshal.PtrToStringAnsi(entry);

The whole thing works the way I intended in my testbed app.
Now I'm doing the real MVVM implementation, and I want the lines added to an ObservableCollection that I've bound to a datagrid.  This is where my problem lies.
The callback is static.  I was hoping to do the rudimentary C++ trick of passing an opaque pointer to the instance of the class or to the ObservableCollection, as an "arg" arg to X.dll.  X.dll doesn't need it, it just passes it back to the callback so that the line can be added to the ObservableCollection.  I tried
ObservableCollection<RemoteListModel> remoteList
   = arg as ObservableCollection<RemoteListModel>;

and got back
Error CS0030: Cannot convert type 'System.Collections.ObjectModel.ObservableCollection<Xapp.Model.RemoteListModel>' to 'System.IntPtr' Xapp

I've tried a few other things too, and basically get the same type of message, which makes sense.
That said, how might I achieve what I'm after without doing something terrible?  Terrible could mean write it to a file and read it later... less terrible might be using shared memory to do the same... or I could add a couple sockets and do it that way.  I feel like I shouldn't have to resort to such things.  If anyone could help with tips on how to solve this, I'd appreciate it.  Thanks for reading.

A: My working backup solution, if there's no way to pass a direct instance of the ViewModel (or ObservableCollection) down to the dll and back up to the callback:

*

*Name the View user control I added to the MainWindow XAML

*Create the ViewModel instance in the MainWindow constructor

*Set the View control DataContext and the MainWindow DataContext to the ViewModel instance

*Access the ObservableCollection in my static callback with
TheViewModel rvm = Application.Current.MainWindow.DataContext as TheViewModel;
As is, I'm restricted to one TheViewModel instance in my app, but if necessary, I could extend it to have the MainWindow DataContext point to a table of instances and use an index in the callback argument to reference the right one.


text:
Q: WAFileLibrary alternative 1)I had a set of ".js" files in a particular Directory structure.
2)I NEED to store them locally with my smalltalk image and need not want to host them seperately.
3) I DONT need to keep them  inside the smalltalk image, with the WAFileLibrary.
Please let me know how  the following code needs to be modified for my requirement.
anHtmlRoot javascript url: 'http://www.google.com/jsapi'.
Something like the following..?
anHtmlRoot javascript url: "/myfolder/MyFile.js"
Help
Varun Isac

A: You can indeed write:
anHtmlRoot javascript url: '/myfolder/MyFile.js'

but it's better to use:
    anHtmlRoot javascript resourceUrl: 'MyFile.js'

Which allows you to setup the path as a configuration parameter. More on that in the Seaside book.
To serve the actual file, there are two options:

*

*serve the file from disk with an external webserver (on the same
machine)

*serve the file from disk using the internal Smalltalk
webserver

For the latter option, you can load the Seaside-Filesystem package from the Seaside30LGPL repository. Once loaded, you can define an 'external directory' handler for your 'myFolder' directory using the Seaside config tool and that handler will serve the files from the disk.


text:
Q: Why is Safari rendering inline blocks inconsistently when word spacing applied? I am trying to create paragraphs of text where each word is actually a div containing text and a canvas above it (long story!). This means I end up with a series of divs in each paragraph, which I style as inline blocks. These divs look too close together, so I use the CSS word-spacing property to increase the spacing between them.
This works fine on every browser except Safari. On Safari (OS X and iOS), the words spill over the edge of the containing div, even when I fix the width of the container. I suspect that this is a bug in Safari, since all other browsers seem to render my HTML the same way, but does anyone have a way around it?
I have distilled the problem down to this example HTML:

This

text

should

look</div
the

same

in

both

boxes

but

it

doesn't

in

Safari

            This text should look the same in both boxes but it doesn't in Safari

This can also be viewed as a JS Fiddle here: http://jsfiddle.net/4eh6G/
P.S. On older versions of Safari, there seems to be a different problem, where word-spacing appears to have no effect at all in this example. Any fix for this would obviously be great, too!


text:
Q: I get an error when dialing as a function My project(shortly):

*

*I'm doing the bookmark section in the Yandex Browser.

Problem:

*

*I've made a bookmark before. The code on that project was:

$("#siteImg").change(function(e){
    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {
        var file = e.originalEvent.srcElement.files[i];

        // image operation
        var reader = new FileReader();
        reader.onloadend = function() {
            source = String(reader.result);
        }
        console.log("asf")
        reader.readAsDataURL(file);
        }
        addBookmark();
    })

There is no problem in this code. Working properly. But I do not want the program to work when the input changes in my current project. I want this code to work when a button is pressed. I wrote a code for this:

function imageData(e){
    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {
        var file = e.originalEvent.srcElement.files[i];

        // image operation
        var reader = new FileReader();
        reader.onloadend = function() {
            source = String(reader.result);
        }
        console.log("asf")
        reader.readAsDataURL(file);
        addBookmark();
    }
}

This code is not working properly. Probably the cause of the problem "e". But I couldn't figure it out. The error message says:

View the codes here

A: originalEvent is part of jQuery and not javascript. In Javascript, you can access the srcElement from event directly.

// jQuery
$('button').on('click', function(e) {
    console.log(e.originalEvent.srcElement);
});

// Javascript
const button = document.querySelector('button');
button.addEventListener('click', function(e) {
    console.log(e.srcElement);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click</button>

A: It sometimes occurs that when an inline event listener involves the event object, it won't be found. It's better to pass a function reference from your JavaScript:
$("#button").onclick = imageData;

A: As I understand you are calling imageData() from different places. For Example :
$("#siteImg1").change(function(e){
     /**/
}

$("#siteImg2").change(function(e){
     /**/
}

You can handle it all image's change event at one place by adding a class siteImg and update your code like :
 $(".siteImg").change(function(e){
     imageData(e);
 }


text:
Q: How to make overlay pane start at the top? (template10, UWP) i use template10 for my UWP-App and need to achive that overlay pane starts at the most top. Do you have any ideas if it is possible?
What i have
What i need

A: In template 10, it is designed so that the HamburgerButton is separated away from the SplitView, you can refer to the source code of HamburgerMenu.xaml. Take a blank Hamburger(Template 10) app's  MainPage for example, you can comment out the controls:PageHeader and modify the controls:Resizer like so:
<controls:Resizer x:Name="parameterResizer" Margin="16,16,16,0"
                  RelativePanel.AlignLeftWithPanel="True"
                  RelativePanel.AlignTopWithPanel="True">

This will solve part of this problem, but it only scratches the surface of a problem, when the window's size is resized or when it runs on mobile, because of its built-in, unexposed-to-the-project style of template 10, this method will fail to make the HamburgerMenu open from the start of the page.
If you're using Template 10, it's better to stick to use its HamburgerMenu, it will make the work easier. But if you insist to make it open from the start of the page, you can create your own SplitView which the HamburgerButton is inside of the SplitView, and together maybe your own navigation system for this.


text:
Q: rnd function in ms access returns same value I have the following ms access query:
SELECT * from mytable WHERE chaptId IN (SELECT Top 1 chaptId  FROM  (SELECT chaptId, Rnd(RowID) AS RandomValue FROM mytable) ORDER  BY RandomValue)
Basically it takes from a table a random unique chaptID value, and for this value extracts all the rows that have this chaptID value.
it works perfectly through ms access. When I try to run it from within VB6 (ADO DB), it always returns the same chaptID and thus the same chapter. Searching I found that I have to use the Randomize function. I don't know how to include it in the query. So I tried to wrap it like this: Rnd(Randomize(RowID)). I did not know how else to use it.
The message I get is Undefined function Randomize in epxression
How can I solve this problem?
Thank you in advance.

A: It's not possible, as discovered, to randomize when using Rnd using ODBC/ADO.
This means we have to introduce randomness somehow.
An obvious choice is by using the system timer:
SELECT * from mytable WHERE chaptId IN (SELECT Top 1 chaptId  FROM  (SELECT chaptId, Rnd(-1 * (RowID + Timer() * 100)) AS RandomValue FROM mytable) ORDER  BY RandomValue)

A: You may study my project on rownumbers, VBA.RowNumbers, which also deals with pseudo-random ordering - see paragraph 4 and the form `Form_RandomProducts.cls``.
For truly random numbers, see my project VBA.Random. A little more code, but simple to implement.
If you only can run native Access SQL, this basic query should do (as your subquery):
SELECT
    *,
    Rnd(-Timer()*[RowID]) AS [Rnd Generator]
FROM
    mytable
ORDER BY
    Rnd(-Timer()*[RowID]);

A: Since your goal is to get a random chapter each time, why not get a random chapter before running the query:
Dim FirstChapter as Integer
Dim LastChapter as Integer
Dim RandomChapter as Integer

FirstChapter = DMin("ChaptId","mytable")
LastChapter = DMax("ChaptId","mytable")

Randomize

RandomChapter = Int((LastChapter - FirstChapter + 1) * Rnd + FirstChapter)

'run vba ADO code for the following SQL
"SELECT * from mytable WHERE chaptId IN (" & RandomChapter & ")"


text:
Q: How can I get object's parameter of array with firestore? I want to get Q2 array and it contains D1's value.
{

'A': {
  'Q1': 'A1',
  'Q2': [
   {'D1': 'hello'}
  ]
 },

'B': {
  'Q1': 'A1',
  'Q2': [
   {'D1': 'hello'}
  ]
 }

}

I tryed to query like this.

*

*where('Q2.D1','==','hello')

*where('Q2.D1','array-contains','hello')

*where('Q2','array-contains',{D1: 'hello'})

*...

But they are not working :(

A: Firestore does not support querying map values inside arrays.  The only thing you can query for in an array is an entire array element.  So, you can search for the entire value {'D1': 'hello'}, but not just the map's field value 'hello'.
You will need to add a new structure for this, or change what you have.  For example, you could create a new array with all the possible values of D1, and use an array-contains query to find documents with the D1 you specify.


text:
Q: How to prevent my jsp application from Cross Frame Scripting? I am using jsp.
I have to provide security to the application from Cross Frame Scripting. I have to ensure that all pages that gather user information prior to and during authentication are not vulnerable. The pages must prevent being encapsulated within a frameset of an unauthorized site.
Need to know more how to prevent frames from becoming encapsulated.
I have already gone through the below link but couldn't find the appropriate solution.
"https://www.owasp.org/index.php/Cross_Frame_Scripting"
I'm expecting some demo project so that I can understand more about Cross Frame Scripting and how my application is safe from being encapsulated.

A: Use the X-Frame-Options header with value DENY, SAMEORIGIN or ALLOW-FROM uri in your HTTP response to prevent your website being loaded in a frame.
Another method is validating your url with the source url and reload the page with your url if any cross frame scripting find.
Refer below script to do it.
    <script>
     window.onload = function() {
      if (window.location !== window.top.location) {
       window.top.location = window.location;
      }
     }
    </script>


text:
Q: Opera does not call Flash's ExternalInterface.callback() function inside js callback called by flash I'm new to Flash ActionScript. I've a flash audio recorder (modified jRecorder) that records audio in WAV format and I've added support for MP3 encoding. The recorder exports some public functions for JS using ExternalInterface.callback() and also calls JS callbacks using ExternalInterface.call() from flash container (website). When a flash exported function is called from JS to start recording/encoding/other that function from flash also calls JS callback event handler for event like- recording_started, recording_stopped, encoding_started, encoding_ended etc. It works fine in IE, FF, Chrome but not in Opera.
I've used it in a web project as follows-
-> Recording time is maximum 2 min and recording stops when user stops it (button) or when time limit reached. And for both conditions, 'recording_stopped' event is triggered and inside that event handler, mp3 encode function is called (a flash exported function).
-> Here, JS event handler is called by flash and which in tern calls a flash exported function.
The problem is, in opera, the exported flash function is not called inside the handler. If the function is called at the end of the handler, all codes above the function are executed but not that function and if I place the function at the beginning of the handler, the codes below it are not executed. And no JS error is shown in the console. But, if I called it from a JS function which is not a callback event handler for flash, the function is executed fine.
I've tested it on two different computers with Opera versions 11.51 & 12.15 and flash player versions 11.3, 11.6 & 11.7.
My opera version is 12.15 and flash player version is 11.7 (for all browsers).
Why is it happening?

A: I've found a way to ignore this problem while typing this question. Solution is, instead of calling the flash exported function directly from the event handler, I'm calling it using JS's window.setTimeout() function like -
window.setTimeout(function(){
    if($.jRecorder.encodeToMp3())
      isEncoding = true;
}, 0);

I'm not sure why it is happening. @Raptor commented a reason on the question and it can be that reason or else.


text:
Q: Why I can't vote again, unless there's an edit to post? What is the reason behind not letting people vote again on the same post (for example -- after changing mind, i.e. downvote after previous upvote, upon further reading or after certain comments)? What this suppose to do, what prevent or in what this should help?
I can't vote again on post, where I have already voted, but I can... edit this post, do some really tiny change and then I can vote again, without any restrictions. Where's the logic?
EDIT: Neither given answer nor linked question (which most of you takes incorrectly as dupe) answers my question. I'm not talking about poor edits etc. I'm precisely asking, why I (with 2k+ rep) am blocked with this restriction, which I can very easily override by doing simple edit? In this case, 2k+ users shouldn't have this dual-voting restriction at all. This question has nothing to do with poor edits or tactical voting. It addresses this -- voting again after changing mind, after explanation by post author made in comments.

A: Most of your question has been covered here:
Idea behind "Your vote is now locked in unless this answer is edited"

However, just to comment on:

I can... edit this post, do some really tiny change and then I can
  vote again, without any restrictions. Where's the logic?

Well, there is awareness raised by an edit.
And the "restrictions" are privileges.
For a direct edit the post owner will be notified, and the question will be bumped onto the front page. And the edit visible to all users who naturally see the post following the edit.
You need 2K rep or more for this, and users with 2K rep and above are fairly familiar with how voting works, and shouldn't be editing to change votes. They're not as likely to make many voting mistakes anyway.
Less than 2k rep are suggested edits, and they have to be peer reviewed so numerous users will see it, including the post owner, and if the edit is approved the post will be bumped to the front page.

It is logical, and necessary
Edits should be based on the edit validity. Regardless of the motives being to change a vote, if the edit is worthy/useful then it should be applied. If this changes votes then all the better for the site, as it makes for better quality and accurately identified content.
Once the post is edited the content has been changed from what their original vote was for. So it's quite viable (and logical) to allow users to change their vote following an edit.
The new edit can make the post poor, so users can retract their upvote and downvote if desired (this is usually from post owners of course, anyone else making posts poor from edits should invoke a rollback).
Also, what quite often happens is a poor post is rectified/improved from an edit and so downvotes can be retracted, and upvotes applied if desired.
The edit being inadequate or poor is another matter however, but this is irrespective of the motives to make the edit.


text:
Q: How to create constant C like struct objects under a namespace in Python I want to create constant objects of a class that I can use again and again in other classes and functions
# Simple C like struct
class data:
  def __init__(self,a,b)
    self.a = a
    self.b = b

# Constant objects in a namespace ??
class DATA_CONSTANTS:
  DATA1 = data(0,0)
  DATA2 = data(3,5)
  DATA3 = data(43, 23)

If I now want to use DATA_CONSTANTS.DATA1, will it be created on first call or everytime I refer to this object ?
What I am looking for is something like in C++ where you create constant objects in a global or given namespace that can be reused as a constant object with fully qualified name say DATA_CONSTANTS::DATA1 or DATA_CONSTANTS::DATA2 etc.
However I am not sure what I am doing above is a pythonic way to accomplish the same in Python. Is this correct ?

A: Variables declared in the upper level of a class are class variables, and are only created once at the site that they're declared, then they remain constants. You can see this for yourself:
def calc_value():
    print("computed the value")
    return 1

class Foo:
    my_var = calc_value()

print(Foo.my_var + Foo.my_var)
# prints "computed the value" then 2


text:
Q: Google Drive viewer "document to images" conversion: is there an API for that? We are developing a document viewer to show documents to our users in the browser (webapp). We would like to use the excellent "document to images" feature of the Google Drive Viewer to convert our documents (PDF, Word, Excel, ...) to images.
Is it possible in any way? (API, libraries that we could run on our servers, other ideas?)
Thank you!

A: This one might be worth a look: http://saaspose.com/
From their front page:

Saaspose is a cloud-based document generation, conversion and automation platform for developers.

From the description of their Words API:

Saaspose.Words, a cloud-based document creation, manipulation and conversion API, helps you process documents with its many flexible features. Saaspose.Words' platform independent document manipulation API is a true REST API that can be used with any language: .NET, Java, PHP, Ruby, Rails, Python, jQuery and many more. The API integrates with other cloud services to give you the flexibility you need when processing documents.

A: A search for Google Drive Viewer returned a third party Chrome extension.
The Google Drive API does allow for file conversions, but the closest to your needs would seem to be conversion to a pdf file
https://developers.google.com/drive/v2/web/integrate-open#open_and_convert_google_docs_in_your_app
You can try a file export here
https://developers.google.com/drive/v2/reference/files/export
In the "Try this API" box, enter the fileID of one of your files, and put
application/pdf
in the MIME type box and click on the execute button.


text:
Q: Shifting eigenvalues via skew-symmetric product Let $X$ be an $n\times n$ real positive definite matrix and consider the following matrix
$$
Y=SX,
$$
where $S$ is an $n\times n$ real skew-symmetric matrix. Let $\{\lambda_i\}_{i=1}^n$, $\lambda_1\ge \lambda_2\ge\cdots\ge \lambda_n$, be the ordered eigenvalues of $X$ and let $\{\mu_i\}_{i=1}^n$, $\Re[\mu_1]\ge \Re[\mu_2]\ge\cdots\ge \Re[\mu_n]$ be the ordered (w.r.t. real parts) eigenvalues of $Y$.

My question. Does there exist a skew-symmetric $S$ such that the real part of the eigenvalues of $Y$ are greater than those of $X$, that is,
  $$
\Re[\mu_i] \ge \lambda_i, \quad i=1,\dots,n \ \ ?
$$
  If not, does there exist a skew-symmetric $S$ such that the largest real part of the eigenvalues of $Y$ is greater than the largest eigenvalue of $X$, that is,
  $$
\Re[\mu_1] \ge \lambda_1 \ \ ?
$$

A: $Y=SX$ is similar to the skew-symmetric matrix $X^{1/2}SX^{1/2}$. Therefore the real parts of the eigenvalues of $Y$ are always zero and they cannot possibly be greater than any eigenvalue of $X$ (which is positive).


text:
Q: An exception has been raised that is likely due to a transient failure - connect local PostgreSQL to Docker container I am trying to access the PostgreSQL on the server from a Docker container in which I run a .net app.
My Dockerfile contains the following environment variables:
ENV DB_DATABASE=db_name
ENV DB_USERNAME=db_username
ENV DB_PASSWORD=db_pw
ENV DB_HOST=public IP (not localhost!)
ENV DB_PORT=port (not the standard 5432)

In Startup.cs I construct the connection string like so:
string host =  Environment.GetEnvironmentVariable("DB_HOST").ToString();
string port =  Environment.GetEnvironmentVariable("DB_PORT").ToString();
string db_name = Environment.GetEnvironmentVariable("DB_DATABASE").ToString();
string db_username = Environment.GetEnvironmentVariable("DB_USERNAME").ToString();
string db_password = Environment.GetEnvironmentVariable("DB_PASSWORD").ToString();

string db_setting = String.Format("Host={0}; Port={1}; Username={2}; Password={3}; Database={4};",host, port, db_username, db_password, db_name);

I am sure that the port, IP, etc for the database are not wrong because they are used in other Docker containers.
The errors that I get:
System.InvalidOperationException: An exception has been raised that is likely due to a transient failure.
       ---> Npgsql.NpgsqlException (0x80004005): Exception while connecting
       ---> System.Net.Sockets.SocketException (111): Connection refused

They files the error point me are database queries.

A: The problem is solved. Apparently, the database port has changed. I find that pretty strange because I had another app that was using the same database with the old port and it was working just fine.

A: Try to update the following code snippet:
string db_setting = String.Format("Host={0}; Port={1}; Username={2}; Password={3}; Database={4};",host, port, db_username, db_password, db_name);

To
string db_setting = String.Format("Host={0}; Port={1}; User Id={2}; Password={3}; Database={4};",host, port, db_username, db_password, db_name);


text:
Q: velero backups failing for "backup resource list not found" After the upgrade of velero from 1.3.2 to 1.7.7 backups started failing.
When describing the failing backup:
velero backup describe mypod-20220204170020 --details

Name:         mypod-20220204170020
Namespace:    velero
Labels:       velero.io/schedule-name=mypod
              velero.io/storage-location=default
Annotations:  velero.io/source-cluster-k8s-gitversion=v1.21.2
              velero.io/source-cluster-k8s-major-version=1
              velero.io/source-cluster-k8s-minor-version=21

Phase:  Failed (run `velero backup logs mypod-20220204170020` for more information)

Errors:    0
Warnings:  0

Namespaces:
  Included:  mypod
  Excluded:  <none>

Resources:
  Included:        *
  Excluded:        <none>
  Cluster-scoped:  auto

Label selector:  <none>

Storage Location:  default

Velero-Native Snapshot PVs:  auto

TTL:  168h0m0s

Hooks:  <none>

Backup Format Version:  1.1.0

Started:    2022-02-04 18:00:20 +0100 CET
Completed:  2022-02-04 18:00:41 +0100 CET

Expiration:  2022-02-11 18:00:20 +0100 CET

Total items to be backed up:  64
Items backed up:              64

Resource List:  <backup resource list not found>

Velero-Native Snapshots:  <error getting snapshot info: file not found>

At first sight it seems like the backups were made correctly:
Errors:    0
Warnings:  0
Items backup: 64 of 64
However, right at the bottom (and only when adding the --details flag with the describe command), you see these two mentions:
Resource List:  <backup resource list not found>
Velero-Native Snapshots:  <error getting snapshot info: file not found>

Is there some clever way to troubleshoot this further? Or do someone have thoughts on what might be the issue here?

*

*Running on AKS (1.21.2)

*Using velero-plugin-for-microsoft-azure:v1.3.1 for snapshots to azure

Much appreciated!

A: Not sure if this solves the issue for everyone, but it worked for me.
After searching inside the velero source code repo,
I located the following go package velero/pkg/cmd/util/output/backup_describer.go that contained the error message I found when describing the failing backup.
See line 328 (1)

The hints at (2) in the source code led me to search on upload issues.
As I am using the velero-plugin-for-microsoft-azure to handle uploads to Azure the following GitHub issue finally gave me the nudge in the right direction.
Seems like the velero-plugin-for-microsoft-azure required more memory (512Mi) since v1.5.3 (if I understood it correctly).
The limits on my one were still at 256Mi and failing, I increased the limits to 512Mi and, presto! It started working again.
A big shout out to David L. Smith-Uchida whose breadcrumbs led me to the solution!

A: I need to know where your data reside means it is using azure disk, or in file share.. Velero does not support azure file share data


text:
Q: VS2008 SP1 hot-fixes for C++ development: where can I found a comprehensive list? I'm still using VS2008 SP1 for C++ development mainly because the IDE is faster than VS2010 SP1.
I'd like to have a comprehensive list of post-SP1 hot-fixes for VS2008, focused on C++ development.
I found some of them in this blog post: Available hotfixes for VC2005-SP1 / VC2008 RTM / VC2008-SP1 .
However, this list seems not comprehensive. For example, I happened to find this blog post by Visual C++ Team: Visual C++ Precompiled Header Errors on Windows 7, which contains a link to another post-SP1 hot-fix for VS2008: KB976656

A: This page is the only one I'm aware of that resembles anything comprehensive:
https://connect.microsoft.com/VisualStudio/downloads/


text:
Q: "Impossible" NPE in a multi-threaded situation I have some inherently asynchronous code in an Android app. I'm using RxJava2. The class Thing is not under my control (but ThingFactory is). In one method (createThing()), a new Thing is instantiated. Thing's constructor does some work and, when it is complete, notifies us via a callback onThingInitialized(). At the point that callback is called, we should be guaranteed that thing exists. In the callback, I schedule work to happen on a separate thread (in this case, using RxJava2, but I don't think it should matter). There is nowhere in this code that I call anything like thing = null. So, once it's set, it's set forever.
I threw a volatile onto it because the instance does get updated, but never nulled. If I'm mis-using it, please feel free to berate me.
public class UsesAThing implements ThingCallbacks {

    private volatile Thing thing; // I feel like I don't understand 'volatile'

    // I call this method
    public void createThing() {
        thing = thingFactory.newThing(param1, param2);
    }

    // Thing's constructor does some work and notifies us when it's done
    @Override
    public void onThingInitialized() {
        // Called on main thread, but I want to do some IO work, so:
        Schedulers.io().scheduleDirect(() -> {
            thing.doStuff(); // NPE!
        });
    }
}

How is an NPE possible there?
EDIT:
Thing's constructor does its work asynchronously. As I said, this is in an Android environment, so the work it's actually doing is binding to a Service. When the Service is bound, its ServiceConnection::onServiceConnected() callback is hit, which itself actually fires up an AsyncTask which, in its onPostExecute() callback, calls the onThingInitialized() callback.
EDIT 2:
I should also note that this NPE doesn't happen all the time. I've run through this code hundreds of time, and I've only seen it occur once.
EDIT 3: Sample calling code
I didn't provide sample code because it's about as simple as one might imagine, but here's what it looks like:
Flowable.just(1)
    .subscribeOn(Schedulers.io())
    .subscribe(i -> createThing());

A: If I understand your comment, createThing() is called in a worker thread.  It's unlikely but possible that the thread scheduler will halt this worker thread after the Thing constructor initiates the sequence of events that leads to the callback, but before newThing() returns and thing is assigned.  If the whole callback sequence runs before the thread calling createThing() runs again, you will see this NPE.
To test this theory, first create a test that runs repeatedly to reproduce the issue.  Then change it so createThing() is called in the main thread and see if the problem goes away.  That would be a workaround, not a fix.  But a real fix would involve not doing work in Thing's constructor, which you stated is out of your control.


text:
Q: Array of structs with new[] doesn't seem to work if said struct have constructor For an assignment I have a struct with constructor defined and wish to create array of these using new[] operator. I can't understand why this doesn't work. The code is like so (pseudo code):
struct Structname
{
int x;
int y;
Structname(int a,int b)
{
x=a;
y=b;
}
}

Now trying to do:
Structname *Array = new Structname[size]

Results in error "No function matching call Structname::Structname() on Structname[size]" (not exact citation). The error doesn't occur when there is no constructor in my struct just as if the compiler expects me to use the constructor in Structname* Array = new Structname[size]. I cannot delete the constructor because I need it in other parts of the code. Also I cannot use std::vector due to assignment rules.

A: When you define parameterised constructor, the compiler doesn't inject the default constructor i.e. Structname::Structname(). That's why you are getting error.
You may get past it in two ways:
1) Define your own default constructor:
struct Structname {
    int x;
    int y;
    Structname(int a,int b) {
        x=a;
        y=b;
    }
    Structname(): Structname(0, 0) { }
}

2) Use default keyword to get constructor which was supposed to be injected by compiler.
struct Structname {
    int x;
    int y;
    Structname(int a,int b) {
        x=a;
        y=b;
    }
    Structname() = default;
}

Please note that in option 1, the data members are initialized with proper values. In option 2, data members won't be initialized to proper values.
So, make your choice based on the requirement.
Suggestion:
Though pretty unrelated to the problem, it is considered a good practice. Never use naked new. Look for other options instead. See std::vector.


text:
Q: How to wait for N number of async functions to finish in node.js so that I can do some work on all their combined results? Please look at the code below. the request module is this one(https://www.npmjs.com/package/request)
var urlArray = [];  // URL in this level
foo ("xyz.com", false);
function crawl (url, finished) {
    request(url, function (error, response, body) {
        if (finished == true) { return; }
        // do some work on body (including getting getting n number of new URLS from
        // the body) and set finished = true if we find what we are looking for.

        // for each new url urlArray.push(newURL);

        // for each new url call crawl(newurl, finished);

        // Now How can I know when ALL these requests have finished?
        // so that I can have a urlArray corresponding to this level of crawling tree and
        // do some work before starting next level of crawl.

    });
}

A: use Promises.
Check out the Q library (specifically I pointed to the methods you need):
Promise creation:
https://github.com/kriskowal/q/wiki/API-Reference#qdefer
var promise = Q.defer();
doAsyncStuff(callbackOfAsync);
return promise.promise;

functioncallbackOfAsync(isSuccess){
   if(isSuccess){
        promise.resolve();
    }
    else{
        promise.reject();
    }
}

Wait for multiple promises:
https://github.com/kriskowal/q/wiki/API-Reference#promise-for-array-methods
Q.all([getFromDisk(), getFromCloud()]).done(function (values) {
    assert(values[0] === values[1]); // values[0] is fromDisk and values[1] is fromCloud
});

A: To answer your question specifically, the following flow of logic should work for you, I have added comments to help it make sense to you:
var urlArray = [];  // URL in this level
var finished = false;

foo("xyz.com", false);

function start() {
    while (urlArray.length) {
        crawl(urlArray.pop());
    }
}

function crawl(url) {
    request(url, function (error, response, body) {
        if (finished) {
            return;
        }
        // 1. at this point, a given batch of crawls have all started
        // AND urlArray is empty.

        // 2. do some work on body (including getting getting n number of new URLS from
        // the body) and set finished = true if we find what we are looking for.

        // 3. for each new url urlArray.push(newURL);

        // 4. start crawling on new batch of URL set
        start();
    });
}

All the request callbacks will be executed after start() completes, this guarantees that urlArray will be empty then.
If processing of one crawl response indicates (by setting finished = true;) that what you're looking for has been found all other processing of responses will terminate as soon as they begin.
Otherwise, reponse is processed and a new batch of urls are set for crawling. You call start() to begin crawling each.
It would help you also (as suggested in the other answer) if you acquainted yourself with the concept of Promises.

A: I don't really understand your question, but I guess you will need Promises. I assume you are using NodeJS.
function makeRequest (url) {
  return new Promise(function (resolve, reject) {
    request(url, function (err, response, body) {
      if (err || response.statusCode !== 200)
        reject(err || body);
      else
        resolve(body);
    }
  })
}

this function returns a promise. You can use it this way:
var request = makeRequest('url.com');
request.then(function (urls) {
  // this is called if no error occured
  urls.forEach(function (url) {
   console.log (url);
  });
}, function (error) {
    // this is called on error
    console.log (error);
});

If you want to wait for multiple requests to be answered to perform an action, use Promise.all:
var requests = [makeRequest(url1), makeRequest(url2), makeRequest(url3)];

Promise.all(requests).then(function (data) {
 // everything is done
 console.log(data);
});

I didn't test the code, but I hope you get the idea.


text:
Q: Develop more efficient for loop that refers to n-1 row I need to run a logic where the "n" step is based on the result of the "n-1" step, and thus i implemented the logic in a for loop. Here the code:
library(data.table)
df<-as.data.table(matrix(rexp(100000, rate=.1), ncol=1000))
weight<-as.data.table(matrix(rexp(100, rate=10), ncol=1))

for (row in 1:nrow(weight))
{
  if (row > 2){

    # from second row start the logic
    # We create weighted averages of variables values: value(n-1)* (1-weight) + value(n) * weight
    df[row] <-
      df[row-1,] * as.numeric(1 - weight[row]) + df[row,] * as.numeric(weight[row])

  }
}

However, it takes really long time to run because the data.table, in reality, is made of 1098 columns and 200k rows.
Does anybody have a ideas on how to develop a more efficient solution?

A: Let me explain my story how I would go about increasing the performance of such a task.
Base Timings
First I recreate your data (a bit smaller) and measure the time it takes to run it:
library(data.table)
library(tictoc) # for timing only

# easier way to create a data.table
NROWS <- 100
NCOLS <- 100
set.seed(123)

df_orig <- data.table(matrix(rexp(NROWS * NCOLS, rate = 0.1), ncol = NCOLS))
wt <- data.table(V1 = rexp(NROWS, rate = 10))

df1 <- copy(df_orig)
tic()
for (r in 1:nrow(wt)) {
  if (r >= 2) { # assuming you mean >= 2 not >= 3 (:= >2)
    # from second row start the logic
    # We create weighted averages of variables values: value(n-1)* (1-weight) + value(n) * weight
    df1[r, ] <- df1[r-1,] * as.numeric(1 - wt[r]) + df1[r,] * as.numeric(wt[r])
  }
}
toc()
#> 1.274 sec elapsed

Created on 2020-05-08 by the reprex package (v0.3.0)
Model 2
Then I look at ways to improve the code. For example, as.numeric() might be expensive, as well as the if () check in the loop. Lets remove that, but make sure that the results stay the same
# no if check in the loop and replace as.numeric with [[1]]
# loop only from 2
df2 <- copy(df_orig)
tic()
for (r in 2:nrow(wt)) {
  df2[r, ] <- df2[r - 1, ] * (1 - wt[r][[1]]) + df2[r, ] * wt[r][[1]]
}
toc()
#> 1.149 sec elapsed

# check that the results are identical
all.equal(df1, df2)
#> [1] TRUE

Created on 2020-05-08 by the reprex package (v0.3.0)
A little bit better, but we are not there yet.
Matrix Model
In general data.table is a great way to improve speeds, but this kind of access is best implemented in a base structure, i.e., matrix().
So lets do that:
# Matrix based
mdf <- as.matrix(df_orig)
mwt <- as.matrix(wt)

tic()
for (r in 2:nrow(wt)) {
  mdf[r, ] <- mdf[r - 1, ] * (1 - mwt[r, ]) + mdf[r, ] * mwt[r, 1]
}
toc()
#> 0.005 sec elapsed

df3 <- data.table(mdf)

all.equal(df3, df1)
#> [1] TRUE

Created on 2020-05-08 by the reprex package (v0.3.0)
That looks like a nice speedup!
But there is more...
Rcpp Model
Especially in these kinds of tasks, Rcpp and c++ are more cumbersome to write, but provide beautiful speedups.
Here we use the Armadillo matrix library for c++ and its Rcpp bindings of RcppArmadillo.
Translating your code to Rcpp yields this:
# using rcpp
rcpp_code <- "// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
// [[Rcpp::export]]
arma::mat my_rcpp_fun(arma::mat data, arma::mat weights) {
  const int len = weights.size();

  // Cpp starts indexing at 0, so 1 is the second row!
  for (int i = 1; i < len; i++) {
    data.row(i) = data.row(i - 1) * (1 - weights.row(i)(0)) + data.row(i) * weights.row(i)(0);
  }
  return data;
}
"

Rcpp::sourceCpp(code = rcpp_code)
mdf2 <- as.matrix(df_orig)
mwt2 <- as.matrix(wt)

tic()
mdf4 <- my_rcpp_fun(mdf2, mwt2)
toc()
#> 0.002 sec elapsed

df4 <- data.table(mdf4)
all.equal(df4, df1)
#> [1] TRUE

Created on 2020-05-08 by the reprex package (v0.3.0)
From 1.274s to 0.002s sounds nice right?!


text:
Q: How do I calculate the naive accuracy an a confusion matrix? confusion matrix
I have an issue where I'm trying to compute the test accuracy for a naive classifier that always predicts ^y=−1.
I have already calculated the test accuracy of the classifier based on the confusion matrix attached above by using (TN + TP)/. But how do I calculate the naive value?
accuracy = (109112+3805)/127933
naive_accuracy = # TODO: Compute the accuracy of the naive classifier

A: It is actually the same formula. You should just notice that your naive classifier never gives positives answers, so TP = 0. TN will be equal to the total number of negatives: TN = 123324.
So naive_accuracy = (TN + TP)/ = (123324 + 0)/127933.
And yes, this is the case when naive classifier actually shows better accuracy than the one given by the confusion matrix you are referring to. This is due to data imbalance problem: there are 30 times more negative examples than positive ones. This is why accuracy is not applicable in that setting. Please check out precision, recall and f-score metrics if you need to have a meaningful result.


text:
Q: Display user notifications in User dashboard in oxwall I am customizing Oxwall notification plugin.
I am using Oxwall 1.7.0
I am trying to display notifications in User's dashboard page.
Currently the notification showing in top right bar with name as "Notifications".
I found out which file is responsible for displaying the content.

ow_plugins/notifications/classes/console_bridge.php

I commented the below code in this file to hide the notification from top right bar.
public function collectItems( BASE_CLASS_ConsoleItemCollector $event )
{
   if ( !OW::getUser()->isAuthenticated() )
   {
      return;
   }
   /* Commented this code to hide the notification.
   $item = new NOTIFICATIONS_CMP_ConsoleItem();
   $event->addItem($item, 3);
   */
}

But when we call the component in user's dashboard using the below code, It gives me error.
$widgetService = BOL_ComponentAdminService::getInstance();
$widget = $widgetService->addWidget('NOTIFICATIONS_CMP_ConsoleItem', false);
$widgetPlace = $widgetService->addWidgetToPlace($widget, BOL_ComponentService::PLACE_DASHBOARD);
$widgetService->addWidgetToPosition($widgetPlace, BOL_ComponentService::SECTION_LEFT);

Error Screenshot:
How to display the notifications in user-dashboard?

A: To display user's notification in user's dashboard page, follow the below code in Widget's construct.
$this->service = NOTIFICATIONS_BOL_Service::getInstance();

$userid = OW::getUser()->getId();

$allNotificationCount = $this->service->findNotificationCount($userid); // Get the notifications of currently logged in user

$notifications = $this->service->findNotificationList($userid, time(), null, $allNotificationCount);

$notify_array = array();

$i=0;

foreach ( $notifications as $notification )
{
    if(( $notification->entityType == "groups_wal" && $notification->entityId==$groupid ) || ( $notification->entityType == "status_comment" ) )
    {

        $itemEvent = new OW_Event('notifications.on_item_render', array(
                    'key' => 'notification_' . $notification->id,
                    'entityType' => $notification->entityType,
                    'entityId' => $notification->entityId,
                    'pluginKey' => $notification->pluginKey,
                    'userId' => $notification->userId,
                    'viewed' => (bool) $notification->viewed,
                    'data' => $notification->getData()
                ), $notification->getData());

        OW::getEventManager()->trigger($itemEvent);

        $notify_array[$i] = $itemEvent->getData();

        $i++;

        if ( empty($item) )
        {
            continue;
        }
    }
}

$this->assign('item', $notify_array);

On Oxwall widget's view, add the below code
{if !empty($item)}

{foreach from=$item key='key' item='v'}
    {$v}
{/foreach}

{else}

No Items

{/if}


text:
Q: stop meteor rerender every child template inside of each block when find query changes? i'm rendering a list of elements based on a collection on the meteor server.
the elements are rendered using an #each block which is populated from a helper method that returns a cursor which is the result of a find query. in order to sort the list based on some attribute of its data i run a new find with a different sort option.
this works fine and the list is rendered in the desired order. the problem is meteor is rerendering each element.
now i have two problems:
1) the elements can contain an embedded video that is playing. this is reset when meteor rerenders the element
2) i want to have some css transitions animate the repositioning of the elements. since meteor rerenders every element in the dom, the css transitions don't work.
i was partially able to solve problem #1 using a constant block but problem #2 remains a mystery. i could do all the sorting and filtering client side without relying on meteor but that seems clumsy.
is there any way that meteor can just reposition the elements in the dom instead of removing and readding them?
in the documentation for renderList i found this (which makes it seem like meteor could at least theoretically do what i want):
renderList is more efficient than using Meteor.render to render HTML for a list of documents. For example, if a new document is created in the database that matches the query, a new item will be rendered and inserted at the appropriate place in the DOM without re-rendering the other elements. Similarly, if a document changes position in a sorted query, the DOM nodes will simply be moved and not re-rendered.


text:
Q: Trying to show dates within 30 days of another date I am trying to show all dates within a 30 day period after another date, but I can't get the last line correct. The result should show all cases of GARN_DATE that are within a 30 day period after TRANS_DATE with a certain code and all cases of SERVICE_DATE after TRANS_DATE with the same code.
This is what I have so far:
    WHERE (CODE LIKE 'XPSREJ'
    AND TRANS_DATE BETWEEN '2021-11-26' AND '2022-05-256')
    AND TRANS_DATE < (DATEADD (day, 30, GARN_DATE) )
    AND TRANS_DATE < SERVICE_DATE


text:
Q: How to update jBoxes? I have a form that uses jBox to provide additional info for some fields in tooltips. The text that is displayed depends on the value of the closest select-tag. jBox is executed on PageLoad (I create a single jBox which uses data-attributes to get title and content) and I then update the data-attributes in response to the change-event on the select-control.
Unfortunately that does not work, the tooltip stays with the initial value.
I have a cut-down repro with tooltip that illustrates the behaviour of not being updated (alertis used to show actual values of data-attributes after a change-event)

$(function() {
  $("[data-jbox-content]").jBox("Tooltip", {
    theme: "TooltipDark",
    id: "jBoxTooltip",
    getTitle: "data-jbox-title",
    getContent: "data-jbox-content"
  });
});
<link href="https://cdn.jsdelivr.net/gh/StephanWagner/jBox@v1.0.5/dist/jBox.all.min.css" rel="stylesheet"/>

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css" rel="stylesheet"/>

      Variable
      Type
      Description

      Car
      <select id="dtCar" class="form-control select2 font-fas" name="dtCar" onchange="$('#infoCar').data('jbox-title','blabla');$('#infoCar').data('jbox-content','dummy');alert($('#infoCar').data('jbox-title')+' / ' + $('#infoCar').data('jbox-content'))">
          <option>Key</option>
          <option selected="selected">Boolean</option>
          <option>Ordinal</option>
          <option>Nominal</option>
          <option>Interval</option>
          <option>Ratio</option>
        </select>

      <input id="inCar" class="form-control" name="inCar" type="text" value="Do you own a car?">

      Age
      <select id="dtHouse" class="form-control select2 font-fas" name="dtAge" onchange="$('#infoAge').data('jbox-title','blabla');$('#infoAge').data('jbox-content','dummy');alert($('#infoAge').data('jbox-title')+' / ' + $('#infoAge').data('jbox-content'))">
          <option>Key</option>
          <option>Boolean</option>
          <option>Ordinal</option>
          <option>Nominal</option>
          <option selected="selected">Interval</option>
          <option>Ratio</option>
        </select>

      <input id="inHouse" class="form-control" name="inAge" type="text" value="How old are you?">

A: There is a common misunderstanding of how jQuery uses .data() and .attr() methods.
.data() adds some internal data to the element itself and will not set an attribute.
To set a data-xxx attribute you need to use .attr(). See more here: https://api.jquery.com/attr/
Also, check out updated snippet:

$(function() {
  $("[data-jbox-content]").jBox("Tooltip", {
    theme: "TooltipDark",
    id: "jBoxTooltip",
    getTitle: "data-jbox-title",
    getContent: "data-jbox-content"
  });
});
<link href="https://cdn.jsdelivr.net/gh/StephanWagner/jBox@v1.0.5/dist/jBox.all.min.css" rel="stylesheet"/>

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css" rel="stylesheet"/>

      Variable
      Type
      Description

      Car
      <select id="dtCar" class="form-control select2 font-fas" name="dtCar" onchange="$('#infoCar').attr('data-jbox-title','blabla');$('#infoCar').attr('data-jbox-content','dummy');">
          <option>Key</option>
          <option selected="selected">Boolean</option>
          <option>Ordinal</option>
          <option>Nominal</option>
          <option>Interval</option>
          <option>Ratio</option>
        </select>

      <input id="inCar" class="form-control" name="inCar" type="text" value="Do you own a car?">

      Age
      <select id="dtHouse" class="form-control select2 font-fas" name="dtAge" onchange="$('#infoAge').attr('data-jbox-title','blabla');$('#infoAge').attr('data-jbox-content','dummy');">
          <option>Key</option>
          <option>Boolean</option>
          <option>Ordinal</option>
          <option>Nominal</option>
          <option selected="selected">Interval</option>
          <option>Ratio</option>
        </select>

      <input id="inHouse" class="form-control" name="inAge" type="text" value="How old are you?">


text:
Q: System.Text.Json Schema Validation Does System.Text.Json expose any methods to validate Json schemas? I have looked at their documentation but it appears that this is still tbd.

A: you can take a look to the current JSON Schema .NET implementations here:
https://json-schema.org/implementations.html#validator-dotnet


text:
Q: Erro ao popular grafico do google charts Estou me deparando com o seguinte erro:

VM3611:231 Uncaught Error: Unknown header type: 6

Código:
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
    var jsonData = $.ajax({
        url: "/client/ajax",
        dataType: "JSON",
        async: false
    }).responseJSON;

    var data = google.visualization.arrayToDataTable([
        ['Name' , 'Tickets']
    ]);

    for(var i=0;i<jsonData.length;i++){
        var array = [jsonData[i].Name , jsonData[i].Tickets]
        data = (google.visualization.arrayToDataTable([
            array
        ]));
    }
    var chart = new google.visualization.L

ineChart(document.getElementById('chart_div'));
chart.draw(data);

Nunca usei o charts, gostaria de saber se estou fazendo certo? E o motivo do erro? Obrigado a comunidade!

A: Na maneira que consegui visualizar os dados, chamei arrayToDataTable() apenas uma vez. Veja o código abaixo.
Quanto a erros, encontrei só um erro de sintaxe. No código postado, falta o } no final da função. Acredito que o código não rodava porque arrayToDataTable() estava sendo chamada repetidamente para cada objeto (array) do JSON, e na verdade ele precisa da linha de "header".
Os dados JSON foram trocados por estáticos. Espero que te ajude!

   google.charts.load('current', {packages: ['corechart']});
   google.charts.setOnLoadCallback(drawChart);

   function drawChart() {
     var jsonData = [
       { "Name": "Joe", "Tickets": 300 },
       { "Name": "Karl", "Tickets": 200 },
       { "Name": "Tina", "Tickets": 900 },
     ];

     var dataArray = [
       ['Name' , 'Tickets'],
     ];

     for(var i=0;i<jsonData.length;i++){
       var row = [jsonData[i].Name , jsonData[i].Tickets];
       dataArray.push(row);
     }

     var data = google.visualization.arrayToDataTable(dataArray);

     var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
     chart.draw(data);
   }
#chart_div {
       height: 100%;
   }
<div id="chart_div">
  </div>
<script src="https://www.gstatic.com/charts/loader.js"></script>


text:
Q: Need help finding installed_app setting in Django I am having trouble finding where the installed_app setting is in the django folder. i can't seem to find anything related to this "setting". Can anyone help?

A: All settings of the project or application are set in the settings.py file. Describe what kind of settings you want to change.

A: INSTALLED_APPS is a list, and located in mysite/settings.py (at the top of the file).


text:
Q: HTML header won't center I'm making a single page scrollable website and want to have the first page to be just a navbar, image, and a header. Now the problem is that I was unable to center the header. Well, at least I got it to center horizontally. But I'm unable to center it vertically. I hope somebody can spot the issue because I've been puzzling this annoying issue for hours.
This: https://startbootstrap.com/previews/grayscale/ is the idea I'm going for, to make it clear.
Here is the code

/*body {
        background: linear-gradient(rgba(#F9774C, .75), rgba(#802A0C, .85));
        background-image: url("Background_photo_2.jpg");
        background-size: cover;
        box-shadow: 4056 3000px rgba(0, 0, 0, 0) inset;
          /* Center and scale the image nicely
        background-position: center;
        background-repeat: no-repeat;
        height: 50%;
                }*/

    nav {
        font-size: medium;
    }

    .nav-item a{
        color: white !important
    }

     body, html {
        height: 100%;
        margin: 0;
        padding: 0;
        font-family: 'Montserrat', sans-serif;
     }

    /*styles background image*/
    .bg-img {
        /*background-image: url("Background_photo_2.jpg");*/

        height: 100%;

        background-position: center;
        background-repeat: no-repeat;
        background-size: cover;

        box-shadow: 4000px 3000px rgba(0, 0, 0, 0.6) inset;

    }

    /* use this to change the general fonts */
    p, h1  {
        color: white;

    }

    /* arranges navbar items to right */
    ul {
        margin-left: auto;
    }

    .bg-img.container {
        display: flex;
        justify-content: center;
        align-items: center;
    }
    #content {
        width: 100%;
        height: 85%;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    /*.container-fluid {
        width: 70%;
    }
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Home - Both Sides Now </title>

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <link rel="stylesheet" type="text/css" href="style.css">

  <link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet">

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

        </button>

              Home (current)

              Features

              Pricing

Grayscale

A free, responsive, one page Bootstrap theme created by Start Bootstrap.

          Get Started

A: No need to use styles. Bootstrap does it for you :

Grayscale

A free, responsive, one page Bootstrap theme created by Start Bootstrap.

      Get Started

Add two classes to header div that I have added above.
Note : after you added row class maybe you have to add col to your content elements.

A: There is two option to do vertical center

*

*you need to give the position to your navigation bar so it does not calculate in flexbox, for that you need to change your code a little bit.

*you need to cut out your navigation bar height from your page, so it does not calculate in flexbox, I calculated your navbar height and its equal to 86px so, I will cut 172px from your page
Now you need to choose best way, from my side, first is better than second.

1st Idea
Just added align-items-center vh-100 in masthead class tag and added CSS
.bg-img > .container {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
}

/*body {
        background: linear-gradient(rgba(#F9774C, .75), rgba(#802A0C, .85));
        background-image: url("Background_photo_2.jpg");
        background-size: cover;
        box-shadow: 4056 3000px rgba(0, 0, 0, 0) inset;
          /* Center and scale the image nicely
        background-position: center;
        background-repeat: no-repeat;
        height: 50%;
                }*/

    nav {
        font-size: medium;
    }

    .nav-item a{
        color: white !important
    }

     body, html {
        height: 100%;
        margin: 0;
        padding: 0;
        font-family: 'Montserrat', sans-serif;
     }

    /*styles background image*/
    .bg-img {
        /*background-image: url("Background_photo_2.jpg");*/

        height: 100%;

        background-position: center;
        background-repeat: no-repeat;
        background-size: cover;

        box-shadow: 4000px 3000px rgba(0, 0, 0, 0.6) inset;

    }

    /* use this to change the general fonts */
    p, h1  {
        color: white;

    }

    /* arranges navbar items to right */
    ul {
        margin-left: auto;
    }

    .bg-img.container {
        display: flex;
        justify-content: center;
        align-items: center;
    }
    #content {
        width: 100%;
        height: 85%;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    /*.container-fluid {
        width: 70%;
    }*/

    .bg-img > .container {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
    }
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Home - Both Sides Now </title>

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <link rel="stylesheet" type="text/css" href="style.css">

  <link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet">

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

        </button>

              Home (current)

              Features

              Pricing

Grayscale

A free, responsive, one page Bootstrap theme created by Start Bootstrap.

          Get Started

2nd Idea
Just added align-items-center in masthead class tag and added CSS
.masthead {
    height: calc(100vh - 172px);
}

/*body {
        background: linear-gradient(rgba(#F9774C, .75), rgba(#802A0C, .85));
        background-image: url("Background_photo_2.jpg");
        background-size: cover;
        box-shadow: 4056 3000px rgba(0, 0, 0, 0) inset;
          /* Center and scale the image nicely
        background-position: center;
        background-repeat: no-repeat;
        height: 50%;
                }*/

    nav {
        font-size: medium;
    }

    .nav-item a{
        color: white !important
    }

     body, html {
        height: 100%;
        margin: 0;
        padding: 0;
        font-family: 'Montserrat', sans-serif;
     }

    /*styles background image*/
    .bg-img {
        /*background-image: url("Background_photo_2.jpg");*/

        height: 100%;

        background-position: center;
        background-repeat: no-repeat;
        background-size: cover;

        box-shadow: 4000px 3000px rgba(0, 0, 0, 0.6) inset;

    }

    /* use this to change the general fonts */
    p, h1  {
        color: white;

    }

    /* arranges navbar items to right */
    ul {
        margin-left: auto;
    }

    .bg-img.container {
        display: flex;
        justify-content: center;
        align-items: center;
    }
    #content {
        width: 100%;
        height: 85%;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    /*.container-fluid {
        width: 70%;
    }*/

    .masthead {
      height: calc(100vh - 172px);
    }
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Home - Both Sides Now </title>

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <link rel="stylesheet" type="text/css" href="style.css">

  <link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet">

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

        </button>

              Home (current)

              Features

              Pricing

Grayscale

A free, responsive, one page Bootstrap theme created by Start Bootstrap.

          Get Started

A:

nav {
            font-size: medium;
        }

        .nav-item a {
            color: white !important
        }

        body,
        html {
            height: 100%;
            margin: 0;
            padding: 0;
            font-family: 'Montserrat', sans-serif;
        }
        /*styles background image*/

        .bg-img {
            /*background-image: url("Background_photo_2.jpg");*/
            height: 100%;
            background-position: center;
            background-repeat: no-repeat;
            background-size: cover;
            box-shadow: 4000px 3000px rgba(0, 0, 0, 0.6) inset;
        }
        /* use this to change the general fonts */

        p,
        h1 {
            color: white;
        }
        /* arranges navbar items to right */

        ul {
            margin-left: auto;
        }

        .bg-img.container {
            display: flex;
            justify-content: center;
            align-items: center;
        }

        #content {
            width: 100%;
            height: 85%;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        /*.container-fluid {
        width: 70%;
    } */

        .mx-auto {
            position: absolute;
            top: 50%;
            left: 50%;
            -webkit-transform: translate(-50%, -50%);
            -moz-transform: translate(-50%, -50%);
            transform: translate(-50%, -50%);
        }
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home - Both Sides Now </title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="style.css">

    <link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet">

                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

                </button>

                            Home (current)

                            Features

                            Pricing

Grayscale

A free, responsive, one page Bootstrap theme created by Start Bootstrap.

                    Get Started


text:
Q: How to avoid DAG Import Errors in Apache Airflow for worker node dependencies? I'm working on an Apache Airflow, container based application.
My environment is made of the following components:

*

*Airflow Scheduler container

*Airflow Webserver container

*Airflow Celery Flower container

*Airflow Worker container (1)

*etc.

My understanding of this pattern is that I can have a scheduler and a webserver containers with just the necessary dependencies for Airflow, then I can have a worker node (or several) with everything I need to run my DAG.
When I try to work with it this way (for instance, adding and using a module in the worker node, let's say it's the crypto module), I get a DAG Import Error exception in the front end, that says the following:
ModuleNotFoundError: No module named 'crypto'.
This makes sense to me, because the scheduler knows that I'll need that module for the execution and throws an error, despite this the DAG correctly work, because when it's run, in the worker node, it has all the required dependencies.
How can I fix this?
Thanks

A: Currently, you will need to sync your dependencies on both Scheduler and Worker.
The scheduler parses DAG Files in a separate process (one per DAG file), so if your dependencies used in DAG file are not installed in Scheduler it will add an ImportError in DB which will be then shown in the Webserver.

A: The above answer by @kaxil is good but seems to be incomplete. At least according to the documentation here:

Airflow scheduler executes the code outside the Operator's execute methods

This means that you can avoid running into this sort of ImportError if you change top-level imports for local imports inside Python callables. The referred documentation explains it in more details.


text:
Q: Acomodar automaticamente los elementos de mi form dependiendo del tamaño del mismo en C# Tengo un Formulario en C#, si maximizo el form todo se queda del mismo tamaño y en el mismo lugar.
Quisiera saber como ajustar los objetos depediendo del tamaño del formulario.
Gracias.

A: Si es para Winforms, puedes usar un TableLayoutPanel
Arrastralo desde la barra de herramientas al formulario
Establece la propiedad "Dock" en full
Establece la cantidad de filas y columnas
Arrastra controles a sus casillas
Ejemplo:

A: Tienes que usar la propiedad anchor de los objetos y ajustarla a form para que se agranden y se achiquen a la par de ellos.
Ten cuidado porque si solo "anclas" un lado del objeto, se extendera para ese lado, pero tambien se movera. Tenes que fijarte que es lo que queres y jugar con eso.
Igual solo los objetos imagenes se suelen anclar, y se ponen dentro de contenedores por lo general... Uno no agranda botones o campos de texto, salvo que seas un editor de texto.

A: Si es con WPF puedes hacerlo poniendo * o auto a tus controles, así cuando el formulario cambie de tamaño, este cambiara con el mismo.
Si es en WinForms puedes usar el  AutoScaleMode.
aqui te explica como se usan estos


text:
Q: Merging Partitions In an attempt to re-arrange/clean up the partitions on my dual boot laptop using gparted I seem to have run into a wall.  Here is my current partition layout:
/dev/sda1 - 25G fat32 Windows Recovery partition
/dev/sda2 - 200G ntfs Windows 8 OS partition
/dev/sda4 - 100G ntfs empty partition
/dev/sda3 - 380G extended partition
--/dev/sda5 - 190G ntfs empty partition
--/dev/sda7 - 180G ext4 Ubuntu partition
--/dev/sda6 - 8G linux-swap
I want to merge sda4 and sda5 into one large partition that can be accessed from both OS's.  I've been trying off the Ubuntu LiveCD GParted.  When I try and delete or do anything with sda5 I get a 'Please unmount any logical partitions higher then 5' error.

A: For general information, it is easier to resize partitions when booting a live usb as you have unmount the partions before you resize them.
Once you boot a live CD/USB, the swap partition (with ubuntu) will mount automatically. Unmount it from within gparted or from the command line:
sudo swapoff -a

You then have to do your resizing in steps. Probably easy to:
delete sda4 -> apply changes
make sda3 bigger -> apply changes
make sda5 larger -> apply changes


text:
Q: Why is my LAST rule [L] not working in apache? Background, I'm running a Zend Framework application. Trying to squeeze the most performance out of it as possible. So I'm trying to move the rules out of .htaccess exactly to the letter per this blog post by the author of a Zend Framework book: http://www.armando.ws/2009/03/how-to-run-zend-framework-with-no-htaccess-file/
So basically, in httpd.conf, I'm adding an include to conf/extra/httpd-zf.conf which contains the same thing that was in my .htaccess file and working perfectly.
Here's the pertinent code that doesn't function right in httpd-zf.conf:
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [L,NC]
RewriteRule ^.*$ /index.php [NC,L]

Controllers work fine. The index.php is seen. But static files don't work. It errors out saying that it isn't a valid controller, so clearly it's being run through index.php.
It's almost as if after running:
RewriteRule ^.*$ - [L,NC]

it keeps right on going. And in point of fact, Removing this line:
RewriteRule ^.*$ /index.php [NC,L]

fixes the static files, but of course breaks the rest of it.
So basically the LAST rule is not working it seems.
Any ideas on getting this to work correctly?
Thank you.
UPDATE
After turning on logging (I had to hike it up to Loglevel 9), it turned out that even though removing
    RewriteRule ^.*$ /index.php [NC,L]
allowed static files to resolve, it was NOT matching on condition RewriteCond %{REQUEST_FILENAME} -s no matter what...it just did "pass through" anyway which allowed the file to show...
so clearly, the fact that .htaccess was on the correct path made it work where the httpd-zf.conf has the wrong path.... There must be a spot somewhere that I can tell httpd-zf.conf what my docroot path is...

A: I don't believe the conditions are associated with the second rule. I suggest turning on rewrite debugging: RewriteLog "/myfolder/mylogfile.log" and RewriteLogLevel 3
Try:
RewriteCond %{REQUEST_FILENAME} !-s
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [NC,L]

A: Found the solution!!
Here's the code that works:
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} -s [OR]
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} -l [OR]
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} -d

This wiki post explains why it wasn't working:
http://wiki.apache.org/httpd/RewriteContext


text:
Q: Filtering ListView IndexOutOfBoundsException After writing inside the EditText i get this exception:
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: android_team.gymme_client, PID: 7500
    java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
        at java.util.ArrayList.get(ArrayList.java:437)
        at android_team.gymme_client.gym.CustomGymTrainerAdapter.getView(CustomGymTrainerAdapter.java:50)
        at android.widget.AbsListView.obtainView(AbsListView.java:2387)
        at android.widget.ListView.makeAndAddView(ListView.java:2067)
        at android.widget.ListView.fillDown(ListView.java:793)
        at android.widget.ListView.fillSpecific(ListView.java:1504)
        ...

The app bug is on this line String name = trainers.get(position).name;
inside the following class (Adapter) :
public class CustomGymTrainerAdapter extends ArrayAdapter<TrainerObject> implements Filterable {

    private static ArrayList<TrainerObject> trainers;
    private Activity context;

    public CustomGymTrainerAdapter(Activity _context, ArrayList<TrainerObject> _trainers) {
        super(_context, R.layout.notification_item, _trainers);
        this.context = _context;
        this.trainers = _trainers;
    }

    @Override
    public int getCount() {
        return trainers.size();
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View r = convertView;
        CustomGymTrainerAdapter.ViewHolder viewHolder = null;
        if (r == null) {
            LayoutInflater layoutInflater = context.getLayoutInflater();
            r = layoutInflater.inflate(R.layout.gym_trainer_item, null);
            viewHolder = new CustomGymTrainerAdapter.ViewHolder(r);
            r.setTag(viewHolder);
        } else {
            viewHolder = (CustomGymTrainerAdapter.ViewHolder) r.getTag();
        }
        String name = trainers.get(position).name;
        String lastname = trainers.get(position).lastname;
        String email = trainers.get(position).email;

        viewHolder.tv_gym_trainer_name.setText(name);
        viewHolder.tv_gym_trainer_lastname.setText(lastname);
        viewHolder.tv_gym_trainer_email.setText(email);

        viewHolder.btn_gym_trainer_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //TODO:
                //LOGICA AGGIUNTA TRAINER SCELTO TRA I PROPRI DIPENDENDTI
            }
        });
        return r;
    }

    class ViewHolder {
        TextView tv_gym_trainer_name, tv_gym_trainer_lastname, tv_gym_trainer_email;
        ImageView btn_gym_trainer_add;

        ViewHolder(View v) {
            tv_gym_trainer_name = v.findViewById(R.id.tv_gym_trainer_name);
            tv_gym_trainer_lastname = v.findViewById(R.id.tv_gym_trainer_lastname);
            tv_gym_trainer_email = v.findViewById(R.id.tv_gym_trainer_email);

            btn_gym_trainer_add = v.findViewById(R.id.btn_gym_trainer_add);
        }
    }

    @NonNull
    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults();
                ArrayList<TrainerObject> FilteredTrainers = new ArrayList<TrainerObject>();
                // perform your search here using the searchConstraint String.
                constraint = constraint.toString().toLowerCase();
                for (TrainerObject t : trainers) {
                    String dataNames = t.name;
                    if (dataNames.toLowerCase().startsWith(constraint.toString())) {
                        FilteredTrainers.add(t);
                    }
                }
                results.values = FilteredTrainers;
                results.count = FilteredTrainers.size();
                Log.e("VALUES", results.values.toString());

                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                Log.e("TEST", results.values.toString());
                trainers = (ArrayList<TrainerObject>) results.values;
                notifyDataSetChanged();
            }

        };
        return filter;
    }
}

For completeness the class TrainerObject: (PS: I know the getter and setter methods are missing and that the variables should be private but it was for testing)
public class TrainerObject {
    public String user_id;
    public String name;
    public String lastname;
    public String email;
    public String qualification;
    public String fiscal_code;

    public TrainerObject(String user_id, String name, String lastname, String email, String qualification, String fiscal_code) {
        this.user_id = user_id;
        this.name = name;
        this.lastname = lastname;
        this.email = email;
        this.qualification = qualification;
        this.fiscal_code = fiscal_code;
    }

    @Override
    public String toString() {
        return "TrainerObject{" +
                "user_id='" + user_id + '\'' +
                ", name='" + name + '\'' +
                ", lastname='" + lastname + '\'' +
                ", email='" + email + '\'' +
                ", qualification='" + qualification + '\'' +
                ", fiscal_code='" + fiscal_code + '\'' +
                '}';
    }
}

The activity that calls the adapter is this one:
public class GymAddTrainerActivity extends AppCompatActivity {

    private int user_id;
    public static ArrayList<TrainerObject> trainers_list;
    static CustomGymTrainerAdapter trainer_adapter;
    ListView lv_trainer;
    EditText inputSearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gym_add_trainer);

        trainers_list = new ArrayList<TrainerObject>();

        //region CHECK INTENT EXTRAS
        Intent i = getIntent();
        if (!i.hasExtra("user_id")) {
            Toast.makeText(this, "User_id mancante", Toast.LENGTH_LONG).show();
            Intent new_i = new Intent(this, LoginActivity.class);
            startActivity(new_i);
        } else {
            user_id = i.getIntExtra("user_id", -1);
            Log.w("user_id ricevuto:", String.valueOf(user_id));
            if (user_id == -1) {
                Toast.makeText(this, "Utente non creato.", Toast.LENGTH_LONG).show();
                Intent new_i = new Intent(this, LoginActivity.class);
                startActivity(new_i);
            }
        }
        //endregion

        lv_trainer = (ListView) findViewById(R.id.lv_free_trainers);
        inputSearch = (EditText) findViewById(R.id.et_search_trainer);

        getTrainers();

        inputSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                // When user changed the Text
                GymAddTrainerActivity.this.trainer_adapter.getFilter().filter(cs);
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });
    }

    private void getTrainers() {
        GymAddTrainerActivity.ReceiveTrainersConn asyncTaskUser = (GymAddTrainerActivity.ReceiveTrainersConn) new GymAddTrainerActivity.ReceiveTrainersConn(new GymAddTrainerActivity.ReceiveTrainersConn.AsyncResponse() {
            @Override
            public void processFinish(ArrayList<TrainerObject> trainers) {
                trainers_list = trainers;
                if (trainers_list.size() > 0) {
                    //DATI RICEVUTI
                    runOnUiThread(new Runnable() {
                        public void run() {
                            //setto tramite l'adapter la lista dei trainer da visualizzare nella recycler view(notificationView)
                            trainer_adapter = new CustomGymTrainerAdapter(GymAddTrainerActivity.this, trainers_list);
                            lv_trainer.setAdapter(trainer_adapter);

                        }
                    });
                } else {
                    // NESSUN DATO RICEVUTO PERCHE' NESSUNA TRAINER LAVORA PER QUESTA PALESTRA
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(GymAddTrainerActivity.this, "Nessun personal triner disponibile", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                //for (int j = 0; j < trainers_list.size(); j++) {
                //    Log.e("trainer n:" + j, trainers_list.get(j).toString());
                //}
            }

        }).execute(String.valueOf(user_id));
    }

    private static class ReceiveTrainersConn extends AsyncTask<String, String, JsonArray> {

        public interface AsyncResponse {
            void processFinish(ArrayList<TrainerObject> trainers);
        }

        public GymAddTrainerActivity.ReceiveTrainersConn.AsyncResponse delegate = null;

        public ReceiveTrainersConn(GymAddTrainerActivity.ReceiveTrainersConn.AsyncResponse delegate) {
            this.delegate = delegate;
        }

        @SuppressLint("WrongThread")
        @Override
        protected JsonArray doInBackground(String... params) {

            URL url;
            HttpURLConnection urlConnection = null;
            JsonArray _trainers = null;
            ArrayList<TrainerObject> t_objects = new ArrayList<TrainerObject>();

            try {
                url = new URL("http://10.0.2.2:4000/gym/get_new_trainers/" + params[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.setConnectTimeout(5000);
                urlConnection.connect();
                int responseCode = urlConnection.getResponseCode();
                urlConnection.disconnect();

                if (responseCode == HttpURLConnection.HTTP_OK) {

                    Log.e("Server response", "HTTP_OK");
                    String responseString = readStream(urlConnection.getInputStream());
                    _trainers = JsonParser.parseString(responseString).getAsJsonArray();

                    for (int i = 0; i < _trainers.size(); i++) {
                        JsonObject trainer = (JsonObject) _trainers.get(i);

                        String user_id = trainer.get("user_id").getAsString().trim();
                        String name = trainer.get("name").getAsString().trim();
                        String lastname = trainer.get("lastname").getAsString().trim();
                        String email = trainer.get("email").getAsString().trim();
                        String qualification = trainer.get("qualification").getAsString().trim();
                        String fiscal_code = trainer.get("fiscal_code").getAsString().trim();

                        TrainerObject t_obj = new TrainerObject(user_id, name, lastname, email, qualification, fiscal_code);
                        t_objects.add(t_obj);

                    }
                    //SE VA TUTTO A BUON FINE INVIO AL METODO procesFinish();
                    delegate.processFinish(t_objects);

                } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
                    Log.e("GET TRAINER", "response: HTTP_NOT_FOUND");
                    delegate.processFinish(new ArrayList<TrainerObject>());
                } else {
                    Log.e("GET TRAINER", "SERVER ERROR");
                }
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("GET TRAINER", "I/O EXCEPTION ERROR");
            } finally {
                if (urlConnection != null)
                    urlConnection.disconnect();
            }
            return _trainers;
        }

        private String readStream(InputStream in) throws UnsupportedEncodingException {
            BufferedReader reader = null;
            StringBuffer response = new StringBuffer();
            try {
                reader = new BufferedReader(new InputStreamReader(in));
                String line = "";
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return response.toString();
        }
    }
}

Observation: both debug log return the correct value.
E/VALUES: [TrainerObject{user_id='9', name='nome', lastname='cognome', email='giova@gmail.com', qualification='asd', fiscal_code='asd'}]
E/TEST: [TrainerObject{user_id='9', name='nome', lastname='cognome', email='giova@gmail.com', qualification='asd', fiscal_code='asd'}]


text:
Q: .NET MVC validation of nullable integer (int?) form input field not working Is there any recommended/standard way to implement such MVC-code that a validation of form fields that are stored as nullable integers (int?) would work?
One of the root problems I'm having with this now, is that if I input something that is not integer like "abc123" and try to submit the form, the MVC tech stack will automatically convert this erroneous integer value to empty string before any validators are processed. Because empty is totally acceptable value in my case, validators will pass, form saving looks like proceeding correctly to the end and everything looks good until the user opens the updated form again and sees only empty field instead of the integer he or she inputted.
At first, I tried multiple dataAnnotation-validators to solve this problem, but none of them worked and the reason seems to be the fact that the erronoeus integer will be converted to empty string before the value is passed to validators.
[Integer]
[RegularExpression("[0-9]{1,}")]
public int? MyTroublesomeIntField { get; set; }

After this I tried to solve the problem by creating custom model binder by implementing IModelBinder. After experimenting with custom model binders, it seems that the erroneous value gets converted to empty string even before the custom model binder starts to run. Here's couple of code snippets from my modelBinder:
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
//f.e. this returns empty string
value.AttemptedValue
//f.e. this also returns empty strings, even though name "raw" leads one to      think that this is the value no one has touched.
value.RawValue
//even this returned empty string even though one could think that by accessing the field from HttpRequest would give access to the truly original value inputted by the user, but no, mvc stack gets to tinker this one as well.
string valueBefore = HttpContext.Current.Request.Form[bindingContext.ModelName];

So it seems to me, that there is some part of MVC tech stack that makes this conversion (erroneous integer input to empty string value) even before the custom model binders start to work. I'm just wondering, where is this happening, and is there a chance to customize it to get access to the original value?
Other alternative I have been thinking by now would be to create a separate string field for each of the free input int? form fields I have in the system. For string fields even those simple dataAnnotations like RegularExpressions would work straight away and the main problem would be solved. Finally I would just need to add binding data from all these "dummy"-string values to real int?-values somewhere in the controller/business logic. But this just seems like a massive work as I'm having loads of these ints in the systm. It feels strange that there would be this much extra work to do in order to get int?s working, when at the same time, exactly similar apporach works pefectly with double? fields which is currently not working with int?s - if I input erroneous double containing f.e. letters, client side validation will catch the error.
Any suggestions what would be the best way to proceed here?
My tech stack is pretty much like this: Razor, MVC5, Entity framework,


text:
Q: transition matrix equal to zero using hmmlearn I am using HMMlearn. I have 4 sets of different observations, that I have concatenated them. I used fit, to learn hmm.
first, why transition matrix is equal to zero?
Second, why the modell.means_  results in a matrix with the same dimension of the data?

A: I fixed it. the problem was that the data was like a 1-d array with length 1. I fixed it with using np.reshape(data, (-1, 1))


text:
Q: Routing to a specific tab using NGX-Bootstrap I'm working on a project, using Angular 6 with NGX-Bootstrap tabs.
What I'm trying to accomplish: Route to my tabs page from a different page, but to a specific tab. So far, I am able to navigate to the page with the tabs, with the correct path showing in the URL (/tabsPage#tab2), but it still lands on the first tab, and not the second.
app.component.ts
@ViewChild('staticTabs') staticTabs: TabsetComponent;

this.route.fragment.subscribe((fragment: string) => {
  if(fragment){
    let id = this.staticTabs.tabs.findIndex(f => f.id == fragment);

    if(id > 0)
      this.staticTabs.tabs[id].active = true;
  }
}

app.component.html
<tabset #staticTabs>
  <tab id="tab1" heading="Tab 1"></tab>
  <tab id="tab2" heading="Tab 2"></tab>
  <tab id="tab3" heading="Tab 3"></tab>
</tabset>

random-page.component.html
Jump to Tab 2

Any help on this would be greatly appreciated. Thanks!

A: I would use query params. They are better suited and can be used as such:
  public ngOnInit() {
    this.activatedRoute.fragments.subscribe(
      (fragment) => { console.log(fragment) }
    );
  }

And in the html:
Jump to Tab A
Jump to Tab B

Working example: https://stackblitz.com/edit/angular-1738es

A: I was able to make a version of my original code work. My "this.route.fragment" had to be inside the subscribe/response for a function in my ngOnInit. I ended up using the following to route from random-page.component.html, to the second tab in app.component.html:
.subscribe(
  response => {
    this.setHouseWatchVehicle(response);

    this.router.navigate([
      `/housewatch/edit/${response.agency}-${response.watchYear}-${response.watchId}`
    ], this.navigationExtras);
  },
);

And then a function in the app.component.ts to call when the page is loaded:
fragmentTabs() {
  this.route.fragment.subscribe((fragment: string) => {
    if(fragment) {
      let id = this.staticTabs.tabs.findIndex(f => f.id == fragment);
      if(id > 0)
        this.staticTabs.tabs[id].active = true;
    }
  });
}