Passing class via delegate : property not updated

Question: don't understand why I didn't get my class property updated (imageData property).
simple example, 2 view controllers embed in navigation controller (important for me):
first one : ViewController with an imageView and a button to the second view controller (via segue)
class ViewController: UIViewController, choosePicVCDelegate {

  @IBOutlet weak var imageView: UIImageView!

  override func viewDidLoad() {
    super.viewDidLoad()
    self.imageView.clipsToBounds = true
  }

  func goodPic(vc: choosePicViewController) {

    if let data = vc.imageData {
      let image = UIImage(data: data)
      self.imageView.image = image
    }
    vc.navigationController?.popViewControllerAnimated(true)
  }

  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let vc = segue.destinationViewController as! choosePicViewController
    vc.delegate = self
  }

}

second one : choosePicViewController with an imagePicker to choose the image to display in the first ViewController. 2 buttons: one to choose the image, the other to go back to the first view controller with the delegate..
protocol choosePicVCDelegate {
  func goodPic(vc: choosePicViewController)
}

class choosePicViewController: UIViewController {

  var delegate: choosePicVCDelegate?
  let imagePicker = UIImagePickerController()
  var imageData: NSData?

  @IBAction func back(sender: UIButton) {
    delegate?.goodPic(self)
  }

  @IBAction func coverPick(sender: UIButton) {
    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
      imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary;
      imagePicker.allowsEditing = false
      self.presentViewController(imagePicker, animated: true, completion: nil)
    }
  }

}

extension choosePicViewController: UIImagePickerControllerDelegate {

  func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
    self.imageData = UIImageJPEGRepresentation(image, 1.0)
    dismissViewControllerAnimated(true, completion: nil)
  }

  func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    dismissViewControllerAnimated(true, completion: nil)
  }

}

always got nil from imageData property, don't understand why.
Answer: I think the problem is your extension, i didn't understand why use extension in this case, whatever. Try do it.
You need set delegate from imagePicker.delegate = self, because with this you can listener the UIImagePickerController delegate. I believe with this you resolve.
protocol choosePicVCDelegate {
    func goodPic(vc: choosePicViewController)
}

class choosePicViewController: UIViewController, UIImagePickerControllerDelegate {

    var delegate: choosePicVCDelegate?
    let imagePicker = UIImagePickerController()
    var imageData: NSData?

    override func viewWillAppear(animated: Bool) {
        imagePicker.delegate = self;
    }

    override func viewDidDisappear(animated: Bool) {
        imagePicker.delegate = nil;
    }

    @IBAction func back(sender: UIButton) {
        delegate?.goodPic(self)
    }

    @IBAction func coverPick(sender: UIButton) {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary;
            imagePicker.allowsEditing = false
            self.presentViewController(imagePicker, animated: true, completion: nil)
        }
    }

    //Delegates from UIImagePickerControllerDelegate
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {

    }

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
        if let img = info[UIImagePickerControllerOriginalImage] as? UIImage{
            self.imageData = UIImageJPEGRepresentation(img, 1.0)
            delegate?.goodPic(self)
            dismissViewControllerAnimated(true, completion: nil)
        }
    }
}

Hope help you!
Comment: you were right, just miss the  imagePicker.delegate = self in viewDidLoad() thanks !


How to execute JS Code when Outlook is started with Web Add Ins?

Question: I want to make a async request to my server every time a user of my plugin starts outlook (or at least before they open an email).
I have a web Add In with a function file. This file is called whenever a user press a button for this addin. The function file is only loaded after a button (of my plugin) press.
Comment: It could be much difference between starting outlook and opening an email. The former is one-time thing, while the later happens every time when an email is opened. In what scenario, you need this feature? Also, when you say "open an email", does it mean opening an existing email or composing a new mail?
Comment: Currently the feature, run an add-in on Outlook load, you requested, is not a part of the product. We track Outlook add-in feature requests on our user-voice page. Please add your request there. Feature requests on user-voice are considered when we go through our planning process.

https://officespdev.uservoice.com/forums/224641-general/category/131778-outlook-add-ins
Comment: That's unclear for me why don't you want to make this request as your web add-in is initialized.
Comment: As I looked at the network tab: the function file is loaded after I click the first button of my plugin. Is there another option to execute code on load?
Comment: Outlook JS add-ins are tight to mail item and loaded by user action (button click) or automatically when add-in implements "pinnable" interface. This still has to be initiated by user first time add-in loads. There is no option to load the add-in on Outlook start.
Comment: @OutlookAdd-insTeam-MSFT The Plugin is only used by my company. It works good on writing mails, but it should update the personal IP on a server when outlook starts. My current idea is to use a VSTO Add In for this. Or trigger it before reading every message (that would be a bit much)
Answer: Try this:
<code>// This function is called when Office.js is ready to start your Add-in
Office.initialize = function ()
{
   $(document).ready(function ()
   {
      //call your function here
</code>
Comment: Thank you Victor for your Answer. This is only triggered after the file is loaded. And the file is only loaded, after a user clicks a button in the plugin.
Comment: Sorry I don't understand. Are you saying that after clicking on the icon of your add-in your code does not run? As far as I know Office.initialize procedure executes after starting the add-in.
Comment: Sry for the missunderstanding. My addin code (function.js) is only loaded (over network) when i click a button of this plugin (as i introduced in the manifest). the code you posted is not loaded when office is started.
Comment: If you interested only in add-in for Outlook (not for OWA) then create a COM add-in (VSTO or not - it doesn't matter).
Answer: This is not possible with WebAddIns as the Outlook Add-Ins Teams said in the comments under the question.
One solution is to create a VSTO AddIn and make the request there.


How to get data attribute from option in multiple select?

Question: How can I get list of selected values from multiple select?
I can get value only(
I need to get attr values ('data-name')
https://playcode.io/301780?tabs=console&index.html&output

<select name="payment" style="width: 246px;" required multiple="multiple" class="select2" id="id_payment">
  <option value="3" data-name="blago">blago</option>
  <option value="4" data-name="usd" selected>usd</option>
  <option value="5" data-name="uah" selected>uah</option>
  <option value="2" data-name="btc">btc</option>
</select>

Comment: why not just set name as value?
Answer: You can use map to loop thru the selected options and use data to get the data-name values.

var result = $("#id_payment option:selected").map(function() {
  return $(this).data("name");
}).get();

console.log(result);

<select name="payment" style="width: 246px;" required multiple="multiple" class="select2" id="id_payment">
  <option value="3" data-name="blago">blago</option>
  <option value="4" data-name="usd" selected>usd</option>
  <option value="5" data-name="uah" selected>uah</option>
  <option value="2" data-name="btc">btc</option>
</select>
Answer: Use each to traverse the items and collect them into an array, like:
var dataNames = [];
$("#id_payment > option[selected]").each(function() {
    dataNames.push($(this).data("name"));
});

Answer: You can use this code
$("#id_payment option:selected").each(function(index, item){

         let name = $(item).data('name');
         //alert(name)
         nameselected.push(name);
         console.log(name);
   })

$(document).ready(function () {
var vals = $('#id_payment').val()
var paymentList = []
var nameselected = []

if (vals) {
    for (var i = 0; i < vals.length; i++) {
        console.log(vals[i])
        paymentList.push($(vals[i]).selector)
    }
  }

   $("#id_payment option:selected").each(function(index, item){

         let name = $(item).data('name');
         //alert(name)
         nameselected.push(name);
         console.log(name);
   })
})

<select name="payment" style="width: 246px;" required multiple="multiple" class="select2" id="id_payment">
        <option value="3" data-name="blago">blago</option>
        <option value="4" data-name="usd" selected>usd</option>
        <option value="5" data-name="uah" selected>uah</option>
        <option value="2" data-name="btc">btc</option>
</select>
Answer: You need to use jquery .each() function.
Example:

<select name="payment" style="width: 246px;" required multiple="multiple" class="select2" id="id_payment">
  <option value="3" data-name="blago">blago</option>
  <option value="4" data-name="usd" selected>usd</option>
  <option value="5" data-name="uah" selected>uah</option>
  <option value="2" data-name="btc">btc</option>
</select>

It is set up so when you make more selections, it still logs all of the selected items


ElasticSearch Regular Expression

Question: Trying to apply a regular expression to the below using ElasticSearch 1.1.1:
127.0.0.1:35946 [27/Jul/2014:15:18:54.097] api.ch.gov.uk-d9928e1_18001 api.xx.yy.zz-d9928e1_18001/api.xx.yy.zz-d9928e1-1 0/0/0/65/15066 200 1956 - - ---- 2/1/1/0/0 0/0 "GET /company/12345678 HTTP/1.1"

Starting with "127.0.0.1" is fine, but adding anything else to the regexp stops it matching, even adding .+. I thought "127.0.0.1".+?GET /company/\d+ would work.
What am I missing?
Comment: what do you want to match exactly?
Comment: Not a generic regexp question, but specifically ES regexp. I really want to know why, in ES, `START` but not `START.+` match against `START MORE`. According to the docs, that won't work. I'm sure I'm doing something wrong, hope someone has had a similar problem.
Comment: sorry, never heard about elastic search before
Answer: Just try the below regex to match from 127.0.0.1 to /company/12345678,
127\.0\.0\.1.+?GET \/company\/\d+

DEMO
To match the whole string,
127\.0\.0\.1.+?GET \/company\/\d+.*

Answer: from the doc

Lucene's patterns are always anchored. The pattern provided must match
  the entire string.

So your pattern will only match if you match it fully like you do with ^ and $ anchors
Use this regex if you want to match :
127.0.0.1.+?GET \/company\/\d+\s+\w+\/\d+\.\d+\"

Comment: That's what I thought, but it's not happening that way.
What could I be doing wrong?

ElasticSearch Regular Expression


How do I change the close/maximise/minimise button sizes in 13.10?

Question: How could I change the button size for the window controls. I'm using a touch screen and I'm having difficulty hitting the right one. I've tried adjusting fonts but this does not help.
Any ideas folks?
Answer: You could use gnome-color-chooser
Answer: For this one - I actually use gnome-tweak-tool for that one.
sudo apt-get install -y gnome-tweak-tool

This will enable you to customize almost everything to your preference.  There are another two apps that would give you more options.
unity-tweak-tool
ubuntu-tweak


Minimum cut over all pairs of vertices in directed and strongly connected graph

Question: I have a graph G that is a directed and strongly connected graph, and I am asked to find a minimum cut over all pairs of vertices, meaning for every pair of S and T in the graph. This should be done in O(m2 × n2) time.
The best I came up with was to consider all vertices to be S, and for each S consider all other vertices to be T, and for each of those run the Ford-Fulkerson algorithm, and then find the min cut. But If I am not mistaken, this algorthm will have complexity of O(m2 × n2 × C).
How can I do this task in O(m2 × n2) time? Is it even possible ?
Comment: Thank you for the edit m69, now we wait for an answer :)
Comment: CS 180 is a struggle
Comment: Hehe, after 5 hours of trial error, I feel like this algorithm actually cannot be done in the required time complexity.
Comment: Are you saying that O(m^2 × n^2 × C) = O(m^2 × n^2) ? C is not a constant, it is the max flow value.
Comment: I think I made a mistake in my complexity and final complexity is O(n^2 x m x C) instead of O(n^2 x m^2 x C). But still, this is not the desired complexity.
Answer: Notation:
m: number of edges n: number of nodes c_max: maximal single edge capacityC: max flow value.
Dinic's algorithm in combination with can be employed to solve the task at hand. It runs in O(m * n^2). The brute-force approach of O(n^2) min cut computations then yield a total of O(m * n^2 * n^2), which is the desired result for m = O(n^2). For sparse graphs with m = o(n^2) I couldn't find a definite result; however,  for m = O(n) this paper gives a result of O(n^2 + n^4 * log n) = O(m^2 * n^2 * log n).
There are several algorithms to compute the min cut ( or, equivalently, the max flow ) in a directed graph whose complexities stays below O( m * n^2 ). Wilf H.S., Algorithms and Complexity, 1st  ed. has a survey on page 65. The most accessible algorithm is probably Dinic (O(m * n^2)).
Though at first glance the Ford-Fulkerson algorithm has a superior time complexity of O( m * C ), it sports some serious drawbacks:

The time complexity is only valid for integer edge capacities. In fact, with irrational edge capacities, the algorithm is not even guaranteed to terminate at all nor to converge to the maximum flow ( see this paper for a provably minimal counterexample; this paper is also referenced in the wikipedia article ).
The time complexity depends on the value of the maximum flow.

Significance of the flow value
The max flow value C is not necessarily a function of the number of nodes and edges. Even if it is (which depends on the graph topology), the following observation holds: the maximum possible flow value in any graph is the number of edges times the maximum edge capacity, m * c_max which amounts to O(m).
That turns the complexity of Ford-Fulkerson for integer edge capacities to O(m^2), unless the maximum capacity of a single edge is a function of the number of nodes or edges in the graph, which is a non-standard assumption.
For other algorithms there is no effect since its execution hinges on the graph topology and the edge capacities relative to each other, but not on the absolute edge capacities (and, by consequence, is no function of the max flow value either).


ActivityMonitor on Intent filter ACTION_SENDTO not hit

Question: I am writing a JUnit test for an activity that launches the default mail client of the device. I want to validate that the "Send To" activity is started and then send a click event to the "Send" button.
I did set up an ActivityMonitor with an intent filter in order to get a reference on the "Send To" activity. I can see the send mail activity appear while running the test but unfortunately the monitor never gets hit.
Here is the unit test code that attempts to find the "Send To" activity:
// register activity monitor for the send mail activity
Instrumentation instrumentation = getInstrumentation();
IntentFilter filter = new IntentFilter(Intent.ACTION_SENDTO);
ActivityMonitor monitor = instrumentation.addMonitor(filter, null, false);

// click on the "Send Feedback" button (use Robotium here)
solo.clickOnButton(0);

// wait for the send mail activity to start
Activity currentActivity = instrumentation.waitForMonitorWithTimeout(monitor, 5000);
assertNotNull(currentActivity);

And here is how the "Send To" activity is started in the application:
Uri uri = Uri.parse("mailto:firstname.lastname@example.com");
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
i.putExtra(Intent.EXTRA_SUBJECT, "Message Title");
i.putExtra(Intent.EXTRA_TEXT, "Hello");
startActivity(i);

Is the intent filter incorrectly set? Or is it impossible to monitor activities that are not defined in the project?
Thanks for your help.
Comment: I have the same problem, I suppose that it is not possible to catch the intent at issue because there is no "real" activity started, in fact the list of the active activities after launching your intent is empty, but have you managed to solve this issue?
Comment: Unfortunatly no. I never solved that issue.
Answer: I had issues with this as well and it turns out that the ActivityMonitor is not working, because Robotium's solo installs its own monitor. This monitor catches all intents, so your custom monitor is never called.
What I ended up doing was first removing the solo monitor, insert my own and and then re-add the solo monitor, so your monitor is matched first. Your code would then look something like this:
// register activity monitor for the send mail activity
Instrumentation instrumentation = getInstrumentation();
IntentFilter filter = new IntentFilter(Intent.ACTION_SENDTO);
ActivityMonitor monitor = new ActivityMonitor(filter, null, false);
ActivityMonitor soloMonitor = solo.getActivityMonitor();

// Remove the solo monitor, so your monitor is first on the list.
instrumentation.removeMonitor(soloMonitor);
// add your own monitor.
instrumentation.addMonitor(monitor);
// Re-add the solo monitor
instrumentation.addMonitor(soloMonitor);

// click on the "Send Feedback" button (use Robotium here)
solo.clickOnButton(0);

// wait for the send mail activity to start
Activity currentActivity = instrumentation.waitForMonitorWithTimeout(monitor, 5000);
assertNotNull(currentActivity);

As a side note: when starting another activity (the mail application), you lose control of the testing environment, so it would be useful to make the monitor blocking (i.e new ActivityMonitor(filter, null, true);)
Answer: I had the same issue with my tests and this worked for me.
At this point your test is working fine, but your monitor doesn't know which data to expect, so your intent filter is not catching anything.
// register activity monitor for the send mail activity
Instrumentation instrumentation = getInstrumentation();
IntentFilter filter = new IntentFilter(Intent.ACTION_SENDTO);

//Here you just need to say to your intent filter what exactly to look for
filter.addDataType(CommonDataKinds.Email.CONTENT_TYPE);

ActivityMonitor monitor = instrumentation.addMonitor(filter, null, true);
// click on the "Send Feedback" button (use Robotium here)
solo.clickOnButton(0);
// wait for the send mail activity to start
Activity currentActivity = instrumentation.waitForMonitorWithTimeout(monitor, 5000);
assertNotNull(currentActivity);

if you do this for sending sms, that line would be:
filter.addDataScheme(Constants.SCHEME_SMS);


Android ListView with active and inactive entries

Question: I need a listview that has several clickable entries. However, some of them are inactive until an asynctask releases them. How should I best do this? First I thought of having a seperate ArrayList with booleans but that seems to be somehow cheap. Is there a way to expand the StableArrayAdapter?
This is my current adapter
import android.content.Context;
import android.widget.ArrayAdapter;

import java.util.HashMap;
import java.util.List;

public class StableArrayAdapter extends ArrayAdapter<String> {

        HashMap<String, Integer> mIdMap = new HashMap<>();

        public StableArrayAdapter(Context context, int textViewResourceId,
                                  List<String> objects) {
            super(context, textViewResourceId, objects);
            for (int i = 0; i < objects.size(); ++i) {
                mIdMap.put(objects.get(i), i);
            }
        }

        @Override
        public long getItemId(int position) {
            String item = getItem(position);
            return mIdMap.get(item);
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }
}

Comment: I just found this here: http://stackoverflow.com/questions/6744863/disable-listview-items-with-selector-and-isenabled
Answer: Override isEnabled() in your adapter. You can return false for the items that should not be clickable at first. Then when your AsyncTask completes, in onPostExecute() you can call some other method you define on your adapter to enable the items, from which point on your isEnabled() implementation should return true for those items.
Answer: Add this method to your adapter
@Override
public boolean isEnabled (int position) {
    // Add your logic here. Return true for the items you
    //want to be enable and false for those you want disable.
}

Usage (From android documentation): Returns true if the item at the specified position is not a separator. (A separator is a non-selectable, non-clickable item). The result is unspecified if position is invalid. An ArrayIndexOutOfBoundsException should be thrown in that case for fast failure.
Answer: I had similar requirement. you can use SparseBooleanArrays to represent the state of each list item whether it has to be active/ inactive.
checkout http://developer.android.com/reference/android/util/SparseBooleanArray.html
Hope this helps.
Answer: Create a model class for the staus of each item in your list and then manipulate it in your getView . Like Below ..
public class StatusBean{

private boolean isNameActive;
private boolean isOtherFieldActive;

public String isnameActive() {
    return isNameActive;
}
public void setNameActive(boolean isNameActive) {
    this.isNameActive=isNameActive;
}
public boolean isOtherFieldActive;() {
    return isOtherFieldActive;
}
public void setOtherFieldActive;(boolean bool) {
    this.isOtherFieldActive = isOtherFieldActive;
}

}
And then set these fields to active state in when your asyncTask is finished. And call
adapter.notifyDataSetChanged();

There you are done! let me know if you face any problem in it


Java executor with no ability to queue tasks

Question: I need an Java executor that rejects tasks if some other task is processing. I guess it's not possible to get manipulating the working queue size.
Someone might wonder why I need an executor with such characteristic in the first place. I need an ability to easily change the policy and allow non-zero queue size.
Any ideas?
Comment: So your executor should only execute one single task at all?
Comment: One at a given time. Also, if execution is pending it should reject other submissions.
Answer: Use a ThreadPoolExecutor with a SynchronousQueue (copied from this answer).
It appears to work:
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class SingleTaskExecutor {

public static void main(String[] args) {

    try {
        new SingleTaskExecutor().runTest();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void runTest() throws Exception {

    ThreadPoolExecutor tp = new ThreadPoolExecutor(1, 1,
            60L, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>());

    tp.setRejectedExecutionHandler(new RejectedTaskHandler());

    final Semaphore oneTaskDone = new Semaphore(0);
    tp.execute(new Runnable() {
        @Override public void run() {
            System.out.println("Sleeping");
            try { Thread.sleep(300); } catch (Exception e) { e.printStackTrace();}
            System.out.println("Done sleeping");
            oneTaskDone.release();
        }
    });
    tp.execute(new Runnable() {
        @Override public void run() { System.out.println("Never happends"); }
        @Override public String toString() { return "Rejected Runnable"; }
    });
    oneTaskDone.acquire();
    tp.execute(new Runnable() {
        @Override public void run() { System.out.println("Running"); }
    });
    tp.shutdown();
    tp.awaitTermination(100, TimeUnit.MILLISECONDS);
    System.out.println("Finished");
}

static class RejectedTaskHandler implements RejectedExecutionHandler {

    @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        System.out.println("Task rejected: " + r);
    }

}

}

Answer: From your statement

One at a given time. Also, if execution is pending it should reject other submissions.

I am concluding that
Processing only one task at a time and rejecting other tasks during current task processing is your requirement.  In this case, below code should do the job.
BlockingQueue queue = new ArrayBlockingQueue(1);
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 10, TimeUnit.SECONDS, queue,
ThreadPoolExecutor.DiscardPolicy);

// Submit Your callable task
executor.submit(yourCallableTask);

Comment: I think this is incorrect. It will execute one task, but allow you to queue one task as well while the first one is executing.  It should be a `SynchronousQueue`.
Answer: Use ThreadPoolExecutor. Before submiting task to executor call getActiveCount() and check if it equals pool size (meaning all threads are active). If it does, just don't submit the task.
Comment: I'd have to make getActiveCount() and submitting atomic. Is is possible without such locking?
Comment: I don't think it is possible without locking. Even if this kind of functionality was already implemented it would still use locking (to ensure thread-safe behavior). Use synchronized block for getActiveCount() + submit and you should be fine.


Capture information about both the file and the regexp found

Question: I have a directory full of files that contain numbers I want to capture. I also want to know which numbers come from which particular files. Right now I'm just running grep, which outputs something like:
grep ./* -e 'expression'
./file1: expression numberA
./file1: expression numberB
./file1: expression numberA
./file2: expression numberC numberD
...

What I want is to extract a piece of the filenames (in this example, 1 for file1), and also all of the numbers that appear after my expression.
While I'd prefer to just do everything in bash, any solution is welcome.
EDIT: To be clear, I want as output the following:
file1:
numberA
numberB
file2:
numberC
numberD
...

I've also edited the earlier portion (./file1: expression numberA). Sorry for not being clear before.
Comment: Well, you can grep the grep output :)
Comment: That just gives me the same thing, since my item of interest is on every line and it prints every matching line...unless I'm misunderstanding
Comment: I don't mean grep by the same pattern, of course. Rather, by something that would only keep the part of the filename and the number. But in case _I_ am misunderstanding, I'd suggest you to update the question with the desired output. P.S. In fact, you could get rid of the `expression` in the output by adjusting the current grep command, but the file names will still be printed unchanged, obviously
Comment: If you could give a concrete example of input and output that would make things clearer. Are you interested in grouping all the numbers from a given file on one line? Or do you just want the file number + number pairs without all the extra text? Also, is `expression` a static string?
Answer: Try this:
grep -e 'expression' * | perl -pe 's/^(.*?)(\d+)(:.*)$/$1$2$3 $2/'

This should produce all input lines. If the filename portion of the input line ends with a number, that number should be appended to the input line.
$1, $2 and $3 are backreferences to the 3 subexpressions (those parts of the regular expression in parentheses).
The commandline switch -e instructs the Perl interpreter to execute the given expression. -p loops on the input and prints $_.
However, since you also want all numbers from after your match, you probably need something more complex:
grep -e 'expression' * | perl -ne '
  chomp;
  ($a,$b) = split ":";
  $a =~ s/.*(\d+)$/$1/;
  $b =~ s/.*expression(.*)/$1/;
  $b =~ s/[^\d]+/ /g;
  print "$_ $a $b\n";
'

-n does the same as -p, only without implicitly printing $_.
Edit: After reading your updated requirements I think you may be better off with an all-Perl solution.
#!/usr/bin/env perl

use strict;
use warnings;

foreach (@ARGV) {
  my $file = $_;
  open FILE, "<$file" or die "Can't open file $file.";
  my $first = 1;
  foreach (<FILE>) {
    if (m/expression(.*)/) {
      my $values = $1;
      if ($first) {
        print "$file:\n";
        $first = 0;
      }
      $values =~ s/(^ +| +$)//g;
      $values =~ s/ +/\n/g;
      print "$values\n";
    }
  }
  close FILE;
}

Comment: This gives the same output that I am getting currently. Forgive my lack of experience, but in perl $1, $2, etc are variables, right? What are they doing? Also what is the -pe flag?  Thanks!
Answer: If you just want to see the file number and numbers you could use something like:
find . -exec sh -c "echo -n \;{}::;grep -e 'expression' {}" \; | perl -pe 's/^.*(\d+)::/File \1:\n/' | perl -pe 's/\D*(\d+)$/\1/'

Note: this would break if your expression contains ::number (used as a delimiter, can be changed). Prints last file name if no matches are found.
Would produce:
File 2:
878
File 3:
199
File 4:
123
234
9
0

Example file2:
foo 123
bar 123
expression 878
lorem ipsum

If you just want the number pairs (file number + number) then you could try:
grep ./* -e 'expression' | perl -pe 's/^.*?(\d+):.*?(\d+)$/\1 \2/'

Output:
2 878
3 199
4 123
4 234
4 9
4 0

As mentioned in my comment, your questions is somewhat unclear on exactly what you want. Providing some examples would be beneficial.
Comment: Sorry, but I do not like this solution! Dozens of processes started for such a simple thing! Find, echo, grep, perl, sh! Lot of `fork`s and `exec`s. It can be solved starting one process!
Answer: Thanks to the two who answered - with the information that both of you gave me, I was able to figure out a perfect solution:
grep -i expression ./* | perl -pe 's/.*(\d+).*:.*(\d+)/$1 $2/' | sort | uniq

This gives as output:
1 numberA
1 numberB
2 numberC numberD

Comment: Four processes used! It seems too much for me... If perl is used, put everything in it!
Answer: I think grep is not needed in this case. Awk or perl needed to use to accumulate data, so they can look for the expression in the file. Here is an awk example:
awk '/expression/ {f[FILENAME]; for(i=2;i<=NF;++i) v[FILENAME,$i]}
END {for(i in f) {print i":"; for(j in v) if(sub("^"i SUBSEP,"",j))print j}}' ./*

Output
file1:
numberB
numberA
file2:
numberD
numberC


How to abstract network model fetching

Question: Instead of putting network model loading in every controller, I'm trying to abstract it in only one controller ModelLoader
Here is what I came up with so far:
protocol ModelLoaderDelegate: class {
    func didFetch(model: Any)
    func modelFailedToFetch(errorMessage: String)
}

final class ModelLoader<ModelType> {

    let api: API
    weak var delegate: ModelLoaderDelegate?
    private let client = dependencies.client

    init(api: API) {
        self.api = api
    }

    func fetchModel() {
        client.performRequest(api: api, decodeTo: ModelType.self, completion: { result in
            switch result {
            case .success(let value):
                self.delegate?.didFetch(model: value)
            case .failure(let error):
                self.delegate?.modelFailedToFetch(errorMessage: error.localizedDescription)
            }
        })
    }
}

The one thing I'm not able to do until now is to replace Any in the didFetch method of the ModelLoaderDelegate to be a generic-like parameter.
I tried to do it like this:
func didFetch<T>(info: T)

but in the implementer of the delegate:
func didFetch<T>(info: T) {
 // I need a concerete type here not a generic
}

Couldn't find another approach.
Comment: So, you want to use multiple instances of `ModelLoader` with one instance of `delegate`?
Comment: @Kamran No. Multiple of both.
Answer: Instead to do this via delegate, you can make the logic by closures:
final class ModelLoader<ModelType> {

    let api: API
    private let client = dependencies.client

    init(api: API) {
        self.api = api
    }

    func fetchModel<ModelType>(completion: @escaping (Result<ModelType, Error>) -> ()) {
        client.performRequest(api: api, decodeTo: ModelType.self, completion: { result in
            switch result {
            case .success(let value):
                completion(.success(value))
            case .failure(let error):
                completion(.failure(error))
            }
        })
    }
}

I think with this approach will be much easier to handle response :)
Comment: Thanks. It's a good approach, but I don't think it's worth it to just move the result handling from the modelLoader to a viewController.

How to abstract network model fetching


Showing that a matrix is a orthogonal projector

Question: How do I show $QQ^T$ as an orthogonal projector? Do I take the dot product? I'm not sure how to answer this question
Suppose that $Q$ is an $n$ x $k$ matrix whose columns form an orthonormal basis for a subspace $S$ of $R^n$. Show that $QQ^T$ is an orthogonal projector onto $S$
Answer: As should be known to anyone faced with such an exercise, the matrix $P=QQ^T$ represents an orthogonal projection if and only if
$P^2=P$ and $P$ is self-adjoint. It is easy to check that $P$ is self-adjoint because
$$P^T=(QQ^T)^T=(Q^T)^TQ^T=QQ^T=P$$
What about $P^2$?
$$P^2=QQ^TQQ^T$$
What can we say about the middle part, $Q^TQ$? We can say that it is the $k\times k$ identity matrix, because the columns of $Q$ are orthonormal.
It follows that
$$P^2=Q\times I_k\times Q^T=QQ^T=P$$
and we are done.


ASP .NET VS2010 Contents of an object in a table

Question: What's the best way to get the contents of objects into tables in ASP.NET?
I've created an OnButtonClick event on a page, which then goes and fetches an object with a bunch of variables and one list, how can I get those variables and list to most easily render in a (initially hidden) table?
Should I use this guide? Table Class or is there some other way to do it?
Comment: Why not use [GridView](http://msdn.microsoft.com/en-us/library/aa479339.aspx)
Comment: I've seen this too, though I don't know how to get my object which has been created OnButtonClick into the gridview. I can choose source, Object, but can't see the object there. Is there a guide? Do you mean that I should use the "ObjectDataSource", so this would then mean that I've got to change the backend to give me what I need in the front?
Comment: http://msdn.microsoft.com/en-us/library/aa581783.aspx
Answer: Just FYI I ended up using the table class, I made a table maker class that I can throw my objects and entities at and it spits out nicely formatted tables, it was finicky but I felt a better solution than drag and drop programming.
Thanks all!


Question about conclusion of proof of theorem 6.20 in Rudin's PMA

Question: The theorem is as follows.

6.20 Theorem Let $f \in \Re$ on $[a,b]$. For $  a \leq x \leq b$, put
$$F(x)  = \int_a^x f(t)dt$$ Then $F$ is continuous on $[a,b]$; furthermore, if
$f$ is continuous at a point $x_0$  of $[a,b]$, then $F$ is
differentiable at $x_o$ and $$F'(x_0) = f(x_0)$$
(I have omitted the proof of continuity of $F$ on $[a,b]$)
Suppose $f$ is continuous at $x_0$. Given $\epsilon > 0 $ choose
$\delta > 0$ such that
$$\vert f(t)- f(x_o) \vert < \epsilon $$
if $\vert t- x_0 \vert < \delta$, and  $a \leq t \leq b $. Hence, if
$x_0 - \delta < s \leq x_0 \leq t < x_0 + \delta$ $\enspace$ with:
$a\ \leq s < t \leq b$
we have by theorem 6.12(d)
$$\left| \frac{F(t) - F(s)}{t-s} - f(x_0) \right| = \left| \frac{1}{t-s} \int_s^t [f(u) - f(x_0)]du \right| < \epsilon$$
it follows that $F'(x_0) = f(x_0)$

I imagine I'm missing something obvious, but why does the last line allow us to conclude that $F'(x_0) = f(x_0)$? In my mind I want to see that
$$
\lim_{t \rightarrow s} \frac{F(t)-F(s)}{t-s} = f(x_0),
$$
but what I understand from the last statement is that the fraction $\frac{F(t)-F(s)}{t-s}$ and $f(x_0)$ become arbitrarily close, but I don't see why we can claim that the limit is attained. Thanks in advance for the clarification.
Answer: Hint: First fix $s=x_0$ and conclude that the right hand derivative of $F$ at $x_0$ exists and equals $f(x_0)$. Then take $t=x_0$ and show that the left hand derivative of $F$ at $x_0$ exists and equals $f(x_0)$. That proves that $F'(x_0)=f(x_0)$.
Comment: We are letting $t$ tend to $x_0$ through values **greater** than $x_0$. So we get the right hand derivative when we fix $s$ to be $x_0$.  @AndreyYanyuk
Comment: Thanks for the hint! Is it enough to say that because the final inequality holds for elements in the intervals $x_0-\delta < s \leq x_0 \leq t < x_0+\delta$, if we take any $t$ such that $x_0-\delta < t< s=x_0$ then we have that $\lim_{t \rightarrow s^-} \frac{F(t)-F(s)}{t-s} = f(x_0)$, then for any t such that $x_0< t< x_0+\delta$ we have $\lim_{t \rightarrow s^+} \frac{F(t)-F(s)}{t-s} = f(x_0)$? I guess I don't understand why fixing $s=x_0$ corresponds to the right hand derivative and not the left one?
Comment: Ah perfect thanks!


Does Firebase hosting allow environment variables?

Question: I am running a single page react app that uses Firebase Authorization and the Twilio API for video chat. Everything works fine locally in dev and everything seems to work in my Firebase hosting production build, except the API to Twilio is not working.
How do you deploy an app to Firebase hosting that has environment variables in a .env file?
My environment variables look like this:
TWILIO_ACCOUNT_SID="XXXXXXXXXXXXXXXXX"

Comment: If you're using Cloud Functions to interact with Twilio, you can use configuration variables:https://firebase.google.com/docs/functions/config-env They're not exactly the same as a `.env` file, but serve the same purpose.
Comment: Firebase Hosting doesn't execute any code on its backend.  Are you referring to Cloud Functions instead? Web content doesn't normally deal with things called "environment variables".
Comment: Yes - I'm trying to use cloud functions with Firebase hosting to get the app to work
Answer: Yes, just declare your environment variable starting with REACT_APP if you're using ReactJS.


NoSuchFileException even though there is? Java (trying to add file on startup windows)

Question:         String hi = System.getProperty("user.dir");
        String noes = "%USERPROFILE%\\Start Menu\\Programs\\Startup\\";
        String sex = "/bin/s";
        Path FROM = Paths.get(hi, sex);
        Path TO = Paths.get(noes, "s");
        System.out.println(TO);
        try {
            Files.copy(FROM, TO);
        } catch (IOException e) {
            e.printStackTrace();
        }

Debug:
%USERPROFILE%\Start Menu\Programs\Startup\s
java.nio.file.NoSuchFileException: C:\Users\Sand N\workspace\miner\bin\s -> %USERPROFILE%\Start Menu\Programs\Startup\s
    at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
    at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
    at sun.nio.fs.WindowsFileCopy.copy(WindowsFileCopy.java:205)
    at sun.nio.fs.WindowsFileSystemProvider.copy(WindowsFileSystemProvider.java:278)
    at java.nio.file.Files.copy(Files.java:1225)
    at miner.mine.main(mine.java:18)

Would appreciate all help, thanks so much stackoverflower's!
I'm pretty confused to be honest, not such what's wrong unfortunately.
I know for a fact the startup folder path is correct, but I'm not sure if Java likes certain keys like %, /, etc.
Comment: My guess is that the environment property `%USERPROFILE%` is not being resolved. Use `System.getProperty("user.home")` instead.
Answer: Instead of accessing windows environment path directly, try with System.getenv("USERPROFILE") to get the directory of user profile and then build the path.
 String noes =  System.getenv("USERPROFILE") + "\\Start Menu\\Programs\\Startup\\";

Comment: Thank you sir, appreciated!
Comment: No need to call me a sir. I am a learner too. And make sure to check the [about page](http://stackoverflow.com/about) page to know how to use this site. Welcome to stackoverflow.


Minimum value of an integral.

Question: Suppose we have a function, $\phi:[a,b]\to\mathbb{R}_{+}$. I am trying to prove that the function:
$$g(\alpha)=\int^{b}_{a}(x-\alpha)^{2}\phi(x)dx$$
attains its minimum value on $(a,b)$, and find the point in which it reaches that value (I believe it can be eventually expressed in terms of the function $\phi$).
The results I've obtained so far are not very promising. First off, the only way that I know to prove the thesis is by finding an $\alpha_{0}$, such that $g^{\prime}(\alpha_{0})=0$ and then show that $g^{\prime\prime}(\alpha_{0})\geq{0}$.
As for the first part, let's define a bivariate function: $h(\alpha,x)=(x-\alpha)^{2}\phi(x)$. We have:
$$g^{\prime}(\alpha)=\int^{b}_{a}\frac{\partial}{\partial\alpha}h(\alpha,x)\,dx=-2\int^{b}_{a}x\phi(x)\,dx+2\alpha\int^{b}_{a}\phi(x)\,dx.$$
I have no idea how to deal with the expression $\int^{b}_{a}x\phi(x)\,dx$. Is there a way we can somehow evaluate it and transform into a more elementary form? If not, then by equating the result we obtained to $0$, we arrive at:
$$\alpha=\frac{\int^{b}_{a}x\phi(x)\,dx}{\int^{b}_{a}\phi(x)\,dx}$$
How can we interpret the above expression, or at least prove that it belongs to the interval $(a,b)$? I would be very thankful on some ideas as to where I should head with this.
EDIT: we also assume that $\phi$ is continuous.
Comment: Are there any smoothness assumptions about $\phi $?
Comment: No, nothing beyond of what I mentioned.
Comment: Sorry, my bad! We do assume that $\phi$ is continuous.
Comment: Can't you just work with the sign of the derivative? $\phi$ is >0 on the whole interval, that means its integral is positive...
Answer: If the function $\phi$ is continuous, $\alpha$ could be interpreted, from a mechanical point of view, as the center of mass abscissa of a material line (the segment $[a,b]$) of linear mass density $\phi(x)$.
Another interpretation of $\alpha$ is, being $\phi$ positive, and if it is left continuous, as the mean value of the probability density distribution
$$
\psi(x)=\frac{1}{N}\phi(x),\qquad N=\int_a^b\phi(x)dx.
$$
Obviously, both interpretations lead to $a\leq \alpha\leq b$, that can be easily proved directly.
Comment: Oook, I do not understand the mechanical interpretation. I do see how this works in the second case (the mean must lie within the interval on which the pdf is defined), though I would appreciate some hints on how a rigorous proof should look (I mean, if we shift to probability, we have to prove that $\psi$ satisfies conditions to be a pdf)
Comment: @JohnnyWesterling: continuity and positivity are enough for a PDF. Also, in your question you ask for an interpretation, so I talked about that. The formal proof is given in the answer by HagenvonEitzen.
Comment: And what about the condition that $\int\psi(x)dx=1$?
Comment: @JohnnyWesterling: it is guaranteed, in this case, by its definition (I mean of $\psi$) and that of $N$.
Comment: Alright, I see it now. Thanks!
Answer: Since $\phi$ continuos, $c:=\min\{\phi(x)\mid a\le x\le b\}$ is assumed at some point in $[a,b]$. Since $\phi$ is strictly positive, we conclude $c>0$ , we have that $(x-a)\phi(x)\ge c(x-a)$ and $(b-x)\phi(x)\ge c(b-x)$ for all $x\in[a,b]$, hence
$$\int_a^b x \phi(x) dx\ge \int_a^b a \phi(x) dx+\int_a^b c(x-a)dx=a\int_a^b\phi(x)dx+\frac c2(b-a)^2.$$
Similarly,
$$\int_a^b x \phi(x) dx\le \int_a^b b \phi(x) dx-\int_a^b c(b-x)dx=a\int_a^b\phi(x)dx-\frac c2(b-a)^2.$$
Because $\frac c2(b-a)^2>0$ and $\int_a^b\phi(x)dx>0$ we conclude
$$ a< \frac{\int_a^b x \phi(x) dx}{\int_a^b \phi(x) dx}< b.$$
Remark: Even if we only assume $\phi(x)\ge0$ for $x\in[a,b]$ and only $\phi(x_0)\ne0$ for some $x_0\in [a,b]$, continuity of $\phi$ allows us to  find a subinterval $[a',b']$ around $x_0$ where $\phi$ is strictly bigger than the positive number $c':=\frac12\phi(x_0)$. Then we still have strict inequalities because we may replace the expression $\frac c2(b-a)^2$ with $\frac {c'}2(b'-a')^2$ in the above argument.

Once you have established $a<\alpha<b$ this way, you of course have immediately that $g''(\alpha)=2\int_a^b\phi(x)dx>0$, i.e. $g(x)$ takes has a local minimum at $x=\alpha$. This is also the global minimum for $[a,b]$ because a minimum at the boundary (i.e. at $x=a$ or $x=b$) would require a local maximum inbetween.
Comment: Thanks. Ok, I do understand the first part, but how does the fact that $\int^{b}_{a}\phi(x)dx>0$ bring us to the second part?
Comment: Thank you very much for a thorough explanation!
Answer: It is widely known that for random variables $X$ for which the expected value $E|X|$ is finite, the value of $\alpha$ that minimizes $E((X-\alpha)^2)$ is $\alpha=E(X)$.
So in case $\varphi$ is a probability density function, that answers the question.  Where $\varphi$ is a non-negative function whose integral is finite, just divide both sides of the inequality by that integral, and again, that answers the question.
Here's a proof:  Consider
$$
\alpha\mapsto E((X-\alpha)^2) = E(X^2) -2\alpha E(X) + \alpha^2.
$$
No you're just minimizing a quadratic polynomial in $\alpha$.
Comment: Yes, I see it. Thanks!
Answer: Let $h(\alpha)=g'(\alpha)$. Then $h$ is continuous everywhere (in fact it is a linear function) with $$h(a)=2\int_a^b(a-x)\phi(x)dx<0$$ and $$h(b)=2\int_a^b(b-x)\phi(x)dx>0$$ by positivity of $\phi$. It follows that there is a zero of $g'$ in $(a,b)$, which the second derivative test shows to be a minimum of $g$. By linearity, $g'$ has a unique zero, the location of which (given in terms of integrals of $\phi$) you have already determined.

Minimum value of an integral.


probability distribution proof $P(a < X \leq b) = F(b) - F(a)$

Question: Let F be the distribution function of the probability $\mathbb{P}$ on $\mathbb{R}$ (induced by some random variable $X$).
Prove: $\mathbb{P}((a,b]) =\mathbb{P}(a < X \leq b) = F(b) - F(a)$
This is how far I got, but i cant figure out the next step, as the proof must hold for pdf and pmf.
\begin{align*}
  \mathbb{P}((a,b]) &= \mathbb{P}(a < X \leq b)\\
  &= \mathbb{P}(\{X > a\} \cup \{X \leq b\})\\
  &= \mathbb{P}(\{X > a\} \cup (-\infty, b])\\
  &= F(b) - \mathbb{P}(\{X > a\})\\
&= \dots\\
\end{align*}
On my notes, the next step should look something like this:
$\mathbb{P}(\{X > a\}) = \mathbb{P}(a \leq X) = F(a)$
I am not sure whether this is true, neither do I understand it...
Answer: You certainly have an error as $\mathbb{P}(a < X \leq b) = \mathbb{P}(\{X > a\} \cap \{X \leq b\})$ with an intersection rather than a union, so perhaps (assuming $a \le b$ and so $\{X \leq a\} \subset \{X \le b\}$ ):
\begin{align*}
  \mathbb{P}((a,b]) &= \mathbb{P}(a < X \leq b)\\
  &= \mathbb{P}(\{X > a\} \cap \{X \leq b\})\\
  &= \mathbb{P}(\{X \leq b\} \,\backslash\, \{X \le a\}) \\
  &= F(b) - F(a)\\
\end{align*}
Answer: You have to use continuity at right of $F$. Let $a_n\to a^+$. I denote $\mathbb P_X(A)=\mathbb P\{X\in A\}$. Then
$$\mathbb P_X(a,b]=\mathbb P_X\left(\bigcup_{n\in\mathbb N}[a_n,b]\right)=\lim_{n\to \infty }\mathbb P_X([a_n,b])=\lim_{n\to \infty }(F(b)-F(a_n))=F(b)-F(a).$$


Adding class with jQuery only works for the first element

Question: I am trying to code Darkmode on my website using jQuery and using classList.toggle to change colors. Everything is working fine for the most part, but navigation only works for the first li and a. Here is my code:
HTML

        <button class="nightModeButton">darkmode</button>

Bio

Galéria

CSS
li a {
    display: inline-block;
    font-family: 'Merriweather', serif;
    font-weight: 500;
    font-size: 22px;
    text-decoration: none;
    color: #171717;
    padding: 0 30px;
}

li a:hover {
    color: #171717;
    text-decoration: none;
}

body.night-mode {
    background: #181b23;
}

li a.night-mode {
    color: #fff !important;
}

Javascript (jQuery)
var nightModeToggleButton = document.querySelector(".nightModeButton");
var body = document.querySelector("body");
var navigacka = document.querySelector("a");

nightModeToggleButton.onclick = function() {
    nightModeToggleButton.classList.toggle("night-mode");
    body.classList.toggle("night-mode");
    navigacka.classList.toggle("night-mode");
};

Answer: Changing
li a.night-mode {
    color: #fff !important;
}

to
.night-mode li a {
  color: #fff !important;
}

gives the result you are expecting.
Just a thought: Instead of applying color modifications directly on li or ul or a, have a class called light-mode maybe, and nest the styles associated to light-mode inside.

var nightModeToggleButton = document.querySelector(".nightModeButton");
        var body = document.querySelector("body");
        var navigacka = document.querySelector("a");

        nightModeToggleButton.onclick = function() {
            nightModeToggleButton.classList.toggle("night-mode");
            body.classList.toggle("night-mode");
            navigacka.classList.toggle("night-mode");
        };
li a {
    display: inline-block;
    font-family: 'Merriweather', serif;
    font-weight: 500;
    font-size: 22px;
    text-decoration: none;
    color: #171717;
    padding: 0 30px;
}

li a:hover {
    color: #171717;
    text-decoration: none;
}

body.night-mode {
    background: #181b23;
}

.night-mode li a {
    color: #fff !important;
}

                        <button class="nightModeButton">darkmode</button>

Bio

Galéria


How to fix a leaking pipe?

Question:
Kitchen pipe is leaking, I think I have identified the leaking is the red circle.

I should not apply glue or any kind of sealant, should I?
What if I tighten it with a spanner and it still leaks? Wrap it up with a piece of clothes?

Thanks
Answer: Well those stupid infomercials would say to "wrap it in flex tape," don't do that, or wrap it in rags. (Fiber fix would be better then both, but please fix it properly.)
That looks like a copper compression fitting. As such just tightening it probably will not stop the leak. There is a small chance that will work, it may have just worked its way loose over the years so start by simply tightening it, a little. Do not over tighten it. After a compression fitting is tight over tightening it will only make it worse.
Unfortunately if it still leaks it is a bit of work. Turn off the water, open up the fitting and replace the brass compression ring in side there. The trouble comes in getting the old ring off. You will either need a compression ring puller or a compression ring cutter (a rotary cutoff tool can be used, but be very careful not to damage the pipe).
With the new ring on, tighten the fitting down it is about one turn after it makes contact.

How to fix a leaking pipe?


Replace part of string in python

Question: I am trying to replace all the column name in the dataframe where column name contains value in count. I have written the following code but it's not working, whereas if in place count in str.replace if i just write '5' then it runs. How can I fix this issue?
count=Final['Rate'].max()
count=str(count)
Final.columns = Final.columns.str.replace('count', 'Final')

Comment: How is it "not working" ?- elaborate. What is your expected result? What are the column names?
Comment: Can you show us a sample of the DF ?
Comment: I mean the code executes but all the columns which contains 5 in the columnname they are not being replace with 'final'
Comment: `Final.columns.str.replace(count, 'Final') ` ?
Comment: @Rakesh, I tried that too but still it don't reflect in the dataframe
Comment: Can you elaborate a bit more on what it is that you want? What does 'Final' look like and what does count look like (I take it that it should just contain '5')?
Comment: The Final dataframe have columns like Rate, Name, cash1, cash2, cash3, interest1, interest2, interest3. I want to replace cash3 as cashfinal, interest3 as interestfinal. There will be as many interest and cash as there is maximum value in rate
Comment: Can you please help ?
Comment: So you just want to replace cash3 with cashFinal (if 3 is the max value), and leave cash1, cash2, etc. as it is?
Comment: Have you checked the contents of `count`? Is it realy the value/string that you expect, or does `Final['Rate'].max()` give you a different number than what is in your column names? Because otherwise the code should work (after you change the last line to: `Final.columns.str.replace(count, 'Final')`)
Answer: I think the problem is that you wrote count as a string instead of a variable.
try:
Final.columns.str.replace(count, 'Final')

instead of:
Final.columns.str.replace('count', 'Final')

At the moment you search for the substring 'count' and if it exists, you replace it with 'Final'.
If this doesn't solve the problem, please edit the question to make it more clear what the exact problem is.

Replace part of string in python


jQuery plugins - the tab widget

Question: I am studying a javascript - more precisely javaqueryui.
<!Doctype html>

<title> 17. Installing and utilizing jQuery plugins</title>

<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.4/themes/dot-

luv/jquery-ui.css" />

 17. Installing and utilizing jQuery plugins

Nunc tincidunt

Proin dolor

Aenean lacinia

Proin elit arcu.

Morbi tincidunt.

Mauris eleifend est et turpis.

Duis cursus.

Can you help me understand why, instead of seeing three tabs with 3 different contents, I see the 3 tabs with the same content?
Current result (visible regardless of which tab I switch to):

Proin elit arcu.
Morbi tincidunt.
Mauris eleifend est et turpis.
Duis cursus.

Expected/desired result:
Tab1 should show

Proin elit arcu.

Tab2 should show:

Morbi tincidunt.

Tab 3 should show:

Mauris eleifend est et turpis.
Duis cursus.

PS: In case you need to view the javascript file content:
$(function() {
    $( "#tabs" ).tabs();
});

all other external script files are referenced from the internet, not downloaded locally (as the src attribute shows)
Answer: Something wrong with your libraries, probably.
I tried your code on jsFiddle and it didn't work. Then I tried to include external libraries from this example:
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">

Your HTML and JS code started work with that links (JSFIDDLE) => libraries links were wrong or they conflicted.
So... Try another source... Check this example on official jQuery UI site.

jQuery plugins - the tab widget


Disabling background or all controls on a ASPX page using Jquery

Question: I am using this code to show a dialog box that will confirm for a delete button, it works fine, but when it pops up it doesn't disable any controls of ASP.Net page, so I can click on any of the controls or text boxes,
First thing I wanna do is fade out the page when Jquery opens my Div tag BOX and second to disable all the controls.
here's the code
Div (Custom Dialouge box)

<asp:Label ID="Label1"  runat="server" Text="Deleting this eDecision will remove all site content and uploaded documents. Are you sure you wish to continue?" CssClass="headertext"></asp:Label>

            <asp:Button ID="btnConfOK" Width="200px" Height="25px" CssClass="gradientbutton" OnClick="btDelete_Click" Runat="server" Text="Yes"></asp:Button>
            <asp:Button ID="btnConfCancel" Width="200px" Height="25px" CssClass="gradientbutton" Runat="server" Text="No"></asp:Button>

Script (jquery)

Button

    <asp:Button ID="btDelete" runat="server" CssClass="gradientbutton" OnClick="btDelete_Click"
    OnClientClick="this.disabled=true;this.value='Please Wait...';" Text="Delete" Width="200px"  />

Css for Dialog Box
    #divConfMessage
{
    position: absolute;
    width: 500px;
    height: 200px;
    top: 50%;
    left: 30%;
    margin-left: -150px; /* Negative half of width. */
    margin-top: -100px; /* Negative half of height. */
    border: 2px solid #000;
    DISPLAY:none;
    background-color:White;
    line-height:20px;
    text-align:center;
}

Note
All of the code is in ASP content place holder for the page except CSS, I have 2 another Contents with different controls + a Master Page defining all these Content Place holders.
<asp:Content ID="Content4" ContentPlaceHolderID="cphSubmit" runat="server">
<%@ Page Language="C#" MasterPageFile="~/my.Master" AutoEventWireup="true" CodeBehind="c.aspx.cs" Inherits="a.b.c" Title="e"  meta:resourcekey="PageResource1"  %>

Answer: set Modal=true; for dilogbox there is modal property, you can set it as True.
try using Jquery dialogue box ( it comes with JqueryUI plugin).
$( "#YourDivorContainerToShowAsDialog" ).dialog({
            modal: true,
            buttons: {
                Ok: function() {
                    $( this ).dialog( "close" );
                }
            }
        });

EDIt: if you don't want to use buttons, then use like this
  $( "#YourDivorContainerToShowAsDialog" ).dialog({
                modal: true
            });

or if you want to use CSS then you can try
#YourDivorContainerToShowAsDialog
{
position: absolute;
Z-index: withMaxValue
}

Comment: Hey Ravi, thanks for your answer, I already tried it, but my Div already have a asp.net buttons, so dont wanna use dialog buttons + it becomes really confusing then
Comment: @TimeToThine you can ignore buttons. only use modal property. so that your div will become modal box
Comment: thanks mate, i tried it but it still not disabling anything :|
Answer: Give a higher Z-index for  #divConfMessage and then the modal dalog will be on top everything.
When you add a dialog append it to body as this way:
 add_block_page();
 add_modal_box();

function add_block_page(){
    var block_page = $('

');
    $(block_page).appendTo('body');
}

function add_modal_box(){
    var pop_up = $('

');
     $(pop_up).appendTo('.page');
 }

Comment: for the Moment its on top of everything but just not blocking the page behind it :)
Comment: Change the background color from white
Comment: If i use your code of line, It Appends the body of the Div , not the page :|
Answer: Use one transperant image to fadeout the page.
Add one outerDiv and apply the image to the div.

<asp:Label ID="Label1"  runat="server" Text="Deleting this eDecision will remove all site content and uploaded documents. Are you sure you wish to continue?" CssClass="headertext"></asp:Label>

            <asp:Button ID="btnConfOK" Width="200px" Height="25px" CssClass="gradientbutton" OnClick="btDelete_Click" Runat="server" Text="Yes"></asp:Button>
            <asp:Button ID="btnConfCancel" Width="200px" Height="25px" CssClass="gradientbutton" Runat="server" Text="No"></asp:Button>

CSS for outerDiv
# outerDiv
{
top:0%;
left:0%;
position:absolute;
background-image:url('../img/FloatingPanel.png');//transperant image
color:White;
z-index: 1102;
Height:100%;
width:100%;
}

Give a higher Z-index for #divConfMessage than the Z-index of outerDiv(ie:1103).
Show the outerDiv onclick of btDelete


PHP Array to JS array and restructure

Question: I have two PHP strings that looks like this (obviously shortened for the question):
 $year [
    [0]=>2003
    [1]=>2003

    [2]=>2004
    [3]=>2004

    [4]=>2005
    [5]=>2005

]

 $cost [
    [0]=>200
    [1]=>300
    [2]=>400
    [3]=>500
    [4]=>410
    [5]=>510
]

I need to turn the PHP arrays above into a JAVASCRIPT array formatted exactly as below:
     var newData=[
          ['2003', 200,300],
          ['2004', 400,500],
          ['2005', 410,510]
        ];

When I type in the JS array implicitly (as above) all works fine (ie the graphics render correctly). However after several hours of trying different approaches, I cannot work out how to easily generate the newData array dynamically (ie from PHP arrays as shown) in exactly the JS Array format shown.
Comment: How do you know how much entries have the 2003 and which of them should take from $cost?
Comment: Take us back one step to how you created these arrays. More efficient to start there
Comment: @legomolina the two PHP arrays are produced in such a way that the key of each array always matches the key of the other. So whatever key value is for array ($year) it will match array($cost).  I will extend the question example to show you
Comment: @charliefl im afraid the php array formats are fixed. Major implications of changing those,
Comment: in PHP: `json_encode($array);` - in JS: `const array = JSON.parse(json);` - the restructuring / merging can be done in PHP or JS.
Comment: There are some things still unclear about the requirements. Will the values of year always be in order? (ie - will the years always be grouped together?) Is there a fixed or variable number of costs associated with each year?
Comment: @Prisoner yes always in order. So 2003 could have (say) 10 instances and that will create 10 cost instances. (The form handler user side forces that).
Comment: @le_m encoding the php array as a string I get. I am not getting the second part though. const array = JSON.parse(json); How does that apply?
Comment: @le_m You do not have to JSON.parse the json_encoded variable, because it will not be trasferred as a string, but as part of the page code and therefore as the corresponding type for the varaible. (In this case object or array)
Comment: @PhilippMaurer How do you know that OP returns the array within the HTML document? If OP does so, then you are right of course.
Comment: @le_m If he does return it via a special ressource, he should set the HTTP header Content-Type to application/json instead, wich will result in not needing the JSON.parse again,
Answer: Your quest can be separated in two tasks:
First of all you want to combine both arrays. I guess you want to do this based on the keys they have. There are multiple functions for that in PHP, like array_combine or array_reduce.
Yet for your case the easiest way is a for_each loop, because you have duplicate values in the $year array.
$combined_array = [];
foreach ($year as $id => $year_val) {
    if (!array_key_exists($year_val, $combined_array)) {
        $combined_array[$year_val] = [(string)$year_val];
    }
    $combined_array[$year_val][] = $cost[$id];
}

Now you have the years as keys, what you do not want, so you can use array_values to remove the keys again.
$combined_array = array_values($combined_array);

The second task is quite easy: Go to the PHP file, that loads the script you want to provide the array to. Add this before you load the script:

After that the PHP array is accessible from JS in the variable `myPhpArray.
Comment: Thank you. I think the bit of this i am not doing right is JSON.parse. I have the php array restructured ok. And i have used (js) var array = ""; .....but that failed (althouigh i have used that method before without problems)?
Comment: Im sorry. I removed the JSON.parse part, because it is not neccessary. Valid JSON is automatically parsed as an JS varaible by the JS engine.
Comment: @WChris, DONT use the quotes between your php echo call. It will make your javascript interpret the code as a string and it must interpret it as javascript code that structures and array.
Answer: if you respect the structure in the example, the following would do the job:
<?php

$year = [
   0 => 2003,
   1 => 2003,
   ...
];

$cost = [
   0 => 200,
   1 => 300,
   ...
];

for($i=0;$i<SIZE_OF_ARRAY;$i+=2)
     $newData[] = [(string) $year[$i], $cost[$i], $cost[$i+1]];

?>

Now in the javascript portion of the code you just need:

Note that i didnt use the quotes between the php code because i do want the javascript to parse the php output as javascript code and not as a javascript string.
Comment: @BigBlast WChris already mentioned in another comment, that there might be 10 costs for 2003 and only 2 for 2004, so your code does not work for his case. Good approach anyway
Comment: @BigBlastThat helps with structuring the PHP data but the issue i am having the problem with is replicating it in JS exactly......json_encode(); fails
Comment: no no, you just need: `var newData = ;` or, if you dont have `short_open_tags` enabled in your php.ini, `var newData = `
Comment: yeah that was what i tried before SO post. Its not happening though. Hmmm...at least Im not doing something really daft. And for that an upvote sir
Comment: ps my prior comment back to you without the json_encode was honestly just a copy paste typo (see my earlier comments to others who responded).
Comment: If the portion of the code that structures the data works correctly, i dont see any reason for the portion that displays the PHP array as a JS Array not work... do you have some other info about the error that you are receiving? Some weird output that being displayed?
Comment: @WChris i've updated my answer to clarify the structure of the code you must implement to achieve your goal.
Answer: Thanks for all the help. Your answers showed I was going about things the right way (json_encode etc). What has happened though is that the legacy system producing the PHP Arrays was not correcting the values for integers rather than strings. The recipient plug in needed INTs -- see the output array format in the question
So json_encoding the php array worked OK - but it was encoding string rather than INT data values. Fixed that and now it all seems fine.
PS If you look at the orginal question yyou will see the OP array in JS needed two datatypes. And of course it was only getting strings. Lesson there for sure!
Heres the snippet
             var a = ['1','2','3'];
             var result = a.map(function (x) {
             return parseInt(x, 10);

PHP Array to JS array and restructure


Is baseboard important? (and 3 choices for trim on wall-to-floor transition)

Question: I'm pulling out wall-to-wall carpet and installing solid hardwood floor. I am also removing the old baseboard and repairing the bottom of the wall with drywall compound to take out any weird ridges the old baseboard may have left. The way I see it I have 3 choices for edging the floor:

Install the hardwood floor first, then install the baseboard over that.
Install the baseboard first, all the way down to the subfloor. Then install the hardwood floor. Then install shoe molding.
Install the hardwood first, then install just shoe molding over that - no baseboard.

3 seems the easiest. Any drawbacks?
Answer: Baseboards provide a useful function in a house.  They are not purely aesthetic.  They protect the bottom of the drywall from being damaged, they build a stopping point for dirt, they keep drywall/paint from being damaged by feet (shoes).  Anyone buying a house with drywall walls would expect some sort of minimal baseboard.
Shoe molding has three issues.  It isn't big enough to protect anything, since you need a gap between drywall and flooring it would be very hard to install, and then since you have this gap the shoe molding will surely get pushed into it, since it is usually flimsy.
Install your floors and sit you baseboards on top of flooring.  If you cut out bottom of drywall so that the drywall depth acts as expansion gap for wood, you don't need shoe molding.
Note:  Think about what type of house you have when you put up molding and what you have in each room.  If this is every single room and you have a nice house I would at the very least put up 4"+ baseboards.  There is usually very little difference in price and installation and staining/painting isn't really any harder.  If you want cheap and fast go with the primed pine from the big boxes.  These usually take one quick coat of paint and good to go.
Comment: Thanks for the explanation of the baseboard function above and beyond appearance. What's the most effective way to cut out the bottom of the wall for an expansion gap? If it matters, I actually happen to have plaster, not drywall.
Comment: Just a utility knife and pull it out - if you a saw it can get messy and you might hit screws/nails.  I actually will cut deep and pop them out with a 10" putty knife.  Probably don't have to cut out more than a half inch.  You don't have a picture of yours but you might not even have to.  Many builders cut drywall an inch short on the bottom.  You just need about 1/8 of an inch above the flooring.
Comment: Hm. Just posted a picture above. Looks like I have wood along the bottom.
Comment: How tall were your previous baseboards and what is the height from the floor currently to the top line?  It really doesn't seem like you have drywall installed but I see a screw.  So it goes wood (which I am guessing is just a face) then concrete, then drywall (or plaster?).
Comment: 3 3/4" from floor to top line. Old baseboard was just under three inches. I definitely do not have drywall. I have plaster over Sheetrock. What you are seeing as a concrete middle layer may just be the raw Sheetrock showing.
Comment: Yea so you can install your basic 4 1/4" baseboards and it should cover everything.  I use my laziness to decide on upgrades and I would see how far up your paint is damaged.  I would then select my size so I don't have any patching within reason.
Comment: Yeah I agree and I've done that before. Question remains if I am going to now need both baseboard and shoe molding since your expansion gap suggestion won't work due to my bottom wood strip.
Comment: What is the wood strip?  How thick is it?
Comment: 3/4". So, same as the hardwood will be.
Comment: What is behind it?  Is the wood just facing?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/19251/discussion-between-greg-smalter-and-dmoore).
Answer: Traditionally in my area is hardwood, then baseboard and shoe molding.
For sure I would put down the floor first. Otherwise whatever baseboard you put in can't be changed out easily, if it's wedged between the wall and the baseboard.
Maybe google it and look at photos, pick what you like best.
Answer: The "correct way" to install this is (in this order) to install the drywall, paint, install baseboard, install flooring, finish baseboard and flooring (assuming it's not tile or carpet), install shoe molding.
The drywall should not touch the floor.  The baseboard both protects the drywall and hides this gap (which is there to allow for expansion).
Wood floors expand and contract and that's the reason for the shoe molding.  Some people say, "oh you just use that to hide mistakes".  While it can be for that, there are going to be gaps at different times of the year, regardless of how good a craftsman the installer is.
Shoe molding also allows you to easily remove just the shoe molding, replace the floor, and then just re-install shoe molding without damaging the wall.
Answer: It's just a matter of aesthetics. Shoe moulding with no baseboard isn't really considered very nice, but there's certainly no reason it won't work, as long as the shoe moulding you choose is wide enough to cover the expansion gap you leave between the wall and the flooring.
However, there's no reason you have to throw away the old baseboard if there's nothing wrong with it. You would follow #1, remove the old baseboard with care, and then simply re-install it after your flooring is in.
Answer: I prefer baseboards with no shoe molding. I think it looks cleaner. I believe that show molding is usually installed when adding flooring later. It may be when carpet is replaced or when a flooring guy comes in later during new construction. Baseboards are usually thick enough to cover any expansion gap for the floor.


Watching network usage level from Java on Windows

Question: I'm currently looking for a way, how to get real-time data about network utilization from Java. I would like to see how several running threads (all downloading stuff from web) utilize network and simultaneously be able to set threshold for spawning new threads if some criteria are not met. Let's say I create 10 threads, all downloading some stuff from web, and network utilization would be on 5%, consider previously set threshold to max utilization of 10%, I would be allowed to spawn a new thread. Thing is, I'm not sure if there's a way how to get such network information. Any help is much appreciated.
Comment: This is likely to be OS-specific. Which OS(es) do you need to support?
Comment: Sorry, totally forgot to write that I'm developing this on Windows. I modified topic name ...
Answer: If you are using Linux, you should be able to read this information from a system file in /proc/net. For example, /proc/net/dev:
Inter-|   Receive                                                |  Transmit
 face |bytes    packets errs drop fifo frame compressed multicast|bytes    packets errs drop fifo colls carrier compressed
    lo: 108751031  226504    0    0    0     0          0         0 108751031  226504    0    0    0     0       0          0
 wlan0: 113355689  146027    0    0    0     0          0         0 18453619  122751    0    0    0     0       0          0
  eth0:       0       0    0    0    0     0          0         0        0       0    0    0    0     0       0          0

This file is easy to read in pretty much any programming language, including Java.
Note: the question has now been changed to explicitly refer to Windows. So this is no longer a fully appropriate answer.
Comment: Thanks for reply. That's really useful. Is there how to do something like that on Windows?
Comment: I stopped using Windows way over 10 years ago. But it never had the Unix philosophy of "everything is a file" that encouraged this style of system APIs on Linux. I believe you'll have to use some native DLL to get the equivalent data, but maybe someone already wrote a JNI for this.


Does Ubuntu 14.04 fit in a 8gb SSD?

Question: I'm about to buy a new laptop that comes with a hybrid HD with a 8GB SSD.
Comment: Yeah. I didn't find this question before. It totally answers my question. So my question can be considered duplicated. Thank you.
Answer: Yes. According to their site, Ubuntu with a GUI only requires 5GB of Hard Disk storage, although any other programs you may install will be above and beyond this total.
Answer: Yes, hybrid drives work by storing pretty much all of the data on the magnetic disk while using the SSD portion to cache commonly used data so you can access it much quicker than if you were to get it directly from the magnetic disk. On most hybrid drives this is done by the firmware on disk at a base level and doesn't involve the OS or drivers in any way at all.
To expand on this answer further, the root partition on my current Linux machine is at 7.62GBs which is lower than the SSD cache so it would be a fair conclusion that most of the data on the root partition would be copied to the SSD side of the drive as root data is essential for Ubuntu to operate and would be used most if not all the time.

Does Ubuntu 14.04 fit in a 8gb SSD?


Creating an excel file in java

Question: I am using SpringFramework. I want to create an excel file using Java.
Below is the code in which i failed creating a excel file.
<code>public  void eventsUpdate(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{

response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=events123.xls");

        HSSFWorkbook hwb = new HSSFWorkbook();
        HSSFSheet sheet = hwb.createSheet("new sheet");
}
</code>
Comment: What is the problem/question?
Answer: I would sugges you take a look at: http://poi.apache.org/spreadsheet/how-to.html

Creating an excel file in java


Async HTTP post android

Question: I am using an application where i just need to download a pair of coordinates for google maps from a mysql server. I can do this successfully using php and a normal httpost but my app freezes for a few seconds when i do it.
I read that you need to make httppost asycronous in order to avoid that freezing until the server finishes the prossess and sends the results.
The point is that i need that results in a json array like the normal httpost.
For example if i had this httppost.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}

String result11 = null;
// convert response to string
try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is11, "iso-8859-1"), 8);
    StringBuilder sb = new StringBuilder();
    sb.append(reader.readLine() + "\n");
    String line = "0";
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    is11.close();
    result11 = sb.toString();
} catch (Exception e) {
    Log.e("log_tag", "Error converting result " + e.toString());
}

// parsing data
try {
    JSONArray jArray1 = new JSONArray(result11);
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

How can i convert that to an asynchronous post so i can avoid the freeze ?
Comment: I have no idea how your code could even compile as it is, but please use [`EntityUtils.toString(response.getEntity())`](http://stackoverflow.com/a/2324739/180740) instead of having your own BufferedReader-n-StringBuilder party. The former is less code, has correct error handling and obeys the character encoding sent by the server.
Answer: There is a nice class AsyncTask which can be used to easily run asynchronous tasks. If you embed your code in such a subclass, you might end up with this:
public class FetchTask extends AsyncTask<Void, Void, JSONArray> {
    @Override
    protected JSONArray doInBackground(Void... params) {
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("id", "12345"));
            nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");
            String line = "0";
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            reader.close();
            String result11 = sb.toString();

            // parsing data
            return new JSONArray(result11);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onPostExecute(JSONArray result) {
        if (result != null) {
            // do something
        } else {
            // error occured
        }
    }
}

You can start the task using:
new FetchTask().execute();

Additional resources:

Painless Threading - developer.android.com
AsyncTask - developer.android.com
Answer: I suggest using android-async-http ( http://loopj.com/android-async-http/ ) library. It makes android async http calls simple and elegant.
Comment: unfortunately there are only few demos available that make it easier for a newbie to understand how to put everything together, like in this case to post data to an URL and to process a response utilizing JSON. I understand it's all there and seems to be very powerful and smart, but a few more examples would definitely help.
Comment: I've used it and found it easy to start with. I started with the code sample given in "Recommended Usage" section in http://loopj.com/android-async-http/. I'd learn and do certain things along the way, such as persisting the cookies, making it work with SSL (trusted and untrusted), adding a check to see if the device is online or not etc. I feel all of these issues will have to  be dealt with whether you use this library or Android API.
Answer: Assuming you want to do this on a button click:
public void onClick(View v) {
  new Thread(new Runnable() {
        public void run() {
            //your code here
        }
    }).start();
}

Basically, you are putting IO intensive operation in a separate thread (not your UI thread) so that the UI does not freeze.
Comment: trying in a while and ill answer you. Thanks a lot for your response :)
Answer: Rather than just starting a new thread, it's a better idea to go with a full-fledged AsyncTask. It provides much greater control of things.
private class DoPostRequestAsync extends AsyncTask<URL, Void, String> {
     protected String doInBackground(URL url) {
        //Your download code here; work with the url parameter and then return the result
        //which if I remember correctly from your code, is a string.
        //This gets called and runs ON ANOTHER thread
     }

     protected void onPostExecute(String result) {
         //This gets called on the interface (main) thread!
         showDialog("Done! " + result);
     }
 }

Place the new class implementation inside of your desired Activity's class. For more info on AsyncTask please follow this link:
http://developer.android.com/reference/android/os/AsyncTask.html
Answer: Use an async http library like ion. https://github.com/koush/ion
All the threading and asynchronous boilerplate will be handled for you.
This is your same code, asynchronous, using Ion. Much simpler:
Ion.with(context)
.load("http://www.yoursite.com/script.php")
.setBodyParameter("id", "12345")
.setBodyParameter("stringdata", "AndDev is Cool!")
.asJsonArray()
.setCallback(new FutureCallback<JsonArray> {
  void onCompleted(Exception e, JsonArray result) {
    // do something with the result/exception
  }
});

Async HTTP post android


Is there a way in Eclipse CDT to automatically switch from . to ->

Question: The Qt Creator have a neat feature I really like. When I'm typing obj.method, it would automatically replace the period (.) with an arrow (->), if obj is a pointer.
Makes sense actually. You never want to type pointer.something, it wouldn't be legal.
Is there a way to achieve a similar function with Eclipse CDT?
This question is a duplicate from an old one found here but i also miss that function and i'm not sure that a comment to that question will "bump" it.
Comment: I'd say it's a bad habit - if ever you change the IDE or work in vim/np++/..., you'll waste all the time you saved by typing 2 chars instead of one on fixing the compilation errors. "clever" editor is not a replacement to Java... ;)
Comment: ooops - should be "typing one char instead of 2"
Answer: The upcoming CDT 8.0 for Eclipse Indigo has that feature.
Comment: How do you use that feature, im on indigo but I haven't seen it do that. Sounds cool


Alternative to contextual menu in a web application

Question: TLDR: I'm currently using a contextual menu in a web app for a complex form, but it has limitations and I'm seeking alternatives
I have a very complex form which follows a non-fixed model. This means, the user can sometimes add new fields of the same type, or add new sub-fields. Plus, each field and sub-field have one or more actions linked to it (e.g. add new, remove, mark as stale etc).
In order to keep the form de-cluttered (as it can really get huge, and it is not possible to split it in parts as the user needs to be able to see the whole of it, my first idea was to use a contextual menu on some elements in order to make those actions available.
You can see how this form currently works in the part # 1 of the attached image.
(This is a very simplified example, the real form is WAY bigger - actually composed by many of those forms where each form have much more fields than those shown in the sample picture)

The contextual menu, though, comes with some disadvantages, some of which are mitigated by the fact that the users get a training in how to use this web application (closed system that they use for work):

People are not used to contextual menus on web applications
This content is hidden, if you don't know that the menu is there you will miss those actions
Not all elements on the page have a contextual menu (even though if they do a different cursor is shown to the user) so the user doesn't even know where to right click
Even if there is a way for keyboard-only users to open a contextual menu, they will have absolutely no clue if the menu is available or not for a certain element

The advantage is, as I said, that the form is a bit cleaner so the user is less intimidated by it and can work in a more comfortable way.
They need to check the form multiple times across fields before submitting, so it is important to have a layout as clear as possible.
It is also important to show them as many field as possible in the smallest space possible so that they don't have to scroll up and down to find what they need.
Anyhow, we noticed that even some of our power users are totally unaware of some of the functions "hidden" in those menus, which is the main reason why I'm considering changing this approach.
As an alternative, I thought of having a 'classical' menu button that extends the same menu on hover or on click. Anyhow, having this button always present makes the form very cluttered (check part #2 of the image). Imagine going through this form 8 hours per day, your head will explode.
I thought about the possibility to have this button appear only on hover, but it would make the interface 'jump' a lot, and I'd possibly have to move some of the content in order to show the menu button (for example, I'd have to move the 'stale' label)
Other ideas I thought about is to have something as gmail for phones does (slide to show options 'hidden' behind the actual field) but this interaction would not really feel natural on desktop, and this web app is mostly used on desktop.
I thought about displaying on hover some icons at the bottom or right of the field but this still makes everything jump around. Furthermore, some actions (e.g. mark as stale) does not have an obvious icon to represent them.
Does anyone have any idea about how to solve this? Any existing pattern I could reuse?
Comment: I'm very interested about your comment that everything needs to fit on one page, which is simply impossible considering responsive design and zoom-levels for accessibility. I know from primary research that users comment on scrolling and might be put off at first, but I did not identify issues. Based on secondary research I believe that scrolling is not an issue and users are very well able to keep a map in mind. Have you actually identified issues in testing when scrolling is necessary?
Comment: of course, adding a table of contents would probably help a lot, which could be another first column in koosvdolk's suggestion.
Comment: And, if verifying the whole form is so important, an additional required test step might be a good idea. Users find errors more easily if they have the feeling they cannot change it directly. They would print documents or export them to PDF to proofread.
Answer: I think I would go for a side panel, something like the Wordpress Plugin Forminator (https://wordpress.org/plugins/forminator/):

See https://blog.hubspot.com/marketing/form-builder-tools for some other ideas.
Answer: I think you have already thought this through very well.

I thought about the possibility to have this button appear only on hover

I think this suggestion can work if you make sure that no content jumps around if the menu icon appears. This pattern is pretty common. The icon should also appear if the field is focused (e.g. for power users that do not use a mouse)
Comment: We're talking about a web app here, touch and keyboard control need to work as well if you're out for good usability.


inside main circuit breaker panel; what are these elements good for?

Question:
Can anyone explain what does that TeleLE circuit breaker do in there ? Also that circuit breaker looking element with only one small black square button on it please.
Comment: Where on the planet? Not my region by appearance, but I'd guess the item with the reset button is what I'd call a whole-house GFCI, but I think it's called an RCD globally. Looks for imbalance in current due to leakage and shuts off at a level of imbalance (IIRC 30ma for this type) - our single-circuit versions trip at 5ma, which is safer for people, but too sensitive for whole-house.
Comment: Looks like relay. C1 and C2 coil, 14 and 12 contacts.
Comment: Did you look for the datasheet for the device? It would explain its function.
Comment: @Transistor No, I could not find it
Answer: Shunt trip breaker add-on
This is GE's "Redline" series of miniature circuit breaker products.
The "Tele LE" device isn't in this catalog, but a "Tele L" device is. (page C.8)  There are other "Tele Lx" with a second character, and those indicate terminal type (lug, ring, etc.)  It is designed to bolt onto a Red Line circuit breaker and provide Shunt Trip for that breaker.  That means if you apply momentary current to lines C1 and 14, it trips the attached breaker.
Shunt trips are used to provide auxiliary ways of safety-tripping a circuit breaker.  For instance, at a "Maker faire" once, I saw an "phone app" with auxiliary hardware which would tell you if you left your oven on. A nice feature would be a "trip my breaker" button on the app, which would tell the hardware to send a 24V pulse to a Shunt Trip breaker in the panel.  Great application for shunt trip.
To reset a shunt-trip breaker, you have to flat-foot back to the panel and reset it by hand.  (there are good reasons for not allowing remote/automated reset!!!!)
The other terminals are an auxiliary contact tied to the breaker handle, so the position of the breaker handle can be remotely sensed.
Mystery gadget
The Tele L is 1 unit wide, so it doesn't account for the mystery gadget on the right, which is clearly not a member of GE's Red Line.  Since its label is gone, it may be illegal to have it in the panel. The button adds mystery but it's not an RCD (GFCI) tripper for this breaker - the breaker is already RCD (note the TEST button).  Obviously the sticker told the tale.
But here's a thought.  Shunt trip breakers typically use low voltage for the shunt trip coil, such as 24-60VAC for the Tele L.  It's plausible that thing is a transformer to create that low voltage supply.
GE's Red Line includes a number of transformers to fill the bill, all 2 modules wide (link, p. D.29) That might be why they weren't used.


I dont understanding eloquent js "a list" exercise (I have some odd result)

Question: I'm at the moment doing the exercises in the EloquentJS book.
chapter 4, "a list" exercise, more precisely. The exercise consist of creating and deconstructing a list from and to an array.
I've tried something that look pretty logic to me but I get a return that i don't understand.
I get a Circular tag/marker.
Here's my first try and my second try separately:
function arrayToListTry1 (array) {
  /**My solution try 1
  My observations:
  I was building it inverted (last elem in first place
  I don't understand why my version gets a circular result and the book solution doesn't
  */
    let list = {
        value: "",
        rest: {}
    };

    for (let i = 0; i < array.length; i++) {
        list.rest = list;
        list.value = array[i];
    }

    return list;
}
/**result:
node eloquentJS_chapter4_ex_arrayToList.js
{ rest: [Circular], value: 'hello' }
*/

function arrayToListTry2 (array) {

    let list = {};

    for (let i = array.length - 1; i >= 0; i--) {
        list.rest = list;
        list.value = array[i];
    }
    return list;
}

//same result

The exercise solution shows an other way I've checked it but don't understand clearly whats the problem with my solution.
I've also checked on stackoverflow what others are saying about this exercise but don't find an explanation i understand.
Here is the actual exercise solution:
function arrayToList(array) {
  let list = null;
  for (let i = array.length - 1; i >= 0; i--) {
    list = {value: array[i], rest: list};
  }
  return list;
}

/**
result:
node eloquentJS_chapter4_ex_arrayToList.js
{ value: 'hello',
  rest: { value: 'world', rest: { value: '!!!', rest: null } } }
*/

Edit:
Here's my final result, I will just past the whole file content. Thanks every one.
let listValue = {
    value: "hello",
    rest: {
        value: "world",
        rest: {
            value: "!!!",
            rest: {}
        }
    }
};

const arrayValue = ["hello", "world", "!!!"];

function arrayToList (array){
    /**Actual solution from book:
    */
// let list = null;
// for (let i = array.length - 1; i >= 0; i--) {
//   list = {value: array[i], rest: list};
// }
// return list;

  /**My solution try 1
  My observations:
  I was building it inverted (last elem in first place
  I dont understand why my version gets a circular result and the book solution doesnt
  */
//  let list = {
// //       value: "",
// //       rest: {
// //
// //       }
//  };
//
//  for (let i = 0; i < array.length; i++) {
//      list.rest = list;
//      list.value = array[i];
//      // console.log(list);
//      // console.log(list.rest);
//  }
//  //console.log(list.rest);
//  // console.log("result:");
//  return list;

  /** try 2
  */
// let list = {};
//
// for (let i = array.length - 1; i >= 0; i--) {
//  list.rest = list;
//  list.value = array[i];
// }
// return list;

/** try 3
    Every loop creates a new list object containing the old one.
    But i still dont see why my tries above don't work.
*/
    let list = {};

    for (let i = array.length - 1; i >= 0; i--) {
        list = {
            value: array[i],
            rest: list
        }
        // console.log(list);
    }

    return list;
}
/***
An other possibility that relate more to my thought process. Given to me on stackoverflow
function arrayToListTry4 (array) {
    let list = {}
    for (let i = array.length - 1; i >= 0; i--) {
        list.rest = Object.assign({}, list);
        list.value = array[i];
    }

    return list
}
**/

function listToArray (list){
    let arr = [];

    while (list.rest !== undefined ) {
        arr.push(list.value);
        list = list.rest;
        // console.log(list);
        // console.log(arr);
    }

    return arr;
}

function prepend (item, list){

    return { value: item, rest: list};
}

function nth (list, nth){
    for (var i = 0; i < nth -1; i++) {
        list = list.rest
    }

    return list.value
}

function recNth (list, nth){

    if (nth - 1 == 0) {
        return list.value;
    } else {
        return recGetNth(list.rest, nth -1);
    }
}

console.log(arrayToList(arrayValue));
// → { value: 'hello',
       rest: { value: 'world', rest: { value: '!!!', rest: {} } } }

console.log(listToArray(list));
// → [ 'hello', 'world', '!!!' ]

console.log(listToArray(arrayToList(arrayValue)));
// → [ 'hello', 'world', '!!!' ]

console.log(arrayToList(listToArray(listValue)));
// → { value: 'hello',
       rest: { value: 'world', rest: { value: '!!!', rest: {} } } }

console.log(prepend("Hey", listValue));
// → { value: 'Hey',
       rest: { value: 'hello', rest: { value: 'world', rest: { value: '!!!', rest: {} } } } }

console.log(nth(listValue, 3));
// → "!!!"

console.log(recNth(listValue, 2));
// → "world"

Comment: "*a list exercise, more precisely*" and what exactly is the goal of the exercise?
Comment: I've also tried to JSON.stringify my list but it return the same result
Answer: Your for loop is basically this statement:
list.rest = list; // this gets constantly reassigned
list.value = array[array.length - 1];

As rest is the same as list, there as a cycle and JS shows you this cycle.
The book solution avoids this problem by creating new lists instead of reusing the same list again and again.
Answer: In list.rest = list; you are setting the list.rest property back as a reference to itself which is why it says "Circular". This is because in Javascript, Objects and Arrays are passed by reference.
What you want to do is create a deep-copy of the original element. You can do that a few ways:
JSON.parse(JSON.stringify(list)) will deconstruct to and from JSON (preserving all keys and all object depth). Alternatively Object.assign({}, list) will assign all of the object's 1st level keys to the new object. This means an object like this:
{
   root: {
      inner: "test",
   }
}

Will only be assigned the root key, but the inner will not get copied when doing Object.assign
Thus a solution for you would be:
for (let i = array.length - 1; i >= 0; i--) {
        list.rest = Object.assign({}, list);
        list.value = array[i];
    }

or
for (let i = array.length - 1; i >= 0; i--) {
        list.rest = JSON.parse(JSON.stringify(list));
        list.value = array[i];
    }

Comment: Thank a lot that exactly what I was asking for. It seems like  I had some misunderstanding on this concept about JavaScript.


twisted python TCP4ServerEndpoint

Question: error no module TCP4.... found.
both on windows and ubuntu 10.04..
do i need to install anything new.
I tried to copy endpoints.py to a directory. but not worked
Answer: Ubuntu 10.04 includes Twisted 10.0.0, but the twisted.internet.endpoints module was introduced in Twisted 10.1.0. You can find more recent versions on the twistedmatrix.com or the PYPI Twisted project page.
Once you have a more recent version installed, here is the import path to the TCP4ServerEndpoint class:
from twisted.internet.endpoints import TCP4ServerEndpoint

twisted python TCP4ServerEndpoint