问:
Share image from SD Card
I'm trying for 2 weeks to find how to share images which are stored on an SD card with no success.

This answer doesn't work to me, nor is it what I'm looking for.

I'm working with Cam Preview app that stores images to SD and then display them in in-app gallery:

```<code>   public class GalleryView extends Activity {

   private static final int SELECT_PICTURE = 1;

private String selectedImagePath;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gallery_view);

    Gallery g = (Gallery) findViewById(R.id.gallery);
    g.setAdapter(new ImageAdapter(this, ReadSDCard()));

    g.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
        }
    });
}

  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);

            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.putExtra(Intent.EXTRA_STREAM, selectedImagePath);
            shareIntent.setType("image/*");
            startActivity(Intent.createChooser(shareIntent, "Share image"));
        }
    }
}

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

@Override
public void onDestroy() {
    super.onDestroy();
}

private List<String> ReadSDCard() {

    createDirIfNotExists();

    List<String> tFileList = new ArrayList<String>();

    //It have to be matched with the directory in SDCard
    File f = new File("/sdcard/Cam App");

    File[] files=f.listFiles();

    for(int i=0; i<files.length; i++) {
        File file = files[i];
        /*It's assumed that all file in the path are in supported type*/
        tFileList.add(file.getPath());
    }

    return tFileList;
}

class ViewHolder {
    ImageView i;
}

public class ImageAdapter extends BaseAdapter {
    int mGalleryItemBackground;
    private Context mContext;
    private List<String> FileList;
    LayoutInflater inflater = getLayoutInflater();
    ViewHolder holder;

    public ImageAdapter(Context c, List<String> fList) {
        mContext = c;
        FileList = fList;
        TypedArray a = obtainStyledAttributes(R.styleable.GalleryTheme);
        mGalleryItemBackground = a.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);
        a.recycle();
    }

    public int getCount() {
        return FileList.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView i = new ImageView(mContext);

        Bitmap bm = BitmapFactory.decodeFile(FileList.get(position).toString());
        i.setImageBitmap(bm);

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.gallery_item, parent, false);

            holder = new ViewHolder();
            holder.i = ((ImageView) convertView.findViewById(R.id.imagenGallery));

            convertView.setTag(holder);
        }
        holder.i.setScaleType(ImageView.ScaleType.FIT_XY);
        holder.i.setBackgroundResource(mGalleryItemBackground);

        return i;
    }
}

public TypedArray obtainStyledAttributes(int theme) {
    // TODO Auto-generated method stub
    return null;
}
}
</code>```

The gallery works fine, but I don't get how to share the images saved on the SD.

How to access that images in Cam App folder and share the image that appears in that moment in the gallery?

I tried to use positions, but it only works with constant images. Any help/tips would be appreciated.

答:
The following code works fine, If you know the path of that image

```<code>Intent shareit=new Intent(Intent.ACTION_SEND);
shareit.setType("image/jpeg");
File f = new File("imagepath");
shareit.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
startActivity(Intent.createChooser(shareit, "Share Image Via"));
</code>```

Create the file with image file name,

File f = new File(Environment.getExternalStorageDirectory() + File.separator + "image_file.jpg");

Title: Share image from SD Card

Body:
I'm trying for 2 weeks to find how to share images which are stored on an SD card with no success.

This answer doesn't work to me, nor is it what I'm looking for.

I'm working with Cam Preview app that stores images to SD and then display them in in-app gallery:

   public class GalleryView extends Activity {

   private static final int SELECT_PICTURE = 1;

private String selectedImagePath;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gallery_view);

    Gallery g = (Gallery) findViewById(R.id.gallery);
    g.setAdapter(new ImageAdapter(this, ReadSDCard()));

    g.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
        }
    });
}

  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);

            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.putExtra(Intent.EXTRA_STREAM, selectedImagePath);
            shareIntent.setType("image/*");
            startActivity(Intent.createChooser(shareIntent, "Share image"));
        }
    }
}

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

@Override
public void onDestroy() {
    super.onDestroy();
}

private List<String> ReadSDCard() {

    createDirIfNotExists();

    List<String> tFileList = new ArrayList<String>();

    //It have to be matched with the directory in SDCard
    File f = new File("/sdcard/Cam App");

    File[] files=f.listFiles();

    for(int i=0; i<files.length; i++) {
        File file = files[i];
        /*It's assumed that all file in the path are in supported type*/
        tFileList.add(file.getPath());
    }

    return tFileList;
}

class ViewHolder {
    ImageView i;
}

public class ImageAdapter extends BaseAdapter {
    int mGalleryItemBackground;
    private Context mContext;
    private List<String> FileList;
    LayoutInflater inflater = getLayoutInflater();
    ViewHolder holder;

    public ImageAdapter(Context c, List<String> fList) {
        mContext = c;
        FileList = fList;
        TypedArray a = obtainStyledAttributes(R.styleable.GalleryTheme);
        mGalleryItemBackground = a.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);
        a.recycle();
    }

    public int getCount() {
        return FileList.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView i = new ImageView(mContext);

        Bitmap bm = BitmapFactory.decodeFile(FileList.get(position).toString());
        i.setImageBitmap(bm);

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.gallery_item, parent, false);

            holder = new ViewHolder();
            holder.i = ((ImageView) convertView.findViewById(R.id.imagenGallery));

            convertView.setTag(holder);
        }
        holder.i.setScaleType(ImageView.ScaleType.FIT_XY);
        holder.i.setBackgroundResource(mGalleryItemBackground);

        return i;
    }
}

public TypedArray obtainStyledAttributes(int theme) {
    // TODO Auto-generated method stub
    return null;
}
}

The gallery works fine, but I don't get how to share the images saved on the SD.

How to access that images in Cam App folder and share the image that appears in that moment in the gallery?

I tried to use positions, but it only works with constant images. Any help/tips would be appreciated.

Body:
The following code works fine, If you know the path of that image

Intent shareit=new Intent(Intent.ACTION_SEND);
shareit.setType("image/jpeg");
File f = new File("imagepath");
shareit.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
startActivity(Intent.createChooser(shareit, "Share Image Via"));

Create the file with image file name,

File f = new File(Environment.getExternalStorageDirectory() + File.separator + "image_file.jpg");


来源: stackexchange

问:
goto vs. switch vs. your own way!! which is your choice for readability
you can notice that it may be flowchart or state machine transition

I am wondering which is the better option to implement the above flowchart of a algorithm.

I think go to is better solution.

How do you think so? I want to know your opinions.

[goto version]

```<code>main () {
    if ( condition == a )
        goto A:
    elif ( condition == b )
        B();
    elif ( condition == c )
        C();
    elif (condition == e )
        E();

    A:
    // do something

    B:
    if ( condition == c )
        // do something
        goto C;
    elif ( condition == d )
        // do somthing
        goto D;

    C:
    if ( condition == d )
        // do something
        goto D;

    D:
    if ( condition == a)
        // do something
        goto A;
    elif ( condition == e)
        // do something
        goto E;

    E:
        // do something

    return;
}
</code>```

[function call version with switch case grammar]

```<code>main () {
    switch (condition) {
        case a:
            A();
            break;
        case b:
            B();
            break;
        case c:
            C();
            break;
        case e:
            E();
            break;
    }
}

fuction A() {
    // do something

    switch (condition) {
        case b:
            B();
            break;
    }
}

function B() {
    // do something

    switch (condition) {
        case c:
            C();
            break;
        case d:
            D();
            break;
    }

}

function C() {
    // do something

    switch (condition) {
        case d:
            D();
            break;
        }

}

function D() {
    // do something

    switch (condition) {
        case a:
            A();
            break;
        case e:
            E();
            break;
    }
}

function E() {
    // do something
    return ;
}
</code>```

[add your way to implement and handle all the execution path]

答:
I think it's a lot better like this:

```<code>main () {
    if ( condition != a ) {
        if ( condition == b )
            B();
        elif ( condition == c )
            C();
        elif (condition == e )
            E();
    }

    for (;;) {
        // do something (A)

        if ( condition == c ) {
            // do something
            if ( condition == d )
                // do something
        }
        elif ( condition == d )
            // do somthing
        if ( condition != a)
            break;
        // do something
    }
    if ( condition == e)
        // do something

    // do something

    return;
}
</code>```

I'm pretty sure this is equivalent to your first version.  I'm not gonna verify that your second version is the same, because it's hard to read, and I wouldn't say that it necessarily implements the state machine you link to.

ContentLicense: CC BY-SA 3.0

Body:
you can notice that it may be flowchart or state machine transition

I am wondering which is the better option to implement the above flowchart of a algorithm.

I think go to is better solution.

How do you think so? I want to know your opinions.

[goto version]

main () {
    if ( condition == a )
        goto A:
    elif ( condition == b )
        B();
    elif ( condition == c )
        C();
    elif (condition == e )
        E();

    A:
    // do something

    B:
    if ( condition == c )
        // do something
        goto C;
    elif ( condition == d )
        // do somthing
        goto D;

    C:
    if ( condition == d )
        // do something
        goto D;

    D:
    if ( condition == a)
        // do something
        goto A;
    elif ( condition == e)
        // do something
        goto E;

    E:
        // do something

    return;
}

[function call version with switch case grammar]

main () {
    switch (condition) {
        case a:
            A();
            break;
        case b:
            B();
            break;
        case c:
            C();
            break;
        case e:
            E();
            break;
    }
}

fuction A() {
    // do something

    switch (condition) {
        case b:
            B();
            break;
    }
}

function B() {
    // do something

    switch (condition) {
        case c:
            C();
            break;
        case d:
            D();
            break;
    }

}

function C() {
    // do something

    switch (condition) {
        case d:
            D();
            break;
        }

}

function D() {
    // do something

    switch (condition) {
        case a:
            A();
            break;
        case e:
            E();
            break;
    }
}

function E() {
    // do something
    return ;
}

[add your way to implement and handle all the execution path]

Body:
I think it's a lot better like this:

main () {
    if ( condition != a ) {
        if ( condition == b )
            B();
        elif ( condition == c )
            C();
        elif (condition == e )
            E();
    }

    for (;;) {
        // do something (A)

        if ( condition == c ) {
            // do something
            if ( condition == d )
                // do something
        }
        elif ( condition == d )
            // do somthing
        if ( condition != a)
            break;
        // do something
    }
    if ( condition == e)
        // do something

    // do something

    return;
}

I'm pretty sure this is equivalent to your first version.  I'm not gonna verify that your second version is the same, because it's hard to read, and I wouldn't say that it necessarily implements the state machine you link to.


问:
How to add 2 buttons into the UINavigationbar on the right side without IB?
How can I add 2 buttons into the UINavigationBar without XIB?

The 2 buttons should be aligned on the right side of the UINavigationBar.

I know how I can add one button, but how about two?

答:
Here Is the Swift 4 code:

```<code>    let editImage   = UIImage(named: "plus")!
    let searchImage = UIImage(named: "search")!
    let editButton   = UIBarButtonItem(image: editImage,  style: .plain, target: self, action:#selector(didTapEditButton))
    let searchButton = UIBarButtonItem(image: searchImage,  style: .plain, target: self, action:#selector(didTapSearchButton))
    navigationItem.rightBarButtonItems = [editButton, searchButton]

 @objc func didTapEditButton(sender: AnyObject){

  }

 @objc func didTapSearchButton(sender: AnyObject){

  }
</code>```

Body:
Here Is the Swift 4 code:

    let editImage   = UIImage(named: "plus")!
    let searchImage = UIImage(named: "search")!
    let editButton   = UIBarButtonItem(image: editImage,  style: .plain, target: self, action:#selector(didTapEditButton))
    let searchButton = UIBarButtonItem(image: searchImage,  style: .plain, target: self, action:#selector(didTapSearchButton))
    navigationItem.rightBarButtonItems = [editButton, searchButton]

 @objc func didTapEditButton(sender: AnyObject){

  }

 @objc func didTapSearchButton(sender: AnyObject){

  }


问:
What is the easiest and fastest way of converting probabilities into prediction labels?
In short, I am looking for a one/two line code for following code:</p>

```<code>for i in range(A.shape[1]):

    # Convert probabilities A[0,i] to actual predictions p[0,i]
    ### START CODE HERE ### (≈ 4 lines of code)
    if(A[i] > .5)
       Y_prediction[i] = 1
    else
        Y_prediction[i] = 0
</code>```

答:
You want to convert the probability values to 0-1 labels. The assignment V_prediction[0, :] = A[0, :] > 0.5 should be enough for that; the boolean values A[0, :] > 0.5 (True/False) will become numbers 1, 0 if the target array V_prediction is numeric. An example:

```<code>V_prediction = np.zeros((3, 10))
A = np.random.uniform(size=(3, 10))
V_prediction[0, :] = A[0, :] > 0.5
</code>```

V_prediction is now (randomly)

```<code>array([[ 1.,  0.,  1.,  1.,  0.,  1.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])
</code>```

If all labels are integers, V_prediction could be declared with integer data type.

A more elaborate approach, which extends to more complex scenarios, is to use numpy.piecewise.

```<code>V_prediction[0, :] = np.piecewise(A[0, :], [A[0, :] > 0.5, A[0, :] <= 0.5], [0, 1])
</code>```

Body:
In short, I am looking for a one/two line code for following code:

for i in range(A.shape[1]):

    # Convert probabilities A[0,i] to actual predictions p[0,i]
    ### START CODE HERE ### (≈ 4 lines of code)
    if(A[i] > .5)
       Y_prediction[i] = 1
    else
        Y_prediction[i] = 0

Body:
You want to convert the probability values to 0-1 labels. The assignment V_prediction[0, :] = A[0, :] > 0.5 should be enough for that; the boolean values A[0, :] > 0.5 (True/False) will become numbers 1, 0 if the target array V_prediction is numeric. An example:

V_prediction = np.zeros((3, 10))
A = np.random.uniform(size=(3, 10))
V_prediction[0, :] = A[0, :] > 0.5

V_prediction is now (randomly)

array([[ 1.,  0.,  1.,  1.,  0.,  1.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])

If all labels are integers, V_prediction could be declared with integer data type.

A more elaborate approach, which extends to more complex scenarios, is to use numpy.piecewise.

V_prediction[0, :] = np.piecewise(A[0, :], [A[0, :] > 0.5, A[0, :] <= 0.5], [0, 1])


问:
Validation error "Column must be a valid timestamp"
So I am creating forms on oracle but I am unable to enter time into the TIMESTAMP field.. i am only able to enter date, if I even try to add time with date, It throws an error. Here is what it looks like:

so basically, It only allows me to enter date, but not the time..

and my datatype for deptime and arrivaltime is TIMESTAMP(6), In fact, when i enter values using sql statement, it does it perfectly fine with time.

答:
Oracle does not have intrinsic "formats" for columns of type DATE or TIMESTAMP - your table doesn't specify any format. The input/output format model is supplied by the application, in this case, Oracle Application Express (APEX).

On the item you can specify the Format Mask, e.g. DD-Mon-RRRR HH24:MI:SS


问:
Can't properly force a component on-screen with scrollComponentToVisible
On a given form, we replace one component with another.

The original component is a series of TextFields, and the new form is some informational text and a button. We hide the first one, and show the second one (the UI designer has both Containers within the form).

I tried using scrollRectToVisible with various values but it didn't seem to make any difference with the scrolling.

```<code> continueButtonContainer.setHidden(false);
 f.forceRevalidate();
 Button continueButton =
     (Button)StateMachine.GetInstance().findByName("ButtonContinue", f);
 f.scrollComponentToVisible(continueButtonContainer);
 f.scrollComponentToVisible(continueButton);
</code>```

I'm expecting the continue button to be near the top of the screen.

If the screen was scrolled before displaying the continue button, the button ends up right at the bottom of the screen (it was below the bottom of the screen before I put in the scrollComponentToVisible line(s).

After the user scrolls the screen, the button goes up to where it needs to be, and stays there.

If the screen is not scrolled, the button appears where it should be.

I know I can probably add some invisible containers underneath the button and force them onto the screen, but I would rather have a slightly more robust solution.

答:
There are a few issues with this. First you are using forceRevalidate which should be used in very rare cases.

Second it seems that you are invoking this on a Form, this is a bit misleading. While it seems that:

```<code>f.add(myCmp);
</code>```

Adds a component to the form it is really a synonym to:

```<code>f.getContentPane().add(myCmp);
</code>```

That's important because you need to invoke the scrollComponentToVisible on the scrollable container which will actually do the work and ideally be the direct parent of said component. I'm assuming it's the content pane in your case but it depends on layout etc.

The last part is letting the layout do its job. If you are invoking this before the form is showing this might not work. Notice that doing it after a call to show is meaningless as the form might take time with transitions. You can use a show listener or override the laidOut callback method to perform things like this.

Body:
On a given form, we replace one component with another.

The original component is a series of TextFields, and the new form is some informational text and a button. We hide the first one, and show the second one (the UI designer has both Containers within the form).

I tried using scrollRectToVisible with various values but it didn't seem to make any difference with the scrolling.

 continueButtonContainer.setHidden(false);
 f.forceRevalidate();
 Button continueButton =
     (Button)StateMachine.GetInstance().findByName("ButtonContinue", f);
 f.scrollComponentToVisible(continueButtonContainer);
 f.scrollComponentToVisible(continueButton);

I'm expecting the continue button to be near the top of the screen.

If the screen was scrolled before displaying the continue button, the button ends up right at the bottom of the screen (it was below the bottom of the screen before I put in the scrollComponentToVisible line(s).

After the user scrolls the screen, the button goes up to where it needs to be, and stays there.

If the screen is not scrolled, the button appears where it should be.

I know I can probably add some invisible containers underneath the button and force them onto the screen, but I would rather have a slightly more robust solution.

Body:
There are a few issues with this. First you are using forceRevalidate which should be used in very rare cases.

Second it seems that you are invoking this on a Form, this is a bit misleading. While it seems that:

f.add(myCmp);

Adds a component to the form it is really a synonym to:

f.getContentPane().add(myCmp);

That's important because you need to invoke the scrollComponentToVisible on the scrollable container which will actually do the work and ideally be the direct parent of said component. I'm assuming it's the content pane in your case but it depends on layout etc.

The last part is letting the layout do its job. If you are invoking this before the form is showing this might not work. Notice that doing it after a call to show is meaningless as the form might take time with transitions. You can use a show listener or override the laidOut callback method to perform things like this.


问:
Tortoise SVN/Windows 7 seems to have lost folders - completely stumped
Have Tortoise SVN (Shell Extension) and Slik SVN (Command line) installed on Windows 7.

Attached a USB drive, did a get on a 100GB source code library.  Tortoise sucked up 50% of CPU trying to keep it in synch, as it was a backup told Tortoise not to synch it.

Disconnected the USB drive.

Hooked it back up a few days later - my repository is gone.

Chkdsk /F -- no errors on drive.

Add up the total files, I get 320GB, but the drive shows 420GB in use so the repository is there alright.

I'd like my repository, or my 100GB back without having to reformat the drive.  No, it's not in the recycle bin...  No it's not a different user.  I have admin privs on the box anyway.

答:
Gave up and formatted the drive...

What I did was an svn get, and then told Tortoise SVN to exclude the drive, unplugged the drive, plugged it in a week later, nothing there.

ContentLicense: CC BY-SA 2.5


问:
C uint8_t array memory inaccessible in function call
I have a simple byte array structure:

```<code>typedef struct ByteArray {
    int size;
    uint8_t* arr;
} ByteArray;
</code>```

that I'm creating like this:

```<code>ByteArray* byte_array_create(size_t size) {
    ByteArray* a = malloc(sizeof(ByteArray));
    a->size = size;
    a->arr = (uint8_t*)malloc(a->size);
    return a;
}
</code>```

later I'm using this in another module like this:

```<code>static void rom_set_prg_bank(Rom* r, iNESHeader* h, FILE* romFile) {
    r->PRG = byte_array_create(h->numPRG * 0x4000);
    size_t size = fread(r->PRG->arr, r->PRG->size, 1, romFile);
    byte_array_print(r->PRG->arr);
}
</code>```

now inside of rom_set_prg_bank() r->PRG->arr has it's allocated memory and everything looks good.  I can look through the memory block and see everything.  As soon as I get into byte_array_print() I get a bad access error.

```<code>void byte_array_print(ByteArray* a) {
    for(int i = 0; i < a->size; i++) {
        // EXC_BAD_ACCESS (code=EXC_I386_GPFLT) happens
        // when I try to access any of the values in the
        // byte array
        printf(a->arr[i]);
    }
}
</code>```

Can anyone see what I'm doing wrong?

答:
```<code>byte_array_print(r->PRG->arr);
</code>```

passes the allocated buffer defined as an element of the ByteArray struct, but byte_array_print expects a pointer to the full ByteArray struct, not the buffer. Fix it with:

```<code>byte_array_print(r->PRG)
</code>```

Body:
I have a simple byte array structure:

typedef struct ByteArray {
    int size;
    uint8_t* arr;
} ByteArray;

that I'm creating like this:

ByteArray* byte_array_create(size_t size) {
    ByteArray* a = malloc(sizeof(ByteArray));
    a->size = size;
    a->arr = (uint8_t*)malloc(a->size);
    return a;
}

later I'm using this in another module like this:

static void rom_set_prg_bank(Rom* r, iNESHeader* h, FILE* romFile) {
    r->PRG = byte_array_create(h->numPRG * 0x4000);
    size_t size = fread(r->PRG->arr, r->PRG->size, 1, romFile);
    byte_array_print(r->PRG->arr);
}

now inside of rom_set_prg_bank() r->PRG->arr has it's allocated memory and everything looks good.  I can look through the memory block and see everything.  As soon as I get into byte_array_print() I get a bad access error.

void byte_array_print(ByteArray* a) {
    for(int i = 0; i size; i++) {
        // EXC_BAD_ACCESS (code=EXC_I386_GPFLT) happens
        // when I try to access any of the values in the
        // byte array
        printf(a->arr[i]);
    }
}

Can anyone see what I'm doing wrong?

Body:
byte_array_print(r->PRG->arr);

passes the allocated buffer defined as an element of the ByteArray struct, but byte_array_print expects a pointer to the full ByteArray struct, not the buffer. Fix it with:

byte_array_print(r->PRG)


问:
Spring Boot web cannot parse nested json to object
first of all, i am quite new to spring (web mvc). I am building a RESTful service for my frontend. I am sending a JSON data but one object in that data was not parsed when it is received by spring.

Here is my data

JSON Data

```<code>{
    "comments" : []
    "description": "Testing",
    "images": "[\"path1\", \"path2\", \"path3\"]",
    "profile": {
        "id": 21234,
        "fullname": "John Michael Doe",
        "nickname": "Doe",
        "email": "jdoe@email.com",
        "profilePic": "/some/host/pic"
    }
}
</code>```

RequestMapper

```<code>@RestController
@RequestMapping("/wish")
public class WishlistController extends WishlistConverter{

        /* Some @Autowired here for services... */

        @RequestMapping(method = RequestMethod.POST)
        public ResponseEntity<?> create(@RequestBody RestWishlist input){
            try {
                logger.info("create({})",input);
                Wishlist wish = convert(input);
                wishlistService.create(wish);
                return new ResponseEntity<>(HttpStatus.OK);
            } catch (Exception e) {
                logger.error("Error: {}",e.getMessage());
                return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
            }
        }
}
</code>```

RestWishlist

```<code>public class RestWishlist {

    private Long wishId;

    private List<RestComment> comments;

    private String description;

    private String images;

    private Long createdAt;

    private Long updatedAt;

    private RestProfile profile;

    /* Getters and Setters here */
}
</code>```

RestProfile

```<code>public class RestProfile {

    private Long id;

    private String fullname;

    private String nickname;

    private String email;

    private String profilePic;
    /* Getters and Setters Here */
}
</code>```

RestComment

```<code>public class RestComment {

    private Long commentId;

    private String description;

    private RestProfile profile;

    private Long createdAt;

    private Long updatedAt;
    /* Getters and Setters Here */
}
</code>```

Now, i have a problem getting the "profile" part of my JSON data, log file show this

```<code>2017-12-03 20:50:31.740  INFO 10212 --- [nio-8080-exec-1] c.s.s.web.controller.WishlistController  : create(RestWishlist [wishId=null, comments=[], description=Testing, images=["path1", "path2", "path3"], createAt=null, updatedAt=null])

2017-12-03 20:50:31.740  INFO 10212 --- [nio-8080-exec-1] c.s.s.services.impl.WishlistServiceImpl  : create(Wishlist [wishId=null, comments=[], description=Testing, images=["path1", "path2", "path3"], createAt=null, updatedAt=null])
</code>```

答:
So i've found the problem after days of tracing. it's a simple bug and really, for me, careless.

"profile" was correctly set from json data. the reason why it does not appear in the logs is because the toString() method in RestWishlist class does not contain the profile. See below

Before

```<code>@Override
public String toString() {
    return "RestWishlist [wishId=" + wishId + ", comments=" + comments + ", description=" + description
            + ", images=" + images + ", createdAt=" + createdAt + ", updatedAt=" + updatedAt + "]";
}
</code>```

After

```<code>@Override
public String toString() {
    return "RestWishlist [wishId=" + wishId + ", comments=" + comments + ", description=" + description
            + ", images=" + images + ", createdAt=" + createdAt + ", updatedAt=" + updatedAt + ", profile="
            + profile + "]";
}
</code>```

I only added the profile variable to be displayed in toString() method

Body:
first of all, i am quite new to spring (web mvc). I am building a RESTful service for my frontend. I am sending a JSON data but one object in that data was not parsed when it is received by spring.

Here is my data

JSON Data

{
    "comments" : []
    "description": "Testing",
    "images": "[\"path1\", \"path2\", \"path3\"]",
    "profile": {
        "id": 21234,
        "fullname": "John Michael Doe",
        "nickname": "Doe",
        "email": "jdoe@email.com",
        "profilePic": "/some/host/pic"
    }
}

RequestMapper

@RestController
@RequestMapping("/wish")
public class WishlistController extends WishlistConverter{

        /* Some @Autowired here for services... */

        @RequestMapping(method = RequestMethod.POST)
        public ResponseEntity<?> create(@RequestBody RestWishlist input){
            try {
                logger.info("create({})",input);
                Wishlist wish = convert(input);
                wishlistService.create(wish);
                return new ResponseEntity<>(HttpStatus.OK);
            } catch (Exception e) {
                logger.error("Error: {}",e.getMessage());
                return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
            }
        }
}

RestWishlist

public class RestWishlist {

    private Long wishId;

    private List<RestComment> comments;

    private String description;

    private String images;

    private Long createdAt;

    private Long updatedAt;

    private RestProfile profile;

    /* Getters and Setters here */
}

RestProfile

public class RestProfile {

    private Long id;

    private String fullname;

    private String nickname;

    private String email;

    private String profilePic;
    /* Getters and Setters Here */
}

RestComment

public class RestComment {

    private Long commentId;

    private String description;

    private RestProfile profile;

    private Long createdAt;

    private Long updatedAt;
    /* Getters and Setters Here */
}

Now, i have a problem getting the "profile" part of my JSON data, log file show this

2017-12-03 20:50:31.740  INFO 10212 --- [nio-8080-exec-1] c.s.s.web.controller.WishlistController  : create(RestWishlist [wishId=null, comments=[], description=Testing, images=["path1", "path2", "path3"], createAt=null, updatedAt=null])

2017-12-03 20:50:31.740  INFO 10212 --- [nio-8080-exec-1] c.s.s.services.impl.WishlistServiceImpl  : create(Wishlist [wishId=null, comments=[], description=Testing, images=["path1", "path2", "path3"], createAt=null, updatedAt=null])

Body:
So i've found the problem after days of tracing. it's a simple bug and really, for me, careless.

"profile" was correctly set from json data. the reason why it does not appear in the logs is because the toString() method in RestWishlist class does not contain the profile. See below

Before

@Override
public String toString() {
    return "RestWishlist [wishId=" + wishId + ", comments=" + comments + ", description=" + description
            + ", images=" + images + ", createdAt=" + createdAt + ", updatedAt=" + updatedAt + "]";
}

After

@Override
public String toString() {
    return "RestWishlist [wishId=" + wishId + ", comments=" + comments + ", description=" + description
            + ", images=" + images + ", createdAt=" + createdAt + ", updatedAt=" + updatedAt + ", profile="
            + profile + "]";
}

I only added the profile variable to be displayed in toString() method


问:
Practicing Java, need help finding the output
I am looking to find the output of the following code.

Suppose that myStack is a linked implementation of a stack of Integers.
What would the output be for this code?

```<code>myStack.push(new Integer(1));
myStack.push(new Integer(2));
System.out.println(myStack.pop());
System.out.println(myStack.pop());
System.out.println(myStack.pop());
</code>```

答:
If this is the only code, then I believe it should throw a run time exception because you try to pop an element out of a stack when the stack size is zero.

So your output would be something like:

```<code>2
1
Error!!!!
</code>```

Though that third line really depends on how your pop() method handles a stack with zero size.

Body:
I am looking to find the output of the following code.

Suppose that myStack is a linked implementation of a stack of Integers.
What would the output be for this code?

myStack.push(new Integer(1));
myStack.push(new Integer(2));
System.out.println(myStack.pop());
System.out.println(myStack.pop());
System.out.println(myStack.pop());

Body:
If this is the only code, then I believe it should throw a run time exception because you try to pop an element out of a stack when the stack size is zero.

So your output would be something like:

2
1
Error!!!!

Though that third line really depends on how your pop() method handles a stack with zero size.


问:
splitting a data frame by date and computing median for all rows with each date
I am attempting to roughly estimate that amount of work than could have been done by staff for a given month.

I've got a csv that looks roughly like this (although it's a lot bigger):

```<code>+--------+-------+---------------+
|  Date  | Name  | Units of Work |
+--------+-------+---------------+
| 1/1/17 | Bob   |           450 |
| 2/1/17 | Alice |           300 |
| 2/1/17 | Bob   |           450 |
| 2/1/17 | Larry |            50 |
| 3/1/17 | Alice |           400 |
| 3/1/17 | Bob   |            11 |
| 3/1/17 | Larry |           100 |
| 4/1/17 | Alice |          1000 |
| 4/1/17 | Bob   |           240 |
| 4/1/17 | Larry |            33 |
+--------+-------+---------------+
</code>```

I want to:

Compute the median 'Units of work' for each 'Date'

Determine if any 'Name' did less than 20% of the median 'Units of work' for that 'Date'

Remove 'Name' if it did fewer than 20% of the median

Multiply the count of 'Name' left for the 'Date' by the median 'Units of work' for that 'Date'

Output a new csv that has each 'Date', appearing only once, on its own row, and that date's median 'Units of work' multiplied by the remaining 'Name' for that 'Date'

I can't even meet requirement 1, much less 2 through 5.  I'm getting one file for each date.  And instead of a column with the median, I get a new column called 'NewColumn' filled with the word 'median', like so:

```<code># -*- coding: utf-8 -*-
import pandas as pd
df = pd.read_csv('source.csv')
df = df.sort_values('date_trunc').assign(NewColumn='median')
df.median(axis=None, skipna=None, level=None, numeric_only=None)
for i, g in df.groupby('date_trunc'):
    g.to_csv('{}.csv'.format(i), header=True, index_label=False, index=False)
    +---------+-------+---------------+-----------+
    |  Date   | Name  | Units of work | NewColumn |
    +---------+-------+---------------+-----------+
    | 12/1/16 | Alice |          6222 | median    |
    | 12/1/16 | Bob   |         14530 | median    |
    | 12/1/16 | Larry |         16887 | median    |
    +---------+-------+---------------+-----------+
</code>```

I know I'm probably doing a lot wrong here, but I'd really appreciate some guidance.

What I want to end up with is a single csv with this:

```<code>+---------+--------+
|  Date   | Median |
+---------+--------+
| 12/1/16 |   1110 |
| 1/1/17  |   1400 |
| 2/1/17  |   1200 |
+---------+--------+
</code>```

答:
I'm around 80% sure I didn't understand the goal perfectly, but here's my attempt.</p>

```<code>import pandas as pd

df = pd.DataFrame({"Date": ["Jan-12", "Jan-12"], "Name": ["Bob", "Alice"], "Work": [400, 300]})

def extract_rows_with_date(df, date):
    return df[df["Date"] == date]

# Extract unique dates
dates = df.Date.unique()

# Creating an empty dataframe dictionary (you get it)
new_df = {"Date": [], "Median": []}

for date in dates:
    # Fun stuff here
    date_df = extract_rows_with_date(df, date)
    median = date_df["Work"].median()

    above_20_median = date_df[date_df["Work"] > (median*20)/100]

    count_above_median = above_20_median.shape[0]

    new_df["Date"].append(date)
    new_df["Median"].append(count_above_median * median)

new_df = pd.DataFrame(new_df)
print(new_df.head())
</code>```

Body:
I am attempting to roughly estimate that amount of work than could have been done by staff for a given month.

I've got a csv that looks roughly like this (although it's a lot bigger):

+--------+-------+---------------+
|  Date  | Name  | Units of Work |
+--------+-------+---------------+
| 1/1/17 | Bob   |           450 |
| 2/1/17 | Alice |           300 |
| 2/1/17 | Bob   |           450 |
| 2/1/17 | Larry |            50 |
| 3/1/17 | Alice |           400 |
| 3/1/17 | Bob   |            11 |
| 3/1/17 | Larry |           100 |
| 4/1/17 | Alice |          1000 |
| 4/1/17 | Bob   |           240 |
| 4/1/17 | Larry |            33 |
+--------+-------+---------------+

I want to:

Compute the median 'Units of work' for each 'Date'

Determine if any 'Name' did less than 20% of the median 'Units of work' for that 'Date'

Remove 'Name' if it did fewer than 20% of the median

Multiply the count of 'Name' left for the 'Date' by the median 'Units of work' for that 'Date'

Output a new csv that has each 'Date', appearing only once, on its own row, and that date's median 'Units of work' multiplied by the remaining 'Name' for that 'Date'

I can't even meet requirement 1, much less 2 through 5.  I'm getting one file for each date.  And instead of a column with the median, I get a new column called 'NewColumn' filled with the word 'median', like so:

# -*- coding: utf-8 -*-
import pandas as pd
df = pd.read_csv('source.csv')
df = df.sort_values('date_trunc').assign(NewColumn='median')
df.median(axis=None, skipna=None, level=None, numeric_only=None)
for i, g in df.groupby('date_trunc'):
    g.to_csv('{}.csv'.format(i), header=True, index_label=False, index=False)
    +---------+-------+---------------+-----------+
    |  Date   | Name  | Units of work | NewColumn |
    +---------+-------+---------------+-----------+
    | 12/1/16 | Alice |          6222 | median    |
    | 12/1/16 | Bob   |         14530 | median    |
    | 12/1/16 | Larry |         16887 | median    |
    +---------+-------+---------------+-----------+

I know I'm probably doing a lot wrong here, but I'd really appreciate some guidance.

What I want to end up with is a single csv with this:

+---------+--------+
|  Date   | Median |
+---------+--------+
| 12/1/16 |   1110 |
| 1/1/17  |   1400 |
| 2/1/17  |   1200 |
+---------+--------+

Body:
I'm around 80% sure I didn't understand the goal perfectly, but here's my attempt.

import pandas as pd

df = pd.DataFrame({"Date": ["Jan-12", "Jan-12"], "Name": ["Bob", "Alice"], "Work": [400, 300]})

def extract_rows_with_date(df, date):
    return df[df["Date"] == date]

# Extract unique dates
dates = df.Date.unique()

# Creating an empty dataframe dictionary (you get it)
new_df = {"Date": [], "Median": []}

for date in dates:
    # Fun stuff here
    date_df = extract_rows_with_date(df, date)
    median = date_df["Work"].median()

    above_20_median = date_df[date_df["Work"] > (median*20)/100]

    count_above_median = above_20_median.shape[0]

    new_df["Date"].append(date)
    new_df["Median"].append(count_above_median * median)

new_df = pd.DataFrame(new_df)
print(new_df.head())


问:
How to Add a Scrollbar to Window in C#
I have created a window as follows:

```<code>Window myWindow = new Window();
</code>```

How can I add a Vertical Scroll Bar to this Windows and make the Scroll Bar only visible if the Height isn't large enough to show all the elements.

答:
try this</p>

```<code>var xpage = your user control or page to which scroll bar need to be added at runtime

            xpage.SetValue(ScrollViewer.CanContentScrollProperty, true);
            xpage.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Auto);
            xpage.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Auto);

            var scrollViewer = xpage.Content as ScrollViewer;
            if (scrollViewer != null)
            {
                var content = scrollViewer.Content;
                scrollViewer.Content = null;
                xpage.Content = content;
            }
            else
            {
                var content = xpage.Content;
                xpage.Content = null;
                xpage.Content = new ScrollViewer { Content = content };
            }
</code>```

Title: How to Add a Scrollbar to Window in C#

Body:
I have created a window as follows:

Window myWindow = new Window();

How can I add a Vertical Scroll Bar to this Windows and make the Scroll Bar only visible if the Height isn't large enough to show all the elements.

Body:
try this

var xpage = your user control or page to which scroll bar need to be added at runtime

            xpage.SetValue(ScrollViewer.CanContentScrollProperty, true);
            xpage.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Auto);
            xpage.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Auto);

            var scrollViewer = xpage.Content as ScrollViewer;
            if (scrollViewer != null)
            {
                var content = scrollViewer.Content;
                scrollViewer.Content = null;
                xpage.Content = content;
            }
            else
            {
                var content = xpage.Content;
                xpage.Content = null;
                xpage.Content = new ScrollViewer { Content = content };
            }


问:
Laravel Subdomain and Valet
I have a site that will have a forward facing public version and an auth user side. I am trying to test it locally so I have anything at the root domain point to one view and the subdomain point to another view. The trouble is they both point to the welcome view.

web routes

```<code>Route::get('/', function () {
    return view('welcome');
});

Route::domain('pro.scorecard.dev')->group(function () {

    Route::get('/', function() {
        return view('app.dashboard');
    });

});
</code>```

I also ran:

valet link pro.scorecard

But if I go to pro.scorecard.dev or scorecard.dev they both show the view welcome.blade.php

答:
Switch the routes as :</p>

```<code>Route::domain('pro.scorecard.dev')->group(function () {
    Route::get('/', function() {
        return view('app.dashboard');
    });
});

Route::get('/', function () {
    return view('welcome');
});
</code>```

Title: Laravel Subdomain and Valet

Body:
I have a site that will have a forward facing public version and an auth user side. I am trying to test it locally so I have anything at the root domain point to one view and the subdomain point to another view. The trouble is they both point to the welcome view.

web routes

Route::get('/', function () {
    return view('welcome');
});

Route::domain('pro.scorecard.dev')->group(function () {

    Route::get('/', function() {
        return view('app.dashboard');
    });

});

I also ran:

valet link pro.scorecard

But if I go to pro.scorecard.dev or scorecard.dev they both show the view welcome.blade.php

Body:
Switch the routes as :

Route::domain('pro.scorecard.dev')->group(function () {
    Route::get('/', function() {
        return view('app.dashboard');
    });
});

Route::get('/', function () {
    return view('welcome');
});


问:
DNN web.config loginUrl
I'm running DNN Version 9 and for some reason pages are being redirected to the root and not to the loginUrl specified in the web.config file. This is causing an endless redirect loop. (i.e. my root www.example.com has view permissions for registered users only - this should redirect to www.example.com/Login if not authenticated)</p>

答:
You wouldn't typically configure the LOGIN url in the web.config file for DNN. You might look at your LOGIN page setting in the database.

You can try running this query to check how the login page is configured currently

```<code>select logintabid, * from portallocalization
</code>```

You can remove the setting by running this QUERY on your database.

```<code>update portallocalization
set logintabid = null

where portalid=0 --assuming your portalid is 0
</code>```

That will typically address login page/settings that have gone awry.

Title: DNN web.config loginUrl

Body:
You wouldn't typically configure the LOGIN url in the web.config file for DNN. You might look at your LOGIN page setting in the database.

You can try running this query to check how the login page is configured currently

select logintabid, * from portallocalization

You can remove the setting by running this QUERY on your database.

update portallocalization
set logintabid = null

where portalid=0 --assuming your portalid is 0

That will typically address login page/settings that have gone awry.


问:
Android getExternalFilesDir get removed on app update
I'm saving pictures related to my app inside External files directory so In Gallery app Device Folder can't access those photos. but when I update app it removes the all data in the following directory.

/storage/emulated/0/Android/data/AppPackage/files

Got this path by the following line of code.

mContext.getExternalFilesDir(null)

Is there any way to stop this folder get removed on app update?

On app Uninstall can I show a warning dialog to user about data get deleted?

答:
here are two things

1) Installing build from android studio, as android studio uninstall the previous build and then install new one that is the actual reason that app folder got removed in the first place.

2) Updating app from playstore doesn't remove app data folder.


问:
How to find week date ranges for a given month
I need to display a range of dates in corresponding week for selected month.
Suppose the selected values are $month=2 and $year=2017.
The output should show a list of ranged dates for weeks in that particular month selected.

```<code>$month = $_GET['month'];
$year = $_GET['year'];
 ...

Output:
Week 1: 01/02/2017 - 05/02/2017
Week 2: 06/02/2017 - 12/02/2017
Week 3: 13/02/2017 - 19/02/2017
Week 4: 20/02/2017 - 26/02/2017
Week 5: 27/02/2017 - 28/02/2017
</code>```

Ive look through Split the current month in to weeks in php , Get week number in month from date in PHP? and Split date ranges into corresponding weeks , but none of them working for me.

Thanks.

答:
Try this:</p>

```<code><?php

$month = 12;
$year = 2017;

$date = new DateTime($year.'-'.$month.'-01');

$count = 1;
$week[$count]['start'] =  $date->format('Y-m-d');

while (1) {
    $date->modify('+1 day');
    if ($date->format('m') != $month) {
        $week[$count]['end'] = $date->format('Y-m-d');
        break;
    }

    if ($date->format('D') === 'Sun') {
        $week[$count++]['end'] = $date->format('Y-m-d');
    }

    if ($date->format('D') === 'Mon') {
        $week[$count]['start'] = $date->format('Y-m-d');
    }

}

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

Body:
I need to display a range of dates in corresponding week for selected month.
Suppose the selected values are $month=2 and $year=2017.
The output should show a list of ranged dates for weeks in that particular month selected.

$month = $_GET['month'];
$year = $_GET['year'];
 ...

Output:
Week 1: 01/02/2017 - 05/02/2017
Week 2: 06/02/2017 - 12/02/2017
Week 3: 13/02/2017 - 19/02/2017
Week 4: 20/02/2017 - 26/02/2017
Week 5: 27/02/2017 - 28/02/2017

Ive look through Split the current month in to weeks in php , Get week number in month from date in PHP? and Split date ranges into corresponding weeks , but none of them working for me.

Thanks.

Body:
Try this:

<?php

$month = 12;
$year = 2017;

$date = new DateTime($year.'-'.$month.'-01');

$count = 1;
$week[$count]['start'] =  $date->format('Y-m-d');

while (1) {
    $date->modify('+1 day');
    if ($date->format('m') != $month) {
        $week[$count]['end'] = $date->format('Y-m-d');
        break;
    }

    if ($date->format('D') === 'Sun') {
        $week[$count++]['end'] = $date->format('Y-m-d');
    }

    if ($date->format('D') === 'Mon') {
        $week[$count]['start'] = $date->format('Y-m-d');
    }

}

print_r($week);


问:
Can a DAWG be used to store word related information?
Can a DAWG be used to store auxiliary information relating to each path, e.g. a word's frequency in the English language? If yes, then how can i do that?</p>

答:
Yes you can. Each path from start of dawg to end of word is unique, and that path can be indexed as an integer. That index number can then be mapped to auxiliary information.

See the paper here: http://www.ic.unicamp.br/~reltech/1992/92-01.pdf
See the a good implementation here: https://github.com/WojciechMula/pyDAWG/blob/master/dawg_mph.c#L37


问:
Convert following code from C to VB.NET
Hey guys,

Can you please give me a hand to convert the following C code into VB.NET. I have a feeling it would be pretty simple... but my C knowledge is very very limited!

Any help would be great!

Thanks

```<code>buf[0] = (num1 & 0xff000000) >> 24;
buf[1] = (num1 & 0xff0000) >> 16;
buf[2] = (num1 & 0xff00) >> 8;
buf[3] =  num1 & 0xff;

buf[4] = (num2 & 0xff000000) >> 24;
buf[5] = (num2 & 0xff0000) >> 16;
buf[6] = (num2 & 0xff00) >> 8;
buf[7] =  num2 & 0xff;

strncpy(buf+8, headers->key3, 8);
buf[16] = '\0';

md5_buffer(buf, 16, target);
target[16] = '\0';
</code>```

答:
```<code>byte[] temp1 = BitConvert.GetBytes(num1);
byte[] temp2 = BitConvert.GetBytes(num2);

Array.Copy(temp1, 0, buf, 0, 4);
Array.Copy(temp2, 0, buf, 4, 4);

Array.Copy(buf, 8, headers.key3, 0, 8)
buf[16] = 0;

Array.Copy(buf, target, 16)
target[16] = 0;

Using MD5 hasher = new MD5CryptoServiceProvider()
    target = hasher.ComputeHash(buf);
End Using
</code>```

Title: Convert following code from C to VB.NET

Body:
Hey guys,

Can you please give me a hand to convert the following C code into VB.NET. I have a feeling it would be pretty simple... but my C knowledge is very very limited!

Any help would be great!

Thanks

buf[0] = (num1 & 0xff000000) >> 24;
buf[1] = (num1 & 0xff0000) >> 16;
buf[2] = (num1 & 0xff00) >> 8;
buf[3] =  num1 & 0xff;

buf[4] = (num2 & 0xff000000) >> 24;
buf[5] = (num2 & 0xff0000) >> 16;
buf[6] = (num2 & 0xff00) >> 8;
buf[7] =  num2 & 0xff;

strncpy(buf+8, headers->key3, 8);
buf[16] = '\0';

md5_buffer(buf, 16, target);
target[16] = '\0';


问:
How to consume a socket.io WebSocket API in C#
I need to consume a third-party WebSocket API in .NET Core and C#; the WebSocket server is implemented using socket.io (using protocol version 0.9), and I am having a hard time understanding how socket.io works... besides that the API requires SSL.

I found out that the HTTP handshake must be initiated via a certain path, which is...

```<code>socket.io/1/?t=...
</code>```

...whereby the value of the parameter t is a Unix-timestamp (in seconds). The service replies with a session-key, timeout information, and a list of supported transport protocols. Due to simplicity, this first request is made via HttpClient and does not involve any additional headers.

Next, another HTTP request is required, which should result in an HTTP 101 Switching Protocol response. I specified the following headers in accordance to the previous request...

```<code>Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Key: ...
Sec-WebSocket-Version: 13
</code>```

...whereby the value of the Key-header is a Base64-encoded GUID-value that the server will use to calculate the Sec-WebSocket-Accept header value. I also precalculate the expected Sec-WebSocket-Accept header value, for validation...

I tried to make that request using HttpClient as well, but that does not seem to work... I actually don´t understand why, because I expect an HTTP response. I also tried to make the request using TcpClient by sending a manually prepared GET request over a SslStream, which accepts the remote certificate as expected. Sending data seems to work, but there´s no response data... the Read-method returns zero.

What do I miss here? Do I need to setup a listener for the WebSocket connection as well, and if yes how? I don´t want to implement a feature complete socket.io client, I´d just like to keep it as simple as possible to catch some events...

答:
The best way of debugging these issues is to use a sniffer like wireshark or fiddler.  Often connect using an IE and compare IE results with my application and modify my app so it works like the IE.  Using WebClient instead of HttpClient will also work better because the WebClient does more automatically than the HttpClient.

A web connection uses the header of the client and the headers in the server webpage to negotiate a connection mode.  Adding additional headers to you client will change the connection mode.  Cookies are also used to select the connection mode.  Cookies are the results of previous connection to the same server which shortens the negotiations and stores info from previous connection so less data has to be downloaded from server.  The server remembers the cookies.  Cookies have a timeout and is kept until timeout expires. The IE history in your client has a list of IP addresses and Net automatically sends the cookies associated with the server IP.

If a bad connection is made to the server the cookies is also bad so the only was of connection is to remove the cookie.  Usually I go into the IE and delete cookies manually in the IE history.

To check if a response is good the server returns a status.  A completed response contains a status 200 DONE.  You can get status which are errors.  You can also get a 100 Continue which means you need to send another request to get the rest of the webpage.

Http has 1.0 (stream mode) and 1.1 (chunk mode).  Net library doesn't work with chunk.  Chunk requires client to send message to get next chunk and I have not found a way in Net to send the next chunk message.  So if a server responds with a 1.1 then you have to add to your client headers to use 1.0 only.

Http uses TCP as the transport layer.  So in a sniffer you will see TCP and HTTP.  Usually you can filter sniffer just to return Http and look at header for debugging.  Occasionally TCP disconnects and then you have to look at TCP to find why the disconnect occurs.

Body:
I need to consume a third-party WebSocket API in .NET Core and C#; the WebSocket server is implemented using socket.io (using protocol version 0.9), and I am having a hard time understanding how socket.io works... besides that the API requires SSL.

I found out that the HTTP handshake must be initiated via a certain path, which is...

socket.io/1/?t=...

...whereby the value of the parameter t is a Unix-timestamp (in seconds). The service replies with a session-key, timeout information, and a list of supported transport protocols. Due to simplicity, this first request is made via HttpClient and does not involve any additional headers.

Next, another HTTP request is required, which should result in an HTTP 101 Switching Protocol response. I specified the following headers in accordance to the previous request...

Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Key: ...
Sec-WebSocket-Version: 13

...whereby the value of the Key-header is a Base64-encoded GUID-value that the server will use to calculate the Sec-WebSocket-Accept header value. I also precalculate the expected Sec-WebSocket-Accept header value, for validation...

I tried to make that request using HttpClient as well, but that does not seem to work... I actually don´t understand why, because I expect an HTTP response. I also tried to make the request using TcpClient by sending a manually prepared GET request over a SslStream, which accepts the remote certificate as expected. Sending data seems to work, but there´s no response data... the Read-method returns zero.

What do I miss here? Do I need to setup a listener for the WebSocket connection as well, and if yes how? I don´t want to implement a feature complete socket.io client, I´d just like to keep it as simple as possible to catch some events...


问:
Replace with multiple strings in multiple lines of a file
I have a file containing six lines as below:

```<code> a1
 b1
 c1
 d1
 e1
 f1
</code>```

The requirement is  that, the output needs to be as below. Simply put, the lower case letters in the above lines, need to be replaced with "AA" and "AB", thrice each.

```<code>AA1
AA1
AA1
AB1
AB1
AB1
</code>```

I have been using the below code to achieve this:

```<code>For each line in File.ReadLines(path)
    For i as integer = 1 to 3
        fOut.WriteLine(Regex.replace(line, regex, replacementString(matchCount)))
    Next
Next
</code>```

The function replacementString(matchCount) returns either "AA" or "AB" depending on the paramter passed.
I have used the "for" loop to iterate over the replacement String(AA or AB) thrice. But, along with the replacement Strings, the line is also getting looped thrice, and is being written thrice into the file. Instead of getting six lines as output, I get 18 lines as output.

I can't wrap my head around as to how I can make the inner for-loop execute only for the replacementString() and not for the line. I am new to programming and would like to know if there is a way to achieve this.

The above code is just to give an example as to what my problem is. In the actual situation, I face this problem for hundreds of lines in a file, which need to be replaced by AA.....ZZ. I can't post my original code from work.

答:
You cannot intertwine two For loops that way. The simplest way to structure something like this is by looping "manually" for the sort-of-inner loop:

```<code>Dim i as Integer = 0
For Each line in File.ReadLines(path)
    fOut.WriteLine(Regex.replace(line, regex, replacementString(i + 1)))
    i = (i + 1) Mod 3
Next
</code>```

Note: I am assuming that matchCount and i are actually the same variable in your real code. I don't see how your code makes sense otherwise.

Body:
I have a file containing six lines as below:

 a1
 b1
 c1
 d1
 e1
 f1

The requirement is  that, the output needs to be as below. Simply put, the lower case letters in the above lines, need to be replaced with "AA" and "AB", thrice each.

AA1
AA1
AA1
AB1
AB1
AB1

I have been using the below code to achieve this:

For each line in File.ReadLines(path)
    For i as integer = 1 to 3
        fOut.WriteLine(Regex.replace(line, regex, replacementString(matchCount)))
    Next
Next

The function replacementString(matchCount) returns either "AA" or "AB" depending on the paramter passed.
I have used the "for" loop to iterate over the replacement String(AA or AB) thrice. But, along with the replacement Strings, the line is also getting looped thrice, and is being written thrice into the file. Instead of getting six lines as output, I get 18 lines as output.

I can't wrap my head around as to how I can make the inner for-loop execute only for the replacementString() and not for the line. I am new to programming and would like to know if there is a way to achieve this.

The above code is just to give an example as to what my problem is. In the actual situation, I face this problem for hundreds of lines in a file, which need to be replaced by AA.....ZZ. I can't post my original code from work.

Body:
You cannot intertwine two For loops that way. The simplest way to structure something like this is by looping "manually" for the sort-of-inner loop:

Dim i as Integer = 0
For Each line in File.ReadLines(path)
    fOut.WriteLine(Regex.replace(line, regex, replacementString(i + 1)))
    i = (i + 1) Mod 3
Next

Note: I am assuming that matchCount and i are actually the same variable in your real code. I don't see how your code makes sense otherwise.


问:
Register ObjectMapper in Spring 4.1.3 to serialize Joda DateTime
I'm trying to configure ObjectMapper in my Web application to serialize/deserialise dates presented as Joda's DateTime in ISO 8601 format. I found useful library jackson-datatype-joda and it's module JodaModule so I've added dependency:

```<code><dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-joda</artifactId>
    <version>2.4.4</version>
</dependency>
</code>```

My Spring configuration:

```<code><bean id="objectMapper"
    class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
    p:indentOutput="true">

    <property name="featuresToDisable">
        <array>
            <util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS" />
        </array>
    </property>

    <property name="modulesToInstall" value="com.fasterxml.jackson.datatype.joda.JodaModule" />
</bean>

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper" ref="objectMapper" />
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>
</code>```

When I try to serialize this bean

```<code>public class Bean {
    private DateTime start = new DateTime();

    public DateTime getStart() { return start; }
    public void setStart(DateTime start) { this.start = start; }
}
</code>```

I get following output as long but instead want it to be in ISO 8601 format:

{"start":1418337158933}

I found that JodaModule also preloads if it is found in classpath so it is not neccessary to register it manually (see github repo) but this code is invoked many times during application start.

I think the reason is that ObjectMapper is instantiated in some other place.

UPDATE: The problem was that there was one more file with Spring configuration where ObjectMapper was declared. Both solutions given in answers will work. Cheers!

答:
If you use Java configuration, it can be like this:</p>

```<code>@Configuration
public class JodaDateTimeConfig {

@Bean
public ObjectMapper getObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JodaModule());
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    return objectMapper;
}
</code>```

Body:
I'm trying to configure ObjectMapper in my Web application to serialize/deserialise dates presented as Joda's DateTime in ISO 8601 format. I found useful library jackson-datatype-joda and it's module JodaModule so I've added dependency:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-joda</artifactId>
    <version>2.4.4</version>
</dependency>

My Spring configuration:

<bean id="objectMapper"
    class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
    p:indentOutput="true">

    <property name="featuresToDisable">
        <array>
            <util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS" />
        </array>
    </property>

    <property name="modulesToInstall" value="com.fasterxml.jackson.datatype.joda.JodaModule" />
</bean>

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper" ref="objectMapper" />
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

When I try to serialize this bean

public class Bean {
    private DateTime start = new DateTime();

    public DateTime getStart() { return start; }
    public void setStart(DateTime start) { this.start = start; }
}

I get following output as long but instead want it to be in ISO 8601 format:

{"start":1418337158933}

I found that JodaModule also preloads if it is found in classpath so it is not neccessary to register it manually (see github repo) but this code is invoked many times during application start.

I think the reason is that ObjectMapper is instantiated in some other place.

UPDATE: The problem was that there was one more file with Spring configuration where ObjectMapper was declared. Both solutions given in answers will work. Cheers!

Body:
If you use Java configuration, it can be like this:

@Configuration
public class JodaDateTimeConfig {

@Bean
public ObjectMapper getObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JodaModule());
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    return objectMapper;
}


问:
Java Complex Sorting
I am stuck in that I have an Object Book that got three variables

```<code>String title
int Year
String authorName
</code>```

I must sort the books by one, two or all three of the variables in ascending or descending order, I implemented the title ordering but I am stuck as to what to do when people choose more than one variable to order.

Here is some of my code:

Book Class:

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

public class Book{

String title;
String authorName;
int editionYear;

public Book(String title, String authorName, int editionYear){
    this.title = title;
    this.authorName = authorName;
    this.editionYear = editionYear;

}

public String getBookInfo(){

    ArrayList bookInfo = new ArrayList();
    bookInfo.add(this.title);
    bookInfo.add(this.authorName);
    bookInfo.add(this.editionYear);
    return bookInfo.toString();
}

}
</code>```

BookSorter Class:

```<code>import java.util.Arrays;
import java.util.Comparator;

public class BookSorter{

private String sortkey;
private String order;
Book[] Books;

public BookSorter(Book Book1, Book Book2, Book Book3, Book Book4){
    this.Books = new Book[] {Book1, Book2, Book3, Book4};
}

public Book[] sortByTitle(boolean sortorder){
    Comparator<Book> byTitle = new TitleComparator(sortorder);
    Arrays.sort(Books, byTitle);
    for(int i=0;i<4;i++) System.out.println(Books[i].title);
    return Books;
}
}
</code>```

TitleComparator:

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

class TitleComparator implements Comparator<Book> {

boolean ascending;

public TitleComparator(boolean ascending){
    this.ascending = ascending;
}

public int compare(Book Book1, Book Book2){
    if(ascending == true){
        if(Book1.title.compareToIgnoreCase(Book2.title) > 0) return 1;
        else if(Book1.title.compareToIgnoreCase(Book2.title) < 0) return -1;
        else return 0;
    }else{
        if(Book2.title.compareToIgnoreCase(Book1.title) < 0) return -1;
        else if(Book2.title.compareToIgnoreCase(Book1.title) > 0) return 1;
        else return 0;
    }
}
}
</code>```

I though I could work a little more on the comparator but I am really stuck on how to model such a thing, Thanks in advance

答: The Group Comparator allows you to sort on multiple properties. You can also use the Bean Comparator so you don't have to keep writing custom Comparators.</p>

Title: Java Complex Sorting

Body:
I am stuck in that I have an Object Book that got three variables

String title
int Year
String authorName

I must sort the books by one, two or all three of the variables in ascending or descending order, I implemented the title ordering but I am stuck as to what to do when people choose more than one variable to order.

Here is some of my code:

Book Class:

import java.util.ArrayList;

public class Book{

String title;
String authorName;
int editionYear;

public Book(String title, String authorName, int editionYear){
    this.title = title;
    this.authorName = authorName;
    this.editionYear = editionYear;

}

public String getBookInfo(){

    ArrayList bookInfo = new ArrayList();
    bookInfo.add(this.title);
    bookInfo.add(this.authorName);
    bookInfo.add(this.editionYear);
    return bookInfo.toString();
}

}

BookSorter Class:

import java.util.Arrays;
import java.util.Comparator;

public class BookSorter{

private String sortkey;
private String order;
Book[] Books;

public BookSorter(Book Book1, Book Book2, Book Book3, Book Book4){
    this.Books = new Book[] {Book1, Book2, Book3, Book4};
}

public Book[] sortByTitle(boolean sortorder){
    Comparator<Book> byTitle = new TitleComparator(sortorder);
    Arrays.sort(Books, byTitle);
    for(int i=0;i<4;i++) System.out.println(Books[i].title);
    return Books;
}
}

TitleComparator:

import java.util.Comparator;

class TitleComparator implements Comparator<Book> {

boolean ascending;

public TitleComparator(boolean ascending){
    this.ascending = ascending;
}

public int compare(Book Book1, Book Book2){
    if(ascending == true){
        if(Book1.title.compareToIgnoreCase(Book2.title) > 0) return 1;
        else if(Book1.title.compareToIgnoreCase(Book2.title) < 0) return -1;
        else return 0;
    }else{
        if(Book2.title.compareToIgnoreCase(Book1.title) < 0) return -1;
        else if(Book2.title.compareToIgnoreCase(Book1.title) > 0) return 1;
        else return 0;
    }
}
}

I though I could work a little more on the comparator but I am really stuck on how to model such a thing, Thanks in advance


问:
Async IO without completion port?
```<code>// 1-
using(FileStream file = File.Open("ConfusedDev", FileMode.Open)) {
    await file.ReadAsync(buffer, 0, 1024);
    Thread.Sleep(Timeout.Infinite); // threadpool shows 1 worker thread in use
}

// 2-
using(FileStream file = new FileStream("ConfusedDev", FileMode.Open, FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous)) {
    await file.ReadAsync(buffer, 0, 1024);
    Thread.Sleep(Timeout.Infinite); // threadpool shows 1 async IO thread in use
}
</code>```

Is it safe to say that case1 is equivalent of Task.Run(() => file.Read)? In other words, a thread in threadpool is blocked before
read returns whereas case2 has no blocking thread as mentioned in
this post: "There is no
thread".

When to use case1(seems to be the default way introduced by
Microsoft Doc) over case2. I am doing some work on the server side, case2 probably give me more spare threads for incoming requests?

Does this only happen to files? I tested against httpClient().GetAsync() it uses async IO thread by default, but maybe there is implementation where GetAsync() spin off another thread?

答:
Most of your question seems to be answered simply by reviewing the source code:

• Is it safe to say that case1 is equivalent of Task.Run(() => file.Read)? In other words, a thread in threadpool is blocked before read returns whereas case2 has no blocking thread as mentioned in this post: "There is no thread".

File.OpenRead() does not pass FileOptions.Asynchronous to the FileStream constructor, so any asynchronous calls are implemented using blocking I/O in the thread pool. Specifically, the call to ReadAsync() ultimately winds up calling FileStream.BeginRead(), and if the instance wasn't created using FileOptions.Asynchronous, it delegates the read to the base class BeginRead(), which eventually executes this anonymous method as a task:

```<code>delegate
{
    // The ReadWriteTask stores all of the parameters to pass to Read.
    // As we're currently inside of it, we can get the current task
    // and grab the parameters from it.
    var thisTask = Task.InternalCurrent as ReadWriteTask;
    Contract.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");

    // Do the Read and return the number of bytes read
    var bytesRead = thisTask._stream.Read(thisTask._buffer, thisTask._offset, thisTask._count);
    thisTask.ClearBeginState(); // just to help alleviate some memory pressure
    return bytesRead;
}
</code>```

While I agree whole-heartedly with the "There is no thread" essay, it's important to avoid taking it too literally. IOCP is more efficient than dedicating threads to individual operations, but it still involves some threads. It's just that a much smaller pool of threads can be used, and any given thread is able to respond to the completion of a larger number of operations.

• When to use case1(seems to be the default way introduced by Microsoft Doc) over case2. I am doing some work on the server side, case2 probably give me more spare threads for incoming requests?

That question is really too broad, and primarily opinion-based anyway. But it's my opinion that you should always use FileOptions.Asynchronous for any significant file I/O. And if for some reason you decide to forego that and use File.OpenRead() anyway, then you should not bother to use any of the asynchronous calls.

File.OpenRead() is convenient and fine for short programs that do very simple synchronous I/O. But you should never use File.OpenRead() if you are going to then call the asynchronous methods on the FileStream object (e.g. ReadAsync(), BeginRead(), etc.). If it's important enough that the code to operates asynchronously, then it's important enough to make sure it actually does so using the efficient asynchronous features in Windows.

• Does this only happen to files? I tested against httpClient().GetAsync() it uses async IO thread by default, but maybe there is implementation where GetAsync() spin off another thread?

The behavior you're asking about is, obviously, specific to the only difference shown in your code examples: using File.Open() (which doesn't pass FileOptions.Asynchronous) and using the FileStream constructor with the FileOptions.Asynchronous option. So it doesn't really make sense to ask whether this happens only to files. The File.Open() method and the FileStream object are by definition applicable only to files.

That said, while if you were to find a different class that had a similar option (i.e. to enable asynchronous I/O or not) surely it would work identically (i.e. not use IOCP without the option enabled), in fact something like HttpClient or NetworkStream is built on top of the Socket class, which has no such option, and asynchronous operations are going to go through that class's implementation of asynchronous I/O, which does use IOCP always.

So, no…you're not going to find an option in the HttpClient class that disables the use of IOCP for asynchronous operations.

Of course, you can always wrap the synchronous calls yourself, to use the main thread pool instead of the IOCP thread pool, and that would then behave just like asynchronous calls on a non-asynchronous FileStream object.

Title: Async IO without completion port?

Body:
// 1-
using(FileStream file = File.Open("ConfusedDev", FileMode.Open)) {
    await file.ReadAsync(buffer, 0, 1024);
    Thread.Sleep(Timeout.Infinite); // threadpool shows 1 worker thread in use
}

// 2-
using(FileStream file = new FileStream("ConfusedDev", FileMode.Open, FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous)) {
    await file.ReadAsync(buffer, 0, 1024);
    Thread.Sleep(Timeout.Infinite); // threadpool shows 1 async IO thread in use
}

Is it safe to say that case1 is equivalent of Task.Run(() => file.Read)? In other words, a thread in threadpool is blocked before
read returns whereas case2 has no blocking thread as mentioned in
this post: "There is no
thread".

When to use case1(seems to be the default way introduced by
Microsoft Doc) over case2. I am doing some work on the server side, case2 probably give me more spare threads for incoming requests?

Does this only happen to files? I tested against httpClient().GetAsync() it uses async IO thread by default, but maybe there is implementation where GetAsync() spin off another thread?

Body:
Most of your question seems to be answered simply by reviewing the source code:

• Is it safe to say that case1 is equivalent of Task.Run(() => file.Read)? In other words, a thread in threadpool is blocked before read returns whereas case2 has no blocking thread as mentioned in this post: "There is no thread".

File.OpenRead() does not pass FileOptions.Asynchronous to the FileStream constructor, so any asynchronous calls are implemented using blocking I/O in the thread pool. Specifically, the call to ReadAsync() ultimately winds up calling FileStream.BeginRead(), and if the instance wasn't created using FileOptions.Asynchronous, it delegates the read to the base class BeginRead(), which eventually executes this anonymous method as a task:

delegate
{
    // The ReadWriteTask stores all of the parameters to pass to Read.
    // As we're currently inside of it, we can get the current task
    // and grab the parameters from it.
    var thisTask = Task.InternalCurrent as ReadWriteTask;
    Contract.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");

    // Do the Read and return the number of bytes read
    var bytesRead = thisTask._stream.Read(thisTask._buffer, thisTask._offset, thisTask._count);
    thisTask.ClearBeginState(); // just to help alleviate some memory pressure
    return bytesRead;
}

While I agree whole-heartedly with the "There is no thread" essay, it's important to avoid taking it too literally. IOCP is more efficient than dedicating threads to individual operations, but it still involves some threads. It's just that a much smaller pool of threads can be used, and any given thread is able to respond to the completion of a larger number of operations.

• When to use case1(seems to be the default way introduced by Microsoft Doc) over case2. I am doing some work on the server side, case2 probably give me more spare threads for incoming requests?

That question is really too broad, and primarily opinion-based anyway. But it's my opinion that you should always use FileOptions.Asynchronous for any significant file I/O. And if for some reason you decide to forego that and use File.OpenRead() anyway, then you should not bother to use any of the asynchronous calls.

File.OpenRead() is convenient and fine for short programs that do very simple synchronous I/O. But you should never use File.OpenRead() if you are going to then call the asynchronous methods on the FileStream object (e.g. ReadAsync(), BeginRead(), etc.). If it's important enough that the code to operates asynchronously, then it's important enough to make sure it actually does so using the efficient asynchronous features in Windows.

• Does this only happen to files? I tested against httpClient().GetAsync() it uses async IO thread by default, but maybe there is implementation where GetAsync() spin off another thread?

The behavior you're asking about is, obviously, specific to the only difference shown in your code examples: using File.Open() (which doesn't pass FileOptions.Asynchronous) and using the FileStream constructor with the FileOptions.Asynchronous option. So it doesn't really make sense to ask whether this happens only to files. The File.Open() method and the FileStream object are by definition applicable only to files.

That said, while if you were to find a different class that had a similar option (i.e. to enable asynchronous I/O or not) surely it would work identically (i.e. not use IOCP without the option enabled), in fact something like HttpClient or NetworkStream is built on top of the Socket class, which has no such option, and asynchronous operations are going to go through that class's implementation of asynchronous I/O, which does use IOCP always.

So, no…you're not going to find an option in the HttpClient class that disables the use of IOCP for asynchronous operations.

Of course, you can always wrap the synchronous calls yourself, to use the main thread pool instead of the IOCP thread pool, and that would then behave just like asynchronous calls on a non-asynchronous FileStream object.


问:
Codename One - Show number of unread messages in the app icon
Please look at the Signal icon in this screenshot:

My question is how to obtain the same result in a Codename One app. Suppose that my app has a variable like "int unreadMdg", how can I show the number of unread message in the app icon?

答:
We currently only support this on iOS as it wasn't available on any Android device when we launched the feature and is still arguably flaky on Android.

For iOS support you can set the badge value via push notification (see the developer guide) or by using the API:

```<code>if(Display.getInstance().isBadgingSupported()) {
    Display.getInstance().setBadgeNumber(unreadCount);
}
</code>```

Body:
We currently only support this on iOS as it wasn't available on any Android device when we launched the feature and is still arguably flaky on Android.

For iOS support you can set the badge value via push notification (see the developer guide) or by using the API:

if(Display.getInstance().isBadgingSupported()) {
    Display.getInstance().setBadgeNumber(unreadCount);
}


问:
MVC @Html.DropDownListFor change displayed value in javascript
Using MVC 4, I am trying to change the displayed value in the view for @Html.DropDownListFor, based on the action of another drop down list.  In the below example, when the user selects any value in the state list, I want the @Html.DropDownListFor to display the indexed 203 value which is US. How to do this?

```<code>//in the controller

ViewBag.statelist = new SelectList(db.states, "state_abbr", "state_name");

ViewBag.countrylist = new SelectList(db.countries, "country_id", "country_name", -1);

//in the View

<div class="form-group">
    @Html.LabelFor(model => model.states)
    @Html.DropDownList("ddlstate", ViewBag.statelist as SelectList, Model.rrq_sec1_waddr_stprov, htmlAttributes: new { @onchange="StateChange()" })
</div>

<div class="form-group">
   @Html.LabelFor(model => model.country)
   @Html.DropDownListFor(model => model.country, ViewBag.countrylist as SelectList, "Select Country", htmlAttributes: new { @id="ddlcountry" })
</div>

//javascript
function StateChange() {

    var state = document.getElementById("ddlstate").value;
    $("#ddlcountry").val = 203;
};
</code>```

How do I get the #ddlcountry index=203 which is "US" show up in view then the state drop down changes?

答:
This might help u to select value in second dropdown, onchange event of first dropdown using this jQuery function.</p>

```<code> $('#ddlstate').change(function () {
 $("#ddlcountry").val( $('#ddlstate').val());
});
</code>```

Body:
Using MVC 4, I am trying to change the displayed value in the view for @Html.DropDownListFor, based on the action of another drop down list.  In the below example, when the user selects any value in the state list, I want the @Html.DropDownListFor to display the indexed 203 value which is US. How to do this?

//in the controller

ViewBag.statelist = new SelectList(db.states, "state_abbr", "state_name");

ViewBag.countrylist = new SelectList(db.countries, "country_id", "country_name", -1);

//in the View

    @Html.LabelFor(model => model.states)
    @Html.DropDownList("ddlstate", ViewBag.statelist as SelectList, Model.rrq_sec1_waddr_stprov, htmlAttributes: new { @onchange="StateChange()" })

   @Html.LabelFor(model => model.country)
   @Html.DropDownListFor(model => model.country, ViewBag.countrylist as SelectList, "Select Country", htmlAttributes: new { @id="ddlcountry" })

//javascript
function StateChange() {

    var state = document.getElementById("ddlstate").value;
    $("#ddlcountry").val = 203;
};

How do I get the #ddlcountry index=203 which is "US" show up in view then the state drop down changes?

Body:
This might help u to select value in second dropdown, onchange event of first dropdown using this jQuery function.

 $('#ddlstate').change(function () {
 $("#ddlcountry").val( $('#ddlstate').val());
});


问:
SugarORM + Multidex
I downloaded the SugarORM source to use it as a library module (so I could override the aplication's  "attachBaseContext" method.

I have already seen the question SugarORM and multidex, Problem is that I can't figure out how to reference the MultiDex library into my new SugarORM library module.
Can someone help me figuring this out?

Error page screenshot

答:
Create a class java file

```<code>public class MultiDex extends SugarApp {
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        android.support.multidex.MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        SugarContext.init(this);
    }

    @Override
    public void onTerminate() {
        SugarContext.terminate();
        super.onTerminate();
    }
}
</code>```

In Manifest, call the java class file.

```<code><application
   .......
    android:name=".MultiDex"

   ......>
</code>```

Check the version of sugar library

 and make sure you complie the latest version of sugar library . Using version like 1.3 will throw some errors with multidex.

add this in your gradle

```<code> compile 'com.github.satyan:sugar:1.5'
</code>```

Title: SugarORM + Multidex

Body:
Create a class java file

public class MultiDex extends SugarApp {
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        android.support.multidex.MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        SugarContext.init(this);
    }

    @Override
    public void onTerminate() {
        SugarContext.terminate();
        super.onTerminate();
    }
}

In Manifest, call the java class file.

<application
   .......
    android:name=".MultiDex"

   ......>

Check the version of sugar library

 and make sure you complie the latest version of sugar library . Using version like 1.3 will throw some errors with multidex.

add this in your gradle

 compile 'com.github.satyan:sugar:1.5'


问:
getting ExpressionChangedAfterItHasBeenCheckedError Angular 4
Im aware similar questions exist but none of those have provided me with an answer that works..

Basically I have a site with some services that inject data dynamically

In my app.component.ts I have two headers.. one when your on the home page and one for when your on any other page

app.component.html

```<code><app-header *ngIf="router.url !== '/'"></app-header>
<app-header-home *ngIf="router.url != '/'"></app-header-home>
<router-outlet></router-outlet>
<app-footer></app-footer>
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'app';
  router: string;

  constructor(
    private _router: Router
  ) {
       this.router = _router.url;
  }
}
</code>```

now I also have a service that dynamically injects the title of the header

headerTitle.service.ts

```<code>import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class HeaderTitleService {
  title = new BehaviorSubject('');

  constructor() { }

  setTitle(title: any) {
  this.title.next(title);
  }
}
</code>```

then In my home component for example I set the title

home.component.ts

```<code>import { Component, OnInit, AfterViewInit } from '@angular/core';
import { HeaderTitleService } from '../../services/headerTitle.service';
import { HeaderImageService } from '../../services/headerImage.service';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  constructor(
    private headerTitleService: HeaderTitleService,
    private headerImageService: HeaderImageService
  ) { }

  ngOnInit() {

  }

  ngAfterViewInit() {
    this.headerTitleService.setTitle(`
    We strive to create things
    <br> that are engaging, progressive
    <br> & above all
    <span class="highlight">
    <em>innovative.</em>
    </span>
  `);
 }

}
</code>```

now basically it was all working until I put in the if statements on the two headers

now Im getting this error

Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: ''. Current value: '
    We strive to create things

 that are engaging, progressive

 & above all

    innovative.

  '.

not sure how I can fix this.. I tried setting the values in ngAfterViewInit but it did nothing

or does anyone know another way I could accomplish this??

Thanks

答:
You can try using a setTimeOut method instead and set the values
  inside of that

```<code>setTimeout(this.headerTitleService.setTitle(`
    We strive to create things
    <br> that are engaging, progressive
    <br> & above all
    <span class="highlight">
    <em>innovative.</em>
    </span>
`), 0);
</code>```

note this is a work around and not a full proff solution to the problem .

To know why this error occurs in Angular change detection you need to know how the change detection works in Angular for this you can refer to this blog by Maxim NgWizard K

Body:
Im aware similar questions exist but none of those have provided me with an answer that works..

Basically I have a site with some services that inject data dynamically

In my app.component.ts I have two headers.. one when your on the home page and one for when your on any other page

app.component.html

<app-header *ngIf="router.url !== '/'"></app-header>
<app-header-home *ngIf="router.url != '/'"></app-header-home>
<router-outlet></router-outlet>
<app-footer></app-footer>

app.component.ts

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'app';
  router: string;

  constructor(
    private _router: Router
  ) {
       this.router = _router.url;
  }
}

now I also have a service that dynamically injects the title of the header

headerTitle.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class HeaderTitleService {
  title = new BehaviorSubject('');

  constructor() { }

  setTitle(title: any) {
  this.title.next(title);
  }
}

then In my home component for example I set the title

home.component.ts

import { Component, OnInit, AfterViewInit } from '@angular/core';
import { HeaderTitleService } from '../../services/headerTitle.service';
import { HeaderImageService } from '../../services/headerImage.service';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  constructor(
    private headerTitleService: HeaderTitleService,
    private headerImageService: HeaderImageService
  ) { }

  ngOnInit() {

  }

  ngAfterViewInit() {
    this.headerTitleService.setTitle(`
    We strive to create things

 that are engaging, progressive

 & above all

    innovative.

  `);
 }

}

now basically it was all working until I put in the if statements on the two headers

now Im getting this error

Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: ''. Current value: '
    We strive to create things

 that are engaging, progressive

 & above all

    innovative.

  '.

not sure how I can fix this.. I tried setting the values in ngAfterViewInit but it did nothing

or does anyone know another way I could accomplish this??

Thanks

Body:
You can try using a setTimeOut method instead and set the values
  inside of that

setTimeout(this.headerTitleService.setTitle(`
    We strive to create things
    <br> that are engaging, progressive
    <br> &amp; above all
    <span class="highlight">
    <em>innovative.</em>
    </span>
`), 0);

note this is a work around and not a full proff solution to the problem .

To know why this error occurs in Angular change detection you need to know how the change detection works in Angular for this you can refer to this blog by Maxim NgWizard K