问:
Unable to deploy WAR in an EAR on WebLogic
I have a web application running on JSF 2.2 on WebLogic Application server 12.2.1.1.

I have a simple java class and trying to initialize it as an ApplicationScoped object using CDI. This gets deployed perfectly fine as a WAR.

```<code>import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;

@Named
@ApplicationScoped
public class AppContext {
    public AppContext() {
    }
}
</code>```

However, when I add this WAR to an EAR it fails to deploy. I am trying all possible solutions and nothing seems to work at this point. The exception log is as below:

```<code>weblogic.management.DeploymentException: CDI deployment failure:WELD-001414: Bean name is ambiguous. Name appContext resolves to beans: [Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named], Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named]]:org.jboss.weld.exceptions.DeploymentException:WELD-001414: Bean name is ambiguous. Name appContext resolves to beans: [Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named], Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named]]
    at org.jboss.weld.bootstrap.Validator.validateBeanNames(Validator.java:641)
    at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:487)
    at org.jboss.weld.bootstrap.WeldStartup.validateBeans(WeldStartup.java:446)
    at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:90)
    at com.oracle.injection.provider.weld.WeldInjectionContainer.start(WeldInjectionContainer.java:150)
    Truncated. see log file for complete stacktrace
</code>```

Also WEB-INF\beans.xml is as follows:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>
</code>```

Application Running On:

```<code>NetBeans IDE 8.2;
JDK 1.8 b121;
Mojarra JSF 2.2;
WebLogic 12.2.1.1;
</code>```

Any hint on fixing this issue is highly appreciated.

答: The fact that it deploys as a standalone WAR but fails as an EAR is a fairly clear indicator of the problem. Either the application contains an object with the same bean name from an external library or this class itself has been copied somewhere else in the EAR. Check that you're not loading this class (or jar containing this class) into any other place in the EAR; APP-INF comes to mind. If you haven't already, the quickest way to determine if it's an external library or your own deployment path is by renaming the class to something that you can ensure is unique (MyUniqueBeanName for example). If the problem persists after a rename, it's most likely your deployment. </p>

Body:
I have a web application running on JSF 2.2 on WebLogic Application server 12.2.1.1.

I have a simple java class and trying to initialize it as an ApplicationScoped object using CDI. This gets deployed perfectly fine as a WAR.

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;

@Named
@ApplicationScoped
public class AppContext {
    public AppContext() {
    }
}

However, when I add this WAR to an EAR it fails to deploy. I am trying all possible solutions and nothing seems to work at this point. The exception log is as below:

weblogic.management.DeploymentException: CDI deployment failure:WELD-001414: Bean name is ambiguous. Name appContext resolves to beans: [Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named], Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named]]:org.jboss.weld.exceptions.DeploymentException:WELD-001414: Bean name is ambiguous. Name appContext resolves to beans: [Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named], Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named]]
    at org.jboss.weld.bootstrap.Validator.validateBeanNames(Validator.java:641)
    at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:487)
    at org.jboss.weld.bootstrap.WeldStartup.validateBeans(WeldStartup.java:446)
    at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:90)
    at com.oracle.injection.provider.weld.WeldInjectionContainer.start(WeldInjectionContainer.java:150)
    Truncated. see log file for complete stacktrace

Also WEB-INF\beans.xml is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>

Application Running On:

NetBeans IDE 8.2;
JDK 1.8 b121;
Mojarra JSF 2.2;
WebLogic 12.2.1.1;

Any hint on fixing this issue is highly appreciated.


来源: stackexchange

问:
Cannot define 'query' and multiple loaders in loaders list, webpack error
I am getting this error

```<code>/home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/LoadersList.js:54
            if(!element.loader || element.loader.indexOf("!") >= 0) throw new Error("Cannot define 'query' and multiple loaders in loaders list");
                                                                    ^

Error: Cannot define 'query' and multiple loaders in loaders list
at getLoadersFromObject (/home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/LoadersList.js:54:65)
at LoadersList.<anonymous> (/home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/LoadersList.js:78:12)
</code>```

I was getting deprecated warning

Webpack 2: WARNING in .png, .svg, .. DEPRECATED. Configure optipng's optimizationLevel option in it's own options. (optipng.optimizationLevel)

after following above thread. I introduced option property in my webpack. Here's my webpack config

```<code>var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: { app: './src/app.js' },
  output: {
    filename: 'public/build/bundle.js',
    sourceMapFilename: 'public/build/bundle.map'
  },
  module: {
    loaders: [
      {
        test: /\.(js|jsx)$/,
        loader: 'babel-loader',
        query: {
          presets: ['stage-0', 'react', 'es2015'],
          plugins: ['transform-decorators-legacy', 'transform-class-properties']
        }
      },
      { test: /\.css$/, loaders: ['style-loader', 'css-loader'] },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        loader: 'file?name=public/fonts/[name].[ext]'
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        loaders: [
          'file?hash=sha512&digest=hex&name=[hash].[ext]',
          'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
        ],

        options: {
          query: {
            mozjpeg: {
              progressive: true
            },
            gifsicle: {
              interlaced: true
            },
            optipng: {
              optimizationLevel: 7
            }
          }
        }
      }
    ]
  }
};
</code>```

But I am still getting that error.

Edit 1 - after Michael's answer

I still got error, this is my webpack now

```<code>    var webpack = require("webpack");
var path = require("path");
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: {app: './src/app.js' },
  output: {filename: 'public/build/bundle.js',
        sourceMapFilename: 'public/build/bundle.map' },
  module: {
    loaders: [
      { test: /\.(js|jsx)$/, loader: 'babel-loader',query: {
        presets: ['stage-0','react','es2015'],
        plugins: ["transform-decorators-legacy","transform-class-properties"]
    } },
      { test: /\.css$/, loaders: [ 'style-loader', 'css-loader' ] },
      { test: /\.(eot|svg|ttf|woff|woff2)$/, loader: 'file?name=public/fonts/[name].[ext]'  },
      {
  test: /\.(jpe?g|png|gif|svg)$/i,
  use: [
    {
      loader: 'file-loader',
      options: {
        name: '[sha512:hash:hex].[ext]'
      }
    },
    {
      loader: 'image-webpack-loader',
      options: {
        bypassOnDebug: true,
        mozjpeg: {
          progressive: true
        },
        gifsicle: {
          interlaced: true
        },
        optipng: {
          optimizationLevel: 7
        }
      }
    }
  ]
}
    ]
  }
}
</code>```

the error looks like this now

```<code>    ERROR in ./public/imgs/common/jcrop/Jcrop.gif
Module parse failed: /home/ubuntu/workspace/node_modules/image-webpack-loader/index.js!/home/ubuntu/workspace/public/imgs/common/jcrop/Jcrop.gif Unexpected character ' (1:6)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected character ' (1:6)
    at Parser.pp$4.raise (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:2221:15)
    at Parser.pp$7.getTokenFromCode (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:2756:10)
    at Parser.pp$7.readToken (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:2477:17)
    at Parser.pp$7.nextToken (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:2468:15)
    at Parser.pp$7.next (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:2413:10)
    at Parser.pp$3.parseIdent (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:2191:10)
    at Parser.pp$3.parseExprAtom (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:1774:21)
    at Parser.pp$3.parseExprSubscripts (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:1715:21)
    at Parser.pp$3.parseMaybeUnary (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:1692:19)
    at Parser.pp$3.parseExprOps (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:1637:21)
    at Parser.pp$3.parseMaybeConditional (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:1620:21)
    at Parser.pp$3.parseMaybeAssign (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:1597:21)
    at Parser.pp$3.parseExpression (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:1573:21)
    at Parser.pp$1.parseStatement (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:727:47)
    at Parser.pp$1.parseTopLevel (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:638:25)
    at Parser.parse (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:516:17)
    at Object.parse (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:3098:39)
    at Parser.parse (/home/ubuntu/workspace/node_modules/webpack/lib/Parser.js:902:15)
    at DependenciesBlock.<anonymous> (/home/ubuntu/workspace/node_modules/webpack/lib/NormalModule.js:104:16)
    at DependenciesBlock.onModuleBuild (/home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/NormalModuleMixin.js:310:10)
    at nextLoader (/home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/NormalModuleMixin.js:275:25)
    at /home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/NormalModuleMixin.js:292:15
    at context.callback (/home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/NormalModuleMixin.js:148:14)
    at /home/ubuntu/workspace/node_modules/image-webpack-loader/index.js:71:9
 @ ./~/css-loader!./src/main-blessed3.css?z=1490800022920 6:271558-271606
</code>```

答:
The problem is your last rule:

```<code>{
  test: /\.(jpe?g|png|gif|svg)$/i,
  loaders: [
    'file?hash=sha512&digest=hex&name=[hash].[ext]',
    'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
  ],

  options: {
    query: {
      mozjpeg: {
        progressive: true
      },
      gifsicle: {
        interlaced: true
      },
      optipng: {
        optimizationLevel: 7
      }
    }
  }
}
</code>```

You define options on the rule, but you have multiple loaders. This is not allowed, it only works if it's a single loader (as a shortcut), otherwise you need to specify the options on the loader directly not the rule. The loaders don't even work in webpack 2 because you're leaving off the -loader suffix which is no longer allowed in webpack 2 (as shown in the Automatic -loader module name extension removed).

Also don't use inline query options, use options on the loader (query exists for compatibility reasons and options should be preferred). Because of the inline configuration you get the deprecation warnings, as you still have the options set there. Also your file-loader options are not correct, the type of the hash is specified in the name option with [<hashType>:hash:<digestType>:<length>] as described in Filename template placeholders.

The correct and clean version of the above rule is:

```<code>{
  test: /\.(jpe?g|png|gif|svg)$/i,
  use: [
    {
      loader: 'file-loader',
      options: {
        name: '[sha512:hash:hex].[ext]'
      }
    },
    {
      loader: 'image-webpack-loader',
      options: {
        bypassOnDebug: true,
        mozjpeg: {
          progressive: true
        },
        gifsicle: {
          interlaced: true
        },
        optipng: {
          optimizationLevel: 7
        }
      }
    }
  ]
}
</code>```

By the way, you also have .svg specified in another rule (for your fonts), this will likely have unwanted effects, you should only have one rule that matches it.

ContentLicense: CC BY-SA 3.0

Body:
I am getting this error

/home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/LoadersList.js:54
            if(!element.loader || element.loader.indexOf("!") >= 0) throw new Error("Cannot define 'query' and multiple loaders in loaders list");
                                                                    ^

Error: Cannot define 'query' and multiple loaders in loaders list
at getLoadersFromObject (/home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/LoadersList.js:54:65)
at LoadersList.<anonymous> (/home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/LoadersList.js:78:12)

I was getting deprecated warning

Webpack 2: WARNING in .png, .svg, .. DEPRECATED. Configure optipng's optimizationLevel option in it's own options. (optipng.optimizationLevel)

after following above thread. I introduced option property in my webpack. Here's my webpack config

var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: { app: './src/app.js' },
  output: {
    filename: 'public/build/bundle.js',
    sourceMapFilename: 'public/build/bundle.map'
  },
  module: {
    loaders: [
      {
        test: /\.(js|jsx)$/,
        loader: 'babel-loader',
        query: {
          presets: ['stage-0', 'react', 'es2015'],
          plugins: ['transform-decorators-legacy', 'transform-class-properties']
        }
      },
      { test: /\.css$/, loaders: ['style-loader', 'css-loader'] },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        loader: 'file?name=public/fonts/[name].[ext]'
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        loaders: [
          'file?hash=sha512&digest=hex&name=[hash].[ext]',
          'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
        ],

        options: {
          query: {
            mozjpeg: {
              progressive: true
            },
            gifsicle: {
              interlaced: true
            },
            optipng: {
              optimizationLevel: 7
            }
          }
        }
      }
    ]
  }
};

But I am still getting that error.

Edit 1 - after Michael's answer

I still got error, this is my webpack now

    var webpack = require("webpack");
var path = require("path");
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: {app: './src/app.js' },
  output: {filename: 'public/build/bundle.js',
        sourceMapFilename: 'public/build/bundle.map' },
  module: {
    loaders: [
      { test: /\.(js|jsx)$/, loader: 'babel-loader',query: {
        presets: ['stage-0','react','es2015'],
        plugins: ["transform-decorators-legacy","transform-class-properties"]
    } },
      { test: /\.css$/, loaders: [ 'style-loader', 'css-loader' ] },
      { test: /\.(eot|svg|ttf|woff|woff2)$/, loader: 'file?name=public/fonts/[name].[ext]'  },
      {
  test: /\.(jpe?g|png|gif|svg)$/i,
  use: [
    {
      loader: 'file-loader',
      options: {
        name: '[sha512:hash:hex].[ext]'
      }
    },
    {
      loader: 'image-webpack-loader',
      options: {
        bypassOnDebug: true,
        mozjpeg: {
          progressive: true
        },
        gifsicle: {
          interlaced: true
        },
        optipng: {
          optimizationLevel: 7
        }
      }
    }
  ]
}
    ]
  }
}

the error looks like this now

    ERROR in ./public/imgs/common/jcrop/Jcrop.gif
Module parse failed: /home/ubuntu/workspace/node_modules/image-webpack-loader/index.js!/home/ubuntu/workspace/public/imgs/common/jcrop/Jcrop.gif Unexpected character ' (1:6)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected character ' (1:6)
    at Parser.pp$4.raise (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:2221:15)
    at Parser.pp$7.getTokenFromCode (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:2756:10)
    at Parser.pp$7.readToken (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:2477:17)
    at Parser.pp$7.nextToken (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:2468:15)
    at Parser.pp$7.next (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:2413:10)
    at Parser.pp$3.parseIdent (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:2191:10)
    at Parser.pp$3.parseExprAtom (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:1774:21)
    at Parser.pp$3.parseExprSubscripts (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:1715:21)
    at Parser.pp$3.parseMaybeUnary (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:1692:19)
    at Parser.pp$3.parseExprOps (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:1637:21)
    at Parser.pp$3.parseMaybeConditional (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:1620:21)
    at Parser.pp$3.parseMaybeAssign (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:1597:21)
    at Parser.pp$3.parseExpression (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:1573:21)
    at Parser.pp$1.parseStatement (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:727:47)
    at Parser.pp$1.parseTopLevel (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:638:25)
    at Parser.parse (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:516:17)
    at Object.parse (/home/ubuntu/workspace/node_modules/webpack/node_modules/acorn/dist/acorn.js:3098:39)
    at Parser.parse (/home/ubuntu/workspace/node_modules/webpack/lib/Parser.js:902:15)
    at DependenciesBlock.<anonymous> (/home/ubuntu/workspace/node_modules/webpack/lib/NormalModule.js:104:16)
    at DependenciesBlock.onModuleBuild (/home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/NormalModuleMixin.js:310:10)
    at nextLoader (/home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/NormalModuleMixin.js:275:25)
    at /home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/NormalModuleMixin.js:292:15
    at context.callback (/home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/NormalModuleMixin.js:148:14)
    at /home/ubuntu/workspace/node_modules/image-webpack-loader/index.js:71:9
 @ ./~/css-loader!./src/main-blessed3.css?z=1490800022920 6:271558-271606

Body:
The problem is your last rule:

{
  test: /\.(jpe?g|png|gif|svg)$/i,
  loaders: [
    'file?hash=sha512&digest=hex&name=[hash].[ext]',
    'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
  ],

  options: {
    query: {
      mozjpeg: {
        progressive: true
      },
      gifsicle: {
        interlaced: true
      },
      optipng: {
        optimizationLevel: 7
      }
    }
  }
}

You define options on the rule, but you have multiple loaders. This is not allowed, it only works if it's a single loader (as a shortcut), otherwise you need to specify the options on the loader directly not the rule. The loaders don't even work in webpack 2 because you're leaving off the -loader suffix which is no longer allowed in webpack 2 (as shown in the Automatic -loader module name extension removed).

Also don't use inline query options, use options on the loader (query exists for compatibility reasons and options should be preferred). Because of the inline configuration you get the deprecation warnings, as you still have the options set there. Also your file-loader options are not correct, the type of the hash is specified in the name option with [<hashType>:hash:<digestType>:<length>] as described in Filename template placeholders.

The correct and clean version of the above rule is:

{
  test: /\.(jpe?g|png|gif|svg)$/i,
  use: [
    {
      loader: 'file-loader',
      options: {
        name: '[sha512:hash:hex].[ext]'
      }
    },
    {
      loader: 'image-webpack-loader',
      options: {
        bypassOnDebug: true,
        mozjpeg: {
          progressive: true
        },
        gifsicle: {
          interlaced: true
        },
        optipng: {
          optimizationLevel: 7
        }
      }
    }
  ]
}

By the way, you also have .svg specified in another rule (for your fonts), this will likely have unwanted effects, you should only have one rule that matches it.


问:
Can we retrieve the applications currently running in iPhone and iPad
Can we retrieve the applications currently  running  in iPhone and iPad?

UPDATE

Can we do it in jail broken phones? Can we do it for an app for CYDIA Store?

答:
You can get a list of running processes and from process ids may be you can figure out which ones are system processes and which one are 3rd party apps, but anyway I don't believe you can use it in application for appstore. (code taken from here)</p>

```<code>- (NSArray *)runningProcesses {

    int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
    size_t miblen = 4;

    size_t size;
    int st = sysctl(mib, miblen, NULL, &size, NULL, 0);

    struct kinfo_proc * process = NULL;
    struct kinfo_proc * newprocess = NULL;

    do {

        size += size / 10;
        newprocess = realloc(process, size);

        if (!newprocess){

            if (process){
                free(process);
            }

            return nil;
        }

        process = newprocess;
        st = sysctl(mib, miblen, process, &size, NULL, 0);

    } while (st == -1 && errno == ENOMEM);

    if (st == 0){

        if (size % sizeof(struct kinfo_proc) == 0){
            int nprocess = size / sizeof(struct kinfo_proc);

            if (nprocess){

                NSMutableArray * array = [[NSMutableArray alloc] init];

                for (int i = nprocess - 1; i >= 0; i--){

                    NSString * processID = [[NSString alloc] initWithFormat:@"%d", process[i].kp_proc.p_pid];
                    NSString * processName = [[NSString alloc] initWithFormat:@"%s", process[i].kp_proc.p_comm];

                    NSDictionary * dict = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:processID, processName, nil]
                                                                        forKeys:[NSArray arrayWithObjects:@"ProcessID", @"ProcessName", nil]];
                    [processID release];
                    [processName release];
                    [array addObject:dict];
                    [dict release];
                }

                free(process);
                return [array autorelease];
            }
        }
    }

    return nil;
}:
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You can get a list of running processes and from process ids may be you can figure out which ones are system processes and which one are 3rd party apps, but anyway I don't believe you can use it in application for appstore. (code taken from here)

- (NSArray *)runningProcesses {

    int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
    size_t miblen = 4;

    size_t size;
    int st = sysctl(mib, miblen, NULL, &size, NULL, 0);

    struct kinfo_proc * process = NULL;
    struct kinfo_proc * newprocess = NULL;

    do {

        size += size / 10;
        newprocess = realloc(process, size);

        if (!newprocess){

            if (process){
                free(process);
            }

            return nil;
        }

        process = newprocess;
        st = sysctl(mib, miblen, process, &size, NULL, 0);

    } while (st == -1 && errno == ENOMEM);

    if (st == 0){

        if (size % sizeof(struct kinfo_proc) == 0){
            int nprocess = size / sizeof(struct kinfo_proc);

            if (nprocess){

                NSMutableArray * array = [[NSMutableArray alloc] init];

                for (int i = nprocess - 1; i >= 0; i--){

                    NSString * processID = [[NSString alloc] initWithFormat:@"%d", process[i].kp_proc.p_pid];
                    NSString * processName = [[NSString alloc] initWithFormat:@"%s", process[i].kp_proc.p_comm];

                    NSDictionary * dict = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:processID, processName, nil]
                                                                        forKeys:[NSArray arrayWithObjects:@"ProcessID", @"ProcessName", nil]];
                    [processID release];
                    [processName release];
                    [array addObject:dict];
                    [dict release];
                }

                free(process);
                return [array autorelease];
            }
        }
    }

    return nil;
}:


问:
Background-Color grey, rather than transparent
So when I try to remove the background-color attribute, the background stay a grey sort of color, rather than becoming transparent. Code:

CSS:

```<code>    #contact-form button[type="submit"] {
    position: absolute;
    width: 100%;
    margin: 100px 0 5px;
    padding: 10px;
    font-size: 15px;
    height: 50px;
    max-width: 372px;
    border: 1px solid white;
    border-radius: 15px;
    color: white;
    text-align: center;
    text-decoration: none;
    cursor: pointer;
    transition: 0.5s;
}

#contact-form button[type="submit"]:hover {
    background-color: #fff;
    color: #2D2D2D;
}
</code>```

答:
try using background:transparent; instead of background:#fff; as this changes the color of background to "white", it do not turn the background transparent, it might help. And as @blackandorangecat said, there might be other conflicting CSS available, please go through your code and try removing it.

Refer to https://www.w3schools.com/cssref/playit.asp?filename=playcss_background-color&preval=transparent for background CSS properties

Body:
So when I try to remove the background-color attribute, the background stay a grey sort of color, rather than becoming transparent. Code:

CSS:

    #contact-form button[type="submit"] {
    position: absolute;
    width: 100%;
    margin: 100px 0 5px;
    padding: 10px;
    font-size: 15px;
    height: 50px;
    max-width: 372px;
    border: 1px solid white;
    border-radius: 15px;
    color: white;
    text-align: center;
    text-decoration: none;
    cursor: pointer;
    transition: 0.5s;
}

#contact-form button[type="submit"]:hover {
    background-color: #fff;
    color: #2D2D2D;
}


问:
Add 1px of Padding(bottom) for Every 1px Scrolled – jQuery or Javascript
I'm setting up an animation so that when a user scrolls, after 10px the menu disappears to the left (easy enough thus far).  I would like it so the menu container appears 'fixed' vertically whilst it scrolls horizontally to the left.  I have figured that if I create a loop which adds 1px of padding-bottom to the container for every px scrolled this will create this effect (i can't use position: fixed; because this will prevent the horizontal animation).

I've never approached anything like this before, although I realise I'll need some form of counter to create the px value and then convert into a paddingBottom value.

I've set up the animation so it triggers on scroll, but I seem to be getting absolutely nowhere in terms of how to adding the padding value incrementally.

The code snippet is showing things thus far, but any pointers on how to achieve the above would be amazing.

Emily.

jQuery(document).ready (function($){

  $(window).scroll(function() {
 if ($(document).scrollTop() > 10) {
   $('.mydiv').css('left', '-100px');
 } else {
   $('.mydiv').css('left', '0px');
 }
 });

var divHeight = $('.mydiv').height(),
    scrollTop = $('.mydiv').scrollTop();

 for (i=0; i < scrollTop.length; i++) {

   var divPaddingBottom = 0;

 }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {height: 200vh; padding: 0; margin: 0;}

.mydiv {
  position: absolute;
  width: 100px;
  height: 100vh;
  background-color: red;
  transition: .5s all;
}</code>```

```

答:
I think this is what you wanted:

jQuery(document).ready (function($){

  $(window).scroll(function() {
    $('.mydiv').css('paddingTop',  $(window).scrollTop() - $('.mydiv').offset().top);
    if ($(document).scrollTop() > 10) {
      $('.mydiv').css('left', '-100px');
    } else {
      $('.mydiv').css('left', '0px');
    }
  }).scroll();

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {height: 200vh; padding: 0; margin: 0;}

.mydiv {
  position: absolute;
  width: 100px;
  height: 100vh;
  background-color: red;
  transition: left .5s;
  transform:translateZ(0);
}</code>```

```

Note that I applied the css transition only to the left property. I also included transform:translateZ(0); for better performance.

Body:
I'm setting up an animation so that when a user scrolls, after 10px the menu disappears to the left (easy enough thus far).  I would like it so the menu container appears 'fixed' vertically whilst it scrolls horizontally to the left.  I have figured that if I create a loop which adds 1px of padding-bottom to the container for every px scrolled this will create this effect (i can't use position: fixed; because this will prevent the horizontal animation).

I've never approached anything like this before, although I realise I'll need some form of counter to create the px value and then convert into a paddingBottom value.

I've set up the animation so it triggers on scroll, but I seem to be getting absolutely nowhere in terms of how to adding the padding value incrementally.

The code snippet is showing things thus far, but any pointers on how to achieve the above would be amazing.

Emily.

jQuery(document).ready (function($){

  $(window).scroll(function() {
 if ($(document).scrollTop() > 10) {
   $('.mydiv').css('left', '-100px');
 } else {
   $('.mydiv').css('left', '0px');
 }
 });

var divHeight = $('.mydiv').height(),
    scrollTop = $('.mydiv').scrollTop();

 for (i=0; i < scrollTop.length; i++) {

   var divPaddingBottom = 0;

 }
});

body {height: 200vh; padding: 0; margin: 0;}

.mydiv {
  position: absolute;
  width: 100px;
  height: 100vh;
  background-color: red;
  transition: .5s all;
}

Body:
I think this is what you wanted:

jQuery(document).ready (function($){

  $(window).scroll(function() {
    $('.mydiv').css('paddingTop',  $(window).scrollTop() - $('.mydiv').offset().top);
    if ($(document).scrollTop() > 10) {
      $('.mydiv').css('left', '-100px');
    } else {
      $('.mydiv').css('left', '0px');
    }
  }).scroll();

});

body {height: 200vh; padding: 0; margin: 0;}

.mydiv {
  position: absolute;
  width: 100px;
  height: 100vh;
  background-color: red;
  transition: left .5s;
  transform:translateZ(0);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="mydiv">
  </div>

Note that I applied the css transition only to the left property. I also included transform:translateZ(0); for better performance.


问:
$this->Form->postLink redirect to '#' cakephp 3.4
I'm actually developping an application using the "AdminLTE" template.

The "postLink" worked normally for me before adding the "Authentification" stuffs, since that all the postLinks are redirecting me to "../currentpage#", notice that "currentpage" is the name of my current page & the "#" is added to the link instead of redirecting me to the wanted action. Here is my code:

index.ctp(Departments)

```<code>  <?= $this->Form->postLink(" ", ['controller' => 'Departments', 'action' => 'delete',$department->id ],['confirm'=> __('Are you sure you want to delete # {0}?', $department->name),'class'=>'btn btn-danger btn-flat fa fa-trash','title'=>__('Delete')],array('escape' => false)) ?>
</code>```

DepartmentsController.php

```<code>  public function delete($id = null)
{

    $this->request->allowMethod(['post', 'delete']);
    echo "Ok";
    $department = $this->Departments->get($id);
    if ($this->Departments->delete($department)) {
        $this->Flash->success(__('The department has been deleted.'));
    } else {
        $this->Flash->error(__('The department could not be deleted. Please, try again.'));
    }

    return $this->redirect(['action' => 'index']);
}
</code>```

AppController.php

```<code>class AppController extends Controller
{

    public function initialize()
    {
        parent::initialize();

        $this->loadComponent('RequestHandler');
        $this->loadComponent('Flash');

        $this->loadComponent('Auth',[
            'logoutRedirect' => [
                'controller' => 'Pages',
                'action' => 'display',
                'home'
            ]
        ]);
    }

    public function beforeRender(Event $event)
    {
        if (!array_key_exists('_serialize', $this->viewVars) &&
            in_array($this->response->type(), ['application/json', 'application/xml'])
        ) {
            $this->set('_serialize', true);
        }

        $this->viewBuilder()->theme('AdminLTE');
        $this->set('theme', Configure::read('Theme'));

        parent::beforeFilter($event);

        $this->Auth->allow();
    }
}
</code>```

Finally, UsersController.php:

```<code>class UsersController extends AppController
{

    public function delete($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $user = $this->Users->get($id);
        if ($this->Users->delete($user)) {
            $this->Flash->success(__('The user has been deleted.'));
        } else {
            $this->Flash->error(__('The user could not be deleted. Please, try again.'));
        }

        return $this->redirect(['action' => 'index']);
    }

    public function login()
    {
        if ($this->request->is('post')) {
            $user = $this->Auth->identify();
            if ($user) {
                $this->Auth->setUser($user);
                return $this->redirect($this->Auth->redirectUrl());
            }
            $this->Flash->error(__('Invalid username or password, try again'));
        }
    }

    public function logout()
    {
        return $this->redirect($this->Auth->logout());
    }

}
</code>```

Thank You

答:
If you want to redirect a different page, you can put in your controller right after the flash helper the redirection method, like this...

```<code>  public function delete($id = null)
{$this->request->allowMethod(['post', 'delete']);
echo "Ok";
$department = $this->Departments->get($id);
if ($this->Departments->delete($department)) {
    $this->Flash->success(__('The department has been deleted.'));
    return $this->redirect(['action' => 'DIFFERENT PAGE']);
} else {
    $this->Flash->error(__('The department could not be deleted. Please, try again.'));
}}
</code>```

Else, if you want the redirect to take place to the same location you can use the redirect referer method...

```<code>return $this->redirect($this->referer());
</code>```

Check more on the Cook book -> https://book.cakephp.org/3.0/en/controllers.html#redirecting-to-other-pages

ContentLicense: CC BY-SA 4.0

Body:
I'm actually developping an application using the "AdminLTE" template.

The "postLink" worked normally for me before adding the "Authentification" stuffs, since that all the postLinks are redirecting me to "../currentpage#", notice that "currentpage" is the name of my current page & the "#" is added to the link instead of redirecting me to the wanted action. Here is my code:

index.ctp(Departments)

  <?= $this->Form->postLink(" ", ['controller' => 'Departments', 'action' => 'delete',$department->id ],['confirm'=> __('Are you sure you want to delete # {0}?', $department->name),'class'=>'btn btn-danger btn-flat fa fa-trash','title'=>__('Delete')],array('escape' => false)) ?>

DepartmentsController.php

  public function delete($id = null)
{

    $this->request->allowMethod(['post', 'delete']);
    echo "Ok";
    $department = $this->Departments->get($id);
    if ($this->Departments->delete($department)) {
        $this->Flash->success(__('The department has been deleted.'));
    } else {
        $this->Flash->error(__('The department could not be deleted. Please, try again.'));
    }

    return $this->redirect(['action' => 'index']);
}

AppController.php

class AppController extends Controller
{

    public function initialize()
    {
        parent::initialize();

        $this->loadComponent('RequestHandler');
        $this->loadComponent('Flash');

        $this->loadComponent('Auth',[
            'logoutRedirect' => [
                'controller' => 'Pages',
                'action' => 'display',
                'home'
            ]
        ]);
    }

    public function beforeRender(Event $event)
    {
        if (!array_key_exists('_serialize', $this->viewVars) &&
            in_array($this->response->type(), ['application/json', 'application/xml'])
        ) {
            $this->set('_serialize', true);
        }

        $this->viewBuilder()->theme('AdminLTE');
        $this->set('theme', Configure::read('Theme'));

        parent::beforeFilter($event);

        $this->Auth->allow();
    }
}

Finally, UsersController.php:

class UsersController extends AppController
{

    public function delete($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $user = $this->Users->get($id);
        if ($this->Users->delete($user)) {
            $this->Flash->success(__('The user has been deleted.'));
        } else {
            $this->Flash->error(__('The user could not be deleted. Please, try again.'));
        }

        return $this->redirect(['action' => 'index']);
    }

    public function login()
    {
        if ($this->request->is('post')) {
            $user = $this->Auth->identify();
            if ($user) {
                $this->Auth->setUser($user);
                return $this->redirect($this->Auth->redirectUrl());
            }
            $this->Flash->error(__('Invalid username or password, try again'));
        }
    }

    public function logout()
    {
        return $this->redirect($this->Auth->logout());
    }

}

Thank You

Body:
If you want to redirect a different page, you can put in your controller right after the flash helper the redirection method, like this...

  public function delete($id = null)
{$this->request->allowMethod(['post', 'delete']);
echo "Ok";
$department = $this->Departments->get($id);
if ($this->Departments->delete($department)) {
    $this->Flash->success(__('The department has been deleted.'));
    return $this->redirect(['action' => 'DIFFERENT PAGE']);
} else {
    $this->Flash->error(__('The department could not be deleted. Please, try again.'));
}}

Else, if you want the redirect to take place to the same location you can use the redirect referer method...

return $this->redirect($this->referer());

Check more on the Cook book -> https://book.cakephp.org/3.0/en/controllers.html#redirecting-to-other-pages


问:
select 1st value with many rows out of 2 values based on column condition else 2nd value all rows ORACLE
i have below oracle sql

```<code>select     *      from     a
where     a.description      in
('Rebook All (1)', 'Created stock identifier')
and     a.date     between     '03/18/2017 00:00:01'
AND     '03/25/2017 00:00:00'
and     a.unit     =     '38240007294677'
</code>```

Now result can have both description like below for a Unit number or can have 1 of the description ,  when it has both description for a Unit number i need to select only 'Rebook all (1)'(this description can be there many times as shows below in results)   description not 'Created stock identifier' and its related details from table a and when it has only 1 description out of these 2 then if 'Rebook All (1)' not there select 'Created stock identifier' and vice versa.
how do i select it?
Thanks in advance.

```<code>Date                       Description
</code>```

3/20/2017 10:11:12.769000 AM    Created     stock     identifier

3/20/2017 10:10:47.775000 AM    Created     stock     identifier

3/20/2017 10:10:47.782000 AM    Created     stock     identifier

3/20/2017 8:14:41.696000 PM     Rebook     all     (1)

3/20/2017 8:14:41.885000 PM     Rebook     all     (1)

3/20/2017 8:13:51.622000 PM     Rebook     all     (1)

答:
One method uses rank():

```<code>select a.*
from (select a.*,
             rank() over (partition by unit order by description desc) as seqnum
      from a
      where a.description in  ('Rebook All (1)', 'Created stock identifier')
            a.date >= date '2017-03-18' and
            a.date < date '2017-03-25' and
            a.unit = '38240007294677'
    ) a
where seqnum = 1;
</code>```

Notes:
 - This uses the fact that "Rebook" comes alphabetically after "Created".  Hence the desc in the order by.
 - I prefer ANSI standard date formats.
 - Notice the change to the date logic, to eliminate the need for times on the dates.

Body:
i have below oracle sql

select     *      from     a
where     a.description      in
('Rebook All (1)', 'Created stock identifier')
and     a.date     between     '03/18/2017 00:00:01'
AND     '03/25/2017 00:00:00'
and     a.unit     =     '38240007294677'

Now result can have both description like below for a Unit number or can have 1 of the description ,  when it has both description for a Unit number i need to select only 'Rebook all (1)'(this description can be there many times as shows below in results)   description not 'Created stock identifier' and its related details from table a and when it has only 1 description out of these 2 then if 'Rebook All (1)' not there select 'Created stock identifier' and vice versa.
how do i select it?
Thanks in advance.

Date                       Description

3/20/2017 10:11:12.769000 AM    Created     stock     identifier

3/20/2017 10:10:47.775000 AM    Created     stock     identifier

3/20/2017 10:10:47.782000 AM    Created     stock     identifier

3/20/2017 8:14:41.696000 PM     Rebook     all     (1)

3/20/2017 8:14:41.885000 PM     Rebook     all     (1)

3/20/2017 8:13:51.622000 PM     Rebook     all     (1)

Body:
One method uses rank():

select a.*
from (select a.*,
             rank() over (partition by unit order by description desc) as seqnum
      from a
      where a.description in  ('Rebook All (1)', 'Created stock identifier')
            a.date >= date '2017-03-18' and
            a.date < date '2017-03-25' and
            a.unit = '38240007294677'
    ) a
where seqnum = 1;

Notes:
 - This uses the fact that "Rebook" comes alphabetically after "Created".  Hence the desc in the order by.
 - I prefer ANSI standard date formats.
 - Notice the change to the date logic, to eliminate the need for times on the dates.


问:
list subdomain of a domain using cpanel xml api php
I am using cpanel xml api.

```<code>https://github.com/CpanelInc/xmlapi-php
</code>```

i can create subdomains and delete them.

Now i want to list the subdomains.

Here is the Answer in API1 level

```<code>$listSubdomain = $xml->api1_query( $cp_un, 'SubDomain', 'listsubdomainsop');

$listSubdomainpaths = $xml->api1_query( $cp_un, 'SubDomain', 'cplistsubdomains');
</code>```

答:
You can use the following:

```<code>$subdomainsList = $xml->api2_query($cpanelUser, 'SubDomain', 'listsubdomains');
</code>```

If you want, it is possible to filter results using a PCRE regex:

```<code>$subdomainsList = $xml->api2_query($cpanelUser, 'SubDomain', 'listsubdomains', [
    'regex' => '\bMySubdomain\b'
]);
</code>```

Body:
I am using cpanel xml api.

https://github.com/CpanelInc/xmlapi-php

i can create subdomains and delete them.

Now i want to list the subdomains.

Here is the Answer in API1 level

$listSubdomain = $xml->api1_query( $cp_un, 'SubDomain', 'listsubdomainsop');

$listSubdomainpaths = $xml->api1_query( $cp_un, 'SubDomain', 'cplistsubdomains');

Body:
You can use the following:

$subdomainsList = $xml->api2_query($cpanelUser, 'SubDomain', 'listsubdomains');

If you want, it is possible to filter results using a PCRE regex:

$subdomainsList = $xml->api2_query($cpanelUser, 'SubDomain', 'listsubdomains', [
    'regex' => '\bMySubdomain\b'
]);


问:
Build grid rows based on columns widths array PHP
I have an array of column widths +  content that I need to process and build row  based on them.

```<code>$content = array(
    '100',
    '80',
    '25',
    '25',
    '25',
    '25',
    '50',
    '50',
    '-1',
    '33.333333333333',
    '33.333333333333',
    '33.333333333333',
    '50',
    '50',
    '100',
    '16.666666666667',
    '-1'
);
</code>```

-1  means that this is not a column , but a text or shortcode and it should not be wrapped in to row.

from the above array desired processed array should be

```<code>$content = array(
    '[row]100[/row]',
    '[row]80[/row]',
    '[row]25',
    '25',
    '25',
    '25[/row]',
    '[row]50',
    '50[/row]',
    '-1',
    '[row]33.333333333333',
    '33.333333333333',
    '33.333333333333[/row]',
    '[row]50',
    '50[/row]',
    '[row]100[/row]',
    '[row]16.666666666667[/row]',
    '-1'
);
</code>```

I have tried a loop with a starting accumulator 0 that I was adding width from loop but is simply buggy.

Any help is appreciated.

答:
```<code>$sum = 100;
$new_content = array();
$prev = false;
for($i=0;$i<count($content);$i++){
    $num = $content[$i];
    $diff = $sum-$num;
    echo $num.'=>'.$diff.',';
    if(!$prev && $diff==0){
        $new_content[] = "[row]".$content[$i]."[/row]";
    }

    if($diff==0 && $prev){
        $new_content[] = $content[$i]."[/row]";
        $sum=100;
        $prev = false;
    }

    if($diff>0 && $diff<100 && $prev && $content[$i]!=-1){
        $new_content[] = $content[$i];
        $sum = $diff;
        $prev = true;
    }

    if($diff>0 && $diff<100 && !$prev){
         $new_content[] = "[row]".$content[$i];
         $sum = $diff;
         $prev = true;
    }
    if($diff<0){
        $new_content[] = "[/row][row]".$content[$i];
        $sum = 100-$content[$i];
        $prev = true;
    }
    if($content[$i]==-1 && $prev){
        $new_content[] = "[/row]".$content[$i];
    }else if($content[$i]==-1){
        $new_content[] = $content[$i];
    }

}

print_r($new_content);
</code>```

Body:
I have an array of column widths +  content that I need to process and build row  based on them.

$content = array(
    '100',
    '80',
    '25',
    '25',
    '25',
    '25',
    '50',
    '50',
    '-1',
    '33.333333333333',
    '33.333333333333',
    '33.333333333333',
    '50',
    '50',
    '100',
    '16.666666666667',
    '-1'
);

-1  means that this is not a column , but a text or shortcode and it should not be wrapped in to row.

from the above array desired processed array should be

$content = array(
    '[row]100[/row]',
    '[row]80[/row]',
    '[row]25',
    '25',
    '25',
    '25[/row]',
    '[row]50',
    '50[/row]',
    '-1',
    '[row]33.333333333333',
    '33.333333333333',
    '33.333333333333[/row]',
    '[row]50',
    '50[/row]',
    '[row]100[/row]',
    '[row]16.666666666667[/row]',
    '-1'
);

I have tried a loop with a starting accumulator 0 that I was adding width from loop but is simply buggy.

Any help is appreciated.


问:
C++ manipulation of HUGE vector using threads: can it be optimized further?
I have a very simple class that contains a single integer. The class has a single function that increments that integer by one. Basically:

```<code>class foo
{
public:
   int bar;
   foo(){bar = 1;}
   void inc() {bar++;}
};
</code>```

I also have a vector that contains 500 million instances of that class (as objects, not pointers).

I have a thread pool that waits to process that vector, with 16 threads (the number of cores on my machine). When I want to process the data, I make the threads run this function (where start/end are the portions of the vector each thread should process, ie...the vector divided evenly into [number of threads] sections):

```<code>void threadFn(vector<foo> &arr, int startInx, int endInx)
{
    for (int i = startInx; i < endInx; i++)
    {
        foo &f = arr[i];
        f.inc();
    }
}
</code>```

If I run this function on only 1 thread, it returns in ~750ms (which excludes the time it took to construct the vector). If I run this function on all 16 threads, it returns in ~100ms. So I'm getting 7.5x the speed, which is nice...but I want to know if there's anything I can do to push it further.

I've read a bit about false sharing, but am not exactly sure how to translate that problem into a practical optimization here in order to avoid it.

Basically I'm looking for any ideas that I can use to help to scale the speed of this algorithm up better with the number of cores used. Or is that not possible?

It might be worth noting beforehand, that my thread pool implementation is not part of the bottleneck. If I strip the loop out of the threadFn, the pool finishes its work in <1ms.

答:
Speed wise, your code is going to be fine; you are almost certainly memory IO bound.

Design wise, you probably want a span type rather than passing around a vector and a pair of ints.

The gsl has a span which represents a chunk of contiguous memory by storing two pointers.  Writing one yourself is easy:

```<code>template<class T>
struct span {
  T* b=0; T* e=0;
  T* begin() const { return b; }
  T* end() const { return b; }
  span( T* s, T* f ):b(s),e(f) {}
  span( T* s, std::size_t length):span(s, s+length) {}

  span() = default;
  span(span const&) = default;
  span& operator=(span const&) = default;
  ~span() = default;

  template<class U, std::size_t N,
    class=std::enable_if_t< std::is_same<std::decay_t<U>, std::decay_t<T>>::value>
  >
  span( U(& arr)[N] ):span(arr, N) {}
  template<class C,
    class=decltype( std::declval<C>().data() ),
    class=std::enable_if_t< !std::is_same<std::decay_t<C>, span>::value >
  >
  span( C&& c ):span(c.data(), c.size()) {}

  // container-like operations:
  bool empty() const { return begin()==end(); }
  std::size_t size() const { return end()-begin(); }
  T& front() const { return *begin(); }
  T& back() const { return *std::prev(end()); }
  T* data() const { return begin(); }

  // create child spans:
  span without_front( std::size_t N=1 ) const {
    return { begin()+(std::min)(N, size()), end() };
  }
  span without_back( std::size_t N=1 ) const {
    return { begin(), end()-(std::min)(N, size()) };
  }
};
</code>```

now your code looks slicker:

```<code>void threadFn(span<Foo> foos)
{
  for (foo& f:foos)
  {
    f.inc();
  }
}
</code>```

as a bonus, non-vector stored data now works, like a std::array or anything else.

span implicitly converts from any std container with a .data() member that returns a pointer.

If your eventual problem involves more complex operations, and less data, you'll find you are less memory bound and more CPU bound.

This will increase your speedup beyond 7.5x over single threaded.  Eventually, as computation dominates over bandwidth, you could consider moving your work to the GPU; the time required to get to/from the GPU becomes the limiting factor.

You can usually determine if a process is CPU or memory bound by examining its growth rate in speed as you add more CPUs, assuming you have avoided contention in its implementation.  Often you can even see an inflection point.

If your problem involves multiple stages, stacking them so that they occur "more locally" may eventually improve this as well.

Body:
I have a very simple class that contains a single integer. The class has a single function that increments that integer by one. Basically:

class foo
{
public:
   int bar;
   foo(){bar = 1;}
   void inc() {bar++;}
};

I also have a vector that contains 500 million instances of that class (as objects, not pointers).

I have a thread pool that waits to process that vector, with 16 threads (the number of cores on my machine). When I want to process the data, I make the threads run this function (where start/end are the portions of the vector each thread should process, ie...the vector divided evenly into [number of threads] sections):

void threadFn(vector<foo> &arr, int startInx, int endInx)
{
    for (int i = startInx; i < endInx; i++)
    {
        foo &f = arr[i];
        f.inc();
    }
}

If I run this function on only 1 thread, it returns in ~750ms (which excludes the time it took to construct the vector). If I run this function on all 16 threads, it returns in ~100ms. So I'm getting 7.5x the speed, which is nice...but I want to know if there's anything I can do to push it further.

I've read a bit about false sharing, but am not exactly sure how to translate that problem into a practical optimization here in order to avoid it.

Basically I'm looking for any ideas that I can use to help to scale the speed of this algorithm up better with the number of cores used. Or is that not possible?

It might be worth noting beforehand, that my thread pool implementation is not part of the bottleneck. If I strip the loop out of the threadFn, the pool finishes its work in <1ms.

Body:
Speed wise, your code is going to be fine; you are almost certainly memory IO bound.

Design wise, you probably want a span type rather than passing around a vector and a pair of ints.

The gsl has a span which represents a chunk of contiguous memory by storing two pointers.  Writing one yourself is easy:

template<class T>
struct span {
  T* b=0; T* e=0;
  T* begin() const { return b; }
  T* end() const { return b; }
  span( T* s, T* f ):b(s),e(f) {}
  span( T* s, std::size_t length):span(s, s+length) {}

  span() = default;
  span(span const&) = default;
  span& operator=(span const&) = default;
  ~span() = default;

  template<class U, std::size_t N,
    class=std::enable_if_t< std::is_same<std::decay_t<U>, std::decay_t<T>>::value>
  >
  span( U(& arr)[N] ):span(arr, N) {}
  template<class C,
    class=decltype( std::declval<C>().data() ),
    class=std::enable_if_t< !std::is_same<std::decay_t<C>, span>::value >
  >
  span( C&& c ):span(c.data(), c.size()) {}

  // container-like operations:
  bool empty() const { return begin()==end(); }
  std::size_t size() const { return end()-begin(); }
  T& front() const { return *begin(); }
  T& back() const { return *std::prev(end()); }
  T* data() const { return begin(); }

  // create child spans:
  span without_front( std::size_t N=1 ) const {
    return { begin()+(std::min)(N, size()), end() };
  }
  span without_back( std::size_t N=1 ) const {
    return { begin(), end()-(std::min)(N, size()) };
  }
};

now your code looks slicker:

void threadFn(span<Foo> foos)
{
  for (foo& f:foos)
  {
    f.inc();
  }
}

as a bonus, non-vector stored data now works, like a std::array or anything else.

span implicitly converts from any std container with a .data() member that returns a pointer.

If your eventual problem involves more complex operations, and less data, you'll find you are less memory bound and more CPU bound.

This will increase your speedup beyond 7.5x over single threaded.  Eventually, as computation dominates over bandwidth, you could consider moving your work to the GPU; the time required to get to/from the GPU becomes the limiting factor.

You can usually determine if a process is CPU or memory bound by examining its growth rate in speed as you add more CPUs, assuming you have avoided contention in its implementation.  Often you can even see an inflection point.

If your problem involves multiple stages, stacking them so that they occur "more locally" may eventually improve this as well.


问:
java network programming TCP chat full duplex
I'm implementing a simple tcp chat between a server and a client. I'm using multi-threading so as the server and the client can send and receive data at the same time (full duplex). The program works but if the server has a console for both typing the sending message and also displaying receiving message (same case for client), I cannot edit my typed message that should be sent to server or client when a message has been received from the other side. For e.g:

run(server console):

input msg to send client:

you:

client: hi server

client: bye server.

For this example, i've typed a message to send to client while the client has already said hi server bye server. Before receiving from client, i see what i've typed but after receiving, I can't see the msg nor edit it.

I can only use console because im not good with GUI and i want the same console for both sending and receiving data.

The codes for the program are shown below.

```<code>import java.net.*;
import java.io.*;
import java.util.Scanner;
public class ThreadServerSend implements Runnable {
String d;
Socket s1 = null;
Scanner sc = new Scanner(System.in);
public ThreadServerSend(Socket s)
{
    s1=s;
}

public void run()
{
    System.out.println("input msg to send client: ");
    while (true){
    try{

        PrintStream p = new PrintStream(s1.getOutputStream());
    System.out.println("you: ");

                                d=sc.nextLine();
                                p.println(d);
                                if (d.charAt(d.length()-1)=='.'){
                            s1.close();
                            break;}
    }
    catch(IOException e){}
    }
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class ThreadServerReceive implements Runnable {

 String m;
Socket s2 = null;
Scanner sc = new Scanner(System.in);
public ThreadServerReceive(Socket s)
{
    s2=s;
}

public void run()
{
    while (true){
    try{

     BufferedReader b = new BufferedReader(new InputStreamReader(s2.getInputStream()));
        m = b.readLine();
                        System.out.println("client: "+m);

                        if (m.charAt(m.length()-1)=='.'){
                            s2.close();
                            break;}}
    catch(IOException e){}
    }
    }
}

import java.io.*;
import java.net.*;
import java.util.*;
public class Server {

public static void main(String[] args) throws UnknownHostException, IOException{
    // TODO Auto-generated method stub

    ServerSocket s = new ServerSocket(444);

            Socket s1 = s.accept();

            new Thread(new ThreadServerSend(s1)).start();
            ServerSocket s4 = new ServerSocket(443);
    Socket s2=s4.accept();
    new Thread(new ThreadServerReceive(s2)).start();

}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class ThreadClientSend implements Runnable {

 String d;
Socket s1 = null;
Scanner sc = new Scanner(System.in);
public ThreadClientSend(Socket s)
{
    s1=s;
}

public void run()
{
    System.out.println("Input msg to send server: ");
    while (true){
    try{

        PrintStream p = new PrintStream(s1.getOutputStream());

    System.out.println("you: ");
    String d = new Scanner(System.in).nextLine();

    p.println(d);
            if (d.charAt(d.length()-1)=='.'){
                            s1.close();
                            break;}
      }
    catch(IOException e){}
    }
    }

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class ThreadClientReceive implements Runnable {

 String m;
Socket s1 = null;
Scanner sc = new Scanner(System.in);
public ThreadClientReceive (Socket s)
{
    s1=s;
}

public void run()
{
    while (true){
    try{
        BufferedReader b = new BufferedReader(new InputStreamReader(s1.getInputStream()));
        m= b.readLine();
        System.out.println("Server: "+m);
                     if (m.charAt(m.length()-1)=='.')
                        {
                            s1.close();
                              break;
                        }
      }
    catch(IOException e){}
    }
    }

}

import java.io.*;
import java.net.*;
import java.util.*;
public class Client {

public static void main(String[] args) throws UnknownHostException, IOException{
    // TODO Auto-generated method stub

    Socket s1= new Socket("localhost",444);
            Socket s2 = new Socket("localhost",443);
            new Thread(new ThreadClientReceive(s1)).start();

    new Thread(new ThreadClientSend(s2)).start();

}

}
</code>```

答:
A bit late, but I actually came up with a working version of this chat client for my programming class. I thought I might as well post it here. I used TCP (full duplex) with multithreading, and I got it to work in console. The small problem is that you can't see your own name (because console has only one active line), but otherwise it works pretty well.

Server (client is more or less the same, obviously the Sockets are normal sockets, not ServerSockets):

```<code>import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.io.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;

@SuppressWarnings("serial")
public class serverProgII extends Thread
{

private static ObjectOutputStream oos;
private static ObjectInputStream ois;
private static Socket connection;
private static ServerSocket server;
private static String ip, clientIP, textin, exitword ="exit";
private static networkmessage nmessage;
private static boolean connected = false;
private static boolean done = false;
private static String myName = "";
private static int counter = 0;

public static boolean started = false;
public String type;

public static void main(String[] args)
{
    try {
        BufferedReader brin = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter your name:> "); //send prompt to DOS window
        myName = brin.readLine();       //read in user input
        setupConnection();
        setupStreams();
        started = true;
    } catch (Exception e) {
        System.out.println("Problem setting up streams and connection!");
    }

    serverProgII sender = new serverProgII("sender");
    serverProgII receiver = new serverProgII("receiver");
    sender.start();
    receiver.start();
}

public serverProgII(String t)
{
    super();
    type = t;
}

public void run() {
    while(started) {
        switch(type) {
            case "sender":
                sender();
                break;
            case "receiver":
                receiver();
                break;
        }
        try {
            Thread.sleep(500); //milliseconds
        } catch(Exception e){}
    }
}

/*  runServer()
    This is where all the actual work gets done.
*/

public void sender()
{
    try {

        BufferedReader inn = new BufferedReader(new InputStreamReader(System.in));
        textin = inn.readLine();

        sendData(textin);

        if (textin.equals(exitword))  // if "exit" is typed in shutdown the server.
        {
            started = false;
            serverShutdown();
        }

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

public void receiver() {
    try {
        getData();
    } catch(Exception e) {
        System.out.println("Error getting data");
    }
}

//setup connection
public static void setupConnection() throws IOException
{
    System.out.println("SERVER MODE ACTIVATED");
    server = new ServerSocket (8000);                       //create the socket at port 8000
    System.out.println("Waiting For Connection...");
    connection = server.accept();                           //wait for a connection
    System.out.println("Received connection: "+connection.getInetAddress());
    clientIP=""+connection.getInetAddress();                //print out the client IP address

}//setupconnection()

//Setup streams connection
public static void setupStreams() throws IOException
{
    //Open up Streams
    System.out.println("Streams Setup");
    oos=new ObjectOutputStream(connection.getOutputStream()); //construct object output stream
    ois=new ObjectInputStream(connection.getInputStream());
    oos.flush();

}//setupStreams()

//method to write/send network data
public void sendData(String toSend) throws IOException
{
    try
    {
        nmessage = new networkmessage(myName, toSend);
        oos.writeObject(nmessage);
    }//try

    catch (IOException ioException)
    {
        System.out.println("IO exception in sendData");
    }

}//sendData()

//method to read in network data
public void getData() throws IOException
{
    try
    {
        networkmessage messageIn =(networkmessage)(ois.readObject());
        System.out.println(messageIn.ipnum +" << "+messageIn.text);

    }//try

    catch (Exception exp1)
    {
        System.out.println("IO exception in sendData");
    }
}//getData()

public void serverShutdown()
{
    System.out.println("exiting initiated");

    try
    {
        done = true;
        textin = "Chat is terminated.  Have a nice day.";
        oos.close();
        server.close();
        connection.close();
    }

    catch (Exception One)
    {
        System.out.println("bad termination");
    }
}

}  // class serverProg
</code>```

Body:
I'm implementing a simple tcp chat between a server and a client. I'm using multi-threading so as the server and the client can send and receive data at the same time (full duplex). The program works but if the server has a console for both typing the sending message and also displaying receiving message (same case for client), I cannot edit my typed message that should be sent to server or client when a message has been received from the other side. For e.g:

run(server console):

input msg to send client:

you:

client: hi server

client: bye server.

For this example, i've typed a message to send to client while the client has already said hi server bye server. Before receiving from client, i see what i've typed but after receiving, I can't see the msg nor edit it.

I can only use console because im not good with GUI and i want the same console for both sending and receiving data.

The codes for the program are shown below.

import java.net.*;
import java.io.*;
import java.util.Scanner;
public class ThreadServerSend implements Runnable {
String d;
Socket s1 = null;
Scanner sc = new Scanner(System.in);
public ThreadServerSend(Socket s)
{
    s1=s;
}

public void run()
{
    System.out.println("input msg to send client: ");
    while (true){
    try{

        PrintStream p = new PrintStream(s1.getOutputStream());
    System.out.println("you: ");

                                d=sc.nextLine();
                                p.println(d);
                                if (d.charAt(d.length()-1)=='.'){
                            s1.close();
                            break;}
    }
    catch(IOException e){}
    }
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class ThreadServerReceive implements Runnable {

 String m;
Socket s2 = null;
Scanner sc = new Scanner(System.in);
public ThreadServerReceive(Socket s)
{
    s2=s;
}

public void run()
{
    while (true){
    try{

     BufferedReader b = new BufferedReader(new InputStreamReader(s2.getInputStream()));
        m = b.readLine();
                        System.out.println("client: "+m);

                        if (m.charAt(m.length()-1)=='.'){
                            s2.close();
                            break;}}
    catch(IOException e){}
    }
    }
}

import java.io.*;
import java.net.*;
import java.util.*;
public class Server {

public static void main(String[] args) throws UnknownHostException, IOException{
    // TODO Auto-generated method stub

    ServerSocket s = new ServerSocket(444);

            Socket s1 = s.accept();

            new Thread(new ThreadServerSend(s1)).start();
            ServerSocket s4 = new ServerSocket(443);
    Socket s2=s4.accept();
    new Thread(new ThreadServerReceive(s2)).start();

}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class ThreadClientSend implements Runnable {

 String d;
Socket s1 = null;
Scanner sc = new Scanner(System.in);
public ThreadClientSend(Socket s)
{
    s1=s;
}

public void run()
{
    System.out.println("Input msg to send server: ");
    while (true){
    try{

        PrintStream p = new PrintStream(s1.getOutputStream());

    System.out.println("you: ");
    String d = new Scanner(System.in).nextLine();

    p.println(d);
            if (d.charAt(d.length()-1)=='.'){
                            s1.close();
                            break;}
      }
    catch(IOException e){}
    }
    }

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class ThreadClientReceive implements Runnable {

 String m;
Socket s1 = null;
Scanner sc = new Scanner(System.in);
public ThreadClientReceive (Socket s)
{
    s1=s;
}

public void run()
{
    while (true){
    try{
        BufferedReader b = new BufferedReader(new InputStreamReader(s1.getInputStream()));
        m= b.readLine();
        System.out.println("Server: "+m);
                     if (m.charAt(m.length()-1)=='.')
                        {
                            s1.close();
                              break;
                        }
      }
    catch(IOException e){}
    }
    }

}

import java.io.*;
import java.net.*;
import java.util.*;
public class Client {

public static void main(String[] args) throws UnknownHostException, IOException{
    // TODO Auto-generated method stub

    Socket s1= new Socket("localhost",444);
            Socket s2 = new Socket("localhost",443);
            new Thread(new ThreadClientReceive(s1)).start();

    new Thread(new ThreadClientSend(s2)).start();

}

}

Body:
A bit late, but I actually came up with a working version of this chat client for my programming class. I thought I might as well post it here. I used TCP (full duplex) with multithreading, and I got it to work in console. The small problem is that you can't see your own name (because console has only one active line), but otherwise it works pretty well.

Server (client is more or less the same, obviously the Sockets are normal sockets, not ServerSockets):

import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.io.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;

@SuppressWarnings("serial")
public class serverProgII extends Thread
{

private static ObjectOutputStream oos;
private static ObjectInputStream ois;
private static Socket connection;
private static ServerSocket server;
private static String ip, clientIP, textin, exitword ="exit";
private static networkmessage nmessage;
private static boolean connected = false;
private static boolean done = false;
private static String myName = "";
private static int counter = 0;

public static boolean started = false;
public String type;

public static void main(String[] args)
{
    try {
        BufferedReader brin = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter your name:> "); //send prompt to DOS window
        myName = brin.readLine();       //read in user input
        setupConnection();
        setupStreams();
        started = true;
    } catch (Exception e) {
        System.out.println("Problem setting up streams and connection!");
    }

    serverProgII sender = new serverProgII("sender");
    serverProgII receiver = new serverProgII("receiver");
    sender.start();
    receiver.start();
}

public serverProgII(String t)
{
    super();
    type = t;
}

public void run() {
    while(started) {
        switch(type) {
            case "sender":
                sender();
                break;
            case "receiver":
                receiver();
                break;
        }
        try {
            Thread.sleep(500); //milliseconds
        } catch(Exception e){}
    }
}

/*  runServer()
    This is where all the actual work gets done.
*/

public void sender()
{
    try {

        BufferedReader inn = new BufferedReader(new InputStreamReader(System.in));
        textin = inn.readLine();

        sendData(textin);

        if (textin.equals(exitword))  // if "exit" is typed in shutdown the server.
        {
            started = false;
            serverShutdown();
        }

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

public void receiver() {
    try {
        getData();
    } catch(Exception e) {
        System.out.println("Error getting data");
    }
}

//setup connection
public static void setupConnection() throws IOException
{
    System.out.println("SERVER MODE ACTIVATED");
    server = new ServerSocket (8000);                       //create the socket at port 8000
    System.out.println("Waiting For Connection...");
    connection = server.accept();                           //wait for a connection
    System.out.println("Received connection: "+connection.getInetAddress());
    clientIP=""+connection.getInetAddress();                //print out the client IP address

}//setupconnection()

//Setup streams connection
public static void setupStreams() throws IOException
{
    //Open up Streams
    System.out.println("Streams Setup");
    oos=new ObjectOutputStream(connection.getOutputStream()); //construct object output stream
    ois=new ObjectInputStream(connection.getInputStream());
    oos.flush();

}//setupStreams()

//method to write/send network data
public void sendData(String toSend) throws IOException
{
    try
    {
        nmessage = new networkmessage(myName, toSend);
        oos.writeObject(nmessage);
    }//try

    catch (IOException ioException)
    {
        System.out.println("IO exception in sendData");
    }

}//sendData()

//method to read in network data
public void getData() throws IOException
{
    try
    {
        networkmessage messageIn =(networkmessage)(ois.readObject());
        System.out.println(messageIn.ipnum +" << "+messageIn.text);

    }//try

    catch (Exception exp1)
    {
        System.out.println("IO exception in sendData");
    }
}//getData()

public void serverShutdown()
{
    System.out.println("exiting initiated");

    try
    {
        done = true;
        textin = "Chat is terminated.  Have a nice day.";
        oos.close();
        server.close();
        connection.close();
    }

    catch (Exception One)
    {
        System.out.println("bad termination");
    }
}

}  // class serverProg


问:
The Canvas Background and the HTML  Element
According to the spec:

It is recommended that authors of HTML documents specify the canvas background for the BODY element rather than the HTML element.

But it doesn't say what advantages it has. Why does the spec recommend this?

P.S. It crossed my mind when I saw Extra scrollbar when body height is 100vh: isn't it better to simply give the background to the html element instead?

答:
My answer will be quicker, because BoltClock's one and the spec explain it minutely.

It is a matter of efficiency.

If you think about the fact that the UA should "[use the] values of that BODY element's background properties are their initial values", it makes sense to assign these values to the body tag.
If you use the html tag, UA may use a kind of fallback to display it, which is time consuming.
Of course, it's nothing for nowadays computers, but what about mobile devices, displaying let's said a background image with a cover background-size?

Furthermore, the order of html tags is a logical one, the link tags are defined in the head, in order to be used for the body and his childrens that come after. But if you apply a css rule to the html tag, the UA may go backward... And then forward.

So what are the advantages of specifying the canvas background for the BODY element? Quite nothing, for you, but some microseconds for the user, some microwatts for the client and the servers, but small streams make big rivers.

The w3c may have decided to do the opposite, it will have been ok too, it's just the purpose of a standard, that you make what a browser expects of you.

What? iOS does not respect the rules? (they can, they are apple). Don't change the correct way to do that, use media queries.

Title: The Canvas Background and the HTML <body> Element


问:
Trying to save word file, from excel vba, without over-writing any existing files
Trying to save word file, from excel vba, without over-writing any existing files.  The possibility exists that the filename chosen (taken from the spreadsheet) may be a duplicate, in which case I would like to pause or stop the code, but instead it over-writes automatically)  As below, though my two prong attempt to error catch fails, and the word document is over written:</p>

```<code>Sub automateword()

        Dim fileToOpen As String
        Dim intChoice As Integer
        Dim myFile As Object

        mysheet = ActiveWorkbook.Name
        Set Wst = Workbooks(mysheet).ActiveSheet

    Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show

If intChoice <> 0 Then
'get the file path selected by the user
fileToOpen = Application.FileDialog( _
msoFileDialogOpen).SelectedItems(1)

End If

    Set wordapp = CreateObject("word.Application")

    Set myFile = wordapp.documents.Add(fileToOpen)

    i = 1
    Do Until IsEmpty(Wst.Cells(i, 2))
        i = i + 1

    Loop
    i = i - 1

    wordapp.Visible = True
    Filename = Wst.Cells(i, 2) + " " + Wst.Cells(i, 3) + Str(Wst.Cells(i, 10))

    On Error GoTo errorline
    wordapp.DisplayAlerts = True
    FullPath = "\\networkpath\" & Filename & ".doc"
    myFile.SaveAs (FullPath)

Exit Sub
errorline:
MsgBox ("filename error")
End Sub
</code>```

答:
You can add this if-statement before adding a word document.

If Dir(fileToOpen) <> "" Then Exit Sub

Body:
Trying to save word file, from excel vba, without over-writing any existing files.  The possibility exists that the filename chosen (taken from the spreadsheet) may be a duplicate, in which case I would like to pause or stop the code, but instead it over-writes automatically)  As below, though my two prong attempt to error catch fails, and the word document is over written:

Sub automateword()

        Dim fileToOpen As String
        Dim intChoice As Integer
        Dim myFile As Object

        mysheet = ActiveWorkbook.Name
        Set Wst = Workbooks(mysheet).ActiveSheet

    Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show

If intChoice <> 0 Then
'get the file path selected by the user
fileToOpen = Application.FileDialog( _
msoFileDialogOpen).SelectedItems(1)

End If

    Set wordapp = CreateObject("word.Application")

    Set myFile = wordapp.documents.Add(fileToOpen)

    i = 1
    Do Until IsEmpty(Wst.Cells(i, 2))
        i = i + 1

    Loop
    i = i - 1

    wordapp.Visible = True
    Filename = Wst.Cells(i, 2) + " " + Wst.Cells(i, 3) + Str(Wst.Cells(i, 10))

    On Error GoTo errorline
    wordapp.DisplayAlerts = True
    FullPath = "\\networkpath\" & Filename & ".doc"
    myFile.SaveAs (FullPath)

Exit Sub
errorline:
MsgBox ("filename error")
End Sub


问:
How to attach IntelliJ Go debugger to local process
I'm coding in Go using IntelliJ IDEA with Go plugin. I am working on a project that uses gocui, which doesn't work in IntelliJ console window. So I run my program from console. </p>

<p>How can I attach this wonderful IntelliJ debugger to the process that runs outside IntelliJ (in my console)? I tried run -> attach to local process, but it showed an empty box. </p>

答: I discovered by accident one trick that allows to run my application in normal console from IntelliJ. Simply run IntelliJ from a console. Then, if I run (or debug) my application, it opens in that console. </p>

Body:
I'm coding in Go using IntelliJ IDEA with Go plugin. I am working on a project that uses gocui, which doesn't work in IntelliJ console window. So I run my program from console.

How can I attach this wonderful IntelliJ debugger to the process that runs outside IntelliJ (in my console)? I tried run -> attach to local process, but it showed an empty box.


问:
Button aligned to bottom of RelativeLayout is cut off
I have a button in my RelativeLayout that is being cut off when I use android:layout_alignParentBottom="true" but nothing else I try is working correctly either. Any ideas?

Here is my layout:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.cdar.sab.cdar.MainActivity$PlaceholderFragment">

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/diagnostics_title" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:layout_below="@+id/section_label"
        android:layout_alignParentStart="true"
        android:layout_marginTop="42dp"
        android:hint="@string/email_hint"
        android:id="@+id/emailTB" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:ems="10"
        android:layout_below="@+id/emailTB"
        android:layout_alignParentStart="true"
        android:layout_marginTop="45dp"
        android:hint="@string/message_hint"
        android:maxLines="10"
        android:id="@+id/messageTB" />

    <Button
        android:text="Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:layout_alignParentBottom="true" />

</RelativeLayout>
</code>```

答:
You need to add a outer relative layout to your Button</p>

```<code><RelativeLayout..............>
    <RelativeLayout android:id="@+id/content_rl>
    <!-- Some ELEMENTS -->
    </RelativeLayout>

    <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/content_rl">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="Button" />
</RelativeLayout>
</code>```

Body:
I have a button in my RelativeLayout that is being cut off when I use android:layout_alignParentBottom="true" but nothing else I try is working correctly either. Any ideas?

Here is my layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.cdar.sab.cdar.MainActivity$PlaceholderFragment">

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/diagnostics_title" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:layout_below="@+id/section_label"
        android:layout_alignParentStart="true"
        android:layout_marginTop="42dp"
        android:hint="@string/email_hint"
        android:id="@+id/emailTB" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:ems="10"
        android:layout_below="@+id/emailTB"
        android:layout_alignParentStart="true"
        android:layout_marginTop="45dp"
        android:hint="@string/message_hint"
        android:maxLines="10"
        android:id="@+id/messageTB" />

    <Button
        android:text="Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:layout_alignParentBottom="true" />

</RelativeLayout>

Body:
You need to add a outer relative layout to your Button

<RelativeLayout..............>
    <RelativeLayout android:id="@+id/content_rl>
    <!-- Some ELEMENTS -->
    </RelativeLayout>

    <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/content_rl">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="Button" />
</RelativeLayout>


问:
How can I place a dot before the last three digits in a terminal output
What is the best way to place a dot after the last three dots in a terminal output?

I want to get from this: 10902MB/88%

to this: 10.902MB/88%

Currently I have this command for that:

```<code>df -m /dev/sda8 | grep -Eo '[0-9]*  [0-9]*%'| sed 's/  */MB\//g'
</code>```

Edit

The output of `df -m /dev/sda8 is

```<code>Filesystem     1M-blocks  Used Available Use% Mounted on
/dev/sda8          90349 74910     10828  88% /
</code>```

I need only the Available and Use% values.

答:
You are trying to get values of "Available" and "Use%" sections from df command output for a certain mounted file system.

Use the following sed approach:

```<code>df -m /dev/sda8 | sed -En 's~.* ([0-9]+)([0-9]{3}) +([0-9]+%).*~\1.\2MB/\3~gp'
</code>```

Body:
What is the best way to place a dot after the last three dots in a terminal output?

I want to get from this: 10902MB/88%

to this: 10.902MB/88%

Currently I have this command for that:

df -m /dev/sda8 | grep -Eo '[0-9]*  [0-9]*%'| sed 's/  */MB\//g'

Edit

The output of `df -m /dev/sda8 is

Filesystem     1M-blocks  Used Available Use% Mounted on
/dev/sda8          90349 74910     10828  88% /

I need only the Available and Use% values.

Body:
You are trying to get values of "Available" and "Use%" sections from df command output for a certain mounted file system.

Use the following sed approach:

df -m /dev/sda8 | sed -En 's~.* ([0-9]+)([0-9]{3}) +([0-9]+%).*~\1.\2MB/\3~gp'