Google Maps Android api v2 and current location

Question: I'm trying to use the new google maps android api v2 and i'm developing an app for android 2.3.3 or higher.
It's a very simple app:
it takes the user current location (using gps or networks signal)
it gets from db a POI
using direction api, it drives the user to the POI.
My problem is get the user current location. thanks to this post  How to get the current location in Google Maps Android API v2? I learned that i can't update current position using new google api.
Another problem is that I can set my position using GoogleMap setMyLocationEnabled(boolean enabled) but I can't use getMyLocation() to know where user is.
I used this guide http://www.vogella.com/articles/AndroidLocationAPI/article.html#maps_mylocation to get my location, and i tried to integrate inside my Activity to draw user position.
here my code:
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="it.mappe"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="it.mappe.permission.MAPS_RECEIVE" />

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="16" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

         <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="MYGMAPSKEY" />
        <activity
            android:name="it.mappe.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

main Activity
package it.mappe;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;

import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements LocationListener {
    private GoogleMap map;
    private static final LatLng ROMA = new LatLng(42.093230818037,11.7971813678741);
    private LocationManager locationManager;
    private String provider;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

        LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean enabledGPS = service
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean enabledWiFi = service
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        // Check if enabled and if not send user to the GSP settings
        // Better solution would be to display a dialog and suggesting to
        // go to the settings
        if (!enabledGPS) {
            Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // Define the criteria how to select the locatioin provider -> use
        // default
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);

        // Initialize the location fields
        if (location != null) {
            Toast.makeText(this, "Selected Provider " + provider,
                    Toast.LENGTH_SHORT).show();
            onLocationChanged(location);
        } else {

            //do something
        }

    }

    /* Request updates at startup */
    @Override
    protected void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(provider, 400, 1, this);
    }

    /* Remove the locationlistener updates when Activity is paused */
    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }

    @Override
    public void onLocationChanged(Location location) {
        double lat =  location.getLatitude();
        double lng = location.getLongitude();
        Toast.makeText(this, "Location " + lat+","+lng,
                Toast.LENGTH_LONG).show();
        LatLng coordinate = new LatLng(lat, lng);
        Toast.makeText(this, "Location " + coordinate.latitude+","+coordinate.longitude,
                Toast.LENGTH_LONG).show();
        Marker startPerc = map.addMarker(new MarkerOptions()
        .position(coordinate)
        .title("Start")
        .snippet("Inizio del percorso")
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
    }

    @Override
    public void onProviderDisabled(String provider) {
        Toast.makeText(this, "Enabled new provider " + provider,
                Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onProviderEnabled(String provider) {
        Toast.makeText(this, "Disabled provider " + provider,
                Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

}

main layout
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.SupportMapFragment" />

It works but not so good, as you can see in the pictures eveytime there is a new location it adds a new Marker (ex Overlay I think... I never use old google maps api).

How can I show only one markers?
In addition on my map i need to display also POI's marker, so i think that it's not a good solution delate all marker and redraw it on the maps.
There is another best way to get user current location, updating it every moment displaying just one custom marker?!
Answer: You can call startPerc.remove(); to delete only this marker.
From here
Comment: Have you tried with this Criteria? `Criteria criteria = Criteria() { Accuracy = Accuracy.Fine };`
Comment: I'm trying it, I think i can add a private Marker currentLocation and set it to current user location, in this way i can delete it when i have a new location and add the new marker.
Comment: it works. thank you. Just a quickly question: are you able to explain me why locationMenager decide to get always network priveder instead of gps provide?
Comment: no, now i try it... but i think that another problem is that I decide the provider inside onCreate(..) method. now I'm reading also this http://developer.android.com/training/basics/location/currentlocation.html#TaskHandleLocationUpdates wich explain how to handle multiple sources of location updates
Answer: Why not just use startPerc.setPosition to move the marker instead of keep adding and removing...
Answer: set the position of the marker when you get another location by this method
marker. set position (location)

Answer: you should use googlemap.clear() before adding the marker because everytime when location changed it add new marker on map with oldest marker. so use googlemap.clear() before add the marker in location changed. it will remove oldest marker and add new marker.
googlemap is the instance of GoogleMap Class.
Answer: You could replace the marker with a new one:
if(userMarker!=null) userMarker.remove();
    userMarker = theMap.addMarker(new MarkerOptions()
    .position(lastLatLng)
    .title("You are here")
    .icon(BitmapDescriptorFactory.fromResource(R.drawable.your_loc_icon))
    .snippet("Your current location"));

Answer: Full shortcut for defining the Google Map android v2 in android......
XML File :
<fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

Menifest file :
<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<permission
    android:name="com.example.mapdemoapiv2.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

<uses-permission android:name="com.example.mapdemoapiv2.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.mapdemoapiv2.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".MapDetail" >
    </activity>

    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="Your Key" />

    <uses-library android:name="com.google.android.maps" />
</application>

Activity class :
public class MainActivity extends android.support.v4.app.FragmentActivity
{
   GoogleMap googleMap;
    MarkerOptions markerOptions;

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

    setUpMapIfNeeded();

    GetCurrentLocation();

    }

private void setUpMapIfNeeded() {
    if (googleMap == null) {

        Log.e("", "Into null map");
        googleMap = ((SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map)).getMap();

        googleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(
                MainActivity.this));

        if (googleMap != null) {
            Log.e("", "Into full map");
            googleMap.setMapType(googleMap.MAP_TYPE_NORMAL);
            googleMap.getUiSettings().setZoomControlsEnabled(false);
        }
    }
}

private void GetCurrentLocation() {

    double[] d = getlocation();
    Share.lat = d[0];
    Share.lng = d[1];

     googleMap
            .addMarker(new MarkerOptions()
                    .position(new LatLng(Share.lat, Share.lng))
                    .title("Current Location")
                    .icon(BitmapDescriptorFactory
                            .fromResource(R.drawable.dot_blue)));

             googleMap
                .animateCamera(CameraUpdateFactory.newLatLngZoom(
                        new LatLng(Share.lat, Share.lng), 5));
}

public double[] getlocation() {
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = lm.getProviders(true);

    Location l = null;
    for (int i = 0; i < providers.size(); i++) {
        l = lm.getLastKnownLocation(providers.get(i));
        if (l != null)
            break;
    }
    double[] gps = new double[2];

    if (l != null) {
        gps[0] = l.getLatitude();
        gps[1] = l.getLongitude();
    }
    return gps;
}

Answer: First of all in map api v2 use LocationClient to retreive your location, see: http://developer.android.com/training/location/retrieve-current.html
Iportant: to kick start API, call this in onStart of main Activity:
private void kickStardedLocationManager(){

 // Acquire a reference to the system Location Manager
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

 // Define a listener that responds to location updates
    android.location.LocationListener locationListener = new android.location.LocationListener() {
        public void onLocationChanged(Location location) {
          // Called when a new location is found by the network location provider.
            //MainActivity.this.makeUseOfNewLocation(location);
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {}

        public void onProviderEnabled(String provider) {}

        public void onProviderDisabled(String provider) {}
      };

      long l = 10;
      float f = 100;
   // Register the listener with the Location Manager to receive location updates
      locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); //LocationManager.GPS_PROVIDER
}


Rails 3.2+ AR: Complex attributes in separate model

Question: I currently have a model called Trip with some "from" and "to" attributes like this (simplified for the sake of the question):
class Trip < ActiveRecord::Base
  attr_accessible :from_street, :from_zip, :from_country, :to_street, :to_zip, :to_country
  ...
end

I would very much like to refactor this into something like this:
class Trip < ActiveRecord::Base
  has_one :from_location
  has_one :to_location
  ...
end

class Location < ActiveRecord::Base
  belongs_to :trip

  attr_accessible :street, :zip, :country
  ...
end

What I am trying to achieve is to create a model that should serve as a "complex attribute". But I am not quite sure, how and where I should place my associations. Is the above correct? Or should the belongs_to be in Trip instead of Location?
Answer: I would do something like this:
class Trip < ActiveRecord::Base
  belongs_to :from_location, class_name: Location.name, foreign_key: 'from_location_id'
  belongs_to :to_location, class_name: Location.name, foreign_key: 'to_location_id'
  ...
end

Comment: And no "has_one" association on Location?


Has this Windows application been successfully installed via Wine?

Question: I just installed Expresso via Wine Windows Program Loader. The installation seemed to be fine.
But when I click the program item from Applications -> Wine -> Programs -> Expresso -> Expresso, the cursor rotated a few seconds and then nothing happened.
Later I checked back on the Expresso website, where there is a paragraph describing the installation process:

You may be prompted to install the
  .NET Framework. If you are not taken
  there automatically, download and
  install the 2.0 or later version of
  the framework from the Microsoft web
  site. Restart the Expresso install
  file after installing the framework.

I was wondering if I have installed Expresso successfully? If not, how shall I do? Do I have to install .NET Framework, and how to?
I also would like to know if it worth to install .NET Framework? My intention to install Expresso is just to have a nice editor for using Regex.
Thanks and regards!
PS: My Wine version is 1.2.2-0ubuntu2~maverick2, and my OS is Ubuntu 10.10.
Comment: NOTE: I've installed this with wine and mono-runtime active, and after installing the .NET 2.0 framework using Winetricks, there is ONE glitch with the program: the menu bar (with menus such as File, Edit, etc) does not run correctly on my system (NOTE: Mono is DEFNINTELY NEEDED to run this correctly, even under Wine.)  There's another regexp thing referenced in this question if you want something that can run without Wine (and works EXCEPTIONALLY well on Linux): http://askubuntu.com/questions/31260/recommendation-for-regex-editor
Comment: @EvilPhoenix: Thanks! (1) By glitch, do you mean the problem has correct itself now? (2) Have you installed both Expresso and RegExr? How is Expresso compared with RegExr?
Comment: @Tim: RegExr is pretty nice, fits my needs perfectly.  Required me to install the `adobeair` package to make it run, but after installing, i was able to install RegExr and it works perfectly for my needs.  If you can give me say another 15 minutes to test out Expresso, I can give you my comparison in a second comment here.
Comment: @Tim: having an error matching the regex patterns with Expresso running under Mono, possibly because the program is so reliant on the .NET framework to function.

Here's two screenshots comparing exactly the same regex patterns.  Note that Expresso dissects the regex pattern and explains it a tiny bit, where as RegExr does not (however, RegExr has active validation and active matching, so that as you edit the regexp, it will actually change through sample text to show you what it matches upon.  Screenie 1: http://koloth.trekweb.org/Expresso.png  Screenie 2: http://koloth.trekweb.org/RegExr.png
Comment: (continuation of previous comment)  @Tim: Lemme make a note though.  I was UNABLE to get Expresso to validate or successfully test the regexp I provided to it, however RegExr succeeded in both validating the regex pattern, as well as identifying the specific patterns it matched on (and shows you the results in the sample text, as well as shows you the specific part of the regex pattern provided that picked up each part of the highlighted [aka "matched"] sample text when you hover over it with the mouse cursor.  I think you should use RegExr because it doesnt have the errors Expresso does.
Comment: @Tim: And by glitch, I mean a persistent error where the menu bar doesnt display correctly, although the dropdown menus from the menu bar still show (but you have absolutely no clue what the menus are nor where they specifically are located.
Comment: @EvilPhoenix: Thanks for the detailed input! Really appreciate that. I will reconsider whether to install Expresso.
Comment: @Tim: no problem.  I just hope the moderators don't throw me into the pit of oblivion for taking 4 comments to answer your initial response to my first comment :P
Answer: If Expresso is just a .Net application, you'd probably have more success running it with Mono .
You can install it with:
sudo apt-get install mono-runtime

Then browse to the application's main executable and run:
mono app.exe

...where app.exe is the executable for the application.
Comment: Thanks! I was wondering if I have to install `app` under mono first?
Comment: @Tim: Probably not. You'll likely need Wine to install the application.
Comment: Thanks! Suppose I have no no Wine and just Mono, do I have to install app under Mono before I can run app? Or Mono is depending on Wine and I have to install  Wine in order to install app?
Comment: @Tim: First of all, Wine and Mono are completely separate (for all practical purposes). You'll probably need Wine to install the app and Mono to run it.
Comment: FYI: I tried this on 10.04, and you will need Wine to install the .NET framework, and Mono alongside it in order to make the program work correctly, save for the issue I stated in my comment to the question itself rather than this answer.
Answer: You could also install the windows version of .NET runtime under Wine. This way, Mono is not required, and everything would run under Wine.
http://msdn.microsoft.com/en-us/netframework/aa569263
This links to .NET framework v4. Maybe this is overkill, and v3 (or even 2) would be enough for Expresso (and most applications)
Comment: I have not been successful getting *any* version of the .Net Framework to install in Wine.
Comment: No even using Winetricks?
Comment: Nope. Not even with `winetricks`.


opengl problem with QT

Question: I'm using QT with opengl to make a chart in order to use it in different simulated physical experiments, but I'm facing the following problem.
I can't see my chart line unless I minimized my form window and then maximized it, and I should do that all the time as long as my line chart is being drawn in order to get the full result!!
What can I do, this is urgent and I need this chart working properly without minimizing and maximizing.??
Answer: It looks like you aren't doing a repaint until minimize/maximize. I suggest using a timer to get the job done. Posting your code will help!!
Comment: you mean calling "updateGL()"?, sorry I can't post the code, it's like a huge project.
Comment: Create a test-case and post that :)
Comment: Are you using QGLWidget, inheriting from something, or using an embedded context?  Basically, what type of widget is doing the rendering and display?
Comment: Yep, I'm inheriting from QGLWidget.
Answer: That's right batbrat, the missing call is updateGL, I used the following timer and it all worked, thanks.
<code>QTimer *timer = new QTimer( this );
connect( timer, SIGNAL(timeout()), this, SLOT(updateGL()));
timer->start(6);
</code>
Comment: Thanks for making me notice that, I'm still new here :)

opengl problem with QT


Exploded list of integers still has object datatype

Question: I have written a code which finds whether any columns in my table is a list, if it is a list it should check whether the list contains integers and if so it should convert the datatype from an object to int.
I have managed to convert the values to int but when I check the data types for the columns it still shows the column as object.
Why is that? Is it because the column itself needs to be changed to an int not just the values?
Dataframe:

Current Code:
x = (docs.applymap(type) == list).all()
y = x.index[x].tolist()
for i in y:
    docs = docs.explode(i)
    if (docs[i].str.isdigit().all()) == True:
        docs[i].apply(lambda x: int(x))

print(docs.dtypes) #shows that the column is still an `object`

DataIds should be converted to an int because it has been exploded and is just integers now but the column still shows it as having an object datatype.
Comment: Please share  a sample of dataframe with expected output for better clarity.
Comment: you cant change the type of the column with the lists. If it contains lists it's an object.
Comment: If you want to check if it contains 1 integer, then it can be
Comment: i've updated my code, basically i'm performing an explode on the column which contains a list, but when it has been exploded it still shows the integers as an `object` datatype, so I need to change the datatype of the exploded list to integers if that's possible
Comment: There's a big difference between a column containing list of ints (which probably needs the Object type) and the column containing a one and only one int (which could take the int type).
Answer: So the issue with the explode() function is that because a list has a datatype of object even when it has been exploded, whether or not it was a list of integers, it will still carry the object datatype.
So if you have a list of integers and you want to explode that list then convert that column to int, use the following code:
docs = docs.explode(i)
if (docs[i].str.isnumeric().all()) == True:
      x = (docs[i].to_frame().columns)
      docs[x] = docs[x].astype(int)


Can't view bash history for SSH sessions

Question: When logging in as a user via ssh, then sudo su - to become root I can't see the history of commands run.
I've tried cat /root/.bash_history  running the "history" command, etc.  I only see the results of root's history.  Additionally, if I run the history command or cat /home/user/.bash_history  I will see the sudo su- command but nothing that happens after that.
We have multiple people logging in and then switching to root via sudo su -  via ssh, but there seems to be no log of what commands are run after this happens.
Comment: Once you do `sudo su` you are not you any more. You are root. So history you should do `sudo cat /root/.bash_history`.
Comment: Please [edit] your question to include the output (from the `sudo su -` shell) of commands `echo "$-"` and `shopt histappend`
Comment: Yes, I did a cat on root and user .bash_history when I cat the root .bash_history, I see commands that I ran explicitly logged in as root when I was setting up the machine, but not the stuff I'm doing as root in the SSH sessions.
Answer: As @user68186 mentioned, when you change the logged-in user the .bash_history file changes with it, you need to search in the home directory of the logged-in user. In this case, it is /root
Comment: I looked at root's .bash_history under /root/.bash_history  and the commands aren't appending to the history file.


Is it possible to reuse a copper pipe's compression fitting?

Question: I removed what I didn't realize was a compression fitting on a copper pipe for my kitchen cold water supply.  Is it possible to reuse the compression fitting or do I need to buy a new one to replace it?
It looks like it's some kind of plastic.  It took a tremendous amount of force to loosen, and a fairly cursory attempt at re-tightening resulted in a leak.  Also, I assume I should wrap everything in teflon tape when replacing the connectors?
Comment: If it was me, I'd cut the pipe and install a T to run a proper valve for the blue line (ice maker?). Those puncture valves are prone to clogging and leaking, so you may as well fix it right while you're down there. Then after the T, install a new compression fitting for the sink. As others mention, the ferrule is deformed by the nut to make a water tight seal and won't properly seal if it becomes too damaged.
Comment: Teflon tape will be worse than useless here. Clean well without scratching. If you have an urge to apply something, somewhere, put a **little** bit of pipe dope (teflon pipe dope if it makes you happy) on the male threads - no effect whatever on the seal, but it will help the next time someone needs to unthread the thing (like anti-sieze, but safe for use around drinking water, which anti-seize is not.)
Comment: @BMitch it's to a basement RO filter, and yes, that's what I ended up doing after writing the post.  It didn't need to be cut; I just disconnected the other end of the copper line that was attached to the cold water shutoff valve.  I have no idea why my Dad presumably installed the copper line rather than pick up a tee when he hooked this up for me years ago.  I've experienced problems with those valves in my basement humidifier connection.
Answer: If it hasn't been tightened many times, it should be okay to reuse.
Clean off the mating faces thoroughly and don't use tape, putty, or anything else.  And don't be gentle tightening:  The seal is formed by forcing the surfaces together and "bending" them to mate.
Even with threaded steel pipes, it can take a day or two for the tightened fittings to form a good seal and they can drip at first.  The essential observation is whether the drip rate slows hour by hour—if it does, it is probably okay and going to seal.
If it doesn't drip more slowly, try tightening a little more with water pressure applied until two consecutive small turns (1/8 turn) doesn't immediately decrease the drip rate.
Comment: A compression fitting is designed to make a tight seal in the absence of any tape/dope/putty. Your more general question about when these are appropriate would be a good subject for another diy.sx question
Comment: I don't understand when tape is appropriate vs. dope, or nothing at all.  Could you clarify?
Comment: @mac just did, thanks for the suggestion.  http://diy.stackexchange.com/q/36613/9750
Answer: Had super short copper stubs and no shut off valves under bathroom sink. To add the compression shut off valves I cleaned the ferrule ring and wrapped it several times with Teflon tape. I tightened very tight and that worked for me - no leaks. Just passing it on. Not an expert or plumber so very grateful for these posts. Good luck all~~~
Comment: Hello, and welcome to Home Improvement. Thanks for the answer; keep 'em coming. And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know the details of contributing here.
Answer: I would be cautious reusing this. Reason being if the surface has a slight indentation from the previous seat from the prior install, and the shape of that end is kind of half spherical, which allows the mating surfaces to change locations depending on the angle to pipe approaches its counterpart.
If the surface is not marred from the prior install though, it is safe to use. Perhaps even a slight mar may be reformed when tightened, worth a shot to me if that is the case.
Do clean it and inspect it first, apply pipe dope if you choose, not teflon tape
Comment: In a nut shell, tape for threads only, dope for mating surfaces, flat, smooth or rounded as yours. It is mainly insurance in my opinion, and I use it too, but the mating surfaces should make a tight fit on their own. I have had a many a leak before using dope, now the leaks are non-existent. Then again, maybe I just got better at it, finally....
Comment: I don't understand when tape is appropriate vs. dope, or nothing at all.  Could you clarify?
Comment: The only place tape is to be used is on threads, to be exact, tapered threads, the kind that are on pipe nipple, male threaded ends of valves. If you look at the threaded end you can see the pipe is smaller at the end than farther down the length. Pipe dope can be used on these threads too. Pipe dope, otherwise can be used on the various types of compression fittings, the type you show here, the type that use a ferrule too. When using metal pipe the type of pipe dope is not that critical, but if using plastic, be careful, there is pipe dope NOT for plastic.
Answer: I'm going to directly contradict the other answers.  As stated in "See Jane Drill episode on "When to Use PFTE Tape, Pipe Dope or Neither"  (see 6:06 onward), warping your ferrule with some plumbers tape is the preffered way to reuse a ferrule you can't remove.
As others have stated, the ferrule is usually scored during the initial fitting and that scoring will likely make it leak during reuse, the teflon tape workes by filling the fills the scored area of the ferrule.
That said, the preferred thing do to is remove the ferrule if you can.  If I were in your situation, I'd cut and replace with a 'push fit' hose + fitting combo (if your valve needs to be replaced your hose should be too, so you might as well buy them as a combo) as they are easy to remove later.


c++ floating point problems

Question: I'm new to C++ and programming in general . I'm trying out small programs just to get my hand dirty . Below is a program I created for calculating the volume of a cone.
Problem : No matter what I do the output is always an integer . I want to get it to two decimal points accuracy . I've tried changing the variables to double and long double to get higher precision and nothing works.
How can I fix this? And why is this happening ? (In detail if possible) I've even asked few junior lecturers at UNi so far no one gave me a proper answer.
int main (){
    float radius,length,volume ;
    const float PI =22/7.0f;
    cin >> radius >> length;
    volume =1/3.0f *radius*radius*length;
    cout << "Volume is " << volume <<endl;
    return 0;
}

I'm using g++ on Fedora
EDIT : I Tried this earlyer with inputs like 50 60/70 50 /120 40 which gives integers. Smaller inputs like 3 4 gives decimals.
EDIT : setprecision() works. thanks for everyone for sent this
Comment: That code prints lots of decimals. (And that approximation for PI is pretty weak.)
Comment: OMG, IT'S TRUE O.O

http://thedailywtf.com/Articles/The-Object-Test,-a-New-PI,-and-More-SHEEIT.aspx
Answer: You may need to use output manipulators:
http://www.cplusplus.com/reference/iostream/manipulators/setprecision/
so that it looks like:
cout << "Volume is " << setprecision(10) << volume << endl;

Answer: I don't see anything wrong with your code, and I cannot reproduce the behaviour you're reporting.
Having said that, if I were you I'd experiment with setprecision():
cout << "Volume is " << setprecision(8) << volume <<endl;

Answer: The program as posted above (adding the missing #include <iostream> and using namespace std;) produces several digits after the decimal point for me. If you want it to produce exactly two decimal after the decimal point you need to use something like this:
std::cout << std::fixed << std::setprecision(2);

somewhere prior to your output (the latter manipulator is declared in <iomanip>). The default precision is to use 6 digits and decide how to best distribute them (this may mean the output goes to scientific notation if the values become too big or too small).
BTW, don't use std::endl unless you really want to flush your output stream. I found several cases where the inappropriate use of std::endl turned into a major performance issue.

c++ floating point problems


How could I generate a list of 's from an array?

Question: How do I generate a list of
's from an array with HTML and using JavaScript?
Answer: This?
var i, p;

for(i = 0; i < array.length; i++) {
   p = document.createElement('p');
   p.innerHTML = array[i];
   document.body.appendChild(p);
}

Answer: If you want to enclose the html content into paragraph maybe you can do it with an oneliner:
var resulting_html = '
' + content_array.join('

') + '
';

assuming that the array containing the html is called content_array.
You will have the html ready to incorporate it into the target element.


Uniform convergence of $\frac{1}{x^3}\cos\left(\frac{x}{n}\right)$

Question: Determine if $\frac{1}{x^3}\cos\left(\frac{x}{n}\right)$ uniformly converges on $E_1$ and $E_2$, where $E_1 = (0, 1)$ and $E_2 = (1, +\infty)$.
The pointwise convergence is trivial, since $\lim \limits_{n \to \infty} \frac{1}{x^3}\cos(\frac{x}{n}) = \frac{1}{x^3}$ for both $E_1$ and $E_2$.
I could also prove that it does not uniformly converge on $E_1$ by picking $x_n = \frac{1}{n^2}$ and plugging it into the original function.
However, I don't know how to prove uniform convergence on $E_2$, because I don't know how to evaluate $\sup f_n(x)$.
What are the methods to prove or disprove uniform convergence on $E_2$?
Answer: As regards $E_2=(1, +\infty)$ , note that by letting $t=x/n$,
$$\sup_{x\in(1, +\infty)} \left|\frac{1}{x^3}-\frac{1}{x^3}\cos\left(\frac{x}{n}\right)\right|=\sup_{t\in(1/n, +\infty)} \frac{1-\cos(t)}{n^3t^3}\leq \frac{1}{2n^3}\sup_{t\in(1/n, +\infty)} \frac{1}{t}=\frac{n}{2n^3}=\frac{1}{2n^2}$$
where we used the fact that for $\frac{1-\cos(t)}{t^2}\leq \frac{1}{2}$ for any $t>0$ (it suffices to show that this function is bounded).
Comment: See also the last property here: https://en.wikipedia.org/wiki/Uniform_continuity#Properties
Comment: @Welez Sorry for the mess, but initially I misread your question.


ExecuteReader requires an open and available Connection. The connection's current state is closed

Question: Ok, I asked about this very error earlier this week and had some very helpful answers and without doubt things have drastically improved since I started following the suggestions.
However, now I am using the 'correct', best practice method to access the database I still get this error on some functions and I cannot get it to disappear for that block.  Here is my code:
    Public Shared Function doesBasketExist(ByVal baskethash As String) As Boolean
    Dim _r As Boolean
    Using db As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("pitstopConnectionString").ConnectionString)
        Using cmd As New SqlCommand("doGetBasketByHash", db)
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Parameters.AddWithValue("@baskethash", baskethash)
            Using dr As SqlDataReader = cmd.ExecuteReader()
                If dr.HasRows() = True Then
                    _r = True
                Else
                    _r = False
                End If
                dr.Close()
            End Using
        End Using
    End Using
    Return _r
End Function

Now no matter what I do I get: ExecuteReader requires an open and available Connection. The connection's current state is closed. on this connection.  I do have functions with objects called the same thing within this class (cmd, dr etc.) but Using closes up after itself doesn't it?
Suggestions welcome :)
Answer: I think you have forgotten to open the connection.
Open it before this line:
cmd.Parameters.AddWithValue("@baskethash", baskethash)

Using -
db.Open()

Answer: You actually forgot to Open connection:
        db.Open()
        Using dr As SqlDataReader = cmd.ExecuteReader()

Answer: One reason for this would be that your connection could not be opening at all. What ever exception that is coming at the "SqlConnection.Open" statement is being suppressed. If the problem is not in your application it could be that server is unable to grant you a connection. Could be because of a connection leak in your app or in some other database hosted on the same server.


Wierd ambiguious call on overloaded function with a function parameter

Question: So say I've got a method which I've overloaded. One takes a function returning uints, one takes a function returning ints.
static void test1(Func<uint> f)
{
    //things
}
static void test1(Func<int> f)
{
    // also things
}

Now I try to call it like this:
test1(Random.FunctionThatReturnsUints);

but I get an ambiguous call error at compile time:
   Error    4   The call is ambiguous between the following methods or
    properties: 'RNG_Comparison.Run.test1(System.Func<int>)' and 'RNG_Comparison.Run.test1
(System.Func<uint>)'

What's up with that? Isn't the whole point of overloading a function for it to understand implicitly which one you mean based on the types? I mean, if I'd called it with a func returning BigInt or something, maybe I could see the compiler's confusion, but this one seems pretty cut and dried.
Does anyone know why I'm getting that error?
Comment: Try `test1(new Func(Random.FunctionThatReturnsUints))` and see if that results in a different compiler error.
Comment: See answer from Eric Lippert on similar topic http://stackoverflow.com/a/2058854/961113
Comment: @cdhowie, that would solve the compiler error.
Comment: overloading seems ok, please post more code.
Answer: Eric Lippert (a member of the C# team) called this sort of thing "one of the hairiest parts of the spec", so to fully answer "why does the compiler do this?" would be a hard question. Suffice to say, it's because the C# specification allows that to happen. This is an easy workaround:
test1(new Func<uint>(Random.FunctionThatReturnsUints));

Comment: Thanks for the shout-out; I note that I am a *former* member of the C# language design and compiler development teams.
Answer: The important thing in the post by Eric Lippert cited by Tim is:

The principle here is that determining method group convertibility requires selecting a method from a method group using overload resolution, and overload resolution does not consider return types.

In your code there's method group conversion in action and that causes the problem.
The proposed solution eliminates the problem.
Comment: Yeah I read through that, interesting stuff. I get why it is the way it is. Thanks


making word cloud in flutter

Question: I want to create a word cloud in flutter.
Is there a way to make it?
For instance, if I have a list
List words = ['banana','banana','banana','banana','purple','orange','apple','apple','green']

I want elements repeated several times to be shown in a big font, and elements repeated a few times to be shown in a small font.
Comment: search for `word cloud "api"` - the first few hits give you an online generator with HTTP interface, and a JavaScript implementation that you could port to Dart / dart:ui
Comment: Just compute the fontSize according to repeated times: Text(word, style: TextStyle(fontSize: calculateFontSizeAccordingToCount(countof(word))))
Answer: I needed to create a word cloud in Flutter, so I created this package: https://github.com/letsar/flutter_scatter
You can create a word cloud like this:
class WordCloudExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    List<Widget> widgets = <Widget>[];
    for (var i = 0; i < kFlutterHashtags.length; i++) {
      widgets.add(ScatterItem(kFlutterHashtags[i], i));
    }

    final screenSize = MediaQuery.of(context).size;
    final ratio = screenSize.width / screenSize.height;

    return Center(
      child: FittedBox(
        child: Scatter(
          fillGaps: true,
          delegate: ArchimedeanSpiralScatterDelegate(ratio: ratio),
          children: widgets,
        ),
      ),
    );
  }
}

class ScatterItem extends StatelessWidget {
  ScatterItem(this.hashtag, this.index);
  final FlutterHashtag hashtag;
  final int index;

  @override
  Widget build(BuildContext context) {
    final TextStyle style = Theme.of(context).textTheme.body1.copyWith(
          fontSize: hashtag.size.toDouble(),
          color: hashtag.color,
        );
    return RotatedBox(
      quarterTurns: hashtag.rotated ? 1 : 0,
      child: Text(
        hashtag.hashtag,
        style: style,
      ),
    );
  }
}

And you will end up with the following layout:

making word cloud in flutter


Formula for $q$-expansion of weight 2 modular forms

Question: Is there a general formula for finding the $q$-expansion of weight 2 modular forms?
Comment: What have you tried so far? Maybe it would be helpful if you showed some of your working?
Comment: Did you spot anything?
Answer: The problem is too deep and important to have a simple, tidy solution! About the best one can get is the approach described in Loic Merel's article "Universal Fourier expansions of modular forms".
EDIT: if you want tables for a specific weight and level, the LMFDB (L-functions and Modular Forms Database) is the place to go.
Comment: Thanks. If I was looking for those of a specific level (say 11) would there be a place to look e.g., some sort of table/reference?


How do I change the width of dashboard in GNOME?

Question: Trying to make few customization to Ubuntu GNOME and I am already surprised to see the flexibility and option to customize Ubuntu.
I have already installed Dash to Dock and Tweak Tool, but I could not find an option to increase the width of the Dashboard that contains all the application.
I might be looking for the wrong keyword as I could not find any solution on Google and Ask Ubuntu.
Screenshot of the Dashboard:
Answer: You may try the "More columns in applications view" GNOME shell extension. It lets you

Set the number of columns in the "applications" view (by default, the maximum is only 6)

and thus you would be able to use those empty spaces.
Refer to this to learn how to install and manage GNOME shell extensions: How do I install and manage GNOME Shell extensions?


Passing Data between View Controllers in Swift

Question: I am trying to convert an app from Objective-C to Swift but I can't find how to pass data between views using Swift.  My Objective-C code is
UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
AnsViewController *ansViewController;
ansViewController = [storyBoard instantiateViewControllerWithIdentifier:@"ansView"];
ansViewController.num = theNum;
[self presentViewController:ansViewController animated:YES completion:nil];

What that is doing is it basically takes the variable, theNum, and passes it to the variable, num, on a different view controller.  I know this may be an easy question but I am getting pretty confused with Swift so if someone could explain how they changed it to Swift that would be greatly appreciated!
Thanks
Comment: Its exactly the same in Swift, what exactly are you unsure about?
Comment: @lagoon Would you mind accepting one of the answers?
Comment: Just the Swift syntax in general. I know that I wouldn't be able to use the square brackets in Swift but in the eBook, it uses a . or parentheses at certain times and I'm not sure which one to use here
Comment: The dot and parentheses syntaxes are very general programming syntaxes found in almost every language. To be **very** brief, `()` is used to call a function, `.` accesses members/properties/functions of a class/struct/etc.
Comment: Thanks, I have most of it figured out now except for the ansViewController.num = theNum part because it says UIViewController does not have a member named theNum
Comment: [Here is a basic example](http://stackoverflow.com/a/31934101/3681880)
Answer: Let's assumed we stand at the firstView go to the DetailView and want passing data from firstView to Detailview. To do that with storyboard, at the firstView we will have a method:
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if (segue.identifier == "segueTest") {
      //Checking identifier is crucial as there might be multiple
      // segues attached to same view
      var detailVC = segue!.destinationViewController as DetailViewController;
      detailVC.toPass = textField.text
    }
}

and then into the class of DetailView we declared a variable:
var toPass: String!

then you can use the variable toPass (of course you can change the type of the variable as you want, in this EX I just demo for string type).
Comment: This looks like what I am needing. I want to pass an array of variables from VC 1 to VC 2. Then, in VC 2, the user will enter information into more fields. That information will be appended to the array. When done, the array is sent to the cloud.

I copied your code into my project and replaced my var names. I am getting an error, 'DispScreenOne does not have a member named 'toPass'.

`{if (segue.identifier == "goToDispenseScreenTwo") {
var DispScreenOne = segue.destinationViewController as! DispenseScreenTwoViewController;
DispScreenOne.toPass = enteredDataArray.text
}`
Comment: @Greg: Please make sure at **DispenseScreenTwoViewController**, you have a variable name **toPass**
Comment: best solution if you need something quick and easy! Thanks
Comment: @Lee: I have a global var toPass. When I try to set a value to toPass in any of my view controllers, it recognizes the var.  What am I missing?
Comment: You have a global variable toPass into your project doesn't mean **DispenseScreenTwoViewController** have this variable. So that you will get the error: **'DispScreenOne does not have a member named 'toPass'**.
Comment: **DispScreenOne.toPass** mean that: at **DispenseScreenTwoViewController** you must have a variable name **toPass**
Comment: it is not working unable to get value on second controller which is passed by first contrioller.
Answer: class AnsViewController: UIViewController {
   var theNum: Int

    override func viewDidLoad() {
        super.viewDidLoad()

        println(theNum)
    }

}

override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    let viewController = self.storyboard.instantiateViewControllerWithIdentifier("ansView") as AnsViewController
    viewController.num = theNum
    self.presentViewController(viewController, animated: true, completion: nil)
}

Comment: where to give view controller identifier
Comment: @zainullah In the Storyboard ID.
Answer: To pass string or any data from one controller to another in swift.
Follows below steps:
1) Create property in child controller as var abc:string!
2) Create object of childcontroller
let storyboard:UIStoryboard()
let viewController: childcontroller = storyboard.instantiateViewControllerWithIdentifier("childcontroller") as! childcontroller
viewController.abc = "hello";
self.navigationController.pushviewController(Controller:viewController animated:true CompletionHandler:nil)

Answer: Using tableview,

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
        {
            let ClubProfileView = self.storyboard?.instantiateViewController(withIdentifier: "CBClubProfileViewController") as! CBClubProfileViewController

            let TempCulubDic:NSDictionary =
                ((ClubsListbyDateDic.object(forKey:((ClubsListbyDateDic.allKeys as! [String]).sorted(by: <)as NSArray).object(at: indexPath.section) as! String) as! NSArray).object(at: indexPath.row))as! NSDictionary

            let ClubId:String=(TempCulubDic.value(forKey: "club_id") as? String)!

            let CheckIndate:String=(TempCulubDic.value(forKey: "chekin_date") as? String)!

            ClubProfileView.ClubID=ClubId

            ClubProfileView.CheckInDate = CheckIndate

            // self.tabBarController?.tabBar.isHidden=true

            ClubProfileView.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(ClubProfileView, animated: true)
            }

Answer:      @IBAction func nextbtnpreesd(_ sender: Any) {

            let mystring = "2"
            performSegue(withIdentifier: "MusicVC", sender: mystring)
        }

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if let destination = segue.destination as? MusicVC{

            if let song = sender as? String{
                destination.strlablevalie = song
            }
        }
    }

//in MusicVC create string like:
 var strlablevalie:String!

Comment: it is not working unable to get value on second controller which is passed by first contrioller. – Chandni 2 mins ago   edit
Answer: To pass string or any data from one controller to another in swift.
Follows below steps:
1) Create variable of type which you want like (String,Int)
var test : String!
2) Create object of childcontroller
 let vc = self.storyboard?.instantiateViewController(withIdentifier: "Here identifier of your VC") as! (Here Name Of Your Controller)
 vc.test = "Hello" (Or any data which you want to pass)
 self.navigationController?.pushViewController(VC, animated: true)

That should solve your problem
Answer: Note: if we are using storyboard
Step 1: Master controller :
    // table row which row was selected
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

        println("You selected cell #\(indexPath.row)!")

        nextScreenRow = indexPath.row

        // get to the next screen
        self.performSegueWithIdentifier("dashboard_static_screen_segue", sender: self)

    }

and then;
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {

        if (segue.identifier == "dashboard_static_screen_segue") {
            var detailController = segue.destinationViewController as StaticScreens;
            detailController.screenNumber = nextScreenRow
        }

    }// end prepareForSegue

step 2: Detail controller (StaticScreen)
// set variable into your detail controller

var screenNumber: NSInteger?

println("selected row \(screenNumber!)")


Rose::DB::Object::Manager and HTML Template

Question: I am using Rose::DB::Object::Manager (get/iterate methods) to source data from a database and HTML::Template for reporting.
The HTML report requires a TMPL_LOOP to display entries in a database.
My question is how do I create an array reference with the get/iterate methods of RDBOM and pass it to HTML::Template. Thank You.
Answer: Rose::DB::Object::Manager's get/iterate methods will give you objects, but HTML::Template wants plain Perl data structures and values.  To bridge the gap, use one or more of the methods in the Rose::DB::Object::Helpers module.  The as_tree or column_value_pairs methods are probably your best bets.


Is this Ubuntu One DBus signal connection code correct?

Question: This is my first time using DBus so I'm not entirely sure if I'm going about this the right way. I'm attempting to connect the the Ubuntu One DBus service and obtain login credentials for my app, however the slots I've connected to the DBus return signals detailed here never seem to be firing, despite a positive result being returned during the connection.
Before I start looking for errors in the details relating to this specific service, could someone please tell me if this code would even work in the first place, or if I'm done something wrong here?
int main()
{
    UbuntuOneDBus *u1Dbus = new UbuntuOneDBus;
    u1Dbus->init()
}

class UbuntuOneDBus : public QObject
{
  Q_OBJECT

  QString busName;
  QString path;
  QString interface;
  QString method;
  QString signature;

  void connectReturnSignals();

private slots:
  void credentialsFound();
  void credentialsNotFound();
  void credentialsError();

public:
  UbuntuOneDBus();

  void init();
};

UbuntuOneDBus::UbuntuOneDBus()
{
  busName = "com.ubuntuone.Credentials";
  path = "/credentials";
  interface = "com.ubuntuone.CredentialsManagement";
  method = "register";
  signature = "a{ss}";

  connectReturnSignals();
}

void UbuntuOneDBus::init()
{
  QDBusMessage message = QDBusMessage::createMethodCall( busName, path, interface, method );
  QDBusConnection::sessionBus().send( message );
}

void UbuntuOneDBus::connectReturnSignals()
{
  QDBusConnection::sessionBus().connect( busName, path, interface, "CredentialsFound", this, SLOT( credentialsFound() ) );
  QDBusConnection::sessionBus().connect( busName, path, interface, "CredentialsNotFound", this, SLOT( credentialsNotFound() ) );
  QDBusConnection::sessionBus().connect( busName, path, interface, "CredentialsError", this, SLOT( credentialsError() ) );
}

void UbuntuOneDBus::credentialsFound()
{
  qDebug() << "Credentials found";
}

void UbuntuOneDBus::credentialsNotFound()
{
  std::cout << "Credentials not found" << std::endl;
}

void UbuntuOneDBus::credentialsError()
{
  std::cout << "Credentials error" << std::endl;
}

Comment: Have you declare this methods:
- credentialsFound
- credentialsNotFound As slots in the .h file?
If that is the case, could you provide some repository or something to obtain the code and debug it if necessary?
Comment: Thanks for your reply, I indeed declared them as slots in the header file. I have updated the code snippet to include the entire class, both declaration and definition, as well as the main() function from which it's invoked.
Answer: The signature argument to the connect method looks wrong.
Funny as it looks, it should be just "a{ss}".
That already means "array of dictionary items with string as key and string as value", so the added part "(Dict of {String, String})" may happen to be interpreted the wrong way. Similarly, the signature for the CredentialsNotFound D-Bus signal should not be "(nothing)", it should be just an empty string like "".
To familiarize yourself with the other data types that D-Bus offers try a tutorial like this:
http://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html#data-types
Comment: Thanks a lot for your help, but that doesn't seem to have been the issue. I actually started using the `connect()` function without the signature parameter but that wasn't working either.
Answer: I'm not entirely sure how slots work in Qt exactly, but my understanding is you still need to define the function to have the correct signature to match the signature of the DBus signals. So in the case of Credentials Found, it needs to take a hash/map of string keys and values, assuming that QtDBus converts the "a{ss}" signature into the correct data type automatically. I suspect such slot functions also need to accept any standard arguments provided by QtDBus itself.
I also found this quick tutorial from Nokia, which might be helpful: http://www.developer.nokia.com/Community/Wiki/QtDbus_quick_tutorial


VBOs Using Interleaved Vertices in C#

Question: I am trying to use VBOs to draw my model in in C# using OpenTK. In my online research I read in many places that it is good practice to make the size of the interleaved data structure an exact multiple of 32 bytes, so I coded up the following:
<code>[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Byte4
{

    public byte R, G, B, A;

    public Byte4(byte[] input)
    {
        R = input[0];
        G = input[1];
        B = input[2];
        A = input[3];
    }

    public uint ToUInt32()
    {
        byte[] temp = new byte[] { this.R, this.G, this.B, this.A };
        return BitConverter.ToUInt32(temp, 0);
    }
}

[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct VertexInterleaved
{
    // data section is exactly 36 bytes long??? - need padding to get multiple of 32?
    public Vector3 vertex; // Vertex
    public Vector3 normal; // Normal Vector
    public Vector2 textureCoord; // First Texture Coordinates
    public Byte4 rgbaColor; // RGBA value of this vertex
    //public byte[] padding;

    public static int VertexStride()
    {
        // if I'm using the padding I have to add the appropriate size to this...
        return (8 * sizeof(float) + 4 * sizeof(byte));
    }
}

public class VertexBufferObject
{
    private uint[] _VBOid;

    private int _vertexStride;
    private int _totalIndices;
    private int _totalVertices;

    public VertexBufferObject ()
    {
        _VBOid = new uint[2];
        GL.GenBuffers(2, _VBOid);
    }

    public bool DeleteVBO()
    {
        GL.DeleteBuffers(2, _VBOid);
    }

    private void BindBuffers()
    {
        GL.BindBuffer(BufferTarget.ArrayBuffer, _VBOid[0]);
        GL.BindBuffer(BufferTarget.ElementArrayBuffer, _VBOid[1]);
    }

    private void ReleaseBuffers()
    {
        GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
        GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
    }

    public void BufferMeshData(Mesh3DCollection mesh3Ds)
    {
        _vertexStride = VertexInterleaved.VertexStride();

        _totalIndices = mesh3Ds.TotalIndices();
        _totalVertices = mesh3Ds.TotalVertices();

        VertexInterleaved[] vboVertices = new VertexInterleaved[_totalVertices];
        uint[] vboIndices = new uint[_totalIndices];

        int vertexCounter = 0;
        int indexCounter = 0;

        foreach (Mesh3D m in mesh3Ds)
        {
            foreach (VertexInterleaved v in m.vertices)
            {
                vboVertices[vertexCounter] = v;
                vertexCounter++;
            }

            foreach (uint i in m.indices)
            {
                vboIndices[indexCounter] = i;
                indexCounter++;
            }
        }

        BindBuffers();

        GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr) (_totalIndices * sizeof(uint)), vboIndices, BufferUsageHint.StaticDraw);
        GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(_totalVertices * _vertexStride), vboVertices, BufferUsageHint.StaticDraw);

        ReleaseBuffers();
    }

    public void RenderVBO()
    {
        GL.EnableClientState(ArrayCap.VertexArray);
        GL.EnableClientState(ArrayCap.NormalArray);
        GL.EnableClientState(ArrayCap.ColorArray);

        BindBuffers();

        GL.VertexPointer(3, VertexPointerType.Float, _vertexStride, (IntPtr) (0));
        GL.NormalPointer(NormalPointerType.Float, _vertexStride, (IntPtr) (3 * sizeof(float)));
        GL.TexCoordPointer(2, TexCoordPointerType.Float, _vertexStride, (IntPtr) (6 * sizeof(float)));
        GL.ColorPointer(4, ColorPointerType.Byte, _vertexStride, (IntPtr) (8 * sizeof(float)));

        GL.DrawElements(BeginMode.Quads, numIndices, DrawElementsType.UnsignedInt, startLocation);

        ReleaseBuffers();

        GL.DisableClientState(ArrayCap.VertexArray);
        GL.DisableClientState(ArrayCap.NormalArray);
        GL.DisableClientState(ArrayCap.ColorArray);
    {

}
</code>
Specific Questions:
1.) Should my interleaved vertex data structure be a struct or a class? Does this make a difference as far as the VBO and/or memory footprint is concerned? (I decided to use a struct, even though it felt wrong, because the vertices aren't going to be altered once they're in memory.)
2.) Does this data structure really need to be a multiple of 32 bytes in size? (i.e., do I need a "dummy" padding member to force a correct size? All of the examples I found online were in C++, so I am particularly interested in whether the same ideas/motivations carry over to C#.
3.) Is the
    [Serializable]
    [StructLayout(LayoutKind.Sequential)]
really necessary? I copied this from an example that I found online, so...
Answer: 1.) If the data within the structure is going to change regularly then it is more advisable to use a class, that is a reference to the memory location. If it is pretty much static, as i imagine this will be, it is better to use structs, that is value type.
2.) I have heard that aligning blocks of interleaved vertex data on 32-byte-aligned boundaries has a performance gain, good cache line coherence but I have yet to see a good example of any performance gain.
3.)yes it is, it specifies that the fields of the type should be laid out in memory in the same order they are declared in your source code. Which is obviously important for interleaved data.
Comment: Regarding 2.), I had read the same thing - my code works the same with or without the padding, so I was afraid I might either be doing something wrong or missing the point somewhere.              Thanks also for alerting me that I accidentally typed "bits" :).

VBOs Using Interleaved Vertices in C#


Update an Entry into mysql database

Question: I am new in coding and i was recently chosen to start training in C# and Asp.Net. I am trying to update an entry into the database but to no avail. The delete, create and read functions work properly. (i know that my code lacks try and catch)
I 've tried different solutions that i found while googling but since i am still training i never fully understand if what i am following is completely correct.
Currently i am able to diplay the fields with their info when navigating to the "Article" i am trying to edit but when i click the Save button nothing happens.
This is in my Article Context file:
public Article EditSingleArticle(int id, int userID, string Title, string Body)
    {
        Article article = new Article();
        using (MySqlConnection conn = GetConnection())
        {
            MySqlCommand cmdslct = new MySqlCommand("SELECT * FROM Article WHERE ID=@id", conn);
            MySqlCommand cmdul = new MySqlCommand("UPDATE Article SET userID=@userID,Title=@Title,Body=@Body WHERE ID=@id", conn);
            conn.Open();
            cmdslct.Parameters.AddWithValue("@ID", id);
            cmdslct.ExecuteNonQuery();
            cmdul.Parameters.AddWithValue("@userID", article.userID);
            cmdul.Parameters.AddWithValue("@Title", article.Title);
            cmdul.Parameters.AddWithValue("@Body", article.Body);
            cmdul.ExecuteNonQuery();
            using (MySqlDataReader reader = cmdslct.ExecuteReader())
            {
                while (reader.Read())
                {
                    article = new Article()
                    {
                        userID = reader.GetInt32("userID"),
                        ID = reader.GetInt32("ID"),
                        Title = reader.GetString("Title"),
                        Body = reader.GetString("Body")
                    };
                }
            }
            conn.Close();
        }

The code below is in my ArticleController file:
public IActionResult Edit(int id, int userID, string Title, string Body)
    {
        ArticleContext context = HttpContext.RequestServices.GetService(typeof(ArticleContext)) as ArticleContext;
        if (ModelState.IsValid)
        {
            return View(context.EditSingleArticle(id, userID, Title, Body));
        }
        return View();
    }

I don't get any error messages but the article i am trying to edit never updates
Comment: You are not adding your id parameter to your update command, so there will be no matching entries in your database to update (`WHERE ID=@id`).
Answer: The issue is that article object only have the default empty fields because you are calling  cmdslct.ExecuteNonQuery() that does not return data at all, only the number of rows affected by an insert, update, or delete.
So you should call ExecuteReader() that returns an object that can iterate over the entire result set while only keeping one record in memory at a time.
Your code should looks like the following code in order to work as expected:
        Article article = new Article();
        using (MySqlConnection conn = GetConnection())
        {
            MySqlCommand cmdslct = new MySqlCommand("SELECT * FROM Article WHERE ID=@id", conn);
            MySqlCommand cmdul = new MySqlCommand("UPDATE Article SET userID=@userID,Title=@Title,Body=@Body WHERE ID=@id", conn);
            conn.Open();
            cmdslct.Parameters.AddWithValue("@ID", id);
            using (MySqlDataReader reader = cmdslct.ExecuteReader())
            {
                while (reader.Read())
                {
                    article = new Article()
                    {
                        userID = reader.GetInt32("userID"),
                        ID = reader.GetInt32("ID"),
                        Title = reader.GetString("Title"),
                        Body = reader.GetString("Body")
                    };
                }
            }
            cmdul.Parameters.AddWithValue("@userID", article.userID);
            cmdul.Parameters.AddWithValue("@Title", article.Title);
            cmdul.Parameters.AddWithValue("@Body", article.Body);
            cmdul.ExecuteNonQuery();

            conn.Close();
        }

Regards,
Comment: i have copied your code but unless i copied something wrong i don't get the result i want
Answer: In your update query you are using a where condition which uses parameter @id. But you are not passing the ID argument to your query. Add a argument '@id' for the update query.
Add this line to the code
cmul.Parameters.AddWithValue("@id", id);

Comment: UPDATE Article SET userID=@userID,Title=@Title,Body=@Body WHERE ID=@id are you refering to this query? if yes what should i change
Comment: Yes in the update query you are using this condition 'WHERE ID=@id'. But @id is not passed as argument to query. To the parameter list add cmul.Parameters.AddWithValue("@id", id);
Comment: i have tried that but i still dont get the result i want
Comment: Then check if the correct id is getting passed in the argument
Comment: when i use the select query, when i navigate to the edit page all the fields are already populated with the details that were passed when the article was created. on the update article query though i cannot get it to save the changes
Comment: thank you for the help you actually helped me with your answer to find the solution. I've changed my update query to "UPDATE Article SET userID='" + userID + "',Title='" + Title + "', Body ='" + Body + "' WHERE ID ='" + id + "'" and it worked.

Update an Entry into mysql database


Downloading 22.04 iso

Question: I'm trying to download the latest Ubuntu for my desktop but when I try to download the iso it says " Load failed , not enough room on your harddrive". I have a 500G drive and a 4.7 G flashdrive and DVD but I can't free up enough room on my desktop to download the iso. Is there a way I can directly download it to the flashdrive or DVD?
Comment: Downloading the ISO directly to DVD or flashdrive (USB) won't make them bootable DVD or USB. Copying the ISO file into the DVD or USB wont work either. You have to first download the ISO into the hard disk of your computer and then use a special software to "burn" or create the DVD or USB to make them bootable. You can buy or borrow a second (and bigger) USB drive and directly download the ISO file into it.
Comment: @user68186 OP seems to have very less free space left in the home folder.
Comment: @ArchismanPanigrahi I edited my comment.
Comment: Try the commands `sudo apt clean` and `sudo apt autoremove -y` to free up some space in the hard drive.
Comment: @ArchismanPanigrahi It is not clear OP is using Ubuntu (or any Linux distro).
Comment: If you have previously installed Ubuntu, then you *already know* that that LiveUSB must be created; that you simply cannot download or copy it onto the USB. This suggests that you might not be using Ubuntu yet, in which case the installer will *certainly* reformat your hard drive, deleting everything. Everything! Back it up onto some other storage if you don't want it lost forever.
Comment: It's possible for you to download an ISO to one thumb-drive (*as a data drive; as it's only a storage location; my downloads are to network shares & never the small drive I have the system installed to; it'd never fit there*), but you cannot install from where its downloaded to. You still need to write the ISO to a media for installation; so whilst downloading it to a different storage media is for sure possible, you still need to write/burn it to media later.  You can boot off an ISO on disk if downloaded to the machine you want to use it on, but that involves a lot of intricate setup.
Answer: As you are not able to free some space up from your hard drive and you have both, a DVD and a thumbdrive available, you can easily solve (temporarily) the problem by downloading the ISO to either your USB flash drive or DVD, then use some of the widely available software to burn the image to the other portable device, for example:
#1. Connect the USB flash drive AND insert the DVD
#2. Download the ISO to your USB
#3. Use a burning software and select the ISO in the USB as source
#4. Burn the image to the DVD
#5. Remove USB and boot from DVD

Downloading 22.04 iso


How to use external Jars in javafxports-Application

Question: i write a javafx andoid application in netbeans with javafxports and gradle. I added the dependencies to gradel, but now i dont know how to add the jars to my project or to use it in my app-code. . .
Do you know how i can us it? I tried searching the www for hours ...
Ok i tried it but i dont get it ...
I did exactly what you said but netbeans still says:
package io.netty.bootstrap does not exist
I created a folder unter src/android/ called libs and add my jar there ...
Here are my dependencies:
dependencies {
    compile fileTree(dir: 'src/android/libs', include: ['*.jar'])
    compile files('src/android/libs/netty-all-4.0.29.Final.jar')
}

FINAL SOLUTION:

You have to add: compile 'io.netty:netty-all:4.0.24.Final' to the build.gradle file. (Example for netty JAR-Libary)
I copy the Libary (netty) to an Folder called "libs" in my main Folder not in sry and so on. Create the folder if not exist
Write your code and you will see, import works.

Thank you to José Pereda for the time and the final solution!
Comment: Could you be more specific or post your build.gradle file? Once you have the required dependencies, you can use them in your main code package, like in any other regular project. If you have platform specific dependencies, then those will be only available on that platfrom package.
Comment: I habe add the dependencies, but if i try to import it in my class, it says that the package is not there . . . normaly i say right click add Jar/libary and then i can use it, but there is no option to import these libarys. I copyed them in the libs folder under Android but the same ... Have you ever worked with javafxports? Can you tell me your way to import external libarys in netbeans?
Comment: I have a few projects you can check... [2048FX](https://github.com/jperedadnr/Game2048FX) or [HelloCharm](https://github.com/jperedadnr/HelloCharm). For starters I'll have a look at this one: [SMSTracker](https://github.com/jperedadnr/SMSTracker), there you'll see how the build.gradle is defined, and the structure of folders. Try to fork it, and run it and then let me know.
Comment: Ok i will do this ... but you have understood, that i want to use external libarys like apache common and so on?

Will write back after i testet SMSTracker . . .
Comment: Ok i have one more question, maybe it awnser all :)

Have you write this in build.gradle:

dependencies {

compile "com.gluonhq:charm-down-common:$CHARM_DOWN_VERSION"

desktopRuntime "com.gluonhq:charm-down-desktop:$CHARM_DOWN_VERSION"

androidRuntime "com.gluonhq:charm-down-android:$CHARM_DOWN_VERSION"

iosCompile "org.robovm:robovm-cocoatouch:1.0.0"

iosRuntime "com.gluonhq:charm-down-ios:$CHARM_DOWN_VERSION"

}

to use this in code?

import com.gluonhq.charm.down.common.PlatformFactory;
Comment: Sure, otherwise it wouldn't work. All the dependencies outside the JDK have to be added to the build file, and then you can simply use them with a regular import.
Comment: Ok and this is exactly my problem could you tell my which statment i have to write unter dependencys to use external jar like apache commons in the lib folder of my project? Currently i use compile fileTree(dir: lib, include: *.jar)
Comment: Including his: `dependencies {
    compile 'org.apache.commons:commons-lang3:3.4'
 }`  will add `commons-lang3-3.4.jar` to your project, and now you can import any of its classes on your main package: `import org.apache.commons.lang3.ArrayUtils;`.
Comment: Ok wow nice THANK YOU. I will test it at home :)

Can you tell me one more pls. In which directory i have to put my JAR-Libary? in the lib folder? Cuz you only give the name of the Jar and not the Path ...
Comment: If you mean local dependencies, you can add them also like: `dependencies { compile files('lib/my-jar.jar) }`, having `my-jar.jar` at a `lib` folder inside your project. If you want to add several jars: `dependencies { compile fileTree(dir: 'lib', include: ['*.jar']) }`.
Comment: Ok yes i mean, that my dependencie is local on the phone. Great Thank you. I will test it at home and i hope you dont kill me if i ask you something to this again ... :) Wish you a nice day!
Comment: Ok, I'll put our comments in terms of a proper answer
Comment: Ok i tried it but it dont work ... pls look at my Question ... i add additional informations for you. Thank you for help!
Comment: First of all, use a `libs` folder outside src. Also you can add your dependencies via `compile 'io.netty:netty-all:4.0.24.Final`
Comment: Ok i tried it with compile 'io.netty:netty-all:4.0.24.Final' but i dosent work. No its download some .pom files for netty but it still shows the same error during import ...
Comment: After any changes on the dependencies, you have to Reload the project, so they are updated. On Projects view, right click on your project and select `Reload Project`.
Comment: Ok now it work ... sry for this loooong meeting :)
Thank you very mutch for your help. I will write the final solution in my Question for all other users.
Comment: Glad it works, anyway, I am going to write a proper answer.
Comment: If it's related to the same topic, go ahead, otherwise start a new question
Comment: One last question: i tried to download gson from google but i dont get the right URL: 'com.google:code:gson:gson.2.3.1'

Can you give me the right url?
Comment: Based on this: `
com.google.code.gson
gson
2.3.1
` it should be `groupId:artifactId:version`, so: `com.google.code.gson:gson:2.3.1`
Comment: There you go, I've added a full answer. Now you know how it works, but surely it will be useful for others...
Answer: Based on the edited question, these are a few suggestions for working with dependencies on a JavaFXPorts project.
Dependencies and build.gradle file
According to this, the default dependency configurations compile and runtime are supported, and the jfxmobile plugin adds extra configurations for each supported platform like androidCompile or desktopRuntime.
To access third party dependencies, from a given repository this should be added:
repositories {
   jcenter()
}
dependencies {
    compile 'groupId:artifactId:version'
}

Since jcenter() is a superset of 'mavenCentral()`, you can use any maven dependency that was in the form of:
<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.0.4</version>
</dependency>

as compile 'groupId:artifactId:version'. So in this case:
dependencies {
    compile 'org.glassfish:javax.json:1.0.4'
}

Local files
Accesing local jars can be done using files:
dependencies {
    compile files('lib/my-jar.jar')
}

having my-jar.jar at a lib folder inside your project, but outside the src folder.
If you want to add several jars:
dependencies {
    compile fileTree(dir: 'lib', include: ['*.jar'])
}

Gluon plugin for NetBeans
After any change in the build.gradle file, it is necessary to reload the project, so the new changes are taken into account, and the new dependencies are retrieved.
Under the Projects view, right click on the Project root and select Reload Project.
Check also the Dependencies folders, those should contain the jars included in the build.
Since there are several of these folders, you can see for instance that Compile for android includes android.jarand jfxdvk-8u60-b3.jar. Compile for main should contain all the jars defined for compile.
Samples
These are some projects where the build.gradle contains dependencies, so they are a good way to start with JavaFXPorts.

HelloPlatform and other samples.
2048FX
SMSTracker
HelloCharm
Comment: For you who use eclipse and gluon - that wants as little trouble as possible. Look at the example of Local files - and also remember to right click project,  add build path and select jar - just like normal. Both are required.


Low voltage fuse blowing in furnace

Question: I have an outside A/C compressor and indoor furnace fan combo in the attic.  The unit was off and the 3 amp fuse was blown.  I replaced the fuse and used the thermostat to turn the fan on followed by the heater then the A/C.  I let the unit run the A/C.  After a while the A/C turned off.  I checked and the furnace was off, fuse blown and thermostat was asking for cool.  I do not know if the fuse blew during operation, shutdown, or when the next request for cool happened.
I checked the wires leading to the outside unit.  They show open when disconnected and 20.8 ohms when connected to the contactor.  The wires leading from the thermostat to the furnace show open until fan, heat or A/C is selected and they show continuity as expected.
The volts across the red and green terminals shows 27 volts.  The transformer is showing 120 in and 27 out.  My first reaction is to replace the contactor on the outside unit, but that 27 volts is interesting to me because the schematic and Xformer say 24 volts.
Update
Performed the following tests.  Disconnected the wires to the outside unit and ran the fan for a few hours no issues.  There are 3 wires going from the furnace to the outside unit.  White wire goes to 1 terminal of the contactor relay.  Red and green wires were tied together and attached to the other terminal.  On the furnace outside white is tied to yellow, outside green is tied to blue.  Outside red was disconnected and loose on furnace.  I disconnected red from green outside and put a wire nut on it.  Measured the voltage on the relay of 27 volts.  The resistance without wires is 16 ohms.  Ran the A/C briefly without issue.  Running the A/C today without 240 to see in the contactor heats up.
The furnace is a Lennox gas heater model number G40UH-36A-070-15.  The outside A/C is a Lennox 13ACD-036-230-02.  I went ahead and ordered a new relay because it is pretty cheap.  It should arrive by this weekend.
What should I do next to troubleshoot this?
Comment: 27 volts is normal for a transformer that is nominally 24vac under no load.  When you replaced the fuse which did you use, fast acting or time delay?
Comment: I believe it is fast acting its the same kind one finds in a car.  It's a Bussman 3 amp I got from Autozone.
Comment: If the red wire that was attached to the contactor, could have shorted to ground on occasion.  That could explain the problem.
Comment: Need the make and model number on the furnace (possibly the condenser, too). Gas or electric heat?
Comment: @Mazura Thanks for pointing out I didn't include the model number.  I updated the question.
Comment: Re. troubleshooting, it would be good to measure the current using an amp meter.  Check between the A/C transformer into the board and then separately leaving the board to the various contactors when each is activated.  The readings should be about 2A or less.  If you find something measures close to the fuse limit, then look more closely in that area.
Answer: Edit:
I concede that the answer to this problem depends on some specifics that are lacking.
If the OP fuse is a glass cartridge style, then it is likely that a slow blow (MDL type or similar) is required in place of the fast acting automotive type.  If the fuse is the automotive blade type as Mazura pointed out, then fast acting is the only option for those and the problem lies elsewhere.
Electrical contactors do draw relatively high current until the contacts seat into the closed position, so I also have to agree that a sticky A/C contactor could blow the fuse even if the contactor coil is actually good.  To test if the contactor is sticking, I would turn off the outdoor disconnect to the compressor and open the condenser access panel for inspection.   Turn the thermostat to "cool" and watch the contactor pull in.  If the contactor action is sluggish, that could cause the problem.  With power to the compressor turned off at the disconnect, this test could be performed repeatedly.
Comment: @chris Yesterday I pulled the panel off the outside unit and watched the contactor cycle.  Can you provide a description of what sluggish looks like?  The plunger moved in rapidly, there was a click and the compressor turned on.  I let it run for about a minute and then someone switched it off with the thermostat.  The plunger moved out rapidly and the unit turned off.  Waited 5 minutes and repeated.  Would it be worth it to pull 240 power from the compressor, call for cool and let the system run that way to see if the contactor overheats?
Comment: @Matt - normal contactor action is very fast and lasts a fraction of a second from the time the contactor is energized.  If there is any discernible buzzing or humming before the contactor pulls in then it is probably sticking.  To check the action of the contactor by observing it, I would turn disconnect to the outdoor condenser off (there should be a service disconnect nearby and 24v should still be available at the contactor with the disconnect off) and then observe many cycles.  If it never sticks, then this is unlikely to be the cause of the burned fuse.
Comment: @Matt - posting the exact model number of the furnace / fan coil and a clear photo of the entire board with the problem fuse identified and clearly visible might enable me to give you better info.
Comment: I'm having a hard time finding a 3 amp slow blow blade fuse. Didn't know that was a thing. If the fuse is blowing, there's a problem with the unit, not the fuse.
Comment: Slow blow fuses and fast acting fuses are not interchangeable and they serve different purposes.   I am not referring to blade style fuses, but instead slow blow in the AGC style cartridge.  I have no trouble finding 3A slow blow fuses of this type.  Amazon:  http://www.amazon.com/Quality-pieces-6X30mm-Slow-Blow-SHIPPING/dp/B00BP8JUGG/ref=sr_1_2?ie=UTF8&qid=1447045983&sr=8-2&keywords=3+amp+slow+blow; Radio Shack: https://www.radioshack.com/products/radioshack-3-0-amp-250v-1-x-slow-blow-fuse-4-pack; Specialty electronics stores....lots of examples.
Comment: OP's are most likely *Blade Fuses* "the kind in your car".
Comment: Hard for me to see how you can assume this.  Originally cars used AGC fuses.  The letters stand for "Automotive Glass Cartridge."  You are correct that automotive blade fuses come in fast acting only, and if one were to use this type in a circuit with an electromagnetic contactor then it would need to be significantly oversize to prevent false tripping.
Comment: Every modern furnace I've installed has blades, some of the older ones have glass though. You're right, we are wrong to assume. @Matt - What's your fuse look like?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/31293/discussion-between-mazura-and-chris).
Comment: You're saying the current through the contactor coil is higher before the contact is closed, so if the contact is closing slowly the coil current is too high?
Comment: @Mazura I would call it a blade.  It is flat with 2 blades that fit into 2 receptacles on the furnace.  I got the replacements at Autozone, they are purple 3 amp Bussman fuses.
Comment: @Tester101 - yes, current is often *several times* higher before the contacts pull in.  In a properly functioning contactor this is a brief current surge.  It is easy to observe this if you have spare parts and a meter lying around.
Comment: @Tester101 - just to clarify, high coil current when open is a characteristic of contactors with AC coils and not DC coils.
Answer: Set the fan to 'on' and have someone monitor the furnace blower. Go outside and hold the AC contacter down for as long as you're willing to. If the furnace blower never trips out, then it is that contacter getting hot and drawing an over current. Otherwise, happy hunting; that's my two cents.
You could also try toggling the fan to 'on' a bunch of times and see if that does it (could be a hard start after all; old motor/bearings). I guess if you want to freeze your unit and check that contacter at the same time (without anyone having to stand there) pull the power feed to the blower motor (from its clips on the control board) and call for AC. If it never trips out, it was the blower motor. If it does blow out, then it's somewhere between the control board, that contacter, or the thermostat and its wires (have fun ;).
Comment: The 3 amp fuse in furnaces are usually on the low voltage side of the transformer, so I wouldn't think motors would have anything to do with the problem.
Comment: @Tester101 - I have suspicions that when it shuts down, something shorts to ground and pops the fuse. I'm shooting in the dark here; grabbing at straws. You're right, if it was doing it from hard starts, it would pop right away, and not get through a cycle. Do AC units ever have a heat coil like fridges do?
Comment: Heat pumps have a defrost, but only when in heat mode. And again, that's on the line voltage side.
Answer: Check all of the wires where they pass through metal. The metal may have worn through the insulation on the wire, causing an intermittent short.
Also, inspect the wires anywhere the outer insulation is stripped back. It's pretty easy to damage the inner insulation when stripping off the outer, which could also lead to an intermittent short.
Answer: So the problem ended up being the contactor on the outside unit.  How I went about troubleshooting the problem was to disconnect the outside from high voltage power.  Then I turned on the thermostat and allowed it to cycle a few times over the course of 2 days.  The fan would come on as expected and the fuse never blew.  I ordered a new contactor and installed it.  Luckily the temperature in Houston was in the 80's in December so I tested the A/C with the new unit in it.  No fuses blew.  It is worth noting that the old contactor showed a little oxidation and the points on it were burnt somewhat.
Answer: Check your reversing valve!!  Was havingg the same problem. Reversing valve is stuck. Good luck. A little more on the cost side.
Comment: Welcome to the site. To improve this answer, details on how to diagnose whether the reversing valve is stuck would be useful.
Comment: Hello, and welcome to Home Improvement. Thanks for the answer; keep 'em coming. And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know how best to contribute here.
Answer: If you think that over-voltage is blowing the fuse (unlikely, but possible) you can always use a larger fuse.  While this is not recommended, there is some wiggle room.  If you were to put a 4 amp 50 volt time-delay fuse in it's place, you would still provide short-circuit protection while bypassing this slight(ish) problem.
Don't quote me on this, but I believe the standard deviation for these types of fuses is like 20%.  That means that your 3 amp fuse could be anywhere between 2.4 and 3.6 amp.
Comment: @Daniel -- no, actually.   Installing a fuse with an amperage rating greater than the intended design is not okay.  Unless one likes smoking the windings on transformers, stay within the VA rating.
Comment: Fuses are not typically used for short-circuit protection, they're used for overcurrent protection. Basically, the fuse burns before your wiring. If you replace the fuse with a larger one, then your wiring might burn first. Using a larger fuse, is almost never the correct solution.
Comment: @Daniel - I do not dispute that fuses have a tolerance range.  One can look this up in the selection charts.  I am simply saying that increasing fuse size above the intended limit is not a wise troubleshooting or repair solution.  I have repaired wiring in more than one machine where prior techs thought a bigger fuse was the solution.  In the end what they really did was make more work for me.
Comment: I'm not sure what it is.  After changing the fuse it blew again after running the A/C for a while.  I have since replaced it again and it is working.  I am thinking I need to replace the contactor.  Just looking for ideas to test.
Comment: @Daniel  --  hypothetical example:  If I short a 22 gauge wire across the secondary of a transformer rated 24volts and 75VA with no separate fuse protection such that the transformer delivers 20A at 5v across the small wire, then the  transformer will get very warm and the small wire will get red hot and can start a fire.  The circuit breaker for the 120v branch circuit will not trip in this situation.  When I was a kid I accidentally burned a hole in my parent's floor this way.
Comment: I'm aware of this @chris, but I'm also aware of the fact that the difference between 3 amps and 4 amps is minuscule compared to what that wiring and transformer can handle.  I'm just saying what I would do in this situation if I wasn't comfortable taking things apart (which I am)
Comment: And same to @Tester101
Comment: Swapping the fuse out to a 5amp [is recommended by some](http://www.furnacereviews.net/goodman-furnace-keeps-blowing-fuses.html), but not by me. However, if you just can't figure it out and don't care if you fry your board (or possibly burn down your house)... well, that's up to you.
Comment: It won't burn down the house, they put breakers in place for a REASON!
Comment: I'm not saying completely remove the fuse.  I'm saying upgrade (or downgrade - whichever you want to say) the fuse.
Comment: @Daniel - Standard CBs protect the wire, *not* you or any of your equipment. That's why GFCI's are in the bathroom; the CB has no idea whether or not your, e.g. electric razor, should be drawing as much current as a heat coil. And if something is amiss, that's what your furnace circuit board becomes: a heat coil. Until it starts pulling more than 15~20 amps minimum (depending), that CB ain't gonna pop (= fire). **TL:DR** - CBs protect your house's wire. Fuses in equipment protect *that* equipment (in turn, protecting your house from fire). They put a 3amp fuse in place for a REASON.
Comment: And a 4 amp fuse in a 3 amp socket is a very small difference when it comes to equipment like this.  The only scenarios in which it would make a catastrophic difference would be those that involve small-signal communication and ICs.  Those blow easy, discreet circuitry doesn't.

Low voltage fuse blowing in furnace


How can I detect in my app if the device it's running on is Sony Xperia Play?

Question: Should I check android.os.Build.PRODUCT or android.os.Build.DEVICE for a particular value? Will this value be the same on all firmware versions?
Or is there some other way?
Comment: what you want `device model or device manufacturer name?`
Comment: Model. I want to know if the device is "Sony Xperia Play" (with gamepad).
Comment: http://developer.android.com/reference/android/os/Build.html
Comment: There is no answer on that page. What particular value should I look for? Is it "Sony Xperia Play"? Is it "Xperia Play"? Is it some code like "R800a"?
Comment: This may help you http://stackoverflow.com/questions/1995439/get-android-phone-model-programmatically
Comment: I'm looking for the value, I know how to get it...
Answer: Here are all the model names of Xperia PLAY in the world.
Xperia™ PLAY (R800)
R800i,R800a, R800x, R800at, Z1i, SO-01D
Depending on what you want to do, there are other ways to detect if it's an Xperia PLAY.
If you want you application to only work on Xperia PLAY, try using Google PLAY(previously Android Market) Developer Console to limit your application to Xperia PLAY.
If you just want to remove controls from the screen when the device is Xperia PLAy, try detecting when the gamepad is opened.
In case you want to do some navigation or other stuff using DPAD, try detecting if the device has a DPAD.
Answer: check android.os.Build.DEVICE. if it was equal to zeus, that means that the device which your app is running is Xperia Play.
like this:
boolean isXperiaPlay = android.os.Build.DEVICE.equalsIgnoreCase("zeus");

for more info: each android phone has a codename, for example, codename of the nexus s is crespo and codename of the nexus one is passion. this value for Xperia Play is Zeus.
Comment: Thanks! But I think the value of android.os.Build.DEVICE depends on firmware.  I asked a user with Xperia Play to test my app and on his phone android.os.Build.DEVICE returned "R800i". Of course I can check for strings "R800*", "R88*" and "zeus", but I'm afraid there might be other values...
Answer: try
String PhoneModel = android.os.Build.MODEL

for example, on my sony LT26i, it shows "LT26i"
Comment: So what value should I expect on Xperia Play?


Run Webstorm as privileged user

Question: I want to update the Webstorm IDE. I get the following error message.
WebStorm does not have write access to /app/extra/webstorm. Please run it by a privileged user to update.

WebStorm was installed from a flatpak from Ubuntu Software Center. When I right-click on Webstorms laucher icon and click Show details Ubuntu Software Center opens with the below screen.
The executable is located at
/var/lib/flatpak/app/com.jetbrains.WebStorm//x86_64/stable/3ed7173f533071abd544a5ff0859eb0b8a8ceb60935d7e2ab3cce3fac03ccabf/files/extra/webstorm/bin/webstorm.sh

How can I run Webstorm by a privileged user?
Answer: Please try the following steps-

Open the installation directory of Web Storm (dpkg --listfiles webstorm or which webstorm)
Find the executable (i.e., webstorm.sh)
Run as sudo sudo ./webstorm.sh
Update
Comment: I found the executable with https://github.com/flatpak/flatpak/wiki/Filesystem
and using the command
find . -name "*.sh"
in
/var/lib/flatpak/app/com.jetbrains.WebStorm .
Comment: I don't know the installation directory. How can I find it?
Comment: How did you installed it?
Comment: Through ubuntu software center.
Comment: Run this command `dpkg --listfiles webstorm` or `which webstorm` and post the result
Comment: dpkg-query: package 'webstorm' is not installed
Use dpkg --info (= dpkg-deb --info) to examine archive files,
and dpkg --contents (= dpkg-deb --contents) to list their contents.
Comment: what is the output for `which WebStorm`?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/98483/discussion-between-digiwizkid-and-michael-h).

Run Webstorm as privileged user