text:
Q: Terraform and container declaration for GCP - how much does indentation matter? I have defined a VM in GCP, running a Memcached container. Now I am in the middle of importing all of the infrastructure into Terraform. There is one little problem that I am afraid of simply ignoring and that is the indentation of the generated YAML while running terraform plan.
To give a little context - the Memcached VM was launched using the GCP Launcher. I created a bare minimum resource in TF, imported it and now I'm backtracking and trying to add all missing data into the resource definition to fully comply with the actual deployment. One thing I can't get exactly right is the metadata, namely the container spec (gce-container-declaration).
I have followed the example on GitHub and created a module, where I defined everything to my best knowledge. However, when I run terraform plan, I get a tiny difference in indentation:
  ~ metadata             = {
      ~ "gce-container-declaration" = <<~EOT
          + ---
            spec:
              containers:
          -     - name: service-memcached
          -       image: launcher.gcr.io/google/memcached1
          -       stdin: false
          -       tty: false
          +   - image: launcher.gcr.io/google/memcached1
          +     name: service-memcached
          +     stdin: false
          +     tty: false
              restartPolicy: Always
          -
          - # This container declaration format is not public API and may change without notice. Please
          - # use gcloud command-line tool or Google Cloud Console to run Containers on Google Compute Engine.
          +   volumes: []
        EOT
        "google-logging-enabled"    = "true"
    }

Is the indentation difference negligible, or am I missing something in the definition?
Module definition:
module "gce-container" {
  source = "github.com/terraform-google-modules/terraform-google-container-vm"

  container = {
    name = "service-memcached"
    image = "launcher.gcr.io/google/memcached1"
    stdin = false
    tty = false
  }

  restart_policy = "Always"
}

A: After consulting with the module creators and performing tests, it is safe to say that the YAML structure is flexible and therefore nothing breaks when such transition is performed.


text:
Q: Splitting Routes into multiple files I'm new to Kotlin and Ktor the below is working fine with me as startup, now I need to add more Routes how can I split the routes in multiple files?
package blog

import org.jetbrains.ktor.netty.*
import org.jetbrains.ktor.routing.*
import org.jetbrains.ktor.application.*
import org.jetbrains.ktor.features.*
import org.jetbrains.ktor.host.*
import org.jetbrains.ktor.http.*
import org.jetbrains.ktor.response.*
import org.jetbrains.ktor.request.*     // for recieve
import org.jetbrains.ktor.util.*       // for ValuesMap

import org.apache.commons.mail.*

fun Application.module() {
    install(DefaultHeaders)
    install(CallLogging)
    install(Routing) {
        get("/") {
            call.respondText("""
            My Example Blog2
                <form action="/contact-us" method="post">
                    <input name="subject" placeholder="Subject">

                    <textarea name="message" placeholder="Your message ..."></textarea>

                    <button>Submit</button>
                </form>
            """, ContentType.Text.Html)
        }
        post("/contact-us") {
            val post = call.receive<ValuesMap>()
            SimpleEmail().apply {
                setHostName("smtp.gmail.com")
                setSmtpPort(465)
                setAuthenticator(DefaultAuthenticator("my_alias@gmail.com", "my_gmil_passoword"))
                setSSLOnConnect(true)
                setFrom("my_alias@gmail.com")
                setSubject(post["subject"])
                setMsg(post["message"])
                addTo("my_alias@gmail.com")
            }.send() // will throw email-exception if something is wrong
            call.respondRedirect("/contact-us/success")
        }
        get("/contact-us/success") {
            call.respondText("Your message was sent", ContentType.Text.Html)
        }
    }
}

fun main(args: Array<String>) {
    embeddedServer(Netty, 8080, watchPaths = listOf("BlogAppKt"), module = Application::module).start()
}

A: Finally I figured it out:
Install routing for the functions name you need, like:
install(Routing) {
        contact()
}

Create a function like fun Route.contact(){ ..} to handle the requisites, so for my example, I created the below:
fun Route.contact(){
        get("/") {
            call.respondText("""
            My Example Blog 12
                <form action="/contact-us" method="post">
                    <input name="subject" placeholder="Subject">

                    <textarea name="message" placeholder="Your message ..."></textarea>

                    <button>Submit</button>
                </form>
            """, ContentType.Text.Html)
        }
        post("/contact-us") {
            val post = call.receive<ValuesMap>() // val userId = registration["userId"]
            SimpleEmail().apply {
                setHostName("smtp.gmail.com")
                setSmtpPort(465)
                setAuthenticator(DefaultAuthenticator("my_alias@gmail.com", "my_gmil_passoword"))
                setSSLOnConnect(true)
                setFrom("my_alias@gmail.com")
                setSubject(post["subject"])
                setMsg(post["message"])
                addTo("my_alias@gmail.com")
            }.send() // will throw email-exception if something is wrong
            call.respondRedirect("/contact-us/success")
        }
        get"/contact-us/success") {
            call.respondText("Your message was sent", ContentType.Text.Html)
        }
}

A: you can create 2 file, example:
Principal.kt
package blog

import org.jetbrains.ktor.netty.*
import org.jetbrains.ktor.routing.*
import org.jetbrains.ktor.application.*
import org.jetbrains.ktor.features.*
import org.jetbrains.ktor.host.*
import org.jetbrains.ktor.http.*
import org.jetbrains.ktor.response.*
import org.jetbrains.ktor.request.*     // for recieve
import org.jetbrains.ktor.util.*       // for ValuesMap

import org.apache.commons.mail.*

fun Application.module() {
    install(DefaultHeaders)
    install(CallLogging)
    routing{
        get("/") {
            call.respondText("""
            My Example Blog2
                <form action="/contact-us" method="post">
                    <input name="subject" placeholder="Subject">

                    <textarea name="message" placeholder="Your message ..."></textarea>

                    <button>Submit</button>
                </form>
            """, ContentType.Text.Html)
        }
}

And Contact.kt
package blog

import org.jetbrains.ktor.netty.*
import org.jetbrains.ktor.routing.*
import org.jetbrains.ktor.application.*
import org.jetbrains.ktor.features.*
import org.jetbrains.ktor.host.*
import org.jetbrains.ktor.http.*
import org.jetbrains.ktor.response.*
import org.jetbrains.ktor.request.*     // for recieve
import org.jetbrains.ktor.util.*       // for ValuesMap

import org.apache.commons.mail.*

fun Application.moduleContact() {
    routing{
        post("/contact-us") {
            val post = call.receive<ValuesMap>()
            SimpleEmail().apply {
                setHostName("smtp.gmail.com")
                setSmtpPort(465)
                setAuthenticator(DefaultAuthenticator("my_alias@gmail.com", "my_gmil_passoword"))
                setSSLOnConnect(true)
                setFrom("my_alias@gmail.com")
                setSubject(post["subject"])
                setMsg(post["message"])
                addTo("my_alias@gmail.com")
            }.send() // will throw email-exception if something is wrong
            call.respondRedirect("/contact-us/success")
        }
        get("/contact-us/success") {
            call.respondText("Your message was sent", ContentType.Text.Html)
        }
    }
}

And modify application.conf
ktor {
    deployment {
        port = 8080
        port = ${?PORT}
    }
    application {
        modules = [ com.ejemplo.blog.PrincipalKt.module,
                    com.ejemplo.blog.ContactKt.moduleContact
        ]
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to pass inputs to java using eclipse? I am trying to get the user input using the following code but on running it gives the error that Arrayindexoutofbounds.
Don't know what is the problem.
public static void main(String[] args) {
    int T = Integer.parseInt(args[1]);
    PercolationStats stats = new PercolationStats(
            Integer.parseInt(args[0]), T);
    double mean = stats.mean();
    StdOut.println("mean = " + mean);
    double stddev = stats.stddev();
    StdOut.println("stddev = " + stddev);
    double d = (1.96 * stddev) / Math.sqrt(T);
    StdOut.println("95% confidence interval = " + (mean - d) + ", "
            + (mean + d));
}

A: To pass arguments to a Java program via Eclipse, you should use the Arguments tab in Run > Run Configurations. Example:
Arguments

Code
public static void main(String[] args) {
    System.out.println(args[0]);
    System.out.println(args[1]);
    System.out.println(args[2]);
}

Result
33
twitter
400.23

A: you can pass your input parameters in following way in Eclipse:
click menu Run -> Run Configurations -> Arguments
in Program arguments put your arguments, which will be loaded to "String [] args"
you could just separate your arguments by space:
e.g.
1 2 3
and your args = {1,2,3}


text:
Q: How to list all uploaded videos (URL) of a YouTube channel with API v3? This article shows how to get all uploaded videos from a particular channel in version 2, but I couldn't figure out how to do it with version 3.
Is it possible? Most of the version 3 articles just talk about searching.

A: Here, you will find all Data API v3 references.
It takes few steps;
1) You list the specific channel that upload is done.
2) You resolve uploads playlist.
3) You can iterate inside this playlist through playlist items for each video.
Here's an Java example. You can find other language examples inside this project as well.


text:
Q: Increment a value regarding a pattern in a file I have a file like this :
"A";"1"
"A";""
"A";""
"B";"1"
"C";"1"
"C";""
"C";""

When I have the same pattern between first part of current line and previous line, I want increment the second part of my line.
like this :
"A";"1"
"A";"2"
"A";"3"
"B";"1"
"C";"1"
"C";"2"
"C";"3"

or if second part is empty I take the previous line and I increment it.
Do you have any idea how I can do this with a shell script or maybe with awk or sed command?

A: With perl:
$ perl -F';' -lane 'if ($F[1] =~ /"(\d+)"/) { $saved = $1; } else { $saved++; $F[1] = qq/"$saved"/; }
   print join(";", @F)' example.txt
"A";"1"
"A";"2"
"A";"3"
"B";"1"
"C";"1"
"C";"2"
"C";"3"

With awk:
$ awk -F';' -v OFS=';' '
   $2 ~ /"[0-9]+"/ { saved = substr($2, 2, length($2) - 2) }
   $2 == "\"\"" { $2 = "\"" ++saved "\"" }
   { print }' example.txt
"A";"1"
"A";"2"
"A";"3"
"B";"1"
"C";"1"
"C";"2"
"C";"3"


text:
Q: Import stand alone Rmd (own repo and project) as a post in blogdown? Most of my analysis is done using the "1 project = 1 repository" approach. In each of these repository, there is a single R project and often a single Rmd file generating a html_document where all the analysis lives.
Some of these analysis would make good blog post, and I'd like the blog post to be updated if I ever update the analysis.
Is there a way to create a blog post from this analysis without re-doing all of it inside the blog's project and repo?
I tried cloning the "analysis repo" into blogdown's /content folder, but all I ended up was the year "0001" on my blog's home page.

A: It is not impossible, but it can be very tricky, and I don't recommend you to do it. Instead, put the .html (and associated dependencies, if any) output file under the static/ directory of your blogdown website (see Section 2.7 of the blogdown book), write a short post under content/, and link to the .html file in the short post.
You can certainly automate this job (copying files from the original directory to static/) in the R script R/build.R (see Appendix D.9). I think it will be a lot easier if you could just put the .Rmd source documents under static/, so that you don't even need to copy files from one directory to another (again, see Section 2.7).


text:
Q: Windows RPC RpcEpResolveBinding failure  RpcEpResolveBinding call fails with 1753 error.
 1753. There are no more endpoints available from the endpoint mapper.

RpcStringBindingCompose
RpcBindingFromStringBinding
calls go through fine and the subsequent call to RpcEpResolveBinding fails.
Asking for suggestions on what all things I can check.


text:
Q: "Oops, something went wrong" error when authenticating w OAuth2 and Eventbrite using iOS / swift I am trying to authenticate w OAuth2 and Eventbrite using iOS / swift. Here is my relevant code snippet:
let oauthswift = OAuth2Swift(
        consumerKey:    Eventbrite["consumerKey"]!,
        consumerSecret: Eventbrite["consumerSecret"]!,
        authorizeUrl:   "https://www.eventbrite.com/oauth/authorize",
        accessTokenUrl: "https://www.eventbrite.com/oauth/token",
        responseType:   "code"
    )
    oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth2-swift://oauth-callback/eventbrite")!, scope: "", state: "",
        success: {
            credential, response, parameters in
            self.showAlertView("Eventbrite", message: "oauth_token:\(credential.oauth_token)")
        }, failure: {(error:NSError!) -> Void in
            println(error.localizedDescription)
    })

However when I go to the eventbrite oauth page after I accept that I want to connect this application with my account I see "Oops, something went wrong" error in eventbrite. The url is: https://www.eventbrite.com/oauth/authorize?client_id={MyClientId}&redirect_uri=oauth2-swift://oauth-callback/eventbrite&response_type=code
I have added the "oauth-swift" URL scheme to info.plist.
Here are my eventbrite App settings:
Application URL: http://mywebsite.com
OAuth Redirect Uri: oauth-swift://oauth-callback/eventbrite
How can I redirect the user to my app so I can retrieve the access token? The app delegate / openURL function is not called when I try to authenticate w Eventbrite (it gets called when I try w Foursquare and Instagram). Also, I tried OAuth2 with Foursquare and Instagram and it works fine.
Am I missing something specific to OAuth2 w eventbrite w.r.t my app settings, code etc.? Thanks

A: Couple of things to be cautious when working with OAuth in iOS:

*

*If you are planning to distribute your app in the App Store make sure you do not use Safari to authenticate. You have to do this within your app and the best place is using a WebView.

*Never store your App/Consumer Secret in your iOS App.

Now, how to implement OAuth authentication via WebView?

*

*If you are using storyboards drag a WebView in to a ViewController. Also create a class file for the ViewController and create an IBOutlet for the WebView.

*On the viewDidAppear function of the ViewController set the WebView to load your authorisation url.
authorisationURL = "https://www.eventbrite.com/oauth/authorize?client_id=YOUR_CLIENT_KEY&response_type=code&redirect_uri=REDIRECT_URI"

self.webView.loadRequest(NSURLRequest(URL: NSURL(string: authorisationURL)!))

*Add UIWebViewDelegate protocol to the ViewController and add function webViewDidFinishLoad(webView: UIWebView). This function will be called whenever the WebView finishes loading a page.

*Once the user provides access to your App, Eventbrite will redirect you to the redirect uri you provided with the code. e.g. https://localhost?code=xxxx. We can access the code by reading this URL.
if (webView.request?.URL?.absoluteString!.rangeOfString("code=") != nil) {
    let queryString = webView.request?.URL?.query
    println(queryString)
    let authenticationCode = queryString!.substringFromIndex(advance(codeContainer!.startIndex, 5))
    // we are advancing 5 characters in order to ignore "code="
}

Now that you have got your code, its time to use your backend to retrieve the access token. Do you have access to a web server? If yes, you just need to pass the code you obtained above to your backend and initiate a POST request from your backend. Eventbrite will respond you with an access token which you can either store in the backend (recommended) or in the client.
    method: 'POST',
    url: 'https://www.eventbrite.com/oauth/token',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: {
      'client_id' : '*******',
      'client_secret' : '********',
      'grant_type' : 'authorization_code',
      'code' : CODE_RECEIVED_FROM_ABOVE
    }

If you do not have access to a web server you can try Parse.com.


text:
Q: Windows start command not able to execute batch file I am executing start command from command prompt.
Command calls batch file named D:\My script.cmd and passes argument "Argument one". Here is command that I am tring to execute.
   C:\Users\ABCUser>start "D:\My script.cmd" "Argument one"

but getting error mesasge as The system cannot find the file Argument one.
I don't understand why command is searching for file. Contents of file My script.cmd.
@echo off
cls
echo "Hello"
echo %1

Am I missing something or command syntax is wrong ? This command is not even working for file name without spaces.

A: It's the well known bug of start/cmd.exe handling a cmd and also an argument with quotes.
The cause is, that start uses cmd.exe /k to start the new task.
The help of cmd /k and cmd /c explains, that in this case the first and last quote are removed.
And additionally you used the start command wrong.
This should work, as the call works like a dummy to supress the quoting problem
start "Title" call "D:\My script.cmd" "Argument one"

A: You can use cmd.exe /c "D:\My script.cmd" arg1 arg2
If there is a problem you can switch the /c with /k which will leave the cmd open for you to examin the errors..
gl,
Refael


text:
Q: Trying to download image from tumblr using java selenium I'm trying to download images form tumblr using java selenium. I extracted the url of the image from src and tried to download images from url. But the images saved not what I expected. Those are in unsupported formats and smaller in size. How can I correct this? Please help.
This is my code:
public static void main(String[] args) throws InterruptedException, AWTException, IOException {

    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("https://artist-childe-hassam.tumblr.com/");
    Thread.sleep(5000);
    Robot robot = new Robot();
    robot.keyPress(KeyEvent.VK_END);
    robot.keyRelease(KeyEvent.VK_END);

    List<WebElement> list = driver.findElements(By.xpath("//img[@alt]"));
    int count;
    count = 1;
    for (WebElement element : list) {

        String srcs = element.getAttribute("src");
        String attribute = element.getAttribute("alt");
        System.out.println("title: " + attribute);
        System.out.println(" ");
        System.out.println("link " + srcs);

        URL url = new URL(srcs);
        InputStream in = new BufferedInputStream(url.openStream());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int n = 0;
        while (-1!=(n=in.read(buf)))
        {
           out.write(buf, 0, n);
        }
        out.close();
        in.close();
        byte[] response = out.toByteArray();

        FileOutputStream fos = new FileOutputStream("path"+count+".jpg");
        count++;
        fos.write(response);
        fos.close();
        }

    }

}

A: I don't have idea on BufferedInputStream to download image from URL. Instead, I used to use curl to download from URL. I have modified your code and its working fine for me.
public static void main(String[] args) throws InterruptedException, AWTException, IOException {
        WebDriverManager.chromedriver().setup();
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://artist-childe-hassam.tumblr.com/");
        Thread.sleep(5000);
        Robot robot = new Robot();
        robot.keyPress(KeyEvent.VK_END);
        robot.keyRelease(KeyEvent.VK_END);

        List<WebElement> list = driver.findElements(By.xpath("//img[@alt]"));
        int count;
        count = 1;
        for (WebElement element : list) {
            String srcs = element.getAttribute("src");
            String attribute = element.getAttribute("alt");
            System.out.println("title: " + attribute);
            System.out.println(" ");
            System.out.println("link " + srcs);

            downloadFromUrl(srcs,"Path" + count+".jpg",Duration.ofSeconds(20));
            count++;
        }

    }

    public static boolean downloadFromUrl(String url, String fileNameWithPath, Duration timeoutDuration) {
        try {
            if(timeoutDuration == null) {
                timeoutDuration = Duration.ofMinutes(5);
            }
            String curlStr = "curl " + url + " --output " + fileNameWithPath;
            Process process = Runtime.getRuntime().exec(curlStr);
            long totalSeconds = 0;
            System.out.println("Downloading file to " + fileNameWithPath + " ...");
            while(process.isAlive()) {
                Thread.sleep(1000);
                totalSeconds++;
                if(totalSeconds > timeoutDuration.getSeconds()) {
                    throw new Exception("Unable to download file even after 5 mins of wait");
                }
            }
            System.out.println(fileNameWithPath + " got downloaded in seconds - " + totalSeconds);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

My downloaded images:


text:
Q: Name of old Sci-fi movie where alien communicates and deceives woman through the TV screen static? When I was a kid (early 80s) I barely remember watching a movie on TV about an alien who masqueraded as a benevolent humanoid and communicated with a woman through television screen static.  The movie ended with the alien tricking the woman, and if my memory is right, somehow kidnapping her through the TV.  (I know it sounds like Poltergeist, but is was a few years before that).
Sorry if the specifics aren't clear or accurate... but it has been driving me crazy for years that I don't know what the movie was called! It did really freak me out at the time.
Any suggestions would be so awesome. Thanks in advance ;-)

A: This is Alien Lover from 1975, part of the Wide World of Mystery anthology series of films.

An orphaned teenager becomes involved with an alien who was beamed to
  Earth from another galaxy in a TV signal. Is the alien a dream come
  true or a harbinger of doom?


text:
Q: How to use multiple handlers in jquery function I have some code I am working on and I cannot seem to figure out the terms to search for assistance.
I am trying to add a jquery statement that executes when the #quickSearchResults_section is clicked "AND" when #nav-input is focused out.
So in a nutshell, I am still learning jquery and programming logic and want to use click function and focusout.
<script>
    $(":not(#quickSearchResults_section)").click(function(){
        $("#quickSearchResults_section").hide();
    });
</script>

A: Try something like this:
$("#nav-input").on("blur", function(){
    $("#quickSearchResults_section").click(function(){
        $("#quickSearchResults_section").hide();
    });
});


text:
Q: Android: Increase Geofences accuracy I'm building an app using Geofences, right now the minimum radius I can set so my geofence can get accurately detected is 30m. I want to be able to set a minimum radius of 5m.
In the Android Developers documentation about geofences says:

When indoor location is available, the accuracy range can be as small as 5 meters.

What does it mean with the indoor location? Is it something I should enable in the phone? I don't get it. Also I looked over internet and I know that the accuracy of a geofence is perform by the system and cannot get the Wifi RTT or anything else work with it.
What can anyone do to get a better accuracy for geofences?

A: Indoor location means using bluetooth beacons to determine a more exact location via triangulation.  It only works in a predefined area as you need special hardware in the physical location.  Getting it down to 5m outside would require GPS hardware more powerful than in the typical phone.  The typical phone is accurate to only about 10m in the best case.  What you wan't just isn't possible.


text:
Q: How do detect when someone makes a call from an Android device in an AIR application? I want to be able to read the contact number of the person to whom the call was made and read when the call ends. I have been googling but couldn't really find anything. How can I achieve this? any help is greatly appreciated.

A: You would need to write an Air native extension (ANE) for Android that creates a class that inherits BroadcastReceiver, you could than wrap actions such as ACTION_NEW_OUTGOING_CALL as ActionScript events to broadcast the phone number, contact info, etc.. to your event handlers.
Developing and using Adobe AIR native extensions for Android device
Example Android java:
public class PhoneStateReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        String extraState = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
        if (action.equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
            Log.d("test", "ACTION_NEW_OUTGOING_CALL");
        }
        else {
            Log.d("test", "ACTION_PHONE_STATE_CHANGED");
            if (extraState.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                Log.d("test", "EXTRA_STATE_RINGING");
            }
            else if (extraState.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
                Log.d("test", "EXTRA_STATE_OFFHOOK");
            }
            else if (extraState.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                Log.d("test", "EXTRA_STATE_IDLE");
            }
        }
    }
}


text:
Q: Jquery topic: editing text on a To-Do-List after adding text It been a while since using Stack over flow and glad to get back in it, here my question.
Im trying to make a simple to do list (link of what i done so far is here: http://lamp.cse.fau.edu/~mcuervo5/p4/ with the Jquery and html code when you "Inspect and look at sources"
I'm a simple "To-DOList" from scratch and 90% done (just need to do the Css part after). The Question I have is trying to make a "edit" button which the sole purpose of editing the text inside the textbox after adding it to the list. The Only problem i how do I write the function in order to let people edit the text. I have the edit button already but it inside the delete function and I dont know what I have to type to let it edit. thank you
PS: Ok, i haveing a hard time pasting the Jquery code so just click the link above the copy the soruce from the website
it should look like this for the code http://imgur.com/tpx3KRg
also How do you paste Jquery code here next time, cause im reading the direction and it still not pasting correctly on stack over flow. thank you

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">

<title>The Reminder list</title>

 The Reminder Friend

<form>

    <input type="text" id="textbox" >

    <input type="button" id= "Sumbit_Button" value="Add">

Todo

</form>

 &copy  Copyright Mauricio Cuervo

A: How about having a hidden textbox per option- when clicking edit display the textbox and hide the option, when clicking enter take the value from the textbox and change the option innerHTML to the value.

A: I took the approach that Shtut said.

$(document).ready( function() {
            //$('#incomplete-tasks').html("
I just replaced your stuff.
");
            $("#Sumbit_Button").click(function() {
                var textbox_Value = $("#textbox").val();
                $('#incomplete-tasks').append('
' + textbox_Value + ""
                                              + '<input/ style="display: none" class="new-value">'
                                              + "<button type='button' class='delete'>Delete</button>"
                                              + "<button type='button' class='edit'>Edit</button>
");
            });
            $('#incomplete-tasks').on('click', '.delete', function() {
                console.log('i am clicked');
               $(this).parent().remove();
            });

            $('#incomplete-tasks').on('click', '.edit',  function () {
                $(this).siblings('input').show();
                $(this).siblings('.delete').hide();
                $(this).hide();
            });

            $('#incomplete-tasks').on('click', '.edit',  function () {
                $(this).siblings('input').show();
                $(this).siblings('span').hide();
                $(this).siblings('.delete').hide();
                $(this).hide();
            });

            $('#incomplete-tasks').on('keyup', '.new-value',  function (e) {
                if(e.keyCode == 13){
                    $(this).siblings('span').text($(this).val()).show();
                    $(this).siblings('input').hide();
                    $(this).siblings('.delete').show();
                    $(this).siblings('.edit').show();
                    $(this).hide();
                }
            });
        });
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>The Reminder list</title>

 The Reminder Friend

    <form>
        <input type="text" id="textbox">
        <input type="button" id="Sumbit_Button" value="Add">

Todo

    </form>

 &copy  Copyright Mauricio Cuervo


text:
Q: Replace numpy arrays of arrays with values I am trying to convert a numpy array of arrays. An example input is this:
np.array([[[0, 0, 0], [255, 255, 255]], [[255, 255, 255], [0, 0, 0]]], np.uint8)

I want to replace all arrays with values [0, 0, 0] with 0 and the [255, 255, 255] with 255. I want the final result to be in this format:
np.array([[0, 255], [255, 0]], np.uint8)

The array will always have the above values but will be different size.
This is the code I created for doing this:
array_list = []
for row in input_image:
    row_list = []
    for item in row:
        if np.array_equal(item, [0, 0, 0]):
            row_list.append(0)
        else:
            row_list.append(255)
    array_list.append(row_list)
output_image = np.array(array_list, np.uint8)

The above code is very slow for big arrays and I was thinking that there might be a way to do this directly with numpy, though I couldn't find a way. Do you have any suggestions for doing this more efficient?

A: X_new = np.mean(X, axis=2)
X_new
array([[  0., 255.],
       [255.,   0.]])


text:
Q: Convertir a JSON Java Script Estoy trabajando en Java JSP y JavaScript, y necesito convertir el resultado de una consulta DataStore de formato:
<Entity [Usuario(5523854313120)]:
    Email = andres@hotmail.com
    PrimerNombre = Andres
    Rol = Administrador
   Password = andres125
>

al formato JSON:
{"Email ":"andres@hotmail.com","PrimerNombre ":"Andres","Rol ":"Administrador", "Password":"andres125"}

Éste es el código:
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query q=new Query("Usuario");
PreparedQuery pq = datastore.prepare(q);
Entity result=pq.asSingleEntity();

A: Lo ideal seria convertir este objeto a un objeto java común y luego utilizar la librería java Jackson como lo señala aquí.
http://chuwiki.chuidiang.org/index.php?title=Java_y_json_con_jackson
Saludos...

A: Tambien depende de la forma en que estas mostrando los datos en el jsp.

*

*Si estas haciendo uso de REST Api, puedes usar jackson y el se encarga de hacer el parseo de los model de java a json. Aqui tienes un ejemplo sencillo: JSON Example with jersey jackson

*Si estas ejecutando el codigo de java desde el jsp, entonces te recomiendo estos dos recursos usando jackson:

*

*https://springframework.guru/processing-json-jackson/

*https://www.journaldev.com/2324/jackson-json-java-parser-api-example-tutorial
Saludos!!!.


text:
Q: How to use installed package in jupyter notebook? I am having difficulties setting up a jupyter notebook environment, using external packages.
!pip install progress.bar

leads to:
Collecting progress.bar
  Downloading https://files.pythonhosted.org/packages/b4/fb/d45c6a34e1242f4c7abef5f98aeb29e7096518defcf390bd601b5d3148ff/progress_bar-8.tar.gz
Building wheels for collected packages: progress.bar
  Building wheel for progress.bar (setup.py) ... done
  Created wheel for progress.bar: filename=progress_bar-8-cp36-none-any.whl size=5587 sha256=46b6c1e0cf1940b29e9e7208d4057a4d65986f9e793cea4b369ea833de896108
  Stored in directory: /root/.cache/pip/wheels/04/7e/72/b2261521999fc5bc4ca704b6d84722270d478643c366c6594e
Successfully built progress.bar
Installing collected packages: progress.bar
Successfully installed progress.bar

which is a success.
But then, how to use this?
Neither of these 3 worked:
bar = Bar()  # Bar is not definied
import progress.bar   #progress it not definied
bar = progress.bar.Bar()  #progress is not definied


text:
Q: Why monitoring power and energy in energy usage meters? This time my question about the how power companies monitor usage.
We get electric usage bill in [Kilo watt hour]/Energy.
What should be looked up on for monitoring the usage the instantaneous energy or power?
Or Both?

I trust it is the second one and why is it necessary to monitor both
  power and energy?

Power is the d/dt of energy.So what change does it make?
And how different will be the result getting from the second method?

A: For certain large consumers, electric companies are actually interested in three things: energy, peak power, and the integral of RMS current.  For smaller consumers, the latter two quantities are assumed to be close enough to being proportional to energy consumption that billing purely on the basis of energy is sufficient, but that doesn't hold true for some larger consumers.
Electric companies need to build enough equipment to handle the maximum instant power demand; during times when customers aren't using that much power, the equipment won't have to provide energy, but it will still have substantial daily maintenance and depreciation costs.  An electric consumer that needs one megawatt of power for one minute per week might compel an electric company to build otherwise-unnecessary equipment, but energy-based billing, even at $0.10/kWh would be less than $10,000/month.  A company that sometimes demands a megawatt will be billed monthly based upon that peak demand, even if it only demands that much power intermittently.
Further, billing for current may seem redundant compared with billing for power, but capacitive or reactive loads will draw power from the line during part of each cycle and return power during part of it.  Energy-based billing will credit the power returned against the power drawn, which would be fair except that power-company wiring will lose some energy beyond what is is drawn, and will lose some of the energy which is returned.  Billing upon energy alone would mean that a consumer which returned 99% of the energy drawn each cycle would only pay 1% as much as a consumer that drew 1% as much energy but returned zero, but the cost of supplying the former customer would be much greater.
It's worthwhile to note that while billing large customers for peak demand and RMS current is a source of revenue, it also serves another more important purpose: it encourages customers to save the utility money.  If a customer has a choice between using one megawatt for one minute per month, or 20 kilowatts (1/50 megawatt) for an hour per month, it may be cheaper for the utility to supply the latter customer's needs even though the latter customer uses more energy.  Further, in many cases where a consumer might consume excess RMS current (relative to power), it would be possible for the customer to install equipment which would reduce RMS current.  Even though such equipment will waste some energy, the reduction of waste in the utility's lines may significantly exceed the amount of energy it consumes.  Consequently, even though the equipment increases billable energy usage, utilities would still like to reward those who supply it themselves.

A: A perfect power meter would measure
$$
E = \int_0^T{V(t)I(t)dt}
$$
where \$ T \$ is your billing period, \$ E \$ is the energy (units can be converted easily) and \$ V \$ and \$ I \$ are the instantaneous voltage and current of the load. That is, they do not measure "power" on its own; they measure voltage and current as separate electrical quantities.
Of course, the real world is not continuous, so in practice it will compute they would compute something like
$$
E = \sum_{n=0}^N{V[n]I[n]\Delta T}
$$
with a sampling period \$ \Delta T\$. In practice, they will probably do many rapid measurements at faster than power line frequency, and then sum those results.
Power matters to utility companies because their costs increase as the demand on the grid increases. At some point, the utility may need to fire up an extra generator or purchase power from another jurisdiction to meet local demand. Every utility has different formulas to translate instantaneous power demand to cost. That is why they are concerned with both your total energy usage in a billing period, and your power usage at various times. Strictly speaking, both quantities are measurements of energy over different windows of time.


text:
Q: Facing SoapFaultClientException while consuming SOAP Web Service in Spring Boot On changing package-info.java file generated by this plugin in spring boot
<plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.jvnet.jaxb2.maven2</groupId>
            <artifactId>maven-jaxb2-plugin</artifactId>
            <version>0.13.2</version>
            <executions>
                <execution>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <generatePackage>com.example.demo.schemas.eligibility.test</generatePackage>
                <generateDirectory>${project.basedir}/src/main/java</generateDirectory>
                <schemaDirectory>${project.basedir}/src/main/resources/wsdl</schemaDirectory>
                <schemaIncludes>
                    <include>*.wsdl</include>
                </schemaIncludes>
            </configuration>
        </plugin>

I'm receiving this Exception that giving sense that we can't change package-info.java file for SOAP Xml classes.
org.springframework.ws.soap.client.SoapFaultClientException: BIP3113E: Exception detected in message flow gen.CRMEligibilityGS.SOAP Input (broker PTCLDEVBK01)
    at org.springframework.ws.soap.client.core.SoapFaultMessageResolver.resolveFault(SoapFaultMessageResolver.java:38) ~[spring-ws-core-3.0.7.RELEASE.jar:na]
    at org.springframework.ws.client.core.WebServiceTemplate.handleFault(WebServiceTemplate.java:830) ~[spring-ws-core-3.0.7.RELEASE.jar:na]
    at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:624) ~[spring-ws-core-3.0.7.RELEASE.jar:na]
    at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:555) ~[spring-ws-core-3.0.7.RELEASE.jar:na]
    at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:390) ~[spring-ws-core-3.0.7.RELEASE.jar:na]
    at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:378) ~[spring-ws-core-3.0.7.RELEASE.jar:na]
    at com.example.demo.config.SOAPConnector.callWebService(SOAPConnector.java:8) ~[classes/:na]
    at com.example.demo.client.SoapClient.getCustmoerEligibilityResponse(SoapClient.java:25) ~[classes/:na]
    at com.example.demo.EligibilityRestController.getCountryDetails(EligibilityRestController.java:31) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_181]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_181]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_181]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_181]

So can we make change in package-info.java file generated by plugin jaxb2 while generating java classes from wsdl file?
Or this exception is telling something else?
this is my package-info.java file
@javax.xml.bind.annotation.XmlSchema(namespace = "http://CRMEligibilityGS")
package com.example.demo.schemas.eligibility.test;

Using Java 8 with Spring Boot 2.1.4.RELEASE
Client Class Code
 public CRMEligibilityGSResponse getCustmoerEligibilityResponse(CRMEligibilityGS eligibilityRequest) {
        webServiceTemplate = new WebServiceTemplate(jaxMarshaller);
        CRMEligibilityGSResponse response = (CRMEligibilityGSResponse) webServiceTemplate.marshalSendAndReceive("http://abcxyz?wsdl", eligibilityRequest);    // url is sample actual one is different that also ends with ?wsdl and url is private
        System.out.println("Response is :"+ response);
        return response;
    }


text:
Q: Azure Cognitive Search: Debug session throws "session status" error Trying to start a debug session to experiment with adding a custom skill. When I hit run, this message appears:
Session status: Running
Debug session is running. Please wait a few seconds for the latest data.

But then is almost immediately replaced with:
Session status: Error
Parsing failure: unexpected ' '; expected end of input (Line 1, Column 16); recently consumed: ment/Start

The Indexer, Skillset, Datasource, and Index objects attached to the debug session all work just fine on their own. I only experience issues from within the debug session. The "Errors/Warnings" tab continues to report "No errors or warnings", even after repeatedly attempting to run the skillset through the debug session and getting that same error.


text:
Q: VirtualBox imported VM - VERR_NOT_SUPPORTED - VERR_CFGM_VALUE_NOT_FOUND On VirtualBox, I've exported a Ubuntu Server VM (File \ Export Appliance) and tried to imported it on a different machine. every thing went well with export and import. But, when I start the imported VM, I get this VERR_NOT_SUPPORTED error VERR_CFGM_VALUE_NOT_FOUND.
Its quite weird. If I ditch the Import process and straight away create a new VM and use the exported VMDK, it works fine!!
Both machines are using the same version of VirtualBox (3.2.4 r62467)
Any clues?

A: I found this same issue, OS X host exported to a Windows XP host. Both VirtualBox 3.2.6 r63112. Perhaps it is a bug that should be filed?
Workaround - create a new VM and import the VMDK manually.
http://blog.anuragg.com/2012/10/vhdx-to-vhd-conversion.html

A: I had the same issue, the settings were imported for the appliance, so I changed the settings to match the new computer (1 cpu instead of 2, and less memory).

A: This may be caused by a known bug in older versions of VirtualBox. See https://www.virtualbox.org/ticket/7251 for details.

A: I just encountered the same error code (VERR_CFGM_VALUE_NOT_FOUND), but with a different error description after editing VirtualBox VMs/<name of vm>/<name of vm>.vbox:

NAT#0: configuration query for "GuestPort" int failed (VERR_CFGM_VALUE_NOT_FOUND)
  Failed to attach the network LUN (VERR_CFGM_VALUE_NOT_FOUND)

It turns out that the name of the forwarding rule should certainly not contain any parentheses or slashes (as shown below). So, when you set a forwarding rule, use a name that consists of spaces, letters or numbers to be safe.

For example, the following does not work (VM refused to start up with previous error message):
...
<NAT>
  <DNS pass-domain="true" use-proxy="false" use-host-resolver="false"/>
  <Alias logging="false" proxy-only="false" use-same-ports="false"/>
  <Forwarding name="HTTP/8088" proto="1" hostip="127.0.0.1" hostport="1080" guestport="80"/>
  <Forwarding name="HTTPS" proto="1" hostip="127.0.0.1" hostport="1443" guestport="443"/>
  <Forwarding name="SSH (2022)" proto="1" hostip="127.0.0.1" hostport="2022" guestport="22"/>
</NAT>

After removing /, ( and ) from the vbox file, the error message goes away and the VM boots again:
<NAT>
  <DNS pass-domain="true" use-proxy="false" use-host-resolver="false"/>
  <Alias logging="false" proxy-only="false" use-same-ports="false"/>
  <Forwarding name="HTTP" proto="1" hostip="127.0.0.1" hostport="1080" guestport="80"/>
  <Forwarding name="HTTPS" proto="1" hostip="127.0.0.1" hostport="1443" guestport="443"/>
  <Forwarding name="SSH on port 2022" proto="1" hostip="127.0.0.1" hostport="2022" guestport="22"/>
</NAT>

This post does not answer the question, but this question was one of the few pages I found when I Googled for a solution to my problem.


text:
Q: iPhone 4 - camera flash I want to write a program for iPhone 4 that uses its camera flash.
Is that possible?
If so, which class should I work with?
Thanks in advance,
sagiftw

A: Yes it is possible...Not sure what exactly you want to do but look at AVFoundation framework specifically AVCaptureDevice AVCaptureDevice ref


text:
Q: How to set up constructor function Bit of a weird question how would you go about setting up a constructor function that would be called like this:
let name = {name:'hi'};
name.log()
// the log() function would log out to the console name.

I have been trying to rap my head around how to do this but I can't seem to figure it out.

A: Add log as a property of the object.

let name = {
  name: 'hi',
  log: function() {
    console.log(this.name);
  }
}
name.log();


text:
Q: I wanted to sort the elements in my array but this doesn't work it always prints the same array in the same order? I tried changing the i and j variables but it doesn't seem to work.
public static void main(String[] args) {

    double[] nameArray = {20.0,30.2,25.2,75.23,20.0,2.0,25.22};
    double tempElement;

    for (int i=0; i < nameArray.length; i++)
    {
        // This inner loop selects and compares each remaining values to the selected element by the outer for loop.
        for (int j=i+1; j < nameArray.length; j++)
        {
            // This if loop compares the elements.
            if (nameArray[i] > nameArray[j]);
            {
                // This if loop will only run if the next array element is smaller than
                // the previous array element being compared.

                // This tempElement is used for proper assigning of the variables.
                tempElement = nameArray[i];
                nameArray[i] = nameArray[j];
                nameArray[j] = tempElement;
            }

        }
    }

    // This for loop assigns the sorted elements in the descending order to the other array.
    for (int i = 0; i<nameArray.length; i++)
    {

        System.out.println(nameArray[i]);

    }
}

A: Simple mistake: Remove the ; after the if-statement.
The semicolon after if means there is nothing to do if the if case is true.
The part in the curly brackets to swap the elements will then always be executed. That is because you can add curly brackets at any point in your code to structure it. It's not effected by the if because that statement was already ended by the semicolon.
To further explain it, you can write a perfectly fine if without any curly brackets. That means only the first following row is supposed to be included in the if statement:
if (condition)
    do()
doA()

In this code do is only executed if the condition is true, doAlways() on the other hand is always executed.
Now if you change it like this:
if (condition)
    do()
{
    doAlways()
{

it still does exactly the same. The curly brackets don't change anything because the do not directly follow the if statement. So only the first row after is included and get's conditionally executed. doAlways() always get's executed again.
Now to change it like you had:
if (condition)
    ; <-- this is an empty statement
{
    doAlways()
{

again only the first row after the if is affected by it. This time it's an empty statement. So basically the condition decides if you should do nothing or execute the empty statement and .. do nothing. doAlways() still get's executed regardless of the condition.

A: the outer loop must stop in the element that comes before the last one in the array  (length-1) so that the algorithme compares it with the last element (j=i+1), then you should put (int i=0; i < nameArray.length-1; i++)   instead of (int i=0; i < nameArray.length; i++)


text:
Q: Is there something like save and restore snapshots in docker I love docker and especially for complex CI environments it is just amazing.
The one thing that I really miss when working with Docker compared to a Virtual Machine is the ability to
save and restore snapshots of the container and I was wondering if Docker offers anything similar?

A: docker checkpoint may answer your needs.
Note that checkpoints is experimental feature and you may need to rerun your docker engine in experimental mode.


text:
Q: php/mysql with multiple queries <?php

$query1 = "CREATE VIEW current_rankings AS SELECT * FROM main_table WHERE date = X";

$query2 = "CREATE VIEW previous_rankings AS SELECT rank FROM main_table WHERE date = date_sub('X', INTERVAL 1 MONTH)";

$query3 = "CREATE VIEW final_output AS SELECT current_rankings.player, current_rankings.rank as current_rank LEFT JOIN previous_rankings.rank as prev_rank
             ON (current_rankings.player = previous_rankings.player)";

$query4 = "SELECT *, @rank_change = prev_rank - current_rank as rank_change from final_output";

$result = mysql_query($query4) or die(mysql_error());

while($row = mysql_fetch_array($result)) {
echo $row['player']. $row['current_rank']. $row['prev_rank']. $row['rank_change'];
}

?>

All the queries work independently but am really struggling putting all the pieces together in one single result so I can use it with mysql_fetch_array.
I've tried to create views as well as temporary tables but each time it either says table does not exist or return an empty fetch array loop...logic is there but syntax is messed up I think as it's the 1st time I had to deal with multiple queries I need to merge all together. Looking forward to some support. Many thanks.

A: Thanks to php.net I've come up with a solution : you have to use (mysqli_multi_query($link, $query)) to run multiple concatenated queries.
 /* create sql connection*/
$link = mysqli_connect("server", "user", "password", "database");

$query = "SQL STATEMENTS;"; /*  first query : Notice the 2 semicolons at the end ! */
$query .= "SQL STATEMENTS;"; /* Notice the dot before = and the 2 semicolons at the end ! */
$query .= "SQL STATEMENTS;"; /* Notice the dot before = and the 2 semicolons at the end ! */
$query .= "SQL STATEMENTS"; /* last query : Notice the dot before = at the end ! */

/* Execute queries */

if (mysqli_multi_query($link, $query)) {
do {
    /* store first result set */
    if ($result = mysqli_store_result($link)) {
        while ($row = mysqli_fetch_array($result))

/* print your results */
{
echo $row['column1'];
echo $row['column2'];
}
mysqli_free_result($result);
}
} while (mysqli_next_result($link));
}

EDIT - The solution above works if you really want to do one big query but it's also possible to execute as many queries as you wish and execute them separately.
$query1 = "Create temporary table A select c1 from t1";
$result1 = mysqli_query($link, $query1) or die(mysqli_error());

$query2 = "select c1 from A";
$result2 = mysqli_query($link, $query2) or die(mysqli_error());

while($row = mysqli_fetch_array($result2)) {

echo $row['c1'];
    }

A: It seems you are not executing $query1 - $query3. You have just skipped to $query4 which won't work if the others have not been executed first.
Also
$query4 = "SELECT *, @rank_change = prev_rank - current_rank as rank_change from final_output";

should probably be
$query4 = "SELECT *, @rank_change := prev_rank - current_rank as rank_change from final_output";

or else the value of rank_change will just be a boolean, true if @rank_change is equal to (prev_rank - current_rank), false if it is not. But do you need @rank_change at all? Will you use it in a subsequent query? Maybe you can remove it altogether.
Even better, you could just combine all the queries into one like this:
SELECT
    curr.player,
    curr.rank AS current_rank,
    @rank_change := prev.rank - curr.rank AS rank_change
FROM
    main_table AS curr
    LEFT JOIN main_table AS prev
        ON curr.player = prev.player
WHERE
    curr.date = X
    AND prev.date = date_sub('X', INTERVAL 1 MONTH)

A: You should concatenate them:
<?php

$query = "CREATE VIEW current_rankings AS SELECT * FROM main_table WHERE date = X";

$query .= " CREATE VIEW previous_rankings AS SELECT rank FROM main_table WHERE date =     date_sub('X', INTERVAL 1 MONTH)";

$query .= " CREATE VIEW final_output AS SELECT current_rankings.player,     current_rankings.rank as current_rank LEFT JOIN previous_rankings.rank as prev_rank
         ON (current_rankings.player = previous_rankings.player)";

$query .= " SELECT *, @rank_change = prev_rank - current_rank as rank_change from final_output";

$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result)) {
echo $row['player']. $row['current_rank']. $row['prev_rank']. $row['rank_change'];
}

?>


text:
Q: Does this particular L-series built from L-functions of prime degree define an L-function? Throughout this question, I call 'L-function' any automorphic L-function belonging to the Selberg class.
Suppose  $ (F_i)_{(i>0)} $ is a sequence of L-functions with  $ F_i $ of degree  $ p_i $ for all  $ i $ and let  $ a_{p_{i}} $ be the  $ p_i$ -th coefficient of the L-series defining  $ F_i $ .
Does the sequence  $ a_{p_i} $ define an L-function ?

A: Surely not.
First, you can't just patch things together at random to get an $L$-function.
Second, your "construction" doesn't limit the growth of the $a_{p_i}$'s, so they need not satisfy Ramanujan.


text:
Q: Solve $0 = ax + b \cdot \log(1 + cx)$ for $x$? I am facing a physics problem that requires me to solve
$$
0 = -gt - \frac{F}{\alpha}\cdot \log\left( 1 - \frac{\alpha t}{M+m} \right)
$$
with $M=5~kg$, $m=10~kg$, $\alpha = 1 kg/s$ and $F = 0.9(M +m)g$. Via computer trial and error I was able to find that $t = 0$ and $t \approx 2.9$ are solutions. However, how can I find the solutions on a mathematical way? Since the parameters are not necessary for the mathematics, I broke it down to this for you:

$$ 0 = ax + b \cdot \log(1 + cx) $$

Note: In the exercise following hint is given: Note that $\alpha t \ll M+m$. It would be helpful already, if you could help me use that hint. Because that hint means (from my point of view) that $\frac{\alpha t}{M+m} \approx 0$. However, it would follow $\log(1 - 0) = 0$ and from that $t = 0$. This is one solutions, but how to find the second (more important) solution?

A: $$0=ax+b\ln(1+cx) \tag 1$$
Note : If $\quad 0=ax+\beta\log_{10}(1+cx)\quad\to\quad b=\beta\ln(10)$
$\ln(1+cx)=-\frac{a}{b}x\quad\to\quad 1+cx=e^{-\frac{a}{b}x}\quad\to\quad (1+cx)e^{-\frac{a}{bc}}=e^{-\frac{a}{b}x-\frac{a}{bc}}$
$\frac{bc}{a}(\frac{a}{b}x+\frac{a}{bc})e^{-\frac{a}{bc}}=e^{-\frac{a}{b}x-\frac{a}{bc}}$
$ (\frac{a}{b}x+\frac{a}{bc})e^{\frac{a}{b}x+\frac{a}{bc}}=\frac{a}{bc}e^{\frac{a}{bc}}$
The solution of $\quad Xe^X=Y\quad$ is $\quad X=W(Y)\quad$ Lambert $W$ function.
http://mathworld.wolfram.com/LambertW-Function.html
With $X=(\frac{a}{b}x+\frac{a}{bc})$ and $Y=\frac{a}{bc}e^{\frac{a}{bc}}
\quad\to\quad\frac{a}{b}x+\frac{a}{bc}=W\left(\frac{a}{bc}e^{\frac{a}{bc}} \right)$
The solution of the equation $(1)$ is :
$$x=-\frac{1}{c}+\frac{b}{a}W\left(\frac{a}{bc}e^{\frac{a}{bc}} \right)$$
The solution cannot be expressed with a finite number of elementary functions. Many equations requires some special functions to have the solution expressed on closed form. This is the case of Equation $(1)$ which solving involves the special function $W$.
A paper for general public about special functions : https://fr.scribd.com/doc/14623310/Safari-on-the-country-of-the-Special-Functions-Safari-au-pays-des-fonctions-speciales
If you don't want to use a special function, approximate solutions are commonly computed in using numerical calculus. That is the method recommended in your case insofar the numerical values of the parameters are known.

A: Using Taylor series for $\ln(1+x)$ plugging $x=-t$ we get $-x-\frac{x^2}2-\frac{x^3}{3}+\cdots$  $$0=-gt-\frac{F}{\alpha}\cdot(-\frac{\alpha t}{M+m}-\frac{\alpha^2t^2}{2(M+m)^2}-\cdots)$$
Now the more terms of the taylor expansion you take the better the approximation, since we can solve a quadratic and we know that $t=0$ is a solution we can take three terms.
$$gt=F(\frac{t}{M+m}+\frac{\alpha t^2}{2(M+m)^2}+\frac{\alpha^2t^3}{3(M+m)^3})$$
$$gt=0.9g(M+m)(\frac{t}{M+m}+\frac{\alpha t^2}{2(M+m)^2}+\frac{\alpha^2t^3}{3(M+m)^3})$$
Since $t=0$ zero is a solution for $t\neq 0$ we divide by $gt$ to get
$$1=0.9+\frac{0.9t}{2(M+m)}+\frac{0.9t^2}{3(M+m)^2}$$
From this $t\approx 2.94727$ (because the other solution is negative). Since $\frac{\alpha t}{M+m}\approx 0.2$ is not small enough the approximation isn't good enough, in case you can solve a $3$rd degree polynomial then taking $4$ terms gives approximately $t\approx 2.904$, larger degree of polynomial equals better approximation.

A: From your parameters, we see that $a\neq 0$, $b\neq 0$ and $c\neq 0$.
The solution of your problem is given by using the Lambert $W$ function
$$x = \dfrac{b}{a}W\left[\dfrac{a}{bc}\exp\left(\dfrac{a}{bc}\right) \right]-\dfrac{1}{c}$$


text:
Q: Setting textview at bottom in android I have Textview inside Linearlayout. I want it to be displayed at bottom but it is showing me only at the centre. My xml file is look like the code below. I tried replacing LinearLayout with RelativeLayout but it did't worked.
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/black">
<RelativeLayout
android:id="@+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000"
android:layout_gravity="bottom" >

 </RelativeLayout>

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/TextViewBottomTitle"
    android:text="@string/app_logo_bottom"
    android:textColor="@color/logo_color"
    android:gravity="center"
    android:textSize="@dimen/logo_size"></TextView>
<TextView
    android:id="@+id/TextViewBottomVersion"
    android:text="@string/app_version_info"
    android:textSize="@dimen/version_size"
    android:textColor="@color/version_color"
    android:background="@color/version_bkgrd"
    android:layout_height="fill_parent"
    android:lineSpacingExtra="@dimen/version_spacing"
    android:layout_width="fill_parent"
    android:layout_gravity="center_vertical|center_horizontal"
    android:gravity="center"></TextView>

</LinearLayout>

Any one have idea?

A: May This help you:
  <LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:background="@android:color/black">

<RelativeLayout
android:id="@+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000"
android:layout_gravity="bottom" >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/TextViewBottomTitle"
    android:text="@string/app_logo_bottom"
    android:textColor="@color/logo_color"
    android:gravity="bottom"
    android:layout_alignParentBottom="true"
    android:textSize="@dimen/logo_size"></TextView>
<TextView
    android:id="@+id/TextViewBottomVersion"
    android:text="@string/app_version_info"
    android:textSize="@dimen/version_size"
    android:textColor="@color/version_color"
    android:background="@color/version_bkgrd"
    android:layout_height="fill_parent"
    android:lineSpacingExtra="@dimen/version_spacing"
    android:layout_width="fill_parent"
    android:layout_gravity="bottom"
    android:layout_alignParentBottom="true"
    android:gravity="bottom"></TextView>

 </RelativeLayout>

</LinearLayout>

A: Can try this worked for me :
android:layout_gravity="bottom"

A: Try this
android:scaleType="fitEnd"

A: Try to add :
android:gravity="bottom|center"


text:
Q: Load tag file xml PHP I have an XML file and wanted to get the values that are in the <arquivo> tag,
<Listings>
    <Listing>
      <id>1</id>
      <endereco>abc</endereco>
      <Media>
        <foto>
          <arquivo>foto1.jpg</arquivo>
        </foto>
        <foto>
          <arquivo>foto2.jpg</arquivo>
        </foto>
      </Media>
    </Listing>
    <Listing>
      <id>2</id>
      <endereco>rua X</endereco>
      <Media>
        <foto>
          <arquivo>...</arquivo>
        </foto>
        <foto>
          <arquivo>...</arquivo>
        </foto>
      </Media>
    </Listing>
</Listings>

but I'm not sure what's wrong with my PHP
$listings = simplexml_load_file("file.xml");

foreach ($listings as $listing):

    echo 'endereco: ' . trim($listing->endereco) . "
";

    foreach($listing->Media as $items):
        foreach($items as $item):
            echo 'Image: ' . trim($item) . "
";
        endforeach;
    endforeach;

endforeach;

The result of my code is
endereco: abc
Imagem:
Imagem:
endereco: rua X
Imagem:
Imagem:

but I hoped it would be
endereco: abc
Imagem: foto1.jpg
Imagem: foto2.jpg
endereco: rua X
Imagem: ...
Imagem: ...

A: You need to enter every level of the structure like you did for enderco. Take a look at:
$x = new simplexmlelement('<Listings>
<Listing>
  <id>1</id>
  <endereco>abc</endereco>
  <Media>
    <foto>
      <arquivo>foto1.jpg</arquivo>
    </foto>
    <foto>
      <arquivo>foto2.jpg</arquivo>
    </foto>
  </Media>
</Listing></Listings>');
foreach ($x as $listing):
    echo 'endereco: ' . trim($listing->endereco) . "
";
    foreach($listing->Media as $items):
            foreach($items->foto as $foto):
                echo 'Image: ' . trim($foto->arquivo) . "
";
            endforeach;
        endforeach;
endforeach;

https://3v4l.org/0bcfj

A: Use a foreach loop around the root elements, and then use an XPath query for easier access to the inner elements. It's still pretty hacky with two foreach loops, but it should work fine.
<?php
$listings = simplexml_load_file("file.xml");
foreach ($listings as $listing) {
    echo "endereco: $listing->endereco
";
    $arquivos = $listing->xpath("Media/foto/arquivo");
    foreach ($arquivos as $ar) {
        echo "Imagem: $ar
";
    }
}


text:
Q: NetworkImageView not loading the image from the first time I'm trying to upload an Image from my API to show it as profile picture, the problem is from the first time that the user opens the navdrawer the image doesn't load and it makes the entire layout disappear, but from the second time it all works, and I notice that it happens when the width of the image is less than the height. This is the class that I'm using:
public class CircledNetworkImageView extends ImageView {

    public boolean mCircled;

    /**
     * The URL of the network image to load
     */
    private String mUrl;

    /**
     * Resource ID of the image to be used as a placeholder until the network image is loaded.
     */
    private int mDefaultImageId;

    /**
     * Resource ID of the image to be used if the network response fails.
     */
    private int mErrorImageId;

    /**
     * Local copy of the ImageLoader.
     */
    private ImageLoader mImageLoader;

    /**
     * Current ImageContainer. (either in-flight or finished)
     */
    private ImageLoader.ImageContainer mImageContainer;

    public CircledNetworkImageView(Context context) {
        this(context, null);
    }

    public CircledNetworkImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircledNetworkImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * Sets URL of the image that should be loaded into this view. Note that calling this will
     * immediately either set the cached image (if available) or the default image specified by
     * {@link CircledNetworkImageView#setDefaultImageResId(int)} on the view.
     * <p/>
     * NOTE: If applicable, {@link CircledNetworkImageView#setDefaultImageResId(int)} and
     * {@link CircledNetworkImageView#setErrorImageResId(int)} should be called prior to calling
     * this function.
     *
     * @param url         The URL that should be loaded into this ImageView.
     * @param imageLoader ImageLoader that will be used to make the request.
     */
    public void setImageUrl(String url, ImageLoader imageLoader) {
        mUrl = url;
        mImageLoader = imageLoader;
        // The URL has potentially changed. See if we need to load it.
        loadImageIfNecessary(false);
    }

    /**
     * Sets the default image resource ID to be used for this view until the attempt to load it
     * completes.
     */
    public void setDefaultImageResId(int defaultImage) {
        mDefaultImageId = defaultImage;
    }

    /**
     * Sets the error image resource ID to be used for this view in the event that the image
     * requested fails to load.
     */
    public void setErrorImageResId(int errorImage) {
        mErrorImageId = errorImage;
    }

    /**
     * Loads the image for the view if it isn't already loaded.
     *
     * @param isInLayoutPass True if this was invoked from a layout pass, false otherwise.
     */
    void loadImageIfNecessary(final boolean isInLayoutPass) {
        int width = getWidth();
        int height = getHeight();
        ScaleType scaleType = getScaleType();

        boolean wrapWidth = false, wrapHeight = false;
        if (getLayoutParams() != null) {
            wrapWidth = getLayoutParams().width == ViewGroup.LayoutParams.WRAP_CONTENT;
            wrapHeight = getLayoutParams().height == ViewGroup.LayoutParams.WRAP_CONTENT;
        }

        // if the view's bounds aren't known yet, and this is not a wrap-content/wrap-content
        // view, hold off on loading the image.
        boolean isFullyWrapContent = wrapWidth && wrapHeight;
        if (width == 0 && height == 0 && !isFullyWrapContent) {
            return;
        }

        // if the URL to be loaded in this view is empty, cancel any old requests and clear the
        // currently loaded image.
        if (TextUtils.isEmpty(mUrl)) {
            if (mImageContainer != null) {
                mImageContainer.cancelRequest();
                mImageContainer = null;
            }
            setDefaultImageOrNull();
            return;
        }

        // if there was an old request in this view, check if it needs to be canceled.
        if (mImageContainer != null && mImageContainer.getRequestUrl() != null) {
            if (mImageContainer.getRequestUrl().equals(mUrl)) {
                // if the request is from the same URL, return.
                return;
            } else {
                // if there is a pre-existing request, cancel it if it's fetching a different URL.
                mImageContainer.cancelRequest();
                setDefaultImageOrNull();
            }
        }

        // Calculate the max image width / height to use while ignoring WRAP_CONTENT dimens.
        int maxWidth = wrapWidth ? 0 : width;
        int maxHeight = wrapHeight ? 0 : height;

        // The pre-existing content of this view didn't match the current URL. Load the new image
        // from the network.
        ImageLoader.ImageContainer newContainer = mImageLoader.get(mUrl,
                new ImageLoader.ImageListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        if (mErrorImageId != 0) {
                            setImageResource(mErrorImageId);
                        }
                    }

                    @Override
                    public void onResponse(final ImageLoader.ImageContainer response, boolean isImmediate) {
                        // If this was an immediate response that was delivered inside of a layout
                        // pass do not set the image immediately as it will trigger a requestLayout
                        // inside of a layout. Instead, defer setting the image by posting back to
                        // the main thread.
                        if (isImmediate && isInLayoutPass) {
                            post(new Runnable() {
                                @Override
                                public void run() {
                                    onResponse(response, false);
                                }
                            });
                            return;
                        }

                        if (response.getBitmap() != null) {
                            setImageBitmap(response.getBitmap());
                        } else if (mDefaultImageId != 0) {
                            setImageResource(mDefaultImageId);
                        }
                    }
                }, maxWidth, maxHeight, scaleType);

        // update the ImageContainer to be the new bitmap container.
        mImageContainer = newContainer;
    }

    private void setDefaultImageOrNull() {
        if (mDefaultImageId != 0) {
            setImageResource(mDefaultImageId);
        } else {
            setImageBitmap(null);
        }
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        loadImageIfNecessary(true);
    }

    @Override
    protected void onDetachedFromWindow() {
        if (mImageContainer != null) {
            // If the view was bound to an image request, cancel it and clear
            // out the image from the view.
            mImageContainer.cancelRequest();
            setImageBitmap(null);
            // also clear out the container so we can reload the image if necessary.
            mImageContainer = null;
        }
        super.onDetachedFromWindow();
    }

    @Override
    protected void drawableStateChanged() {
        super.drawableStateChanged();
        invalidate();
    }

    /**
     * In case the bitmap is manually changed, we make sure to
     * circle it on the next onDraw
     */
    @Override
    public void setImageBitmap(Bitmap bm) {
        mCircled = false;
        super.setImageBitmap(bm);
    }

    /**
     * In case the bitmap is manually changed, we make sure to
     * circle it on the next onDraw
     */
    @Override
    public void setImageResource(int resId) {
        mCircled = false;
        super.setImageResource(resId);
    }

    /**
     * In case the bitmap is manually changed, we make sure to
     * circle it on the next onDraw
     */
    @Override
    public void setImageDrawable(Drawable drawable) {
        mCircled = false;
        super.setImageDrawable(drawable);
    }

    /**
     * We want to make sure that the ImageView has the same height and width
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        Drawable drawable = getDrawable();
        if (drawable != null) {
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int diw = drawable.getIntrinsicWidth();
            if (diw > 0) {
                int height = width * drawable.getIntrinsicHeight() / diw;
                setMeasuredDimension(width, height);
            } else
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        } else
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //Let's circle the image
        if (!mCircled && getDrawable() != null) {
            Drawable d = getDrawable();
            try {
                //We use reflection here in case that the drawable isn't a
                //BitmapDrawable but it contains a public getBitmap method.
                Bitmap bitmap = (Bitmap) d.getClass().getMethod("getBitmap").invoke(d);
                if (bitmap != null) {
                    Bitmap circleBitmap = getCircleBitmap(bitmap);
                    setImageBitmap(circleBitmap);
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
                //Seems like the current drawable is not a BitmapDrawable or
                //that is doesn't have a public getBitmap() method.
            }

            //Mark as circled even if it failed, because if it fails once,
            //It will fail again.
            mCircled = true;
        }
        super.onDraw(canvas);
    }

    /**
     * Method used to circle a bitmap.
     *
     * @param bitmap The bitmap to circle
     * @return The circled bitmap
     */
    public static Bitmap getCircleBitmap(Bitmap bitmap) {
        int size = Math.min(bitmap.getWidth(), bitmap.getHeight());

        Bitmap output = Bitmap.createBitmap(size,
                size, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        BitmapShader shader;
        shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP,
                Shader.TileMode.CLAMP);

        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setShader(shader);
        paint.setAlpha(254);

        RectF rect = new RectF(0, 0, size, size);
        int radius = size / 2;
        canvas.drawRoundRect(rect, radius, radius, paint);
        return output;
    }
}

I came up with that solution, but I didn't like it, because the image loses its quality:
public class UserActivity extends AppCompatActivity {

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

        toolbar = (Toolbar) findViewById(R.id.toolbar_user);
        camera = (ImageView) findViewById(R.id.camera);
        fechar = (TextView) findViewById(R.id.fechar);
        editar = (TextView) findViewById(R.id.editar);
        membro = (TextView) findViewById(R.id.membro);
        nome = (TextView) findViewById(R.id.nome_usuario);
        email = (TextView) findViewById(R.id.email_usuario);
        email = (TextView) findViewById(R.id.email_usuario);
        profilePic = (NetworkImageView) findViewById(R.id.foto);
        mImageView = (ImageView) findViewById(R.id.cropped);
        progress_wheel = (ProgressWheel) findViewById(R.id.progress_wheel);

        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder getImageFrom = new AlertDialog.Builder(UserActivity.this);
                getImageFrom.setTitle("Abrir com:");
                final CharSequence[] opsChars = {getResources().getString(R.string.takepic), getResources().getString(R.string.opengallery)};
                getImageFrom.setItems(opsChars, new android.content.DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                            mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                                    "tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));

                            intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);

                            try {
                                intent.putExtra("return-data", true);

                                startActivityForResult(intent, PICK_FROM_CAMERA);
                            } catch (ActivityNotFoundException e) {
                                e.printStackTrace();
                            }
                        } else if (which == 1) {

                            Intent intent = new Intent();

                            intent.setType("image/*");
                            intent.setAction(Intent.ACTION_GET_CONTENT);

                            startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
                        }
                        dialog.dismiss();
                    }
                });
                getImageFrom.show();

            }
        });

        profilePic.setImageUrl(GlobalModel.getPerfil().getIdDaImagem(), imageLoader);
        profilePic.setDefaultImageResId(R.drawable.avatar_);

    }

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

            if (resultCode != RESULT_OK) return;

            switch (requestCode) {
                case PICK_FROM_CAMERA:
                    profilePic.setVisibility(View.GONE);
                    progress_wheel.setVisibility(View.VISIBLE);

                    selectedImagePath = ImageFilePath.getPath(getApplicationContext(), mImageCaptureUri);
                    Log.i("Image File Path", "" + selectedImagePath);
                    mImageCaptureUri = Uri.parse(selectedImagePath);

                    final BitmapFactory.Options option = new BitmapFactory.Options();
                    option.inSampleSize = 8;

                    Bitmap photo = BitmapFactory.decodeFile(mImageCaptureUri.getPath(), option);

                    photo = Bitmap.createScaledBitmap(photo, 200, 200, false);
                    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                    photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

                    File f = new File(Environment.getExternalStorageDirectory()
                            + File.separator + "Imagename.jpg");
                    f.createNewFile();
                    FileOutputStream fo = new FileOutputStream(f);
                    fo.write(bytes.toByteArray());
                    fo.close();

                    previewCapturedImage(f.getAbsolutePath());
                    profilePic.setVisibility(View.VISIBLE);
                    progress_wheel.setVisibility(View.GONE);
                    profilePic.setImageBitmap(BitmapFactory.decodeFile(mImageCaptureUri.getPath()));

                    break;

                case PICK_FROM_FILE:

                    profilePic.setVisibility(View.GONE);
                    progress_wheel.setVisibility(View.VISIBLE);
                    mImageCaptureUri = data.getData();
                    selectedImagePath = ImageFilePath.getPath(getApplicationContext(), mImageCaptureUri);
                    Log.i("Image File Path", "" + selectedImagePath);
                    mImageCaptureUri = Uri.parse(selectedImagePath);

                    final BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 8;

                    Bitmap photoGaleria = BitmapFactory.decodeFile(mImageCaptureUri.getPath(), options);

                    photoGaleria = Bitmap.createScaledBitmap(photoGaleria, 200, 200, false);
                    ByteArrayOutputStream bytesG = new ByteArrayOutputStream();
                    photoGaleria.compress(Bitmap.CompressFormat.JPEG, 100, bytesG);

                    File fG = new File(Environment.getExternalStorageDirectory()
                            + File.separator + "Imagename.jpg");
                    fG.createNewFile();
                    FileOutputStream foG = new FileOutputStream(fG);
                    foG.write(bytesG.toByteArray());
                    foG.close();

                    previewCapturedImage(fG.getAbsolutePath());

                    profilePic.setVisibility(View.VISIBLE);
                    progress_wheel.setVisibility(View.GONE);
                    profilePic.setImageBitmap(BitmapFactory.decodeFile(mImageCaptureUri.getPath()));

                    break;

            }

        } catch (Exception e)

        {
            e.printStackTrace();
        }

    }

    private void previewCapturedImage(String path) {
        try {

            UploadFoto mUpload = new UploadFoto(path);
            mUpload.setEventoListener(new IExecutarTarefa<UploadFoto>() {
                @Override
                public void AntesDeExecutar(UploadFoto tarefa) {

                }

                @Override
                public void DepoisDeExecutar(UploadFoto tarefa) {

                    if (tarefa.getResposta()[0].equals("200")) {
                        GlobalModel.getPerfil().setIdDaImagem(WebService.imgURL + tarefa.getResposta()[1].replace("\"", ""));
                        profilePic.setImageUrl(GlobalModel.getPerfil().getIdDaImagem(), imageLoader);
                    }
                }
            });
            mUpload.execute();

        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        overridePendingTransition(R.anim.animation_back, R.anim.animation_back_leave);
    }

    @Override
    protected void onResume() {
        super.onResume();
        CarregarPerfil mCarrega = new CarregarPerfil();
        mCarrega.execute();
    }
}

XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    xmlns:wheel="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical">

    <include
        android:id="@+id/toolbar_user"
        layout="@layout/toolbaruser" />

    <RelativeLayout
        android:id="@+id/campoImagem"
        android:layout_width="fill_parent"
        android:layout_height="200dp"
        android:layout_below="@+id/toolbar_user"
        android:background="@color/armadillo">

        <com.android.volley.toolbox.NetworkImageView
            android:id="@+id/foto"
            android:layout_width="200dp"
            android:layout_height="fill_parent"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:adjustViewBounds="true"
            android:scaleType="centerCrop"
            android:src="@drawable/user"
            android:visibility="visible" />

        <com.pnikosis.materialishprogress.ProgressWheel
            android:id="@+id/progress_wheel"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_gravity="center"
            android:visibility="gone"
            wheel:matProg_barColor="@color/white"
            wheel:matProg_progressIndeterminate="true"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true" />

        <ImageView
            android:id="@+id/cropped"
            android:layout_width="200dp"
            android:layout_height="fill_parent"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:layout_gravity="center"
            android:visibility="visible"/>

        <ImageView
            android:id="@+id/camera"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:padding="15dp"
            android:src="@drawable/ic_camera" />

        <TextView
            android:id="@+id/Button_crop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:gravity="center"
            android:padding="15dp"
            android:text="Salvar"
            android:textColor="@color/white"
            android:visibility="gone" />

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true">

        <TextView
            android:id="@+id/membro"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:gravity="center"
            android:paddingBottom="10dp"
            android:paddingLeft="10dp"
            android:paddingTop="5dp"
            android:text="Membro Retornar desde Julho de 2015"
            android:textColor="@color/star_dust" />
    </RelativeLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/campoImagem"
        android:layout_marginBottom="30dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="15dp"
        android:gravity="center"
        android:orientation="vertical">

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="left"
            android:paddingBottom="0dp"
            android:paddingLeft="10dp"
            android:paddingRight="0dp"
            android:paddingTop="10dp"
            android:text="Nome"
            android:textColor="@color/star_dust"
            android:textSize="@dimen/text1" />

        <TextView
            android:id="@+id/nome_usuario"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="left"
            android:paddingBottom="0dp"
            android:paddingLeft="10dp"
            android:paddingTop="5dp"
            android:textColor="@color/armadillo"
            android:textSize="@dimen/text1" />

        <TextView
            android:id="@+id/entrar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="left"
            android:paddingLeft="10dp"
            android:paddingTop="10dp"
            android:text="E-mail"
            android:textColor="@color/star_dust"
            android:textSize="@dimen/text1" />

        <TextView
            android:id="@+id/email_usuario"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="left"
            android:paddingBottom="0dp"
            android:paddingLeft="10dp"
            android:paddingTop="5dp"
            android:text="jgvidotto@gmail.com"
            android:textColor="@color/armadillo"
            android:textSize="@dimen/text1" />

    </LinearLayout>

</RelativeLayout>

A: Because you have not posted your Activity calling the Navigation Drawer, so I have used both your CircledNetworkImageView class and built-in NetworkImageView in my project. It works well. Please refer to the following:
CustomNavigationDrawer.java:
public class CustomNavigationDrawer {
    private static ActionBarDrawerToggle sDrawerToggle;

    public static DrawerLayout setUpDrawer(final Context context) {
        final Activity activity = ((Activity) context);
        DrawerLayout sDrawerLayout = (DrawerLayout) activity.findViewById(R.id.drawer_layout);

        if (activity.getActionBar() != null) {
            activity.getActionBar().setDisplayHomeAsUpEnabled(true);
            activity.getActionBar().setHomeButtonEnabled(true);
        }

        sDrawerToggle = new ActionBarDrawerToggle(
                activity,
                sDrawerLayout,
                R.drawable.ic_drawer,
                R.string.drawer_open,
                R.string.drawer_close
        ) {
            public void onDrawerClosed(View view) {
                activity.invalidateOptionsMenu();
                syncState();
            }
            public void onDrawerOpened(View drawerView) {
                activity.invalidateOptionsMenu();
                syncState();
            }
        };

        sDrawerLayout.setDrawerListener(sDrawerToggle);
        return sDrawerLayout;
    }

    public static void syncState() {
        sDrawerToggle.syncState();
    }

    public static void onConfigurationChanged(Configuration newConfig) {
        sDrawerToggle.onConfigurationChanged(newConfig);
    }
}

MainActivity.java:
public class MainActivity extends Activity {
    final Context mContext = this;
    final String mUrl = "http://.../getimage";
    NetworkImageView mNetworkImageView;
    CircledNetworkImageView mCircledNetworkImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CustomNavigationDrawer.setUpDrawer(this);
        mNetworkImageView = (NetworkImageView) findViewById(R.id.networkImageView);
        mNetworkImageView.setImageUrl(mUrl, VolleySingleton.getInstance(mContext).getImageLoader());
        mCircledNetworkImageView = (CircledNetworkImageView) findViewById(R.id.circleImageView);
        mCircledNetworkImageView.setImageUrl(mUrl, VolleySingleton.getInstance(mContext).getImageLoader());
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        CustomNavigationDrawer.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        CustomNavigationDrawer.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
}

activity_main.xml:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin">

        <com.android.volley.toolbox.NetworkImageView
            android:id="@+id/networkImageView"
            android:layout_width="300dp"
            android:layout_height="wrap_content" />

        <com.example.networkimageview.CircledNetworkImageView
            android:id="@+id/circleImageView"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/networkImageView" />
    </RelativeLayout>
</android.support.v4.widget.DrawerLayout>

You can create a new sample project and use my sample code. Hope this helps!

A: if (width == 0 && height == 0 && !isFullyWrapContent) {
I guess the first you loadImage code will return because of this condition. The width and height is equal to 0 before the whole UI load success. log before this condition return.  Hope this can help you.


text:
Q: Using Regex.Split to remove anything non numeric and splitting on - I'm not sure why but for some reason The Regex Split method is going over my head. I'm trying to look through tutorials for what I need and can't seem to find anything.
I simply am reading an excel doc and want to format a string such as $145,000-$179,999 to give me two strings. 145000 and 179999. At the same time I'd like to prune a string such as '$180,000-Limit to simply 180000.
var loanLimits = Regex.Matches(Result.Rows[row + 2 + i][column].ToString(), @"\d+");

The above code seems to chop '$145,000-$179,999 up into 4 parts: 145, 000, 179, 999. Any ideas on how to achieve what I'm asking?

A: Regular expressions match exactly character by character (there's no knowledge of the concept of a "number" or a "word" in regular expressions - you have to define that yourself in your expression).  The expression you are using, \d+, uses the character class \d, which means any digit 0-9 (and + means match one or more).  So in the expression $145,000, notice that the part you are looking for is not just composed of digits; it also includes commas.  So the regular expression finds every continuous group of characters that matches your regular expression, which are the four groups of numbers.
There are a couple of ways to approach the problem.

*

*Include , in your regular expression, so (\d|,)+, which means match as many characters in a row that are either a digit or a comma.  There will be two matches: 145,000 and 179,999, from which you can further remove the commas with myStr.Replace(",", ""). (DEMO)

*Do as you say in the title, and remove all non-numeric characters.  So you could use Regex.Replace with the expression [^\d-]+ - which means match anything that is not a digit or a hyphen - and then replace those with "".  Then the result would be 145000-179999, which you can split with a simple non-regular-expression split, myStr.Split('-'), to get your two parts. (DEMO)

Note that for your second example ($180,000-Limit), you'll need an extra check to count the number of results returned from Match in the first example, and Split in the second example to determine whether there were two numbers in the range, or only a single number.

A: you can try to treat each string separately by spiting it based on - and extraction only numbers from it
 ArrayList mystrings = new ArrayList();
 List<string> myList = Result.Rows[row + 2 + i][column].ToString().Split('-').ToList();

 foreach(var item in myList)
 {

     string result = Regex.Replace(item, @"[^\d]", "");
     mystrings.Add(result);
 }

A: An alternative to using RegEx is to use the built in string and char methods in the DotNet framework. Assuming the input string will always have a single hypen:
string input = "$145,000-$179,999";

var split = input.Split( '-' )
        .Select( x => string.Join( "", x.Where( char.IsLetterOrDigit ) ) )
        .ToList();

string first = split.First(); //145000
string second = split.Last(); //179999

*

*first you split the string using the standard Split method

*then you create a new string by selectively taking only Letters or Digits from each item in the collection: x.Where...

*then you join the string using the standard Join method

*finally, take the first and last item in the collection for your 2 strings.


text:
Q: Pixel exact string measurement I try to compute the exact pixel size of a given text (e.g. to InvalidateRect or create a bitmap of sufficient size later on). I do not have a device context at the moment of measurement, so I have to resort to a memory device context.
I found that DrawText with DT_CALCRECT apparently returns the "advance width" and not the actual width occupied by pixels when drawn. Compensating this using GetCharABCWidths (see here for a explanation of ABC widths) is at best another approximation since e.g. possibly the ABC widths of the second glyph is decisive if the first glyph is very narrow (even it it "seems to give good results" for my example cases), not to mention font smoothing.
Thus, I tried using SetBoundsRect/GetBoundsRect:
auto MeasureTest = [](int x, int y) {
    auto dc = CreateCompatibleDC(nullptr);
    SetBoundsRect(dc, nullptr, DCB_ENABLE | DCB_RESET);
    auto const text = L"Test";
    RECT rect{x, y, x, y};
    DrawText(dc, text, 4, &rect, DT_NOCLIP);
    GetBoundsRect(dc, &rect, 0);
    return rect;
};

(Please ignore memory leaks. I verified that all those functions return what I would expect from what I have read in MSDN.)
Using this routine, I get the following results:
MeasureTest(0, 0);       // returns (0,0)-(1,1); reasonable (dc holds a 1x1 bitmap)

As noted, this seemed reasonable since the dc contains a 1x1 bitmap initially. However, the following two calls indicate that at least some measurement has been done:
MeasureTest(-100, -100); // returns (0,0)-(-72,-84), i.e. an empty rect
MeasureTest(100, 100);   // returns (100,100)-(1,1), i.e. an empty rect

I tried selecting a sufficiently large bitmap (1000x1000 px) into the device context before drawing, which apparently gave correct results. But this, of course, raises the initial question: how many pixels does the string occupy?
Is there a reliable way to determine the exact pixel size for a string?


text:
Q: Does warping of space under relativity suggest displacement The picture I see in documentaries is a flat piece of cloth depressed downward by the large mass, say a star, and objects falling into the depression. But this is one side of the star.So if I were to look on the other side of the star, there would be another depression going on the opposite side. So, these two depressions should cancel right?
Seems to me in this case the Newtonian concept of gravity being influenced by a point in the centre of the larger object ... seems more intuitive in this scenario

A: These pictures are misleading, since the rubber cloth is 2 dimensional it shall provide a picture how curved space works like attraction, but in reality the three dimensional space is curved, but you can not really picture this. The tree dim curvature goes in all three direction, so this picture is wrong.