text:
Q: Why is setCustomValidity('') ignored on input (Chrome 65) Note: to the best of my knowledge this question is not a duplicate question of the following:

*

*HTML5: Why does my "oninvalid" attribute let the pattern fail?

*HTML5 form required attribute. Set custom validation message?

*How can I change or remove HTML5 form validation default error messages?

Overview
Given a field that:

*

*Has pattern attribute set for validation, for example "[a-f,0-9]{4}" for a 4 character hex string input.

*Has oninvalid set with setCustomValidity('...some message...') to define a custom validation message

*Has oninput set with setCustomValidity('') to reset on input

Here is an example showing this:

/* jshint esnext: true */
const form   = document.querySelector("#form");
const field  = document.querySelector("#field");
const output = document.querySelector("#output");

form.addEventListener('submit', (e) => {
  console.log("SUBMIT");
  output.textContent = field.value;
  e.preventDefault(); // Prevent default POST request
});

field.oninvalid = (event) => {
  console.log("INVALID");
  event.target.setCustomValidity('must be valid 4 hex characters');
}

field.oninput = (event) => {
  console.log("INPUT");
  event.target.setCustomValidity('');
}
Output: No output
<form id="form">
  Enter 4 character hex code:
  <input id="field" type="text" pattern="[a-f,0-9]{4}" autocomplete=off>
</form>

Validation works almost as desired, except when the user enters an invalid entry and then proceeds to try and edit it, where their following input states are still invalid:

At this point, neither the custom setCustomValidity message defined in oninvalid is used, nor the empty one defined in onInput.
Instead, as long as the field is in an invalid state and not blurred, the default Please match the requested format. message appears.

Question
What is going on here? Looking at the console, the oninput event is called each time, and therefore event.target.setCustomValidity(''); is called each time.
So why is it that we are still seeing the generic default validation message? Shouldn't setCustomValidity('') disable that?
An acceptable answer here should exhibit the following:

*

*The parameter field is respected for validation.

*Any validation message appears if and only if the user attempts to submit an invalid field and not when they modify the input immediately afterward.

*The default Please match the requested format. message never appears at all.

A: It appears that this is a bug with Chrome 65 in windows.
using setCustomValidity('') in oninput should disable the default validation messages appearing on input.
The following workaround works for me:

/* jshint esnext: true */
const form   = document.querySelector("#form");
const field  = document.querySelector("#field");
const output = document.querySelector("#output");

const pattern = field.getAttribute("pattern");

form.addEventListener('submit', (e) => {
  console.log("SUBMIT");
  output.textContent = `User submitted: ${field.value}`;
  e.preventDefault(); // Prevent default POST request
});

field.oninvalid = (event) => {
  console.log("INVALID");
  event.target.setCustomValidity('must be valid 4 hex characters');
}

field.oninput = (event) => {
  console.log("INPUT");
  event.target.setCustomValidity('');
  event.target.removeAttribute("pattern");
}

field.onchange = (event) => {
  console.log("CHANGE");
  event.target.setAttribute("pattern", pattern);
}
  Output: No output
  <form id="form">
    Enter 4 character hex code:
    <input id="field" type="text" pattern="[a-f,0-9]{4}" autocomplete=off>
  </form>

A: setCustomValidity is meant to be used when multiple inputs, in combination are invalid. That is why it has to be reset to the empty string manually after. Other wise the title attribute should be used.
Trying to hide the validation error after editing the input is understandable but it is against the HTML5 form philosophy. It is meant to be shown as long as the input is invalid.
Adding maxlength can help the user to not cross the upper limit.
If you really want your bullet points to be satisfied feel free to not use HTML5 form validation but something custom instead.
So the reason a tooltip is shown even when setCustomValidity is set to empty string is because the input element is still invalid as per pattern attribute.
<form id="form">
  Enter 4 character hex code:
  <input id="field" type="text" pattern="[a-f,0-9]{4}" maxlength="4" minlength="4" autocomplete="off" title="must be valid 4 hex characters">
</form>

JS
const form   = document.querySelector("#form");
const field  = document.querySelector("#field");
const output = document.querySelector("#output");

form.addEventListener('submit', (e) => {
  console.log("SUBMIT");
  output.textContent = field.value;
  e.preventDefault(); // Prevent default POST request
});

field.oninvalid = (event) => {
  console.log("INVALID");
}

field.oninput = (event) => {
  console.log("INPUT");
}


text:
Q: HTTP header weird field explanation If you look on the response header of the http://www.yale.edu, there is a field such as
Expires: Sun, 19 Nov 1978 05:00:00 GMT.

What does it stand for?
If you want to look at it yourself, just type in terminal
 curl -I http://www.yale.edu

A:
A couple of years back, this was the main way of specifying when assets expires. Expires is simply a basic date-time stamp. It's fairly useful for old user agents which still roam unchartered territories. It is however important to note that cache-control headers, max-age and s-maxage still take precedence on most modern systems. It's however good practice to set matching values here for the sake of compatibility. It's also important to ensure you format the date properly or it might be considered as expired.

taken from here
After that the response is no longer cached. See here
Also worth to look at

redpajama_set_name: RedPajamaStackExchange


text:
Q: Analysis: Approximate function using Taylor Series. Question: Find an approximation of $\sqrt(11)$ using some quadratic Taylor polynomial.  Estimate the error using Lagrange's Form of Remainder.
Attempt:
Consider $f(x)=\sqrt(1+x)$.    Taylor Series for this function around x=0 is:$1+1/2x-1/8x^2+R_2(x)$.
$R_2(x)=1/16$* $(1+c)^-5/2 x^3$ $\leq 1/16x^3$, as $c\in[0,x]$.
Thus, plugging in x=10, to find the approximation of $\sqrt(11)$ , I get:
$1+(1/2*10)-1/8*(10^2)$=$-6.5$, which is clearly wrong.
Error$\leq$ $(1/16)*(10^3)$=$62.5$
Obviously,I am doing something wrong as I'm getting numbers that don't make any sense, so I could really use some help.  Thank you.

A: $x=10$ is too far away to expect good results out of a series expansion of $\sqrt{1+x}$ about $x=0$. But you could take an expansion of $\sqrt{9+x}$ about $x=0$; then you know the first term of the expansion so you can continue.
Also, there is a way to reuse your work by writing $\sqrt{9+x}=a\sqrt{1+bx}$ for appropriate constants $a,b$.


text:
Q: Is there a Windows batch command that can copy files from a Linux server to my local machine? I have been using the following scp command:
SET cfolder=c:\temp\%currentdate%
scp -r username@servername.com:/opt/logs/test.log %cfolder%\test_K1B.log

The problem with the above is that it keeps asking for a password. Is there a way to automate this command without entering the username and/or password?
Since I am the only person running the commands and it will be on my local machine, I don't mind saving the username/password combo in a text file.
The other issue is that I don't have write access on the server. I can only read and copy files from it. Plus I don't want to mess around by logging onto the server.
My purpose is to set this up as an automated script that performs the file copy from the remote server to the temp directory.

A: You can use WinSCP scripting. WinSCP supports providing a password in its scripts (though it supports public key authentication as well).
winscp.com /ini=nul /command ^
    "open sftp://username:password@example.com/" ^
    "get /remote/path/* C:\local\path\" ^
    "exit"

WinSCP GUI can generate a batch file template like this for you.
(I'm the author of WinSCP)

A: C:\Users\ching\proj\fdGlIfFix\src\BP>pscp PS104T ching@moscow_host:/home/ching/tmp/
ching@moscow_host's password:
PS104T                    | 44 kB |  44.4 kB/s | ETA: 00:00:00 | 100%

C:\Users\ching\proj\fdGlIfFix\src\BP>pscp -i c:\users\ching\random.ppk PS104T ching@moscow_host:/home/ching/tmp/
PS104T                    | 44 kB |  44.4 kB/s | ETA: 00:00:00 | 100%

Is this what you want?
Try PuTTY's pscp and its Key Generator at
http://www.chiark.greenend.org.uk/~sgtatham/putty/
Provided having your remote server trusted your windows, i.e., have deployed the generated public key to your remote server, you specify the your private key instead of entering password.

A: I just looked up ssh scp .. 'cos i'd heard scp was quite limited.
Try SFTP.
a link summarized from google says "SFTP is a file transfer protocol similar to FTP but uses the SSH protocol as the network protocol" and "SCP is only for transferring files, and can't do other things like list remote directories or removing files, which SFTP does do"
Well, SSH lets you log in automatically(see ssh-copy-id), so as long as you can SSH automatically you should be able to SFTP fine.

A: SET cfolder=c:\temp\%currentdate%

scp -p linuxpwd -r username@servername.com:/opt/logs/test.log %cfolder%\test_K1B.log

You can use this -p option to mention the password. It is not secure way but as you said you can do this.


text:
Q: Topological sort of partial order into sorted sets Given a partial order of elements, one can use topological sorting to produce a sorted list of elements. For example, if we have the partial order A->B and A->C, then the possible topological sort results are [A,B,C] and [A,C,B].
I am interested in producing a sorted list of sets [$S_1, \ldots, S_k$] that satisfy the partial order. (The sets $S_i$ partition the elements.) Here, the requirements are:

*

*for $i = 1 \ldots k-1$, $\exists e_1 \in S_i,e_2 \in S_{i+1}$ s.t. $e_1 < e_2$

*for each set $S_i$, $\nexists e_1, e_2 \in S_i$ such that $e_1 < e_2$ or $e_2 < e_1$
In our example, the only correct sorted list of sets is [{A},{B,C}]. Given a partial order, how many possible sorted lists of sets exist? Is there a name for this kind of sorting? Any pointers are appreciated.

A: We can take $S_1$ to be the set of minimal elements, then remove those and proceed inductively. Or go in the other direction, pealing off the maximal elements first. So in any case such lists do exist.

A: EDIT: This answer was for a previous version of the question.
There is usually no such list: consider the case where some element is incomparable to everything else.


text:
Q: Increasingly long query times on stored procedure. - EXEC vs SP_EXECUTESQL I am using a stored procedure to that returns a set of rows about the data in a varbinary column. I cannot, for the life of me, figure out why the query times always increase at the same rate when I use sp_executesql as opposed to exec.
Query with sp_executesql times go: <1s, 1s, 2s, 4s, 8s, 24s (etc) until, eventually, the problem "goes away" for a few minutes and the query is always ~0.006s
Query times with exec are always <500ms.
At first, I thought this was a problem with Linq2Sql, but when we ran the query Linq produces in SQL Management Studio, we got the same result.
Here's the body of the sproc (heavily censored)
Note that the varbinary column is not being pulled
select DF.FileID,
       DF.DerpFkGuid,
       DF.DerpName,
       DF.[FileName],
       DF.FileSize as 'FileSizeBytes',
       ISNULL(DFA.File_Size_Bytes_String,'Unknown') as 'FileSizeFriendly',
       CONVERT(nvarchar(30),DF.FoundDate,120) as 'FileDateUploaded',
       CONVERT(nvarchar(30),DF.FileDateCreated,120) as 'FileDateCreated',
       CONVERT(nvarchar(30),DF.FileDateLastModified,120) as 'FileDateModified',
       CASE WHEN ISNULL(dfa.Derp_ID,'00000000-0000-0000-0000-000000000000')='00000000-0000-0000-0000-000000000000' THEN 0 ELSE 1 END as 'AttachedToDerp',
       ISNULL(dfa.Derp_ID,'{00000000-0000-0000-0000-000000000000}') as 'Derp_ID'
from DerpFiles DF
inner join DFDerpDerp DFdd      on DFdd.DerpName = DF.DerpName
left outer join Derp_Files_Attachments dfa      on dfa.FileID =  DF.FileID
where WR.UserName = @UserName and DF.DuplicateFileDetected=0

Here is the code that runs consistently  < 500ms
USE [DerpDatabase]
GO

DECLARE @return_value int

EXEC    @return_value = [dbo].[DerpSproc]
        @UserName = N'derp',
        @DomainName = N'derp'

SELECT  'Return Value' = @return_value

GO

Here is the code that runs 1s ,2s ,4s, 8s , 24s, etc
declare @p5 int
set @p5=0
exec sp_executesql N'EXEC   @RETURN_VALUE = [dbo].[DerpSproc]
                            @UserName = @p0,
                            @DomainName = @p1',
                            N'@p0 nvarchar(4000),
                            @p1 nvarchar(4000),
                            @RETURN_VALUE int output',
                            @p0=N'derp',
                            @p1=N'derp',
                            @RETURN_VALUE=@p5 output
select @p5

As far as I can tell, the 2 ways the sprocs are being called are essentially the same. The only difference is sp_executesql vs exec
It also appears that exec will produce the same increasing query times without the go keyword at the end. I can't tell for sure because I don't know if the query just happened to cache when I tried adding go?

A: This might be a parameter sniffing issue. Sometimes when you pass parameters into a procedure, SQL has a hard time figuring out how to use them efficiently. Try setting your parameters to local variables in the procedure, and then use the local variables in the where clause.
Parameter Sniffing

A: We solved our problem by moving the VARBINARY field from the files table to its own dedicated table. We cannot add a proper relationship between the file table and the metadata table without the query times going through the roof.
This only happens when we execute the query as a stored procedure. This does not happen when we do the same exact query as a view with a WHERE clause for our filters. Our mildly educated theory is that SQL Server 2012 has a bug(?) that causes the VARBINARY field in a table that we join against to be read on our query even though it's not included in our SELECT statement.


text:
Q: MySQL query optimisation when using index I'm busy to optimize and understand the group by function in MySQL. From the answer on SO i learned from Gordon:

All columns in the select should either be columns in the group by or
  use aggregate functions (sum(), avg(), and so on).

I have to following table and query
Table
+-----------------+-----------+------------+-------------+
|Id (primary key) | ip(index) | lastattack | create_date |
+-----------------+-----------+------------+-------------+

Query
  SELECT ip,
         lastattack
    FROM blacklist
   WHERE ip = 'xxx.xxx.xxx.xxx'
GROUP BY ip

When I execute the above query I receive the following info from EXPLAIN
+----+-------------+-------+------+---------------+-----+---------+-----+------+----------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------+---------------+-----+---------+-----+------+----------+-------+
| 1  | SIMPLE      | ipall | ref  | idx           | idx | 257     |const| 2    | 100.00   | Using index condition |
+----+-------------+-------+------+---------------+-----+---------+-----+------+----------+-------+

When i execute the query like Gordon told me i receive the following in extra
  SELECT ip,
         lastattack
    FROM blacklist
   WHERE ip = 'xxx.xxx.xxx.xxx'
GROUP BY ip, lastattack

Using index condition; Using where; Using temporary; Using filesort

People told me to avoid temporary or filesort.

A: Your query, as it stands, is incorrect - or rather, it is ambiguous. Suppose you have:
192.168.0.1    Attack1    2017-10-01 23:30
192.168.0.1    Attack2    2017-10-01 23:35

Which value of lastattack should be output? You do not provide enough data to the server, which can't read your mind and surmise that if the field is called "lastattack", you probably want the one with greatest timestamp.
This is what Gordon Linoff was saying - "All columns in the select should either be columns in the GROUP BY, or use aggregate functions"; here, lastattack is neither, as you do not GROUP BY lastattack (but only by IP), and you do not aggregate it (you SELECT lastattack, not AVG(lastattack) or SOME_AGGREGATE_FUNCTION(lastattack)).
You might still get the correct value - but you might not. In practice, records will be retrieved in deterministic order, and chances are that's the order you want. But other DB implementations might fetch the first value they encounter and leave you with the first attack instead of the last.
To obtain the result you want, you need first to establish the date of the last attack:
SELECT ip, MAX(attackdate) AS maxdate FROM blacklist GROUP BY ip;

This gives you a table with the correct timestamps. To get the last attack you need a JOIN (which risks duplicates if two attacks came in the same second, so that you can't determine which was the last one):
SELECT a.ip, a.maxdate, b.lastattack
    FROM (
        SELECT ip, MAX(attackdate) AS maxdate FROM blacklist GROUP BY ip
    ) AS a
JOIN blacklist AS b ON (a.ip = b.ip AND a.maxdate = b.lastattack)

You need an index on ip and attackdate for the inner query, and that should also work for the outer query. You might want to create an index on ip, attackdate and lastattack in this order to see whether that changes anything.


text:
Q: Core dump? I've gone through my program so many times don't know what is wrong I keep getting a core dump after I added my fraction reducing function gcd. It will work fine until it gets to outputting the subtraction part in my main file then it just gives me a core dump. It will work perfectly fine for numbers like 2000/3000 which it will reduce to 2/3 like it should but when I put in 10/20 for a fraction it will reduce it to 1/2 like it should until it gets to outputting the subtraction part as I said before it will just give me a core dump. What is wrong??
//Rational.h file
   #include <iostream>
   using namespace std;

   class Rational
{
  public:
    // constructors

    Rational();

    Rational(int num, int den);

    // accessors

    int get_numer()const;

    int get_denom()const;

    // mutators

    void set_numer(int n);

    void set_denom(int d);

    // friend functions

    friend Rational operator +(const Rational& r1, const Rational& r2);

    friend Rational operator -(const Rational& r1, const Rational& r2);

    friend Rational operator *(const Rational& r1, const Rational& r2);

    friend Rational operator /(const Rational& r1, const Rational& r2);

    friend bool operator == (const Rational& r1, const Rational& r2);

    friend ostream& operator <<(ostream& file_out, const  Rational& r);

    friend istream& operator >>(istream& file_in, Rational& r);

private:
   int numerator;
   int denominator;
   void normalize();
   void gcd();
};

// nonmember functions

bool operator <(const Rational& r1, const Rational& r2);

bool operator !=(const Rational& r1, const Rational& r2);

//Rational.cc file
#include <iostream>
#include <cstdlib>
#include "Rational.h"
using namespace std;

Rational::Rational()
{
  numerator = 0;
  denominator = 1;
}

Rational::Rational(int num, int den)
{
  numerator = num;
  denominator = den;

if(den == 0)
{
  cout << "Error denominator is 0\n";
  exit(1);
}

  gcd();
  normalize();
}

void Rational::set_numer(int n)
{
  numerator = n;
  gcd();
  normalize();
}

void Rational::set_denom(int d)
{
  denominator = d;

  if(denominator == 0)
  {
    cout << "Error denominator is 0\n";
    exit(1);
  }

  gcd();
  normalize();
  }

int Rational::get_numer() const
{
  return(numerator);
}

int Rational::get_denom() const
{
  return(denominator);
}

void Rational::normalize()
{
   if(denominator < 0)
   {
     numerator *= -1;
     denominator = abs(denominator);
   }
   else if(numerator < 0 && denominator < 0)
   {
     numerator = abs(numerator);
     denominator = abs(denominator);
   }
 }

void Rational::gcd()
{
  int big;
  int small;
  int remainder;
  int great;

  if(numerator > denominator)
  {
    big = numerator;
    small = denominator;
  }else{
    big = denominator;
    small = numerator;
  }

  do{
    remainder = big % small;

  if(remainder == 0)
    great = small;
  else
  {
    big = small;
    small = remainder;
  }
}while(remainder != 0);

  numerator /= great;
  denominator /= great;
}

Rational operator +(const Rational& r1, const Rational& r2)
{
  Rational temp;

  temp.numerator = r1.numerator * r2.denominator + r1.denominator * r2.numerator;
  temp.denominator = r1.denominator * r2.denominator;

  temp.gcd();
  temp.normalize();

  return(temp);
}

Rational operator -(const Rational& r1, const Rational& r2)
{
  Rational temp;

  temp.numerator = r1.numerator * r2.denominator - r1.denominator * r2.numerator;
  temp.denominator =  r1.denominator * r2.denominator;

  temp.gcd();
  temp.normalize();

  return(temp);
}

Rational operator *(const Rational& r1, const Rational& r2)
{
  Rational temp;

  temp.numerator = r1.numerator * r2.numerator;
  temp.denominator =  r1.denominator * r2.denominator;

  temp.gcd();
  temp.normalize();

  return(temp);
}

Rational operator /(const Rational& r1, const Rational& r2)
{
  Rational temp;

  temp.numerator = r1.numerator * r2.denominator;
  temp.denominator = r1.denominator * r2.numerator;

  temp.gcd();
  temp.normalize();

  return(temp);
}

bool operator == (const Rational& r1, const Rational& r2)
{
  return((r1.numerator * r2.denominator) == (r1.denominator * r2.numerator));
}

ostream& operator <<(ostream& file_out, const  Rational& r)
{
  file_out << r.numerator << '/' << r.denominator;

  return(file_out);
}

istream& operator >>(istream& file_in, Rational& r)
{
  char ch;

  file_in >> r.numerator >> ch >> r.denominator;

  if(r.denominator == 0)
  {
    cout << "Error denominator is 0\n";
    exit(1);
  }

  r.gcd();
  r.normalize();

  return(file_in);
}

bool operator <(const Rational& r1, const Rational& r2)
{
  return((r1.get_numer() * r2.get_denom()) < (r1.get_denom() * r2.get_numer()));
}

bool operator !=(const Rational& r1, const Rational& r2)
{
  return((r1.get_numer() * r2.get_denom()) != (r1.get_denom() * r2.get_numer()));
}

//main.cc file
#include <iostream>
#include "Rational.h"
using namespace std;

int main()
{
  Rational r1(1,2), r2, r3;

// test the constructors
  cout << "Testing the constructors  \n\n";
  cout << "Testing the constructor with 2 arguments " << r1 << endl << endl;

// test the overloaded >> operator
  cout << "Testing the overloaded >> operator \n";
  cout << "Enter a rational number in the form 3/4  ";
  cin >> r2;

  cout << r1 << " + " << r2 << " = " << (r1 + r2) << endl;

  // test the set functions
  r3.set_numer(23);
  r3.set_denom(-13);

  cout <<"\nTesting the set functions "<< r3 << endl << endl;

// Testing the overloaded << operator and the +
  cout << r1 << " + " << r2 << " = " << r1 + r2;
  cout << endl << endl;

//testing the overloaded - operator

  r3 = r1 - r2;

  cout << r1 << " - " << r2 << " = " << r3;
  cout << endl << endl;

//testing the * and / function

  r3 = r1 * r2;

  cout << r1 << " * " << r2 << " = " << r3;
  cout << endl << endl;

  r3 = r1 / r2;

  cout << r1 << " / " << r2 << " = " << r3;
  cout << endl << endl;

//testing the < and == function

  if(r1 < r2)
    cout << r2 << " is bigger than " << r1 << endl;
  else if(r2 < r1)
    cout << r1 << " is bigger than " << r2 << endl;
  else if(r1 == r2)
    cout << r1 << " and " << r2 << " are equal pairs\n";

//testing the != function

  if(r1 != r2)
    cout << r1 << " and " << r2 << " are not equal pairs\n";

  return 0;
}

A: Looks to me like a divide by zero risk in gcd() at remainder = big % small;.
You'll know for sure if you use a debugger to get a backtrace from the core dump.


text:
Q: MySQL Query Is Too Slow Or Times Out I am having a complete nightmare with my application. I haven't worked with datasets this big before, and my query is either timing out or taking ages to return something. I've got a feeling that my approach is just all wrong.
I have a payments table with a postcode field (among others). It has 40,000 rows roughly (one for each transaction). It has an auto-inc PRIMARY key and an INDEX on the postcode foreign-key.
I also have a postcodes lookup table with 2,500,000 rows. The table is structured like so;
postcode | country | county | localauthority | gor
AB1 1AA    S99999    E2304     X               45
AB1 1AB    S99999    E2304     X               45

The postcode field is PRIMARY and I have INDEXes on all the other fields.
Each field (apart from postcode) has a lookup table. In the case of country it's something like;
code   | description
S99999   Wales

The point of the application is that the user can select areas of interest (such as "England", "London", "South West England" etc) and be shown payments results for those areas.
To do this, when a user selects the areas they are interested, I then created a temp table, with one row, listing ALL postcodes for the areas they selected. Then I LEFT JOIN it on to my payments table.
The problem is that if the user selects a big region (like "England") then I have to create a massive temp table (or about 1 million rows) and then compare it to the 40,000 payments to decide which to display.
UPDATE
Here is my code;
$generated_temp_table = "selected_postcodes_".$timestamp_string."_".$userid;
    $temp_table_data = $temp_table
    ->setTempTable($generated_temp_table)
    ->newQuery()
    ->with(['payment' => function ($query) use ($column_values) {
        $query->select($column_values);
    }])
    ;

Here is my attempt to print out the raw query;
    $sql = str_replace(['%', '?'], ['%%', "'%s'"], $temp_table_data->toSql());
    $fullSql = vsprintf($sql, $temp_table_data->getBindings());
    print_r($fullSql);

This is the result;
select * from `selected_postcodes_1434967426_1`

This doesn't look like the right query, I can't work out what Eloquent is doing here. I don't know why the full query is not printing out.

A: if you have too many result like 1 million, then use offset limit concept. Then it will save you'r time of the query. Also make sure in you select query you are filtering required fields only.( avoid select * from XXXX. use select A, B from XXX).


text:
Q: In Corona SDK How to hide a group if application suspended? I am building a word game and I want to hide the board when application is suspended?
the code looks fine however it givs a strange behaviour!!,
when I suspend the app nothing will happen but when i resume the application then the board will hide!!
local onSystem = function( event )
    if event.type == "applicationSuspend" then
       print("suspend")
       board_group.alpha = 0
    end
end
Runtime:addEventListener( "system", onSystem )

Note: you might wonder how do I know how the application looks when suspended?
the answer is: by pressing the home button twice.
example
SpellTower in normal state
https://dzwonsemrish7.cloudfront.net/items/430k0c0b0y0b413d0b42/Image%202012.11.12%208:08:24%20AM.png?v=4822f549
SpellTower after pressing the home button twice
https://dzwonsemrish7.cloudfront.net/items/280a1y0r2U3W321y1B2z/Image%202012.11.12%208:08:31%20AM.png?v=09c37567
you can see how they are hiding the letters, this is exactly what I want to do for my game, the only difference is i am using Corona SDK

A: When you do board_group.alpha = 0 you only has set a variable, the result will only take effect after a screen update.
But since the application is suspended... it won't update! So, changing any graphics on applicationSuspend don't work.

A: I believe the reason is because the application is not considered as suspended. In normal objective c programming it means that applicationWillResignActive is called when the user double clicks on the home button. So what you want to do is to add that code for this part.
Here is a flow of events:
http://www.cocoanetics.com/2010/07/understanding-ios-4-backgrounding-and-delegate-messaging/
Corona seems to have these events:

*

*"applicationStart" occurs when the application is launched and all code
in main.lua is executed.

*"applicationExit" occurs when the user quits the application.

*"applicationSuspend" occurs when the device needs to suspend the application such as during a phone call or if the phone goes to sleep
from inactivity. In the simulator, this corresponds to the simulator
running in the background. During suspension, no events (not even
enterFrame events) are sent to the application while suspended, so if
you have code that depends on time, you should account for the time
lost to an application being suspended.

*"applicationResume" occurs when the application resumes after a suspend. On the phone, this occurs if the application was suspended
because of a phone call. On the simulator, this occurs when the simulator was in the background and now is the foreground application.

So my guess is that you have to implement it outside of the corona API.
According to the corona documents you can implement them in the delegate:

You can intercept UIApplicationDelegate events via your implementation
  of the CoronaDelegate protocol.
This protocol conforms to the UIApplicationDelegate protocol. Corona's
  internal delegate will call your protocol's method if it is
  implemented.
Please keep in mind the following:
Methods that Apple has deprecated will be ignored.
  In most cases, your class' version will be invoked after Corona's corresponding version of the UIApplicationDelegate method. There is one situation in which your version will be called before.
  In situations where the app is about to suspend or go to the background, your method will be called before Corona's version, e.g.
  applicationWillResignActive: and applicationDidEnterBackground:.

http://docs.coronalabs.com/native/enterprise/ios/CoronaDelegate.html
But this is just a guess. Hope it helps!
Edit:
I was thinking, something really simple you could do is catch it outside and present a "pause" screen, then just hide it when the application enters foreground.

A: So if you can't do that (for now), one other option is to save application state when the application is about to terminate, and then set UIApplicationExitsOnSuspend = true in your plist file. This will cause the application to exit instead of suspending, which will avoid any screenshots, effectively "hiding" the board, etc. The downfall is, the app will have to read the session state when it launches again... this is only useful if your application can be designed to actually exit without losing your state, and is quite honestly, a little extreme. That said, it may be the only way to effectively do what you're trying to do.
Other ideas would be to see if you can add a large black layer to the screen, even though the application is suspending; perhaps this will somehow trigger an internal screen update by natively setting setNeedsDisplay. Also, instead of modifying the alpha, you might consider temporarily removing all of your layers and see if that has a similar effect.


text:
Q: Express middleware with different methods (PUT/POST) on a route app.route('/ad/apply')
        .put(adController.applyAd)
        .post(notificationController.addNotification)

Above route won't work, I got error 404 not found if I added in 3rd line like that. How do I do PUT and then POST? if it's both PUT I can just do
app.route('/ad/apply')
        .put(adController.applyAd, notificationController.addNotification)

A:
Above route won't work, I got error 404 not found if I added in 3rd line like that.

To reproduce your scenario locally, I tried the following code. It didnt have any specific issues with line alignment.
'use strict';

let http = require('http');
let express = require('express');

let app = express();

let server = http.createServer(app);

const PORT = 8888;
server.listen(PORT, () => {
  console.log(`Server is up at ${PORT}`);

  app.route('/').put((req, res) => {
    return res.status(200).send({
      msg: 'hello from PUT'
    });
  }).post((req, res) => {
    return res.status(200).send({
      msg: 'hello from POST'
    });
  });

});

May be, 404 is because of some other routes taking precedence over this based on the order of declaration.


text:
Q: Under what circumstances does DirectX not paint over child windows of the window whose handle was passed to CreateDevice()? There is an interesting behaviour of DirectX where it differs between the Windows implementation (DirectX 11) and the Wine implementation under Linux.
In order to determine whether it is a bug in the Wine implementation or the program, I'd like to know where exactly this behaviour is documented, as I have not been able to find anything except "It works for Windows".
Here's the description: When drawing on a window using DirectX, it seems that any visible child window of this window is not painted over. As an example, here is the MeshViewer from the DirectX SDK's samples:
http://imageshack.us/photo/my-images/264/unbenannt2nf3.jpg/
(The main window's handle is passed as the hDeviceWindow in the present parameters in CreateDevice.) The tool bar and status bar are visible in Windows, but under Wine they are obscured by the DirectX surface:
http://i.imgur.com/WP8rd.png
I have also observed this behaviour in another application with a tool bar that creates a DirectX surface the size of the window's client area and relies on DirectX to figure out which areas to paint over. Interestingly enough, the tool bar seems to be not painted over the DirectX surface every frame (I've set a breakpoint in the tool bar's Paint handler), so my guess is that DirectX somehow figures out the position of the child windows and does not paint over them in the first place.
Is that correct and if yes, where is it documented?


text:
Q: How to use Automapper when class structure is not fully same here is sample classes
public class Person {
    public int Id{ get; set ;}
    public string FirstName{ get; set ;}
    public string LastName{ get; set ;}
    public string Email{ get; set ;}
    public string PhoneNo{ get; set ;}
    public string Sex{ get; set ;}
}

public class PersonView {
    public int Id{ get; set ;}
    public string FirstName{ get; set ;}
    public string LastName{ get; set ;}
    public string Mail{ get; set ;}
    public string Phone{ get; set ;}
    public string PostCode{ get; set ;}
}

now please see my two class structure. there few fields are same and some time fields name are bit different but same
as example Email & PhoneNo are there in PersonView but name is bit different. so in that case how to map ?
another scenario is Sex & PostCode do not exist in each other same way? so guide me how field by field mapping will be possible?
thanks

A: To map where the field names are different use need to explicitly define the mapping. Fields which are not in the destination model will be ignored (Sex in this case). Where there is a field in the destination that does not exist in the source then you could use a default value (Postcode in this case):
  Mapper.CreateMap<Person, PersonView>()
      .ForMember(pv => pv.Mail, opt => opt.MapFrom(p => p.Email))
      .ForMember(pv => pv.Phone, opt => opt.MapFrom(p => p.PhoneNo))
      .ForMember(pv => pv.PostCode, opt => opt.UseValue("Unknown postcode"));

  var viewModel = Mapper.Map<Person,PersonView>(me);


text:
Q: Is there a server-side Websocket client for node.js? I've been using socket.io to create a websocket enabled server in node.js, and its great.   Now i'd like however, to create a server-side client in node.js which can connect to a websocket server elsewhere.  Are there any libraries out there for this?
Thanks

A: https://github.com/pgriess/node-websocket-client <-- does this one work for you?
Found on this list here: https://github.com/joyent/node/wiki/modules

A: Not any that are great.
I talked to Guillermo about this on mailing list a couple days ago, see http://groups.google.com/group/socket_io/browse_thread/thread/74e9ff6d7e931f6e
I wrote this as a bootstrap to help in my testing:
https://github.com/jmoyers/mettle/blob/master/test/test-socket.coffee#L18-49
Guillermo is working on one here for 0.7:
https://github.com/LearnBoost/Socket.IO-node-client

A: I've just been working on a project with similar needs: a Node server that acts as a Socket.io server and connects to another service via proper websockets. I used the ws module for the websocket client in Node.
Do be aware that, as noted above by Josh, Socket.io is a protocol on top of web sockets.


text:
Q: How to make a more advanced responding chatbot with NLTK? I have done a lot of research on how to create chat bots (the responding part) however I can't find a way to make it more advanced. For example, I keep seeing NLTK reflections but I want to know if there are more advanced methods in NLTK (or other modules) that allow me to create a learning bot, smart bot or even an AI but I am struggling in finding modules, tutorials or documentation that help with getting started and proceeding that way. Reflections don't always work well like responding in context unless you have many lines of code pre-written for content which is inefficient and may not always be accurate. Note: I don't want to be spoon fed, I just want to be pointed in the right direction of stuff that I can do and look at.
a solution would be
e.g. user asks: "who is your favourite actor?"
bot replies with: "Brad Pitt"
(only though of Brad because of the ad astra advertisements xD)
Below is the code that I am trying to stay away from.
pairs = [
    [
        r"my name is (.*)",
        ["Hello %1, How are you today ?",]
    ],
     [
        r"what is your name ?",
        ["My name is Chatty and I'm a chatbot ?",]
    ],
    [
        r"how are you ?",
        ["I'm doing good\nHow about You ?",]
    ],
    [
        r"sorry (.*)",
        ["Its alright","Its OK, never mind",]
    ],
    [
        r"i'm (.*) doing good",
        ["Nice to hear that","Alright :)",]
    ]```

A: There are two main styles of conversational agents: retrieval and generative. The regex code you show can be thought of as a very simple retrieval model. More complicated retrieval models classify user input with a classifier (at this point, almost always a neural network). Generative models treat the input to output mapping as a machine translation problem, and use techniques from NMT, neural machine translation.
Some resources:

*

*The new verrsion of Speech and Language processing, by Dan Jurafsky and James H. Martin has three chapters on bots/question-answering

*If you are trying to build something practical, then you should use a mature library. IMO, Rasa has been leading the pack for a few years at this point

A: The code you want to stay away from used to be the very beginning of cahtbots (Eliza: https://blog.infermedica.com/introduction-to-chatbots-in-healthcare/). A good starting point is a full dialogue system. You could use for example the trindikit for python, which is basically a dialogue manager. Furthermore, you need to implement some sort of common sense reasoning database (e.g. compare Erik T Mueller: Commonsense Reasoning - An event Calculus based approach). Normally, most chatbots are focussed on a specific domain (product questions, recommender etc.), so you need to fix exactly what intentions may provoke which speech acts, classify and model them accordingly (LSTM for calssification, Bayes for production).
Upon all this you either have to build a surface realisation system or use canned text as templates, which is growing work when your domain expands more and more.


text:
Q: C#; EF database first mode I used database-first mode in EF. I need your help because I have a problem when I try to run this code:
private void btnSearch_Click(object sender, EventArgs e)
{
    string SNumber = txtSearchByNum.Text;

    var qSearchByTypeText = database.tblNote.SqlQuery("select * From tblNote Where fNumber=@t0", SNumber).ToList();
}

I get this error :

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.Entity.dll
Additional information: Must declare the scalar variable "@t0".

Could this be due to the ٍEntity Framework version?

A: you need to pass parameter like:
var qSearchByTypeText = database.tblNote.SqlQuery("select * From tblNote Where fNumber=@t0", new SqlParameter("@t0", SNumber)).ToList();

A: If you are asking for an EF6.0 "Using" statement to enclose an EF/ORM query that creates and returns a list of rows, here is what I would do:
var qSearchByTypeText = new List<Note>();  //where "Note" is a data structure that looks like a row of columns in "tblNote".

using (var myDbEntity = new [your 'Database First' Entity name]())
{
   //then your query
   qSearchByTypeText = (from n in myDBEntity.tblNotes where n.fNumber == SNumber select n).ToList();

}


text:
Q: In spotfire - html page tab view I want to implement a HTML page tab view (attached the sample image:page tab view.jpg) in the spotfire text area. On click of the menu in the Tab view, the visualization has to be shown.
Pasted the HTML, CSS and JS code below. If you save it as a html file to your desktop and open it, you could easily understand my requirement.
I know the styles can be added as part of HTML tags but i am not sure whether the level of css styles mentioned in the html code shown below can be included as part of the html tag in spotfire. also i am not sure how to pass the control from text area when clicked on a menu option and show the visualisation.
could anyone please share any video link or sample code or documentation how this is achieved in spotfire?
Page Tab View Sample Picture. Want to achieve this in Spotfire

<!DOCTYPE html>

London

Paris

Tokyo

London

London is the capital city of England.

Paris

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.


text:
Q: Laravel: Understanding which api framework to choose Our company is about to start a real estate project and have decided to go with the laravel 5.3 framework. The first phase is to write the apis and then these apis will be consumed by the mobile team and the frontend team to build the official mobile app and the web portal respectively.
Now I am confused whether to use laravel's built-in Resource controllers (as instructed in this tutorial http://www.programmableweb.com/news/how-to-build-restful-apis-using-php-and-laravel/how-to/2014/08/13) or use the Dingo Api framework.
Could you please help me which one should I go for and why as per the requirements i mentioned above?
Thanks in advance

A: Since, Laravel 5.3 comes with Passport (for api authentication), I would suggest you to use Resource controller, which is very simple and easy to work with, and also it create a meaningful end points
Route::resource('post','PostController');

GET /post/{post}
POST /post
EDIT /post/{post}/edit
DELETE /post/{post}


text:
Q: Rotating a point in spherical coordinates around Cartesian axis If I have a point in spherical coordinates, and I rotate it around one of the Cartesian axes, what will be the new spherical coordinates for the point? Both spherical and Cartesian coordinate systems have the same origin. Rotation axes go through origin as in the image below.

I'm building a mechanical device that has a camera rotating around object, and camera's relative coordinates should remain same while object rotates. I've read Wikipedia pages about transformation matrices etc, but those goes way over my head.

A: You can work with the rotation operators in $\mathbb{C}^2$. This method is well-known in quantum mechanics (rotation on the Bloch sphere).
I assume the following spherical coordinates system ($\theta$: colatitude, $\phi$: longitude):

Given the coordinate angles $(\theta, \phi)$, define a vector $Q(\theta, \phi)$ in $\mathbb{C}^2$ by
$$
Q(\theta, \phi) = \begin{pmatrix} \cos \frac{\theta}{2} \\ e^{i\phi}\sin\frac{\theta}{2}\end{pmatrix}.
$$
Conversely, given a vector $\begin{pmatrix} z_1 \\ z_2 \end{pmatrix} \in \mathbb{C}^2$, define the coordinate angles $(\theta, \phi)$ by
$$
Q^{-1}\begin{pmatrix} z_1 \\ z_2 \end{pmatrix} =
\left( 2\, \textrm{atan} \frac{\textrm{Mod}(z_2)}{\textrm{Mod}(z_1)}, \textrm{Arg}(z_2)-\textrm{Arg}(z_1)\right).
$$
Then the rotation to the angle $\alpha$ around a Cartesian axis maps the coordinate angles $(\theta,\phi)$ to the coordinate angles
$$
(\theta', \phi') = (Q^{-1} \circ R_{\textrm{axis}}(\alpha) \circ Q)(\theta,\phi)
$$
where the rotation operator $R_{\textrm{axis}}(\alpha)$ is, depending on the rotation axis:
\begin{gather}
R_x(\alpha) = \begin{pmatrix} \cos\frac{\alpha}{2} & -i\sin\frac{\alpha}{2} \\ -i\sin\frac{\alpha}{2} & \cos\frac{\alpha}{2} \end{pmatrix}, \\
R_y(\alpha) = \begin{pmatrix} \cos\frac{\alpha}{2} & -\sin\frac{\alpha}{2} \\ \sin\frac{\alpha}{2} & \cos\frac{\alpha}{2} \end{pmatrix}, \\
R_z(\alpha) = \begin{pmatrix} e^{-i\frac{\alpha}{2}} & 0 \\ 0 & e^{i\frac{\alpha}{2}} \end{pmatrix}.
\end{gather}

A: Denote rotation matrix about an axis $\omega$ and rotation angle $\theta$ by $R_\omega(\theta)$. Then the Cartesian coordinate of a point can be represented by spherical coordinates in the following way:
$$
\left[\begin{array}{c}
x\\
y\\
z
\end{array}\right]=R_z(\theta)\cdot R_y(\varphi)\cdot rz,\quad z=\left[\begin{array}{c}
0\\
0\\
1
\end{array}\right]
$$
Then rotate the point $p=(x,y,z)$ about the three coordinate axes is given by (note that $R_z(\sigma)\cdot z=z, \forall \sigma\in\mathbb R$):
$$
\begin{split}
R_x(\alpha)\cdot R_z(\theta)\cdot R_y(\varphi)\cdot rz&=R_z(\theta')\cdot R_y(\varphi')\cdot rz\\
(&=R_z(\theta')\cdot R_y(\varphi')\cdot R_z(\sigma')\cdot rz)
\end{split}
$$
$$
\begin{split}
R_y(\beta)\cdot R_z(\theta)\cdot R_y(\varphi)\cdot rz&=R_z(\theta'')\cdot R_y(\varphi'')\cdot rz\\
(&=R_z(\theta'')\cdot R_y(\varphi'')\cdot R_z(\sigma'')\cdot rz)
\end{split}
$$
and
$$
R_z(\gamma)\cdot R_z(\theta)\cdot R_y(\varphi)\cdot rz=R_z(\theta+\gamma)\cdot R_y(\varphi)\cdot rz
$$
This way, you see that for rotation about $z$, the result is immediate, and for rotation about $x$, this is the problem of transform between $YZX$ and $ZYZ$ Euler angles, and for $y$ it is between $YZY$ and $ZYZ$ Euler angles. There are ready-to-use routines for solving this problem (it might help to use quaternions to deal with the consecutive rotation if you intend to write the code yourself).


text:
Q: Mixed indexing behaviour for typedef array? I have a typedef:
typedef unsigned char MyType[2];

I pass it to a function and the result is FAIL!
void f(MyType * m)
{
*m[0] = 0x55;
*m[1] = 0x66;
}

void main(void)
{
Mytype a;
a[0] = 0x45;
a[1] = 0x89;

f(&a);
}

The manipulation of variable a in main() works on 1 byte indexing, so a is equal to {0x45, 0x89}. However in function f the indexing acts on 2 bytes (the sizeof the type).
So in function f, *m[1] in this instance is actually modifying memory out of bounds.
Why is this, what have I forgotten?
Thanks.

A: Try:
(*m)[1]

instead of *m[1]

A: Ah just worked it out after giving up! Brackets Boy, Brackets.
void f(MyType * m)
{
(*m)[0] = 0x55;
(*m)[1] = 0x66;
}

void main(void)
{
Mytype a;
a[0] = 0x45;
a[1] = 0x89;

f(&a);
}


text:
Q: ReleaseHandleFailed was detected when debugging with MSTest When I run my unit tests in debug mode, I get a recurrent exception like this:

I click  "Continue" and then the test goes on without any problem. I have to do this around 10 to 15 times per test I want to debug. If I simple RUN the test, I get no exception whatsoever.
The test does well anyway, I click "Continue" on the recurrent exception and the test ends gracefully.
The exception has no stack trace. All the information I can get about it is in that screenshot. Even if I choose to "Copy MDA message to clipboard", it is the same as appears on the screenshoot.
The test is using Entity Framework Code First, and dropping and creating the database each time.
What could be the problem? I am not using any kind of encryption, but the test connects to the SqlServer and do some operations with it.
Thanks.

A: I got to disable the warning: http://msdn.microsoft.com/en-us/library/d21c150d.aspx
But I would like to know what is going on.
Cheers.


text:
Q: Check that a key from json output exists I keep getting the following error when trying to parse some json:
Traceback (most recent call last):
  File "/Users/batch/projects/kl-api/api/helpers.py", line 37, in collect_youtube_data
    keywords = channel_info_response_data['items'][0]['brandingSettings']['channel']['keywords']
KeyError: 'brandingSettings'

How do I make sure that I check my JSON output for a key before assigning it to a variable? If a key isn't found, then I just want to assign a default value. Code below:
try:
    channel_id = channel_id_response_data['items'][0]['id']
    channel_info_url = YOUTUBE_URL + '/channels/?key=' + YOUTUBE_API_KEY + '&id=' + channel_id + '&part=snippet,contentDetails,statistics,brandingSettings'
    print('Querying:', channel_info_url)
    channel_info_response = requests.get(channel_info_url)
    channel_info_response_data = json.loads(channel_info_response.content)
    no_of_videos = int(channel_info_response_data['items'][0]['statistics']['videoCount'])
    no_of_subscribers = int(channel_info_response_data['items'][0]['statistics']['subscriberCount'])
    no_of_views = int(channel_info_response_data['items'][0]['statistics']['viewCount'])
    avg_views = round(no_of_views / no_of_videos, 0)
    photo = channel_info_response_data['items'][0]['snippet']['thumbnails']['high']['url']
    description = channel_info_response_data['items'][0]['snippet']['description']
    start_date = channel_info_response_data['items'][0]['snippet']['publishedAt']
    title = channel_info_response_data['items'][0]['snippet']['title']
    keywords = channel_info_response_data['items'][0]['brandingSettings']['channel']['keywords']
except Exception as e:
    raise Exception(e)

A: You can either wrap all your assignment in something like
try:
    keywords = channel_info_response_data['items'][0]['brandingSettings']['channel']['keywords']
except KeyError as ignore:
    keywords = "default value"

or, let say, use .has_key(...). IMHO In your case first solution is preferable

A: suppose you have a dict, you have two options to handle the key-not-exist situation:
1) get the key with default value, like
d = {}
val = d.get('k', 10)

val will be 10 since there is not a key named k
2) try-except
d = {}
try:
  val = d['k']
except KeyError:
  val = 10

This way is far more flexible since you can do anything in the except block, even ignore the error with a pass statement if you really don't care about it.

A:
How do I make sure that I check my JSON output

At this point your "JSON output" is just a plain native Python dict

for a key before assigning it to a variable? If a key isn't found, then I just want to assign a default value

Now you know you have a dict, browsing the official documention for dict methods should answer the question:
https://docs.python.org/3/library/stdtypes.html#dict.get

get(key[, default])
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

so the general case is:
var = data.get(key, default)

Now if you have deeply nested dicts/lists where any key or index could be missing, catching KeyErrors and IndexErrors can be simpler:
try:
   var = data[key1][index1][key2][index2][keyN]
except (KeyError, IndexError):
   var = default

As a side note: your code snippet is filled with repeated channel_info_response_data['items'][0]['statistics'] and channel_info_response_data['items'][0]['snippet'] expressions. Using intermediate variables will make your code more readable, easier to maintain, AND a bit faster too:
# always set a timeout if you don't want the program to hang forever
channel_info_response = requests.get(channel_info_url, timeout=30)
# always check the response status - having a response doesn't
# mean you got what you expected. Here we use the `raise_for_status()`
# shortcut which will raise an exception if we have anything else than
# a 200 OK.
channel_info_response.raise_for_status()

# requests knows how to deal with json:
channel_info_response_data = channel_info_response.json()

# we assume that the response MUST have `['items'][0]`,
# and that this item MUST have "statistics" and "snippets"
item = channel_info_response_data['items'][0]
stats = item["statistics"]
snippet = item["snippet"]

no_of_videos = int(stats.get('videoCount', 0))
no_of_subscribers = int(stats.get('subscriberCount', 0))
no_of_views = int(stats.get('viewCount', 0))
avg_views = round(no_of_views / no_of_videos, 0)

try:
   photo = snippet['thumbnails']['high']['url']
except KeyError:
   photo = None

description = snippet.get('description', "")
start_date = snippet.get('publishedAt', None)
title = snippet.get('title', "")
try:
   keywords = item['brandingSettings']['channel']['keywords']
except KeyError
   keywords = ""

You may also want to learn about string formatting (contatenating strings is quite error prone and barely readable), and how to pass arguments to requests.get()


text:
Q: Required jars for invoking an EJB on JBoss 7.1.1 I have been following the tutorial here:
https://docs.jboss.org/author/display/AS71/EJB+invocations+from+a+remote+client+using+JNDI
It has helped a lot with getting a JBoss 7.1.1 project with EJB 3.0 started. I have the server up and running fine with my EAR. The problem I'm having now is with the client. I don't think I have all the required JAR's in my classpath. I'm getting this error: http://pastebin.com/0mMBKjGJ
I found this tutorial: http://middlewaremagic.com/jboss/?p=1177
which has a list of the JAR's that should be included. Those are not the JAR's in the JBoss 7.1.1 modules folder though. Which JAR's should I be using?


text:
Q: JSON.stringify() &quot &quot caterstrophy connection.query( 'SELECT DeskName FROM desks WHERE stat = ?',["Booked"], function(err,   rows){
if(err) {
    throw err;
}else{
    try{
var toParse = new Array();
toParse = rows;
res.render('workspaces.html',{myArray : JSON.stringify(toParse)});

i have this code here which its suppose to stringify the the values inside the array called toParse and pass it to an html page. But what i get after passing the sringified array is strange strings ""["MYRESULT"["" that encloses my results.
Below is my call in the HTML page:
<script>
function myFunction(){

alert( "<%= JSON.stringify(myArray) %>" );
 }
</script>

A: It looks like your query function is retuning an array MYRESULT which contains the result set.
It would help if we could see what the query call was doing.
Try:
JSON.stringify(toParse.MYRESULT)

That is more likely to return what you are expecting
L


text:
Q: Prove that $-\psi(y) \leq c(x,y) + c(x,\bar y) - \psi(\bar y)$ In the book Optimal Transport for Applied Mathematicians, Theorem 1.37, the authors states an inequality, but I'm having trouble seeing how one shows that the inequality is indeed true.
Definition: Given a function $c:X\times Y \to \mathbb R$, we say that $\Gamma \subset X \times Y$ is $c$-cyclically monotone ($c$-CM) if for every $k \in \mathbb N$, every permutation $\sigma$ and every finite family of points $(x_1,y_1),...,(x_k,y_k) \in \Gamma$ we have
$$
\sum^k_{i=1} c(x_i,y_i) \leq
\sum^k_{i=1} c(x_i,y_{\sigma(i)})
$$
Now, assume that $\Gamma$ is $c$-CM. Then, fix $(x_0, y_0) \in \Gamma$, and define:
$$
-\psi(y) = \inf\{
-c(x_n,y) +c(x_n,y_{n-1})-c(x_{n-1},y_{n-1})+...+ c(x_1,y_0) - c(x_0,y_0) : n \in \mathbb N,
(x_i,y_i) \in \Gamma \quad  \forall i=1,...,n
\}
$$
How does one then shows that fo $(x,y) \in \Gamma$ and $\bar y \in \text{Proj}_y \circ\Gamma$, we can then write:
$$
-\psi(y) \leq - c(x,y) + c(x,\bar y) - \psi(\bar y)
$$
In the proof, the author claims that this inequality follows from the very definition of the function $\psi$. What I found odd was that since $y$ and $\bar y$ are arbitrary, then I could just swap them, obtaining the opposite inequality, and hence, I actually have an equality. Which would be kind of odd. Anyways, how can you prove this inequality? And is it actually an equality?

A: By assumption $-\psi(\bar{y})>-\infty$. Thus, there is a cycle $\Gamma':=\lbrace (x_{1},y_{1}),\dots,(x_{r},y_{r})\rbrace$ such that $-\psi(\bar{y})=-c(x_{r},\bar{y})+c(x_{r},y_{r-1})+\dots+c(x_{1},y_{0})-c(x_{0},y_{0})$. Then, considering the cylce $\Gamma'':=\Gamma'\cup\lbrace{(x,\bar{y})\rbrace}$ it follows
\begin{equation}
-\psi(y)\le -c(x,y)+\sum_{k=1}^{r+1} c(x_{k},y_{k-1})-c(x_{k-1},y_{k-1})-c(x_{0},y_{0})=-c(x,y)+c(x,\bar{y})-\psi(\bar{y}).
\end{equation}

A: Ok, so after some struggle and the help of a friend I figured what I was misunderstanding. Here is the proof:
First, note that since $\bar y \in \pi_y\circ\Gamma$, this means that $\exists \quad  \bar x : (\bar x,\bar y) \in \Gamma$. Also, note that
$\{(x,y),(\bar x, \bar y)\} \subset \Gamma$, henece
$$
-\psi(y) \leq -c(x,y) + c(x,\bar y) - c(\bar x, \bar y)
$$
Now, fix the first two terms in the inequality. Note that for any $n \in \mathbb N$ and $(x_i,y_i) \in \Gamma$ for $i \in \{0,...,n\}$, we have:
$$
-\psi(y) \leq -c(x,y) + c(x,\bar y) - c(\bar x_n, \bar y) + c(\bar x_n,\bar y)-...-c(\bar x_0,\bar y_0)
$$
We can then conclude that
$$
-\psi(y) \leq -c(x,y) + c(x,\bar y) +
\inf \{-c(\bar x_n, \bar y) +...-c(\bar x_0,\bar y_0): n\in \mathbb N
, (\bar x_i,\bar y_i) \in \Gamma \quad \forall i \in \{0,...,n\} \} \\
-\psi(y) \leq -c(x,y) + c(x,\bar y) -\psi(\bar y)
$$


text:
Q: using a batch file to run a ps1 file but hide the command prompt after start? I build a small tool with powershell and i open it through a batch-file.
Batch file has the following content :
powershell -file "D:\scripts\Powershell\xxx.ps1"

Now it opens my tool but always displays the command prompt in background. I want the CMD to be hidden after running my file.
How to achieve that? I tried -hidden  but then my programm is hidden :D
Thanks

A: Try using the START utility in your batch file, it will launch the program in a new window and allow the batch's cmd window to exit in the background.
START powershell -file "D:\scripts\Powershell\xxx.ps1"

Be aware START exhibits [potentially] unexpected behavior when the first parameter contains double quotes.
If you're using GUI elements, or external applications, and you want to hide Powershell's window, but not the GUI, try the following:
START powershell -WindowStyle Hidden "D:\scripts\Powershell\xxx.ps1"

Here's an example of how I've used batch in tandem with PowerShell GUI:
Contents of C:\call.cmd:
START "" powershell -NoLogo -WindowStyle Hidden "C:\gui.ps1"

Contents of C:\gui.ps1:
# VB Assembly GUI example
Add-Type -AssemblyName Microsoft.VisualBasic
[Microsoft.VisualBasic.Interaction]::MsgBox(
    "Do you like VB in PowerShell?",
    [Microsoft.VisualBasic.MsgBoxStyle]::YesNo,
    "Hello"
)

# Windows Forms GUI example
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.MessageBox]::Show(
    "Do you like Windows Forms?",
    "Hello",
    [System.Windows.Forms.MessageBoxButtons]::YesNo
)

# External app GUI example
& notepad.exe

Running the call.cmd batch will use START to launch PowerShell [exiting cmd] and PowerShell will hide its window, but otherwise display the GUI elements executed from the PS1 file.


text:
Q: Minimum length of last line of a paragraph There is a more or less equivalent question to this: Ensure minimal length of last line, but I absolutely need a TeX solution. I more or less stumbled upon the problem mentioned in the discussion of egreg's answer, and I'd like to see a deeper analysis just to make sure there absolutely is no working TeX solution.
Replicating Patrick's solution (insert unbrekable space between words at the end) in TeX will get really ugly.
So there I was naively saying
\parfillskip 0pt plus 100pt

in the hope this would make sure the horizontal space at the end of the last line of every paragraph was at most 100pt wide.
But witness the result of my MWE:
\documentclass[11pt]{article}

\usepackage{lipsum}

\begin{document}

\parfillskip 0pt plus 100pt

\let\opar\par
\def\par{\opar\hbox to \linewidth{\hfill\vrule width100pt height\fboxrule}}

\lipsum

\end{document}

You'll see that the 100pt are disregarded even by 'unproblematic' paragraphs. \sloppy doesn't really help either, so the problem doesn't really lie in the fact that there is not enough material to stretch out.
Here's an extreme example:

The rule indicates the point to which the last line should stretch.
Looking at the resulting box yields
.\hbox(7.60416+0.0)x360.0, glue set 2.49602
..\OT1/cmr/m/n/10.95 c
..\OT1/cmr/m/n/10.95 u
..\OT1/cmr/m/n/10.95 r
..\discretionary
...\OT1/cmr/m/n/10.95 -
..\OT1/cmr/m/n/10.95 s
..\OT1/cmr/m/n/10.95 u
..\OT1/cmr/m/n/10.95 s
..\glue 3.65 plus 1.825 minus 1.21666
..\OT1/cmr/m/n/10.95 l
..\OT1/cmr/m/n/10.95 u
..\OT1/cmr/m/n/10.95 c
..\discretionary
...\OT1/cmr/m/n/10.95 -
..\OT1/cmr/m/n/10.95 t
..\OT1/cmr/m/n/10.95 u
..\OT1/cmr/m/n/10.95 s
..\glue 3.65 plus 1.825 minus 1.21666
..\OT1/cmr/m/n/10.95 m
..\OT1/cmr/m/n/10.95 a
..\OT1/cmr/m/n/10.95 u
..\discretionary
...\OT1/cmr/m/n/10.95 -
..\OT1/cmr/m/n/10.95 r
..\OT1/cmr/m/n/10.95 i
..\OT1/cmr/m/n/10.95 s
..\OT1/cmr/m/n/10.95 .
..\penalty 10000
..\glue(\parfillskip) 0.0 plus 100.0
..\glue(\rightskip) 0.0

So I assume the glue set 2.49602 is applied to the \parfillskip glue, yielding 249.6pt, which looks more or less like what's on the screenshot.
My question is now: Is there another solution to get the intended effect in TeX?
Edit: I found that adding \usepackage[latin]{babel} will make the 'problem' go away in this case, but the real "text" I need to typeset is a list of symbols with spaces between them. They need to be spaced out in any manner such that the last line is not too short, so the real application is much nearer to the MWE I'm giving (without proper hyphenation).
Conclusion Thanks to David, my original application now works like a charm:

I think the pictograms slightly stretched out look much better than the alternative with only one pictogram in the last line!

A: \emergencystretch.3\textwidth

works for me to keep all the last lines inside the ruled area.
Alternatively you can do
 \parfillskip  100pt minus 100pt

But that works by  s t r e t ch i n g the last line only, so looks rather horrible.
Or you could do a combination of the two....

A: In one of my Glisterings columns in TUGboat (TUGboat, 28, 2, 229--232, 2007) I wrote about several different paragraph formatting methods (see www.tug.org /TUGboat/tb28-2/tb89glister.pdf). The following code is taken from that 2007 article.
\newdimen\parabout
\newdimen\about
\about=2em
\def\nottooshort{%
  \parabout=\hsize
  \advance\parabout -\about
  \leftskip=0pt plus 0pt minus 0pt
  \rightskip=\leftskip
  \parfillskip=\parabout minus \parabout
  \parindent=2em}

Following the declaration \nottooshort then the last line of paragraphs will be at least approximately \about long.

A: In my experience, automated solutions tend to produce less than ideal results. For typesetting fiction, the best solution I found was setting \linenottooshort as in \linenottooshort[5em]. However, even that created some unexpected last lines with odd spacing between the words. I finally opted for using \linebreak to decide the length of the last line of a paragraph.


text:
Q: Como eu faço para voltar a versões antigas no nodejs pelo npm? Preciso ir Node.js versão 5.10.0 para poder usar o Hospedagem do firebase

A: Basta
sudo npm cache clean -f
sudo npm install -g n
sudo n x.x.x

Aonde x.x.x é a versão que você quer
Fonte:https://www.abeautifulsite.net/how-to-upgrade-or-downgrade-nodejs-using-npm

A: No Windows você pode resolver com o gerenciador de pacotes Chocolatey:
*Partindo do princípio que você tenha o Chocolatey instalado, siga os passos abaixo:

*

*No CMD como administrador, digite o comando:
cinst nodejs.install –version [xx.xx.x] –allow-downgrade
Certifique-se de alterar xx.xx.x pelo número da versão que deseja instalar.
EX: cinst nodejs.install –version 10.16.1 –allow-downgrade

*Feche e abra novamente o CMD ou reinicie seu computador.

Fonte: Como substituir ou voltar para uma versão do Node.js


text:
Q: What's the max Windows 7 access possible to restrict tampering with single service? I'm developing an ADHD management system for myself. Without going into detail (and as silly as it may sound for a grown man to need something like this), I need to build a me-proof service to run on my Windows 7 Ultra laptop. I still need fairly complete access to the system, though.
How can I set things up so that I'm unable to "easily" (ie. within 3-5 mins without rebooting) stop the service or prevent it from running?
EDIT: I recognize that the solution here is probably some sort of pre-existing software that I need to hunt down for myself and that it would run under an admin account (w/password known by someone else) while I regularly use a limited account. The issue is that I'm a developer & regularly need more than standard user access to the machine. Here are some specifics in terms of what I tend to need to do:

*

*Install/remove programs

*Run virtual machines via vmware or virtualbox, sometimes through Vagrant

*Kill processes I've started

*Start/stop services that may not be running under my account

*Have access to most files/directories (don't regularly need access to hosts file)

...I think that covers the standards that would be too frequent for me to ask someone to type in a password.

A: You may need to go into a little bit more detail about the particular service you want to prevent from running, or protect, ect.. (without diving into the personals, of course)

A: You'll need to spend some time on this one, if you only want a select few websites blocked you'll need to edit your host file in:
    %systemroot%/system32/drivers/ect/hosts

-But this would be permanent, you would have to manually undo this everytime. It might be easier to use a timer script or series of timers, waiting to kill whatever program after however many seconds, then loop taskkill to prevent it from starting up again.

A: Investigate the different Internet filtering programs (a.k.a. content-filtering software) available. They generally have additional options like usage timers, blocking access to installed software etc.
Years ago I worked in that business and we had clients who bought the software for just this purpose, e.g. a family that had a son who got upset when seeing certain websites, so with his knowledge they used our software. That specific product is no longer on the market.
Install and manage the software on a separate administrator account, while you yourself work on a limited user account.
Once this system is set up and works like you wish:
If there is someone 'nearby' who you trust, have him/her change the admin password.
[Note that if you do that last thing, depending on the filtering program, you may not even need to use separate Win accounts, just have that person change the program password.]
Additional note: Building stuff like this yourself is hard if you want to make it tamper-proof. It is not something you can do with a bit of Windows configuration.
Added 30 June:
Another method to store the password is to take a really complicated password that you can remember, write it on a piece of paper, and keep at a different location where you can't quickly get at it, e.g. at your work location.

A: Why don't you take a leaf out of Paul Graham's book and just disconnect from the internet completely on your work computer?

...set up a separate computer for using the Internet.
I now leave wifi turned off on my main computer except when I need to
  transfer a file or edit a web page, and I have a separate laptop on
  the other side of the room that I use to check mail or browse the web.
  (Irony of ironies, it's the computer Steve Huffman wrote Reddit on.
  When Steve and Alexis auctioned off their old laptops for charity, I
  bought them for the Y Combinator museum.)
My rule is that I can spend as much time online as I want, as long as
  I do it on that computer. And this turns out to be enough. When I have
  to sit on the other side of the room to check email or browse the web,
  I become much more aware of it. Sufficiently aware, in my case at
  least, that it's hard to spend more than about an hour a day online.
And my main computer is now freed for work. If you try this trick,
  you'll probably be struck by how different it feels when your computer
  is disconnected from the Internet. It was alarming to me how foreign
  it felt to sit in front of a computer that could only be used for
  work, because that showed how much time I must have been wasting.
Wow. All I can do at this computer is work. Ok, I better work then.

http://www.paulgraham.com/distraction.html
I personally find that a bit extreme and use Leechblock instead just to limit the worst timesinking sites: https://addons.mozilla.org/en-US/firefox/addon/leechblock/


text:
Q: Paintbrush Effect in using HTML and CSS I hope that this finds everyone well.
In the following example, I was wondering if the paintbrush effect, writing kygo is feasible to do with css and HTML alone, and if not, would I be able to do this using javascript?
Example for reference:
https://dribbble.com/shots/4221064-Kygo-Landing-Concept
Thank you in advance!

A: I would choose a proper font (for example this) and add a blueish green gradient with CSS, then reveal the letters as they were painted with a clipping mask combined with CSS animation.
Here's the first step:

@import url('http://fonts.cdnfonts.com/css/magic-brush');
#kygo {
  font-family: 'Magic Brush', sans-serif;
  font-size: 250px;
  background: -webkit-linear-gradient(45deg, #a5f9b3, #66deef);
  -webkit-background-clip: text;
  -moz-background-clip: text;
  -webkit-text-fill-color: transparent;
  -moz-text-fill-color: transparent;
  animation: 3s reveal-text;
}

@keyframes reveal-text {
  0% {
    -webkit-clip-path: polygon(0 0, 10% 0, 10% 0, 0 0);
clip-path: polygon(0 0, 10% 0, 10% 0, 0 0);
  }
100% {
   -webkit-clip-path: polygon(0 100%, 10% 100%, 10% 0, 0 0);
clip-path: polygon(0 100%, 10% 100%, 10% 0, 0 0);
  }

}

KYGO


text:
Q: How to register a Boost.Geometry distance strategy for OGRPoint and OGRLineString? I am creating a wrapper that allows using OGR's classes with Boost.Geometry. So far, I've created that necessary iterator facade and registered OGR's geometry classes (OGRPoint, OGRLineString, OGRLinearRing and OGRPolygon) with Boost.Geometry.
Now, I'd like to use the OGR classes predicates such as OGRGeometry::Distance() with boost instead of those employed by Boost.Geometry (because, for example, stock Boost.Geometry 1.57.0 does not have any notion of map projections). It worked for boost::geometry::distance(OGRPoint, OGRPoint), but it does not for bg::distance(OGRPoint, OGRLineString) or any other collection of points. My guess that is because Boost.Geometry treats linestrings, rings and polygons as an ordered collection of points to iterate on, since the compiler tries to instanciate the following template:
struct boost::geometry::strategy::distance::services::default_strategy<
        boost::geometry::point_tag,
        boost::geometry::segment_tag,
        OGRPoint,                           // NOTE: Twice OGRPoint!
        OGRPoint,
        MyCode::OGRCoordinateSystemTag,
        MyCode::OGRCoordinateSystemTag, void>

The full error message is as follows:
In file included from /usr/include/boost/geometry/strategies/strategies.hpp:30:0,
                 from /usr/include/boost/geometry/geometry.hpp:43,
                 from /usr/include/boost/geometry.hpp:17,
                 from ../../../winzent/test/simulation/OGRLineStringAdapterTest.cpp:7:
/usr/include/boost/geometry/strategies/distance.hpp: In instantiation of 'struct boost::geometry::strategy::distance::services::default_strategy<boost::geometry::point_tag, boost::geometry::segment_tag, OGRPoint, OGRPoint, Winzent::Simulation::boost::OGRCoordinateSystemTag, Winzent::Simulation::boost::OGRCoordinateSystemTag, void>':
/usr/include/boost/geometry/algorithms/detail/distance/default_strategies.hpp:57:8:   required from 'struct boost::geometry::detail::distance::default_strategy<OGRPoint, OGRLineString, boost::geometry::pointlike_tag, boost::geometry::linestring_tag, false>'
/usr/include/boost/geometry/algorithms/detail/distance/default_strategies.hpp:73:8:   required from 'struct boost::geometry::detail::distance::default_strategy<OGRLineString, OGRPoint, boost::geometry::linestring_tag, boost::geometry::pointlike_tag, true>'
/usr/include/boost/geometry/strategies/distance_result.hpp:60:8:   required from 'struct boost::geometry::resolve_strategy::distance_result<OGRLineString, OGRPoint, boost::geometry::default_strategy>'
/usr/include/boost/geometry/strategies/distance_result.hpp:79:8:   required from 'struct boost::geometry::resolve_variant::distance_result<OGRLineString, OGRPoint, boost::geometry::default_strategy>'
/usr/include/boost/geometry/strategies/distance_result.hpp:199:8:   required from 'struct boost::geometry::distance_result<OGRLineString, OGRPoint, boost::geometry::default_strategy>'
/usr/include/boost/geometry/strategies/distance_result.hpp:205:8:   required from 'struct boost::geometry::distance_result<OGRLineString, OGRPoint, void>'
/usr/include/boost/geometry/strategies/default_distance_result.hpp:35:8:   required from 'struct boost::geometry::default_distance_result<OGRLineString, OGRPoint>'
/usr/include/boost/geometry/algorithms/detail/distance/interface.hpp:392:1:   required by substitution of 'template<class Geometry1, class Geometry2> typename boost::geometry::default_distance_result<Geometry1, Geometry2>::type boost::geometry::distance(const Geometry1&, const Geometry2&) [with Geometry1 = OGRLineString; Geometry2 = OGRPoint]'
../../../winzent/test/simulation/OGRLineStringAdapterTest.cpp:71:62:   required from here
/usr/include/boost/geometry/strategies/distance.hpp:97:456: error: no matching function for call to 'assertion_failed(mpl_::failed************ (boost::geometry::strategy::distance::services::default_strategy<boost::geometry::point_tag, boost::geometry::segment_tag, OGRPoint, OGRPoint, Winzent::Simulation::boost::OGRCoordinateSystemTag, Winzent::Simulation::boost::OGRCoordinateSystemTag, void>::NOT_IMPLEMENTED_FOR_THIS_POINT_TYPE_COMBINATION::************)(mpl_::assert_::types<OGRPoint, OGRPoint, Winzent::Simulation::boost::OGRCoordinateSystemTag, Winzent::Simulation::boost::OGRCoordinateSystemTag>))'
     BOOST_MPL_ASSERT_MSG

So I tried to provide a template specialization specifically for struct boost::geometry::detail::distance::default_strategy<OGRPoint, OGRLineString, boost::geometry::pointlike_tag, boost::geometry::linestring_tag, false>, but with no luck --- the same error message prevails.
This is my code:
namespace boost {
    namespace geometry {
        namespace detail {
            namespace distance {

                template <>
                struct default_strategy<
                        OGRPoint,
                        OGRLineString,
                        pointlike_tag,
                        linestring_tag,
                        false>
                {
                    typedef OGRPointToLineStringDistanceStrategy type;
                };
            } // namespace distance
        } // namespace detail
    } // namespace geometry
} // namespace boost

How can I "intercept" the template instanciation that leads to the usage of the iterator/range concept and use OGRGeometry::Distance() directly?

A: It turned out that the problem wasn't related to OGR and Boost using two different algorithms. Instead, it was my adapter code that was to blame. More specifically, the iterator facade I wrote in order to adapt OGRLineString, OGRLinearRing and ultimately OGRPolygon to the Boost.Geometry code. I posted a question as soon as I recognized the issue: Create a well-behaved iterator for a write-to-pointer API.
My currently working (and final) version is available as a GitHub project. Perhaps somebody finds it useful.


text:
Q: Dependency Injection not working When Interface is given as parameter This is my Controller class
@Controller
public class HomeController{

    @RequestMapping("/")
    public String home(MyTest test){
        test.draw();
        return "homePage";
    }
}

on passing MyTest(Interface) as parameter to home method ,Spring does not inject its implementation class, instead throws an exception
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/spring-mvc-demo] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: No primary or default constructor found for interface com.managers.MyTest] with root cause
java.lang.NoSuchMethodException: com.managers.MyTest.<init>()
    at java.lang.Class.getConstructor0(Unknown Source)
    at java.lang.Class.getDeclaredConstructor(Unknown Source)
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:209)
    at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:84)
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:132)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:124)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:161)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:131)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:870)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1686)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

But on passing directly the implementation class i.e MyTestImpl it works fine .
@RequestMapping("/")
    public String home(MyTestImpl test){
        test.draw();
        return "homePage";
    }

Can you please tell the reason of Exception here in case of Interface.
Below is MyTest implementation class
@Component
public class MyTestImpl implements MyTest{

    @Override
    public void draw() {
        System.out.println("inside test");

    }
}

Spring.xml
<context:component-scan base-package="com.controllers,com.ManagerImpl" />
    <mvc:annotation-driven/>
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>

A: The way you are doing is completely wrong.  Here is a working code,
@Controller
public class HomeController{
  private final MyTest test;

   @Autowired
   public HomeController(MyTest test) {
      this.test = test;
   }

   @RequestMapping("/")
   public String home(){
      test.draw();
      return "homePage";
   }
}

Arguments to the methods anntotated with @RequestMapping should/will come in the form Pathvariable or RequestParams or just HttpServletRequest object itself. That is not how you autowire the instances.
Dependency Injection works on Constructor, Field and Interface level. Not at a method parameter level. Hope its clear.

A: First of all, i'd like to point out that you are mixing different terminlogies.
Autowiring is as previously stated is a core concept of spring. As previously stated, @Autowire should be done on setters for non config beans*, here is the relevant phrase :

Marks a constructor, field, setter method or config method as to be autowired by Spring's dependency injection facilities.

Secondly, here you are trying to inject a bean (@Component) into a MVC Controller and more specifically an interface of thus bean.
If you look closely at the documentation (here), you can see that Spring supports various parameters and will try as best as it can to pass them to your controller method.
The problem here is that Spring has no way of knowing what to pass to your method.
When the controller is called, spring will see that this parameter falls into the last category, ie Any other argument :
If a method argument is not matched to any of the above, by default it is resolved as an @RequestParam if it is a simple type, as determined by BeanUtils#isSimpleProperty, or as an @ModelAttribute otherwise.
Thus spring will consider this as a @ModelAttribute, but it cannot know how to map it as an interface cannot be instantiated, hence your error.
Now depending on your problem, either you :
Autowire your bean or interface as a member of your @Controller, ex :
@Controller
public class HomeController{

    //might need @Qualifier if more than one implementation
    @Autowire
    private MyTest test;

    @RequestMapping("/")
    public String home(){
        test.draw();
        return "homePage";
    }
}

or pass your implementation to your method controller.

*Although i haven't found anything clear in the spring documentation that states what clearly is a config method, i'm pretty sure that does not apply to @Controller methods.

A: Is your componentscan value covers the package where interface resides. Use @Autowired annotation for injection.

A: What you are doing is correct, except you need to tell Spring how to de-serialize your interface (i.e. which concrete class implementation is expected. If you use JSON serialization (usual Spring default) in your MyTest implementation add the following annotation
    @JsonDeserialize(as=MyTestImpl.class)
    public interface MyTest  {
    ...

Also assuming that you are using Post method change your Controller to:
@PostMapping(value = "/",
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String home(MyTest test){
        test.draw();
        return "homePage";
    }

("produces" param may of course be text/html or whatever you return)


text:
Q: Operation table for A+B where + denotes the operation of symmetric difference If someone could please verify if my operation table in the picture below is correct it'd be much appreciated.
The task was  given:

$P_D=\{A: A \subset D\}$ and $D$ is a $3$-element set $D=\{a, b, c\}$  with the operation of symmetric difference defined as $A+B=(A-B) \cup (B-A)$. Write all the elements of $P_D$ and then write the operation table for $(P_D, +)$.

I got a little befuddled in doing this because I'm relatively new to dealing formally with sets, and I had trouble thinking of a, b, and as sets because in the previous problem it used A, B instead. Also, it was a little trickier with 3 sets and some simplified nicely while others did not...so I wasn't sure if that's okay or if I was perhaps doing something wrong or if you're only supposed to simplify to a certain point when doing an operation table (I didn't show my work here though...its on other pages and much messier).
I apologize for the small print and messy handwriting, but I think it's readable enough and I'd already re-written it several times so I thought that was good enough (I have trouble "organizing" my math).

A: In general, in operation tables you're supposed to simplify until each entry looks like one of the elements in the group, so you're probably expected to simplify more in most of them.
You're missing the curly brackets around each element of $P_D$; the power set of $D$ contains subsets of $D$, and $a$ is not a set, but $\{a\}$ is. This might be why you're having trouble simplifying them.

I'll write three of the simplifications to illustrate:
\begin{align} \{a\} &\triangle \{b\} = (\{a\}\setminus \{b\}) \cup (\{b\} \setminus \{a\}) = \{a\}\cup \{b\}=\{a,b\} \\
\{a,b\} &\triangle \{a,c\} = (\{a,b\}\setminus \{a,c\}) \cup (\{a,c\} \setminus \{a,b\}) = \{b\}\cup \{c\}=\{b,c\} \\
\{a,b\} &\triangle \{c\} = (\{a,b\}\setminus \{c\}) \cup (\{c\} \setminus \{a,b\}) = \{a,b\}\cup \{c\}=\{a,b,c\}
\end{align}
The rest are similar. (Feel free to ask about this if it's confusing.)
You could compute all the others like this, or you could realize that the symmetric difference of two sets $X$ and $Y$ is the set containing all the elements that are in $X$ or in $Y$ but not in both: $$ X \triangle Y = (X \setminus Y) \cup (Y \setminus X) = (X \cup Y) \setminus (Y \cap X)  ,$$ so, since the sets are small, you could find the symmetric differences by inspection, by removing any elements that  $X$ and $Y$ share and collecting the rest.

It would also save you a lot of work to show that the operation is commutative, because then you could compute only what's above the diagonal and complete the rest by symmetry.


text:
Q: Netbeans - Use correct JRE for debugging on Kubuntu I know this question has been asked before, but the solutions do not work.
I've installed a new jdk 1.8 and configured it as platform.  In netbeans.conf I've configured  netbeans_jdkhome="/home/niklas/Java/jdk1.8.0_65/".
using update-alternatives I've configured the new jre for java. java -version correctly returns "java version "1.8.0_65"
Nevertheless running my project from inside netbeans it does not load, instead the "javafx requires newer version" error appears.
When I run exactly the same project with java -jar it runs correctly.
What did I forget to configure?

A: After long try-and-error here my solution:
the standard ubuntu package seems not to contain javafx. Therefore netbeans has to be installed from netbeans downloadpage.
Step-by-step solution:

*

*Uninstall netbeans (e.g. sudo apt-get remove netbeans)

*Download netbeans-8.1-javase-linux.sh

*Run sh netbeans-8.1-javase-linux.sh --javahome /[PATH_TO_JDK]/jdk1.8.0_[VERSION]   (note that this installer fails without warning if you use [PATH_TO_JDK]/jre/)

*Edit [INSTALLATION_DIR]/etc/netbeans.conf

*Make sure netbeans_jdkhome="[PATH_TO_JDK]" points to the right path (it didn't in my case.) and has no # before

note that the "All"-linux installer from the downloadpage is broken today (11.11.2015). Maybe this will be fixed soon.


text:
Q: Use high resolution local video but limit video size in WebRTC connection I'm developing a website for a one on one webrtc video call on mobile browsers. I also support the capturing of photos on the local stream. For the photo capture I use ImageCapture api where available, and drawing to canvas elsewhere.
The problem is that I want the video to be HD resolution 1280x720 (to reduce the bandwith needed for the call) while I need to capture the photos at 1920x1080.
What I do now is that before I capture the photo I apply constraints and set the resolution to Full HD and after capturing it I set the resolution back to HD. What happens sometimes is because of the change in resolution, the photos are not focused since the camera has to refocus.
So if I want higher resolution photos I see 2 options, of which I already tried the first one:

*

*I tried having 2 separate MediaStreamTracks, one with resolution of 1280x720 that I was sending through the WebRTC connection, and one with resolution of 1920x1080 that I used to display it locally and capture the photos. This worked well on most phones, but there were some phones where one track had the video but the second track didn't work at all (it didn't display any video) (specifically iPhone 6s)

*If possible I would only use one MediaStreamTrack with the resolution of 1920x1080 and I would limit the video size within the connection itself so it would send the lower resolution through the WebRTC connection.

So my question is, is it possible to locally use higher resolution video and then limit the video size sent through WebRTC connection to reduce bandwith usage?

A:
is it possible to locally use higher resolution video and then limit the video size sent through WebRTC connection to reduce bandwith usage?

Yes, use scaleResolutionDownBy, a parameter of RTCRtpSender that does just this (except in iOS)
This parameter, originally aimed at multi-layer (simulcast) transmissions, works just fine on a single encoding as well. It's a ratio, and you set it with setParameters. There's also a maxBitrate you can control directly:
const sender = pc.addTrack(cameraTrack);

async function setParams(height, bitrate) {
  const ratio = sender.track.getSettings().height / height;

  const params = sender.getParameters();
  params.encodings[0].scaleResolutionDownBy = Math.max(ratio, 1);
  params.encodings[0].maxBitrate = bitrate;
  await sender.setParameters(params);
}

See my blog for a working demo.
Browser bugs and caveats
Unfortunately, browsers have various bugs and different stages of support around this feature:

*

*Safari implements maxBitrate but not scaleResolutionDownBy which always shows as 1.

*Firefox supports both, but still uses an early version of setParameters that needs some tweaks.

We work around this by adding a minor tweak for Firefox, and by falling back to using track.clone and applyConstraints to downscale in Safari:
// With workarounds for Firefox and Safari

const sender = pc.addTrack(cameraTrack.clone()); // Note we clone the track

async function setParams(height, bitrate) {
  const ratio = sender.track.getSettings().height / height;

  const params = sender.getParameters();
  if (!params.encodings) {
    params.encodings = [{}]; // Firefox workaround
  }
  params.encodings[0].scaleResolutionDownBy = Math.max(ratio, 1);
  params.encodings[0].maxBitrate = bitrate;
  await sender.setParameters(params);

  // Safari fallback
  if (sender.getParameters().encodings[0].scaleResolutionDownBy == 1) {
    await sender.track.applyConstraints({height});
  }
}

Here's a tweaked version of the earlier demo that should work in all browsers, including Safari on macOS.
Note: Once Safari adds native support for scaleResolutionDownBy the fiddle should pick up on the new functionality. Until then you'll unfortunately run into the same limitation on iOS you're experiencing now.
Note: Safari 14 supports scaleResolutionDownBy natively (but unsure about iOS).


text:
Q: Attach font icon to last word in text string and prevent from wrapping I want to attach a Font Awesome icon to the last word in a text string:
foo bar●

But if a line wrap is required, I want the icon to attach to the last word and have them wrap together:
foo
bar●

My problem is very similar to:
Prevent :after element from wrapping to next line
However, the solution assumes I have access to the last word. In my case, the text will be generated dynamically. Is there a css/html-only way to ensure the icon wraps with the last word?
Here's a jsfiddle.

A: Interestingly enough, I found you only need to change one line of code for this to work.
Testing on your .container2 element in jsFiddle, change this
.container2:after {
    font-family: FontAwesome;
    content: "\f111";
    display: inline-block;
}

to
.container2:after {
    font-family: FontAwesome;
    content: "\f111";
    display: inline;
}

It seems to work with any width I set the container to and will stay connected to what ever foo will be.

A: You can use negative margin the width of the icon and css transform. Here a fiddle how to do :

    .container {
        width: 50px;
    }
    .icon-circle {
        background:black;
        height:10px;
        width:10px;
        display: inline-block;
        margin-left:5px;
    }
    .ANSWER{
        display:block;
        padding-right:15px; /* width of the icon */
    }
    .ANSWER .icon-circle{
        margin-left:-10px;
        transform:translate(15px);
    }

What we want

        foo bar

What happenned

        foo bar

The answer

        foo bar

Have a nice day!

A: I just wanted to point out why the change that @Unmocked provided actually works, and it has to do with the difference between display: inline and display: inline-block.
To explain, here's a little background on the difference between block display and inline display.
Block Display
block elements, in general, are elements which cause layout. They receive their own bounding box, and have the ability to push other elements around to some degree in order to fit into the space available within the browser's rendering area. Examples of block items include: h1, p, ul, and table. Note that each of these items, by default, starts a new line and also ends its own line when closed. In other words - they fit into a block of text by creating their own paragraph-level section.
Inline Display
inline elements, in general, are displayed in-line with the text. In other words, they are designed to display with-in the line of text. Examples include i, b, or span. Note that each of these items, by default, continues with the flow of its surrounding text, without forcing a newline before or after itself.
Enter the mid-way case...
Inline-Block Display
inline-block is a hybrid of the above two. In essence, an inline-block element starts wherever its preceding text leaves off, and attempts to fit into the flow of the document inline. However, if it reaches a point where it needs to wrap, it will drop to a new line, as if it were a block element. Subsequent text will then continue immediately following the inline-block element, and continue wrapping as normal. This can lead to some strange situations.
Here is an example, to show what I mean. To see it in action, check out this cssdesk snippet.

In your example, you were setting the :after pseudo-element to be display: inline-block - which meant that when it happened to extend past the right-most boundary of the wrapping display, it acted like the light-blue text in the example - and wrapped, as a block. When you instead change the :after element to display: inline, it causes it to act just like any other text - and without whitespace between it and the preceding letters, the word-wrap acts as you wanted it to.
I hope this helps!
Note: The other thing which changed between your original fiddle and the updated one is the elimination of white-space around the text.
In the first fiddle, your HTML looks like:

    foo bar

While the browser doesn't display the spaces before and after the text, it does contain the spaces, and when the :after element is rendered, it is as if this is happening:

 foo bar :after

The browser compresses the multiple spaces into single spaces, but still puts a space between the word "bar" and the :after element. Just like a space between any other words, this will cause the wrap to occur after "bar" but before :after at a certain width.
In the second fiddle, you are using:

foo bar

foo bar

In this case, because there are no spaces trailing the "foo bar" strings, the browser renders the :after element displayed immediately following the end of the content string. It is as if this is happening:

foo bar:after

No break in inline-rendered text means no break.
For an example demonstrating this, please see this update to your jsFiddle.