text:
Q: How to access SSH from web without connecting from client I have a server which is behind a firewall and the SSH port is disabled.
I want to access via SSH to monitor services on a server. My web server is Apache Tomcat. How can I achieve this? is there any java application for this?

A: There are 2 Solutions(which you may combine together too!):

*

*Web-Terminals:There are many "web based terminals" written in different languages, i'm not sure which one simply runs on Apache Tomcat, but i'm sure there are some written in Java like WebTerm or JCTerm.

*Tunnels: You could also try "TCP over HTTP Tunnels".
I believe a good way to start is to take a look at this comparison of these Tools by AnyTerm.


text:
Q: Identifying X-Y coordinates from a raster I need to find the high and low values of multiple raster datasets individually. Then determine the x,y location of these values.  I am using ArcGIS 10.1, have built the mosaic datasets I need, and have determined the locations of the high and low values (estimations are fine).  However I cannot determine the X,Y location for these values (points).
I know there is a "Find x-y" tool, but I need the opposite.  Is there a way to point click and return the x-y for that location?
With vector data I could populate a field with x-y values, however I do not have the time to cut out the raster datasets individually and turn them into vector data to do this.
There must be another way?

A: You could use Get Raster Properties to determine min and max values.  Then a conditional statement in raster calculator will create a raster of these values.  These cells can then be converted to points.
This can easily be implemented in Model Builder or a python script to save time whenever this needs to be done.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is any difference between bitwise copy and shallow copy? With respect to the question What is the difference between memberwise copy, bitwise copy, shallow copy and deep copy? author of first answer says:

Shallow Copy
Refers to copying just the immediate members of an object, without
duplicating whatever structures are pointed by them. It is what you
get when you do a bit-wise copy.

Why are we having 2 terms used for same thing as Bitwise copy and Shallow copy. Is there really no difference between them?
Does the same apply for other languages (not just C++) and can I use these words interchangeable generally?

A: A bit-wise copy is a shallow copy but not necessarily vice versa.
The reason is that due to padding there can be bits in objects that you usually ignore, yet they are part of an object.
For example this
struct bar {
    int x;
    foo b;
};

Can lool like this in memory:
| x | some padding | b | more padding |

When you copy the bits via eg memcpy then the padding bits will be copied as well. By comparing the members x and b you cannot tell the difference, but at the level of bits there is a difference. You can notice it when you compare two objects bit wise (instead of member-wise).

As pointed out by Yakk - Adam Nevraumont in a comment, padding is not the only reason why a shallow copy can differ from a bitwise copy. For example
struct foo{
    foo* self;
    foo() : self(this) {}
    foo& operator=(const foo& other) {}
    foo(const foo& other) : self(this) {}
};

The member self should point to the object itself, thats an invariant of the class (proper encapsulation omitted for the sake of simplicity). Just copying the pointer would make self->this point to other not to this, hence break the invariant. The operator= does not have to copy anything and a copy constructor merely has to properly initialize self. This can be considered as a shallow copy, because we are only "copying" the pointer self not what it points to (and actually a deep copy would be fatal here). However, a bitwise copy would be different, it would cause a.self point to b after copying b to a (which again would break the invariant).

Consider this example:
#include <iostream>
#include <cstring>

struct X {
    int a = 1;
    double b = 2;
    float c = 3;
    X& operator=(const X& x){
        a = x.a;
        b = x.b;
        c = x.c;
        return *this;
    }
};

int main()
{
    X a;
    X b;
    std::cout << "sizeof(X) " << sizeof(X) << "\n";
    std::cout << "sizeof(int) " << sizeof(int) << "\n";
    std::cout << "sizeof(double) " << sizeof(double) << "\n";
    std::cout << "sizeof(float) " << sizeof(float) << "\n";

    //memcpy(&a,&b,sizeof(X));
    a = b;
    char* aptr = reinterpret_cast<char*>(&a);
    char* bptr = reinterpret_cast<char*>(&b);
    for (size_t i = 0; i < sizeof(X); ++i) {
        if (aptr[i] != bptr[i]) std::cout << " !!! ";
    }
}

Possible output is:
sizeof(X) 24
sizeof(int) 4
sizeof(double) 8
sizeof(float) 4
 !!!

The size of X is not the sum of the size of its members. That is padding. For more details I refer you to Struct padding in C++.
The operator= does a member-wise copy. Because the object contain bytes that are not used for the members, you can observe a difference between a and b after copying the members and looking at the bit representation.
On the other hand, if the copy was made via memcpy then the bit representation of a and b would be guaranteed to be identical (ie no output !!!).

A: If I understand correctly, a bitwise copy is a shallow copy. A bitwise copy is simply copying over each bit to create a copy, while a shallow copy is more general in copying the immediate members as said in your quote.


text:
Q: Derivative of Lagrangian with respect to a vector Sometimes to find an equation of motion, the Lagrangian is derivated with respect to the (position) vector. How can this be possible?

A: We can take the derivative with respect to each component of the vector and then assemble that list of results into another vector (the gradient). In other words, $\partial L/\partial \vec x$ is sometimes used as an abbreviation for the quantity $\vec\nabla L$ with components $\partial L/\partial x_i$.
To be more careful, we should distinguish between covariant and contravariant vectors (or between vectors and one-forms), but those distinctions are probably beside the point of the question.


text:
Q: Parsing a datetime string in python containing micro and milliseconds? How do I parse a datetime string that looks like:
2015-11-01 10:10:00 00:10:00

So far I have:
date_object = datetime.datetime.strptime(line, '%Y-%m-%d %H:%M:%S %f')

But then I get an error,
ValueError: unconverted data remains: :10:00

And this is because it is not sure what to do with the rest of the datetime string because there is more than just microseconds there. Any ideas? Thanks!


text:
Q: MySQL Greater Than IN Currently I'd have to write a query like this
SELECT * FROM table WHERE value1 > 5000 OR value2 > 5000 OR value3 > 5000 OR value4 > 5000

As you can see, the 5000 is compared to all of those columns. Ideally, you'd be able to write a query like this
SELECT * FROM table WHERE 5000 GREATER(value1,value2,value3,value4)

I know you can do
SELECT * FROM table WHERE 5000 IN(value1,value2,value3,value4)

But that tests for equality, not greater than.
Is there a way to do what I'm looking for?

A: You could do:
SELECT *
FROM table
WHERE greatest(value1, value2, value3, value4, value5) > 5000 ;

As a note, this is not exactly the same.  If any of the values are NULL this will return NULL, which is treated as false.  The version with or will skip NULL values.


text:
Q: cross-browser element onresize (HTML / JS) I know that IE supports the onresize event for any element while FireFox supports it for the window object only.
Since I need that functionality for any modern browser I am currently using a (fairly fast) interval timer that continuously checks the clientWidth/clientHeight of an element to emulate the onresize. Of course this is very inefficient and I'd like to know if there is a cross-browser way that does this. Or, alternatively, different methods that work in Firefox/WebKit/IE so that the timer-method can be used as a fallback for remaining browsers.
Targeting at plain JavaScript, instead of jQuery / Prototype etc.

A: If you don't want to use jQuery then you must check what browser sends to your's script, so:
if(!element.onresize != null) element.onresize += event;
if(!element.onresizeAnotherHandler != null) element.onresizeAnotherHandler += event;

I don't know is it that easy, but it is a general concept.
EDIT: It looks like there is not event handler for Firefox. But there is an trick:

*

*If you are changing width in your's JS just create an function update
function update(var nx, var ny){
    // do something with nx and ny
}

*If you added an resize handle using CSS do it using JavaScript

*If you are using something like 80% in your's CSS then handle window.onresize:
function resize(){
    alert(document.getElementById("test").style.width);
}

window.onresize = resize;
It looks that there is no other way.


text:
Q: Is android ViewModelStore a dependency injector Hi? How should I perceive androids architecture component ViewModelStore does it invalidate the need to inject ViewModels using a dependency injection library?

A: ViewModels are intimately tied to Activities or Fragments, things with an Android Lifecycle. Because they are so closely tied to these objects they have functions, features and needs that a dependency injection library does not provide. The most important feature a ViewModel provides is the ability to retain its state on configuration changes but not on separate launches of the Activity, which is what developers need most of the time. When you need state which is saved between separate launches of an activity, that's when you employ a database layer, such as the Room Persistence Library.
So the simple answer is YES. It is best to use
ViewModelProviders.of(activity).get(MyViewModel.class)

to instantiate and lookup your view models.

A: ViewModelStore is not at all related to dependency injection of ViewModel. It is a container of ViewModel objects of a particular owner. You can get ViewModelStore of an activity or fragment by using of method of ViewModelStores.
  ViewModelStore vms = ViewModelStores.of(this);

ViewModelStore gives you control over life time of viewmodel objects of a particular owner if you need.


text:
Q: How to resolve ssl issue in ionic3 filetransfer? I'm facing an issue while trying to use the IONIC Cordova File Transfer plugin to upload a file while the laravel Server is running in HTTPS.
I'm able to login to the application and access all APIs from the server with get and post, but when I try to use fileTransfer for uploading data I'm getting the below message.
body: null
code: 3
exception: "java.security.cert.CertPathValidatorException: Trust anchor for certification path not found."
http_status: null
source: "content://com.android.providers.media.documents/document/image%3A16679"
target: "https://reddyflix.com/api/profile/photo/update"

I have dowloaded the (.cer) certificate file into the www directory of the project and setSSLCertMode = pinned. But I am still facing this issue.
let options: FileUploadOptions = {
httpMethod: "post",
chunkedMode: false,
fileKey: 'file',
fileName: 'name.png',
headers: headers
};
let trustAllHosts = true;
fileTransfer.upload(
uri,encodeURI('https://domain/api/profile/photo/update'), options,trustAllHosts)
.then((data) => {
console.log(data);
}, (err) => {
console.log(err);
})


text:
Q: Multiple TextBox and ComboBox Search in Windows Form Application C# using MS-Access I am having trouble in creating multiple TextBox and ComboBoxsearch.
I used the following Query first:
SELECT p.property_id, p.property_name, s.type_name, p.property_purpose, p.property_price, p.area, p.bedrooms, p.property_location, c.customer_name, c.customer_mobile1
FROM (tb_property AS p INNER JOIN lk_tb_property_type AS s ON p.property_type_id=s.property_type_id) INNER JOIN tb_customer AS c ON p.customer_id=c.customer_id
WHERE ([@propertyType] Is Null Or s.type_name Like '%'+[@propertyType]+'%') And ([@propertyPurpose] Is Null Or p.property_purpose Like '%'+[@propertyPurpose]+'%') And ([@area] Is Null Or p.area Like '%'+[@area]+'%') And ([@bedrooms] Is Null Or p.bedrooms Like '%'+[@bedrooms]+'%') And ([@price] Is Null Or p.property_price Like '%'+[@price]+'%') And ([@buidName] Is Null Or p.property_name Like '%'+p.property_name+'%') And ([@location] Is Null Or p.property_location Like '%'+[@location]+'%');

When which when I am running in query wizard in MS-Access, what it is doing is when I dont pass any parameter to it i.e all parameters null it displays all contents. And the moment I pass single parameter it ain't giving me anything, just displays blank table.
And the moment I use this query using CommandText and pass the parameters using Parameters.Add I am getting error that one or more parameter is missing.
Can anybody provide me the solution that what is the way of doing search in MS-Access DB
I have used the same type of query in SQL Server which gives proper results.
I am using the following c# code:
string propertyType = combo_prop_type.Text;
if (propertyType == "Select Property Type")
{
    propertyType = null;
}
else
{
    propertyType = combo_prop_type.Text;
}

string propertyPurpose = combo_purpose.Text;
if (propertyPurpose == "Select Property Purpose")
{
    propertyPurpose = null;
}
else
{
    propertyType = combo_prop_type.Text;
}

string area = combo_area.Text;
if (area == "Select Area")
{
    area = null;
}
else
{
    area = combo_area.Text.ToString();
}

string bedrooms = combo_bedrooms.Text;
if (bedrooms == "Select Bedrooms")
{
    bedrooms = null;
}
else
{
    bedrooms = combo_bedrooms.Text.ToString();
}

string price = combo_price.Text;
if (price == "Select Price")
{
    price = null;
}
else
{
    price = combo_price.Text.ToString();
}

string buidName = txt_build_name.Text.Trim();
string location = txt_location.Text.Trim();

OleDbConnection con = new OleDbConnection(constr);
OleDbCommand cmd = new OleDbCommand();

cmd.Connection = con;
cmd.CommandText = "select p.property_id, p.property_name, s.type_name, p.property_purpose, p.property_price, p.area, p.property_location, c.customer_name, c.customer_mobile1  from ((tb_property p INNER JOIN lk_tb_property_type s ON p.property_type_id = s.property_type_id) INNER JOIN tb_customer c ON p.customer_id = c.customer_id) WHERE (@propertyType is null or s.type_name like '%' + @propertyType + '%') and (@propertyPurpose is null or p.property_purpose like '%'+ @propertyPurpose +'%') and (@area is null or p.area like '%'+ @area +'%') and (@bedrooms is null or p.bedrooms like '%'+ @bedrooms +'%') and (@price is null or p.property_price like '%'+ @price +'%') and (@buidName is null or p.property_name like '%'+ @buildName +'%') and (@location is null or p.property_location like '%'+ @location +'%')";
cmd.Parameters.Add("@propertyType", OleDbType.VarChar, 50).Value = propertyType;
cmd.Parameters.Add("@propertyPurpose", OleDbType.VarChar, 50).Value = propertyPurpose;
cmd.Parameters.Add("@area", OleDbType.VarChar, 50).Value = area;
cmd.Parameters.Add("@bedrooms", OleDbType.VarChar, 50).Value = bedrooms;
cmd.Parameters.Add("@price", OleDbType.VarChar, 50).Value = price;
cmd.Parameters.Add("@buildName", OleDbType.VarChar, 50).Value = buidName;
cmd.Parameters.Add("@location", OleDbType.VarChar, 50).Value = location;
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{

    for (int j = 0; j < 9; j++)
    {
        dataGridView2.Rows.Add(new DataGridViewRow());
        dataGridView2.Rows[i].Cells[j].Value = ds.Tables[0].Rows[i][j].ToString();
    }
}
con.Close();

I have also searched that IFF() or COALESCE() or NZ() are the following functions to use when we need to send default value but for COALESCE() i am getting undefined function in MS-ACCESS and when I am using IFF the OR condition that when user provides nothing to the to the TextBox or ComboBox its showing nothing into the DataGrid. Its only working when user provides atleast some value to every TextBox or ComboBox

A: You can not reference the same parameter twice in the query sentence. Because every time it refers a new parameter!

MSDN - OleDbCommand.Parameters
The OLE DB .NET Provider does not support named parameters for passing
  parameters to an SQL statement or a stored procedure called by an
  OleDbCommand when CommandType is set to Text. In this case, the
  question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which
  OleDbParameter objects are added to the OleDbParameterCollection must
  directly correspond to the position of the question mark placeholder
  for the parameter in the command text.

Instead you will have to build the query and dynamic parameters according to your UI mode.
like this:
string propertyType = combo_prop_type.Text;
if (propertyType == "Select Property Type")
{
    propertyType = null;
}
else
{
    da.SelectCommand.CommandText += " AND s.type_name LIKE ? ";
    da.SelectCommand.Parameters.Add("", "%" + combo_prop_type.Text + "%");
}


text:
Q: htaccess rewrite working but not all rules These are my rules in .htacces file.
Options -MultiViews

# Turn Rewrite Engine On
RewriteEngine on

# Rewrite for login.php
RewriteRule ^Login login.php [NC,L]

# Rewrite for myaccount.php
RewriteRule ^Myaccount myaccount.php [NC,L]

# Rewrite for index.php
RewriteRule ^Home index.php [NC,L]

# Rewrite for post-images.php?post=xxxx
 RewriteRule ^Postimages/([0-9a-zA-Z_-]+) post-images.php?post=$1 [NC,L]

All rules are working fine but the last one. post-images.php pages is perfectly working if i directly use the url but not with rewriteurl. its showing
Not Found
The requested URL /PostImages/135 was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

A: Mmh, I tried to edit your RewriteRule and edited it to make this rule:
RewriteRule ^Postimages/(.*)$ http://www.yourwebsite.com/post-images.php?post=$1 [R=301,L]

It works for me, would u mind trying it?


text:
Q: Have Windows add the current date to a filename during the save process Is it possible to pass a variable in along with a Windows input box for filename?  I'd like the variable to be the current date.  The best way I can describe this is..think of the window that comes up whenever you choose "SAVE AS" in Windows. In addition to typing out the name of the file that I want, I also want the current date with the filename; I don't neeed it formatted in any an exact way.  I just need the current date as part of the filename.

A: You may not need to do anything. After the file-save-as dialog box returns, it returns the file name selected by the user. You can do whatever you want with that file name before actually saving it to disk.
But if you need to do a customization in place while the dialog is visible, I think you want a Windows common dialog box extension.  This is a code hook that allows you to customize the standard Windows file open (or file save) dialog within your own code.
The most obvious example of a file open dialog extension is the one written for Notepad. From the File menu in Windows Notepad, select, "Open... or "Save...".  You can see the "Encoding" combobox at the bottom of this dialog.

Your dialog extension can basically hook most of the events while the file-open dialog box is open.  You can add additional control, get notified of when buttons are getting pressed, open/close notifications, and I think you can override the filename selected as well.


text:
Q: Create new list (or numpy.array) with a named list (or numpy.array) I have a name list, and I want to construct a new list of the same type of data inside the list. How can I do it? What if it is a numpy array?
x=[1,2,3,4]
newx=[x,5,6]
[[1, 2, 3, 4], 5, 6]

#numpy
y=np.array([0,1,2,3,4])
newy=[y,5,6]
[array([0, 1, 2, 3, 4]), 5, 6]

Desired output
[1, 2, 3, 4, 5, 6]

A: For mere Python lists you do:
x = [1, 2, 3, 4]
x += [5, 6]
>>> [1, 2, 3, 4, 5, 6]

and for numpy-arrays:
x = np.array([1, 2, 3, 4])
x = np.concatenate((x, np.array([5, 6])))
>>> np.array([1, 2, 3, 4, 5, 6])

Mind the double parentheses in np.concatenate, since the arguments must be passed as a tuple.


text:
Q: Incorrect Parsed Date My code:
DateFormat format = new SimpleDateFormat("dd/MM/YYYY");

Date Today = format.parse(today);
Date Date = format.parse(date);

difference = (Date.getTime() - Today.getTime()) / 86400000;
Math.abs(difference);
System.out.println(String.valueOf("date" + date));
System.out.println(String.valueOf("date" + Date));
System.out.println(String.valueOf("date" + today));
System.out.println(String.valueOf("date" + Today));

The output:
date29/11/2016
dateSun Dec 27 00:00:00 GMT+08:00 2015
date20/11/2016
dateSun Dec 27 00:00:00 GMT+08:00 2015
I have problems while parsing the date, the original date is 29/11/2016, however when parsed, the date becomes Sun Dec 27 00:00:00 GMT+08:00 2015.
This problem appears in my whole program whenevr it's related to date.

A: Format dd/MM/YYYY should be dd/MM/yyyy. See javadoc of SimpleDateFormat: y = Year, Y = Week year. – Andreas 12 mins ago
Thanks resolved.

A: I know you got your solution from Andreas' comment already. What I want to do here is take a step back and suggest a few improvements to your code. Feel free to ignore.

*

*Most importantly I suggest you throw the long outdated classes Date, DateFormat and SimpleDateFormat overboard and start using their modern replacements. These came out in the java.time package early in 2014. These also offer a much more straightforward and clear way of calculating the difference.

*Follow the convention that says that a variable name begins with a lowercase letter. Specifically, in the same source file to use a class called Date and two variable called date and Date is bound to cause confusion.

*Like Henry I also think you intended difference = Math.abs(difference);.

*Your calls to String.valueOf() are superfluous and just seem to make the code a bit harder to read. Drop them.

For the sake of the example, in the code I suggest below, I am deliberately using your incorrect date format pattern string, dd/MM/YYYY.
    DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/YYYY");

    LocalDate todayAsLocalDate = LocalDate.parse(today, format);
    LocalDate dateAsLocalDate = LocalDate.parse(date, format);

    difference = ChronoUnit.DAYS.between(todayAsLocalDate, dateAsLocalDate);
    difference = Math.abs(difference);
    System.out.println("date " + date);
    System.out.println("date " + dateAsLocalDate);
    System.out.println("date " + today);
    System.out.println("date " + todayAsLocalDate);
    System.out.println(difference);

As the code stands now, it throws a java.time.format.DateTimeParseException: Text '20/11/2016' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {WeekBasedYear[WeekFields[SUNDAY,1]]=2016, MonthOfYear=11, DayOfMonth=20},ISO of type java.time.format.Parsed. When the code is incorrect, I much prefer an exception over an incorrect result that might go unnoticed. So this is better than what SimpleDateFormat gave you.
While the message is not easy to read, the bit to notice is WeekBasedYear. Week-based years are only useful with week numbers, you intended none of that. If you compare with the documentation, you will see that uppercase Y in the pattern is week-based-year while lowercase y is year-of-era. So let's correct:
    DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy");

Now the code prints:
date 29/11/2016
date 2016-11-29
date 20/11/2016
date 2016-11-20
9

We note one final advantage of the modern classes: you can have a date without a time-of-day when this is what you need, again giving code that models your requirements more precisely and thereby leaves less room for confusion.
Question: can I use the modern classes with my Java version?
If using at least Java 6, you can.

*

*In Java 8 and later the new API comes built-in.

*In Java 6 and 7 get the ThreeTen-Backport library, the backport of the new classes (that's "ThreeTen" for JSR 310, where the modern API was first defined).

*On Android, use the Android edition of ThreeTen-Backport. It's called ThreeTenABP, and I think that there's a wonderful explanation in this question: How to use ThreeTenABP in Android Project.


text:
Q: `\Hy@raisedlink` block hyphenation and perturbate line breaking the \Hy@raisedlink (used because of what explaned in this  answer: https://tex.stackexchange.com/a/17138/7712) seems make trouble with hyphenations.
Cf this MWE
 \documentclass[a4paper]{book}
\usepackage[a4paper]{geometry}
\usepackage{polyglossia,fontspec,hyperref}
\setmainfont{Linux Libertine O}
\setmainlanguage{greek}

\makeatletter
\newcommand\test{6. Καὶ δὴ τῷ κράτει
    \edtext{τοῦ} \edtext{συγγενέος} \edtext{ἐπιθαρσήσας}, \edtext{οὐμενοῦν}
    \edtext{εἴ τι}
καὶ \edtext{δέοι}
παθεῖν
δείσας
καλὴν ἑαυτῷ
τῆς εἰς Χριστὸν πίστεως, τὴν ἐν
    \edtext{Γράμματι}
νομοθεσίαν,
ὑποβάθραν
    \edtext{προύθηκεν}.
    \edtext{Περιτυχὼν}
γὰρ
    \edtext{τῶν}, \edtext{Μωσαικῶν}
    \edtext{βιβλίων},
καὶ
    \edtext{τῆς Ἐβραίων ἁπάσης Γραφῆς},
καὶ τούτοις ὡς μάλιστα φιλομαθῶς
    \edtext{ἐναπασχολήσας}τὸν νοῦν, καὶ
    \edtext{ὅλος}
    \edtext{ὅλῳ}
στοιχειωθεὶς,}

\begin{document}

\section{Good}
\def\edtext#1{#1}
\test

\section{Bad}
\def\edtext#1{\Hy@raisedlink{}#1\Hy@raisedlink{}}

\test

\section{Better}
\def\edtext#1{\Hy@raisedlink{}\hspace{0pt}#1\Hy@raisedlink{}\hspace{0pt}}

\test

\section{Ok?}
\def\edtext#1{\Hy@raisedlink{}\hspace{0pt}#1\Hy@raisedlink{}}

\test

\end{document}

The \edtext without \Hy@raisedlink produce good hyphen / , not with \Hy@raisedlink. The version suggested by @Ulrike Fischer are better, but not so good. Idealy, all line should be as in example 1, without \Hy@raisedlink{}.

A: I have asked the same question on a french website, http://texnique.fr.
One user (@unbonpetit) provides me a good answer. I recopy it here.
The problem comes with the penalties added by \Hy@raisedlink. The solution of adding \hspace{0pt} as proposed by @UlrikeFischer is not good, as it creates new node for line breaking, and can produce thing bad like horizontal space after a comma at the end of line.
So, the only solution see by @unbonpetit is too create a new macro \Hy@raisedlink@left, similar to \Hy@raisedlink but to be called at the begin (left) of a word. It use \llap to not perturbate spacing and breaking.
\documentclass[a4paper]{book}
\usepackage[a4paper]{geometry}
\usepackage{polyglossia,fontspec,hyperref,xcolor}
\setmainfont{Linux Libertine O}
\setmainlanguage{greek}

\makeatletter
\def\Hy@raisedlink@left#1{%
    \ifvmode
        #1%
    \else
        \Hy@SaveSpaceFactor
        \llap{\smash{% \llap{ added
        \begingroup
            \let\HyperRaiseLinkLength\@tempdima
            \setlength\HyperRaiseLinkLength\HyperRaiseLinkDefault
            \HyperRaiseLinkHook
        \expandafter\endgroup
        \expandafter\raise\the\HyperRaiseLinkLength\hbox{%
            \Hy@RestoreSpaceFactor
            #1%
            \Hy@SaveSpaceFactor
        }%
        }}% } to close \llap
        \Hy@RestoreSpaceFactor
        \penalty\@M\hskip\z@
    \fi
}

\newcommand\test{6. Καὶ δὴ τῷ κράτει
    \edtext{τοῦ} \edtext{συγγενέος} \edtext{ἐπιθαρσήσας}, \edtext{οὐμενοῦν}
    \edtext{εἴ τι} καὶ \edtext{δέοι} παθεῖν δείσας καλὴν ἑαυτῷ
    τῆς εἰς Χριστὸν πίστεως, τὴν ἐν \edtext{Γράμματι} νομοθεσίαν,
    ὑποβάθραν \edtext{προύθηκεν}. \edtext{Περιτυχὼν} γὰρ \edtext{τῶν},
    \edtext{Μωσαικῶν} \edtext{βιβλίων}, καὶ \edtext{τῆς Ἐβραίων ἁπάσης Γραφῆς},
    καὶ τούτοις ὡς μάλιστα φιλομαθῶς \edtext{ἐναπασχολήσας}τὸν νοῦν, καὶ
    \edtext{ὅλος} \edtext{ὅλῳ}
στοιχειωθεὶς,}

\begin{document}

\section{Good}
\def\edtext#1{#1}
\test

\section{Bad}
\def\edtext#1{\Hy@raisedlink@left{}#1\Hy@raisedlink{}}
\test

\end{document}

See the original answer


text:
Q: character stops after second key pressed is lifted I'm taking input from the arrow keys and moving a character accordingly on a 2D canvas game in JavaScript.
When I press two keys, I want special things to happen like moving diagonally and stopping.
These special things do happen, however there is a glitch when I lift up the second key that was pressed down: my character stops moving.  This doesn't happen, though, if I lift the first key pressed and keep the second key pressed.  In that case, my character continues in that direction.  Why does this occur??
Here is a snippet of the function:
//both up and down keys pressed, character should stop
if(Keys.up && Keys.down){
    character.y -= 10;
    character.y += 10;
}
else if(Keys.down){
    character.y += 10;
}
else if(Keys.up){
    character.y -= 10;
}

Also, I am taking the input from onkeydown and onkeyup events and storing them in an object called Keys.  (e.g. Keys[e.keyCode] = true )
When the key is pressed, that key's boolean value is true.  When lifted it is false.

A: To move diagonal, you need an x component, not just a Y. So you need a listener for both x and y.
Also, for this, why not just do (instead of forcing the client to do the calculations for no reason):
if(Keys.up && Keys.down){
    return;
}

Also, when you add the X component, dont use "else if" - just use "if" as you want to be able to capture more than one input at a time to move diagonally.
Should look something like:
if(Keys.up && Keys.down){
    return;
}
if(Keys.down){
    character.y += 10;
}
if(Keys.up){
    character.y -= 10;
}
if(Keys.left){
    character.x -= 10;
}
if(Keys.right){
    character.x += 10;
}

You can also do interpolation using CSS animation to move between the positions in order to make the movement smoother (and not jump 10px each button press).


text:
Q: Glow around objects in AFM image (amplitude modulation mode) I have made an AFM scan (Amplitude modulation mode) of a sample consisting of polyethylene in a matrix of polystyrene. I have tried to figure out why there appears a 'glow' around the domes of polyethylene. I am also interested in knowing why the dark edge appears on the left side of the image. The reason why it only appears on the left side is likely because the sample had a slight inclination, with the left side slightly higher than the right side.
Can anyone give an explanation of the glow and the dark edges?


text:
Q: recyclerView on android Studio RecyclerView recyclerView = findViewById(R.id.recyclerView);
                recyclerView.setHasFixedSize(true);
                recyclerView.setLayoutManager(new LinearLayoutManager(NoticeMngActivity.this));
                RecyclerView.Adapter mAdapter = new noticeListAdapter(NoticeMngActivity.this, noticeList);
                recyclerView.setAdapter(mAdapter);

I did this code in the main activity and there was error
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
This error pointed to
    public int getItemCount() {
    return noticeset.size();
}

But I checked noticeList size is 4 by log.d()...before passing to Adapter. why doesn't it work....
And there was more error above this error
E/RecyclerView: No adapter attached; skipping layout
I'm stuck with this problem a day....
This Adapter.java
public class noticeListAdapter extends RecyclerView.Adapter<noticeListAdapter.NoticeViewHolder> {
private Activity activity;
private ArrayList<notice> noticeset = null;

public static class NoticeViewHolder extends RecyclerView.ViewHolder{
    public CardView cardView;
    public NoticeViewHolder(CardView v){
        super(v);
        cardView = v;
    }
}

public noticeListAdapter(Activity activity, ArrayList<notice> noticeset){
    this.activity = activity;
    noticeset = noticeset;
}

@NonNull
@Override
public NoticeViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    CardView cardView = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_notice, parent, false);
    final NoticeViewHolder noticeViewHolder = new NoticeViewHolder(cardView);
    cardView.setOnClickListener(view -> {
        Intent resultIntent = new Intent();
        resultIntent.putExtra("ProfilePath", (CharSequence) noticeset.get(noticeViewHolder.getAdapterPosition()));
        activity.setResult(Activity.RESULT_OK, resultIntent);
        activity.finish();
    });
    return noticeViewHolder;
}

@Override
public void onBindViewHolder(@NonNull NoticeViewHolder holder, int position) {
    CardView cardView = holder.cardView;
    TextView titletextView = cardView.findViewById(R.id.titletextView);
    TextView datetextView = cardView.findViewById(R.id.datetextView);
    titletextView.setText(noticeset.get(position).gettitle());
    datetextView.setText(noticeset.get(position).getdate());
}

@Override
public int getItemCount() {
    return noticeset.size();
}

And this is main
public class NoticeMngActivity extends AppCompatActivity {
private ListView listView;
private noticeListAdapter adapter;
private List<notice> noticeList = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_notice_mng);
    Intent intent = getIntent();
    Button writeBtn = findViewById(R.id.writeButton);
    writeBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {//Write버튼 누르면 writeactivity로 이동
            Intent intent = new Intent(getApplicationContext(), NoticeWriteActivity.class);
            startActivity(intent);
        }
    });
    createNoticeGroups();
}

private void createNoticeGroups()
{
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    db.collection("notice").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if(task.isSuccessful()){
                final ArrayList<notice> noticeList = new ArrayList<>();
                for(QueryDocumentSnapshot document : task.getResult()){
                    noticeList.add(new notice(document.getData().get("title").toString(),
                            (ArrayList<String>)document.getData().get("content"),
                            document.getData().get("date").toString()));
                    //Log.d("로그:", "데이터 : "+document.getData().get("title").toString());
                }

                RecyclerView recyclerView = findViewById(R.id.recyclerView);
                recyclerView.setHasFixedSize(true);
                recyclerView.setLayoutManager(new LinearLayoutManager(NoticeMngActivity.this));
                RecyclerView.Adapter mAdapter = new noticeListAdapter(NoticeMngActivity.this, noticeList);
                recyclerView.setAdapter(mAdapter);
            } else{
                Log.d(TAG, "Error getting documents: ", task.getException());
            }
        }
    });


text:
Q: Jenkins filter branches empty I'm using Jenkins v 1.601 with git and gitlab plugin and gitLab as a repository manager. I want to trigger build only when push occurred to specific branch. I have enabled gitlab CI and added project url. In jenkins job configuration I want to select only specific branch in filter branches part, but that field is empty. How can I fix it?
As a side note that might be helpful, there is token field in gitlab CI service, but I can't find any way to use it in jenkins.

A: I found out the answer after checking out gitlab plugin docs. In order to have jenkins see project branches in the job configuration, you need to get your account token from gitlab and add it in jenkins configure system page gitlab plugin. After that, you have to add that account to the project in gitlab (even as guest will suffice) and then in jenkins job configuration you will be able to see branches from the repo.
As for the token field in gitlab project ci settings according to docs:

For Token put any random string (This is not yet functioning)


text:
Q: Flat file read- line to columns R I have a .txt file with the following data:
PSAP_Agency

Public Safety

Char(120)

PSAP_ID

Pitney Bowes

Integer

I need to read this in R with the structure:
column      desc           type
PSAP_Agency Public Safety  Char(120)
PSAP_ID     Pitney Bowes   Integer

How do I do this?

A: Considering your text file has the data in sequences of 3 lines with empty lines between them:
PSAP_Agency

Public Safety

Char(120)

PSAP_ID

Pitney Bowes

Integer

The following code reads data from the file and transforms it to the desired data frame structure:
text_file_name <- "text.txt" #path to the text file
number_of_columns <- 3
txt <- readLines(text_file_name)
txt <- txt[txt != ""] #removing empty lines
lst <- split(txt, as.integer(gl(length(txt), number_of_columns, length(txt))))
df <- as.data.frame(do.call(rbind, lst))
names(df) <- c("column", "desc", "type")
print(df)

Hope it helps! :)


text:
Q: Drag & Drop Json into Chrome I'm looking for a way to drag&drop a json file into chrome and extract it's info.

A: You can use a combination of HTML5 Drag & Drop and FileReader API to read the file:
var dnd = new DnDFileController('body', function(files) {
  var f = files[0];

  if (!f.type.match('application/json')) {
    alert('Not a JSON file!');
  }

  var reader = new FileReader();
    reader.onloadend = function(e) {
    var result = JSON.parse(this.result);
    console.log(result);
  };
  reader.readAsText(f);
});

DnDFileController is from http://html5-demos.appspot.com/static/filesystem/filer.js/demos/js/dnd.js and just sets up the correct DnD event listeners on the element you pass in as the selector.
See http://jsbin.com/oqosav/2/edit

A: Here's minimal working code that is self-contained, without external dependencies:
function dropJSON(targetEl, callback) {
    // disable default drag & drop functionality
    targetEl.addEventListener('dragenter', function(e){ e.preventDefault(); });
    targetEl.addEventListener('dragover',  function(e){ e.preventDefault(); });

    targetEl.addEventListener('drop', function(event) {

        var reader = new FileReader();
        reader.onloadend = function() {
            var data = JSON.parse(this.result);
            callback(data);
        };

        reader.readAsText(event.dataTransfer.files[0]);
        event.preventDefault();
    });
}

dropJSON(
    document.getElementById("dropTarget"),
    function(data) {
        // dropped - do something with data
        console.log(data);
    }
);

The code doesn't contain any sanity checks or error handling.


text:
Q: CodeIgniter Remove index.php with .htaccess I've been working on this for an hour already so I figured I might as well ask.
I am trying to remove the index.php from my CodeIgniter app's URL and can not do it.
The app is running on a dedicated server in my office and I access the app through the url http://smr_local
This is my base virtual host block
<VirtualHost 192.168.1.90:80>
    ServerAdmin admin@server.com
    DocumentRoot "/var/www/smr.dev/app"
    ServerName smr_local
    ErrorLog "/etc/httpd/logs/error_log"
    CustomLog "/etc/httpd/logs/access_log" common
    <Directory /var/www/smr.dev/app>
        Order allow,deny
        Allow from all
        AllowOverride All
    </Directory>
    <IfModule mod_rewrite.c>
        RewriteEngine on
    </IfModule>
</VirtualHost>

Here is my .htaccess file
RewriteEngine on
RewriteBase /
# Hide the application and system directories by redirecting the request to index.php
RewriteRule ^(application|system|\.svn) index.php/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [QSA,L]

And my config file
$config['base_url']    = "http://smr_local/";
$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI';

Right now when I'm trying to access my base url http://smr_local/user/courses I get an error in my apache error log I get this.
File does not exist: /var/www/smr.dev/app/user

I really don't know what to try next. Any help would be appreciated.

A: Have you checked official user guide?
example.com/index.php/news/article/my_article

You can easily remove this file by using a .htaccess file with some simple rules. Here is an example of such a file, using the "negative" method in which everything is redirected except the specified items:
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

In the above example, any HTTP request other than those for index.php, images, and robots.txt is treated as a request for your index.php file.

I have been working with Codeigniter previously and that is how I get it to work:
Here is my .htaccess (assuming you have default folder structure):
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    # Removes access to the system folder by users.
    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    # Prevents user access to the application folder
    RewriteCond %{REQUEST_URI} ^application.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    # Checks to see if the user is attempting to access a valid file,
    # such as an image or css document, if this isn't true it sends the
    # request to index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    ErrorDocument 404 /index.php
</IfModule>

That is relevant part of config.php:
$config['base_url'] = '';
$config['index_page'] = '';
$config['uri_protocol'] = 'AUTO';
$config['url_suffix'] = '';

If this won't help, your problem likely in Apache configuration.
Then provide your httpd.conf and any other relevant configurations, not only virtual-hosts.


text:
Q: Variadic template specialization with const reference How to specialize variadic template function that has const reference for an argument?
Example:
template<typename T, typename... Args>
T foo(Args... args) = delete;

template<> int foo(int a, const char* str, const Test& t) { .... } // Fails to compile
//template<> int foo(int a, const char* str, Test ) { .... } // Ok

int main() {

    auto i = foo<int>(10, "test string!", t);
    return 0;
}

When invoking function foo with declared const Test&argument, the compiler fails to see specialized function and fallbacks to deleted function:
 error: use of deleted function 'T foo(Args ...) [with T = int; Args = {int, const char*, Test}]'
     auto i = foo<int>(10, "test string!", t);

The above code compiles fine if I remove const reference from argument. What am I doing wrong?
The code can be found here

A: This is because the template arguments which the primary template deduce for your call are int, const char*, and Test, not const Test&. This means that your specialization is not used because the template arguments don't match the parameters.
Your simplest option is to provide a separate overload rather than a specialization:
template <typename T>
T foo(int a, const char* str, const Test& t) { /*...*/; }

Live demo

A: Automatic template deduction is not smart enough to guess that you want it to set the last template parameter to const Test& instead of Test. More exactly type deduction always remove cv qualifiers from a type.
You new explicit template instantiation here:
auto i = foo<int, int, const char *, const Test&>(10, "test string!", t);


text:
Q: Django - How to redirect users without hard-coding URLS I am creating Django Application. We want user to be redirected to new screen on button click, but we don't want to have to hardcode URL.
We have a top level screen, and we want to redirect user to screens after they click a button on the Level screen, However, we have multiple level screens so it would't make sense to hardcode each URL for each section of the Level screen.
Here is the view for the Level1 Screen as an example:
def level1(request):
    return render(request, 'Levels/level/Welcome1.html')

As you can see, we render out  Welcome1.html, however, we also have other Welcome screens assosiated with level 1, like Welcome2.html and Welcome3.html.
This is the URL for level 1:
path('levels/level1/', views.level1, name = "level1")

Again, it would't make sense for us to have a URL for each level (level 1, level2) and then all the subscreens for them such as Welcome1, Welcome2.
How can I make it so I can associate different screens with a URL and not have to render them out individually?
I am not sure how to go about doing this problem. We are working on big project and can give part of budget to someone who helps solve.

A: Django has a "parser" which allows you to define dynamic links within the urls.py
A dynamic url can for example be a way to access different pictures in the /media folder. For example: host/media/{?}. This isn't how you write it in django, but this is just to explain the logic behind dynamic urls. The {?} in this scenario would be to access any file within the media folder. sort of like if you grabbed the arguments from a terminal application.
Particularly in your case, it would look something like this:
path('levels/level<int:num>/', views.levelHandler)

This would get any integer written after level and pass it along as an argument to a levels function where you can route it to the different levels you have in the script.
The function can look something like this:
def levelHandler(request, num=0):
    if(num == 0): return level0(request)
    if(num == 1): return level1(request)
    ...

This should solve the problem. I'll edit the answer incase i missed something.
Give it a shot and tell me how it goes


text:
Q: How to parse object1 which contains array1, array1 contains object2, object2 contains array3 and so on.. in typescript or javascript I am having a json response like below. I want to fetch id(s) from all levels of children so that I can put them into an array and further passed on checkbox tree.
   {
  "status": "SUCCESS",
  "status_code": "200",
  "message": "Orgnization Hierarchy",
  "responseBody": {
    "data": {
      "id": "2",
      "parentId": "0",
      "value": "Company1",
      "children": [
        // this is level 1 object 1
        {
          "id": "54",
          "parentId": "2",
          "value": "MasterCard",
          "children": [
            // this is level 2 of object 1
            {
              "id": "56",
              "parentId": "54",
              "value": "Branch bangalore",
              "children": [
                {
                  "id": "51",
                  "parentId": "56",
                  "value": "Area1",
                  "children": [
                     { id:"66",
                      "parentId":"56",
                       value: "Deposite dept.",
                       // this is level 3 of object 1 and so on..
                       "children": [...] // further expanded
                     }
                   ]
                },
                // this is level 1 of object 2
                {
                   "id": "5",
                   "parentId": "54",
                   "value": "Branch pune",
                   "children": [...]
                }
              ]
            }
          ]
        },
       // level 1 object 2
        {
          "id": "74",
          "parentId": "2",
          "value": "Axis bank",
          "children": [...] // further expanded
        }
      ]
    }
  }
}

So, if I want to get id [in the example above like (2, 54, 56, 51, 66,...,5,...,74 )] from every level of the children, how can we achieve that? is there any recursive way or without recursive we can achieve it?
I processed below approach :
   var arrayOfids;
   function parsejson(){

    for(var i = 0; i < data.length; i++){
      var objectid = data[i].id
      var objchildren = data[i].children;
      getidfromchildren(objchildren);
    }
   }

   function getidfromchildren(arr){
     for(var j=0; j < arr.length; j++){
       arrayOfids.push(arr[i].id);

         if(arr[i].children.length != 0){
            getidfromchildren(arr);
         }
     }
   }

A: You could take Array#flatMap and get all id.
This approach assumes, that all children properties have at least an empty array.
If not, you need an array as default parameter, like
getId = ({ id, children = [] }) => [id, ...children.flatMap(getId)]
//                      ^^^^

const
    getId = ({ id, children }) => [id, ...children.flatMap(getId)],
    data = { status: "SUCCESS", status_code: "200", message: "Orgnization Hierarchy", responseBody: { data: { id: "2", parentId: "0", value: "Company1", children: [{ id: "54", parentId: "2", value: "MasterCard", children: [{ id: "56", parentId: "54", value: "Branch bangalore", children: [{ id: "51", parentId: "56", value: "Area1", children: [{ id: "66", parentId: "56", value: "Deposite dept.", children: [] }] }, { id: "5", parentId: "54", value: "Branch pune", children: [] }] }] }, { id: "74", parentId: "2", value: "Axis bank", children: [] }] } } },
    ids = [data.responseBody.data].flatMap(getId);

console.log(ids)


text:
Q: R: Produce machine-readable output for summary / describe I have a data frame with 10k rows and 500 columns. For each column, I want to create a count for each unique value in the row. E.g.
      Fruit    Vegetable  Meat
1     Apple    Carrot     Steak
2     Apple    Potato     Chicken
3     Pear     Peas       Duck

Would produce:
Fruit;Apple;2;Pear;1
Vegetable;Carrot;1;Potato;1;Peas;1
Meat;Steak;1;Chicken;1;Duck;1

The Hmisc describe function produces this kind of analysis, but the output is so badly formatted as to be useless.
Thanks.

A: You could run the table function through apply
For instance
fruit <- c("Apple", "Apple", "Pear")
veg <- c("Carrot", "Potato", "Peas")
meat <- c("Steak", "Chicken", "Duck")
df <- data.frame(fruit, veg, meat)

apply(df, 2, table)

$fruit

Apple  Pear
    2     1

$veg

Carrot   Peas Potato
     1      1      1

$meat

Chicken    Duck   Steak
      1       1       1

A: lapply(names(df),function(x){ tb <- table(df[[x]]);
      write.table(file="test.csv", append=TRUE, quote=FALSE,
                  row.names=FALSE, col.names=FALSE, sep=";",
                  x= paste(x, paste( names(tb), tb, collapse=";", sep=";") ,
                           sep=";")
                  )})
#--------
fruit;Apple;2;Pear;1
veg;Carrot;1;Peas;1;Potato;1
meat;Chicken;1;Duck;1;Steak;1

You will also see a list of three NULLs which would not be sent to a text file. Writing tables and matrices to files is not a strong point of R. There is a write.matrix function in package::MASS. My initial effort with writeLines failed because it has no 'append' option and I wasn't able to cobble together a connection call that would do the append.
(The other gotcha' in R is that processing a list (and by inheritance a dataframe) with 'apply/lapply/sapply' does not pass the names of the list-element (and colnames for dataframes) to the function, so "write" functions would not have the names internally for writing to a file. That is why I worked with names(df) rather than just df.
As a further note, there are probably JSON-writing functions out there and they might be more reliable. I'll take a look and report back.
There is the RJSONIO package:
> require(RJSONIO)
Loading required package: RJSONIO
> toJSON(df)
[1] "{\n \"fruit\": [ \"Apple\", \"Apple\", \"Pear\" ],\n\"veg\": [ \"Carrot\", \"Potato\", \"Peas\" ],\n\"meat\": [ \"Steak\", \"Chicken\", \"Duck\" ] \n}"


text:
Q: sscanf handles maximal unsigned integer value differently than assignment does Consider the following code :
main()
{
  int assigned = 4294967295;     // Max unsigned integer value on 32-bits arch

  char input[] = "4294967295";
  int sscanned;

  unsigned int result = sscanf(input, "%d", &sscanned);
  printf ("scanned %u elements : %d\n
          "Assigned j = %d\n",
          result, sscanned, assigned);

  return 0;
}

When compiled for 32-bits arch (with compilation command: gcc -Wall -Wextra -std=c11 -pedantic -m32 test_sscanf.c -o test_sscanf32), it spits out an expectable warning about "overflow in conversion from 'long long int' to 'int' changes value from '4294967295' to '-1' [-Woverflow]".
Now seeing the result :
> ./test_sscanf32
scanned 1 elements : 2147483647
Assigned j = -1

While the assigned value has rightfully been converted into the maximal negative signed integer value, through two's complement representation (-1 = -2^31 + 2^30 + ... + 2^0), the scanned value on the other hand has apparently got its MSB dismissed which caused it to shrink to the value 2147483647 = 2^31 - 1.
So my question is : what does justify such a difference in the treatment of the maximum n-bits integer value on an n-bits machine (knowing that on a 64-bits arch, the same behavior occurs) ?
Is a programmer not rightfully entitled to expect that sscanf would treat the value the same way an assignment does, on a given architecture ?

A: Converting an integer value to int by cast or assignment, when the value is not representable by int but is representable by some supported type with a larger range, produces an implementation-defined value in the int (C11 §6.3.1.3).  Almost all implementations nowadays define this conversion such that int x = UINT_MAX; sets x to −1.  The only exception I am aware of is Unisys (née Burroughs) mainframes, which still use ones-complement representation for negative numbers.
By contrast, all of the scanf functions have undefined behavior upon reading a number which is outside of the representable range for the type of the variable the number will be written to (C11 §7.21.6.2p10).  That means, not only can you not count on it to do the same thing that integer conversion does, you can't count on it to do anything constructive at all, and the compiler would in fact be entitled to generate machine code that makes demons fly out of your nose.
It is my considered opinion that 7.21.6.2p10 is a defect in the standard, but since I consider the scanf family unfit for purpose anyway (this is only one of many problems with them), I can't be bothered to file a DR.  Use the strto* functions instead.  They have well-defined and documented overflow behavior.

A: Using the wrong format specifier for scanf invokes undefined behavior, so the result doesn't have to make sense.
For example, running the same code on my machine gives the following results:
scanned 1 elements : -1
Assigned j = -1

So use %u instead of %d.


text:
Q: Run Function only once in Javascript Execute function only one time in Javascript, no matter how many times it has been called.
I write the following code, but does not working.
var counter = 0;

if(n.data === YT.PlayerState.BUFFERING) {
  setTimeout(function() {
    if(counter===0) {
      r.frontPlayer.seekTo(10);
      counter++;
  }}, 2000);
}

A: Try not to use timeouts, they invite misery and suffering. This is a simple example, I use jquery for attaching the events but the function is independent of jquery. The key thing is using the object, the anonymous function in this case, to track state.
<button id="testButton">
test
</button>

$("#testButton").click(function() {
    if (null == this.ran) {
    console.log("do something");
    this.ran = true;
  }
})

A: Take a look at underscore or lodash's _.once function:
var fn = _.once(function() {
  console.log('this will only run once');
});

Or writing it yourself:
var fn = (function() {
  var called = false;
  var ret;

  return function() {
    if (called) return ret;
    called = true;
    // do stuff
    // ..
    ret = 'some return value';
    return ret;
  };
})();


text:
Q: How to minimally perturb a matrix $A$ into $\hat{A}$ so that the inexact system of equations $Ax=b$, is exact on $\hat{A}x=b$? Given that A is over-determined and, as written in the subject, how can I minimally perturb matrix $A$ into $\hat{A}$ so that the inexact system of equations $\hat{A}x=b$ is exact? The original problem $Ax=b$ gives a non zero error.
The question can be rephrased as, how can I minimally change $A$ into $\hat{A}$ such that column vector $b$ is part of $\hat{A}$'s column space given that for $A$ isn't.


text:
Q: multi level dictionary python I want to create a multi level dictionary from a file like this:
node1     :
 key1 : value1
node2          :
 key2              :               value2
 key3              :               value3
 key4              :               value4
node3              :
 key2              :
  interkey2        :               value
node4          :
 key2              :
  interkey2        :
   moreinterkey    :               value5
  interkey3        :
   moreinterkey    :               value5

and I want that it keeps in memory to acces as:
>>> variable["node1"]["key2"]["interkey2"]
value2

any idea of which is the best way? I'm iterating line by line but I don't really know how to set the dict value depending of the level of each value
Thanks,
As seems my question is not really understand, I edit to put what I want to do, but I don't know how to make it more pythonic:
result = {}
level_keys = []
for line in input_text:
    actual_indent = len(line) - len(line.lstrip(' '))
    splitted_string = line.split(':')
    level_keys = level_keys[:actual_indent]
    level_keys[actual_indent] = splitted_string[0]
    if actual_indent == 0:
        result[level_keys[0]] = splitted_string[1]
    elif actual_indent == 1:
        result[level_keys[0]][level_keys[1]] = splitted_string[1]
    elif actual_indent == 2:
        result[level_keys[0]][level_keys[1]][level_keys[2]] = splitted_string[1]
    elif actual_indent == 3:
        result[level_keys[0]][level_keys[1]][level_keys[2]][level_keys[3]] = splitted_string[1]
return result

I hope now is more clear my question, sorry for the first attempt

A: Instead of using a custom file format, could you use YAML file format and use a well-known parsing library. For example, the example in landing page of the PyYAML Documentation looks quite similar to yours.
The first example - setup:
import yaml
document = """
  a: 1
  b:
    c: 3
    d: 4
"""
print yaml.dump(yaml.load(document))

The first example - output:
a: 1
b: {c: 3, d: 4}


text:
Q: PuTTy works extremely bad with VPS Problem brief: extremely slow and unreliable connection using PuTTy while apache server works fine.
I have a VPS with CentOS 6 installed and PuTTY SSH client running on Windows7 64 bit at home.
The problem is that PuTTY works extremely slow and connection often drops.
Sometimes I have to wait few minutes to get a responce (if I get any at all) thus working process is extremely inconvenient. Same problem also has FTP server vsftpd.
But the apache server (httpd) running on the same VPS shows excelent performance and always responds very quickly.
One more strange thing: if any task with long execution time (for example wget or make) has been launched, PuTTy's output is always quick and connection never drops.
Any suggestions?
I think about two possible reasons:

*

*Priority of SSH and SFTP server is low

*Some unknown specifics of VPS

I am not familiar with Linux close enough and would like to hear any suggestions
to solve this annoying problem. Also it is interesting if anybody has similar problem.

A: Connections via ssh or web are different.
The connection web is opened, the data is sent and then closes.
The SSH session instead remains open until it is explicitly closed.
The SSH session, therefore, is subject to timeout. I don't know why the connections are so slow so I can not express myself, but I can tell you that if you set a keepalive of putty can prevent sessions time out and go that close. You have to edit and save your session.
Look at the image,

You have to check "Enable TCP keepalives" and set a value (i think 10 is sufficient) in "seconds between keepalives"

A: SSH works fine from linux machine like Android smartphone or Raspberry PI. That means the problem is in Windows 7 settings. As for details, I'm not interested to go further in because I found a workaround using Android as a proxy and that works fine for me. Thanks everyone.


text:
Q: Installation Root (Cern) v6.00.02 with Cygwin I have installed Root (Cern).
Before calling "root" it is necessary starting the X server (by Cygwin, typing "startx"), to allow Root to use Windows.
By setup-x86_64.exe I installed Cygwin (approximately 50 GB of HD)
and I chose "install" for all packages;
I fear, however, there is something else to install, because by giving the command startx reports the error:
gnome-session: PID 3552: WARNING: Could not connect to ConsoleKit: Failed to connect to
socket /var/run/dbus/system_bus_socket: No such file or directory";

In fact the folder "dbus" is missing.

*

*What's missing?

*what are the essential things to install ?

A: You need to install:
dbus-x11 and dbus
The list of available packages on cygwin is here
https://cygwin.com/packages/package_list.html
PS: use startxwin instead of startx


text:
Q: How to fix "refusing to merge unrelated histories"? I have tried "git pull origin master --allow-unrelated-histories" I am trying to pull everything from my dev branch to master but I am getting "Already up to date". So when I tried to merge them together, i get, "fatal: refusing to merge unrelated histories". Can someone please help me.
I have tried git reset --hard
iwithman~/Programming/ibusiness-card-web$:git merge wip269 origin/master
fatal: refusing to merge unrelated histories
iwithman~/Programming/ibusiness-card-web$:git branch

*

*master
wip269
iwithman~/Programming/ibusiness-card-web$:git merge wip269
fatal: refusing to merge unrelated histories
iwithman~/Programming/ibusiness-card-web$:git pull wip269
fatal: 'wip269' does not appear to be a git repository
fatal: Could not read from remote repository.

A: You can use --allow-unrelated-histories, as morty answered.  But watch out: this may not do what you want.  It depends on what you want, and what's in the two commits you'll choose this way.
git merge works by comparing the merge base commit with the two particular other commits that you select.  You select one of the two commits you want to use by checking it out:
git checkout master

and the other with an argument to git merge:
git merge wip269

for instance.
The merge base, however, is determined by the history, and history, in Git, consists of the commits in the repository, as linked by those commits themselves.  This is where the command is failing, because the histories are not related to each other: there is no merge base commit.
If the histories were related, this:
          A--B--...--H   <-- master
         /
...--o--*
         \
          P--Q--...--W   <-- wip269

might be a good way to draw the commit graph.  From this drawing, you could see that the history in master starts (or ends) at commit H and works backwards to A, and then to commit * and further back; and history in wip269 starts (or end) at commit W, then works back to P and on to * and further back.
Commit * would then be the merge base.  The merge base is defined as the best common commit.  The best one is obviously *—commits that come before it would work too, but it seems better to stick with the one closest to the two branch-ends you started from.  The way git merge works is to compare the files in the merge base to the files in your current commit—here H—to see what you changed, then compare those same files in the same merge base to the files in their commit (W) to see what they changed.  Having found what you both changed, Git can combine the changes.
The problem here is that your history does not look anything like this.  It probably looks something like this:
A--B--...--H   <-- master (HEAD)

P--Q--...--W   <-- wip269

That is, starting at H and working backwards, Git eventually arrives at commit A, which is a root commit: it has no previous history.  Meanwhile, starting at W and working backwards, Git eventually arrives at commit P, which is also a root commit.  There is no shared commit that is on both branches.
Using --allow-unrelated-histories tells git merge: OK, if there's no common commit, play a pretend game that there is: pretend that there is a common commit that contains no files at all, and use that as the merge base.
This means that what you changed is: you invented every file from scratch.  Meanwhile, what they changed is that they, too, invented every file from scratch.
Where the invented files have different names, Git will take the new files.  Where they have the same names, Git will declare an add/add conflict and leave you to figure out what should go in the file with that name.
If and when you resolve all such conflicts and commit—or if there are no conflicts—Git will make a new merge commit whose parents are both H and W:
A--B--...--H
            \
             X   <-- master (HEAD)
            /
P--Q--...--W   <-- wip269

and now commits P through W are on both branches.  Commits A through H, plus X, are (only) on master.  If you move the name wip269 so that it, too, points to new commit X, all 17 commits will be on both branches; or you can delete the name wip269 now, if you're done with it, after which all commits are only on master.
Side note on git pull
All git pull does is run git fetch, then immediately run a second Git command.  The second command is usually—and is in your case—git pull.  So you can do this with git pull (which can pass --allow-unrelated-histories to its git merge), but you might as well do it with git merge at this point—you've probably already done any necessary fetch.

A: dev and master branches have 'unrelated histories' which means they have no common base by default.
git merge does not allow two branches with unrelated histories to be merged to prevent parallel histories.
You can use --allow-unrelated-histories to force the merge.


text:
Q: Вывод html текста из модели в DJANGO Есть модель в django
#  Слайдер на главной на темном фоне
class MainDarkSlider(models.Model):
    title = models.CharField('Заголовок c тегами html', max_length=100)
    description = models.TextField('Описание',  blank=True)

    def __str__(self):
        return f'{self.title}'

    class Meta:
        verbose_name = 'Слайдер на главной'
        verbose_name_plural = 'Слайдеры на главной'

В поле title в админке я хочу ввести текст с html тегами, но django html экранирует, в итоге мне на странице сайта такой текст

Вместо такого как в html верстке

Как мне поправить модель?

A: Используй {{ obj.description|safe }} при выводе в шаблоне
Подробней о фильтрах можно посмотреть https://docs.djangoproject.com/en/3.1/ref/templates/builtins/#std:templatefilter-safe


text:
Q: Getting the 'Start Tag Expected' error in R I am trying to parse a XML file using RStudio. Here are few lines of my file
<?xml version="1.0" encoding="UTF-8"?>
<iaapi:Project name="IA Quickstart" xmlns:iaapi="http://www.ibm.com/investigate/api/iaapi">
<DataRuleDefinition name="DRD_dummy_rule">
<ExecutableRules>
I used the function xmlParse() to parse the file, but am getting the following error: Start tag expected.'<' not found'
But as we can see we have the '<' tag in the beginning of the xml string. Help is greatly appreciated.

Blockquote

A: I had same error. My code was:
xml = xmlTreeParse("data-raw/documentos.xml", useInternalNodes=TRUE, encoding="UTF-8)

My solution was:
txt = readLines("data-raw/documentos.xml", encoding = "UTF-8")
xml = xmlTreeParse(txt, useInternalNodes=TRUE)

Apparently when read documentos.xml the first line has a stranger character <U+FEFF>, that I believe to be the source of the problem.


text:
Q: Why we can't subscript 'int' object in Python I'm trying to return the days of the month according to the given year, in the end, if the year isn't leap, it should return the no of days according to the defined list, but I'm getting error.
Here's my code
days_of_month=[0,31,28,31,30,31,30,31,31,30,31,30,31]
year=int(input('enter the year - '))
month=int(input('enter the month - '))

def isleap(year):
    return year%4==0 and (year % 100!=0 or year % 400==0)
def days(month,year):
    if month > 12 or month < 1:
        print('Invalid')
    else:
        if month==2 and isleap(year):
            return 29
        else:
            return month[days_of_month]

print(days(month,year))

Error Message
Traceback (most recent call last):
  File "d:\Function_Example.py", line 16, in <module>
    print(days(month,year))
  File "d:\Function_Example.py", line 14, in days
    return month[days_of_month]
TypeError: 'int' object is not subscriptable

Is there any onther way to get the element from the list ?

A: you confused the last line of the function.
it should be:
days_of_month=[0,31,28,31,30,31,30,31,31,30,31,30,31]
year=int(input('enter the year - '))
month=int(input('enter the month - '))

def isleap(year):
    return year%4==0 and (year % 100!=0 or year % 400==0)
def days(month,year):
    if month > 12 or month < 1:
        print('Invalid')
    else:
        if month==2 and isleap(year):
            return 29
        else:
            return days_of_month[month]

print(days(month,year))


text:
Q: Access ('07 -'10) form is not showing entered records I have a form that I enter data into that is broken into a number of different tables for normalization.
However, once I reopen the form, only the first record is shown.
I have it set as "single form" and Data Entry is set to "no".
I've tried some macros to open the form to the last record but those don't seem to work.

A: Try setting it to continuous forms instead of single.
Also, if it's set to single form you should be able to navigate thorough all the records, one at time, with the navigation buttons in the lower left of the form.


text:
Q: Does the restriction of $\mathcal{O}(1)$ to a quadric have a square root? Let $Q^n$ be a smooth $n$-dimensional quadric in $P^{n+1}(\mathbb{C})$. Does the restriction of $\mathcal{O}(1)$ to $Q^n$ have a square root, for any $n \geq 1$?
If $n = 1$, then $Q^1$ is biholomorphic to $P^1(\mathbb{C})$, and the restriction of $\mathcal{O}(1)$ to $P^1(\mathbb{C})$ is $\mathcal{O}(2)$ (that is, $\mathcal{O}(2)$ with respect to $P^1(\mathbb{C})$) and thus has a square root, namely $\mathcal{O}(1)$ (with respect to $P^1(\mathbb{C})$).
My question is whether this also holds for $n > 1$.
Edit: I don't think so, but could someone please confirm? If $n = 2$, I think that the restriction of $\mathcal{O}(1)$ to $Q^2$, itself biholomorphic to $P^1(\mathbb{C}) \times P^1(\mathbb{C})$, is the line bundle $\mathcal{O}(1,1)$, which does not have a square root. Am I right?

A: You're correct about $n = 2$. One way to see this is that there is an embedding $\mathbb{CP}^1\times\mathbb{CP}^1 \to \mathbb{CP}^3$ given by $([x_0, x_1], [y_0, y_1]) \mapsto [x_0y_0, x_0y_1, x_1y_0, x_1y_1]$ with image the quadric defined by the equation $z_0z_3 - z_1z_2 = 0$. Restricting the map to $\mathbb{CP}^1\times\{[0, 1]\}$, we see that the image is the intersection of two hyperplanes, so pulling back $\mathcal{O}(1) \to \mathbb{CP}^3$ to $\mathbb{CP}^1$ via this map gives $\mathcal{O}(1)$, and likewise for the other factor.
For $n > 2$, the inclusion $i : Q^n \hookrightarrow \mathbb{CP}^{n+1}$ induces an isomorphism on cohomology $i^* : H^2(\mathbb{CP}^{n+1}; \mathbb{Z}) \to H^2(Q^n; \mathbb{Z})$ by the Lefschetz Hyperplane Theorem. As $c_1(\mathcal{O}(1))$ is a generator of $H^2(\mathbb{CP}^{n+1}; \mathbb{Z})$, the element $i^*c_1(\mathcal{O}(1)) = c_1(i^*\mathcal{O}(1))$ is a generator of $H^2(Q^n ; \mathbb{Z})$. It follows that $i^*\mathcal{O}(1)$ does not have a square root.
To apply the Lefschetz Hyperplane Theorem, note that a degree $d$ hypersurface of $\mathbb{CP}^{n+1}$ is a hyperplane section of $\nu_d(\mathbb{CP}^{n+1}) \subset \mathbb{CP}^N$ where $\nu_d : \mathbb{CP}^{n+1} \to \mathbb{CP}^N$ denotes the degree $d$ Veronese embedding.


text:
Q: Computed property depending on ALL properties of @each I've used before the type of computed property that looks like this:
isAnyoneHungry: function () {
  var everyone = this.get('everyone'),
      anyoneHungry = false;
  everyone.forEach(function(person) {
    if (person.get('isHungry')) {
      anyoneHungry = true;
    }
  });
  return anyoneHungry;
}.property('everyone.@each.isHungry'),

everyone: Ember.A() // an array that will hold person models

for computing something based on one property of each object in an array.
Is it possible to make a computed property based on every property of each object in an array?
Say that the person model has many boolean properties like isHungry, isTired, isCranky, ... and I want to be able to recompute this property when any one of those changes. But I'm lazy and don't want to type every single property like this:
function(){...}.property('everyone.@each.isHungry', 'everyone.@each.isTired', 'everyone.@each.isCranky'.
Instead I'd like something like this:
isAnyoneUnhappy: function () {
  var everyone = this.get('everyone'),
      isAnyoneUnhappy = false;
  everyone.forEach(function (person) {
    if (person.get('isHungry') || person.get('isTired') || person.get('isCranky')) {
      isAnyoneUnhappy = true;
    }
  });
  return isAnyoneUnhappy;
}.property('everyone.@each.iWantEveryPropertyHere')

Is this possible in Ember yet?

A: Have you tried the following?
isAnyoneUnhappy: function () {
  var everyone = this.get('everyone'),
      isAnyoneUnhappy = false;
  everyone.forEach(function (person) {
    if (person.get('isHungry') || person.get('isTired') || person.get('isCranky')) {
      isAnyoneUnhappy = true;
    }
  });
  return isAnyoneUnhappy;
}.property('everyone.@each.*')

I looked into the Ember source and there seems to be some logic dealing with the star notation. I am not sure though.

A: Ideally you should have a property on person that rolls up the unhappy attributes, something like:
isUnhappy: function () {
  if (this.get('isHungry') || this.get('isTired') || this.get('isCranky')) {
    return true;
  }
}.property('isTired', 'isHungry', 'isCranky')

Then isAnyoneUnhappy just observes everyone.@each.isUnhappy


text:
Q: Write output to both log.out and console I have a basic build script that I want to log its entire output to a log file. Example
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>log.out 2>&1
echo "Run Date: $(date)"
echo "another line"
conda -V

With this the console remains blank and everything is saved to the log.out
This works great for me but I would also like it to still print everything to the console as well.
Essentially, I want it to mimic the behavior of
echo "Run Date: $(date)" 2>&1 | tee -a log.out
echo "another line"  2>&1 | tee -a log.out
conda -V 2>&1 | tee -a log.out

without having to type 2>&1 | tee -a log.out at the end of every line.

A: You could do this by enclosing all your commands in a code block and redirecting the output of the entire block. You'd still have to contend with the redirection syntax but it would only be in one place:
{
    echo "Run Date: $(date)"
    echo "another line"
    conda -V
} 2>&1 | tee -a log.out

A: You could group all your commands and capture that output to a log with tee:
#!/bin/bash

{
    echo "duck"
    echo "duck"
    echo "goose" >>/dev/stderr
    echo "Run Date: $(date)"
} 2>&1 |tee -a log.out

.... or just have the script output to stdout/stderr as it would without the redirects,  and capture that output on whatever launches the script?   ./test.sh 2>&1 |tee -a log.out


text:
Q: In vscode, how to debug on a compute node of slurm cluster? Here is my dilemma

*

*First, log in login-node via remote-ssh in vscode

*Then apply a compute-node with gpu

*If i debug the python program, it would go to the login-node which is not allowed.
Now, i can only debug the program through print which is veryyy inconvenient.
So, iwant to know is there any solution?

A: You can try this course of action:

*

*login and apply for a compute-node with gpu

*set a configuration for that gpu node in your .ssh/config with a ProxyJump through the login node

*log in gpu-node via remote-ssh in vscode


text:
Q: (change) vs (ngModelChange) in angular Angular 1 does not accept onchange() event, it's only accepts ng-change() event.
Angular 2, on the other hand, accepts both (change) and (ngModelChange) events, which both seems to be doing the same thing.
What's the difference?
which one is best for performance?
ngModelChange:
<input type="text" pInputText class="ui-widget ui-text"
    (ngModelChange)="clearFilter()" placeholder="Find"/>

vs change:
<input type="text" pInputText class="ui-widget ui-text"
    (change)="clearFilter()" placeholder="Find"/>

A: As per my experience (change) and (ngModelChange) has two different usage.

*

*(ngModelChange) triggers when HTML renders, user changed the value of that element.

*(change) triggers when user changes the value and leave the element focus.
Usage:

*

*(ngModelChange): when you have critical things that depends on html any type of changes that you have to handle.

*(change): When you have to handle only value changes done by user.

Note: Be careful while using the (ngModelChange) because sometimes it will give you maximum call stack issue and your form will stuck.

A: (change) event bound to classical input change event.
https://developer.mozilla.org/en-US/docs/Web/Events/change
You can use (change) event even if you don't have a model at your input as
<input (change)="somethingChanged()">

(ngModelChange) is the @Output of ngModel directive. It fires when the model changes. You cannot use this event without ngModel directive.
https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_model.ts#L124
As you discover more in the source code, (ngModelChange) emits the new value.
https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_model.ts#L169
So it means you have ability of such usage:
<input (ngModelChange)="modelChanged($event)">

modelChanged(newObj) {
    // do something with new value
}

Basically, it seems like there is no big difference between two, but ngModel events gains the power when you use [ngValue].
  <select [(ngModel)]="data" (ngModelChange)="dataChanged($event)" name="data">
      <option *ngFor="let currentData of allData" [ngValue]="currentData">
          {{data.name}}
      </option>
  </select>

dataChanged(newObj) {
    // here comes the object as parameter
}

assume you try the same thing without "ngModel things"
<select (change)="changed($event)">
    <option *ngFor="let currentData of allData" [value]="currentData.id">
        {{data.name}}
    </option>
</select>

changed(e){
    // event comes as parameter, you'll have to find selectedData manually
    // by using e.target.data
}

A: As I have found and wrote in another topic  - this applies to angular < 7 (not sure how it is in 7+)
Just for the future
we need to observe that [(ngModel)]="hero.name" is just a short-cut that can be de-sugared to: [ngModel]="hero.name" (ngModelChange)="hero.name = $event".
So if we de-sugar code we would end up with:
<select (ngModelChange)="onModelChange()" [ngModel]="hero.name" (ngModelChange)="hero.name = $event">
or
<[ngModel]="hero.name" (ngModelChange)="hero.name = $event" select (ngModelChange)="onModelChange()">
If you inspect the above code you will notice that we end up with 2 ngModelChange events and those need to be executed in some order.
Summing up: If you place ngModelChange before ngModel, you get the $event as the new value, but your model object still holds previous value.
If you place it after ngModel, the model will already have the new value.
SOURCE

A: 1 - (change) is bound to the HTML onchange event. The documentation about HTML onchange says the following :

Execute a JavaScript when a user changes the selected option of a <select> element

Source : https://www.w3schools.com/jsref/event_onchange.asp
2 - As stated before, (ngModelChange) is bound to the model variable binded to your input.
So, my interpretation is :

*

*(change) triggers when the user changes the input

*(ngModelChange) triggers when the model changes, whether it's consecutive to a user action or not

A: In Angular 7, the (ngModelChange)="eventHandler()" will fire before the value bound to [(ngModel)]="value" is changed while the (change)="eventHandler()" will fire after the value bound to [(ngModel)]="value" is changed.


text:
Q: Google Spreadsheets ImportXML into 2 columns I have an xml document that looks like this:
<Time>
<ID>22653948</ID>
<Job>
<ID>J000010</ID>
<Name>NEP0001_Evesham</Name>
</Job>
<Task>
<ID>12379652</ID>
<Name>Assemble</Name>
</Task>
<Staff>
<ID>68684</ID>
<Name>Ruiardh Robinson</Name>
</Staff>
<Date>2012-10-29T00:00:00</Date>
<Minutes>180</Minutes>
<Note/>
<Billable>true</Billable>
</Time>

The document contains multiple <Time> entries and what I'm trying to do is import all the <Date> and <Minutes> fields for each task, only where the date contains the string "2014". I can import all the dates fields from 2014 using:
=QUERY(ImportXML('Time Data'!F2, "//Time/Date"), "SELECT * WHERE Col1 contains '2014-04'")

But I can't get the corresponding minutes field for the same entry, I know you can do multiple xpath queries using the | operator and I tried the following but it doesn't work as it just returns the first date field from the first entry for some reason.
=QUERY(ImportXML('Time Data'!F2, "//Time/Date | //Time/Minutes"), "SELECT * WHERE Col1 contains '2014-04'")

Does anyone know how I can import both columns only where the date contains "2014"?

A: You could use:
//Time/*[self::Date or self::Minutes]

however the way google reads the XML, this will populate across rows and not columns, so if you have the query in A1 the result will be
   A                    B                  C     ...
1 2012-10-29T00:00:00
2 180

So if you want this to be in columns you could just add a 2nd ImportXML query in B1 that uses //Time/Minutes
Personaly however I'd just import the whole XML in another sheet and then query that.
Btw you could also use //Time[starts-with(Date, '2014')] instead of wrapping the ImportXML in QUERY


text:
Q: Contain an image within a div? I want to contain an image into a 250 x 250 div, forcing the image to resize but not stretch. How can I do this? By the way, the image will usually be bigger than the div itself, which is why resizing comes into the picture.

#container { width:250px; height:250px; border:1px solid #000; }

Here's a jsfiddle which someone can edit:
http://jsfiddle.net/rV77g/

A: object-fit, behaves like background-size, solving the issue of scaling images up and down to fit.

The object-fit CSS property specifies how the contents of a replaced element should be fitted to the box established by its used height and width.

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

.cover img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    overflow: hidden;
}

Browser Support
There's no IE support, and support in Edge begins at v16, only for img element: https://caniuse.com/#search=object-fit
The bfred-it/object-fit-images polyfill works very well for me in IE11, tested on Browserstack: demo.

Alternative without polyfill using an image in SVG
For Edge pre v16, and ie9, ie10, ie11:

You can crop and scale any image using CSS object-fit and object-position. However, these properties are only supported in the latest version of MS Edge as well as all other modern browsers.
If you need to crop and scale an image in Internet Explorer and provide support back to IE9, you can do that by wrapping the image in an <svg>, and using the viewBox and preserveAspectRatio attributes to do what object-fit and object-position do.
http://www.sarasoueidan.com/blog/svg-object-fit/#summary-recap

(The author explains the technique thoroughly, and duplicating the detail here would be impractical.)

A: Use max width and max height. It will keep the aspect ratio
#container img
{
 max-width: 250px;
 max-height: 250px;
}

http://jsfiddle.net/rV77g/

A: You have to style the image like this
#container img{width:100%;}

and the container with hidden overflow:
#container{width:250px; height:250px; overflow:hidden; border:1px solid #000;}

A: Since you don't want stretching (all of the other answers ignore that) you can simply set max-width and max-height like in my jsFiddle edit.
#container img {
    max-height: 250px;
    max-width: 250px;
}

See my example with an image that isn't a square, it doesn't stretch

A: Here is javascript I wrote to do just this.
function ImageTile(parentdiv, imagediv) {
imagediv.style.position = 'absolute';

function load(image) {
    //
    // Reset to auto so that when the load happens it resizes to fit our image and that
    // way we can tell what size our image is. If we don't do that then it uses the last used
    // values to auto-size our image and we don't know what the actual size of the image is.
    //
    imagediv.style.height = "auto";
    imagediv.style.width = "auto";
    imagediv.style.top = 0;
    imagediv.style.left = 0;

    imagediv.src = image;
}

//bind load event (need to wait for it to finish loading the image)
imagediv.onload = function() {
    var vpWidth = parentdiv.clientWidth;
    var vpHeight = parentdiv.clientHeight;
    var imgWidth = this.clientWidth;
    var imgHeight = this.clientHeight;

    if (imgHeight > imgWidth) {
        this.style.height = vpHeight + 'px';
        var width = ((imgWidth/imgHeight) * vpHeight);
        this.style.width = width + 'px';
        this.style.left = ((vpWidth - width)/2) + 'px';
    } else {
        this.style.width = vpWidth + 'px';
        var height = ((imgHeight/imgWidth) * vpWidth);
        this.style.height = height + 'px';
        this.style.top = ((vpHeight - height)/2) + 'px';
    }
};

return {
    "load": load
};

}
And to use it just do something like this:
 var tile1 = ImageTile(document.documentElement, document.getElementById("tile1"));
 tile1.load(url);

I use this for a slideshow in which I have two of these "tiles" and I fade one out and the other in. The loading is done on the "tile" that is not visible to avoid the jarring visual affect of the resetting of the style back to "auto".

A: #container img{
 height:100%;
 width:100%;
}

A:

#container img {
        max-width:250px;
        max-height:250px;
        width: 250px;
        height: 250px;
        border:1px solid #000;
    }

The img will lose aspect ratio


text:
Q: Remove empty , but allow only one per group I was wondering how to remove empty elements, but allow only one empty element per group (next to non-empty one) ?
Something like :

Example HTML :

Hello world

Lorem ipsum dolor sit amet

Eum ne nostro admodum

And jQuery for checking the empty elements :
var p_empty = $('p').filter(function(i,v){return $.trim($(v).text()).length===0;});

Now I got all empty elements, But any idea how to remove those next empty elements ?
Workflow : http://jsfiddle.net/jmy0uzw1/
PS: I am looking for good JS performance also

A: In your case since you are not using containers, you will have to use sibling selectors + and make sure the preceding p element itself is not of .empty
$('p.empty:not(p:not(.empty) + p.empty)').remove();

var p_empty = $('p').filter(function(i, v) {
  return $.trim($(v).text()).length === 0;
});

p_empty.addClass('empty');

$('p.empty:not(p:not(.empty) + p.empty)').remove();
p {
  padding: 3px 10px;
  background: #eee;
  color: #999;
  font-size: 12px;
  line-height: 12px;
}
p.empty {
  border: 1px dashed #fff;
  background: #edd;
}

Hello world

Lorem ipsum dolor sit amet

Eum ne nostro admodum

A:

var p_empty = $('p').filter(function(i, v) {
  return $.trim($(v).text()).length === 0;
});

p_empty.addClass('empty');
$('p.empty + p.empty').remove();
p {
  padding: 3px 10px;
  background: #eee;
  color: #999;
  font-size: 12px;
  line-height: 12px;
}
p.empty {
  border: 1px dashed #fff;
  background: #edd;
}

Hello world

Lorem ipsum dolor sit amet

Eum ne nostro admodum

Try this:
$('p.empty + p.empty').remove();

Full code
var p_empty = $('p').filter(function(i, v) {
  return $.trim($(v).text()).length === 0;
});

p_empty.addClass('empty');
$('p.empty + p.empty').remove();

A: Just add more to your filter
var p_empty = $('p').filter(function(i,v){
    return $.trim($(v).text()).length===0 && $.trim($(v).prev().text()).length===0;
});


text:
Q: AWS SDK Get All Files Between Date Is there a way to get all files from an AWS Bucket that were uploaded between two dates? Right now I have the code below which is using the S3DirectoryInfo which returns information on ALL files in the corresponding bucket. Is there a way to get file info within a date range instead of grabbing information on all files in the bucket?
        AmazonS3Client s3Client = new AmazonS3Client(AWSAccessKey, AWSSecretAccessKey, AWSRegion);
        S3DirectoryInfo dir = new S3DirectoryInfo(s3Client, AWSBucketName);
        List<IS3FileSystemInfo> files = dir.GetFileSystemInfos().ToList();


text:
Q: Syntax with Passing a function into another function I'm writing a function that returns a data frame and I'd like to have one of the columns of this data frame to essentially take a column of data, pass it into a predifined function and then set that as a column of the new data frame.
So i set the function up to take a set of data, a function which applies logic and the set of data which that function uses.
I was able to get it to work if I use .apply in the final line of of my code that is arrowed.
bt_data['Position'] = signal_data.apply(trade_logic)

but I was advised to use np.select instead of apply b/c it's vectorized and I was wondering since my function is using vectorization is there a better syntax to use to set a column called bt_data['Positions'] to just be the trade_logic function applied on mlr_data['Slope'}
Slope
3.98
3.78
-6.67
-17.6
-18.05
-14.48
-12.25
-13.9
-16.89
-13.3
-13.19
-18.63
-26.36
-26.23
-22.94
-23.23
-15.7
-11.01
-12.65
0.33
14.85
14.79
6.8
2.57

Code:
def trade_logic(x):
    conditions = [x.between(0, 10, inclusive=False), x.between(-10, 0, inclusive=False)]
    values = ['Long', 'Short']
    np.select(conditions, values, 'Flat')

def slope_test(x):
    if x >0 and x<20:
        return 'Long'
    elif x<0 and x>-20:
        return 'Short'
    else:
        return 'Flat'

def backtest_data(data,trade_logic,signal_data):

    bt_data = pd.DataFrame()

    bt_data['TickChange'] = bt_data['C']-bt_data['C'].shift(1)
    bt_data['CumTickChange'] = bt_data['TickChange'].cumsum()
    bt_data['Position'] = trade_logic(signal_data)  < ------

    return bt_data

results = backtest_data(mlr_data,trade_logic,mlr_data['Slope'])
print(results)


text:
Q: Using a transistor as a switch to let a 9V Battery flow I'm fairly new to electric engineering and wanted to try building the following circuit:
3.3V Power Source (On/Off Controlled via. Microcontroller ESP8266)
9V Power Source (Battery)
Transistor/MOSFET
The 9V Power Source should only flow if the 3.3V Power Source is active.
| e.g. Microcontroller turns on 3.3 Power Source -> 9V Power Source flows and powers XYZ.
I've tried simulating it via. an online tool but couldn't really get it to work, can someone give me a heads up? Thanks in advance!

A: Most of MOSFETs can not be controlled (or turn on) by 3.3 V. It needs 10 volts at least. So, I suggest using a transistor.
There're many ways and configurations that makes you control your load using a transistor and this depends on your application or your load so, It would be better if you mentioned your load in your question. Anyway, I will give you a general idea:

simulate this circuit – Schematic created using CircuitLab
Here's how the circuit works:
I assume that you want to control an LED using your Microcontroller. I mean the LED is your load.
When you apply a signal to the gate of the transistor (3.3V), The transistor turns ON and allows the current to flow from the collector to the emitter and the LED turns on.
When the output of the Microcontroller is 0V, No signal is applied to the gate of the transistor. So, The transistor turns OFF and prevent current from flowing and the LED is OFF.
A 9V can not applied directly to an LED to prevent damaging of the led. So, you need R1 to protect it.
When you read the datasheet of the Microcontroller, You will find that it can provide a limited current from its output. You must not exceed this limit. So, you need to use R2 to protect the your Microcontroller and your transistor as well (Base current should be limited too).


text:
Q: Draw a parabola with 3 given points canvas I need to draw a perfect curve / parabola in an html5 canvas. The 3 {x;y} coordinates of the points are given. I tried with a bezierCurveTo or a quadraticCurveTo, but the curve won't go in the middle point.
The result I want ( the blue doted curve, and the blue one ) : Wanted result
The result I have : Current result
Code :
      ctx.strokeStyle = '#00478a';
      ctx.lineWidth = 1.5;

      ctx.beginPath();
      ctx.moveTo(x1AtRatio, 30);
      ctx.quadraticCurveTo(criticalSectionAtRatio, 100, x2AtRatio, 30);

      ctx.stroke();

Where x1AtRatio - x2AtRatio - criticalSectionAtRatio are the given x by user input and 30 - 100 - 30 are the y

A: Control points define slopes
You will need to use two beziers as the curve will not pass through the control point.
The control points set the slopes of the curve out from the last point and in to the next point.
The example (below) draws a parabola using two curves. The function drawCurve()

*

*I draw it twice once scaled and once normal.

*Control points are blue.

*The three points on the curve are red

*The slopes are in green.

For example

const ctx = canvas.getContext("2d");

// drawScaled
ctx.setTransform(2,0,0,2,-50, -55);
drawAll();

// without scale
ctx.setTransform(1,0,0,1,-50, 0);
drawAll();

function drawCurve() {
    ctx.beginPath();
    ctx.strokeStyle = "#000";
    ctx.moveTo(100 - 30, 30);  // start left side
    ctx.quadraticCurveTo(
        100 - 30 / 2, 100,     // controls point sets slope out from start and into center
        100, 100               // center point
    );
    ctx.quadraticCurveTo(
        100 + 30 / 2, 100,     // control point sets slope out from center and into last point
        100 + 30, 30           // last point
    );
    ctx.stroke();
}

function drawAll() {
    // points on curve
    drawPoint(100-30, 30);
    drawPoint(100, 100);
    drawPoint(100+30, 30);

    // Control points
    drawPoint(100 - 30 / 2, 100, "#00F");
    drawPoint(100 + 30 / 2, 100, "#00F");

    // Draw line through all points to show slopes
    drawLine(100-30, 30, 100 - 30 / 2, 100);
    drawLine(100 - 30 / 2, 100, 100, 100);
    drawLine(100, 100, 100 + 30 / 2, 100);
    drawLine(100 + 30 / 2, 100, 100 + 30, 30);

    // Draw curve
    drawCurve();
}

function drawPoint(x,y,col = "red") {
    ctx.fillStyle = col;
    ctx.beginPath();
    ctx.arc(x, y, 2, 0, Math.PI * 2);
    ctx.fill();
}
function drawLine(x,y, x1, y1, col = "#0A08") {
    ctx.strokeStyle = col;
    ctx.beginPath();
    ctx.lineTo(x, y);
    ctx.lineTo(x1, y1);
    ctx.stroke();
}
canvas {
    border: 1px solid black;
}
<canvas id="canvas"></canvas>


text:
Q: How to save and restore working environment, each app in a virtual desktop (including browsers with tabs)? Is there a ready solution for saving and restoring whole working environment?
I want to save a project's workspace, and restore it inside a virtual desktop:

*

*browsers (with their own tabs)

*other apps (any app that was there in that desktop and can be automatically started)

*possibly terminal sessions (i'm not greedy, though)

Why:
I want to be recover my workspace after a restart for any reason, e.g. power drain, accidental crash, multi-boot, etc.)
Or to "save" an entire project and load it at another time.
I'm not looking for perfect solutions, but the more - the better.
(P.S. I know of "screen" and alike for terminal sessions.  This is not the big issue here)

A: There is not a ready solution in standard Ubuntu, which uses Gnome Shell. Even basic session saving, i.e., where you can save your desktop state such that it is restored after a reboot, has been dropped because it had issues. Other desktops may provide session saving, but usually will not allow you to save different states. However, KDE desktop probably does.
You are looking for an even more refined experience, where you can save desktop states depending on what project/activity you want to continue. This is actually what KDE desktop provides through their "Activities" function. This post, although quite old already, gives you an idea what these "Activities" are about. So it may be worthy to explore the KDE desktop environment to see how well it fits what you are after.


text:
Q: Firebase connection not working on Linux in SpringBoot What I'm trying to achieve is to open a connection to my firebase database and get some data which i need to parse. I am running Spring with the Spring Boot framework, the admin sdk of firebase, kotlin and gradle. On Windows 10 it is working like expected, but when i try to run the .jar file on my linux server it doesn't get any data or errors. It gets stuck at the ValueEventListener. I have ufw installed, but disabling it or adding ports 5228:5230 (tcp/udp), didn't solve the problem.
    val dataMinifiedRef = database.reference.child("minifiedData").child("areas")
    dataMinifiedRef.addListenerForSingleValueEvent(object : ValueEventListener {
        override fun onCancelled(error: DatabaseError?) {
            log.info(error!!.message)
        }

        override fun onDataChange(dataSnapshot: DataSnapshot) {
            log.info("Got data")
        }
    })

EDIT:
This is how I parse the service account.
    val str = "{\n" +
              ...
              "}\n"

    // convert String into InputStream
    val serviceAccount = ByteArrayInputStream(str.toByteArray())

    val options = FirebaseOptions.Builder()
            .setCredentials(GoogleCredentials.fromStream(serviceAccount))
            .setDatabaseUrl("https://xxx.firebaseio.com")
            .build()

I get the following error.
Tue Dec 19 15:31:41 CET 2017 [DEBUG] com.google.firebase.database.connection.PersistentConnection: pc_0 - Trying to fetch auth token
Tue Dec 19 15:31:41 CET 2017 [DEBUG] com.google.firebase.database.connection.PersistentConnection: pc_0 - Error fetching token: java.io.IOException: Error getting access token for service account:

A: The problem was that the time on our Linux server was not synchronized automatically. I have found this article where he mentioned the solution. I have then followed this guide and added NTP servers which are equal to our server location.