I need a Regex expression that will stop anything that is not 3 (or more) letter word?

In my code I want anything that isn’t a three (or more) letter word to go into the while loop and anything else to continue into the code. I am not that confident with Regex and would like help on how to fix it.

    while (!(word.matches("(a-z){3,}")))
    {
        System.out.println("You have not entered in a valid word (it has to be at least 3 letters long).");

        System.out.println();

        System.out.print("Please enter a word of your choice: ");
        word = keyboard.nextLine();

    }

N.B. This is for homework

Change integer value from another Activity

I want change a value from another activity like this

Main_activity.java

...
long notify_interval = 1000; //ms
...

But, In another activity, called system.java, I have this code

btn_normal.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Main_activity.notify_interval = 1000; // HERE <<--
            Toast.makeText(getApplicationContext(), "Interval changed!", Toast.LENGTH_SHORT).show();
        }
    });

But isn’t working, someone tells me that this way never will work. So, what should I do?

Thanks!

Convert a 1-dimensional array to a two-dimensional array with the powers of the number in the array paired together

The below picture demonstrates what I wish to accomplish:

enter image description here

Here is my code:

public static int[][] square(int[] array) {
    int arraySquare[][] = new int[array.length][2];

    try {
        for (int i = 0; i < array.length; i++) {
            arraySquare[i][0] = array[i];
            arraySquare[i][1] = (int) Math.pow(array[i], 2);

        }
    } catch (ArrayIndexOutOfBoundsException ex) {
    }

    return arraySquare;

}

Where does it go wrong?

Edit:

The following @Test case is given:

 private final int[] array1 = {1, 2, 3};
  private final int[] array7 = {1, 4, 9};

  @Test
  public void testSquare1() {
    int[][] r = Arrays.square(array1);
    assertEquals(2, r.length);
    assertArrayEquals(array1, r[0]);
    assertArrayEquals(array7, r[1]);
  }

how to extract an object from the camera preview android opencv

I am trying to scan a MTG card using OpenCV on android. I have it to where I can detect the edges of the card and even draw an outline around it but am confused on how to extract just the card from the background and then exit from the camera preview. Here is my code so far:

public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
    Mat result = new Mat();
    Mat mask = new Mat();
    List<MatOfPoint> contours = new ArrayList<>();
    Mat hierarchy = new Mat();
    mRgba = inputFrame.rgba();
    Imgproc.Canny(mRgba, result, 40, 120);
    Imgproc.GaussianBlur(result, result, new Size(9,9), 2, 2);
    Imgproc.findContours(result, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE, new Point(0,0));
    Imgproc.drawContours(mask, contours, -1, new Scalar(0, 255, 0), 1);
    hierarchy.release();

    for ( int contourIdx=0; contourIdx < contours.size(); contourIdx++ )
    {
        // Minimum size allowed for consideration
        MatOfPoint2f approxCurve = new MatOfPoint2f();
        MatOfPoint2f contour2f = new MatOfPoint2f( contours.get(contourIdx).toArray() );
        //Processing on mMOP2f1 which is in type MatOfPoint2f
        double approxDistance = Imgproc.arcLength(contour2f, true)*0.02;
        Imgproc.approxPolyDP(contour2f, approxCurve, approxDistance, true);

        //Convert back to MatOfPoint
        MatOfPoint points = new MatOfPoint( approxCurve.toArray() );

        // Get bounding rect of contour
        Rect rect = Imgproc.boundingRect(points);

        Imgproc.rectangle(mRgba, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(255, 0, 0, 255), 3);
    }
    Bitmap card = Bitmap.createBitmap(result.cols(), result.rows(), Bitmap.Config.ARGB_8888);
    Utils.matToBitmap(result, card);
    return mRgba;
}

}

Here is an example of what it looks like when run the code. As you can see the card is outlined by a red rectangle now but how do I extract just whats in the rectangle, save it to a mat or bitmap and then exit the camera?
screenshot of outlined card

onResume not always call after exit with home button

I was wondering what may be the reason for this strange behavior.
From time to time (rarely) in my app when I exit it with the home button and then get back onResume is not called and for some strange reason the data I loaded in onCreate is gone. I have ListView with items and in the case when onResume is not called, the list is empty and no items are displayed and no matter how many times I exit with the home button and get back it stays empty, unless I press back or kill the app.

What may be the reason behind that. I read some articles that this might be caused by endless loop. But I have no idea how to test it and how to find the reason for this.

I will be glad to have some advice if someone has encountred that behavior or knows what the possible issue might be

JVM: How does Scala’s JavaConversions work inside Java code?

I understand that Scala’s JavaConversions adds implicit conversions between various Java and Scala collections. I understand how that works in Scala, with the implicit keyword.

However, in my case, I am running some Java code, and it has at the top:

import scala.collection.JavaConversions;

Now somehow, seemingly by magic, having that import at the top changes the code below when Java collections are used.

For instance, I have a method:

public static Collection<String> foo() { return ... }

and if I call that method from outside, the Collection instance I get back is … altered, somehow. It has extra methods added. Through some mechanism I don’t understand, that code — which does not involve Scala or JavaConversions at all — causes the class loader to bring in Scala classes.

How does it work?

The Java language itself does not have an implicit keyword or extension methods, but Scala does. Somehow, importing that Scala library is doing something low-level that (presumably) can’t be expressed in Java but is still supported by the JVM.

  • What happens when that import is encountered?
  • How does Scala add methods to existing Java classes?
  • What is the timing involved, here? Does something happen at import time, at class-load time, or something else?

Formatting and encoding a string to JSON

I have some Java code that has a String in the below format:

{username=username, password=password}

I want to convert it to JSON and pass it to a Http Post entity in an acceptable format. How do I do it?

Expected:

{
  "username": "username",
  "password": "password"
}  

Convert VB script into Java (handle security prompt)

I want to convert VB script into Java as I want to handle security prompt pop-up and wanted to provide credential from different source read the credential remotely and pass in the prompt.

Here is the below VB code I want to convert in Java Selenium webdriver:

Set oShell = CreateObject("WScript.Shell")
Set oRet = oShell.exec("powershell.exe Invoke-Command -ComputerName KP1DWABCQ111 -ScriptBlock{cd c:'Program Files (x86)'SecurityApplicationPasswordSdk;.CLIPasswordSDK.exe GetPassword /p AppDescs.AppID=APP_QA /p Query=""Safe=APP_QA;Folder=Root;Object=" & user & """ /o Password}")
pswd = Replace(Replace(oRet.StdOut.ReadLine(),chr(10),""),chr(13),"")
Set oRet = Nothing
Set oShell = Nothing

Error in running freetts text to speech in JavaFx

This is JavaFx code which i run phpStorm.

Code compile successfully.
But problem is vm.getVoice();
I add libraries correctly problem in libraries.

package sample;

import com.sun.speech.freetts.*;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.fxml.FXML;

public class Text_to_spech {
    @FXML
    Button btn;
    @FXML
    TextArea text;
    String voicename="kevin16";
    public void btn() {
        Voice voice;
        VoiceManager vm = VoiceManager.getInstance();
        voice=vm.getVoice(voicename);
        System.out.println(text.getText());
        voice.allocate();
        try {
           voice.speak(text.getText());
        } catch (Exception ex) {
              System.out.println("Error");
        }
    }
}

Error Which is showing in PhpStorm When i write text in text area:

                            "C:Program FilesJavajdk-9binjava" "-javaagent:C:Program 
                    FilesJetBrainsIntelliJ IDEA 2017.2.5libidea_rt.jar=57844:C:Program 
                    FilesJetBrainsIntelliJ IDEA 2017.2.5bin" -Dfile.encoding=UTF-8 -classpath 
                    C:UsersKrishnaOracleExpertoutproductionOracleExpert;C:UsersKrishna
                    Desktopspeechgtranslateapi-1.0.jar;C:UsersKrishnaDesktopspeech
                    jl1.0.jar;C:UsersKrishnaDesktopspeechfreetts-1.2.2libjsapi.jar;C:
                    UsersKrishnaDesktopspeechfreetts-1.2.2-binfreetts-1.2lib
                    cmu_time_awb.jar;C:UsersKrishnaDesktopspeechfreetts-1.2.2-binfreetts-
                    1.2libcmu_us_kal.jar;C:UsersKrishnaDesktopspeechfreetts-1.2.2-
                    binfreetts-1.2libfreetts-jsapi10.jar;C:UsersKrishnaDesktopspeech
                    freetts-1.2.2-binfreetts-1.2liben_us.jar;C:UsersKrishnaDesktopspeech
                    freetts-1.2.2-binfreetts-1.2libfreetts.jar;C:UsersKrishnaDesktop
                    speechfreetts-1.2.2-binfreetts-1.2libjsapi.jar;C:UsersKrishnaDesktop
                    speechfreetts-1.2.2-binfreetts-1.2libmbrola.jar;C:UsersKrishnaDesktop
                    speechfreetts-1.2.2-binfreetts-1.2binClient.jar;C:UsersKrishnaDesktop
                    speechfreetts-1.2.2-binfreetts-1.2binEmacspeakServer.jar;C:Users
                    KrishnaDesktopspeechfreetts-1.2.2-binfreetts-1.2bin
                    FreeTTSEmacspeakServer.jar;C:UsersKrishnaDesktopspeechfreetts-1.2.2-
                    binfreetts-1.2binFreeTTSHelloWorld.jar;C:UsersKrishnaDesktopspeech
                    freetts-1.2.2-binfreetts-1.2binHelloWorld.jar;C:UsersKrishnaDesktop
                    speechfreetts-1.2.2-binfreetts-1.2binJTime.jar;C:UsersKrishnaDesktop
                    speechfreetts-1.2.2-binfreetts-1.2binMixedVoices.jar;C:Users
            KrishnaDesktopspeechfreetts-1.2.2-binfreetts-1.2binPlayer.jar;C:Users
            KrishnaDesktopspeechfreetts-1.2.2-binfreetts-1.2binServer.jar;C:Users
            KrishnaDesktopspeechfreetts-1.2.2-binfreetts-1.2binWebStartClock.jar 
            sample.ABC
                            Exception in thread "JavaFX Application Thread" 
    java.lang.RuntimeException: java.lang.reflect.InvocationTargetException  

                atjavafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:178


                7)
                            at javafx.fxml/javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLo
                ader.java:1670)
                                at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent

                        (CompositeEventHandler.java:86)

                                at 
                javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent

                        (EventHandlerManager.java:238)
                                at 
                javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent

                        (EventHandlerManager.java:191)

                                at 
                javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubbling

                        Event(CompositeEventDispatcher.java:59)

                                at 
                javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEv

                        entDispatcher.java:58)
                                at 
                javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Event
                        DispatchChainImpl.java:114)
                                at 
                javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEv
                        entDispatcher.java:56)
                                at 
                javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Event
                        DispatchChainImpl.java:114)
                                at 
                javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEv
                        entDispatcher.java:56)
                                at 
                javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Event
                        DispatchChainImpl.java:114)
                                at 
                javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
                                at 
                javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
                                at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
                                at javafx.graphics/javafx.scene.Node.fireEvent(Node.java:8863)
                                at javafx.controls/javafx.scene.control.Button.fire(Button.java:200)
                                at javafx.controls/com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseRe
                        leased(ButtonBehavior.java:206)
                                at javafx.controls/com.sun.javafx.scene.control.inputmap.InputMap.handle(Input
                        Map.java:274)
                                at javafx.base/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRe
                        cord.handleBubblingEvent(CompositeEventHandler.java:218)
                                at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEve
                        nt(CompositeEventHandler.java:80)
                                at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(
                        EventHandlerManager.java:238)
                                at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(
                        EventHandlerManager.java:191)
                                at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingE
                        vent(CompositeEventDispatcher.java:59)
                                at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEv
                        entDispatcher.java:58)
                                at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Event
                        DispatchChainImpl.java:114)
                                at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEv
                        entDispatcher.java:56)
                                at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Event
                        DispatchChainImpl.java:114)
                                at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Basic
                        EventDispatcher.java:56)
                                at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Event
                        DispatchChainImpl.java:114)
                                at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
                                at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
                                at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
                                at javafx.graphics/javafx.scene.Scene$MouseHandler.process(Scene.java:3876)
                                at javafx.graphics/javafx.scene.Scene$MouseHandler.access$1300(Scene.java:3604)
                                at javafx.graphics/javafx.scene.Scene.processMouseEvent(Scene.java:1874)
                                at javafx.graphics/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2613)
                                at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEvent
                        Notification.run(GlassViewEventHandler.java:397)
                                at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEvent
                        Notification.run(GlassViewEventHandler.java:295)
                                at java.base/java.security.AccessController.doPrivileged(Native Method)
                                at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$
                        handleMouseEvent$2(GlassViewEventHandler.java:434)
                                at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRender
                        Lock(QuantumToolkit.java:389)
                                at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouse
                        Event(GlassViewEventHandler.java:433)
                                at javafx.graphics/com.sun.glass.ui.View.handleMouseEvent(View.java:556)
                                at javafx.graphics/com.sun.glass.ui.View.notifyMouse(View.java:942)
                                at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
                                at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApp
                        lication.java:189)
                                at java.base/java.lang.Thread.run(Thread.java:844)
                            Caused by: java.lang.reflect.InvocationTargetException
                                at
         java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native 

        Method)
                                at 
        java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethod

                        AccessorImpl.java:62)
                                at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Delegat

                        ingMethodAccessorImpl.java:43)
                                at java.base/java.lang.reflect.Method.invoke(Method.java:564)
                                at com.sun.javafx.reflect.Trampoline.invoke(MethodUtil.java:76)
                                at jdk.internal.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
                                at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Delega
                        tingMethodAccessorImpl.java:43)
                                at java.base/java.lang.reflect.Method.invoke(Method.java:564)
                                at javafx.base/com.sun.javafx.reflect.MethodUtil.invoke(MethodUtil.java:275)
                                at javafx.fxml/com.sun.javafx.fxml.MethodHelper.invoke(MethodHelper.java:83)
                                at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1784)
                                ... 47 more
                            Caused by: java.lang.ClassCastException: com.sun.speech.freetts.en.us.cmu_time_awb.AlanVoiceDirectory cannot be cast 
to com.sun.speech.freetts.VoiceDirectory

                                at 
com.sun.speech.freetts.VoiceManager.getVoices(VoiceManager.java:113)

                                at com.sun.speech.freetts.VoiceManager.getVoice(VoiceManager.java:502)
                                at sample.Text_to_spech.btn(Text_to_spech.java:17)
                                ... 58 more

                            Process finished with exit code 0

If any other api you know for text to speech in Java then please write its name?
I am currently using Intellij idea.

Disable Reoplening Activitiy Mulitple Times on Map Long Clicks

I am making an app that enables a user to long click on map, and open a new activity that would allow them to add a new tag and info about it. When user long clicks once, if he is fast enough he can long click on the map twice, and the second activity would open twice. I am trying to find a way to disable this behavior. I already tried some examples, and tried to add flags, but it had no effect.

I would like to disable user to long click twice. I would also like to maybe add a loader.

My maps fragment looks like this:

 //Add marker on long click
 mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {

     @Override
     public void onMapLongClick(final LatLng arg0) {

         RequestQueue queue = Volley.newRequestQueue(getActivity());
                    String url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + String.valueOf(arg0.latitude) + "," + String.valueOf(arg0.longitude) + "&key=myKey";

         // Request a string response from the provided URL.
         StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
             @Override
             public void onResponse(String response) {
                 try {
                     JSONArray jObj = new JSONObject(response).getJSONArray("results").getJSONObject(0).getJSONArray("address_components");

                     Intent intent = new Intent(getActivity(), AddRestaurantActivity.class);

                      for (int i = 0; i < jObj.length(); i++) {
                          String componentName = new JSONObject(jObj.getString(i)).getJSONArray("types").getString(0);
                          if (componentName.equals("postal_code") || componentName.equals("locality") || componentName.equals("street_number") || componentName.equals("route")
                                                    || componentName.equals("neighborhood") || componentName.equals("sublocality") || componentName.equals("administrative_area_level_2")
                                                    || componentName.equals("administrative_area_level_1") || componentName.equals("country")) {
                                                intent.putExtra(componentName, new JSONObject(jObj.getString(i)).getString("short_name"));
                           }
                      }

                       intent.putExtra("latitude", arg0.latitude);
                       intent.putExtra("longitude", arg0.longitude);

                       startActivity(intent);

                   } catch (JSONException e) {
              e.printStackTrace();
              }
          }
    }, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
        int x = 1;
    }
 });
 // Add the request to the RequestQueue.
 queue.add(stringRequest);

    }
});

And this is the activity it opened, with this and this answers tried (among others) to add a flag:

private void setRestaurant(final String userId, final String message, final String pickDate, final String pickTime, final String location, final String lat, final String lon, final String sendTo, final boolean enableComments) {
    // Tag used to cancel the request
    String tag_string_req = "req_add_restaurant";

    final String commentsEnabled = (enableComments) ? "0" : "1";

    pDialog.setMessage(getString(R.string.setting_a_restaurant));
    showDialog();

    ApiInterface apiService =
            ApiClient.getClient().create(ApiInterface.class);

    Call<DefaultResponse> call = apiService.addrestaurant(userId, message, lat, lon, pickDate, pickTime, sendTo, commentsEnabled);
    call.enqueue(new Callback<DefaultResponse>() {
        @Override
        public void onResponse(Call<DefaultResponse> call, retrofit2.Response<DefaultResponse> response) {

            // Launch main activity
            Intent intent = new Intent(SetRestaurantActivity.this,
                    MainActivity.class);
            // I TRIED TO BLOCK IT HERE
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            // I ALSO TRIED: 
            // intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
            finish();

            Toast.makeText(getApplicationContext(), R.string.sucessfully_created_restaurant, Toast.LENGTH_LONG).show();
        }
    });
}