问:
ClassNotFoundException extending Android MultiDexApplication class
I'm spending hours to solve this problem, but can't find a solution between the dozens of replies for similar problems.

So there's my problem. I'm creating a simple multidex Android app and I need to execute some things at app startup. So, I've extended the MultiDexApplication class, added the class path to application element on AndroidManifest.xml file but crashes every time I run it with the following exception:

```<code>java.lang.RuntimeException: Unable to instantiate application rmpt.app.MyApplication: java.lang.ClassNotFoundException: Didn't find class "rmpt.app.MyApplication" on path: DexPathList[[zip file "/data/app/rmpt.app-1.apk"],nativeLibraryDirectories=[/data/app-lib/rmpt.app-1, /vendor/lib, /system/lib, /system/lib/arm]]
   at android.app.LoadedApk.makeApplication(LoadedApk.java:509)
   at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4472)
   at android.app.ActivityThread.access$1300(ActivityThread.java:144)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
   at android.os.Handler.dispatchMessage(Handler.java:99)
   at android.os.Looper.loop(Looper.java:150)
   at android.app.ActivityThread.main(ActivityThread.java:5162)
   at java.lang.reflect.Method.invokeNative(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:525)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:744)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
   at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: Didn't find class "rmpt.app.MyApplication" on path: DexPathList[[zip file "/data/app/rmpt.app-1.apk"],nativeLibraryDirectories=[/data/app-lib/rmpt.app-1, /vendor/lib, /system/lib, /system/lib/arm]]
   at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:53)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
   at android.app.Instrumentation.newApplication(Instrumentation.java:975)
   at android.app.LoadedApk.makeApplication(LoadedApk.java:504)
   at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4472)
   at android.app.ActivityThread.access$1300(ActivityThread.java:144)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
   at android.os.Handler.dispatchMessage(Handler.java:99)
   at android.os.Looper.loop(Looper.java:150)
   at android.app.ActivityThread.main(ActivityThread.java:5162)
   at java.lang.reflect.Method.invokeNative(Native Method)
</code>```

If I remove the android:name attribute from the AndroidManifest.xml file (so it uses the default android Application class) everything works fine, but I NEED to execute some things at onCreate method of my application.

I leave here my files so you can see them and maybe see something wrong (already 2 days trying to solve this problem for me)

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="rmpt.app">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:name=".MyApplication">

        <activity android:name=".view.LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>
</code>```

MyApplication.java

```<code>package rmpt.app;

import android.support.multidex.MultiDexApplication;

public class MyApplication extends MultiDexApplication {

    @Override
    public void onCreate() {
        super.onCreate();

        // do my stuff
    }
}
</code>```

build.gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "25.0.2"

    defaultConfig {
        applicationId "rmpt.app"
        minSdkVersion 18
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true

        jackOptions {
            enabled true
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    dexOptions {
        javaMaxHeapSize "2g"
    }

    packagingOptions{
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/LICENSE'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.google.android.gms:play-services:9.4.0'
    compile 'com.android.support:design:23.4.0'

}
</code>```

I'm working on MacOS 10.11.6

答:
Please follow the instructions at this link. They fix the error you have encountered.

According to Android Documentation

the primary classes.dex must contain the classes necessary for calling
  this class methods.

ie, MyApplication must be a part of classes.dex as it calls the MultiDex#install(Context) method. The instructions in the aforementioned link help you decide which classes must be included in the primary dex file (classes.dex)

Body:
I'm spending hours to solve this problem, but can't find a solution between the dozens of replies for similar problems.

So there's my problem. I'm creating a simple multidex Android app and I need to execute some things at app startup. So, I've extended the MultiDexApplication class, added the class path to application element on AndroidManifest.xml file but crashes every time I run it with the following exception:

java.lang.RuntimeException: Unable to instantiate application rmpt.app.MyApplication: java.lang.ClassNotFoundException: Didn't find class "rmpt.app.MyApplication" on path: DexPathList[[zip file "/data/app/rmpt.app-1.apk"],nativeLibraryDirectories=[/data/app-lib/rmpt.app-1, /vendor/lib, /system/lib, /system/lib/arm]]
   at android.app.LoadedApk.makeApplication(LoadedApk.java:509)
   at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4472)
   at android.app.ActivityThread.access$1300(ActivityThread.java:144)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
   at android.os.Handler.dispatchMessage(Handler.java:99)
   at android.os.Looper.loop(Looper.java:150)
   at android.app.ActivityThread.main(ActivityThread.java:5162)
   at java.lang.reflect.Method.invokeNative(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:525)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:744)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
   at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: Didn't find class "rmpt.app.MyApplication" on path: DexPathList[[zip file "/data/app/rmpt.app-1.apk"],nativeLibraryDirectories=[/data/app-lib/rmpt.app-1, /vendor/lib, /system/lib, /system/lib/arm]]
   at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:53)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
   at android.app.Instrumentation.newApplication(Instrumentation.java:975)
   at android.app.LoadedApk.makeApplication(LoadedApk.java:504)
   at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4472)
   at android.app.ActivityThread.access$1300(ActivityThread.java:144)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
   at android.os.Handler.dispatchMessage(Handler.java:99)
   at android.os.Looper.loop(Looper.java:150)
   at android.app.ActivityThread.main(ActivityThread.java:5162)
   at java.lang.reflect.Method.invokeNative(Native Method)

If I remove the android:name attribute from the AndroidManifest.xml file (so it uses the default android Application class) everything works fine, but I NEED to execute some things at onCreate method of my application.

I leave here my files so you can see them and maybe see something wrong (already 2 days trying to solve this problem for me)

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="rmpt.app">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:name=".MyApplication">

        <activity android:name=".view.LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

MyApplication.java

package rmpt.app;

import android.support.multidex.MultiDexApplication;

public class MyApplication extends MultiDexApplication {

    @Override
    public void onCreate() {
        super.onCreate();

        // do my stuff
    }
}

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "25.0.2"

    defaultConfig {
        applicationId "rmpt.app"
        minSdkVersion 18
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true

        jackOptions {
            enabled true
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    dexOptions {
        javaMaxHeapSize "2g"
    }

    packagingOptions{
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/LICENSE'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.google.android.gms:play-services:9.4.0'
    compile 'com.android.support:design:23.4.0'

}

I'm working on MacOS 10.11.6


来源: stackexchange

问:
RethinkDB on success Update returns empty object
I have wrote an API usin NodeJS + ExpressJS + RethinkDB. But I got a problem with returning data result while doing update or insert.

In the following example function does update. Query works as should, but inside result is empty object {}, but should return object with old/new data and other state data.

Query

```<code>router.put( '/users/contact_data/:user_id', ( request, response ) => {
    let user_id = request.params.user_id;
    let updateFields = clean_obj.getCleanObject(request.body);

    r.db(db_name).table( 'User' )
        .get( user_id )
        .do((client)=>{
                return r.db("Planner").table('ContactData')
                    .get(client("contact_data_id"))
                    .update(
                        updateFields,
                        {
                            returnChanges: true
                        }
                    )
            }
        )
        .run( request._rdb )
        .then( cursor => cursor.toArray() )
        .then( result => {
            response.send( result );
        } )
        .catch( error => response.send( error ) );
} );
</code>```

Expected Result should look like (copied from rethinkdb docs):

```<code>{
    deleted: 0,
    errors: 0,
    inserted: 0,
    changes: [
        {
            new_val: {
                id: 1,
                author: "Julius_Caesar",
                title: "Commentarii de Bello Gallico",
                content: "Aleas jacta est",
                views: 207
            },
            old_val: {
                id: 1,
                author: "Julius_Caesar",
                title: "Commentarii de Bello Gallico",
                content: "Aleas jacta est",
                views: 206
            }
        }
    ],
    replaced: 1,
    skipped: 0,
    unchanged: 0
}
</code>```

I can't understand what am I doing wrong...

答:
You are treating the response as a cursor:

```<code>.then(cursor => cursor.toArray())
</code>```

But in reality, the response should be a plain object.

ContentLicense: CC BY-SA 3.0

Body:
I have wrote an API usin NodeJS + ExpressJS + RethinkDB. But I got a problem with returning data result while doing update or insert.

In the following example function does update. Query works as should, but inside result is empty object {}, but should return object with old/new data and other state data.

Query

router.put( '/users/contact_data/:user_id', ( request, response ) => {
    let user_id = request.params.user_id;
    let updateFields = clean_obj.getCleanObject(request.body);

    r.db(db_name).table( 'User' )
        .get( user_id )
        .do((client)=>{
                return r.db("Planner").table('ContactData')
                    .get(client("contact_data_id"))
                    .update(
                        updateFields,
                        {
                            returnChanges: true
                        }
                    )
            }
        )
        .run( request._rdb )
        .then( cursor => cursor.toArray() )
        .then( result => {
            response.send( result );
        } )
        .catch( error => response.send( error ) );
} );

Expected Result should look like (copied from rethinkdb docs):

{
    deleted: 0,
    errors: 0,
    inserted: 0,
    changes: [
        {
            new_val: {
                id: 1,
                author: "Julius_Caesar",
                title: "Commentarii de Bello Gallico",
                content: "Aleas jacta est",
                views: 207
            },
            old_val: {
                id: 1,
                author: "Julius_Caesar",
                title: "Commentarii de Bello Gallico",
                content: "Aleas jacta est",
                views: 206
            }
        }
    ],
    replaced: 1,
    skipped: 0,
    unchanged: 0
}

I can't understand what am I doing wrong...

Body:
You are treating the response as a cursor:

.then(cursor => cursor.toArray())

But in reality, the response should be a plain object.


问:
Find out specific Exception
Apologies for the lack of information...

Is there a way to find out what is the specific Exception that is causing a call to throw the Exception?

Currently, I am catching all the Exceptions by doing catch(Exception e) but I know this is not good practices at all.

Is there a way to know from the Exception what is the specific one that caused the issue so I can be more granular?

答:
You can catch different types of exceptions. With this solution you are able to handle the different types easily.</p>

```<code>try
{
    //Try something
}
catch (StackOverflowException soe)
{
    //Handle StackOverFlowException
}
catch (FormatException fe)
{
    //Handle FormatException
}
//... Other exceptions
</code>```

Title: Find out specific Exception

Body:
You can catch different types of exceptions. With this solution you are able to handle the different types easily.

try
{
    //Try something
}
catch (StackOverflowException soe)
{
    //Handle StackOverFlowException
}
catch (FormatException fe)
{
    //Handle FormatException
}
//... Other exceptions


问:
Less: Combining selector variables
Given i want to simplify the following LESS code:

```<code>@title1: ~"h1.someclass > a";
@title2: ~"h1.otherclass > a";

@{title1},@{title2} {
  &:after {
    display: none;
  }
}
</code>```

which evaluates to:

```<code>h1.someclass > a:after,
h1.otherclass > a:after {
  display: none;
}
</code>```

I tried to merge the classes by using

```<code>@titles: ~"@{title1},@{title2}"; // Combine selectors for easier code
@{titles} {
  &:after {
    display: none;
  }
}
</code>```

This however will yield different CSS.

```<code>h1.someclass > a,h1.otherclass > a:after {
  display: none;
}
</code>```

Is this due to the Lazy Evaluation of the variables? If so, why does it yield the CSS this way? And is there a diffrent way of combining selector variables and later using &:after?

答:
(almost copy-pasting from the more wide https://stackoverflow.com/a/23954580/271274)

There're two problems with your attempt:

By definition a content of escaped strings is not a subject for any kind of evaluation at all, so commas (as well as any other special ops) have no meaning there.

Variable interpolation in selectors assumes a single interpolated variable contains only a single selector element. So, strictly speaking, even ~"h1.someclass > a" is already nothing but a hack expected to have side-effects and unspecified/undefined behaviour for anything but extremely trivial cases.

So in your code above the value of @titles works just as a simple/single selector element (the same as body for example).

I.e. in summary and in general, "string-based selector manipulation" (like ~"@{title1}, @{title2}") should be avoided where possible simply because in Less selectors are not strings and strings are not selectors (nor they automatically converted to each other except in, yet again, certain extremely trivial cases).

So far the only non-hackish method to define a reusable list of selectors in Less is a mixin (mixins can be considered as "variables" too even if they have another syntax) that puts an arbitrary set of rules into a ruleset having the said list as its selector. E.g. for your example above it would be something like:

@title1: ~"h1.someclass  > a";
@title2: ~"h1.otherclass > a";

.titles(@rules) {
    @{title1}, @{title2} {@rules();}
}

// usage:

.titles({
    &:after {
        display: none;
    }
});
```

Demo.

Title: Less: Combining selector variables

Body:
Given i want to simplify the following LESS code:

@title1: ~"h1.someclass > a";
@title2: ~"h1.otherclass > a";

@{title1},@{title2} {
  &:after {
    display: none;
  }
}

which evaluates to:

h1.someclass > a:after,
h1.otherclass > a:after {
  display: none;
}

I tried to merge the classes by using

@titles: ~"@{title1},@{title2}"; // Combine selectors for easier code
@{titles} {
  &:after {
    display: none;
  }
}

This however will yield different CSS.

h1.someclass > a,h1.otherclass > a:after {
  display: none;
}

Is this due to the Lazy Evaluation of the variables? If so, why does it yield the CSS this way? And is there a diffrent way of combining selector variables and later using &:after?

Body:
(almost copy-pasting from the more wide https://stackoverflow.com/a/23954580/271274)

There're two problems with your attempt:

By definition a content of escaped strings is not a subject for any kind of evaluation at all, so commas (as well as any other special ops) have no meaning there.

Variable interpolation in selectors assumes a single interpolated variable contains only a single selector element. So, strictly speaking, even ~"h1.someclass > a" is already nothing but a hack expected to have side-effects and unspecified/undefined behaviour for anything but extremely trivial cases.

So in your code above the value of @titles works just as a simple/single selector element (the same as body for example).

I.e. in summary and in general, "string-based selector manipulation" (like ~"@{title1}, @{title2}") should be avoided where possible simply because in Less selectors are not strings and strings are not selectors (nor they automatically converted to each other except in, yet again, certain extremely trivial cases).

So far the only non-hackish method to define a reusable list of selectors in Less is a mixin (mixins can be considered as "variables" too even if they have another syntax) that puts an arbitrary set of rules into a ruleset having the said list as its selector. E.g. for your example above it would be something like:

@title1: ~"h1.someclass  > a";
@title2: ~"h1.otherclass > a";

.titles(@rules) {
    @{title1}, @{title2} {@rules();}
}

// usage:

.titles({
    &:after {
        display: none;
    }
});

Demo.


问:
Android Studio: Flexible Layout (Only with XML?)
I've got problems to make my layout flexible.

If I switch to landscape my buttons inside my gridlayout keep static. And there is a lot of space on the right side of my gridlayout.

I want to center my gridlayout and make the size of my buttons changeable to any device size.

My XML-Code here (showing only two buttons):

```<code><?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.fdai3744.taschenrechnerneu.MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_column="0"
        android:layout_row="0"
        style="@style/ButtonStyle"
        android:text="@string/cal_btn_clear" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_column="1"
        android:layout_row="0"
        style="@style/ButtonStyle"
        android:text="@string/cal_btn_clear_entry" />
</GridLayout>
</code>```

Is it possible only to use XML or should I also use Java?

答:
want to center my gridlayout:

Use:

```<code>android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
</code>```

in your GridLayout.

make the size of my buttons changeable to any device size:
In order to do that, you will have to create multiple values folders in your project so that you can support multiple screens. For example, ldpi, mdpi, hdpi, xhdpi, ..ect. There are plenty of resources on how to do that here in Stack.

Hope that helps.

Body:
I've got problems to make my layout flexible.

If I switch to landscape my buttons inside my gridlayout keep static. And there is a lot of space on the right side of my gridlayout.

I want to center my gridlayout and make the size of my buttons changeable to any device size.

My XML-Code here (showing only two buttons):

<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.fdai3744.taschenrechnerneu.MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_column="0"
        android:layout_row="0"
        style="@style/ButtonStyle"
        android:text="@string/cal_btn_clear" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_column="1"
        android:layout_row="0"
        style="@style/ButtonStyle"
        android:text="@string/cal_btn_clear_entry" />
</GridLayout>

Is it possible only to use XML or should I also use Java?

Body:
want to center my gridlayout:

Use:

android:layout_centerHorizontal="true"
android:layout_centerVertical="true"

in your GridLayout.

make the size of my buttons changeable to any device size:
In order to do that, you will have to create multiple values folders in your project so that you can support multiple screens. For example, ldpi, mdpi, hdpi, xhdpi, ..ect. There are plenty of resources on how to do that here in Stack.

Hope that helps.


问:
Can you get the default folder open/closed icons from the system without an actual path?
I already know how to get file-system-related icons for specific paths by P/Invoking to SHGetFileInfo.  But that requires an actual path.  Plus, it only returns a single icon.

What I'm wondering is two-fold.

How one would get both the default folder open and closed icons (I believe they are stored in 'C:\WINDOWS\system32\imageres.dll' or '%SystemRoot%\system32\shell32.dll' but I could be wrong)

How to get those icons without actually specifying a path (i.e. via a constant or similar.)

Is there even such a way or am I going to have to simply pass it a 'dummy' path to SHGetFileInfo and forget about having two states?

For reference, I'm seeking this because we're building a custom tree to display certain file system objects, but they will be displayed underneath a few app-defined groups and we want those groups to resemble the same graphical folders as those used for actual directories.

答:
Yes it is possible to specify a dummy path when calling SHGetFileInfo. Set the pszPath parameter to something like c:\foo. Include SHGFI_USEFILEATTRIBUTES in the uFlags parameter along with your icon flags, this tells Windows that there is no real file to load (also include SHGFI_OPENICON to get the open folder). Include FILE_ATTRIBUTE_DIRECTORY in the dwFileAttributes parameter so Windows knows you want folder data.

See also:

What does SHGFI_USEFILEATTRIBUTES mean?

Why doesn’t SHGetFileInfo give me customized folder icons?


问:
How to Divide Control Class into Implementation vs. Public Interface?
I've created an MFC control class, which I derived from CWnd.

The control is written from scratch and does not use any child controls. This single class implements all the control logic, including state maintenance, painting, responding to events, etc.

In addition, I need a more "public" interface to be used by the code that uses the control. Ideally, it seems like this would be a simpler class with a much simpler interface. However, having two MFC classes associated with the same Window seems to cause all sorts of problems, or is not even possible.

I'm not really sure the best way to approach this. I'm interested in thoughts on how best to provide a simple interface class to a control like this.

Note that the control is not precompiled into a library or anything. It will be compiled as part of the application.

答:
You might try splitting the class in two, with the more complicated implementation class being a child of the public class.

Ordinarily I'd suggest making a separate pure virtual interface class and using multiple inheritance to connect it to MFC, but I'm guessing you'll want to be able to use the standard CWnd methods on the interface.

ContentLicense: CC BY-SA 2.5


问:
How to match multiple string keywords when you read each line of file (fs) and get the results?
Basically i have mutiple search strings from client that i have to find in each line in the file , if line matches with all the strings from user input push that line to results, with below code its sending empty array of results.

How can i loop through each search string and find a match and once loops is done push all matching lines to results.

searchLogs.js

```<code>/* Example client input
    var searchStr = [{"text":"457383",{"text":"requestPdr"}]
    */
async.eachSeries(filesData.logFiles, function(logfile, done) {
        // read file
        readStream = fs.createReadStream('./logs/' + filesData.searchEnv + '/' + logfile.filename, 'utf8')
        readStream.pipe(split())
            .on('data', function(line) {
                for (var i = 0; i < searchStr.length; i++) {
                    if (line.toLowerCase().indexOf(searchStr[i].toLowerCase()) != -1)
                        results.push({
                            filename: logfile.filename,
                            value: line
                        });

                }
            });

    },
    function(err) {
        if (err) {
            console.log('error', err);
        }
        readStream.on('end', function() {
            callback(results);
        });
        results = [];
    });
</code>```

答:
Try changing

searchStr[i].toLowerCase()

to

searchStr[i]['text'].toLowerCase()

Body:
Basically i have mutiple search strings from client that i have to find in each line in the file , if line matches with all the strings from user input push that line to results, with below code its sending empty array of results.

How can i loop through each search string and find a match and once loops is done push all matching lines to results.

searchLogs.js

/* Example client input
    var searchStr = [{"text":"457383",{"text":"requestPdr"}]
    */
async.eachSeries(filesData.logFiles, function(logfile, done) {
        // read file
        readStream = fs.createReadStream('./logs/' + filesData.searchEnv + '/' + logfile.filename, 'utf8')
        readStream.pipe(split())
            .on('data', function(line) {
                for (var i = 0; i < searchStr.length; i++) {
                    if (line.toLowerCase().indexOf(searchStr[i].toLowerCase()) != -1)
                        results.push({
                            filename: logfile.filename,
                            value: line
                        });

                }
            });

    },
    function(err) {
        if (err) {
            console.log('error', err);
        }
        readStream.on('end', function() {
            callback(results);
        });
        results = [];
    });


问:
How to provide favicon.png in an Angular app instead of favicon.ico?
I created a new Angular app with:

```<code>ng new ...
</code>```

And I can view the application with:

```<code>ng serve --open
</code>```

I removed the default src/favicon.ico and replaced it with src/favicon.png. I also opened src/index.html and changed the appropriate line to read:

```<code><link rel="icon" type="image/png" href="favicon.png">
</code>```

This doesn't seem to have worked. Issuing a GET request for /favicon.png simply returns the content from src/index.html. Restarting ng serve makes no difference.

How can I make this file accessible to the application?

答:
Make a PNG image with same name (i.e. favicon.png) and change the name in these files.

index.html

```<code><link rel="icon" type="image/x-icon" href="favicon.png" />
</code>```

angular.json

```<code>"assets": [
  "src/favicon.png"
  "src/assets",
]
</code>```

In older version of Angular (prior to v.7), the latter file is angular-cli.json

```<code>"assets": [
  "favicon.png"
  "assets",
]
</code>```

Afterwards, depending on browser, version OS etc.

restart the app

restart the browser

clean cache

Body:
I created a new Angular app with:

ng new ...

And I can view the application with:

ng serve --open

I removed the default src/favicon.ico and replaced it with src/favicon.png. I also opened src/index.html and changed the appropriate line to read:

<link rel="icon" type="image/png" href="favicon.png">

This doesn't seem to have worked. Issuing a GET request for /favicon.png simply returns the content from src/index.html. Restarting ng serve makes no difference.

How can I make this file accessible to the application?

Body:
Make a PNG image with same name (i.e. favicon.png) and change the name in these files.

index.html

<link rel="icon" type="image/x-icon" href="favicon.png" />

angular.json

"assets": [
  "src/favicon.png"
  "src/assets",
]

In older version of Angular (prior to v.7), the latter file is angular-cli.json

"assets": [
  "favicon.png"
  "assets",
]

Afterwards, depending on browser, version OS etc.

restart the app

restart the browser

clean cache

ContentLicense: CC BY-SA 4.0


答:
If you want to make it more specific for logging errors, try something like:

```<code>e.GetType()
</code>```

Or, if you need some more information like the StackTrace or message:

```<code>e.ToString()
</code>```

If you only want to catch a specific type of exception, you need to do something like:

```<code>try {
   // someCode
} catch (SpecificExceptionType e) {
   // someCode (e.g. Console.WriteLine(e.ToString()); )
}
catch (AnotherSpecificExceptionType e) {
   // someCode (e.g. Console.WriteLine(e.ToString()); )
}
</code>```

Title: Find out specific Exception

Body:
Apologies for the lack of information...

Is there a way to find out what is the specific Exception that is causing a call to throw the Exception?

Currently, I am catching all the Exceptions by doing catch(Exception e) but I know this is not good practices at all.

Is there a way to know from the Exception what is the specific one that caused the issue so I can be more granular?

Body:
If you want to make it more specific for logging errors, try something like:

e.GetType()

Or, if you need some more information like the StackTrace or message:

e.ToString()

If you only want to catch a specific type of exception, you need to do something like:

try {
   // someCode
} catch (SpecificExceptionType e) {
   // someCode (e.g. Console.WriteLine(e.ToString()); )
}
catch (AnotherSpecificExceptionType e) {
   // someCode (e.g. Console.WriteLine(e.ToString()); )
}


问:
position of widget in a panel using wxpython
am trying to put the radioBox in the center and a button below it, but no matter i try it the radioBox is positioned on top left corner of frame and button doesn't even show! .
I don't understand why this is happening</p>

```<code>class Panelchoose(wx.Panel):
    """
     panel for calculating separately without saving
    """
    def __init__(self ,*args, **kw):
        super(Panelchoose, self).__init__(*args, **kw)
        self.SetBackgroundColour('#48C9B0')
        topsizer=wx.BoxSizer(wx.VERTICAL)
        radiosizer=wx.BoxSizer(wx.VERTICAL)
        btnsizer=wx.BoxSizer(wx.HORIZONTAL)

        lblist=['calculationGrid','calculations','xyz2comcat']
        self.rbox=wx.RadioBox(self,label="choose from the models below:   ",
                              choices=lblist,majorDimension=3,
                              style=wx.RA_SPECIFY_ROWS)

        btn_next=wx.Button(self ,label=" NEXT  ")
        #self.Bind(wx.EVT_BUTTON,self.next_, btn_next)

        topsizer.Add(self.rbox,0,wx.CENTER|wx.ALIGN_CENTER_VERTICAL,10)
        btnsizer.Add(btn_next,0,wx.ALIGN_CENTER_VERTICAL|wx.BOTTOM|wx.EXPAND,5)

        topsizer.Add(btnsizer,4,wx.CENTER|wx.BOTTOM,10)
</code>```

答:
The part your forgot was to tell your panel what its sizer was. If you add self.SetSizer(topsizer) to the end of your class's __init__, it will work as you expect.

Here's a full runnable version:

```<code>import wx

class Panelchoose(wx.Panel):
    """
     panel for calculating separately without saving
    """
    def __init__(self ,*args, **kw):
        super(Panelchoose, self).__init__(*args, **kw)
        self.SetBackgroundColour('#48C9B0')
        topsizer=wx.BoxSizer(wx.VERTICAL)
        radiosizer=wx.BoxSizer(wx.VERTICAL)
        btnsizer=wx.BoxSizer(wx.HORIZONTAL)

        lblist=['calculationGrid','calculations','xyz2comcat']
        self.rbox=wx.RadioBox(self,label="choose from the models below:   ",
                              choices=lblist,majorDimension=3,
                              style=wx.RA_SPECIFY_ROWS)

        btn_next=wx.Button(self ,label=" NEXT  ")
        #self.Bind(wx.EVT_BUTTON,self.next_, btn_next)

        topsizer.Add(self.rbox,0,wx.CENTER|wx.ALIGN_CENTER_VERTICAL,10)
        btnsizer.Add(btn_next,0,wx.ALIGN_CENTER_VERTICAL|wx.BOTTOM|wx.EXPAND,5)

        topsizer.Add(btnsizer,0,wx.CENTER|wx.BOTTOM,10)

        self.SetSizer(topsizer)

if __name__ == '__main__':
    app = wx.App(False)
    frame = wx.Frame(None, title='Test')
    Panelchoose(parent=frame)
    frame.Show()
    app.MainLoop()
</code>```

Body:
am trying to put the radioBox in the center and a button below it, but no matter i try it the radioBox is positioned on top left corner of frame and button doesn't even show! .
I don't understand why this is happening

class Panelchoose(wx.Panel):
    """
     panel for calculating separately without saving
    """
    def __init__(self ,*args, **kw):
        super(Panelchoose, self).__init__(*args, **kw)
        self.SetBackgroundColour('#48C9B0')
        topsizer=wx.BoxSizer(wx.VERTICAL)
        radiosizer=wx.BoxSizer(wx.VERTICAL)
        btnsizer=wx.BoxSizer(wx.HORIZONTAL)

        lblist=['calculationGrid','calculations','xyz2comcat']
        self.rbox=wx.RadioBox(self,label="choose from the models below:   ",
                              choices=lblist,majorDimension=3,
                              style=wx.RA_SPECIFY_ROWS)

        btn_next=wx.Button(self ,label=" NEXT  ")
        #self.Bind(wx.EVT_BUTTON,self.next_, btn_next)

        topsizer.Add(self.rbox,0,wx.CENTER|wx.ALIGN_CENTER_VERTICAL,10)
        btnsizer.Add(btn_next,0,wx.ALIGN_CENTER_VERTICAL|wx.BOTTOM|wx.EXPAND,5)

        topsizer.Add(btnsizer,4,wx.CENTER|wx.BOTTOM,10)

Body:
The part your forgot was to tell your panel what its sizer was. If you add self.SetSizer(topsizer) to the end of your class's __init__, it will work as you expect.

Here's a full runnable version:

import wx

class Panelchoose(wx.Panel):
    """
     panel for calculating separately without saving
    """
    def __init__(self ,*args, **kw):
        super(Panelchoose, self).__init__(*args, **kw)
        self.SetBackgroundColour('#48C9B0')
        topsizer=wx.BoxSizer(wx.VERTICAL)
        radiosizer=wx.BoxSizer(wx.VERTICAL)
        btnsizer=wx.BoxSizer(wx.HORIZONTAL)

        lblist=['calculationGrid','calculations','xyz2comcat']
        self.rbox=wx.RadioBox(self,label="choose from the models below:   ",
                              choices=lblist,majorDimension=3,
                              style=wx.RA_SPECIFY_ROWS)

        btn_next=wx.Button(self ,label=" NEXT  ")
        #self.Bind(wx.EVT_BUTTON,self.next_, btn_next)

        topsizer.Add(self.rbox,0,wx.CENTER|wx.ALIGN_CENTER_VERTICAL,10)
        btnsizer.Add(btn_next,0,wx.ALIGN_CENTER_VERTICAL|wx.BOTTOM|wx.EXPAND,5)

        topsizer.Add(btnsizer,0,wx.CENTER|wx.BOTTOM,10)

        self.SetSizer(topsizer)

if __name__ == '__main__':
    app = wx.App(False)
    frame = wx.Frame(None, title='Test')
    Panelchoose(parent=frame)
    frame.Show()
    app.MainLoop()


问:
Set value in Report Parameter (report viewer in remote mode)
I have already created a report in SSRS 2008. I'm using the Report Viewer to view it. I have one Report Parameter which is a list of usernames. I'd like to programatically select a particular value from that list.

So for instance, user: sdsmith goes to the page. The webpage will grab that username, check it against the list in ReportParameter1, then set the value of ReportParameter1 to sdsmith if it's found in the list.

答:
I am assuming you would be OK with creating a web page that would get the username, and then you could pass it as part of the URL to the actual report on the report server.

http://social.msdn.microsoft.com/Forums/en/sqlreportingservices/thread/de8b7774-a766-4454-a817-81cc19bab4a3


问:
NodeJS: Why is function being skipped?
am new to nodeJs and trying to understand why in this file--app.js--the function main() never gets executed.

If I add a console.log statement before the function, it gets executed, but nothing inside the function gets executed.

I have used the debugger, and sure enough, the function is being skipped altogether.

Why is this occurring? Is there some component of node that I have overlooked?

```<code>'use strict';

const sendEmail = require('./send-email');

module.exports = main;

//console.log("This gets executed");

//this function never gets executed!
function main()
{
debugger
...some functionality...
}
</code>```

答: You have defined main in your module but did not call main(). If this is all your code you need to add main() at the end of your code to execute it.

Title: NodeJS: Why is function being skipped?

Body:
am new to nodeJs and trying to understand why in this file--app.js--the function main() never gets executed.

If I add a console.log statement before the function, it gets executed, but nothing inside the function gets executed.

I have used the debugger, and sure enough, the function is being skipped altogether.

Why is this occurring? Is there some component of node that I have overlooked?

'use strict';

const sendEmail = require('./send-email');

module.exports = main;

//console.log("This gets executed");

//this function never gets executed!
function main()
{
debugger
...some functionality...
}


问:
BigQuery concatenate string and integer/timestamp?
I'm using BigQuery and am trying to create a String out of a timestamp int and a plain string. I've tried casting it to a string using STRING() but it does not seem to be working.

What can I do to convert everything within the STRING() function to a string?

```<code>_TABLE_SUFFIX BETWEEN STRING('intraday_' + FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY))) AND 'intraday_' + FORMAT_TIMESTAMP('%Y%m%d', CURRENT_TIMESTAMP) AND
</code>```

答:
try below  </p>

```<code>_TABLE_SUFFIX BETWEEN CONCAT('intraday_', FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY)))
              AND CONCAT('intraday_', FORMAT_TIMESTAMP('%Y%m%d', CURRENT_TIMESTAMP))
</code>```

Body:
I'm using BigQuery and am trying to create a String out of a timestamp int and a plain string. I've tried casting it to a string using STRING() but it does not seem to be working.

What can I do to convert everything within the STRING() function to a string?

_TABLE_SUFFIX BETWEEN STRING('intraday_' + FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY))) AND 'intraday_' + FORMAT_TIMESTAMP('%Y%m%d', CURRENT_TIMESTAMP) AND

Body:
try below

_TABLE_SUFFIX BETWEEN CONCAT('intraday_', FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY)))
              AND CONCAT('intraday_', FORMAT_TIMESTAMP('%Y%m%d', CURRENT_TIMESTAMP))


问:
How to change color of Vertical header of QTableWidget
I have a table widget. i want to set the color of vertical header in CSS.

want to change the color where blue arrow is marked.

I tried the code

```<code>QHeaderView::section{background-color:rgb(120,120,120);color: white;}
</code>```

but i get this

答:
This works perfect for me. You can try it !</p>

```<code>stylesheet = "::section{Background-color:rgb(190,1,1);border-radius:14px;}"
Table.verticalHeader().setStyleSheet(stylesheet)
</code>```

Body:
I have a table widget. i want to set the color of vertical header in CSS.

want to change the color where blue arrow is marked.

I tried the code

QHeaderView::section{background-color:rgb(120,120,120);color: white;}

but i get this

Body:
This works perfect for me. You can try it !

stylesheet = "::section{Background-color:rgb(190,1,1);border-radius:14px;}"
Table.verticalHeader().setStyleSheet(stylesheet)


问:
I want to pass latlng values from one activity to the other in android
I made a list with some restaurants in the first activity and what I want is to see in the googlemap the specific location of each restaurant I select every time.How can I  pass these values from the first activity to the maps activity?  </p>

答:
All you need to do is this (from the Google Map API documentation):-    </p>

```<code>// Create a Uri from an intent string. Use the result to create an Intent.
Uri gmmIntentUri = Uri.parse("google.streetview:cbll=46.414382,10.013988");

// Create an Intent from gmmIntentUri. Set the action to ACTION_VIEW
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
// Make the Intent explicit by setting the Google Maps package
mapIntent.setPackage("com.google.android.apps.maps");

// Attempt to start an activity that can handle the Intent
startActivity(mapIntent);
</code>```

Body:
All you need to do is this (from the Google Map API documentation):-

// Create a Uri from an intent string. Use the result to create an Intent.
Uri gmmIntentUri = Uri.parse("google.streetview:cbll=46.414382,10.013988");

// Create an Intent from gmmIntentUri. Set the action to ACTION_VIEW
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
// Make the Intent explicit by setting the Google Maps package
mapIntent.setPackage("com.google.android.apps.maps");

// Attempt to start an activity that can handle the Intent
startActivity(mapIntent);


问:
How do I override the default back button action in Cordova?
I've followed the example code in the Cordova docs to override the device back button (using ES6), but it doesn't work as expected:

```<code>const onBackButtonPress = () => {
  console.log('pressed');
};
document.addEventListener('backbutton', onBackButtonPress, false);
</code>```

When I run the app on my Android device, my override code gets invoked, but the app also exits as if the default back button action is also being invoked.

How can I prevent the app from exiting when the back button is pressed?

I've already tried adding e.preventDefault() to the callback function for addEventListener

I'm doing this after the deviceready event has fired.

I'm using Cordova 7.0.1 and my platform is cordova-android 6.2.3

答:
I am using this code in my apps:

```<code>document.addEventListener("backbutton", function(e) {
    e.preventDefault();
    return;
}, false);
</code>```

Note, to run this code when device is ready

Body:
I've followed the example code in the Cordova docs to override the device back button (using ES6), but it doesn't work as expected:

const onBackButtonPress = () => {
  console.log('pressed');
};
document.addEventListener('backbutton', onBackButtonPress, false);

When I run the app on my Android device, my override code gets invoked, but the app also exits as if the default back button action is also being invoked.

How can I prevent the app from exiting when the back button is pressed?

I've already tried adding e.preventDefault() to the callback function for addEventListener

I'm doing this after the deviceready event has fired.

I'm using Cordova 7.0.1 and my platform is cordova-android 6.2.3

Body:
I am using this code in my apps:

document.addEventListener("backbutton", function(e) {
    e.preventDefault();
    return;
}, false);

Note, to run this code when device is ready


问:
Python Range Error in While Loop
I am trying to write a python program that will take any string of lowercase letters and return the longest alphabetical substring within it. Below is a segment of the code. </p>

```<code>s="abc"                                            #sample string
anslist=[]                                         #stores answers
shift=0                                            #shifts substring
expan=0                                            #expands substring
while len(s) >= 1+shift+expan:                     #within bounds of s
    if s[0+shift+expan] > s[1+shift+expan]:        #if not alphabetical
        shift += 1                                 #moves substring over
    else:                                          #if alphabetical
        while s[0+shift+expan] <= s[1+shift+expan]:  #while alphabetical
            expan += 1                               #checks next letter
        anslist += s[0+shift:2+shift+expan]       #adds substring to ans
        expan = 0                                  #resets expansion
</code>```

<p>When I run the code, the line containing
while s[0+shift+expan] <= s[1+shift+expan]:
creates an error that the string index is outside of the range. I see that adding to expan will put the index out of range, but shouldn't the largest while loop solve this? I appreciate any help. </p>

答:
Have a look at this. </p>

```<code>>>> import re
>>> words = []
>>> word = r'[a]*[b]*[c]*[d]*[e]*[f]*[g]*[h]*[i]*[j]*[k]*[l]*[m]*[n]*[o]*[q]*[r]*[s]*[t]*[u]*[v]*[x]*[y]*[z]*' # regex that would match sub-strings. Just extend it up to z.
>>> string = "bacde"
>>> for m in re.finditer(word, string):
...         words.append(m.group())
>>> print(words) # list of substrings
['b', 'acde']
</code>```

<p>Then you can extract the largest string from the list of strings </p>

```<code>>>> print(max(words, key=len))
acde
</code>```

Title: Python Range Error in While Loop

Body:
I am trying to write a python program that will take any string of lowercase letters and return the longest alphabetical substring within it. Below is a segment of the code.

s="abc"                                            #sample string
anslist=[]                                         #stores answers
shift=0                                            #shifts substring
expan=0                                            #expands substring
while len(s) >= 1+shift+expan:                     #within bounds of s
    if s[0+shift+expan] > s[1+shift+expan]:        #if not alphabetical
        shift += 1                                 #moves substring over
    else:                                          #if alphabetical
        while s[0+shift+expan] <= s[1+shift+expan]:  #while alphabetical
            expan += 1                               #checks next letter
        anslist += s[0+shift:2+shift+expan]       #adds substring to ans
        expan = 0                                  #resets expansion

When I run the code, the line containing
while s[0+shift+expan] <= s[1+shift+expan]:
creates an error that the string index is outside of the range. I see that adding to expan will put the index out of range, but shouldn't the largest while loop solve this? I appreciate any help.

Body:
Have a look at this.

>>> import re
>>> words = []
>>> word = r'[a]*[b]*[c]*[d]*[e]*[f]*[g]*[h]*[i]*[j]*[k]*[l]*[m]*[n]*[o]*[q]*[r]*[s]*[t]*[u]*[v]*[x]*[y]*[z]*' # regex that would match sub-strings. Just extend it up to z.
>>> string = "bacde"
>>> for m in re.finditer(word, string):
...         words.append(m.group())
>>> print(words) # list of substrings
['b', 'acde']

Then you can extract the largest string from the list of strings

>>> print(max(words, key=len))
acde


问:
VBA to save workbook - error with replacing file with same name
I am using the VBA Code below to automatically save a file, but allow for the user to pick the file location and name.   I have a fixed filename that I want the user to use, for example: TestImport.xlsx, but I need some code to allow them to pick the path on their specific PC.   They will be running this routine weekly, so they will likely have a previous version of the Workbook with the exact same name, so they will have to answer the dialog box prompt to replace the file.

When I run the code, I get the following error:

Run-time error '1004'

  Cannot access 'TestImport.xlsx'

Can you help me see what the problem is with the content below?

```<code>Dim fd As FileDialog, fillName As String

    On Error GoTo ErrorHandler

    Set fd = Application.FileDialog(msoFileDialogSaveAs)

    If fd.Show = True Then
        If fd.SelectedItems(1) <> vbNullString Then
            fillName = fd.SelectedItems(1)
        End If
    Else
        'Stop Code Execution for Null File String
        End
    End If

    saveFileAs = fillName

    'Cleanup
    Set fd = Nothing

    Windows("MeritImport.xlsx").Activate
    Application.ActiveWorkbook.SaveAs Filename:=fillName, _
        FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

    Exit Sub

ErrorHandler:
    Set fd = Nothing
    MsgBox "Error " & Err & ": " & Error(Err)
</code>```

答:
I have a fixed filename that I want the user to use, for example: TestImport.xlsx

Then let the user only select the folder location and use that to save your file. For example

```<code>Sub Sample()
    Dim Ret
    Dim flname As String

    Ret = BrowseForFolder("C:\")

    If Not Ret = "" Then
        If Right(Ret, 1) <> "\" Then Ret = Ret & "\"

        flname = Ret & "TestImport.xlsx"

        MsgBox flname
        '
        '~~> Rest of your code
        '
    End If
End Sub

Function BrowseForFolder(Optional OpenAt As Variant) As Variant
    Dim ShellApp As Object

    Set ShellApp = CreateObject("Shell.Application"). _
    BrowseForFolder(0, "Please choose a folder", 0, OpenAt)

    On Error Resume Next
    BrowseForFolder = ShellApp.self.Path
    On Error GoTo 0

    Set ShellApp = Nothing

    Select Case Mid(BrowseForFolder, 2, 1)
    Case Is = ":"
        If Left(BrowseForFolder, 1) = ":" Then GoTo Invalid
    Case Is = "\"
        If Not Left(BrowseForFolder, 1) = "\" Then GoTo Invalid
    Case Else
        GoTo Invalid
    End Select

    Exit Function
Invalid:
    BrowseForFolder = False
End Function
</code>```

When you try to use flname to overwrite the file (if there is already a copy) then you will get a prompt. The user can choose "Yes" or "No". If you do not want to give the user a choice then you can use Application.DisplayAlerts = False

Note: If the copy is open then you cannot overwrite it. It will give you an error if you try to do so.

Body:
I am using the VBA Code below to automatically save a file, but allow for the user to pick the file location and name.   I have a fixed filename that I want the user to use, for example: TestImport.xlsx, but I need some code to allow them to pick the path on their specific PC.   They will be running this routine weekly, so they will likely have a previous version of the Workbook with the exact same name, so they will have to answer the dialog box prompt to replace the file.

When I run the code, I get the following error:

Run-time error '1004'

  Cannot access 'TestImport.xlsx'

Can you help me see what the problem is with the content below?

Dim fd As FileDialog, fillName As String

    On Error GoTo ErrorHandler

    Set fd = Application.FileDialog(msoFileDialogSaveAs)

    If fd.Show = True Then
        If fd.SelectedItems(1) <> vbNullString Then
            fillName = fd.SelectedItems(1)
        End If
    Else
        'Stop Code Execution for Null File String
        End
    End If

    saveFileAs = fillName

    'Cleanup
    Set fd = Nothing

    Windows("MeritImport.xlsx").Activate
    Application.ActiveWorkbook.SaveAs Filename:=fillName, _
        FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

    Exit Sub

ErrorHandler:
    Set fd = Nothing
    MsgBox "Error " & Err & ": " & Error(Err)

Body:
I have a fixed filename that I want the user to use, for example: TestImport.xlsx

Then let the user only select the folder location and use that to save your file. For example

Sub Sample()
    Dim Ret
    Dim flname As String

    Ret = BrowseForFolder("C:\")

    If Not Ret = "" Then
        If Right(Ret, 1) <> "\" Then Ret = Ret & "\"

        flname = Ret & "TestImport.xlsx"

        MsgBox flname
        '
        '~~> Rest of your code
        '
    End If
End Sub

Function BrowseForFolder(Optional OpenAt As Variant) As Variant
    Dim ShellApp As Object

    Set ShellApp = CreateObject("Shell.Application"). _
    BrowseForFolder(0, "Please choose a folder", 0, OpenAt)

    On Error Resume Next
    BrowseForFolder = ShellApp.self.Path
    On Error GoTo 0

    Set ShellApp = Nothing

    Select Case Mid(BrowseForFolder, 2, 1)
    Case Is = ":"
        If Left(BrowseForFolder, 1) = ":" Then GoTo Invalid
    Case Is = "\"
        If Not Left(BrowseForFolder, 1) = "\" Then GoTo Invalid
    Case Else
        GoTo Invalid
    End Select

    Exit Function
Invalid:
    BrowseForFolder = False
End Function

When you try to use flname to overwrite the file (if there is already a copy) then you will get a prompt. The user can choose "Yes" or "No". If you do not want to give the user a choice then you can use Application.DisplayAlerts = False

Note: If the copy is open then you cannot overwrite it. It will give you an error if you try to do so.


问:
Converting a working SQL NOT IN
I have some SQL to tell me the superheroes who don't ever wield a sword.

Creating the table

First, here is the (MySQL) script to create and populate the table.

```<code>CREATE TABLE IF NOT EXISTS `mydb`.`weaponry` (
  `hero` VARCHAR(20) NULL,
  `weapon` VARCHAR(20) NULL)
ENGINE = InnoDB

insert into weaponry (hero, weapon) values ('Wonder Woman', 'Lasso of truth');
insert into weaponry (hero, weapon) values ('Wonder Woman', 'Sword');
insert into weaponry (hero, weapon) values ('Wonder Woman', 'Shield');
insert into weaponry (hero, weapon) values ('Spider Man', 'Web');
insert into weaponry (hero, weapon) values ('Gamora', 'Sword');
insert into weaponry (hero, weapon) values ('Gamora', 'Daggar');
insert into weaponry (hero, weapon) values ('Batman', 'Batarang');
insert into weaponry (hero, weapon) values ('Batman', 'Batgrapple');
insert into weaponry (hero, weapon) values ('Batman', 'Tranquilizer gun');
</code>```

Working code using a NOT IN and a subselect

```<code>select distinct hero from weaponry
  where hero not in
  (select hero from weaponry where weapon = 'Sword')
</code>```

This correctly returns Spider Man and Batman, who don't wield a sword.

Alternative 1: Using NOT EXISTS

I would like to implement the same query using NOT EXISTS.
I looked at https://stackoverflow.com/a/5231731/509840.
I tried this:

```<code>select distinct hero from weaponry
  where not exists
  (select * from weaponry where weapon = 'Sword')
</code>```

Unfortunately, this returns no rows.

Alternative 2: Using LEFT JOIN

I also took a look at this answer: https://stackoverflow.com/a/17413996/509840 .
I was curious to try replacing the NOT IN with a LEFT JOIN.

```<code>  select * from weaponry a
    left join weaponry b on a.hero=b.hero and a.weapon=b.weapon
    where a.weapon <> 'Sword'
</code>```

But this just returns all non-sword heroes (including Wonder Woman and Gamora), since all wield weapons other than swords.

Would you please help me rewrite the NOT IN query with either the NOT EXISTS or the LEFT JOIN?

EDIT: Left Join and the correlated subquery

@JeffUK suggested in his comments that one could understand the correlated subquery better by removing the WHERE clause. Here's a small modification to the select with the where removed.

```<code>select distinct a.hero, weaponryInner.hero from weaponry a
    left join
        (Select * from weaponry b where weapon = 'Sword') as weaponryInner
    on a.hero=weaponryInner.hero
</code>```

The results are two columns of heroes, some of which are NULL.

```<code>-------------------------------
Hero          |  Hero
-------------------------------
Wonder Woman  |  Wonder Woman
Gamora        |  Gamora
Spider Man    |  <null>
Batman        |  <null>
-------------------------------
</code>```

So adding the final where weaponryInner.Weapon is null will return just Spider Man and Batman.

答:
I think you can use the below:</p>

```<code>select distinct hero from weaponry w
LEFT JOIN
(select hero from weaponry where weapon = 'Sword') h ON h.hero = w.hero
WHERE h.hero IS NULL
</code>```

Title: Converting a working SQL NOT IN

Body:
I have some SQL to tell me the superheroes who don't ever wield a sword.

Creating the table

First, here is the (MySQL) script to create and populate the table.

CREATE TABLE IF NOT EXISTS `mydb`.`weaponry` (
  `hero` VARCHAR(20) NULL,
  `weapon` VARCHAR(20) NULL)
ENGINE = InnoDB

insert into weaponry (hero, weapon) values ('Wonder Woman', 'Lasso of truth');
insert into weaponry (hero, weapon) values ('Wonder Woman', 'Sword');
insert into weaponry (hero, weapon) values ('Wonder Woman', 'Shield');
insert into weaponry (hero, weapon) values ('Spider Man', 'Web');
insert into weaponry (hero, weapon) values ('Gamora', 'Sword');
insert into weaponry (hero, weapon) values ('Gamora', 'Daggar');
insert into weaponry (hero, weapon) values ('Batman', 'Batarang');
insert into weaponry (hero, weapon) values ('Batman', 'Batgrapple');
insert into weaponry (hero, weapon) values ('Batman', 'Tranquilizer gun');

Working code using a NOT IN and a subselect

select distinct hero from weaponry
  where hero not in
  (select hero from weaponry where weapon = 'Sword')

This correctly returns Spider Man and Batman, who don't wield a sword.

Alternative 1: Using NOT EXISTS

I would like to implement the same query using NOT EXISTS.
I looked at https://stackoverflow.com/a/5231731/509840.
I tried this:

select distinct hero from weaponry
  where not exists
  (select * from weaponry where weapon = 'Sword')

Unfortunately, this returns no rows.

Alternative 2: Using LEFT JOIN

I also took a look at this answer: https://stackoverflow.com/a/17413996/509840 .
I was curious to try replacing the NOT IN with a LEFT JOIN.

  select * from weaponry a
    left join weaponry b on a.hero=b.hero and a.weapon=b.weapon
    where a.weapon <> 'Sword'

But this just returns all non-sword heroes (including Wonder Woman and Gamora), since all wield weapons other than swords.

Would you please help me rewrite the NOT IN query with either the NOT EXISTS or the LEFT JOIN?

EDIT: Left Join and the correlated subquery

@JeffUK suggested in his comments that one could understand the correlated subquery better by removing the WHERE clause. Here's a small modification to the select with the where removed.

select distinct a.hero, weaponryInner.hero from weaponry a
    left join
        (Select * from weaponry b where weapon = 'Sword') as weaponryInner
    on a.hero=weaponryInner.hero

The results are two columns of heroes, some of which are NULL.

-------------------------------
Hero          |  Hero
-------------------------------
Wonder Woman  |  Wonder Woman
Gamora        |  Gamora
Spider Man    |  <null>
Batman        |  <null>
-------------------------------

So adding the final where weaponryInner.Weapon is null will return just Spider Man and Batman.

Body:
I think you can use the below:

select distinct hero from weaponry w
LEFT JOIN
(select hero from weaponry where weapon = 'Sword') h ON h.hero = w.hero
WHERE h.hero IS NULL


答:
You never call the main function.

Think of a function as a piece of code that is being out-sourced, and given a name. As long as you don't call it by its name, nothing will happen.

So, you need to add somewhere in your code the following line:

```<code>main();
</code>```

Then it will work. (Please note that you should do this after declaring the main function.)

The console.log gets executed automatically, as it is not within a function, but already on the top-level. The same is true for the declaration of the function. That's why Node.js creates this function for, but you do not tell it to actually do something with it.

Actually, calling main will also work if done before declaring it, due to the way JavaScript handles function statements, but I'd call it better style not to do so. The same is true for using module.exports, this will also work this way, but I'd call it better style as well if you did it after creating the function.

So, to cut a long story short, your code should look like this:

```<code>'use strict';

const sendEmail = require('./send-email');

console.log("This gets executed");

function main()
{
  // ...
}

main();

module.exports = main;
</code>```

This will run the main function for you, and export it as well (which is useful if you want to run the same function from another file).

Title: NodeJS: Why is function being skipped?

Body:
You never call the main function.

Think of a function as a piece of code that is being out-sourced, and given a name. As long as you don't call it by its name, nothing will happen.

So, you need to add somewhere in your code the following line:

main();

Then it will work. (Please note that you should do this after declaring the main function.)

The console.log gets executed automatically, as it is not within a function, but already on the top-level. The same is true for the declaration of the function. That's why Node.js creates this function for, but you do not tell it to actually do something with it.

Actually, calling main will also work if done before declaring it, due to the way JavaScript handles function statements, but I'd call it better style not to do so. The same is true for using module.exports, this will also work this way, but I'd call it better style as well if you did it after creating the function.

So, to cut a long story short, your code should look like this:

'use strict';

const sendEmail = require('./send-email');

console.log("This gets executed");

function main()
{
  // ...
}

main();

module.exports = main;

This will run the main function for you, and export it as well (which is useful if you want to run the same function from another file).


问:
user defined commands in verbatim environment
is it possible to create a new command with a parameter in a verbatim environment and some indentation?

```<code>\newcommand{codeblock}[1]{\begin{quote}\begin{verbatim}#1\end{verbatim}\end{quote}}
</code>```

This does not work. Is there an other way?

答:
How \begin{verbatim} works. briefly and roughly.

\begin{verbatim} is expanded to \verbatim.

Then \verbatim sets category code of each special characters to 12.
Now all chars is like digits or puncts.

Then \verbatim sets font, parindent and calls \@xverbatim.

\@xverbatim catches the end of verbatim using the following trick:

```<code>\def\@xverbatim#1\end{#1\end}
</code>```

Then \end{verbatim} finishes work.

How \newcommand{\codeblock}[1]{\begin{quote}\begin{verbatim}#1\end{verbatim}\end{quote}} works.

First of all \codeblock{Some {}$&%^_} reads its argument.

#1 --> Some code {}$&%^_

Note: {,},$,&,%,^,_ have categories 1,2,3,4,6,7,8 rather than 11 or 12!!!)

\codeblock expands to \begin{quote}\begin{verbatim} Some {}$&%^_\end {verbatim}\end {quote}.
 Important: backslash of \end has category 0 rather than 11.
 Moreover { and } have categories 1 and 2  rather than 11.
 And $,&,%,^,_ have categories 3,4,6,7,8.

\begin{quote} expands to \quote and \quote executes.

Then \begin{verbatim} expands to \varbatim.
 \varbatim changes all categories and font. But (important)
 the category of backslash (in \end) remains equal to 0. And the categories of {, }, $, &, %, ^, _ typed after Some remains because of "argument reading" executes before \verbatim changes all categories. But you need that all char has categories 11 o 12.

Then \verbatim calls \@xverbatim.

\@xverbatim tries to catch your argument using the following trick:

```<code>\def\@xverbatim#1\end{#1\end}
</code>```

but it is impossible because of \@xverbatim tries to catch
  \end where all letters (\,e,n,d) have the category 12 and 11.
  But in fact there are four letters with other category code:
  \ with category 0 and e,n,d with category 11.

It is possible (I am not sure) that trick is more masterly:

Red chars have category 12. Green chars have category 11.
 \def, \@xverbatim, \end are macros with \ (category 0) and letters (category 11).

\@xverbatim is trying and trying to find \end where backslash (\) has category 11 but.... File ended while scanning use of \@xverbatim

If you want to create new macro \codeblock you must do something like above text.

Body:
is it possible to create a new command with a parameter in a verbatim environment and some indentation?

\newcommand{codeblock}[1]{\begin{quote}\begin{verbatim}#1\end{verbatim}\end{quote}}

This does not work. Is there an other way?

Body:
How \begin{verbatim} works. briefly and roughly.

\begin{verbatim} is expanded to \verbatim.

Then \verbatim sets category code of each special characters to 12.
Now all chars is like digits or puncts.

Then \verbatim sets font, parindent and calls \@xverbatim.

\@xverbatim catches the end of verbatim using the following trick:

\def\@xverbatim#1\end{#1\end}

Then \end{verbatim} finishes work.

How \newcommand{\codeblock}[1]{\begin{quote}\begin{verbatim}#1\end{verbatim}\end{quote}} works.

First of all \codeblock{Some {}$&%^_} reads its argument.

#1 --> Some code {}$&%^_

Note: {,},$,&,%,^,_ have categories 1,2,3,4,6,7,8 rather than 11 or 12!!!)

\codeblock expands to \begin{quote}\begin{verbatim} Some {}$&%^_\end {verbatim}\end {quote}.
 Important: backslash of \end has category 0 rather than 11.
 Moreover { and } have categories 1 and 2  rather than 11.
 And $,&,%,^,_ have categories 3,4,6,7,8.

\begin{quote} expands to \quote and \quote executes.

Then \begin{verbatim} expands to \varbatim.
 \varbatim changes all categories and font. But (important)
 the category of backslash (in \end) remains equal to 0. And the categories of {, }, $, &, %, ^, _ typed after Some remains because of "argument reading" executes before \verbatim changes all categories. But you need that all char has categories 11 o 12.

Then \verbatim calls \@xverbatim.

\@xverbatim tries to catch your argument using the following trick:

\def\@xverbatim#1\end{#1\end}

but it is impossible because of \@xverbatim tries to catch
  \end where all letters (\,e,n,d) have the category 12 and 11.
  But in fact there are four letters with other category code:
  \ with category 0 and e,n,d with category 11.

It is possible (I am not sure) that trick is more masterly:

Red chars have category 12. Green chars have category 11.
 \def, \@xverbatim, \end are macros with \ (category 0) and letters (category 11).

\@xverbatim is trying and trying to find \end where backslash (\) has category 11 but.... File ended while scanning use of \@xverbatim

If you want to create new macro \codeblock you must do something like above text.


问:
Xlwings safe Excel range as Python list
I need to import an Excel range as a list in Python. I came up with the following basic code.

```<code>import xlwings as xw

r2 = xw.sheets('Tabelle1').range('A1').value # last row of range

r2 = int(r2)

r2 = str(r2)

r1 = 'B3:B'

r3 = r1 + r2
InputData = [xw.sheets('Tabelle1').range(r3).value]
</code>```

This code works perfectly fine when I start the code within my Spyder Environment. I will see the variable InputData as List in the variable explorer. However when I start the script from Excel/VBA using the Xlwings tool, the variable InputData will not be shown in the variable explorer.

Any ideas how I could modify this so the InputData variable will always be shown as a list, no matter how I start the script?

答:
At the core of any Python installation is the interpreter. If you're working on a Windows machine, then the interpreter is an executable called python.exe. It is the piece of software that actually runs your Python code.

You can feed code to the interpreter in many different ways. One way is by means of the Spyder application. The Spyder application is in effect a human-friendly interface built on top of the interpreter. The Spyder application relays your Python commands to the interpreter, lets the interpreter run it, and then collects any outputs generated by the interpreter (e.g. calculated variable values which you can then view in Spyder's variable explorer).

But the Spyder application is only one of many possible ways to use the Python interpreter. You can also (and from what I understand this is what you're looking for) use an Excel application to feed Python code to the interpreter and handle all the outputs. In this case Excel is the interface on top of the Python interpreter instead of Spyder (i.e. Spyder is not needed at all).

This approach of using Excel (with VBA scripting) to do all control and communication with the Python interpreter is nicely demonstrated in these example files on the xlwings website. It even includes an example with database operations (using a SQLite database) I would suggest to download them and play around with them. Then go the xlwings documentation here and here to get a detailed understanding of what is happening in these examples.

Title: Xlwings safe Excel range as Python list

Body:
I need to import an Excel range as a list in Python. I came up with the following basic code.

import xlwings as xw

r2 = xw.sheets('Tabelle1').range('A1').value # last row of range

r2 = int(r2)

r2 = str(r2)

r1 = 'B3:B'

r3 = r1 + r2
InputData = [xw.sheets('Tabelle1').range(r3).value]

This code works perfectly fine when I start the code within my Spyder Environment. I will see the variable InputData as List in the variable explorer. However when I start the script from Excel/VBA using the Xlwings tool, the variable InputData will not be shown in the variable explorer.

Any ideas how I could modify this so the InputData variable will always be shown as a list, no matter how I start the script?


问:
Define getter/setter on existing object w/ TypeScript
How would I write the following code using TypeScript?

```<code>document.__defineGetter__('cookie', function() { ... });
document.__defineSetter__('cookie', function(v) { ... });
</code>```

Thanks in advance!

(p.s. this assumes document exists, but document.cookie does not... )

答:
You can use Object.defineProperty in order to do so.

You'll also have to amend the existing's object interface so the compiler knows you added it too.

interface Document {
    cake: string
}

Object.defineProperty(document, 'cake', {
    get: function () {
        return this.id + 'a';
    },
    set: function (value) {
        this.id = value;
    }
});

console.log(document.cake);

document.cake = 'abc';

console.log(document.cake);
```

You can see a working example here.

Body:
How would I write the following code using TypeScript?

document.__defineGetter__('cookie', function() { ... });
document.__defineSetter__('cookie', function(v) { ... });

Thanks in advance!

(p.s. this assumes document exists, but document.cookie does not... )

Body:
You can use Object.defineProperty in order to do so.

You'll also have to amend the existing's object interface so the compiler knows you added it too.

interface Document {
    cake: string
}

Object.defineProperty(document, 'cake', {
    get: function () {
        return this.id + 'a';
    },
    set: function (value) {
        this.id = value;
    }
});

console.log(document.cake);

document.cake = 'abc';

console.log(document.cake);

You can see a working example <a href="http://www.typescriptlang.org/play/index.html#src=%0D%0Ainterface%20Document%20%7B%0D%0A%20%20%20%20cake%3A%20string%0D%0A%7D%0D%0A%0D%0AObject.defineProperty(document%2C%20'cake'%2C%20%7B%0D%0A%20%20%20%20get%3A%20function%20()%20%7B%0D%0A%20%20%20%20%20%20%20%20return%20this.id%20%2B%20'a'%3B%0D%0A%20%20%20%20%7D%2C%0D%0A%20%20%20%20set%3A%20function%20(value)%20%7B%0D%0A%20%20%20%20%20%20%20%20this.id%20%3D%20value%3B%0D%0A%20%20%20%20%7D%0D%0A%7D)%3B%0D%0A%0D%0A%0D%0Aconsole.log(document.cake)%3B%0D%0A%0D%0Adocument.cake%20%3D%20'abc'%3B%0D%0A%0D%0Aconsole.log(document.cake)%3B%0D%0A" rel="noreferrer">here.


问:
Dagger 2 Scopes, where to place Presenters?
what would it be the best practice about placing Presenters in a Scope?

Could we have Presenters on @Singleton or @AppScope without any problem?

Should they be placed in an @ActivityScope in order to destroy them each time the activity is destroyed?

答:
what would it be the best practice about placing Presenters in a Scope?

Usually a presenter should be in some scope. Not placing it in any scope will lead to problems, as every time you request a presenter it would create a new one.

Which scope you choose mostly depends on your programming style, but the most common would probably be @PerActivity, as a scope that follows the lifecycle of the Activity. (the same way you can use something like @PerFragment with Fragments and their lifecycle)

Could we have Presenters on @Singleton or @AppScope without any problem?

Yes and no. Longer living objects referencing shorter lived ones (e.g. a @Singleton object that references an activity-lifecycled one) usually is not a good practice that might lead to memory leaks.

You can avoid these issues by properly adding / removing your shorter lived objects (e.g. add in onCreate, remove in onDestroy) or using WeakReference.

Some programmers will keep their presenters as @Singleton or in some similar fashion and swap views, but again this depends on how you prefer your code. It will work, but you must make sure what objects you reference and to clean up afterwards.

Should they be placed in an @ActivityScope in order to destroy them each time the activity is destroyed?

This is by far the easiest option, since you have no problem referencing the Activity or anything else that depends on it. You most likely won't have to worry about memory leaks or other issues this way.

In the end its your code and you have to do what works best for you.


答:
```<code>const sendEmail = require('./send-email');
</code>```

… loads the module and assigns the value of exports to sendEmail.

That is all it does.

The value of exports is a function. If you want to call that function then you have to … call it.

```<code>sendEmail();
</code>```

Title: NodeJS: Why is function being skipped?

Body:
am new to nodeJs and trying to understand why in this file--app.js--the function main() never gets executed.

If I add a console.log statement before the function, it gets executed, but nothing inside the function gets executed.

I have used the debugger, and sure enough, the function is being skipped altogether.

Why is this occurring? Is there some component of node that I have overlooked?

'use strict';

const sendEmail = require('./send-email');

module.exports = main;

//console.log("This gets executed");

//this function never gets executed!
function main()
{
debugger
...some functionality...
}

Body:
const sendEmail = require('./send-email');

… loads the module and assigns the value of exports to sendEmail.

That is all it does.

The value of exports is a function. If you want to call that function then you have to … call it.

sendEmail();


问:
Delaying not preventing Bash function from simultaneous execution
I need to block the simultaneous calling of highCpuFunction function. I have tried to create a blocking mechanism, but it is not working. How can I do this?

```<code>nameOftheScript="$(basename $0)"
pidOftheScript="$$"

highCpuFunction()
{
    # Function with code causing high CPU usage. Like tar, zip, etc.

    while [  -f /tmp/"$nameOftheScript"*  ];
    do
        sleep 5;
    done
    touch /tmp/"$nameOftheScript"_"$pidOftheScript"

    echo "$(date +%s) I am a Bad function you do not want to call me simultaniously..."
    # Real high CPU usage code for reaching the database and
    # parsing logs. It takes the heck out of the CPU.

    rm -rf /tmp/"$nameOftheScript"_"$pidOftheScript" 2>/dev/null
}

while true
do
   sleep 2
    highCpuFunction
done

# The rest of the code...
</code>```

In short, I want to run highCpuFunction at least with a gap of 5 seconds. Regardless of the instance/user/terminal. I need to allow other users to run this function but in proper sequence and with a gap of at least 5 seconds.

答:
Use the flock tool. Consider this code (let's call it 'onlyoneofme.sh'):

```<code>#!/bin/sh

exec 9>/var/lock/myexclusivelock

flock 9
echo start
sleep 10
echo stop
</code>```

It will open file /var/lock/myexclusivelock as descriptor 9 and then try to lock it exclusively. Only one instance of the script will be allowed to pass behind the flock 9 command. The rest of them will wait for the other script to finish (so the descriptor will be closed and the lock freed). After this, the next script will acquire the lock and execute, and so on.

Body:
I need to block the simultaneous calling of highCpuFunction function. I have tried to create a blocking mechanism, but it is not working. How can I do this?

nameOftheScript="$(basename $0)"
pidOftheScript="$$"

highCpuFunction()
{
    # Function with code causing high CPU usage. Like tar, zip, etc.

    while [  -f /tmp/"$nameOftheScript"*  ];
    do
        sleep 5;
    done
    touch /tmp/"$nameOftheScript"_"$pidOftheScript"

    echo "$(date +%s) I am a Bad function you do not want to call me simultaniously..."
    # Real high CPU usage code for reaching the database and
    # parsing logs. It takes the heck out of the CPU.

    rm -rf /tmp/"$nameOftheScript"_"$pidOftheScript" 2>/dev/null
}

while true
do
   sleep 2
    highCpuFunction
done

# The rest of the code...

In short, I want to run highCpuFunction at least with a gap of 5 seconds. Regardless of the instance/user/terminal. I need to allow other users to run this function but in proper sequence and with a gap of at least 5 seconds.

Body:
Use the flock tool. Consider this code (let's call it 'onlyoneofme.sh'):

#!/bin/sh

exec 9>/var/lock/myexclusivelock

flock 9
echo start
sleep 10
echo stop

It will open file /var/lock/myexclusivelock as descriptor 9 and then try to lock it exclusively. Only one instance of the script will be allowed to pass behind the flock 9 command. The rest of them will wait for the other script to finish (so the descriptor will be closed and the lock freed). After this, the next script will acquire the lock and execute, and so on.


问:
-timestamp in Django
I'm trying to learn Django. I'm completely green so far. I'm learning from not very good book - first thing we're creating is a simple blog. So, at the end of this excersie they want me to sort my blog post - so the new posts are on top. In order to achieve that im adding:

```<code>class Meta:
    ordering = ('-timestamp',)
</code>```

in views.py. Unfortunately, it changes nothing - my posts are not moving. The book is not very descriptive about that. Do I have to register this class somewhere? I want my pseudo-blog to be pwetty! :P

Thanks in advance.

答:
There's a few ways to do this. By adding a Meta class, you give the object an inherent ordering. Using the manager to get all() will return you a list-like group of every object, in order. I haven't tested it myself but the list you get from a filter() ought to be in order too.

Now, you can also order at the time of the query:

```<code>BlogEntry.objects.all().order_by('-timestamp')
</code>```

will sort by descending timestamp.

Note that these both presuppose a field in your model called 'timestamp' that contains a sortable field (like a DateTimeField, probably, in this case)

If adding the Meta didn't change your order, I suspect you're sorting by something else, somewhere else. How about posting the query that should generate the sorted list?

Title: -timestamp in Django

Body:
I'm trying to learn Django. I'm completely green so far. I'm learning from not very good book - first thing we're creating is a simple blog. So, at the end of this excersie they want me to sort my blog post - so the new posts are on top. In order to achieve that im adding:

class Meta:
    ordering = ('-timestamp',)

in views.py. Unfortunately, it changes nothing - my posts are not moving. The book is not very descriptive about that. Do I have to register this class somewhere? I want my pseudo-blog to be pwetty! :P

Thanks in advance.

Body:
There's a few ways to do this. By adding a Meta class, you give the object an inherent ordering. Using the manager to get all() will return you a list-like group of every object, in order. I haven't tested it myself but the list you get from a filter() ought to be in order too.

Now, you can also order at the time of the query:

BlogEntry.objects.all().order_by('-timestamp')

will sort by descending timestamp.

Note that these both presuppose a field in your model called 'timestamp' that contains a sortable field (like a DateTimeField, probably, in this case)

If adding the Meta didn't change your order, I suspect you're sorting by something else, somewhere else. How about posting the query that should generate the sorted list?


问:
Are message queues obsolete in linux?
I've been playing with message queues (System V, but POSIX should be ok too) in Linux recently and they seem perfect for my application, but after reading The Art of Unix Programming I'm not sure if they are really a good choice.

http://www.faqs.org/docs/artu/ch07s02.html#id2922148

The upper, message-passing layer of System V IPC has largely fallen out of use. The lower layer, which consists of shared memory and semaphores, still has significant applications under circumstances in which one needs to do mutual-exclusion locking and some global data sharing among processes running on the same machine. These System V shared memory facilities evolved into the POSIX shared-memory API, supported under Linux, the BSDs, MacOS X and Windows, but not classic MacOS.

http://www.faqs.org/docs/artu/ch07s03.html#id2923376

The System V IPC facilities are present in Linux and other modern Unixes. However, as they are a legacy feature, they are not exercised very often. The Linux version is still known to have bugs as of mid-2003. Nobody seems to care enough to fix them.

Are the System V message queues still buggy in more recent Linux versions? I'm not sure if the author means that POSIX message queues should be ok?

It seems that sockets are the preferred IPC for almost anything(?), but I cannot see how it would be very simple to implement message queues with sockets or something else. Or am I thinking too complexly?

I don't know if it's relevant that I'm working with embedded Linux?

答:
Biggest disadvantages of POSIX message queue:

POSIX message queue does not make it a requirement to be compatible with select().(It works with select() in Linux but not in Qnx system)

It has surprises.

Unix Datagram socket does the same task of POSIX message queue. And Unix Datagram socket works in socket layer. It is possible to use it with select()/poll() or other IO-wait methods. Using select()/poll() has the advantage when designing event-based system. It is possible to avoid busy loop in that way.

There is surprise in message queue. Think about mq_notify(). It is used to get receive-event. It sounds like we can notify something about the message queue. But it is actually registering for notification instead of notifying anything.

More surprise about mq_notify() is that it has to be called after every mq_receive(), which may cause a race-condition(when some other process/thread call mq_send() between the call of mq_receive() and mq_notify()).

And it has a whole set of mq_open, mq_send(), mq_receive() and mq_close() with their own definition which is redundant and in some case inconsistent with socket open(),send(),recv() and close() method specification.

I do not think message queue should be used for synchronization. eventfd and signalfd are suitable for that.

But it(POSIX message queue) has some realtime support. It has priority features.

```<code>Messages are placed on the queue in decreasing order of priority, with newer messages of the same priority being placed after older messages with the same priority.
</code>```

But this priority is also available for socket as out-of-band data !

Finally, to me , POSIX message queue is a legacy API. I always prefer Unix Datagram socket instead of POSIX message queue as long as the real-time features are not needed.

Title: Are message queues obsolete in linux?

Body:
Biggest disadvantages of POSIX message queue:

POSIX message queue does not make it a requirement to be compatible with select().(It works with select() in Linux but not in Qnx system)

It has surprises.

Unix Datagram socket does the same task of POSIX message queue. And Unix Datagram socket works in socket layer. It is possible to use it with select()/poll() or other IO-wait methods. Using select()/poll() has the advantage when designing event-based system. It is possible to avoid busy loop in that way.

There is surprise in message queue. Think about mq_notify(). It is used to get receive-event. It sounds like we can notify something about the message queue. But it is actually registering for notification instead of notifying anything.

More surprise about mq_notify() is that it has to be called after every mq_receive(), which may cause a race-condition(when some other process/thread call mq_send() between the call of mq_receive() and mq_notify()).

And it has a whole set of mq_open, mq_send(), mq_receive() and mq_close() with their own definition which is redundant and in some case inconsistent with socket open(),send(),recv() and close() method specification.

I do not think message queue should be used for synchronization. eventfd and signalfd are suitable for that.

But it(POSIX message queue) has some realtime support. It has priority features.

Messages are placed on the queue in decreasing order of priority, with newer messages of the same priority being placed after older messages with the same priority.

But this priority is also available for socket as out-of-band data !

Finally, to me , POSIX message queue is a legacy API. I always prefer Unix Datagram socket instead of POSIX message queue as long as the real-time features are not needed.


问:
Is it possible to make a transparent container with only html while keeping text opacity?
I would like to make my container background transparent while keeping the text/image opacity. Is it possible to do this using only html?
Here is my code:</p>

```<code><div class="container">
 <div class="well text-center" >
    <div class="col-md-10"></div>
    <div class="row">

        <div class="col-md-3">
            <a href="#"><img src="images/link/BDSlogo-vert-blue.png" alt="logo"></a>
        </div>
        <div class="col-md-3">
            <a href="#"><img src="images/link/skyjacker.png" alt="logo"></a>
        </div>
        <div class="col-md-3">
            <a href="#"><img src="images/link/magnaflow.png" alt="logo"></a>
        </div>
        <div class="col-md-3">
            <a href="#"><img src="images/link/jeep_poison_spyder_logo.jpeg" alt="logo"></a>
        </div>

    </div>
  </div>
</div>
</code>```

答:
I saw your question and, if I'm understanding you correctly, I think I know what you can do. One thing I noticed, before I go any further is that it looks like you are using a Bootstraps code.

It would probably be better, more efficient and possibly not break other elements of the overall code if you changed the CSS stylesheet that may be linked to this, but let's see if my solution will work for you regardless.

Basically want you want to do is:

1) write a "style" tag in your html and then put in the styling (css) properties within that (you can put it in the header of your html code to keep better track of it).

2) use the "rgba" format of providing a background color and giving it an opacity of "0" as the 4th value of the code snippet.

So, for example, the style tag in the head could be:

```<code><style>.container {background-color: rgba(255, 255, 255, 0);}</style>
</code>```

That is the only way I can think of that you can  have a transparent background, without using a stylesheet and only using CSS.

One thing I should mention is that the default color for elements (divs) is actually transparent. But I don't know if you have some special conditions in your code elsewhere that is the reason for you asking your question.

Hey, I hope that helps. Please post your results.

Body:
I saw your question and, if I'm understanding you correctly, I think I know what you can do. One thing I noticed, before I go any further is that it looks like you are using a Bootstraps code.

It would probably be better, more efficient and possibly not break other elements of the overall code if you changed the CSS stylesheet that may be linked to this, but let's see if my solution will work for you regardless.

Basically want you want to do is:

1) write a "style" tag in your html and then put in the styling (css) properties within that (you can put it in the header of your html code to keep better track of it).

2) use the "rgba" format of providing a background color and giving it an opacity of "0" as the 4th value of the code snippet.

So, for example, the style tag in the head could be:

<style>.container {background-color: rgba(255, 255, 255, 0);}</style>

That is the only way I can think of that you can  have a transparent background, without using a stylesheet and only using CSS.

One thing I should mention is that the default color for elements (divs) is actually transparent. But I don't know if you have some special conditions in your code elsewhere that is the reason for you asking your question.

Hey, I hope that helps. Please post your results.


问:
Error in Crystal Reports (Failed to load database information)
I am developing a system and I need to produce reports. I am using Crystal Report and my language is C#. The problem is, when I execute the program, it gives me an error like what you see in the picture below but there is no error in code. What is the solution for these?

My code in windows form application:

```<code>private void MedReceipt_Load(object sender, EventArgs e)
{
            ReportDocument cryRpt = new ReportDocument();
            cryRpt.Load("C:\\Users\\Joseph\\Documents\\Visual Studio 2010\\Projects\\PRMS-Capstone\\PRMS-Capstone\\Receipt1.rpt");
            reportMedReceipt.ReportSource = cryRpt;
            reportMedReceipt.Refresh();
}
</code>```

答:
Try this answer

Add the <startup> code below code under the <configuration> element in your app.config

```<code><startup useLegacyV2RuntimeActivationPolicy="true"></startup>
</code>```

Body:
I am developing a system and I need to produce reports. I am using Crystal Report and my language is C#. The problem is, when I execute the program, it gives me an error like what you see in the picture below but there is no error in code. What is the solution for these?

My code in windows form application:

private void MedReceipt_Load(object sender, EventArgs e)
{
            ReportDocument cryRpt = new ReportDocument();
            cryRpt.Load("C:\\Users\\Joseph\\Documents\\Visual Studio 2010\\Projects\\PRMS-Capstone\\PRMS-Capstone\\Receipt1.rpt");
            reportMedReceipt.ReportSource = cryRpt;
            reportMedReceipt.Refresh();
}

Body:
Try this answer

Add the <startup> code below code under the <configuration> element in your app.config

<startup useLegacyV2RuntimeActivationPolicy="true"></startup>