How to automatically get rid of trailing zeroes?

Question: My goal of my program is to cut off pi at a given point as dictated by the user.
I have figured out how to do it, but I cannot figure out how to get rid of the trailing zeroes.
#include <stdio.h>
#include <math.h>
int main()
{

int i,length;
double almost_pi,pi;
printf("How long do you want your pi: ");
scanf("%d", &length);

pi = M_PI;

i = pi * pow(10,length);

almost_pi = i / pow(10,length);

printf("lf\n",almost_pi);

return 0;
}

Let's say user inputs 3, it should return 3.141, but it is returning 3.141000.
Please and thanks!
Comment: http://en.wikipedia.org/wiki/Printf_format_string#Format_placeholders
Comment: This [article][1] will help get you started in the right direction.

  [1]: http://stackoverflow.com/questions/7425030/how-can-i-limit-the-number-of-digits-displayed-by-printf-after-the-decimal-point
Comment: 3.141 is the same thing as 3.141000.  For that matter, it's also the same as 3.141000000000000000.  Your issue is with displaying the value, not what is entered.
Answer: Is this what you're trying to do??
#include <stdio.h>
#include <math.h>

int main()
{
    int length = 4;
    printf("How long do you want your pi: ");
    if (1 == scanf("%d", &length))
        printf("%.*f\n", length, M_PI);
    return 0;
}

Sample Output #1
How long do you want your pi: 4
3.1416

Sample Output #2
How long do you want your pi: 12
3.141592653590

Answer: You need to specify a formatting parameter, the length, as an additional argument to printf:
printf("%.*f\n, length, almost_pi);

This reference states that the .* means that "The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted."
As an aside, you can use %f for both doubles and floats with printf, but you still have to use %lf for doubles with scanf.  See here.
Answer: printf("%.3f\n",almost_pi); will fix it.
Comment: He has to make it so that it is based on user input, not statically always set to '3'.


Chimney repair for old unused flue

Question: We bought a house, built in 1986. The home has a "real" fireplace (heatilator style)- (Center flue), furnace is direct vented (now), and water heater is vented through the chimney (right flue).
The Chimney has three flues:

So here is my question....
Clearly water is getting into the chimney. It probably has been for years. I'm confused on why someone would break down a flue like this and leave it open to the elements? The house plans show the left hand side flue as being used originally for the furnace, so when they went direct vent, I "guess" they capped it off? But when you look at the water heater vent you can see it was once much larger, like for the furnace?
So I suppose it is possible this flue was never used? Clearly repair work has been performed up top to include mastic, and new caps. Why would no one cap off this flue?
I've called some masonry contractors in the area and am awaiting a visit from one of them. Should I consider using silicone/mastic and repairing the cracks and capping the flue flush to the crown with a piece of ceramic tile/stainless/aluminum OR should I consider a full chimney chase cover which I'm assuming could be cheaper in the long run as I would not have to have it resealed often or worry about more cracks in the crown?
Seeing the basement picture and the open flue picture, I'm under the impression the structure of the chimney is fine internally, am I being unrealistic given that this has been this way for a minimum of 5 years (winters, rain etc)?
Answer: I've had two masonry contractors out.  They both agreed the flue  is unused, both stated  it is a dummy flue. I'm not convinced, but it doesn't matter.
Both noted the water getting inside.  Booth discussed the cream of the crop solution,  New crown.  Neither oversold it.
One liked the idea of metal cap,  one never heard of it,  lol.
Both suggested to cementing cap the dummy flue and sealing cracks. As I know I'll never use this flue,  it made enough sense, I went this approach.
Job done as it was the simplest most immediate solution.  I suspect in the near future,  maybe next season,  I will do a stainless,  or all out copper top,  with a drip edge,  as its astute top lady longer than concrete in wet snowy buffalo weather.

Chimney repair for old unused flue


Parse Cloud function which every hour checks all rows in Parse.com table and if needed updates a column

Question: I need to deploy a function which every hour checks all rows in a table in Parse.com. I have there columns ValidFrom(Date), ValidTo(Date) and Active(bool). So it passes all rows and for a row where DateTime.UtcNow < ValidTo && DateTime.UtcNow >= ValidFrom it updates Active value to True otherwise it updates Active to False.
I don't know where to start.. Can you point me to the right direction please?
Comment: I don't understand why someone give a minus point for this question a gave no answer and no comment. What's wrong on this question??
Answer: you can use a background job in parse and schedule it to work every hour by adding it to  the jobs schedule in the Web Console.
check this link
http://blog.parse.com/2013/09/04/introducing-background-jobs/
Comment: Thank you Mahmoud, this is exactly what I need. With a little querying I can do that job.


How To Get Browser To Open From Same Folder?

Question: I don't know how to make the title any more clear. Let me give an example - When I want to add an image to an article on my blog, I click "Browse" button in the image uploader, and then upload the image to the blog.
The problem is, when I want to upload another image to my blog, I want the browser to look into the same directory; but it's always takes me to the "Recently Used" directory.
Is there a way to change this? I hope I have made myself clear enough.
EDIT: This issue probably pertains to Google Chrome browser only. As you can see in the comments, it's fine with Mozilla Firefox.
Comment: I always thought browsers sort of learning that, which folder was the last used, i doubt there's a simple setting for this.
Comment: Which web browser do you use? At least Firefox does remember the last upload directory.
Comment: Yes, I thought so too, but it just doesn't remember... or is it only on my PC? I am talking about Chrome by the way, to be specific. Doesn't it happen to you?
Comment: "Recently Used" is a GNOME 3 feature intended to show you a list of the files/folders you used last. Is your images directory shown in there?
Comment: Yeah, I am getting used to it (I just learnt it's similar to what I want). The only problem is it also shows the files I deleted.
Answer: Looks like many have got adjusted with it, the way it is. FWIW, I realized that the "Recently Used" feature in Gnome/Unity shows the most recently changed / downloaded files (not folders).
Since I first download the image that I want add to my blog post, the image(s) is always shown among those "Recently Used". I didn't notice that at first.
The point is, I (and we) want the browser -- here we are talking about Chrome -- to use the same folder/directory as downloads and uploads location. That is, if I download a file, it should go to the "XXX" directory, and when I browse to upload a file, the browser should directly take me to that folder (XXX), instead of the default folders like Pictures, Downloads etc.
What you should realize is that the "Recently Used" feature does the same thing, but in quite a different way. (I tried to make my point clear.)


I need help in optimization of an array problem that has been asked in interview last month

Question: Given 2 arrays a and b find the max value of b[i] + b[j] + b[k] (i !=j != k) , where the following condition is satisfied
a[i] > a[j] > a[k]
I can calculate it by using 3 loops. I have been asked to optimize the problem during the interview but was unable to do it.
any optimized method better than O(n^3) ?
thanks
Answer: You can probably get away with an O(n log n) solution by sorting B (n log n time) and tracking which indexes are used, checking A for the property A[i] > A[j] > A[k]. Note that since the only relationship between i, j and k is that they are not equal, their order doesn't seem to matter. (Also, it might be that i and k can be equal, but we'll ignore that for now.)
Pseudocode:
function findSum(A, B):
  declare array B_with_index

  // O(n)
  for index 0 to |B|-1:
    insert (B[index], index) into B_with_index

  // O(n log n)
  sort B_with_index by its first value, descending

  // O(n)
  for index 0 to |B|-3:
    b_1 := B_with_index[index]
    b_2 := B_with_index[index+1]
    b_3 := B_with_index[index+2]

    // Note that we're only checking for inequality here
    // This is because i, j and k have no relationship
    // other than inequality. E.q., if A[i] < A[j], we can
    // just swap the definitions of i and j.
    if A[b_1.index] != A[b_2.index] and A[b_2.index] != A[b_3.index] then
      return b_1.value + b_2.value + b_3.value

  return error

This relies on the fact that if you sort an array such as [1, 5, 25, 2, -5, 50], the maximum sum will be at the start: [50, 25, 5, 2, 1, -5]. Then all you have to do is make sure the indexes involved have the right property within A.


Counter Counter Knife - Punch Stab

Question: Sometime in BF4 people will punch me and knife me giving me no opportunity to counter knife, even if the F key is prompting to press. How do I do this when I knife people so that they cannot counter?
For reference - Here's a Video of what I mean. When you're actually in the game though, you can mash F to counter but it has no effect.
Answer: You (or your victim) only gets a chance to counter the knife attack if you try it head on (you and your victim are facing each other).
To guarantee a kill without a counter, you have to attack from an angle (from the side, from behind, etc.).
The "magic punch" in the video happens because the opportunity to counter was missed, and not due to a specific button combination.
Comment: Exactly. Every other case can be blamed on "netcode" (although I hate that complaint) or other synchronization bugs, where the knifed player is facing in another direction than the one you see or the "player pressed F" message arrives too late at the server.

Counter Counter Knife - Punch Stab


How to speedup data retrieval from 2 servers on different hosts

Question: I have a database server on host A, and some applications also on host A,
on host B hosted by mediatemple i have application that needs to retrieve data from host A, this app works fine and super fast when on host A, but when on host B it's A LTO slower, it sometimes take 10 seconds to generate the page.
Because slow SQL queries.
I tried persistent connections, it made the app load twice as fast,
also i setup a ssh tunnel, it also improved the speed a bit, but it is still extremely slow!
Any solution to my problem?
Answer: I suggest making a cache. Make a local copy of important host B data on A server, then use a cron job to synchronize it every 15-60seconds. Synchronization can be make in both sides.
Answer: Well since no other method worked as well, i decided to setup a Master => Slave relationship and use database replication.
Works like a charm, quite fast, and i can use SSL for data transfer!
Tnx a lot
Answer: Try experimenting with mysql replication or a ndb node.


WCF, StackOverflowException

Question: I'm getting StackOverflowException at this line. I'm kind of new to WCF but as far as i can see it's not called in an infinity loop. Well i was hoping someone here could shed some light on this problem.
 get { return LevStad; }

The code.
 // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        string GetData(int value);
    [OperationContract]
    Kund GetDataUsingDataContract(Kund kund);

    // TODO: Add your service operations here
}
[DataContract]
public class Kund
{
    int iD;
    string fornamn = "";
    string efterNamn = "";
    string telefon = "";
    string boAdress = "";
    string boPostnummer = "";
    string boStad = "";
    string boLand = "";
    string levAdress = "";
    string levPostnummer = "";
    string levStad = "";
    string levLand = "";

    [DataMember]
    public int ID
    {
        get { return iD; }
        set { iD = value; }
    }

    [DataMember]
    public string Fornamn
    {
        get { return fornamn; }
        set { fornamn = value; }
    }
    [DataMember]
    public string EfterNamn
    {
        get { return efterNamn; }
        set { efterNamn = value; }
    }
    [DataMember]
    public string Telefon
    {
        get { return telefon; }
        set { telefon = value; }
    }
    [DataMember]
    public string BoAdress
    {
        get { return boAdress; }
        set { boAdress = value; }
    }
    [DataMember]
    public string BoPostnummer
    {
        get { return boPostnummer; }
        set { boPostnummer = value; }
    }
    [DataMember]
    public string BoStad
    {
        get { return boStad; }
        set { boStad = value; }
    }
    [DataMember]
    public string BoLand
    {
        get { return boLand; }
        set { BoLand = value; }
    }
    [DataMember]
    public string LevAdress
    {
        get { return levAdress; }
        set { levAdress = value; }
    }
    [DataMember]
    public string LevPostnummer
    {
        get { return levPostnummer; }
        set { levPostnummer = value; }
    }
    [DataMember]
    public string LevStad
    {
        get { return LevStad; }
        set { levStad = value; }
    }
    [DataMember]
    public string LevLand
    {
        get { return levLand; }
        set { levLand = value; }
    }
}

    public class Service : SQLBase, IService
    {
        public Service() : base()
        {

        }
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }
        public Kund GetDataUsingDataContract(Kund kund)
        {
            kund = new Kund();
            SqlCommand SQLCom = new SqlCommand(@"SELECT Kund.ID, Förnamn, Efternamn, Telefon, Adress, Postnummer, Stad, Land
FROM Webbshop.dbo.Kund INNER JOIN Webbshop.dbo.Adress ON Kund.BoAdress = Adress.ID");
            SQLCom.Connection = DatabaseConnection;
            SQLCom.Connection.Open();
            SqlDataReader rdr = SQLCom.ExecuteReader();
            while (rdr.Read())
            {
                kund.ID = (int) rdr[0];
                kund.Fornamn = rdr[1].ToString().Trim();
                kund.EfterNamn = rdr[2].ToString().Trim();
                kund.Telefon = rdr[3].ToString().Trim();
                kund.BoAdress = rdr[4].ToString().Trim();
                kund.BoPostnummer = rdr[5].ToString().Trim();
                kund.BoStad = rdr[6].ToString().Trim();
                //kund.BoLand = rdr[7].ToString().Trim();
                //kund.LevAdress = rdr[8].ToString();
                //kund.LevPostnummer = rdr[9].ToString();
                //kund.LevStad = rdr[10].ToString();
                //kund.LevLand = rdr[11].ToString();
            }
            SQLCom.Connection.Close();
            return kund;
        }
    }

public class SQLBase
{
    protected static SqlConnection DatabaseConnection = new SqlConnection();
    public SQLBase()
    {
        DatabaseConnection.ConnectionString =
           "Data Source=(local);Initial Catalog=Webbshop;Integrated Security=True";
    }
}

Kund kund = null;// = new Kund();
using (ServiceReference.ServiceClient wcfClient = new ServiceReference.ServiceClient())
{
    kund = wcfClient.GetDataUsingDataContract(kund);
}

Comment: If you want people to read your code and try to help, please consider removing the irrelevant 99%.
Answer: It's the capitalization. It should return the variable:
get { return levStad; }
Right now, it's returning itself, which calls get, which returns itself... stack overflow.

You'll also have an issue with BoLand; set will set itself, which will call set... again, capitalization:
public string BoLand
{
    get { return boLand; }
    set { boLand = value; }
}
Answer: public string LevStad
{
    get { return LevStad; }
    set { levStad = value; }
}

There is your problem. It's recursing on LevStad.
ie. You get LevStad and it tries to get the property LevStad, which tries to get the property LevStad. And so it goes on until the call-stack overflows.
Just make it set the field instead (C# is case-sensitive).
public string LevStad
{
    get { return levStad; }
    set { levStad = value; }
}

You will have a similar problem on the set of BoLand.
public string BoLand
{
    get { return boLand; }
    set { BoLand = value; }
}

Comment: That's actually another similar error. The one OP asked about is LevStad

WCF, StackOverflowException


How to use component binding in JSF right ? (request-scoped component in session scoped bean)

Question: Mojara 2.1.21
I've updated my question based on comments. I have two situation where a component is bound to server session bean. (Additional links with information: Binding attribute causes duplicate component ID found in the view and https://stackoverflow.com/a/12512672/2692917)
Version 1:
single.xhtml:
 <h:outputText value=... binding="#{mysessionbean.out}" />

java:
 @SessionScoped @Named public class Mysessionbean {
    UIOutput out;
    //getter and setter ....
 }

Version 2:
template.xhtml:
 <h:outputText value=... binding="#{mysessionbean.out}"

view1.xhtml:
 <ui:composition template="template.xhtml" />

view2.xhtml:
 <ui:composition template="template.xhtml" />

java:
 @SessionScoped @Named public class Mysessionbean {
    UIOutput out;
    //getter and setter ....
 }

Version 1 is ok. (At least I've not encounter any errors so far). But in version 2 the duplicate id error is occured if I navigate from one page to another. Why does it happen ?
Is it safe to use (request-scoped) component (in version 1) with session scoped binding ?
Are there another use cases to consider ?
Edit:
Functional requirement 1:
I want to use Primefaces datatable in a view. I need some info from this datatable. (Such as selected row or row index). So binding the datatable helps me to retrieve this info.
Functional requirement 2:
Components binding in composite components. They will be bound to session scoped bean. (And used mainly on one page, but what if I used it on another page ?
Requirements 3
The situation as in "Version 2". Template with primefaces menu and session scoped binding. For this I've used the EL-Binding.
Comment: This is very definitely not right, no. Component instances are inherently request scoped. See also: http://stackoverflow.com/questions/2101755/. Before posting an answer, please elaborate the concrete functional requirement for which you thought that this would be the right solution. Then I can tell the right way for that.
Comment: You have still not elaborated the functional requirement.
Comment: 2 and 3 are unclear. The functional requirement is missing.
Answer: In JSF 2.x, unless you want to manipulate components programmatically (which is at its own also rather fishy), there is no sensible real world use case to bind components to a backing bean. For sure not if they are further not been used in the backing bean itself, or if it are solely their attributes which are been flattened out.

As to the functional requirement of getting the current row of the data table, there are much better ways listed here, How can I pass selected row to commandLink inside dataTable?, for example if your environment supports EL 2.2:
<h:dataTable value="#{bean.items}" var="item">
    <h:column>
        <h:commandLink value="Foo" action="#{bean.foo(item)}" />

The two last requirements are totally unclear. At least, if you're doing something like:
<x:someComponent binding="#{bean.someComponent}" />

with in bean
someComponent.setSomeAttribute(someAttribute);
someComponent.setOtherAttribute(otherAttribute);

then you should instead be doing
<x:someComponent someAttribute="#{bean.someAttribute}" otherAttribute="#{bean.otherAttribute}" />

Or, if you intend to be able to use the component somewhere else in the view like so
<h:inputText ... required="#{not empty param[bean.save.clientId]}" />
...
<h:commandButton binding="#{bean.save}" ... />

and the instance is further nowhere been used in the bean, then just get rid of the unnecessary property altogether:
<h:inputText ... required="#{not empty param[save.clientId]}" />
...
<h:commandButton binding="#{save}" ... />

If there is really, really no way for some unclear reason, then split all request scoped properties of the session scoped bean out into a separate request scoped bean which you in turn bind to form actions. The session scoped one can just be injected as a @ManagedProperty of the request scoped one.

See also:

Binding attribute causes duplicate component ID found in the view
How does the 'binding' attribute work in JSF? When and how should it be used?
Comment: Nice abstract explanation! To your last suggestion, I am using CDI, so can I inject request scoped wrapper class in session scope ? Because likely I need component in session scoped bean as inversely.
Comment: Yes, that can in turn also.
Answer: We ran into a similar problem and I just want to share our solution:
Problem:
In a view there was a (extended largely customized) datatable.
<x:dataTable binding="#{bean.someSomeDataTable}" />

After navigating to another page and back we wanted the datatable to have the exact same state. Previously we solved that by binding the datatable to to backing bean. This worked fine with JSPs. With Facelets we could not do that (Duplicate ID errors). So we used the binding, but only saved/restored the state of the datatable component.
public HtmlDataTable getSomeDataTable()
{
 HtmlDataTable htmlDataTable = new HtmlDataTable();
 if (tableState != null)
   htmlDataTable.restoreState(FacesContext.getCurrentInstance(), tableState);
 return htmlDataTable;
}

public void setSomeDataTable(HtmlDataTable table)
{
  tableState = table.saveState(FacesContext.getCurrentInstance());
}


Android: Fragment is not attached to Activity error

Question: So I'm working on an app and I had this part working for days, and out of no where it just stopped working for no reason...
I also had the same error when I was trying to use another headless fragment in my MainActivity, but ended up replacing the fragment with inner methods inside of the MainActivity and everything went back to working properly.
However, I can't rewrite every bit of code I have just to avoid using fragments. The fragment code is below.
public class IMEIFragment extends Fragment implements ActivityCompat.OnRequestPermissionsResultCallback{

    public static final String TAG_IMEI = "IMEILoader";
    protected Activity mActivity;

    private String RecordedIMEI;
    //public static final String CHECK_INTERNET = "network_connection";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return null; //Do we need this at all?
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Activity activity = context instanceof Activity ? (Activity) context : null;
        mActivity = activity;
    }

    //Is this needed?
    @SuppressWarnings("deprecation")

    @Override
    public void onAttach(Activity activity) {
        activity = getActivity();
        if (isAdded() && activity != null) {
            super.onAttach(activity);
        }

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            mActivity = activity;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mActivity = null;
    }

    public String loadIMEI(Context context) {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE)
                    != PackageManager.PERMISSION_GRANTED) {
                // READ_PHONE_STATE permission has not been granted.
                requestPermissions(context);
            } else {
                // READ_PHONE_STATE permission is already been granted.
                RecordedIMEI = permissionGrantedActions(context);
            }
            if (RecordedIMEI != null) {
                Log.i("loadIMEIService", "IMEI number returned!");
            }
        } else {
            // READ_PHONE_STATE permission is already been granted.
            RecordedIMEI = permissionGrantedActions(context);
        }
        if (RecordedIMEI != null) {
            Log.i("loadIMEIService", "IMEI number returned!");
        }
        return RecordedIMEI;
    }
    private void requestPermissions(Context context) {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            Log.i("loadIMEIService", "READ_PHONE_STATE permission not granted, asking for it...");

            // TODO create proper notification content

            PermissionHelper.requestPermissions(((PriceActivity) getActivity()),
                    new String[]{Manifest.permission.READ_PHONE_STATE},
                    Constants.PERM_REQUEST_PHONE_STATE,
                    getString(R.string.notify_perm_title),
                    getString(R.string.notify_perm_body),
                    R.drawable.ic_security);
        }
    }

    // Callback received when a permissions request has been completed.
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        boolean isGranted = false;
        for (int i = 0; i < grantResults.length; i++)
            if (permissions[i].equals(Manifest.permission.READ_PHONE_STATE) && (grantResults[i] == PackageManager.PERMISSION_GRANTED))
                isGranted = true;
        if (isGranted) {
            Context context = getActivity().getApplicationContext();
            permissionGrantedActions(context);
        }
        else
            Log.w("loadIMEIService", "READ_PHONE_STATE permission not granted. loadIMEI will not be available.");
    }

    public String permissionGrantedActions(Context context) {
        //Have an  object of TelephonyManager
        TelephonyManager tm =(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        //Get IMEI Number of Phone
        String IMEINumber = tm.getDeviceId();

        if(IMEINumber != null) {
            Log.i("loadIMEIService", "IMEI number recorded!");
        }
        return IMEINumber;
    }
}

Error is below:
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.android.project1, PID: 5498
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.project1/com.android.project1.main.MainActivity}: java.lang.IllegalStateException: Fragment IMEIFragment{3e80da7 IMEILoader} not attached to Activity
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                      at android.app.ActivityThread.-wrap11(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:148)
                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                   Caused by: java.lang.IllegalStateException: Fragment IMEIFragment{3e80da7 IMEILoader} not attached to Activity
                      at android.app.Fragment.getResources(Fragment.java:805)
                      at android.app.Fragment.getString(Fragment.java:827)
                      at com.android.project1.fragments.IMEIFragment.requestPermissions(IMEIFragment.java:107)
                      at com.android.project1.fragments.IMEIFragment.loadIMEI(IMEIFragment.java:80)
                      at com.android.project1.main.MainActivity.onCreate(MainActivity.java:108)
                      at android.app.Activity.performCreate(Activity.java:6237)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                      at android.app.ActivityThread.-wrap11(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:148)
                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

And here's the relevant part of my MainActivity:
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDeviceCode = (TextView) findViewById(R.id.device_code);

        // Initializing headless fragment
        mFragment =
                (IMEIFragment) getFragmentManager()
                        .findFragmentByTag("IMEILoader");

        if (mFragment == null) {
            mFragment = new IMEIFragment();
            getFragmentManager().beginTransaction()
                    .add(mFragment, "IMEILoader").commit();
        }
        if (mFragment != null) {
            mNumber = mFragment.loadIMEI(MainActivity.this);
            mDeviceCode.setText(Html.fromHtml("IMEI: " + mNumber));
        }

I literally had the exact same code working for over a week. Anyone knows what could be the problem?
Edit 1: The error is pointing to requestPermissions inside my fragment
Comment: We've already covered that [you don't really need a Fragment here](http://stackoverflow.com/questions/41844116/android-studio-error-of-java-lang-nullpointerexception-when-the-headlessfragmen)
Comment: why multiple overrides to onAttach() ?
Comment: @CSmith If I remember right, it was for different build versions as some method was deprecated. I will try to take one of them out and see if it affects anything.
Comment: you certainly can't call getActivity() from onAttach() and expect it to work.  Get rid of both onAttach() overrides and onDetach(), they aren't needed.  If you need access to a context, use getActivity().  Follow the guidance from @Blattman
Answer: Fragments should be self contained as much as possible. You are calling directly into your IMEIFragment from the activity,
           Caused by: java.lang.IllegalStateException: Fragment IMEIFragment{3e80da7 IMEILoader} not attached to Activity
              at android.app.Fragment.getResources(Fragment.java:805)
              at android.app.Fragment.getString(Fragment.java:827)
              at com.android.project1.fragments.IMEIFragment.requestPermissions(IMEIFragment.java:107)
              at com.android.project1.fragments.IMEIFragment.loadIMEI(IMEIFragment.java:80)
              at com.android.project1.main.MainActivity.onCreate(MainActivity.java:108)

You can't do that. Adding the fragment via a transaction from the activity is an asynchronous operation. E.g., when the commit() method completes, the fragment is not initialized. Moreover, you have no way of knowing when it's initialized. That's why it should be self contained. The fragment decides when to call loadIMEI(), not the activity.
If you really need it to be initiated by the activity, you can add a callback from the fragment to the activity like,
void onFragmentReady(Fragment f);

Or something.
And yes, onCreateView() should return something. If your fragment really doesn't have any UI at all, you don't need it to be a fragment.
Comment: Headless fragment == `Object`.
Comment: I think I got most of what you're trying to say. So, in my MainActivity I should change this>>if (mFragment != null) {
            mNumber = mFragment.loadIMEI(MainActivity.this);
            mDeviceCode.setText(Html.fromHtml("IMEI: " + mNumber));
        }<< to this>> if (mFragment != null && mFragment.isAdded()) {
            mNumber = mFragment.loadIMEI(MainActivity.this);
            mDeviceCode.setText(Html.fromHtml("IMEI: " + mNumber));
        }<<
Comment: Or should I call the loadIMEI inside onResume() instead of from within the Activity?
Comment: Your activity should not call any method on your fragment class. Your fragment should call `loadIMEI()` as part of its lifecycle. Consider my comments above re: Do you really need a fragment?
Comment: Looks like OP is trying to make a headless fragment.
Comment: I don't think that I really need a fragment. I used a headfragment for multiple reasons; so I don't have to worry about screen rotation and such, and for writing a manageable code and to request runtime permissions from outside of my MainActivity (I already have runtime permission methods there and use it for different group of perm.).
Comment: @Zack A singleton object can also "handle rotation" because it is loaded in memory exactly once. Using fragments for handling that is a bad design because you have nothing in your IMEI loading that would benefit from handling rotation. You request permissions, and they are accepted or denied.
Comment: @cricket_007 I think you're right. I'm rewriting my code right now. I might have a couple follow up questions as I remember I had some difficulty implementing this last time you suggested it and I would really appreciate some pointers. I wish I listened earlier, I used the same design for a lot of things, I'm in too deep...


What is proper way to wire hard wired LED strip light power supply/controller/driver?

Question: I'm considering LED strip lighting for a pantry and for the stairway to the basement.  I see three types of power supplies for the strips:  with an AC plug, with pigtails, and with screw posts.  The ones with an AC plug are easy to use and I might consider that for the stairway, but I can't easily hide the plug and outlet in the pantry (it wouldn't look "clean").
The power supplies look to be too large to fit inside an electrical box.
I could mount the pigtailed power supply outside the box and run the wires to the inside where I attach to 120 VAC.  But, I'm concerned you can't have exposed AC wires (going from the supply to the box).  What's code compliant?  Do I put them in some sort of conduit?
What about the supplies with the screw posts??  I'm pretty sure I can't wrap tape around it to isolate the AC (tape could come off).  These mystify me.
Thanks,
Jim
p.s.  Got asked for examples...First is an example of one with a plug, second is an example of one with pigtails, and third is an example of one with screw posts:
Comment: Just FYI you can get electrical boxes of just about any size you want -- you're not limited to the tiny ones used for light switches and outlets.  That may not help you in your kitchen cabinets however.
Comment: The drivers I've seen with screw posts, the posts are actually under a cover. Sometimes a product photo doesn't show the cover. I'd agree that you don't want exposed line voltage. It would help if you would provide data and photos about the specific products you're considering.
Comment: I didn't know that--thanks.  I did a quick search and see pretty large size PVC boxes--not sure how they mount and how you attach wires (I don't see knockouts).  I'll keep looking.
Comment: @AdirondackJim some NEMA enclosures (aka "big electrical boxes") come with knockouts, while others don't, as you're expected to use a punch (metal) or holesaw (plastic) to make your own KOs in such boxes
Comment: ThreePhaseEel, thanks for explaining what I saw.
Answer: I'm pretty sure the proper way involves using a (large) electrical box (Thanks Nate S).  They make them in a variety of sizes--some quite large, like the ones holding your circuit breakers.  I saw a picture of a large one containing a large switching power supply.  You mount it some place out of the way, like in the basement, or in the attic (if you have access) and then run low voltage wires to the room/led tape.
If the power supply is pigtailed, I also think you could butt it up against an electrical box and have the high voltage wires enter where it butts up.  That way no high voltage wires are exposed--kind of how I see the doorbell or boiler transformer mounted to a box.  I'm basing this solely on the transformers I've seen.


PS4 and TV link stopped working

Question: I played the PS4 earlier today and didn't face any issues.
However I fired it up a few moments ago and all I get is a blank screen with flickering audio. The screen is permanently blank though, it tries to load the PS4 logo but it turns out skewed and scattered around the screen (for a very brief moment) then goes back to being blank.
What I've tried but didn't fix the problem :

Changing HDMI cables
Plugged in HDMI from a working device to the PS4; still blank
Tried booting in safe mode; blank/flickering screen and audio
Turned TV Off then back On
Keep the PS4 running for a while

However now I noticed that this happens with one TV only. I tried connecting my PS4 to a PC Monitor and it ran fine !!
What could cause the TV to stop recognising the PS4 ? All HDMI ports do not provide visual output from the PS4. Also, the last update the PS4 received was for the playroom, not sure if it has anything to do with it. The camera is usually plugged in but I don't know if someone plugged it out or something before the issue appeared.
Comment: Did you ask this like a week ago too? I swear I saw it before...
Comment: "Plugged in HDMI from a working device to the PS4; still blank" Does this mean you moved an HDMI cable from, say a working PS3, to the PS4?  Basically, the TV's HDMI ports work with other devices, and the PS4 works with other TV's?  Perhaps provide the make/model of your TV?
Comment: @turbo Yeah the HDMI ports work with other devices, and the PS4 works on other TVs. It's just that particular TV and PS4 clashing ! My TV is the LG 55LW6510
Answer: Remember that TV's these days are basically dumb computers with huge monitors.  If the PS4 is fine, it could be the logic board on the TV itself.
Comment: Any reason given for the downvote?

PS4 and TV link stopped working


Available RAM not being used

Question: I am running a program that takes a significant amount of time to complete.  According to my system monitor, only 20% of the available memory is being used (1.6GiB out of 7.7GiB available).
I'm wondering why is the available memory not being used?  Any information would be greatly appreciated.
Comment: Does the program have configurable options or use other programs such as MySQL where you can allocate more memory to caches, etc that will increase the speed of operations?
Answer: It probably doesn't need that much RAM.
If I write a program that opens a file with a random filename, writes "Hi there, Moon!", and closes that file cleanly, and repeats that a couple of million times, It would use very little memory, but will take a lot of time.

Available RAM not being used


ParseInt of toLocaleTimeString() in Internet Explorer

Question: I have problem with parse string after toLocaleTimeString()
var b = new Date();
var c = b.toLocaleTimeString();
var d = c.split(":");
var e = parseInt(d[0]);

After this:
 Internet Explorer:
     e is NaN,
     d is "15"
 Chrome:
     e is 15,
     d is "15"
Answer: In IE you need to use charAt() instead of d[0] after converting to string.

var b = new Date();
var c = b.toLocaleTimeString();
var d = c.split(":");

// For IE Support...
var D = d.toString();
var e = parseInt(D.charAt(0));
if ( isNaN(e) === true ){
    var e = parseInt(D.charAt(1));
}

alert(d);
alert(e);


Letter Z drawn with stars python

Question: I'm new in python and I'm struggling with one problem. I have to make letter Z with stars(*) using for loop. I am working in Python 2.7. Can anyone help?
Comment: Are you given the number of start to use on the top and bottom stroke? Is the diagonal stroke to be at a 45 degree angle? Is this to be a function or a code segment? Can three for-loops be used or must there be only one? Is this letter to be printed or stored for later use? Finally, what have you tried--please show us some code.
Comment: are you struggling to start coding? or struggling with some part of the problem? If you are working with python 2.7, please show some code, something, for us to start with.. If it's `for` loop syntax that you need help with, check this out: https://wiki.python.org/moin/ForLoop, start with one line, etc, if you get stuck, click the [edit](http://stackoverflow.com/posts/40518628/edit) button on your question, add some code you've written, then we can help you further. Also, this has a good starting point http://stackoverflow.com/questions/22736522/creating-shapes-or-letters-using-python
Comment: I won't do this because I would just received ten downvotes, but I'm really tempted to answer with "Yes, I can help.".
Answer: Here is a solution:
def print_z():
    base = '***************'
    print base
    for i in reversed(range(0, len(base))):
        void = ' '.join(['' for j in range(0,i+1)])
        print void + '*'
    print base

One improvement is to give the width of the base as an argument:
def print_z(width):
    base = '*'.join(['' for i in range(0, width+1)])
    print base
    for i in reversed(range(0, width)):
        void = ' '.join(['' for j in range(0,i+1)])
        print void + '*'
    print base

It outputs something like this:
**********
         *
        *
       *
      *
     *
    *
   *
  *
 *
*
**********

Comment: Do you really want to give a complete answer to a vague question showing so little work?
Comment: @RoryDaulton while I agree, down-votes are unwarranted on the answer and should be directed to the question only.
Comment: @RoryDaulton is it against SO rules? or against SO "spirit"? Also I don't think that deserves to be down voted.
Comment: @EmileBergeron: That is not what I have seen in other similar situations, including ones I where I answered such a question and got downvotes. Is there some official policy on this issue somewhere? (This is a real question, not snark.) I'll change my vote if I see adequate evidence, of course.
Comment: @RoryDaulton it's really unfortunate to receive down-votes when trying to help. It's true that by answering a bad question, it kind of do the opposite to the community. The best would be to flag, and down-vote the question. Inform the user with a comment is also good.
Comment: @RoryDaulton [Is it okay to downvote answers to bad questions?](http://meta.stackoverflow.com/questions/255459/is-it-okay-to-downvote-answers-to-bad-questions)
Comment: @EmileBergeron: OK, that link convinced me. I'll change my downvote to an upvote. I wish I could give that link to all who downvoted me when I started here and gave answers to such questions.
Comment: @RoryDaulton don't mind down-votes as it takes 5 to counter 1 upvote. If your answer is down-voted to hell, maybe deleting is the best option (you even receive a [badge](http://stackoverflow.com/help/badges/38/peer-pressure) for that!)

Letter Z drawn with stars python


Fetching an Object from a tableview cell using fetchcontroller?

Question: I want the user to be able to click a cell in a table and it retrieve whatever object is at that index path and set it to a variable so i can pull it though to the next VC.
How is this achieved? My logic was to use something like:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if segue.identifier == "loadTodaysRoutine" {
      setRoutine = fetchedResultsController.fetchedobjects[indexPath.row]
      if let todaysRoutineController = segue.destination as? RoutineController {
                todaysRoutineController.routineObject = setRoutine
      }

I thought that this would make setRoutine the index patch clicked, then i could send it to another VC via a segue, but i feel im missing some steps as it doesnt work!
Thanks for any help filling in the gaps in my understanding
update, whole VC as requested
import Foundation
import UIKit
import CoreData

class YourWorkoutsController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate {

    // MARK: - DECLARATIONS

    private let persistentContainer = NSPersistentContainer(name: "Lift")
    var managedObjectContext: NSManagedObjectContext?

    fileprivate var setRoutine: NSManagedObject?

    @IBAction func unwindToTemplates(segue: UIStoryboardSegue) {}
    @IBOutlet weak var workoutTemplateTable: UITableView!
    @IBOutlet weak var createWorkoutLabel: UILabel!
    @IBOutlet weak var nameLabel: UILabel!

    // MARK: - ACTIONS

    @IBAction func cancelWorkoutSelection(_ sender: Any) {
        self.performSegue(withIdentifier: "unwindToRoutineWithSegue", sender: self)
    }

    // MARK: - VIEWDIDLOAD

    override func viewDidLoad() {
        super.viewDidLoad()
        setupView()
        workoutTemplateTable.delegate = self
        workoutTemplateTable.dataSource = self

        view.backgroundColor = (UIColor.customBackgroundGraphite())

        persistentContainer.loadPersistentStores { (persistentStoreDescription, error) in
            if let error = error {
                print("Unable to Load Persistent Store")
                print("\(error), \(error.localizedDescription)")

            } else {
                self.setupView()

                do {
                    try self.fetchedResultsController.performFetch()
                } catch {
                    let fetchError = error as NSError
                    print("Unable to Perform Fetch Request")
                    print("\(fetchError), \(fetchError.localizedDescription)")
                }

                self.updateView()
            }
        }
    }

    // MARK: - VIEWWILLAPPEAR

    override func viewWillAppear(_ animated: Bool) {

        do {
            try self.fetchedResultsController.performFetch()
        } catch {
            let fetchError = error as NSError
            print("Unable to Perform Fetch Request")
            print("\(fetchError), \(fetchError.localizedDescription)")
        }
        self.workoutTemplateTable.reloadData()
    }

    // MARK: - TABLE SETUP

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard let userRoutine = fetchedResultsController.fetchedObjects else { return 0 }
        return userRoutine.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

        cell.backgroundColor = UIColor.customBackgroundGraphite()
        cell.textLabel?.textColor = UIColor.white

        let userRoutine = fetchedResultsController.object(at: indexPath)
        cell.textLabel?.text = userRoutine.name
        return cell
    }

    // MARK: - TABLE UPDATING COMPONENTS

    private func setupView() {
        setupMessageLabel()
        updateView()
    }

    private func setupMessageLabel() {
        createWorkoutLabel.text = "You Don't Have Any Workouts Yet\n Tap + To Create A New Workout"
    }

    fileprivate func updateView() {
        var hasUserRoutines = false
        if let UserRoutine = fetchedResultsController.fetchedObjects {
            hasUserRoutines = UserRoutine.count > 0
        }
        workoutTemplateTable.isHidden = !hasUserRoutines
        createWorkoutLabel.isHidden = hasUserRoutines

    }

    // MARK: - COREDATA FETCH

    fileprivate lazy var fetchedResultsController: NSFetchedResultsController<UserRoutine> = {

        // Create Fetch Request
        let fetchRequest: NSFetchRequest<UserRoutine> = UserRoutine.fetchRequest()
        // Configure Fetch Request
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
        // Create Fetched Results Controller
        let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: nil)
        // Configure Fetched Results Controller
        fetchedResultsController.delegate = self
        return fetchedResultsController
    }()

    // MARK: - ADDING NEW ROUTINE TO THE VC / PUSHING ROUTINE TO TODAYSROUTINE VC

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.setRoutine = fetchedResultsController.fetchedObjects[indexPath.row]
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "addNewRoutineSegue" {
            if let destinationViewController = segue.destination as? WorkoutDesignerController {
                // Configure View Controller
                destinationViewController.managedObjectContext = persistentContainer.viewContext
            }
        }

        if segue.identifier == "loadTodaysRoutine" {

            if let todaysRoutineController = segue.destination as? RoutineController {
                todaysRoutineController.routineObject = self.setRoutine
            }
        }
    }

    func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        workoutTemplateTable.beginUpdates()
    }

    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        workoutTemplateTable.endUpdates()
        updateView()
    }

    // MARK: - ADDING TABLE ROW

    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
        switch (type) {
        case .insert:
            if let indexPath = newIndexPath {
                workoutTemplateTable.insertRows(at: [indexPath], with: .fade)
            }
            break;
        case .delete:
            if let indexPath = indexPath {
                workoutTemplateTable.deleteRows(at: [indexPath], with: .fade)
            }
            break;
        default:
            print("...")
        }
    }

    // MARK: - DELETING TABLE ROW

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            //fetch exercise
            let UserRoutine = fetchedResultsController.managedObjectContext
            //delete exercise
            UserRoutine.delete(fetchedResultsController.object(at: indexPath))
            //save exercise persistence
            do {
                try UserRoutine.save()
            } catch {
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

}

Comment: could you post more code?
Comment: such as? this is the segue, i wasnt sure what else is needed to construct a request
Comment: where do you call that segue? (in cellForRowAtIndexPath) ?
Comment: the segue is just linked in the storyboard from the cell prototype
Comment: the tableview is static ?
Answer: First create a local var in your current VC and assign the value to it in your didSelectRow like :
fileprivate var setRoutine: Any?
.....

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       if let routine = fetchedResultsController.fetchedObjects[indexPath.row] {
        self.setRoutine = routine
    }
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     if segue.identifier == "loadTodaysRoutine" {
         if let todaysRoutineController = segue.destination as? RoutineController {
               todaysRoutineController.routineObject = self.setRoutine
         }
     }
}

Comment: apparently im not using any didSelectRow method in my superclass to override, what classes does the VC need to be using for this to work? also getting 'Value of optional type '[UserRoutine]?' not unwrapped; did you mean to use '!' or '?'?'
Comment: What is the superclass for your `tableView`? Please refer this doc https://developer.apple.com/reference/uikit/uitableview
Comment: im just using UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate currently
Comment: This `didSelect` method is defined in `UITableViewDelegate`. Please go through the above document, you will understand.
Comment: I assume im missing something but i cant see didselect in the doc above and im using UITableViewDelegate currently but still have the issue
Comment: What issues do you have? and which line it is giving you errors? Could you post whole code in your question?
Comment: well it wasnt part of my question, its your didSelectRowAt function in your answer, it throws method does not override method from its superclass, and then 'Value of optional type '[UserRoutine]?' not unwrapped; did you mean to use '!' or '?'?'
Comment: Please post more code which shows your current `VC` declarations and `fetchedObjects`
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/130233/discussion-between-santosh-and-infernouk).
Comment: Alright, remove the `override` keyword for `didSelect` method. Now which line the other error you are seeing?
Comment: the line below it, "self.setRoutine = fetchedResultsController.fetchedObjects[indexPath.row]
" because its pulling up the managedobject but not unwrapping as the error says
Comment: same issue on same row, you arent unwrapping the NSManagedObject pulled from the fetch request
Comment: Then unwrap it, try casting to the right `type`. Do you know what is wrapping/unwrapping?
Comment: pretty sure i can just do "self.setRoutine = fetchedResultsController.fetchedObjects?[indexPath.row]" adding the ? after the fetched object, this solves the error
Comment: out of interest to see if this is working, is there a way to print or check that the object setting sent through has information in it? I tried print(routineObject) but its not doing anything
Comment: Please go to above chat session


statement.executeUpdate() always returns 1

Question: I have a problem with the JDBC executeUpdate() method. It always returns 1 whether it updates a row or not. As far as I understand the method it should return 0 is no rows are altered.
Here is a sample of my code:
try {
conn = pool.getConnection();
        PreparedStatement ps = conn.prepareStatement("{CALL UPDATE_USER (?,?,?)}");
        ps.setString(1, field.toString());
        ps.setString(2, change);
        ps.setString(3, userID);
        int updated = ps.executeUpdate();
        System.out.println(updated);
        if(updated==0){
            throw new NoUserException();
        }
        ps.close();
    } catch (SQLException e) {
        log.error("An error occurred while creating the connection");
        e.printStackTrace();
    } finally {
        pool.returnConnection(conn);
    }

Could this be because I'm using a prepared statement or a stored procedure?
Here is the stored procedure:
create or replace
PROCEDURE UPDATE_USER
(
  updateColumn IN user_tab_columns.column_name%type,
  changeStr IN VARCHAR2,
  unID IN VARCHAR2
)
IS
BEGIN
  EXECUTE IMMEDIATE
    'UPDATE
      users
SET ' || updateColumn || '= :1
WHERE
  uniqueID = :2'
  USING changeStr, unID;
END;

Comment: It is probably updating to row with the same information, so you get 1 but see no change
Comment: What is the code in the UPDATE_USER procedure? And what are the values of the three parameters that you are passing in?
Comment: does update_user return a value?
Comment: @KevinBrydon passes in a column name(string), a string to change it to and a userID(string)
Comment: Usually if you do `UPDATE ... SET x = y WHERE id = ...`, then the row is updated, even if nothing was changed (`x` already was `y`). So the number of updated rows is 1.
Answer: It can't get info from stored proc execution. If you want to get row count (or anything else) switch PROCEDURE to FUNCTION, add return clause in this function, and change your call to something like ? = CALL ... Test with sql%rowcount inside function to get impacted row count.
Answer: You can use Callable statement a procedure or function.  And return the no of rows affected as a return parameter
Comment: I was trying to avoid using Callable statements to avoid using vendor specific implementations


Can I reach this place in Superfrog?

Question: I was a bit nostalgic and fired up my WinUAE and played some Superfrog. At the last level of the ice world I found something funny:

My question is: Can I get to those goods somehow? I searched for secret doors but no luck. Any ideas? Or is this an easter egg?
Comment: The tag "retro-game-challenge" has so far been used for the Nintendo DS game of that name. In my opinion it is a potential cause of confusion in this question.
Comment: It's probably an easter egg or a teaser. You can't get any further with the pencil blocking your path. 6-4 has something similar near the end.
Answer: I'm going to go out on a ledge and assert that no, you cannot.  I'm basing this opinion on this longplay, which shows the area in question at 1:39:39.
The author of that video goes to great lengths to show all the hidden passages, item collects, etc, and seems to indicate, through jumping around the pencil that it is impassable.
It's not proof, but barring the game's developer making a statement to the contrary I don't think we're likely to get any further on this one.

Can I reach this place in Superfrog?


How to get the minCardinality of properties?

Question: I am using Jena. How can I get the minCardinality of a property?
Answer: Try asking on SemanticOverflow.com
Answer: Let me guess... it's a class assignment? Maybe ask Fateme. :)


How can I create different portals to different sky block islands for multiplayer?

Question: I downloaded a sky block datapack and I want to create different portals to different sky block island for multiplayer.
How can I achieve this?
Comment: What datapack did you download?
Answer: Best Solution
From they way you posed the question it sounded like you intended to use minecraft's built-in portals, particularly the nether portal, impossible to do without a mod or script. (which you should provide more information about)    However the best, most well rounded solution I can come up with is a teleportation pad using a "special" block. The command for that would look something like this.
The command:
execute at @e[distance=..3] if block ~ ~-1 ~ ^your block^ at @s as @s run tp @e[distance=..3,limit=1] ^coordinates^ ^rotational coordinates^

^your block^ is where players(and all entities including items and pantings) are teleported from, it should never show up anywhere else in the map.
^coordinates^ where you want to teleport to. Your current coordinates (x, y, z) can be found by pressing Fn+F3 and looking for Block: "some numbers/coordinates".
^rotational coordinates^ these are 2 more coordinates that determine the direction your looking, these can be found by looking 2 rows under your coordinates.

By placing this command in a "repeating" command block set to "always active" right next to or under ^your block^, players will be teleported to ^coordinates^. From the side would look like...

□=Air
▅=Block
▣=Command Block
⊞=Portal Stone
▅ ▅ ⊞ ⊞ ⊞ ▅ ▅▅ ▅ ▅ ▣ ▅ ▅ ▅
Or like this..□ □ □ □ □ □ ▣ □▅ ▅ ⊞ ⊞ ⊞ ▅ ▅ Or this..▅ ▅ ⊞ ⊞ ⊞ ▣ ▅▅ ▅ ▅ ▅ ▅ ▅ ▅

To add some flare to the teleport, add a similar command block with an identical command but instead of run tp type run particle. For the sake of being concise, I will link to another forum post that explains how to finish the command.
How can I improve on this answer?
If it was helpful mark it correct so people visiting this page know.


How to use a map method on Set?

Question: Sorry for the stupid question, but I can't find the answer in Swift documentation...
let set: Set<String> = ["foo1", "foo2", "foo3"]
let res: Set<String> = set.map { return $0+"_bar" } // Ambiguous reference to member 'map'

How can I use map method on Set<T>?
p.s. Suggested "duplicate" question: 1) about other issue; 2) answers doesn't work in current Swift version
Comment: @i_am_jorf I'm not sure – it seems in earlier versions Set didn't has a "map" method – that's what that question about. In current version, Set has own "map" method, but I can't use it because of the error...
Answer: The problem is that set.map (really CollectionType.map) returns an Array, not a Set.  Hence:
let res = set.map { $0 + "_bar" }

Works and leaves you with [String] which you can convert back to a Set<String> with the constructor:
let res : Set<String> = Set(set.map{$0 + "_bar"})

Answer: Ah, the answer is pretty easy – thanks to other community for the help!
let set: Set<String> = ["foo1", "foo2", "foo3"]
let res: Set<String> = Set(set.map { return $0+"_bar" })

How to use a map method on Set?


php cookie ignoring secure flag

Question: I am trying to set a cookie with false in the secure parameter but when it is sent it always says secure/true. What could be causing my cookie setting to ignore that parameter?
setcookie( 'TEST', 'Testing', 0, C_PATH, C_DOMAIN, false );

Header:
Set-Cookie: TEST=Testing; path=/;HttpOnly;Secure

Answer: You also have the HttpOnly flag set - which is not on by default in PHP either. So it might be that these are added by your web server or something else between the client and PHP. Because PHP has no way of enabling these flags by default, you always have to set them explicitely for every setcookie call.
Yet I would recommend using both of them if you use them for PHP.
Comment: I tried using the httponly flag enabled and disabled and it still only comes across as a secure cookie..
Comment: Something else than PHP has to be modifying your cookies. I tried your example with the built-in PHP server (`php -S localhost:8000`) and `setcookie( 'TEST', 'Testing', 0, '/', null);` and received `Set-Cookie: TEST=Testing; path=/`

php cookie ignoring secure flag


After installing Firestarter system doesn't automatically switch between wired and wireless network

Question: I initially installed Firestarter to set up some thing in network and watch if connections to my computer work. I used wizard, which was definitely wrong decision.
I use both cable (and occassionally share connection via wi-fi) and wi-fi often, and now system doesn't switch "Internet source" automagically: I have to manually open Firestarter and re-run wizard every time.
How do I revert standard settings? I suppose I could copy iptables rules from fresh installation, where do I find configs then?
Answer: I found it.
Apparently, firestarter is installed on Ubuntu 12.04 either by default or as a dependency or recommendation to something I normally install. It was present on two different 12.04 machines but I don't remember installing it. Also never heard about it anywhere.
Firestarter only considers one of your network connections your internet gateway, and by default that's the wifi. So it sets up your linux firewall to block all incoming connections for wifi, but not ethernet, because it considers ethernet to be your local network.
The tricky part is that ufw and gufw, which seem to have replaced firestarter as Ubuntu's recommended firewall, have their own set of iptables rules, so they don't even notice firestarter is there and can't switch it off.
To get rid of the firestarter rules temporarily, launch firestarter and click the stop button.
To get rid of firestarter and its rules permanently, do:
sudo apt-get remove firestarter
You can now either leave the firewall as it is and possible disable samba when you're on public wifi, or you can set up a couple of rules of your own with ufw or gufw. I just left if off and plan to switch on gufw by hand if I go on public wifi.


What is the best way to implement Socket.io in android?

Question: I am finding best way to implement socketio in android
Answer: I implemented this client and everything will be working just fine.
Comment: My question is that can we create braodcast receiver so that it listen the emit done by sserver. If it is possbile then i will not have to create listener in SERVICE class
Comment: I think [this is](https://www.tutorialspoint.com/socket.io/socket.io_broadcasting.htm) what you're looking for.


Are exhaust fans inter-connected in a 3 stories condo?

Question: I am a smoker who lives on the first floor of a 100 years old 3 stories condo. During the winter, I smoke in my bathroom with the exhaust fan (on the ceiling) turned on to draw the smoke out. Each of the units has its own exhaust outlet on the exterior wall, so I guess the vent pipes should be independent of the other units.
However, I recently received complaints from the upstairs residents for cigarette smoke smell in their bathrooms, which are directly on top of mine. Is it possible the vent pipes are interconnected and it was the normal practice at that era (1910-1820)?
Comment: how would they know you were smoking to complain to you? Do you have laundry in your apt, or in a common area?
Answer: Many building like that were built without actual duct work but used the space between the joists, ceilings and floors. Running your fan would increase the pressure in that space and smoke would find it's way through any openings... like your neighbors vents. There is also the possibility that there is duct work but that it wasn't connected right when the exhaust fans were installed or replaced. You'll need to do some investigating to see if ducts are there to your bathroom fan and connected right. Also check the exhaust outlet for ducts being connected to it.
Comment: If the bathroom exhausts are lined up vertically on the outside wall, yours is switched on, theirs is switched off, and if there is any negative pressure in their apartments created by a kitchen exhaust or an unvented high efficiency water heater or even a window fan in a bedroom ... your smoke could be sucked into their bathrooms.
Comment: If the building was build in the 1910's, @r13, it could be balloon framed. That would allow smoke and other smells to travel all the way from the foundation to the rafters.
Comment: It could be traveling through holes or raceways for the plumbing pipes, vents, drains etc..  maybe the second floor people don't notice it or don't care.
Comment: @AloysiusDefenestrate Yes. I can smell myself if I don't smoke for a few days :)
Comment: I understand your answer, which is very true and my smoke can find its way to the second floor through the ceiling space, but the third floor? Which reported smell is limited to their bathroom only. This really puzzles me.
Comment: @jay613  Yes... and if their fans are off and his is on.... that would force smoke into their unit......  Exactly what happened to my brother.... he ended up just leaving his fan on all the time to keep smoke from entering...
Comment: More than any other type of room in a house, bathroom walls are extra porous because of pipes running full height between floors. So it isn't at all surprising that a bathroom two floors up would smell you. (Plus, with the general reduction in public smoking, I personally have become much more sensitive to the smell — I wouldn't be surprised if that was common.)
Answer: You're not supposed to build vents like that, but a lot of people build things they're not supposed to. Anything's possible. First thing I'd do is look on the outside of the building and try to find the vent outlet(s) - that'll give you some clues. If you don't see any vent outlets at all, that's also a clue - it could mean that it's vented into the walls, which is a big no-no.
Answer: It may not be related to the fan vents at all.  Even with the fan on, the smoke smell will disperse in the air faster than the fan will push it out.  And once it is outside, it can easily come back in (through their vent exhaust if it's right above yours).  When I walk to my mailbox, if my neighbor has a window open, I can smell the smoke smell 100 ft away.  When you search online regarding the smell of smoke entering homes, you will find people that complain they smell the smoke from a completely different house even with all windows closed.  I used to have issues with carbon monoxide coming back into the house on the 2nd floor through the roof soffits, so I'm sure smoke smell can easily come back in the same way.
Comment: Thanks. Your answer makes sense in certain times or houses with old windows without a good seal. A stronger smoke smells outdoor and affects locations farther away from the house should indicate the fan is powerful and works.


sdk can build my cmake project but recipe in bitbake can't

Question: I can build my project with the toolchain which yocto generates for me. but when I wrote a recipe for building and adding it in an image I get this error in do_compile:
<code>fatal error: stdio.h: NO such file or directory
</code>
why this happened and how to fix it?
Comment: You should add your recipe and the complete error log.
Answer: I found the problem. I was setting compiler Flags in my CMakeList.txt. After deleting all of them, the problem was fixed.


How to create a directory "dir" with subdirectories from subdir00 to subdir10 each of which contains subdirectoriess from subsubdir00 to subsubdir10?

Question: So, dir contains subirectories from subdir00 to subdir10 and each subdirectory contains subirectoriess from subsubdir00 to subsubdir10.
mkdir -p dir/subdir0{0..9}/subsubdir0{0..9}

works fine, but how to modify it to get correct two digits names? From 0 to 9 the numbers should be as 00 to 09.
Comment: Is that your homework, or has it some practical use ? We don't do homework for you,
Comment: thank you, it's not my homework) i'm just a dumbass practicing with bash. Could you please help to get result?
Comment: @emanyalpsid What are your OS details? Please [edit] your question to add the output of `uname -a` and `bash --version`.
Answer: You can use brace expansion as follows to do that with a single command:
mkdir -p dir/subdir{00..10}/subsubdir{00..10}

The -p flag is used to create parent directories if needed.
As stated in the Bash documentation I'm referencing above (or in man bash):

Supplied integers may be prefixed with '0' to force each term to have
the same width. When either x or y begins with a zero, the shell
attempts to force all generated terms to contain the same number of
digits, zero-padding where necessary.
Comment: IIRC the zero-padding feature was added in bash version 4.0 - it's *possible* the OP is using an older version (but if so, that's likely off-topic since no supported version of Ubuntu ships with such an old bash version)
Comment: thank you for answer. when doing it- dirs from 0 to 9 doesn't have a "0" before them. I mean instead of 00, 01- there are 0, 1 and so on.
Comment: @emanyalpsid Did you run the command as I provided it? It should work exactly as you want.
Comment: exactly as you provide. but there are no 01, 02, but 1, 2 .. How to change command to force it to make zero's for before 1-9?
Comment: @BeastOfCaerbannog I tested it out, and it workes till 10 is chosen. For example, `echo {00..5}` outputs `00 01 02 03 04 05` while `echo {0..10}` outputs `0 1 2 3 4 5 6 7 8 9 10`. I guess that's what @emanyalpsid has issues with. Still, you solution is perfectly valid, unless he needs a number higher than `09`
Comment: @steeldriver Thank you! That's probably the issue.
Comment: @steeldriver Indeed zero-padding was introduced in bash version 4.0: https://github.com/bminor/bash/blob/master/CHANGES#L4678-L4680


Solving trigonometric equation with both a dependent within a cos and outside

Question: I'm trying to solve the equation $0.8t+10\cdot \cos(\frac{t}{2})=0$
However i end up with something like this:
$$-6,25=\frac{(\cos^{-1}t)}{t}$$
How is something like this solved? I feel like I am missing a simple step or something.
Comment: i have found $$t\approx -.3000940041$$
Comment: You can set $y=t/2$ and then you will obtain $\frac{\cos y}{ y} = - 0.16$. https://www.wolframalpha.com/input/?i=cos+y+%2F+y+%3D+-0.16
Comment: Your second equation is not equivalent to your first.
Answer: Assuming that the second equation of yours is correct, you know that:
$$-6.25=\frac{(\cos^{-1}t)}{t}\implies$$
$$\implies-6.25 = \frac{\pi}{2x} + \frac{i\log(\sqrt{1-x^2}+ix)}{x}$$
By running the following Mathematica program:
<code>TrigToExp[-6.25 == ArcCos[x]/x]
</code>
We obtain the raw value:
$$x\approx-0.300094004058679$$
You probably made a mistake though, and therefore you can find the values from the original equation with number computational methods (like Newton's method of calculus)
Answer: There is no "closed form" solution.  There are five real solutions to the equation
$0.8 t + 10 \cos(t/2) = 0$, approximately
$$-12.49116333,\; -11.99716416,\; -2.705293407,\; 3.751175051,\; 8.029608133$$
They can be found using numerical methods, e.g. Newton's method.
You made an error in finding the second equation.
Comment: So you are saying the only way to find the solutions is by solving numerically? Are there a certain way this can be proven or something?
Comment: "Closed form" is not a precisely defined concept.  Even if you gave a precise definition of what functions are allowed, I doubt that it would be possible to prove.  All I can prove is that the solutions are transcendental numbers (by the Lindemann-Weierstrass theorem).
Comment: Every method that returns an explicit number is a "numerical method".  There are alternatives to Newton-type methods, e.g. a solution $t$ of $x t + \cos(t/2) = 0$ satisfies the differential equation $(x - \sin(t/2)/2) t' + t = 0$, which can be solved numerically or by series.


ERROR: (gcloud.app.deploy) Error Response: [13] An internal error occurred while creating a Google Cloud Storage bucket

Question: I was following this tutorial : link
This is the google cloud version i used :
<code>(venv) C:\Users\user\Desktop\python-docs-samples\appengine\standard_python3\django>gcloud --version
Google Cloud SDK 367.0.0
bq 2.0.72
core 2021.12.10
gsutil 5.5
</code>
During the deploy process I was getting the following error:
<code>(venv) C:\Users\user\Desktop\python-docs-samples\appengine\standard_python3\django>gcloud app deploy
Initializing App Engine resources...failed.
ERROR: (gcloud.app.deploy) Error Response: [13] An internal error occurred while creating a Google Cloud Storage bucket.
</code>
I've searched from various sources and they suggest running this:
<code>gcloud config set app/use_deprecated_preparation True
</code>
But when I run the error appears:
<code>(venv) C:\Users\user\Desktop\python-docs-samples\appengine\standard_python3\django>gcloud config set app/use_deprecated_preparation True
ERROR: (gcloud.config.set) Section [app] has no property [use_deprecated_preparation].
</code>
I running it in the project directory folder.
Can anyone help me?
Comment: To isolate the potential issue, could you attempt to perform this deployment from, ideally, the Cloud Shell? Otherwise, a different computer with a different environment could suffice
Comment: Have you been able to fix the problem?
Answer: Does you network have a proxy?
Maybe you can try the command without a proxy.
Comment: As per tutorial, I use cloud_sql_proxy.exe. I've tried turning it off and running gcloud app deploy again but still the same error appears


Does mysqli class in PHP protect 100% against sql injections?

Question: I've seen lots of articles and questions about mysqli, and all of them claim that it protects against sql injections. But is it fool proof, or is there still some way to get around it. I'm not interested in cross site scripting or phishing attacks, only sql injections.
What I should have said to begin with is that I am using prepared statements. That is what I meant with mysqli. If I use prepared statements without any string concatenation, then is it foolproof?
Answer:
But is it fool proof, or is there still some way to get around it.

No, you have to know what you're doing. If you use bound parameters (A feature that MySqli comes with), you are completely safe from injection type attacks from this attack vector. This doesn't prevent you - the programmer - from embedding strings directly, and thereby enabling injection attacks. You have to use the feature as intended.
Re: Edit

What I should have said to begin with is that I am using prepared statements. That is what I meant with mysqli. If I use prepared statements without any string concatenation, then is it foolproof?

Foolproof is still such a dangerous word. But you are safe from injection attacks for the variables that are bound through prepared statements. This is because bound parameters are transmitted separately from the SQL query. With the "traditional" embed-string approach, the database server needs to parse the input and there are lots of edge cases in that (Charsets etc.). When the data and the query are sent separate, there is no actual parsing going on (At least not parsing of the variable data).
Answer: It doesn't protect from sql injections any better than the old mysql module, just makes doing it easier for the developer, who can now use prepared statements instead of calling mysql_real_escape_string.


How to Install Grsync without internet?

Question: I want to install Grsync on Ubuntu server 12.04 without internet,
or to download the package from Windows.
Comment: Download the latest .tar.gz and compile it. http://sourceforge.net/projects/grsync/files/
Answer:
Run sudo apt-get install grsync. It will fail, but show you the required package dependencies missing on your system. On my box, it shows:
The following NEW packages will be installed:
grsync libgtk2.0-0
Go to http://packages.ubuntu.com/precise/grsync and download the missing dependencies.
Copy the downloaded *.deb files to /var/cache/apt/archives/.
Run sudo apt-get install grsync again. Now it should pick files from cache and won't require an internet connection to install grsync.

How to Install Grsync without internet?


sql - concatenate date and time into date field

Question: The date comes from a form and so does the time which is limited to 4 characters in 24 hour format. Trying to concatenate these values together and update a DATE field in the DB with both the date and time together... any ideas
I am getting weird outputs for the time... something other than what I input...
This captures a value from a textbox where someone can only insert a 24 HHMM time...
$form1 = $_SESSION['moviedate'];
$form2 = $_POST['screentime'];

$sql = oci_parse($con, "Update schemaA.tableA SET SCREEN=to_date(:dmovie||:stime, 'DD-MON-YY HH24MI') WHERE ID=5");

oci_bind_by_name($sql, ':dmovie', $form1);
oci_bind_by_name($sql, ':stime', $form2);

$obj = oci_execute($sql, OCI_DEFAULT);

Comment: 'Weird' isn't very helpful. Do you have an example of entry and result? Do you get an error? If not how are you querying to see what was set in the table? Having a space between the bind variables would be nice but not crucial. Does the date entry match the format model you're using? And why two-digit years?
Answer: I am not sure but try this one:
$sql = oci_parse($con, "Update schemaA.tableA SET SCREEN=to_date(:date, 'DD-MON-YY HH24MI') WHERE ID=5");
oci_bind_by_name($sql, ':date', $form1 . " " . $form2);

Are you sure that format of provided date is always DD-MON-YY (include proper language of month name)? Is the time always 4 digits?


Set a maximum depth of JSON serialization in .NET Web API

Question: Let's say I have these entitites with these relations: This is just a fictious example, and not my current entities.

Course
User
NewsPosts

Courses have many Users,
Users have many Courses
Courses has many NewsPosts,
NewsPosts has many Courses
Users has many NewsPosts,
NewsPosts has Many Users
I'm using Entity Framework code first with .NET Web API, which sends back entities in the form of JSON. When I try to Get a Course, it sends back a JSON result with the relations of the entites, which is fine, but I would wish to set a limit of how many levels it serializes so it does not serialize all the relations beyond the first or second level.
GET Course/ would be serialized to:
<code>   {
     "Users":[{
                "id":1,
                "newsPosts": [{
                                "id":1,
                                "message":"foo"
                             }]
             }],
   "newsPosts":[{
                 "id":2,
                 "message":"bar"
               }]

   }
</code>
What i would want is to serialize only 1 or maybe 2 levels, So that the result would be:
<code>   {
     "Users":[{
                "id":1,
                "newsPosts": []
             }],
   "newsPosts":[{
                 "id":2,
                 "message":"bar"
               }]

   }
</code>
I have added a:
<code>    json.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
</code>
This is to remove the referencelooping.
So in short: Is there any way of setting a maximum amount of nodes to serialize?
Comment: possible duplicate of [How to serialize or deserialize a JSON Object to a certain depth in C#?](http://stackoverflow.com/questions/10453127/how-to-serialize-or-deserialize-a-json-object-to-a-certain-depth-in-c)
Comment: A custom JsonWriter and a custom ContractResolver seems to be the way to go. Thanks for noticing the duplicate.
Comment: over engineering here. Prepare the data you want to send, before returning it. EF is not appropriate for this, what you need is an extra layer, like someone else suggested already, use some DTOs and return those.
Answer: The way I see it you have 2 options:

Write a custom serializer, or use an existing library if you can find one
Prepare the data you want the endpoints to send back before you attempt to serialise anything.

One of the best practices when it comes to APIs is to only send back the data which is needed because this affects the size of the data sent back.
Entity Framework works in a certain way by providing way too much and you want to limit that. A common way of solving this problem is to not have the API return Entity Framework entities. There are a number of reasons for that which can be researched separately.
So, one approach would be to start using DTOs to return data. This has a number of advantages:

You are in control of the data you send back and you don't need any custom serializer or yet another library.
You have control over the contents of the response, meaning sometimes you don't need all public properties in a class to be sent back, you need a subset and you can control that.
The API is not tightly coupled with Entity Framework and its entities anymore.

Disadvantages:

You now have another set of classes to deal with, however this complexity can be easily managed with something like AutoMapper, for example.
Answer: I recommend mapping your domain classe(es) to custom DTO objects using something like AutoMapper, and then passing those for serialization.
Comment: It is not a good practice to recommend something without asking a question. E.g. may be there json will be used for using in generic contexts: like state handling, caching, logging...
Answer: I'm not terribly familiar with Web API, but it seems like you'll want to make a custom MediaTypeFormatter that uses JavaScriptSerializer, which has a property to set a recursion limit.
MSDN - JavaScriptSerializer.RecursionLimit Property
Another option is to make a custom formatter that uses JSON.NET which has the same sort of options.
Comment: Yes. Still want to use JSON.NET though. Seems as though there are more features on json.NET than javascriptserializer. So yea, seems like i want to go for the other option! Found a comparison here: http://json.codeplex.com/
Comment: JavaScriptSerializer.RecursionLimit  doesn't work for it. JavaScriptSerializer will  throw an exception in case of limit was achieved.
Answer: Isn't this simply a question of how you construct the data to send from your get function ?
I mean the JSON serializer does its job by serializing all the data you give him, simply remove the data, or don't include it, and it won't get serialized.
If it's finer tuning you are looking for a custom JsonWriter is what you want, the link posted by Alex Filipovici give good details on what to do to achieve that.


How do I watch movies and shows on my laptop using Ubuntu TV?

Question: I compiled and in installed Ubuntu TV using ubuntu-tv/wiki site. When I run it, though, it can't play TV Shows. It says
unity-2d-shell: [WARNING] GStreamer; Unable to play -
    "file:///home/ubuntu/Videos/unity/local/epg/epg.mkv

I am assuming that I need an epg file. I have also tried running ~/ubuntu-tv/shell/dash/epgdata/refreshdata.py but with no luck.
Does Ubuntu TV need to be a "TV" to watch movies and shows? What's going on?
Comment: i havent installed it yet but i'm using XBMC and its awesome

here is a little video i made for my buddies to decide!

https://www.youtube.com/watch?v=q7Yl-V_PHcc
Answer: If you want to watch tv you'll need a compatible DVB-T tuner for your computer in order to capture video and read the electronic program guide (epg). http://www.mythtv.org/wiki/Video_capture_card
By the way there is a ppa for ubuntu tv here: http://www.webupd8.org/2012/01/how-to-install-ubuntu-tv-from-ppa.html