text:
Q: memcached use cases What are some usecases that will benefit from using memcached with a mysql DB. I would guess it would be good for data that does not change much over time.
More specifically if my data changes often then its not worth using memcached right?
Even more specifically I am trying to use the DB as a data structure for a multi player game. So the records are going to change with every move the players make. And all players views should be updated with the latest moves. So my app is getting read and write intensive. Trying to see what I can do about it. If I use memcached, for every write we read 3 times max since 4 players max can play the game at a time.
Thanks.
Pav

A: Usecase: webshop with a lot of products. These products are assigned to various pages, and per product a user gets to see certain specs. The specs are called with a "getSpec" function. This is expensive and a query per time.
If we put these in memcached, its much quicker. Everytime someone changes something about the product, you jsut update the memcached.
so if your data changes it still can be worth it! Not everything might change at once.
edit: In your case, you could make your write also update memcached: no stale cache. But that's just a random thought, I don't know if making your write heavier like that has any disadvantaged. This would essentially mean you're running everything from memcached, and are just using your DB as a sort of backup :)

A: Caching is a tradeoff between speed and (potentially) stale data. You have to determine if the speed gain is appropriate given your own use cases.
We cache everything that doesn't require real-time data. Some things that are typically cached: Reports, user content, entire pages (though you may consider caching these to disk via some other system), etc..
Our API allows clients to query for huge amounts of data. We use memcached to store that for quick paging on the clients end.
If you plan ahead, you can setup your application to cache most everything and just invalidate parts of the cache as needed (for instance, when some data in your db is updated).

A: It's going to depend on how often "often" is and how busy your app is.  For example, if you have a piece of data that changes hourly, but that data is queried 500 times per hour, it would probably make sense to cache it even though it changes relatively frequently.


text:
Q: How to override base classes\structs such as int, string? To reduce downvotes: (Skippable at first)

I am aware that this question sounds pointless and\or weird. I am creating JIT that takes C# code compiles it with csc.exe, extracts the IL and parallize it into CUDA, and I want to override some of the things in C#.

How override base things such as int\ string?
I tried:
class String { /* In namespace System of course */
    BasicString wrap_to;
    public String( ) {
        wrap_to = new BasicString( 32 ); // capacity
    }
    public String( int Count ) {
        wrap_to = new BasicString( Count );
    }
    public char this[ int index ] {
        get { return wrap_to[ index ]; }
        set {
            if ( wrap_to.Handlers != 1 )
                wrap_to = new BasicString( wrap_to );
            wrap_to[ index ] = value;
        }
    }
    ...
}
... // not in namespace System now
class Test {
    public static void f(string s) { }
}

But when I tried:
Test.f( new string( ) );

It error'd Cannot implicitly convert type 'System.String' to 'string'. I tried moving my System.String to just string in the global scope and it error'd on the class itself. Any ideas how? I think somehow it could help if I can compile my .cs files without that mscorlib.dll, but I can't find a way to do it.
Even a way to reach to csc.exe source code may help. (This is critical.)

A: Yes, you will have to not reference mscorlib.dll. Otherwise there will be two System.String classes, and clearly the predefined (C# Specification given) type string cannot be both of them.
See /nostdlib C# compiler option. The page also describes how to do it with a setting in the Visual Studio IDE.
You need to write really many other required types (or copy-paste them) when you do not refer mscorlib.dll!

A:
Even a way to reach to csc.exe source code may help. (This is critical.)

Judging by your comments, this is actually the bit you really need. (Trying to change int and string themselves would involve changing mscorlib and almost certainly the CLR as well. Ouch.)
Fortunately, you're in luck: Microsoft has open-sourced Roslyn, the next generation C# compiler that will ship with Visual Studio 2015.
If you want to change how the compiler behaves, you can fork the code and modify it appropriately. If you really just need to get at the abstract syntax tree (and the like) then you can do that without changing the compiler at all - Roslyn is design to be a "compiler API" rather than just a black-box which takes in source code and spits out IL. (As a mark of how rich the API is, Visual Studio 2015 uses the public API for everything - Intellisense, refactoring, etc.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как получить каждую сотую строку в таблице sql Пытаюсь сделать паджинацию для вывода таблицы.
Сейчас делаю так:
SELECT 'table_id' FROM 'table' WHERE 'условие' ORDER BY 'table_id' DESC

Получаю все table_id и уже потом перебирая их получаю каждый сотый элемент и строю таблицу с пиджинацией.
Но сейчас понял, что в таблице слишком много записей и поиск даже одного поля происходит слишком долго.
Может кто знает как сразу в запросе получить каждый сотый элемент ?
UPD:
Если есть возможность прошу указать пример строки с моими параметрами.


text:
Q: Asynchronous raw socket in python 3.5 I was trying to use raw socket on python 3.5 in an asynchronous way.
I found the asyncore library where we can use raw sockets but it seems it has been deprecated and asyncio library is the way to go.
However after reading the documentation it seems asyncio doesn't support raw sockets.
Do you know other libraries or another way to achieve this goal ?

A: asyncio does provide a public API for raw sockets; however, it's probably better to use the Transport/Protocol abstraction in most cases.
The loop.sock_* coroutines implement the low-level socket operations. If you want even more control, you could watch the file descriptor for events and then read from the socket accordingly.


text:
Q: Snowflake SQL - Create Temporary Date Table for EoM dates I'm only a self-taught data-querying guy and am wholly unfamiliar with creating tables and such. The database I'm working on does have a calendar table, but it's only a forward moving calendar moving three years out. I am needing to create a date table for end of month records between two dates, including before the system dates table begins.
How best can one create this in Snowflake SQL?
Thank you much

A: This will create N end of month records.  You can change the start date and change N to be the delta between your dates.
select
   row_number() over (order by null)  id,
   add_months('2020-01-01'::date, + id) - 1
from table(generator(rowcount => 100))


text:
Q: ClamAV Version Update for rhel-fedora Amazon Linux AMI I have been using ClamAV for quite a while now without any issues however just this week I started getting the following error whenever I try to update the Virus definitions database :
[root@staging milindr]# freshclam
ClamAV update process started at Thu Feb 10 14:12:14 2022
WARNING: Your ClamAV installation is OUTDATED!
WARNING: Local version: 0.102.4 Recommended version: 0.103.5
DON'T PANIC! Read https://www.clamav.net/documents/upgrading-clamav
daily database available for download (remote version: 26448)
Time: 0.0s, ETA: 0.0s [=============================>] 16B/16B
WARNING: downloadFile: Unexpected response (403) from https://database.clamav.net/daily.cvd
WARNING: getcvd: Can't download daily.cvd from https://database.clamav.net/daily.cvd
Trying again in 5 secs...
daily database available for download (remote version: 26448)
Time: 0.0s, ETA: 0.0s [=============================>] 16B/16B
WARNING: downloadFile: Unexpected response (403) from https://database.clamav.net/daily.cvd
WARNING: getcvd: Can't download daily.cvd from https://database.clamav.net/daily.cvd
Trying again in 5 secs...
daily database available for download (remote version: 26448)
Time: 0.0s, ETA: 0.0s [=============================>] 16B/16B
ERROR: downloadFile: Unexpected response (403) from https://database.clamav.net/daily.cvd
ERROR: getcvd: Can't download daily.cvd from https://database.clamav.net/daily.cvd
Giving up on https://database.clamav.net...
ERROR: Update failed for database: daily
WARNING: fc_update_databases: fc_update_database failed: HTTP GET failed (11)
ERROR: Database update process failed: HTTP GET failed (11)
ERROR: Update failed.

However when I do try to update it, I get the following response :
[root@staging milindr]# yum -y install clamav clamav-update
Loaded plugins: priorities, update-motd, upgrade-helper
amzn-main                                                                                | 2.1 kB  00:00:00
amzn-updates                                                                                | 3.8 kB  00:00:00
1067 packages excluded due to repository priority protections
Package clamav-0.102.4-1.44.amzn1.x86_64 already installed and latest version
Package clamav-update-0.102.4-1.44.amzn1.x86_64 already installed and latest version
Nothing to do

Unsure as to why there's this issue and what I can do to fix it as I have tried updating my clamAV version by following the steps provided on  https://www.clamav.net/documents/upgrading-clamav but that has not been very helpful either.
I am a bit new to the Linux environment and have a feeling am missing a major step somewhere. Thanks in advance.

A: 0.102.4 is outdated and old version. Actual version is 0.103.5 or newer.
Here is some reasons why you can't update ClamAV:

*

*Amazon remote repository is outdated and not maintained anymore (you should to update your Linux OS to be able migrate to new repository). This case is most possible if you using current EC2 instance couple of years without updates

*Local repository info is outdated. Try to run sudo yum update before ClamAV installation to update local info

If sudo yum update won't help try to Download newest clamav-0.104.2.linux.x86_64.rpm and install it manually (don't forget to delete old versions first).


text:
Q: Dojox Accordion - uncollapsed panes on add to accordion I'm using dojox/mobile/Accordion and have added some panes to it.
Is there a property I can set on a pane(ContentPane) or an Accordion so that as the panes get added they are added not collapsed?

Thanks

A: You can use the selected parameter for your child panes. See this fiddle for an example; you just add selected: true to your data-dojo-props attribute or the properties that you pass to the child widget constructor if doing it programmatically:
Declaratively

Programmatically
require([
    "dojox/mobile/Accordion",
    "dojox/mobile/ContentPane",
    "dojox/mobile/parser",
    "dojox/mobile",
], function(Accordion, ContentPane) {
    // ...

    var p1 = new ContentPane({
        label: 'External Content1',
        iconPos1: '16,32,16,16',
        href: 'data/fragment1.html',
        selected: true
    });

    // ...
});

A: When you add content panes programmatically you can set selected:true which will initialize them opened
var pane = new ContentPane({
    label: "Added Content",
    selected:true,
    content: "My Content"
});
accordion.byId("testAccordion").addChild(pane2);

Note that this only works in the programmatic approach. Setting selected:true on data-dojo-props declaratively for multiple elements does not work (currently 1.10)
JSFiddle


text:
Q: Update notification I updated to version 16.04 of Ubuntu from version 15.10.
I now get operating system update notifications from the Ubuntu Software program. But does not update other programs I have installed, IE Kcad, Geany. I have to use the software updater program to update these other programs, some of which require a PPA addition to software updater.
Is there a way I can get Ubuntu Software to look at these PPA sites for updates?
Thanks for your help!


text:
Q: Request gets overridden with other data I'm trying to get data for autocomplete using laravel.
Controller:
public function collection_search(Request $request) {
      $term = $request->search;
      $serveurapObj = new Serveurap();
      $result = $serveurapObj->collectionAutocomplete();
      return response()->json($result);
}

Model:
public function collectionAutocomplete($term) {
      $where= ['m.supprime'=>'0', 's.supprime'=>'0'];
      return DB::table('serveuraps AS s')
              ->select(DB::raw('s.nom as hostname'))
              ->join('machines AS m','m.id','=','s.machine_id')
              ->join('typeserveurs AS t','t.id','=','m.typeserveur_id')
              ->where($where)
              ->where('hostname','like','%'.$term.'%')
              ->get();
}

View:

            {!! __('script.serveur') !!}

                <input class="form-control" type="text" name="serveur" id="relance-serveur" role="textbox" aria-autocomplete="list" aria-haspopup="true">

Jquery/Ajax:
$(document).ready(function () {
    // relance serveur autocomplete textbox
    $('#relance-serveur').autocomplete({
        source: function (request, response) {
            alert(request.term)
            $.ajax({
                url: '/scripts/relanceCollection/collection',
                dataType: 'json',
                data: {
                    search: request.term
                },
                success: function (data) {
                    response(data);
                }
            });
        },
    });
});

I'm getting error when accessing the search from js in controller.
Error:

I printed $request but it showed the json data from model. how would I get the search from js to controller so that I can search data based on that term ?

A: The key you are sending is search, not term. Either change your controller code to reflect that, or change the ajax data.
$.ajax({
    ...
    data: {
        → search: request.term
    },
    ...
});

public function collection_search(Request $request)
{
    $term = $request->search; ←
    ...
}

$.ajax({
    ...
    data: {
        → term: request.term
    },
    ...
});

public function collection_search(Request $request)
{
    $term = $request->term; ←
    ...
}

A: You aliased the wrong class. You don't want an instance of a Facade, ever. If you want an instance of something you want the underlying instance, not the facade.
use Illuminate\Http\Request;

Now, $request would be an instance of that class and not the Facade, Illuminate\Support\Facades\Request.

A: I got the result by adding $.map function in success function in JS. if anyone needs it, please refer below js code:
$(document).ready(function () {
    var headers = {
            'X-CSRF-TOKEN':'<meta name="csrf-token" content="{{ csrf_token() }}">'
        };
    // relance serveur autocomplete textbox
    $('#relance-serveur').autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '/scripts/relanceCollection/collection',
                data: {
                    term: request.term
                },
                headers: headers,
                dataType: 'json',
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.hostname,
                            value: item.hostname
                        };
                    }));
                }
            });
        },
        select: function (event, ui) {
            $('#relance-serveur').val(ui.item.label); // display the selected text
            return false;
        },
        minLength: 1
    });
});


text:
Q: Enabling horizontal scaling / scrolling on QChartView (Nov-2016 Qt-5.7.0) I have a long QLineSeries containing something like a strip chart.  I can display it in a QChartView, and if I set HorizontalRubberBand, I can zoom in on a section of it.  The default QChartView also zooms out on right mouse click.  But I don't know how to hook up the horizontal scroll bar so that when I zoom in, I can also scroll left and right along the strip.
The code below creates a simple QLineSeries containing two sine cycles. If I could get that zooming and scrolling correctly, I can extend the idea to my actual project.  Any help?
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QLineSeries *s = new QLineSeries;
    QChart      *c = new QChart;

    for (double theta = 0.0; theta < 4.0 * M_PI; theta += M_PI / 50.0)
        s->append( theta, sin( theta ) );

    c->addSeries( s );
    c->createDefaultAxes( );

    ui->chartview->setChart( c );
    ui->chartview->setRubberBand( QChartView::HorizontalRubberBand );
}

MainWindow::~MainWindow()
{
    delete ui;
}

A: I started playing with the various signals available, and I managed to get my sample program working as desired.  I'm not sure whether this is the approved method, or if it scales well, but it works for me.
One thing that wasn't especially clear to me is that the scroll bars on the QChartView don't scroll the right thing.  They scroll the whole QChart, axes and all.  To scroll the zoomed data in the chart, you need to add a separate scroll bar, and then call the QChart's scroll() function in response to the valueChanged signal.  (I didn't test this, but it might work to call the QAxis's setRange( min, max ) instead.)
Here is code that displays two sine-wave cycles and allows rubber-band zooming.  When zoomed, you can scroll back and forth along the wave.
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
  : QMainWindow(parent)
  , ui(new Ui::MainWindow)
  , scrolling( false )
{
    ui->setupUi(this);

    QLineSeries *s = new QLineSeries;
    QChart      *c = new QChart;

    for (double theta = 0.0; theta < 4.0 * M_PI; theta += M_PI / 50.0)
        s->append( theta / M_PI, sin( theta ) );

    c->addSeries( s );
    c->createDefaultAxes( );
    c->legend( )->hide( );

    ui->chartView->setChart( c );
    ui->chartView->setRubberBand( QChartView::HorizontalRubberBand );

    // PlotAreaChanged seems like it might be useful, but not for this purpose
    // rangeChanged (on the axis) is the one you need.

    connect( c->axisX( ), SIGNAL(rangeChanged(qreal, qreal)), this, SLOT(on_rangeChanged(qreal,qreal)) );
}

void
MainWindow::on_chartScroll_valueChanged( int v )
{
    if (!scrolling) {
        scrolling = true;
//      cerr << "scroll " << v << endl;
        ui->chartView->chart( )->scroll( v - sv, 0 );
        sv = v;
        scrolling = false;
    }
}

void
MainWindow::on_rangeChanged( qreal min, qreal max )
{
    if (scrolling) return;  // Scrolling causes range changes, but we don't have to do anything.

    QChart          *c = ui->chartView->chart( );
    QAbstractAxis   *x = c->axisX( );
    qreal            avg = (min + max) / 2.0;
    bool             range_fixed = false;

    /*
     * Make sure the new range is sane; fix if not.
     */
    if ((max - min) < 0.1) {    // Avoid overzooming
        min = avg - 0.05;
        max = avg + 0.05;
        range_fixed = true;
    }

    if (min < 0.0) { min = 0.0; range_fixed = true; }

    if (max > 4.0) { max = 4.0; range_fixed = true; }

    if (range_fixed) {
        x->setRange( min, max );    // will re-signal with the fixed range
        return;
    }

    qreal    vis_width = c->plotArea( ).width( );
    qreal    all_width = vis_width * (4.0 - 0.0) / (max - min);

//    cerr << "range " << min << " ... " << max << " in " << vis_width << " pixels" << endl;
//    cerr << "full width requires " << all_width << " pixels" << endl;;

    if (max - min < 4.0) {
//        cerr << "set scroll parameters" << endl;
        scrolling = true;
        ui->chartScroll->setMaximum( all_width - vis_width );
        sv = min / (4.0 - 0.0) * all_width;
        ui->chartScroll->setValue( sv );
        scrolling = false;
    } else {
//        cerr << "disable scroll bar" << endl;
        scrolling = true;
        ui->chartScroll->setMaximum( 0 );
        ui->chartScroll->setValue( sv );
        scrolling = false;
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

(Apologies for the hard-coded 4.0 [from 4π].  The Right Thing to do is look at the full range of the data you're scrolling through.)


text:
Q: QThread data sharing method for GL vertex data Let's say I want to render an animated triangle using two threads. One thread manipulates the vertices and the other one manages the QT window and renders the GL context. I have a class cTriangle, with members Eigen::Vector3d m_A, m_B, m_C representing the triangle vertices and a method void updateCoordinates() that operates on the vertices.
cTriangle.h:
#ifndef CTRIANGLE_H
#define CTRIANGLE_H

#include <Eigen/Core>
#include <QObject>
#include <vector>

class cTriangle : public QObject
{
    Q_OBJECT

public:
    cTriangle();

public:

    Eigen::Vector3d m_A;
    Eigen::Vector3d m_B;
    Eigen::Vector3d m_C;

public slots:
    void updateCoordinates();

};

#endif // CTRIANGLE_H

cTriangle.cpp:
#include "cTriangle.h"
#include <iostream>

cTriangle::cTriangle()
{
    m_A = Eigen::Vector3d(0.0, 0.0, 0.0);
    m_B = Eigen::Vector3d(0.2, 0.0, 0.0);
    m_C = Eigen::Vector3d(0.0, 0.2, 0.0);
}

void cTriangle::updateCoordinates()
{
    int ctr = 0;
    double t = 0.0;

    while (true)
    {
        std::cout << "cTriangle::updateCoordinates " << ctr << std::endl;
        double offset = 0.3*sin(t);
        m_A = Eigen::Vector3d(offset, 0.0, 0.0);
        t += 0.00001;
        ctr++;
    }
}

The driver creates a new cTriangle and initiates a QThread, which continuously loops over updateCoordinates(). I also initialize the MainWindow containing a GLWidget.
main.cpp:
int main(int argc, char *argv[])
{

    cTriangle* tri = new cTriangle();

    QThread* thread = new QThread;
    tri->moveToThread(thread);
    QObject::connect(thread, SIGNAL(started()), tri, SLOT(updateCoordinates()) );
    thread->start();

    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

glwidget.h:
#ifndef GLWIDGET_H
#define GLWIDGET_H
#include <QGLWidget>
#include "cTriangle.h"

class GLWidget : public QGLWidget
{
    Q_OBJECT
public:
    explicit GLWidget(QWidget *parent = 0);
    void initializeGL();
    void resizeGL(int w, int h);

private:

signals:
    void repaint();

public slots:
    void paintGL();

};

#endif // GLWIDGET_H

glwidget.cpp:
GLWidget::GLWidget(QWidget *parent) : QGLWidget(parent)
{

}

void GLWidget::initializeGL()
{
    glClearColor(0.2, 0.2, 0.2, 1);
}
void GLWidget::paintGL()
{
    std::cout << "paintGL " << std::endl;

    // ********************************
    // How do I access Triangle data here??
    // ********************************

    glClear(GL_COLOR_BUFFER_BIT);

    glLoadIdentity();

    glBegin(GL_TRIANGLES);
        glColor3f  (1,0,0);
        glVertex3f (0, -0.5, 0);
        glColor3f  (0,1,0);
        glVertex3f (0.5, -0.5, 0);
        glColor3f  (0,0,1);
        glVertex3f (0.0, 0.5, 0);
    glEnd();

}
void GLWidget::resizeGL(int w, int h)
{}

Finally, my question: I need to access the vertex data in the object tri from within GLWidget::painGL. What is the best method for doing so? Setting up signal-slot functionality? Passing a pointer of tri in a thread-safe manner (if so, how?). This is just a toy example, generally the vertex data could be very large. Thanks!!
=============================
One step further:
My plan now is set set up a signal->signal->slot mechanics. GLWidget::glPaint() emits a SIGNAL GLWidget::requestVertices() to another SIGNAL cTriangle::sendVertices(whateverType vertexData), which is then received by SLOT GLWidget::receiveVertices(whateverType vertexData). In main.cpp, how do I CONNECT these signals? How do I get the reference to the GLWidget object? QObject::connect( ???, SIGNAL( requestVertices() ), tri, SIGNAL( sendVertices(double arg) ) );

A: Start by using the signal and slot mechanism. If you emit a signal with a QList of points, the QList uses implicit sharing, so will only copy-on-write.
This is the simplest method for using data across threads and doesn't require any handling of locks by you. If at some point you find this to be too slow, then you can look into optimising the code to improve the speed.
One possible method of optimisation would be to use multiple QList of points, so you write to one, then move on to writing to the next, while emitting the first, to ensure you're not writing to the list being shared and thus minimising the chance of a copy-on-write occurring.
However, there is no need to optimise, unless you're seeing a problem in the first place.


text:
Q: Weird number overlay at the bottom left of Tikzplot I am trying to create a graph using very small numbers and I think I have it working. The problem is that at the bottom left there's an overlay of text that I cannot figure out how to remove. Help would be appreciated. Thanks!
\documentclass{standalone}
%graph and diagrams
\usepackage{tikz}
\usepackage{pgfplots}
\usetikzlibrary{automata,positioning}

\pgfplotsset{compat=1.17} %remember this line or the graph wont work
\begin{document}
\begin{tikzpicture}
\begin{axis}[width=\linewidth, height=15cm,
    title={$\kappa$ as Determined by Distance and Capacitance},
     xlabel={$Distance: \frac{E_0A}{d}_{(10^{-10} \cdot m^{-2}kg^{-1}s^4A^2)} $},
    ylabel={$Capacitance: C_{(nF)}$},
    label style={font=\small},
    xmin=0, xmax=.0000000007,
     ymin=0, ymax= 0.0000000016,
    xtick={0,.00000000005,...,.0000000007},
    ytick ={0.0000000002, 0.0000000004,..., 0.0000000016},
    legend pos=north west,
    ymajorgrids=true,
    grid style=dashed, %remove for undashed grid%
    tick label style={font=\scriptsize,
                      /pgf/number format/.cd, fixed, fixed zerofill},
    scaled ticks=true,
    yticklabel style={/pgf/number format/precision=1},
    xticklabel style={/pgf/number format/precision=1},             ]
%legend
    \legend{$1.777x + 2.7 \cdot 10^{-10}$}
%linear line
\addplot [domain=0:.0000000007, samples=100,color=blue]   {1.777*x + 0.00000000027};
%data points
\addplot +[only marks, mark=oplus, color=black] coordinates
      {(0.0000000000304,0.000000000254) (0.000000000172 ,0.000000001) (0.0000000000369,0.000000000260) (0.0000000000132,0.000000000111) (0.000000000689,0.0000000014)};

\end{axis}

\end{tikzpicture}
\end{document}

A: OP's example throws several errors, of which the first one is
! Package pgfkeys Error: I do not know the key '/pgf/number format/at', to which you passed '(xticklabel cs:0.9,5pt)', and I am going to ignore it. Perhaps you misspelled it.

This is caused by /pgf/number format/.cd used in
    tick label style={font=\scriptsize,
                      /pgf/number format/.cd, fixed, fixed zerofill},

which changes the default path to /pgf/number format. It turns out that pgfplots uses other keys along with the keys passed to tick label style and those "other keys" require the default path unchanged.
Using /pgf/number format/fixed, /pgf/number format/fixed zerofill eliminates the errors as well as the reported "weird number overlay".
PS: When the compilation raises errors, it's better to concentrate on the first error and mention it in question description.


text:
Q: e2fsck fails to check root partition while running from ubuntu usb Even though I booted of a Ubuntu live USB. I keep getting the error:
e2fsck: Cannot continue, aborting.
The root partition I am trying to check is not mounted.
I need to do this so that I can reduce the size of my lvm volume.
How can I overcome this porblem?
 Device     Boot  Start      End  Sectors  Size Id Type
/dev/sda1  *      2048   499711   497664  243M 83 Linux
/dev/sda2       501758 78163967 77662210   37G  5 Extended
/dev/sda5       501760 78163967 77662208   37G 8e Linux LVM

Device     Boot Start      End  Sectors  Size Id Type
/dev/sdb1        2048 78156287 78154240 37.3G 8e Linux LVM

NAME                    MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sdb                       8:16   0 37.3G  0 disk
└─sdb1                    8:17   0 37.3G  0 part
  └─NAS1-root           253:0    0 73.4G  0 lvm  /
sda                       8:0    0 37.3G  0 disk
├─sda2                    8:2    0    1K  0 part
├─sda5                    8:5    0   37G  0 part
│ ├─NAS1-swap_1         253:1    0  892M  0 lvm  [SWAP]
│ └─NAS1-root           253:0    0 73.4G  0 lvm  /
└─sda1                    8:1    0  243M  0 part /boot

I use sudo -i when I run the e2fsck command.
When I run the check on sda1 it works ok but when I run it on sda5 and sdb1 it fails. sda5 and sdb1 are part of my lvm VG for root partition.


text:
Q: PHP echo file size located in pc Ι have somewhere located in my pc a txt file, let's say for example C:\Users\my_file.txt. Is there a way to print its size? As I search it, I am given:
$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';

But what path should I give to filename variable?

A: In Linux, the path separator is /. In Windows, it is either \,  / or \\.
I personally use front-slashes / on both OS so I never get confused.

Below you can find 3 valid full paths on Windows, i.e.:
C:/Users/my_file.txt

or
C:\\Users\\my_file.txt

or simply:
C:\Users\my_file.txt

To get the filesize you can use the function filesize
$myFile = "C:\Users\my_file.txt"
echo filesize($myFile) . "bytes";

If the file is on the same dir as the php script you can use a relative path:
$myFile = "my_file.txt"
echo filesize($myFile) . "bytes";

If the file is one dir below you can also use a relative path.
$myFile = "../my_file.txt"
echo filesize($myFile) . "bytes";

Another relative path example, this time 1 dir UP:
$myFile = "./newdir/my_file.txt"
echo filesize($myFile) . "bytes";

A: Ideally you just give filesize an absolute path.
If that is not an option, you have to give it a relative path (relative to the PHP-file you are in).
Say you have a dir files with another folder in it (php), and in it again there is a file called filesize.php. In the files folder you have a file called bigfile.txt.
To get the filesize of the bigfile.txt in your php script which is in php/filesize.php you could do one of the following:
<?php
$filesize = filesize("../bigfile.txt"); // One folder up (relative)
$filesize = filesize("C:\files\bigfile.txt"); // Absolute path


text:
Q: Assigning an id to this.state to play the correct animation? React Native I have been working ways to figure this problem out. The way I have my code set up is that I have animations in a flatlist and it has created a single animation for how ever many data I have. For example, my JSON data contains 8 categories, my flatlist automatically contains 8 animations. Here is my code:
<FlatList

   data={ this.state.dataSource}

   ItemSeparatorComponent = {this.FlatListItemSeparator}

   renderItem={({item}) => <View>

   <Card>

     <View>
     <TouchableOpacity
     onPress={this.anim_star.bind(this, item.id)}
      style={{position:'absolute',  height: '100%', width: '100%',}}>
      <Animation
      progress={this.state.progress[item.id]}
      source={require('../Animations/favourite_app_icon.json')}
      style={{ height: '100%', width: '100%', position: 'absolute'}}
      resizeMode={`contain`}

      />
      </TouchableOpacity>

     </View>

   </Card>

   </View>

 }

 keyExtractor={(item, index) => index.toString()}
 removeClippedSubviews

/>
Right here, I have been trying to give those animations a unique id (item.id). Here is the function I used for binding:
    anim_star = (id) => {

  let progress = this.state.progress;
  progress[id] = new Animated.Value(0);

    this.setState({ progress });
console.log(this.state.progress);
  Animated.timing(this.state.progress, {
    toValue: 1,
    duration: 2000,
    easing: Easing.linear,
  }).start();

}

I did a console.log to see my results and I can see the correct id being displayed, but I don't think it's corresponding correctly. The animation does not play at all. When I take off the [item.id] in the progress=this.state.progress, the animation works, but every animation in that flatlist plays. I want to play that one animation with the correct id.
Here is my console results:
https://imgur.com/a/7Ja3Tlk
And lastly here are what the constructors look like:
    constructor(props)
{
  super(props);

  this.state = {
  isLoading: true,
  id: '',
  dataSource: '',
  progress: {},
};

Also to note, when all animations did play I console logged those results and noticed that the _children array have [AnimatedProps] and I think that is what triggers the animation.
https://imgur.com/a/9a3VPZa
The array(8) represents all the data that have animations triggered. The reason why the 10 is still there is because I didn't remove:
let progress = this.state.progress;
  progress[id] = new Animated.Value(0);

I tried searching for some answers similar to my problem, but I could not find a single solution. Is there a way to play animations uniquely?
Also you may notice that  is not part of the react-native library, that is because I am using Lottie to play json animations.


text:
Q: Library doesn't properly link at command 'make' I am trying to use some open-source CFD code, and it uses PETSC and some other libraries, so I installed them. But when I try to compile program useing 'make', it seems like libraries are not properly linked with makefile

It seems like petsc isn't properly linked, but I can't know why...

A: The problem is that PETSc depends on some more libraries (X11) than the CFD package counted on. It should have a proper configure that figures these out. However, you can get the link line you need using
cd PETSC_DIR; make getlinklibs

which you can then put in LIBFLAG.


text:
Q: D3: How to select every thing under svg element I create an svg element under body. Subsequently I append more things to the svg.
svg = d3.select("body")
  .append("svg")
    .attr("width", 1000)
    .attr("height", 500)

svg.append("g")
// ... and many others more

How do I select everything under svg but svg itself? Like,
d3.select(all_under("svg"))

A: d3.select('svg').selectAll('*')

or even better as Lars Kotthoff purposed:
d3.selectAll("svg > *")


text:
Q: How to whitelist Zapier IP addresses in AWS RDS security group I've inherited an AWS RDS instance and it's my first run at trying to manage that side of things in the data world, sorry if I'm misunderstanding or overlooking anything!
I'm trying to use Zapier to connect a 3rd party app to our AWS RDS Postgresql database. I've created a new user in postgres and can connect with these credentials from my local machine without issue. However, when I try to connect Zapier to our db with the same credentials, it fails. This is definitely due to the fact that we only allow whitelisted IPs to connect to our db. So, I should be able to whitelist Zapier's IP address(es) and problem solved, yeah?
Unfortunately I'm unable to figure out which IPs Zapier needs me to whitelist. This article is of no use, because the "We send out database connections from the IP addresses listed here." link is dead. I can find a similar link in the MongoDB connection help page, but it links to, what I think is, every single AWS IP address.
Surely many before me have been able to set this connection up, so what am I missing? Zapier has been of little assistance to me so far.

A: In the article you link to only the PostreSQL-Link is dead, the other two (MySQL and SQL-Server) work. In both cases the claim, that they're using a static IP to connect to your database (Source):

This is useful if you use a non-AWS host, for example: Rackspace, HostGator, Linode, DigitalOcean, etc. Zapier connections currently come from static IP addresses. Zapier will make connections to your database from the following IP address:
54.86.9.50
Important: Don't forget to do both things: open up your firewall and add the IPs to your user GRANT permissions.

The IP 54.86.9.50 is listed in both articles so chances are they're using that to create connections to Postgres as well.
I'd try to add 54.86.9.50 to the security group and check if it works.


text:
Q: How to create own inheritable class with underscore I want to built a Backbone.Model like object/class.
I looked through the Backbone docs and found that they create a inheritable object/class with its inheritable attributes, methods in two steps:
I. Create a function with some attributes
var Model = Backbone.Model = function(attributes, options) {
    var defaults;
    attributes || (attributes = {}); //?
    if (options && options.parse) attributes = this.parse(attributes); //?
    if (defaults = getValue(this, 'defaults')) {
      attributes = _.extend({}, defaults, attributes); // ?
    }
    if (options && options.collection) this.collection = options.collection;
    this.attributes = {};
    this._escapedAttributes = {};
    this.cid = _.uniqueId('c');
    this.changed = {};
    this._silent = {};
    this._pending = {};
    this.set(attributes, {silent: true});

    this.changed = {};
    this._silent = {};
    this._pending = {};
    this._previousAttributes = _.clone(this.attributes);
    this.initialize.apply(this, arguments);
};

II. use underscore's extend to give it some functions
_.extend(Model.prototype, Events, { // Events?
   changed: null,

   _silent: null,

   _pending: null,

   idAttribute: 'id',

   initialize: function(){},

   toJSON: function(options) {
       return _.clone(this.attributes);
   }

   // other Model methods...
};

I have some questions about this behaviour:

*

*What does line 3-4 in the first part do

*What happens in line 6?

*Why do we overgive "_.extend" the Events object, what else could I give as parameter?

Is there anything else I have to pay attention about?
Regards

A: Line 3, attributes || (attributes = {}); is an example of short circuit evaluation.
If attributes has a falsy valye, then javascript will evaluate the second part of the OR expression. That part assigns attributes a value of {}, an empty object. The end result is, if attributes is null or undefined (typical case) then, assign attributes an empty object.
That line is equivalent to saying:
if (attributes == false) { // attributes can be any value that evaluates to false
                           // attributes could be null, undefined, false, 0 etc
   attributes = {};
}

Same case with line 4, if (options && options.parse) attributes = this.parse(attributes);
If an options object exists, ie its not null or undefined, and the options object has a valid property called parse, then assign attributes the value of this.parse(attributes);
EDIT 1:
The _.extend lines can be explained by the Underscore.js documentation.
Its a standard pattern to create a new object that will contain properties of all passed in objects. In the first example attributes = _.extend({}, defaults, attributes); // ? the pattern is used to override the default values with what ever may have been passed. You would see this pattern followed in most plugins that allow you to pass in an options object. If you dont pass in anything, the default values will be used. If you pass in only a few properties, the remaining will get their values from the defaults.
http://api.jquery.com/jQuery.extend/ is NOT the exact same thing. But its very similar. Their documentation is much better. You will understand the concept better.
EDIT 2:
The Backbone Events class has some event handling related methods. The Backbone Model class also needs to be able to make use of event handling. It needs to raise events to tell the view to re-render itself, it needs to listen to events from the dom when the view changes the underlying data. This event handling functionality could either have been re-written from scratch when defining the Model class, or the Model class could be extended to get these methods from the Events class. That latter is what is happening.
If you read the documentation for the $.extend or _.extend, you will realize that the Model class is being extended not just with the properties under Events, but also with other properties like toJSON and initialize etc...

A: As to what's going on on line 6 - the object is created that contains all properties of defaults object and all from attributes object.
Any  property of defaults object that is already defined in attributes object will get overwriten by the value of latter.


text:
Q: Which is faster in perl, Parallel::ForkManager or threads? Threads are considered as lightweight processes. Will they actually run faster than an equal number of forked processes?

A:
Threads are considered as lightweight processes.

Oh no, they are not. The Perl threading model is intertwined with fork mocking on Windows systems. In many respects, spawning a new thread in Perl behaves the same as forking off a new process: Both resulting control flows run in seperate perl interpreters. That is, the whole program state is copied to make a new interpreter.

Will they actually run faster than an equal number of forked processes?

Not likely. Spawning a new thread is software-side, and done by perl. Forking is done by the OS (on *nix systems) which can make use of copy-on-write techniques. This can make forking much cheaper. A small test:
$ time perl -Mthreads -e'threads->new(sub{threads->exit})->detach for 1 .. 5E3'
real    0m10.651s
user    0m16.421s
sys     0m1.904s
$ time perl -Mthreads -e'fork || exit  for 1 .. 5E3'
real    0m2.347s
user    0m0.032s
sys     0m0.516s

This spawns five thousand threads/processes. As it was tested on Linux, spawning a new process turns out to be faster. This may not be the case on other OSes.
This is not to say that Perl threads would be useless: They provide many benefits like optionally shared data, queues to pass data around, semaphores to manage shared resources, threads can return values etc.. The easiest way to share data betwen processes (without using modules) is the pipe builtin which creates two linked filehandles.

Do not confuse different interpretation of the word thread which each other:

*

*kernel threads are hardware-level execution lines. They are not generally scheduled, but run in parallel. Each processor has at least one thread.

*OS threads are provided by the operating system. Modern OSes schedule thread execution themselves (preemptive scheduling). Generally, all data is shared, the threads just have different stacks. Perl threads choose not to emphasize shared properties.

*Software threads, also green threads are scheduled by the software itself, often by cooperative scheduling. Many languages with cheap threads choose this model, e.g. Go. Two green threads do not neccessarily run in parallel. Coroutines and green threads effectively are related concepts: both describe concurrent execution paths.
Software threads can sometimes run faster than OS threads because the software can make context switches at convenient places in the program. (Preemptive switching between OS threads or processes is more expensive, as the OS kernel has to run on regular intervals, and the processor cache and registers will have to be updated with data of another thread on each context switch. This does not matter much when writing regular application code)
Perl threading does not generally use this model, however a module for coroutines exists (Coro).

A: The threads and forks module provide the same interface. You can switch between worker threads and worker processes by changing a single word in your program. Test it yourself.
The difference is going to be eclipsed by how you use threads/forks. Misuing them can slow down your program enormously.


text:
Q: Deploy WAR file to Openshift without using GIT? I want to upload a WAR file to my Openshift account , but it forces me
to use GIT ot GITHUB (here). Please forgive me for saying this , but this is very very annoying .
Is there any way upload a WAR file straight to my application without using some third party ?
My application (in the Openshift) consists of : Tomcat 7 (JBoss EWS 2.0), MySQL 5.5 .
Much appreciated

A: Please follow the instructions in the following link
https://www.openshift.com/kb/kb-e1088-how-to-deploy-pre-compiled-java-applications-war-and-ear-files-onto-your-openshift-gear
More details :
You can use like this :
Hit git and log into the git bash , and then do this:
scp <your local file name> <your hash number>@<your app name>-<your domain name>.rhcloud.com:~/<app name>/data/

example:
scp hello.csv 87b95e67477f442c9356a4ae49cd7c9e@cdapp-music.rhcloud.com:~/cdapp/data/

External Sources : from here

A: You may refer https://developers.openshift.com/en/tomcat-deployment-options.html
Steps:

*

*git clone to download the source code

*remove  src and pom.xml from repo and push

*Use Win Scp / FileZilla to log into your app

*Paste ROOT.war here /var/lib/openshift/{APP_ID}/app-root/runtime/dependencies/jbossews/webapps
or simply app-root/runtime/dependencies/jbossews/webapps from the landing directory.


text:
Q: Consumir funcion Web Service WSDL con Nusoap PHP alguien me prodia ayudar , soy nuevo en php y estoy  tratando de consumir un servicio por el protocolo soap  y no he podido llamar la función que contiene un array con un listado para cargarlo a un combobox . si alguien me prodria ayudar se lo agradecería.
 $respuesta = $client->__soapCall('alumnos', array('id' => '01','Nombre' => 'Esteban'));
    print_r($respuesta);


text:
Q: java: How can I know the type of variable inside of Object? I have the following code:
void testme(Object a) {
  # printing the type of the variable transferred to the function
}

how can I know the type of the variable that passed to that function? for example how can I know the difference if the user executed the function as the following:
Integer a=5;
testme(a);

or
String a="a";
testme(a);

in general i'm building a generic functions to work with my database, and I need to use setLong/setInt/setString depends on which type of variable transfered to the function.
any ideas?
thanks

A: You can use instanceof and/or getClass. The former tests against a specific class, the latter actually gives you the Class object (String.class, etc.) for the argument. So for instance:
if (a instanceof String) {
    // ...
}
else if (a instanceof Integer) {
    // ...
}
// ...

But for your specific case, you may be able to use one of the versions of PreparedStatement#setObject.

A: *

*object.getClass() returns the class of the object. You can use equals or isAssignableFrom(..) to make reflective comparisons.

*you can use the instanceof operator to make static comparisons: if (object instanceof String) {..}
While they are fine in your case, you should avoid using these in the general case. If you know in advance what will be the types that are passed, overload the methods: foo(Integer i) and foo(String s). If you don't know, you can use polymorphism and double-dispatch. Just make your objects implement a common interface:
interface Testable {
   void invokeTest();
}

class FooTest implements Testable {
    public void invokeTest() { // code specific for FooTest }
}

class BarTest implements Testable {
    public void invokeTest() { // code specific for BarTest }
}

And then:
public void test(Testable testable) {
    test.invokeTest();
}

A: Use the instanceof keyword
if(something instanceof String)
{
}
else if(something instanceof YourType)
{
}

A: if (a instanceof Integer) or
if (a instanceof String)

A: If you're end goal is to operate with the database it's best NOT to use Object on your function like this.  It doesn't tell anyone what is legal to pass.  I'd suggest using JDBC setObject(int parameterIndex, Object x, int targetSqlType) instead, and have the caller identify the JDBC Type to you:
 public void someFunction( Object obj, int targetSqlType ) {
    statement.setObject( nextIndex, obj, targetSqlType );
 }

What you are doing with instanceof or getClass() is typically a bad practice.  You're loosing vital type information by using Object then turning around and hard coding that type information in an if ladder.  It's better to define multiple methods for each type all named the same thing.  So if you have someFunction that can take 5 different parameter type you'd do the following:
  public void someFunction( Integer value ) {
       statement.setInt( convertThisValue( value ) );
  }

  public void someFunction( Long value ) {
       statement.setLong( convertThisValue( value ) );
  }

  public void someFunction( String value ) {
     ...
  }

  public void someFunction( Boolean value ) {
     ...
  }

  public void someFunction( Double value ) {
     ...
  }

  private <T extends Number> T convertThisValue( T value ) {
     // do some shared logic on processing the value
  }

In this example I've shown how you can easily define all the types you understand as separate methods differing only by type, and how you might centralize some conversion logic in a generic function (convertThisValue()) so you can share some processing between multiple types.  What's better about this approach is you're using the Java complier to handle the work for you matching up the right method with the type the caller passed to it.  No need for an if ladder, and the compiler will complain to the user when they aren't using a known type as oppose to using Object and having it die at runtime.
In JDBC the known types are well defined so you can easily create methods that know how to handle each type understood by every JDBC database.  Also using the setObject() method makes your job much easier.


text:
Q: How to do the uninstall process by using UI dialog box? i.e. If i click the uninstall button in UI dialog box It should process uninstall for my msi file. what things i need to add to the wix coding and is that custom action need for this?

A: There is no need for a custom action.
You will have to include one of the Wix provided dialog sets as part of your installer source code.
http://wixtoolset.org/documentation/manual/v3/wixui/dialog_reference/wixui_minimal.html
Your requirement can very well be met by making use of the WixUI_Minimal dialog set.
For an example of how to include a built in dialog set to your installer, please see the following URL:
http://wixtoolset.org/documentation/manual/v3/wixui/wixui_dialog_library.html
Hope this helps.


text:
Q: upcasting in actionscript 3 Hi I have a custom class that extends Sprite, that controls positioning on the stage.  I would like the class that manages the stage to be able to take any sprite that is added to the stage and convert it to custom class type, ie wrap it so that the managing class can position a native sprite accordingly.
Does anyone know if it is possible to do something like the following
var managed:managedSprite = new managedSprite(nativeSprite);

where the managedSprite extends the Sprite class? I don't want to have to composite in a reference to the sprite if at all possible in order to prevent the overhead associated with the managedSprite already extending Sprite.
Is there anyway using reflection (perhaps the commons.reflection library)?
Thanks

A: You may want to use the 'Decorator' pattern.
It seems a little bit complex at the first sight but it's quite easy to understand and use.
http://www.as3dp.com/2009/04/actionscript-30-easy-and-practical-decorator-design-pattern/

A: You can add an event listener to the stage and use Event.ADDED to get a reference to any display object added anywhere in the display list.
Then simply type cast if the added item is a subclass of ManagedSprite (BTW, the convention is to start your class names with an uppercase letter):
stage.addEventListener (Event.ADDED, onAdded);

function onAdded( ev:Event ):void {
    if (ev.target is ManagedSprite) {
        var managed:ManagedSprite = ManagedSprite( ev.target );
        doStuffWith( managed );
    }
}

EDIT
I think I only just understood your question:  You are not trying to do an actual type cast - which would require your class hierarchy to be already set up, i.e. you'd have to have extended the ManagedSprite class already - but to add functionality at runtime!
I would strongly discourage you from trying to do deep copies or such - it will be heavy on performance, depending on how many sprites you are going to add, and you will no longer have your compiler to help you prevent errors.
Rather, see if you can't favor composition over inheritance: Create a kind of "proxy" class for the sprite, let's call it ManagedSpriteProxy, which implements all the methods you would call on ManagedSprite, but forwards all the actual manipulations to its `managedSprite' property.  Then use the event handler I outlined above to create the proxy objects and attach the respective sprites:
public class ManagedSpriteProxy {
    private var _managedSprite:Sprite;

    public function ManagedSpriteProxy( managedSprite:Sprite ) {
        this.managedSprite = managedSprite;
    }

    public function get managedSprite():Sprite {
        return _managedSprite;
    }

    public function set managedSprite( managedSprite : Sprite ):void {
        _managedSprite = managedSprite;
        setUpAnyHandlersOrWhatever();
    }

    private function setUpAnyHandlersOrWhatever():void {
        // Many wonderful things happening
    }

    // Many more wonderful things happening via public API
}

// somewhere else

public class SpriteManager {
    private var _managedSprites:Array = [];

    public function SpriteManager() {
        addEventListener( Event.ADDED_TO_STAGE, onAddedToStage );
    }

    private function onAddedToStage( ev:Event ):void {
        removeEventListener( Event.ADDED_TO_STAGE );
        stage.addEventListener( Event.ADDED, onAdded );
    }

    private function onAdded( ev:Event ):void {
        if( ev.target is Sprite ) {
            addWithProxy( ev.target as Sprite );
        }
    }

    private function addWithProxy( sprite:Sprite ) : void {
        var proxy:ManagedSpriteProxy = new ManagedSpriteProxy( sprite );
        _managedSprites.push( proxy );
    }

    // Insert here whatever methods used to manage the sprites,
    // all of them call the proxies instead of the sprites!
}


text:
Q: AADSTS500011 - PowerBi C# .NET (resource x not found in tenant y) I am trying to integrate the power bi embedded with C#, I always have this same error that comes out, I put it to you just below, as well as the versions of the packages and the code (basic) which is supposed to do the work .
Thank you for all your answers
Microsoft.PowerBI.Api (v2.0.12)
Microsoft.PowerBI.JavaScript (v2.5.1)
Microsoft.IdentityModel.Clients.ActiveDirectory (v3.13.9)

Microsoft PowerBI JavaScript (v2.5.1)
Microsoft IdentityModel Clients.ActiveDirectory (v3.13.9)
Note that the two head variables are temporary.
The error always come out at this line : var authenticationResult = await authenticationContext.AcquireTokenAsync(this.resourceUrl, this.applicationId, credential);
There is the error message : "exceptionMessage": "AADSTS500011: The resource principal named https://analysis.windows.net/powerbi/api/ was not found in the tenant named x. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent your authentication request to the wrong tenant.
public async Task<EmbedConfigResource> EmbedReport([FromUri]string username, [FromUri]string roles)
    {
        roles = "None";
        username = this.pbiUsername;

        var result = new EmbedConfigResource { Username = username, Roles = roles };

        var credential = new UserPasswordCredential(this.pbiUsername, this.pbiPassword);
        var authenticationContext = new AuthenticationContext(this.authorityUrl);
        var authenticationResult = await authenticationContext.AcquireTokenAsync(this.resourceUrl, this.applicationId, credential);
        var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");

        using (var client = new PowerBIClient(new Uri(this.apiUrl), tokenCredentials))
        {
            var reports = await client.Reports.GetReportsInGroupAsync(this.workspaceId);

            Report report = reports.Value.FirstOrDefault(r => r.Id == this.reportId);

            var datasets = await client.Datasets.GetDatasetByIdInGroupAsync(this.workspaceId, report.DatasetId);
            result.IsEffectiveIdentityRequired = datasets.IsEffectiveIdentityRequired;
            result.IsEffectiveIdentityRolesRequired = datasets.IsEffectiveIdentityRolesRequired;
            GenerateTokenRequest generateTokenRequestParameters;

            var rls = new EffectiveIdentity(this.pbiUsername, new List<string> { report.DatasetId });
            if (!string.IsNullOrWhiteSpace(roles))
            {
                var rolesList = new List<string>();
                rolesList.AddRange(roles.Split(','));
                rls.Roles = rolesList;
            }

            generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view", identities: new List<EffectiveIdentity> { rls });

            var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(this.workspaceId, report.Id, generateTokenRequestParameters);

            result.EmbedToken = tokenResponse;
            result.EmbedUrl = report.EmbedUrl;
            result.Id = report.Id;

            return result;
        }
    }

A: You must log into Azure portal, go to Azure Active Directory -> App registrations, select your app, click View API permissions, and then grant admin consent by clicking the button at the bottom:

If you don't have access to the portal, or the button is disabled, you must ask your admin to do it for you.


text:
Q: Connectedness of subsets Let $(X,d_x)$ be a metric space, and let $A$ be a non connected, non empty, closed subset of $X$.
Can I conclude that $A$ equals to $X$ and $X$ is not connected?

It seems that I had wrong understanding towards connectedness, but now I understand it.
And I have a further question: if there is another metric space (Y,dy), can I say that the image of f(A) is a closed subset of Y?

A: The answer to the additional question is no. Let $\langle X,d_x\rangle$ be $\Bbb R$ with the usual metric, and let $\langle Y,d_y\rangle$ be $[-1,1]$ with the usual metric. $\Bbb Z$ is a closed subset of $X$ that is not connected. Let
$$f:\Bbb R\to[-1,1]:x\mapsto\frac2\pi\tan^{-1}x\;;$$
$f$ is continuous and maps $\Bbb R$ onto $(-1,1)$. However, $f[\Bbb Z]$ is not closed in $[-1,1]$: both $-1$ and $1$ are limit points of $f[\Bbb Z]$.
For a simpler example, let $X=\Bbb Z^+$ with the usual metric, and let $Y=\{0\}\cup\left\{\frac1n:n\in\Bbb Z^+\right\}$ with its usual metric. $X$ is a closed subset of itself that is certainly not connected. The map
$$f:X\to Y:n\mapsto\frac1n$$
is continuous, and $f[X]=\left\{\frac1n:n\in\Bbb Z^+\right\}$ is not closed in $Y$, since it has $0$ as a limit point.


text:
Q: how to print application name provided in .yml file in every log statement? I wanna print my application name provided in .yml file in my log4j logs
my log4j pattern is
LOG_PATTERN=[%d{yyyy-MM-dd HH:mm:ss.SSS}] boot%X{context} - ${PID} ${LOG_LEVEL_PATTERN} [%t] --- %c{1}: %m%n

Currently I am getting logs like
2017-09-16 15:53:35.687 INFO 18302 --- [  restartedMain] mc.n.e.EurekaDiscoveryClientConfiguration : My Log print statement

The format i want my logs to print
2017-09-16 15:53:35.687 INFO 18302 --- [**APPLICATION_NAME**] [  restartedMain] mc.n.e.EurekaDiscoveryClientConfiguration : My Log print statement

How can I put the application name in there in log4j log

A: Assuming this is a web application, you can use a Filter and MDC.
See example:
public class MDCFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        try {
            MDC.put("appName", "**APPLICATION_NAME**");
            chain.doFilter(request, response);
        } finally {
            MDC.remove("appName");
        }
    }
}

The Filter above will put your app name into MDC and then you can use a log pattern to print the app name.
Based on your log pattern, see modification below:
%d{yyyy-MM-dd HH:mm:ss.SSS} boot%X{context} - ${PID} ${LOG_LEVEL_PATTERN} [%t] --- [%X{appName}%n] %c{1}: %m%n

Note: %X{appName}%n which will output what was placed in the filter MDC.put("appName", "**APPLICATION_NAME**");
The above will output the following:
2017-09-16 15:53:35.687 INFO 18302 --- [**APPLICATION_NAME**] [  restartedMain] mc.n.e.EurekaDiscoveryClientConfiguration : My Log print statement


text:
Q: Date Formatting with two dates I am converting the input string to date. When i try to give two dates as inputs Date of Birth and Date of Joining, i don't get any satisfied result. Also help me with re-promt if the input is invalid. Thanks in advance.
public class EmployeeInfo {
int id;
static String name, DoBS, DoJS;
Date DoB, DoJ;

public void checkDate(String dt) throws ParseException {

    SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy");
    SimpleDateFormat sdf3 = new SimpleDateFormat("dd MMMM yyyy");

    Date date = null;

    try {
        date = sdf1.parse(dt);
    } catch (ParseException e) {
        try {
            date = sdf2.parse(dt);
        } catch (ParseException e1) {
            try {
                date = sdf3.parse(dt);
            } catch (ParseException e2) {
                String invalid="Invalid,Retry";
                System.out.println(invalid);
                // TODO: Whatever to do when it doesn't find a date
            }
        }
    }

        setDateOfBirth(date);
        setDateOfJoining(date);
}

void setDateOfBirth(Date DoB) {
    this.DoB = DoB;
}

void setDateOfJoining(Date DoJ) {
    this.DoJ = DoJ;
}

void print() {
    System.out.println("User ID: " + id);
    System.out.println("Name: " + name);
    System.out.println("Date Of Birth: " + DoB);
    System.out.println("Date of Joining: " + DoJ);
}

public static void main(String[] args) throws ParseException {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter the name: ");
    name = scanner.nextLine();

    System.out.println("Enter the Date Of Birth: ");
    DoBS = scanner.nextLine();

    System.out.println("Enter the Date of Joining: ");
    DoJS = scanner.nextLine();

    EmployeeInfo e = new EmployeeInfo();

    e.checkDate(DoBS);
    e.checkDate(DoJS);
    e.print();

}
}

A: So I went and fixed it up for you, its a bit hacked together, but will work just fine
First of all, you should have EmployeeInfo as separate class
EmployeeInfo.java
public class EmployeeInfo {
    int id;
    static String name;
    Date DoB, DoJ;

    public void setName(final String name) {
        this.name = name;
    }

    public void setDateOfBirth(final Date DoB) {
        this.DoB = DoB;
    }

    public void setDateOfJoining(final Date DoJ) {
        this.DoJ = DoJ;
    }

    void print() {
        System.out.println("User ID: " + id);
        System.out.println("Name: " + name);
        System.out.println("Date Of Birth: " + DoB);
        System.out.println("Date of Joining: " + DoJ);
    }
}

And then you should have your main class that runs and has all the logic
Main.java
public class Main {
    public static Date checkDate(final String dt) throws ParseException {

        final SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
        final SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy");
        final SimpleDateFormat sdf3 = new SimpleDateFormat("dd MM yyyy");

        Date date = null;

        try {
            date = sdf1.parse(dt);
        } catch (final ParseException e) {
            try {
                date = sdf2.parse(dt);
            } catch (final ParseException e1) {
                try {
                    date = sdf3.parse(dt);
                } catch (final ParseException e2) {
                    final String invalid = "Invalid,Retry";
                    System.out.println(invalid);
                }
            }
        }
        return date;
    }

    public static void main(final String[] args) throws ParseException {
        final Scanner scanner = new Scanner(System.in);
        final EmployeeInfo e = new EmployeeInfo();
        System.out.println("Enter the name: ");
        e.setName(scanner.nextLine());
        Date d = null;
        while (d == null) {
            System.out.println("Enter the Date Of Birth: ");
            d = checkDate(scanner.nextLine());
        }
        e.setDateOfBirth(d);
        d = null;
        while (d == null) {
            System.out.println("Enter the Date of Joining: ");
            d = checkDate(scanner.nextLine());
        }
        e.setDateOfJoining(d);

        e.print();

    }
}

Hope this gives you some insight of how it is done. I implore you to compare both source codes, your amd mine and try to understand what has been changed and try to find out why(on your own).


text:
Q: does n-way equi join follow associative law? If there are 3 tables and I wish to equi-join all of them.
Example Statement 1 : (Table_1 EQUIJOIN Table_2) EQUIJOIN Table_3
Example Statement 2 : (Table_2 EQUIJOIN Table_3) EQUIJOIN Table_1
When these statements are executed separately, are the outputs from both the statements same?

A: Yes.  Equijoins are associative and commutative and all that.  The ordering of the tables doesn't matter.  The ordering of the conditions within each table doesn't.
You can sort of visualize this because an equi-join is a subset of the Cartesian product of all the tables.  The joins are then filtering this down, and the order of the filters doesn't matter -- if a row is not in any of the filters, the ordering of the filters is irrelevant.

A: An Equi Join is just a particular case of INNER JOIN where all the comparisons are equality. Since INNER JOIN is associative and commutative, Equi Join must also be. See Does the join order matter in SQL? and Proof that Inner Join is Commutative.


text:
Q: Why am I getting a HTTPError when trying to connect to my Azure ADLS Gen 2 container via Spyder IDE? I am trying to connect to a CSV file in my ADLS GEN 2 Container using Python. I am trying to do this using the Spyder IDE. I saw an example code online:
https://learn.microsoft.com/en-us/azure/synapse-analytics/spark/tutorial-use-pandas-spark-pool
So with it, I came up with the following:
import pandas

#read csv file
df = pandas.read_csv('https://david65.dfs.core.windows.net/taxi/raw/taxi_zone.csv')
print(df)

But I get the following error:
HTTPError: Server failed to authenticate the request. Please refer to the information in the www-authenticate header.

Any help would be greatly appreciated

A:
HTTPError: Server failed to authenticate the request. Please
refer to the information in the www-authenticate header.

This error occurs due to the path of Adls are not being correctly formulated.
The Azure Data Lake Storage Gen2 connector only supports paths with container, and not subfolder or file.
https://<Storage Account name>.dfs.core.windows.net/<container name>

You can also see same issue in MS Q& A by WaqqasZia-4002
As Thomas said please check your linked service in your Azure synapse studio  please check if you have given correct keys and url:

Reference:
Solved: Re: Error when trying to connect to ADLS Gen2 file.


text:
Q: Euler transform of a series i want to prove some identity but i am having trouble using euler transform properly on a specific function, i checked the equality and it doesnt hold, here is the theorem and my approach. THeorem.
$$\frac{1}{1-at}f\left(\frac{bt}{1-at}\right)=\sum_{n=0}^{+\infty}t^{n}\sum_{k=0}^{n}{{n}\choose{k}}b^{k}a^{n-k}a_{k}$$
$$f(t)=\sum_{n=0}^{+\infty}a_{n}t^{n}$$
Where f is analytiic on a unit disk.
I want to apply this transformation to a function given as follows
$$\frac{1}{4}\ln ^{2}\left(\frac{1+x}{1-x}\right)=\sum_{n=1}^{+\infty}\frac{h_{n}}{n}x^{2n}$$
Where $h_{n}=\sum_{p=1}^{n}\frac{1}{2p-1}$.
What i get is
$$\frac{1}{4}\frac{1}{1-at}\ln ^{2}\left(\frac{1+\frac{bt}{1-at}}{1-\frac{bt}{1-at}}\right)=\sum_{n=1}^{+\infty}x^{2n}\sum_{k=1}^{n}{{n}\choose{k}}\frac{h_{k}}{k}b^{k}a^{n-k}$$
I checked it for $a=b=\frac{1}{2}$ and for $t=\frac{1}{3}$ and it doesnt hold. Please point out the mistake and help me. Thank you very much.


text:
Q: jQuery: Unbind event handler I chose to go with binding element to the body to have them affecting elements even though they are not yet there. Now, I want to unbind some handlers as I go and this is where I am encountering some difficulties.
Code:
$('body').unbind('click', deleteComment); //unbind
$('body').on('click', '.deleteCommentButton > img', deleteComment); //binding

The question is how I am supposed to unbind it specifically for .deleteComment > img?

A: If you use .on you need .off to unbind
$("body").off('click', '.deleteCommentButton > img', deleteComment);

look here http://api.jquery.com/off/

A: You can remove this by using:
$("body").off('click', '.deleteCommentButton > img', deleteComment);

This will unbind the event handler from the selected elements.
Link to the api


text:
Q: Hide for 10 seconds I'm doing a small script which the element should disappear for only 2 seconds and then return to appear alone, I leave the link here Fiddle

im trying using fade and set time but it not works

A: The this on $(this).fadeIn(); does not point to the image anymore.
Try this:
 $(document).ready(function() {
            $('img').click(function() {
                var img = this; /* Store it on variable img */
                $(img).fadeOut();
                setTimeout(function() {
                    $(img).fadeIn(); /* Can access variable img here */
                }, 1000);
                //$(this).toggle();
            });
        });

Fiddle: https://jsfiddle.net/7rfypomx/1/

A: $(this) refer to the window, you have to use $('img').fadeIn(); to make the image appearing again
 $(document).ready(function() {
            $('img').click(function() {
                $(this).fadeOut();
                setTimeout(function() {
                    $('img').fadeIn();

                }, 1000);
                //$(this).toggle();
            });
        });

https://jsfiddle.net/ftf6wr8L/

A: Try doing this it will work.

A: Try this I also updated here:
$(document).ready(function() {
        $('img').click(function() {
            var img = $(this);
            $(this).fadeOut();
            setTimeout(function() {
                img.fadeIn();

            }, 1000);
            //$(this).toggle();
        });
    });

A: Assign $(this) into a variable ex. var ty = $(this);
and use below line for faceIn() function.
$(ty).fadeIn();

Also I have updated in your existing fiddle link as well. Check Here

A:

 $(document).ready(function() {
        $('img').click(function() {
            $(this).fadeOut(function(){
               $(this).fadeIn(15000);
            });
      });
});
    table,
        th,
        td {
            border: 1px solid black;
        }

        img {
            width: 25px;
            height: 25px;
        }


text:
Q: How to print a dictionary's name? daisy = {
    'type' : 'dog',
    'owner' : 'miranda',
    }

bella = {
    'type' : 'cat',
    'owner' : 'luke',
    }

charlie = {
    'type' : 'lizard',
    'owner' : 'mike',
}

pets = [daisy, bella, ruby]

How to print out only the names of the dictionaries i.e. daisy, bella, charlie from a list?

A: This is really an xy problem. You should never need to print the names of variables. The reason is that the data structures often get passed around in ways that the names of the variable get lost. This is what happens when you do:
pets = [daisy, bella, ruby]

Here pets is just a list of dictionaries...they are no longer named.
If the name is significant, then it should be part of the data. For example:
daisy = {
    'name': 'Daisy',
    'type': 'dog',
    'owner': 'miranda',
    }

bella = {
    'name': 'Bella',
    'type': 'cat',
    'owner': 'luke',
    }

charlie = {
    'name': 'Charlie',
    'type': 'lizard',
    'owner': 'mike',
}

pets = [daisy, bella, charlie]

for pet in pets:
    print(pet['name'])

Prints:
Daisy
Bella
Charlie

In fact, you can get rid of the named variable altogether now:
pets = [
    {
        'name': 'Daisy',
        'type': 'dog',
        'owner': 'miranda',
    },
    {
        'name': 'Bella',
        'type': 'cat',
        'owner': 'luke',
    },
    {
        'name': 'Charlie',
        'type': 'lizard',
        'owner': 'mike',
    }
]

A: You can do it like this:
daisy = {
    'type' : 'dog',
    'owner' : 'miranda',
    }

bella = {
    'type' : 'cat',
    'owner' : 'luke',
    }

ruby = {
    'type' : 'lizard',
    'owner' : 'mike',
}

pets = [daisy, bella, ruby]

for i, e in list(globals().items()):
    if e in pets:
        print(i)

A: daisy = {
    'name': 'Daisy',
    'type': 'dog',
    'owner': 'miranda',
    }

bella = {
    'name': 'Bella',
    'type': 'cat',
    'owner': 'luke',
    }

charlie = {
    'name': 'Charlie',
    'type': 'lizard',
    'owner': 'mike',
}

pets = [daisy, bella, charlie]

for i in pets:
    name = i["name"]
    print(name)


text:
Q: Concurrent static file handling in Tornado is blocking? I have a webserver which among other things serves static files. From this http://tools.pingdom.com report, it seems something is blocking when serving several files at the same time to the same client?
The wait-time increases for each image:

Report: http://tools.pingdom.com/fpt/dgrKAX/http://arkgis.org/DIQAB7
Why is this? The files are served with the default tornado.web.StaticFileHandler class, but this is not the behaviour that I expected! We have a need for speed!
What can I do to fix this?
EDIT:
I've now set up a nginx front-end — but I actually get the same increasing connect times in pingdom.com.  Am I reading the report wrong?  Is this due to something client-side?  Or is my nginx configured wrong?
Report with nginx front-end:

A: Use nginx.
File access in Python is blocking, so the Tornado IOLoop is going to be blocked while reading from disk.


text:
Q: upload and resize image with codeigniter Here is my code for upload and resize in codeigniter. Everything is ok with upload but resize keeps giving me errors:

Your server does not support GD function to process this image type.

function do_upload()
{
    $config['upload_path'] = './gallery/gallery_big/';
    $config['allowed_types'] = 'jpg|jpeg|png|gif';
    $config['max_size'] = '900000 * 50';
    $config['max_width']  = '21024 * 50';
    $config['max_height']  = '21068 * 50';
    $config['remove_spaces']= TRUE;
    $config['upload_url']=site_url()."gallery/gallery_big/";

    $this->load->library('upload', $config);
    $this->upload->initialize($config);
    $field_name ="upfiles";
    $upload_data = $this->upload->data();
    $file_name =   $upload_data['file_name'];

    if(!$this->upload->do_upload($field_name))
    {
        $error = $this->upload->display_errors();

        ?>
            <script type="text/javascript">
                alert("<?php echo $error; ?>");
            </script>
        <?php
    }
    else
    {
        $success ='File Successfully Uploaded !!';

        ?>
            <script type="text/javascript">
                alert("<?php echo $success; ?>");
            </script>
        <?php
    }

    $this->resize_img();
    //$this->resize_img1();
    //$this->resize_img2();
}

function resize_img()
{
    $config1['image_library'] = 'gd2';
    $config1['source_image']='./gallery/gallery_big/';
    $config1['maintain_ratio'] = TRUE;
    $config1['quality'] = 100;
    $config1['new_image']='./gallery/thumbnails/';
    $config1['width']= 100;
    $config1['height']= 100;

    $this->image_lib->initialize($config1);
    if(!$this->image_lib->resize())
    {
        $error = $this->image_lib->display_errors();

        ?>
            <script type="text/javascript">
                alert("<?php echo $error; ?>");
            </script>
        <?php
    }

    //$this->image_lib->clear();
}


text:
Q: Recyclerview lags when accessing position from its adapter I am looking to do one-time job which is obtaining the first three objects from my custom list in my adapter & do some logic with it, thus i am accessing position from OnBindViewHolder
But when i do access it and do my logic, it produces major lag into my recyclerview especially when am scrolling
if (position == 0) {
    holder.mGoldTrophy.setVisibility(View.VISIBLE);
} else if (position == 1) {
    holder.mSilverTrophy.setVisibility(View.VISIBLE);
} else if (position == 2) {
    holder.mBronzeTrophy.setVisibility(View.VISIBLE);
}

When i remove this code, it runs smoothly
Edit: I tried to remove position & setting visibility right away, it caused lag as well, so i thought it would be problem with my layout
 <FrameLayout
                android:layout_width="65dp"
                android:layout_height="65dp">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <de.hdodenhof.circleimageview.CircleImageView
                    xmlns:app="http://schemas.android.com/apk/res-auto"
                    android:id="@+id/ID_image_upload_photoOfTheUser"
                    android:layout_width="64dp"
                    android:layout_height="64dp"
                    android:src="@drawable/hey"
                    app:civ_border_width="2dp"
                    app:civ_border_color="#FF000000" />

                <!--It can be 30dp & 36dp-->

                <ImageView
                    android:id="@+id/ID_my_talent_golden_trophy"
                    android:visibility="gone"
                    android:src="@drawable/golden_trophy"
                    android:layout_width="40dp"
                    android:layout_height="48dp"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentBottom="true" />

                <ImageView
                    android:id="@+id/ID_my_talent_silver_trophy"
                    android:visibility="gone"
                    android:src="@drawable/silver_trophy"
                    android:layout_width="40dp"
                    android:layout_height="48dp"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentBottom="true" />

                <ImageView
                    android:id="@+id/ID_my_talent_bronze_trophy"
                    android:visibility="gone"
                    android:src="@drawable/bronze_trophy"
                    android:layout_width="40dp"
                    android:layout_height="48dp"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentBottom="true" />

            </RelativeLayout>
        </FrameLayout>

A: There was nothing wrong with the code, the problem was with the image, i used a very large image without resizing it, thus it showed much lag when i used it.
Solution would be changing the size of my drawable  into smaller sizes
I used Android Asset Studio to fix up this error, and it works fine with smooth motion, Thanks for your time.


text:
Q: how to make camel-example-cxf-proxy work in serviceMix 4.3.0 I downloaded camel 2.6.0 and used example camel-example-cxf-proxy (under example folder) to deploy into serviceMix.
what i would like to do is  packaging it to become a jar file and then goto serviceMix karaf console to install this jar.
(install -s wrap:file:/c:/...jar)

But this example doesn't work in serviceMix 4.3.0.
Do you know what thing i have to modify to make it work within serviceMix 4.3.0
Do i have to install any other bundle into serviceMix?

A: The first thing is that you should make sure your maven project builds a bundle. I recently did a tutorial that shows how to run camel routes in OSGi:
http://www.liquid-reality.de/display/liquid/2012/01/03/Karaf+Tutorial+Part+5+-+Running+Apache+Camel+integrations+in+OSGi
So basically you have to make sure that the camel features you need are installed. In your case this is probably camel-cxf and camel-http.
Then you need to change the pom to create a bundle. See the pom of the example:
https://github.com/cschneider/Karaf-Tutorial/blob/master/camel/jms2rest/pom.xml
You need to change the packaging to bundle and add the maven bundle plugin. For camel projects the default typically work very well.
Btw. you can also run camel on pure karaf when you follow the instructions in my tutorial. This has the advantage that you can almost always use the newest camel version while servicemix often comes with an older version.


text:
Q: Android call sync. function on each app start Good morning together,
I have an android app, which saves data into SQLite database.
The app gets this data of my MYSQL Database via http post.
I would like to realize, that on each app start (if the activity with the list view will appear) the http post function will be execute.
Where I have to put this code?
In my iOS app, I can put this into the AppDelegate.

A: Show a progress bar each time until response processed and ListView updated with that data.
You can do it in onCreate() method by calling a method for populating data.
Ofcourse do it in background thread. Use okHTTP library for this.

A: Create application class and register in manifiest file
Application.onCreate() call once when application start/restart but not call when activity restart
import android.app.Application;

    public class MyApplication extends Application {

        //it's call when application start ;
        @Override
        public void onCreate() {
            super.onCreate();
         // do your work here
        }

    }

AndroidManifiest.xml
 <application
        android:name="com.xyz.MyApplication"
.
.
.
   >

</application>

A: You need to make a Custom Application class to do that stuff. Because, when Activity is started and application is not loaded, then onCreate() methods will be called.
public class CustomApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        callHttpPost();
    }

    private void callHttpPost(){
         // Do Your Stuff
    }

}

Also set the application name in your manifest file .
<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:name=".CustomApplication"
        android:theme="@style/AppTheme">

       <!-- All your Activity goes here -->

</application>

A: There some third party libraries if your requirement very strict.
or else you have to extend Application to create your own Application class, and make calls  in below method in your application class
public void onCreate ()

Docs : Called when the application is starting, before any activity,
  service, or receiver objects (excluding content providers) have been
  created. Implementations should be as quick as possible (for example
  using lazy initialization of state) since the time spent in this
  function directly impacts the performance of starting the first
  activity, service, or receiver in a process. If you override this
  method, be sure to call super.onCreate().

A: You can do this in onCreate() .


text:
Q: Is there a minimum time between prompts for SKStoreReviewController.requestReview()? I understand that when we call SKStoreReviewController.requestReview(), Apple decides whether to show a review prompt based on a variety of factors. What I'm curious about is the minimum time between prompts for our app. According to Apple, there is some limit (emphasis mine):

If the user hasn't already given feedback and a request hasn't been
  made too recently, the system displays an in-app prompt that asks for
  a rating and an optional written review.

I understand that there are no guarantees about the behavior of this call beyond what's in its documentation, but I'm wondering what happens in practice.
I'm trying to figure out whether we need to implement our own logic to wait a reasonable amount of time before requesting the prompt again, or if Apple's definition of "recently" is good enough for this purpose.

A: The advice our team was given from Apple was to call requestReview after the user completes a "high value" task. For example, in our video app, we call it after the user has completed watching two videos. Doing this, the user is naturally likely to be more satisfied with the app, and more willing to rate it as they are not being interrupted in the middle of a task.
I would recommend putting more effort on identifying the best times to prompt for a review, and let Apple's code regulate the frequency of the prompts. The exact behavior is likely to be fine-tuned by Apple over time.

A: It's not documented and there is no (non-hacky) way to detect if the prompt was displayed, hence no way to collect data on this behaviour. Very frustrating!
Personally I throttle the frequency of calls to requestReview to ensure that they are sufficiently spaced out in time and that the first call won't happen before the user has had plenty of time to use the app.


text:
Q: Finding linear orders on a measure space whose initial segments have all possible measures Let $\mu$ be a non-atomic probability measure on some space $(X, \Sigma)$.
Is it always possible to find a linear order, $\leq$, on $X$ such that $\mu: \mathcal{A}\rightarrow [0,1]$ is surjective, where $\mathcal{A}=\{\{y : y\leq x\} : x\in X\}$? If so, is it possible to strengthen that to bijectivity?

A: Using the atomlessness of $\mu$, inductively construct a binary tree $\langle X_{\sigma} : \sigma \in 2^{< \omega}\rangle$ such that $X_{\phi} = X$ and for each $\sigma$, $X_{\sigma 0}, X_{\sigma 1}$ partition $X_{\sigma}$ into two sets of equal measure. For each $f \in 2^{\omega}$, let $X_f = \bigcap_n X_{f \upharpoonright n}$. Note that each $X_f$ is $\mu$-null. Let $<_f$ be an arbitrary linear order on $X_f$. For $x, y \in X$ defined $x< y$ iff either for some $f \in 2^{\omega}$, $x, y \in X_f$ and $x <_f y$ or for some $f \neq g \in 2^{\omega}$, $x \in X_f, y \in X_g$ and $f < g$ in lexicographic order. Now check.


text:
Q: How can i get specific user data from firestore in React? So the problem is, when i'm trying to get the details by using forEach function it gives me all the user's details which is available on the firestore..let me explain with code:
Here is my code for getting details in Profile Page :
import React from 'react';
import firebase from 'firebase';

const firestore = firebase.firestore();

class ProfilePage extends React.Component {
    state = {
        profiledata : null
    }

    componentDidMount(){
        firestore.collection('profiledata')
            // .doc("JgT2LyOB4jqhMv9YMgrh")
            .get()

             .then((snapshot) => {
                const profiledata  = []
                snapshot.forEach(function(doc){
                    const data = doc.data();
                    profiledata.push(data);
                }
                )
                this.setState({profiledata :  profiledata})
                })
                }

            render(){
        return(

User

                {
                    this.state.profiledata &&
                        this.state.profiledata.map( profiledata => {
                            return(

                                        First Name : {String(profiledata.firstname)}
                                        Last Name : {String(profiledata.lastname)}
                                        Company Name : {String(profiledata.companyname)}

                            )
                        })
                }

        )
    }export default ProfilePage;

A: As mentioned by Frank in the comments you are querying the entire collection profileData without a referencing a specific document or filtering it, so the expect result is to get all users, which is exactly what you are getting.
In order to get a specific document, as you can see in this documentation you have to reference a documentId in your call with .doc(), like you apparently were doing in the commented out part of your, so if you do this:
firestore.collection('profiledata')
         .doc("JgT2LyOB4jqhMv9YMgrh")
         .get()

You should get the user with id JgT2LyOB4jqhMv9YMgrh, if it exists.


text:
Q: Pycharm ненормально распечатывает код Печатает растягивая текст кода и смещая его вправо, правая часть кода обрезается (хотя строки не длинные), поля справа игнорируются и текст кода почти до самого края страницы. Менял настройки в "Print" Pycharm, делал отступ меньше - не помогло. Сам принтер печатает нормально, в настройках указано печать с полями.

A: Попробуй ctrl+alt+L (reformat code), это должно сработать, если код больше длинны а4. В ином случае просто скопируй код в office word и распечатай оттуда.


text:
Q: When debugging my code a variable doesn't appear its value correctly in debug window I have a strange problem When debugging my code (just one line of code) a variable doesn't appear its value correctly in the debug window.
Note that that problem just occurs in a specific project but the other projects don't occur.
#include <iostream>
#include <string>

using namespace std;

int main() {
    wstring u16 = L"Hello 日本語 سلام Ä भारतीय עברית ไทย";
    return 0;
}

The following are two screenshots of two different projects:

I am using "MS VS2019".
There are no problems in the IDE but that problem happened suddenly and I don't know what caused it.
Is there any solution?


text:
Q: Kestrel using Microsoft.AspNetCore.Authentication.Negotiate with multiple users The Microsoft.AspNetCore.Authentication.Negotiate documentation says the following here about how to configure Kestrel to use Windows Authentication:

The Microsoft.AspNetCore.Authentication.Negotiate component performs
  User Mode authentication. Service Principal Names (SPNs) must be added
  to the user account running the service, not the machine account.
  Execute setspn -S HTTP/myservername.mydomain.com myuser in an
  administrative command shell.

which works fine. But it does not explain what to do if there are multiple applications that run under different users. If I try to execute setspn -S HTTP/myservername.mydomain.com myuser; setspn -S HTTP/myservername.mydomain.com myuser2 I get the error Duplicate SPN found, aborting operation!.
I tried to use the port when registering the SPN (setspn -S HTTP/myservername.mydomain.com:5000 myuser) but that registration seems to be ignored.
Is it not possible to run two asp.net core applications with windows authentication on the same server under different users or do I have to register this differently?

A: The service principal name must be unique within Active Directory and can only be associated to a single service account.
SPNs are determined based on the hostname they're connecting to, so
https://foo.bar.com is equivalent to https://foo.bar.com:8234/baz
And for completeness if foo.bar.com is a CNAME record, the browser will actually use the canonical A record (e.g. foo.bar.com => srv1-ny-web.corp.bar.net will use the latter when searching for an SPN).
You have two options: run on separate (sub-)domains or use the same account for both. Using the same account for both is identical to using the machine account. For further similarity use a gMSA account so you don't have to manage the password.


text:
Q: How to filter record keys based on their values? I have this record:
interface TheRecord extends TheRecordType {
  a: { typeA: 'string' },
  b: { typeB: 123 },
  c: { typeA: 'string' },
}

type TheRecordType = Record<string, TypeA | TypeB>

type TypeA = { typeA: string }
type TypeB = { typeB: number }

I want my function to accept only keys who's values are of typeA
doStuff('b'); //this should fail

function doStuff(arg: keyof FilteredForTypeA): void {
  ...
}

Here's how I try to filter them out
type FilteredForTypeA = { [k in keyof TheRecord]: TheRecord[k] extends TypeA ? TheRecord[k] : never }

A: There's a few things going on here so I'll make an answer since it's not a direct duplicate of the relevant existing questions I found.
When your type has an index signature it's hard to extract just the "known" literal keys of the object if they are subtypes of the index signature.  That is, keyof {[k: string]: any, foo: any} is just string, and "foo" is completely subsumed in that.  You can use a conditional type trick to extract just the known literal keys, as shown in this related question:
type KnownKeys<T> = Extract<{
    [K in keyof T]: string extends K ? never : number extends K ? never : K
} extends { [_ in keyof T]: infer U } ? U : never, keyof T>;

On the other hand, you want only the keys whose values have a property matching a particular type.  That is doable with a mapped-conditional-lookup, as shown in this related question:
type KeysMatching<T, V> = { [K in keyof T]: T[K] extends V ? K : never }[keyof T];

Put those together and you get:
type KnownKeysMatching<T, V> = KeysMatching<Pick<T, KnownKeys<T>>, V>

And you can verify that it works as I think you intend:
function doStuff(arg: KnownKeysMatching<TheRecord, TypeA>): void {
}

doStuff('a'); // okay
doStuff('b'); // error!
doStuff('c'); // okay
doStuff('d'); // error!

Note how arg cannot be 'b', as desired, but it also cannot be 'd' or any other "unknown" string, even though TheRecord has a string index signature.  If you need some other behavior for 'd', that could be done, but it seems outside the scope of the question.
Hope that helps; good luck!
Link to code

A: Using a slightly modified version of KnownKeys to exclude keys whose values also extend never, you end up with this
interface TheRecord extends TheRecordType {
  a: { typeA: 'string' },
  b: { typeB: 123 },
  c: { typeA: 'string' },
}

type TheRecordType = Record<string, TypeA | TypeB>
type KnownKeys<T> = {
  [K in keyof T]: string extends K ? never : number extends K ? never : T[K] extends never ? never : K
} extends { [_ in keyof T]: infer U } ? U : never;

type TypeA = { typeA: string }
type TypeB = { typeB: number }

function doStuff(arg: KnownKeys<FilteredForTypeA>): void {

}

type FilteredForTypeA = { [k in keyof TheRecord]: TheRecord[k] extends TypeA ? TheRecord[k] : never }

doStuff('b'); // error!


text:
Q: Show that partial derivatives of a function are not continuous Define $f:\mathbb{R}^2 \rightarrow \mathbb{R}$ by
$$
f(x,y)=
\begin{cases}
 \frac{xy}{x^2+y^2} &\text{if}\, (x,y)\neq(0,0)\\
      0 &\text{if}\, (x,y)=(0,0)
\end{cases}
$$
I have found that for $(x,y)\neq(0,0)$
$$\frac{\partial f}{\partial x}=\frac{y(y^2-x^2)}{(x^2+y^2)^2}$$
and
$$\frac{\partial f}{\partial y}=\frac{x(x^2-y^2)}{(x^2+y^2)^2}$$
I don't know how to show that these are not continuous functions.
I know there exists similar questions, but there is no duplicate of this question since I am asking about the continuity of the partial derivatives not of $f(x,y)$

A: By direct calculation, you'll get $f_x(0, 0) = 0$ and $f_y(0, 0) = 0$. So you can check whether $\lim_{(x, y)\to(0, 0)}f_x(x, y) = 0$ or not, and the same for $f_y$. Can you find suitable path s.t $f_x$ does not converge to $0$?


text:
Q: Parameter tuning using GridSearchCV I am using pipeline in Gridsearch cv object to tune parameters.My code is as follows
X_train = df_train.drop("SalePrice", axis=1)
Y_train = df_train["SalePrice"]
X_test  = df_test.drop("Id", axis=1).copy()
from sklearn.linear_model import LinearRegression
lr = LinearRegression()
from sklearn.preprocessing import MinMaxScaler
from sklearn.grid_search import GridSearchCV
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline
scaler = MinMaxScaler()
param_grid={'features__pca__n_components':[1, 2, 3,5,10],}
pipeline = Pipeline(steps=[('scaler', scaler),('algorithm',lr)])
gs = GridSearchCV(pipeline, param_grid, scoring='f1')
gs.fit(X_train, Y_train)
print "Best estimator",gs.best_estimator_
clf = gs.best_estimator_
# fit the optimal model
clf.fit(X_train, Y_train)
# predict based on the optimal model
pred = clf.predict(X_test)
acc_log = round(clf.score(X_train, Y_train) * 100, 2)
acc_log

I am getting this error where X_train and Y_train parameters are numpy arrays.
ValueError                                Traceback (most recent call last)
<ipython-input-681-9e3b37600170> in <module>()
      7 pipeline = Pipeline(steps=[('scaler', scaler),('algorithm',lr)])
      8 gs = GridSearchCV(pipeline, param_grid, scoring='f1')
----> 9 gs.fit(X_train, Y_train)
     10 print "Best estimator",gs.best_estimator_
     11 clf = gs.best_estimator_

ValueError: Invalid parameter features for estimator Pipeline(steps=[('scaler', MinMaxScaler(copy=True, feature_range=(0, 1))), ('algorithm', LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False))]). Check the list of available parameters with `estimator.get_params().keys()`.

How should I configure parameters?
Kindly help me solve this.Thanks