text:
Q: How to calculate the determinant and how to prove Cayley-Hamilton's rate? I'm trying to understand this pre-exam questions, but doesn't go well. Having the exam tomorrow. Can someone help me to understand what and how should I do here?

*

*With help of $M=\begin{pmatrix} 3 & 2 \\ 1 & 4 \end{pmatrix}$ and $I=\begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}$ calculate the determinant of $\bigl(M-\lambda I \bigr)$

*With help of $M=\begin{pmatrix} m_{11} & m_{12} \\ m_{21} & m_{22} \end{pmatrix}$ and $I=\begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}$ calculate the determinant of $\bigl(M-\lambda I \bigr)$

*Prove Cayley-Hamilton's rate for arbitrary 2 × 2 matrices: $M=\begin{pmatrix} m_{11} & m_{12} \\ m_{21} & m_{22} \end{pmatrix}$ by direct calculation.

A: For $M=\begin{pmatrix} m_{11} & m_{12} \\ m_{21} & m_{22} \end{pmatrix}$ we have
$\det(M- \lambda I)=\lambda^2-(m_{11}+m_{22}) \lambda -m_{12}m_{21}$.
You have to show that
$$M^2-(m_{11}+m_{22})M -m_{12}m_{21}I=0.$$


text:
Q: php displays 'Empty' even when all fields are actually not In this form I created, it checks if the fields are set and are empty. I made a class with two methods, areSet() as isset(), and areEmpty() as empty(). In the areEmpty() method, it is supposed to display "Empty" if all the fields are empty, but even when all the fields are filled up, it still displays "Empty". Is it because of the implode() function that I used? I need someone's help to point out the wrong with my code.
HTML
<form action="validate.php" method="post">
    <input type="text" name="firstname" placeholder="First Name" autocomplete="off">

    <input type="text" name="lastname" placeholder="Last Name" autocomplete="off">

    <input type="text" name="email" placeholder="Email" autocomplete="off">

    <input type="text" name="username" placeholder="Username" autocomplete="off">

    <input type="password" name="password" placeholder="Password" autocomplete="off">

    <input type="password" name="passwordAgain" placeholder="Confirm password" autocomplete="off">

    <input type="submit" value="Submit">
</form>

validate.php
<?php

require 'include/class.php';

if(Input::areSet('firstname','lastname','email','username','password','passwordAgain')) {
    if(Input::areEmpty('firstname','lastname','email','username','password','passwordAgain')) {
        echo 'Empty';
    } else {
        echo 'Not empty';
    }
}

class.php
<?php

class Input {
    // isset()
    public static function areSet(...$fields) {
        $setFieldsArray = [];

        foreach($fields as $field) {
            $setFieldsArray[] = $_POST[$field];
        }

        return isset($setFieldsArray);
    }

    // empty()
    public static function areEmpty(...$fields) {
        $emptyFieldsArray = [];

        foreach($fields as $field) {
            $emptyFieldsArray[] = empty($_POST[$field]);
        }

        return implode(' || ', $emptyFieldsArray);
    }
}

A: I have no idea what you're doing there by setting an array and then returning an imploded array; but just loop through the $fields, check if the associated $_POST variable is empty and return true if so and at the end false if none are empty:
public static function areEmpty(...$fields) {

    foreach($fields as $field) {
        if(empty($_POST[$field])) {
            return true; // something was empty
        }
    }
    return false; // none were empty
}

You'll have issues with areSet() as well, because you loop $fields and set an array element of $setFieldsArray and then return if it is empty, which it will never be empty because you create array elements in it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: FEM: Getting Resulting Electric Force on each body from electric field Based on this excellent answer FEM: Electric Field between two arbitrary defined shapes I can compute the electric field ef between two conducting objects.

$$ F = qE$$
Now, I tried to compute the total resultant electric force on each object (acting at it´s geometric center), by simply integrating the electric field around the boundary of the object :
So according to the Mathematica Documentation, the correct way to specify a domain, is for example:
NIntegrate[1, {x, y, z} \[Element]

ImplicitRegion[x^2 + y^2 == 1 [And] z == 0, {x, y, z}]]
Since
Region`RegionProperty[RegionBoundary[object1], {x, y},
         "FastDescription"][[1]][[2]]

gives me the implicit region of the contour of object1, I can find the force as follows:
NIntegrate[
 Evaluate[ef], {x, y} \[Element]
  ImplicitRegion[
   Region`RegionProperty[RegionBoundary[object1], {x, y},
      "FastDescription"][[1]][[2]], {x, y}]]

Here is the full code to compute the electric field:
Needs["NDSolve`FEM`"];
(*Define Boundaries*)
air = Rectangle[{-5, -5}, {5, 5}];
object1 = Rectangle[{-2.5, 2.5}, {2.5, 2}];
object2 = Rectangle[{-2.5, -2.5}, {2.5, -2}];
reg12 = RegionUnion[object1, object2];
reg = RegionDifference[air, reg12]

mesh = ToElementMesh[reg, MaxCellMeasure -> 0.1];
mesh["Wireframe"]

eq = Laplacian[u[x, y], {x, y}]; V1 = 1; V2 = -2;
bc = {DirichletCondition[u[x, y] == V1,
    Region`RegionProperty[RegionBoundary[object1], {x, y},
       "FastDescription"][[1]][[2]]],
   DirichletCondition[u[x, y] == V2,
    Region`RegionProperty[RegionBoundary[object2], {x, y},
       "FastDescription"][[1]][[2]]]};
U = NDSolveValue[{eq == 0, bc}, u, {x, y} \[Element] mesh];

ef = -Grad[U[x, y], {x, y}];

force1 = NIntegrate[
   Evaluate[ef], {x, y} \[Element]
    ImplicitRegion[
     Region`RegionProperty[RegionBoundary[object1], {x, y},
        "FastDescription"][[1]][[2]], {x, y}]];

centroid1 = RegionCentroid[object1];

StreamDensityPlot[Evaluate[ef], {x, y} \[Element] reg,
 ColorFunction -> "Rainbow", PlotLegends -> Automatic,
 FrameLabel -> {x, y}, StreamStyle -> LightGray, VectorPoints -> Fine,
  PlotRange -> Automatic,
 Epilog -> {{Arrow[{centroid1, centroid1 + force1}],
    Text["Force", centroid1 + force1/2, Background -> LightRed]}}]

I get:

My question is: Is this approach correct ? And if not: How would you do it ?

A: Electrostatic force acting on a conductor in electric field is given by $\vec {F}=\int{\frac {E^2}{8\pi}\vec {n}dS}$. In this case we have a plate with normal vector $\vec {n}=(0,\pm 1)$ for upper and lower surfaces respectively. To calculate electric field we take air more wide and compute sufficient mesh:
 Needs["NDSolve`FEM`"];
(*Define Boundaries*)
air = Rectangle[{-10, -10}, {10, 10}];
object1 = Rectangle[{-2.5, 2.}, {2.5, 2.5}];
object2 = Rectangle[{-2.5, -2.5}, {2.5, -2}];
reg12 = RegionUnion[object1, object2];
reg = RegionDifference[air, reg12];

mesh = ToElementMesh[reg,
  MeshRefinementFunction ->
   Function[{vertices, area},
    area > 0.003 (0.1 + 10 Norm[Mean[vertices]])]]
mesh["Wireframe"]
eq = Laplacian[u[x, y], {x, y}]; V1 = 1; V2 = -2;
bc = {DirichletCondition[u[x, y] == V1,
    Region`RegionProperty[RegionBoundary[object1], {x, y},
       "FastDescription"][[1]][[2]]],
   DirichletCondition[u[x, y] == V2,
    Region`RegionProperty[RegionBoundary[object2], {x, y},
       "FastDescription"][[1]][[2]]]};
U = NDSolveValue[{eq == 0, bc}, u, {x, y} \[Element] mesh];

ef = -Grad[U[x, y], {x, y}];

force1 = -NIntegrate[Evaluate[ef.ef] /. y -> 2, {x, -2.5, 2.5}];
force1 = force1 +
  NIntegrate[Evaluate[ef.ef] /. y -> 2.5, {x, -2.5, 2.5}];force=force1/(8 Pi);
centroid1 = RegionCentroid[object1];

StreamDensityPlot[Evaluate[ef], {x, y} \[Element] reg,
 ColorFunction -> "Rainbow", PlotLegends -> Automatic,
 FrameLabel -> {x, y}, StreamStyle -> LightGray, VectorPoints -> Fine,
  PlotRange -> Automatic,
 Epilog -> {{Arrow[{centroid1, centroid1 + {0, force1}}],
    Text["Force", centroid1 + {0, force1/2},
     Background -> LightRed]}}]


text:
Q: Moving navigator in Highcharts I would like to fetch data for example from this website: https://www.highcharts.com/stock/demo/lazy-loading
To get the data with high resolution, I have to set the min max to small value and then I have to go over the complete diagram.
It is possible to get data from the website with "Highcharts.charts[0].series[0]"
But I didn't find a possibility to programable changing the navigators, to get other data ranges.
Is it possible to move the navigator to a specific position?

A: You can use Axis.setExtremes function for this.
Live demo: http://jsfiddle.net/kkulig/am3cgo5w/
API reference: https://api.highcharts.com/class-reference/Highcharts.Axis#setExtremes

A: Thank you for your answear. Here is my code if somebody needs:
I saw, that the redraw event will be called 5 times till the diagram is finishd redrawn
counter = 1
// Get chart
chart = $('#highcharts-graph').highcharts()
// add event
Highcharts.addEvent(chart, 'redraw', function (e) {
console.log(counter);
counter = counter+1;
if(counter>5){
    console.log('finish loaded')
    function2()
}
})
var newSelectedMin = 0
var newSelectedMax = 10
chart.xAxis[0].setExtremes(newSelectedMin, newSelectedMax);


text:
Q: Is there any React JS library to display the sytem language from React JS For example let us consider that user current language is english then while i display system language from React JS it should output 'en'.
I tried with os-locale,os,i18n and many more libraries but i didnt get any method related to system locale.

A: If you want to get user's OS language you can try to get it from environment:
const env = process.env,
language = env.LANG || env.LANGUAGE || env.LC_ALL || env.LC_MESSAGES;

A: os-locale might be what you're looking for.
But remember, this is for system locale. Of the server you're running your Node API on.
If you want user's language, you have to ask them. Which means in your app or website, you get the user's locale and then pass it to your Node API.

A: if you want user's language you can either use Accept-Language header in request (viable only if you're using server-side rendering in your app, i guess) or get it from browser and send it to your backend


text:
Q: Declaring constructors as private shows errors. Is at least one public constructor mandatory? I am a learner of C++. I have compiled the below program. I am working on constructors and destructors concept. I have this code here below where I declare a private destructor and access the private members using member function of the class from main(). I know that a private constructor can be declared but is a public constructor also mandatory? here is my code below:
class Book
{
private:
    int *pages;
    int *price;

    Book()        //default constructor
    {
        pages = new int;
        price = new int;
        *pages = 300;
        *price = 8;
    }

public:
    void pre_destructor()
    {
        std::cout << "The pages:" << *pages << "\n";
        std::cout << "The price:" << *price << "\n";
    }

~Book() //destructor
    {
        std::cout << "The pages:" << *pages << "\n";
        std::cout << "The price:" << *price << "\n";
        delete pages;
        delete price;
    }

};

int main()
{
    using namespace std;
    Book book1;

    cout << "Before using destructors" << endl;
    cout << "---------------------------------"<< endl;

    book1.pre_destructor();

    cout << "After using destructors" << endl;
    cout << "---------------------------------";

    return 1;

}

For the above program, two errors are shown. One is in the main function where an object is declared; Error: error within content. And the second one is in the line where the constructor is called; Error:Book::Book() is private.
The main is not directly accessing the constructor in the code. Then why does it shows the access error?

A: No, a public constructor is not mandatory. There are use cases for private constructors.

*

*A class with only static methods might have private (or deleted) constructors to prevent instances being created.

*A singleton class (where only one instance of the class exists) might enforce its singleton status by having a private constructor. That instance can be accessed through a static getter.

*You might want to follow a builder or factory pattern, where you force your users to construct instances using a process beside calling the constructor. That builder or factory would be either a member of the class or a friend, so able to call a private constructor. This scheme is much more common in Java than C++, but C++ allows it as well.

That said, you're looking to simply construct an instance of a class:
Book book1;

This use definitely requires a public default constructor.

A: When you make a constructor private, you need to expose a method so that external classes/methods can create object of this class. You'd do so by creating a static method, which in turn creates the object.
following code demonstrates:
#include <iostream>
class Book
{
private:
    int *pages;
    int *price;

    Book()        //default constructor
    {
        pages = new int();
        price = new int();
        *pages = 300;
        *price = 8;
    }

public:
    static Book* constructBook()
    {
        return new Book();
    }

    void pre_destructor()
    {
        std::cout << "The pages:" << *pages << "\n";
        std::cout << "The price:" << *price << "\n";
    }

    ~Book() //destructor
    {
        delete pages;
        delete price;
    }

};

int main()
{
    Book* book1 = Book::constructBook();

    std::cout << "Before using destructors" << endl;
    std::cout << "---------------------------------"<< endl;

    book1->pre_destructor();

    cout << "After using destructors" << endl;
    cout << "---------------------------------";
    delete book1;
    return 0;

}

A: Not at all ! You don't need a public constructor but you need a factory fuction to create an instance of that class & in that case you need to qualify that function with the keyword static. See below :-
#include <iostream>
using namespace std;
class X
{
    int x;
    X(int x)
    {
        cout<<"creation\n";
        this->x = x;
    }
    public:
    static X make_X (int x) // without static error message will be : error: cannot call member function 'X X::make_X(int)' without object
    {
        return X(x);
    }
    int& getx()
    {
        return x;
    }
    ~X()
    {
        cout<<"destruction\n";
    }
};
int main()
{
    auto obj = X::make_X(5);
    auto ano = X::make_X(7);
    cout << obj.getx() << '\t' << ano.getx() << '\n';
    return 0;
}

Output is :-
creation
creation
5   7
destruction
destruction

There is no need of a public contrcutor here. But you needed make_X to create an instance of the class.
You can also use friend instead of static. In that case the code will be :-
friend X make_X (int x);  // declare a prototype in the class

Then define outside the class definition :-
X make_X (int x)
{
    return X(x);
}

That's how it works ! Cheers!!


text:
Q: Flexbox space-around except at left and right border I have the following scenario:

.flex-container {
  padding: 0;
  margin: 0;
  list-style: none;
  display: flex;
  flex-wrap:wrap;
  justify-content: space-around;
}

.flex-item {
  background: tomato;
  padding: 5px;
  width: 150px;
  height: 75px;
  margin-top: 10px;

  line-height: 75px;
  color: white;
  font-weight: bold;
  font-size: 3em;
  text-align: center;
}

1

2

3

4

5

http://codepen.io/HugoGiraudel/pen/LklCv
I want one thing changed:
The left and right divs should not have a space between the parent div and itself.
When I do justify-content: space-between, that problem is solved but then the divs are no longer centered.


text:
Q: Generate **bare** CREATE TABLE and CREATE PROC statemnts in SQL Server The deployment procedures in my company require that SQL scripts for creation of procedures and tables, etc. be bare.
Generating create scripts in SQL Server Management Studio gives you significantly more than a bare script, which is unfortunate in this case.  For example, for a test table this is what SSMS generated for me:
USE [DemoDB]
GO

/****** Object:  Table [dbo].[example]    Script Date: 08/07/2012 15:46:32 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[example](
    [fake_row] [int] NULL
) ON [PRIMARY]

GO

So, what I'd like to know is:
Can I somehow run a query on SQL Server in SSMS that would give me a script that was literally just the following?
create table example (
    fake_row int
)

A: You can create your own "create table" statements, using information_schema (Aaron . . . I know, INFORMATION_SCHEMA ;).
I have written some code for this purpose, but it doesn't use INFORMATION_SCHEMA.  I know, if uses older system tables that are probably scheduled to be removed.  It also adds in some additional information (which you can remove, since you don't need it).  Just put the list of tables in the @INCLUSIONLIST and run this in the database where the tables reside.
SET @INCLUSIONLIST = '|table1|table2|';

SELECT (CASE WHEN rownum = 1 THEN 'CREATE TABLE ['+a.t_name+'] ('
             WHEN c.column_id IS NOT NULL
             THEN '    ['+c.c_name+'] ' +
                  (CASE WHEN CHARINDEX('CHAR', datatype) > 0 THEN datatype+'('+(case when length < 0 then 'max' else cast(length as varchar) end)+')'
                        WHEN CHARINDEX('BINARY', datatype) > 0 THEN datatype+'('+cast(length as varchar)+')'
                        WHEN datatype = 'float' AND precision <> 24 THEN datatype+'('+cast(precision as varchar)+')'
                        WHEN datatype IN ('numeric', 'decimal') AND scale = 0 THEN datatype+'('+cast(precision as varchar)+')'
                        WHEN datatype IN ('numeric', 'decimal') AND scale > 0 THEN datatype+'('+cast(precision as varchar)+','+cast(scale as varchar)+')'
                        ELSE datatype END)+' '+
                  (CASE WHEN c.identity_seed IS NOT NULL
                        THEN 'IDENTITY(' + CAST(identity_seed AS VARCHAR) + ',' + CAST(identity_increment AS VARCHAR) + ') '
                        ELSE '' END) +
                  (CASE WHEN c.is_nullable = 0 THEN 'NOT NULL ' ELSE '' END) +
                  (CASE WHEN c.default_definition IS NOT NULL
                        THEN 'DEFAULT '+default_definition ELSE '' END) +
                  (CASE WHEN max_column_id = column_id AND pk.pk_name IS NULL THEN '' ELSE ',' END)
            WHEN rownum = max_column_id + 2 and pk.pk_name IS NOT NULL
            THEN '    PRIMARY KEY ('+pk.pk_columns+')'
            WHEN rownum = max_column_id + 3 THEN ')  /* CREATE TABLE '+a.t_name+' */'
            WHEN rownum = max_column_id + 4 THEN 'GO'
            WHEN rownum = max_column_id + 5 THEN ''
        END)
 FROM (SELECT t.t_name, rownum, max_column_id
       FROM (SELECT t.name as t_name, MAX(c.column_id) as max_column_id
             FROM sys.columns c join
                  (SELECT * FROM sys.tables WHERE CHARINDEX('|'+name+'|', @INCLUSIONLIST) > 0 ) t
                  ON c.object_id = t.object_id
             GROUP BY t.name) t join
            (SELECT ROW_NUMBER() OVER (ORDER BY object_id) as rownum FROM sys.columns c) ctr
            ON ctr.rownum <= t.max_column_id + 5
      ) a LEFT OUTER JOIN
      (SELECT t.name as t_name, c.column_id, c.name AS c_name, u.name as datatype,
              ISNULL(baset.name, N'') AS systemtype,
              CAST(CASE WHEN baset.name IN (N'nchar', N'nvarchar') AND c.max_length <> -1
                        THEN c.max_length/2 ELSE c.max_length END AS INT) AS length,
              c.precision AS precision,
              c.scale as scale,
              c.is_nullable,
              dc.definition as default_definition,
              idc.seed_value as identity_seed, idc.increment_value as identity_increment
       FROM sys.tables t JOIN
            sys.all_columns AS c
            ON c.object_id = t.object_id LEFT OUTER JOIN
            sys.types u
            ON u.user_type_id = c.user_type_id LEFT OUTER JOIN
            sys.types baset
            ON baset.user_type_id = c.system_type_id AND
               baset.user_type_id = baset.system_type_id LEFT OUTER JOIN
            sys.default_constraints dc
            ON c.object_id = dc.parent_object_id AND
               c.column_id = dc.parent_column_id LEFT OUTER JOIN
            sys.identity_columns idc
            ON c.object_id = idc.object_id AND
               c.column_id = idc.column_id
      ) c
      ON a.t_name = c.t_name AND
         c.column_id + 1 = a.rownum LEFT OUTER JOIN
      (SELECT t.name as t_name, kc.name as pk_name,
              (MAX(CASE WHEN index_column_id = 1 THEN '['+c.name+']' ELSE '' END) +
               MAX(CASE WHEN index_column_id = 2 THEN ','+'['+c.name+']' ELSE '' END) +
               MAX(CASE WHEN index_column_id = 3 THEN ','+'['+c.name+']' ELSE '' END) +
               MAX(CASE WHEN index_column_id = 4 THEN ','+'['+c.name+']' ELSE '' END) +
               MAX(CASE WHEN index_column_id = 5 THEN ','+'['+c.name+']' ELSE '' END) +
               MAX(CASE WHEN index_column_id = 6 THEN ','+'['+c.name+']' ELSE '' END) +
               MAX(CASE WHEN index_column_id = 7 THEN ','+'['+c.name+']' ELSE '' END) +
               MAX(CASE WHEN index_column_id = 8 THEN ','+'['+c.name+']' ELSE '' END) +
               MAX(CASE WHEN index_column_id = 9 THEN ','+'['+c.name+']' ELSE '' END) +
               MAX(CASE WHEN index_column_id = 10 THEN ','+'['+c.name+']' ELSE '' END)
              ) as pk_columns
       FROM sys.indexes i JOIN
            sys.key_constraints kc
            ON i.name = kc.name AND
               kc.type = 'PK' JOIN
            sys.tables t
            ON i.object_id = t.object_id JOIN
            sys.index_columns ic
            ON i.object_id = ic.object_id AND
           i.index_id = ic.index_id JOIN
            sys.columns c
            ON ic.index_column_id = c.column_id AND
               ic.object_id = c.object_id
       GROUP BY t.name, kc.name
      ) pk
      ON pk.t_name = a.t_name
ORDER BY a.t_name, rownum

A: Apologies for the self-answer, marking other good answers +1.
It turns out you can get pretty much all of the way there with  utility in SSMS.

*

*Right click on the database in the object explorer

*Click "Tasks"

*Click "Generate Scripts"

*Select "Script Specific Objects" and choose tables, or whatever else

*Select "Save To File" & "Single File Per Object" (or just spool to query window)

*Click "Advanced" and you can enable/disable the generation of virtually every part of the statements you're generating including constraints, use statements, etc.

*If further removal is required (e.g. removing GO), it's minimal

A: Optionally, you can control the general scripting behavior of SSMS like so: Options for scripting SQL Server database objects.

A: I would create stored procs that read from the INFORMATION_SCHEMA views.
Getting the stored proc text is just:
    DECLARE @SQL VARCHAR(8000)
    SET @SQL=' '

    select  @SQL = @SQL + ROUTINE_DEFINITION
    from INFORMATION_SCHEMA.ROUTINES
    where ROUTINE_TYPE='PROCEDURE'
    AND SPECIFIC_NAME = 'updateComments'

    PRINT @SQL

The one to script the table would looks something like:
DECLARE @tableName VARCHAR(50)
SET @tableName = 'Location'

-- Need to know how many columns
DECLARE @NumColumns int
SELECT @NumColumns = MAX(ORDINAL_POSITION)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @tableName

DECLARE @SQL VARCHAR(8000)
SET @SQL=' '

DECLARE @Results TABLE
(LineNumber int,
Line VARCHAR(1000))

INSERT INTO @Results
    SELECT 0 AS ORDINAL_POSITION,
    'CREATE TABLE '+TABLE_SCHEMA+'.'+@tableName+' (' AS Line
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_NAME = @tableName

    UNION ALL

    SELECT ORDINAL_POSITION,
    '['+COLUMN_NAME+'] '+ DATA_TYPE +
    CASE WHEN DATA_TYPE = 'varchar' OR DATA_TYPE = 'char'
    THEN '('+ CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR) +')'
    ELSE '' END +
    CASE WHEN IS_NULLABLE = 'NO'
    THEN ' NULL '
    ELSE ' NOT NULL' END +
    CASE WHEN ORDINAL_POSITION < @NumColumns
    THEN ', '
    ELSE ' ' END
    AS LINE
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = @tableName

    UNION ALL

    SELECT 999, ' )'

SELECT Line
FROM @Results
ORDER BY LineNumber

SELECT @SQL = @SQL + Line
FROM @Results
ORDER BY LineNumber

SELECT @SQL
PRINT @SQL

This creates the simple table script that you want, but it is not complete - doesn't do numeric precision, primary key, etc.  But this is enough to get you started.
I would just make each one of these into a stored proc that takes the object name as a parameter.


text:
Q: How do i debug Java native calls in Eclipse? Is there a way to debug a native call (f.e. OpenCV calls) from java in eclipse? If so, what can i do?
I know that it is possible inside a Maven-Project, but i don't want to have one.


text:
Q: @ instagram api : Getting the results based on complex boolean expression @ instagram api : As we can write description of a photo (160 characters ) in Instagaram. I want to utilize this information.
Q: Can I create a complex search expression like FIFAorFOOTBALLandFRANCEnotSPAIN which gives me the images having fifa, football and france in description field but not the spain.

A: The Instagram API only supports searching a single tag at a time.


text:
Q: Linked Sales Navigator Login issue in salesforce I did the configuration for linkedIn Sales Navigator and Salesforce. I am able to see Member and Company Information in LinkedIn widget embedded in Contact Layout too while I am logged in using LinkedIn Credentials on my system. The problem arises when I logged out of LinkedIn on my PC and check LinkedIn widget in salesforce. It's again asking for login as in attached Image.

A: If anyone else is facing same issue, Just want to add that I contacted LinkedIn support and confirmed that it is expected behaviour. Cheers!


text:
Q: summing a range of columns in data frame I am having trouble summing select columns within a data frame, a basic problem that I've seen numerous similar, but not identical questions/answers for on StackOverflow.
With this perhaps overly complex data frame:
site<-c(223,257,223,223,257,298,223,298,298,211)
moisture<-c(7,7,7,7,7,8,7,8,8,5)
shade<-c(83,18,83,83,18,76,83,76,76,51)
sampleID<-c(158,163,222,107,106,166,188,186,262,114)
bluestm<-c(3,4,6,3,0,0,1,1,1,0)
foxtail<-c(0,2,0,4,0,1,1,0,3,0)
crabgr<-c(0,0,2,0,33,0,2,1,2,0)
johnson<-c(0,0,0,7,0,8,1,0,1,0)
sedge1<-c(2,0,3,0,0,9,1,0,4,0)
sedge2<-c(0,0,1,0,1,0,0,1,1,1)
redoak<-c(9,1,0,5,0,4,0,0,5,0)
blkoak<-c(0,22,0,23,0,23,22,17,0,0)

my.data<-data.frame(site,moisture,shade,sampleID,bluestm,foxtail,crabgr,johnson,sedge1,sedge2,redoak,blkoak)

I want to sum the counts of each plant species (bluestem, foxtail, etc. - columns 4-12 in this example) within each site, by summing rows that have the same site number.  I also want to keep information about moisture and shade (these are consistant withing site, but may also be the same between sites), and want a new column that is the count of number of rows summed.
the result would look like this
site,moisture,shade,NumSamples,bluestm,foxtail,crabgr,johnson,sedge1,sedge2,redoak,blkoak
211,5,51,1,0,0,0,0,0,1,0,0
223,7,83,4,13,5,4,8,6,1,14,45
257,7,18,2,4,2,33,0,0,1,1,22
298,8,76,3,2,4,3,9,13,2,9,40
The problem I am having is that, my real data sets (and I have several of them) have from 50 to 300 plant species, and I want refer a range of columns (in this case, [5:12] ) instead of my.data$foxtail, my.data$sedge1, etc., which is going to be very difficult with 300 species.
I know I can start off by deleting the column I don't need (SampleID)
my.data$SampleID <- NULL

but then how do I get the sums?  I've messed with the aggregate command and with ddply, and have seen lots of examples which call particular column names, but just haven't gotten anything to work. I recognize this is a variant of a commonly asked and simple type of question, but I've spent hours without resolving it on my own.  So, apologies for my stupidity!

A: This works ok:
x <- aggregate(my.data[,5:12], by=list(site=my.data$site, moisture=my.data$moisture, shade=my.data$shade), FUN=sum, na.rm=T)

library(dplyr)

my.data %>%
  group_by(site) %>%
  tally %>%
  left_join(x)

  site n moisture shade bluestm foxtail crabgr johnson sedge1 sedge2 redoak blkoak
1  211 1        5    51       0       0      0       0      0      1      0      0
2  223 4        7    83      13       5      4       8      6      1     14     45
3  257 2        7    18       4       2     33       0      0      1      1     22
4  298 3        8    76       2       4      3       9     13      2      9     40

Or to do it all in dplyr
my.data %>%
  group_by(site) %>%
  tally %>%
  left_join(my.data) %>%
  group_by(site,moisture,shade,n) %>%
  summarise_each(funs(sum=sum)) %>%
  select(-sampleID)

    site moisture shade n bluestm foxtail crabgr johnson sedge1 sedge2 redoak blkoak
  1  211        5    51 1       0       0      0       0      0      1      0      0
  2  223        7    83 4      13       5      4       8      6      1     14     45
  3  257        7    18 2       4       2     33       0      0      1      1     22
  4  298        8    76 3       2       4      3       9     13      2      9     40

A: Try following using base R:
outdf<-data.frame(site=numeric(),moisture=numeric(),shade=numeric(),bluestm=numeric(),foxtail=numeric(),crabgr=numeric(),johnson=numeric(),sedge1=numeric(),sedge2=numeric(),redoak=numeric(),blkoak=numeric())

my.data$basic = with(my.data, paste(site, moisture, shade))

for(b in unique(my.data$basic)) {
        outdf[nrow(outdf)+1,1:3] = unlist(strsplit(b,' '))
        for(i in 4:11)
             outdf[nrow(outdf),i]= sum(my.data[my.data$basic==b,i])
}

outdf
  site moisture shade bluestm foxtail crabgr johnson sedge1 sedge2 redoak blkoak
1  223        7    83      13       5      4       8      6      1     14     45
2  257        7    18       4       2     33       0      0      1      1     22
3  298        8    76       2       4      3       9     13      2      9     40
4  211        5    51       0       0      0       0      0      1      0      0


text:
Q: What is $\lim_{n\to\infty}\sum_{r=1}^{n} \frac{r}{4r^2+1}$? What is $$\lim_{n\to\infty}\sum_{r=1}^{n} \frac{r}{4r^2+1}?$$
I have no clue how to do it.Any way to break this into telescoping sum?

A: Note that
$$\displaystyle\sum_{r=1}^n \displaystyle \frac{r}{4r^2+1} \geq \displaystyle\sum_{r=1}^n \displaystyle \frac{r}{4r^2+r^2} = \displaystyle\sum_{r=1}^n \displaystyle \frac{r}{5r^2} = \displaystyle\sum_{r=1}^n \displaystyle \frac{1}{5r}$$
and $\displaystyle\sum_{r=1}^{\infty} \displaystyle \frac{1}{5r}$ diverges by the integral test (or whatever you use to prove the harmonic series diverges), so this series (of positive terms) also diverges by the comparison test.
So the limit of your series is $\infty$ as $n \rightarrow \infty$.

A: It diverges by comparison:$$\sum_{r=1}^{n} \frac{r}{4r^{2}+1} \ge \sum_{r=1}^{n} \frac{1}{5r} \to \infty$$


text:
Q: File only 15MB - drive.files.insert failed with error: Request Too Large I have a short script to OCR jpg files by converting them to GDOCS. It works fine for JPGs around 5MB. But for a 600dpi scan, where the file size is more like 15MB I get the following error for a single image:
5:40:58 PM  Notice  Execution started
5:41:03 PM  Error
GoogleJsonResponseException: API call to drive.files.insert failed with error: Request Too Large
convertJpegToGdoc   @ convertJpegToGdoc.gs:27

The relevant line of code is:
Drive.Files.insert({title: file.getName(), parents: [{id: dstFolderId}]
                    }

I am aware of quotas Quotas for Google Services The error I am getting is not one of these. The time shows that the script is not exceeding the 6 mins listed in the docs. BTW I can convert multiple images, each approx 1.5MB, with 24 character JPG file basenames, into gdocs without problems using this script.
The Google Drive API for insert docs javascript example suggests, perhaps,  that I may need to upgrade my code to handle larger files. But I am not sure where to start.
Any suggestion appreciated.
Full code:
// this function does OCR while copying from ocrSource to ocrTarget
function convertJpegToGdoc() {

var files = DriveApp.getFolderById(srcFolderId).getFilesByType(MimeType.JPEG);

while (files.hasNext()) { var file = files.next();
Drive.Files.insert({title: file.getName(), parents: [{id: dstFolderId}]
                        },
    file.getBlob(), {ocr: true});

}

// this moves files from ocrSource to ocrScriptTrash
// handy for file counting & keeping ocrSource free for next batch of files
var inputFolder = DriveApp.getFolderById(srcFolderId);
var processedFolder = DriveApp.getFolderById(trshFolderId);

var files = inputFolder.getFiles();
while (files.hasNext()) {
    var file = files.next();
    file.moveTo(processedFolder);
     }

}

A: I believe your goal is as follows.

*

*You want to convert a JPEG to Google Doucment as OCR using Drive API.

When I saw your question, I remembered that I experienced the same situation as you. At that time, even when the resumable upload is used, the same error of Request Too Large couldn't be removed. For example, as the reason for this issue, I thought the file size, the image size, the resolution of the image, and so on. But I couldn't find a clear reason for this. So, in that case, I used the following workaround.
My workaround is to reduce the image size. By this, the file size and image size can be reduced. By this, I could remove the issue. In this answer, I would like to propose this workaround.
When your script is modified, it becomes as follows.
From:
Drive.Files.insert({title: file.getName(), parents: [{id: dstFolderId}]
                        },
    file.getBlob(), {ocr: true});

}

To:
try {
  Drive.Files.insert({ title: file.getName(), parents: [{ id: dstFolderId }] }, file.getBlob(), { ocr: true });
} catch ({ message }) {
  if (message.includes("Request Too Large")) {
    const link = Drive.Files.get(file.getId()).thumbnailLink.replace(/=s.+/, "=s2000");
    Drive.Files.insert({ title: file.getName(), parents: [{ id: dstFolderId }] }, UrlFetchApp.fetch(link).getBlob(), { ocr: true });
  }
}

*

*In this modification, when the error of Request Too Large occurs, the image size is reduced by modifying the thumbnail link. In this sample, the horizontal size is 2000 pixels by keeping the aspect ratio.

Note:

*

*This modified script supposes that Drive API has already been enabled at Advanced Google services. Please be careful about this.

Added:
Your script in your question is as follows.
// this function does OCR while copying from ocrSource to ocrTarget
function convertJpegToGdoc() {

var files = DriveApp.getFolderById(srcFolderId).getFilesByType(MimeType.JPEG);

while (files.hasNext()) { var file = files.next();
Drive.Files.insert({title: file.getName(), parents: [{id: dstFolderId}]
                        },
    file.getBlob(), {ocr: true});

}

// this moves files from ocrSource to ocrScriptTrash
// handy for file counting & keeping ocrSource free for next batch of files
var inputFolder = DriveApp.getFolderById(srcFolderId);
var processedFolder = DriveApp.getFolderById(trshFolderId);

var files = inputFolder.getFiles();
while (files.hasNext()) {
    var file = files.next();
    file.moveTo(processedFolder);
     }

}

In my answer, I proposed the following modification.
From:
Drive.Files.insert({title: file.getName(), parents: [{id: dstFolderId}]
                        },
    file.getBlob(), {ocr: true});

}

To:
try {
  Drive.Files.insert({ title: file.getName(), parents: [{ id: dstFolderId }] }, file.getBlob(), { ocr: true });
} catch ({ message }) {
  if (message.includes("Request Too Large")) {
    const link = Drive.Files.get(file.getId()).thumbnailLink.replace(/=s.+/, "=s2000");
    Drive.Files.insert({ title: file.getName(), parents: [{ id: dstFolderId }] }, UrlFetchApp.fetch(link).getBlob(), { ocr: true });
  }
}

But, when I saw your current script, your current script is as follows.
// convertJpegToGdoc.js - script converts .jpg to .gdoc files
// Google Script Project - ocrConvert  https://script.google.com/home/projects/1sDHfmK4H19gaLxxtXeYv8q7dql5LzoIUHto-OlDBofdsU2RyAn_1zbcr/edit
// clasp location C:\Users\david\Google Drive\ocrRollConversion

// Begin with empty folders (see below)
// Transfer a set of Electoral Roll .JPG from storage into ocrSource folder
// Running this script performs OCR conversions on the .JPG files
// .JPG files are converted to .GDOC & stored in ocrTarget
// The .JPG ocrSource files are transferred to ocrScriptTrash leaving the ocrSource folder empty if all goes well

// Uses Google Drive root folders (~\Google Drive\)
// 1. ocrSource
// 2. ocrTarget
// 3. ocrScriptTrash

// to check Id value open folder in Google Drive then examine URL
let srcFolderId = "###"; //ocrSource
let dstFolderId = "###"; //ocrTarget
let trshFolderId = "###"; //ocrScriptTrash

// this function does OCR while copying from ocrSource to ocrTarget (adjusted try/catch for larger jpgs)
function convertJpegToGdocRev1() {

var files = DriveApp.getFolderById(srcFolderId).getFilesByType(MimeType.JPEG);

try {
    Drive.Files.insert({ title: file.getName(), parents: [{ id: dstFolderId }] }, file.getBlob(), { ocr: true });
  } catch ({ message }) {
    if (message.includes("Request Too Large")) {
      const link = Drive.Files.get(file.getId()).thumbnailLink.replace(/=s.+/, "=s2000");
      Drive.Files.insert({ title: file.getName(), parents: [{ id: dstFolderId }] }, UrlFetchApp.fetch(link).getBlob(), { ocr: true });
    }
  }

// this moves files from ocrSource to ocrScriptTrash
// handy for file counting & keeping ocrSource free for next batch of files
var inputFolder = DriveApp.getFolderById(srcFolderId);
var processedFolder = DriveApp.getFolderById(trshFolderId);

var files = inputFolder.getFiles();
while (files.hasNext()) {
    var file = files.next();
    file.moveTo(processedFolder);
     }

}

Unfortunately, it seems that you miscopied my proposed answer. In your current script, var files = DriveApp.getFolderById(srcFolderId).getFilesByType(MimeType.JPEG); is not used. And, when try-catch is not used, an error occurs. But, because of try-catch, when you run the script, No result. No errors occurs. I think that the reason for your current issue of No result. No errors is due to this.
In order to use my proposed modification, please correctly copy and paste the script. By this, the modified script is as follows.
Modified script:
Please enable Drive API at Advanced Google services.
let srcFolderId = "###"; //ocrSource
let dstFolderId = "###"; //ocrTarget
let trshFolderId = "###"; //ocrScriptTrash

function convertJpegToGdocRev1() {
  var files = DriveApp.getFolderById(srcFolderId).getFilesByType(MimeType.JPEG);
  while (files.hasNext()) {
    var file = files.next();
    var name = file.getName();
    console.log(name) // You can see the file name at the log.
    try {
      Drive.Files.insert({ title: name, parents: [{ id: dstFolderId }] }, file.getBlob(), { ocr: true });
    } catch ({ message }) {
      if (message.includes("Request Too Large")) {
        const link = Drive.Files.get(file.getId()).thumbnailLink.replace(/=s.+/, "=s2000");
        Drive.Files.insert({ title: file.getName(), parents: [{ id: dstFolderId }] }, UrlFetchApp.fetch(link).getBlob(), { ocr: true });
      }
    }
  }
  var inputFolder = DriveApp.getFolderById(srcFolderId);
  var processedFolder = DriveApp.getFolderById(trshFolderId);
  var files = inputFolder.getFiles();
  while (files.hasNext()) {
    var file = files.next();
    file.moveTo(processedFolder);
  }
}


text:
Q: How to use html2canvas JavaScript with Selenium webdriver in C# With selenium webdriver, I would test html2canvas JS script to take "screenshots" of webpages or parts of it, directly on the browser.
I have a written this C# code to test it, but obj is always null.
C# Code for reference
        IWebDriver Driver = new FirefoxDriver();
        Driver.Navigate().GoToUrl("http://www.monsite.com");

        string scriptJS = File.ReadAllText("html2canvas.js");
        scriptJS += @"
            html2canvas(document.body, {
                onrendered: function(canvas) {
                    var img = canvas.toDataURL("image/png");
                    return img;
                }
            });";

        IJavaScriptExecutor executorJS = Driver as IJavaScriptExecutor;
        var obj = executorJS.ExecuteScript(scriptJS);

A: There are two thinks that are wrong:

*

*return img is value that is retured by onrendered function. That means html2canvas() call doesn't return image as you expect in your code.

*executorJS.ExecuteScript returns IWebElement, Int64, Boolean, String, List<IWebElement|Int64|Boolean|String> or null. So you can't get this image as return value, see for more details the doc.
If you need screenshot of site, you can use use ((ITakesScreenshot) driver).GetScreenshot(); (doc).
If you need image in this site, you have to implement it into onrendered function.

UPDATE (25.10.2013)
You can call executorJS.ExecuteAsyncScript. Last parameter in javascript function call will be callback function injected by webdriver. Async method returns after injected method
is called, or scriptTimeout is done. For this reason it is a good idea to set timeout to higher value (just to ensure that application is running like expected, later you can put value that is used in productive system).
    Driver.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromSeconds(5));

    scriptJS += @"
        var webDriverCallback = arguments[arguments.length - 1];

        html2canvas(document.body, {
            onrendered: function(canvas) {
                var img = canvas.toDataURL('image/png').replace('data:image/png;base64,', '');;
                webDriverCallback(img);
            }
        });";

    IJavaScriptExecutor executorJS = Driver as IJavaScriptExecutor;
    var obj = executorJS.ExecuteAsyncScript(scriptJS);

The result is base64 encoded image as String.


text:
Q: POST Request gives FileNotFoundException POST request gives FileNotFoundException for the URL
I am making an Http POST request to a Url https://nitos.gr in android.
The url has not domain name. Stackoverflow does not allow me to include URL with numbers in my text, so i just write a random url https://nitos.gr for having an example.
I get a 400  response code, and print the getErrorStream() giving libcore.net.http.UnknownLengthHttpInputStream@41eba330
However, i perform succesfully HTTP GET request. The url is https, thus i have a fake trust manager allowing all SSL connections.
In summary:
Protocol: HTTPS
GET Request: successful
POST Request: Fails
Request code: 400
Error message: java.io.FileNotFoundException: https://nitos.gr
ErrorStream: java.io.FileNotFoundException: https://nitos.gr
The method performing the POST Request follows:
public void setTestbedData(String path, String data) {
        HttpURLConnection con = null;

        try {
            con = (HttpURLConnection) ( new URL(Constants.BASE_URL + path)).openConnection();
             // If you invoke the method setDoOutput(true) on the URLConnection, it will always use the POST method.
            con.setRequestMethod("POST");
            con.setDoInput(true);
            con.setDoOutput(true);

            con.setRequestProperty("Accept", "application/json");
            con.setRequestProperty("Content-Type", "application/json");

            Log.i("data", data);

            OutputStream outputStream = con.getOutputStream();
            outputStream.write(data.getBytes());
            outputStream.flush();

            Log.w("RESPONSE CODE", "code " + con.getResponseCode());

            Log.w("this is connection ",""+con);
            InputStream errorstream = con.getErrorStream();
            Log.w("GetErrorStream  ", ""+errorstream);

            InputStream _is;
            if (con.getResponseCode() >= 400) {
                _is = con.getInputStream();
            } else {

                _is = con.getErrorStream();

                String result = getStringFromInputStream(_is);
                Log.i("Error != 400", result);
            }

            if (con.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                    + con.getResponseCode());
            }

            BufferedReader responseBuffer = new BufferedReader(new InputStreamReader((con.getInputStream())));

            String output;
            Log.i("TestbedHttpClient","Output from Server:");
            while ((output = responseBuffer.readLine()) != null) {
                Log.i("Output",output);
            }

            con.disconnect();

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

    }

The error messages:
RESPONSE CODE(18936): code 400
libcore.net.http.HttpsURLConnectionImpl$HttpUrlConnectionDelegate:https://nitos.gr
GetErrorStream(18936): libcore.net.http.UnknownLengthHttpInputStream@41eba330
System.err(18936): java.io.FileNotFoundException: https://nitos.gr
 System.err(18936):     at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)

A: Replace following code
        Log.w("this is connection ",""+con);
        InputStream errorstream = con.getErrorStream();
        Log.w("GetErrorStream  ", ""+errorstream);

        InputStream _is;
        if (con.getResponseCode() >= 400) {
            _is = con.getInputStream();
        } else {

            _is = con.getErrorStream();

            String result = getStringFromInputStream(_is);
            Log.i("Error != 400", result);
        }

with
        InputStream _is;
        if (con.getResponseCode() / 100 == 2) { // 2xx code means success
            _is = con.getInputStream();
        } else {

            _is = con.getErrorStream();

            String result = getStringFromInputStream(_is);
            Log.i("Error != 2xx", result);
        }

Or in other words: It doesn't make sense to read from getInputStream() when HTTP status code is greater than or equal to 400. It's not that simple, maybe you have to deal with some 3xx codes as well. Have a look at List of HTTP status codes.
A last word: if you find HttpURLConnection cumbersome to use, you could use one of the abstraction libraries listed here.

A: Finally, I could not perform POST Request due to the fact that the server has authentication.
So, there is no problem with the configuration of the POST Request.
Thus, now i should find a way to attach a certificate to the REST Call to the server.


text:
Q: JQuery related Problems How can i write this formula : (loanAmt((i / 360) + (i / 360 / (1 + i / 360)^ n * 30 - 1)) in jQuery......the code which i had written in my application is not working.....so please suggest me how can i write that.......
$("#btnDimi").click(function (evt) {
    var loanAmt,
        i,
        n;

    loanAmt = $("#LoanAmt").val();
    i = $("#Interest").val();
    n = $("#LoanPeriod").val();
    var selectedRadio = $("input[name='PaymentType']:checked").val();

    if (selectedRadio == 'Daily') {
        var result = eval(" loanAmt((i / 360) + (i / 360 / Math.pow(1 + i / 360, n * 30)) - 1) ");
        $("#Payment").val(result);
    } else {
        // some other codes...... with another formula
    }
});

A: Change your lines like this(Note:You can use parseInt() method to convert your input values to integer):
loanAmt = praseInt($("#LoanAmt").val()); - Like this for all
 var result = eval(" loanAmt((i / 360) + (i / 360 / Math.pow(1 + i / 360, n * 30)) - 1) ");

TO

 var result = eval(" loanAmt*((i / 360) + (i / 360 / Math.pow(1 + i / 360, n * 30)) - 1) ");


text:
Q: Android browser GREEN border on click I want to develop a web application using HTML, CSS and Javascript one thing that is really annoying is that any link or button etc when clicked inside the Android browser gets highlighted with a green border.
To demonstrate what I mean I have included a link to a page that contains a basic game written in CSS
http://marbles2.com/app/
Is there any way that you are aware of to disable the click green border?
Cheers
Paul

A: Try this in your style:
style="-webkit-tap-highlight-color:rgba(0, 0, 0, 0);"

Hope this helps.

A: In your CSS stylesheet (the one in your web application), add this:
* {
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}


text:
Q: jquery file upload with spring mvc : 400 bad request I coded a file upload with SpringMVC, following the manual example (LINK) and it works fine.
Then, I changed the client to use jQuery file upload
http://blueimp.github.com/jQuery-File-Upload/
in order to have a more powerful client (with drag and drop).
I downloaded the widget and implemented a jsp with it.
But it does not work. The browser receives a response 400 (bad request) and no exception is throw with tomcat7.
I saw a difference in the request:
with the working spring mvc doc exemple the request look like (firebug) :
-----------------------------26989305212543489571047641949 Content-Disposition: form-data; name="name"
-----------------------------26989305212543489571047641949 Content-Disposition: form-data; name="file"; filename="content.txt"
Content-Type: text/plain hello
-----------------------------26989305212543489571047641949--

and for the non working jsp with jQuery fileupload default implementation the request in firebug looks like :
-----------------------------205805102810633831841397435868 Content-Disposition: form-data; name="files"; filename="content.txt" Content-Type: text/plain hello
-----------------------------205805102810633831841397435868--

So, with the jQuery non working version, more is sent to the server. Some kind of extra meta-data. Is that the problem or am i searching in the wrong way? I'm no expert at all in file upload / multipart.
Thanks for your help.
Spring v3.1.2
Tomcat v7.0
jQuery 1.8
The project use sitemesh (I don't think it makes a difference but...)
The controller code
import java.io.IOException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUploadController {

    @RequestMapping(value = "/form", method = RequestMethod.POST)
    public String handleFormUpload(@RequestParam(value="name",required=false) String  name,
       @RequestParam("file") MultipartFile file) throws IOException {

       if (!file.isEmpty()) {
           byte[] bytes = file.getBytes();
           // store the bytes somewhere
          return "redirect:home";
      } else {
          return "redirect:uploadFailure";
      }
       System.out.println(file.length);
       return "home";
    }

}

working jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

       <title>Upload a file please</title>

Please upload a file

       <form method="post" action="form" enctype="multipart/form-data">
           <input type="text" name="name"/>
           <input type="file" name="file"/>
           <input type="submit"/>
       </form>

Non working jsp (with jQuery) :
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator"

    prefix="decorator"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html >

<link rel="stylesheet" type="text/css" href="/ReformYourCountry/css/test-style.css" />
<link rel="stylesheet" type="text/css" href="/ReformYourCountry/css/template.css" />
<link rel="stylesheet" type="text/css" href="/ReformYourCountry/css/content.css" />

<meta charset="utf-8">
<title>jQuery File Upload Demo</title>
<meta name="description" content="File Upload widget with multiple file selection, drag&drop support, progress bar and preview images for jQuery. Supports cross-domain, chunked and resumable file uploads. Works with any server-side platform (Google App Engine, PHP, Python, Ruby on Rails, Java, etc.) that supports standard HTML form file uploads.">
<meta name="viewport" content="width=device-width">

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/base/jquery-ui.css" id="theme">

<link rel="stylesheet" href="http://blueimp.github.com/jQuery-Image-Gallery/css/jquery.image-gallery.min.css">

<link rel="stylesheet" href="css/jquery.fileupload-ui.css">

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

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

    <form id="fileupload" action="form" method="POST" enctype="multipart/form-data">

                   Add files...
                   <input type="file" name="files" multiple>

               <button type="submit" class="btn btn-primary start">

                   Start upload
               </button>
               <button type="reset" class="btn btn-warning cancel">

                   Cancel upload
               </button>
               <button type="button" class="btn btn-danger delete">

                   Delete
               </button>
               <input type="checkbox" class="toggle">

    </form>

A: I've used the jQuery File Upload widget with Spring MVC with controller code like the following (note there is a dependency on apache commons fileupload for handing the multipart content):
@RequestMapping(value="/project/file", method=POST)
public void addFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (!ServletFileUpload.isMultipartContent(request)) {
            throw new IllegalArgumentException("Request is not multipart, please 'multipart/form-data' enctype for your form.");
        }
        ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());

        try {
            List<FileItem> items = uploadHandler.parseRequest(request);
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    byte [] fileBytes = item.get();
                }
         } catch(FileUploadException e) {
             throw new RuntimeException(e);
         }

   }

A: with Jer's help i maked this working method:
@RequestMapping(value="imageuploadsubmit", method=RequestMethod.POST)
public void addFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {

    if (!(request instanceof DefaultMultipartHttpServletRequest)){
        throw new IllegalArgumentException("Request is not multipart, please 'multipart/form-data' enctype for your form.");
    }

    DefaultMultipartHttpServletRequest dmhsRequest = (DefaultMultipartHttpServletRequest) request ;
    MultipartFile multipartFile = (MultipartFile) dmhsRequest.getFile("image");

    //make traitment like a File object
}


text:
Q: Is there an advantage/disadvantage to open a different tcp port for every client? I build a middle ware server.
I have 5(or 6) clients(different computer/IP address), and every client can have up to 6 connection -> max 36 connection to the server.
It is better to use only 1 port for all (e.g. 9000) or one different port for every client(e.g. 9000-9005) ?
I write me a simple test server(see code).
It worked like expected but maybe there is some room for optimization.
Thanks
My TCP server
public class TCPServerMulti : IDisposable
    {
    private static TcpListener _tcpListener;
    private string _ipAdress = "";
    private int _port = 9050;
    private readonly Thread _listener;
    private readonly bool _running;

    private int cc = 0; //Test Counter

    public string IPAdress
    {
        get { return _ipAdress; }
        set { _ipAdress = value; }
    }

    public TCPServerMulti(int port)
    {
        if(port>0)
            _port = port;

        _running = true;
        string sHostName = Dns.GetHostName();
        IPAdress = "";
        //Only use the first address -> need to change
        IPAddress[] localAddress = Dns.GetHostAddresses(sHostName);
        foreach (IPAddress ipAddress in localAddress)
        {
            if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
            {
                _tcpListener = new TcpListener(ipAddress, _port);
                IPAdress = ipAddress.ToString();
                break;
            }
        }
        if (IPAdress == "")
        {
            Console.Writeline("TCP Error");
            return;
        }
        _tcpListener.Start();
        _listener = new Thread(Listen) { IsBackground = true };
        _listener.Start();
    }
    public TCPServerMulti():this(-1)
    {}
    //listening for clients
    public void Listen()
    {
        try
        {
            while(_running)
            {
                cc++;
                //create a own client object for every connection
                TCPClientData cd = new TCPClientData(this, ""+cc, _tcpListener.AcceptTcpClient());
                cd.StartClient();
                if (ClientConnected != null) ClientConnected("Connected: " + cc);
            }
            _tcpListener.Stop();
        }
        catch (Exception)
        {
        }
    }

    public void Dispose()
    {
        _listener.Abort();
        _tcpListener.Stop();
    }
    //Handle for Mainthread
    internal void ReceiveClient(TCPClientData sender, string msg)
    {
        if (ReceiveMsg != null)
            ReceiveMsg(sender, msg);
    }

    public delegate void ReceiveEventHandler(TCPClientData sender, string msg);
    public event ReceiveEventHandler ReceiveMsg;

    public delegate void ConnectedEventHandler(string msg);
    public event ConnectedEventHandler ClientConnected;
}

Clientdata object
public class TCPClientData : IDisposable
{
    private TCPServerMulti _master;
    private byte[] _data;
    private NetworkStream _networkStream;
    private int _received;
    private TcpClient _tcpClient;

    private Thread _worker;
    private bool _wrunning;

    private string _id;
    public TCPClientData(TCPServerMulti master,string id,TcpClient client)
    {
        _data = new byte[1024];
        _master = master;
        _id = id;
        _tcpClient = client;
    }

    public string ID
    {
        get { return _id; }
    }

    private string ByteArrayToString(byte[] arr)
    {
        UTF8Encoding enc = new UTF8Encoding();
        return enc.GetString(arr);
    }

    private byte[] StringToByteArray(string data)
    {
        UTF8Encoding enc = new UTF8Encoding();
        return enc.GetBytes(data);
    }
    // Reading Data
    private void Worker()
    {
        try
        {
            while (_wrunning)
            {

                if (_networkStream.DataAvailable)
                {
                    _received = _networkStream.Read(_data, 0, _data.Length);

                    string s = ByteArrayToString(_data);
                    _master.ReceiveClient(this, s.Substring(0, _received));
                }
                else
                {
                    Thread.Sleep(20);
                }
            }
            _networkStream.Close();
            _tcpClient.Close();
        }
        catch (Exception)
        { }
    }

    public void Dispose()
    {
        _worker.Abort();
        _networkStream.Close();
        _tcpClient.Close();
    }

    public void StartClient()
    {
        _networkStream = _tcpClient.GetStream();
        _networkStream.ReadTimeout = 200;
        _wrunning = true;
        _worker = new Thread(Worker) { IsBackground = true };
        _worker.Start();
    }
    public void StopClient()
    {
        _wrunning = false;
        Thread.Sleep(700);
    }
    //Sending Data
    public void WriteData(string msg)
    {
        byte[] b = StringToByteArray(msg);
        _networkStream.Write(b,0,b.Length);
        _networkStream.Flush();
    }
}

Main Thread
static void Main(string[] args)
    {
        //Create Server
        TCPServerPlugin.TCPServerMulti server=new TCPServerMulti(12345);
        server.ClientConnected += Server_ClientConnected;
        server.ReceiveMsg += Server_ReceiveMsg;
        while (true)
        {

        }
    }
    //Callbacks
    private static void Server_ClientConnected(string msg)
    {
        Console.WriteLine(msg);
    }

    private static void Server_ReceiveMsg(TCPClientData sender, string msg)
    {
        Console.WriteLine(string.Format("Sender: {0} -> MSG:{1}",sender.ID,msg));
        if (msg == "!!X")
        {
            sender.Dispose();
            sender = null;
        }
        else if(msg=="DATE")
            sender.WriteData(DateTime.Now.ToLongDateString());
        else if(msg=="TIME")
            sender.WriteData(DateTime.Now.ToShortTimeString());
    }


text:
Q: Empty list in GrapQL schema- should be null or []? I have Post type with tags field that is array of strings, but some posts do not have tags. Is there any convention how to handle 0 items (tags in my example) - from backend should I return null in query or empty array []? If this is developer preference and there is no standard for that, what is used more often in all graphql projects?

A: It's better to use an empty list ([]): https://github.com/nuwave/lighthouse/issues/1980#issuecomment-970189037


text:
Q: Php mysqli real escape string add back slashes I have a text field that stores a value in database. When I input inverted commas i.e " " or apostrophe i.e. '' it automatically adds back slash to my string. How to remove back slashes or inverted commas and apostrophe?
<?php
if (empty($_POST['video_title'])) {
        $error[] = 'You must enter a video title';
    } else {
        $vid_title =  mysqli_real_escape_string($conn, $_POST['video_title']);
    }
?>

A: that is happening because of magic quotes, you should disable, if you don't want to, you can run stripslashes()
such as
<?php
if (empty($_POST['video_title'])) {
        $error[] = 'You must enter a video title';
    } else {
        $vid_title =  mysqli_real_escape_string($conn, $_POST['video_title']);
        $vid_title = stripslashes($vid_title);
    }
?>


text:
Q: How are Android-Binding and Roboguice? As a beginner for Android development, code samples I am learning from look somewhat disorganized and are hard to test or even to understand. So I followed this post suggested: Using Dependency Injection with Roboguice? and am trying to use Android-binding and Roboguice. But I am now worrying about how good they really are.

*

*Are they good enough for all Android projects including ones with a couple of views?

*After building an app with these tools, how is the app's performance in comparison without the tools? Any problem with using these tools?

*Is there any other tool that can help me for Agile/TDD?

A: I've only used Roboguice and this is my opinion of it.
Roboguice is derived from Guice. So it's not really a dependency injection framework built from the grounds up for mobile environment. That being said, it can cause quite some overhead to your app.
On the other hand, I haven't seen any mobile app that reached a complexity that really needs dependency injection. I had an app the used Roboguice, but soon I realized that it's making my app more complex than it needs to be. So I stripped it out. I guess this depends a lot on the scale of your app.


text:
Q: Elasticsearch 2.1: how to delete by query using curl I have an _index: varnish_logs and _type: varnish
a field having two different values "server" : "india" and "server" : "usa"
Now I want to delete only the records which are in usa.
I tried using
$ curl -XDELETE 'http://localhost:9200/_all/_query?q=server:usa'
response: No handler found for uri [] and method [DELETE]

and also tried to delete all the data using query
curl -XDELETE 'http://localhost:9200/varnish_logs/varnish/_query' -d '
{
"query" :{
"match_all" : {}
}
}'
all I get response: found: "false"

Please let me know where I'm wrong

A: Elasticsearch has removed the delete-by-query functionality. They have instead replaced it by a plugin with same name. It is slower than the previous but fixes the problem elasticsearch had previously.
This post from elasticsearch might help.


text:
Q: Replacing full referrer using REGEX Google Data Studio I'm using Google Data Studio to create a report analyzing specific referral sites. My data source is my site Google Analytics.
I want to replace the Full Referrer (e.g. of the format webaddress.com/page-name-one) with a text only value (i.e Page name one), so that it's clearer to see in the report which page is which in my charts and tables.
I've used the below formulae in the calculated fields, but none of them seem to change Full Referrer to match what I need it to. Data studio recognizes them all as valid formulae too.
I've anonymised my examples, but it has the same principles. I've tried:
REGEXP_REPLACE(Full Referrer,"[webaddress\\.com\\/page\\-name\\-one].*","Page name one")

REGEXP_REPLACE(Full Referrer, 'webaddress.com/page-name-one', 'Page name one')

REGEXP_REPLACE(Full Referrer, 'webaddress\\.com\\/page\\-name\\-one', 'Page name one')

REGEXP_REPLACE(Full Referrer, 'name', 'Page name one')

REGEXP_REPLACE(Full Referrer, 'page-name-one', 'Page name one')

REGEXP_REPLACE(Full Referrer, 'page\\-name\\-one', 'Page name one')

A: In testing this on one of my own GA data sources, I was able to achieve this using one of your patterns:
REGEXP_REPLACE(Full Referrer,'webaddress.com/page-name-one','Page name one')

It should be noted, however, that the . should be properly escaped (either by \ or wrapping it in a character class like [.]; see re2 syntax for details). Because you have to double-backslash, I also prefer to use something Data Studio borrowed from BigQuery (sort of an undocumented feature), which is the regular expression string type (r"" or r''). When using this, you only have to single-backslash (unless you want a literal backslash):
REGEXP_REPLACE(Full Referrer,r'webaddress\.com/page-name-one','Page name one')

Because you're using REGEXP_REPLACE, anything before or after your match string will still exist after the replacement—meaning that for a Full Referrer of "m.facebook.com/l", REGEXP_REPLACE(Full Referrer,r'facebook\.com','FB') would return "m.FB/l"
So your pattern above will match the value anywhere in the string, which likely isn't what you want. To anchor it to the beginning, use the ^ (start of string) assertion:
REGEXP_REPLACE(Full Referrer,r'^webaddress\.com/page-name-one','Page name one')

If you want to only match that exact value of Full Referrer (i.e. not including any additional path levels), make sure to use the $ (end of string) assertion as well:
REGEXP_REPLACE(Full Referrer,r'^webaddress\.com/page-name-one$','Page name one')

Keep in mind that if you're doing this in the data source as a calculated field, you aren't actually changing the original metric—you're working on a copy of it. So you need to replace Full Referrer with whatever you named your calculated field in the data source.
Often you're wanting to do this for a bunch of sites or pages, so you can use CASE and REGEXP_MATCH to handle all this logic in a single field:
CASE
  WHEN REGEXP_MATCH(Full Referrer,r'^webaddress\.com/page-name-one$') THEN 'Page name one'
  WHEN REGEXP_MATCH(Full Referrer,r'^site2\.com/example$') THEN 'S2 Example'
  ELSE Full Referrer
END

These matches are done in order, so you can even match a specific page or pages, and then still provide a different value for anything on that domain that you didn't match:
CASE
  WHEN REGEXP_MATCH(Full Referrer,r'^site\.com/$') THEN 'Site - Home'
  WHEN REGEXP_MATCH(Full Referrer,r'^site\.com/about$') THEN 'Site - About'
  WHEN REGEXP_MATCH(Full Referrer,r'^site\.com/') THEN 'Site - (other)'
  ELSE Full Referrer
END

You can also use the ELSE if you want to bucket all of the unmatched values into an "other" grouping instead of just leaving the original value.
Another thing to remember is that due to shared fields in GA, things like Source (utm_source) also show up in Full Referrer, so you could be seeing values there that you wouldn't normally expect. Often you can get rid of these by also filtering to only the Default Channel Grouping of "Referral".
If your patterns still aren't matching, please update the question with some additional details such as what the output actually is, whether there's an error message, etc.—and also whether you're doing this as a calculated field in the data source or the "Create Field" button on a single chart.


text:
Q: My MySQL database was wiped and I think it was a SQL injection, where am I wrong? So I have a test DB that is live, I was away for the holidays and come back and my MYSQL DB is wiped of data (only about 8 lines).  It was all test data so I am not worried about it, my thoughts is that I was SQL injected through my PHP signup form but I don't see any vulnerabilities here.
I am using variables for my SQL queries which is what I thought prevented this type of attack.
I am at a loss as to where the vulnerabilities are.  I only have 5 files, here is the one that I think is the problem, it is receiving data from a previous form.

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Challenge Me</title>

<?php

if($_GET["dispname"] && $_GET["regemail"] && $_GET["regpass"] && $_GET["regpass2"] )
{
if($_GET["regpass"]==$_GET["regpass2"])
{
$regemail = $_GET["regemail"] ;
$servername="localhost";
$username="***";
$password="***";
$database="***";
$conn= mysql_connect($servername,$username,$password)or die(mysql_error());
mysql_select_db("$database",$conn);

$query = 'SELECT email FROM users WHERE email = "' . $regemail . '"';
$result = mysql_query($query) or die(mysql_error());

if (mysql_num_rows($result) ) {
        die("Duplicate email found!  Please press the back button to use another email or " . "CLICK HERE to have your password emailed");
    }
    else {}

$sql="insert into users (fullname, displayname,email,password)values('$_GET[fullname]','$_GET[dispname]','$_GET[regemail]','$_GET[regpass]')";
$result=mysql_query($sql,$conn) or $string = mysql_error();

$to = $_GET['regemail'];
$subject = "Thank you for Registering!";
$message = "Hello " . $_GET['dispname'];
$from = "noreply@challengeme.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers) or die('You have successfully registered however mail servers are currently down, you may or may not receive an email');

print "
You have registered successfully
";

print "You will receive an email shortly with your confirmation.  You may now log in";
}
else print "passwords do not match";
}
else print"Please fill out all required fields";
?>

A:
I am using variables for my SQL queries which is what I thought
  prevented this type of attack.

Well, that is where you are wrong. The word you're looking for is parameters. ($_GET is already a variable, assigning it to another variable does nothing at all for security)
If you want to stick with mysql, you need to use mysql_real_escape_string on your variables.
Your best bet is to rewrite, using PDO or MySQLi, so you can use paramterized queries, which automates the escaping and injection-prevention for you.


text:
Q: Block the index page of the REST API in Tastypie Is it possible to block the index page of the API? I don't want to display all the resources like that to none authenticated users? Right now, if people do for example:
http://example.com/api/rest/?format=json
They will see every possible resources within the API!

A: do you look at tatsypie authorization manual. If not look at this Tatsypie Authorization


text:
Q: How to turn strings into boolean expressions? I'm working on a problem generator that spits out phrases like "!(A && B) || (A || B)", but it does so in a string (I have a function that spits this out in string form). How would I convert this string expression into a same boolean expression in javascript? I've tried to use JSON.parse() but it keeps giving me an error.

A: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval should be the function you're looking for, however read the note about the huge security risk!


text:
Q: JMeter returning different value than from tibco designer I am seeing some weird formatting going in with the JMeter response.  If I run the same request from the tibco designer, I am seeing correct values.
From Tibco designer:
<ns1:Month>07</ns1:Month>
<ns1:TotalTransactionAmount>58.77</ns1:TotalTransactionAmount>

<ns1:Month>08</ns1:Month>
<ns1:TotalTransactionAmount>20.53</ns1:TotalTransactionAmount>

From JMeter 3.0/2.11
<ns1:Month>07</ns1:Month>
<ns1:TotalTransactionAmount>5.877E1</ns1:TotalTransactionAmount>

<ns1:Month>08</ns1:Month>
 <ns1:TotalTransactionAmount>2.053E1</ns1:TotalTransactionAmount>

It seems the decimal is a place off and an E1 is placed in the value as well.  What is causing this?


text:
Q: What is the best way of getting the CFAbsoluteTime of midnight of today? Im using CFAbsoluteTimeGetCurrent() to get the current time, as a CFAbsoluteTime struct.
What is the best way of getting the CFAbsoluteTime of midnight of today?
Ive considered getting midnight using a similar method to the one shown here and then converting the result to a CFAbsoluteTime, but this seems ridiculously complicated to do a simple thing.
Is there a better way?

A: Computing "midnight of the current day" is not completely trivial, because things as
the time zone and daylight savings time transitions must be taken into account.
My preferred way is
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *midnight;
[calendar rangeOfUnit:NSDayCalendarUnit
            startDate:&midnight
             interval:NULL
              forDate:[NSDate date]];

which you can then convert with
CFAbsoluteTime cfMidnight = [midnight timeIntervalSinceReferenceDate];


text:
Q: JSch doesn't detect $HOME/.ssh/id_rsa public key I'm trying to authenticate to a remote Git server using JSch version 0.1.55 via JGit. Using the command-line Git authentication works fine, but via JSch, it does not. The error I'm getting is:
Caused by: org.eclipse.jgit.errors.TransportException: git@REDACTED_HOST:petter/rio.git: Auth fail
    at org.eclipse.jgit.transport.JschConfigSessionFactory.getSession(JschConfigSessionFactory.java:158)
    at org.eclipse.jgit.transport.SshTransport.getSession(SshTransport.java:107)
    at org.eclipse.jgit.transport.TransportGitSsh$SshPushConnection.<init>(TransportGitSsh.java:306)
    at org.eclipse.jgit.transport.TransportGitSsh.openPush(TransportGitSsh.java:143)
    at org.eclipse.jgit.transport.PushProcess.execute(PushProcess.java:127)
    at org.eclipse.jgit.transport.Transport.push(Transport.java:1335)
    at org.eclipse.jgit.api.PushCommand.call(PushCommand.java:137)
    ... 10 more
Caused by: com.jcraft.jsch.JSchException: Auth fail
    at com.jcraft.jsch.Session.connect(Session.java:519)
    at org.eclipse.jgit.transport.JschConfigSessionFactory.getSession(JschConfigSessionFactory.java:112)
    ... 16 more

My theory is that it's unable to find any public keys, based on the last lines of the debug log:
11:07:56.228 [main] DEBUG re.dacted - JSCH: Authentications that can continue: publickey,keyboard-interactive,password
11:07:56.228 [main] DEBUG re.dacted - JSCH: Next authentication method: publickey
11:07:56.295 [main] DEBUG re.dacted - JSCH: Disconnecting from REDACTED_HOST port 22

I think that may be caused by some weird interaction between JSch and the ssh-agent on my Mac (I'm using gpg-agent). Based on  https://gist.github.com/niclasnilsson/038f20bee1bd19e970d59ba35732e262, I tried creating a .ssh/config file with the '*' entry included there, and at one point I got a different error, from the UserAuthPublic key class. However, no matter what I try, I can't seem to be getting back to that stage.
I also tried the instructions from https://dzone.com/articles/how-to-authenticate-with-jgit (ofc, without hard-coding the passphrase, which seems like a very odd thing to have to do), but no luck. It seems like it's not even getting to the point of trying to invoke any of the methods on the UserInfo.
I do get a key back from ssh-add -l. Not sure what else to do in order to try troubleshooting this. Any pointers would be highly appreciated!

A: JSch does not load any private key automatically from anywhere.
If you want to use public key authentication, you need to explicitly tell JSch what private key to use.
See Can we use JSch for SSH key-based communication?

A: Of course I found the answer shortly after posting the question. :) By debugging what the UserAuthPublicKey class was doing during authentication, I realised I had misunderstood how the UserInfo class is used. By using the following Kotlin code, I got it to read the passphrase via a terminal prompt instead:
    private val sshSessionFactory = object : JschConfigSessionFactory() {
        override fun configure(hc: OpenSshConfig.Host?, session: Session?) {
            session?.userInfo = object : UserInfo {
                override fun promptPassphrase(p0: String?) = true
                override fun getPassphrase(): String? = passphraseSupplier()
                override fun getPassword(): String? = null
                override fun promptYesNo(p0: String?) = false
                override fun showMessage(message: String?) = Unit
                override fun promptPassword(p0: String?) = false
            }
        }
    }

My misunderstanding was in what the meaning of 'promptX' and 'getX' methods is. It seems as if 'prompt' means 'do you support prompting the user for X', and that if the UserInfo implementation for 'promptX' returns true, then a following call to 'getX' should return the correct value. It would have been great with some javadocs describing this, that would have saved me several hours!


text:
Q: About a compact imbedding of Sobolev spaces I am studying the Compactness lemma ( on page 570) of the article http://projecteuclid.org/euclid.cmp/1103922134.
The lemma says
(Compactness lemma ): for $0 < \sigma < \frac{2}{N-2}$, $(N \geq 3)$, the  imbedding
$$ H^{1}_{rad}(R^n) \rightarrow L^{2 \sigma +2} (R^n)$$
is compact, where $H^{1}_{rad}(R^n)$ is the radial functions of $H^{1}(R^n)$.
Proof of the lemma:
Consider the interpolation estimate
$$ || u ||^{2 \sigma +2}_{2 \sigma +2} \leq C || u||^{\sigma N}_{H^{1}(R^n)} || u||_{L^2(R^n)}^{2 + \sigma(2-N)} , 0 < \sigma < \frac{2}{N-2} $$
(this is the classical Gagliardo - Nirenberg - Sobolev inequality ).
If we can show that a bounded sequence in $H^{1}_{rad}(R^n)$ is uniformly small at infinity , then follows the result (*).
This uniformity follows from the inequality
$$|u(x)| \leq \frac{C}{|x|^{\frac{N-1}{2}}} || u||_{H^1}  (**)$$
The inequality of $(**)$ is given in a article. But i am not understanding the affirmation of $(*)$
Someone can help me to understand?
thanks in advance

A: It suffices to establish that any sequence $\,u_k=u_k(|x|)\to 0\,$ weakly convergent in $\,H_{rad}^1(\mathbb{R}^n)\,$ will be srongly convergent in $\,L^{2\sigma+2}(\mathbb{R}^n)$, which might be ruined by the unboundedness of $\,\mathbb{R}^n$ if it were not for the remarkable inequality $\,(\ast\ast)\,$ that provides cutting off the infinity.  Indeed, given any $\varepsilon >0$, choose $R_{\varepsilon}>1$ such that
$$
\int\limits_{|x|>R_{\varepsilon}}\Bigl|u_k(|x|)\Bigr|^{2\sigma+2}dx\leqslant \Biggl(\int\limits_{\,\,|x|>R_{\varepsilon}}\Bigl|u_k(|x|)\Bigr|^{2}dx\Biggr)\!\cdot\!\Biggl(\frac{\|u_k\|_{H^1(\mathbb{R}^n)}}{R_{\varepsilon}^{\frac{n-1}{2}}}\Biggr)^{\!2\sigma}\!
\leqslant\\ \leqslant R_{\varepsilon}^{-\sigma (n-1)}\!\!\cdot\!\Bigl(\sup\limits_{k\geqslant 1}\|u_k\|_{H^1(\mathbb{R}^n)}\Bigr)^{2\sigma+2}<\frac{\varepsilon}{2}
\quad \forall\, k\geqslant 1,
$$
and notice that there is $\,m_{\varepsilon}\in \mathbb{N}\,$ such that
$$
\int\limits_{|x|<R_{\varepsilon}}\Bigl|u_k(|x|)\Bigr|^{2\sigma+2}dx
<\frac{\varepsilon}{2} \quad \forall\, k>m_{\varepsilon}
$$
due to the compact embedding $\,H^1(B_{R_{\varepsilon}})\hookrightarrow
L^{2\sigma+2}(B_{R_{\varepsilon}})\,$ for a ball $\,B_{R_{\varepsilon}}=
\{x\in\mathbb{R}^n\,\colon\,|x|<R_{\varepsilon}\} $.


text:
Q: Hovering over SPAN needs to change background of DIV on same level I have created a fiddle for this: http://jsfiddle.net/Lux0ztyt/
When hovering over the SPAN (A,B,C,D, etc.), I need it to change the background to the same as when hovering the rest of the bar however I can't work out how to do it.
I know the problem is because the SPAN is at the END of all the elements but I am not able to change the positioning of this. How can it work with the positions staying as they are?
I have tried:
#my-list li span:hover ~ div {
    /* background stuff */
}

And also:
#my-list li span:hover div {
    /* background stuff */
}

And also:
#my-list li span:hover + div {
    /* background stuff */
}

Any suggestions?
HTML:

100%
A

85%
B

95%
C

85%
D

95%
E

80%
F

90%
G

95%
H

CSS:
#my-list {
    list-style-type: none;
    margin: 0px;
    padding: 0px;
}

#my-list li {
    display: block;
    width: auto;
    text-align: left;
    position: relative;
    margin: 2px 0px;
}

#my-list li span {
    position: absolute;
    left: 5px;
    top: 0px;
    color: #fff;
    text-shadow: 1px 1px 1px #555;
    font-size: 0.85em;
}

#my-list li div, #my-list li label, #my-list li span, #my-list li  {
    height: 30px;
    line-height: 30px;
}

#my-list li div {
    position: absolute;
    background: #b02976;
    left: 0px;
    top: 0px;
    width: 0px;
    border-radius: 7px;
    transition: width 1s, background-color 0.4s ease;
}

#my-list li div:hover {
    background: #009e77;
    transition: all 0.4s ease;
}

#my-list li div:hover > label {
    display: block;
    opacity: 1.0;
    transition: all 0.4s ease;
}

#my-list li div label {
    position: absolute;
    right: 5px;
    color: #fff;
    font-weight: bold;
    font-size: 0.7em;
    opacity: 0;
    transition: all 0.4s ease;
    text-shadow: 1px 1px 1px #555;
}

A: Your code is almost working. The only thing you should change:
Handle the :hover on li rather than the div - then you have no problem:
change
#my-list li div:hover

to
#my-list li:hover div

and
#my-list li div:hover > label

to
#my-list li:hover div > label

The span element will send its :hover to the li - which then will colorize its div child as defined in the css.
http://jsfiddle.net/taqveyjs/1/

A: TimeDead's answer is correct in that you can't target a parent in CSS. I took a different approach though:
http://jsfiddle.net/austinthedeveloper/Lux0ztyt/2/
#my-list li div {
    position: absolute;
    background: #b02976;
    left: 0px;
    top: 0px;
    width: 0px;
    border-radius: 7px;
    transition: width 1s, background-color 0.4s ease;
    z-index:-1;
}

#my-list li:hover div {
    background: #009e77;
    transition: all 0.4s ease;
}

#my-list li:hover div > label {
    display: block;
    opacity: 1.0;
    transition: all 0.4s ease;
}

The trick is to z-index the div so it is behind the li, masking your span. After that, you just update your hover classes to target the li instead of the div and everything works.

A: Sadly what your asking to do I'm not sure can be done strictly in CSS since in CSS you cannot select and change the parents background in this case the span is the child of the div there for cannot modify it's attributes.


text:
Q: Why is my text going over the margin? I have written a paragraph of text and one line is protruding out into the right margin. I am completely baffled, can anyone help?
My text is thus
"... cohomology of the base manifold. These invariants describe the obstruction to the presence of global sections, which we may interpret as a measure of the twisting of a bundle.
Today there are three main expositions of characteristic classes: Chern-Weil theory; the approach of Grothendieck; and the study of universal bundles. Each exposition has its merits and its drawbacks, and we shall not have time to present all three. We will focus initially on the Chern-Weil approach as presented in Madsen \& Tornehave \cite{Madsen} in which characteristic classes are derived by taking invariant polynomials in the curvature form, a construction well studied in differential geometry. This approach is preferred as it leads to simple proofs of the important naturality and Whitney-sum properties. We will then discuss briefly the approach of Grothendieck as presented in Bott \& Tu \cite{Bott} which deserves attention simply for its elegance. Here a class is constructed for a rank 2, oriented vector bundle, living in the cohomology of the base manifold, which is seen to pull back its information from the fibre above, counting the number of obstructions to the presence of a global section. Then, using the Leray-Hirsch theorem and some clever algebra as well as a result from cohomology, characteristic classes are derived from this for general complex vector bundles. This approach allows us to present a clear computation.
Neither of these first two expositions really address the important question of {\textit{why}} such characteristic classes..."
And here's how it is coming out!

Any ideas?
Thanks,
Adam.

A: There are several possibilitys to solve your problem.
Because you gave no MWE I created a simple one (I left out your cites, say you will see ? instead) and used package geometry to get the layout you showed in your picture. (Remark: It would be easier next time you provide such a MWE by your own, please!)
I added package showframe to show the typing area.
Then I added command \hyphenation{Gro-then-dieck} to show that only this command will give you the result you want.
But you do not need \hyphenation if you use package microtype.  Only with microtype you get in this example a proper justifing left and right without a hyphenation of Grothendieck. (Play with the margins in geometry and you will get situations that an hyphenation occurs.)
I suggest to call package microtype in all your documents.
MWE (with activated microtype; comment it and uncomment the line for hyphenation to test the other version; comment both to have your situation):
\documentclass{article}

\usepackage[margin=2.2cm]{geometry}
\usepackage{showframe}

 \usepackage{microtype}      % <=========================================
%\hyphenation{Gro-then-dieck}% <=========================================

\begin{document}
... cohomology of the base manifold. These invariants describe the
obstruction to the presence of global sections, which we may interpret
as a measure of the twisting of a bundle.

Today there are three main expositions of characteristic classes:
Chern-Weil theory; the approach of Grothendieck; and the study of
universal bundles. Each exposition has its merits and its drawbacks,
and we shall not have time to present all three. We will focus initially
on the Chern-Weil approach as presented in Madsen \& Tornehave
\cite{Madsen} in which characteristic classes are derived by taking
invariant polynomials in the curvature form, a construction well studied
in differential geometry. This approach is preferred as it leads to
simple proofs of the important naturality and Whitney-sum properties.
We will then discuss briefly the approach of Grothendieck as presented
in Bott \& Tu \cite{Bott} which deserves attention simply for its
elegance. Here a class is constructed for a rank 2, oriented vector
bundle, living in the cohomology of the base manifold, which is seen to
pull back its information from the fibre above, counting the number of
obstructions to the presence of a global section. Then, using the
Leray-Hirsch theorem and some clever algebra as well as a result from
cohomology, characteristic classes are derived from this for general
complex vector bundles. This approach allows us to present a clear
computation.

Neither of these first two expositions really address the important
question of {\textit{why}} such characteristic classes ...
\end{document}

and the result:

and with both uncommented lines you get an hyphenation in Grothendieck:


text:
Q: How to add swipe gesture to segmented control? I have an ImageView added to UIView. Tapping on the image take to Segmented Control which is also part of same UIView. I am trying to add swipe gestures to this segmented control.
Tried following.
override func viewDidLoad() {
    super.viewDidLoad()

    let rightSwipe = UISwipeGestureRecognizer(target: SegmentCotroller, action: Selector("swiped:"))
    rightSwipe.direction = .Right
    self.SegmentCotroller.addGestureRecognizer(rightSwipe)
}

func swiped(sender:UIGestureRecognizer){
    print("Swiped.....!")
}

Code never reaches to swiped method when swiping right.
Any help is appreciated!
Thanks

A: You need to se the swipe gestures target to self
let rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("swiped:"))
rightSwipe.direction = .Right
self.segmentController.addGestureRecognizer(rightSwipe)

The target sets where the action will be executed so you want it pointing at wherever you have the action implemented.


text:
Q: How to show markings on QDial in PyQt5 Python I am designing a ui in qt-desginer where I have added dial. It looks like below:

It doesn't have any markings. Is it possible to add some markings to understand it better. Something like below:

A: Unfortunately, QDial is a widget that has never been really cared about, mostly because it's scarcely used, but also because many feature needs might change its behavior in inconsistent ways. In any case, this is not possible from Designer.
It can be partially done by subclassing QDial and promoting it in designer, but you'll end up having numbers drawn over the notches or the dial itself, which will look ugly.
In order to achieve what you want, you need to use a custom widget that contains the dial, and eventually promote that widget, but you'll not be able to see it in designer nor set its properties (unless you create a Designer plugin, which is not very easy). This is achieved by setting the container layout margins, so that there's always enough space to show the values as text.
This is a possible implementation. Consider that, for obvious reasons, if you have a big value range with a small dial, the numbers will overlap.
class ValueDial(QtWidgets.QWidget):
    _dialProperties = ('minimum', 'maximum', 'value', 'singleStep', 'pageStep',
        'notchesVisible', 'tracking', 'wrapping',
        'invertedAppearance', 'invertedControls', 'orientation')
    _inPadding = 3
    _outPadding = 2
    valueChanged = QtCore.pyqtSignal(int)

    def __init__(self, *args, **kwargs):
        # remove properties used as keyword arguments for the dial
        dialArgs = {k:v for k, v in kwargs.items() if k in self._dialProperties}
        for k in dialArgs.keys():
            kwargs.pop(k)
        super().__init__(*args, **kwargs)
        layout = QtWidgets.QVBoxLayout(self)
        self.dial = QtWidgets.QDial(self, **dialArgs)
        layout.addWidget(self.dial)
        self.dial.valueChanged.connect(self.valueChanged)
        # make the dial the focus proxy (so that it captures focus *and* key events)
        self.setFocusProxy(self.dial)

        # simple "monkey patching" to access dial functions
        self.value = self.dial.value
        self.setValue = self.dial.setValue
        self.minimum = self.dial.minimum
        self.maximum = self.dial.maximum
        self.wrapping = self.dial.wrapping
        self.notchesVisible = self.dial.notchesVisible
        self.setNotchesVisible = self.dial.setNotchesVisible
        self.setNotchTarget = self.dial.setNotchTarget
        self.notchSize = self.dial.notchSize
        self.invertedAppearance = self.dial.invertedAppearance
        self.setInvertedAppearance = self.dial.setInvertedAppearance

        self.updateSize()

    def inPadding(self):
        return self._inPadding

    def setInPadding(self, padding):
        self._inPadding = max(0, padding)
        self.updateSize()

    def outPadding(self):
        return self._outPadding

    def setOutPadding(self, padding):
        self._outPadding = max(0, padding)
        self.updateSize()

    # the following functions are required to correctly update the layout
    def setMinimum(self, minimum):
        self.dial.setMinimum(minimum)
        self.updateSize()

    def setMaximum(self, maximum):
        self.dial.setMaximum(maximum)
        self.updateSize()

    def setWrapping(self, wrapping):
        self.dial.setWrapping(wrapping)
        self.updateSize()

    def updateSize(self):
        # a function that sets the margins to ensure that the value strings always
        # have enough space
        fm = self.fontMetrics()
        minWidth = max(fm.width(str(v)) for v in range(self.minimum(), self.maximum() + 1))
        self.offset = max(minWidth, fm.height()) / 2
        margin = self.offset + self._inPadding + self._outPadding
        self.layout().setContentsMargins(margin, margin, margin, margin)

    def translateMouseEvent(self, event):
        # a helper function to translate mouse events to the dial
        return QtGui.QMouseEvent(event.type(),
            self.dial.mapFrom(self, event.pos()),
            event.button(), event.buttons(), event.modifiers())

    def changeEvent(self, event):
        if event.type() == QtCore.QEvent.FontChange:
            self.updateSize()

    def mousePressEvent(self, event):
        self.dial.mousePressEvent(self.translateMouseEvent(event))

    def mouseMoveEvent(self, event):
        self.dial.mouseMoveEvent(self.translateMouseEvent(event))

    def mouseReleaseEvent(self, event):
        self.dial.mouseReleaseEvent(self.translateMouseEvent(event))

    def paintEvent(self, event):
        radius = min(self.width(), self.height()) / 2
        radius -= (self.offset / 2 + self._outPadding)
        invert = -1 if self.invertedAppearance() else 1
        if self.wrapping():
            angleRange = 360
            startAngle = 270
            rangeOffset = 0
        else:
            angleRange = 300
            startAngle = 240 if invert > 0 else 300
            rangeOffset = 1
        fm = self.fontMetrics()

        # a reference line used for the target of the text rectangle
        reference = QtCore.QLineF.fromPolar(radius, 0).translated(self.rect().center())
        fullRange = self.maximum() - self.minimum()
        textRect = QtCore.QRect()

        qp = QtGui.QPainter(self)
        qp.setRenderHints(qp.Antialiasing)
        for p in range(0, fullRange + rangeOffset, self.notchSize()):
            value = self.minimum() + p
            if invert < 0:
                value -= 1
                if value < self.minimum():
                    continue
            angle = p / fullRange * angleRange * invert
            reference.setAngle(startAngle - angle)
            textRect.setSize(fm.size(QtCore.Qt.TextSingleLine, str(value)))
            textRect.moveCenter(reference.p2().toPoint())
            qp.drawText(textRect, QtCore.Qt.AlignCenter, str(value))

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    dial = ValueDial(minimum=1, maximum=11)
    dial.setNotchesVisible(True)
    dial.show()
    sys.exit(app.exec_())


text:
Q: Proper way of using npm timepicker Laravel 5.8 I am new in installing packages in Laravel. Now, I am trying to implement timepicker from https://timepicker.co/. I already installed npm i jquery-timepicker.
What is the next thing in doing it? I always get timepicker is not a function when running this script
$(document).ready(function(){
    $('input.timepicker').timepicker({});
});

Any help is highly appreciated, thank you

A: You have to require that plugin, where you require jQuery to your application.
It has to be something like this.
window.$ = window.jQuery = require('jquery')
require('timepicker')


text:
Q: How to derive some part of the Proca lagrangian for a Vector (spin-1)? I'm trying to derive Eq. (10.17) & Eq. (10.18) from the textbook. Where does the term
-1/(4*pi) come from, and how do I cancel out the rest of the term (see my text, second picture).


text:
Q: File is not checked out Exception in Publishing Page with WebParts I have a problem with Sharepoint 2010.
When I edit a publishing page (checked in) without webparts:
1 - (Checked out the page automatically)
2 - It's all OK I can edit the page.
When I edit a publishing page (checked in) with webparts:
It crashes! :(
"Microsoft.SharePoint.WebPartPages.WebPartPageUserException:File is not checked out".
Can you help me?
Kind regards

A: To edit the page, first you must check out the page. This is only thing you need to consider before editing.


text:
Q: How to sort values with special chars in array? First, I set the proper locale to spanish:
setlocale(LC_ALL, 'es_ES');

This array holds a list of languages which must be reordered alphabetically.
$lang['ar'] = 'árabe';
$lang['fr'] = 'francés';
$lang['de'] = 'alemán';

So I do this:
asort($lang,SORT_LOCALE_STRING);

The final result is:

*

*alemán

*francés

*árabe
...and it should be:

*

*árabe

*alemán

*francés

The asort() function is sending the á character to the bottom of the ordered list. How can I avoid this issue? Thanks!
Solution linked by @Sbls
function compareASCII($a, $b) {
    $at = iconv('UTF-8', 'ASCII//TRANSLIT', $a);
    $bt = iconv('UTF-8', 'ASCII//TRANSLIT', $b);
    return strcmp($at, $bt);
}
uasort($lang, 'compareASCII');

A: Try using Collator::asort from the intl module:
<?php
$collator = collator_create('es_ES');
$collator->asort($array);

A: It is likely that the comparison checks the multibyte value of the character, and á in that case is probably greater than z, so it will show afterwards. If you want a comparison that does not take that into account, I see two possibilites:

*

*Sort using uasort and create your own comparison function.

*Generate a mapping from the ascii version of your strings, to the real one, and sort on the keys.

A: Solution linked by @Sbls in comments
function compareASCII($a, $b) {
    $at = iconv('UTF-8', 'ASCII//TRANSLIT', $a);
    $bt = iconv('UTF-8', 'ASCII//TRANSLIT', $b);
    return strcmp($at, $bt);
}
uasort($lang, 'compareASCII');