text:
Q: why SSH publickey authentification fails on one account but work on the other on the same server I have a strange issue with SSH public keys. There's one account on the server where I've uploaded my public key to .ssh/authorized_keys and it works as expected (I can login with no password). Then there's an account on the same server where I've done the same (few times already), but it still asks me for a password to login.
The settings that match for those accounts are following:

*

*Directory permissions are correct .ssh directory's owner and group is user. Permission set to 0700

*.ssh/authorized_keys has user and group set to the correct user and permissions are 0600

*I've tried comparing the files they're exactly the same. And tried scp ~/.ssh/id_rsa.pub user@server.com:.ssh/authorized_keys few times.

If I try to add -v to the ssh connection I get the following info for the one that's NOT WORKING:
OpenSSH_4.7p1, OpenSSL 0.9.8g 19 Oct 2007
debug1: Reading configuration data /Users/pacis/.ssh/config
debug1: Reading configuration data /opt/local/etc/ssh/ssh_config
debug1: Connecting to xxx.xxx.xxx.xxx [xxx.xxx.xxx.xxx] port 22.
debug1: Connection established.
debug1: identity file /Users/pacis/.ssh/identity type -1
debug1: identity file /Users/pacis/.ssh/id_rsa type 1
debug1: identity file /Users/pacis/.ssh/id_dsa type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.1p1 Debian-5
debug1: match: OpenSSH_5.1p1 Debian-5 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_4.7
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-cbc hmac-md5 none
debug1: kex: client->server aes128-cbc hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Host 'xxx.xxx.xxx.xxx' is known and matches the RSA host key.
debug1: Found key in /Users/pacis/.ssh/known_hosts:40
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Offering public key: /Users/pacis/.ssh/id_rsa
debug1: Authentications that can continue: publickey,password
debug1: Trying private key: /Users/pacis/.ssh/identity
debug1: Trying private key: /Users/pacis/.ssh/id_dsa
debug1: Next authentication method: password

And here's the same from the one that's working as expected:
OpenSSH_4.7p1, OpenSSL 0.9.8g 19 Oct 2007
debug1: Reading configuration data /Users/pacis/.ssh/config
debug1: Reading configuration data /opt/local/etc/ssh/ssh_config
debug1: Connecting to xxx.xxx.xxx.xxx [xxx.xxx.xxx.xxx] port 22.
debug1: Connection established.
debug1: identity file /Users/pacis/.ssh/identity type -1
debug1: identity file /Users/pacis/.ssh/id_rsa type 1
debug1: identity file /Users/pacis/.ssh/id_dsa type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.1p1 Debian-5
debug1: match: OpenSSH_5.1p1 Debian-5 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_4.7
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-cbc hmac-md5 none
debug1: kex: client->server aes128-cbc hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Host 'xxx.xxx.xxx.xxx' is known and matches the RSA host key.
debug1: Found key in /Users/pacis/.ssh/known_hosts:40
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Offering public key: /Users/pacis/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 277
debug1: Authentication succeeded (publickey).
debug1: channel 0: new [client-session]
debug1: Entering interactive session

Here's the /etc/ssh/sshd_config:
Port 22
# Use these options to restrict which interfaces/protocols sshd will bind to
#ListenAddress ::
#ListenAddress 0.0.0.0
Protocol 2
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
#Privilege Separation is turned on for security
UsePrivilegeSeparation yes

# Lifetime and size of ephemeral version 1 server key
KeyRegenerationInterval 3600
ServerKeyBits 768

# Logging
SyslogFacility AUTH
LogLevel INFO

# Authentication:
LoginGraceTime 120
PermitRootLogin yes
StrictModes yes

RSAAuthentication yes
PubkeyAuthentication yes
#AuthorizedKeysFile %h/.ssh/authorized_keys

# Don't read the user's ~/.rhosts and ~/.shosts files
IgnoreRhosts yes
# For this to work you will also need host keys in /etc/ssh_known_hosts
RhostsRSAAuthentication no
# similar for protocol version 2
HostbasedAuthentication no
# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication
#IgnoreUserKnownHosts yes

# To enable empty passwords, change to yes (NOT RECOMMENDED)
PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Change to no to disable tunnelled clear text passwords
#PasswordAuthentication yes

# Kerberos options
#KerberosAuthentication no
#KerberosGetAFSToken no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes

X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
#UseLogin no

#MaxStartups 10:30:60
#Banner /etc/issue.net

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

Subsystem sftp /usr/lib/openssh/sftp-server

UsePAM yes

The last info I can think of that's relative it's ls -la of both accounts home dirs and .ssh dirs.
Working one:
total 40
drwxr-x--- 5 user1 www-data 4096 2009-10-29 22:11 .
drwxr-x--x 6 root  www-data 4096 2009-10-27 23:09 ..
....
drwx------ 2 user1 user1    4096 2009-10-23 07:20 .ssh

total 12
drwx------ 2 user1 user1   4096 2009-10-23 07:20 .
drwxr-x--- 5 user1 www-data 4096 2009-10-29 22:11 ..
-rw------- 1 user1 user1    413 2009-10-23 07:20 authorized_keys

Not working one:
total 68
drwxrwxr--  6 user2 www-data    4096 2009-11-07 12:13 .
drwxr-x--x  5 root  root            4096 2009-10-09 14:29 ..
....
drwx------  2 user2 user2       4096 2009-11-07 15:52 .ssh

total 12
drwx------ 2 user2 user2 4096 2009-11-08 20:32 .
drwxrwxr-- 6 user2 www-data     4096 2009-11-07 12:13 ..
-rw------- 1 user2 user2  412 2009-11-07 09:55 authorized_keys

I have no clue whatsoever why it's not working and I've checked and doublechecked everything several times already. What am I missing?
Thank you for your time.

A: Try removing the group write access to the user2 home directory on the account that's not working... If anyone has write access other than the account user SSH will complain. If you look at the directory listings posted the working one has:
drwxr-x--- 5 user1 www-data 4096 2009-10-29 22:11 ..

The non-working account has:
drwxrwxr-- 6 user2 www-data     4096 2009-11-07 12:13 ..

As I stated in my earlier comments to the original question 9 times out of 10 this is a permissions/ownership issue. Once the information was provided this is made apparently obvious.
Looking at one of my own accounts I get the following:
$ ls -lnd .
drwxr-xr-x 14 97037 97037 4096 Nov  8 09:31 .
$ ls -lnd .ssh
drwx------ 2 97037 97037 4096 Jun 16 11:30 .ssh
$ ls -lnd .ssh/authorized_keys
-rw------- 1 97037 97037 388 Jun 16 11:30 .ssh/authorized_keys

I can only imagine the group membership to www-data is a mis-guided way of restricting access to the home directory while allowing Apache to serve web pages inside the users directory.
Furthermore cawer's suggestion was given a summary dismissal for suggesting the permissions on the ~/.ssh directory stating that all the permissions were correct and identical but the proof provided shows otherwise.
Since proof is in the pudding... Here's the ssh connection log to my account:
$ ssh -v example.com
OpenSSH_5.1p1 Debian-6ubuntu2, OpenSSL 0.9.8g 19 Oct 2007
debug1: Reading configuration data /home/jbouse/.ssh/config
debug1: Applying options for *
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug1: Connecting to example.com [x.x.x.x] port 22.
debug1: Connection established.
debug1: identity file /home/jbouse/.ssh/keys.d/id_rsa.example type -1
debug1: identity file /home/jbouse/.ssh/keys.d/id_dsa.example type -1
debug1: identity file /home/jbouse/.ssh/keys.d/jbouse@example type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_4.3
debug1: match: OpenSSH_4.3 pat OpenSSH_4*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_5.1p1 Debian-6ubuntu2
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-cbc hmac-md5 none
debug1: kex: client->server aes128-cbc hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Host 'example.com' is known and matches the RSA host key.
debug1: Found key in /home/jbouse/.ssh/known_hosts:85
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Trying private key: /home/jbouse/.ssh/keys.d/id_rsa.example
debug1: Trying private key: /home/jbouse/.ssh/keys.d/id_dsa.example
debug1: Trying private key: /home/jbouse/.ssh/keys.d/jbouse@example
debug1: read PEM private key done: type RSA
debug1: Authentication succeeded (publickey).
debug1: channel 0: new [client-session]
debug1: Entering interactive session.
debug1: Sending environment.
debug1: Sending env LANG = en_US.UTF-8

If I then run the following to set my home directories permissions the same as your user2 account:
$ ls -lnd .
drwxr-xr-x 14 97037 97037 4096 Nov  8 09:31 .
$ chmod g+w .
$ ls -lnd .
drwxrwxr-x 14 97037 97037 4096 Nov  8 09:31 .

Finally try to connect again and I get the following ssh log:
$ ssh -v example.com
OpenSSH_5.1p1 Debian-6ubuntu2, OpenSSL 0.9.8g 19 Oct 2007
debug1: Reading configuration data /home/jbouse/.ssh/config
debug1: Applying options for *
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug1: Connecting to example.com [x.x.x.x] port 22.
debug1: Connection established.
debug1: identity file /home/jbouse/.ssh/keys.d/id_rsa.example type -1
debug1: identity file /home/jbouse/.ssh/keys.d/id_dsa.example type -1
debug1: identity file /home/jbouse/.ssh/keys.d/jbouse@example type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_4.3
debug1: match: OpenSSH_4.3 pat OpenSSH_4*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_5.1p1 Debian-6ubuntu2
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-cbc hmac-md5 none
debug1: kex: client->server aes128-cbc hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Host 'example.com' is known and matches the RSA host key.
debug1: Found key in /home/jbouse/.ssh/known_hosts:85
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Trying private key: /home/jbouse/.ssh/keys.d/id_rsa.example
debug1: Trying private key: /home/jbouse/.ssh/keys.d/id_dsa.example
debug1: Trying private key: /home/jbouse/.ssh/keys.d/jbouse@example
debug1: read PEM private key done: type RSA
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: password

When I change the permissions back by removing the group write permissions I can once again log into the account.

A: Check permissions for the folder .ssh on the server you are trying to login.
Run chmod -R 600 .ssh. Ssh is fussy when it comes to broken permissions and public keys.

A: You've checked all the common candidates for key authentication failure; the next thing I'd be doing is bumping up the logging level on the server and checking out /var/log/auth.log to see what it's reporting differently for the two logins.
Another thing worth clarifying -- on the account where it asks for the password, if you enter the password does it work and allow you to login?  If PAM restrictions deny login for a particular account (and you've configured SSH to use PAM) you can get this sort of result, because for password auth the other PAM restrictions aren't checked until after you've entered the password.

A: Your "authorized_keys" file can have a different name. Check it out:
cat /etc/ssh/sshd_config | grep AuthorizedKeys
#AuthorizedKeysFile     %h/.ssh/authorized_keys

If it's not overriden, check permissions for that file, and its directory: it must be readable for the user that you're logging into.

A: Is this a Debian system?  If so the user that doesn't work may have a weak key.
See the Debian wiki for how to test your keys.
If you've got a weak key you'll have to upgrade the ssh packages on the client system and re-generate the keys for the user with the issue.

A: ln -s authorized_keys authorized_keys2

usually solved the problem for me. note that IIRC the documentation discourages this.


text:
Q: Finding error in Simpson's Integration Rule by Lagrange's Interpolating Polynomial This was asked here before but I wonder if I can also get the error expression in Simmpson's Rule as follows:
Suppose we want to estimate the integral a function $f$ in the interval $[x_0,x_2]$. We divide this interval in two subintervals of same length $h$: $[x_0,x_1]$ and $[x_1,x_2]$. The error of Simpson's Rule is given by
$$R:=\frac{1}{6}\int_{x_0}^{x_2}f^{(3)}(\xi_x)(x-x_0)(x-x_1)(x-x_2)dx,$$
where $\xi_x\in \left]x_0,x_2\right[$. We can divide this integral in two in order to apply the Mean Value Theorem for Integrals:
\begin{align*}R&=\frac{1}{6}\left(\int_{x_0}^{x_1}f^{(3)}(\xi_x)(x-x_0)(x-x_1)(x-x_2)dx+\int_{x_1}^{x_2}f^{(3)}(\xi_x)(x-x_0)(x-x_1)(x-x_2)dx\right)\\
&=\frac{1}{6}\left(f^{(3)}(\xi_1)\int_{x_0}^{x_1}(x-x_0)(x-x_1)(x-x_2)dx+f^{(3)}(\xi_2)\int_{x_1}^{x_2}(x-x_0)(x-x_1)(x-x_2)dx\right),\end{align*}
where $\xi_1\in \left]x_0,x_1\right[$ and $\xi_2\in \left]x_1,x_2\right[$. We have used the fact that $(x-x_0)(x-x_1)(x-x_2)$ doesn't change sign in any of the intervals $\left[x_0,x_1\right]$, $\left[x_1,x_2\right]$.
Now, the integrals above are $h^4/4$ and $-h^4/4$, respectively. Thus,
$$R=\frac{h^4}{24}\left(f^{(3)}(\xi_1)-f^{(3)}(\xi_2)\right).$$
To continue, my idea is to use the standard Mean Value Theorem to obtain that
$$R=-\frac{h^4}{24}f^{(4)}(\xi)\color{red}{(\xi_2-\xi_1)},$$
for some $\xi \in \left]x_0,x_2\right[$. However, I'm not able to get rid of the red part since the actual error expression is
$$-\frac{h^5}{90}f^{(4)}(\xi).$$
Any ideas?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Check unique player with objectify I use objectify with GAE and I want to create unique player by pseudo. I know that there is no unique key like sql database. So I tried to use transaction to do it. I want to start my transaction, search if there is already a player with this pseudo, and create the player if not.
Player player = ofy().load().type(Player.class).filter("pseudo =", tmpPseudo).first().now();

But this doesn't work because there is a filter. Now I'm stuck because I have no idea how to fix it.
Thanks.

A: you have to mark the field pseudo with the @Index annotation like this:
Player.java
import com.googlecode.objectify.annotation.Index;

@Index
String pseudo;

so it can be filtered by that field.

A: The easiest strategy is to check if it is used, write, then requery after the save.  If you get two results and yours is the older one, delete the row and return an error (or whatever).  There is still the possibly of missing it though due to "eventual consistency" constraints in datastore.  Adding a delay before the requery can help but depending on app load may not really be necessary.

A: In my case, I solved my problem by copying the object into the transaction.
final Player player = ofy().load().type(Player.class).filter("pseudo =", tmpPseudo).first().now();
Then inside transaction I do the check instead of before the transaction:
Player currentPlayer = player
if the currentPlayer == null ==> create player, otherwise no.


text:
Q: Can no longer stay on my home page As soon as I reach the home page of the S/P website I am immediately getting redirected to the page viewer web part address (internet address). I'd like now to get rid of this page viewer (don't really need it) but need to be able to stay on the home page, edit it, and finally remove the page viewer web part. Can you help?
Thank you

A: Open the page in web part maintenance mode.

To access the Web Part Maintenance Page for a page that is not stored
  in a document library, such as the site home page, append ?Contents=1
  to the end of the URL for the page.

Then delete the webpart in question.


text:
Q: JavaFX imageview throws null when adding to StackPane I have fairly complicated program which we are suppose to modify.
Here we a MainWindow which wraps around the components of the application and display them as UI.
MainWindow.java:
// Independent Ui parts residing in this Ui container
private BrowserPanel browserPanel;
..
@FXML
private StackPane browserPlaceholder;
..
void fillInnerParts(){
  browserPanel = new BrowserPanel(logic.selectedPersonProperty());
  browserPlaceholder.getChildren().add(browserPanel.getRoot());
  ..
}

BrowserPanel.java:
 /**
 * The Browser Panel of the App.
 */
public class BrowserPanel extends UiPart<Region> {

   ..

    private static final String FXML = "BrowserPanel.fxml";

    @FXML
    private WebView browser;

    public BrowserPanel(ObservableValue<Person> selectedPerson) {
        super(FXML);
        ..
    }
 ..

BrowserPanel.fxml:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.web.WebView?>

<StackPane xmlns:fx="http://javafx.com/fxml/1">
  <WebView fx:id="browser"/>
</StackPane>

I tried modifying this Browser class to display an image instead.
MainWindow.java
// Independent Ui parts residing in this Ui container
private ImagePanel imagePanel;
..
@FXML
private StackPane ImagePanelPlaceholder;
..
void fillInnerParts(){
  imagePanel = new ImagePanel();
  imagePanelPlaceholder.getChildren().add(imagePanel.getRoot());
  ..
}

ImagePanel.java
public class ImagePanel extends UiPart<Region>{
    private static final String FXML = "ImagePanel.fxml";

    @FXML
    private ImageView imageView;

    public ImagePanel(){
        super(FXML);
        Image sample = new Image("/images/sample.png");
        imageView.setImage(sample);
    }
}

ImagePanel.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.image.ImageView?>

<ImageView fx:id="imageView" fitHeight="150.0" fitWidth="200.0" pickOnBounds="true" preserveRatio="true" xmlns="http://javafx.com/javafx/10.0.1" xmlns:fx="http://javafx.com/fxml/1" />

However, I am getting the error:
SEVERE: Fatal error during initializing nullnull
java.lang.NullPointerException
    at seedu.address.ui.MainWindow.fillInnerParts(MainWindow.java:120)

where fillInnerParts is the method to add all components into the MainWindow as shown above.
How would I go about modifying this such that I can display a picture on my JavaFX application?


text:
Q: Max of a concave function Given a concave function $f(x)$ over a convex set $S$, so $f(a)+f(b) \leq 2 \times f (\frac{a+b}{2})$. Here, $a$ and $b$ lies in the same convex set $S$.
I know that the maximum value of $f(a)+f(b)$ is possible when $a=b$. But I don't know how to argue for it. Though I have some intuition, I need formal arguments to justify it.
For eg. the $\sin$ function is concave in the interval $[0, \pi]$, so  $\sin(x)+ \sin (y) \leq 2  \times \sin\left(\frac{x+y}{2}\right)$. So, can we say that maximum of $\sin(x)+ \sin (y)$ is possible if $x=y$ ?

A: Here is a hint.
Notice that the line connecting two points $(x_{1},f(x_{1}))$ and $(x_{2},f(x_{2}))$ lies completely below the curve $y=f(x)$. The midpoint of this line is $\left(\frac{x_{1}+x_{2}}{2},\frac{f(x_{1})+f(x_{2})}{2}\right)$


text:
Q: How can I change the text on the 404 not found view in Laravel? I'm setting up an API with Laravel. When I enter a route that does not exist I get redirected to a view that says 404 | Not found.
How could I change this view to abort( response()->json('Not Found', 404)); so that the person that tries to access the API via another application get a JSON response saying Not Found.

A:
You may publish Laravel's error page templates using the
  vendor:publish Artisan command. Once the templates have been
  published, you may customize them to your liking:

php artisan vendor:publish --tag=laravel-errors

A: You only need to create a 404.blade.php file under resources/views/errors/ with whatever content and style you want. I've just done that...

A: Otherwhise

define a fallback route at the end of the routes/api.php file:

Route::fallback(function(){
    return response()->json(['message' => 'Not Found.'], 404);
})->name('api.fallback.404');

Source

A: Try these steps:
1) In the app/Exceptions/Handler.php file, modify the render method.
/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
{
    if ($this->isHttpException($exception)) {
        if ($exception->getStatusCode() == 404) {
            return response()->view('errors.' . '404', [], 404);
        }
    }

    return parent::render($request, $exception);
}

2) Create a new view file errors/404.blade.php.
<!DOCTYPE html>
<html>
<head>
    <title>Page not found - 404</title>
</head>
<body>
The page your are looking for is not available
</body>
</html>


text:
Q: Using triggers to maintain data integrity from similar tables in two databases I have two SQL Server databases.
One is being used as the back-end for a Ruby-On-Rails system that we are transitioning from but is still in use because of the Ruby apps we are rewriting in ASP.NET MVC.
The databases have similar tables, but not identical, for the Users, Roles and Roles-Users tables.
I want to create some type of trigger to update the user and roles-users tables on each database when a modification is made on the other database of the same table.
I can't just use the users table on the original database because Ruby has a different hash function for the passwords, but I want to ensure that changes on one system are reflected on the other instanter.
I also want to avoid the obvious problem that an update on the one database triggers an update on the other which triggers an update on the first and the process repeats itself until the server crashes or something similarly undesirable happens or a deadlock occurs.
I do not want to use database replication.
Is there a somewhat simple way to do this on a transaction per transaction basis?
EDIT
The trigger would be conceptually something like this:
USE Original;
GO

CREATE TRIGGER dbo.user_update
ON dbo.user WITH EXECUTE AS [cross table user identity]
AFTER UPDATE
AS
BEGIN
   UPDATE Another.dbo.users SET column1=value1, etc., WHERE inserted.ID = Another.dbo.users.ID;
END

The problem I am trying to avoid is a recursive call.
Another.dbo.users will have a similar trigger in place on it because the two databases have different types of applications, Ruby-On-Rails on the one and ASP.NET MVC on the other that may be working on data that should be the same on the two databases.

A: I would add a field to both tables if possible.  When adding or updating a table the 'check' field would be set to 0.  The trigger would look at this field and if it is 0, having been generated by an application event, then the trigger fires the insert/update into the second table but the check field would have a 1 instead of 0.
So when the trigger fires on the second table it will skip the insert back into table one.
This will solve the recursive problem.
If for some reason you can not add the check field, you can use a separate table with the primary key to the table and the check field.  This need more coding but would work also.


text:
Q: Module was blocked because of a disallowed MIME type ("text/html") I'm surprised that there are so many questions regarding the same problem but there are no good answers anywhere. In fact this question doesn't even have a single answer. Anyway, my problem is much similar. Everything was working fine before I decided to run my frontend and backend both on same port (PORT 3000 in my case). I followed these steps:

*

*Used ng build --prod to compile development file. A dist folder was created.

*Then just uploaded all the server files and dist folder to server.

*And run the server using pm2. The command is pm2 start server.js.

Well I know from where did these lines come in index.html:

script src="runtime-es2015.858f8dd898b75fe86926.js" type="module"
script src="polyfills-es2015.5728f680576ca47e99fe.js" type="module"
script src="runtime-es5.741402d1d47331ce975c.js" nomodule>
script src="polyfills-es5.7f43b971448d2fb49202.js" nomodule>
script src="main-es2015.ec7a803b995f0d691eeb.js" type="module">
script src="main-es5.1cd51b4ce24f28c1391b.js" nomodule>

But now they are creating these errors:

Loading module from "http://localhost:3000/runtime-es2015.858f8dd898b75fe86926.js" was blocked because of a disallowed MIME type ("text/html").
Loading module from "http://localhost:3000/polyfills-es2015.5728f680576ca47e99fe.js" was blocked because of a disallowed MIME type ("text/html").
Loading module from "http://localhost:3000/main-es2015.ec7a803b995f0d691eeb.js" was blocked because of a disallowed MIME type ("text/html").

I tried setting type=text/javascript and many more solutions and hacks. But nothing is working.
PS: Here is the entire project before build. View its README also.

A: The problem you have, is that your javascript files are not being found by the server. It returns an error header with status code like 404 (Not Found), 401 (Unauthorized) and an html page somewhere along these lines:
<html>
    <body>
    ERROR 404: NOT FOUND
    </body>
</html>

Since the browser expects a javascript file (the default MIME Type of the script element is type="text/javascript"), it will complain when it receives an HTML-file.
You can see the server response (status code and the actual html) in the developer tools of your browser. Go to the Network tab and click one of the javascript file to see the headers and the content of the response.

A: Perhaps not directly relevant for the OP, but may help others that end up here.
The same error may arise if your import statement does not have the .js extension.
For example, during local development in Firefox (v94), a main script trying to import from a "module" in the same folder, as follows, will generate the error:
import { MyClass } from './my_module';

This can be fixed by adding the .js extension:
import { MyClass } from './my_module.js';

A: For me, the error got solved when I served my dist folder with app.use(express.static(path.join(__dirname, "..", "dist")));. Your path may be different.
Before serving the static JS files, the server wasn't able to find them, but now he does.


text:
Q: Trying to tell TypeScript to ignore node_modules, but it's not working. Can you help me out? My tsconfig:
{
  "compilerOptions": {
    "esModuleInterop": true,
    "outDir": "dist",
    "rootDir": ".",
    "lib": ["esnext"],
    "strict": true,
    "skipLibCheck": true,
    "types": []
  },
  "include": ["./**/*"],
  "exclude": [
    "node_modules",
    "./node_modules",
    "./node_modules/*",
    "./node_modules/@types/node/index.d.ts",
    "./node_modules/.prisma/*",
    "node_modules/*"
  ]
}

I'm compiling with tsx command, and it still prints out a lot of errors from files in node_modules directory:
[...]
node_modules/.prisma/client/index.d.ts:3907:3 - error TS1135: Argument expression expected.

3907   export class Prisma__TopicClient<T> implements PrismaPromise<T> {
       ~~~~~~

node_modules/.prisma/client/index.d.ts:5660:1 - error TS1128: Declaration or statement expected.

5660 }
     ~

Found 136 errors.

A: I recommend moving your code into /src
{
    "include": [
        "src/**/*"
    ],
}


text:
Q: How do I get django to execute a remote celery task? Seems to ignore BROKER_URL in settings.py I've got a django app that's trying to call a celery task that will eventually be executed on some remote hosts. The task codebase is completely separate to the django project, so I'm using celery.execute.send_task and calling it from a post_delete model signal. The code looks a bit like this:
class MyModel(models.Model):
    @staticmethod
    def do_async_thing(sender, instance, **kwargs):
        celery.execute.send_task("tasks.do_my_thing", args=[instance.name])

signals.post_delete.connect(MyModel.do_async_thing, sender=MyModel)

I'm using the latest Django (1.6.1) and celery 3.1.7, so I understand that I don't need any extra module or app in my django project for it to be able to talk to celery. I've set BROKER_URL inside my settings.py to be the right url amqp://user:password@host/vhost.
When this method fires, I get a Connection Refused error. There's no indication on the celery broker that any connection was attempted - I guess it's not seeing the BROKER_URL configuration and is trying to connect to localhost.
How do I make this work? What extra configuration does send_task need to know where the broker is?

A: So I discovered the answer, and it was to do with not reading the tutorial (http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html) closely enough.
Specifically, I had the correct celery.py in place which I would have thought should have loaded the settings, but I'd missed the necessary changes to __init__.py in the django project, which wasn't hooking everything together.
My celery.py should be:
from __future__ import absolute_import

import os

from celery import Celery

from django.conf import settings

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')

app = Celery('mypoject')

# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

and the __init__.py should be simply:
from __future__ import absolute_import

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app


text:
Q: spring 3 + hibernate 4 + user authentication and authorization privileges Status: Waiting for comprehensive answers with code examples concerning dao, service, controller, view.
With spring 3 + hibernate 4, in a service, dao, controller, view (mvc scenario), like http://www.cavalr.com/blog/Spring_3_and_Annotation_Based_Hibernate_4_Example ,
where is the good place to have authentications before doing something. e.g
Occasions:

*

*Is user logged in? (first check by session , then by data base username password match)

session made? getting previous session on every transaction and authenticating if no session has made.

*More authentications for every transaction e.g:
get some value or boolean from database, check if its true (e.g can this user add more users), then proceed.

*Does user have permissions?  and if authentication fails, how to respond to user?
Ways to respond:
a. Redirect to error page (dont like that though)
b. redirect to the same page with an error message (ok)
c. Do all with ajax, (most preferred) dont reload or redirect page, just authentication by

*

*session and or

*database

*send error message on the same page by ajax.

*proceed if authentication succeeds.
Where to put the logic? in dao, service, controller?
What options do I have?
Can some one give a sample code? I have googled but found irrelevent examples.
I know one solution is spring security, but what do you think? and is there a sample code for it that covers all my questions?
Example scenario:

my scenarios is like this. a user comes and a db query tels/lists the borads he has access to. when he enters a board. the boxes privileges are lists and only readable boxes are shown to him.  then same with tasks.     each of them has  create/read/update/delete permision   and that is known/fetched at the time when the user acts for one. e.g tries to create/read/update/delete a   board/box/task.
now there are millions of boxes / tasks.       loading permissions for each might be insane?
I do not understand how to and where to do the authentication and authorization. daos, services,controllers, and then sending the problems to views as error messages. One dao may call another, one service may call another dao(s) and / or service. all or most may give authorization failures. how to pass the failure strings to view placing them accordingly?
Thanks!


text:
Q: WCF writing Nested Json Webservice I have to write a WCF webservice in dot net in nested Json  structured below. I know how to write simple json but not sure to make it nested for `results
{
    "version": 2,

        "results": [{
        "company": "ABC Company Inc.",
        "city": "Sacramento",
        "state": "CA"
    }

    ]
}

What I am doing is :
file1.cs
namespace Test
{
    public class file1
    {
        public class child
        {
            [DataMember]
            public string version { get; set; }
        }

        public class parent
        {
            [DataMember]
            public string company { get; set; }

            [DataMember]
            public string city { get; set; }

        }
    }
}

In file2.svc.cs
public List<file1> method()
     {

         List<file1.child> result = new List<file1.child>();
         List<file1.parent> result1 = new List<file1.parent>();
         List<file1> final = new List<file1>();
         foreach (DataRow catt1 in dtcategory.Rows)
         {

             result.Add(new file1.child()
             {
                 version= catt1["version"].ToString(),

                });

             result1.Add(new file1.parent() {

                 company= catt1["company"].ToString(),
                 city= catt1["city"].ToString(),

             });
             final.Add(new file1()
             {

             });
              }

         return Add;

     }

Please let me where I am going wrong

A: Class Structure:
public class class1
{

[DataMember]
public string version {get;set;}

[DataMember]
public List<class2> results {get;set;}

}

public class class2
{

[DataMember]
public string company {get;set;}

[DataMember]
public string city{get;set;}

[DataMember]
public string state {get;set;}

}

A: Your question is sort of unclear.  However, if you are asking "how can I design my classes file1.child and file1.parent so that, when serialized by DataContractJsonSerializer or Json.NET, they produce the JSON shown", then you can do:
    public class file1
    {
        [DataContract]
        public class child
        {
            [DataMember(Name="version")]
            public string Version { get; set; }

            [DataMember(Name="results")]
            public List<parent> Results { get; set; }
        }

        [DataContract]
        public class parent
        {
            [DataMember(Name="company")]
            public string Company { get; set; }

            [DataMember(Name="city")]
            public string City { get; set; }

            [DataMember(Name="state")]
            public string State { get; set; }
        }
    }

Note that, given your class names, parent is contained inside child, which is counterintuitive.  You might want to change those names.


text:
Q: Is 5V 20A power supply output safe? I have a 5 Volt 20 Amp DC power supply. I was wondering if it is safe in terms of electricity shock due to high current output? Do I need to seal the connection to the device for protection?
Edit: Thanks for your answers.
Basically, I am going to connect the power supply to a string of LEDs which are all parallel (they have a series resistor to control the current of each branch). I want to know whether I need to seal the connection of the string and the power supply?

A: That power supply can, if it's demanded of it, put out enough current to start a fire in the wires or a resistive load. The wires coming from it always need to be big enough to carry 20A safely. If they are thinner, then they need to be protected by a fuse at the power supply.
5v will not give you a shock.
If the supply is mains powered, rather than battery powered, then a fault in it could give you a shock. Commercial electronic equipment is designed so that a single fault anywhere should not give you a shock, two or more faults are required. One way is that supply is grounded. If this is the case, then you must make sure the ground wire is always connected using a 3 pin socket. If the supply only has two leads, then it is 'double insulated', and does not need earthing.

A: Good thing you ask.  If you are sure this is a 5V DC power supply then it is safe. It is always wise to measure the voltage. Please ask a adult to do so. Please take a look at Ohms law.
$$V = I \cdot R $$
You will get hurt if:

*

*your body resistance (R) is too low, for instance if you are in the bathroom and your skin is wet. Or when your skin is damaged.

*When the voltage (V) is high.
This will result in a high current stopping your heart or will burn you.

A: 5V does not generate harmful current when touched by hands. But a short circuit is surely not a wanted thing. The sealing helps.
You did not specify, is your power supply galvanically isolated from the mains voltage. If it's not, then a proper insulative sealing is a must.
MUST ADD: Get an experienced electrician to check your system!!!!!!!!!!!!


text:
Q: Expressions for "a wish dedicated to one self" I was translating a short story about a mortician (someone who does makeup for the dead) when I came across an idea I don't know how to express. In the story, the protagonist was talking about her dying wishes, one of which was that her apprentice would be the one to embalm her when she dies. Apparently, this was the only wish that was "dedicated" to herself, others were probably "dedicated" to others e.g. having her dog taken care of after she dies. I ended up writing:

She said, "When I go, you must be the one who does my makeup. Don't let any stranger touch my body." That was her only wish dedicated to herself.

But it doesn't feel right to me. "Dedicated" doesn't seem to be the appropriate word and the sentence is clumsy. Are there better ways to express the idea?


text:
Q: line height and font size What sets the height of the textbox, line height or font size?

A: None
its
height

attribute
<input type="text" class="hei" id="txt1" />
<style>
.hei
{
   height: 40px;
}
</style>

font-size: Sets or retrieves a value that indicates the font size used for text in the object.
line-height: Sets or retrieves the distance between lines in the object

A: input {
    height: 100px;
}

A: the css option height?

A: If it's <input type="text" /> then it's a combination of font-size, line-height and any explicitly declared height attributes.
For <textarea> it's an explicit height declaration, though I think it's expressed as rows rather than height.


text:
Q: How many subspace topologies of $\mathbb{R}$? Say two subsets of $\mathbb{R}$ are equivalent if they are homeomorphic, with the subspace topology.  How many equivalence classes are there?
It's immediate that there are at least $\beth_0$ (we can get any finite discrete topology) and no more than $\beth_2 = \mathcal{P}(\mathbb{R})$. I have a semi-complex construction below to show there are at least $\beth_1$.
Without the generalized continuum hypothesis, this question seems harder and possibly independent.  I would be interested in an answer which assumes the continuum hypothesis, and thus answers either $\beth_1$ or $\beth_2$.
Let's not complicated things too much, but we could also ask this question on $S^1$ and $\mathbb{R}^2$: on $S^1$ the construction below does not work, and on $\mathbb{R}^2$ it's much easier.
Construction of $\beth_1$ non-homeomorphic subsets: The idea is that being a limit point, or being a limit point of limit points, or being a limit point of limit points of limit points... are topological properties.  For a given set $A \subset \mathbb{R}$, call a point

*

*A $P_0$ point if it is in $A$.

*A $P_n$ point if it is the limit point of $P_{n-1}$ points.

*A $Q_n$ point if it is a $P_n$ point, but not a $P_{n+1}$ point.

*A $R_n$ point if it is a $Q_n$ point and each neighborhood of the point (in A) is uncountable.

The existence of a $R_n$ point is a topological invariant.  I claim that for any $J \subset \mathbb{N}$, it's possible to create $A \subset \mathbb{R}$ which has a $R_n$ point if and only if $n \in J$.
To motivate the construction and the definition of $Q_n$, first think about constructing a $P_n$ point.  For example, the set $\{0\} \cup \{ 1/k : k \in \mathbb{N} \}$ has $0$ as a $P_1$ point.  Now, add some points to that set: on each interval $(1/(k+1), 1/k)$, add a sequence of points limiting to $1/(k+1)$.  Then

*

*The points we just added are $P_0$ points.

*For each $k$, the point $1/k$ is a $P_1$ point and a $P_0$ point, and thus a $Q_1$ point but not a $Q_0$ point.

*0 is a $P_2$ point, a $P_1$ point, and a $P_0$ point.  Therefore it is a $Q_2$ point.

Now, it would be simpler if we didn't need the $R_n$ definition.  But as you see, we can't make a $Q_n$ point without also making a $Q_{n-1}$ point.  Now consider adding the interval $(-1, 0)$ to the set we've constructed so far.  The $0$ would be a $R_2$ point, but there would be no $R_1$ or $R_0$ points.
To construct a set corresponding to $J \subset \mathbb{N}$, do similar constructions as above all around $\mathbb{R}$, for each $n \in J$.

A: Since every continuous function $f:X \rightarrow \mathbb{R}$ can be extended to a continuous function $f':G \rightarrow \mathbb{R}$ on a $G_{\delta}$ set, the equivalence class of every $X \subseteq \mathbb{R}$ has size at most continuum. So there must be $2^{2^{\omega}} = \beth_2$ many equivalence classes.


text:
Q: How long do Drupal caches last? Using the devel module I can see a lot of calls to cache_get() and cache_set(). After how long does a cached value need to be refreshed? Does the cache get invalidated every few minutes?

A: The module that is using cache_set sets the expiration in the call.  Some things have explicit durations, others have permanent or semi-permanent lifetimes, based on the situation.
Caches get explicitly cleared when you invoke the method through the admin interface (or drush), or otherwise through the use of drupal_flush_all_caches or cache_clear_all.
Lately, I have been using a hook_cron to clear certain cache tables each night.
EDIT to answer comment:
To see which cache, I usually put this in a separate script somewhere:
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
header("Content-Type: text/plain; encoding=utf-8");
$user = user_load(1);
print "Modules implementing hook_cron:\n" . implode("\n", module_implements('cron'));

To see expirations, examine the various cache tables in the database and look at the expire column.  Modules can set expirations on each individual call to cache_set, so it can vary entry by entry.


text:
Q: Simulate shared_ptr cyclic references I wanted to create two objects, sharing a shared_ptr to each other,  to deliberately create cyclic reference case in visual studio , the debugger gone nuts ( as expected , shown in snapshot), but the program still executes (why?) and give result. I wanted to replace the pointer by weak_ptr now, but how ?
struct B;
struct A
{
    void print() { cout << "A " << endl; }
    shared_ptr<B> pB;
};

struct B
{
    void print() { cout << "B " << endl; }
    shared_ptr<A> pA;
};

int main()
{
    shared_ptr<A> a = make_shared<A>();
    shared_ptr<B> b = make_shared<B>();

    a->pB = b;
    b->pA = a;
    a->print();
    a->pB->print();

    a.reset();

    b->pA->print();

    return 0;
}

A: With std::weak_ptr, it look like something like:
struct B;
struct A
{
    void print() const { std::cout << "A " << std::endl; }
    std::weak_ptr<B> pB;
};

struct B
{
    void print() const { std::cout << "B " << std::endl; }
    std::weak_ptr<A> pA;
};

int main()
{
    auto a = std::make_shared<A>();
    auto b = std::make_shared<B>();

    a->pB = b;
    b->pA = a;
    a->print();
    auto wb = a->pB.lock();
    if (wb) { wb->print(); } else { std::cout << "nullptr\n"; }

    a.reset();

    auto wa = b->pA.lock();
    if (wa) { wa->print(); } else { std::cout << "nullptr\n"; }
}

Demo


text:
Q: Can't compile with editline on OpenBSD I think that I must install the editline (libedit?) library but where can I get it for OpenBSD? The code compiles fine with PC-BSD, but with OpenBSD I get this error
implicit declaration of rl_bind_key

It is the editline library that is not found. I tried googling for where to find it for OpenBSD, but it was not found. Can you help me? The headers I use are
#define _XOPEN_SOURCE 500

#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/wait.h>
#include "openshell.h"
#include "errors.h"
#include <errno.h>
#include <locale.h>
#include <editline/readline.h>

Makefile
CC = gcc
GIT_VERSION := $(shell git describe --abbrev=4 --dirty --always --tags)
CFLAGS := $(CFLAGS) -pedantic -std=c99 -Wall -O3 -ledit -g -DVERSION=\"$(GIT_VERSION)\"

shell: main.o
    $(CC) -o shell main.o errors.c util.c pipeline.c -ledit

main.o: main.c errors.c util.c

.PHONY: clean
clean:
    rm -f *.o

This is the offending code
int exec_program(const char *name) {
    FILE *fp;
    int r = 0;
    char *input, shell_prompt[100];
    if (sourceCount >= MAX_SOURCE) {
        fprintf(stderr, "Too many source files\n");
        return 1;
    }
    fp = stdin;
    if (name) {
        fp = fopen(name, "r");

        if (fp == NULL) {
            perror(name);

            return 1;
        }
    }
    sourcefiles[sourceCount++] = fp;
    setlocale(LC_CTYPE, "");
    /*Configure readline to auto-complete paths when the tab key is hit.*/
    rl_bind_key('\t', rl_complete);
    stifle_history(7);
    for (; ;) {
        /* Create prompt string from user name and current working directory.*/
        snprintf(shell_prompt, sizeof(shell_prompt), "%s:%s $ ", getenv("USER"), getcwd(NULL, 1024));
        // Display prompt and read input (NB: input must be freed after use)...
        input = readline(shell_prompt);
        // Check for EOF.
        if (!input)
            break;
        add_history(input);
        r = command(input);
        free(input);
    }
    return r;
}

If I run locate editline then it finds and I change the Makefile and get a new error undefined reference to tgetnum that according to google seems like I must link with the ncurseslibrary. Now it compiles. The new Makefile is:
CC = gcc
GIT_VERSION := $(shell git describe --abbrev=4 --dirty --always --tags)
CFLAGS := $(CFLAGS) -L/usr/local/include/ -L/usr/include -pedantic -std=c99 -Wall -O3 -g -DVERSION=\"$(GIT_VERSION)\" -ledit -lncurses

LDIRS = -L/usr/local/lib -L/usr/lib
LIBS = -ledit lncurses -lcurses

shell: main.o
    $(CC) -o shell main.o errors.c util.c pipeline.c -ledit -lncurses -lcurses

main.o: main.c errors.c util.c

.PHONY: clean
clean:
    rm -f *.o

A: Check where editline/readline.h can be found (e.g. with locate).
If it is in /usr/local/include, you should probably add that to your CFLAGS in your Makefile;
CFLAGS := $(CFLAGS) -I/usr/local/include -pedantic -std=c99 -Wall -O3 -g -DVERSION=\"$(GIT_VERSION)\"
LDIRS = -L/usr/local/lib
LIBS = -ledit

SRCS= main.c errors.c util.c pipeline.c
OBJS= $(SRCS:.c=.o)

shell: $(OBJS)
    $(CC) $(LDIRS) -o shell $(OBJS) $(LIBS)


text:
Q: hackerrank python 3 string operation, resume function for 8 different strings There are 6 test cases and 5 are getting passed based on python 3 on a string operations problem, but 1 test case is failing since inception.
Pls help me out. The question is as follows:
8 Strings are given in a function.

*

*Remove spaces from both end of strings: first, second, parent, city

*Capitalize : first, second, parent

*Print Strings with a space : first, second, parent, city

*Check if string : 'phone' only contains digits

*Check if phone number starts with value in string 'start' and print the result(True or False)

*Print : total no. of times 'strfind' appears in the strings : first, second, parent, city

*Print : list generated by using split function on 'string1'

*Find position of 'strfind' in 'city'

My Code is as follows: Let me know what wrong I have done. 5/6 test cases are passed only 1 test case failed for unknown reason. :(
def resume(first, second, parent, city, phone, start, strfind, string1):

    first = first.strip()
    second = second.strip()
    parent = parent.strip()
    city = city.strip()
    first = first.capitalize()
    second = second.capitalize()
    parent = parent.capitalize()
    print(first + " " + second + " " + parent + " " +city)
    print(phone.isdigit())
    print(phone[0]==start[0])
    res = first + second + parent + city
    res_count = res.count(strfind)
    print(res_count)
    print(string1.split())
    print(city.find(strfind))

A: Not too sure without being given details on the test case. However, number 5 may be incorrect as you are only checking if the first values of the strings are the same. This is not the same as checking if "phone number starts with value in string 'start'". I recommend using the following code instead:
print(phone.startswith(start))

In addition number 6 seems like it could cause some mismatches with overlapping strings. Instead I would suggest using:
print(first.count(strfind) + second.count(strfind) + parent.count(strfind) + city.count(strfind))

A: first = first.strip()
second = second.strip()
parent = parent.strip()
city = city.strip()
first = first.capitalize()
second = second.capitalize()
parent = parent.capitalize()
print(first + " " + second + " " + parent + " " +city)
print(phone.isnumeric())
print(phone.startswith(start))
res = first + second + parent + city
res_count = res.count(strfind)
print(res_count)
print(string1.split())
print(city.find(strfind))


text:
Q: Keyboard shortcut to open Extensions menu in Chrome? I open the Keyboard Shortcut menu far more often than I'd like to admit. How do I open this with a keyboard shortcut?

A: There doesn't appear to be an official keyboard shortcut built into Chrome for the Extensions menu. However, without using additional software, there are still ways to be able to access the menu relatively quickly.
You can add the Extensions menu as a bookmark on the bookmarks bar. Its URL is chrome://extensions/.

This puts it one click away. However, if you want to be able to access it from the keyboard only, there is another way. Right-click the Omnibar and choose "Edit search engines". Under "Other search engines", fill in the information as shown, and then choose Done.

This creates a "search engine" which can be accessed through the keyword 'ex'. Now, to access Extensions, you can press Ctrl+L to select the Omnibar, type ex, and press Enter. Of course, you can customize the "ex" keyword.

A: Since Extensions is a menu item in Chrome, you can assign it a keyboard shortcut through OS X's System Preferences.

*

*Go to the 'Keyboard' Panel

*Select the 'Shortcuts' tab

*Choose 'App Shortcuts' from the left column

*Click the + under the right column to add Google Chrome as an App in the list.

*In the pop-up, type "Extensions" (without quotes) in the space beside 'Menu Title'

*Assign a keyboard shortcut (I use ⌥+⌘ for all my personal shortcuts so I used ⌥+⌘+E for this one)

Done.
:)
Yahenda


text:
Q: How to drag a JqueryUI dialog box outside the page I have a jqueryUI dialog box used to upload some files while the parent page allow users to fill some details. I want the dialog box to be moved out of the window of the parent to facilitate this. I have set the modal attribute to false to enable editing in the parent page. Is this possible? Any help is much appreciated.
This is the div i use as a dialog

notice that I have an iframe, in which src i will set next when i load the dialog essentially loading another page inside dialog box
$(".someClass").click(function () {
            $("#dialogBox").attr('src', $(this).attr("href") + "?EmailFolderPath=" + folderID);
            $("#myDiv").dialog({
                width: 400,
                height: 450,
                modal: false,
                close: function () {
                }
            });

any idea how can i do this?

A: Because you didn't provide any code, I worked on something like this:
$.ui.dialog.prototype._makeDraggable = function() {
this.uiDialog.draggable({
    containment: false,
    });
};

You just have to add this to your stylesheet!
body {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
overflow-y: hidden;
overflow-x: hidden;
}

html {
overflow-y: hidden;
background-color: transparent;
}

All I needed was to set the bottom and right as 0
For me it worked, it should work for too.


text:
Q: Why does wrapping my RecyclerView adapter in another class cause different behaviour? I have come across an issue when using RecyclerViews. Basically during the initial load of a RecyclerView (after I start an activity) there is a small delay before items appear.
After experimenting for a while I found a way to remove this delay by wrapping my adapter in another class as follows:
public class AdapterWrapper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private RecyclerView.Adapter<RecyclerView.ViewHolder> mAdapter;

    public AdapterWrapper(RecyclerView.Adapter<RecyclerView.ViewHolder> adapter) {
        mAdapter = adapter;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return mAdapter.onCreateViewHolder(parent, viewType);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        mAdapter.onBindViewHolder(holder, position);
    }

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

    @Override
    public int getItemViewType(int position) {
        return mAdapter.getItemViewType(position);
    }
}

Then in my activity I have this:
protected void onCreate(Bundle savedInstanceState) {
    ...
    setUpRecyclerView();
    ...
}

public void setUpRecyclerView() {
    mAdapter = new MyAdapter(this, mCursor);
    mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);

    //mRecyclerView.setAdapter(mAdapter);                   // This causes a small delay.
    mRecyclerView.setAdapter(new AdapterWrapper(mAdapter)); // This doesn't
}

This seems really weird to me and I have no idea why the behaviour is different. Has anybody got any potential theory to explain this?
Extra information:
  -I'm using a cursor loader to provide data to my adapter.
  -My adapter is subclassed using a CursorRecyclerAdapter found at http://quanturium.github.io

A: You have to override every method, not just implement the abstract methods.
When you call your overriden methods on AdapterWrapper it's getting passed to the wrapped object. Every other method is going to your wrapper and not getting passed on.

A: If im right, your premise may be a red herring. Delays like this can be—and usually are—because you are performing updates to the ui from a background thread.
We had a similar issue and finally tracked it dowm to that being rhe case. Moving the code back to the main thread, everything became instant again.
Hope this helps!


text: Q: Re Exporting complete data from Google Earth to QGIS I am trying to export Google Earth searches as a KML file to QGIS. How come all existing locations of a search (e.g. Walmart) in the United States only shows select locations. I'm doing a project on food deserts and want to include all major chains and their locations in the U.S.


text:
Q: Speeding up an insert/ignore between database server connections I've successfully refactored the below script to select records from a table on server 1, and then connect to server 2 and insert/ignore the missing records into the cloned table there.
This works but takes about 1.5 minutes to run. I'm hoping someone can help with a slightly faster and more efficient way of doing this, since it's successful but expensive.
I don't have the option to do federated storage or replication, so this has to be done with a script. I previously did this by using the max ID of the source table but after the insert I was missing up to 15 records a day.
Here's the script:
$source_data = mysqli_query($conn,
    "select * from `cdrdb`.`session` where ts >= now() - INTERVAL 1 DAY");

while($source = $source_data->fetch_assoc()) {
    //Insert new rows into ambition.session
    $stmt = $conn2->prepare(
        "INSERT IGNORE INTO ambition.session (SESSIONID,
         SESSIONTYPE,CALLINGPARTYNO,FINALLYCALLEDPARTYNO,
         DIALPLANNAME,TERMINATIONREASONCODE,ISCLEARINGLEGORIGINATING,
         CREATIONTIMESTAMP,ALERTINGTIMESTAMP,CONNECTTIMESTAMP,DISCONNECTTIMESTAMP,
         HOLDTIMESECS,LEGTYPE1,LEGTYPE2,INTERNALPARTYTYPE1,INTERNALPARTYTYPE2
         ,SERVICETYPEID1,SERVICETYPEID2,EXTENSIONID1,EXTENSIONID2,
         LOCATION1,LOCATION2,TRUNKGROUPNAME1,TRUNKGROUPNAME2,SESSIONIDTRANSFEREDFROM
         ,SESSIONIDTRANSFEREDTO,ISTRANSFERINITIATEDBYLEG1,
         SERVICEEXTENSION1,SERVICEEXTENSION2,SERVICENAME1,
         SERVICENAME2,MISSEDUSERID2,ISEMERGENCYCALL,NOTABLECALLID,
         RESPONSIBLEUSEREXTENSIONID,
         ORIGINALLYCALLEDPARTYNO,ACCOUNTCODE,ACCOUNTCLIENT,ORIGINATINGLEGID
         ,SYSTEMRESTARTNO,PATTERN,HOLDCOUNT,AUXSESSIONTYPE,
         DEVICEID1,DEVICEID2,ISLEG1ORIGINATING,ISLEG2ORIGINATING,
         GLOBALCALLID,CADTEMPLATEID,CADTEMPLATEID2,ts,INITIATOR,
         ACCOUNTNAME,APPNAME,CALLID,CHRTYPE,CALLERNAME,serviceid1,serviceid2)

        VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
    or die(mysqli_error($conn2)) ;

    mysqli_stmt_bind_param($stmt,
        "iisssiissssiiiiiiiiissssiiissssiiiisssiisiiiiiiiiisisssisii"
         ,$source['SESSIONID']
         ,$source['SESSIONTYPE']
         ,$source['CALLINGPARTYNO']
         //omitting other columns for sake of space
       );
          $stmt->execute() or die(mysqli_error($conn2));
                                    }

A: A simple improvement would be to move the call to prepare() to before the loop. Since the prepared statement is the same each time through the loop, there's no need to contact the DB server each time.
You can also move the call to bind_param() outside the loop, since the variables are the same each time. bind_param binds to a reference, so updating the variable will change what gets inserted when you call execute().
However, these are likely to make only a small difference. One of the most effective ways to improve speed of INSERT queries is to insert multiple rows at a time. This is much easier to do with PDO than mysqli, because you can provide an array of parameters in the call to $stmt->execute(). The code would look like:
$params = array();
$count = 0;
$batch_size = 100;
$placeholders = implode(", ", array_fill(0, $batch_size, "(SESSIONID,
     SESSIONTYPE,CALLINGPARTYNO,FINALLYCALLEDPARTYNO,
     DIALPLANNAME,TERMINATIONREASONCODE,ISCLEARINGLEGORIGINATING,
     CREATIONTIMESTAMP,ALERTINGTIMESTAMP,CONNECTTIMESTAMP,DISCONNECTTIMESTAMP,
     HOLDTIMESECS,LEGTYPE1,LEGTYPE2,INTERNALPARTYTYPE1,INTERNALPARTYTYPE2
     ,SERVICETYPEID1,SERVICETYPEID2,EXTENSIONID1,EXTENSIONID2,
     LOCATION1,LOCATION2,TRUNKGROUPNAME1,TRUNKGROUPNAME2,SESSIONIDTRANSFEREDFROM
     ,SESSIONIDTRANSFEREDTO,ISTRANSFERINITIATEDBYLEG1,
     SERVICEEXTENSION1,SERVICEEXTENSION2,SERVICENAME1,
     SERVICENAME2,MISSEDUSERID2,ISEMERGENCYCALL,NOTABLECALLID,
     RESPONSIBLEUSEREXTENSIONID,
     ORIGINALLYCALLEDPARTYNO,ACCOUNTCODE,ACCOUNTCLIENT,ORIGINATINGLEGID
     ,SYSTEMRESTARTNO,PATTERN,HOLDCOUNT,AUXSESSIONTYPE,
     DEVICEID1,DEVICEID2,ISLEG1ORIGINATING,ISLEG2ORIGINATING,
     GLOBALCALLID,CADTEMPLATEID,CADTEMPLATEID2,ts,INITIATOR,
     ACCOUNTNAME,APPNAME,CALLID,CHRTYPE,CALLERNAME,serviceid1,serviceid2)"));
$stmt = $pdo->prepare("INSERT INTO ambition.sentence (<columns>) VALUES $placeholders");
while ($row = $source_data->fetch(PDO::FETCH_NUM)) {
    $params += $row; // Append this row to $params
    $count++;
    if ($count != $batch_size) {
        continue;
    }
    $stmt->execute($params);
    // Reset variables for next batch
    $params = array();
    $count = 0;
}
if ($count) { // Handle the last batch that isn't the full size
    $placeholders = implode(", ", array_fill(0, $count, "( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"));
    $stmt = $pdo->prepare("INSERT INTO ambition.sentence (SESSIONID,
         SESSIONTYPE,CALLINGPARTYNO,FINALLYCALLEDPARTYNO,
         DIALPLANNAME,TERMINATIONREASONCODE,ISCLEARINGLEGORIGINATING,
         CREATIONTIMESTAMP,ALERTINGTIMESTAMP,CONNECTTIMESTAMP,DISCONNECTTIMESTAMP,
         HOLDTIMESECS,LEGTYPE1,LEGTYPE2,INTERNALPARTYTYPE1,INTERNALPARTYTYPE2
         ,SERVICETYPEID1,SERVICETYPEID2,EXTENSIONID1,EXTENSIONID2,
         LOCATION1,LOCATION2,TRUNKGROUPNAME1,TRUNKGROUPNAME2,SESSIONIDTRANSFEREDFROM
         ,SESSIONIDTRANSFEREDTO,ISTRANSFERINITIATEDBYLEG1,
         SERVICEEXTENSION1,SERVICEEXTENSION2,SERVICENAME1,
         SERVICENAME2,MISSEDUSERID2,ISEMERGENCYCALL,NOTABLECALLID,
         RESPONSIBLEUSEREXTENSIONID,
         ORIGINALLYCALLEDPARTYNO,ACCOUNTCODE,ACCOUNTCLIENT,ORIGINATINGLEGID
         ,SYSTEMRESTARTNO,PATTERN,HOLDCOUNT,AUXSESSIONTYPE,
         DEVICEID1,DEVICEID2,ISLEG1ORIGINATING,ISLEG2ORIGINATING,
         GLOBALCALLID,CADTEMPLATEID,CADTEMPLATEID2,ts,INITIATOR,
         ACCOUNTNAME,APPNAME,CALLID,CHRTYPE,CALLERNAME,serviceid1,serviceid2) VALUES $placeholders");
    $stmt->execute($params);
}

For this to work as I've written it, you need to ensure that the columns returned by the SELECT query are in the same order as the list you're inserting. Avoid using SELECT * when doing this, so you don't get any surprises if there's a change in the schema of the source table.

A: You probably know by now that inserting one row at a time, one transaction per row, is the slowest way to load data.
I have tested different ways of loading data, and I gave a talk at Percona Live 2017:
Load Data Fast!
TL;DR: Use LOAD DATA INFILE, even if you have to dump your source data into a CSV file first.
Here's an example, though I have not tested it:
$all_columns = "
  `SESSIONID`, `SESSIONTYPE`, `CALLINGPARTYNO`, `FINALLYCALLEDPARTYNO`,
  `DIALPLANNAME`, `TERMINATIONREASONCODE`, `ISCLEARINGLEGORIGINATING`,
  `CREATIONTIMESTAMP`, `ALERTINGTIMESTAMP`, `CONNECTTIMESTAMP`,
  `DISCONNECTTIMESTAMP`, `HOLDTIMESECS`, `LEGTYPE1`, `LEGTYPE2`,
  `INTERNALPARTYTYPE1`, `INTERNALPARTYTYPE2`, `SERVICETYPEID1`,
  `SERVICETYPEID2`, `EXTENSIONID1`, `EXTENSIONID2`, `LOCATION1`, `LOCATION2`,
  `TRUNKGROUPNAME1`, `TRUNKGROUPNAME2`, `SESSIONIDTRANSFEREDFROM`,
  `SESSIONIDTRANSFEREDTO`, `ISTRANSFERINITIATEDBYLEG1`, `SERVICEEXTENSION1`,
  `SERVICEEXTENSION2`, `SERVICENAME1`, `SERVICENAME2`, `MISSEDUSERID2`,
  `ISEMERGENCYCALL`, `NOTABLECALLID`, `RESPONSIBLEUSEREXTENSIONID`,
  `ORIGINALLYCALLEDPARTYNO`, `ACCOUNTCODE`, `ACCOUNTCLIENT`, `ORIGINATINGLEGID`,
  `SYSTEMRESTARTNO`, `PATTERN`, `HOLDCOUNT`, `AUXSESSIONTYPE`, `DEVICEID1`,
  `DEVICEID2`, `ISLEG1ORIGINATING`, `ISLEG2ORIGINATING`, `GLOBALCALLID`,
  `CADTEMPLATEID`, `CADTEMPLATEID2`, `ts`, `INITIATOR`, `ACCOUNTNAME`, `APPNAME`,
  `CALLID`, `CHRTYPE`, `CALLERNAME`, `serviceid1`, `serviceid2`"

$select_sql = "
  SELECT $all_columns FROM `cdrdb`.`session`
  WHERE ts >= NOW() - INTERVAL 1 DAY";

$source_data = mysqli_query($conn, $select_sql);

$tmpfilename = tempnam('/tmp', 'data');
fp = fopen($tmpfilename, 'w'); // do proper error handling and use
while ($source = $source_data->fetch_assoc()) {
    fputcsv($fp, array_values($source));
}
fclose($fp);

$tmpfilename = mysqli_real_escape_string($conn2, $tmpfilename);

$load_sql = "
  LOAD DATA LOCAL INFILE '$tmpfilename'
  IGNORE INTO TABLE `ambition`.`session`
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  ( $all_columns )";

$conn2->query($load_sql);


text:
Q: Android Module reference layout error I'm not good at using the modules on Android
So I have a problem. When I called module activity it must refer the module layout but actually it's referring to the App layout.
I guess it might R.java problem, but I'm not sure.
Here is how it is setup in my project.

A: During the build process, any resources in a library module are ignored if the same resource appears in the main module. That's why androidmodule2.MainActivity is picking up the activity_main layout from the app module: the resource of the same name in the library module is being thrown away during the build process.
Change the name of the layout resource in one of the modules so there's no name collision and all should then be well. (Well, at least this particular problem should go away.)


text:
Q: Why does Release/Debug have a different result for std::min? Here is the test program:
void testFunc()
{
    double maxValue = DBL_MAX;
    double slope = std::numeric_limits<double>::quiet_NaN();

    std::cout << "slope is " << slope << std::endl;
    std::cout << "maxThreshold is " << maxValue << std::endl;
    std::cout << "the_min is " << std::min( slope, maxValue) << std::endl;
    std::cout << "the_min is " << std::min( DBL_MAX, std::numeric_limits<double>::quiet_NaN()) << std::endl;
}

int main( int argc, char* argv[] )
{
    testFunc();
    return 0;
}

In Debug, I get:
slope is nan
maxThreshold is 1.79769e+308
the_min is nan
the_min is 1.79769e+308

In Release, I get:
slope is nan
maxThreshold is 1.79769e+308
the_min is 1.79769e+308
the_min is nan

Why would I get a different result in Release than Debug?
I already checked Stack Overflow post Use of min and max functions in C++, and it  does not mention any Release/Debug differences.
I am using Visual Studio 2015.

A: In IEEE 754 comparing NAN to anything will always yield false, no matter what it is.
slope > 0; // false
slope < 0; // false
slope == 0; // false

And, more importantly for you
slope < DBL_MAX; // false
DBL_MAX < slope; // false

So it seems that the compiler reorders the parameters/uses > or <= instead of <, and that's why you get the differing results.
For example, those functions could be described as such
Release:
double const& min(double const& l, double const r) {
    return l <= r ? l : r;
}

Debug:
double const& min(double const& l, double const& r) {
    return r < l ? r : l;
}

The requirements (LessThanComparable) on std::min aside, those have the same meaning arithmetically. But they yield different results when you use them with NaN.

A: Got it:
Here is the implementation used by VS in Debug mode (with _Pred being DEBUG_LT, LT for Lower Than):
template<class _Pr,
    class _Ty1,
    class _Ty2> inline
    _CONST_FUN bool _Debug_lt_pred(_Pr _Pred,
        _Ty1&& _Left, _Ty2&& _Right,
        _Dbfile_t _File, _Dbline_t _Line)
    {   // test if _Pred(_Left, _Right) and _Pred is strict weak ordering
    return (!_Pred(_Left, _Right)
        ? false
        : _Pred(_Right, _Left)
            ? (_DEBUG_ERROR2("invalid comparator", _File, _Line), true)
            : true);
    }

Which is equivalent to (more readable):
    if (!_Pred(_Left, _Right))
    {
        return false;
    }
    else
    {
        if ( _Pred(_Right, _Left) )
        {
            assert( false );
            return true;
        }
        else
        {
            return true;
        }
    }

Which, again is equivalent to (!_Pred(_Left, _Right)). Transcripted as a macro, it becomes #define _DEBUG_LT(x, y)   !((y) < (x)) (i.e: NOT right < left).
Release implementation is actually a macro #define _DEBUG_LT(x, y) ((x) < (y)) (i.e: left < right).
So Debug (!(y<x)) and Release (x<y) implementations are definitely not the same and they do behave differently if one parameter is a NaN...! Don't ask why they did that....

A: You didn't specify which floating point representation format your processor uses. But, since you use Visual Studio, I'll assume that you use Windows, and then I'll assume that your processor uses IEEE 754 representation.
In IEEE 754, NaN is unordered in respect to every number. This means that (NaN < f) == false and (f < NaN) == false for any value of f. Pedantically, this means that floating point numbers that support NaN do not meet the requirements of LessThanComparable which is a requirement for std::min. Practically std::min behaves as specified in the standard as long as neither argument is NaN.
Since one of the arguments is NaN in your code, the result is unspecified by the standard - it could be one or the other depending on any external factors such as release vs debug build, version of compiler, phase of the moon, etc.


text:
Q: How do I make each of the list items in an array clickable? I have a list of different cities that I have to sort by location closest to me.
Here is the fiddle: http://jsfiddle.net/t24g3umj/
var jsonString ='{"City A":{"Position":{"Longitude":9.96233,"Latitude":49.80404}},"City B":{"Position":{"Longitude":6.11499,"Latitude":50.76891}},"City C":{"Position":{"Longitude":6.80592,"Latitude":51.53548}},"City D":{"Position":{"Longitude":9.50523,"Latitude":51.31991}},"City E":{"Position":{"Longitude":9.66089,"Latitude":48.70158}},"City F":{"Position":{"Longitude":9.93368,"Latitude":53.55608}},"City G":{"Position":{"Longitude":11.56122,"Latitude":48.14496}},"City H":{"Position":{"Longitude":13.34253,"Latitude":52.5319}},"City I":{"Position":{"Longitude":6.11327,"Latitude":50.77715}},"City J":{"Position":{"Longitude":13.36671,"Latitude":52.54344}}}';

var myData = JSON.parse(jsonString);

$(document).ready(function () {

var distanceObj = [],
    i = 0;
$.each(myData, function (a, b) {
    distanceObj[i] = {
        distance: hesapla(9.9608999, 49.7222842, b.Position.Longitude, b.Position.Latitude),
        location: a
    };
    ++i;
});

distanceObj.sort(function (a, b) {
    return parseInt(a.distance) - parseInt(b.distance)
});

$.each(distanceObj, function (a, b) {
    $('#groups').append('
' + b.location + ': ' + b.distance + 'm
');
});

console.log(distanceObj);

function hesapla(meineLongitude, meineLatitude, long1, lat1) {
    erdRadius = 6371;

    meineLongitude = meineLongitude * (Math.PI / 180);
    meineLatitude = meineLatitude * (Math.PI / 180);
    long1 = long1 * (Math.PI / 180);
    lat1 = lat1 * (Math.PI / 180);

    x0 = meineLongitude * erdRadius * Math.cos(meineLatitude);
    y0 = meineLatitude * erdRadius;

    x1 = long1 * erdRadius * Math.cos(lat1);
    y1 = lat1 * erdRadius;

    dx = x0 - x1;
    dy = y0 - y1;

    d = Math.sqrt((dx * dx) + (dy * dy));

    return Math.round(d * 1000);
};
});

I am wondering, how to make each of the li elements clickable?
Also, a secondary question is how to filter a special city to the top of the list regardless of distance?
Thanks in advance to the wonderful community at stackoverflow.

A: *

*You can also use delegated event binding on the handler using on, given that you are adding li dynamically:

$(document).ready(function () {
    $('#groups').on('click', 'li', function() {
       // handler here
    }

*You can use jQuery .prepend() to add an li to the top of the list, instead of append() which adds it to the bottom

$('#groups').prepend('
I am special ...
');

A: Is that You Want?
$.each(distanceObj, function(a, b) {
    $('#groups').append('
' + b.location + ': ' + b.distance + 'm
');
});

A: To make the elements clickable, you need to use "" tag, within each li. Below is the modified code.
$.each(distanceObj, function(a, b) {
    $('#groups').append('
' + b.location + ': ' + b.distance + 'm
');
});

http://jsfiddle.net/t24g3umj/1/


text:
Q: How to display an array of 0 and 1, in a textview in theory my matrix is formed, but I want to show it, as I show it; Is it correct to show it in a textview?, or in which I can show it.
My: "matrix [y] [x];"; only shows the last.
public void Matriz(){
    BitmapDrawable drawable = (BitmapDrawable) imgviewREXBlancoNegro.getDrawable();
    Bitmap bitmap = drawable.getBitmap();

    int Width =  bitmap.getWidth();
    int Height  =  bitmap.getHeight();

    int matriz[][] = new int [Height][Width];

    for (int x=0 ; x<=Width-1; x++) {
        for (int y=0 ; y<=Height-1; y++) {
            int coordenada = bitmap.getPixel(x,y);// pixel
            double r = Color.red(coordenada);
            double g = Color.green(coordenada);
            double b = Color.blue(coordenada);
            double alpha = Color.alpha(coordenada);

            if (r == 255 && g == 255 && b == 255 && alpha == 255) {
                 matriz[y][x]=0;
            }else{
                 matriz[y][x]=1;
            }
            txtviewmatriz.setText(matriz[y][x]+"");
        }
    }

A: The trick is to collect your output into a variable and set this value after your entire collection ends.
If you call the setText() method inside the loops, you override the content of the text field with each call. This is why you only see the last combination.
 String output = "";

 for (int x=0 ; x<=Width-1; x++) {
      for (int y=0 ; y<=Height-1; y++) {
          // your code

          output += matriz[y][x] + " ";
      }
 }

 txtviewmatriz.setText(output);


text:
Q: i want to join two ffmpeg command to gather This command is for add video in to video :

ffmpeg -i 1.mp4 -i over.mp4 -filter_complex
  "[0:v]setpts=PTS-STARTPTS,scale=224x400[top];[1:v]setpts=PTS-STARTPTS,scale=100x44[bottom];[top][bottom]overlay=x=115:y=346:eof_action=pass;[0]volume=0.7[a1];[1]volume=0.3[a2];[a1][a2]amix=inputs=2[a]"
  -acodec aac -vcodec libx264 -map 0:v -map "[a]" out.mp4

This command is for add water mark and username text in to video :

ffmpeg -i 1.mp4 -i watermark.png -filter_complex
  "overlay=main_w-overlay_w-5:main_h-overlay_h-15,drawtext=fontfile=/path/to/font.ttf:text='@Unknown':
  fontcolor=white: fontsize=10: box=1: boxcolor=black@0.0: boxborderw=5:
  x=160: y=380" -codec:a copy output.mp4

If i want to execute this two command together then what i have to do OR how can i join this two command in one ?

A: Add the watermark and drawtext after the overlay.
ffmpeg -i 1.mp4 -i over.mp4 -i watermark.png -filter_complex "[0:v]setpts=PTS-STARTPTS,scale=224x400[top];[1:v]setpts=PTS-STARTPTS,scale=100x44[bottom];[top][bottom]overlay=x=115:y=346:eof_action=pass[vid];[vid][2]overlay=main_w-overlay_w-5:main_h-overlay_h-15,drawtext=fontfile=/path/to/font.ttf:text='@Unknown': fontcolor=white: fontsize=10: box=1: boxcolor=black@0.0: boxborderw=5: x=160: y=380;[0]volume=0.7[a1];[1]volume=0.3[a2];[a1][a2]amix=inputs=2" -acodec aac -vcodec libx264 out.mp4


text:
Q: How to disable xhci-hcd (in LibreElec) (Disable USB 3.0) I asked at the same question at LibreELEC forum but I am trying here as well.
I'm running media box with LibreELEC and external drives (all USB3.0).
The box itself does not have USB3 capabilities (although the USB driver supports USB3 the SoC S912 that controls it does not).
Some drives - namely WD My Passport 2TB - have problems communicating with the box.
If the box is idle or do just ls or create empty dir, the drive is ok.
But if I start to copy a large file there the dmesg log looks something like this:
[66588.736256@6] usb 1-1.3: reset high-speed USB device number 4 using xhci-hcd
[66588.736292@6] xhci-hcd xhci-hcd.0.auto: Setup ERROR: setup context command for slot 3.
[66588.816251@6] usb 1-1.3: reset high-speed USB device number 4 using xhci-hcd
[66588.816289@6] xhci-hcd xhci-hcd.0.auto: Setup ERROR: setup context command for slot 3.
[66588.896254@6] usb 1-1.3: reset high-speed USB device number 4 using xhci-hcd
[66588.937029@4] xhci-hcd xhci-hcd.0.auto: xHCI xhci_drop_endpoint called with disabled ep ffffffc06278b980
[66588.937047@4] xhci-hcd xhci-hcd.0.auto: xHCI xhci_drop_endpoint called with disabled ep ffffffc06278b9c0

After googling around, it seems the problem is USB support in my very old kernel (3.14.29).
Some answers I found suggest turning the xHCI off in favour of eHCI either by blacklisting the module, or by 'quirks' (which I believe effectively blacklists it for certain device IDs).
Since my box does not really support USB3 anyway, I wouldn't lose any functionality.
Unfortunately, I struggle with applying the solutions to the LibreELEC environment.
All drives use usb-storage but the root-hub uses Driver=xhci-hcd which I would like to get rid of.
Dev 4 (WD My Passport 4TB) and Dev 3 (Maxtor M3 4TB) from the lsusb output below works ok, but Dev 5 (WD My Passport 2TB) does not.
gt1:~ # lsusb -t
/:  Bus 02.Port 1: Dev 1, Class=root_hub, Driver=xhci-hcd/0p, 5000M
/:  Bus 01.Port 1: Dev 1, Class=root_hub, Driver=xhci-hcd/3p, 480M
    |__ Port 1: Dev 2, If 0, Class=Hub, Driver=hub/4p, 480M
        |__ Port 3: Dev 4, If 0, Class=Mass Storage, Driver=usb-storage, 480M
        |__ Port 4: Dev 5, If 0, Class=Mass Storage, Driver=usb-storage, 480M
    |__ Port 2: Dev 3, If 0, Class=Mass Storage, Driver=usb-storage, 480M

gt1:~ # lsusb
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 003: ID 0bc2:61b7 Seagate RSS LLC
Bus 001 Device 005: ID 1058:25e1 Western Digital Technologies, Inc.
Bus 001 Device 004: ID 1058:25e2 Western Digital Technologies, Inc.
Bus 001 Device 002: ID 05e3:0608 Genesys Logic, Inc. Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Question:
How to apply the solutions (blacklist module, quirks, ...) to LibreELEC environment?
Related questions:
related question


text:
Q: How to work around cdr not understanding the empty list? My problem is the butSecondLastAtom algorithm. It doesn't work because cdr doesn't comprehend an empty list. But I see no other way of writing the algorithm. It's at the end of the page. Everything works but when the last element of a list is a list.
http://lpaste.net/110959
The problem is in the recursive call of (cdr (cdr l)) but more in the 3rd condition. Idk what to do. I'm just going to stop tonight and start fresh in the morning.
((and (isAtom (second_last_element l)) (notAtom (last_element l)))
        (cons
           (car l)
             (butSecondLastAtom (last_element l))))

A: I think the main problem in your code is the use of null? or cdr on the cdr of a list, both in flatten and in butLast. Don't do this; always use the procedures and predicates on the list itself.
I'd suggest the following:
Flattening the list
Most Schemes have a version of flatten build-in, which takes care of nested lists and improper lists. The version you implemented is not entirely correct (try (flatten '())), use this one:
(define (flatten lst)
  (let loop ((lst lst) (res null))
    (cond
      ((null? lst) res)
      ((pair? lst) (loop (car lst) (loop (cdr lst) res)))
      (else        (cons lst res)))))

> (flatten '(1 2 (3 (4 5 6))))
'(1 2 3 4 5 6)
> (flatten '(1 2 (3 (4 5 (6)))))
'(1 2 3 4 5 6)
> (flatten '())
'()

Dropping the second last element
So this becomes much easier now, looping through a simple flat proper list while keeping track of the last (n-1) and second-last (n-2) element. An example implementation is:
(define (butSecondLastAtom lst)
  (define flst (flatten lst))
  (if (< (length flst) 2)
      flst
      (let loop ((flst (cddr flst)) (n-2 (car flst)) (n-1 (cadr flst)) (res null))
        (if (null? flst)
            (reverse (cons n-1 res)) ; here we drop the second-last element
            (loop (cdr flst) n-1 (car flst) (cons n-2 res))))))

If you want to avoid going through the list twice (once for length, once for the loop), you can also keep track of the length yourself:
(define (butSecondLastAtom lst)
  (define flst (flatten lst))
  (let loop ((lst flst) (len 0) (n-2 #f) (n-1 #f) (res null))
    (if (null? lst)
        (if (< len 2)
            flst
            (reverse (cons n-1 res))) ; here we drop the second-last element
        (loop (cdr lst) (add1 len) n-1 (car lst) (if (< len 2) null (cons n-2 res))))))

Testing
> (butSecondLastAtom '(1 2 (3 (4 5 6))))
'(1 2 3 4 6)
> (butSecondLastAtom '(1 2 (3 (4 5 (6)))))
'(1 2 3 4 6)
> (butSecondLastAtom '(((a))))
'(a)
> (butSecondLastAtom '())
'()