Categories
discuss

Access variable from function

I have a function that has a values inserted into variables in another function.

Initialise:

When the window resizes, it fires the resizeImage() function.

$(window).resize(function () {
    resizeImage();
});

Resize Function:

This function checks every element with the image-resize class and add readjust the SRC for the image by changing the width value (dynamic from scene7).

The problem is that element.attr(‘src’, newSrc); newSrc doesn’t exist as its stored in sizingMethod().

Is there anyway of grabbing the variable from sizingMethod() function and placing it within the element.attr(‘src’, newSrc);.

function resizeImage() {
    $('.image-resize').each(function () {

        var element = $(this), src = $(this).attr('src'), regx = /wid=d+(.d)*/g, currentWidth, newWidth, newSrc;

        var attrElement = $(this), attrSrc = $(this).attr('data-zoom-image'), attrRegex = /wid=d+(.d)*/g, attrCurrentWidth, attrNewWidth, attrNewSrc;

        if ($(window).width() > 1824) {
            sizingMethod(src, regx, currentWidth, newWidth, newSrc, '2000');
        } else if ($(window).width() <= 1824 && $(window).width() > 1366) {
            sizingMethod(src, regx, currentWidth, newWidth, newSrc, '1824');
        }

        element.attr('src', newSrc);
    });
};

Sizing Function:

function sizingMethod(sSrc, sRegex, sCurrentW, sNewW, sNewSrc, sNewWidth){
    sCurrentW = sSrc.match(sRegex);
    sNewW = 'wid=' + sNewWidth;
    sNewSrc = sSrc.replace(sCurrentW, sNewW);
    textWidth = sNewW.replace('wid=', '');
    $(".dsply-screen-size").text($(window).width());
    $(".dsply-image-size").text(textWidth);
}

Answer

When you use a primitive, what you send is the value not the reference, so the sNewSrc != newSrc, so any changes you do to sNewSrc that variable will not change newSrc.

You can fix your code using:


return: returning the value in the function sizingMethod:

if ($(window).width() > 1824) {
    newSrc = sizingMethod(src, regx, currentWidth, newWidth, '2000');
} else if ($(window).width() <= 1824 && $(window).width() > 1366) {
    newSrc = sizingMethod(src, regx, currentWidth, newWidth, '1824');
}

Sizing Function:

function sizingMethod(sSrc, sRegex, sCurrentW, sNewW, sNewWidth){
    sCurrentW = sSrc.match(sRegex);
    sNewW = 'wid=' + sNewWidth;
    var sNewSrc = sSrc.replace(sCurrentW, sNewW);
    textWidth = sNewW.replace('wid=', '');
    $(".dsply-screen-size").text($(window).width());
    $(".dsply-image-size").text(textWidth);
    return sNewSrc;
}

closure: if declare sizingMethod inside the anonymous function you have access to the variable newSrc and other variables as well.

function resizeImage() {
    $('.image-resize').each(function () {

        var element = $(this), src = $(this).attr('src'), regx = /wid=d+(.d)*/g, currentWidth, newWidth, newSrc;

        var attrElement = $(this), attrSrc = $(this).attr('data-zoom-image'), attrRegex = /wid=d+(.d)*/g, attrCurrentWidth, attrNewWidth, attrNewSrc;

        if ($(window).width() > 1824) {
            sizingMethod('2000');
        } else if ($(window).width() <= 1824 && $(window).width() > 1366) {
            sizingMethod('1824');
        }

        element.attr('src', newSrc);

        function sizingMethod(sNewWidth){
            currentWidth = src.match(regx);
            var sNewW = 'wid=' + sNewWidth;
            newSrc = sSrc.replace(currentWidth, sNewW);
            textWidth = sNewW.replace('wid=', '');
            $(".dsply-screen-size").text($(window).width());
            $(".dsply-image-size").text(textWidth);
        }
    });
};

object: if you use an object/array instead of a primitive as an argument

function resizeImage() {
    $('.image-resize').each(function () {

        var element = $(this), src = $(this).attr('src'), regx = /wid=d+(.d)*/g, currentWidth, newWidth, newSrc = {};

        var attrElement = $(this), attrSrc = $(this).attr('data-zoom-image'), attrRegex = /wid=d+(.d)*/g, attrCurrentWidth, attrNewWidth, attrNewSrc;

        if ($(window).width() > 1824) {
            sizingMethod(src, regx, currentWidth, newWidth, newSrc, '2000');
        } else if ($(window).width() <= 1824 && $(window).width() > 1366) {
            sizingMethod(src, regx, currentWidth, newWidth, newSrc, '1824');
        }

        element.attr('src', newSrc.src);
    });
};

Sizing Function:

function sizingMethod(sSrc, sRegex, sCurrentW, sNewW, sNewSrc, sNewWidth){
    sCurrentW = sSrc.match(sRegex);
    sNewW = 'wid=' + sNewWidth;
    sNewSrc.src = sSrc.replace(sCurrentW, sNewW);
    textWidth = sNewW.replace('wid=', '');
    $(".dsply-screen-size").text($(window).width());
    $(".dsply-image-size").text(textWidth);
}
Categories
discuss

Webview keeps losing focus

I have an app that is basically just a wrapper for an internal company website. The idea is to easily load the website in its own window on my Chromebook, that way it won’t unload when RAM gets low.

I have a very simple app with a single WebView that consumes an entire app window. The problem is, whenever I switch away from the window and come back, the webview has lost focus. This is particularly annoying because it’s a chat app, and I’d like to start talking immediately upon alt-tabbing back to the window.

I’ve looked into focusing the webview each time the window receives focus, but the disconnect between Window (from chrome.windows) and AppWindow (from chrome.app.window) makes this nontrivial. The event that I need only exists for Window objects, but I can only definitively obtain the current AppWindow. I could theoretically get the currently active Window when the app first launches, but that seems hackish and unreliable.

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Chat App</title>
    <link rel="stylesheet" href="styles.css">
  </head>

  <body>
    <webview src="https://example.com/" id="chat"></webview>
  </body>
</html>

background.js

chrome.app.runtime.onLaunched.addListener(function(launchData) {
  chrome.app.window.create(
    'index.html',
    {
      id: 'chat'
    }
  );
});

styles.css

Making the webview consume the entire window was a bit tricky; I had to use some redundant CSS properties to get it to work properly.

html, body {
  margin: 0;
  padding: 0;
  overflow: hidden;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
}

#chat {
  border: 0 none;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
}

Answer

You can achieve this simply with the Page Visibility API. You can use it to add an event listener and check the document.hidden state to return focus to the chat box. You can also do other things, like play an audio alert when you receive chat messages when the tab is not visible.

In this example, I’ve also added an event listener to the first chat box so if focus is lost, it tries to get it again. This is a rather heavy-handed approach, but you can adjust your logic to suit requirements.

JSFiddle

function handleVisibilityChange() {
    console.log(document.hidden);
    if (!document.hidden) {
        chatFocus();
    }
}

function chatFocus() {
    document.getElementById("ChatBox1").focus();
}

document.addEventListener("visibilitychange", handleVisibilityChange, false);
document.getElementById("ChatBox1").addEventListener("blur", chatFocus, true);
<input type="text" id="ChatBox1" placeholder="ChatBox1">
<input type="text" id="ChatBox2" placeholder="ChatBox2">

Testing this on Chrome, you’ll find that if you switch to another tab, or minimize the window, the visibilitychange event will be fired. If you just switch to another window, though, it won’t consider the page to be hidden. You can also make use of window.onblur to listen for when the page loses focus in general.

PS. About your ‘tricky’ redundant CSS: specifying left: 0 and width: 100% should be all you need (right: 0 shouldn’t be necessary), but in addition to that, text fields tend to have border and padding etc. so in order to ensure the field doesn’t end up wider than its container, you need to set box-sizing: border-box so that padding and borders are included when determining its size. It’s a trick that solves many problems in CSS.

Categories
discuss

Eclipse error JVM terminated. Exit code=1 /usr/Java70/jre/bin/java

I get a error like

JVM terminated. Exit code=1
/usr/Java70/jre/bin/java
-Dosgi.requiredJavaVersion=1.7
-Xms512m
-Xmx1024m

My java version is:

java version "1.7.0"
Java(TM) SE Runtime Environment (build pxa6470sr9-20150417_01(SR9))
IBM J9 VM (build 2.6, JRE 1.7.0 Linux amd64-64 Compressed References 20150406_242981 (JIT enabled, AOT enabled)
J9VM - R26_Java726_SR9_20150406_1443_B242981
JIT  - tr.r11_20150401_88894
GC   - R26_Java726_SR9_20150406_1443_B242981_CMPRSS
J9CL - 20150406_242981)
JCL - 20150414_02 based on Oracle 7u79-b14

My eclipse.ini:

-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20140116-2212
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.7
-Xms512m
-Xmx512m

Linux version:

LSB_VERSION=base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-noarch:printing-4.0-amd64:printing-4.0-noarch
Red Hat Enterprise Linux Server release 6.6 (Santiago)

Why am I get that error and how can I solve it?

Ran java -jar plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar

java: cairo-misc.c:380: _cairo_operator_bounded_by_source: Assertion `NOT_REACHED' failed.
JVMDUMP039I Processing dump event "abort", detail "" at 2015/06/30 21:51:32 - please wait.
JVMDUMP032I JVM requested System dump using '/root/Desktop/core.20150630.215132.10911.0001.dmp' in response to an event
JVMPORT030W /proc/sys/kernel/core_pattern setting "|/usr/libexec/abrt-hook-ccpp %s %c %p %u %g %t e" specifies that the core dump is to be piped to an external program.  Attempting to rename either core or core.11074.

JVMDUMP010I System dump written to /root/Desktop/core.20150630.215132.10911.0001.dmp
JVMDUMP032I JVM requested Java dump using '/root/Desktop/javacore.20150630.215132.10911.0002.txt' in response to an event
JVMDUMP010I Java dump written to /root/Desktop/javacore.20150630.215132.10911.0002.txt
JVMDUMP032I JVM requested Snap dump using '/root/Desktop/Snap.20150630.215132.10911.0003.trc' in response to an event
JVMDUMP010I Snap dump written to /root/Desktop/Snap.20150630.215132.10911.0003.trc
JVMDUMP013I Processed dump event "abort", detail "".

Answer

The problem was that whenever navigating to any workitem on RTC, that error occurred and eclipse crashed. Basically the UI did not appear or half appeared. This was solved by adding the following to the last line in eclipse.ini:

-Dorg.eclipse.swt.internal.gtk.cairoGraphics=false
Categories
discuss

Android how to get response string from Callback using OkHttp?

This is my code:

    OkHttpClient okHttpClient = new OkHttpClient();

    Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build();

    Callback callback = new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {

        }

        @Override
        public void onResponse(Response response) throws IOException {

        }
    };

    okHttpClient.newCall(request).enqueue(callback);

    String responseString;

In the above code, I want to store the value of response.body().string() from the onResponse() method in the variable responseString, however I can’t access it.

Answer

I think what you want to do is something like this:

public class MyActivity extends Activity implements Callback , View.OnClickListener {


 @Override
 public void onCreate(Bundle savedState) {
   super.onCreate(savedState);
   findViewById(R.id.DoHttp).setOnClickListener(this);
 } 

 @Override
 public void onClick(View v) {
   if (v.getId(() == R.id.DoHttp) {

     OkHttpClient okHttpClient = new OkHttpClient();

     Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build();
     okHttpClient.newCall(request).enqueue(this);
   }
 }


 @Override
 public void onFailure(Request request, IOException e) {
  //do something to indicate error
 }

  @Override
  public void onResponse(Response response) throws IOException {
    if (response.isSuccessful()) {
     parse(response.body().string());
    }
  }

  private void parse(String response) {
   //do something with response
  } 
}

In the above activity we implement Callback and then when we create the okhttp request, we pass it an instance of ourself (this) and that way we can get oktthp to call back the class, we could have done an inner class just as easily but this reduces the # of classes we have to make. I used a button click to illustrate when the Http call is made but that could be some other time, for instance it could happen when the screen is first created (in onCreate). Be careful though of screen rotations. Also this assumes that the callback is done on the main thread which I think it would be but I’m not positive as I use okttp in a different way than you. If it does not return the results on the response on the main thread then you can call runOnUiThread() and pass it a Runnable that does the work of updating the views.

Categories
discuss

Why can’t I create an array of an inner class of a generic type?

The following code gives a “generic array creation” error.

public class TestClass<K, V> {
    Entry[] entry;

    private TestClass() {
        entry = new Entry[10]; // <--- this line gives generic array creation error
    }

    private class Entry {
        public Entry() {

        }
    }
}

I’m wondering why this is, because class Entry is not a generic class and has no objects of generic type.

Is it because the inner class still has access to the generic types, even if it doesn’t use any? That’s the best I can come up with, though if it were the case, I don’t understand why Java couldn’t look and see it makes no use of generic types and is therefore not a generic class?

And yes, I have seen many many threads about generic type arrays, but no, I have not found a single one regarding inner classes.

Answer

The type is actually TestClass<K, V>.Entry (yes it’s because it’s an inner class). You can solve this by transforming it into a nested static class:

private static class Entry {
    public Entry() {

    }
}
Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..