Q:

generating strings from a file

This is the start of a solution for Project Euler Problem 22.  I have a sample version of their text file from which I am trying to generate names one name at a time.  This is a link to the documentation on string methods.  I have written the following code for the task:
def name_gen():
    with open('C:/python/namessample.txt') as nameFile:
        nameGenerator = (i.strip('"').split(sep='","') for i in nameFile)
        for name in nameGenerator:
            yield type(name), type(nameGenerator), type(nameFile), name

for i in name_gen():
    print(i)

This is the code output:
(<class 'list'>, <class 'generator'>, <class '_io.TextIOWrapper'>, ['DOUGLASS', 'CORDELL', 'OSWALDO', 'ELLSWORTH', 'VIRGILIO', 'TONEY', 'NATHANAEL', 'DEL', 'BENEDICT', 'MOSE', 'JOHNSON', 'ISREAL', 'GARRET', 'FAUSTO', 'ASA', 'ARLEN', 'ZACK', 'WARNER', 'MODESTO', 'FRANCESCO', 'MANUAL', 'GAYLORD', 'GASTON', 'FILIBERTO', 'DEANGELO', 'MICHALE', 'GRANVILLE', 'WES', 'MALIK', 'ZACKARY', 'TUAN', 'ELDRIDGE', 'CRISTOPHER', 'CORTEZ', 'ANTIONE', 'MALCOM', 'LONG', 'KOREY', 'JOSPEH', 'COLTON', 'WAYLON', 'VON', 'HOSEA', 'SHAD', 'SANTO', 'RUDOLF', 'ROLF', 'REY', 'RENALDO', 'MARCELLUS', 'LUCIUS', 'KRISTOFER', 'BOYCE', 'BENTON', 'HAYDEN', 'HARLAND', 'ARNOLDO', 'RUEBEN', 'LEANDRO', 'KRAIG', 'JERRELL', 'JEROMY', 'HOBERT', 'CEDRICK', 'ARLIE', 'WINFORD', 'WALLY', 'LUIGI', 'KENETH', 'JACINTO', 'GRAIG', 'FRANKLYN', 'EDMUNDO', 'SID', 'PORTER', 'LEIF', 'JERAMY', 'BUCK', 'WILLIAN', 'VINCENZO', 'SHON', 'LYNWOOD', 'JERE', 'HAI', 'ELDEN', 'DORSEY', 'DARELL', 'BRODERICK', 'ALONSO'])

The type for nameFile and nameGenerator seem to be correct, but name should ideally be one string at a time, not a list of strings.  I would guess that the reason why name is a list is because .split returns a list, however I could not figure out a different way to separate the names in the file.  Also I used .strip to remove the leading and trailing quotes.

A:

The file contains one line, so there is no need to loop over the file, really. Just loop over the split list:
def name_gen():
    with open('C:/python/namessample.txt') as nameFile:
        for name in nameFile.read().split(','):
            yield name.strip('"')

or just return the whole list; you've read it into memory already anyway:
def name_gen():
    with open('C:/python/namessample.txt') as nameFile:
        return [name.strip('"') for name in nameFile.read().split(',')]

If you did have multiple lines with each line containing multiple names, you could nest loops:
def name_gen():
    with open('C:/python/namessample.txt') as nameFile:
        for line in nameFile:
            for name in line.rstrip('\n').split(','):
                yield name.strip('"')


Q:

What are the audible symptoms of a failing starter motor?

My 2004 Subaru WRX has 110000 miles on the odometer and I'm worried about the original equipment starter motor.  Here are the audible symptoms that have me concerned:

During the winter, I noticed that sometimes on a (very) cold start, turning the key would result in quite a grinding screech.  However, the car would start right up.
As the weather has gotten warmer, I've noticed that even on a warm day, the starter still makes a low amplitude grinding squeal.  Much harder to hear but it's there.

Here are the things that I am pretty sure aren't problems:

Alternator - the voltage appears good on the dash.
Oil - Subaru's are prone to some piston slap and I was afraid I was hearing a low oil condition.  Not so.
Battery is not new but isn't original.

To date, there haven't been any problems starting the car.  However, I'm naturally concerned, especially considering the expense that we've recently put into the wife's car (!).
Does any of the above sound like a failing starter?  Or should I listen elsewhere?

A:

It depends specifically on what's wrong with the starter.

Sometimes you hear a clicking sound when you turn the key but the starter motor gears don't actually turn.  This could actually be due to a weak battery, but if you know the battery has a full charge, then it could be the starter gears actually failing to turn.
You may hear a whining sound, similar to what you would hear of a gear turned in the starter but that didn't actually turn the flywheel.  This could be caused by the gears turning in the starter, but without the starter gear moving into position on the flywheel.

In both of those cases, the entire starter usually needs to be removed.  Most auto parts stores can test the unit independent of the other systems on the car, which would give you an even more accurate diagnosis as to the problem by either confirming or ruling out the starter motor/solenoid as the problem.
UPDATE:
Keep in mind that most of the time the starter won't just up and die.  It's generally a slow decline where you'll experience these symptoms occasionally, but the starter will still kick over with a few tries or with the tap of a hammer on the starter.  If you let these symptoms persist, eventually you will have a completely dead starter, and you'll be sitting in a parking lot somewhere waiting for a tow truck or a buddy with some tools, a jack, and a starter!
From what you describe, I would definitely suggest getting it checked out.  Cars talk to you and tell you when they're sick.  It's up to us to listen and take action so we continue moving from points A to B and back to A.
Here is an article on How to Spot Symptoms of a Bad Starter Motor, which you may find helpful

A:

Beyond what jmort253 said, and separated out into a specific answer at Bob Cross' suggestion:
I ran into a particular difficult to track down problem which was caused by the clutch in the starter opening up. The starter would wind up and make a screeching sound, but sometimes wouldn't turn the engine over. I was thinking it might be a broken tooth on the flywheel or bad solenoid causing the starter not to engage, but it ended up being the clutch between the starter motor and the starter gear.
In retrospect, I was trying to save some money by fixing only the part that was broken, thinking it was the solenoid that wasn't engaging the gear with the flywheel, but I should have followed the parts department recommendation and just bought a whole new starter.


Q:

TFileOpenDialog FileTypes : how to change at runtime

In a TFileOpenDialog I set the FileTypes property to a custom list of files populated by selected files from the current folder.
dlg := TFileOpenDialog.Create( self );
Filter := TStringList.Create();
// ...
// Filter contains the selected files
  if Filter.Count>0 then
    begin
      msg := '';
      for i := 0 to Filter.Count-1 do
          msg := msg + Filter[i] + ';';
      dlg.FileTypes.Clear;
      dlg.FileTypes.Add.DisplayName := '';
      dlg.FileTypes.Add.FileMask := msg;
    end;

It works as desired.
I handle the OnFolderChange event in that I create a new file selection from the newly selected folder. I set the FileTypes property to this new list.
But I observe that the FileTypes property remains unchanged. As a result no files are found.
Am I right to assume that the FileTypes property cannot be changed for the current TFileOpenDialog?

A:

This control is a wrapper around the common item dialog. The documentation for IFileDialog::SetFileTypes says:

This method must be called before the dialog is shown and can only be called once for each dialog instance. File types cannot be modified once the Common Item dialog box is displayed.

So you cannot modify the file types after the dialog has been shown.
FWIW, each time you call FileTypes.Add you are adding a new file type. You need to call FileTypes.Add once per file type.


Q:

How can we restrict future date selection from tkCalender Date Entry picker in Python?

I am creating a graphic user application in Python using tkinter. For date picker I am using Date Entry from tkCalendar for this purpose. The requirement is to restrict user from selecting future dates. How can I achieve that in this case?
Python version 3.7
tkCalendar version 1.3.1

A:

You can use the set_date method from DateEntry combined with root.after() to control the user input.
import tkinter as tk
from tkcalendar import DateEntry
from datetime import datetime
from tkinter import messagebox

root = tk.Tk()
time_now = datetime.now()
calendar = DateEntry(root, width=12, background='darkblue',foreground='white', borderwidth=2)
calendar.pack()

def date_check():
    calendar_date = datetime.strptime(calendar.get(),"%m/%d/%y")
    if calendar_date > time_now:
        messagebox.showerror("Error", "Selected date must not exceed current date")
        calendar.set_date(time_now)
    root.after(100,date_check)

root.after(100,date_check)

root.mainloop()


Q:

Does filling your reputation bar with paragon prevent you from filling it with renegade?

If I have played through the game and done a good job of responding to all the opportunities to gain reputation and paragon points then my bar will probably be fairly full and I might have 2 or 3 tick mark levels of Paragon points.
Let's assume that when I play through again in new game+ I want to try the renegade path.  My reputation is transferred from the last play through, does this mean I will still have a full Paragon bar?  If so, will I be restricted from filling my renegade bar somehow or will I encounter more "+reputation" opportunities to that I could have both the P&R bars full simultaneously?

A:

Yes your bar will update accordingly.
It's because even though it's hidden, you actually have points (like 100 paragon points etc.) and the bar is just the ratio of Paragon:Renegade:Neutral (the neutral part doesn't appear on the bar, just increases its size).
So you might end a game with 1000 paragon points and 100 renegade points.
Starting a new game plus will keep those scores. If you then finish the game gaining 1000 renegade and 100 paragon, you'll have 1100 of each and be split perfectly.


Q:

Replay a sound using EvalSound before the sound is ended

I have this code:
<script>
function EvalSound(soundobj) {
  var thissound=document.getElementById(soundobj);
  thissound.Play();
}
</script>

<embed src="success.wav" autostart=false width=1 height=1 id="sound1"
enablejavascript="true">

I play this sound when a function is triggered, with this javascript code. My code looks like this:
-function code-
pA = false;
EvalSound('sound1');
} else {
-more code-

This all works, but if triggers again before the sound is done playing, it will do nothing. I want it to replay the sound immediately when the function is triggered again, even if the sound isn't ended yet.
Tried EvalSoundOff but no luck with that one
Hope this is possible, all suggestions are welcome thanks!!

A:

Adding thissound.Rewind(); above thissound.Play(); worked for me!


Q:

Mounted a windows file in ubuntu, can't access it through terminal

So I am 95% sure I mounted the drive(files) that I wanted from a Windows server to ubuntu. I followed the tutorial on http://www.howtogeek.com/howto/22518/how-to-mount-a-remote-folder-in-ubuntu/ and I am given the option to unmount the folder I set up and am calling engineer.
I am trying to push my code onto a git repo on the server.  I cannot figure out how to access the files in what I mounted through the terminal.  Is there something similliar to the cd command to use in the terminal to access the server?  I don't know if this picture helps, but there are two drives mounted on computer which I can access
fine.
However engineer is listed under network and i do not know how to access it in terminal.  When I hover the mouse over it smb::/192./engineering does appear.  But I cannot figure out how to access this.

A:

Just drag the folder or file you want to access, to the terminal, and you will have the location to access it in the terminal.


Q:

How to get the difference between now and a different date (in minutes) using ksh (or another shell script)?

Giving two variables with the followind values:
date1 = Mon Feb 27 16:21:34 WET 2012
date2 = Mon Feb 27 16:29:34 WET 2012

How can I make the difference (in minutes) between them using ksh?
I'm using Solaris 10.

I made what you said and this was the error:
$ function d { echo $((($(date -d"$2" +%s)-$(date -d"$1" +%s))/60)); }
$ d "Mon Feb 27 16:21:34 WET 2012" "Mon Feb 27 16:29:34 WET 2012"
date: illegal option -- d
date: illegal option -- M
date: illegal option -- o
date: illegal option -- n
date: illegal option --
date: illegal option -- F
date: illegal option -- e
date: illegal option -- b
date: illegal option --
date: illegal option -- 2
date: illegal option -- 7
date: illegal option --
date: illegal option -- 1
date: illegal option -- 6
date: illegal option -- :
date: illegal option -- 2
date: illegal option -- 9
date: illegal option -- :
date: illegal option -- 3
date: illegal option -- 4
date: illegal option --
date: illegal option -- W
date: illegal option -- E
date: illegal option -- T
date: illegal option --
date: illegal option -- 2
date: illegal option -- 0
date: illegal option -- 1
date: illegal option -- 2
usage:  date [-u] mmddHHMM[[cc]yy][.SS]
        date [-u] [+format]
        date -a [-]sss[.fff]
date: illegal option -- d
date: illegal option -- M
date: illegal option -- o
date: illegal option -- n
date: illegal option --
date: illegal option -- F
date: illegal option -- e
date: illegal option -- b
date: illegal option --
date: illegal option -- 2
date: illegal option -- 7
date: illegal option --
date: illegal option -- 1
date: illegal option -- 6
date: illegal option -- :
date: illegal option -- 2
date: illegal option -- 1
date: illegal option -- :
date: illegal option -- 3
date: illegal option -- 4
date: illegal option --
date: illegal option -- W
date: illegal option -- E
date: illegal option -- T
date: illegal option --
date: illegal option -- 2
date: illegal option -- 0
date: illegal option -- 1
date: illegal option -- 2
usage:  date [-u] mmddHHMM[[cc]yy][.SS]
        date [-u] [+format]
        date -a [-]sss[.fff]
0
$

A:

well, here's a C program that might work. it's (lightly) tested on solaris.
it uses the POSIX standard strptime(3) function to parse a given string and prints the result in epoch seconds.
in theory invocation should be
$ ./strptime "Mon Feb 27 16:21:34 WET 2012" "%a %b %e %H:%M:%S %Z %Y"

but i haven't been able to get it to recognize the "WET" timezone, so you may need to just put that in as a literal:
$ ./strptime "Mon Feb 27 16:21:34 WET 2012" "%a %b %e %H:%M:%S WET %Y"
1330377694

here's the code:
#define _GNU_SOURCE

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <time.h>

#define ARGS 3
#define USAGE printf("Usage: %s string format\n",argv[0]);
#define EARGS { printf("%s: %s arguments (%d)\n",argv[0],argc<ARGS?"Insufficient":"Too many",argc-1); USAGE; exit(2); }

#define err(_s,_p,_f) {fprintf(stderr,"%s: %s: %s\n",(_p),(_f),strerror(errno));exit(_s);}

int main(int argc,char**argv){
        struct tm tm;
        time_t t;

        if(argc!=ARGS)EARGS;

        strptime(argv[1],argv[2],&tm);
        if(-1==(t=mktime(&tm)))err(1,argv[0],"mktime");
        if(0>printf("%lld\n",(long long)t))err(1,argv[0],"printf");
        return 0;
}

compile with something along the lines of
$ CFLAGS='-W -Wall -Wshadow -std=gnu99' make strptime

(probably requires gcc, no idea if sun cc will work here)


Q:

mergeForm() - symfony

I'm using mergeForm to display a form and then another merged into it.
The form I'm editting is the admin module for Article with a ContentItemForm merged.
Schema in simple terms is:
Article
id

ContentItem
id
article_id
is_comment

In my ArticleForm I have the following:
  public function configure()
  {
     $this->mergeForm(new ContentItemForm(ContentItemPeer::retrieveByPK($this->getObject()->getId())));
  }

  public function save($con = null)
  {
    parent::save();

    $this->updateContentItem();

    return $this->object;
  }

  protected function updateContentItem()
  {
    // update content item
    if (!is_null($article_content = $this->getContentItem()))
    {

     $values = $this->getValues();
     if ( $article_content->isNew() )
     {
         $values['article_id'] = $this->object->getId();
     }

      $article_content->fromArray($values, BasePeer::TYPE_FIELDNAME);

      $article_content->save();
    }
   }

   protected function getContentItem()
   {
      if (!$this->object->getContentItem())
      {
        return new ContentItem();
      }
      else
      {
      return $this->object->getContentItem();
      }
   }

In the admin, this merges the form and i see the contentItemForm and it's fields.
is_comment is a boolean value and therefore displays a checkbox.
When I have it checked, it is suppoed to update the is_comment field in the content_item table to 1, unchecked and saved, should be 0.
Unfortunately, this isn't working. The is_comment field is never updated.
Does anyone know what could be causing this?

A:

Have you set a relation between Article and ContentItem? Then you shouldn't have to do anything specific in the save() method.


Q:

loading time of IDependencyResolver.GetService() is too long

The loading time of my website (asp.net mvc 4) is too long when it runs on the server, on my local machine it loads very fast!
I installed Glimpse for MVC to see what is happening. Glimpse trace tab shows that it is taking 12879 ms for 'IDependencyResolver.GetService' to load.
The full message is:

IDependencyResolver.GetService()
  = ASP._Page_Views_Cagegories_GetByCity_cshtml

The server is dedicated server and should be strong enough.
Does anyone can advise what can I do to solve this?
Page url: http://2send.co.il/City/%D7%A2%D7%A4%D7%95%D7%9C%D7%94
Thanks.

A:

I don't know exactly what changed on my server but the problem was solved after I run windows update.
Among the other updates, I saw framework 4 update so I guess that's it!


Q:

Is parseInt() supposed to work like this?

If I write this script :
alert(parseInt("123blahblahblah456"));
I get the alert with the value 123
Ideally, shouldn't the function NOT do anything since it is an invalid integer string?
Similar is the case with parseFloat()

A:

Yes, cf all the anwers. I'd like to add that this is why checking if certain value can be converted to a number, it's better to use Number or just +.
Number("123blahblahblah456"); //=> NaN
Number("123"); //=> 123
+"97.221" //=> 97.221
// if the conversion result needs to be an int
Math.round(Number("123.4567")); //=> 123

Be aware though that Number in some cases (unexpectely) returns 0.
+null   //=> 0
+"  "   //=> 0
+""     //=> 0
+false  //=> 0
+[]     //=> 0

A:

parseInt attempts to parse the string until it finds a non-integer value, at which point it returns whatever it had.
So if the string is:

1234abcd - it returns 1234
1a3f - it returns 1
a14883 - it returns NaN
1.5 - it returns 1
-1.3a - it returns -1

Same with parseFloat except that won't break on a .

1234abcd - it returns 1234
1a3f - it returns 1
a14883 - it returns NaN
1.5 - it returns 1.5
-1.3a - it returns -1.3

A:

Yes: parseInt() is absolutely meant to work like that; to quote the Mozilla Developer Network entry:

The parseInt function converts its first argument to a string, parses it, and returns an integer or NaN. If not NaN, the returned value will be the decimal integer representation of the first argument taken as a number in the specified radix (base). For example, a radix of 10 indicates to convert from a decimal number, 8 octal, 16 hexadecimal, and so on. For radices above 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used.
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.

It seems that parseInt() is explicitly expecting to take a string and will take the first sequence of numbers (until it encounters an invalid numerical character) and return that as a number of whatever base was specified in the radix parameter.
Incidentally, to reduce errors when parsing the strings passed to parseInt() remember to use the radix parameter, for example:
parseInt('123odod24',10); // for base-10
parseInt('123odod24',16); // for base-16

Reference:

parseInt() at the MDC.


Q:

AJAX call with Content Type Application/json not retrieving data from PHP

I'm having trouble retrieving JSON data from an AJAX call.
I tried to get JSON data from different webpages with PHP cURL; this works successfully. The PHP page is called from a Jquery AJAX call. I can get the JSON data to return as a string from one of the websites, but not the other.
jQuery
    var formData = {"data1" : a, "data2" : b, "data3" : c};

    $.ajax({
        dataType: "json",
        contentType : "application/json; charset=UTF-8",
        url: '/getjson.php',
        data : formData,
        success: function(response) {
            CurrentArray = response;
        }
    });

PHP
<?php
//select webpage to get JSON from
switch ($_GET['data1']){
    Case 1:
        $result = get_with_curl($webpage1);//select webpage 1
    break;

    Case 2:
        $result = get_with_curl($webpage2);//select webpage 1
    break;
}
echo $result['FILE'];
?>

1. What works

AJAX call to PHP which is executing a CURL call
Curls sends back a JSON string with Content Type : text/html;
charset:UTF-8
This JSON string is retrieved back in the AJAX call

The symbol (in the # column) of this command is displayed as <> in fiddler
2. What doesn't work

When doing this at another site, CURL sends back a JSON string but the Content-Type of the retrieving curl command in PHP is now applcation/json; charset;UTF-8. When I echo this in PHP, the object will not retreived in AJAX.

Here the symbol (in the # column)  of this command is displayed as {JSON} in the fiddler.
When I modify Data Type into "Text" and the Content Type into "text/plain ; charset:UTF-8", The data (as from point 2) is retreived in text; but I want the data in an object format.
Relevant AJAX PHP issue 1
Relevant AJAX PHP issue 2

A:

Finally Solved the problem,
I completely teared down the PHP cUrl function, in a way that only basic functionality was left. Now the JSON data is returned to the AJAX call. What I noticed was that there were some warnings when the cUrl function was executed (like undefined variables) but the JSON data was still returned in the PHP function. So, primary you should think that warnings should be no problem. After resolve the warning coming from the cUrl function, the JSON data as returned properly to the AJAX call. In other words, the Ajax call will not return data when a PHP warning is occurring.


Q:

Entender instanciacao de classes

Tenho uma dúvida e gostaria de entender melhor como funciona a instanciação de classes. Mais especificamente a forma mais adequada de fazer(se existir) e os impactos de fazer da forma errada.
Supondo esses dois cenários, qual devo utilizar e Porque?
Cenário 1: Instanciando fora dos métodos.
public class PerfilController : Controller
{
    PerfilDTO viewDTO = new PerfilDTO();
    Perfil perfilNEG= new Perfil();
    Recurso recursoNEG = new Recurso();

    public ActionResult Cadastro()
    {
        viewDTO.ListaPerfis = perfilNEG.ObterPerfis();
        viewDTO.ListaRecursos = recursoNEG.ObterRecursos();

        return View(viewDTO);
    }

    public ActionResult Listagem()
    {
        viewDTO.ListaPerfis = perfilNEG.ObterPerfis();
        viewDTO.ListaRecursos = recursoNEG.ObterRecursos();

        return View(viewDTO);
    }
}

Cenário 2: Instanciando dentro dos métodos
public class PerfilController : Controller
{
    public ActionResult Cadastro()
    {
        PerfilDTO viewDTO = new PerfilDTO();
        Perfil perfilNEG= new Perfil();
        Recurso recursoNEG = new Recurso();

        viewDTO.ListaPerfis = perfilNEG.ObterPerfis();
        viewDTO.ListaRecursos = recursoNEG.ObterRecursos();

        return View(viewDTO);
    }

    public ActionResult Listagem()
    {
        PerfilDTO viewDTO = new PerfilDTO();
        Perfil perfilNEG= new Perfil();
        Recurso recursoNEG = new Recurso();

        viewDTO.ListaPerfis = perfilNEG.ObterPerfis();
        viewDTO.ListaRecursos = recursoNEG.ObterRecursos();

        return View(viewDTO);
    }
}

OBS: Se houver outra forma diferente e melhor também podem me alertar.

A:

Ao meu ver:
Instanciando da primeira forma, ao você criar o objeto PerfilController também serão criados mais 3 objetos em memória (PerfilDTO, Perfil e Recurso) mesmo se eles nunca forem usados.
Instanciando da segunda forma, os 3 objetos mencionados serão criados apenas quando os métodos forem chamados, ou seja, quando realmente for necessário. A desvantagem é que você precisa instanciar em cada método (repetição de código) e os objetos serão criados diversas vezes em memória conforme o número de chamadas ao método.
O que você poderia fazer (isso que vou falar é passível de análise) é se utilizar do padrão de projetos Singleton, que garante apenas uma instância de determinado objeto. Exemplo:
private ClasseExemplo getObjetoExemplo() {
    if (objetoExemplo == null) {
        objetoExemplo = new ClasseExemplo();
    }
    return objetoExemplo;
}

E onde for necessário, bastaria usar esse método:
objeto.objetoExemplo = getObjetoExemplo():

Assim estaria garantido que o objeto seria instanciado apenas quando necessário e somente uma vez.
Quis dar minha contribuição conforme aquilo que eu entendo, quem sabe outras pessoas expliquem de forma mais ampla e didática que eu.


Q:

In Java, can & be faster than &&?

In this code:
if (value >= x && value <= y) {

when value >= x and value <= y are as likely true as false with no particular pattern, would using the & operator be faster than using &&?
Specifically, I am thinking about how && lazily evaluates the right-hand-side expression (ie only if the LHS is true), which implies a conditional, whereas in Java & in this context guarantees strict evaluation of both (boolean) sub-expressions. The value result is the same either way.
But whilst a >= or <= operator will use a simple comparison instruction, the && must involve a branch, and that branch is susceptible to branch prediction failure - as per this Very Famous Question: Why is it faster to process a sorted array than an unsorted array?
So, forcing the expression to have no lazy components will surely be more deterministic and not be vulnerable to prediction failure. Right?
Notes:

obviously the answer to my question would be No if the code looked like this: if(value >= x && verySlowFunction()). I am focusing on "sufficiently simple" RHS expressions.
there's a conditional branch in there anyway (the if statement). I can't quite prove to myself that that is irrelevant, and that alternative formulations might be better examples, like boolean b = value >= x && value <= y;
this all falls into the world of horrendous micro-optimizations. Yeah, I know :-) ... interesting though?

Update
Just to explain why I'm interested: I've been staring at the systems that Martin Thompson has been writing about on his Mechanical Sympathy blog, after he came and did a talk about Aeron. One of the key messages is that our hardware has all this magical stuff in it, and we software developers tragically fail to take advantage of it. Don't worry, I'm not about to go s/&&/\&/ on all my code :-) ... but there are a number of questions on this site on improving branch prediction by removing branches, and it occurred to me that the conditional boolean operators are at the core of test conditions.
Of course, @StephenC makes the fantastic point that bending your code into weird shapes can make it less easy for JITs to spot common optimizations - if not now, then in the future. And that the Very Famous Question mentioned above is special because it pushes the prediction complexity far beyond practical optimization.
I'm pretty much aware that in most (or almost all) situations, && is the clearest, simplest, fastest, best thing to do - although I'm very grateful to the people who have posted answers demonstrating this! I'm really interested to see if there are actually any cases in anyone's experience where the answer to "Can & be faster?" might be Yes...
Update 2:
(Addressing advice that the question is overly broad. I don't want to make major changes to this question because it might compromise some of the answers below, which are of exceptional quality!) Perhaps an example in the wild is called for; this is from the Guava LongMath class (thanks hugely to @maaartinus for finding this):
public static boolean isPowerOfTwo(long x) {
    return x > 0 & (x & (x - 1)) == 0;
}

See that first &? And if you check the link, the next method is called lessThanBranchFree(...), which hints that we are in branch-avoidance territory -  and Guava is really widely used: every cycle saved causes sea-levels to drop visibly.  So let's put the question this way: is this use of & (where && would be more normal) a real optimization?

A:

Ok, so you want to know how it behaves at the lower level... Let's have a look at the bytecode then!
EDIT : added the generated assembly code for AMD64, at the end. Have a look for some interesting notes.
EDIT 2 (re: OP's "Update 2"): added asm code for Guava's isPowerOfTwo method as well.
Java source
I wrote these two quick methods:
public boolean AndSC(int x, int value, int y) {
    return value >= x && value <= y;
}

public boolean AndNonSC(int x, int value, int y) {
    return value >= x & value <= y;
}

As you can see, they are exactly the same, save for the type of AND operator.
Java bytecode
And this is the generated bytecode:
  public AndSC(III)Z
   L0
    LINENUMBER 8 L0
    ILOAD 2
    ILOAD 1
    IF_ICMPLT L1
    ILOAD 2
    ILOAD 3
    IF_ICMPGT L1
   L2
    LINENUMBER 9 L2
    ICONST_1
    IRETURN
   L1
    LINENUMBER 11 L1
   FRAME SAME
    ICONST_0
    IRETURN
   L3
    LOCALVARIABLE this Ltest/lsoto/AndTest; L0 L3 0
    LOCALVARIABLE x I L0 L3 1
    LOCALVARIABLE value I L0 L3 2
    LOCALVARIABLE y I L0 L3 3
    MAXSTACK = 2
    MAXLOCALS = 4

  // access flags 0x1
  public AndNonSC(III)Z
   L0
    LINENUMBER 15 L0
    ILOAD 2
    ILOAD 1
    IF_ICMPLT L1
    ICONST_1
    GOTO L2
   L1
   FRAME SAME
    ICONST_0
   L2
   FRAME SAME1 I
    ILOAD 2
    ILOAD 3
    IF_ICMPGT L3
    ICONST_1
    GOTO L4
   L3
   FRAME SAME1 I
    ICONST_0
   L4
   FRAME FULL [test/lsoto/AndTest I I I] [I I]
    IAND
    IFEQ L5
   L6
    LINENUMBER 16 L6
    ICONST_1
    IRETURN
   L5
    LINENUMBER 18 L5
   FRAME SAME
    ICONST_0
    IRETURN
   L7
    LOCALVARIABLE this Ltest/lsoto/AndTest; L0 L7 0
    LOCALVARIABLE x I L0 L7 1
    LOCALVARIABLE value I L0 L7 2
    LOCALVARIABLE y I L0 L7 3
    MAXSTACK = 3
    MAXLOCALS = 4

The AndSC (&&) method generates two conditional jumps, as expected:

It loads value and x onto the stack, and jumps to L1 if value is lower. Else it keeps running the next lines.
It loads value and y onto the stack, and jumps to L1 also, if value is greater. Else it keeps running the next lines.
Which happen to be a return true in case none of the two jumps were made.
And then we have the lines marked as L1 which are a return false.

The AndNonSC (&) method, however, generates three conditional jumps!

It loads value and x onto the stack and jumps to L1 if value is lower. Because now it needs to save the result to compare it with the other part of the AND, so it has to execute either "save true" or "save false", it can't do both with the same instruction.
It loads value and y onto the stack and jumps to L1 if value is greater. Once again it needs to save true or false and that's two different lines depending on the comparison result.
Now that both comparisons are done, the code actually executes the AND operation -- and if both are true, it jumps (for a third time) to return true; or else it continues execution onto the next line to return false.

(Preliminary) Conclusion
Though I'm not that very much experienced with Java bytecode and I may have overlooked something, it seems to me that & will actually perform worse than && in every case: it generates more instructions to execute, including more conditional jumps to predict and possibly fail at.
A rewriting of the code to replace comparisons with arithmetical operations, as someone else proposed, might be a way to make & a better option, but at the cost of making the code much less clear.
IMHO it is not worth the hassle for 99% of the scenarios (it may be very well worth it for the 1% loops that need to be extremely optimized, though).
EDIT: AMD64 assembly
As noted in the comments, the same Java bytecode can lead to different machine code in different systems, so while the Java bytecode might give us a hint about which AND version performs better, getting the actual ASM as generated by the compiler is the only way to really find out.
I printed the AMD64 ASM instructions for both methods; below are the relevant lines (stripped entry points etc.).
NOTE: all methods compiled with java 1.8.0_91 unless otherwise stated.
Method AndSC with default options
  # {method} {0x0000000016da0810} 'AndSC' '(III)Z' in 'AndTest'
  ...
  0x0000000002923e3e: cmp    %r8d,%r9d
  0x0000000002923e41: movabs $0x16da0a08,%rax   ;   {metadata(method data for {method} {0x0000000016da0810} 'AndSC' '(III)Z' in 'AndTest')}
  0x0000000002923e4b: movabs $0x108,%rsi
  0x0000000002923e55: jl     0x0000000002923e65
  0x0000000002923e5b: movabs $0x118,%rsi
  0x0000000002923e65: mov    (%rax,%rsi,1),%rbx
  0x0000000002923e69: lea    0x1(%rbx),%rbx
  0x0000000002923e6d: mov    %rbx,(%rax,%rsi,1)
  0x0000000002923e71: jl     0x0000000002923eb0  ;*if_icmplt
                                                ; - AndTest::AndSC@2 (line 22)

  0x0000000002923e77: cmp    %edi,%r9d
  0x0000000002923e7a: movabs $0x16da0a08,%rax   ;   {metadata(method data for {method} {0x0000000016da0810} 'AndSC' '(III)Z' in 'AndTest')}
  0x0000000002923e84: movabs $0x128,%rsi
  0x0000000002923e8e: jg     0x0000000002923e9e
  0x0000000002923e94: movabs $0x138,%rsi
  0x0000000002923e9e: mov    (%rax,%rsi,1),%rdi
  0x0000000002923ea2: lea    0x1(%rdi),%rdi
  0x0000000002923ea6: mov    %rdi,(%rax,%rsi,1)
  0x0000000002923eaa: jle    0x0000000002923ec1  ;*if_icmpgt
                                                ; - AndTest::AndSC@7 (line 22)

  0x0000000002923eb0: mov    $0x0,%eax
  0x0000000002923eb5: add    $0x30,%rsp
  0x0000000002923eb9: pop    %rbp
  0x0000000002923eba: test   %eax,-0x1c73dc0(%rip)        # 0x0000000000cb0100
                                                ;   {poll_return}
  0x0000000002923ec0: retq                      ;*ireturn
                                                ; - AndTest::AndSC@13 (line 25)

  0x0000000002923ec1: mov    $0x1,%eax
  0x0000000002923ec6: add    $0x30,%rsp
  0x0000000002923eca: pop    %rbp
  0x0000000002923ecb: test   %eax,-0x1c73dd1(%rip)        # 0x0000000000cb0100
                                                ;   {poll_return}
  0x0000000002923ed1: retq

Method AndSC with -XX:PrintAssemblyOptions=intel option
  # {method} {0x00000000170a0810} 'AndSC' '(III)Z' in 'AndTest'
  ...
  0x0000000002c26e2c: cmp    r9d,r8d
  0x0000000002c26e2f: jl     0x0000000002c26e36  ;*if_icmplt
  0x0000000002c26e31: cmp    r9d,edi
  0x0000000002c26e34: jle    0x0000000002c26e44  ;*iconst_0
  0x0000000002c26e36: xor    eax,eax            ;*synchronization entry
  0x0000000002c26e38: add    rsp,0x10
  0x0000000002c26e3c: pop    rbp
  0x0000000002c26e3d: test   DWORD PTR [rip+0xffffffffffce91bd],eax        # 0x0000000002910000
  0x0000000002c26e43: ret
  0x0000000002c26e44: mov    eax,0x1
  0x0000000002c26e49: jmp    0x0000000002c26e38

Method AndNonSC with default options
  # {method} {0x0000000016da0908} 'AndNonSC' '(III)Z' in 'AndTest'
  ...
  0x0000000002923a78: cmp    %r8d,%r9d
  0x0000000002923a7b: mov    $0x0,%eax
  0x0000000002923a80: jl     0x0000000002923a8b
  0x0000000002923a86: mov    $0x1,%eax
  0x0000000002923a8b: cmp    %edi,%r9d
  0x0000000002923a8e: mov    $0x0,%esi
  0x0000000002923a93: jg     0x0000000002923a9e
  0x0000000002923a99: mov    $0x1,%esi
  0x0000000002923a9e: and    %rsi,%rax
  0x0000000002923aa1: cmp    $0x0,%eax
  0x0000000002923aa4: je     0x0000000002923abb  ;*ifeq
                                                ; - AndTest::AndNonSC@21 (line 29)

  0x0000000002923aaa: mov    $0x1,%eax
  0x0000000002923aaf: add    $0x30,%rsp
  0x0000000002923ab3: pop    %rbp
  0x0000000002923ab4: test   %eax,-0x1c739ba(%rip)        # 0x0000000000cb0100
                                                ;   {poll_return}
  0x0000000002923aba: retq                      ;*ireturn
                                                ; - AndTest::AndNonSC@25 (line 30)

  0x0000000002923abb: mov    $0x0,%eax
  0x0000000002923ac0: add    $0x30,%rsp
  0x0000000002923ac4: pop    %rbp
  0x0000000002923ac5: test   %eax,-0x1c739cb(%rip)        # 0x0000000000cb0100
                                                ;   {poll_return}
  0x0000000002923acb: retq

Method AndNonSC with -XX:PrintAssemblyOptions=intel option
  # {method} {0x00000000170a0908} 'AndNonSC' '(III)Z' in 'AndTest'
  ...
  0x0000000002c270b5: cmp    r9d,r8d
  0x0000000002c270b8: jl     0x0000000002c270df  ;*if_icmplt
  0x0000000002c270ba: mov    r8d,0x1            ;*iload_2
  0x0000000002c270c0: cmp    r9d,edi
  0x0000000002c270c3: cmovg  r11d,r10d
  0x0000000002c270c7: and    r8d,r11d
  0x0000000002c270ca: test   r8d,r8d
  0x0000000002c270cd: setne  al
  0x0000000002c270d0: movzx  eax,al
  0x0000000002c270d3: add    rsp,0x10
  0x0000000002c270d7: pop    rbp
  0x0000000002c270d8: test   DWORD PTR [rip+0xffffffffffce8f22],eax        # 0x0000000002910000
  0x0000000002c270de: ret
  0x0000000002c270df: xor    r8d,r8d
  0x0000000002c270e2: jmp    0x0000000002c270c0

First of all, the generated ASM code differs depending on whether we choose the default AT&T syntax or the Intel syntax.
With AT&T syntax:

The ASM code is actually longer for the AndSC method, with every bytecode IF_ICMP* translated to two assembly jump instructions, for a total of 4 conditional jumps.
Meanwhile, for the AndNonSC method the compiler generates a more straight-forward code, where each bytecode IF_ICMP* is translated to only one assembly jump instruction, keeping the original count of 3 conditional jumps.

With Intel syntax:

The ASM code for AndSC is shorter, with just 2 conditional jumps (not counting the non-conditional jmp at the end). Actually it's just two CMP, two JL/E and a XOR/MOV depending on the result.
The ASM code for AndNonSC is now longer than the AndSC one! However, it has just 1 conditional jump (for the first comparison), using the registers to directly compare the first result with the second, without any more jumps.

Conclusion after ASM code analysis

At AMD64 machine-language level, the & operator seems to generate ASM code with fewer conditional jumps, which might be better for high prediction-failure rates (random values for example).
On the other hand, the && operator seems to generate ASM code with fewer instructions (with the -XX:PrintAssemblyOptions=intel option anyway), which might be better for really long loops with prediction-friendly inputs, where the fewer number of CPU cycles for each comparison can make a difference in the long run.

As I stated in some of the comments, this is going to vary greatly between systems, so if we're talking about branch-prediction optimization, the only real answer would be: it depends on your JVM implementation, your compiler, your CPU and your input data.

Addendum: Guava's isPowerOfTwo method
Here, Guava's developers have come up with a neat way of calculating if a given number is a power of 2:
public static boolean isPowerOfTwo(long x) {
    return x > 0 & (x & (x - 1)) == 0;
}

Quoting OP:

is this use of & (where && would be more normal) a real optimization?

To find out if it is, I added two similar methods to my test class:
public boolean isPowerOfTwoAND(long x) {
    return x > 0 & (x & (x - 1)) == 0;
}

public boolean isPowerOfTwoANDAND(long x) {
    return x > 0 && (x & (x - 1)) == 0;
}

Intel's ASM code for Guava's version
  # {method} {0x0000000017580af0} 'isPowerOfTwoAND' '(J)Z' in 'AndTest'
  # this:     rdx:rdx   = 'AndTest'
  # parm0:    r8:r8     = long
  ...
  0x0000000003103bbe: movabs rax,0x0
  0x0000000003103bc8: cmp    rax,r8
  0x0000000003103bcb: movabs rax,0x175811f0     ;   {metadata(method data for {method} {0x0000000017580af0} 'isPowerOfTwoAND' '(J)Z' in 'AndTest')}
  0x0000000003103bd5: movabs rsi,0x108
  0x0000000003103bdf: jge    0x0000000003103bef
  0x0000000003103be5: movabs rsi,0x118
  0x0000000003103bef: mov    rdi,QWORD PTR [rax+rsi*1]
  0x0000000003103bf3: lea    rdi,[rdi+0x1]
  0x0000000003103bf7: mov    QWORD PTR [rax+rsi*1],rdi
  0x0000000003103bfb: jge    0x0000000003103c1b  ;*lcmp
  0x0000000003103c01: movabs rax,0x175811f0     ;   {metadata(method data for {method} {0x0000000017580af0} 'isPowerOfTwoAND' '(J)Z' in 'AndTest')}
  0x0000000003103c0b: inc    DWORD PTR [rax+0x128]
  0x0000000003103c11: mov    eax,0x1
  0x0000000003103c16: jmp    0x0000000003103c20  ;*goto
  0x0000000003103c1b: mov    eax,0x0            ;*lload_1
  0x0000000003103c20: mov    rsi,r8
  0x0000000003103c23: movabs r10,0x1
  0x0000000003103c2d: sub    rsi,r10
  0x0000000003103c30: and    rsi,r8
  0x0000000003103c33: movabs rdi,0x0
  0x0000000003103c3d: cmp    rsi,rdi
  0x0000000003103c40: movabs rsi,0x175811f0     ;   {metadata(method data for {method} {0x0000000017580af0} 'isPowerOfTwoAND' '(J)Z' in 'AndTest')}
  0x0000000003103c4a: movabs rdi,0x140
  0x0000000003103c54: jne    0x0000000003103c64
  0x0000000003103c5a: movabs rdi,0x150
  0x0000000003103c64: mov    rbx,QWORD PTR [rsi+rdi*1]
  0x0000000003103c68: lea    rbx,[rbx+0x1]
  0x0000000003103c6c: mov    QWORD PTR [rsi+rdi*1],rbx
  0x0000000003103c70: jne    0x0000000003103c90  ;*lcmp
  0x0000000003103c76: movabs rsi,0x175811f0     ;   {metadata(method data for {method} {0x0000000017580af0} 'isPowerOfTwoAND' '(J)Z' in 'AndTest')}
  0x0000000003103c80: inc    DWORD PTR [rsi+0x160]
  0x0000000003103c86: mov    esi,0x1
  0x0000000003103c8b: jmp    0x0000000003103c95  ;*goto
  0x0000000003103c90: mov    esi,0x0            ;*iand
  0x0000000003103c95: and    rsi,rax
  0x0000000003103c98: and    esi,0x1
  0x0000000003103c9b: mov    rax,rsi
  0x0000000003103c9e: add    rsp,0x50
  0x0000000003103ca2: pop    rbp
  0x0000000003103ca3: test   DWORD PTR [rip+0xfffffffffe44c457],eax        # 0x0000000001550100
  0x0000000003103ca9: ret

Intel's asm code for && version
  # {method} {0x0000000017580bd0} 'isPowerOfTwoANDAND' '(J)Z' in 'AndTest'
  # this:     rdx:rdx   = 'AndTest'
  # parm0:    r8:r8     = long
  ...
  0x0000000003103438: movabs rax,0x0
  0x0000000003103442: cmp    rax,r8
  0x0000000003103445: jge    0x0000000003103471  ;*lcmp
  0x000000000310344b: mov    rax,r8
  0x000000000310344e: movabs r10,0x1
  0x0000000003103458: sub    rax,r10
  0x000000000310345b: and    rax,r8
  0x000000000310345e: movabs rsi,0x0
  0x0000000003103468: cmp    rax,rsi
  0x000000000310346b: je     0x000000000310347b  ;*lcmp
  0x0000000003103471: mov    eax,0x0
  0x0000000003103476: jmp    0x0000000003103480  ;*ireturn
  0x000000000310347b: mov    eax,0x1            ;*goto
  0x0000000003103480: and    eax,0x1
  0x0000000003103483: add    rsp,0x40
  0x0000000003103487: pop    rbp
  0x0000000003103488: test   DWORD PTR [rip+0xfffffffffe44cc72],eax        # 0x0000000001550100
  0x000000000310348e: ret

In this specific example, the JIT compiler generates far less assembly code for the && version than for Guava's & version (and, after yesterday's results, I was honestly surprised by this).
Compared to Guava's, the && version translates to 25% less bytecode for JIT to compile, 50% less assembly instructions, and only two conditional jumps (the & version has four of them).
So everything points to Guava's & method being less efficient than the more "natural" && version.
... Or is it?
As noted before, I'm running the above examples with Java 8:
C:\....>java -version
java version "1.8.0_91"
Java(TM) SE Runtime Environment (build 1.8.0_91-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.91-b14, mixed mode)

But what if I switch to Java 7?
C:\....>c:\jdk1.7.0_79\bin\java -version
java version "1.7.0_79"
Java(TM) SE Runtime Environment (build 1.7.0_79-b15)
Java HotSpot(TM) 64-Bit Server VM (build 24.79-b02, mixed mode)
C:\....>c:\jdk1.7.0_79\bin\java -XX:+UnlockDiagnosticVMOptions -XX:CompileCommand=print,*AndTest.isPowerOfTwoAND -XX:PrintAssemblyOptions=intel AndTestMain
  .....
  0x0000000002512bac: xor    r10d,r10d
  0x0000000002512baf: mov    r11d,0x1
  0x0000000002512bb5: test   r8,r8
  0x0000000002512bb8: jle    0x0000000002512bde  ;*ifle
  0x0000000002512bba: mov    eax,0x1            ;*lload_1
  0x0000000002512bbf: mov    r9,r8
  0x0000000002512bc2: dec    r9
  0x0000000002512bc5: and    r9,r8
  0x0000000002512bc8: test   r9,r9
  0x0000000002512bcb: cmovne r11d,r10d
  0x0000000002512bcf: and    eax,r11d           ;*iand
  0x0000000002512bd2: add    rsp,0x10
  0x0000000002512bd6: pop    rbp
  0x0000000002512bd7: test   DWORD PTR [rip+0xffffffffffc0d423],eax        # 0x0000000002120000
  0x0000000002512bdd: ret
  0x0000000002512bde: xor    eax,eax
  0x0000000002512be0: jmp    0x0000000002512bbf
  .....

Surprise! The assembly code generated for the & method by the JIT compiler in Java 7, has only one conditional jump now, and is way shorter! Whereas the && method (you'll have to trust me on this one, I don't want to clutter the ending!) remains about the same, with its two conditional jumps and a couple less instructions, tops.
Looks like Guava's engineers knew what they were doing, after all! (if they were trying to optimize Java 7 execution time, that is ;-)
So back to OP's latest question:

is this use of & (where && would be more normal) a real optimization?

And IMHO the answer is the same, even for this (very!) specific scenario: it depends on your JVM implementation, your compiler, your CPU and your input data.

A:

For those kind of questions you should run a microbenchmark. I used  JMH for this test.
The benchmarks are implemented as
// boolean logical AND
bh.consume(value >= x & y <= value);

and
// conditional AND
bh.consume(value >= x && y <= value);

and
// bitwise OR, as suggested by Joop Eggen
bh.consume(((value - x) | (y - value)) >= 0)

With values for value, x and y according to the benchmark name.
The result (five warmup and ten measurement iterations) for throughput benchmarking is:
Benchmark                                 Mode  Cnt    Score    Error   Units
Benchmark.isBooleanANDBelowRange          thrpt   10  386.086 ▒ 17.383  ops/us
Benchmark.isBooleanANDInRange             thrpt   10  387.240 ▒  7.657  ops/us
Benchmark.isBooleanANDOverRange           thrpt   10  381.847 ▒ 15.295  ops/us
Benchmark.isBitwiseORBelowRange           thrpt   10  384.877 ▒ 11.766  ops/us
Benchmark.isBitwiseORInRange              thrpt   10  380.743 ▒ 15.042  ops/us
Benchmark.isBitwiseOROverRange            thrpt   10  383.524 ▒ 16.911  ops/us
Benchmark.isConditionalANDBelowRange      thrpt   10  385.190 ▒ 19.600  ops/us
Benchmark.isConditionalANDInRange         thrpt   10  384.094 ▒ 15.417  ops/us
Benchmark.isConditionalANDOverRange       thrpt   10  380.913 ▒  5.537  ops/us

The result is not that different for the evaluation itself. As long no perfomance impact is spotted on that piece of code I would not try to optimize it. Depending on the place in the code the hotspot compiler might decide to do some optimization. Which probably is not covered by the above benchmarks.
some references:
boolean logical AND -  the result value is true if both operand values are true; otherwise, the result is false
conditional AND - is like &, but evaluates its right-hand operand only if the value of its left-hand operand is true
bitwise OR - the result value is the bitwise inclusive OR of the operand values

A:

I'm going to come at this from a different angle.
Consider these two code fragments,
  if (value >= x && value <= y) {

and
  if (value >= x & value <= y) {

If we assume that value, x, y have a primitive type, then those two (partial) statements will give the same outcome for all possible input values.  (If wrapper types are involved, then they are not exactly equivalent because of an implicit null test for y that might fail in the & version and not the && version.)
If the JIT compiler is doing a good job, its optimizer will be able to deduce that those two statements do the same thing:

If one is predictably faster than the other, then it should be able to use the faster version ... in the JIT compiled code.
If not, then it doesn't matter which version is used at the source code level.
Since the JIT compiler gathers path statistics before compiling, it can potentially have more information about the execution characteristics that the programmer(!).
If the current generation JIT compiler (on any given platform) doesn't optimize well enough to handle this, the next generation could well do ... depending on whether or not empirical evidence points to this being a worthwhile pattern to optimize.
Indeed, if you write you Java code in a way that optimizes for this, there is a chance that by picking the more "obscure" version of the code, you might inhibit the current or future JIT compiler's ability to optimize.

In short, I don't think you should do this kind of micro-optimization at the source code level.  And if you accept this argument1, and follow it to its logical conclusion, the question of which version is faster is ... moot2.
1 - I do not claim this is anywhere near being a proof.
2 - Unless you are one of the tiny community of people who actually write Java JIT compilers ...

The "Very Famous Question" is interesting in two respects:

On the one hand, that is an example where the kind of optimization required to make a difference is way beyond the capability of a JIT compiler.
On the other hand, it would not necessarily be the correct thing to sort the array ... just because a sorted array can be processed faster.  The cost of sorting the array, could well be (much) greater than the saving.


Q:

Lattice hopping

A bunny is hopping around the plane.  She must

land on the following $25$ points on the main diagonal (multiples of 4):  $(4, 4)$, $(8, 8)$, $(12, 12)$, $\ldots,$ $(100, 100)$,  (The bunny can land on other points too, but the goal is to hit these multiples of four.)
only land on lattice points $\mathbb{Z}^2$,
only jump integer distances, and
move so no pair of jumps are parallel or perpendicular to each other.  That means if the bunny jumps directly north for its first jump, it cannot jump directly north, south, east or west for any of the remaining jumps.

The bunny can start by jumping to any lattice point you wish.  How can the bunny accomplish this task?

A:

If $(a,b,c)$ is a Pythagorean triple, the bunny can do moves $(a,b)$ followed by $(-a,b)$ to move a displacement of $2b$ in any orthogonal direction.
Using triples of the form $(m^2-1,2m,m^2+1)$, we can obtain any even number $b=2m$, and so any orthogonal displacement $4m$. By moving $4(m+1)$ spaces, then $4m$ spaces the other way, we can move $4$ spaces.
With $m$ sufficiently large, we can guarantee that we haven't used $m$ and $m+1$ before, so this move isn't parallel or perpendicular to any previous move. (When $m$ is odd, the triple has a GCD of 2, so we have to care that its halved version hasn't been used either.)
The bunny can start at $(0,0)$ and repeatedly move $4$ steps and $4$ steps right to hit every required point.


Q:

Fatal error for permissions in Facebook API

I got following error
Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user. thrown in /home/.../third_party/base_facebook.php on line 1106

my function is,
public function isPhotoPermission()
        {
            $facebook = new Facebook();
            $access_token = $facebook->getAccessToken();
            $permissions = $facebook->api("/me/permissions","GET",array('access_token' => $access_token));
            if( array_key_exists('user_photos', $permissions['data'][0]) )
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }

that 1106 line is,
1105:  protected function throwAPIException($result) {
1106:    $e = new FacebookApiException($result);
1107:    switch ($e->getType()) { ....

error occurring by following code:
$permissions = $facebook->api("/me/permissions","GET",array('access_token' => $access_token));

Where is the Problem? Thanks for advance.

A:

Are you sure you didn't forget the parameters as for the Facebook() constructor?
$config = array();
$config[‘appId’] = 'YOUR_APP_ID';
$config[‘secret’] = 'YOUR_APP_SECRET';
$config[‘fileUpload’] = false; // optional

$facebook = new Facebook($config);

https://developers.facebook.com/docs/reference/php/
Or perhaps did you initialize your $facebook object somewhere else in the code? In that case, you should:

either pass $facebook to your isPhotoPermission() function in order to get it back,
or set $facebook as global whether it is initialized in another function,
or simply remove the $facebook = new Facebook(); line if $facebook has been defined outside a function (would mean it is already global).


Q:

What are the chances to get an edible apple from a tree grown from seed?

I am growing a few good apple trees in my roof garden, in pots. I love growing the trees, and of course love the fruit. Since I am in a warm climate, I grow appropriate apple cultivars which are professionally grafted and yield beautiful apples.
Apart from that I also have an experimental area where I grow six apple plants grown from seed. One of them finally blossomed this year (about 4 years from seed) and the fruits have set and look promising. The others have not yet blossomed.
Since this is a four year experiment (and counting) I had time to look online and try to answer a question I had all this time - what are my chances of success?
According to some sources, the chance to get an apple tree which yields any fruit is about 1 in 10, and a tree yielding edible apples at about 1 in 25. Other sources also claim statistics as 1:250 to get an apple as good as the origin, and 1:250,000 to get a better apple than the original. All the sources are contradictory, and I don't know if growing apple from seed is a sensible thing to do, or an incredibly slim chance of success.
To be clear: I have no intentions of growing the next commercial cultivar in my roof garden - I just hope to get nice, edible apples. Does anyone know the chances of getting there?

A:

My experience is different. It is very easy to have a apple tree from seed.
But apple trees are not auto-fertile. This mean that to have apple on a tree, you need pollen from an other trees (and other varieties).  There are tables about which varieties could pollinate which other variety, so different variety is not always enough.  To complicate things, you really want varieties which flower on the same period.
So I would say: you need several apple trees (of different varieties) near your experiment.
For the edible part, it is also complex.  Many apples (also in commerce) are not edible (your definition on question's comment) when picked from the plant.  Time will make them ripe (hay will help), for commercial apples.  On your experiment, maybe they will never be sweet.  On the other hand, not all apple varieties can be stored.
Note: such experiment will give you possibly a non stable variety, with years the fruit form, colour and taste could change (and possibly less resilient to diseases and climate), so from a good apple to a commercial variety there is an other leap.
I would make the experiment, and you will like the (possibly) small green acid apples. I would say that it is probable (> 1/3) that you get an apple that you could use somewhere (fruit salads [you will save some lemon], pies, etc.).  Worst case, you have them as decoration.  To be really edible picked from plant (and enjoyable) I could not really say that 1/25 seems are good estimate.

A:

Apples are quite variable in their genetics, which is why all varieties eaten (as opposed to being made into cider) are clones. Any apple from seed should be edible, in the sense of not being poisonous, but they very probably will not be something you'd like to eat. You can, however, make them into cider - especially, hard cider. This is why Johnny Appleseed was so popular :) - Here's a reputable source: https://www.smithsonianmag.com/arts-culture/real-johnny-appleseed-brought-applesand-booze-american-frontier-180953263/


Q:

Can we check GPU memory usage inside a CUDA kernel?

I want to check the free memory on the device while executing a CUDA kernel. cuMemGetInfo(&free, &total) is a host (CPU) based command which gives free memory on the Device.
But is there any way to check free memory inside a CUDA kernel code during execution ?

A:

Use profiler - The NVIDIA Visual Profiler is a cross-platform performance profiling tool that delivers developers vital feedback for optimizing CUDA C/C++ applications.
First introduced in 2008, Visual Profiler supports all 350 million+ CUDA capable NVIDIA GPUs shipped since 2006 on Linux, Mac OS X, and Windows.
The NVIDIA Visual Profiler is available as part of the CUDA Toolkit.
See User's Guide Here


Q:

How to prevent substitution of $1 value, while passing the argument value as 'abc$1xyz' in shell script

test.sh
#!/bin/bash

foo()
{
   echo $1;
}
foo $1

running the script as: ./test.sh abc$1xyz
Output is:
abcxyz

But expecting output is:
abc$1xyz

So, here $1 value is replacing with empty, but I want to prevent that. I know we can do with using single quotes like foo 'abc$1xyz' but actually I can't do that, because that value will passing from third person, I can't tell them to add single quotes or any escaping characters. So, please let me know is there any other work around will be available for this.
Edit: Based on the requested comments, and please tell me still you need any clarity the one who had down voted this.

A:

In short, you can't do what you want. If someone is using your tool from the command line, they simply must use your command according to the rules of the shell.
The behavior you are seeing is because the shell will translate the argument before your program ever sees it. There is absolutely no way for your command to affect what happens before it is called.
It is because of this -- because the shell processes arguments before running your script -- that quotes were created in the first place. Quoting (both single quotes, double quotes, and backslash quotes) exists to give users control over how arguments are treated before calling some function.
So, if you want a string like abc$1xyz to be sent to your program without variable expansion you have two choices:

require the user to use some other shell that doesn't translate arguments before calling your program, or
require the user to use the facilities of the shell to properly quote their arguments.


Q:

Derivation of impedance matching formula

When matching impedances with a quarter wavelength coupler, how do I derive that its impedance has to be
$$
Z_2=\sqrt{Z_1 Z_3}
$$
where $Z_1,Z_3$ are the impedances of the adjacent materials?

A:

Assume plane waves. The tangential boundary conditions show that the transverse electric and magnetic field vectors must stay in the same direction on transmission or reflexion from the interfaces, assumed aligned with the wavefronts.
Since we know the direction of the waves, let's say the $\vec{E}$ fields are all in the $\hat{X}$ direction, the magnetic fields all in the $\hat{Y}$. By convention, let all  $\vec{E}$ fields point in the +X direction: the amplitude will be negative if this needs to change. Then, if a forward travelling wave has an E field of $+E\, \hat{X}$, the magnetic field will be $+E \,\hat{Y}/\mathcal{Z}$, where $\mathcal{Z}$ is the characteristic impedance of the medium in question. If the wave is propagating in the opposite direction, as the reflected waves will be, an electric field of $+E \,\hat{X}$ corresponds to a magnetic field of $-E\,\hat{Y}/\mathcal{Z}$.
So let the incident wave on the have complex amplitude 1. Then the incident magnetic field is $1/\mathcal{Z}_1$. There will also be a reflected electric field $E_r\,\hat{X}$, which we must solve for. The reflected magnetic field will thus be $-E_r\,\hat{Y}/\mathcal{Z}_1$; the negative sign because of the right hand rule relationship between propagation direction, electric field and magnetic field.
In the layer, there is a forward travelling wave with electric amplitude field $E^+$ and a backwards wave with electric amplitude field $E^-$, both of which you must solve for. The corresponding magnetic fields are $+E^+\,\hat{Y}/\mathcal{Z}_2$ and $-E^-\,\hat{Y}/\mathcal{Z}_2$, again taking proper heed of the sign for the direction of each wave. Then, at the first boundary, a statement of the boundary conditions is:
$$E^+ + E^- = 1$$
$$\frac{1}{\mathcal{Z}_2}\left(E^+-E^-\right) = -\frac{1}{\mathcal{Z}_1}E_r\,\hat{Y}\tag{1}$$
Now let the layer thickness be $\ell$ and the wavenumber be $k$. The layer electric fields are $E^+\,e^{i\,k\,\ell}\,\hat{X}$ and $E^-\,e^{-i\,k\,\ell}\,\hat{X}$ for forward and backwards waves, respectively (note the sign of the phase). The magnetic fields will be $+E^+\,e^{i\,k\,\ell}\,\hat{Y}/\mathcal{z}_2$ and $-E^-\,e^{-i\,k\,\ell}\,\hat{Y}/\mathcal{z}_2$, respectively.
In the third layer, there is only the transmitted field: $E_t\,\hat{X}$ and $E_t\,\hat{Y}/\mathcal{Z}_3$ for the magnetic field.
So the tangential electromagnetic boundary conditions at the second layer are therefore:
$$E^+\,e^{i\,k\,\ell} + E^-\,e^{-i\,k\,\ell} = E_t$$
$$\frac{1}{\mathcal{Z}_2}\left(E^+\,e^{i\,k\,\ell} - E^-\,e^{-i\,k\,\ell}\right) = \frac{1}{\mathcal{Z}_3}\,E_t\tag{2}$$
You can now eliminate $E_t,\,E^+,\,E^-$ from the system (1) and (2) to get an expression for the complex reflexion co-efficient $E_r$. You will find that this implies a condition on the layer thickness as well as the characteristic impedance relationship you cite if you want $E_r=0$.


Q:

Implement Scala-style String Interpolation In Scala

I want to implement a Scala-style string interpolation in Scala. Here is an example,
val str = "hello ${var1} world ${var2}"

At runtime I want to replace "${var1}" and "${var2}" with some runtime strings. However, when trying to use Regex.replaceAllIn(target: CharSequence, replacer: (Match) ⇒ String), I ran into the following problem:
import scala.util.matching.Regex
val placeholder = new Regex("""(\$\{\w+\})""")
placeholder.replaceAllIn(str, m => s"A${m.matched}B")
java.lang.IllegalArgumentException: No group with name {var1}
  at java.util.regex.Matcher.appendReplacement(Matcher.java:800)
  at scala.util.matching.Regex$Replacement$class.replace(Regex.scala:722)
  at scala.util.matching.Regex$MatchIterator$$anon$1.replace(Regex.scala:700)
  at scala.util.matching.Regex$$anonfun$replaceAllIn$1.apply(Regex.scala:410)
  at scala.util.matching.Regex$$anonfun$replaceAllIn$1.apply(Regex.scala:410)
  at scala.collection.Iterator$class.foreach(Iterator.scala:743)
  at scala.collection.AbstractIterator.foreach(Iterator.scala:1174)
  at scala.util.matching.Regex.replaceAllIn(Regex.scala:410)
  ... 32 elided

However, when I removed '$' from the regular expression, it worked:
val placeholder = new Regex("""(\{\w+\})""")
placeholder.replaceAllIn(str, m => s"A${m.matched}B")
res2: String = hello $A{var1}B world $A{var2}B

So my question is that whether this is a bug in Scala Regex. And if so, are there other elegant ways to achieve the same goal (other than brutal force replaceAllLiterally on all placeholders)?

A:

$ is a treated specially in the replacement string. This is described in the documentation of replaceAllIn:

In the replacement String, a dollar sign ($) followed by a number will be interpreted as a reference to a group in the matched pattern, with numbers 1 through 9 corresponding to the first nine groups, and 0 standing for the whole match. Any other character is an error. The backslash (\) character will be interpreted as an escape character and can be used to escape the dollar sign. Use Regex.quoteReplacement to escape these characters.

(Actually, that doesn't mention named group references, so I guess it's only sort of documented.)
Anyway, the takeaway here is that you need to escape the $ characters in the replacement string if you don't want them to be treated as references.
new scala.util.matching.Regex("""(\$\{\w+\})""")
    .replaceAllIn("hello ${var1} world ${var2}", m => s"A\\${m.matched}B")
// "hello A${var1}B world A${var2}B"


Q:

Imitating specific USB device

I recently got hands on an workout device which has a USB to PC interface and logs workouts on a lousy Windows Application. My intention is to read out the USB and build a custom application for presenting that data.
When connected to a linux machine the device registers in /dev/ttyUSB0, can be seen with lsusb and stty reports the baudrate among other information. I fire up minicom with the stty settings and as soon as the workout is initiated the device sends a series of 41 bytes
I assume that those bytes represent an announcement to the the PC interface.
What I would like to do is to imitate the workout device and send those 41 bytes to the PC interface myself in order to see what the PC side does upon initiation. Is there a way to imitate the device so that the PC software will recognize it?

A:

if the device is /dev/ttyUSB0 it is very likel implementing a virtual COM port, this is USB Communication Device class CDC (ACM).
the operating system knows what driver / kernel module it has to load because when you plug in the device in USB protocol descriptors are exchanged ( the device sends its device descriptor to the host, according to this the host loads the driver / kernel module ), you can see this information with lsusb -v. Specifically the device sends the following descriptors to the host : device descriptor, configuration descriptor, interface descriptor, endpoint descriptor : http://www.beyondlogic.org/usbnutshell/usb1.shtml
for imitating a device you have to write a firmware on a MCU with exaclty these descriptors and additionally with identic VID ( vendor id ) and PID ( product id )
the 41 bytes you receive flow over the virtual COM port and so in RS-232 protocol ( you are able to receive them with minicom ) and so they are above USB level, however they are part of the payload in USB packets. if you have a proprietary driver in windows of your device in windows these 41 bytes are very likely addressed to the driver ( whichs source code you very likely do not have ...). this is very common there are multimeters with RS-232 interface and one has to send a  D = 44 (hex) = 01000100 (bin)  to receive any data
so you can try to sniff the virtual COM port ( RS-232 protocol ) directly using a RS-232 sniffer, i.e. https://www.eltima.com/rs232-sniffer.html
alternatively you can try is to sniff the underlying USB traffic with wireshark ( or usbmon in linux ) and extract the payload from the USB packets to record the communication between the windows driver and ther device
https://ask.wireshark.org/question/36/how-to-capture-usb-packets-please/
https://www.youtube.com/watch?v=EfkC7kmIMt8 ( USB in Wireshark )
https://www.kernel.org/doc/Documentation/usb/usbmon.txt
( https://www.kernel.org/doc/html/v4.13/driver-api/usb/URB.html )


Q:

$(G, \cdot)$ - group such that $|G|<\infty$. $G$ has exactly $2$ subgroups

$(G, \cdot)$ - group such that $|G|<\infty$. $G$ has exactly $2$ subgroups. Prove that order of $a\in G$ is a prime if $a\neq e$ where $e$ is neutral element.
I am stuck. Here is what I got so far:
$G$ has exactly two subgroups that means that the only subgroups are $e$ and $G$.
Let $a^k=e$ and assume that $k$ is not prime, that means $k=p_1 p_2$ where $p_1$ and $p_2$ are prime numbers. Then $a^k=a^{p_1 p_2}=(a^{p_1})^{p_2}=e^{p_2}$.
Now I am stuck because I think that means that it implies that $a^{p_1}=e$ and then I would know what to do, but does it?

A:

You have some work to do here. First off, what is your overall proof technique? What you need to prove, given the assumptions, that if $a\in G$ and $a\neq e$, then the order of $a$ is prime.
You (nearly) correctly observe that under the assumptions, the two subgroups of $G$ are $\{e\}$ (to be careful with the notation, this is not the same thing as $e$) and $G$. (You might note that for these to be different, $\vert G\vert$ must be greater than $1$.)
Now how are you going about proving the if-then result you need to prove? You could attempt a direct proof (assume that $a\in G$ and $a\neq e$ and conclude that the order of $a$ is prime), or a proof by contrapositive or contradiction (assume that $a\in G$ and the order of $a$ is not prime, and conclude that $a=e$ or that $G$ is not finite, or that $G$ has more than two subgroups.)
You begin by assuming that $a^k=e$ where $k$ is not prime, so it looks like you are attempting a proof by contrapositive or contradiction, but this isn’t quite the right assumption, because you should assume that the order of $a$ is not prime, and that’s not the same thing as assuming $a$ raised to a non-prime power is $e$. Do you know the definition of order of an element of a group?
In fact, there are always non-prime values of $k$ for which $a^k=e$. For example, $a^{250\vert G\vert}=e$ for every element $a$ of $G$, so you won’t be able to conclude much about $a$ from that.
You also say that if $k$ is not prime, it is the product of two primes, but this is not true. For example, $12$ is not prime, but it isn’t the product of two primes.


Q:

What php.ini settings are required to allow a session to remain active for approximately two days?

http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-lifetime
says that a session.cookie_lifetime of 0 "goes until the browser is closed".  Is that the absolute maximum length that the session can have (always wiped when the browser is closed), or would setting a session.cookie_lifetime of, say, 23243245234 yeild a result that would probably last beyond whenever the browser is closed?
More to the point, what php.ini settings would I need to set to make sessions last somewhere along the lines of two days, and is there a security reason to recommend a certain (I would expect lower) time limit, and if so what would the recommended period be?
Intended behavior
Edit:  Here is what I want to achieve, perhaps I'll be able to understand the behavior by getting some settings suggestions as opposed to the specific values of the php.ini settings:
I want the session to last as long as possible, up to (approximately) two days.
If the session can last beyond browser close, I would like it to do so (up to approximately two days).
What would I set for php.ini settings (and yes, I have direct edit access to the php.ini) to acheive that?

A:

There are two parameters you need to worry about regarding sessions.  The first is the TTL for the cookie, the other is how old a session data file can become before it gets garbage collected.
session.cookie_lifetime determines, in seconds, how long the cookie sent to the browser will last.  It defaults to 0, which means until the browser closes.  For two days it'd need to be 172800 seconds.
session.gc_maxlifetime determines, also in seconds, how long before session data marked on the server will be regarded as garbage and can be deleted.
Setting these two ini directives should give you sessions that survive for two days, except for one more thing of which you need to be aware.
Some operating systems do automated garbage collection on their default temporary directories.  If PHP is configured to store session data there, then if the GC period for the temp directory is short you may find yoruself losing your session before the value in session.gc_maxlifetime is reached.  To avoid this, make sure PHP is storing session data to a location other than /tmp or whatever the temporary directory of your host operating system is.

A:

It means that the session is lost at the time the browser gets closed.
That is, the cookie containing that session id gets deleted together with the onclose event of the browser.

session.cookie_lifetime specifies the
  lifetime of the cookie in seconds
  which is sent to the browser

The recommended period depends basically on what your session needs to hold. Say you want to keep your user logged in the website (remind me), you should go for the largest period. Just as an example.
If you want the session alive for approximately two days, you just count
60 [seconds] * 60 [minutes] * 48 [hours] = 172800 seconds


Q:

React state is undefined

Playing with react, trying to build a simple chat app that will be connected to firebase.
I have one container - ChatApp - and one component UserInput.
ChatApp ->
import React from 'react';
import UserInput from '../components/UserInput';

export default React.createClass({
    getInitialState: function() {
        return {
            chatting: false
        };
    },
    render: function() {
        return

            <UserInput
                startChat={this.chatCanStart}
            />

;
    },
    chatCanStart: function(recipient) {
        console.log(recipient);
        this.setState({
            chatting: true
        })
    }
});

UserInput ->
import React from 'react';

export default React.createClass({
    getInitialState: function() {
        return {
            username: '',
            recipient: 'asgasg'
        };
    },
    handleUsernameChange: function(event) {
        let text = event.target.text;
        this.setState({
            username: text
        });
    },
    handleRecipientChange: function(event) {
        let text = event.target.text;
        this.setState({
            recipient: text
        });
    },
    handleStartChat: function() {
        if (this.state.username !== '' && this.state.recipient !== ''){
            console.log(this.state.recipient);
            this.props.startChat(this.state.recipient);
        }
    },
    render: function() {
        return

 Welcome to the chat app done in React

                     Username
                    <input type="email" className="form-control" value={this.state.username} onChange={this.handleUsernameChange} />

                     Recipient
                    <input type="email" className="form-control" value={this.state.recipient} onChange={this.handleRecipientChange} />

                <button type="button" className="btn btn-primary" onClick={this.handleStartChat}> Chat now </button>

;
    }
});

When I change the Username and Recipient fields and then click on the Chat now button, I am expecting the chatting state in the ChatApp container to change to true and also want to log the passed recipient.
But I get 'undefined', why is that? I get 'undefined' even in the console.log in the UserInput component. Even though the inputs value in the form is being changed just fine.
What am I doing wrong?
Thanks.

A:

To get value from input you need to use .value property instead of .text
handleUsernameChange: function(event) {
  let text = event.target.value;
  this.setState({
    username: text
  });
},

handleRecipientChange: function(event) {
  let text = event.target.value;
  this.setState({
    recipient: text
  });
},

Example


Q:

Spring boot Ldap Authentication failing with LDAP error code 49 - 80090308 data 52e

I am trying to use LDAP User authentication in my web application with spring security but getting error 52e, below is my spring security ldap authentication code:
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  auth.ldapAuthentication()
   .contextSource().url("ldap://192.168.1.5:389/DC=zonetest,DC=lk")
   .managerDn("CN=administrator@zonetest.lk,DC=zonetest,DC=lk").managerPassword("P@ssw0rd")
   .and()
   .userSearchBase("OU=SL Users")
   .userSearchFilter("(CN={0})");
}

My Ldap structure is provided in the screenshot for reference :

LDAP structure
LDAP structure

I am getting this error in postman client
{
    "timestamp": 1505368170503,
    "status": 401,
    "error": "Unauthorized",
    "message": "[LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903C5, comment: AcceptSecurityContext error, data 52e, v2580\u0000]; nested exception is javax.naming.AuthenticationException: [LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903C5, comment: AcceptSecurityContext error, data 52e, v2580\u0000]",
    "path": "/"
}

Please help me out.

A:

There is another simple way for ldap authentication.i used the below code to do the ldap authentication.This worked for me like a charm:
            package app.config;
            import org.springframework.beans.factory.annotation.Value;
            import org.springframework.context.annotation.Bean;
            import org.springframework.context.annotation.Configuration;
            import org.springframework.security.authentication.AuthenticationManager;
            import org.springframework.security.authentication.AuthenticationProvider;
            import org.springframework.security.authentication.ProviderManager;
            import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
            import org.springframework.security.config.annotation.web.builders.HttpSecurity;
            import org.springframework.security.config.annotation.web.builders.WebSecurity;
            import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
            import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
            import org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider;
            import java.util.Arrays;

            @Configuration
            @EnableWebSecurity
            public class WebSecurityConfigAD extends WebSecurityConfigurerAdapter {

             @Value("${ad.domain}")
             private String AD_DOMAIN;

             @Value("${ad.url}")
             private String AD_URL;

             @Override
             protected void configure(HttpSecurity http) throws Exception {
              http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
             }

             @Override
             protected void configure(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
              authManagerBuilder.authenticationProvider(activeDirectoryLdapAuthenticationProvider()).userDetailsService(userDetailsService());
             }

             @Bean
             public AuthenticationManager authenticationManager() {
              return new ProviderManager(Arrays.asList(activeDirectoryLdapAuthenticationProvider()));
             }
             @Bean
             public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
              ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider(AD_DOMAIN, AD_URL);
              provider.setConvertSubErrorCodesToExceptions(true);
              provider.setUseAuthenticationRequestCredentials(true);

              return provider;
             }
            }


Q:

How to move UIimageView over another UIImageView

I am moving most of UIImageViews on view and keeping an UIImageview fixed. Everything is happening fine but problem is when moving imageviews are containing or intersecting the fixed imageview, they are just moving from under fixed imageview.
How to make UIImageviews to move over the fixed imageview.
Please Find the function StartMoving code which makes UIImageviews to move in screen and called on buttonClick event.
In code...
CGPoint pos1,Pos2,pos3;

UIImageView *ball1,*ball2,*ball3,*fixedball;

-(void)StartMoving
{
    pos1=CGPointMake(5.0, 5.0);
    pos2=CGPointMake(5.0, 8.0);
    pos3=CGPointMake(8.0, 5.0);

    ball1.center=CGPointMake(ball1.center.x+pos1.x, ball1.center.y+pos1.y);
    ball2.center=CGPointMake(ball2.center.x+pos2.x, ball2.center.y+pos2.y);
    ball3.center=CGPointMake(ball3.center.x+pos3.x, ball3.center.y+pos3.y);
    if(ball1.center.x>320||ball1.center.x<0)
        pos1.x=-pos1.x;
    if(ball1.center.y>480||ball1.center.y<0)
        pos1.y=-pos1.y;
    if(ball2.center.x>320||ball2.center.x<0)
        pos2.x=-pos2.x;
    if(ball2.center.y>480||ball2.center.y<0)
        pos2.y=-pos2.y;
    if(ball3.center.x>320||ball3.center.x<0)
        pos3.x=-pos3.x;
    if(ball3.center.y>480||ball3.center.y<0)
        pos3.y=-pos3.y;
}

...and have added all moving and fixed imageviews in stroyboard.
Thanks in advance

A:

You need to bring that subview to the front of the other subviews:
UIView *viewContainingBalls; // most likely ball1.superview
[viewContainingBalls bringSubviewToFront:ball1];

Use this method to bring the other balls to the front as needed.
Or if you always want the fixed ball to be behind all the other balls you could just send this to the back:
UIView *viewContainingBalls; // most likely fixedball.superview
[viewContainingBalls sendSubviewToBack:fixedball];

There are other methods such as exchangeSubviewAtIndex:withSubviewAtIndex: that also accomplish similar a thing.


Q:

Почему не видны jars sockjs и stomp?

В Maven они видны. Он на них не ругается.

Но в браузере пишет, что их нет

Мои зависимости

Настройки:
package com.example.socialnetwork.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.*;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic");
        registry.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/chat");
        registry.addEndpoint("/chat").withSockJS();
    }
}

Контроллер
package com.example.socialnetwork.controllers;

import com.example.socialnetwork.models.Message;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class ChatController {

    @GetMapping("/chat")
    public String showChat() {
        return "chat";
    }

    @MessageMapping("/chat")
    @SendTo("/topic/messages")
    public Message send(Message message) throws Exception {
        String time = new SimpleDateFormat("HH:mm").format(new Date());
        return message;
    }
}

JavaScript:
'use strict';

let stompClient = null;

function setConnected(connected) {
    document.getElementById('connect').disabled = connected;
    document.getElementById('disconnect').disabled = !connected;
    document.getElementById('conversationDiv').style.visibility
        = connected ? 'visible' : 'hidden';
    document.getElementById('response').innerHTML = '';
}

function connect() {
    let socket = new SockJS('/chat');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function(frame) {
        setConnected(true);
        console.log('Connected: ' + frame);
        stompClient.subscribe('/topic/messages', function(messageOutput) {
            showMessageOutput(JSON.parse(messageOutput.body));
        });
    });
}

function disconnect() {
    if(stompClient != null) {
        stompClient.disconnect();
    }
    setConnected(false);
    console.log("Disconnected");
}

function sendMessage() {
    let from = document.getElementById('from').value;
    let text = document.getElementById('text').value;
    stompClient.send("/app/chat", {}, JSON.stringify({'from':from, 'text':text}));
}

function showMessageOutput(messageOutput) {
    let response = document.getElementById('response');
    let p = document.createElement('p');
    p.style.wordWrap = 'break-word';
    p.appendChild(document.createTextNode(messageOutput.from + ": "
        + messageOutput.text + " (" + messageOutput.time + ")"));
    response.appendChild(p);
}

И html:

    <title>Chat WebSocket</title>

            <input type="text" id="from" placeholder="Choose a nickname"/>

            <button id="connect" onclick="connect();">Connect</button>
            <button id="disconnect" disabled="disabled" onclick="disconnect();">
                Disconnect
            </button>

            <input type="text" id="text" placeholder="Write a message..."/>
            <button id="sendMessage" onclick="sendMessage();">Send</button>

A:

После тщетных попыток указывания пути к jar-кам, я прописал ссылку на библиотеки и всё сработало. Странно, что сработало именно сейчас, ведь раньше я тоже пытался прописат прямую ссылку на библиотеки.


Q:

Show values instead of ids for multiple fields sqlite

How do I resolve user IDs to user names for multiple fields in an SQLite query. I have 2 tables, "Tickets" and "Users". "Tickets" has the user IDs, "Users" links the ID to the user's name. So I have the query below, but how do I show the user names instead of the ID numbers in the "created_by" and "assigned_to" columns.
SELECT tickets.id, tickets.summary, tickets.created_by, tickets.assigned_to
FROM   tickets

I don't think joining is the solution as joining on one field leaves me with a problem with the other.

A:

You could try to join them like this two different alias
SELECT tickets.id, tickets.summary, u1.name, u2.name
FROM tickets
LEFT JOIN users AS u1 ON tickets.created_by = u1.id
LEFT JOIN users AS u2 ON tickets.assigned_to = u2.id


Q:

Looking up XML attributes with wildcard values, using XSL

The task of my little piece of XSL is to go through all the OptionRef tags in the XML file and to print the id and the displayName attributes for the OptionRef tags. The id´s are looked-up in the Options section to find displayName.
And now, the problem:
Some of the OptionRef id attributes use wildcards (*) as part of their values. These id´s cannot be looked-up with regards to displayName, unless they first get resolved to real id´s found in the Options section. Is there some way to extend the XSL to do this kind of "globbing"?
I would like to print the id´s and displayNames of all the id´s that are matching the wildcard.
For instance "A01*" will match both "A0101" and "A0102" in the Options section, so these id´s and their display names should be printed.
This is a sample of the XML:
    <?xml version="1.0" encoding="UTF-8"?>
    <OptionList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <Group>
            <OptionRef id="A0102"/>
            <OptionRef id="A03"/>
            <OptionRef id="A04"/>
            <OptionRef id="A0101"/>
            <OptionRef id="A0102"/>
            <OptionRef id="B01"/>
        </Group>
        <Options>
            <Option displayName="Option A02" id="A02"/>
            <Option displayName="Option A03" id="A03"/>
            <Option displayName="Option A0101" id="A0101"/>
            <Option displayName="Option A0102" id="A0102"/>
            <Option displayName="Option A04" id="A04"/>
            <Option displayName="Option B01" id="B01"/>
        </Options>
        <Rules>
            <Opportunities>
                <OptionRef id="A01*">
                    <OptionRef id="A03"/>
                    <OptionRef id="A04"/>
                </OptionRef>
            </Opportunities>
            <Problems>
                <Problem>
                    <OptionRef id="A03"/>
                    <OptionRef id="A04"/>
                </Problem>
            </Problems>
        </Rules>
    </OptionList>

This is the XSL:
    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
        <xsl:output method="text" indent="yes"/>

        <xsl:key name="Option_Key" match="Option" use="@id"/>

        <xsl:template match="OptionRef" >
           <xsl:value-of select="@id"/>:
                <xsl:value-of select="key('Option_Key', @id)/@displayName"/>
        </xsl:template>

    </xsl:stylesheet>

A:

How about something like:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:strip-space elements="*"/>
<xsl:output method="text" encoding="UTF-8"/>

<xsl:key name="Option_Key" match="Option" use="@id"/>
<xsl:variable name="options" select="/OptionList/Options/Option" />

<xsl:template match="OptionRef">
    <xsl:value-of select="@id"/>
    <xsl:text>:
</xsl:text>
    <xsl:choose>
        <xsl:when test="contains(@id, '*')">
            <xsl:for-each select="$options[starts-with(@id, substring-before(current()/@id, '*'))]">
                <xsl:value-of select="@displayName"/>
                <xsl:text>
</xsl:text>
            </xsl:for-each>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="key('Option_Key', @id)/@displayName"/>
            <xsl:text>
</xsl:text>
        </xsl:otherwise>
    </xsl:choose>
   <xsl:text>
</xsl:text>
</xsl:template>

</xsl:stylesheet>

Applied to you example input, the result will be:
A0102:
Option A0102

A03:
Option A03

A04:
Option A04

A0101:
Option A0101

A0102:
Option A0102

B01:
Option B01

A01*:
Option A0101
Option A0102

A03:
Option A03

A04:
Option A04


Q:

Can I add new methods to the String class in Java?

I'd like to add a method AddDefaultNamespace() to the String class in Java so that I can type "myString".AddDefaultNamespace() instead of DEFAULTNAMESPACE + "myString", to obtain something like "MyDefaultNameSpace.myString". I don't want to add another derived class either (PrefixedString for example).
Maybe the approach is not good for you but I personally hate using +. But, anyway, is it possible to add new methods to the String class in Java?
Thanks and regards.

A:

String is a final class which means it cannot be extended to work on your own implementation.

A:

Well, actually everyone is being unimaginative. I needed to write my own version of startsWith method because I needed one that was case insensitive.
class MyString{
    public String str;
    public MyString(String str){
        this.str = str;
    }
    // Your methods.
}

Then it's quite simple, you make your String as such:
MyString StringOne = new MyString("Stringy stuff");

and when you need to call a method in the String library, simple do so like this:
StringOne.str.equals("");

or something similar, and there you have it...extending of the String class.

A:

As everyone else has noted, you are not allowed to extend String (due to final).  However, if you are feeling really wild, you can modify String itself, place it in a jar, and prepend the bootclasspath with -Xbootclasspath/p:myString.jar to actually replace the built-in String class.
For reasons I won't go into, I've actually done this before.  You might be interested to know that even though you can replace the class, the intrinsic importance of String in every facet of Java means that it is use throughout the startup of the JVM and some changes will simply break the JVM.  Adding new methods or constructors seems to be no problem.  Adding new fields is very dicey - in particular adding Objects or arrays seems to break things although adding primitive fields seems to work.


Q:

Uage of `ce que` vs `ce qui`

As I understand it,

ce qui is used when referring to a subject, and ce que when referring to an object in a relative clause[1].

In my exercise book I found the following sentence

À cause de diverses formalités liées au décès de son père a Bruxelles, elle était obligée de séjourner encore quelque jours dans la capitale belge - ce qui arrangeait deux policiers.

which confuses me, as I would have expected the usage of ce que instead of ce qui.
As I understand it, ce qui refers to the object of the relative clause (i.e. what the two policemen arranged) and hence should be replaced by ce que. What is my misconception here? Is my translation wrong or is there an exception to the rule (1.)?

A:

Note the difference:

À cause de diverses formalités liées au décès de son père a Bruxelles, elle était obligée de séjourner encore quelque jours dans la capitale belge - ce qui arrangeait deux policiers.
Because of various formalities related to the death of her father in Brussels, she was obliged to stay for a few more days in the Belgian capital - which was convenient for two policemen.

vs

À cause de diverses formalités liées au décès de son père a Bruxelles, elle était obligée de séjourner encore quelque jours dans la capitale belge - ce que deux policiers arrangeaient.
Due to various formalities linked to the death of her father in Brussels, she was forced to stay for a few days in the Belgian capital - which two police officers arranged.

In the former:

Qu'est-ce qui arrangeait les deux policiers ?

In the latter:

Qu'est-ce que les deux policiers arrangeaient ?

Update: There is a nice comment below that I wish to add to my answer. It provides better insight to your query. (Many thanks to the teacher of French @Luke Sawczak for his comment and the verification as well!).

Your mistake is actually one of vocabulary, not grammar. There is a verb arranger that means to suit someone or to please someone. Thus the officers didn't arrange her stay, in which case they'd be the subject of arrangeait and you'd be right — rather, her stay suited the officers. You can find a clue as to the true subject in the conjugation of arrangeait, which is singular. Your original reading would actually require two errors, not one.


Q:

Which function to execute grant or synonyms?

I have a synonym statement:
CREATE OR REPLACE SYNONYM  sample-table-name FOR master.sample-table-name

I want to execute this by using R language using RJDBC library. I've tried different functions including dbGetQuery function etc. But it is not able to execute this statement.
Could someone please advise on how to execute these statements in R.

A:

I would expect that using dbExecute() should work. Failing that, dbSendStatement() should almost certainly work, as it seems to be intended for that sort of DDL.
The docs on dbGetQuery say:

This method is for SELECT queries only

To look at the functions that are available to you, it can be helpful to do something like ls('package:DBI').  Per the docs:
dbExecute:

Executes a statement and returns the number of rows affected.
  dbExecute() comes with a default implementation (which should work
  with most backends) that calls dbSendStatement(), then
  dbGetRowsAffected(), ensuring that the result is always free-d by
  dbClearResult().

dbSendStatement:

The dbSendStatement() method only submits and synchronously executes
  the SQL data manipulation statement (e.g., UPDATE, DELETE, INSERT
  INTO, DROP TABLE, ...) to the database engine. To query the number of
  affected rows, call dbGetRowsAffected() on the returned result object.
  You must also call dbClearResult() after that. For interactive use,
  you should almost always prefer dbExecute().

EDIT: Those methods will likely work for other implementations of DBI, and perhaps for RJDBC in the future.  In any case, it looks like they have implemented dbSendStatement() using dbSendQuery(), so they will not work for this purpose.
In the RJDBC framework, dbSendUpdate() is what you want.

dbSendQuery and dbSendUpdate submit a SQL query to the database. The
  difference between the two is only that dbSendUpdate is used with DBML
  queries and thus doesn't return any result set.

Confirmed using a similar query on another DBMS:
dbSendStatement(conn,'SET search_path=public;')
#Error in .verify.JDBC.result(r, "Unable to retrieve JDBC result set for ",  :
#Unable to retrieve JDBC result set for SET search_path=public; (No results were returned by the query.)

traceback()
#7: stop(..., " (", .jcall(x, "S", "getMessage"), ")")
#6: .verify.JDBC.result(r, "Unable to retrieve JDBC result set for ",
#       statement)
#5: .local(conn, statement, ...)
#4: dbSendQuery(conn, statement, ...)
#3: dbSendQuery(conn, statement, ...)                ## this is the problem
#2: dbSendStatement(conn, "SET search_path=public;")
#1: dbSendStatement(conn, "SET search_path=public;")

dbSendUpdate(conn, 'SET search_path=public;')
# successful

dbCommit(conn)
# persist the change past the current session (RJDBC seems to give you transaction control here)


Q:

rendering difference when using class vs id selector

I am having issues with rendering a 'chat bubble' in a div.
See Demo Here
When the CSS rules for the bubble container are applied using a className as the selector it is rendered differently then when the ID is the selector (pure CSS or JQuery, so It is not a JQuery issue).
Here is the CSS
#tweetBox {
    position: absolute;
    top: 72px;
    right: 158px;
    display: none;
    margin: 0 0 15px 15px;
}
.tweetBox-class {
    position: absolute;
    top: 72px;
    right: 158px;
    display: none;
    margin: 0 0 15px 15px;
}

as you can see from the example, when the class selector is used the width of the container goes all wonky.
Why is there a difference in the rendering when using ID selectors VS Class selectors?

A:

You have other classes in your stylesheet and they're being applied to your container in your JavaScript code:
function sID(message) {
    var b = $("<div id='tweetBox' />");
    $("#header").html("").append(b);
    b.addClass("triangle-right right");
    b.html(message).fadeIn(300).delay(2000).fadeOut(300);
}
function sCLASS(message) {
    var b = $("<div />");
    $("#header").html("").append(b);
    b.addClass("tweetBox-class triangle-right right");
    b.html(message).fadeIn(300).delay(2000).fadeOut(300);
}

So the browser has to take all those classes into account when rendering your container.
The rule with the ID selector overrides every other rule with only class selectors, while the one with the class selector is applied first since it comes first before your other classes, and some styles become overridden by the other classes as they occur later in your stylesheet.