问:
android app crashing when calling a timer
The timer check every minute if there is a change of hour if it is then a button need to become green and clickable otherwise it stays red and un-clickable.

So far I am getting this error and I don't know how to handle this:-

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

```<code>Timer timer = new Timer();

timer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        CHECK();
    }
}, 1*60*1000, 1*60*1000);

public void CHECK(){

    sqliteDbHelper_ = new Sqlite_DBHelper(getActivity());
    sqLiteDatabase = sqliteDbHelper_.getWritableDatabase();
    String[] columns = {"hour_only","JAKOST"};
    cursor = sqLiteDatabase.query("podatki", columns,null,null,null,null,null);
    Calendar calander = Calendar.getInstance();
    Integer currentHour = calander.get(Calendar.HOUR_OF_DAY);
    buttonSaveOnMainPage.setClickable(true);
    cursor.moveToLast();
    if (cursor.moveToLast()== false){
         lastInputedHour = 0;
    }
    else{
     lastInputedHour = cursor.getInt(0);
    }
    Log.e(TAG+"zadnja vnesena URA",""+lastInputedHour);
    Log.e(TAG+"trenutna URA",""+currentHour);
    if (lastInputedHour == currentHour){
        buttonSaveOnMainPage.setBackgroundResource(R.color.ColorRed);
        buttonSaveOnMainPage.setClickable(false);
    }
    else
        buttonSaveOnMainPage.setBackgroundResource(R.color.ColorGreenDark);
        buttonSaveOnMainPage.setClickable(true);
}
</code>```

答:
The error is quite self explanatory. Implement the timer inside the OnClickListener() of the UI element. Here's an example:-

```<code>  Button1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //Some business logic
            Update_ui();
            if (!Player.isTuningnow) {
                Button1.setImageResource(R.drawable.btn_pause_pressed);
                Player.Paused = false;
                new CountDownTimer(600, 1) {

                    public void onTick(long millisUntilFinished) {

                    }

                    public void onFinish() {
                        Button1.setImageResource(R.drawable.music_btn_play);
                        //Some more business logic
                    }
                }.start();
</code>```

Body:
The timer check every minute if there is a change of hour if it is then a button need to become green and clickable otherwise it stays red and un-clickable.

So far I am getting this error and I don't know how to handle this:-

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

Timer timer = new Timer();

timer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        CHECK();
    }
}, 1*60*1000, 1*60*1000);

public void CHECK(){

    sqliteDbHelper_ = new Sqlite_DBHelper(getActivity());
    sqLiteDatabase = sqliteDbHelper_.getWritableDatabase();
    String[] columns = {"hour_only","JAKOST"};
    cursor = sqLiteDatabase.query("podatki", columns,null,null,null,null,null);
    Calendar calander = Calendar.getInstance();
    Integer currentHour = calander.get(Calendar.HOUR_OF_DAY);
    buttonSaveOnMainPage.setClickable(true);
    cursor.moveToLast();
    if (cursor.moveToLast()== false){
         lastInputedHour = 0;
    }
    else{
     lastInputedHour = cursor.getInt(0);
    }
    Log.e(TAG+"zadnja vnesena URA",""+lastInputedHour);
    Log.e(TAG+"trenutna URA",""+currentHour);
    if (lastInputedHour == currentHour){
        buttonSaveOnMainPage.setBackgroundResource(R.color.ColorRed);
        buttonSaveOnMainPage.setClickable(false);
    }
    else
        buttonSaveOnMainPage.setBackgroundResource(R.color.ColorGreenDark);
        buttonSaveOnMainPage.setClickable(true);
}

Body:
The error is quite self explanatory. Implement the timer inside the OnClickListener() of the UI element. Here's an example:-

  Button1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //Some business logic
            Update_ui();
            if (!Player.isTuningnow) {
                Button1.setImageResource(R.drawable.btn_pause_pressed);
                Player.Paused = false;
                new CountDownTimer(600, 1) {

                    public void onTick(long millisUntilFinished) {

                    }

                    public void onFinish() {
                        Button1.setImageResource(R.drawable.music_btn_play);
                        //Some more business logic
                    }
                }.start();


来源: stackexchange

问:
How to make same height of all responsive images in a row
The first image of the row doesn't have the same height as the other ones. I am using Bootstrap .img-responsive.

HTML

```<code><div class="row">
    <div class="down-content">
        <div class="haber">
            <!--HABER 1-->
            <div class="col-sm-3">
                <div id="haber1">
                    <div id="haberimg1">
                        <img class="img-responsive" src="http://www.avukatwebsite.net/public/_uploads/photos/temalar/avukat-web-site-tema-1.jpg" >
                    </div>
                    <div id="haberyazi1">
                        <h3>Kanser Affetmedi...</h3>
                        <p>Sanssiz genc Kanser yüzünden öldü...</p>
                        <button type="button" class="btn">Devamini Oku...</button>
                    </div>
                </div>
            </div>
            <!--HABER 2-->
            <div class="col-sm-3">
                <div id="haber2">
                    <div id="haberimg2">
                        <img class="img-responsive" src="http://medicare.bold-themes.com/clinic/wp-content/uploads/sites/2/2015/12/shutterstock_288977717-1200x800.jpg" >
                    </div>
                    <div id="haberyazi2">
                        <h3>Sizofreni Salgini</h3>
                        <p>Türkiyede ki Sizofren sayisinda artis görüldü...</p>
                        <button type="button" class="btn">Devamini Oku...</button>
                    </div>
                </div>
            </div>
            /* we deleted the other parts because of mostly code problem */
        </div>
        <!--HABER BÖLÜMÜ BITIS-->
    </div>
</div>
</code>```

Bootstrap CSS

```<code>.img-responsive,
.thumbnail > img,
.thumbnail a > img,
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
    display: block;
    max-width: 100%;
    height: auto;
}
</code>```

This is the issue:

答:
A simple way is to use images that have the same width and the same height! (You avoid a lot of problems and there is no need to fix something with CSS)

HTML

```<code><div class="row">
    <div class="col-sm-3">
        <img src="http://placehold.it/400x300" alt="" class="img-responsive">
        <h3>Heading</h3>
        <p>Text</p>
        <button class="btn">More</button>
    </div>
    <div class="col-sm-3">
        <img src="http://placehold.it/400x300" alt="" class="img-responsive">
        <h3>Heading</h3>
        <p>Text</p>
        <button class="btn">More</button>
    </div>
    <div class="col-sm-3">
        <img src="http://placehold.it/400x300" alt="" class="img-responsive">
        <h3>Heading</h3>
        <p>Text</p>
        <button class="btn">More</button>
    </div>
    <div class="col-sm-3">
        <img src="http://placehold.it/400x300" alt="" class="img-responsive">
        <h3>Heading</h3>
        <p>Text</p>
        <button class="btn">More</button>
    </div>
</div>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The first image of the row doesn't have the same height as the other ones. I am using Bootstrap .img-responsive.

HTML

Kanser Affetmedi...

Sanssiz genc Kanser yüzünden öldü...

                        <button type="button" class="btn">Devamini Oku...</button>

Sizofreni Salgini

Türkiyede ki Sizofren sayisinda artis görüldü...

                        <button type="button" class="btn">Devamini Oku...</button>

            /* we deleted the other parts because of mostly code problem */

Bootstrap CSS

.img-responsive,
.thumbnail > img,
.thumbnail a > img,
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
    display: block;
    max-width: 100%;
    height: auto;
}

This is the issue:

Body:
A simple way is to use images that have the same width and the same height! (You avoid a lot of problems and there is no need to fix something with CSS)

HTML

<div class="row">
    <div class="col-sm-3">
        <img src="http://placehold.it/400x300" alt="" class="img-responsive">
        <h3>Heading</h3>
        <p>Text</p>
        <button class="btn">More</button>
    </div>
    <div class="col-sm-3">
        <img src="http://placehold.it/400x300" alt="" class="img-responsive">
        <h3>Heading</h3>
        <p>Text</p>
        <button class="btn">More</button>
    </div>
    <div class="col-sm-3">
        <img src="http://placehold.it/400x300" alt="" class="img-responsive">
        <h3>Heading</h3>
        <p>Text</p>
        <button class="btn">More</button>
    </div>
    <div class="col-sm-3">
        <img src="http://placehold.it/400x300" alt="" class="img-responsive">
        <h3>Heading</h3>
        <p>Text</p>
        <button class="btn">More</button>
    </div>
</div>


问:
React Native fixed footer
I'm trying to create a react native app that looks like an existing web app. I have a fixed footer at bottom of the window. Does anyone have an idea how this can be achieved with react native?

In the existing app it's simple:

.footer {
  position: fixed;
  bottom: 0;
}
```

答:
The way I did this was to have a view (lets call it P) with flex 1, then inside that view have 2 more views (C1 and C2) with flex 0.9 and 0.1 respectively (you can change the flex heights to required values). Then, inside the C1 have a scrollview. This worked perfectly for me. Example below.</p>

```<code><View style={{flex: 1}}>
    <View style={{flex: 0.9}}>
        <ScrollView>
            <Text style={{marginBottom: 500}}>scrollable section</Text>
        </ScrollView>
    </View>
    <View style={{flex: 0.1}}>
        <Text>fixed footer</Text>
    </View>
</View>
</code>```

ContentLicense: CC BY-SA 4.0

Title: React Native fixed footer

Body:
The way I did this was to have a view (lets call it P) with flex 1, then inside that view have 2 more views (C1 and C2) with flex 0.9 and 0.1 respectively (you can change the flex heights to required values). Then, inside the C1 have a scrollview. This worked perfectly for me. Example below.

<View style={{flex: 1}}>
    <View style={{flex: 0.9}}>
        <ScrollView>
            <Text style={{marginBottom: 500}}>scrollable section</Text>
        </ScrollView>
    </View>
    <View style={{flex: 0.1}}>
        <Text>fixed footer</Text>
    </View>
</View>


问:
Button not visible inside Linear Layout
I have this vehicle_list_fragment_layout.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<!-- Layout per il fragment VehicleListFragment. -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include layout="@layout/recycler_view_fragment_layout"/>

    <Button
        android:id="@+id/btnAddVehicle"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="+"/>
</LinearLayout>
</code>```

which is used by my VehicleListFragment in this way:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View rootView = inflater.inflate(R.layout.vehicle_list_fragment_layout, container, false);
    btnStartActivity = (Button) rootView.findViewById(R.id.btnAddVehicle);
    mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
    mLayoutManager = new LinearLayoutManager(getActivity());

    setRecyclerViewLayoutManager(LayoutManagerType.LINEAR_LAYOUT_MANAGER);
    initAdapter();
    mRecyclerView.setAdapter(mAdapter);
    setButtonClickListener();

    return rootView;
}
</code>```

The problem is that the RecyclerView is shown correctly, but my btnAddVehicle is not shown.

This is activity_vehicle_layout.xml, the layout of the Activity which hosts my VehicleListFragment:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="clyky.cartracker.activities.VehicleActivity">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/vehicleContainer">
    </FrameLayout>
</android.support.constraint.ConstraintLayout>
</code>```

I use vehicleContainer as container for my fragment.
Thanks in advance!

EDIT

this is my recycler_view_fragment_layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<!-- Layout per un fragment che contiene una RecyclerView -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:id="@+id/recyclerView">
    </android.support.v7.widget.RecyclerView>
</LinearLayout>
</code>```

答:
Try this. Basicall add weightsum to parent view and layout_weight to their child like i added in below,

```<code>  <?xml version="1.0" encoding="utf-8"?><!-- Layout per il fragment VehicleListFragment. -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:weightSum="1">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:layout_weight=".8"
        android:id="@+id/recyclerView">
    </android.support.v7.widget.RecyclerView>

    <Button
        android:id="@+id/btnAddVehicle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight=".2"
        android:text="+" />
</LinearLayout>
</code>```

Need to add Orientation to parent as well to show recycler view and button vertically

Title: Button not visible inside Linear Layout

Body:
I have this vehicle_list_fragment_layout.xml:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include layout="@layout/recycler_view_fragment_layout"/>

    <Button
        android:id="@+id/btnAddVehicle"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="+"/>
</LinearLayout>

which is used by my VehicleListFragment in this way:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View rootView = inflater.inflate(R.layout.vehicle_list_fragment_layout, container, false);
    btnStartActivity = (Button) rootView.findViewById(R.id.btnAddVehicle);
    mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
    mLayoutManager = new LinearLayoutManager(getActivity());

    setRecyclerViewLayoutManager(LayoutManagerType.LINEAR_LAYOUT_MANAGER);
    initAdapter();
    mRecyclerView.setAdapter(mAdapter);
    setButtonClickListener();

    return rootView;
}

The problem is that the RecyclerView is shown correctly, but my btnAddVehicle is not shown.

This is activity_vehicle_layout.xml, the layout of the Activity which hosts my VehicleListFragment:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="clyky.cartracker.activities.VehicleActivity">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/vehicleContainer">
    </FrameLayout>
</android.support.constraint.ConstraintLayout>

I use vehicleContainer as container for my fragment.
Thanks in advance!

EDIT

this is my recycler_view_fragment_layout:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:id="@+id/recyclerView">
    </android.support.v7.widget.RecyclerView>
</LinearLayout>

Body:
Try this. Basicall add weightsum to parent view and layout_weight to their child like i added in below,

  <?xml version="1.0" encoding="utf-8"?><!-- Layout per il fragment VehicleListFragment. -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:weightSum="1">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:layout_weight=".8"
        android:id="@+id/recyclerView">
    </android.support.v7.widget.RecyclerView>

    <Button
        android:id="@+id/btnAddVehicle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight=".2"
        android:text="+" />
</LinearLayout>

Need to add Orientation to parent as well to show recycler view and button vertically


问:
https vs ssl- when to use what
Is https different from http with ssl? If so, when should one use https and when ssl?</p>

答: Nope. HTTPS is HTTP over SSL.</p>

ContentLicense: CC BY-SA 2.5

Title: https vs ssl- when to use what

Body: Nope. HTTPS is HTTP over SSL.


问:
trouble with codeigniter site -shows a hash in the URL
Hi I am listing data using Ajax but after that when i try to get into another menu i get hash in my URL, blocking the loading of link and i have to click on dashboard first and then another menu.http://localhost:8080/project/customers/customers_view#
How do i remove this # from url</p>

答:
The anchor tag which you're clicking may have a hash attached to the href tag. that is

hashify

change it to

hashify

which is javascript void zero, which will solve your problem.

Body:
The anchor tag which you're clicking may have a hash attached to the href tag. that is

<a href="#" class="nohash">hashify</a>

change it to

<a href="javascript:;" class="nohash">hashify</a>

which is javascript void zero, which will solve your problem.


问:
Python: 3D clustering of lists based on their absolute number of same strings content
I have hundreds of lists containing strings of names, and I want to cluster them on 3D graph. Here I give example of 3 lists. The lists with most number of same strings content should be closer to the other on the graph.

How can I do it?

```<code>person1 = ['mike', 'alex', 'arker','locke','dave','david','ross','rachel','anna','ann','darl','carl','karle']

person2 = ['mika', 'adlex', 'parker','ocke','ave','david','rosse','rachel','anna','ann','darla','carla','karle']

person3 = ['mika', 'alex', 'parker','ocke','ave','david','rosse','ross','anna','ann','darla','carla','karle', 'sasha', 'daria']
</code>```

答:
Set intersection can be used as a similarity metric for hierarchical clustering. See, e.g., Jaccard and dice coefficients.

Then you can cluster, but I don't see how this relates to 3D...

Body:
I have hundreds of lists containing strings of names, and I want to cluster them on 3D graph. Here I give example of 3 lists. The lists with most number of same strings content should be closer to the other on the graph.

How can I do it?

person1 = ['mike', 'alex', 'arker','locke','dave','david','ross','rachel','anna','ann','darl','carl','karle']

person2 = ['mika', 'adlex', 'parker','ocke','ave','david','rosse','rachel','anna','ann','darla','carla','karle']

person3 = ['mika', 'alex', 'parker','ocke','ave','david','rosse','ross','anna','ann','darla','carla','karle', 'sasha', 'daria']


问:
cuda - can't access blockDim.x?
I'm working on a cuda program to process a 2D image.

The problem is when I try to access blockDim.x and blockId.x, the kernel always failed to launch and output unknown error.

Besides, if I use a 3x5 image, I can access the threadId.x, while I use a 2048x2048 image I can't.

My kernel code runs OK when I use PyCuda, but now I have to switch to cuda C.

I think the problem may be related to

the way I pass the array pointer and there's something wrong with cudaMalloc

the configuration with my block size and grid size( but the same configuration works well in PyCuda so I don't know how to correct it).

And I use cuda-memcheck, I got unknown error 30 and I googled for solutions but no helpful information.

```<code>__global__ void extractor(const unsigned char* in, unsigned char* out, int* debug)
{
    int idx = (threadIdx.x) + blockDim.x * blockIdx.x ;
    debug[idx] = threadIdx.x; // debug variable is used for debugging
}

int main(int arg, char* args[])
{
    // ...
    int size = w*h; // w is image width and h is image height
    unsigned char *in = 0;
    unsigned char *out = 0;
    int* debug = 0;

    // Allocate GPU buffers for the images
    cudaMalloc((void**)&in, size * sizeof(unsigned char));
    cudaMalloc((void**)&out, num_sample_per_point * size * sizeof(unsigned char));
    cudaMalloc((void**)&debug, size * sizeof(int));

    // Copy image data from host memory to GPU buffers.
    cudaMemcpy(in, &img_data[0], size * sizeof(unsigned char),cudaMemcpyHostToDevice);

    dim3 b_dim(BLOCK_SIZE, 1, 1);   // (1024, 1, 1)
    dim3 g_dim(int(w*h/BLOCK_SIZE)+1, 1, 1);    // (4097, 1, 1)
    extractor<<<g_dim, b_dim>>>(in, out, debug);

    // clean up code and processing result
}
</code>```

Now I can't get expected index so I can't do processing in the kernel, what can be the problem?

EDIT

I want to use 1D index, which means I assume the image array is a "flattened" 1D array and do indexing.

EDIT

After I added the thread check, there's still something wrong.

```<code>__global__ void extractor(const unsigned char* in, unsigned char* out, int* debug)
{
    int idx = (threadIdx.x) + blockDim.x * blockIdx.x ;
    int y; int x;
    int temp_x; int temp_y; int temp_idx;
    int check = width*height;
    if (idx < check) {
        debug[0] = 1;    // get kernel launch failed "unknown error"
    }
}
</code>```

I've tried to put the debug[0]=1; expression both in the thread check block and out the block, both of them get the same error.

So I doubt the memalloc is not been done correctly?

BTW, I used nvprof and it said

```<code>=22344== Warning: Found 2 invalid records in the result.
==22344== Warning: This can happen if device ran out of memory or if a device kernel was stopped due to an assertion.
</code>```

EDIT

complete code:

```<code>#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include <cmath>
#include <iostream>

#include "PNG.h"

#define L 3
#define INC1 1
#define INC2 1
#define R_IN 2
#define N_P 4
#define BLOCK_SIZE 1024
#define PI 3.14159265358979323846

using namespace std;

__global__ void extractor(const unsigned char* in, unsigned char* out, int* debug, int* disX, int* disY, int width, int height, int pad, int num_sample)
{
    int idx = (threadIdx.x) + blockDim.x * blockIdx.x ;
    int y; int x;
    int temp_x; int temp_y; int temp_idx;
    int check = width*height;

       if (idx < check) {
        debug[idx] = threadIdx.x;
        y = idx/width;
        x = idx%width;
            if ((x < pad) || (x >= (width-pad)) || (y < pad) || (y >= (height-pad))) {
                // need padding
                for (int i = 0; i < num_sample; ++i){
                    temp_x = x + disX[i];
                    temp_y = y + disY[i];

                    if (!((temp_x < 0)||(temp_x > (width-1)) || (temp_y < 0) ||(temp_y>(height-1)))) {
                    temp_idx = temp_y*width + temp_x;   // sampled index
                    out[(idx*num_sample)+i] = in[temp_idx]; // copy sampled value to result
                }
                }
            } else {
                for (int i = 0; i < num_sample; ++i)
                {
                    temp_x = x + disX[i];
                    temp_y = y + disY[i];
                    temp_idx = temp_y*width + temp_x;   // sampled index
                    out[(idx*num_sample)+i] = in[temp_idx]; // copy sampled value to result
                }
            }
       }
  }

vector<int> getCirclePos() {
    int r = 0;
    vector <int> circlePos;
    while (!(r>(L/2))) {
        circlePos.push_back(r);
        if (r < R_IN) r += INC1;
        else r += INC2;
    }
    cout << "circlePos:" << endl;
    for (auto i = circlePos.begin(); i != circlePos.end(); ++i)
    {cout << *i << ' ';}
    cout << endl;
    return circlePos;
}

int main(int arg, char* args[])
{
    cudaError_t cudaStatus;
    vector<int> circlePos = getCirclePos();

    // get disX, disY
    int num_sample_per_point = circlePos.size() * N_P;
    int* disX = new int[num_sample_per_point];
    int* disY = new int[num_sample_per_point];
    int r; int cnt = 0;
    for (int i = 0; i < circlePos.size(); ++i)
    {
        r = circlePos[i];
        float angle;
        for (int j = 0; j < N_P; ++j)
        {
            angle = j*360.0/N_P;
            disX[cnt] = r*cos(angle*M_PI/180.0);
            disY[cnt] = r*sin(angle*M_PI/180.0);
            // cout nvpro   << disX[cnt] << "|" << disY[cnt]<< endl;

            cnt++;
        }
    }

    PNG inPng("test.png");
    // PNG outPng;
    // outPng.Create(inPng.w, inPng.h);

    //store width and height so we can use them for our output image later
    const unsigned int w = inPng.w;
    const unsigned int h = inPng.h;
    cout << "w: " << w << " h: " << h << endl;
    //4 because there are 4 color channels R, G, B, and A
    int size = w * h;

    unsigned char *in = 0;
    unsigned char *out = 0;
    int* debug = 0;

    // Allocate GPU buffers for the images
    cudaMalloc((void**)&in, size * sizeof(unsigned char));
    cudaMalloc((void**)&out, num_sample_per_point * size * sizeof(unsigned char));
    cudaMalloc((void**)&debug, size * sizeof(int));

    vector<unsigned char> img_data;
    for (int i = 0; i < size; ++i)
    {
        img_data.push_back(inPng.data[i*4]);
    }

    // debug
    cout << "========= img_data ==========" << endl;
    for (int i = 0; i < size; ++i)
    {
        cout << int(img_data[i]) << "," ;
    }
    cout << endl;

    // Copy image data from host memory to GPU buffers.
    cudaMemcpy(in, &img_data[0], size * sizeof(unsigned char), cudaMemcpyHostToDevice);

    //free the input image because we do not need it anymore
    inPng.Free();

    // Launch a kernel on the GPU with one thread for each element.
    dim3 b_dim(BLOCK_SIZE, 1, 1);   // (1024, 1, 1)
    dim3 g_dim(int(w*h/BLOCK_SIZE)+1, 1, 1);    // (4097, 1, 1)
    int pad = L/2;

    // __global__ void extractor(const unsigned char* in, unsigned char* out, vector<int> disX, vector<int> disY, int width, int height, int pad, int num_sample)
    extractor<<<g_dim, b_dim>>>(in, out, debug, disX, disY, w, h, pad, num_sample_per_point);

    cudaStatus = cudaGetLastError();
    if (cudaStatus != cudaSuccess)
    {
        std::cout << "Kernel launch failed: " << cudaGetErrorString(cudaStatus) << std::endl;
        cudaFree(in);
        cudaFree(out);
        cudaFree(debug);
        exit(1);
    }

    auto tmp = new unsigned char[size*num_sample_per_point];
    auto tmp_debug = new int [size];

    cudaMemcpy(tmp_debug, debug, size * sizeof(int), cudaMemcpyDeviceToHost);
    cudaMemcpy(tmp, out, num_sample_per_point * size * sizeof(unsigned char), cudaMemcpyDeviceToHost);

    cout << "========= out =========" << endl;
    for (int i = 0; i < size*num_sample_per_point; ++i)
    {
        cout << int(tmp[i]) << ", ";
    }
    cout << endl;

    cout << "========debug=======" << endl;
    for (int i = 0; i < size; ++i)
    {
        cout << tmp_debug[i] << ", ";
    }
    cout << endl;

    cudaFree(in);
    cudaFree(out);
    cudaFree(debug);

    delete[] tmp; delete[] tmp_debug;

    return 0;
}
</code>```

答:
This (according to your comment) is defining 1024 threads per block:

```<code>dim3 b_dim(BLOCK_SIZE, 1, 1);   // (1024, 1, 1)
</code>```

According to your question text, w and h are each 2048 in the failing case, so this:

```<code>dim3 g_dim(int(w*h/BLOCK_SIZE)+1, 1, 1);    // (4097, 1, 1)
</code>```

is creating 4097 blocks, just as you indicate in your comment.

4097 blocks of 1024 threads each is 4195328 threads total, but your allocation sizes are only providing 2048*2048 elements, or 4194304 elements total. So you are launching 4195328 threads with only 4194304 elements, leaving 1024 threads left over.

So what do those 1024 extra threads do?  They still run the kernel code and attempt to access your debug array beyond the end of the allocated space.

This results in undefined behavior in C and in C++.

The customary method to fix this is to pass the problem size to your kernel and  add a "thread check" in your kernel code, like this:

```<code>__global__ void extractor(const unsigned char* in, unsigned char* out, int* debug, int n)
{
    int idx = (threadIdx.x) + blockDim.x * blockIdx.x ;
    if (idx < n)
      debug[idx] = threadIdx.x; // debug variable is used for debugging
}
</code>```

which prevents the "extra" threads from doing anything.

If you search here on the cuda tag for "thread check" you will find many other examples of questions like this.

As an example, based on the code pieces you have shown, the following runs without error for me:

```<code>$ cat t147.cu
const int width = 2048;
const int height = 2048;
const int BLOCK_SIZE = 1024;
__global__ void extractor(const unsigned char* in, unsigned char* out, int* debug)
{
    int idx = (threadIdx.x) + blockDim.x * blockIdx.x ;
//    int y; int x;
//    int temp_x; int temp_y; int temp_idx;
    int check = width*height;
    if (idx < check) {
        debug[idx] = 1;    // get kernel launch failed "unknown error"
    }
}
int main(int arg, char* args[])
{

    const int w = width;
    const int h = height;
    const int num_sample_per_point = 1;
    int size = w*h; // w is image width and h is image height
    unsigned char *in = 0;
    unsigned char *out = 0;
    int* debug = 0;

    // Allocate GPU buffers for the images
    cudaMalloc((void**)&in, size * sizeof(unsigned char));
    cudaMalloc((void**)&out, num_sample_per_point * size * sizeof(unsigned char));
    cudaMalloc((void**)&debug, size * sizeof(int));

    // Copy image data from host memory to GPU buffers.
//    cudaMemcpy(in, &img_data[0], size * sizeof(unsigned char),cudaMemcpyHostToDevice);

    dim3 b_dim(BLOCK_SIZE, 1, 1);   // (1024, 1, 1)
    dim3 g_dim(int(w*h/BLOCK_SIZE)+1, 1, 1);    // (4097, 1, 1)
    extractor<<<g_dim, b_dim>>>(in, out, debug);
    cudaDeviceSynchronize();
}
$ nvcc -arch=sm_61 -o t147 t147.cu
$ cuda-memcheck ./t147
========= CUDA-MEMCHECK
========= ERROR SUMMARY: 0 errors
$
</code>```

In your complete code, you simply have an illegal access problem in your kernel.  I've modified it to remove the dependency on PNG, and if we omit the kernel code other than the debug setting, it runs fine.  However if we include your kernel code, and run with cuda-memcheck we get all sorts of out-of-bounds accesses.  In the future, you could use the method described here to debug these:

```<code>$ cat t146.cu
#include <cmath>
#include <iostream>
#include <vector>

#define L 3
#define INC1 1
#define INC2 1
#define R_IN 2
#define N_P 4
#define BLOCK_SIZE 1024
#define PI 3.14159265358979323846

using namespace std;

__global__ void extractor(const unsigned char* in, unsigned char* out, int* debug, int* disX, int* disY, int width, int height, int pad, int num_sample)
{
    int idx = (threadIdx.x) + blockDim.x * blockIdx.x ;
    int y; int x;
    int temp_x; int temp_y; int temp_idx;
    int check = width*height;

       if (idx < check) {
        debug[idx] = threadIdx.x;
        y = idx/width;
        x = idx%width;
#ifdef  FAIL
            if ((x < pad) || (x >= (width-pad)) || (y < pad) || (y >= (height-pad))) {
                // need padding
                for (int i = 0; i < num_sample; ++i){
                    temp_x = x + disX[i];
                    temp_y = y + disY[i];

                    if (!((temp_x < 0)||(temp_x > (width-1)) || (temp_y < 0) ||(temp_y>(height-1)))) {
                    temp_idx = temp_y*width + temp_x;   // sampled index
                    out[(idx*num_sample)+i] = in[temp_idx]; // copy sampled value to result
                }
                }
            } else {
                for (int i = 0; i < num_sample; ++i)
                {
                    temp_x = x + disX[i];
                    temp_y = y + disY[i];
                    temp_idx = temp_y*width + temp_x;   // sampled index
                    out[(idx*num_sample)+i] = in[temp_idx]; // copy sampled value to result
                }
            }
#endif
       }
  }

vector<int> getCirclePos() {
    int r = 0;
    vector <int> circlePos;
    while (!(r>(L/2))) {
        circlePos.push_back(r);
        if (r < R_IN) r += INC1;
        else r += INC2;
    }
    cout << "circlePos:" << endl;
    for (auto i = circlePos.begin(); i != circlePos.end(); ++i)
    {//cout << *i << ' ';
      }
    cout << endl;
    return circlePos;
}

int main(int arg, char* args[])
{
    cudaError_t cudaStatus;
    vector<int> circlePos = getCirclePos();

    // get disX, disY
    int num_sample_per_point = circlePos.size() * N_P;
    int* disX = new int[num_sample_per_point];
    int* disY = new int[num_sample_per_point];
    int r; int cnt = 0;
    for (int i = 0; i < circlePos.size(); ++i)
    {
        r = circlePos[i];
        float angle;
        for (int j = 0; j < N_P; ++j)
        {
            angle = j*360.0/N_P;
            disX[cnt] = r*cos(angle*M_PI/180.0);
            disY[cnt] = r*sin(angle*M_PI/180.0);
            // cout nvpro   << disX[cnt] << "|" << disY[cnt]<< endl;

            cnt++;
        }
    }

    const unsigned int w = 2048;
    const unsigned int h = 2048;
    cout << "w: " << w << " h: " << h << endl;
    //4 because there are 4 color channels R, G, B, and A
    int size = w * h;

    unsigned char *in = 0;
    unsigned char *out = 0;
    int* debug = 0;

    // Allocate GPU buffers for the images
    cudaMalloc((void**)&in, size * sizeof(unsigned char));
    cudaMalloc((void**)&out, num_sample_per_point * size * sizeof(unsigned char));
    cudaMalloc((void**)&debug, size * sizeof(int));

    vector<unsigned char> img_data;
    for (int i = 0; i < size; ++i)
    {
        img_data.push_back(0);
    }

    // debug
    cout << "========= img_data ==========" << endl;
    for (int i = 0; i < size; ++i)
    {
 //       cout << int(img_data[i]) << "," ;
    }
    cout << endl;

    // Copy image data from host memory to GPU buffers.
    cudaMemcpy(in, &img_data[0], size * sizeof(unsigned char), cudaMemcpyHostToDevice);

    // Launch a kernel on the GPU with one thread for each element.
    dim3 b_dim(BLOCK_SIZE, 1, 1);   // (1024, 1, 1)
    dim3 g_dim(int(w*h/BLOCK_SIZE)+1, 1, 1);    // (4097, 1, 1)
    int pad = L/2;

    // __global__ void extractor(const unsigned char* in, unsigned char* out, vector<int> disX, vector<int> disY, int width, int height, int pad, int num_sample)
    extractor<<<g_dim, b_dim>>>(in, out, debug, disX, disY, w, h, pad, num_sample_per_point);

    cudaStatus = cudaGetLastError();
    if (cudaStatus != cudaSuccess)
    {
        std::cout << "Kernel launch failed: " << cudaGetErrorString(cudaStatus) << std::endl;
        cudaFree(in);
        cudaFree(out);
        cudaFree(debug);
        exit(1);
    }

    auto tmp = new unsigned char[size*num_sample_per_point];
    auto tmp_debug = new int [size];

    cudaMemcpy(tmp_debug, debug, size * sizeof(int), cudaMemcpyDeviceToHost);
    cudaMemcpy(tmp, out, num_sample_per_point * size * sizeof(unsigned char), cudaMemcpyDeviceToHost);

    cout << "========= out =========" << endl;
    for (int i = 0; i < size*num_sample_per_point; ++i)
    {
   //     cout << int(tmp[i]) << ", ";
    }
    cout << endl;

    cout << "========debug=======" << endl;
    for (int i = 0; i < size; ++i)
    {
     //   cout << tmp_debug[i] << ", ";
    }
    cout << endl;

    cudaFree(in);
    cudaFree(out);
    cudaFree(debug);

    delete[] tmp; delete[] tmp_debug;

    return 0;
}
$ nvcc -std=c++11 -o t146 t146.cu -arch=sm_61 -lineinfo
t146.cu(18): warning: variable "y" was set but never used

t146.cu(18): warning: variable "x" was set but never used

t146.cu(19): warning: variable "temp_x" was declared but never referenced

t146.cu(19): warning: variable "temp_y" was declared but never referenced

t146.cu(19): warning: variable "temp_idx" was declared but never referenced

t146.cu(18): warning: variable "y" was set but never used

t146.cu(18): warning: variable "x" was set but never used

t146.cu(19): warning: variable "temp_x" was declared but never referenced

t146.cu(19): warning: variable "temp_y" was declared but never referenced

t146.cu(19): warning: variable "temp_idx" was declared but never referenced

$ cuda-memcheck ./t146
========= CUDA-MEMCHECK
circlePos:

w: 2048 h: 2048
========= img_data ==========

========= out =========

========debug=======

========= ERROR SUMMARY: 0 errors
$ nvcc -std=c++11 -o t146 t146.cu -arch=sm_61 -lineinfo -DFAIL
$ cuda-memcheck ./t146
...
========= Invalid __global__ read of size 4
=========     at 0x00000418 in /home/ubuntu/bobc/misc/t146.cu:41:extractor(unsigned char const *, unsigned char*, int*, int*, int*, int, int, int, int)
=========     by thread (197,0,0) in block (17,0,0)
=========     Address 0x00c8b290 is out of bounds
=========     Saved host backtrace up to driver entry point at kernel launch time
=========     Host Frame:/usr/lib/x86_64-linux-gnu/libcuda.so.1 (cuLaunchKernel + 0x2c5)
...
(and much more output like this)
</code>```

The above output points to line 41 in the code, which is reading from disX.

As it turns out, your disX is a host-allocated variable:

```<code>int* disX = new int[num_sample_per_point];
</code>```

but you are attempting to pass it to device code:

```<code>extractor<<<g_dim, b_dim>>>(in, out, debug, disX, disY, w, h, pad, num_sample_per_point);
                                            ^^^^
</code>```

That is just completely broken.  You can't do that in CUDA.  You need to make a device copy of that variable, and also disY  When I fix that problem, the modified code runs without error for me:

```<code>$ cat t146.cu
#include <cmath>
#include <iostream>
#include <vector>

#define L 3
#define INC1 1
#define INC2 1
#define R_IN 2
#define N_P 4
#define BLOCK_SIZE 1024
#define PI 3.14159265358979323846

using namespace std;

__global__ void extractor(const unsigned char* in, unsigned char* out, int* debug, int* disX, int* disY, int width, int height, int pad, int num_sample)
{
    int idx = (threadIdx.x) + blockDim.x * blockIdx.x ;
    int y; int x;
    int temp_x; int temp_y; int temp_idx;
    int check = width*height;

       if (idx < check) {
        debug[idx] = threadIdx.x;
        y = idx/width;
        x = idx%width;
#ifdef  FAIL
            if ((x < pad) || (x >= (width-pad)) || (y < pad) || (y >= (height-pad))) {
                // need padding
                for (int i = 0; i < num_sample; ++i){
                    temp_x = x + disX[i];
                    temp_y = y + disY[i];

                    if (!((temp_x < 0)||(temp_x > (width-1)) || (temp_y < 0) ||(temp_y>(height-1)))) {
                    temp_idx = temp_y*width + temp_x;   // sampled index
                    out[(idx*num_sample)+i] = in[temp_idx]; // copy sampled value to result
                }
                }
            } else {
                for (int i = 0; i < num_sample; ++i)
                {
                    temp_x = x + disX[i];
                    temp_y = y + disY[i];
                    temp_idx = temp_y*width + temp_x;   // sampled index
                    out[(idx*num_sample)+i] = in[temp_idx]; // copy sampled value to result
                }
            }
#endif
       }
  }

vector<int> getCirclePos() {
    int r = 0;
    vector <int> circlePos;
    while (!(r>(L/2))) {
        circlePos.push_back(r);
        if (r < R_IN) r += INC1;
        else r += INC2;
    }
    cout << "circlePos:" << endl;
    for (auto i = circlePos.begin(); i != circlePos.end(); ++i)
    {//cout << *i << ' ';
      }
    cout << endl;
    return circlePos;
}

int main(int arg, char* args[])
{
    cudaError_t cudaStatus;
    vector<int> circlePos = getCirclePos();

    // get disX, disY
    int num_sample_per_point = circlePos.size() * N_P;
    int* disX = new int[num_sample_per_point];
    int* disY = new int[num_sample_per_point];
    int r; int cnt = 0;
    for (int i = 0; i < circlePos.size(); ++i)
    {
        r = circlePos[i];
        float angle;
        for (int j = 0; j < N_P; ++j)
        {
            angle = j*360.0/N_P;
            disX[cnt] = r*cos(angle*M_PI/180.0);
            disY[cnt] = r*sin(angle*M_PI/180.0);
            // cout nvpro   << disX[cnt] << "|" << disY[cnt]<< endl;

            cnt++;
        }
    }

    int *d_disX, *d_disY;
    cudaMalloc(&d_disX, num_sample_per_point*sizeof(int));
    cudaMalloc(&d_disY, num_sample_per_point*sizeof(int));
    cudaMemcpy(d_disX, disX, num_sample_per_point*sizeof(int), cudaMemcpyHostToDevice);
    cudaMemcpy(d_disY, disY, num_sample_per_point*sizeof(int), cudaMemcpyHostToDevice);
    const unsigned int w = 2048;
    const unsigned int h = 2048;
    cout << "w: " << w << " h: " << h << endl;
    //4 because there are 4 color channels R, G, B, and A
    int size = w * h;

    unsigned char *in = 0;
    unsigned char *out = 0;
    int* debug = 0;

    // Allocate GPU buffers for the images
    cudaMalloc((void**)&in, size * sizeof(unsigned char));
    cudaMalloc((void**)&out, num_sample_per_point * size * sizeof(unsigned char));
    cudaMalloc((void**)&debug, size * sizeof(int));

    vector<unsigned char> img_data;
    for (int i = 0; i < size; ++i)
    {
        img_data.push_back(0);
    }

    // debug
    cout << "========= img_data ==========" << endl;
    for (int i = 0; i < size; ++i)
    {
 //       cout << int(img_data[i]) << "," ;
    }
    cout << endl;

    // Copy image data from host memory to GPU buffers.
    cudaMemcpy(in, &img_data[0], size * sizeof(unsigned char), cudaMemcpyHostToDevice);

    // Launch a kernel on the GPU with one thread for each element.
    dim3 b_dim(BLOCK_SIZE, 1, 1);   // (1024, 1, 1)
    dim3 g_dim(int(w*h/BLOCK_SIZE)+1, 1, 1);    // (4097, 1, 1)
    int pad = L/2;

    // __global__ void extractor(const unsigned char* in, unsigned char* out, vector<int> disX, vector<int> disY, int width, int height, int pad, int num_sample)
    extractor<<<g_dim, b_dim>>>(in, out, debug, d_disX, d_disY, w, h, pad, num_sample_per_point);

    cudaStatus = cudaGetLastError();
    if (cudaStatus != cudaSuccess)
    {
        std::cout << "Kernel launch failed: " << cudaGetErrorString(cudaStatus) << std::endl;
        cudaFree(in);
        cudaFree(out);
        cudaFree(debug);
        exit(1);
    }

    auto tmp = new unsigned char[size*num_sample_per_point];
    auto tmp_debug = new int [size];

    cudaMemcpy(tmp_debug, debug, size * sizeof(int), cudaMemcpyDeviceToHost);
    cudaMemcpy(tmp, out, num_sample_per_point * size * sizeof(unsigned char), cudaMemcpyDeviceToHost);

    cout << "========= out =========" << endl;
    for (int i = 0; i < size*num_sample_per_point; ++i)
    {
   //     cout << int(tmp[i]) << ", ";
    }
    cout << endl;

    cout << "========debug=======" << endl;
    for (int i = 0; i < size; ++i)
    {
     //   cout << tmp_debug[i] << ", ";
    }
    cout << endl;

    cudaFree(in);
    cudaFree(out);
    cudaFree(debug);

    delete[] tmp; delete[] tmp_debug;

    return 0;
}
$ nvcc -std=c++11 -o t146 t146.cu -arch=sm_61 -lineinfo -DFAIL
$ cuda-memcheck ./t146
========= CUDA-MEMCHECK
circlePos:

w: 2048 h: 2048
========= img_data ==========

========= out =========

========debug=======

========= ERROR SUMMARY: 0 errors
$
</code>```

Title: cuda - can't access blockDim.x?

Body:
I'm working on a cuda program to process a 2D image.

The problem is when I try to access blockDim.x and blockId.x, the kernel always failed to launch and output unknown error.

Besides, if I use a 3x5 image, I can access the threadId.x, while I use a 2048x2048 image I can't.

My kernel code runs OK when I use PyCuda, but now I have to switch to cuda C.

I think the problem may be related to

the way I pass the array pointer and there's something wrong with cudaMalloc

the configuration with my block size and grid size( but the same configuration works well in PyCuda so I don't know how to correct it).

And I use cuda-memcheck, I got unknown error 30 and I googled for solutions but no helpful information.

__global__ void extractor(const unsigned char* in, unsigned char* out, int* debug)
{
    int idx = (threadIdx.x) + blockDim.x * blockIdx.x ;
    debug[idx] = threadIdx.x; // debug variable is used for debugging
}

int main(int arg, char* args[])
{
    // ...
    int size = w*h; // w is image width and h is image height
    unsigned char *in = 0;
    unsigned char *out = 0;
    int* debug = 0;

    // Allocate GPU buffers for the images
    cudaMalloc((void**)&in, size * sizeof(unsigned char));
    cudaMalloc((void**)&out, num_sample_per_point * size * sizeof(unsigned char));
    cudaMalloc((void**)&debug, size * sizeof(int));

    // Copy image data from host memory to GPU buffers.
    cudaMemcpy(in, &img_data[0], size * sizeof(unsigned char),cudaMemcpyHostToDevice);

    dim3 b_dim(BLOCK_SIZE, 1, 1);   // (1024, 1, 1)
    dim3 g_dim(int(w*h/BLOCK_SIZE)+1, 1, 1);    // (4097, 1, 1)
    extractor<<<g_dim, b_dim>>>(in, out, debug);

    // clean up code and processing result
}

Now I can't get expected index so I can't do processing in the kernel, what can be the problem?

EDIT

I want to use 1D index, which means I assume the image array is a "flattened" 1D array and do indexing.

EDIT

After I added the thread check, there's still something wrong.

__global__ void extractor(const unsigned char* in, unsigned char* out, int* debug)
{
    int idx = (threadIdx.x) + blockDim.x * blockIdx.x ;
    int y; int x;
    int temp_x; int temp_y; int temp_idx;
    int check = width*height;
    if (idx < check) {
        debug[0] = 1;    // get kernel launch failed "unknown error"
    }
}

I've tried to put the debug[0]=1; expression both in the thread check block and out the block, both of them get the same error.

So I doubt the memalloc is not been done correctly?

BTW, I used nvprof and it said

=22344== Warning: Found 2 invalid records in the result.
==22344== Warning: This can happen if device ran out of memory or if a device kernel was stopped due to an assertion.

EDIT

complete code:

#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include <cmath>
#include <iostream>

#include "PNG.h"

#define L 3
#define INC1 1
#define INC2 1
#define R_IN 2
#define N_P 4
#define BLOCK_SIZE 1024
#define PI 3.14159265358979323846

using namespace std;

__global__ void extractor(const unsigned char* in, unsigned char* out, int* debug, int* disX, int* disY, int width, int height, int pad, int num_sample)
{
    int idx = (threadIdx.x) + blockDim.x * blockIdx.x ;
    int y; int x;
    int temp_x; int temp_y; int temp_idx;
    int check = width*height;

       if (idx < check) {
        debug[idx] = threadIdx.x;
        y = idx/width;
        x = idx%width;
            if ((x < pad) || (x >= (width-pad)) || (y < pad) || (y >= (height-pad))) {
                // need padding
                for (int i = 0; i < num_sample; ++i){
                    temp_x = x + disX[i];
                    temp_y = y + disY[i];

                    if (!((temp_x < 0)||(temp_x > (width-1)) || (temp_y < 0) ||(temp_y>(height-1)))) {
                    temp_idx = temp_y*width + temp_x;   // sampled index
                    out[(idx*num_sample)+i] = in[temp_idx]; // copy sampled value to result
                }
                }
            } else {
                for (int i = 0; i < num_sample; ++i)
                {
                    temp_x = x + disX[i];
                    temp_y = y + disY[i];
                    temp_idx = temp_y*width + temp_x;   // sampled index
                    out[(idx*num_sample)+i] = in[temp_idx]; // copy sampled value to result
                }
            }
       }
  }

vector<int> getCirclePos() {
    int r = 0;
    vector <int> circlePos;
    while (!(r>(L/2))) {
        circlePos.push_back(r);
        if (r < R_IN) r += INC1;
        else r += INC2;
    }
    cout << "circlePos:" << endl;
    for (auto i = circlePos.begin(); i != circlePos.end(); ++i)
    {cout << *i << ' ';}
    cout << endl;
    return circlePos;
}

int main(int arg, char* args[])
{
    cudaError_t cudaStatus;
    vector<int> circlePos = getCirclePos();

    // get disX, disY
    int num_sample_per_point = circlePos.size() * N_P;
    int* disX = new int[num_sample_per_point];
    int* disY = new int[num_sample_per_point];
    int r; int cnt = 0;
    for (int i = 0; i < circlePos.size(); ++i)
    {
        r = circlePos[i];
        float angle;
        for (int j = 0; j < N_P; ++j)
        {
            angle = j*360.0/N_P;
            disX[cnt] = r*cos(angle*M_PI/180.0);
            disY[cnt] = r*sin(angle*M_PI/180.0);
            // cout nvpro   << disX[cnt] << "|" << disY[cnt]<< endl;

            cnt++;
        }
    }

    PNG inPng("test.png");
    // PNG outPng;
    // outPng.Create(inPng.w, inPng.h);

    //store width and height so we can use them for our output image later
    const unsigned int w = inPng.w;
    const unsigned int h = inPng.h;
    cout << "w: " << w << " h: " << h << endl;
    //4 because there are 4 color channels R, G, B, and A
    int size = w * h;

    unsigned char *in = 0;
    unsigned char *out = 0;
    int* debug = 0;

    // Allocate GPU buffers for the images
    cudaMalloc((void**)&in, size * sizeof(unsigned char));
    cudaMalloc((void**)&out, num_sample_per_point * size * sizeof(unsigned char));
    cudaMalloc((void**)&debug, size * sizeof(int));

    vector<unsigned char> img_data;
    for (int i = 0; i < size; ++i)
    {
        img_data.push_back(inPng.data[i*4]);
    }

    // debug
    cout << "========= img_data ==========" << endl;
    for (int i = 0; i < size; ++i)
    {
        cout << int(img_data[i]) << "," ;
    }
    cout << endl;

    // Copy image data from host memory to GPU buffers.
    cudaMemcpy(in, &img_data[0], size * sizeof(unsigned char), cudaMemcpyHostToDevice);

    //free the input image because we do not need it anymore
    inPng.Free();

    // Launch a kernel on the GPU with one thread for each element.
    dim3 b_dim(BLOCK_SIZE, 1, 1);   // (1024, 1, 1)
    dim3 g_dim(int(w*h/BLOCK_SIZE)+1, 1, 1);    // (4097, 1, 1)
    int pad = L/2;

    // __global__ void extractor(const unsigned char* in, unsigned char* out, vector<int> disX, vector<int> disY, int width, int height, int pad, int num_sample)
    extractor<<<g_dim, b_dim>>>(in, out, debug, disX, disY, w, h, pad, num_sample_per_point);

    cudaStatus = cudaGetLastError();
    if (cudaStatus != cudaSuccess)
    {
        std::cout << "Kernel launch failed: " << cudaGetErrorString(cudaStatus) << std::endl;
        cudaFree(in);
        cudaFree(out);
        cudaFree(debug);
        exit(1);
    }

    auto tmp = new unsigned char[size*num_sample_per_point];
    auto tmp_debug = new int [size];

    cudaMemcpy(tmp_debug, debug, size * sizeof(int), cudaMemcpyDeviceToHost);
    cudaMemcpy(tmp, out, num_sample_per_point * size * sizeof(unsigned char), cudaMemcpyDeviceToHost);

    cout << "========= out =========" << endl;
    for (int i = 0; i < size*num_sample_per_point; ++i)
    {
        cout << int(tmp[i]) << ", ";
    }
    cout << endl;

    cout << "========debug=======" << endl;
    for (int i = 0; i < size; ++i)
    {
        cout << tmp_debug[i] << ", ";
    }
    cout << endl;

    cudaFree(in);
    cudaFree(out);
    cudaFree(debug);

    delete[] tmp; delete[] tmp_debug;

    return 0;
}

Body:
This (according to your comment) is defining 1024 threads per block:

dim3 b_dim(BLOCK_SIZE, 1, 1);   // (1024, 1, 1)

According to your question text, w and h are each 2048 in the failing case, so this:

dim3 g_dim(int(w*h/BLOCK_SIZE)+1, 1, 1);    // (4097, 1, 1)

is creating 4097 blocks, just as you indicate in your comment.

4097 blocks of 1024 threads each is 4195328 threads total, but your allocation sizes are only providing 2048*2048 elements, or 4194304 elements total. So you are launching 4195328 threads with only 4194304 elements, leaving 1024 threads left over.

So what do those 1024 extra threads do?  They still run the kernel code and attempt to access your debug array beyond the end of the allocated space.

This results in undefined behavior in C and in C++.

The customary method to fix this is to pass the problem size to your kernel and  add a "thread check" in your kernel code, like this:

__global__ void extractor(const unsigned char* in, unsigned char* out, int* debug, int n)
{
    int idx = (threadIdx.x) + blockDim.x * blockIdx.x ;
    if (idx < n)
      debug[idx] = threadIdx.x; // debug variable is used for debugging
}

which prevents the "extra" threads from doing anything.

If you search here on the cuda tag for "thread check" you will find many other examples of questions like this.

As an example, based on the code pieces you have shown, the following runs without error for me:

$ cat t147.cu
const int width = 2048;
const int height = 2048;
const int BLOCK_SIZE = 1024;
__global__ void extractor(const unsigned char* in, unsigned char* out, int* debug)
{
    int idx = (threadIdx.x) + blockDim.x * blockIdx.x ;
//    int y; int x;
//    int temp_x; int temp_y; int temp_idx;
    int check = width*height;
    if (idx < check) {
        debug[idx] = 1;    // get kernel launch failed "unknown error"
    }
}
int main(int arg, char* args[])
{

    const int w = width;
    const int h = height;
    const int num_sample_per_point = 1;
    int size = w*h; // w is image width and h is image height
    unsigned char *in = 0;
    unsigned char *out = 0;
    int* debug = 0;

    // Allocate GPU buffers for the images
    cudaMalloc((void**)&in, size * sizeof(unsigned char));
    cudaMalloc((void**)&out, num_sample_per_point * size * sizeof(unsigned char));
    cudaMalloc((void**)&debug, size * sizeof(int));

    // Copy image data from host memory to GPU buffers.
//    cudaMemcpy(in, &img_data[0], size * sizeof(unsigned char),cudaMemcpyHostToDevice);

    dim3 b_dim(BLOCK_SIZE, 1, 1);   // (1024, 1, 1)
    dim3 g_dim(int(w*h/BLOCK_SIZE)+1, 1, 1);    // (4097, 1, 1)
    extractor<<<g_dim, b_dim>>>(in, out, debug);
    cudaDeviceSynchronize();
}
$ nvcc -arch=sm_61 -o t147 t147.cu
$ cuda-memcheck ./t147
========= CUDA-MEMCHECK
========= ERROR SUMMARY: 0 errors
$

In your complete code, you simply have an illegal access problem in your kernel.  I've modified it to remove the dependency on PNG, and if we omit the kernel code other than the debug setting, it runs fine.  However if we include your kernel code, and run with cuda-memcheck we get all sorts of out-of-bounds accesses.  In the future, you could use the method described here to debug these:

$ cat t146.cu
#include <cmath>
#include <iostream>
#include <vector>

#define L 3
#define INC1 1
#define INC2 1
#define R_IN 2
#define N_P 4
#define BLOCK_SIZE 1024
#define PI 3.14159265358979323846

using namespace std;

__global__ void extractor(const unsigned char* in, unsigned char* out, int* debug, int* disX, int* disY, int width, int height, int pad, int num_sample)
{
    int idx = (threadIdx.x) + blockDim.x * blockIdx.x ;
    int y; int x;
    int temp_x; int temp_y; int temp_idx;
    int check = width*height;

       if (idx < check) {
        debug[idx] = threadIdx.x;
        y = idx/width;
        x = idx%width;
#ifdef  FAIL
            if ((x < pad) || (x >= (width-pad)) || (y < pad) || (y >= (height-pad))) {
                // need padding
                for (int i = 0; i < num_sample; ++i){
                    temp_x = x + disX[i];
                    temp_y = y + disY[i];

                    if (!((temp_x < 0)||(temp_x > (width-1)) || (temp_y < 0) ||(temp_y>(height-1)))) {
                    temp_idx = temp_y*width + temp_x;   // sampled index
                    out[(idx*num_sample)+i] = in[temp_idx]; // copy sampled value to result
                }
                }
            } else {
                for (int i = 0; i < num_sample; ++i)
                {
                    temp_x = x + disX[i];
                    temp_y = y + disY[i];
                    temp_idx = temp_y*width + temp_x;   // sampled index
                    out[(idx*num_sample)+i] = in[temp_idx]; // copy sampled value to result
                }
            }
#endif
       }
  }

vector<int> getCirclePos() {
    int r = 0;
    vector <int> circlePos;
    while (!(r>(L/2))) {
        circlePos.push_back(r);
        if (r < R_IN) r += INC1;
        else r += INC2;
    }
    cout << "circlePos:" << endl;
    for (auto i = circlePos.begin(); i != circlePos.end(); ++i)
    {//cout << *i << ' ';
      }
    cout << endl;
    return circlePos;
}

int main(int arg, char* args[])
{
    cudaError_t cudaStatus;
    vector<int> circlePos = getCirclePos();

    // get disX, disY
    int num_sample_per_point = circlePos.size() * N_P;
    int* disX = new int[num_sample_per_point];
    int* disY = new int[num_sample_per_point];
    int r; int cnt = 0;
    for (int i = 0; i < circlePos.size(); ++i)
    {
        r = circlePos[i];
        float angle;
        for (int j = 0; j < N_P; ++j)
        {
            angle = j*360.0/N_P;
            disX[cnt] = r*cos(angle*M_PI/180.0);
            disY[cnt] = r*sin(angle*M_PI/180.0);
            // cout nvpro   << disX[cnt] << "|" << disY[cnt]<< endl;

            cnt++;
        }
    }

    const unsigned int w = 2048;
    const unsigned int h = 2048;
    cout << "w: " << w << " h: " << h << endl;
    //4 because there are 4 color channels R, G, B, and A
    int size = w * h;

    unsigned char *in = 0;
    unsigned char *out = 0;
    int* debug = 0;

    // Allocate GPU buffers for the images
    cudaMalloc((void**)&in, size * sizeof(unsigned char));
    cudaMalloc((void**)&out, num_sample_per_point * size * sizeof(unsigned char));
    cudaMalloc((void**)&debug, size * sizeof(int));

    vector<unsigned char> img_data;
    for (int i = 0; i < size; ++i)
    {
        img_data.push_back(0);
    }

    // debug
    cout << "========= img_data ==========" << endl;
    for (int i = 0; i < size; ++i)
    {
 //       cout << int(img_data[i]) << "," ;
    }
    cout << endl;

    // Copy image data from host memory to GPU buffers.
    cudaMemcpy(in, &img_data[0], size * sizeof(unsigned char), cudaMemcpyHostToDevice);

    // Launch a kernel on the GPU with one thread for each element.
    dim3 b_dim(BLOCK_SIZE, 1, 1);   // (1024, 1, 1)
    dim3 g_dim(int(w*h/BLOCK_SIZE)+1, 1, 1);    // (4097, 1, 1)
    int pad = L/2;

    // __global__ void extractor(const unsigned char* in, unsigned char* out, vector<int> disX, vector<int> disY, int width, int height, int pad, int num_sample)
    extractor<<<g_dim, b_dim>>>(in, out, debug, disX, disY, w, h, pad, num_sample_per_point);

    cudaStatus = cudaGetLastError();
    if (cudaStatus != cudaSuccess)
    {
        std::cout << "Kernel launch failed: " << cudaGetErrorString(cudaStatus) << std::endl;
        cudaFree(in);
        cudaFree(out);
        cudaFree(debug);
        exit(1);
    }

    auto tmp = new unsigned char[size*num_sample_per_point];
    auto tmp_debug = new int [size];

    cudaMemcpy(tmp_debug, debug, size * sizeof(int), cudaMemcpyDeviceToHost);
    cudaMemcpy(tmp, out, num_sample_per_point * size * sizeof(unsigned char), cudaMemcpyDeviceToHost);

    cout << "========= out =========" << endl;
    for (int i = 0; i < size*num_sample_per_point; ++i)
    {
   //     cout << int(tmp[i]) << ", ";
    }
    cout << endl;

    cout << "========debug=======" << endl;
    for (int i = 0; i < size; ++i)
    {
     //   cout << tmp_debug[i] << ", ";
    }
    cout << endl;

    cudaFree(in);
    cudaFree(out);
    cudaFree(debug);

    delete[] tmp; delete[] tmp_debug;

    return 0;
}
$ nvcc -std=c++11 -o t146 t146.cu -arch=sm_61 -lineinfo
t146.cu(18): warning: variable "y" was set but never used

t146.cu(18): warning: variable "x" was set but never used

t146.cu(19): warning: variable "temp_x" was declared but never referenced

t146.cu(19): warning: variable "temp_y" was declared but never referenced

t146.cu(19): warning: variable "temp_idx" was declared but never referenced

t146.cu(18): warning: variable "y" was set but never used

t146.cu(18): warning: variable "x" was set but never used

t146.cu(19): warning: variable "temp_x" was declared but never referenced

t146.cu(19): warning: variable "temp_y" was declared but never referenced

t146.cu(19): warning: variable "temp_idx" was declared but never referenced

$ cuda-memcheck ./t146
========= CUDA-MEMCHECK
circlePos:

w: 2048 h: 2048
========= img_data ==========

========= out =========

========debug=======

========= ERROR SUMMARY: 0 errors
$ nvcc -std=c++11 -o t146 t146.cu -arch=sm_61 -lineinfo -DFAIL
$ cuda-memcheck ./t146
...
========= Invalid __global__ read of size 4
=========     at 0x00000418 in /home/ubuntu/bobc/misc/t146.cu:41:extractor(unsigned char const *, unsigned char*, int*, int*, int*, int, int, int, int)
=========     by thread (197,0,0) in block (17,0,0)
=========     Address 0x00c8b290 is out of bounds
=========     Saved host backtrace up to driver entry point at kernel launch time
=========     Host Frame:/usr/lib/x86_64-linux-gnu/libcuda.so.1 (cuLaunchKernel + 0x2c5)
...
(and much more output like this)

The above output points to line 41 in the code, which is reading from disX.

As it turns out, your disX is a host-allocated variable:

int* disX = new int[num_sample_per_point];

but you are attempting to pass it to device code:

extractor<<<g_dim, b_dim>>>(in, out, debug, disX, disY, w, h, pad, num_sample_per_point);
                                            ^^^^

That is just completely broken.  You can't do that in CUDA.  You need to make a device copy of that variable, and also disY  When I fix that problem, the modified code runs without error for me:

$ cat t146.cu
#include <cmath>
#include <iostream>
#include <vector>

#define L 3
#define INC1 1
#define INC2 1
#define R_IN 2
#define N_P 4
#define BLOCK_SIZE 1024
#define PI 3.14159265358979323846

using namespace std;

__global__ void extractor(const unsigned char* in, unsigned char* out, int* debug, int* disX, int* disY, int width, int height, int pad, int num_sample)
{
    int idx = (threadIdx.x) + blockDim.x * blockIdx.x ;
    int y; int x;
    int temp_x; int temp_y; int temp_idx;
    int check = width*height;

       if (idx < check) {
        debug[idx] = threadIdx.x;
        y = idx/width;
        x = idx%width;
#ifdef  FAIL
            if ((x < pad) || (x >= (width-pad)) || (y < pad) || (y >= (height-pad))) {
                // need padding
                for (int i = 0; i < num_sample; ++i){
                    temp_x = x + disX[i];
                    temp_y = y + disY[i];

                    if (!((temp_x < 0)||(temp_x > (width-1)) || (temp_y < 0) ||(temp_y>(height-1)))) {
                    temp_idx = temp_y*width + temp_x;   // sampled index
                    out[(idx*num_sample)+i] = in[temp_idx]; // copy sampled value to result
                }
                }
            } else {
                for (int i = 0; i < num_sample; ++i)
                {
                    temp_x = x + disX[i];
                    temp_y = y + disY[i];
                    temp_idx = temp_y*width + temp_x;   // sampled index
                    out[(idx*num_sample)+i] = in[temp_idx]; // copy sampled value to result
                }
            }
#endif
       }
  }

vector<int> getCirclePos() {
    int r = 0;
    vector <int> circlePos;
    while (!(r>(L/2))) {
        circlePos.push_back(r);
        if (r < R_IN) r += INC1;
        else r += INC2;
    }
    cout << "circlePos:" << endl;
    for (auto i = circlePos.begin(); i != circlePos.end(); ++i)
    {//cout << *i << ' ';
      }
    cout << endl;
    return circlePos;
}

int main(int arg, char* args[])
{
    cudaError_t cudaStatus;
    vector<int> circlePos = getCirclePos();

    // get disX, disY
    int num_sample_per_point = circlePos.size() * N_P;
    int* disX = new int[num_sample_per_point];
    int* disY = new int[num_sample_per_point];
    int r; int cnt = 0;
    for (int i = 0; i < circlePos.size(); ++i)
    {
        r = circlePos[i];
        float angle;
        for (int j = 0; j < N_P; ++j)
        {
            angle = j*360.0/N_P;
            disX[cnt] = r*cos(angle*M_PI/180.0);
            disY[cnt] = r*sin(angle*M_PI/180.0);
            // cout nvpro   << disX[cnt] << "|" << disY[cnt]<< endl;

            cnt++;
        }
    }

    int *d_disX, *d_disY;
    cudaMalloc(&d_disX, num_sample_per_point*sizeof(int));
    cudaMalloc(&d_disY, num_sample_per_point*sizeof(int));
    cudaMemcpy(d_disX, disX, num_sample_per_point*sizeof(int), cudaMemcpyHostToDevice);
    cudaMemcpy(d_disY, disY, num_sample_per_point*sizeof(int), cudaMemcpyHostToDevice);
    const unsigned int w = 2048;
    const unsigned int h = 2048;
    cout << "w: " << w << " h: " << h << endl;
    //4 because there are 4 color channels R, G, B, and A
    int size = w * h;

    unsigned char *in = 0;
    unsigned char *out = 0;
    int* debug = 0;

    // Allocate GPU buffers for the images
    cudaMalloc((void**)&in, size * sizeof(unsigned char));
    cudaMalloc((void**)&out, num_sample_per_point * size * sizeof(unsigned char));
    cudaMalloc((void**)&debug, size * sizeof(int));

    vector<unsigned char> img_data;
    for (int i = 0; i < size; ++i)
    {
        img_data.push_back(0);
    }

    // debug
    cout << "========= img_data ==========" << endl;
    for (int i = 0; i < size; ++i)
    {
 //       cout << int(img_data[i]) << "," ;
    }
    cout << endl;

    // Copy image data from host memory to GPU buffers.
    cudaMemcpy(in, &img_data[0], size * sizeof(unsigned char), cudaMemcpyHostToDevice);

    // Launch a kernel on the GPU with one thread for each element.
    dim3 b_dim(BLOCK_SIZE, 1, 1);   // (1024, 1, 1)
    dim3 g_dim(int(w*h/BLOCK_SIZE)+1, 1, 1);    // (4097, 1, 1)
    int pad = L/2;

    // __global__ void extractor(const unsigned char* in, unsigned char* out, vector<int> disX, vector<int> disY, int width, int height, int pad, int num_sample)
    extractor<<<g_dim, b_dim>>>(in, out, debug, d_disX, d_disY, w, h, pad, num_sample_per_point);

    cudaStatus = cudaGetLastError();
    if (cudaStatus != cudaSuccess)
    {
        std::cout << "Kernel launch failed: " << cudaGetErrorString(cudaStatus) << std::endl;
        cudaFree(in);
        cudaFree(out);
        cudaFree(debug);
        exit(1);
    }

    auto tmp = new unsigned char[size*num_sample_per_point];
    auto tmp_debug = new int [size];

    cudaMemcpy(tmp_debug, debug, size * sizeof(int), cudaMemcpyDeviceToHost);
    cudaMemcpy(tmp, out, num_sample_per_point * size * sizeof(unsigned char), cudaMemcpyDeviceToHost);

    cout << "========= out =========" << endl;
    for (int i = 0; i < size*num_sample_per_point; ++i)
    {
   //     cout << int(tmp[i]) << ", ";
    }
    cout << endl;

    cout << "========debug=======" << endl;
    for (int i = 0; i < size; ++i)
    {
     //   cout << tmp_debug[i] << ", ";
    }
    cout << endl;

    cudaFree(in);
    cudaFree(out);
    cudaFree(debug);

    delete[] tmp; delete[] tmp_debug;

    return 0;
}
$ nvcc -std=c++11 -o t146 t146.cu -arch=sm_61 -lineinfo -DFAIL
$ cuda-memcheck ./t146
========= CUDA-MEMCHECK
circlePos:

w: 2048 h: 2048
========= img_data ==========

========= out =========

========debug=======

========= ERROR SUMMARY: 0 errors
$


问:
I wanted to add an element to my array after sorting the array
Here is my code</p>

```<code>import java.util.*;

public class ArrayExample {
    public static void main(String[] args) {
        Integer arr[] = {5,4,3,2,15,8,9};
        List<Integer> list = Arrays.asList(arr);
        Collections.sort(list);
        System.out.println(list);
        list.add(6);// here I am adding 6 to my array.
        System.out.println(list);
        // Here I should get output as [2,3,4,5,6,8,9,15]
    }
}
</code>```

答:
If you want the array to stay sorted, you will have to sort it after each insert.

However, using a binary search, you could also find the index i where the item should be inserted and insert it there using list.add(i,6). Which would be more efficient.

Body:
Here is my code

import java.util.*;

public class ArrayExample {
    public static void main(String[] args) {
        Integer arr[] = {5,4,3,2,15,8,9};
        List<Integer> list = Arrays.asList(arr);
        Collections.sort(list);
        System.out.println(list);
        list.add(6);// here I am adding 6 to my array.
        System.out.println(list);
        // Here I should get output as [2,3,4,5,6,8,9,15]
    }
}


问:
order of precedence of Sling run modes
I have a doubt over this question

```<code>Question: What is the correct order of precedence to setup runmodes in aem? (From left to right, left beign the highest)?

A. System property, Sling properties file, jar file
B. jar file, sling properties file, system property
C. Sling properties file, jar file, system property
D. jar file, System property, Sling properties file

Answer : B
</code>```

I had gone through various docs and had done multiple experiments over this.

Acc to Adobe documentation the order is - Sling.properties, System property, jar file

Similarly, this Adobe doc has a contradictory opinion - jar file, sling.properties, system property

Also, Apache Sling Doc says that any property to option D (-D) set in manner, n=v, overwrites same named properties in the sling.properties file. which means system property has higher precedence then sling.properties.

Now,  these are all according to docs, what I had experimented is-

I made a path ${dir}/crx-quickstart/conf and created a file sling.properties and wrote sling.run.modes=publish. Then renamed the jar file as cq-author-7502.jar. Then run this jar with the command java -jar cq-author-7502.jar -Dsling.run.modes=prod

This is my observation:

1. When the jar runs, Setting 'sling.run.modes' to 'publish' from sling.properties. this message is shown in the terminal.

2. The instance up in author mode. And

3. When I checked the instance-mode in felix console, it was prod

I am totally confused about the order of precedence. As everything seems contradictory to me.

It would be grateful if anyone can put some light on it..

Thank you

答:
There are two conflicting Adobe articles that say something quite different

Article 1: (Assumed more recent)

Starting CQ with a specific run mode If you have defined
  configurations for multiple run modes then you need to define which is
  to be used upon startup. There are several methods for specifying
  which run mode to use; the order of resolution is:

sling.properties file

  -r option

  system properties (-D)

  Filename detection

From this Reference: Configure Run Modes
   - the answer is C

Article 2:

Behavior when run modes are specified more than one way The run mode
  specified in the naming of the jar file takes precedence. If run modes
  are not specified in the naming of the jar file, the values in the
  sling.properties file are used. If run modes are not specified in
  either the naming of the jar file or the sling.properties file, the
  system property (or JVM argument) is used.

From this Reference: Configure Run Modes
   - the answer is B

However based on my experience and based on process of elimination I'd go with answer B.

Title: order of precedence of Sling run modes

Body:
I have a doubt over this question

Question: What is the correct order of precedence to setup runmodes in aem? (From left to right, left beign the highest)?

A. System property, Sling properties file, jar file
B. jar file, sling properties file, system property
C. Sling properties file, jar file, system property
D. jar file, System property, Sling properties file

Answer : B

I had gone through various docs and had done multiple experiments over this.

Acc to Adobe documentation the order is - Sling.properties, System property, jar file

Similarly, this Adobe doc has a contradictory opinion - jar file, sling.properties, system property

Also, Apache Sling Doc says that any property to option D (-D) set in manner, n=v, overwrites same named properties in the sling.properties file. which means system property has higher precedence then sling.properties.

Now,  these are all according to docs, what I had experimented is-

I made a path ${dir}/crx-quickstart/conf and created a file sling.properties and wrote sling.run.modes=publish. Then renamed the jar file as cq-author-7502.jar. Then run this jar with the command java -jar cq-author-7502.jar -Dsling.run.modes=prod

This is my observation:

1. When the jar runs, Setting 'sling.run.modes' to 'publish' from sling.properties. this message is shown in the terminal.

2. The instance up in author mode. And

3. When I checked the instance-mode in felix console, it was prod

I am totally confused about the order of precedence. As everything seems contradictory to me.

It would be grateful if anyone can put some light on it..

Thank you


问:
Finding label of a property
I am trying to find label of a property on dbpedia with this query

```<code>PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>
SELECT
    ?label
WHERE {
    geo:lat rdfs:label ?label.
} LIMIT 20
</code>```

But it does not return anything. I've checked wgs84 ontology, and lat has the label latitutde. Why doesn't it work, and how would I go about finding properties labels in general?

答:
I've checked wgs84 ontology, and lat has the label latitutde [sic].

That doesn't mean that DBpedia includes all the triples that that ontology specifies.  If DBpedia doesn't include that data, then you'd need to look for it in places where it is available.  DBpedia doesn't include any triples with geo:lat as subject or object, as shown by the zero results to this query:

```<code>select * where {
  { geo:lat ?p ?o }
  union
  { ?s ?p geo:lat }
}
</code>```

DBpedia just happens to include triples where geo:lat is used as a predicate.  For more information about the predicate, you'll have to look to where it's defined.

Title: Finding label of a property

Body:
I am trying to find label of a property on dbpedia with this query

PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>
SELECT
    ?label
WHERE {
    geo:lat rdfs:label ?label.
} LIMIT 20

But it does not return anything. I've checked wgs84 ontology, and lat has the label latitutde. Why doesn't it work, and how would I go about finding properties labels in general?

Body:
I've checked wgs84 ontology, and lat has the label latitutde [sic].

That doesn't mean that DBpedia includes all the triples that that ontology specifies.  If DBpedia doesn't include that data, then you'd need to look for it in places where it is available.  DBpedia doesn't include any triples with geo:lat as subject or object, as shown by the zero results to this query:

select * where {
  { geo:lat ?p ?o }
  union
  { ?s ?p geo:lat }
}

DBpedia just happens to include triples where geo:lat is used as a predicate.  For more information about the predicate, you'll have to look to where it's defined.


问:
How to specify regex replacement for different capturing groups in F#
I'm writing a md2html compiler in F# and I want to replace the ** surrounding texts with  and  tags.

e.g.
this is **bold** will be changed to this is bold

I am trying to accomplish this with Regex.Replace method using the pattern (\*\*).*?(\*\*). So the first capturing group will be replaced by  and the second one will be replaced by  I would like to know how I can specify the replacement for these different "capturing groups" rather than the entire regex match?

答:
Just use this regex: \*\*(.*?)\*\* and replace the matches with $1

Explanation:

\*\* matches ** literally.

( starts a capture group.

.* just matches everything it can get that isn't a new line.

? this makes the .* lazy, so that it doesn't match other bold text.

) ends the capture group.

\*\* matches ** literally.

Body:
Just use this regex: \*\*(.*?)\*\* and replace the matches with <b>$1</b>

Explanation:

\*\* matches ** literally.

( starts a capture group.

.* just matches everything it can get that isn't a new line.

? this makes the .* lazy, so that it doesn't match other bold text.

) ends the capture group.

\*\* matches ** literally.


答:
You can't because this declaration :

```<code>List<Integer> list = Arrays.asList(arr);
</code>```

From documentation :

Arrays.asList Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)
  This method acts as bridge between array-based and collection-based
  APIs, in combination with Collection.toArray(). The returned list is
  serializable and implements RandomAccess.

for that you can't add to this list, even if you try to remove list.remove(index); this not work.

so to solve your problem you can use :

```<code>List<Integer> list = new ArrayList<>();//declare the list
for(Integer i : arr){
    list.add(i);//add element by element to the list
}
</code>```

Or simply you can use :

```<code>List<Integer> list = new ArrayList<>(Arrays.asList(arr));
//----------------------------------^------------------^
</code>```

Title: I wanted to add an element to my array after sorting the array

Body:
You can't because this declaration :

List<Integer> list = Arrays.asList(arr);

From documentation :

Arrays.asList Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)
  This method acts as bridge between array-based and collection-based
  APIs, in combination with Collection.toArray(). The returned list is
  serializable and implements RandomAccess.

for that you can't add to this list, even if you try to remove list.remove(index); this not work.

so to solve your problem you can use :

List<Integer> list = new ArrayList<>();//declare the list
for(Integer i : arr){
    list.add(i);//add element by element to the list
}

Or simply you can use :

List<Integer> list = new ArrayList<>(Arrays.asList(arr));
//----------------------------------^------------------^


答:
Answer 1:

You have to set a fixed height to the img parent div and then set height:100% to the img Check below Snippet:

.haberImg {
    height: 75px;
}

.haberImg img {
    height: 100%;
    width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="row">

  <div class="down-content">
    <div class="haber">

      <!--HABER 1-->
      <div class="col-xs-3">
        <div id="haber1">
          <div id="haberimg1" class="haberImg">
            <img class="img-responsive" src="http://www.avukatwebsite.net/public/_uploads/photos/temalar/avukat-web-site-tema-1.jpg"></div>
          <div id="haberyazi1">
            <h3>Kanser Affetmedi...</h3>
            <p>Sanssiz genc Kanser yüzünden öldü...</p>
            <button type="button" class="btn">Devamini Oku...</button>
          </div>
        </div>
      </div>

      <!--HABER 2-->
      <div class="col-xs-3">
        <div id="haber2">
          <div id="haberimg2" class="haberImg">
            <img class="img-responsive" src="http://medicare.bold-themes.com/clinic/wp-content/uploads/sites/2/2015/12/shutterstock_288977717-1200x800.jpg"></div>
          <div id="haberyazi2">
            <h3>Sizofreni Salgini</h3>
            <p>Türkiyede ki Sizofren sayisinda artis görüldü...</p>
            <button type="button" class="btn">Devamini Oku...</button>
          </div>
        </div>
      </div>
    </div>
  </div></code>```

Answer 2:

You have to set a fixed height to the img parent div as the smallest img height and then add overflow:hidden.  Check below Snippet:

.haberImg {
    height: 80px;
    overflow:hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="row">

  <div class="down-content">
    <div class="haber">

      <!--HABER 1-->
      <div class="col-xs-3">
        <div id="haber1">
          <div id="haberimg1" class="haberImg">
            <img class="img-responsive" src="http://www.avukatwebsite.net/public/_uploads/photos/temalar/avukat-web-site-tema-1.jpg"></div>
          <div id="haberyazi1">
            <h3>Kanser Affetmedi...</h3>
            <p>Sanssiz genc Kanser yüzünden öldü...</p>
            <button type="button" class="btn">Devamini Oku...</button>
          </div>
        </div>
      </div>

      <!--HABER 2-->
      <div class="col-xs-3">
        <div id="haber2">
          <div id="haberimg2" class="haberImg">
            <img class="img-responsive" src="http://medicare.bold-themes.com/clinic/wp-content/uploads/sites/2/2015/12/shutterstock_288977717-1200x800.jpg"></div>
          <div id="haberyazi2">
            <h3>Sizofreni Salgini</h3>
            <p>Türkiyede ki Sizofren sayisinda artis görüldü...</p>
            <button type="button" class="btn">Devamini Oku...</button>
          </div>
        </div>
      </div>
    </div>
  </div></code>```

Title: How to make same height of all responsive images in a row

Body:
Answer 1:

You have to set a fixed height to the img parent div and then set height:100% to the img Check below Snippet:

.haberImg {
    height: 75px;
}

.haberImg img {
    height: 100%;
    width: 100%;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="row">

  <div class="down-content">
    <div class="haber">

      <!--HABER 1-->
      <div class="col-xs-3">
        <div id="haber1">
          <div id="haberimg1" class="haberImg">
            <img class="img-responsive" src="http://www.avukatwebsite.net/public/_uploads/photos/temalar/avukat-web-site-tema-1.jpg"></div>
          <div id="haberyazi1">
            <h3>Kanser Affetmedi...</h3>
            <p>Sanssiz genc Kanser yüzünden öldü...</p>
            <button type="button" class="btn">Devamini Oku...</button>
          </div>
        </div>
      </div>

      <!--HABER 2-->
      <div class="col-xs-3">
        <div id="haber2">
          <div id="haberimg2" class="haberImg">
            <img class="img-responsive" src="http://medicare.bold-themes.com/clinic/wp-content/uploads/sites/2/2015/12/shutterstock_288977717-1200x800.jpg"></div>
          <div id="haberyazi2">
            <h3>Sizofreni Salgini</h3>
            <p>Türkiyede ki Sizofren sayisinda artis görüldü...</p>
            <button type="button" class="btn">Devamini Oku...</button>
          </div>
        </div>
      </div>
    </div>
  </div>

Answer 2:

You have to set a fixed height to the img parent div as the smallest img height and then add overflow:hidden.  Check below Snippet:

.haberImg {
    height: 80px;
    overflow:hidden;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="row">

  <div class="down-content">
    <div class="haber">

      <!--HABER 1-->
      <div class="col-xs-3">
        <div id="haber1">
          <div id="haberimg1" class="haberImg">
            <img class="img-responsive" src="http://www.avukatwebsite.net/public/_uploads/photos/temalar/avukat-web-site-tema-1.jpg"></div>
          <div id="haberyazi1">
            <h3>Kanser Affetmedi...</h3>
            <p>Sanssiz genc Kanser yüzünden öldü...</p>
            <button type="button" class="btn">Devamini Oku...</button>
          </div>
        </div>
      </div>

      <!--HABER 2-->
      <div class="col-xs-3">
        <div id="haber2">
          <div id="haberimg2" class="haberImg">
            <img class="img-responsive" src="http://medicare.bold-themes.com/clinic/wp-content/uploads/sites/2/2015/12/shutterstock_288977717-1200x800.jpg"></div>
          <div id="haberyazi2">
            <h3>Sizofreni Salgini</h3>
            <p>Türkiyede ki Sizofren sayisinda artis görüldü...</p>
            <button type="button" class="btn">Devamini Oku...</button>
          </div>
        </div>
      </div>
    </div>
  </div>


问:
How can I select a specific tag in two different HTML structure?
I have two different HTML structure and I cannot change them. Now I need to write a jQuery code to get the href attribute of one specific  in them. Here is my code:

$(document).on('click', '.myclass', function(e){
  e.preventDefault(e);

  var url = $(this).attr('href');
  console.log(url);

  $(this).closest('li').css('background-color','#f1f1f1');
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li{
  border: 1px solid gray;
}

a{
  display:block;
}

.myclass{
    cursor: pointer;
}</code>```

HTML1:

    sth
    something
    link

HTML2:

    something

sth

```
</div>
</div>
</p>

<p>Ok, let me explain. I want two things happen when the user clicks on <code>.myclass</code> element: <em>(as you see, <code>.myclass</code> element is different in two HTML structures)</em></p>

<ul>
<li><p>Setting a pale gray color to the background of <code>li</code>.</p></li>
<li><p>Printing the <code>href</code> value of the link in the console.</p></li>
</ul>

<p>My current code works correctly for the first HTML structure <em>(but not for the second one)</em>. </p>

<hr>

<p><strong>Note:</strong> For the second one, jQuery code should look like this:</p>

``` $(document).on('click', '.myclass', function(e){
  e.preventDefault(e);

  var url = $(this).find('a').attr('href');
  console.log(url);

  $(this).css('background-color','#f1f1f1');
})
```

See? I've added find('a') (there is always one  in the second kind of HTML) and removed closest('li').

Anyway, how can I write one jQuery code instead of both above?

答:
I am not very clear about the problem at hand, but tried this</p>

```<code>$(document).on('click', '.myclass', function(e){
{
    e.stopPropagation();
    var x='';
    if(evt.target.tagName=="LI")
    {
        x = $(this).find('a.myclass').attr('href');
        $(this).css('background-color', '#f1f1f1');
    }
    else if(evt.target.tagName=="A")
    {
        x =  $(this).attr('href');
        $(this).parent("li").css('background-color', '#f1f1f1');
    }
    console.log(x);
});
</code>```

Body:
I have two different HTML structure and I cannot change them. Now I need to write a jQuery code to get the href attribute of one specific  in them. Here is my code:

$(document).on('click', '.myclass', function(e){
  e.preventDefault(e);

  var url = $(this).attr('href');
  console.log(url);

  $(this).closest('li').css('background-color','#f1f1f1');
})

li{
  border: 1px solid gray;
}

a{
  display:block;
}

.myclass{
    cursor: pointer;
}

HTML1:

    sth
    something
    link

HTML2:

    something

sth

Ok, let me explain. I want two things happen when the user clicks on .myclass element: (as you see, .myclass element is different in two HTML structures)

Setting a pale gray color to the background of li.

Printing the href value of the link in the console.

My current code works correctly for the first HTML structure (but not for the second one).

Note: For the second one, jQuery code should look like this:

 $(document).on('click', '.myclass', function(e){
  e.preventDefault(e);

  var url = $(this).find('a').attr('href');
  console.log(url);

  $(this).css('background-color','#f1f1f1');
})

See? I've added find('a') (there is always one  in the second kind of HTML) and removed closest('li').

Anyway, how can I write one jQuery code instead of both above?

Body:
I am not very clear about the problem at hand, but tried this

$(document).on('click', '.myclass', function(e){
{
    e.stopPropagation();
    var x='';
    if(evt.target.tagName=="LI")
    {
        x = $(this).find('a.myclass').attr('href');
        $(this).css('background-color', '#f1f1f1');
    }
    else if(evt.target.tagName=="A")
    {
        x =  $(this).attr('href');
        $(this).parent("li").css('background-color', '#f1f1f1');
    }
    console.log(x);
});


答:
You should capture what you need to keep. You need to just match what you need to replace.

Use \*\*(.*?)\*\* pattern and $1 replacement.

If you expect line breaks in between asterisks, use a singleline modifier (?s):  (?s)\*\*(.*?)\*\*

Title: How to specify regex replacement for different capturing groups in F#

Body:
I'm writing a md2html compiler in F# and I want to replace the ** surrounding texts with  and  tags.

e.g.
this is **bold** will be changed to this is bold

I am trying to accomplish this with Regex.Replace method using the pattern (\*\*).*?(\*\*). So the first capturing group will be replaced by  and the second one will be replaced by  I would like to know how I can specify the replacement for these different "capturing groups" rather than the entire regex match?

Body:
You should capture what you need to keep. You need to just match what you need to replace.

Use \*\*(.*?)\*\* pattern and <b>$1</b> replacement.

If you expect line breaks in between asterisks, use a singleline modifier (?s):  (?s)\*\*(.*?)\*\*


问:
non blocking write to file in c/c++
I'm writing a logging program, and I need to read from serial once a second then print to a log file.
The problem is that sometimes, something is holding up my loop and data is getting backed up. After timing every activity in my loop, I noticed that the function that prints my data to the log file is the one taking up too much time sometimes. I was looking into non-blocking write to file, and according to this post:

File writing with overlapped IO vs file writing in a separate thread

The "write to files" should not be blocking my program by default. But it seems like they are.

I'm using MS visual studio EX and I'm writing a consol c++ app. Can someone tell me if fprintf and << are supposed to be non-blocking/asynchronous by default? If not, is there a way to make them so?

答:
Based on your description, it looks like you are writing too little data too many times.
If the IO activity is high, it can cause delays on the buffered file I/O. As mentioned before you can use memory based files or use block writes.
The idea is to reduce the number of writes by clubbing multiple writes in one shot, so instead of doing 10 write of 500 bytes, you do one write of 5k each.
In most of the OS the typical page size (and write size) is around 4k (not sure about windows).
So try some open source package or writing a wrapper that will reduce the # of writes.</p>

Title: non blocking write to file in c/c++


答:
The simplest way to do this is to capture the inner group instead of the surrounding ** and then use it in the replacement.

```<code>Regex.Replace("this is **bold**", "\*\*(.*?)\*\*", "<b>$1</b>")
</code>```

Regex.Replace doesn't replace captured groups, but the whole match.

Body:
The simplest way to do this is to capture the inner group instead of the surrounding ** and then use it in the replacement.

Regex.Replace("this is **bold**", "\*\*(.*?)\*\*", "<b>$1</b>")

Regex.Replace doesn't replace captured groups, but the whole match.


问:
Is this way is prefered to swap two variable without temp in c?
```<code>#include<stdio.h>

int main()
{

    int a=20,b=30;

    a=a+b;
    b=a-b;
    a=a-b;

    return 0;
}
</code>```

Can I use this program to swap both positive and negative values.

答:
There is no preferred way to swap two variables without using a temporary variable in C.

The preferred way to swap two variables in C is to use a temporary variable.

Swapping without using a temporary is an obsolete problem.  It might once have been an interesting problem back when we were writing (a) assembly language code for (b) machines with very few registers and not much memory.  But when we're writing in a higher level language like C, on a machine with ample memory and registers, there is nothing -- nothing! -- positive to be gained by trying to eliminate the temporary variable.

Asking "What's the best way to swap two variables without using a temporary?" is a lot like asking "What's the best way to get my horse to pull my buggy without using a buggy whip?".

(Sorry for the opinionated answer, but while swapping without using temporaries might be an interesting intellectual problem, it is a an error-prone waste of time in any practical programming situation.  The likelihood that you will improve the performance of your program by eliminating the temporary is zero.  The likelihood that you will introduce subtle bugs is substantially nonzero.)

Body:
#include<stdio.h>

int main()
{

    int a=20,b=30;

    a=a+b;
    b=a-b;
    a=a-b;

    return 0;
}

Can I use this program to swap both positive and negative values.


问:
How to disable or hide acrobat reader bookmarks panel in winform?
I'm showing PDF documents in my application using Acrobat ActiveX. I want to know is it possible to disable or hide Bookmarks(and Pages,Search,Comments,Attachments in left of panel) on PDF adobe reader when showing pdf?</p>

答:
the solution is to add "#toolbar=0" ending path file, like this

```<code>axAcroPdf1.scr="c:/mifile.pdf"+"#toolbar=0"
</code>```

Also, you can add other properties seperating with "&"

Body:
the solution is to add "#toolbar=0" ending path file, like this

axAcroPdf1.scr="c:/mifile.pdf"+"#toolbar=0"

Also, you can add other properties seperating with "&"


问:
Selenium - ScrollIntoView - hiding element behind header/footer
Problem : ScrollIntoView hiding element behind header/footer . My application is having header/footer .

Tried following solutions :

1) ScrollIntoView(true) , it hiding web element behind header if element is up and tried to scroll from bottom .

2) Sending true/false  , it works , but I don't know exact location of element , so cant use every time to tell framework scroll down/up towards element .

3) Directly clicked ( taken action ) on element , chrome automatically scroll to visibility , but header is present that's why it hiding behind that .

Please let me know is there any single code that will make a element visible even it header/footer present .Looking solution is c# and using chrome browser .

答:
I have several suggestions to this:

Have you looked at the actions API, as described in this post (It is mainly targeted at Java, but the C# api is quite similar)

You might apply the following procedure:

Scroll the element into view

Find out if it is hiding behind the header or the footer

Scroll it downward by the height of the header, or upward by the height of the footer.

You can fetch its absolute position in the page, and scroll to there.