EzDevInfo.com

home-directory interview questions

Top home-directory frequently asked interview questions

Are Java system properties always non-null?

There are a couple of Java system properties, among them things like java.home and path.separator, user.home. The spec does not mention any formal promises on the existence of those values.

Especially I am interested in user.home. Does it always point to some existing path?


Source: (StackOverflow)

Fix msysGit Portable $HOME location

I have successfully installed and configured msysGit Portable on my flash drive, and have used it to pull and push GitHub repos. However, I seem to always have to kludge the SSH support.

Specifically, in order for SSH to find my key files, I have to follow these instructions to start a second instance of ssh-agent and then ssh-add my key every time I run git-bash.bat.

Using the output of ssh -v git@github.com to debug I see that msysGit defaults to my Windows user directory to look for keys. It can't do that; I need it to look in its own directory on the portable drive.

How can I force $HOME to be the program's own folder?

Update for broken Vox link

Instructions from this page are similar to the now-broken link I originally posted. Quoted below. Also here's the webarchive of original Vox article.

However, if you try this and get:

% ssh-add
Could not open a connection to your authentication agent. 

then your session is not running under the ssh-agent. You can get around this by restarting a new shell under the agent by running:

exec ssh-agent bash 

where you can replace bash with the shell of your choice. Once you do this, you should be able to run ssh-add to load your key for that shell.


Source: (StackOverflow)

Advertisements

Detecting Unix home in Wine application

My Windows application is frequently used on *nix using Wine.

As it is a file-centric application, it frequently uses (and presents to an user) Windows "documents" folder (as resolved using CSIDL_PERSONAL). Unfortunately under Wine that points to fake Wine/Windows directory that's usually empty and unused. I'd like to point user to his Unix home folder instead.

Is there any reliable way to find out its location under Wine?

I was hoping I can read HOME environment variable, but it's not exported (contrary to most other variables) to Windows environment.

Currently I'm guessing the home using Z:\home\%USERNAME%. But that does not look robust to me.

If there's no way to find home directory, is there at least a way to detect Wine root drive (Z: by default), so I do not need to hard-code at least a drive-part of path?


Source: (StackOverflow)

What is the Windows equivalent of pwd.getpwnam(username).pw_dir?

The Python pwd module provides access to getpwnam(3) POSIX API, which can be used to get the home directory for a particular user by username, as well determining if the username is valid at all. pwd.getpwnam will raise an exception if called with a non-existent username.

At first it seems like the same result can be achieved in a cross-platform manner via os.path.expanduser('~username'). However, it appears that with Python 2.6 on Windows XP this won't actually produce a failure for a non-existent username. Furthermore, on Python 2.5 on Windows XP, it seems to fail even for valid users.

Can this information be obtained reliably on Windows? How?


Source: (StackOverflow)

Read user home directory from PHP

I cannot find a way to get the user's home directory (e.g. /home/jack; whatever ~ in bash points to) in PHP using CGI (suPHP). The $_ENV array is empty, and getenv('HOME') returns nothing.

The reason I want to do this is that in absense of configuration saying otherwise, I want to find variable files used by my application in /home/user/.myappnamehere, as most Linux applications do.


I've built something, but it's not the best; While it works, it assumes a lot about the system (e.g. the presence of /etc/passwd)

 $usr = get_current_user();
    $passwd = file('/etc/passwd');
    $var = false;
    foreach ($passwd as $line) {
        if (strstr($line, $usr) !== false) {
            $parts = explode(':', $line);
            $var = realpath($parts[5].'/.report');
            break;
        }
    }

Source: (StackOverflow)

Salt: $HOME of users which does not exist yet

I create a user foo on a minion. The minion evalutes /etc/default/useradd. This means the salt master does not know whether the new $HOME will be /home/foo or in our case /localhome/foo.

How can I get the $HOME of user foo as jinia variable?

I need it in a systemd service file.

I would like to avoid custom pillar data, since this is redundant. Is there a way to get it via grains?

Does it work during boostrapping? First the user foo needs to be created, then the systemd file can be created by looking up the $HOME of foo...

This would work if the user does already exist:

{{ salt['user.info'](user).get('home') }}/foo:
  file.recurse:
    - source:    salt://conf/common/foo

Related issue: https://github.com/saltstack/salt/issues/7883


Source: (StackOverflow)

How can I make perl recognize paths with '~'?

Possible Duplicate:
How do I find a user's home directory in Perl?

I'm running Ubuntu.

Whenever I pass a Perl script a path that starts with ~ (e.g. ~/Documents/file.txt) it fails finding it. I must pass the canonical path (e.g. /home/dave/Documents/file.txt).

Why is that?

Can I make perl recognize ~ paths?

UPDATE

All the suggested solutions include changing the code in the scripts. I would like for a solution that would not involve any changes to the scripts themselves (since not all of them are mine). Perhaps something in the way bash works?

UPDATE 2 The updated version of the question was posted at SU.


Source: (StackOverflow)

Mac Shell script get home directory

I need to get the home directory in my shell script so my coworkers can run it. What my shell does is really simple, it only copy some directories to another. I've used:

$HOME,
$(whoami)
even this:
ABSPATH=$(cd "$(dirname "$0")"; pwd),

but when I use the variable like this:

DIR= $ABSPATH/folder/afolder/bfolder/

and run it I receive this:

/Users/theUser/Desktop/FusionTest.command: line 14: /Users/theUser/Desktop/folder/afolder/bfolder: is a directory
Copying to usage: cp [-R [-H | -L | -P]] [-fi | -n] [-apvX] source_file target_file cp [-R [-H | -L | -P]] [-fi | -n] [-apvX] source_file ... target_directory logout
[Process completed]

I'm using the command cp -r to copy all files and directories.

Whay I am missing? or how can I do this??


Source: (StackOverflow)

Struts 2 Default Page

I have a a web application using struts two that can access a action by literally typing it into the URL

localhost/project/index.action

but it won't redirect to this default action without explicitly typing it in.

localhost/project/

gives the error

Error 404: SRVE0190E: File not found: {0}

I am assuming the file isn't found because I don't have something configured correctly.

Can anyone point me in the right direction as for getting this behavior with Struts 2?

Per request here is my struts.xml and web.xml

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Doc Parser</display-name>

<filter>
    <filter-name>struts-prepare</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter</filter-class>
</filter>
<filter>
    <filter-name>struts-execute</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter</filter-class>
</filter>
<filter>
    <filter-name>sitemesh</filter-name>
    <filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>struts-prepare</filter-name>
    <url-pattern>*.action</url-pattern>
    <url-pattern>/struts/*</url-pattern>
    <url-pattern>/</url-pattern>
</filter-mapping>
<filter-mapping>
    <filter-name>sitemesh</filter-name>
    <url-pattern>*.action</url-pattern>
    <url-pattern>/struts/*</url-pattern>
    <url-pattern>/</url-pattern>
</filter-mapping>
<filter-mapping>
    <filter-name>struts-execute</filter-name>
    <url-pattern>*.action</url-pattern>
    <url-pattern>/struts/*</url-pattern>
    <url-pattern>/</url-pattern>
</filter-mapping>

<listener>
    <listener-class>org.apache.struts2.dispatcher.ng.listener.StrutsListener</listener-class>
</listener>

<servlet>
    <servlet-name>sitemesh-freemarker</servlet-name>
    <servlet-class>org.apache.struts2.sitemesh.FreemarkerDecoratorServlet</servlet-class>
    <init-param>
        <param-name>default_encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet>
    <servlet-name>sitemesh-velocity</servlet-name>
    <servlet-class>org.apache.struts2.sitemesh.VelocityDecoratorServlet</servlet-class>
    <init-param>
        <param-name>default_encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>


<servlet-mapping>
    <servlet-name>sitemesh-freemarker</servlet-name>
    <url-pattern>*.ftl</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>sitemesh-velocity</servlet-name>
    <url-pattern>*.vm</url-pattern>
</servlet-mapping>

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

Strust.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">

<constant name="struts.freemarker.templatesCache" value="true" />

<constant name="site.framework.roles"
    value="
    free => http://security.site.com/service/mwstutorial/getItems,
    loggedIn => http://security.site.com/service/mwstutorial/setItems" />

<package name="blank" extends="default">

</package>


Source: (StackOverflow)

How to change the $HOME directory in Git

I would like to know, since I've been looking quite some time on how to do this, atleast in this community. would like to know how to change the $HOME directory in a Mac OS X Lion, in Git.

In other words, how do I make it so that my global user settings are saved in a folder like git and not right inside the main user folder? Or is it already like that? I basically want to keep a centralized place for all my files and stuff that I use in Git (for example, a .gitmessage.txt file, if I'm not mistaken, this shouldn't be hidden since it's a TXT file).

If you need more info don't hesitate to ask.


Source: (StackOverflow)

Java System.getProperty("user.home") directory missing separator

Whenever a user enters "~" as an argument, my program replaces it with System.getProperty("user.home").

After debugging, I see that this replaces "~" with "C:UsersSoulBeaver" and not "C:/Users/SoulBeaver".

Going through previous questions about incorrect user.home folders, I found out that Java tries to fetch the path from

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\

However, I'm using Windows 8 and there is seemingly nothing wrong:

At this point I'm assuming Java "eats" the backslash... so how do I prevent that from happening?

Update

Since the code was requested, here it is. This is taken from Allen Holub's Solving Java's Configuration Problem

/**
 * For every enum element in the array, treat keys[i].name() as a key
 * and load the associated value from the following places (in order):
 *
 * <ol>
 *     <li>a -D command-line switch (in System properties)</li>
 *     <li>if no -D value found, an environment variable with the same name as the key</li>
 *     <li>if no environment found, the default stored in the Enum element itself</li>
 * </ol>
 *
 * That value must identify an existing directory in the file system, and a
 * File representing that location can be retrieved from {@link #directory(Enum)}.
 *
 * @param keys The values() array associated with the enum that's using this class.
 * @throws IllegalStateException if a given key doesn't have a value associated with it
 *          or if that value doesn't identify an existing directory.
 */
public LocationsSupport(T[] keys) throws IllegalStateException {
    StringBuilder logMessage = new StringBuilder("Loaded environment/-D properties:\n");

    try {
        for (T element : keys) {
            String how = "???";
            String key = element.name();

            String value;
            if ((value = System.getProperty(key)) != null)
                how = "from system property (-D)";
            else if ((value = System.getenv(key)) != null)
                how = "from environment";
            else if ((value = element.defaultValue()) != null)
                how = "from default. Mapped from: " + value;

            if (value != null)
                value = value.replaceAll("~", System.getProperty("user.home"));

            if (value == null || value.isEmpty())
                throw new IllegalStateException("Value for " +key +" cannot be null or empty.");

            File location = new File(value);

            createLocationIfNecessary(location, element.createIfNecessary());

            if (!location.isDirectory())
                throw new IllegalStateException("Location specified in "
                        +key
                        +" (" +asString(location) +") "
                        +"does not exist or is not a directory.");


            dictionary.put(key, location);

            logMessage.append("\t");
            logMessage.append(key);
            logMessage.append("=");
            logMessage.append(asString(location) );
            logMessage.append(" (");
            logMessage.append(how);
            logMessage.append(")\n");
        }
    } finally {
        if (log.getAllAppenders() instanceof NullEnumeration)
            System.err.println(logMessage);
        else
            log.info(logMessage);
    }
}

It's failing at trying to locate the default location for CONFIG:

public enum Places implements Locations {
    CONFIG ("~/config"),
    HOME   ("~"),
    TMP    ("~/tmp", true),

    TERM_STORE     ("~/tmp/indices/term_store/",     true),
    RESOURCE_STORE ("~/tmp/indices/resource_store/", true),
    PERSON_STORE   ("~/tmp/indices/person_store/",   true);

I am using Java 1.7.0_13 and IntelliJ IDEA 12.1.3


Source: (StackOverflow)

Proper usage of the windows user profile directory

I need to create a directory inside a windows users 'home' directory (c:\Documents and Settings\someusername\ or c:\users\someusername\). This directory will exist permanently but will only contain temporary files.

What is is the best location for this directory within the users profile if I want to be a good citizen? I should note that my program will be run by (possibly) non-admin users and will only need access to their own profile, but they must have permission to create the folder.

Using My Documents\NameOfMyApp\ is possible I guess, but that seems intrusive.

Is there a better location for this type of data, and a specific MFC call to access it?


Source: (StackOverflow)

Start program in user folder without knowing user name

I have no idea if I can just run this code and it will work but here:

public void actionPerformed(ActionEvent e) {
        try
        {
        Runtime rt = Runtime.getRuntime();
        Process p = rt.exec("c:\\Users\\Toby\\AppData\\Roaming\\.minecraft\\minecraft.exe");
        }

        catch(Exception a)
        {

        }
    }

This is linked to a button, and it launches the minecraft launcher. If I want to give it to my friends, what do I have to do so that it doesn't look for the user 'Toby', but instead looks for their home folder? Sorry if its confusing!


Source: (StackOverflow)

Prevent Backup to iCloud,is following code correct?

I am downloading many audio and video files and stored them in my Home directory. Now i want to "prevent backup to iCloud" so i have added following code for my every file's url

- (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL

{

    const char* filePath = [[URL path] fileSystemRepresentation];



    const char* attrName = "com.apple.MobileBackup";

    u_int8_t attrValue = 1;



    int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);

    return result == 0;

}

Can anyone tell me that will this code work for all IOS versions. if not then please suggest the correct way to do this. Thank You


Source: (StackOverflow)

How to find the real user home directory using python?

I see that if we change the HOME(linux) or USERPROFILE(windows) environmental variable and run a python script, it returns the new value as the user home when I tried, os.environ['HOME'] os.exp

Is there any way to find the real user home directory without relying on the environmental variable?. Thanx.
edit:
Here is a way to find userhome in windows by reading in the registry,
http://mail.python.org/pipermail/python-win32/2008-January/006677.html

edit:
One way to find windows home using pywin32,

from win32com.shell import shell,shellcon
home = shell.SHGetFolderPath(0, shellcon.CSIDL_PROFILE, None, 0)

Source: (StackOverflow)