问:
NestedScrollview won't start from top
I have a Recyclerview in a NestedScrollview.. everything is working fine except one thig. I have total three view in NestedScrollview First two are LinearLayout then Recyclerview. when i run my app the Activity don't show top two layout it starts from top of the Recyclerview.

How its show my layout:

How its suppose to show:

And i am loading this enite layout under a viewpager and my viewpager is a child of Coordinator Layout.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/home_layout_background">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <com.daimajia.slider.library.SliderLayout
            android:id="@+id/image_slider"
            android:layout_width="match_parent"
            android:layout_height="@dimen/image_slider_height"
            android:layout_marginTop="@dimen/image_slider_top_margin" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/popular_fragment_side_padding"
        android:layout_marginRight="@dimen/popular_fragment_side_padding"
        android:layout_marginTop="@dimen/popular_fragment_side_padding"
        android:orientation="horizontal"
        android:weightSum="4">

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <RelativeLayout
                android:id="@+id/free_delivery"
                android:layout_width="76dp"
                android:layout_height="76dp"
                android:layout_centerInParent="true"
                android:background="@color/white">

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true">

                    <ImageView
                        android:id="@+id/btnImageViewFreeDelivery"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerHorizontal="true"
                        android:background="@drawable/icon_free_delivery" />

                    <TextView
                        android:id="@+id/btnTextFreeDelivery"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/btnImageViewFreeDelivery"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="2dp"
                        android:text="@string/free_delivery_txt"
                        android:textColor="@color/popular_fragment_four_btn_txt"
                        android:textSize="@dimen/popular_fragment_four_btn_txt_size" />
                </RelativeLayout>

            </RelativeLayout>

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <RelativeLayout
                android:id="@+id/flash_deals"
                android:layout_width="76dp"
                android:layout_height="76dp"
                android:layout_centerInParent="true"
                android:background="@color/white">

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true">

                    <ImageView
                        android:id="@+id/btnImageViewFlashDeals"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerHorizontal="true"
                        android:background="@drawable/icon_flash_deals" />

                    <TextView
                        android:id="@+id/btnTextFlashDeals"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/btnImageViewFlashDeals"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="2dp"
                        android:text="@string/flash_deals_txt"
                        android:textColor="@color/popular_fragment_four_btn_txt"
                        android:textSize="@dimen/popular_fragment_four_btn_txt_size" />
                </RelativeLayout>

            </RelativeLayout>

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <RelativeLayout
                android:id="@+id/for_you"
                android:layout_width="76dp"
                android:layout_height="76dp"
                android:layout_centerInParent="true"
                android:background="@color/white">

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true">

                    <ImageView
                        android:id="@+id/btnImageViewForYou"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerHorizontal="true"
                        android:background="@drawable/icon_for_you" />

                    <TextView
                        android:id="@+id/btnTextForYou"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/btnImageViewForYou"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="2dp"
                        android:text="@string/for_you_txt"
                        android:textColor="@color/popular_fragment_four_btn_txt"
                        android:textSize="@dimen/popular_fragment_four_btn_txt_size" />
                </RelativeLayout>

            </RelativeLayout>
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <RelativeLayout
                android:id="@+id/shake_deals"
                android:layout_width="76dp"
                android:layout_height="76dp"
                android:layout_centerInParent="true"
                android:background="@color/white">

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true">

                    <ImageView
                        android:id="@+id/btnImageViewShakeDeals"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerHorizontal="true"
                        android:background="@drawable/icon_shake_deals" />

                    <TextView
                        android:id="@+id/btnTextShakeDeals"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/btnImageViewShakeDeals"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="2dp"
                        android:text="@string/shake_deals"
                        android:textColor="@color/popular_fragment_four_btn_txt"
                        android:textSize="@dimen/popular_fragment_four_btn_txt_size" />
                </RelativeLayout>

            </RelativeLayout>
        </RelativeLayout>
    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="@dimen/popular_fragment_side_padding"
        android:layout_marginRight="@dimen/popular_fragment_side_padding"
        android:layout_marginTop="18dp"
        android:scrollbars="none" />

</LinearLayout>

</android.support.v4.widget.NestedScrollView>
</code>```

My ViewPager Layout

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v4.view.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/home_layout_background"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_gravity="center"
        android:background="@drawable/toolbar_background"
        app:layout_scrollFlags="scroll|enterAlways">

        <TextView
            android:id="@+id/toolbar_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="@string/title_home"
            android:textColor="@color/toolbar_title_txt_color"
            android:textSize="@dimen/toolbar_txt_size"
            android:textStyle="bold" />

    </android.support.v7.widget.Toolbar>

    <android.support.design.widget.TabLayout android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        app:tabMode="scrollable"
        app:tabTextColor="@color/tab_bar_txt"
        app:tabIndicatorColor="@color/tab_bar_txt_selected"
        app:tabSelectedTextColor="@color/tab_bar_txt_selected"
        app:tabTextAppearance="@style/TabTextAppeareance"/>

</android.support.design.widget.AppBarLayout>

</android.support.design.widget.CoordinatorLayout>
</code>```

答:
I had the same problem, and I fixed it the following way.

Add android:descendantFocusability="blocksDescendants" to the Linear Layout which is the only child of the Nested Scroll View.

This allows the Nested Scroll View to start from the top with minimal change to code.

ContentLicense: CC BY-SA 4.0

Title: NestedScrollview won't start from top

Body:
I have a Recyclerview in a NestedScrollview.. everything is working fine except one thig. I have total three view in NestedScrollview First two are LinearLayout then Recyclerview. when i run my app the Activity don't show top two layout it starts from top of the Recyclerview.

How its show my layout:

How its suppose to show:

And i am loading this enite layout under a viewpager and my viewpager is a child of Coordinator Layout.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/home_layout_background">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <com.daimajia.slider.library.SliderLayout
            android:id="@+id/image_slider"
            android:layout_width="match_parent"
            android:layout_height="@dimen/image_slider_height"
            android:layout_marginTop="@dimen/image_slider_top_margin" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/popular_fragment_side_padding"
        android:layout_marginRight="@dimen/popular_fragment_side_padding"
        android:layout_marginTop="@dimen/popular_fragment_side_padding"
        android:orientation="horizontal"
        android:weightSum="4">

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <RelativeLayout
                android:id="@+id/free_delivery"
                android:layout_width="76dp"
                android:layout_height="76dp"
                android:layout_centerInParent="true"
                android:background="@color/white">

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true">

                    <ImageView
                        android:id="@+id/btnImageViewFreeDelivery"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerHorizontal="true"
                        android:background="@drawable/icon_free_delivery" />

                    <TextView
                        android:id="@+id/btnTextFreeDelivery"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/btnImageViewFreeDelivery"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="2dp"
                        android:text="@string/free_delivery_txt"
                        android:textColor="@color/popular_fragment_four_btn_txt"
                        android:textSize="@dimen/popular_fragment_four_btn_txt_size" />
                </RelativeLayout>

            </RelativeLayout>

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <RelativeLayout
                android:id="@+id/flash_deals"
                android:layout_width="76dp"
                android:layout_height="76dp"
                android:layout_centerInParent="true"
                android:background="@color/white">

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true">

                    <ImageView
                        android:id="@+id/btnImageViewFlashDeals"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerHorizontal="true"
                        android:background="@drawable/icon_flash_deals" />

                    <TextView
                        android:id="@+id/btnTextFlashDeals"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/btnImageViewFlashDeals"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="2dp"
                        android:text="@string/flash_deals_txt"
                        android:textColor="@color/popular_fragment_four_btn_txt"
                        android:textSize="@dimen/popular_fragment_four_btn_txt_size" />
                </RelativeLayout>

            </RelativeLayout>

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <RelativeLayout
                android:id="@+id/for_you"
                android:layout_width="76dp"
                android:layout_height="76dp"
                android:layout_centerInParent="true"
                android:background="@color/white">

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true">

                    <ImageView
                        android:id="@+id/btnImageViewForYou"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerHorizontal="true"
                        android:background="@drawable/icon_for_you" />

                    <TextView
                        android:id="@+id/btnTextForYou"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/btnImageViewForYou"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="2dp"
                        android:text="@string/for_you_txt"
                        android:textColor="@color/popular_fragment_four_btn_txt"
                        android:textSize="@dimen/popular_fragment_four_btn_txt_size" />
                </RelativeLayout>

            </RelativeLayout>
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <RelativeLayout
                android:id="@+id/shake_deals"
                android:layout_width="76dp"
                android:layout_height="76dp"
                android:layout_centerInParent="true"
                android:background="@color/white">

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true">

                    <ImageView
                        android:id="@+id/btnImageViewShakeDeals"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerHorizontal="true"
                        android:background="@drawable/icon_shake_deals" />

                    <TextView
                        android:id="@+id/btnTextShakeDeals"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/btnImageViewShakeDeals"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="2dp"
                        android:text="@string/shake_deals"
                        android:textColor="@color/popular_fragment_four_btn_txt"
                        android:textSize="@dimen/popular_fragment_four_btn_txt_size" />
                </RelativeLayout>

            </RelativeLayout>
        </RelativeLayout>
    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="@dimen/popular_fragment_side_padding"
        android:layout_marginRight="@dimen/popular_fragment_side_padding"
        android:layout_marginTop="18dp"
        android:scrollbars="none" />

</LinearLayout>

</android.support.v4.widget.NestedScrollView>

My ViewPager Layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v4.view.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/home_layout_background"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_gravity="center"
        android:background="@drawable/toolbar_background"
        app:layout_scrollFlags="scroll|enterAlways">

        <TextView
            android:id="@+id/toolbar_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="@string/title_home"
            android:textColor="@color/toolbar_title_txt_color"
            android:textSize="@dimen/toolbar_txt_size"
            android:textStyle="bold" />

    </android.support.v7.widget.Toolbar>

    <android.support.design.widget.TabLayout android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        app:tabMode="scrollable"
        app:tabTextColor="@color/tab_bar_txt"
        app:tabIndicatorColor="@color/tab_bar_txt_selected"
        app:tabSelectedTextColor="@color/tab_bar_txt_selected"
        app:tabTextAppearance="@style/TabTextAppeareance"/>

</android.support.design.widget.AppBarLayout>

</android.support.design.widget.CoordinatorLayout>


来源: stackexchange

问:
Load resources in Java from absolute path within jar
Don't flag as duplicate yet!

Hear me out; all of the solutions that I have seen are good, but I don't understand how the class paths work when loading resources using:

```<code>ClassLoader classLoader = getClass().getClassLoader()
</code>```

I want to set up a resource loader (named ResourceLoader) that can load from anywhere within the jar package.

So if the loader is placed in com.spikespaz.engine.loader.ResourceLoader, I don't want to be stuck in the relative path of com.spikespaz.engine.loader.

I want to be able to load from com.spikespaz.game.resources.textures and com.spikespaz.game.resources.models without the need to put a reader in the parent directory.

What I found is this: https://stackoverflow.com/a/3862115/2512078

But from what I understood, all of those options in his answer must be relative to the class loading them. (getClass()) Is there a way around this, or am I misunderstanding it?

If I am misunderstanding it, could someone explain better?

Any solutions must be relative to the exact root of the jar package or source of the development environment, and I must not need to put anything in that root.

Thanks.

答:
I think you misunderstood or misread his answer https://stackoverflow.com/a/3862115/2512078

Both the normal classloader and the context classloader are able to load resources with an absolute path.

To do this using the normal classloader, make sure the resource path has a leading / in front of it, otherwise it loads the resource relative to the package of the class loading it.

```<code>this.getClass().getResource("/foo/bar.txt")`
</code>```

The context classloader is never loading resources relative to a class, paths are always interpreted as absolute paths.

```<code>Thread.currentThread().getContextClassLoader().getResource("foo/bar.txt")
</code>```

Note: Do not use a leading slash with the context classloader.

ContentLicense: CC BY-SA 3.0

Body:
Don't flag as duplicate yet!

Hear me out; all of the solutions that I have seen are good, but I don't understand how the class paths work when loading resources using:

ClassLoader classLoader = getClass().getClassLoader()

I want to set up a resource loader (named ResourceLoader) that can load from anywhere within the jar package.

So if the loader is placed in com.spikespaz.engine.loader.ResourceLoader, I don't want to be stuck in the relative path of com.spikespaz.engine.loader.

I want to be able to load from com.spikespaz.game.resources.textures and com.spikespaz.game.resources.models without the need to put a reader in the parent directory.

What I found is this: https://stackoverflow.com/a/3862115/2512078

But from what I understood, all of those options in his answer must be relative to the class loading them. (getClass()) Is there a way around this, or am I misunderstanding it?

If I am misunderstanding it, could someone explain better?

Any solutions must be relative to the exact root of the jar package or source of the development environment, and I must not need to put anything in that root.

Thanks.

Body:
I think you misunderstood or misread his answer https://stackoverflow.com/a/3862115/2512078

Both the normal classloader and the context classloader are able to load resources with an absolute path.

To do this using the normal classloader, make sure the resource path has a leading / in front of it, otherwise it loads the resource relative to the package of the class loading it.

this.getClass().getResource("/foo/bar.txt")`

The context classloader is never loading resources relative to a class, paths are always interpreted as absolute paths.

Thread.currentThread().getContextClassLoader().getResource("foo/bar.txt")

Note: Do not use a leading slash with the context classloader.


问:
StatusBarNotification how to get data or resend intent?
My Apps receives Push Notification via Firebase. Now there a 3 distinct situations that can happen when the notification arrives:

The app is in the foreground

The app is in the background

The app is not running

Situation 1 is no problem. The notification is received in the app ok.
Situation 2 and 3 work fine as long as you tap the notification in the drawer.
In Situation 2 and 3 when the app icon is tapped instead of the drawer icon the app does not receive any notification at all. I've tried to get the active notifications from the StatusBar and that works but I can not either retrieve the data from the Extras or resend the notification to the waiting push notification service. Here's the experimental code to get the Notifications.

```<code>        NotificationManager notificationManager = (NotificationManager)Application.Context.GetSystemService(Context.NotificationService);

        var notifications = notificationManager.GetActiveNotifications()
            .Where(notif => notif.PackageName == Application.Context.PackageName);

        foreach (var notification in notifications)
        {
            Log.Info(TAG, "OnActivityResumed: Notification in active in Status Bar: {0}", notification.Notification.ToString());

            var data = notification.Notification.Extras.GetString("data");

            Log.Debug("Notifier", "Data received: {0}", data);

            //if (data != null)
            //{
            //    Settings.Notification = JsonConvert.DeserializeObject<LoginNotificationParameter>(data);
            //}
        }

        // Canceling all notifications
        notificationManager.CancelAll();
</code>```

Questions:

Is it correct behavior that the app does not receive any intents when a notification is in the drawer?

If so how to I handle situations 2 and 3 when the user tapps the app icon instead of the drawer notification?

I see this data in het Notification when printing all the Extras Key Values:

```<code>06-28 16:34:13.174 20792 20792 I Notifier: OnActivityResumed: Notification is active in Status Bar: Notification(pri=0 contentView=null vibrate=null sound=content://settings/system/notification_sound defaults=0x0 flags=0x10 color=0x00000000 vis=PRIVATE semFlags=0x0 semPriority=0)
06-28 16:34:13.191 20792 20792 I Notifier: KeyIn: Extras Key: android.title Data: Login
06-28 16:34:13.191 20792 20792 I Notifier: KeyIn: Extras Key: android.subText Data:
06-28 16:34:13.191 20792 20792 I Notifier: KeyIn: Extras Key: android.template Data: android.app.Notification$BigTextStyle
06-28 16:34:13.192 20792 20792 I Notifier: KeyIn: Extras Key: android.showChronometer Data: false
06-28 16:34:13.192 20792 20792 I Notifier: KeyIn: Extras Key: android.text Data: Er is een inlogverzoek voor u ontvangen.
06-28 16:34:13.194 20792 20792 I Notifier: KeyIn: Extras Key: android.progress Data: 0
06-28 16:34:13.194 20792 20792 I Notifier: KeyIn: Extras Key: android.progressMax Data: 0
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.appInfo Data: ApplicationInfo{a27f281 nl.natuurnetwerk.notifier}
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.showWhen Data: true
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.largeIcon Data:
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.bigText Data: Er is een inlogverzoek voor u ontvangen.
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.infoText Data:
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.originatingUserId Data: 0
06-28 16:34:13.196 20792 20792 I Notifier: KeyIn: Extras Key: android.progressIndeterminate Data: false
06-28 16:34:13.196 20792 20792 I Notifier: KeyIn: Extras Key: android.remoteInputHistory Data:
</code>```

答:
Extends FirebaseMessagingService and override the onMessageReceived and onDeletedMessages callbacks. To automatically open an application / activity when a notification is received, you need to use a data (something like {"data" : { "some_key" : "some_value"}}) attribute in your payload, which guarantees to always invoke the FirebaseMessagingService.onMessageReceived() method.

Please note that opening an activity / app on notification without user's interaction is really bad and should be avoided.

Body:
My Apps receives Push Notification via Firebase. Now there a 3 distinct situations that can happen when the notification arrives:

The app is in the foreground

The app is in the background

The app is not running

Situation 1 is no problem. The notification is received in the app ok.
Situation 2 and 3 work fine as long as you tap the notification in the drawer.
In Situation 2 and 3 when the app icon is tapped instead of the drawer icon the app does not receive any notification at all. I've tried to get the active notifications from the StatusBar and that works but I can not either retrieve the data from the Extras or resend the notification to the waiting push notification service. Here's the experimental code to get the Notifications.

        NotificationManager notificationManager = (NotificationManager)Application.Context.GetSystemService(Context.NotificationService);

        var notifications = notificationManager.GetActiveNotifications()
            .Where(notif => notif.PackageName == Application.Context.PackageName);

        foreach (var notification in notifications)
        {
            Log.Info(TAG, "OnActivityResumed: Notification in active in Status Bar: {0}", notification.Notification.ToString());

            var data = notification.Notification.Extras.GetString("data");

            Log.Debug("Notifier", "Data received: {0}", data);

            //if (data != null)
            //{
            //    Settings.Notification = JsonConvert.DeserializeObject<LoginNotificationParameter>(data);
            //}
        }

        // Canceling all notifications
        notificationManager.CancelAll();

Questions:

Is it correct behavior that the app does not receive any intents when a notification is in the drawer?

If so how to I handle situations 2 and 3 when the user tapps the app icon instead of the drawer notification?

I see this data in het Notification when printing all the Extras Key Values:

06-28 16:34:13.174 20792 20792 I Notifier: OnActivityResumed: Notification is active in Status Bar: Notification(pri=0 contentView=null vibrate=null sound=content://settings/system/notification_sound defaults=0x0 flags=0x10 color=0x00000000 vis=PRIVATE semFlags=0x0 semPriority=0)
06-28 16:34:13.191 20792 20792 I Notifier: KeyIn: Extras Key: android.title Data: Login
06-28 16:34:13.191 20792 20792 I Notifier: KeyIn: Extras Key: android.subText Data:
06-28 16:34:13.191 20792 20792 I Notifier: KeyIn: Extras Key: android.template Data: android.app.Notification$BigTextStyle
06-28 16:34:13.192 20792 20792 I Notifier: KeyIn: Extras Key: android.showChronometer Data: false
06-28 16:34:13.192 20792 20792 I Notifier: KeyIn: Extras Key: android.text Data: Er is een inlogverzoek voor u ontvangen.
06-28 16:34:13.194 20792 20792 I Notifier: KeyIn: Extras Key: android.progress Data: 0
06-28 16:34:13.194 20792 20792 I Notifier: KeyIn: Extras Key: android.progressMax Data: 0
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.appInfo Data: ApplicationInfo{a27f281 nl.natuurnetwerk.notifier}
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.showWhen Data: true
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.largeIcon Data:
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.bigText Data: Er is een inlogverzoek voor u ontvangen.
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.infoText Data:
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.originatingUserId Data: 0
06-28 16:34:13.196 20792 20792 I Notifier: KeyIn: Extras Key: android.progressIndeterminate Data: false
06-28 16:34:13.196 20792 20792 I Notifier: KeyIn: Extras Key: android.remoteInputHistory Data:


问:
Unable to view text in columnHeaders in jasper report
I am trying to create a jasper report (pdf format) that displays list of calls handled. The report is getting created but the heading are not being shown. I have tried to make changes in style but nothing seems to work for this case.

I am using the following libs for this

```<code>-    jasper-compiler-jdt-5.5.15.jar
-    jasperreports-6.2.0.jar
-    jasperreports-fonts-6.0.0.jar
-    itext-2.1.7.jar
-    itextpdf-5.5.10.jar
</code>```

Following is part of jrxml file

```<code><?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="StockReport" pageWidth="1200" pageHeight="600" columnWidth="50" leftMargin="35" rightMargin="35" topMargin="50" bottomMargin="40">

<parameter name="Title" class="java.lang.String"/>

<field name="id" class="java.lang.Long"/>
<field name="dateTime" class="java.util.Date"/>

 --------------------------------------------------

<title>
<band height="50" splitType="Stretch">
    <textField isBlankWhenNull="true">
        <reportElement x="0" y="5" width="960" height="30"/>
            <textElement textAlignment="Center">

            </textElement>
            <textFieldExpression class="java.lang.String"><![CDATA[$P{Title}]]>
            </textFieldExpression>
   </textField>
</band>
</title>
<pageHeader>
<band height="20" splitType="Stretch">
    <textField>
        <reportElement mode="Opaque" x="55" y="5" width="1000" height="15" forecolor="#FFFFFF" backcolor="#8c8c8c"/>
        <textElement textAlignment="Center">
        </textElement>
        <textFieldExpression class="java.lang.String"><![CDATA["Daily Reports"]]></textFieldExpression>
    </textField>
</band>
</pageHeader>
<columnHeader>
   <band height="20" splitType="Stretch">
    <staticText>
        <reportElement mode="Opaque" x="55" y="4" width="30" height="15" forecolor="#FFFFFF" backcolor="#b30000"/>
        <textElement textAlignment="Left">
            <font isBold = "true"/>
        </textElement>
        <text>
            <![CDATA["Record Id"]]>
        </text>
    </staticText>
    <staticText>
         <reportElement positionType="Float" mode="Opaque" x="85" y="4" width="100" height="15" forecolor="#FFFFFF" backcolor="#b30000"/>
        <textElement>
            <font isBold = "true"/>
        </textElement>
        <text>
            <![CDATA["Date/Time"]]>
         </text>
    </staticText>

 -------------------------------------------

 </band>
</columnHeader>
<detail>
   <band height="80" splitType="Stretch">
    <textField>
        <reportElement x="65" y="4" width="15" height="60"/>
    <textElement textAlignment="Left"/>
        <textFieldExpression class="java.lang.Long"><![CDATA[$F{id}]]>
        </textFieldExpression>
    </textField>
    <textField isStretchWithOverflow="true">
        <reportElement positionType="Float" x="95" y="4" width="90" height="60"/>
    <textElement/>
    <textFieldExpression class="java.util.Date"><![CDATA[$F{dateTime}]]></textFieldExpression>
</textField>

 -----------------------------------------------------
</code>```

This is my jrxml file.

It is displaying all the data correctly except the column headers. I cannot understand what the problem is. Also I am getting the following warning

```<code>WARN  [net.sf.jasperreports.engine.export.PdfGlyphRenderer] -------- Unpatched iText found, cannot use glyph rendering
</code>```

Screenshot of generated pdf (some details have been scratched off)

Any help will be highly appreciated.

I am not using iReport tool. Currently the use of the same is restricted to our group. Please suggest a solution other than this.

Thanks in advance.

答:
Thanks to all who helped.

The problem was not related to itext and was related to element styling.

The updated code is as follows.

```<code>  <?xml version="1.0" encoding="UTF-8"?>
  <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="StockReport" pageWidth="1200" pageHeight="600" columnWidth="50" leftMargin="35" rightMargin="35" topMargin="50" bottomMargin="40">

<parameter name="Title" class="java.lang.String"/>

<field name="id" class="java.lang.Long"/>
<field name="dateTime" class="java.util.Date"/>

--------------------

<title>
<band height="50" splitType="Stretch">
<textField isBlankWhenNull="true">
    <reportElement x="0" y="5" width="960" height="30"/>
    <textElement textAlignment="Center">
    </textElement>
    <textFieldExpression class="java.lang.String"><![CDATA[$P{Title}]]></textFieldExpression>
</textField>
 </band>
 </title>
 <pageHeader>
 <band height="20" splitType="Stretch">
<textField>
    <reportElement mode="Opaque" x="55" y="5" width="1000" height="15" forecolor="#FFFFFF" backcolor="#8c8c8c"/>
    <textElement textAlignment="Center">
    </textElement>
    <textFieldExpression class="java.lang.String"><![CDATA["Daily Reports"]]></textFieldExpression>
</textField>
 </band>
 </pageHeader>
    <columnHeader>
  <band height = "23">

     <staticText>
        <reportElement mode = "Opaque" x = "55" y = "3"
           width = "1000" height = "15" backcolor = "#70A9A9" />

        <box>
           <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" />
        </box>

        <textElement />
        <text><![CDATA[]]> </text>
     </staticText>

-------------------------------------

     <staticText>
        <reportElement x = "85" y = "3" width = "100" height = "15" />

        <textElement textAlignment = "Center" verticalAlignment = "Middle">
           <font isBold = "true" />
        </textElement>

        <text><![CDATA[Date/Time]]></text>
     </staticText>

     <staticText>
        <reportElement x = "55" y = "3" width = "30" height = "15" />

        <textElement textAlignment = "Center" verticalAlignment = "Middle">
           <font isBold = "true" />
        </textElement>

        <text><![CDATA[#Id]]></text>
     </staticText>

  </band>
</code>```

What i did is that I simply added a   element, with no text content to be used as column header banner and added the header text on top of it by specifying the position.

I am not sure of the logic behind this. As for the warning, the Unpatched iText found, cannot use glyph rendering still persits. I am not sure of how to resolve that, but the above cited helped me resolve the initial problem. I hope this would help if anyone come across a similar issue.

Once again thanks to all those who helped and as suggested in above comments I will try to do the same with updated libraries and will definitely edit my post with updated results if it help solve the issue.

Body:
I am trying to create a jasper report (pdf format) that displays list of calls handled. The report is getting created but the heading are not being shown. I have tried to make changes in style but nothing seems to work for this case.

I am using the following libs for this

-    jasper-compiler-jdt-5.5.15.jar
-    jasperreports-6.2.0.jar
-    jasperreports-fonts-6.0.0.jar
-    itext-2.1.7.jar
-    itextpdf-5.5.10.jar

Following is part of jrxml file

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="StockReport" pageWidth="1200" pageHeight="600" columnWidth="50" leftMargin="35" rightMargin="35" topMargin="50" bottomMargin="40">

<parameter name="Title" class="java.lang.String"/>

<field name="id" class="java.lang.Long"/>
<field name="dateTime" class="java.util.Date"/>

 --------------------------------------------------

<title>
<band height="50" splitType="Stretch">
    <textField isBlankWhenNull="true">
        <reportElement x="0" y="5" width="960" height="30"/>
            <textElement textAlignment="Center">

            </textElement>
            <textFieldExpression class="java.lang.String"><![CDATA[$P{Title}]]>
            </textFieldExpression>
   </textField>
</band>
</title>
<pageHeader>
<band height="20" splitType="Stretch">
    <textField>
        <reportElement mode="Opaque" x="55" y="5" width="1000" height="15" forecolor="#FFFFFF" backcolor="#8c8c8c"/>
        <textElement textAlignment="Center">
        </textElement>
        <textFieldExpression class="java.lang.String"><![CDATA["Daily Reports"]]></textFieldExpression>
    </textField>
</band>
</pageHeader>
<columnHeader>
   <band height="20" splitType="Stretch">
    <staticText>
        <reportElement mode="Opaque" x="55" y="4" width="30" height="15" forecolor="#FFFFFF" backcolor="#b30000"/>
        <textElement textAlignment="Left">

        </textElement>
        <text>
            <![CDATA["Record Id"]]>
        </text>
    </staticText>
    <staticText>
         <reportElement positionType="Float" mode="Opaque" x="85" y="4" width="100" height="15" forecolor="#FFFFFF" backcolor="#b30000"/>
        <textElement>

        </textElement>
        <text>
            <![CDATA["Date/Time"]]>
         </text>
    </staticText>

 -------------------------------------------

 </band>
</columnHeader>
<detail>
   <band height="80" splitType="Stretch">
    <textField>
        <reportElement x="65" y="4" width="15" height="60"/>
    <textElement textAlignment="Left"/>
        <textFieldExpression class="java.lang.Long"><![CDATA[$F{id}]]>
        </textFieldExpression>
    </textField>
    <textField isStretchWithOverflow="true">
        <reportElement positionType="Float" x="95" y="4" width="90" height="60"/>
    <textElement/>
    <textFieldExpression class="java.util.Date"><![CDATA[$F{dateTime}]]></textFieldExpression>
</textField>

 -----------------------------------------------------

This is my jrxml file.

It is displaying all the data correctly except the column headers. I cannot understand what the problem is. Also I am getting the following warning

WARN  [net.sf.jasperreports.engine.export.PdfGlyphRenderer] -------- Unpatched iText found, cannot use glyph rendering

Screenshot of generated pdf (some details have been scratched off)

Any help will be highly appreciated.

I am not using iReport tool. Currently the use of the same is restricted to our group. Please suggest a solution other than this.

Thanks in advance.

Body:
Thanks to all who helped.

The problem was not related to itext and was related to element styling.

The updated code is as follows.

  <?xml version="1.0" encoding="UTF-8"?>
  <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="StockReport" pageWidth="1200" pageHeight="600" columnWidth="50" leftMargin="35" rightMargin="35" topMargin="50" bottomMargin="40">

<parameter name="Title" class="java.lang.String"/>

<field name="id" class="java.lang.Long"/>
<field name="dateTime" class="java.util.Date"/>

--------------------

<title>
<band height="50" splitType="Stretch">
<textField isBlankWhenNull="true">
    <reportElement x="0" y="5" width="960" height="30"/>
    <textElement textAlignment="Center">
    </textElement>
    <textFieldExpression class="java.lang.String"><![CDATA[$P{Title}]]></textFieldExpression>
</textField>
 </band>
 </title>
 <pageHeader>
 <band height="20" splitType="Stretch">
<textField>
    <reportElement mode="Opaque" x="55" y="5" width="1000" height="15" forecolor="#FFFFFF" backcolor="#8c8c8c"/>
    <textElement textAlignment="Center">
    </textElement>
    <textFieldExpression class="java.lang.String"><![CDATA["Daily Reports"]]></textFieldExpression>
</textField>
 </band>
 </pageHeader>
    <columnHeader>
  <band height = "23">

     <staticText>
        <reportElement mode = "Opaque" x = "55" y = "3"
           width = "1000" height = "15" backcolor = "#70A9A9" />

        <box>
           <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" />
        </box>

        <textElement />
        <text><![CDATA[]]> </text>
     </staticText>

-------------------------------------

     <staticText>
        <reportElement x = "85" y = "3" width = "100" height = "15" />

        <textElement textAlignment = "Center" verticalAlignment = "Middle">
           <font isBold = "true" />
        </textElement>

        <text><![CDATA[Date/Time]]></text>
     </staticText>

     <staticText>
        <reportElement x = "55" y = "3" width = "30" height = "15" />

        <textElement textAlignment = "Center" verticalAlignment = "Middle">
           <font isBold = "true" />
        </textElement>

        <text><![CDATA[#Id]]></text>
     </staticText>

  </band>

What i did is that I simply added a   element, with no text content to be used as column header banner and added the header text on top of it by specifying the position.

I am not sure of the logic behind this. As for the warning, the Unpatched iText found, cannot use glyph rendering still persits. I am not sure of how to resolve that, but the above cited helped me resolve the initial problem. I hope this would help if anyone come across a similar issue.

Once again thanks to all those who helped and as suggested in above comments I will try to do the same with updated libraries and will definitely edit my post with updated results if it help solve the issue.


问:
java.lang.StringIndexOutOfBoundsException: String index out of range: -4
I have this simple Java code which gives the following error:
java.lang.StringIndexOutOfBoundsException: String index out of range: -4

the code is:

```<code>String date = "14000101";
String repayDate = date.substring(0, 4)+"-"+date.substring(5, 2)+"-"+date.substring(6, 2);
</code>```

the length of the string is 8 and yet it gives an error starting form the second part.

Any ideas?

Thanks!

答:
date.substring(5, 2) should be date.substring(5, 7) and date.substring(6, 2) should be date.substring(6, 8).

The second argument is the index of the character following the last character of the desired sub-string.

Body:
I have this simple Java code which gives the following error:
java.lang.StringIndexOutOfBoundsException: String index out of range: -4

the code is:

String date = "14000101";
String repayDate = date.substring(0, 4)+"-"+date.substring(5, 2)+"-"+date.substring(6, 2);

the length of the string is 8 and yet it gives an error starting form the second part.

Any ideas?

Thanks!


问:
How to speed up rbind?
I'm supposed to download a table from MS-SQL server.

The number of row is larger than 6million. The server cannot return entire data at once.

So, I wrote a code that downloads 10,000 rows at a time. and, it binds rows in the loop.

Assume that getData() function returns a data frame contains 10000 rows at a time. (Pseudo Code)

```<code>for(i in 1:600)
{
    tempValue <- getData()
    wannagetValue <- rbind(wannagetValue,tempValue)
    print(i)
}
</code>```

The problem is that it gets slower as time goes by.

I think using rbind like that way is not a good idea.

Any advice will be very helpful. Thank you in advance.

答:
Perhaps you could do SELECT COUNT(*) FROM table_name WHERE ... and then preallocate space for your data frame.

Actually, I don't think querying your database per 10k rows is a good idea. Try to avoid that by exporting the data to a local disk and read from there. It will improve the speed as well. Storage is cheap, network bandwidth and memory are not.

Title: How to speed up rbind?

Body:
I'm supposed to download a table from MS-SQL server.

The number of row is larger than 6million. The server cannot return entire data at once.

So, I wrote a code that downloads 10,000 rows at a time. and, it binds rows in the loop.

Assume that getData() function returns a data frame contains 10000 rows at a time. (Pseudo Code)

for(i in 1:600)
{
    tempValue <- getData()
    wannagetValue <- rbind(wannagetValue,tempValue)
    print(i)
}

The problem is that it gets slower as time goes by.

I think using rbind like that way is not a good idea.

Any advice will be very helpful. Thank you in advance.


问:
Is it safe to frequently Compact and Repair Access DB?
I have an Access Database which I populate using a pass through query.

I get specific data from an SQL database and dumps it on Access.

This Access DB is updated weekly but I cannot simply append new data from the previous week because all other past weeks also updates.

What I did is truncate the Access DB and then load everything again.

When I do that, I need to Compact and Repair the DB so that the size doesn't bloat.

My question is, is it ok to do that? Currently I am using the logic posted in this answer.

I have not encountered any problems yet but I just want to make sure and get our access guru's thought about it. Also I'm planning on doing a scheduled run on our server to do the task.

Just need to make sure that it will not get corrupted easily (what is the chance of corrupting the file in the first place?).

If you'll ask, why do I need to do this? Users of data have no access on SQL server.
So I have to pull data for them so they can just connect to Access DB instead.

Just in case you need the code:

```<code>Dim sqlDelete As String
Dim sqlAppend As String

sqlDelete = "DELETE * FROM dbo_Table;"

sqlAppend = "INSERT INTO dbo_Table (Col1,Col2) SELECT Col1,Col2 FROM passThrough;"

With DoCmd
    .SetWarnings False
    .RunSQL sqlDelete

    .RunSQL sqlAppend
    .SetWarnings True
End With

Application.SetOption "Auto Compact", True
</code>```

答: I will refer this forum post: http://www.utteraccess.com/forum/index.php?showtopic=1561733</p>

Body:
I have an Access Database which I populate using a pass through query.

I get specific data from an SQL database and dumps it on Access.

This Access DB is updated weekly but I cannot simply append new data from the previous week because all other past weeks also updates.

What I did is truncate the Access DB and then load everything again.

When I do that, I need to Compact and Repair the DB so that the size doesn't bloat.

My question is, is it ok to do that? Currently I am using the logic posted in this answer.

I have not encountered any problems yet but I just want to make sure and get our access guru's thought about it. Also I'm planning on doing a scheduled run on our server to do the task.

Just need to make sure that it will not get corrupted easily (what is the chance of corrupting the file in the first place?).

If you'll ask, why do I need to do this? Users of data have no access on SQL server.
So I have to pull data for them so they can just connect to Access DB instead.

Just in case you need the code:

Dim sqlDelete As String
Dim sqlAppend As String

sqlDelete = "DELETE * FROM dbo_Table;"

sqlAppend = "INSERT INTO dbo_Table (Col1,Col2) SELECT Col1,Col2 FROM passThrough;"

With DoCmd
    .SetWarnings False
    .RunSQL sqlDelete

    .RunSQL sqlAppend
    .SetWarnings True
End With

Application.SetOption "Auto Compact", True


问:
Getting empty result in output when using Select statement in Grid-View
Here what I have done
I make a GridView and choose the data key name as id and in the basis of id I want to show the DetailsView. Here the CS code

```<code>using (SqlConnection con1 = new SqlConnection("Data Source= IA; initial catalog =aip; integrated Security=true;"))
{
    con1.Open();
    SqlCommand cmd = new SqlCommand("select * from Pm where user_id='" +(String)Session["uid"]+ "'", con1);
    DataSet ds = new DataSet();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(ds);
    GridView1.DataSource = ds;
    GridView1.DataBind();
    con1.Close();
}
</code>```

Then I make DetailsView method on SelectedIndexChanged:
But it is showing empty DetailsView in output on selecting 'Select' option
here is the code image
enter image description here

答:
@PIYUSH Itspk please check query and replace

```<code> SqlCommand cmd = new SqlCommand("select * from Pm where user_id=" +Session["uid"].tostring()+ ", con1);
</code>```

i think its help you if any other query please notify me

Body:
Here what I have done
I make a GridView and choose the data key name as id and in the basis of id I want to show the DetailsView. Here the CS code

using (SqlConnection con1 = new SqlConnection("Data Source= IA; initial catalog =aip; integrated Security=true;"))
{
    con1.Open();
    SqlCommand cmd = new SqlCommand("select * from Pm where user_id='" +(String)Session["uid"]+ "'", con1);
    DataSet ds = new DataSet();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(ds);
    GridView1.DataSource = ds;
    GridView1.DataBind();
    con1.Close();
}

Then I make DetailsView method on SelectedIndexChanged:
But it is showing empty DetailsView in output on selecting 'Select' option
here is the code image
enter image description here

Body:
@PIYUSH Itspk please check query and replace

 SqlCommand cmd = new SqlCommand("select * from Pm where user_id=" +Session["uid"].tostring()+ ", con1);

i think its help you if any other query please notify me


问:
Centering my Logo Div
I have tried every possible method to center my logo div but no luck. I even ended up going back to old school align="center" but no luck.

Please help - http://rezaee.me/kel/

Cheers

答:
I don't think removing position fixed is enough.  Remove all css and try this

Make your logo an img tag instead of a background, then use margin-left:50%; margin-right:50%; width: (width of img);

ContentLicense: CC BY-SA 2.5

Title: Centering my Logo Div


问:
An elegant way to find shortest and fastest route in Google Maps API v3?
I am making a taxi fare calculator. One of the business requirements is that, the company wants the shortest and fastest route options. I know Google directionService by default searched for the fastest route. I set the "avoidhighways" option in request parameter to true in order to get the shortest route, but I am not quite happy with the result.

Anyone have a better solution than that??

答:
I took code from Soldeplata Saketos answer and edited it since it wasn't working. Added params so you can just call it with it like.

```<code>shortestRoute(origin, destination, map);
</code>```

Works for me all though I'm not sure how correct it is.

Here:

```<code>function shortestRoute(origin, destination, map) {

  directionsService = new google.maps.DirectionsService();
  var routesResponses = [];
  //avoiding tolls
  directionsService.route({
    origin: origin,
    destination: destination,
    provideRouteAlternatives: true,
    avoidTolls: true,
    travelMode: google.maps.TravelMode.DRIVING
  }, function (response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
      routesResponses.push(response);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
  //avoiding highways
  directionsService.route({
    origin: origin,
    destination: destination,
    provideRouteAlternatives: true,
    avoidHighways: true,
    travelMode: google.maps.TravelMode.DRIVING
  }, function (response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
      routesResponses.push(response);
    } else {
      window.alert('Directions request failed due to ' + status);
    }

    //Results analysis and drawing of routes
    var fastest = Number.MAX_VALUE,
      shortest = Number.MAX_VALUE;

    routesResponses.forEach(function (res) {
      res.routes.forEach(function (rou, index) {
        console.log("distance of route " + index + ": ", rou.legs[0].distance.value);
        console.log("duration of route " + index + ": ", rou.legs[0].duration.value);
        if (rou.legs[0].distance.value < shortest) shortest = rou.legs[0].distance.value;
        if (rou.legs[0].duration.value < fastest) fastest = rou.legs[0].duration.value;

      })
    })
    console.log("shortest: ", shortest);
    console.log("fastest: ", fastest);
    //painting the routes in green blue and red
    routesResponses.forEach(function (res) {
      res.routes.forEach(function (rou, index) {
        new google.maps.DirectionsRenderer({
          map: map,
          directions: res,
          routeIndex: index,
          polylineOptions: {
            strokeColor: rou.legs[0].duration.value == fastest ? "red" : rou.legs[0].distance.value == shortest ? "darkgreen" : "blue",
            strokeOpacity: rou.legs[0].duration.value == fastest ? 0.8 : rou.legs[0].distance.value == shortest ? 0.9 : 0.5,
            strokeWeight: rou.legs[0].duration.value == fastest ? 9 : rou.legs[0].distance.value == shortest ? 8 : 3,
          }
        });
      });
    });
  });
}
</code>```

Body:
I took code from Soldeplata Saketos answer and edited it since it wasn't working. Added params so you can just call it with it like.

shortestRoute(origin, destination, map);

Works for me all though I'm not sure how correct it is.

Here:

function shortestRoute(origin, destination, map) {

  directionsService = new google.maps.DirectionsService();
  var routesResponses = [];
  //avoiding tolls
  directionsService.route({
    origin: origin,
    destination: destination,
    provideRouteAlternatives: true,
    avoidTolls: true,
    travelMode: google.maps.TravelMode.DRIVING
  }, function (response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
      routesResponses.push(response);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
  //avoiding highways
  directionsService.route({
    origin: origin,
    destination: destination,
    provideRouteAlternatives: true,
    avoidHighways: true,
    travelMode: google.maps.TravelMode.DRIVING
  }, function (response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
      routesResponses.push(response);
    } else {
      window.alert('Directions request failed due to ' + status);
    }

    //Results analysis and drawing of routes
    var fastest = Number.MAX_VALUE,
      shortest = Number.MAX_VALUE;

    routesResponses.forEach(function (res) {
      res.routes.forEach(function (rou, index) {
        console.log("distance of route " + index + ": ", rou.legs[0].distance.value);
        console.log("duration of route " + index + ": ", rou.legs[0].duration.value);
        if (rou.legs[0].distance.value < shortest) shortest = rou.legs[0].distance.value;
        if (rou.legs[0].duration.value < fastest) fastest = rou.legs[0].duration.value;

      })
    })
    console.log("shortest: ", shortest);
    console.log("fastest: ", fastest);
    //painting the routes in green blue and red
    routesResponses.forEach(function (res) {
      res.routes.forEach(function (rou, index) {
        new google.maps.DirectionsRenderer({
          map: map,
          directions: res,
          routeIndex: index,
          polylineOptions: {
            strokeColor: rou.legs[0].duration.value == fastest ? "red" : rou.legs[0].distance.value == shortest ? "darkgreen" : "blue",
            strokeOpacity: rou.legs[0].duration.value == fastest ? 0.8 : rou.legs[0].distance.value == shortest ? 0.9 : 0.5,
            strokeWeight: rou.legs[0].duration.value == fastest ? 9 : rou.legs[0].distance.value == shortest ? 8 : 3,
          }
        });
      });
    });
  });
}


问:
If else statement with string JavaScript
I am designing a page where can display score when the users make their choices.

However, this code seems not working and does not show any result in the 'score' field.
My Html code:

```<code><tr>
  <td>
    <div>
      <input list="typeList" name="type" id="type">
      <datalist id="typeList">
        <option value="basketball">
        <option value="soccer">
        <option value="table tenis">
      </datalist>
    </div>
  </td>

  <td><input type="text" id="score" name="score" autocomplete="off"></td>
</tr>
</code>```

My Script is below:

```<code>var type = document.getElementById("type");
var score = document.getElementById("score");

if (type === 0) {
  score.value = 0;
} else if (type === 'basketball') {
  score.value = 1;
} else if (type === 'soccer') {
  score.value = 2;
} else if (type === 'table tenis') {
  score.value = 3;
}
</code>```

答:
```<code>var type = document.getElementById("type");
//...
</code>```

here should be var type = document.getElementById("type").value;

and also

```<code>if (type === 0) {
</code>```

to

```<code>if (type === "0") {
</code>```

Body:
I am designing a page where can display score when the users make their choices.

However, this code seems not working and does not show any result in the 'score' field.
My Html code:

      <input list="typeList" name="type" id="type">
      <datalist id="typeList">
        <option value="basketball">
        <option value="soccer">
        <option value="table tenis">
      </datalist>

  <input type="text" id="score" name="score" autocomplete="off">

My Script is below:

var type = document.getElementById("type");
var score = document.getElementById("score");

if (type === 0) {
  score.value = 0;
} else if (type === 'basketball') {
  score.value = 1;
} else if (type === 'soccer') {
  score.value = 2;
} else if (type === 'table tenis') {
  score.value = 3;
}

Body:
var type = document.getElementById("type");
//...

here should be var type = document.getElementById("type").value;

and also

if (type === 0) {

to

if (type === "0") {


问:
C# : "Cannot explicitly call operator or accessor"
I know that questions with this error have been asked a lot, but I have tried everything they suggested and nothing worked.

First of all, I'm new to C#, that's why I can't find a solution for myself :(

My problem: I have this code (if I summarize it a lot)

```<code>public class ClassA {
  private static int numA;

  public static void MainProcess() {
    numA = ClassB.get_numB();
    ...
  }
}

public ClassB {
  private static int numB { get; set; }
  ...
}
</code>```

Now, it get the error 'numB.get' cannot explicitly call operator or accessor . I have seen that we should write numA = ClassB.numB instead, but this time I get the errors : The property or indexer 'ClassB.numB' cannot be used in this context because the get accessor is inaccessible and 'ClassB.numB' is inaccessible due to its protection level.

So, the only thing I have tried and that works is to change numB in public static int numB, but I don't really like it to not be a private variable... so, is there a solution?

Thank you !

答:
You either have it as a private or public variable. If you want to access it, make it public!

Actually, if you just want to make the getter public but the setter private, you can do this:

```<code>public static int numB { get; private set; }
</code>```

Or you can make it readonly:

```<code>public static readonly int numB;
</code>```

Then you can set the value of it in the constructor and its value can never change.

Body:
I know that questions with this error have been asked a lot, but I have tried everything they suggested and nothing worked.

First of all, I'm new to C#, that's why I can't find a solution for myself :(

My problem: I have this code (if I summarize it a lot)

public class ClassA {
  private static int numA;

  public static void MainProcess() {
    numA = ClassB.get_numB();
    ...
  }
}

public ClassB {
  private static int numB { get; set; }
  ...
}

Now, it get the error 'numB.get' cannot explicitly call operator or accessor . I have seen that we should write numA = ClassB.numB instead, but this time I get the errors : The property or indexer 'ClassB.numB' cannot be used in this context because the get accessor is inaccessible and 'ClassB.numB' is inaccessible due to its protection level.

So, the only thing I have tried and that works is to change numB in public static int numB, but I don't really like it to not be a private variable... so, is there a solution?

Thank you !

Body:
You either have it as a private or public variable. If you want to access it, make it public!

Actually, if you just want to make the getter public but the setter private, you can do this:

public static int numB { get; private set; }

Or you can make it readonly:

public static readonly int numB;

Then you can set the value of it in the constructor and its value can never change.


问:
Manually supplying arguments to a MongoDB query to support collation feature (for case insensitive index)
I have installed the current development version 3.3.11 in order to test the case insensitive index that is apparently supported according to https://jira.mongodb.org/browse/SERVER-90. I have tried this from a mongo shell and a simple test database and it does seem to work.

Unfortunately, even though one specifies collation (and strength) during index creation, one must also specify the same collation params with .find in order to get case insensitive matches. If collation is omitted from the query, index behaves in a case sensitive fashion.

Even the newest C# MongoDB driver (2.3.0-beta1) does not seem to support supplying collation params to a query. So even though I have upgraded the engine and database, C# driver, created the index with required collation, I cannot seem to get the results using the current driver.

Is there a "manual" way of supplying extra arguments to a query?

答:
This is now possible in the newer version of the C# mongo driver (since 2.4.0).

For example, to query against a case-insensitive index:

```<code>IMongoCollection<SomeObject> someCollection;
var results = someCollection.Find<SomeObject>(x => x.name == someName,
  new FindOptions() {  Collation = new Collation("en", strength: CollationStrength.Secondary) } )
</code>```

Notice that to enjoy the power of the index, you need to specify in the query the exact same collation parameter as specified when creating the index.

Body:
This is now possible in the newer version of the C# mongo driver (since 2.4.0).

For example, to query against a case-insensitive index:

IMongoCollection<SomeObject> someCollection;
var results = someCollection.Find<SomeObject>(x => x.name == someName,
  new FindOptions() {  Collation = new Collation("en", strength: CollationStrength.Secondary) } )

Notice that to enjoy the power of the index, you need to specify in the query the exact same collation parameter as specified when creating the index.


问:
splitting length (metre) data by interval with Pandas
I have a dataframe of length-interval data (from boreholes) which looks something like this:

```<code>df
Out[46]:
   from  to  min intensity
0     0  10   py        2
1     5  15  cpy       3.5
2    14  27  spy       0.7
</code>```

I need to pivot this data, but also break it on the least common length interval; resulting in the 'min' column as column headers, and the values being the 'rank'. The output would look like this:

```<code>df.somefunc(index=['from','to'], columns='min', values='intensity', fill_value=0)
Out[47]:
   from  to  py  cpy  spy
0     0  5   2   0    0
1     5  10  2   3.5  0
2    10  14  0   3.5  0
3    14  15  0   3.5  0.7
4    15  27  0   0    0.7
</code>```

so basically the "From" and "To" describe non-overlapping intervals down a borehole, where the intervals have been split by the least common denominator - as you can see the "py" interval from the original table has been split, the first (0-5m) into py:2, cpy:0 and the second (5-10m) into py:2, cpy:3.5.

The result from just a basic pivot_table function is this:

```<code>pd.pivot_table(df, values='intensity', index=['from', 'to'], columns="min", aggfunc="first", fill_value=0)
Out[48]:
min      cpy  py  spy
from to
0    10    0   2    0
5    15  3.5   0    0
14   27    0   0    0.75
</code>```

which just treats the from and to columns combined as an index. An important point is that my output cannot have overlapping from and to values (IE the subsequent 'from' value cannot be less than the previous 'to' value).

Is there an elegant way to accomplish this using Pandas? Thanks for the help!

答:
I don't know natural interval arithmetic in Pandas, so you need do do it.
Here a way to do that, If  I correctly understand bound conditions.
This can be a O(n^3) problem, it will create huge table for big entries.

```<code># make the new bounds
bounds=np.unique(np.hstack((df["from"],df["to"])))
df2=pd.DataFrame({"from":bounds[:-1],"to":bounds[1:]})

#find inclusions
isin=df.apply(lambda x :
df2['from'].between(x[0],x[1]-1)
| df2['to'].between(x[0]+1,x[1])
,axis=1).T

#data
data=np.where(isin,df.intensity,0)

#result
df3=pd.DataFrame(data,
pd.MultiIndex.from_arrays(df2.values.T),df["min"])
</code>```

For :

```<code>In [26]: df3
Out[26]:
min     py  cpy  spy
0  5   2.0  0.0  0.0
5  10  2.0  3.5  0.0
10 14  0.0  3.5  0.0
14 15  0.0  3.5  0.7
15 27  0.0  0.0  0.7
</code>```

Body:
I have a dataframe of length-interval data (from boreholes) which looks something like this:

df
Out[46]:
   from  to  min intensity
0     0  10   py        2
1     5  15  cpy       3.5
2    14  27  spy       0.7

I need to pivot this data, but also break it on the least common length interval; resulting in the 'min' column as column headers, and the values being the 'rank'. The output would look like this:

df.somefunc(index=['from','to'], columns='min', values='intensity', fill_value=0)
Out[47]:
   from  to  py  cpy  spy
0     0  5   2   0    0
1     5  10  2   3.5  0
2    10  14  0   3.5  0
3    14  15  0   3.5  0.7
4    15  27  0   0    0.7

so basically the "From" and "To" describe non-overlapping intervals down a borehole, where the intervals have been split by the least common denominator - as you can see the "py" interval from the original table has been split, the first (0-5m) into py:2, cpy:0 and the second (5-10m) into py:2, cpy:3.5.

The result from just a basic pivot_table function is this:

pd.pivot_table(df, values='intensity', index=['from', 'to'], columns="min", aggfunc="first", fill_value=0)
Out[48]:
min      cpy  py  spy
from to
0    10    0   2    0
5    15  3.5   0    0
14   27    0   0    0.75

which just treats the from and to columns combined as an index. An important point is that my output cannot have overlapping from and to values (IE the subsequent 'from' value cannot be less than the previous 'to' value).

Is there an elegant way to accomplish this using Pandas? Thanks for the help!

Body:
I don't know natural interval arithmetic in Pandas, so you need do do it.
Here a way to do that, If  I correctly understand bound conditions.
This can be a O(n^3) problem, it will create huge table for big entries.

# make the new bounds
bounds=np.unique(np.hstack((df["from"],df["to"])))
df2=pd.DataFrame({"from":bounds[:-1],"to":bounds[1:]})

#find inclusions
isin=df.apply(lambda x :
df2['from'].between(x[0],x[1]-1)
| df2['to'].between(x[0]+1,x[1])
,axis=1).T

#data
data=np.where(isin,df.intensity,0)

#result
df3=pd.DataFrame(data,
pd.MultiIndex.from_arrays(df2.values.T),df["min"])

For :

In [26]: df3
Out[26]:
min     py  cpy  spy
0  5   2.0  0.0  0.0
5  10  2.0  3.5  0.0
10 14  0.0  3.5  0.0
14 15  0.0  3.5  0.7
15 27  0.0  0.0  0.7


问:
C: Add auto prefix to hex calculation
This is my C program

```<code>#include <stdio.h>
void main() {
    printf("Diff = %x\n",0xffffffff-0xfffffffa);
}
</code>```

And the standard output would be like this

```<code>C:\Codes>prog.exe
Diff = 5
</code>```

What I'm trying to achieve is to add auto prefix 0x00000005 automatically to the answer so the output would be like this.

```<code>C:\Codes>prog.exe
Diff = 0x00000005
</code>```

or

```<code>C:\Codes>prog.exe
Diff = 0x00000A35
</code>```

I know we can do this manually with this code

```<code>#include <stdio.h>
void main() {
    printf("Diff = 0x0000000%x\n",0xffffffff-0xfffffffa);
}
</code>```

But, is it possible to accomplish this without manually write 0x0000000%x in printf?

答:
Hexadecimal prefix

There are multiple ways to add the hexadecimal prefix to the output:

```<code>#include <stdio.h>

int main(void)
{
    printf("Diff = %#x\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = %#X\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = 0x%X\n", 0xFFFFFFFF - 0xFF012345);

    printf("Diff = %#.8x\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = %#.8X\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = 0x%.8X\n", 0xFFFFFFFF - 0xFF012345);
    return 0;
}
</code>```

The output is:

```<code>Diff = 0xfedcba
Diff = 0XFEDCBA
Diff = 0xFEDCBA
Diff = 0x00fedcba
Diff = 0X00FEDCBA
Diff = 0x00FEDCBA
</code>```

You can choose the 0x lower-case prefix with the lower-case hex digits, or the upper-case prefix with the upper-case digits.  Personally, I like the lower-case prefix and the upper-case digits, so I always use the third option.

The # flag for printf() chooses an alternative representation:

# —  Specifies that the value is to be converted to an alternative form. For o conversion, it shall increase the precision, if and only if necessary, to force the first digit of the result to be a zero (if the value and precision are both 0, a single 0 is printed). For x or X conversion specifiers, a non-zero result shall have 0x (or 0X) prefixed to it. For a, A, e, E, f, F, g, and G conversion specifiers, the result shall always contain a radix character, even if no digits follow the radix character. Without this flag, a radix character appears in the result of these conversions only if a digit follows it. For g and G conversion specifiers, trailing zeros shall not be removed from the result as they normally are. For other conversion specifiers, the behavior is undefined.

Leading zeros

You can specify the number of digits in various ways, not always with the desired result when using the manual prefix.  Note that the prefix is counted in the minimum field width when the # flag is used.

```<code>#include <stdio.h>

int main(void)
{
    printf("Diff = %#x\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = %#X\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = 0x%X\n", 0xFFFFFFFF - 0xFF012345);

    printf("Diff = %#.8x\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = %#.8X\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = 0x%.8X\n", 0xFFFFFFFF - 0xFF012345);

    printf("Diff = %#10x\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = %#10X\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = 0x%10X\n", 0xFFFFFFFF - 0xFF012345);

    printf("Diff = %#10.10x\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = %#10.10X\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = 0x%10.10X\n", 0xFFFFFFFF - 0xFF012345);
    return 0;
}
</code>```

Output:

```<code>Diff = 0xfedcba
Diff = 0XFEDCBA
Diff = 0xFEDCBA
Diff = 0x00fedcba
Diff = 0X00FEDCBA
Diff = 0x00FEDCBA
Diff =   0xfedcba
Diff =   0XFEDCBA
Diff = 0x    FEDCBA
Diff = 0x0000fedcba
Diff = 0X0000FEDCBA
Diff = 0x0000FEDCBA
</code>```

On 32-bit systems, I normally use 0x%8.8X; on 64-bit systems, I use one of 0x%12.12X or 0x%16.16X.  The latter often leaves the addresses I'm printing with more leading zeros than I want.

You can left-justify if you need to, and so on and so forth.  See the specification of printf() already linked, which is formally for POSIX but the POSIX extensions are clearly marked.

And for printing addresses, I use uintptr_t and PRIXPTR from <inttypes.h>, leading to a format string along the lines of:

```<code>printf("0x%8.8" PRIXPTR "\n", (uintptr_t)&x);
</code>```

As you can see, there are many variations that can be used — you need to choose what works best for you.

Title: C: Add auto prefix to hex calculation

Body:
This is my C program

#include <stdio.h>
void main() {
    printf("Diff = %x\n",0xffffffff-0xfffffffa);
}

And the standard output would be like this

C:\Codes>prog.exe
Diff = 5

What I'm trying to achieve is to add auto prefix 0x00000005 automatically to the answer so the output would be like this.

C:\Codes>prog.exe
Diff = 0x00000005

or

C:\Codes>prog.exe
Diff = 0x00000A35

I know we can do this manually with this code

#include <stdio.h>
void main() {
    printf("Diff = 0x0000000%x\n",0xffffffff-0xfffffffa);
}

But, is it possible to accomplish this without manually write 0x0000000%x in printf?

Body:
Hexadecimal prefix

There are multiple ways to add the hexadecimal prefix to the output:

#include <stdio.h>

int main(void)
{
    printf("Diff = %#x\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = %#X\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = 0x%X\n", 0xFFFFFFFF - 0xFF012345);

    printf("Diff = %#.8x\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = %#.8X\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = 0x%.8X\n", 0xFFFFFFFF - 0xFF012345);
    return 0;
}

The output is:

Diff = 0xfedcba
Diff = 0XFEDCBA
Diff = 0xFEDCBA
Diff = 0x00fedcba
Diff = 0X00FEDCBA
Diff = 0x00FEDCBA

You can choose the 0x lower-case prefix with the lower-case hex digits, or the upper-case prefix with the upper-case digits.  Personally, I like the lower-case prefix and the upper-case digits, so I always use the third option.

The # flag for printf() chooses an alternative representation:

# —  Specifies that the value is to be converted to an alternative form. For o conversion, it shall increase the precision, if and only if necessary, to force the first digit of the result to be a zero (if the value and precision are both 0, a single 0 is printed). For x or X conversion specifiers, a non-zero result shall have 0x (or 0X) prefixed to it. For a, A, e, E, f, F, g, and G conversion specifiers, the result shall always contain a radix character, even if no digits follow the radix character. Without this flag, a radix character appears in the result of these conversions only if a digit follows it. For g and G conversion specifiers, trailing zeros shall not be removed from the result as they normally are. For other conversion specifiers, the behavior is undefined.

Leading zeros

You can specify the number of digits in various ways, not always with the desired result when using the manual prefix.  Note that the prefix is counted in the minimum field width when the # flag is used.

#include <stdio.h>

int main(void)
{
    printf("Diff = %#x\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = %#X\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = 0x%X\n", 0xFFFFFFFF - 0xFF012345);

    printf("Diff = %#.8x\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = %#.8X\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = 0x%.8X\n", 0xFFFFFFFF - 0xFF012345);

    printf("Diff = %#10x\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = %#10X\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = 0x%10X\n", 0xFFFFFFFF - 0xFF012345);

    printf("Diff = %#10.10x\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = %#10.10X\n",  0xFFFFFFFF - 0xFF012345);
    printf("Diff = 0x%10.10X\n", 0xFFFFFFFF - 0xFF012345);
    return 0;
}

Output:

Diff = 0xfedcba
Diff = 0XFEDCBA
Diff = 0xFEDCBA
Diff = 0x00fedcba
Diff = 0X00FEDCBA
Diff = 0x00FEDCBA
Diff =   0xfedcba
Diff =   0XFEDCBA
Diff = 0x    FEDCBA
Diff = 0x0000fedcba
Diff = 0X0000FEDCBA
Diff = 0x0000FEDCBA

On 32-bit systems, I normally use 0x%8.8X; on 64-bit systems, I use one of 0x%12.12X or 0x%16.16X.  The latter often leaves the addresses I'm printing with more leading zeros than I want.

You can left-justify if you need to, and so on and so forth.  See the specification of printf() already linked, which is formally for POSIX but the POSIX extensions are clearly marked.

And for printing addresses, I use uintptr_t and PRIXPTR from <inttypes.h>, leading to a format string along the lines of:

printf("0x%8.8" PRIXPTR "\n", (uintptr_t)&x);

As you can see, there are many variations that can be used — you need to choose what works best for you.


问:
ASP MVC3 with razor running on Azure
I would like to create a simple ASP MVC3 web applications for learning and have this hosted. I am familiar with ASP MVC but don't yet know much about the Azure cloud. If possible I would like to have these hosted on the cloud but I'm not sure where to start.

Can anyone give me any advice. For example for something very very low usage and making use of a SQL CE database what kind of azure account do I need and approximately how much would it cost.

Thanks in advance for your help.

答:
You need at least two instances if you want to have an SLA.

Depending on the load you expect I would assume that a Small instance variant would be enough for you.

making use of a SQL CE database

That would rather become either SQL Azure or table storage instead. SQL Azure costs quite some more money than table/blob storage so try to get more information about what you want to use if costs matter to you.

To calculate the costs I suggest you check out this great tool: http://azureroi.cloudapp.net/.

Title: ASP MVC3 with razor running on Azure


问:
Python - how can i catch error of chown. chown: invalid user
If there is an error, I want to show this error to the messagebox and stop the if statement.

how can I catch the error guys?

答:
Depends on how your calling it. If your using the subprocess module :

```<code>p = subprocess.Popen(['chown', 'bad_user', '/file_path'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
print(err)
</code>```

should give you:

chown: bad_user: illegal user name

Now this is in Python 2.7. Python 3 has an easier way of calling it. Should be: (Not tested)

```<code>result = subprocess.run(['chown', 'bad_user', '/file_path'], stdout=subprocess.PIPE)
result.stdout
</code>```

Body:
Depends on how your calling it. If your using the subprocess module :

p = subprocess.Popen(['chown', 'bad_user', '/file_path'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
print(err)

should give you:

chown: bad_user: illegal user name

Now this is in Python 2.7. Python 3 has an easier way of calling it. Should be: (Not tested)

result = subprocess.run(['chown', 'bad_user', '/file_path'], stdout=subprocess.PIPE)
result.stdout


问:
Mapped Event throws
I have mapped all classes from an assembly.  When starting up Rebus mentions as it should:

```<code>Mapped MyNamespace.Events.EmailSend -> Rebus/Test/Input
</code>```

But I get an error when I try to submit a message inside a handler, using the code below:

```<code>await _bus.Send(new EmailSend
{
    MyProperty = 1
}).ConfigureAwait(false);
</code>```

I tried also with .Reply() and .SendLocal(), but that does not help me getting rid of the error below.

The stack trace:

```<code>Rebus.Retry.ErrorTracking.InMemErrorTracker WARN (Thread #10): Unhandled exception 1 while handling message with ID a2c3b234-f519-4d86-bec9-715b2045ef94: Rebus.Exceptions.RebusApplicationException: Message with ID a2c3b234-f519-4d86-bec9-715b2045ef94 and type MyNamespace.Events.EmailSend, MyAssembly.Messaging.Models could not be dispatched to any handlers
at Rebus.Pipeline.Receive.DispatchIncomingMessageStep.<Process>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Rebus.Sagas.LoadSagaDataStep.<Process>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Rebus.Pipeline.Receive.ActivateHandlersStep.<Process>d__3.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Rebus.Pipeline.Receive.DeserializeIncomingMessageStep.<Process>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Rebus.Retry.Simple.SimpleRetryStrategyStep.<DispatchWithTrackerIdentifier>d__7.MoveNext()
</code>```

答:
The first line really says it all:

```<code>Rebus.Retry.ErrorTracking.InMemErrorTracker WARN (Thread #10): Unhandled exception 1 while handling message with ID a2c3b234-f519-4d86-bec9-715b2045ef94: Rebus.Exceptions.RebusApplicationException: Message with ID a2c3b234-f519-4d86-bec9-715b2045ef94 and type MyNamespace.Events.EmailSend, MyAssembly.Messaging.Models could not be dispatched to any handlers
</code>```

Pay attention to the last part:

```<code>Message with ID a2c3b234-f519-4d86-bec9-715b2045ef94 and type MyNamespace.Events.EmailSend, MyAssembly.Messaging.Models could not be dispatched to any handlers
</code>```

It means that Rebus could not find a handler for the message, i.e. an implementation of IHandleMessages<EmailSend>.

If you are using an IoC container, this can be a sign that, while you might have registered the handler type correctly, one of its dependencies could not be resolved.

If you did not register the handler: I guess it's pretty obvious then :)

Title: Mapped Event throws

Body:
I have mapped all classes from an assembly.  When starting up Rebus mentions as it should:

Mapped MyNamespace.Events.EmailSend -> Rebus/Test/Input

But I get an error when I try to submit a message inside a handler, using the code below:

await _bus.Send(new EmailSend
{
    MyProperty = 1
}).ConfigureAwait(false);

I tried also with .Reply() and .SendLocal(), but that does not help me getting rid of the error below.

The stack trace:

Rebus.Retry.ErrorTracking.InMemErrorTracker WARN (Thread #10): Unhandled exception 1 while handling message with ID a2c3b234-f519-4d86-bec9-715b2045ef94: Rebus.Exceptions.RebusApplicationException: Message with ID a2c3b234-f519-4d86-bec9-715b2045ef94 and type MyNamespace.Events.EmailSend, MyAssembly.Messaging.Models could not be dispatched to any handlers
at Rebus.Pipeline.Receive.DispatchIncomingMessageStep.<Process>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Rebus.Sagas.LoadSagaDataStep.<Process>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Rebus.Pipeline.Receive.ActivateHandlersStep.<Process>d__3.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Rebus.Pipeline.Receive.DeserializeIncomingMessageStep.<Process>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Rebus.Retry.Simple.SimpleRetryStrategyStep.<DispatchWithTrackerIdentifier>d__7.MoveNext()

Body:
The first line really says it all:

Rebus.Retry.ErrorTracking.InMemErrorTracker WARN (Thread #10): Unhandled exception 1 while handling message with ID a2c3b234-f519-4d86-bec9-715b2045ef94: Rebus.Exceptions.RebusApplicationException: Message with ID a2c3b234-f519-4d86-bec9-715b2045ef94 and type MyNamespace.Events.EmailSend, MyAssembly.Messaging.Models could not be dispatched to any handlers

Pay attention to the last part:

Message with ID a2c3b234-f519-4d86-bec9-715b2045ef94 and type MyNamespace.Events.EmailSend, MyAssembly.Messaging.Models could not be dispatched to any handlers

It means that Rebus could not find a handler for the message, i.e. an implementation of IHandleMessages<EmailSend>.

If you are using an IoC container, this can be a sign that, while you might have registered the handler type correctly, one of its dependencies could not be resolved.

If you did not register the handler: I guess it's pretty obvious then :)


答:
I have used Jquery in this, The mistake you made is, there is no watch for the event.

$('#type').on('input',function(e){
     var type = document.getElementById("type").value;
var score = document.getElementById("score");
if (type === 0) { score.value = 0; }
else if (type === 'basketball') { score.value = 1; }
else if (type === 'soccer') { score.value = 2; }
else if (type === 'table tenis') { score.value = 3; }
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
  <td>
    <div>
      <input list="typeList" name="type" id="type">
      <datalist id="typeList">
        <option value="basketball">
        <option value="soccer">
        <option value="table tenis">
      </datalist>
    </div>
  </td>

  <td><input type="text" id="score" name="score" autocomplete="off"></td>
</tr></code>```

Hope this helps

Title: If else statement with string JavaScript

Body:
I have used Jquery in this, The mistake you made is, there is no watch for the event.

$('#type').on('input',function(e){
     var type = document.getElementById("type").value;
var score = document.getElementById("score");
if (type === 0) { score.value = 0; }
else if (type === 'basketball') { score.value = 1; }
else if (type === 'soccer') { score.value = 2; }
else if (type === 'table tenis') { score.value = 3; }
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
  <td>
    <div>
      <input list="typeList" name="type" id="type">
      <datalist id="typeList">
        <option value="basketball">
        <option value="soccer">
        <option value="table tenis">
      </datalist>
    </div>
  </td>

  <td><input type="text" id="score" name="score" autocomplete="off"></td>
</tr>

Hope this helps


答:
```<code>substring(int beginIndex, int endIndex)
</code>```

In your code, endIndex is lesser than beginIndex. Check this

```<code>beginIndex - the beginning index, inclusive.
endIndex - the ending index, exclusive.

IndexOutOfBoundsException - if the beginIndex is negative, or
endIndex is larger than the length of this String object, or
beginIndex is larger than endIndex.
</code>```

Body:
I have this simple Java code which gives the following error:
java.lang.StringIndexOutOfBoundsException: String index out of range: -4

the code is:

String date = "14000101";
String repayDate = date.substring(0, 4)+"-"+date.substring(5, 2)+"-"+date.substring(6, 2);

the length of the string is 8 and yet it gives an error starting form the second part.

Any ideas?

Thanks!

Body:
substring(int beginIndex, int endIndex)

In your code, endIndex is lesser than beginIndex. Check this

beginIndex - the beginning index, inclusive.
endIndex - the ending index, exclusive.

IndexOutOfBoundsException - if the beginIndex is negative, or
endIndex is larger than the length of this String object, or
beginIndex is larger than endIndex.


问:
Date comparisson issue MS ACCESS 2007
I have been reading and learning a lot on this site, and now its my time to set a question, which is giving me some problems.

I have a query on MS ACCESS on which i need to compare two different dates, call them CreationDate and AnalysisDate. I compare them in order to get results for two different criterias:

Crit1:

```<code>SiInm(CreationDate < AnalysisDate;1)
</code>```

Crit2:

```<code>SiInm(CreationDate >= AnalysisDate;1)
</code>```

I have had no problems comparing dates within June, but when i try to compare dates from June as > or < with July, and it returns a wrong result.

Does anybody knows why this happen?

I checked on my tables and the date format is well setted on every source table i use on my queries.

Thanks in advance to everyone.

Regards

PS: SiInm works as IF (function in Spanish)

答:
PS: SiInm works as IF (function in Spanish)

It most likely doesn't. If it can't compare date values, it's because it converts internally to string expressions which can't be compared reliably.

You don't tell what SiInm does. Perhaps it strips a time part.

So, either correct SiInm or use:

```<code>CreationDate < AnalysisDate
</code>```

or:

```<code>DateValue(CreationDate) < DateValue(AnalysisDate)
</code>```

or use DateDiff which is here exactly for comparing date values:

```<code>DateDiff("d"; CreationDate; AnalysisDate) > 0
</code>```

Title: Date comparisson issue MS ACCESS 2007

Body:
I have been reading and learning a lot on this site, and now its my time to set a question, which is giving me some problems.

I have a query on MS ACCESS on which i need to compare two different dates, call them CreationDate and AnalysisDate. I compare them in order to get results for two different criterias:

Crit1:

SiInm(CreationDate < AnalysisDate;1)

Crit2:

SiInm(CreationDate >= AnalysisDate;1)

I have had no problems comparing dates within June, but when i try to compare dates from June as > or < with July, and it returns a wrong result.

Does anybody knows why this happen?

I checked on my tables and the date format is well setted on every source table i use on my queries.

Thanks in advance to everyone.

Regards

PS: SiInm works as IF (function in Spanish)

Body:
PS: SiInm works as IF (function in Spanish)

It most likely doesn't. If it can't compare date values, it's because it converts internally to string expressions which can't be compared reliably.

You don't tell what SiInm does. Perhaps it strips a time part.

So, either correct SiInm or use:

CreationDate < AnalysisDate

or:

DateValue(CreationDate) < DateValue(AnalysisDate)

or use DateDiff which is here exactly for comparing date values:

DateDiff("d"; CreationDate; AnalysisDate) > 0


问:
How to dynamically specify version for dubbo @Service
```<code>  @Service(version = "${spring.dubbo.application.version}")
</code>```

I want to let the version here read from the profile, how to do it, thank you, I need help

答: I think you are asking a spring related question, so please check how to use @Value annotation of Spring from this post, or you can leverage Environment class to read property from configuration file like environment.getProperty("spring.dubbo.application.version").

Body:
  @Service(version = "${spring.dubbo.application.version}")

I want to let the version here read from the profile, how to do it, thank you, I need help


问:
ASP.NET MVC: how to prevent unauthenticated user to directly GET images?
I have confidential images that I only want to show to authenticated users. On the  razor view, which is only accessible to authenticated users, I have

How do I prevent an unauthenticated user to bypass my razor view and directly request this photo through a HTTP GET?

答:
You can use Attributes concept in mvc to accomplish your task.  Use ActionFilterAttribute and override OnActionExecuting method. For implementation you can visit following links.

Asp.net mvc restrict specific users to access folder content

ASP.NET MVC 4 intercept all incoming requests

Thanks


问:
MinGW compiler suite
I am installing the MinGW compiler suite in the directory C:\MinGW and also set PATH environment. I don't know about uses in any project, and I want to compile my program with the GCC compiler, but I don't know the steps. How do I compile my program with GCC?

答:
Just use this:

mingw-downloader

Title: MinGW compiler suite

Body:
Just use this:

mingw-downloader