问:
Handlebars and Node.js: {{#if !user}} Then Show Log In Button
I'm creating a login validation app using Node.js, Express, and Handlebars for the templating engine.

If there is no user logged in, I want my dashboard to display a "Log In" button. If a user is logged in, I don't want it to show. I tried this without having logged in...

```<code>{{#if user}}
    <a type = "button" class = "btn btn-default" href = "/users/login">Log In</a>
{{/if}}
</code>```

Funny thing is, this hide the element. Then when I corrected the code to what it should be... This...

```<code>{{#if !user}}
    <a type = "button" class = "btn btn-default" href = "/users/login">Log In</a>
{{/if}}
</code>```

I get this error,

I've never used handlebars before so I'm kind of shooting blind. Any help appreciated in advance!

答:
You can either deliver the user variable in its opposite state from the start or you could try to use {{#unless user}}.

http://handlebarsjs.com/builtin_helpers.html

Body:
I'm creating a login validation app using Node.js, Express, and Handlebars for the templating engine.

If there is no user logged in, I want my dashboard to display a "Log In" button. If a user is logged in, I don't want it to show. I tried this without having logged in...

{{#if user}}
    Log In
{{/if}}

Funny thing is, this hide the element. Then when I corrected the code to what it should be... This...

{{#if !user}}
    Log In
{{/if}}

I get this error,

I've never used handlebars before so I'm kind of shooting blind. Any help appreciated in advance!


来源: stackexchange

问:
mediawiki DBLoadBalancer error while setting up wiki
I've just installed MediaWiki 1.28 on arch linux with nginx 1.10.3, php 7.1.1, php-fpm, and sqlite 3.16.2. I followed the arch wiki guide: https://wiki.archlinux.org/index.php/MediaWiki. I've installed the required PHP extensions and PHP, sqlite, nginx all seem to run fine on their own.

Now when I'm trying to do the setting up LocalSettings.php part of the MediaWiki installation, I go to 0.0.0.0/mediawiki in the browser, click the setup and get the error below. Maybe it's a setting for sqlite that has to be enabled?

```<code>[1449c8c65e65734059748f4e] /mw-config/index.php MediaWiki\Services\ServiceDisabledException from line 340 of /usr/share/webapps/mediawiki/includes/services/ServiceContainer.php: Service disabled: DBLoadBalancer

Backtrace:

#0 /usr/share/webapps/mediawiki/includes/MediaWikiServices.php(509): MediaWiki\Services\ServiceContainer->getService(string)
#1 /usr/share/webapps/mediawiki/includes/GlobalFunctions.php(3089): MediaWiki\MediaWikiServices->getDBLoadBalancer()
#2 /usr/share/webapps/mediawiki/includes/GlobalFunctions.php(3075): wfGetLB(boolean)
#3 /usr/share/webapps/mediawiki/includes/cache/LinkCache.php(267): wfGetDB(integer)
#4 /usr/share/webapps/mediawiki/includes/Title.php(3184): LinkCache->addLinkObj(Title)
#5 /usr/share/webapps/mediawiki/includes/Title.php(934): Title->getArticleID(integer)
#6 /usr/share/webapps/mediawiki/includes/content/ContentHandler.php(282): Title->getContentModel()
#7 /usr/share/webapps/mediawiki/includes/Title.php(4684): ContentHandler::getForTitle(Title)
#8 /usr/share/webapps/mediawiki/includes/parser/Parser.php(867): Title->getPageLanguage()
#9 /usr/share/webapps/mediawiki/includes/parser/Parser.php(2110): Parser->getTargetLanguage()
#10 /usr/share/webapps/mediawiki/includes/parser/Parser.php(2075): Parser->replaceInternalLinks2(string)
#11 /usr/share/webapps/mediawiki/includes/parser/Parser.php(1290): Parser->replaceInternalLinks(string)
#12 /usr/share/webapps/mediawiki/includes/parser/Parser.php(441): Parser->internalParse(string)
#13 /usr/share/webapps/mediawiki/includes/installer/Installer.php(675): Parser->parse(string, Title, ParserOptions, boolean)
#14 /usr/share/webapps/mediawiki/includes/installer/WebInstaller.php(681): Installer->parse(string, boolean)
#15 /usr/share/webapps/mediawiki/includes/installer/WebInstaller.php(657): WebInstaller->getInfoBox(string, string, string)
#16 /usr/share/webapps/mediawiki/includes/installer/WebInstaller.php(401): WebInstaller->getErrorBox(string)
#17 /usr/share/webapps/mediawiki/mw-config/index.php(54): WebInstaller->showError(Message, string)
#18 /usr/share/webapps/mediawiki/mw-config/index.php(38): wfInstallerMain()
#19 {main}
</code>```

答:
Regardless of what Tgr said above, fixing the sessions did fix the issue for me. I'm using Apache ITK so the resolution I use is slightly different since each virtual host runs under its own unique uid.

First I create a separate directory for the sessions and change ownership

```<code>mkdir /var/lib/php/sessions-wiki
chown wiki. /var/lib/php/sessions-wiki
</code>```

Then in my VirtualHosts directive I tell Apache/php where to find the session files by adding

```<code>php_admin_value session.save_path "/var/lib/php/sessions-wiki"
</code>```

Then to make sure your config didn't break it.

```<code>apachectl configtest
</code>```

Finally reload your config

```<code>apachectl graceful
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've just installed MediaWiki 1.28 on arch linux with nginx 1.10.3, php 7.1.1, php-fpm, and sqlite 3.16.2. I followed the arch wiki guide: https://wiki.archlinux.org/index.php/MediaWiki. I've installed the required PHP extensions and PHP, sqlite, nginx all seem to run fine on their own.

Now when I'm trying to do the setting up LocalSettings.php part of the MediaWiki installation, I go to 0.0.0.0/mediawiki in the browser, click the setup and get the error below. Maybe it's a setting for sqlite that has to be enabled?

[1449c8c65e65734059748f4e] /mw-config/index.php MediaWiki\Services\ServiceDisabledException from line 340 of /usr/share/webapps/mediawiki/includes/services/ServiceContainer.php: Service disabled: DBLoadBalancer

Backtrace:

#0 /usr/share/webapps/mediawiki/includes/MediaWikiServices.php(509): MediaWiki\Services\ServiceContainer->getService(string)
#1 /usr/share/webapps/mediawiki/includes/GlobalFunctions.php(3089): MediaWiki\MediaWikiServices->getDBLoadBalancer()
#2 /usr/share/webapps/mediawiki/includes/GlobalFunctions.php(3075): wfGetLB(boolean)
#3 /usr/share/webapps/mediawiki/includes/cache/LinkCache.php(267): wfGetDB(integer)
#4 /usr/share/webapps/mediawiki/includes/Title.php(3184): LinkCache->addLinkObj(Title)
#5 /usr/share/webapps/mediawiki/includes/Title.php(934): Title->getArticleID(integer)
#6 /usr/share/webapps/mediawiki/includes/content/ContentHandler.php(282): Title->getContentModel()
#7 /usr/share/webapps/mediawiki/includes/Title.php(4684): ContentHandler::getForTitle(Title)
#8 /usr/share/webapps/mediawiki/includes/parser/Parser.php(867): Title->getPageLanguage()
#9 /usr/share/webapps/mediawiki/includes/parser/Parser.php(2110): Parser->getTargetLanguage()
#10 /usr/share/webapps/mediawiki/includes/parser/Parser.php(2075): Parser->replaceInternalLinks2(string)
#11 /usr/share/webapps/mediawiki/includes/parser/Parser.php(1290): Parser->replaceInternalLinks(string)
#12 /usr/share/webapps/mediawiki/includes/parser/Parser.php(441): Parser->internalParse(string)
#13 /usr/share/webapps/mediawiki/includes/installer/Installer.php(675): Parser->parse(string, Title, ParserOptions, boolean)
#14 /usr/share/webapps/mediawiki/includes/installer/WebInstaller.php(681): Installer->parse(string, boolean)
#15 /usr/share/webapps/mediawiki/includes/installer/WebInstaller.php(657): WebInstaller->getInfoBox(string, string, string)
#16 /usr/share/webapps/mediawiki/includes/installer/WebInstaller.php(401): WebInstaller->getErrorBox(string)
#17 /usr/share/webapps/mediawiki/mw-config/index.php(54): WebInstaller->showError(Message, string)
#18 /usr/share/webapps/mediawiki/mw-config/index.php(38): wfInstallerMain()
#19 {main}

Body:
Regardless of what Tgr said above, fixing the sessions did fix the issue for me. I'm using Apache ITK so the resolution I use is slightly different since each virtual host runs under its own unique uid.

First I create a separate directory for the sessions and change ownership

mkdir /var/lib/php/sessions-wiki
chown wiki. /var/lib/php/sessions-wiki

Then in my VirtualHosts directive I tell Apache/php where to find the session files by adding

php_admin_value session.save_path "/var/lib/php/sessions-wiki"

Then to make sure your config didn't break it.

apachectl configtest

Finally reload your config

apachectl graceful


问:
Dependency upgrade hell. What is wrong with this CSS loader?
In dependency upgrade hell. Wondering if I can get a tip from anyone.

Been able to hammer everything out but one thing. I’m using CSS Modules with PostCSS on a project. I’m upgrading to Webpack 2 and taking the opportunity to also upgrade all other packages.

The issue I’m having is with one of the CSS processors. Basically any CSS file containing a composes property that loads a class from another file fails.

This is what the Webpack CSS loader looks like:

```<code>test: /\.css/,
exclude: /node_modules/,
use: [
    'style-loader',
    {
        loader: 'css-loader',
        options: {
            modules: true,
            localIdentName: '[folder]__[local]___[hash:base64:5]',
            importLoaders: 1
        }
    },
    'postcss-loader'
]
</code>```

When I try to load a page that uses a stylesheet with one of these composes I see this error in the browser error console:

```<code>Dynamic page loading failed TypeError: Cannot read property 'removeChild' of null
    at removeStyleElement (eval at ./node_modules/style-loader/addStyles.js (main.js:9858), <anonymous>:122:25)
    at remove (eval at ./node_modules/style-loader/addStyles.js (main.js:9858), <anonymous>:168:4)
    at Array.updateStyle (eval at ./node_modules/style-loader/addStyles.js (main.js:9858), <anonymous>:180:4)
    at addStylesToDom (eval at ./node_modules/style-loader/addStyles.js (main.js:9858), <anonymous>:69:22)
    at module.exports (eval at ./node_modules/style-loader/addStyles.js (main.js:9858), <anonymous>:37:2)
    at eval (eval at ./app/components/EntryGroup/styles.css (1.chunk.js:29), <anonymous>:7:77)
    at Object../app/components/EntryGroup/styles.css (1.chunk.js:29)
    at __webpack_require__ (main.js:687)
    at fn (main.js:106)
    at eval (eval at ./app/components/EntryGroup/index.js (1.chunk.js:22), <anonymous>:3:70)
</code>```

style-loader seems to be throwing the error, but I assume it’s because css-loader is letting something through that it shouldn’t. Other than that I’m not sure where to look.

Suggestions?

答: I'm using css modules and Webpack 2, and it was working fine until I tried to add new webpack.NamedModulesPlugin(). If you're using that, try removing it and seeing if css modules work

Body:
In dependency upgrade hell. Wondering if I can get a tip from anyone.

Been able to hammer everything out but one thing. I’m using CSS Modules with PostCSS on a project. I’m upgrading to Webpack 2 and taking the opportunity to also upgrade all other packages.

The issue I’m having is with one of the CSS processors. Basically any CSS file containing a composes property that loads a class from another file fails.

This is what the Webpack CSS loader looks like:

test: /\.css/,
exclude: /node_modules/,
use: [
    'style-loader',
    {
        loader: 'css-loader',
        options: {
            modules: true,
            localIdentName: '[folder]__[local]___[hash:base64:5]',
            importLoaders: 1
        }
    },
    'postcss-loader'
]

When I try to load a page that uses a stylesheet with one of these composes I see this error in the browser error console:

Dynamic page loading failed TypeError: Cannot read property 'removeChild' of null
    at removeStyleElement (eval at ./node_modules/style-loader/addStyles.js (main.js:9858), <anonymous>:122:25)
    at remove (eval at ./node_modules/style-loader/addStyles.js (main.js:9858), <anonymous>:168:4)
    at Array.updateStyle (eval at ./node_modules/style-loader/addStyles.js (main.js:9858), <anonymous>:180:4)
    at addStylesToDom (eval at ./node_modules/style-loader/addStyles.js (main.js:9858), <anonymous>:69:22)
    at module.exports (eval at ./node_modules/style-loader/addStyles.js (main.js:9858), <anonymous>:37:2)
    at eval (eval at ./app/components/EntryGroup/styles.css (1.chunk.js:29), <anonymous>:7:77)
    at Object../app/components/EntryGroup/styles.css (1.chunk.js:29)
    at __webpack_require__ (main.js:687)
    at fn (main.js:106)
    at eval (eval at ./app/components/EntryGroup/index.js (1.chunk.js:22), <anonymous>:3:70)

style-loader seems to be throwing the error, but I assume it’s because css-loader is letting something through that it shouldn’t. Other than that I’m not sure where to look.

Suggestions?


问:
Show File Download Progress in MB
I'm downloading a mp3 file from the internet and saving it into the internal storage. The progress of the download is shown in a ProgressDialog. The ProgressDialog displays the progress in percent which is fine. In the right it displays the progress as 1/100 .... I'd like it to display the current size of the file downloaded in MB / the total size of the file being downloaded in MB.

Like in the following picture. The grey text is the current text being displayed. I'd like it to be displayed like the text below it in red.

Here's the current code :

```<code>public class DownloadSKHindi extends AsyncTask<String, Integer, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("Downloading");
        progressDialog.setMax(100);
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        int count = 0;
        try {
            url = new URL(skURL[10]);

            connection = url.openConnection();
            connection.connect();

            int lengthOfFile = connection.getContentLength();

            InputStream input = new BufferedInputStream(url.openStream());

            OutputStream output = getActivity().openFileOutput(file.getPath(), Context.MODE_PRIVATE);

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;

                publishProgress((int) (total * 100 / lengthOfFile));
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressDialog.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        progressDialog.dismiss();
    }
}
</code>```

答:
Use TextView that is appended after progressDialog inside XML file.
Consider TextView tv = findViewById();

Use this: publishProgress((int) (total * 100 / lengthOfFile), total ,lengthOfFile); to push new data.

And to update the tv use this:

```<code> @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressDialog.setProgress(values[0]);
tv.setText((values[1]/(1024*1024)) + "" +(values[1]/(1024*1024)));
    }
</code>```

Title: Show File Download Progress in MB

Body:
I'm downloading a mp3 file from the internet and saving it into the internal storage. The progress of the download is shown in a ProgressDialog. The ProgressDialog displays the progress in percent which is fine. In the right it displays the progress as 1/100 .... I'd like it to display the current size of the file downloaded in MB / the total size of the file being downloaded in MB.

Like in the following picture. The grey text is the current text being displayed. I'd like it to be displayed like the text below it in red.

Here's the current code :

public class DownloadSKHindi extends AsyncTask<String, Integer, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("Downloading");
        progressDialog.setMax(100);
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        int count = 0;
        try {
            url = new URL(skURL[10]);

            connection = url.openConnection();
            connection.connect();

            int lengthOfFile = connection.getContentLength();

            InputStream input = new BufferedInputStream(url.openStream());

            OutputStream output = getActivity().openFileOutput(file.getPath(), Context.MODE_PRIVATE);

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;

                publishProgress((int) (total * 100 / lengthOfFile));
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressDialog.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        progressDialog.dismiss();
    }
}

Body:
Use TextView that is appended after progressDialog inside XML file.
Consider TextView tv = findViewById();

Use this: publishProgress((int) (total * 100 / lengthOfFile), total ,lengthOfFile); to push new data.

And to update the tv use this:

 @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressDialog.setProgress(values[0]);
tv.setText((values[1]/(1024*1024)) + "" +(values[1]/(1024*1024)));
    }


问:
Convert a byte array into an int array in java
Is there was a way to convert a hole array of bytes (lets say 1024) into an int array of total 256 integers without using something similar to this:</p>

```<code>int result = 0;
    result = b[0] & MASK;
    result = result + ((b[1] & MASK) << 8);
    result = result + ((b[2] & MASK) << 16);
    result = result + ((b[3] & MASK) << 24);
return result;
</code>```

答:
You can use Unsafe but probably shouldn't</p>

```<code>    try {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        UNSAFE = (Unsafe) theUnsafe.get(null);
    } catch (Exception e) {
        throw new AssertionError(e);
    }

    byte[] bytes = new byte[128];
    for (int i = 0; i < bytes.length; i++) bytes[i] = (byte) i;
    int[] ints = new int[bytes.length / Integer.BYTES];
    UNSAFE.copyMemory(bytes, Unsafe.ARRAY_BYTE_BASE_OFFSET, ints, Unsafe.ARRAY_INT_BASE_OFFSET, bytes.length);
    for (int i : ints)
        System.out.printf("%08x%n", i);
</code>```

Body:
Is there was a way to convert a hole array of bytes (lets say 1024) into an int array of total 256 integers without using something similar to this:

int result = 0;
    result = b[0] & MASK;
    result = result + ((b[1] & MASK) << 8);
    result = result + ((b[2] & MASK) << 16);
    result = result + ((b[3] & MASK) << 24);
return result;

Body:
You can use Unsafe but probably shouldn't

    try {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        UNSAFE = (Unsafe) theUnsafe.get(null);
    } catch (Exception e) {
        throw new AssertionError(e);
    }

    byte[] bytes = new byte[128];
    for (int i = 0; i < bytes.length; i++) bytes[i] = (byte) i;
    int[] ints = new int[bytes.length / Integer.BYTES];
    UNSAFE.copyMemory(bytes, Unsafe.ARRAY_BYTE_BASE_OFFSET, ints, Unsafe.ARRAY_INT_BASE_OFFSET, bytes.length);
    for (int i : ints)
        System.out.printf("%08x%n", i);


问:
Angular 2: No provider for (injected) service
I have two services in my app - MainService and RightClickService. Only MainService is accessible globally in the application, and RightClickService is injected to MainService. Therefore, I defined the following files as:

app.module.ts

```<code>@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [MainService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

RightClickService is not mentioned in app.module.ts.

service.ts

```<code> @Injectable()
 export class MainService {

  constructor(private rightClickService: RightClickService) {
    console.log("Constructor is init");
  }
}
</code>```

RightClickService exists only in one component named inside the big application RightClickComponent.

right-click.component.ts:

```<code>@Component({
  selector: 'right-click',
  template: `
    ...
  `,
  styleUrls: ['...'],
  providers: [RightClickService]
})
export class RightClickComponent implements OnInit {

  constructor(private rightClickService: RightClickService) {}

}
</code>```

Still, I get the error:

```<code>EXCEPTION: No provider for RightClickService!
</code>```

Do you know what I'm doing wrong?

答:
In addition to what already said, you must know two things:

Your app has only one root injector that contains all providers delcared in @NgModule.providers array of any module in your app including AppModule.

Each Component has its own injector (child injector of the root injector) that contains providers declared in @Component.providers array of the component.

when angular want to resolve dependencies (RightClickService) of a service (MainService) it looks for it in the root injector which contains providers of all NgModules.

When angular want to resolve dependencies (RightClickService) of a component (RightClickComponent) it looks for it in the component injector if not found it looks for it in the parent component injector if not found he will do the same until he reaches  the root injector if not found an error will be thrown.

if you want to solve the problem you can do this :

```<code>function MainServiceFactory(RightClickService) {
    return new MainService(new RightClickService());
}

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [
   {
     provide: MainService,
     useFactory: MainServiceFactory,
     deps: [RightClickService]
   }
],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Body:
I have two services in my app - MainService and RightClickService. Only MainService is accessible globally in the application, and RightClickService is injected to MainService. Therefore, I defined the following files as:

app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [MainService],
  bootstrap: [AppComponent]
})
export class AppModule { }

RightClickService is not mentioned in app.module.ts.

service.ts

 @Injectable()
 export class MainService {

  constructor(private rightClickService: RightClickService) {
    console.log("Constructor is init");
  }
}

RightClickService exists only in one component named inside the big application RightClickComponent.

right-click.component.ts:

@Component({
  selector: 'right-click',
  template: `
    ...
  `,
  styleUrls: ['...'],
  providers: [RightClickService]
})
export class RightClickComponent implements OnInit {

  constructor(private rightClickService: RightClickService) {}

}

Still, I get the error:

EXCEPTION: No provider for RightClickService!

Do you know what I'm doing wrong?

Body:
In addition to what already said, you must know two things:

Your app has only one root injector that contains all providers delcared in @NgModule.providers array of any module in your app including AppModule.

Each Component has its own injector (child injector of the root injector) that contains providers declared in @Component.providers array of the component.

when angular want to resolve dependencies (RightClickService) of a service (MainService) it looks for it in the root injector which contains providers of all NgModules.

When angular want to resolve dependencies (RightClickService) of a component (RightClickComponent) it looks for it in the component injector if not found it looks for it in the parent component injector if not found he will do the same until he reaches  the root injector if not found an error will be thrown.

if you want to solve the problem you can do this :

function MainServiceFactory(RightClickService) {
    return new MainService(new RightClickService());
}

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [
   {
     provide: MainService,
     useFactory: MainServiceFactory,
     deps: [RightClickService]
   }
],
  bootstrap: [AppComponent]
})
export class AppModule { }

ContentLicense: CC BY-SA 4.0


问:
Enable PHP's POSIX functions on Rackspace Cloud Sites
I use Rackspace Cloud Sites for web hosting.  I was trying to use a couple of the posix_* functions and noticed that they aren't available.  Using phpinfo() I was able to see that --disable-posix is part of the "Configure Command".  Also, the disable_functions directive has this string leak,posix_getpwuid,posix_getpwnam,posix_getgrid,posix_getgrnam,posix_getgroups.

Is there a way to override this using .htaccess? I didn't see any mention of it in the manual.

答:
No.  They are disabled for a reason.  That's the price you pay for using Rackspace Cloud Sites.  If you need to enable stuff and change configuration settings beyond what .htaccess allows you to do, you'll need to setup a Rackspace Cloud Server for your web hosting (which is not managed by Rackspace b.t.w.)

Edit: Though I should clarify what I meant by "not managed by Rackspace"... They manage the hardware, but not the software that goes on your server.  That's completely up to you.

ContentLicense: CC BY-SA 2.5


问:
Use latest version of Internet Explorer in the webbrowser control
The default version of the webbrowser control in a C# Windows Forms
application is 7. I have changed to 9 by the article Browser Emulation, but how is it possible to use the latest version of the installed Internet Explorer in a webbrowser control?

答:
I know this has been posted but here is a current version for dotnet 4.5 above that I use. I recommend to use the default browser emulation respecting doctype

InternetExplorerFeatureControl.Instance.BrowserEmulation = DocumentMode.DefaultRespectDocType;

```<code>internal class InternetExplorerFeatureControl
{
    private static readonly Lazy<InternetExplorerFeatureControl> LazyInstance = new Lazy<InternetExplorerFeatureControl>(() => new InternetExplorerFeatureControl());
    private const string RegistryLocation = @"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl";
    private readonly RegistryView _registryView = Environment.Is64BitOperatingSystem && Environment.Is64BitProcess ? RegistryView.Registry64 : RegistryView.Registry32;
    private readonly string _processName;
    private readonly Version _version;

    #region Feature Control Strings (A)

    private const string FeatureRestrictAboutProtocolIe7 = @"FEATURE_RESTRICT_ABOUT_PROTOCOL_IE7";
    private const string FeatureRestrictAboutProtocol = @"FEATURE_RESTRICT_ABOUT_PROTOCOL";

    #endregion

    #region Feature Control Strings (B)

    private const string FeatureBrowserEmulation = @"FEATURE_BROWSER_EMULATION";

    #endregion

    #region Feature Control Strings (G)

    private const string FeatureGpuRendering = @"FEATURE_GPU_RENDERING";

    #endregion

    #region Feature Control Strings (L)

    private const string FeatureBlockLmzScript = @"FEATURE_BLOCK_LMZ_SCRIPT";

    #endregion

    internal InternetExplorerFeatureControl()
    {
        _processName = $"{Process.GetCurrentProcess().ProcessName}.exe";
        using (var webBrowser = new WebBrowser())
            _version = webBrowser.Version;
    }

    internal static InternetExplorerFeatureControl Instance => LazyInstance.Value;

    internal RegistryHive RegistryHive { get; set; } = RegistryHive.CurrentUser;

    private int GetFeatureControl(string featureControl)
    {
        using (var currentUser = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, _registryView))
        {
            using (var key = currentUser.CreateSubKey($"{RegistryLocation}\\{featureControl}", false))
            {
                if (key.GetValue(_processName) is int value)
                {
                    return value;
                }
                return -1;
            }
        }
    }

    private void SetFeatureControl(string featureControl, int value)
    {
        using (var currentUser = RegistryKey.OpenBaseKey(RegistryHive, _registryView))
        {
            using (var key = currentUser.CreateSubKey($"{RegistryLocation}\\{featureControl}", true))
            {
                key.SetValue(_processName, value, RegistryValueKind.DWord);
            }
        }
    }

    #region Internet Feature Controls (A)

    /// <summary>
    /// Windows Internet Explorer 8 and later. When enabled, feature disables the "about:" protocol. For security reasons, applications that host the WebBrowser Control are strongly encouraged to enable this feature.
    /// By default, this feature is enabled for Windows Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature using the registry, add the name of your executable file to the following setting.
    /// </summary>
    internal bool AboutProtocolRestriction
    {
        get
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{AboutProtocolRestriction} requires Internet Explorer 8 and Later.");
            var releaseVersion = new Version(8, 0, 6001, 18702);
            return Convert.ToBoolean(GetFeatureControl(_version >= releaseVersion ? FeatureRestrictAboutProtocolIe7 : FeatureRestrictAboutProtocol));
        }
        set
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{AboutProtocolRestriction} requires Internet Explorer 8 and Later.");
            var releaseVersion = new Version(8, 0, 6001, 18702);
            SetFeatureControl(_version >= releaseVersion ? FeatureRestrictAboutProtocolIe7 : FeatureRestrictAboutProtocol, Convert.ToInt16(value));
        }
    }

    #endregion

    #region Internet Feature Controls (B)

    /// <summary>
    /// Windows Internet Explorer 8 and later. Defines the default emulation mode for Internet Explorer and supports the following values.
    /// </summary>
    internal DocumentMode BrowserEmulation
    {
        get
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{nameof(BrowserEmulation)} requires Internet Explorer 8 and Later.");
            var value = GetFeatureControl(FeatureBrowserEmulation);
            if (Enum.IsDefined(typeof(DocumentMode), value))
            {
                return (DocumentMode)value;
            }
            return DocumentMode.NotSet;
        }
        set
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{nameof(BrowserEmulation)} requires Internet Explorer 8 and Later.");
            var tmp = value;
            if (value == DocumentMode.DefaultRespectDocType)
                tmp = DefaultRespectDocType;
            else if (value == DocumentMode.DefaultOverrideDocType)
                tmp = DefaultOverrideDocType;
            SetFeatureControl(FeatureBrowserEmulation, (int)tmp);
        }
    }

    #endregion

    #region Internet Feature Controls (G)

    /// <summary>
    /// Internet Explorer 9. Enables Internet Explorer to use a graphics processing unit (GPU) to render content. This dramatically improves performance for webpages that are rich in graphics.
    /// By default, this feature is enabled for Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature by using the registry, add the name of your executable file to the following setting.
    /// Note: GPU rendering relies heavily on the quality of your video drivers. If you encounter problems running Internet Explorer with GPU rendering enabled, you should verify that your video drivers are up to date and that they support hardware accelerated graphics.
    /// </summary>
    internal bool GpuRendering
    {
        get
        {
            if (_version.Major < 9)
                throw new NotSupportedException($"{nameof(GpuRendering)} requires Internet Explorer 9 and Later.");
            return Convert.ToBoolean(GetFeatureControl(FeatureGpuRendering));
        }
        set
        {
            if (_version.Major < 9)
                throw new NotSupportedException($"{nameof(GpuRendering)} requires Internet Explorer 9 and Later.");
            SetFeatureControl(FeatureGpuRendering, Convert.ToInt16(value));
        }
    }

    #endregion

    #region Internet Feature Controls (L)

    /// <summary>
    /// Internet Explorer 7 and later. When enabled, feature allows scripts stored in the Local Machine zone to be run only in webpages loaded from the Local Machine zone or by webpages hosted by sites in the Trusted Sites list. For more information, see Security and Compatibility in Internet Explorer 7.
    /// By default, this feature is enabled for Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature by using the registry, add the name of your executable file to the following setting.
    /// </summary>
    internal bool LocalScriptBlocking
    {
        get
        {
            if (_version.Major < 7)
                throw new NotSupportedException($"{nameof(LocalScriptBlocking)} requires Internet Explorer 7 and Later.");
            return Convert.ToBoolean(GetFeatureControl(FeatureBlockLmzScript));
        }
        set
        {
            if (_version.Major < 7)
                throw new NotSupportedException($"{nameof(LocalScriptBlocking)} requires Internet Explorer 7 and Later.");
            SetFeatureControl(FeatureBlockLmzScript, Convert.ToInt16(value));
        }
    }

    #endregion

    private DocumentMode DefaultRespectDocType
    {
        get
        {
            if (_version.Major >= 11)
                return DocumentMode.InternetExplorer11RespectDocType;
            switch (_version.Major)
            {
                case 10:
                    return DocumentMode.InternetExplorer10RespectDocType;
                case 9:
                    return DocumentMode.InternetExplorer9RespectDocType;
                case 8:
                    return DocumentMode.InternetExplorer8RespectDocType;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }

    private DocumentMode DefaultOverrideDocType
    {
        get
        {
            if (_version.Major >= 11)
                return DocumentMode.InternetExplorer11OverrideDocType;
            switch (_version.Major)
            {
                case 10:
                    return DocumentMode.InternetExplorer10OverrideDocType;
                case 9:
                    return DocumentMode.InternetExplorer9OverrideDocType;
                case 8:
                    return DocumentMode.InternetExplorer8OverrideDocType;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }
}

internal enum DocumentMode
{
    NotSet = -1,
    [Description("Webpages containing standards-based !DOCTYPE directives are displayed in IE latest installed version mode.")]
    DefaultRespectDocType,
    [Description("Webpages are displayed in IE latest installed version mode, regardless of the declared !DOCTYPE directive.  Failing to declare a !DOCTYPE directive could causes the page to load in Quirks.")]
    DefaultOverrideDocType,
    [Description(
        "Internet Explorer 11. Webpages are displayed in IE11 edge mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
    )] InternetExplorer11OverrideDocType = 11001,

    [Description(
        "IE11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 edge mode. Default value for IE11."
    )] InternetExplorer11RespectDocType = 11000,

    [Description(
        "Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive."
    )] InternetExplorer10OverrideDocType = 10001,

    [Description(
        "Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10."
    )] InternetExplorer10RespectDocType = 10000,

    [Description(
        "Windows Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
    )] InternetExplorer9OverrideDocType = 9999,

    [Description(
        "Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode. Default value for Internet Explorer 9.\r\n" +
        "Important  In Internet Explorer 10, Webpages containing standards - based !DOCTYPE directives are displayed in IE10 Standards mode."
    )] InternetExplorer9RespectDocType = 9000,

    [Description(
        "Webpages are displayed in IE8 Standards mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
    )] InternetExplorer8OverrideDocType = 8888,

    [Description(
        "Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. Default value for Internet Explorer 8\r\n" +
        "Important  In Internet Explorer 10, Webpages containing standards - based !DOCTYPE directives are displayed in IE10 Standards mode."
    )] InternetExplorer8RespectDocType = 8000,

    [Description(
        "Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode. Default value for applications hosting the WebBrowser Control."
    )] InternetExplorer7RespectDocType = 7000
}
</code>```

Body:
I know this has been posted but here is a current version for dotnet 4.5 above that I use. I recommend to use the default browser emulation respecting doctype

InternetExplorerFeatureControl.Instance.BrowserEmulation = DocumentMode.DefaultRespectDocType;

internal class InternetExplorerFeatureControl
{
    private static readonly Lazy<InternetExplorerFeatureControl> LazyInstance = new Lazy<InternetExplorerFeatureControl>(() => new InternetExplorerFeatureControl());
    private const string RegistryLocation = @"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl";
    private readonly RegistryView _registryView = Environment.Is64BitOperatingSystem && Environment.Is64BitProcess ? RegistryView.Registry64 : RegistryView.Registry32;
    private readonly string _processName;
    private readonly Version _version;

    #region Feature Control Strings (A)

    private const string FeatureRestrictAboutProtocolIe7 = @"FEATURE_RESTRICT_ABOUT_PROTOCOL_IE7";
    private const string FeatureRestrictAboutProtocol = @"FEATURE_RESTRICT_ABOUT_PROTOCOL";

    #endregion

    #region Feature Control Strings (B)

    private const string FeatureBrowserEmulation = @"FEATURE_BROWSER_EMULATION";

    #endregion

    #region Feature Control Strings (G)

    private const string FeatureGpuRendering = @"FEATURE_GPU_RENDERING";

    #endregion

    #region Feature Control Strings (L)

    private const string FeatureBlockLmzScript = @"FEATURE_BLOCK_LMZ_SCRIPT";

    #endregion

    internal InternetExplorerFeatureControl()
    {
        _processName = $"{Process.GetCurrentProcess().ProcessName}.exe";
        using (var webBrowser = new WebBrowser())
            _version = webBrowser.Version;
    }

    internal static InternetExplorerFeatureControl Instance => LazyInstance.Value;

    internal RegistryHive RegistryHive { get; set; } = RegistryHive.CurrentUser;

    private int GetFeatureControl(string featureControl)
    {
        using (var currentUser = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, _registryView))
        {
            using (var key = currentUser.CreateSubKey($"{RegistryLocation}\\{featureControl}", false))
            {
                if (key.GetValue(_processName) is int value)
                {
                    return value;
                }
                return -1;
            }
        }
    }

    private void SetFeatureControl(string featureControl, int value)
    {
        using (var currentUser = RegistryKey.OpenBaseKey(RegistryHive, _registryView))
        {
            using (var key = currentUser.CreateSubKey($"{RegistryLocation}\\{featureControl}", true))
            {
                key.SetValue(_processName, value, RegistryValueKind.DWord);
            }
        }
    }

    #region Internet Feature Controls (A)

    /// <summary>
    /// Windows Internet Explorer 8 and later. When enabled, feature disables the "about:" protocol. For security reasons, applications that host the WebBrowser Control are strongly encouraged to enable this feature.
    /// By default, this feature is enabled for Windows Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature using the registry, add the name of your executable file to the following setting.
    /// </summary>
    internal bool AboutProtocolRestriction
    {
        get
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{AboutProtocolRestriction} requires Internet Explorer 8 and Later.");
            var releaseVersion = new Version(8, 0, 6001, 18702);
            return Convert.ToBoolean(GetFeatureControl(_version >= releaseVersion ? FeatureRestrictAboutProtocolIe7 : FeatureRestrictAboutProtocol));
        }
        set
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{AboutProtocolRestriction} requires Internet Explorer 8 and Later.");
            var releaseVersion = new Version(8, 0, 6001, 18702);
            SetFeatureControl(_version >= releaseVersion ? FeatureRestrictAboutProtocolIe7 : FeatureRestrictAboutProtocol, Convert.ToInt16(value));
        }
    }

    #endregion

    #region Internet Feature Controls (B)

    /// <summary>
    /// Windows Internet Explorer 8 and later. Defines the default emulation mode for Internet Explorer and supports the following values.
    /// </summary>
    internal DocumentMode BrowserEmulation
    {
        get
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{nameof(BrowserEmulation)} requires Internet Explorer 8 and Later.");
            var value = GetFeatureControl(FeatureBrowserEmulation);
            if (Enum.IsDefined(typeof(DocumentMode), value))
            {
                return (DocumentMode)value;
            }
            return DocumentMode.NotSet;
        }
        set
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{nameof(BrowserEmulation)} requires Internet Explorer 8 and Later.");
            var tmp = value;
            if (value == DocumentMode.DefaultRespectDocType)
                tmp = DefaultRespectDocType;
            else if (value == DocumentMode.DefaultOverrideDocType)
                tmp = DefaultOverrideDocType;
            SetFeatureControl(FeatureBrowserEmulation, (int)tmp);
        }
    }

    #endregion

    #region Internet Feature Controls (G)

    /// <summary>
    /// Internet Explorer 9. Enables Internet Explorer to use a graphics processing unit (GPU) to render content. This dramatically improves performance for webpages that are rich in graphics.
    /// By default, this feature is enabled for Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature by using the registry, add the name of your executable file to the following setting.
    /// Note: GPU rendering relies heavily on the quality of your video drivers. If you encounter problems running Internet Explorer with GPU rendering enabled, you should verify that your video drivers are up to date and that they support hardware accelerated graphics.
    /// </summary>
    internal bool GpuRendering
    {
        get
        {
            if (_version.Major < 9)
                throw new NotSupportedException($"{nameof(GpuRendering)} requires Internet Explorer 9 and Later.");
            return Convert.ToBoolean(GetFeatureControl(FeatureGpuRendering));
        }
        set
        {
            if (_version.Major < 9)
                throw new NotSupportedException($"{nameof(GpuRendering)} requires Internet Explorer 9 and Later.");
            SetFeatureControl(FeatureGpuRendering, Convert.ToInt16(value));
        }
    }

    #endregion

    #region Internet Feature Controls (L)

    /// <summary>
    /// Internet Explorer 7 and later. When enabled, feature allows scripts stored in the Local Machine zone to be run only in webpages loaded from the Local Machine zone or by webpages hosted by sites in the Trusted Sites list. For more information, see Security and Compatibility in Internet Explorer 7.
    /// By default, this feature is enabled for Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature by using the registry, add the name of your executable file to the following setting.
    /// </summary>
    internal bool LocalScriptBlocking
    {
        get
        {
            if (_version.Major < 7)
                throw new NotSupportedException($"{nameof(LocalScriptBlocking)} requires Internet Explorer 7 and Later.");
            return Convert.ToBoolean(GetFeatureControl(FeatureBlockLmzScript));
        }
        set
        {
            if (_version.Major < 7)
                throw new NotSupportedException($"{nameof(LocalScriptBlocking)} requires Internet Explorer 7 and Later.");
            SetFeatureControl(FeatureBlockLmzScript, Convert.ToInt16(value));
        }
    }

    #endregion

    private DocumentMode DefaultRespectDocType
    {
        get
        {
            if (_version.Major >= 11)
                return DocumentMode.InternetExplorer11RespectDocType;
            switch (_version.Major)
            {
                case 10:
                    return DocumentMode.InternetExplorer10RespectDocType;
                case 9:
                    return DocumentMode.InternetExplorer9RespectDocType;
                case 8:
                    return DocumentMode.InternetExplorer8RespectDocType;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }

    private DocumentMode DefaultOverrideDocType
    {
        get
        {
            if (_version.Major >= 11)
                return DocumentMode.InternetExplorer11OverrideDocType;
            switch (_version.Major)
            {
                case 10:
                    return DocumentMode.InternetExplorer10OverrideDocType;
                case 9:
                    return DocumentMode.InternetExplorer9OverrideDocType;
                case 8:
                    return DocumentMode.InternetExplorer8OverrideDocType;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }
}

internal enum DocumentMode
{
    NotSet = -1,
    [Description("Webpages containing standards-based !DOCTYPE directives are displayed in IE latest installed version mode.")]
    DefaultRespectDocType,
    [Description("Webpages are displayed in IE latest installed version mode, regardless of the declared !DOCTYPE directive.  Failing to declare a !DOCTYPE directive could causes the page to load in Quirks.")]
    DefaultOverrideDocType,
    [Description(
        "Internet Explorer 11. Webpages are displayed in IE11 edge mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
    )] InternetExplorer11OverrideDocType = 11001,

    [Description(
        "IE11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 edge mode. Default value for IE11."
    )] InternetExplorer11RespectDocType = 11000,

    [Description(
        "Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive."
    )] InternetExplorer10OverrideDocType = 10001,

    [Description(
        "Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10."
    )] InternetExplorer10RespectDocType = 10000,

    [Description(
        "Windows Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
    )] InternetExplorer9OverrideDocType = 9999,

    [Description(
        "Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode. Default value for Internet Explorer 9.\r\n" +
        "Important  In Internet Explorer 10, Webpages containing standards - based !DOCTYPE directives are displayed in IE10 Standards mode."
    )] InternetExplorer9RespectDocType = 9000,

    [Description(
        "Webpages are displayed in IE8 Standards mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
    )] InternetExplorer8OverrideDocType = 8888,

    [Description(
        "Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. Default value for Internet Explorer 8\r\n" +
        "Important  In Internet Explorer 10, Webpages containing standards - based !DOCTYPE directives are displayed in IE10 Standards mode."
    )] InternetExplorer8RespectDocType = 8000,

    [Description(
        "Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode. Default value for applications hosting the WebBrowser Control."
    )] InternetExplorer7RespectDocType = 7000
}


问:
Automated fsck (with init 1/init 5) on a FreeBSD machine?
I'm looking to automated fsck on my FreeBSD server. I have an idea how to do this, but because it's running pretty powerful commands, I'd like some more eyes on it before I set it to run.

Step 1. Cron job.
My cron will look something like this: 0 17 * * 0 myfsckscript.sh > /usr/local/var/log/fscklog/$(date).log, to run at 5PM every sunday. It will be run from root's crontab, because what I'm doing requires root permissions.

The script goes something like this:

```<code>init 1 # Run single-user mode, so fsck can run correctly
fsck -y # Run fsck
fsck -y # Run again, to clean up. Makes my machine act better
init 5 # bring it back up.
</code>```

My main concerns follow:

Does running this pose any substantial dangers I should know about?

Are there any errors in my script?

Anything I should add?

Did I actually get it right?

I'm sorry this is mostly a confirmation question, but with my level of skill with sh I'm not comfortable setting this to run without someone more experienced taking a look first.

答:
What about just add this to /etc/rc.conf:

```<code>fsck_y_enable="YES"
background_fsck="NO"
</code>```

Basically, means to run fsck -y and don't try to run in background, so depending on the size of your disks, this could take a while to finish.

Body:
I'm looking to automated fsck on my FreeBSD server. I have an idea how to do this, but because it's running pretty powerful commands, I'd like some more eyes on it before I set it to run.

Step 1. Cron job.
My cron will look something like this: 0 17 * * 0 myfsckscript.sh > /usr/local/var/log/fscklog/$(date).log, to run at 5PM every sunday. It will be run from root's crontab, because what I'm doing requires root permissions.

The script goes something like this:

init 1 # Run single-user mode, so fsck can run correctly
fsck -y # Run fsck
fsck -y # Run again, to clean up. Makes my machine act better
init 5 # bring it back up.

My main concerns follow:

Does running this pose any substantial dangers I should know about?

Are there any errors in my script?

Anything I should add?

Did I actually get it right?

I'm sorry this is mostly a confirmation question, but with my level of skill with sh I'm not comfortable setting this to run without someone more experienced taking a look first.

Body:
What about just add this to /etc/rc.conf:

fsck_y_enable="YES"
background_fsck="NO"

Basically, means to run fsck -y and don't try to run in background, so depending on the size of your disks, this could take a while to finish.


问:
Object reference not set to an instance of an object C# Unity tutorial
I am working on creating a game using the 2D rouge-like tutorial provided by unity. Everything works as expected thus far apart from movement. When the game runs a single error appears.

"NullReferenceException: object reference not set to an instance of an object completed.player.start () (at Assets/Completed/Scripts/Player.cs:39) "

This is the line of code causing the error:
healthText.text = "Health: " + health;

The code for the entire script is below:

```<code>using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using UnityEngine.UI;   //Allows us to use UI.

namespace Completed
    {
    //Player inherits from MovingObject, our base class for objects that can move, Enemy also inherits from this.
    public class Player : MovingObject
    {
        public float restartLevelDelay = 1f;        //Delay time in seconds to restart level.
        public int pointsPerGoodFood = 10;          //Number of points to add to player health points when picking up a GoodFood object.
        public int pointsPerOkayFood = 20;          //Number of points to add to player health points when picking up a OkayFood object.
        public int wallDamage = 1;                  //How much damage a player does to a wall when attacking it.
        public Text healthText;                     //UI Text to display current player health total.
        public AudioClip moveSound1;                //1 of 2 Audio clips to play when player moves.
        public AudioClip moveSound2;                //2 of 2 Audio clips to play when player moves.
        public AudioClip eatSound1;                 //1 of 4 Audio clips to play when player collects a GoodFood object.
        public AudioClip eatSound2;                 //2 of 4 Audio clips to play when player collects a GoodFood object.
        public AudioClip eatSound3;                 //3 of 4 Audio clips to play when player collects a OkayFood object.
        public AudioClip eatSound4;                 //4 of 4 Audio clips to play when player collects a OkayFood object.
        public AudioClip gameOverSound;             //Audio clip to play when player dies.

        private Animator animator;                  //Used to store a reference to the Player's animator component.
        private int health;                         //Used to store player health points total during level.

        //Start overrides the Start function of MovingObject
        protected override void Start ()
        {
            //Get a component reference to the Player's animator component
            animator = GetComponent<Animator>();

            //Get the current health point total stored in GameManager.instance between levels.
            health = GameManager.instance.playerHealthPoints;

            //Set the foodText to reflect the current player health total.
            healthText.text = "Health: " + health;

            //Call the Start function of the MovingObject base class.
            base.Start ();
        }

        //This function is called when the behaviour becomes disabled or inactive.
        private void OnDisable ()
        {
            //When Player object is disabled, store the current local health total in the GameManager so it can be re-loaded in next level.
            GameManager.instance.playerHealthPoints = health;
        }

        private void Update ()
        {
            //If it's not the player's turn, exit the function.
            if(!GameManager.instance.playersTurn) return;

            int horizontal = 0;     //Used to store the horizontal move direction.
            int vertical = 0;       //Used to store the vertical move direction.

            //Check if we are running either in the Unity editor or in a standalone build.
            #if UNITY_STANDALONE || UNITY_WEBPLAYER

            //Get input from the input manager, round it to an integer and store in horizontal to set x axis move direction
            horizontal = (int) (Input.GetAxisRaw ("Horizontal"));

            //Get input from the input manager, round it to an integer and store in vertical to set y axis move direction
            vertical = (int) (Input.GetAxisRaw ("Vertical"));

            //Check if moving horizontally, if so set vertical to zero.
            if(horizontal != 0)
            {
                vertical = 0;
            }

            //Check if we have a non-zero value for horizontal or vertical
            if (horizontal != 0 || vertical != 0)
            {
                //Call AttemptMove passing in the generic parameter Wall, since that is what Player may interact with if they encounter one (by attacking it)
                //Pass in horizontal and vertical as parameters to specify the direction to move Player in.
                AttemptMove<Wall> (horizontal, vertical);
            }
        }

        //AttemptMove overrides the AttemptMove function in the base class MovingObject
        //AttemptMove takes a generic parameter T which for Player will be of the type Wall, it also takes integers for x and y direction to move in.
        protected override void AttemptMove <T> (int xDir, int yDir)
        {
            //Every time player moves, subtract from health points total.
            health--;

            //Update health text display to reflect current score.
            healthText.text = "Health: " + health;

            //Call the AttemptMove method of the base class, passing in the component T (in this case Wall) and x and y direction to move.
            base.AttemptMove <T> (xDir, yDir);

            //Hit allows us to reference the result of the Linecast done in Move.
            RaycastHit2D hit;

            //If Move returns true, meaning Player was able to move into an empty space.
            if (Move (xDir, yDir, out hit))
            {
                //Call RandomizeSfx of SoundManager to play the move sound, passing in two audio clips to choose from.
                SoundManager.instance.RandomizeSfx (moveSound1, moveSound2);
            }

            //Since the player has moved and lost health points, check if the game has ended.
            CheckIfGameOver ();

            //Set the playersTurn boolean of GameManager to false now that players turn is over.
            GameManager.instance.playersTurn = false;
        }

        //OnCantMove overrides the abstract function OnCantMove in MovingObject.
        //It takes a generic parameter T which in the case of Player is a Wall which the player can attack and destroy.
        protected override void OnCantMove <T> (T component)
        {
            //Set hitWall to equal the component passed in as a parameter.
            Wall hitWall = component as Wall;

            //Call the DamageWall function of the Wall we are hitting.
            hitWall.DamageWall (wallDamage);

            //Set the attack trigger of the player's animation controller in order to play the player's attack animation.
            animator.SetTrigger ("playerAttack");
        }

        //OnTriggerEnter2D is sent when another object enters a trigger collider attached to this object (2D physics only).
        private void OnTriggerEnter2D (Collider2D other)
        {
            //Check if the tag of the trigger collided with is Exit.
            if(other.tag == "Exit")
            {
                //Invoke the Restart function to start the next level with a delay of restartLevelDelay (default 1 second).
                Invoke ("Restart", restartLevelDelay);

                //Disable the player object since level is over.
                enabled = false;
            }

            //Check if the tag of the trigger collided with is GoodFood.
            else if(other.tag == "GoodFood")
            {
                //Add pointsPerGoodFood to the players current health total.
                health += pointsPerGoodFood;

                //Update healthText to represent current total and notify player that they gained points
                healthText.text = "+" + pointsPerGoodFood + " Health: " + health;

                //Call the RandomizeSfx function of SoundManager and pass in two eating sounds to choose between to play the eating sound effect.
                SoundManager.instance.RandomizeSfx (eatSound1, eatSound2);

                //Disable the GoodFood object the player collided with.
                other.gameObject.SetActive (false);
            }

            //Check if the tag of the trigger collided with is OkayFood.
            else if(other.tag == "OkayFood")
            {
                //Add pointsPerOkayFood to players health points total
                health += pointsPerOkayFood;

                //Update healthText to represent current total and notify player that they gained points
                healthText.text = "+" + pointsPerOkayFood + " Health: " + health;

                //Call the RandomizeSfx function of SoundManager and pass in two eating sounds to choose between to play the eating sound effect.
                SoundManager.instance.RandomizeSfx (eatSound3, eatSound4);

                //Disable the OkayFood object the player collided with.
                other.gameObject.SetActive (false);
            }
        }

        //Restart reloads the scene when called.
        private void Restart ()
        {
            //Load the last scene loaded, in this case Main, the only scene in the game.
            SceneManager.LoadScene(0);
        }

        //LoseHealth is called when an enemy attacks the player.
        //It takes a parameter loss which specifies how many points to lose.
        public void LoseHealth (int loss)
        {
            //Set the trigger for the player animator to transition to the playerHit animation.
            animator.SetTrigger ("playerHit");

            //Subtract lost health points from the players total.
            health -= loss;

            //Update the health display with the new total.
            healthText.text = "-"+ loss + " Health: " + health;

            //Check to see if game has ended.
            CheckIfGameOver ();
        }

        //CheckIfGameOver checks if the player is out of health points and if so, ends the game.
        private void CheckIfGameOver ()
        {
            //Check if health point total is less than or equal to zero.
            if (health <= 0)
            {
                //Call the PlaySingle function of SoundManager and pass it the gameOverSound as the audio clip to play.
                SoundManager.instance.PlaySingle (gameOverSound);

                //Stop the background music.
                SoundManager.instance.musicSource.Stop();

                //Call the GameOver function of GameManager.
                GameManager.instance.GameOver ();
            }
        }
    }
}
</code>```

答: Check in the inspector if the healthText variable is linked to a UI text object. The link must be not set (None) or otherwise broken (Missing) if you are getting this exception.

Body:
I am working on creating a game using the 2D rouge-like tutorial provided by unity. Everything works as expected thus far apart from movement. When the game runs a single error appears.

"NullReferenceException: object reference not set to an instance of an object completed.player.start () (at Assets/Completed/Scripts/Player.cs:39) "

This is the line of code causing the error:
healthText.text = "Health: " + health;

The code for the entire script is below:

using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using UnityEngine.UI;   //Allows us to use UI.

namespace Completed
    {
    //Player inherits from MovingObject, our base class for objects that can move, Enemy also inherits from this.
    public class Player : MovingObject
    {
        public float restartLevelDelay = 1f;        //Delay time in seconds to restart level.
        public int pointsPerGoodFood = 10;          //Number of points to add to player health points when picking up a GoodFood object.
        public int pointsPerOkayFood = 20;          //Number of points to add to player health points when picking up a OkayFood object.
        public int wallDamage = 1;                  //How much damage a player does to a wall when attacking it.
        public Text healthText;                     //UI Text to display current player health total.
        public AudioClip moveSound1;                //1 of 2 Audio clips to play when player moves.
        public AudioClip moveSound2;                //2 of 2 Audio clips to play when player moves.
        public AudioClip eatSound1;                 //1 of 4 Audio clips to play when player collects a GoodFood object.
        public AudioClip eatSound2;                 //2 of 4 Audio clips to play when player collects a GoodFood object.
        public AudioClip eatSound3;                 //3 of 4 Audio clips to play when player collects a OkayFood object.
        public AudioClip eatSound4;                 //4 of 4 Audio clips to play when player collects a OkayFood object.
        public AudioClip gameOverSound;             //Audio clip to play when player dies.

        private Animator animator;                  //Used to store a reference to the Player's animator component.
        private int health;                         //Used to store player health points total during level.

        //Start overrides the Start function of MovingObject
        protected override void Start ()
        {
            //Get a component reference to the Player's animator component
            animator = GetComponent<Animator>();

            //Get the current health point total stored in GameManager.instance between levels.
            health = GameManager.instance.playerHealthPoints;

            //Set the foodText to reflect the current player health total.
            healthText.text = "Health: " + health;

            //Call the Start function of the MovingObject base class.
            base.Start ();
        }

        //This function is called when the behaviour becomes disabled or inactive.
        private void OnDisable ()
        {
            //When Player object is disabled, store the current local health total in the GameManager so it can be re-loaded in next level.
            GameManager.instance.playerHealthPoints = health;
        }

        private void Update ()
        {
            //If it's not the player's turn, exit the function.
            if(!GameManager.instance.playersTurn) return;

            int horizontal = 0;     //Used to store the horizontal move direction.
            int vertical = 0;       //Used to store the vertical move direction.

            //Check if we are running either in the Unity editor or in a standalone build.
            #if UNITY_STANDALONE || UNITY_WEBPLAYER

            //Get input from the input manager, round it to an integer and store in horizontal to set x axis move direction
            horizontal = (int) (Input.GetAxisRaw ("Horizontal"));

            //Get input from the input manager, round it to an integer and store in vertical to set y axis move direction
            vertical = (int) (Input.GetAxisRaw ("Vertical"));

            //Check if moving horizontally, if so set vertical to zero.
            if(horizontal != 0)
            {
                vertical = 0;
            }

            //Check if we have a non-zero value for horizontal or vertical
            if (horizontal != 0 || vertical != 0)
            {
                //Call AttemptMove passing in the generic parameter Wall, since that is what Player may interact with if they encounter one (by attacking it)
                //Pass in horizontal and vertical as parameters to specify the direction to move Player in.
                AttemptMove<Wall> (horizontal, vertical);
            }
        }

        //AttemptMove overrides the AttemptMove function in the base class MovingObject
        //AttemptMove takes a generic parameter T which for Player will be of the type Wall, it also takes integers for x and y direction to move in.
        protected override void AttemptMove <T> (int xDir, int yDir)
        {
            //Every time player moves, subtract from health points total.
            health--;

            //Update health text display to reflect current score.
            healthText.text = "Health: " + health;

            //Call the AttemptMove method of the base class, passing in the component T (in this case Wall) and x and y direction to move.
            base.AttemptMove <T> (xDir, yDir);

            //Hit allows us to reference the result of the Linecast done in Move.
            RaycastHit2D hit;

            //If Move returns true, meaning Player was able to move into an empty space.
            if (Move (xDir, yDir, out hit))
            {
                //Call RandomizeSfx of SoundManager to play the move sound, passing in two audio clips to choose from.
                SoundManager.instance.RandomizeSfx (moveSound1, moveSound2);
            }

            //Since the player has moved and lost health points, check if the game has ended.
            CheckIfGameOver ();

            //Set the playersTurn boolean of GameManager to false now that players turn is over.
            GameManager.instance.playersTurn = false;
        }

        //OnCantMove overrides the abstract function OnCantMove in MovingObject.
        //It takes a generic parameter T which in the case of Player is a Wall which the player can attack and destroy.
        protected override void OnCantMove <T> (T component)
        {
            //Set hitWall to equal the component passed in as a parameter.
            Wall hitWall = component as Wall;

            //Call the DamageWall function of the Wall we are hitting.
            hitWall.DamageWall (wallDamage);

            //Set the attack trigger of the player's animation controller in order to play the player's attack animation.
            animator.SetTrigger ("playerAttack");
        }

        //OnTriggerEnter2D is sent when another object enters a trigger collider attached to this object (2D physics only).
        private void OnTriggerEnter2D (Collider2D other)
        {
            //Check if the tag of the trigger collided with is Exit.
            if(other.tag == "Exit")
            {
                //Invoke the Restart function to start the next level with a delay of restartLevelDelay (default 1 second).
                Invoke ("Restart", restartLevelDelay);

                //Disable the player object since level is over.
                enabled = false;
            }

            //Check if the tag of the trigger collided with is GoodFood.
            else if(other.tag == "GoodFood")
            {
                //Add pointsPerGoodFood to the players current health total.
                health += pointsPerGoodFood;

                //Update healthText to represent current total and notify player that they gained points
                healthText.text = "+" + pointsPerGoodFood + " Health: " + health;

                //Call the RandomizeSfx function of SoundManager and pass in two eating sounds to choose between to play the eating sound effect.
                SoundManager.instance.RandomizeSfx (eatSound1, eatSound2);

                //Disable the GoodFood object the player collided with.
                other.gameObject.SetActive (false);
            }

            //Check if the tag of the trigger collided with is OkayFood.
            else if(other.tag == "OkayFood")
            {
                //Add pointsPerOkayFood to players health points total
                health += pointsPerOkayFood;

                //Update healthText to represent current total and notify player that they gained points
                healthText.text = "+" + pointsPerOkayFood + " Health: " + health;

                //Call the RandomizeSfx function of SoundManager and pass in two eating sounds to choose between to play the eating sound effect.
                SoundManager.instance.RandomizeSfx (eatSound3, eatSound4);

                //Disable the OkayFood object the player collided with.
                other.gameObject.SetActive (false);
            }
        }

        //Restart reloads the scene when called.
        private void Restart ()
        {
            //Load the last scene loaded, in this case Main, the only scene in the game.
            SceneManager.LoadScene(0);
        }

        //LoseHealth is called when an enemy attacks the player.
        //It takes a parameter loss which specifies how many points to lose.
        public void LoseHealth (int loss)
        {
            //Set the trigger for the player animator to transition to the playerHit animation.
            animator.SetTrigger ("playerHit");

            //Subtract lost health points from the players total.
            health -= loss;

            //Update the health display with the new total.
            healthText.text = "-"+ loss + " Health: " + health;

            //Check to see if game has ended.
            CheckIfGameOver ();
        }

        //CheckIfGameOver checks if the player is out of health points and if so, ends the game.
        private void CheckIfGameOver ()
        {
            //Check if health point total is less than or equal to zero.
            if (health <= 0)
            {
                //Call the PlaySingle function of SoundManager and pass it the gameOverSound as the audio clip to play.
                SoundManager.instance.PlaySingle (gameOverSound);

                //Stop the background music.
                SoundManager.instance.musicSource.Stop();

                //Call the GameOver function of GameManager.
                GameManager.instance.GameOver ();
            }
        }
    }
}


问:
Apache not starting in MAMP (but MySQL working) in OSX
I've had MAMP working for a few months and recently installed PostgreSQL.  It recommended installing Apache as well, which I did to make sure PostgreSQL worked.  I then uninstalled PostgreSQL and the apache build and tried to restart MAMP.  It fired up the MySQL database (green light) but Apache didn't start.  I uninstalled and reinstalled MAMP only to face the same problem.

Apache doesn't seem to be logging any errors in the MAMP folder, so without any errors to report I'm struggling with where to begin fixing it.  I'm hoping its to do with the fact that I installed another version (and deleted it) that has caused the problem but I'm too inexperienced to know what I've done.

Where might I find any errors if not in the MAMP folder? Not in:

/Applications/MAMP/Library/logs

/Applications/MAMP/bin/logs

答:
I have been going through all Stackoverflow posts, but no luck. Finally, I came across this:
https://www.speakinginbytes.com/2013/02/mamp-problems/

Sometimes Apache is set through MAMP to open a particular folder and that folder no longer exists. If you simple go to MAMP and change that
  setting through the preferences button you should be able to fix it.

That did the trick for me. Hopefully it will help someone else!


问:
Is my class allocating GPU memory leaking if it throws an exception which is caught?
I am writing a "error-check" function with is throwing std::runtime_error whenever an error is encountered (code samples below).

Situation:

Let's say that in foo constructor (in file: fooClass.h sample below) I was able to successfully set cuda device and allocate gpu memory, but my call to cudaMemcpy(***) has returned an error for whatever reason. That means my errchk(***) function is throwing an exception and is transferring control to main() function (in file: Start.cpp).

Because foo constructor did not finish it job, no foo object was created and ~foo() destructor was not called, therefore previously allocated gpu resources have been not released.

I know try block in main() is supposed to de-allocate all resources in reversed order to their initialization (whenever exception is thrown).

Question #1:

Does that mean I experienced gpu memory leak? OR somehow throw, try and catch can handle this situation?

Question #2 (? Opinion based ?):

I am learning C++ exception system and therefor I would like to know if this is a good idea to throw exceptions everywhere, and catch them only in main() function?

I think this is worth considering because then I am able to end my program in "natural" way - return EXIT_FAILURE; in opposition to exit(EXIT_FAILURE);

ErrorCheck.h: (whole file)

```<code>#pragma once
#ifndef __ERROR_CHECK_H__
#define __ERROR_CHECK_H__
#include <stdexcept>

// The function:
template <typename T>
bool errchk(const T check, const char* file, unsigned int line, const char* from, const char* func);

// How To call it:
#define ERRCHK(_check) \
    errchk(_check, __FILE__, __LINE__, __FUNC__, #_check)

#endif // !__ERROR_CHECK_H__
</code>```

ErrorCheck.cpp: (simplified version)

```<code>// Include:
#include <cuda.h>              // cudaError_t
#include <cuda_runtime_api.h>
#include <cufft.h>             // cufftResult_t
#include <cublas.h>            // cublasStatus_t
#include <curand_kernel.h>     // curandStatus_t
#include <cusolver_common.h>   // cusolverStatus_t
#include <cusparse.h>          // cusparseStatus_t

#include <stdexcept>
#include "ErrorCheck.h"

// Functions bellow are overloaded 7 times for every error type from headers included above
inline const bool testForError(const Type & check) { return check != SuccessValue; };
inline const char * getErrorName(const Type & error) { /* ... */ };
inline const char * getErrorString(const Type & error) { /* ... */ };

// The function:
template <typename T, T successValue>
void errchk(const T check, const char* file, unsigned int line, const char* from, const char* func)
{
    if (testForError(check)) {

        // generate error description in form of a string.

        throw std::runtime_error(errorDescription);
    }
}

// Instantiations:
template void errchk <bool            > (const bool             check, const char * file, unsigned int line, const char * from, const char * func);
template void errchk <cudaError_t     > (const cudaError_t      check, const char * file, unsigned int line, const char * from, const char * func);
template void errchk <cufftResult_t   > (const cufftResult_t    check, const char * file, unsigned int line, const char * from, const char * func);
template void errchk <cublasStatus_t  > (const cublasStatus_t   check, const char * file, unsigned int line, const char * from, const char * func);
template void errchk <curandStatus_t  > (const curandStatus_t   check, const char * file, unsigned int line, const char * from, const char * func);
template void errchk <cusolverStatus_t> (const cusolverStatus_t check, const char * file, unsigned int line, const char * from, const char * func);
template void errchk <cusparseStatus_t> (const cusparseStatus_t check, const char * file, unsigned int line, const char * from, const char * func);
</code>```

fooClass.h:

```<code>#include "ErrorCheck.h"
class foo
{
private:
    float * dev_floatArray;
    float * host_floatArray;

public:
    foo() {
        // Do something...
        ERRCHK(cudaSetDevice(0));
        ERRCHK(cudaMalloc(&dev_floatArray, 10000 * sizeof(float)));
        // Do something...
        ERRCHK(cudaMemcpy(host_floatArray, dev_floatArray, 10000 * sizeof(float), cudaMemcpyDeviceToHost));
        // Do something...
    }
    ~foo() {
        // Do something...
        ERRCHK(cudaFree(dev_floatArray));
        ERRCHK(cudaDeviceReset());
    }
}
</code>```

Start.cpp:

```<code>#include <iostream>
#include "fooClass.h"
using namespace std;

int main() {
    try {
        foo bar; // constructor of "foo" Class is called.
    }
    catch (std::runtime_error error) {
        cout << error.what() << endl;
        getchar();
        return EXIT_FAILURE;
    }
}
</code>```

答:
Does that mean I experienced gpu memory leak?

Yes, it does. You must not allocate resources without ensuring they will eventually be deallocated; and by throwing an exception if the cudaMemCpy() fails - you're not making that assurance.

OR somehow throw, try and catch can handle this situation?

Actually, yes, sort of.. as @Jean-BaptisteYunès suggests, RAII is key. Please read this:

What destructors are run when the constructor throws an exception?

So, if you could shove your memory allocation and de-allocation into a RAII member of your foo class, you would have completed its construction, and thus its destructor - which deallocates - would have run on exiting the foo() scope, even with an exception.

At this point I'll say that you're reinventing the wheel with some of the code you're writing. You can find both a mechanism for wrapping CUDA errors with exceptions and a unique-pointer-like RAII holder for your allocated memory in my cuda-api-wrappers library*. So you would have something like:

```<code>class foo {
public:
    using element_type = float;
    enum : size_t { num_elements };
protected:
    struct {
        cuda::memory::device::unique_ptr<element_type> device;
        cuda::memory::host::unique_ptr<element_type>   host;
    } data;

public:
    foo() : data( {
        cuda::memory::device::make_unique<element_type[]>(
            cuda::device::default_device_id,
            num_elements
        ),
        cuda::memory::host::make_unique(num_elements)
    } )
    {
        // Do something...
        cuda::memory::copy(
            data.host.get(), data.device.get(), num_elements * sizeof(element_type)
        );
        // Do something...
    }
    ~foo() {
        // Do something...

        // ERRCHK(cudaFree(dev_floatArray));
        // No need to free anything! It's magic!

        // ERRCHK(cudaDeviceReset());
        // Don't reset your device you really need to - and
        // you don't need to.
    }
}
</code>```

Another approach you could consider, instead of a RAII class for holding memory, is Andrei Alexandrescu's 'Scope Guard' mechanism. He explains it (well, the latest version of it) in this video:

CppCon 2015: Andrei Alexandrescu - Declarative Control Flow

Is it a good idea to throw exceptions everywhere, and catch them only in main() function?

Make that a separate question, because the answer is not a simple yes/no. Actually, there are enough questions and answers here on SO which cover that, I think.

* - Other libraries may also provide something similar, e.g. Thrust, perhaps; but with this one you're not bound to complex abstractions, just CUDA Runtime API wrappers.)

Body:
I am writing a "error-check" function with is throwing std::runtime_error whenever an error is encountered (code samples below).

Situation:

Let's say that in foo constructor (in file: fooClass.h sample below) I was able to successfully set cuda device and allocate gpu memory, but my call to cudaMemcpy(***) has returned an error for whatever reason. That means my errchk(***) function is throwing an exception and is transferring control to main() function (in file: Start.cpp).

Because foo constructor did not finish it job, no foo object was created and ~foo() destructor was not called, therefore previously allocated gpu resources have been not released.

I know try block in main() is supposed to de-allocate all resources in reversed order to their initialization (whenever exception is thrown).

Question #1:

Does that mean I experienced gpu memory leak? OR somehow throw, try and catch can handle this situation?

Question #2 (? Opinion based ?):

I am learning C++ exception system and therefor I would like to know if this is a good idea to throw exceptions everywhere, and catch them only in main() function?

I think this is worth considering because then I am able to end my program in "natural" way - return EXIT_FAILURE; in opposition to exit(EXIT_FAILURE);

ErrorCheck.h: (whole file)

#pragma once
#ifndef __ERROR_CHECK_H__
#define __ERROR_CHECK_H__
#include <stdexcept>

// The function:
template <typename T>
bool errchk(const T check, const char* file, unsigned int line, const char* from, const char* func);

// How To call it:
#define ERRCHK(_check) \
    errchk(_check, __FILE__, __LINE__, __FUNC__, #_check)

#endif // !__ERROR_CHECK_H__

ErrorCheck.cpp: (simplified version)

// Include:
#include <cuda.h>              // cudaError_t
#include <cuda_runtime_api.h>
#include <cufft.h>             // cufftResult_t
#include <cublas.h>            // cublasStatus_t
#include <curand_kernel.h>     // curandStatus_t
#include <cusolver_common.h>   // cusolverStatus_t
#include <cusparse.h>          // cusparseStatus_t

#include <stdexcept>
#include "ErrorCheck.h"

// Functions bellow are overloaded 7 times for every error type from headers included above
inline const bool testForError(const Type & check) { return check != SuccessValue; };
inline const char * getErrorName(const Type & error) { /* ... */ };
inline const char * getErrorString(const Type & error) { /* ... */ };

// The function:
template <typename T, T successValue>
void errchk(const T check, const char* file, unsigned int line, const char* from, const char* func)
{
    if (testForError(check)) {

        // generate error description in form of a string.

        throw std::runtime_error(errorDescription);
    }
}

// Instantiations:
template void errchk <bool            > (const bool             check, const char * file, unsigned int line, const char * from, const char * func);
template void errchk <cudaError_t     > (const cudaError_t      check, const char * file, unsigned int line, const char * from, const char * func);
template void errchk <cufftResult_t   > (const cufftResult_t    check, const char * file, unsigned int line, const char * from, const char * func);
template void errchk <cublasStatus_t  > (const cublasStatus_t   check, const char * file, unsigned int line, const char * from, const char * func);
template void errchk <curandStatus_t  > (const curandStatus_t   check, const char * file, unsigned int line, const char * from, const char * func);
template void errchk <cusolverStatus_t> (const cusolverStatus_t check, const char * file, unsigned int line, const char * from, const char * func);
template void errchk <cusparseStatus_t> (const cusparseStatus_t check, const char * file, unsigned int line, const char * from, const char * func);

fooClass.h:

#include "ErrorCheck.h"
class foo
{
private:
    float * dev_floatArray;
    float * host_floatArray;

public:
    foo() {
        // Do something...
        ERRCHK(cudaSetDevice(0));
        ERRCHK(cudaMalloc(&dev_floatArray, 10000 * sizeof(float)));
        // Do something...
        ERRCHK(cudaMemcpy(host_floatArray, dev_floatArray, 10000 * sizeof(float), cudaMemcpyDeviceToHost));
        // Do something...
    }
    ~foo() {
        // Do something...
        ERRCHK(cudaFree(dev_floatArray));
        ERRCHK(cudaDeviceReset());
    }
}

Start.cpp:

#include <iostream>
#include "fooClass.h"
using namespace std;

int main() {
    try {
        foo bar; // constructor of "foo" Class is called.
    }
    catch (std::runtime_error error) {
        cout << error.what() << endl;
        getchar();
        return EXIT_FAILURE;
    }
}

Body:
Does that mean I experienced gpu memory leak?

Yes, it does. You must not allocate resources without ensuring they will eventually be deallocated; and by throwing an exception if the cudaMemCpy() fails - you're not making that assurance.

OR somehow throw, try and catch can handle this situation?

Actually, yes, sort of.. as @Jean-BaptisteYunès suggests, RAII is key. Please read this:

What destructors are run when the constructor throws an exception?

So, if you could shove your memory allocation and de-allocation into a RAII member of your foo class, you would have completed its construction, and thus its destructor - which deallocates - would have run on exiting the foo() scope, even with an exception.

At this point I'll say that you're reinventing the wheel with some of the code you're writing. You can find both a mechanism for wrapping CUDA errors with exceptions and a unique-pointer-like RAII holder for your allocated memory in my cuda-api-wrappers library*. So you would have something like:

class foo {
public:
    using element_type = float;
    enum : size_t { num_elements };
protected:
    struct {
        cuda::memory::device::unique_ptr<element_type> device;
        cuda::memory::host::unique_ptr<element_type>   host;
    } data;

public:
    foo() : data( {
        cuda::memory::device::make_unique<element_type[]>(
            cuda::device::default_device_id,
            num_elements
        ),
        cuda::memory::host::make_unique(num_elements)
    } )
    {
        // Do something...
        cuda::memory::copy(
            data.host.get(), data.device.get(), num_elements * sizeof(element_type)
        );
        // Do something...
    }
    ~foo() {
        // Do something...

        // ERRCHK(cudaFree(dev_floatArray));
        // No need to free anything! It's magic!

        // ERRCHK(cudaDeviceReset());
        // Don't reset your device you really need to - and
        // you don't need to.
    }
}

Another approach you could consider, instead of a RAII class for holding memory, is Andrei Alexandrescu's 'Scope Guard' mechanism. He explains it (well, the latest version of it) in this video:

CppCon 2015: Andrei Alexandrescu - Declarative Control Flow

Is it a good idea to throw exceptions everywhere, and catch them only in main() function?

Make that a separate question, because the answer is not a simple yes/no. Actually, there are enough questions and answers here on SO which cover that, I think.

* - Other libraries may also provide something similar, e.g. Thrust, perhaps; but with this one you're not bound to complex abstractions, just CUDA Runtime API wrappers.)


问:
Django: using template tags inside of javascript for Google Maps
I'm trying to use template tags in my javascript to make it dynamic and load maps according to the address sent. My map is working and my geocode as well. I can even pass the latitude and longitude to the template, but when I place it inside of javascritp it doesn't work as expected.

For example:

if the {{longitude}} is -122,0843845 in the HTML, I get on my alert( {{longitude}} ) only -122. It seems that I there is a problem in Django converting a dot to comma, like -122.08... to -122,08. Either way it didn't work even when I tried with integers like -122.

Not sure if it is a float to string issue or something else, I'm quite new to javascript.

The code.

views.py

class ImovelDetail(DetailView):
    model = Imovel

```<code>def get_context_data(self, *args, **kwargs):
    address = "1600 Amphitheatre Parkway, Mountain View, CA"
    api_key = "AIzaSyAiw0iU0egdeVrOKboOOZ2n1WXS3Os0WgI"
    api_response = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address={0}&key={1}'.format(address, api_key))
    api_response_dict = api_response.json()

    if api_response_dict['status'] == 'OK':
        context = super(ImovelDetail, self).get_context_data(**kwargs)
        latitude = api_response_dict['results'][0]['geometry']['location']['lat']
        longitude  = api_response_dict['results'][0]['geometry']['location']['lng']
        print(latitude)
        context.update({'latitude': latitude, 'longitude': longitude})
        return context
</code>```

template.html

```<code>{% block js %}
    <!-- <script>
    SOMETHING THAT I TRIED
        var latitude = {{ latitude }};
        var longitude = {{ longitude }};
    </script> -->
    <script>
    function initMap() {
        var address = {lat: {{latitude}}, lng:{{longitude}} };

        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 15,
          center: address
        });
        var marker = new google.maps.Marker({
          position: address,
          map: map
        });
    }
    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAiw0iU0egdeVrOKboOOZ2n1WXS3Os0WgI&callback=initMap"></script>
{% endblock %}
</code>```

答:
It is because javascript uses dot in decimal numbers. So if you pass number to javascript you need use dot. Like this: 159.0857
If you pass it with comma javascript will round it

If you are using coordinates with commas (which is not very good approach). Then you need to replace comma. Maybe with custom filter. But how I said. It will be much better use decimal numbers with dots.

Of course if you have some objects on the page you can assign coordinates (with dots) to the html elements.

```<code><p class="address" latitude="49.055" longitude="40.808">Your address</p>
</code>```

and then you can get this values via JQuery or javascript.

If you have comma in your lat and lon, you have to replace it first. In your view try this:

```<code>return context.update({'latitude': float(latitude.replace(',','.')), 'longitude': float(longitude.replace(',','.'))}
</code>```

Edited

The last thing which could make this problem (you said it is OK on your standard output) is localization.  Check this answer

You will have to set USE_L10N=False

Body:
I'm trying to use template tags in my javascript to make it dynamic and load maps according to the address sent. My map is working and my geocode as well. I can even pass the latitude and longitude to the template, but when I place it inside of javascritp it doesn't work as expected.

For example:

if the {{longitude}} is -122,0843845 in the HTML, I get on my alert( {{longitude}} ) only -122. It seems that I there is a problem in Django converting a dot to comma, like -122.08... to -122,08. Either way it didn't work even when I tried with integers like -122.

Not sure if it is a float to string issue or something else, I'm quite new to javascript.

The code.

views.py

class ImovelDetail(DetailView):
    model = Imovel

def get_context_data(self, *args, **kwargs):
    address = "1600 Amphitheatre Parkway, Mountain View, CA"
    api_key = "AIzaSyAiw0iU0egdeVrOKboOOZ2n1WXS3Os0WgI"
    api_response = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address={0}&key={1}'.format(address, api_key))
    api_response_dict = api_response.json()

    if api_response_dict['status'] == 'OK':
        context = super(ImovelDetail, self).get_context_data(**kwargs)
        latitude = api_response_dict['results'][0]['geometry']['location']['lat']
        longitude  = api_response_dict['results'][0]['geometry']['location']['lng']
        print(latitude)
        context.update({'latitude': latitude, 'longitude': longitude})
        return context

template.html

{% block js %}

{% endblock %}

Body:
It is because javascript uses dot in decimal numbers. So if you pass number to javascript you need use dot. Like this: 159.0857
If you pass it with comma javascript will round it

If you are using coordinates with commas (which is not very good approach). Then you need to replace comma. Maybe with custom filter. But how I said. It will be much better use decimal numbers with dots.

Of course if you have some objects on the page you can assign coordinates (with dots) to the html elements.

<p class="address" latitude="49.055" longitude="40.808">Your address</p>

and then you can get this values via JQuery or javascript.

If you have comma in your lat and lon, you have to replace it first. In your view try this:

return context.update({'latitude': float(latitude.replace(',','.')), 'longitude': float(longitude.replace(',','.'))}

Edited

The last thing which could make this problem (you said it is OK on your standard output) is localization.  Check this answer

You will have to set USE_L10N=False