text:
Q: hide all actionbar content I'm trying to use a custom layout for the action bar, but i cannot seem to hide all the standard content from the action bar as you can see in the attached screenshot

Here is my code where i try to hide all the data.
getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.nav_bar));
getSupportActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);

I'm using appcompat and building with android lollipop (21).
This is my custom layout actionbar.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scaleType="fitXY"
    android:src="@drawable/nav_bar"/>

<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Title"
    android:layout_centerInParent="true"
    android:textColor="@color/irapptheme_color"
    android:textSize="20sp"/>

<ImageButton
    android:id="@+id/btn_back"
    android:layout_width="48dp"
    android:layout_height="match_parent"
    android:background="@android:color/darker_gray"
    android:padding="12dp"
    android:layout_centerVertical="true"
    android:scaleType="fitCenter"
    android:src="@drawable/btn_back"
    android:visibility="gone"/>

<ImageButton
    android:id="@+id/btn_search"
    android:layout_width="48dp"
    android:layout_height="match_parent"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:padding="12dp"
    android:background="@android:color/transparent"
    android:src="@drawable/btn_search"
    android:visibility="gone"/>

A: Is getActionBar().hide() not working ?

A: Use the new ToolBar (available in stock android 21 or in appcompat-v7). It's a new ViewGroup designed to replace the ActionBar and its far more flexible than the ActionBar. You control everything, therefor you can hide everything.


text:
Q: Sharepoint Search 2013 - is there any way to index a list of URLs stored in a database? I have a database table with a list of URLs that I would like Sharepoint Search 2013 to index so they show up in search results - the URLs are a mixture of content types - web pages, Word documents, PDFs, etc.
All the URLs are internal to my network but aren't Sharepoint pages or files stored in Sharepoint.
I am using Sharepoint 2013 Enterprise Search on a Windows 2008 R2 server.
Does anyone have any ideas on how to achieve this?
I have searched for options but can't seem to find anything relevant - BDC and BCS have come up a lot but seems to be more indexing content returned by the connector.  What I want to do is to use the data returned from the table as pointer to items to be indexed.
I'm very new to Sharepoint and Sharepoint Search and am at a bit of loss on how to go about this (to make it even more difficult I would like to apply ACLs to the results, and the ACLs are in another table but that's another question!). Given my experience level I would like the answer to be as basic as possible if you can, but any help would be apprecieated.

A: BDC and BCS is the proper way to do it, but it's very complicated. If you want something simple, create a small script that writes all the URLs to a single HTML document. Then use the web crawler to crawl this document. It will follow the links and crawl the content.

redpajama_set_name: RedPajamaStackExchange


text:
Q: python: recover exception from try block if finally block raises exception Say I have some code like this:
try:
    try:
        raise Exception("in the try")
    finally:
        raise Exception("in the finally")
except Exception, e:
    print "try block failed: %s" % (e,)

The output is:
try block failed: in the finally

From the point of that print statement, is there any way to access the exception raised in the try, or has it disappeared forever?
NOTE: I don't have a use case in mind; this is just curiosity.

A: I can't find any information about whether this has been backported and don't have a Py2 installation handy, but in Python 3, e has an attribute called e.__context__, so that:
try:
    try:
        raise Exception("in the try")
    finally:
        raise Exception("in the finally")
except Exception as e:
    print(repr(e.__context__))

gives:
Exception('in the try',)

According to PEP 3314, before __context__ was added, information about the original exception was unavailable.

A: try:
    try:
        raise Exception("in the try")
    except Exception, e:
        print "try block failed"
    finally:
        raise Exception("in the finally")
except Exception, e:
    print "finally block failed: %s" % (e,)

However, It would be a good idea to avoid having code that is likely to throw an exception in the finally block - usually you just use it to do cleanup etc. anyway.


text:
Q: Активная ссылка в python kivy Моя программа выдает на экран множество разных ссылок, мне бы хотелось узнать, как сделать их активными (чтобы на них можно было нажать и перейти на страницу в интернете)?

A: Label:
    markup: True
    text: '[ref=]My link[/ref]'
    on_ref_press: webbrowser.open(link)


text:
Q: Unable to connect to Oracle database 21c I have fresh Oracle Linux with Oracle Database 21c installed on it.
Issue is I cannot connect to it from the outside, locally there is no problem.
lsof was showing that port 1521 was open only for IPv6, so I changed the listener.ora config to:
(ADDRESS = (PROTOCOL = TCP)(HOST = linux-oracledb)(PORT = 1521)(IP=V4_ONLY))

lsof is showing:
tnslsnr   1285 oracle    9u  IPv4  27233      0t0  TCP *:1521 (LISTEN)

But when I'm testing the connection from another pc I have:

TCP connect to (10.10.8.44 : 1521) failed

Firewall rules are ok.
Any idea what I am missing here?

A: Starting with a disclaimer here - I am not an Oracle guy so don't be hard on me. But do you know if your server is listening on 127.0.0.1, 10.10.8.44, or something else? I think you will need it to have it listen on 0.0.0.0 for receiving outside connection


text:
Q: Can I keep a commit but remove all the changes? Is there a simple way to revert all the changes of a commit but keep the commit itself? I have a lot of files in my commit, and most of them are generated. After a minor change all those files needs to be removed or reverted.
So the obvious way to do this is to git rm those files and git reset the ones that are not new files. But is there a faster way to do this? If I create a new commit on another branch and copy the change id will it become another patch for the same commit?
Edit:
To clarify I just want to undo the changes made to the current commit without checking out a new commit or creating a new one. I have posted an answer myself which takes the diff with the previous commit and either removes the files or reverts it depending on if they were newly created or modified. There might be a better solution however but this works for my use case.

A: In case, you don't want to commit modified files. You can take git stash into consideration.

*

*git stash to reset all files which have been modified or added to git.

*git stash pop when I want to restored files have been stashed.

In other hand, if you committed those files, you could use git checkout, git reset or git revert

A: I found a decent solution. Running these two commands will restore all the changes in the commit without removing the commit.
git diff-tree -no-commit-id --name-status -r HEAD | grep -oP '(?<=A).*' | xargs git rm
git diff-tree -no-commit-id --name-status -r HEAD | grep -oP '(?<=M).*' | xargs git checkout HEAD~1
The first line removes all the added files and the second line restores the changes made to already existing files.
The first command git diff-tree returns the changes in the commit, option --no-commit-id removes the id and --name-status only returns the name of the files and the character that indicates if it is a new file, modified or a deleted file. The result is piped into a grep command that searches for either A or M (added or modified files) and returns the line excluding that character. Finally xargs transforms the output to arguments and then I perform the necessary git command on the files, git rm for added files and git checkout HEAD~1 for modified files.


text:
Q: question mark inside ant property I want to put a question mark character in an ant property (via a property file), but I keep getting a Dangling meta character '?' error. How on earth do I put a question mark inside an ant property??

I have the following inside an ant property file:
 installerTemplate=E:/projectX/branch/?/path/to/installer.exe
 installerBranch=foobar

ant file:
<project .... >
    <taskdef resource="net/sf/antcontrib/antcontrib.properties"/>
    <property file="project.properties" />

    <target name="fixPath">
        <propertyregex property="installerFileLocation" input="${installerTemplate}"
            regexp="?" replace="${installerVersion}" global="true" />
        <propertyregex property="installerFileLocation.win" input="${installerFileLocation}"
            regexp="/" replace="\\\\"/>
        <echo>${installerFileLocation.win}</echo>
    </target>
</project>

But whenever I run ant, I get this:
BUILD FAILED
E:\p4-abird\depot_cfg\ssb\tools\ssb_dev_env_automation\create_ssb_vm.xml:37: java.util.regex.PatternSyntaxException: Dangling meta character '?' near index 0
?
^
    at java.util.regex.Pattern.error(Pattern.java:1713)
    at java.util.regex.Pattern.sequence(Pattern.java:1878)
    at java.util.regex.Pattern.expr(Pattern.java:1752)
    at java.util.regex.Pattern.compile(Pattern.java:1460)
    at java.util.regex.Pattern.<init>(Pattern.java:1133)
    at java.util.regex.Pattern.compile(Pattern.java:847)
    at org.apache.tools.ant.util.regexp.Jdk14RegexpMatcher.getCompiledPattern(Jdk14RegexpMatcher.java:67)
    at org.apache.tools.ant.util.regexp.Jdk14RegexpMatcher.matches(Jdk14RegexpMatcher.java:94)
    at net.sf.antcontrib.property.RegexTask.doReplace(RegexTask.java:135)
    at net.sf.antcontrib.property.RegexTask.execute(RegexTask.java:192)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
    at org.apache.tools.ant.Task.perform(Task.java:348)
    at org.apache.tools.ant.Target.execute(Target.java:392)
    at org.apache.tools.ant.Target.performTasks(Target.java:413)
    at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1399)
    at org.apache.tools.ant.Project.executeTarget(Project.java:1368)
    at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
    at org.apache.tools.ant.Project.executeTargets(Project.java:1251)
    at org.apache.tools.ant.Main.runBuild(Main.java:811)
    at org.apache.tools.ant.Main.startAnt(Main.java:217)
    at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)
    at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)

Total time: 0 seconds

How on earth do I put a question mark inside an ant property??

A: The problem seems to be with:
regexp="?"

'?' is a regex meta char that has special meanings in the regex pattern. If you want to match the literal '?' char, you'll need to escape it.


text:
Q: How to find out IP address and default gateway in XP in cmd when DHCP is enabled? When DHCP is disabled and network is setup manually, I can run
netsh interface ip show config

to see IP address and default gateway. However, when DHCP is enabled I can see only that DHCP is enabled and DNS server address.
Is there a way to see a client IP address and a default gateway in XP via command prompt and netsh when DHCP is enabled?

A: ipconfig is the command that you need for this.


text:
Q: Updating the GUI from background worker The name of the question is: "Updating the GUI from background worker", but the correct name world be: "Updating the GUI from background worker OR reporting multiple-variables (other than an integer) from background worker"
Please let me explain my situation. In a program I have a background worker which analyses the information.As the result of this analysis - form GUI  elements should be populated with necessary data. In GUI I would like to update

*

*2 datagridviews

*1 listbox

*5 labels

As I understand - I can only natively report 1 int value via ReportProgress() method of background worker.
So the question is - how can I pass a List<> ( + some other variables: string, int) via ReportProgress()? Basically - i want to update the GUI with the information but "1 integer" just won't do.. So either it should be possible to pass multiple variables via an  ReportProgress() OR i can use an Invoke from inside the BackgroundWorker itself to update the GUI.. Personally I don't like the Invoke approach... What's your opinion?
Here is my code (see the comments):
   private void button9_Click(object sender, EventArgs e) // start BW
    {
        bw.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
        bw.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);

        bw.WorkerReportsProgress = true;
        bw.WorkerSupportsCancellation = true;

        bw.RunWorkerAsync(10);
    }

    private void button10_Click(object sender, EventArgs e) // cancel BW
    {
        bw.CancelAsync();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        int count = (int)e.Argument;
        for (int i = 1; i <= count; i++)
        {
            if (bw.CancellationPending)
            {
                e.Cancel = true;
                break;
            }

            List<List<string>> list_result = new List<List<string>>();
            list_result = Proccess();

            bw.ReportProgress(list_result.Count()); // right now I can only return a single INT

            /////////// UPDATE GUI //////////////
            // change datagridview 1 based on "list_result" values
            // change datagridview 2
            // change listbox
            // change label 1
            // change label ..

            Thread.Sleep(20000);
        }

        MessageBox.Show("Complete!");
        e.Result = sum;
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        prog_count++;
        listBox1.Items.Add("Count: (" + prog_count.ToString() + "/20). Found: " + e.ProgressPercentage.ToString() + ".");
    }

A: There's a UserState parameter when calling ReportProgress.
var list_result = new List<List<string>>();

new backgroundWorker1.ReportProgress(0, list_result);

The parameter type is an object so you'll have to cast it back to the type you need:
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    var userState = (List<List<string>>)e.UserState;
}

The tricky issue with this is, how do you determine whether you're passing back a List, or a list of lists, or a single string, number, etc. You'll have to test for each possibility in the ProgressChanged event.
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    var myList = e.UserState as List<List<string>>;
    if (myList != null)
    {
        // use list
        return;
    }

    int myNumber;
    if (Int32.TryParse(e.UserState.ToString(), out myNumber))
    {
        // use number
        return;
    }

    var myString = e.UserState.ToString();
    // use string
}

Alternatively, you could create a class that holds all the values you need (or use Tuple), run everything in the background to populate that class, then pass that to the RunWorkerCompleted event, and update your UI all at once from there.

A: I have written two very easy methods that enable you to invoke your code (only if required) and you only need to write your code once. I think this makes Invoke much friendlier to use:
1) BeginInvoke
public static void SafeBeginInvoke(System.Windows.Forms.Control control, System.Action action)
{
    if (control.InvokeRequired)
        control.BeginInvoke(new System.Windows.Forms.MethodInvoker(() => { action(); }));
    else
        action();
}

2) Invoke
public static void SafeInvoke(System.Windows.Forms.Control control, System.Action action)
{
    if (control.InvokeRequired)
        control.Invoke(new System.Windows.Forms.MethodInvoker(() => { action(); }));
    else
        action();
}

It can be called like this:
SafeInvoke(textbox, () => { textbox.Text = "text got changed"; });

Alternatively you could just
System.Windows.Forms.Form.CheckForIllegalCrossThreadCalls = false;

(which only changes behaviour in debug mode btw) and look if you run into problems.More often than not you actually don't. It took me quite some time to find cases very Invoke is really required for things not to get messed up.

A: The basic pattern for updating the UI from another thread is:
If controlItem.InvokeRequired Then
    controlItem.Invoke(Sub() controlItem.Text = textUpdateValue)
Else
    controlItem.Text = textUpdateValue
End If

This could update your list of controls without requiring you to pass anything through ReportProgress. If you would like to update your control from within the thread, I don't believe you need to check InvokeRequired, because it will always be required. However, best practices might be to expose the setting of a control via a property and then to do the full check so you can call it from anywhere.


text:
Q: Jump to the first occurrence of symbol in Emacs I use the excellent highlight-symbol.el to move between different occurrences of the same symbol.

In this screenshot, foo_bar is highlighted, and I can call highlight-symbol-prev to jump to it. Note that this is syntax-aware, so it's smart enough to know that foo_bar_baz is different (something isearch doesn't understand).
I'd really like to be able to jump to the first occurrence of a symbol. This would be brilliant for finding where symbols were imported. How would I go about this?

A: Something along these lines should do what you want.
(defun goto-first-reference ()
  (interactive)
  (eval
   `(progn
      (goto-char (point-min))
      (search-forward-regexp
       (rx symbol-start ,(thing-at-point 'symbol) symbol-end))
      (beginning-of-thing 'symbol))))

A: (eval-when-compile (require 'cl))
(require 'highlight-symbol)

(defmacro save-mark-ring (&rest body)
  "Save mark-ring; execute BODY; restore the old mark-ring."
  `(let ((old-mark-ring mark-ring))
    ,@body
    (setq mark-ring old-mark-ring)))

(defun highlight-symbol-jump-to-first ()
  "Jump to the first occurrence of the symbol at point."
  (interactive)
  (push-mark)
  (save-mark-ring
   (let (earliest-symbol-pos)
     (loop do
           (highlight-symbol-jump -1)
           (setq earliest-symbol-pos (point))
           while (< (point) earliest-symbol-pos)))))


text:
Q: Allow multiple controllers to users according to their role in cakephp Suppose, there are two roles: one is admin, another is restaurant_owner.
I want to give access to some of the pages to restaurant_owner.
In AppController, I used beforeFilter function. Here is the code..
public function beforeFilter() {
   if($this->Auth->user('role') == 'restaurant_owner'){
     /* Controllers Name, that Admin want to give access to restaurant admin*/
      $this->loadModel('Userpermission');
      $AuthPermission = $this->Userpermission->find('first',array('conditions' => array('Userpermission.user_id' => $this->Auth->user('id'))));
      print_r($AuthPermission); //returns controller names e.g. receipes, menuitems
  }
}

My question is, how I deny access to role restaurant_owner to all controllers except but a few? I'm using CakePHP 2.x.

A: The proper way of handling this is through ControllerAuthorize and the AuthComponent::isAuthorized() callback.
First, you have to enable this functionality in AppController. Edit your Auth config and array and add the following:
public $components = array(
    'Auth' => array('authorize' => 'Controller'),
);

Then add the following to the controllers which restaurant_owner should have access to:
public function isAuthorized($user) {

    if ($user['role']=="restaurant_owner") {
        return true;
    }

    return parent::isAuthorized($user);
}

Finally, add the following to AppController:
public function isAuthorized($user) {

    if ($user['role']=="restaurant_owner") {
        return false;
    }

    return true; //Every other role is authorized
}

You will have to tweak the above logic to match your needs.


text:
Q: how to convert my integer value to a string of binary values I need to convert a nummeric value (integer) to a binary string in R. This is what my dataframe looks like:
     V1 V2 V3
  1  1  90 336
  2  1  90 336
  3  3  4  420
  4  12 2  413
  5  12 4  411

I want a first row with a zero followed by 90 1's and 336 zeros again (so read by row). So the output would be a matrix with 427 columns and 5 rows. Also if possible I would like the NA's to be read as for 1's.
Dirk

A: Try this
df <- read.table(header = TRUE, text="     V1 V2 V3
  1  1  90 336
  2  1  90 336
  3  3  4  420
  4  12 2  413
  5  12 4  411")
mat <- matrix(apply(df, 1, function(x) {
  rep(c(0, 1, 0), x)
}), nrow = 5, ncol = 427, byrow = TRUE)


text:
Q: Covering space morphism maps each sheet onto some other sheet I am considering a connected topological space $X$, with a connected covering space $Y$ and $p:Y \to X$. Is it true that given any continuous map $f:Y\to Y$ such that $p=p\circ f$, $f$ always maps a sheet onto some other sheet?
If not, under what conditions of $Y$ can we conclude this?


text:
Q: php pagination getting error (Fatal Error:unspported operand types) I got an Error Fatal error: Unsupported operand types in line12 while doing pagination in my page. Please help me how to solve this
<?php
 require_once("pagination.php");
    $page=1;//Default page
    $limit=1;//Records per page
    $start=0;//starts displaying records from 0
    if(isset($_GET['page']) && $_GET['page']!=''){
    $page=$_GET['page'];
    }
    $start=($page-1)*$limit;
    ?>

A: try:
$start = (is_numeric($page) ? (int)$page : 0)*limit;

How to get int instead string from form?


text:
Q: Dynamically call javascript object function from html I'm working on a kind of javascript text-based game engine. I have a javascript object with an 'onuse' method. This works fantastically when I use it like this:
var button = new CanvasObject();
button.text = "test" // Necessary for the next code sample
button.onuse = function(){ button.x += 1 }; // Some simple reaction;

I have code in a Canvas object that when drawing a CanvasObject will wrap it in a span tag like so:
test
// Or to make the HTML cleaner:
test
// where canvas.callFunction will call the function needed.
// Canvas keeps an array of functions that can be called.

The Canvas will call the function, and since it uses 'absolute' terms, the line 'button.x += 1', will work fine. The problem is that I have another class that I extended from CanvasObject, for example, ButtonObject. I want the class definition to have an onuse function that is already defined. For example (using the inheritance technique lined out here)
ButtonObject.method('onuse', function(){
   this.x++; // Some function requiring 'this'.
});

When I called a function from the HTML using the first technique, my engine would just call it as an anonymous function. Then, 'this' then would be defined as the window. I want every instance of ButtonObject to have the same 'onuse' function, so defining it each time like I did with CanvasObject seems like a lot of extra code. One possible solution I thought of was to modify the way my engine works such that each object is given a 'name' property, that is equivalent to it's javascript name. This way the engine could simple write the string like this:
innerHTML += ( "" );

But this technique would require me to state the name of the object twice, every time I instantiate it, like this:
var startButton = ButtonObject('startButton');

Is this truly my only option? Or is there way to call a function in the context of the object without having the name of that object?

A: bind a function to this for later:
ButtonObject.method('onuse', function(){
   this.x++; // Some function requiring 'this'.
} .bind(ButtonObject)  );

of if not ButtonObject in the calling context, bind it to whatever holds your methods.


text:
Q: Instantiation error I am following a beginner's java book and one of the projects is to pick an error from commonly thrown errors and try to do what you can to induce the error.
I picked InstantiationError and am up to the level of knowing you can't instantiate abstract classes or interfaces. The docs says the error is usually caught by the compiler but can be thrown at runtime if the definition of a class has incompatibly changed.
I don't know how a class definition could be changed while the program is running and am looking for some tips on where I should read further.
Thanks!

A:
I don't know how a class definition could be changed while the program is running

It can't change while it's running but it can change after you've compiled.
For example, try this:
// In Test.java
public class Test {
    public static void main(String[] args){
        System.out.println(new Foo());
    }
}

// In Foo.java
public class Foo {
}

Compile:
javac Foo.java Test.java

Run:
java Test

// Some output like this...
Foo@1d6535bf

Now change Foo.java like this:
// No parameterless constructor any more!
public class Foo {
    public Foo(int x) {
    }
}

Recompile just Foo.java:
javac Foo.java

And rerun Test:
Exception in thread "main" java.lang.NoSuchMethodError: Foo: method <init>()V
    not found
    at Test.main(Test.java:3)

This is not what I'd call a "commonly thrown error" though.
Note that that's not InstantiationError - but you can change Foo.java again, to:
public interface Foo {
}

Again, just recompile Foo.java and this time you'll get:
Exception in thread "main" java.lang.InstantiationError: Foo
        at Test.main(Test.java:3)

A: Maybe when you instantiate an abstract class at runtime using reflection.
Code sample:
public abstract class MyAbstractClass{
}

public class MyMainClass() {
    public void test(String[] args) {
             this.getClass().getClassLoader().loadClass("MyAbstractClass").getConstructors()[0].newInstance();
    }
}

A: Have a look at the Reflection API, which offers a way to instantiate a class by name.
public void throwError() {
    AbstractType type = this.getClassLoader().newInstance("my.abstract.Type");
}

A: a simple thing that can cause this type of error is if you try to create an object with the wrong number of parameters. say the constructor takes two parameters, but you have your interface designed in such a way that the user could input 3 or more parameters. normally, the number of parameters would be caught by the compiler, but if it was created "on the fly" then it would get caught at runtime


text:
Q: getting some problem with gridview paging I have two pages.
In one page I have placed a GridView. In the grid I am using two hyperlinks for select and edit. When I click for the edit page I am redirected to another page. When I have finished editing the record it goes back to the first page.
The problem is when I was on the 2nd or 3rd page of the GridView and then edited, it went back to first page, not the 2nd or 3rd page I was on.
I want the same page after I go back to the page I left. How can I go about this?

A: Response.Redirect("einward.aspx");

you have to redirect to the page, wtever page u want.

A: The problem is that the webpage needs to know what page to send you to. The way I do this is to pass a querystring parameter when I change pages.
So in the URL to the edit page you want to have the URL say (for example) http://server/edit.aspx?value=number&returnPage=2 and then when you go back to the grid page you'll pass the page value like http://server/grid.aspx?page=2
This way you'll always know what page to tell the GridView to goto. And it should be pretty easy to add in depending on your level of comfort with the Params object.


text:
Q: How to format number in pandas plot table? I have some data that I can plot using pandas plot command. I can plot a bar chart with a table, using this plotdata.plot(kind='bar', colormap='gnuplot', ylabel = 'Yield', xticks=[], table=True). But I cannot figure out how to format the numbers in the table.

I tried to use the applymap('{:,.2f}'.format) in the command.
plotdata.applymap('{:,.2f}'.format).plot(kind='bar', colormap='gnuplot', ylabel = 'Yield', xticks=[], table=True)
But then all the data in the dataframe are strings and pandas cannot plot anything.
Error:
no numeric data to plot
I tried to google the problem but cannot find something.


text:
Q: How does an inductor store energy? I know that the capacitors store energy by accumulating charges at their plates, similarly people say that an inductor stores energy in its magnetic field. I cannot understand this statement. I can't figure out how an inductor stores energy in its magnetic field, that is I cannot visualize it.
Generally, when electrons move across an inductor, what happens to the electrons, and how do they get blocked by the magnetic field? Can someone explain this to me conceptually?
And also please explain these:

*

*If electrons flow through the wire, how are they converted to energy in the magnetic field?

*How does back-EMF get generated?

A: This is my way of visualizing the concept of inductor and capacitor.
The way is to visualize potential energy and kinetic energy, and understanding the interaction between these two forms of energy.

*

*Capacitor is analogous to a spring, and

*Inductor is analogous to a water wheel.

Now see the comparisons.
Spring energy is \$\frac{1}{2}kx^2\$, whereas capacitor energy is \$\frac{1}{2}CV^2\$.
So, capacitance, \$C\$ is analogous to the spring constant, \$k\$.
Capacitance voltage,\$V\$, is analogous to spring displacement, \$x\$.
Electric field across the capacitance is analogous to the force generated across the spring. What happens is that the kinetic energy of electrons are stored in the capacitor as potential energy. The resultant potential energy difference is the voltage which is kind of a pressure in the form of electric field. So, the capacitor always pushes the electrons back because of its potential energy.
Next, the kinetic energy of a water wheel can be expressed as \$\frac{1}{2}I\omega^2\$, where \$I\$ is the moment of inertia and \$\omega\$ is the angular frequency.
Whereas, the energy stored in an inductor is \$\frac{1}{2}Li^2\$, where \$i\$ is the current. Thus, current is analogous to velocity which it is as \$i = \frac{dq}{dt}\$.
When current flows through a wire, the moving electrons create a magnetic field around the wire. For a straight wire, the generated magnetic field will not effect the electrons in that wire or at least can be ignored in most cases. However, if we wind the wires several thousands times such that the generated magnetic field affects the wire electrons themselves, then any change in the velocity will be opposed by the force from the magnetic field. Thus, the overall force, \$F\$, electrons face is expressed by \$\mathbf{F} = q\mathbf{E} + q\mathbf{v} \times \mathbf{B}\$.
The potential energy in a capacitor is stored in the form of electric field, and the kinetic energy in an inductor is stored in the form of magnetic field.
In summary, inductor acts as inertia which reacts against the change in velocity of electrons, and capacitor acts as spring which reacts against the applied force.
Using the above analogies, you can easily find why the phase relationships between voltage and current are different for inductors and capacitors. This analogy also helps to understand energy exchange mechanism between a capacitor and an inductor such as in a LC oscillator.
For further thinking, ask the following questions. How the kinetic energy in a mechanical system is stored? When we are running, where and how is the kinetic energy stored? When we are running, are we creating a field that interacts on our moving body?

A: One way to conceptualize it is to imagine it to be similar to inertia of the current through the inductor. A good way to illustrate it is with the idea of a hydraulic ram pump:
In a hydraulic ram pump, water flows through a large pipe, into a fast acting valve. When the valve closes, the inertia of the heavy flowing mass of water causes a sudden huge increase in water pressure at the valve. This pressure then forces water upwards through a one way valve. As the energy from the water ram dissipates, the main fast acting valve opens, and the water builds up some momentum in the main pipe, and the cycle repeats again. See the wiki page for an illustration.
This is exactly how boost converters work, only with electricity instead of water. The water flowing through the pipe is equivelant to an inductor. Just like the water in the pipe resists changes in flow, the inductor resists change in current.

A: A capacitor can store energy: -
Energy = \$\dfrac{C\cdot V^2}{2}\$ where V is applied voltage and C is capacitance.
For an inductor it is this: -
Energy = \$\dfrac{L\cdot I^2}{2}\$ where L is inductance and I is the current flowing.
Me in particular, I always have trouble visualizing charge and voltage but I never have trouble visualizing current (except when it comes to realizing that current is flow of charge). I accept that voltage is what it is and just live with that. Maybe I think too hard. Maybe you do too?
I end up going back to basics and this for me, is as far as I want to go back because I'm not a physicist. Basics: -
Q = CV or \$\dfrac{dQ}{dt} = C\cdot\dfrac{dV}{dt}\$ = current, I
What this tells me is that for a given rate of change of voltage across a capacitor, there is a current OR, if you force a current thru a capacitor there will be a ramping voltage.
There is a similar formula for an inductor which basically tells you that for a given voltage placed across the terminals, the current will ramp up proportionately: -
V = \$L\dfrac{di}{dt}\$ when V is applied to the terminals and
V = \$-L\dfrac{di}{dt}\$ when computing the back emf due to external flux collapsing or flux from another coil changing.
These two formulas explain to me what goes on.

A: May be we can visualize it in this way. Inductors are made by making conductor turns over a magnetic core or just air. Unlike a capacitor, in which a dielectric substance is sandwiched between conductors plates.
every atom acts as a current carrying loop. It is so because, electron revolve in a circular path. This give rise to magnetic dipoles (atoms) inside substances. Initially all the magnetic dipoles are randomly directed inside a substance, making the resultant direction of magnetic field lines to be null.
Current flows due to flow of electrons. In a circuit consisting of an inductor, there is a specific direction of current flow (or electron flow) through the inductor. as such, this current tries to align the magnetic dipoles in a specific direction.
The reluctance of the magnetic dipoles to get aligned in a specific direction, is responsible for the opposition of current. the opposition can be called as back emf.
This opposition offered is different for different material. hence, we have different reluctance values. the inductor is said to be saturated when all the magnetic dipoles are aligned in the specific direction which is given by Fleming's Right Hand Thumb Rule. the direction of opposition is given by Lenz's Law (the direction of back emf).
These magnetic dipoles are only responsible for the storage of magnetic energy. Assume this inductor connected to a closed circuit without any current supply. now the aligned magnetic dipoles try to retain their initial position, because of the absence of current. This results in the flow of current. it can be said that the, energy stored in the the inductor is due to the temporary alignment of these dipoles. but few magnetic dipoles can not attain their initial configuration. hence, we say pure inductor is not present practically.
Scientists know that the electric fields and magnetic fields are co-related. This was first confirmed by Oersted by his experiment with a magnetic compass. even scientist believe that magnetic behavior is exhibited by individual electrons too, due to their spin about their own axis.

A: This is a deeper question than it sounds. Even physicists disagree over the exact meaning of storing energy in a field, or even whether that's a good description of what happens. It doesn't help that magnetic fields are a relativistic effect, and thus inherently weird.
I'm not a solid state physicist, but I'll try to answer your question about electrons. Let's look at this circuit:

simulate this circuit – Schematic created using CircuitLab
To start with, there's no voltage across or current through the inductor. When the switch closes, current begins to flow. As the current flows, it creates a magnetic field. That takes energy, which comes from the electrons. There are two ways to look at this:

*

*Circuit theory: In an inductor, a changing current creates a voltage across the inductor \$(V = L\frac{di}{dt})\$. Voltage times current is power. Thus, changing an inductor current takes energy.

*Physics: A changing magnetic field creates an electric field. This electric field pushes back on the electrons, absorbing energy in the process. Thus, accelerating electrons takes energy, over and above what you'd expect from the electron's inertial mass alone.
Eventually, the current reaches 1 amp and stays there due to the resistor. With a constant current, there's no voltage across the inductor \$(V = L\frac{di}{dt} = 0)\$. With a constant magnetic field, there's no induced electric field.
Now, what if we reduce the voltage source to 0 volts? The electrons lose energy in the resistor and begin to slow down. As they do so, the magnetic field begins to collapse. This again creates an electric field in the inductor, but this time it pushes on the electrons to keep them going, giving them energy. The current finally stops once the magnetic field is gone.
What if we try opening the switch while current is flowing? The electrons all try to stop instantaneously. This causes the magnetic field to collapse all at once, which creates a massive electric field. This field is often big enough to push the electrons out of the metal and across the air gap in the switch, creating a spark. (The energy is finite but the power is very high.)
The back-EMF is the voltage created by the induced electric field when the magnetic field changes.
You might be wondering why this stuff doesn't happen in a resistor or a wire. The answer is that is does -- any current flow is going to produce a magnetic field. However, the inductance of these components is small -- a common estimate is 20 nH/inch for traces on a PCB, for example. This doesn't become a huge issue until you get into the megahertz range, at which point you start having to use special design techniques to minimize inductance.

A: Picture a series circuit comprising an ideal capacitor, C, an ideal inductor, L, and a switch. The inductor has a soft magnetic core, such that the strength of its magnetic field is proportional to the current flowing through it. The capacitor dielectric is perfect and thus there are no losses.
Initially, let's assume the switch is open and all initial conditions are zero. That is, there is zero charge on the capacitor, zero current through the inductor and hence the magnetic field in the core is zero. We give the capacitor an initial charge to V volts using a battery.
The switch is now closed, at t=0, and L and C form a simple series circuit. At all values of time after switch closure, the capacitor voltage must equal the inductor voltage (Kirchoff's voltage law). So what happens????

*

*At t=o, the voltage across C is V, so the voltage across L must also be V. Therefore the rate of change of current, di/dt, from C to L, must be such that Ldi/dt = V. Thus, the rate of change of current is quite large, but the current itself, at the instant t=0 is i=0, and di/dt = V/L

*As time progresses, the voltage across C decreases (as the charge flows out) and the rate of change of current necessary to maintain the inductor voltage at the same level as the capacitor voltage decreases. The current is still increasing, but its gradient is decreasing.

*As the current inceases, the strength of the magnetic field in the inductor core increase (field strength is proportional to current).

*At the point where the capacitor has lost all its charge, the capacitor voltage is zero, the current is at its maximum value (it's been increasing since t=0), but the rate of change, di/dt, is now zero since the inductor does not need to generate a voltage to balance the capacitor voltage. Also at this point the magnetic field is at its maximum strength (actually, energy stored is LI^2/2, where I is the maximum current and this equates to the original energy in C = CV^2/2

*Now there is no more energy left in the capacitor, so it is unable to supply any current to maintain the inductor's magnetic field. The magnetic field starts to collapse, but in so doing it creates a current that tends to oppose the collapsing magnetic field (Lenz's law). This current is in the same direction as the original current flowing in the circuit but it now acts to charge the capacitor in the opposite direction (i.e. whereas the top plate may have originally been positive, now the bottom plate is being charged positive).

*The inductor is now in the driving seat. It's generating a current, i, in response to the collapsing magnetic field and, because this current is decreasing from its original value (I), a voltage is generated with magnitude, Ldi/dt (opposite polarity to previous).

*This regime continues until the magnetic field has completely dissipated, having transferred its energy back to the capacitor, albeit with opposite polarity, and the whole operation starts again but this time the capacitor forces current around the circuit in the opposite direction to previous.

*The above represents the positive half-cycle of the current waveform and step 7 is the begining of the negative half-cycle. One complete discharge-charge waveform is one cycle of a sinusoidal waveorm. If the L and C components are perfect or 'ideal' there is no energy loss and the voltage and current sinusoids continue to infinity.
So I think it's clear that the magnetic field has the ability to store energy. However it is not as capable of long term storge as a capacitor, as the  opportunities for, and mechanisms of energy leakage are manifold. Interesting to note that early computer memory was made of inductors wound around ferrite toroidal cores (one toroid per bit!!), but these needed electronic refreshing frequently to retain the stored data.

A: Let's not talk about fields at all. Let's talk instead first about what voltage is. Electrons really don't like to be near each other. The electrical force is incredibly strong. Let me give you an example of this. If 1 Ampere of current passed through a wire this would mean that 1 Coloumb of electrical charge has passed through that wire in 1 second. Let us suppose that you were able to store all of these electrons that passed in one second on an electrically isolated metal sphere. Then you waited another second and stored the same amount of electrons on another isolated metal sphere. Now you have 1 Coulomb of electrons on one sphere and 1 Coulomb of electrons on the other sphere. As you know, like charges will repel each other. If I held these two spheres 1 meter apart how much force to you think one would apply on the other due to Coulomb repulsion? The answer is in Coulomb's constant, which is:   \$ 9 \cdot 10^9 N \cdot m^2 \cdot C^{-2}\$.
Since we are 1m apart and since we have 1 Coulomb the force is 9 x 10^9 Newtons. This means that it will support 9 x 10^8 kg in Earth's gravity. Which is the weight of a very large building. This illustrates that excess electrons do not like to be near each other at all.
Voltage is the energy an excess electron has when it is added to an object. And you don't need many electrons at all to increase the voltage substantially. This means that objects, including metal wires, have a very very low capacity for excess electrons. What then is a capacitor? A capacitor has a high capacity for electrons so that when a battery adds electrons to a piece of wire that has a capacitor on the end the voltage does not increase as much per each electron. This is not due to the fact that a capacitor has a plate (no matter how large it is) : a single plate has a very very LOW capacity for extra electrons. The secret to a capacitor is the opposing plate that is very close to it. What happens is that any excess electrons on the plate are attracted to the opposing plate from which electrons have been removed by the battery. This means that the overall energy per excess electron is reduced and you can fit in more electrons per unit voltage increase. Capacitors therefore cannot have an air gap between them because the forces are so great. They need to have a solid between them to prevent the plates from collapsing into each other.
Now we come to the inductor. This is a crazy thing. There is no such thing as a magnetic field. It is just a Coulomb attraction. But this Coulomb attraction only occurs when current is flowing in this case. How can this happen? Well remember that the Coulomb force is incredibly strong so its effects can be seen from quite subtle changes in electron density that we cannot see. And now for the crux of the matter. The subtle changes are, in fact, due to Einstein's relativity. Electrons have an average spacing in a wire and this average spacing is the same as the average spacing of the positive charges. When a current flows you might think that the average spacing stays the same but now you have to take into account length contraction. To an outside observer any moving object will appear to be shorter and this is what happens to (the space between) electrons. With a coil of wire, on the opposite sides of the circle the electrons are flowing in the opposite direction. One side see the other as having a greater density of electrons than positive charges due to relativity. This creates a repulsion between the electrons in wires having opposing current directions and increases their energy (i.e. voltage). The voltage therefore rises much faster than for an ordinary wire. People therefore think of inductors as opposing current flow. But what it really happening is that the voltage increased very quickly and more so if a greater current flows. You might have noticed that all text books treat magnetism in a mathematical way and never really point out the actual particle responsible. Well its the electron and the force is due to relativity, and the force is most definitely Coulombic. This is true even in permanently magnetized materials (but that is another discussion). Forget fields, they are a mathematical construct for people who do not want to understand the world.

A: Visualizing b-fields and inductors?   Like this video?
https://youtu.be/1elpVmpkBH4

Go find professor J. Belcher's videos from MIT e&m course "TEAL project," with EM animated visualizations.  Every coil is like a stack of metal flywheels, where the electrons inside the turns of wire are like the atoms in the moving flywheels.

*

*Coil suddenly turned on: https://youtu.be/1elpVmpkBH4

*Coil turning off: https://youtu.be/iesoHVfIg6I

*supermagnet falls through copper ring, w/electron-flow
induced fields https://youtu.be/YywaJkGKOaY

*same w/ superconducting ring https://youtu.be/c3kxyqbsERI also https://youtu.be/uL4pfisCX14

*Charging a 2-sphere capacitor: https://youtu.be/O5fHvc4Edvg
Also: A Tour of Classical Electromagnetism (w/MPG animations)
http://web.mit.edu/8.02t/www/802TEAL3D/visualizations/guidedtour/Tour.htm
Try these MPEG collections:

*

*http://web.mit.edu/8.02t/www/802TEAL3D/visualizations/magnetostatics/

*http://web.mit.edu/8.02t/www/802TEAL3D/visualizations/faraday/

found that there was no way to visualize things happening in an inductor

NOT TRUE!   Instead, engineering authors never try doing that, partly because animated diagrams don't work in paper textbooks.  But also I've repeatedly found that animated diagrams are seen as a "For Dummies" technique, and attract scoffing, since they make things far too easy to understand.  No math rigor, far too much "physics for poets."  Engineering course work is expected to be complex and difficult: we're supposed to learn the math-models alone, never seeing any simple straightforward animations based on those same equations.  (Heh, if we NEEDED a non-math visual version, then maybe we're in the wrong degree program, and should take simpler classes?  Screw that: instead I want to teach this material to everyone, little kids and grandfathers.  Use the math-models to create 3D animations, interactive visual simulations where we can SEE the currents inside the wires, etc..)

A: All these answers are wonderful, but to answer the question about back emf, the key points to keep in mind:

*

*A changing B field induces an E field.

*E is related to ε (emf) through:
ε = W/q -> W = ∮F⋅ds -> W/q = -∮(F/q)⋅ds -> E = F/q -> W/q = -∮E⋅ds
(where s is an infinitesimal distance in direction of motion)
So when there's a changing magnetic field, there is an induced E field, and hence there will be an induced voltage (emf).

*ε = -∮(E_ind)⋅ds = -∂(Φ_B)/∂t = -(d/dt)(∫Β⋅dA) Remember, it's the B field changing here, so: = -(∂Β/∂t)A

The reason for it opposing the constant voltage source (e.g., a battery) is simply because F (proportional to E) points perpendicularly to B and I:

*F = Ids × B. (Current times ds, an infinitesimal piece of wire in the direction of I — current can only flow through the wire)

(Direction given by right hand rule)
This force adds a velocity component to the charges in the current in the direction of F. In turn, this new velocity component now creates a force component mutually orthogonal to the new component and B field, which is in the direction opposing the original flow of current, or opposing the original supplied voltage, and hence why it is called a "back emf".
It is this back emf that slows the charge (it doesn't block them).

A: I like to think about it like this.
It's analogous to why it takes work to stop a moving body;
why a body moves indefinitely with unchanged velocity when there is no net force on it.
➡ The electrons do the same.
Current is analogous to that kinetic energy of a body, and, respectively the electrons forced into a capacitor are analogous to lifting a body up (potential energy.) (The electrons or a body are forced somewhere they don't "want" to go themselves, and they "want" to leave.)
Note: This is not physical reasoning. OP's post is requesting a working mental model, not a deep explanation.
But I like to think about it and explain it like that. We need good mental models to be able to engineer. This is a good model IMO, because the behavior is the same in both cases - even the differential equations are the same.


text:
Q: Get filepath relative to Apache's document root Given $abs_path='/var/www/foo/html/bar/bla/bla';, how do I get the path relative to Apache's document root?
I recognize I could just use somethinglike $rel_path=str_replace ($_SERVER['DOCUMENT_ROOT'],'',$abs_path,1 );, but curious if there is a built in function.


text:
Q: scripting creation of a linux machine My need is to store the configuration of a linux machine in a file and be able to replicate the machine (as simply as possible) using the file. The file should be as small as possible.
I think that the following should be possible: create a minimal Linux installation CD which installs the systems from internet and applies some bash script to the resulting system. In principle the ISO of the CD could be very small and could by installed on a real machine (by burning the CD) or on a virtual machine (by means of ISO file).
I wonder if this approach has been implemented... I was not able to figure out the keywords for a google search.
add: or even a simpler two-step solution: a minimal linux distribution which has the ability to retrieve packages and software from internet following a configuration script (which could be copied on the system after installation). This would result in even smaller files since the ISO image would be always the same and is not contained in the file describing the system.

A: This kind of linux has been around for long time. a Command Line only (with no GUI) live cd which you would download and boot from it. Usually boot to RAM. these distros come with their own package manager software. these package managers are combination of bash and a programming language mostly Perl.
For example Gentoo; which its livecd is about 100mb i think or maybe less. there are other distros as well


text:
Q: Listview order.runOnUiThread? Hi guys I have a problem with my ListView...
This is my code:
     private ArrayAdapter<String> adapter ;

      private ProgressDialog m_ProgressDialog = null;
        private ArrayList<Order> m_orders = null;
        public OrderAdapter m_adapter;
        private Runnable viewOrders;

        public class Order {

            private String orderName;
            private String orderStatus;

            public String getOrderName() {
                return orderName;
            }
            public void setOrderName(String orderName) {
                this.orderName = orderName;
            }
            public String getOrderStatus() {
                return orderStatus;
            }
            public void setOrderStatus(String orderStatus) {
                this.orderStatus = orderStatus;
            }
        }
        private class OrderAdapter extends ArrayAdapter<Order> {

            private ArrayList<Order> items;

            public OrderAdapter(Context context, int textViewResourceId, ArrayList<Order> items) {
                    super(context, textViewResourceId, items);
                    this.items = items;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {

                    View v = convertView;
                    if (v == null) {
                        LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        v = vi.inflate(R.layout.list_single, null);
                    }
                    Order o = items.get(position);
                    if (o != null) {
                          //  TextView tv2 = (TextView) v.findViewById(R.id.tv2);
                        TextView tv1 = (TextView) v.findViewById(R.id.tv1); //codice volo
                        TextView tv2 = (TextView) v.findViewById(R.id.tv2); // citta

                        TextView tv5 = (TextView) v.findViewById(R.id.tv5); //stato volo
                        TextView tv6 = (TextView) v.findViewById(R.id.tv6); //ora prevista
                        TextView tv7 = (TextView) v.findViewById(R.id.tv7); //ora stimata                           if (tt != null) {

                        tv1.setText("VOLO: "+o.getOrderName());
                        }
                    return v;
            }
        }

        private void getOrders(){
              try{
                  m_orders = new ArrayList<Order>();
                  Order o1 = new Order();
                  o1.setOrderName("SF services");
                  o1.setOrderStatus("Pending");
                  Order o2 = new Order();
                  o2.setOrderName("SF Advertisement");
                  o2.setOrderStatus("Completed");
                  m_orders.add(o1);
                  m_orders.add(o2);
                     Thread.sleep(2000);
                  Log.i("ARRAY", ""+ m_orders.size());
                } catch (Exception e) {
                  Log.e("BACKGROUND_PROC", e.getMessage());
                }
                runOnUiThread(returnRes);
            }
        public LayoutInflater getSystemService(String layoutInflaterService) {
            // TODO Auto-generated method stub
            return null;
        }

        private Runnable returnRes = new Runnable() {

            @Override
            public void run() {
                if(m_orders != null && m_orders.size() > 0){
                    m_adapter.notifyDataSetChanged();
                    for(int i=0;i<m_orders.size();i++)
                    m_adapter.add(m_orders.get(i));
                }
                m_ProgressDialog.dismiss();
                m_adapter.notifyDataSetChanged();
            }
          };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

       View ios = inflater.inflate(R.layout.arrivi, container, false);

       m_orders = new ArrayList<Order>();
       this.m_adapter = new OrderAdapter(getActivity(), R.layout.list_single, m_orders);
               setListAdapter(getActivity(),m_adapter);

       viewOrders = new Runnable(){
           @Override
           public void run() {
               getOrders();
           }
       };
   Thread thread =  new Thread(null, viewOrders, "MagentoBackground");
       thread.start();
       m_ProgressDialog = ProgressDialog.show(getActivity(),
             "Please wait...", "Retrieving data ...", true);

//   new MyTask().execute("");
   return ios;

}

private void setListAdapter(FragmentActivity activity,
        OrderAdapter m_adapter2) {
    // TODO Auto-generated method stub

}

In eclipse I get this error:
The method runOnUiThread(Runnable) is undefined for the type arrivi
This code isn't in MainActivity but in a fragment named arrivi.
The file XML is list_single.xml and is associated at custom rows!
Can you help me please?
Another question...
How to implement AsyncTask for replacing Thread?
public class MyTask extends AsyncTask<String, Void, String> {
    ProgressDialog prog;
    String info;

.... When I run my app... it's in loop in "Retrieving data ..."
Thank you so much!!

A: runOnUiThread is a method of Activity subclasses. Inside a Fragment :
getActivity().runOnUiThread(runnable);

A: You need to create an instance for AsyncTask like this and execute your program on background.
 new AsyncTask<Void, Integer, Long>(){
        @Override
        protected Long doInBackground(Void... params) {
            try {

                // call you method here

            } catch (Exception ex) {
                // handle the exception here
            }
            return null;
        }
    }.execute();

runOnUiThread is used to execute some program in main Thread. When you call runOnUiThread , the action will be executed immediately if we are already in UIThread else will be posted in Queue.
You need to use the Activity Context associated with your Fragment to `runOnUiThread'.
 getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            // execute your code here
        }
    });


text:
Q: Why is it recommended to avoid unidirectional one-to-many association on a foreign key?
Possible Duplicate:
Hibernate unidirectional one to many association - why is a join table better?

In the Hibernate online documentation, under section 7.2.3 One-to-many, it's mentioned, that:

unidirectional one-to-many association
  on a foreign key is an unusual case,
  and is not recommended. You should
  instead use a join table for this kind
  of association.

I would like to know why? The only thing that comes to my mind is, it can create problems during cascade deletes. For example, Person refers to address on a one to many relationship on a foreign key, and the address would refuse to be deleted before the person.
Can anyone explain the rational behind the recommendation?
Here is the link to the reference document content: 7.2.3. One-to-many
I have copy pasted the actual content here:

A unidirectional one-to-many association on a foreign key is an
  unusual case, and is not recommended.
<class name="Person">
    <id name="id" column="personId">
        <generator class="native"/>
    </id>
    <set name="addresses">
        <key column="personId"
            not-null="true"/>
        <one-to-many class="Address"/>
    </set>
</class>

<class name="Address">
    <id name="id" column="addressId">
        <generator class="native"/>
    </id>
</class>

create table Person (personId bigint not null primary key)
create table Address (addressId bigint not null primary key, personId bigint not null)

You should instead use a join table for this kind of association.

A:
unidirectional one-to-many association
  on a foreign key is an unusual case,
  and is not recommended.

There are two aspects to this:

*

*unidirectional

*one-to-many

The thread @CalmStorm's deleted answer links to addresses only the second of these things, but let's start with it.
That thread recommends replacing one-to-many relationships with join tables because otherwise the one-to-many approach 'populates the many side table with columns that don't belong to that entity, are there only for "linking" porpuses (sic)'.  This tactic may result in a clean model in the Hibernate layer but unfortunately it results in a broken database.
Because SQL can only assert that the child record has a parent; there is no way to enforce a rule that the parent must have a child.  Consequently there is no way to insist that a table have entries in a join table, the upshot being that it becomes possible to have orphaned child records, the very thing that foreign keys are intended to prevent.
I have several other objections, but the next most important one is inappropriateness.  Intersection tables are meant to represent many-to-many relationships.  Using them to represent one-to-many relationships is confusing and requires too many additional database objects for my liking.
So, to the second aspect: unidirectional one-to-many associations.  The problem with these is the peculiar fashion in which Hibernate handles them by default.  If we insert a parent and a child in the same transaction, Hibernate inserts the child record, then it inserts the parent, then it updates the child with the parent's key.  This requires deferrable foreign key constraints (yuck!) and probably deferrable not null constraints as well (double yuck).
There are a couple of workarounds to this.  One is to use birectional one-to-many associations.  According to in the document you cite this is the most common approach.  The other approach is to tweak the mapping of the child object but that has its own ramifications.


text:
Q: Range Error Maximum call stack size exceeded Angular So I want to add machine detail and buton bar to my app, and this is what happens. I've used it in other parts aswell and it worked fine, only in core module are the errors.
The error message
main.ts
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.error(err));

core module (error appears when I add "IfaButtonModule" or "MachineModule")
@NgModule({
  declarations: [
    TakePhotoComponent,
    ConfirmationDialogComponent,
    ShareMachineComponent,
    NotificationsComponent,
  ],
  imports: [
    CommonModule,
    WebcamModule,
    MatButtonModule,
    TranslateModule,
    MatDialogModule,
    MatFormFieldModule,
    MatInputModule,
    ReactiveFormsModule,
    MatIconModule,
    MatExpansionModule,
    MatBadgeModule,
    MatCardModule,
    MatMenuModule,
    IfaButtonModule,
    MachineModule
  ],
  exports: [
    TakePhotoComponent,
    ConfirmationDialogComponent,
    ShareMachineComponent,
    NotificationsComponent
  ],
  providers: [NgxImageCompressService]
})
export class CoreModule { }

button-module
@NgModule({
  declarations: [
    IfaButtonBarItemComponent,
    IfaButtonBarComponent,
    IfaButtonBarGroupComponent
  ],
  imports: [
    CommonModule,
    CoreModule,
    MatButtonModule,
    TranslateModule
  ],
  exports: [
    IfaButtonBarComponent,
    IfaButtonBarGroupComponent,
    IfaButtonBarItemComponent
  ]
})
export class IfaButtonModule { }

machine module
@NgModule({
  declarations: [
    MachineListComponent,
    MachineDetailEditComponent,
    MachineDetailComponent,
    MachineListItemComponent
  ],
  imports: [
    CommonModule,
    CoreModule,
    MatCardModule,
    MatMenuModule,
    MatListModule,
    MatButtonModule,
    FormsModule,
    ReactiveFormsModule,
    NgxPaginationModule,
    MatFormFieldModule,
    MatInputModule,
    TranslateModule,
    MatDialogModule,
    MatExpansionModule,
    IfaButtonModule,
    OperationModeModule,
    ProtectionModule,
    ManipulationModule
  ],
  exports: [
    MatMenuModule,
    MachineDetailEditComponent,
    MachineListComponent,
    MachineDetailComponent
  ]
})
export class MachineModule {

}

the html that uses the components: (inside the core module area)
<ng-container>
  <app-machine-detail [machine]="completeMachine">
  </app-machine-detail>
  <app-ifa-button-bar-group>
    <app-ifa-button-bar-item [label]="'MISC.BACK'" (click)="navigateBack()">
    </app-ifa-button-bar-item>
  </app-ifa-button-bar-group>
</ng-container>

A: This is probably happening because you import CoreModule in the MachineModule and the MachineModule in the CoreModule. This should not happen, you should re-work your module dependencies and fix the circular import. IfaButtonModule has the exact same issue.


text:
Q: use $(this) within an external function JQuery I would like to target the element clicked using $(this) however I need this code to be within a function like this:
function openQv(){
      var  lookImg = $(this).parent().find(".look-img").attr("src");
}

$(document).on('click touchstart', '.hotspot', function(e){
      e.preventDefault();
      openQv();
});

Using $(this) within an external function doesn't seem to work, is there a way to do this?

A: Reference the function and it works out of the box
function openQv(e){
    e.preventDefault();
    var  lookImg = $(this).parent().find(".look-img").attr("src");
}

$(document).on('click touchstart', '.hotspot', openQv);

Or you could set the this value using call, apply or bind
$(document).on('click touchstart', '.hotspot', function(e){
      e.preventDefault();
      openQv.call(this);
});


text:
Q: Laravel: HasManyThrough on ManyToMany (ManyToManyThrough?) I've got the following tables: users, orders, order_items, item, and I'm trying to get all of the the items related to a user through an order.
I have two issues:

*

*The hasManyThrough relationship doesn't appear to with with many-to-many relationships on the final model.

*Non standard table name - My order_items table doesn't follow the alphabetical order naming convention, and it appears you can't set the $table name on a pivot class.
Is there a way that I can get all items for a given user as a relationship? Ideally the plan is to be able to groupBy so that I can count the number of items on the relationship.
If needed I can potentially rename the pivot table name, but it would be prefereable not to.
I'm trying to define a relationship so that I can simply call the items on the user rather than using the pivot table, so something like:
$user->items


text:
Q: Timer task makes app crash I have a Canvas object in my app and I want to update it each 20 ms. I tried Java's TimerTask, but it makes my app crash after few updates. Here's update code;
 timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            invalidate(); // canvas's update
        }
    }, 20, 20);

What shall I do?
Edit: Error log:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

A: In this case, run() is called on a background thread, and invalidate() is called on that background thread. This will lead to the exception you have in your question, as those sorts of updates can only be done on the main application thread.
Since calling invalidate() 50 times/second is unlikely to be the right solution for whatever problem you are trying to solve, you may wish to ask a separate Stack Overflow question where you explain what sorts of changes you are trying to make to your UI every 20ms, to see what the recommended approach is. Or, pick up a book on Android game development — while you may not be building a game, game developers drawing to a Canvas also have these sorts of concerns, so the techniques that they use might be relevant to you as well.

A: If you really want to do this, just change invalidate to postInvalidate.


text:
Q: How bind to TemplatedParent from DataTemplate defined in a style? I am developing a custom control derived from an ItemsControl. In the generic.xaml-file I created the style for that control and also defined an ItemTemplate:
<Style TargetType="local:MyItemsControl">
    <Setter Property="ItemTemplate">
        <Setter.Value>
            <DataTemplate>
                <Border Background="Red">
                    <!-- Other things in here -->
                </Border>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

I want to bind the Background property of the Border in the DataTemplate to a dependency property of the MyItemsControl.
If found several questions here suggesting to use the element name of the MyItemsControl in the binding, but that only works when defining the ItemTemplate where the control is being used. I also tried binding to a RelativeSource defining the local:MyItemsControl as ancestor type.
Nothing worked. What am I missing here?

A: What`s the type of that DependencyProperty? Is it Brush or string?
This simple code works for me:
Background="{Binding Name, RelativeSource={RelativeSource AncestorType=ItemsControl}}"

Just for test here I bind to Name property of ItemsControl that is 'Yellow' - and it works.


text:
Q: Ни одна из перегрузок метода "Write" не принимает 0 аргументов Люди помогите, новичок в c# и появилась ошибка, которую я не могу решить "Ни одна из перегрузок метода "Write" не принимает 0 аргументов."
class HelloWorld {
  static void Main() {
    Console.Write();
    HelloWorld.WriteSentence();
    }

  public static void WriteSentence() {
    string sentence = Console.ReadLine();
    string[] words = sentence.Split(' ');
    Console.WriteLine(words);
    }
}

Вот дополнение кода
    string sentence = Console.ReadLine();
    string[] words = sentence.Split(' ');
    foreach(string word in words){
      Console.WriteLine(word);
    }


text:
Q: C# sockets How can I handle unplanned disconnections on socket servers? I am building a socket server in C#, and i have an issue with unplanned sockets disconnects.
For now, i am handling this like that:
private List<TCPClient> _acceptedClientsList = new List<TCPClient>();
public void checkIfStillConnected()
{
    while (true)
    {
        lock (_sync)
        {
            for (int i = 0; i < _acceptedClientsList.Count(); ++i)
            {
                if (_acceptedClientsList[i].Client.Client.Poll(10, SelectMode.SelectRead) == true && (_acceptedClientsList[i]).Client.Client.Available == 0) // 5000 is the time to wait for a response, in microseconds.
                {
                    NHDatabaseHandler dbHandler = new NHDatabaseHandler();
                    dbHandler.Init();
                    if (_acceptedClientsList[i].isVoipClient == true)
                    {
                        dbHandler.UpdateUserStatus(_acceptedClientsList[i].UserName, EStatus.Offline);
                    }
                    RemoveClient(i); // this function removes the selected client at i from the acceptedClientsList
                    i--;
                }
            }
        }
    }
}

But this is not optimized at all. This is a thread who checks every sockets status with the socket.poll, every time, infinitely...
I don't know if it's the best thing to do... It looks like it's heavy and weird.
Does anyone has an idea?
Thanks

A: It is best to have one dedicated thread to read incoming data from each socket. When unplanned socket disconnection occurs (for e.g. the client side network drops out or crashes), the socket will throw an exception. You can then catch exception, then close the socket connection and end the thread cleanly while keeping other socket running.
I learnt the TCP/IP communication from this tutorial.
http://www.codeproject.com/Articles/155282/TCP-Server-Client-Communication-Implementation
The author explains his implementation very well. It's worth learning from. You can reference it to rewrite your own library.


text:
Q: uninitialized constant ActiveSupport::Json despite "require 'active_support/all'" I'm receiving a "uninitialized constant ActiveSupport::Json" error on the line where I call responseJson = ActiveSupport::Json.decode(response), in a small controller in my small Rails app.
The response variable returns a string with a response of the type {"token":"this_is_your_session_token"}.
I've added gem 'activesupport', '~> 4.2.3', to my Gemfile, tried different require statements with 'active_support/core_ext/object/json, and tried this in the IRB (with the same error). I'm not sure how to debug this further. Any help would be greatly appreciated.
require 'active_support/json'
require 'active_support'
require 'active_support/all'
require 'rest-client'

class WelcomeController < ApplicationController
  def login_attempt
    username = params[:u]
    password = params[:p]

    puts "waiting on request"
    response = RestClient.post 'http://localhost:3001/v1/login', :email => username, :password => password
    responseJson = ActiveSupport::Json.decode(response)
  end

end

A: ActiveSupport::JSON (all caps). FYI, if you use pry instead of irb, you can run a command like 'ls ActiveSupport' and see the contained modules, methods, etc.


text:
Q: Rails Action controller: Exception caught Hello I get this error in the heading of my application.html.erb file
ActionView::Template::Error (TypeError: Cet objet ne gère pas cette propriété ou cette méthode):
    2: <html>
    3: <head>
    4:   <title>LifeHacks</title>
    5:   <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
    6:   <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
    7:   <%= csrf_meta_tags %>
    8: </head>
  app/views/layouts/application.html.erb:5:in `_app_views_layouts_application_html_erb___906694100_51941424'

Could anyone help me figure out how to fix this? Thanks.
The exception I get well error is
ExecJS::ProgramError in Homepage#index
Here is my homepagecontroller
 class HomepageController < ApplicationController
    def index
    end
end

and lastly here is my routes file
Rails.application.routes.draw do

  root "homepage#index"

end

I do have a turbolinks gem added

A: Are you running on Windows? If so, your question might be solved by using a different version coffee-script-source (1.8.0 instead of 1.9.0) as shown here: javascript_include_tag throws unsupported method


text:
Q: Unable to read a 64 bit registry key from a 32 bit version of win2008 using powershell Im trying to read the below registry key on a 64 bit version of windows server 2008 r2  from a 32 bit windows 2008 using powershell, but the value comes as blank and does not return anyvalues.
can some help me on how can i read a 64 bit reg key from a 32 bit server ?
$line = "WIN-QENOBBC64B8"
$regkey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, $line)
$ref = $regKey.OpenSubKey("SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL")
$ref

A: From 32bit powershell, you access the 64bit registry by calling the 64bit version of reg.exe from the command line.  The trick is in using the sysnative path instead of system32, which gets you out of the syswow64 sandbox and into the real 64 bit registry.
C:\Windows\SysNative\reg.exe QUERY "HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL"

A: If you are running PowerShell on .NET 4 (look at the output of $PSVersionTable) then you can use the new RegistryView enumeration (and OpenRemoteBaseKey overload) with the [Microsoft.Win32.RegistryView]::Registry64 to be able to view the 64-bit registry.
Alternatively you could use PowerShell remoting since by default you will be connected to the 64-bit PowerShell endpoint on the remote machine e.g.:
$line = "WIN-QENOBBC64B8"
Invoke-Command -ComputerName $line {Get-Item 'HKLM:\Software\Microsoft\Microsoft SQL Server\Instance Names\SQL'}

Note that you may have to enable remoting on the remote server (can't remember if PowerShell remoting is enabled by default on servers).  You can do this by running the following commands on the remote server in an elevated/admin PowerShell prompt:
Set-ExecutionPolicy RemoteSigned
Enable-PSRemoting

A: Try this as your last line if looking for values:
$ref.GetValueNames()

or if you are looking for keys:
$ref.GetSubKeyNames()


text:
Q: Pagination with flutter gridview fails I am trying to integrate pagination with gridview.builder,it's working in listview without any problem but in gridview it doesn't work as expected,The problem i am facing is The API data is returns 20 data per page,
Problem:In API it returns 20 data/page,in this API it returns total of 21 data,in 1 st page contains 20 data 2nd page contains only 1 data the pagination is working i can load data but i cannot scroll back to page 1 data it just stuck with page 2 data
I am following this Tutorial,this is working with listview without no problem but in gridview the above problem occurs
InitState and Variable initialization
 var page = 1;
  ScrollController _sccontroller = new ScrollController();

  @override
  void initState() {
    super.initState();
    Future token = SharedPrefrence().getToken();
    token.then((data) async {
      userToken = data;
      this.getSearchResult(page);
      _sccontroller.addListener(() {
        if (_sccontroller.position.pixels ==
            _sccontroller.position.maxScrollExtent) {
          getSearchResult(page);
        }
      });
    });
    setState(() {
      title = name;
    });

  }

  @override
  void dispose() {
    _sccontroller.dispose();
    super.dispose();
  }

Gridview
GridView.builder(
          controller: _sccontroller,
          itemCount: search_result_list.length + 1,
          physics: const AlwaysScrollableScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(childAspectRatio: 5.2 / 8.0,
          crossAxisCount: 2, crossAxisSpacing: 3.0, mainAxisSpacing: 3.0),
          itemBuilder: (BuildContext context, int index) {
            if (index == search_result_list.length) {
              return Center(child: Padding(padding: const EdgeInsets.all(8.0), child: CircularProgressIndicator(),));
            } else {
              return Container(
                child: Padding(
                  padding: const EdgeInsets.only(top:10),
                  child: GestureDetector(
                    onTap: () {

                    },
                    child: Container(
                      // height: 700,
                      child: Card(
                        elevation: 2,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(2),
                        ),
                        child: Container(
                            width: 300,
                            //height: 500,
                            child: Stack(
                              children: [
                                Column(
                                  mainAxisSize: MainAxisSize.min,
                                  //crossAxisAlignment: CrossAxisAlignment.start,
                                  //  mainAxisAlignment: MainAxisAlignment.start,
                                  children: [
                                    Padding(
                                      padding: EdgeInsets.all(2),
                                      child: Image.network(
                                        Urls.baseImageUrl +
                                            search_result_list[index]
                                                .thumb_path,
                                        fit: BoxFit.fill,
                                        height: 180,
                                        width: 180,
                                      ),
                                    ),
                                    Padding(
                                        padding: const EdgeInsets.all(5),
                                        child: Align(
                                          child: Text(
                                            search_result_list[index].name,
                                            style: TextStyle(
                                                fontSize: 11,
                                                fontWeight: FontWeight.bold),
                                            textAlign: TextAlign.left,
                                          ),
                                          alignment: Alignment.centerLeft,
                                        )),

                                  ],
                                ),

                              ],
                            )),
                      ),
                    ),
                  ),
                ),
              );
            }
          },
        )

API Function
 Future<void> getSearchResult(int index) async {
    print("size" + index.toString());
    if (!isLoading) {
      setState(() {
        isLoading = true;
      });
      // ProgressDialog dialog = CustomDialogs().showLoadingProgressDialog(context);
      List<PrefrenceModel> tList = List();
      var response = await http.get(
        "${Urls.baseUrl}${Urls.CategorySearch}?latitude=${Constants
            .latitude}&longitude=${Constants
            .longitude}&radius=100&locale=en&keyword=${slug}&page=${index
            .toString()}&type=item",
        headers: {
          "Content-Type": "application/json",
          "Authorization": "Bearer ${userToken}",
          "Accept": "application/json"
        },
      );

      Map<String, dynamic> value = json.decode(response.body);
      if (response.statusCode == 200) {
        // dialog.dismissProgressDialog(context);
        try {
          print("response search " + response.body.toString());
          Map<String, dynamic> value = json.decode(response.body);

          var status = value['success'];
          var message = value['message'];
          last_page = value['last_page'];
          print(message);
          if (status == true) {
            search_result_list.clear();
            try {
              var data = value['data']['data'];
              if (data.length > 0) {
                for (int i = 0; i < data.length; i++) {
                  var obj = data[i];
                  //var petrol_obj = obj['petrolstation'];
                  search_result_list.add(PrefrenceModel(
                    obj['id'].toString(),
                    obj['description'].toString(),
                    obj['valid_from'].toString(),
                    obj['valid_to'].toString(),
                    obj['thumbs']['md'].toString(),
                    obj['status'].toString(),
                    "",
                    "",
                    obj['name'].toString(),
                    "",
                    obj['flyer_slug'].toString(),
                    obj['type'].toString(),
                    obj['isClipped'],
                    obj['url'].toString(),
                    obj['price'].toString(),
                    obj['flyer_page_id'].toString(),
                    obj['id'].toString(),
                    obj['shop_name'].toString(),
                    obj['shop_logo'].toString(),
                    obj['brand_name'].toString(),
                    obj['brand_logo'].toString(),
                  ));
                }
                setState(() {
                  isLoading = false;
                  search_result_list.addAll(tList);
                  page++;
                });
              } else {
                final snackBar = SnackBar(content: Text("No Data Available"));
                _scaffoldKey.currentState.showSnackBar(snackBar);
              }
            } catch (e) {
              e.toString();
            }
          } else {
            print("Error...");
            final snackBar = SnackBar(content: Text(message));
            _scaffoldKey.currentState.showSnackBar(snackBar);
          }
        } catch (e) {
          print(e.toString());
        }
      } else {
        var message = value['message'];
        // dialog.dismissProgressDialog(context);
        final snackBar = SnackBar(content: Text(message));
        _scaffoldKey.currentState.showSnackBar(snackBar);
      }
    }
    else
      {
        setState(() { isLoading = false; });
      }
  }

A: Pagination will gives you the data related to the page, for example page one will returns data from 1 to 20, page two from 21 to 40. so you have to add data of page 2 to existed data from page 1. but in your case you are calling search_result_list.clear(); this will erase the old data and put only the new data into the list.


text:
Q: Associate user with multiple other users I'm connecting my C++ program to a MySQL server, and I'm having a bit of a hard time.
Each user has a contacts/friends list which (of course) holds other users. I'm not sure how to actually associate a user with other users in the database. what datatype could work for such a task?
The only thing I could think of is maybe to have a text field with numbers separated by spaces and parse it each time the user connects. but for some reason it sounds awfully wrong to me, so I'm not sure.
What could you recommend? Thank you.

A:
The only thing I could think of is maybe to have a text field with numbers separated by spaces and parse it each time the user connects. but for some reason it sounds awfully wrong to me

That sounds like a bad idea to me too.
You want a many-to-many relationship:
contact
user    friend
1       2
1       3
1       5
2       4
3       1

Note that in a contact list you may want to store additional attributes for each contact list entry. For example the user may wish to change the name that is displayed in their own contact list. For example, your table might look like this if user 1 wants to see user 3's name to be displayed as "foo".
contact
user    friend   displayName
1       2        NULL
1       3        'foo'
1       5        NULL
2       4        NULL
3       1        NULL

Here NULL means that the user has not specified a preferred display name for their contact, so the contact's name should be shown.


text:
Q: Error loading fxml files from a folder other than the bin folder I am a fairly new java programmer. I only have about five weeks of experience, starting from zero, and I am having problems getting javafx fxml files created in Scene Builder to load correctly if they are not in the same folder as the controller classes.
I am using
Win7x64 running jre7x86 for this build

Eclipse Juno Service Release 1
Build id: 20120920-0800

jre version 1.7.0_07

javaFx version 2.2.1-b03

SceneBuilder version 1.0-b50

My scene loader code is
private static final String RESOURCE_PATH = "/resources/";
public static Stage buildStage(@SuppressWarnings("rawtypes") Class pClass,
         String stageTitle, String resourceLocation)
   {
      Stage temp = new Stage();
      Pane page = null;
      try
      {
         page = FXMLLoader.load(pClass.getResource(RESOURCE_PATH + resourceLocation), null,
               new JavaFXBuilderFactory());
      }
      catch (IOException e)
      {
         e.printStackTrace();
      }
      Scene scene = new Scene(page);
      temp.setScene(scene);
      temp.setTitle(stageTitle);
      temp.setResizable(false);
      return temp;
   }

I know that the project directory is the /workspace/projectName/ so theoretically the loader should be able to find the files if it's given a relative path right? The error I'm getting is
Exception in Application start method
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:403)
    at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:47)
    at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException: Location is required.
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2737)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2721)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2707)
    at outofunit.system.StageFactory.buildStage(StageFactory.java:32)
    at outofunit.desktop.ArcMaster.start(ArcMaster.java:28)
    at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319)
    at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:206)
    at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:173)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:29)
    at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:73)
    ... 1 more

I've tried giving the loader an absolute path as well but it just isn't accepting anything that isn't directly in the same directory. I'm grasping at straws here trying to figure this out.
I've tried to research this on my own but I haven't gotten much, the few answers on here that seemed similar didn't seem to help, that or I am too dense and/or inexperienced to make sense of them. They are JavaFX 2.0 loading fxml files with event handlers fails and JavaFX 2.0 FXML resource loading error
A buddy of mine was able to overcome this problem by using this code
public void load(String pFileName, Stage pStage, String pTitle)
   {
      String fName = RESOURCE_PATH + pFileName;

      try
      {
         String externalForm = getClass().getResource(fName)
            .toExternalForm();

         InputStream inStream = new URL(externalForm).openStream();

         FXMLLoader loader = new FXMLLoader();
         Pane p = (Pane)loader.load(inStream);

         pStage.setTitle(pTitle);
         pStage.setScene(new Scene(p));

         mWindowControl = loader.getController();
         mWindowControl.setUp(pStage);

         pStage.show();
      }
      catch (Exception e)
      {
         e.printStackTrace();
      }
   }

The biggest difference and the reason why I haven't been using his code is because my root pane is an Anchor pane instead of a normal pane, and his way URL instream forces a normal pane. Am I at fault for not using a normal pane as my base? I would love any help or input you guys can give. Thank you.
Edit: So I've been working on this problem and the error message has changed.
I changed the code to this
private final String RESOURCE_PATH = "resources/";
public void load(String pFileName, Stage pStage, String pTitle)
   {
      String fName = RESOURCE_PATH + pFileName;

      Pane page = null;

      FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(fName));

      try
      {
         page = (Pane) fxmlLoader.load();
      }
      catch (IOException exception)
      {
         throw new RuntimeException(exception);
      }

      Scene scene = new Scene(page);
      pStage.setScene(scene);
      pStage.setTitle(pTitle);

      mWindowControl = fxmlLoader.getController();
      mWindowControl.setUp(pStage);

      pStage.show();
   }

but the error I'm now getting is
java.lang.IllegalStateException: Location is not set.
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2021)
    at outofunit.desktop.WindowLoader.load(WindowLoader.java:136)
    at outofunit.desktop.WindowLoader.load(WindowLoader.java:62)
    at outofunit.desktop.ArcMaster.start(ArcMaster.java:30)
    at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319)
    at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:206)
    at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:173)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:29)
    at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:73)
    at java.lang.Thread.run(Unknown Source)

I don't understand how the location is not being set

A: It's a path issue, java needs to know where to get the file from the package hierarchy.
So using "/package1/resourcename.fxml" should find the source from the root of the tree.
You normally leave off the "/" at the start as you are already at the top of the package tree.

A: Both exceptions say "the (FXML) file you are trying to load cannot be found in the location you have provided". Your filename is wrong or its path. Give your package structure or at least the path of class file that includes load(String pFileName, Stage pStage, String pTitle) method and the path of FXML file you want to load. Read the javadoc API of getResource() and examine sample codes about it on the net.


text:
Q: Bootstrap - Carousel Jumbotron - Iframes with WebGL content This question is pretty specific, but I'll ask anyways.
First off, I know iframe's are probably not the best design but I don't know how else to solve my problem. Anyways, let me start of with some background information:
I have a page with some WebGL content on it (it just loads a .obj and .mtl model using Three.js, and adds some keyboard navigation for camera movement).
This page is structured so that it gets a variable using php's $_GET array, and then loads the model based on that variable (if the variable was "Bus" then it would load from obj/Bus/Bus.obj, and if the variable was "Shoe" then it would load from obj/Shoe/Shoe.obj).
The link to the page would be like "browser.php?name=Bus" or "browser.php?name=Shoe".
Now, I want to display several of these pages in a carousel of iframes. Because I am using Bootstrap, this task is trivial with the following code:

          ‹
          ›

          ‹
          ›

This works perfectly except for one issue, the carousel-caption and all of its content are not showing. I am not sure if this is because of the iframe, or of the WebGL content, because when I just had an image there, its content was showing.
WebGL Iframe Carousel:

Normal Image Carousel:

Finally, my question: How do I fix my code / organization / design so that I can display the WebGL content in a carousel?
Sorry if this is a duplicate, but I was unable to find any relating links on google.
Thanks for taking your time to read/possibly answer this question,
Bucco
[EDIT]:
I just realized that my question was horribly worded, and was not clear enough. My main issue is with the navigator arrows not showing up in the WebGL content carousel (see the images). How do I fix my design / code so that I can display the WebGL content in a carousel with the navigator arrows?

A: The only obvious thing I see is that the s are missing their closing tags, which are actually required according to the W3C (http://www.w3.org/TR/html-markup/iframe.html#iframe-tags).
I assume the normal behavior of an  is kicking in, which means that any children of the  are only displayed if the src cannot be loaded. Or, stated another way: lacking the closing tag, it looks like your navigation elements are treated as "fallback" content rather than sibling elements.
In fact, loading your content into a jsFiddle seems to prove me out: http://jsfiddle.net/dRtvH/ - w/o closing tags, no carousel, but simply closing the s makes the nav buttons show up.


text:
Q: Eclipse RSE connect to a localhost on a remote machine I'm trying to work with Hbase, thrift, and python on a remote machine(Ubuntu) from Eclise RSE on windows. Everything is working fine but when I'm trying to connect to the localhost I get an error:
thrift.transport.TTransport.TTransportException: Could not connect to localhost:9090

If I run this code via ssh terminal on a remote machine, it works perfectly.
Here is my code:
#!/usr/bin/env python

import sys, glob
sys.path.append('gen-py')
sys.path.insert(0, glob.glob('lib/py/build/lib.*')[0])

from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from hbase import Hbase

# Connect to HBase Thrift server
transport = TTransport.TBufferedTransport(TSocket.TSocket('localhost', 9090))
protocol = TBinaryProtocol.TBinaryProtocolAccelerated(transport)

# Create and open the client connection
client = Hbase.Client(protocol)
transport.open()

tables = client.getTableNames()

print(tables)

# Do Something

transport.close()

A: Do you know what localhost means? It means the machine you're running the command on. E.g. if I type http://localhost:8080/ in a browser on my PC then it will call the server running on port 8080 on MY machine.
I'm sure your connection worked fine if you tried connecting to localhost while on the same box. If connecting from a different machine then you'll need to know the IP address or the hostname of the box you're connecting to.