问:
TTS Error: leaked ServiceConnection android.speech.tts.TextToSpeech

Solution

It appears you must call the super method in onActivityResult

```<code>super.onActivityResult(requestCode, resultCode, data);
</code>```

I am getting this error from TTS when I press the back button on my Activity.  Aparently it is because I am not calling shutdown() but I am, see onDestroy() below.  I have made an abstract TtsActivity Class which Activities Extend.  I am calling super.onDestroy() in all subclasses.

```<code>12-05 18:04:05.268: ERROR/ActivityThread(30240): Activity com.mysite.myapp.ActivitySelectItGame has leaked ServiceConnection android.speech.tts.TextToSpeech$1@43e9b4a0 that was originally bound here
12-05 18:04:05.268: ERROR/ActivityThread(30240): android.app.ServiceConnectionLeaked: Activity com.mysite.myapp.ActivitySelectItGame has leaked ServiceConnection android.speech.tts.TextToSpeech$1@43e9b4a0 that was originally bound here
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.app.ActivityThread$PackageInfo$ServiceDispatcher.<init>(ActivityThread.java:1121)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.app.ActivityThread$PackageInfo.getServiceDispatcher(ActivityThread.java:1016)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.app.ContextImpl.bindService(ContextImpl.java:863)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.content.ContextWrapper.bindService(ContextWrapper.java:347)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.speech.tts.TextToSpeech.initTts(TextToSpeech.java:467)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.speech.tts.TextToSpeech.<init>(TextToSpeech.java:433)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at com.mysite.android.library.activity.ActivityTTS.onActivityResult(ActivityTTS.java:98)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at com.mysite.myapp.ActivityGame.onActivityResult(ActivityGame.java:445)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.app.Activity.dispatchActivityResult(Activity.java:3890)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3511)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3557)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.app.ActivityThread.access$2800(ActivityThread.java:125)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2063)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.os.Looper.loop(Looper.java:123)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.app.ActivityThread.main(ActivityThread.java:4627)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at java.lang.reflect.Method.invokeNative(Native Method)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at java.lang.reflect.Method.invoke(Method.java:521)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at dalvik.system.NativeStart.main(Native Method)
</code>```

The Activity that my classes are extending

```<code>public abstract class ActivityTTS extends Activity implements OnInitListener {
    //TEXT TO SPEECH SERVICE
    public static final int CHECK_TTS_AVAILABILITY = 101;
    private static final String TAG = "ActivityTTS";
    private TextToSpeech mTts; //Text to speech library

    //MESSAGES
    private String NO_TTS_ANDROID_MARKET_REDIRECT =
            "'SpeechSynthesis Data Installer' is not installed on your system, you are being redirected to" +
            " the installer package. You may also be able to install it my going to the 'Home Screen' then " +
            "(Menu -> Settings -> Voice Input & output -> Text-to-speech settings)";
    private String NO_TTS_AVAILABLE =
            "'SpeechSynthesis Data Installer' is not available on your system, " +
            "you may have to install it manually yourself. You may also be able to install it my going to the 'Home Screen' " +
            "then (Menu -> Settings -> Voice Input & output -> Text-to-speech settings)";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate() called in ActivityTTS");

        try { //A weird error was occurring on some phones with the TTS, hence the try catch
            //TTS Service
            Intent checkIntent = new Intent();
            checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
            startActivityForResult(checkIntent, CHECK_TTS_AVAILABILITY);
        } catch (Exception e) {
            Toast.makeText(this, NO_TTS_AVAILABLE, Toast.LENGTH_LONG).show();
            finish();
        }

    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * Add a custom audio file for a particular
     * audio element.
     *
     * @param text
     * @param filename
     */
    protected void addSpeech(String text, String filename ) {
        mTts.addSpeech(text, filename);
    }

    /**
     * For TTS
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            //Log.d(TAG, "TTS Response: "+requestCode);
            if (requestCode == CHECK_TTS_AVAILABILITY) {
                if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {

                    // success, create the TTS instance
                    this.mTts = new TextToSpeech(this, this);

                } else {
                    // missing data, install it
                    Toast.makeText(this, NO_TTS_ANDROID_MARKET_REDIRECT, Toast.LENGTH_LONG).show();

                    PackageManager pm = getPackageManager();
                    Intent installIntent = new Intent();
                    installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                    ResolveInfo resolveInfo = pm.resolveActivity( installIntent, PackageManager.MATCH_DEFAULT_ONLY );

                    if( resolveInfo == null ) {
                       // Not able to find the activity which should be started for this intent
                        Toast.makeText(this, NO_TTS_AVAILABLE, Toast.LENGTH_LONG).show();
                    } else {
                       startActivity( installIntent );
                    }

                    finish();
                }
            }
        }catch (Exception e) {
            Log.e(TAG, "Unable to access service");
            finish();
        }

    }

    /**
     * Loads when the TTS is ready
     */
    @Override
    public void onInit(int status) {
        mTts.setLanguage(Locale.getDefault());
    }

    /**
     * Speak text
     */
    protected void speak(String text) {
        try{
            mTts.stop(); //Stop speaking
            mTts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
        }
        catch(Exception e) {
            Log.e(TAG, "TTS Failed - cannot say: "+text );
        }
    }

    /**
     * Speak a pre-recorded word
     */
    protected void speak(String text, File filename) {
        try{
            mTts.stop(); //Stop speaking
            mTts.addSpeech(text, filename.toString());
            mTts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
        }
        catch(Exception e) {
            Log.e(TAG, "TTS Failed - cannot say: "+text );
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //Close the Text to Speech Library
        if(mTts != null) {

            mTts.stop();
            mTts.shutdown();
            Log.d(TAG, "TTS Destroyed");
        }
    }

    public void setLanguage(Locale audioLocale) {
        mTts.setLanguage(audioLocale);
    }
}
</code>```

Here is the code related the the activity in ActivityGame

```<code>public abstract class ActivityGame extends ActivityTTS {

...

    protected void speak() {
        if (Logging.INFO) Log.i(TAG, "Speaking");

        if(this.mVoicePreference) {
            String word = mBoundService.getCurrentWord().getSpelling();

            if(WordRecordingHelper.recordingExists(word)) {

                try{
                    File f = new File(Constants.SDCARD_RECORDINGS+WordRecordingHelper.formatRecordedWord(word));
                    super.addSpeech(word, f.getAbsolutePath());
                } catch (Exception e) {
                    if(Logging.WARN) Log.w(TAG, "An error occurred while trying to use addSpeech()", e);
                }
            }

            //play the audio
            super.speak(word);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ...

        }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        ....
        }

}
</code>```

And here is ActivitySelectItGame, it doe not reference TTS at all, just extends ActivityGame

```<code>public class ActivitySelectItGame extends ActivityGame {
    ...
}
</code>```

But I get the exact same problem from a totally unrelated Activity the extends ActivityTTS.

答: onCreate(), where you start the activity for result in order to check whether TTS is available, can be called by the framework many times. So I think you may be creating multiple TTS instances in onActivityResult(). For more information, see the diagram for the Activity class. Note that onCreate() can be called again after a call to onStop()

Body:
Solution

It appears you must call the super method in onActivityResult

super.onActivityResult(requestCode, resultCode, data);

I am getting this error from TTS when I press the back button on my Activity.  Aparently it is because I am not calling shutdown() but I am, see onDestroy() below.  I have made an abstract TtsActivity Class which Activities Extend.  I am calling super.onDestroy() in all subclasses.

12-05 18:04:05.268: ERROR/ActivityThread(30240): Activity com.mysite.myapp.ActivitySelectItGame has leaked ServiceConnection android.speech.tts.TextToSpeech$1@43e9b4a0 that was originally bound here
12-05 18:04:05.268: ERROR/ActivityThread(30240): android.app.ServiceConnectionLeaked: Activity com.mysite.myapp.ActivitySelectItGame has leaked ServiceConnection android.speech.tts.TextToSpeech$1@43e9b4a0 that was originally bound here
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.app.ActivityThread$PackageInfo$ServiceDispatcher.<init>(ActivityThread.java:1121)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.app.ActivityThread$PackageInfo.getServiceDispatcher(ActivityThread.java:1016)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.app.ContextImpl.bindService(ContextImpl.java:863)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.content.ContextWrapper.bindService(ContextWrapper.java:347)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.speech.tts.TextToSpeech.initTts(TextToSpeech.java:467)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.speech.tts.TextToSpeech.<init>(TextToSpeech.java:433)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at com.mysite.android.library.activity.ActivityTTS.onActivityResult(ActivityTTS.java:98)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at com.mysite.myapp.ActivityGame.onActivityResult(ActivityGame.java:445)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.app.Activity.dispatchActivityResult(Activity.java:3890)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3511)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3557)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.app.ActivityThread.access$2800(ActivityThread.java:125)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2063)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.os.Looper.loop(Looper.java:123)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at android.app.ActivityThread.main(ActivityThread.java:4627)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at java.lang.reflect.Method.invokeNative(Native Method)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at java.lang.reflect.Method.invoke(Method.java:521)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12-05 18:04:05.268: ERROR/ActivityThread(30240):     at dalvik.system.NativeStart.main(Native Method)

The Activity that my classes are extending

public abstract class ActivityTTS extends Activity implements OnInitListener {
    //TEXT TO SPEECH SERVICE
    public static final int CHECK_TTS_AVAILABILITY = 101;
    private static final String TAG = "ActivityTTS";
    private TextToSpeech mTts; //Text to speech library

    //MESSAGES
    private String NO_TTS_ANDROID_MARKET_REDIRECT =
            "'SpeechSynthesis Data Installer' is not installed on your system, you are being redirected to" +
            " the installer package. You may also be able to install it my going to the 'Home Screen' then " +
            "(Menu -> Settings -> Voice Input & output -> Text-to-speech settings)";
    private String NO_TTS_AVAILABLE =
            "'SpeechSynthesis Data Installer' is not available on your system, " +
            "you may have to install it manually yourself. You may also be able to install it my going to the 'Home Screen' " +
            "then (Menu -> Settings -> Voice Input & output -> Text-to-speech settings)";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate() called in ActivityTTS");

        try { //A weird error was occurring on some phones with the TTS, hence the try catch
            //TTS Service
            Intent checkIntent = new Intent();
            checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
            startActivityForResult(checkIntent, CHECK_TTS_AVAILABILITY);
        } catch (Exception e) {
            Toast.makeText(this, NO_TTS_AVAILABLE, Toast.LENGTH_LONG).show();
            finish();
        }

    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * Add a custom audio file for a particular
     * audio element.
     *
     * @param text
     * @param filename
     */
    protected void addSpeech(String text, String filename ) {
        mTts.addSpeech(text, filename);
    }

    /**
     * For TTS
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            //Log.d(TAG, "TTS Response: "+requestCode);
            if (requestCode == CHECK_TTS_AVAILABILITY) {
                if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {

                    // success, create the TTS instance
                    this.mTts = new TextToSpeech(this, this);

                } else {
                    // missing data, install it
                    Toast.makeText(this, NO_TTS_ANDROID_MARKET_REDIRECT, Toast.LENGTH_LONG).show();

                    PackageManager pm = getPackageManager();
                    Intent installIntent = new Intent();
                    installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                    ResolveInfo resolveInfo = pm.resolveActivity( installIntent, PackageManager.MATCH_DEFAULT_ONLY );

                    if( resolveInfo == null ) {
                       // Not able to find the activity which should be started for this intent
                        Toast.makeText(this, NO_TTS_AVAILABLE, Toast.LENGTH_LONG).show();
                    } else {
                       startActivity( installIntent );
                    }

                    finish();
                }
            }
        }catch (Exception e) {
            Log.e(TAG, "Unable to access service");
            finish();
        }

    }

    /**
     * Loads when the TTS is ready
     */
    @Override
    public void onInit(int status) {
        mTts.setLanguage(Locale.getDefault());
    }

    /**
     * Speak text
     */
    protected void speak(String text) {
        try{
            mTts.stop(); //Stop speaking
            mTts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
        }
        catch(Exception e) {
            Log.e(TAG, "TTS Failed - cannot say: "+text );
        }
    }

    /**
     * Speak a pre-recorded word
     */
    protected void speak(String text, File filename) {
        try{
            mTts.stop(); //Stop speaking
            mTts.addSpeech(text, filename.toString());
            mTts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
        }
        catch(Exception e) {
            Log.e(TAG, "TTS Failed - cannot say: "+text );
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //Close the Text to Speech Library
        if(mTts != null) {

            mTts.stop();
            mTts.shutdown();
            Log.d(TAG, "TTS Destroyed");
        }
    }

    public void setLanguage(Locale audioLocale) {
        mTts.setLanguage(audioLocale);
    }
}

Here is the code related the the activity in ActivityGame

public abstract class ActivityGame extends ActivityTTS {

...

    protected void speak() {
        if (Logging.INFO) Log.i(TAG, "Speaking");

        if(this.mVoicePreference) {
            String word = mBoundService.getCurrentWord().getSpelling();

            if(WordRecordingHelper.recordingExists(word)) {

                try{
                    File f = new File(Constants.SDCARD_RECORDINGS+WordRecordingHelper.formatRecordedWord(word));
                    super.addSpeech(word, f.getAbsolutePath());
                } catch (Exception e) {
                    if(Logging.WARN) Log.w(TAG, "An error occurred while trying to use addSpeech()", e);
                }
            }

            //play the audio
            super.speak(word);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ...

        }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        ....
        }

}

And here is ActivitySelectItGame, it doe not reference TTS at all, just extends ActivityGame

public class ActivitySelectItGame extends ActivityGame {
    ...
}

But I get the exact same problem from a totally unrelated Activity the extends ActivityTTS.


来源: stackexchange

问:
The Constructor is undefined? Enum error
```<code>public Tipo getTipo() {
    return this.Importo < 0.0 ? Tipo.USCITA : Tipo.ENTRATA;
}

public int compareTo(Movimento m) {
    if (this.idConto != this.idConto) {
        return this.idConto - this.idConto;
    }
    return this.DataMov.compareTo(this.DataMov);
}

public static enum Tipo {
    ENTRATA,// here i have this error : The constructor Movimento.Tipo() is undefined
    USCITA;// here is the same : The constructor Movimento.Tipo() is undefined

    private Tipo(String string2, int n2) {
    }
}
</code>```

I already have constructor that I need, what else I need to write?

答:
You are written wrong enum.

```<code>public enum abc {

    ENTRATA("abc", 1),// here i have this error : The constructor Movimento.Tipo() is undefined
    USCITA("xyz", 2);// here is the same : The constructor Movimento.Tipo() is undefined

    private abc(String string2, int n2) {
    }
</code>```

}

ContentLicense: CC BY-SA 3.0

Body:
public Tipo getTipo() {
    return this.Importo < 0.0 ? Tipo.USCITA : Tipo.ENTRATA;
}

public int compareTo(Movimento m) {
    if (this.idConto != this.idConto) {
        return this.idConto - this.idConto;
    }
    return this.DataMov.compareTo(this.DataMov);
}

public static enum Tipo {
    ENTRATA,// here i have this error : The constructor Movimento.Tipo() is undefined
    USCITA;// here is the same : The constructor Movimento.Tipo() is undefined

    private Tipo(String string2, int n2) {
    }
}

I already have constructor that I need, what else I need to write?

Body:
You are written wrong enum.

public enum abc {

    ENTRATA("abc", 1),// here i have this error : The constructor Movimento.Tipo() is undefined
    USCITA("xyz", 2);// here is the same : The constructor Movimento.Tipo() is undefined

    private abc(String string2, int n2) {
    }

}


问:
button doesn't click in android studio
```<code>private Button mfactbutton;
private TextView mfacttext;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_fun_fact);

    Button mfactbutton = (Button) findViewById(R.id.button);
    TextView mfacttext = (TextView) findViewById(R.id.textView2);

    // now we need to make out button to click
    View.OnClickListener Listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String[] facts = {
                    "Ants stretch when they wake up in the morning.",
                    "Ostriches can run faster than horses.",
                    "Olympic gold medals are actually made mostly of silver.",
                    "You are born with 300 bones; by the time you are an adult you will have 206.",
                    "It takes about 8 minutes for light from the Sun to reach Earth.",
                    "Some bamboo plants can grow almost a meter in just one day.",
                    "The state of Florida is bigger than England.",
                    "Some penguins can leap 2-3 meters out of the water.",
                    "On average, it takes 66 days to form a new habit.",
                    "Mammoths still walked the earth when the Great Pyramid was being built." };

            String fact = "";

            // randomly select a fact

            Random randomGenerator = new Random();
            int randomNumber = randomGenerator.nextInt(facts.length);
            fact = facts[randomNumber] + "";
        }
    };
    mfactbutton.setOnClickListener(Listener);

}
</code>```

}

Hey everyone! i need help! my button doesn't just simply clicl!!!!! heeeeeeeeelp!i'm just trying to make a simple button that changes the textview2 with each click! at first it was working but now it started not to work.

答:
use this</p>

```<code>  mfactbutton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
// Your code goes here
    }
});
</code>```

Title: button doesn't click in android studio

Body:
private Button mfactbutton;
private TextView mfacttext;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_fun_fact);

    Button mfactbutton = (Button) findViewById(R.id.button);
    TextView mfacttext = (TextView) findViewById(R.id.textView2);

    // now we need to make out button to click
    View.OnClickListener Listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String[] facts = {
                    "Ants stretch when they wake up in the morning.",
                    "Ostriches can run faster than horses.",
                    "Olympic gold medals are actually made mostly of silver.",
                    "You are born with 300 bones; by the time you are an adult you will have 206.",
                    "It takes about 8 minutes for light from the Sun to reach Earth.",
                    "Some bamboo plants can grow almost a meter in just one day.",
                    "The state of Florida is bigger than England.",
                    "Some penguins can leap 2-3 meters out of the water.",
                    "On average, it takes 66 days to form a new habit.",
                    "Mammoths still walked the earth when the Great Pyramid was being built." };

            String fact = "";

            // randomly select a fact

            Random randomGenerator = new Random();
            int randomNumber = randomGenerator.nextInt(facts.length);
            fact = facts[randomNumber] + "";
        }
    };
    mfactbutton.setOnClickListener(Listener);

}

}

Hey everyone! i need help! my button doesn't just simply clicl!!!!! heeeeeeeeelp!i'm just trying to make a simple button that changes the textview2 with each click! at first it was working but now it started not to work.

Body:
use this

  mfactbutton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
// Your code goes here
    }
});


问:
JPA perfomance with case insensitive in select
I have a JPA select where you receibe a parameter then we can search using some attributes (username, email, identifier) The user only have a text field to write the criteria text.

The problem is perfomance, in the database We have about 9Millions of users registereds, and the search is too slow, using JPA,

Form:
  - Value (Input text)

User sends the value in the form (He doesn't say if he is using username, email or identifier)

User (Table) Fields:
  - Identifier
  - Name
  - Email

JPA Query:

```<code>select u from UserEntity u where u.alias LIKE lower(:query) OR u.email LIKE lower(:query) OR lower(u.identifier) LIKE lower(:query) ORDER BY u.alias
</code>```

I don't know what the best method to improve the speed of the search, (We have some indexes in the table in these fields), if we remove the lower in the u.identifier field the speed improves a lot (almost instant). But we can have the identifier in a lot of ways (migrations, registers, manual client inserts..)

答:
You can solve it using different techniques.

One is using a collate that ignores case. For example in MySQL https://dev.mysql.com/doc/refman/5.7/en/case-sensitivity.html

Another strategy is to have a derived field with an index. In DB2, for example, you can create a field 'lower_identifier generated always as lower(identifier)' and an index in the field and it will use it automatically when doing a lower search. You don't have to map the field in JPA.

Body:
I have a JPA select where you receibe a parameter then we can search using some attributes (username, email, identifier) The user only have a text field to write the criteria text.

The problem is perfomance, in the database We have about 9Millions of users registereds, and the search is too slow, using JPA,

Form:
  - Value (Input text)

User sends the value in the form (He doesn't say if he is using username, email or identifier)

User (Table) Fields:
  - Identifier
  - Name
  - Email

JPA Query:

select u from UserEntity u where u.alias LIKE lower(:query) OR u.email LIKE lower(:query) OR lower(u.identifier) LIKE lower(:query) ORDER BY u.alias

I don't know what the best method to improve the speed of the search, (We have some indexes in the table in these fields), if we remove the lower in the u.identifier field the speed improves a lot (almost instant). But we can have the identifier in a lot of ways (migrations, registers, manual client inserts..)


问:
How to access service in vagrant from native ip 127.0.0.1?
Use Vagrant installed devstack. Set the HOST_IP to 127.0.0.1 before the installation config. After finish the installation, it told use these information to access web ui:

```<code>=========================
DevStack Component Timing
=========================
Total runtime    3523

run_process      113
test_with_retry    7
pip_install      647
wait_for_service  51
yum_install      338
git_timed        853
=========================

This is your host IP address: 127.0.0.1
This is your host IPv6 address: ::1
Horizon is now available at http://127.0.0.1/dashboard
Keystone is serving at http://127.0.0.1/identity/
The default users are: admin and demo
The password: secret
Services are running under systemd unit files.
For more information see:
https://docs.openstack.org/developer/devstack/systemd.html
</code>```

I set private_ip in Vagrantfile with 192.168.33.11, I tried this way to access the web ui:

http://192.168.33.11/dashboard

But not works. Therefore, I test used curl in Vagrant can confirm something:

```<code>[stack@localhost devstack]$ curl -I http://127.0.0.1/dashboard
HTTP/1.1 302 Found
Date: Mon, 05 Jun 2017 10:38:37 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.1e-fips mod_wsgi/3.4 Python/2.7.5
Vary: Accept-Language,Cookie
X-Frame-Options: SAMEORIGIN
Content-Language: en
Location: http://127.0.0.1/dashboard/auth/login/?next=/dashboard/
Content-Type: text/html; charset=utf-8
</code>```

How to access the dashboard now?

答:
This way works:

```<code>$ ssh -L 8080:localhost:80 vagrant@192.168.33.11
</code>```

From browser:

http://localhost:8080/dashboard

Reference

```<code>$ man ssh
-L [bind_address:]port:host:hostport
         Specifies that the given port on the local (client) host is to be forwarded to the given host and port on the remote side.  This works by allocating a socket to listen to
         port on the local side, optionally bound to the specified bind_address.  Whenever a connection is made to this port, the connection is forwarded over the secure channel,
         and a connection is made to host port hostport from the remote machine.  Port forwardings can also be specified in the configuration file.  IPv6 addresses can be specified
         by enclosing the address in square brackets.  Only the superuser can forward privileged ports.  By default, the local port is bound in accordance with the GatewayPorts set‐
         ting.  However, an explicit bind_address may be used to bind the connection to a specific address.  The bind_address of “localhost” indicates that the listening port be
         bound for local use only, while an empty address or ‘*’ indicates that the port should be available from all interfaces.
</code>```

Body:
Use Vagrant installed devstack. Set the HOST_IP to 127.0.0.1 before the installation config. After finish the installation, it told use these information to access web ui:

=========================
DevStack Component Timing
=========================
Total runtime    3523

run_process      113
test_with_retry    7
pip_install      647
wait_for_service  51
yum_install      338
git_timed        853
=========================

This is your host IP address: 127.0.0.1
This is your host IPv6 address: ::1
Horizon is now available at http://127.0.0.1/dashboard
Keystone is serving at http://127.0.0.1/identity/
The default users are: admin and demo
The password: secret
Services are running under systemd unit files.
For more information see:
https://docs.openstack.org/developer/devstack/systemd.html

I set private_ip in Vagrantfile with 192.168.33.11, I tried this way to access the web ui:

http://192.168.33.11/dashboard

But not works. Therefore, I test used curl in Vagrant can confirm something:

[stack@localhost devstack]$ curl -I http://127.0.0.1/dashboard
HTTP/1.1 302 Found
Date: Mon, 05 Jun 2017 10:38:37 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.1e-fips mod_wsgi/3.4 Python/2.7.5
Vary: Accept-Language,Cookie
X-Frame-Options: SAMEORIGIN
Content-Language: en
Location: http://127.0.0.1/dashboard/auth/login/?next=/dashboard/
Content-Type: text/html; charset=utf-8

How to access the dashboard now?

Body:
This way works:

$ ssh -L 8080:localhost:80 vagrant@192.168.33.11

From browser:

http://localhost:8080/dashboard

Reference

$ man ssh
-L [bind_address:]port:host:hostport
         Specifies that the given port on the local (client) host is to be forwarded to the given host and port on the remote side.  This works by allocating a socket to listen to
         port on the local side, optionally bound to the specified bind_address.  Whenever a connection is made to this port, the connection is forwarded over the secure channel,
         and a connection is made to host port hostport from the remote machine.  Port forwardings can also be specified in the configuration file.  IPv6 addresses can be specified
         by enclosing the address in square brackets.  Only the superuser can forward privileged ports.  By default, the local port is bound in accordance with the GatewayPorts set‐
         ting.  However, an explicit bind_address may be used to bind the connection to a specific address.  The bind_address of “localhost” indicates that the listening port be
         bound for local use only, while an empty address or ‘*’ indicates that the port should be available from all interfaces.


问:
need explanation acc_x = Wire.read()<<8|Wire.read();
what does wire.read()<<8|wire.read() do? </p>

```<code>while(Wire.available() < 14);
until all the bytes are received
 acc_x = Wire.read()<<8|Wire.read();
 acc_y = Wire.read()<<8|Wire.read();
 acc_z = Wire.read()<<8|Wire.read();
 temp = Wire.read()<<8|Wire.read();
 gyro_x = Wire.read()<<8|Wire.read();
 gyro_y = Wire.read()<<8|Wire.read();
 gyro_z = Wire.read()<<8|Wire.read();
</code>```

答:
Judging from this code I'd say the device reports acceleration as more than an 8-bit number, perhaps 16 bits, but only 8 bits at a time...so assuming the acc_x value is defined as an integer in your sketch. So we're filling a 16-bit value 8 bits at a time I'd guess...

So, Wire.read() probably gets an 8-bit  value.  The next part <<8 shifts that value, eight bits left, effectively multiplying it by 256.  The second Wire.read is ored with the first with | , effectively adding it to the first byte. This read-shift-or process is repeated for every measure the device supplies.

```<code>00001010 // let's assume this is the result of the first read
<<8 gives 00001010_00000000
00001111  // let's assume this is the result of the second read
00001010_00000000 | 00001111  // | has the effect of adding here

gives 00001010_00001111 //final acceleration value
</code>```

So to recap, the 16-bit number is built up by taking the number from the first read, left-shifting it to make its bits more significant, then oring (adding) the result of the second read.

As your tag suggests, this is called bitwise math or bitwise manipulation and it's very common on Arduino and all microcontroller platforms which have input pins arranged in 8-bit "ports," and it's also common for peripherals for these devices to supply their data one byte at a time like this so as to reduce the number of pins to interface the peripheral.

Body:
what does wire.read()<<8|wire.read() do?

while(Wire.available() < 14);
until all the bytes are received
 acc_x = Wire.read()<<8|Wire.read();
 acc_y = Wire.read()<<8|Wire.read();
 acc_z = Wire.read()<<8|Wire.read();
 temp = Wire.read()<<8|Wire.read();
 gyro_x = Wire.read()<<8|Wire.read();
 gyro_y = Wire.read()<<8|Wire.read();
 gyro_z = Wire.read()<<8|Wire.read();

Body:
Judging from this code I'd say the device reports acceleration as more than an 8-bit number, perhaps 16 bits, but only 8 bits at a time...so assuming the acc_x value is defined as an integer in your sketch. So we're filling a 16-bit value 8 bits at a time I'd guess...

So, Wire.read() probably gets an 8-bit  value.  The next part <<8 shifts that value, eight bits left, effectively multiplying it by 256.  The second Wire.read is ored with the first with | , effectively adding it to the first byte. This read-shift-or process is repeated for every measure the device supplies.

00001010 // let's assume this is the result of the first read
<<8 gives 00001010_00000000
00001111  // let's assume this is the result of the second read
00001010_00000000 | 00001111  // | has the effect of adding here

gives 00001010_00001111 //final acceleration value

So to recap, the 16-bit number is built up by taking the number from the first read, left-shifting it to make its bits more significant, then oring (adding) the result of the second read.

As your tag suggests, this is called bitwise math or bitwise manipulation and it's very common on Arduino and all microcontroller platforms which have input pins arranged in 8-bit "ports," and it's also common for peripherals for these devices to supply their data one byte at a time like this so as to reduce the number of pins to interface the peripheral.


问:
css class not working properly
i'm redesigning my website. and doing that i'm finding myself in some problems using the css code i wrote.

i use div's to get an image and some text next to each other.
i'm unable to get the text moved to the correct place (see pictures) the margin-left doesn't seem to work when it is in the css file but it works when directly embedded in the div tags, am i doing something wrong?

also i'dd like to add that i don't need to set the image size in the html code but its in the css code is this possible?

What i get

What i want

body
{
 background:#333 url(bg.jpg) repeat top left;
 font-family:Arial;
 color:white;
 text-align:center;
}

body header.heading
{
 width:1150px;
 /*background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;*/
 margin:0 auto;
 z-index:0;

}

body.Content
{
 width:1150px;
}

main
{
width:1150px;
 margin: 0 auto;
}

section
{
 text-align:left;
 margin:0 auto;
}

header nav
{
 width:1150px;
 background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;
 margin:0 auto;
 z-index:0;
}

header nav ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

header nav li {
    float: left;
    border-right: 1px solid #bbb;
}

header nav li:last-child {
    border-right: none;
}

/*header nav li a {
    display: block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}*/

/* Change the link color to #111 (black) on hover */
header nav li a:hover {
    background-color: #111;
}

header nav li.active {
    background-color: #4CAF50;
}

header nav li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}

header nav li a:hover, .dropdown:hover .dropbtn {
    background-color:  #111;
}

header nav li.dropdown {
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

nav
{
 text-align:left;
 margin:0 auto;
}

.hidden {display:none}

hr
{
 border-left: none;
 border-right: none;
 height:4px;
 margin: 2em 0 2em 0;
}

main a:link {color:#fff;}      /* unvisited link */

main a:visited {color:#fff;}  /* visited link */

main a:hover {color:#159;}  /* mouse over link */

blockquote{
 color:white;
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
}

h2
{
 font-size: 30px;
 color:Black;
}

h1,h2,h3,h4
{
 font-family: 'Open Sans Condensed', sans-serif;
 color:#4CAF50;
 text-decoration:underline;
}

h2, h3
{
 font-size: 1.6em;
 letter-spacing: -1px;
 margin: 0 0 0.75em 0;
}

h3
{
 font-size:1.3em;
}

h1
{
 font:bold;
}

h4
{
 font-size:1em;
 margin: 0.5em 0 0.5em;
 padding-left:1em;
}

.green
{
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
 color: #4CAF50;
 margin-left:40px;
 font-style:oblique;
}

article.centeralign
{
 text-align:center;
}

div.wrapper{
 width: 800px;
 overflow: hidden;
}

div.toolsWrapper{
 width: 980px;
 overflow: hidden;
}

div.left{
    width: 200px;
    float:left;
    margin-right:40px;
    padding-left:40px;
}

div.right{
    float:left;
    margin-left: 20px;
}

div.cc
 {
  width:200px;
  text-align:right;
  font-size:10px;
 }

div.ccf
 {
  text-align:center;
  font-size:12px;
 }

iframe
{
 text-align:center;
 float:center;
}

/* ===========================
   ====== Contact Form =======
   =========================== */

input, textarea {
 padding: 10px;
 border: 1px solid #E5E5E5;
 width: 200px;
 color: #999999;
 box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
}

textarea {
 width: 400px;
 height: 150px;
 max-width: 400px;
 line-height: 18px;
}

input:hover, textarea:hover,
input:focus, textarea:focus {
 border-color: 1px solid #C9C9C9;
 box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
}

.form label {
 margin-left: 10px;
 color: #999999;
}

/* ===========================
   ====== Submit Button ======
   =========================== */

.submit input {
 width: 100px;
 height: 40px;
 background-color: #474E69;
 color: #FFF;
 border-radius: 3px;
 -moz-border-radius: 3px;
 -webkit-border-radius: 3px;
}

table, th, td {
    border: 1px solid black;
    border-color:white;
}

th, td {
    padding: 15px;
}

.blue{
  background: url(blue.png) no-repeat left center;
    color: #109CEF;
    padding: 0px 40px 0px 20px;
  font-style:oblique;
 }

.red{
  background: url(red.png) no-repeat left center;
  color:#FF0000;
  padding: 0px 40px 0px 20px;
  font-style:oblique;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article>
  <h1>Audio Projects</h1>
    <blockquote>
     <h3>

              Class D Amplifier

      </h3>
      <div class="wrapper">
          <div class="left">
              <img src="Damp/Damp_front.JPG"/>
          </div>
          <div class="right">
              Some text that should be next to image
          </div>
      </div>
  </blockquote>
</article></code>```

答:
I guess problem is with width of left class division. Try to make it auto.

```<code>div.left{
   width: auto;
   ....
}
</code>```

Title: css class not working properly

Body:
i'm redesigning my website. and doing that i'm finding myself in some problems using the css code i wrote.

i use div's to get an image and some text next to each other.
i'm unable to get the text moved to the correct place (see pictures) the margin-left doesn't seem to work when it is in the css file but it works when directly embedded in the div tags, am i doing something wrong?

also i'dd like to add that i don't need to set the image size in the html code but its in the css code is this possible?

What i get

What i want

body
{
 background:#333 url(bg.jpg) repeat top left;
 font-family:Arial;
 color:white;
 text-align:center;
}

body header.heading
{
 width:1150px;
 /*background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;*/
 margin:0 auto;
 z-index:0;

}

body.Content
{
 width:1150px;
}

main
{
width:1150px;
 margin: 0 auto;
}

section
{
 text-align:left;
 margin:0 auto;
}

header nav
{
 width:1150px;
 background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;
 margin:0 auto;
 z-index:0;
}

header nav ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

header nav li {
    float: left;
    border-right: 1px solid #bbb;
}

header nav li:last-child {
    border-right: none;
}

/*header nav li a {
    display: block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}*/

/* Change the link color to #111 (black) on hover */
header nav li a:hover {
    background-color: #111;
}

header nav li.active {
    background-color: #4CAF50;
}

header nav li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}

header nav li a:hover, .dropdown:hover .dropbtn {
    background-color:  #111;
}

header nav li.dropdown {
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

nav
{
 text-align:left;
 margin:0 auto;
}

.hidden {display:none}

hr
{
 border-left: none;
 border-right: none;
 height:4px;
 margin: 2em 0 2em 0;
}

main a:link {color:#fff;}      /* unvisited link */

main a:visited {color:#fff;}  /* visited link */

main a:hover {color:#159;}  /* mouse over link */

blockquote{
 color:white;
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
}

h2
{
 font-size: 30px;
 color:Black;
}

h1,h2,h3,h4
{
 font-family: 'Open Sans Condensed', sans-serif;
 color:#4CAF50;
 text-decoration:underline;
}

h2, h3
{
 font-size: 1.6em;
 letter-spacing: -1px;
 margin: 0 0 0.75em 0;
}

h3
{
 font-size:1.3em;
}

h1
{
 font:bold;
}

h4
{
 font-size:1em;
 margin: 0.5em 0 0.5em;
 padding-left:1em;
}

.green
{
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
 color: #4CAF50;
 margin-left:40px;
 font-style:oblique;
}

article.centeralign
{
 text-align:center;
}

div.wrapper{
 width: 800px;
 overflow: hidden;
}

div.toolsWrapper{
 width: 980px;
 overflow: hidden;
}

div.left{
    width: 200px;
    float:left;
    margin-right:40px;
    padding-left:40px;
}

div.right{
    float:left;
    margin-left: 20px;
}

div.cc
 {
  width:200px;
  text-align:right;
  font-size:10px;
 }

div.ccf
 {
  text-align:center;
  font-size:12px;
 }

iframe
{
 text-align:center;
 float:center;
}

/* ===========================
   ====== Contact Form =======
   =========================== */

input, textarea {
 padding: 10px;
 border: 1px solid #E5E5E5;
 width: 200px;
 color: #999999;
 box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
}

textarea {
 width: 400px;
 height: 150px;
 max-width: 400px;
 line-height: 18px;
}

input:hover, textarea:hover,
input:focus, textarea:focus {
 border-color: 1px solid #C9C9C9;
 box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
}

.form label {
 margin-left: 10px;
 color: #999999;
}

/* ===========================
   ====== Submit Button ======
   =========================== */

.submit input {
 width: 100px;
 height: 40px;
 background-color: #474E69;
 color: #FFF;
 border-radius: 3px;
 -moz-border-radius: 3px;
 -webkit-border-radius: 3px;
}

table, th, td {
    border: 1px solid black;
    border-color:white;
}

th, td {
    padding: 15px;
}

.blue{
  background: url(blue.png) no-repeat left center;
    color: #109CEF;
    padding: 0px 40px 0px 20px;
  font-style:oblique;
 }

.red{
  background: url(red.png) no-repeat left center;
  color:#FF0000;
  padding: 0px 40px 0px 20px;
  font-style:oblique;
}

Audio Projects

              Class D Amplifier

              Some text that should be next to image

Body:
I guess problem is with width of left class division. Try to make it auto.

div.left{
   width: auto;
   ....
}


问:
C# | Login doesn't work
I can't figure it out why my Login system doesn't work.

It always resulting "FALSE" or "WRONG PASSWORD" tho I've entered the right password.

And yes, I've checked the column name and the table name as well. Nothing wrong but doesn't work.

I can't figure it out.

```<code>namespace GitGut {
    public partial class Login : Window {
        public String thisName;
        private String thisConnectionString = @"Data Source = THISISMINE\SQLEXPRESS;Initial Catalog = GitGut; Integrated Security = True";
        public Login() {
            InitializeComponent();
        }

        private void Button_Login_Click(object sender, RoutedEventArgs e) {
            Console.WriteLine("Button_Login pressed.");
            if(theValidation(TextBox_Username.Text, PasswordBox_Password.Password) == true) {
                Dashboard Form_Dashboard = new Dashboard();
                Form_Dashboard.Show();
                this.Hide();
            } else {
                MessageBox.Show("ERROR", "ERROR");
            }
        }

        private Boolean theValidation(String thisUsername, String thisPassword) {
            SqlConnection thisSqlConnection = new SqlConnection(thisConnectionString);
            SqlCommand thisSqlCommand = new SqlCommand();
            thisSqlCommand.Parameters.Add("@Username", SqlDbType.VarChar).Value = thisUsername;
            thisSqlCommand.Parameters.Add("@Password", SqlDbType.VarChar).Value = thisPassword;
            String thisQuery = "SELECT * FROM [User] WHERE [Username] = '@Username' AND [Password] = '@Password'";
            thisSqlCommand.Connection = thisSqlConnection;
            thisSqlCommand.CommandText = thisQuery;
            thisSqlConnection.Open();
            SqlDataReader thisSqlDataReader = thisSqlCommand.ExecuteReader();
            if(thisSqlDataReader.Read()) {
                thisSqlConnection.Close();
                return true;
            } else {
                thisSqlConnection.Close();
                return false;
            }
        }
    }
}
</code>```

答:
You should remove the ' from the query string:

```<code>String thisQuery = "SELECT * FROM [User] WHERE [Username] = @Username AND [Password] = @Password";
</code>```

The Sqlcommand parameters does not need any separator/indicator. You are already telling what type they are in thisSqlCommand.Parameters.Add("@Password", SqlDbType.VarChar)..., so the query string is correctly constructed.

Title: C# | Login doesn't work

Body:
I can't figure it out why my Login system doesn't work.

It always resulting "FALSE" or "WRONG PASSWORD" tho I've entered the right password.

And yes, I've checked the column name and the table name as well. Nothing wrong but doesn't work.

I can't figure it out.

namespace GitGut {
    public partial class Login : Window {
        public String thisName;
        private String thisConnectionString = @"Data Source = THISISMINE\SQLEXPRESS;Initial Catalog = GitGut; Integrated Security = True";
        public Login() {
            InitializeComponent();
        }

        private void Button_Login_Click(object sender, RoutedEventArgs e) {
            Console.WriteLine("Button_Login pressed.");
            if(theValidation(TextBox_Username.Text, PasswordBox_Password.Password) == true) {
                Dashboard Form_Dashboard = new Dashboard();
                Form_Dashboard.Show();
                this.Hide();
            } else {
                MessageBox.Show("ERROR", "ERROR");
            }
        }

        private Boolean theValidation(String thisUsername, String thisPassword) {
            SqlConnection thisSqlConnection = new SqlConnection(thisConnectionString);
            SqlCommand thisSqlCommand = new SqlCommand();
            thisSqlCommand.Parameters.Add("@Username", SqlDbType.VarChar).Value = thisUsername;
            thisSqlCommand.Parameters.Add("@Password", SqlDbType.VarChar).Value = thisPassword;
            String thisQuery = "SELECT * FROM [User] WHERE [Username] = '@Username' AND [Password] = '@Password'";
            thisSqlCommand.Connection = thisSqlConnection;
            thisSqlCommand.CommandText = thisQuery;
            thisSqlConnection.Open();
            SqlDataReader thisSqlDataReader = thisSqlCommand.ExecuteReader();
            if(thisSqlDataReader.Read()) {
                thisSqlConnection.Close();
                return true;
            } else {
                thisSqlConnection.Close();
                return false;
            }
        }
    }
}

Body:
You should remove the ' from the query string:

String thisQuery = "SELECT * FROM [User] WHERE [Username] = @Username AND [Password] = @Password";

The Sqlcommand parameters does not need any separator/indicator. You are already telling what type they are in thisSqlCommand.Parameters.Add("@Password", SqlDbType.VarChar)..., so the query string is correctly constructed.


问:
SharpZipLib - ZipException "System.ArgumentOutOfRangeException" - Why am I getting this exception?
I'm using SharpZipLib to unzip files. My code has been working nicely for all zipfiles except the zip file what i am extracting now...

Got this exception:

```<code>System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: length
</code>```

The exception is being thrown at   size = s.Read(data, 0, data.Length);

Hereb is my code...

```<code> public static void UnzipFile(string sourcePath, string targetDirectory)
     {
        try
        {
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(sourcePath)))
            {
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    //string directoryName = Path.GetDirectoryName(theEntry.Name);
                    string fileName = Path.GetFileName(theEntry.Name);

                    if (targetDirectory.Length > 0)
                    {
                        Directory.CreateDirectory(targetDirectory);
                    }

                    if (fileName != String.Empty)
                    {
                        using (FileStream streamWriter = File.Create(targetDirectory + fileName))
                        {
                            int size = 2048;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception("Error unzipping file \"" + sourcePath + "\"", ex);
        }
    }
</code>```

答:
Change your code    int size = 2048;  to int size = data.Length;. You won't take OutOfRange exception.

```<code> using (FileStream streamWriter = File.Create(targetDirectory + fileName))
    {
       int size = data.Length;
       byte[] data = new byte[size];
       while (true)
       {
            size = s.Read(data, 0, data.Length);
            if (size > 0)
            {
                streamWriter.Write(data, 0, size);
            }
            else
            {
               break;
            }
       }
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm using SharpZipLib to unzip files. My code has been working nicely for all zipfiles except the zip file what i am extracting now...

Got this exception:

System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: length

The exception is being thrown at   size = s.Read(data, 0, data.Length);

Hereb is my code...

 public static void UnzipFile(string sourcePath, string targetDirectory)
     {
        try
        {
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(sourcePath)))
            {
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    //string directoryName = Path.GetDirectoryName(theEntry.Name);
                    string fileName = Path.GetFileName(theEntry.Name);

                    if (targetDirectory.Length > 0)
                    {
                        Directory.CreateDirectory(targetDirectory);
                    }

                    if (fileName != String.Empty)
                    {
                        using (FileStream streamWriter = File.Create(targetDirectory + fileName))
                        {
                            int size = 2048;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception("Error unzipping file \"" + sourcePath + "\"", ex);
        }
    }

Body:
Change your code    int size = 2048;  to int size = data.Length;. You won't take OutOfRange exception.

 using (FileStream streamWriter = File.Create(targetDirectory + fileName))
    {
       int size = data.Length;
       byte[] data = new byte[size];
       while (true)
       {
            size = s.Read(data, 0, data.Length);
            if (size > 0)
            {
                streamWriter.Write(data, 0, size);
            }
            else
            {
               break;
            }
       }
    }


问:
What is the benefit of define constant by closure in Swift 3
```<code>let a: UIView = {
    let a = UIView()
    a.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
    return a
}()
</code>```

I saw a lot of people's Swift source code defining let as this way. I just curious what is the benefit of this way?

答:
In this case, there is no benefit, but if the variable in question were a value type then the benefit would be that you could perform some mutating setup code and still get a constant out of it.

It also lets you hide temporary variables that were only needed to initialize the constant, since they'll only exist inside the closure's scope.

Body:
let a: UIView = {
    let a = UIView()
    a.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
    return a
}()

I saw a lot of people's Swift source code defining let as this way. I just curious what is the benefit of this way?


问:
VueJS 2 typeahead callback method
I'm using the Typeahead component from vue-strap,

Am trying to make a callback after i hit on the selection which will stamp the data into my input texts.

Once i hit enter, inventoryName and inventoryId is successfully stamped in but the inventoryCode component is reset.

How to prevent it from reset or did i do anything wrong? As i can see from console.log it has the value.

```<code><typeahead v-model="inventoryCode" placeholder="Inventory code..." async="{{url('api/inventory')}}/" :template="inventorySearch" :on-hit="inventoryCallBack"></typeahead>
<input type="text" name="inventory_name" id="inventory_name" class="form-control" v-model="inventoryName" readonly />

new Vue({
        el: '#app',
        components:{Typeahead},
        data: {
            'inventoryCode': '',
            'inventoryName': '',
            'inventoryId': '',
            'inventorySearch': '<div style="min-width:150px;"><b>@{{item.inventory_name}}</b></div><div>@{{item.inventory_code}}</div><div>@{{item.inventory_short_desc}}</div>'
        },
methods:{
    inventoryCallBack: function(item){
                    console.log(item.inventory_code);
                    this.inventoryCode = item.inventory_code;
                    this.inventoryName = item.inventory_name;
                    this.inventoryId = item.id;
                    console.log(this.inventoryCode);
                },
}
});
</code>```

答:
```<code>inventoryCallBack: function(item){
                    console.log(item.inventory_code);
                    this.inventoryCode = item.inventory_code;
                    this.inventoryName = item.inventory_name;
                    this.inventoryId = item.id;
                    return item.inventory_code
                },
</code>```

This should do the trick, missed out this part.

Title: VueJS 2 typeahead callback method

Body:
I'm using the Typeahead component from vue-strap,

Am trying to make a callback after i hit on the selection which will stamp the data into my input texts.

Once i hit enter, inventoryName and inventoryId is successfully stamped in but the inventoryCode component is reset.

How to prevent it from reset or did i do anything wrong? As i can see from console.log it has the value.

<typeahead v-model="inventoryCode" placeholder="Inventory code..." async="{{url('api/inventory')}}/" :template="inventorySearch" :on-hit="inventoryCallBack"></typeahead>
<input type="text" name="inventory_name" id="inventory_name" class="form-control" v-model="inventoryName" readonly />

new Vue({
        el: '#app',
        components:{Typeahead},
        data: {
            'inventoryCode': '',
            'inventoryName': '',
            'inventoryId': '',
            'inventorySearch': '
@{{item.inventory_name}}

@{{item.inventory_code}}

@{{item.inventory_short_desc}}
'
        },
methods:{
    inventoryCallBack: function(item){
                    console.log(item.inventory_code);
                    this.inventoryCode = item.inventory_code;
                    this.inventoryName = item.inventory_name;
                    this.inventoryId = item.id;
                    console.log(this.inventoryCode);
                },
}
});

Body:
inventoryCallBack: function(item){
                    console.log(item.inventory_code);
                    this.inventoryCode = item.inventory_code;
                    this.inventoryName = item.inventory_name;
                    this.inventoryId = item.id;
                    return item.inventory_code
                },

This should do the trick, missed out this part.


问:
Vaadin Plupload uploads wrong filename
Anyone has come across this issue where the uploaded filename is looking a bit weird.

I am trying this Vaadin Plupload addon which is a very nice addon. However, it uploads the wrong file name.

```<code>  //add file uploaded handler
    uploader.addFileUploadedListener(new Plupload.FileUploadedListener() {

        @Override
        public void onFileUploaded(PluploadFile file) {
            File uploadedFile = file.getUploadedFile();
            System.out.println("This file was just uploaded: "
              + uploadedFile.getAbsolutePath());
        }
    });
</code>```

And it gives me this kind of file name o_199r9ll9e1g6q15vmrdj13l51rdbl.txt ...how do I get the normal.txt file name instead of such weird file name.

答:
Finally solved this issue, here is the discussion for this specific issue from Vaadin site:</p>

```<code>Path myPath = Paths.get(YOUR_UPLOAD_DIRECTORY + file.getId() + (FilenameUtils.getExtension(file.getName()).isEmpty()
                        ? "" : ('.' + FilenameUtils.getExtension(file.getName()))));
                Path rF = Paths.get(YOUR_UPLOAD_DIRECTORY + file.getName());
                try {
                    Files.move(myPath, rF, StandardCopyOption.REPLACE_EXISTING);
                    //refresh your tree table container
                } catch (IOException e) {
                    log.error("Unable to rename file" + file.getName(), e);
                }
</code>```

Title: Vaadin Plupload uploads wrong filename

Body:
Anyone has come across this issue where the uploaded filename is looking a bit weird.

I am trying this Vaadin Plupload addon which is a very nice addon. However, it uploads the wrong file name.

  //add file uploaded handler
    uploader.addFileUploadedListener(new Plupload.FileUploadedListener() {

        @Override
        public void onFileUploaded(PluploadFile file) {
            File uploadedFile = file.getUploadedFile();
            System.out.println("This file was just uploaded: "
              + uploadedFile.getAbsolutePath());
        }
    });

And it gives me this kind of file name o_199r9ll9e1g6q15vmrdj13l51rdbl.txt ...how do I get the normal.txt file name instead of such weird file name.

Body:
Finally solved this issue, here is the discussion for this specific issue from Vaadin site:

Path myPath = Paths.get(YOUR_UPLOAD_DIRECTORY + file.getId() + (FilenameUtils.getExtension(file.getName()).isEmpty()
                        ? "" : ('.' + FilenameUtils.getExtension(file.getName()))));
                Path rF = Paths.get(YOUR_UPLOAD_DIRECTORY + file.getName());
                try {
                    Files.move(myPath, rF, StandardCopyOption.REPLACE_EXISTING);
                    //refresh your tree table container
                } catch (IOException e) {
                    log.error("Unable to rename file" + file.getName(), e);
                }


问:
Escape sequence for bold text in Bixolon printer
What is correct syntax for creating Escape Sequences that work with Bixolon printers? I would like to see some samples for bold text that will work on SPP-R200III Bixolon printer. Thanks in advance.</p>

答: According to the Manual (page 35), the escape code to toggle bold text is ESC E (Hex 1B 45)


问:
How can a map be used to search the list of employe objects on the basis of different parameters?
I was asked this question in an interview today to which I explained the best to my abilities. But I still don't understand if this is the correct answer.

There is a cache which has Employee object as the key. The cache is populated with data from the database. Now there is a UI where we can enter either or all of the 3 attributes from the Employee object- name, ID and date of joining. Now this search would lead to multiple matching results.  To achieve this we need to check in the cache for the data.

To this I replied saying that my map would be of the structure - >. for the same EmployeeDetails object ,
 I will have multiple keys in the map(EmployeeDetails class is the object which contains complete detail of the Employee including address etc. Employee object just has 3 attributes - name, ID and date of joining.).

One of the objects with only name populated. The other with ID populated and the third one with date of joining populated. And now with the combination of attributes. So the map will be having the following keys -
Employee object with only the name populated -> Value would be list of of all the Employee objects with the same name.
Employee object with only the ID populated ->  Value would be list of of all the Employee objects with the same ID. Ideally the list size in this case should be 1.
Employee objects with only the Date Of Joining -> List of all the employee objects with the same date of joining.

Similarly there would be number of other Employee objects. For one such employee , all the three attributes - name , ID and date of joining would be populated.

In this way, I could have achieved the requirement to display all the employee results in case only some of the attributes out of name, ID and value is set on the UI.

I just want to understand if this is the correct way to achieve the outcome (display of list of matching results on the UI). Since I did not get selected, I believe there is something else which I possibly missed!

答:
One of the neat things about Java 8 is the Streams API.  With this new API, you an hold all of those Employee objects within just a normal List and walk away with the same results you were trying to achieve with multiple mapping objects with less overhead.

See, this API has a .filter() method that you can pass over a List that has been transformed into a Stream to only return objects that meet the criteria described in the body of the filter.

```<code>List<Employee> emps = getEmps();

List<Employee> matchedEmps = emps.stream().filter((e)->e.getID().equals(searchedID)).filter((e)->e.getName().equals(searchedName)).collect(Collectors.toList());
</code>```

As you can see you can chain filters to match multiple criteria, although it may be more efficient just to have all matching done in one filter:

```<code>ist<Employee> matchedEmps = emps.stream().filter((e)->{boolean matches = e.getID().equals(searchedID);return matches && e.getName().equals(searchedName);}).collect(Collectors.toList());
</code>```

Body:
One of the neat things about Java 8 is the Streams API.  With this new API, you an hold all of those Employee objects within just a normal List and walk away with the same results you were trying to achieve with multiple mapping objects with less overhead.

See, this API has a .filter() method that you can pass over a List that has been transformed into a Stream to only return objects that meet the criteria described in the body of the filter.

List<Employee> emps = getEmps();

List<Employee> matchedEmps = emps.stream().filter((e)->e.getID().equals(searchedID)).filter((e)->e.getName().equals(searchedName)).collect(Collectors.toList());

As you can see you can chain filters to match multiple criteria, although it may be more efficient just to have all matching done in one filter:

ist<Employee> matchedEmps = emps.stream().filter((e)->{boolean matches = e.getID().equals(searchedID);return matches && e.getName().equals(searchedName);}).collect(Collectors.toList());


问:
Passing complex type as parameter of action method. MVC
I have a problem with passing data to action method. I created action link in my view in the way shown below:

```<code>@model ComplexModel

...

<a href=@Url.Action( "ComplexAction", "ComplexController", new { complex= @Model, str = "string" } )
class="ui-btn">!!!Change all</a>
</code>```

And action method with to get all passed parameters:

```<code>public ActionResult ComplexAction( ComplexModeloAufgabeViewModel complex, string str )
{
    return View();
}
</code>```

String is passed correctly, but complex model is allways null. What is happening here?

答:
You have to use a form in order for the model binder to work

```<code>@model SomeComplexViewModel

@using Html.BeginForm("Action", "Controller")
{
   // fields for every one of the complex type properties
   Html.TextBoxFor(m=>m.FirstProperty)

   <input type="submit" value="submit" />
}
</code>```

And then in the action method you will receive your model

Body:
I have a problem with passing data to action method. I created action link in my view in the way shown below:

@model ComplexModel

...

!!!Change all

And action method with to get all passed parameters:

public ActionResult ComplexAction( ComplexModeloAufgabeViewModel complex, string str )
{
    return View();
}

String is passed correctly, but complex model is allways null. What is happening here?

Body:
You have to use a form in order for the model binder to work

@model SomeComplexViewModel

@using Html.BeginForm("Action", "Controller")
{
   // fields for every one of the complex type properties
   Html.TextBoxFor(m=>m.FirstProperty)

   <input type="submit" value="submit" />
}

And then in the action method you will receive your model


问:
How to print a value with the same criteria - JavaScript
I am trying to print numbers that are divisible by 3 and 5.
For numbers divisible by 3, print out "Fizz".
For numbers divisible by 5, print out "Buzz".
For numbers divisible by both 3 and 5, print out "FizzBuzz" in
the console. Otherwise, just print out the number.

Tried these codes:

```<code>var i;

for(i = 1; i <= 20; i++){
  if(i % 3 === 0){
     console.log("Fizz");
  }else if(i % 5 === 0){
     console.log("Buzz");
 }else if(i % 3 === 0 && i % 5 === 0){
      console.log("FizzBuzz");
  }else {
   console.log(i);
}
}
</code>```

But it seems it passing out the 3rd else if...
Is there a better way to do this?

答:
```<code>var i;

for (i = 1; i <= 20; i++) {
    if (i % 3 === 0 && i % 5 === 0) {
        document.write("FizzBuzz");
    } else if (i % 3 === 0) {
        document.write("Fizz");
    } else if (i % 5 === 0) {
        document.write("Buzz");
    } else {
       document.write(i);
    }
}
</code>```

Body:
I am trying to print numbers that are divisible by 3 and 5.
For numbers divisible by 3, print out "Fizz".
For numbers divisible by 5, print out "Buzz".
For numbers divisible by both 3 and 5, print out "FizzBuzz" in
the console. Otherwise, just print out the number.

Tried these codes:

var i;

for(i = 1; i <= 20; i++){
  if(i % 3 === 0){
     console.log("Fizz");
  }else if(i % 5 === 0){
     console.log("Buzz");
 }else if(i % 3 === 0 && i % 5 === 0){
      console.log("FizzBuzz");
  }else {
   console.log(i);
}
}

But it seems it passing out the 3rd else if...
Is there a better way to do this?