问:
Why might Graphics.RotateTransform() not be applied?
I have the following function:

```<code>static private Image CropRotate(Image wholeImage, Rectangle cropArea)
{
    Bitmap cropped = new Bitmap(cropArea.Width, cropArea.Height);

    using(Graphics g = Graphics.FromImage(cropped))
    {
        g.DrawImage(wholeImage, new Rectangle(0, 0, cropArea.Width, cropArea.Height), cropArea, GraphicsUnit.Pixel);
        g.RotateTransform(180f);
    }
    return cropped as Image;
}
</code>```

It's supposed to crop an image, then rotate the resulting sub-image. In actuality though, it only performs the crop.

Why is RotateTransform() not being applied?

答:
The RotateTransform call alters the current transform matrix, which has an effect on all subsequent operations.  It does not transform the already output operations at all.  This is the same for any of the operations that change the transform matrix (like ScaleTransform).

Make sure you call these before you perform the operations you want transformed - in this case, before the call to DrawImage.

You can use this to do something like

Draw (not rotated or scaled)

Rotate (only changes transform matrix)

Scale (only changes transform matrix)

Draw (now rotated and scaled)

ClearTransform  (only changes transform matrix)

Draw  (not rotated or scaled)

the first and last draw outputs will not be transformed, but the middle one would be affected by both the rotate and scale (in that order).

ContentLicense: CC BY-SA 2.5

Body:
I have the following function:

static private Image CropRotate(Image wholeImage, Rectangle cropArea)
{
    Bitmap cropped = new Bitmap(cropArea.Width, cropArea.Height);

    using(Graphics g = Graphics.FromImage(cropped))
    {
        g.DrawImage(wholeImage, new Rectangle(0, 0, cropArea.Width, cropArea.Height), cropArea, GraphicsUnit.Pixel);
        g.RotateTransform(180f);
    }
    return cropped as Image;
}

It's supposed to crop an image, then rotate the resulting sub-image. In actuality though, it only performs the crop.

Why is RotateTransform() not being applied?


来源: stackexchange

问:
Sorting rows in DataTable by extracting a number
I have a question that could maybe be simple. I have some values in a datatable column like "F-213", "F-1113/A" and so on. Is it possible to extract the number of these and sort the rows of the table by the number? I tried something like this:

```<code>DataTable orderedDt = _table.AsEnumerable()
            .OrderBy(r => int.Parse(r.Field<string>(int.Parse(Regex.Match("F-Number", @"\d+").Value))))
            .CopyToDataTable();
</code>```

but I'm getting an Format exception.

Thank you!

答:
you can try with regex as below </p>

```<code>var reg = @"(\w)-(\d+)(.*)";
var orderedDataRowList = dataTable.Rows.Cast<DataRow>()
       .OrderBy(c =>
                   int.Parse(Regex.Match(c["F-Number"].ToString(), reg).Groups[2].Value))
       .ToList();
</code>```

<p>I've tested this and its working fine. </p>

ContentLicense: CC BY-SA 3.0

Body:
I have a question that could maybe be simple. I have some values in a datatable column like "F-213", "F-1113/A" and so on. Is it possible to extract the number of these and sort the rows of the table by the number? I tried something like this:

DataTable orderedDt = _table.AsEnumerable()
            .OrderBy(r => int.Parse(r.Field<string>(int.Parse(Regex.Match("F-Number", @"\d+").Value))))
            .CopyToDataTable();

but I'm getting an Format exception.

Thank you!

Body:
you can try with regex as below

var reg = @"(\w)-(\d+)(.*)";
var orderedDataRowList = dataTable.Rows.Cast<DataRow>()
       .OrderBy(c =>
                   int.Parse(Regex.Match(c["F-Number"].ToString(), reg).Groups[2].Value))
       .ToList();

I've tested this and its working fine.


问:
EntityFramework Core one-to-many configuration
I'm trying to configurate entity relation one-to-many.

Whats the way to configure to not allow to delete parent if it has childs and be allowed to creat parent without child?

Folling the EF Core documentation example. How can I configure Blog not allow to delete if it has Post but can creat blog withou post.

答:
Set OnDelete Restrict in OnModelCreating method of your DbContext. as following:

Entities:

```<code>public class Blog
{
    public int Id{get; set;}

    public string Name{get; set;}

    public virtual ICollection<Post> Posts{get; set;}
}

public class Post
{
    public int Id{get; set;}

    public string Name{get; set;}

    public int BlogId {get; set;}

    public virtual Blog Blog{get; set;}
}
</code>```

Configuration in DbContext:

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Blog>()
        .HasMany(a => a.Posts)
        .WithOne(a => a.Blog)
        .HasForeignKey(a => a.BlogId)
        .IsRequired()
        .OnDelete(DeleteBehavior.Restrict);
}
</code>```

Body:
Set OnDelete Restrict in OnModelCreating method of your DbContext. as following:

Entities:

public class Blog
{
    public int Id{get; set;}

    public string Name{get; set;}

    public virtual ICollection<Post> Posts{get; set;}
}

public class Post
{
    public int Id{get; set;}

    public string Name{get; set;}

    public int BlogId {get; set;}

    public virtual Blog Blog{get; set;}
}

Configuration in DbContext:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Blog>()
        .HasMany(a => a.Posts)
        .WithOne(a => a.Blog)
        .HasForeignKey(a => a.BlogId)
        .IsRequired()
        .OnDelete(DeleteBehavior.Restrict);
}


问:
Low size image uploading
I try upload image to server. I get image by path and convert it to byte array:

```<code>BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap picture = BitmapFactory.decodeFile(imagePath, bmOptions);

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
ByteArrayOutputStream bao = new ByteArrayOutputStream();

bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bao);
byte[] bytes = bao.toByteArray();

builder.addPart("uploadedfile", new ByteArrayBody(bytes, "name" + ".jpg"));
</code>```

For example image's size is 300kb but size of uploaded image is 800kb.

How can I send image (selected by path) without size increasing?

SOULUTION

@greenapps right. I converted image as file:

```<code>public static byte[] fullyReadFileToBytes(File f) throws IOException {
    int size = (int) f.length();
    byte bytes[] = new byte[size];
    byte tmpBuff[] = new byte[size];
    FileInputStream fis= new FileInputStream(f);;
    try {

        int read = fis.read(bytes, 0, size);
        if (read < size) {
            int remain = size - read;
            while (remain > 0) {
                read = fis.read(tmpBuff, 0, remain);
                System.arraycopy(tmpBuff, 0, bytes, size - remain, read);
                remain -= read;
            }
        }
    }  catch (IOException e){
        throw e;
    } finally {
        fis.close();
    }

    return bytes;
}
</code>```

答: Put the image file in a byte array without using an intermediate Bitmap.</p>

Title: Low size image uploading

Body:
I try upload image to server. I get image by path and convert it to byte array:

BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap picture = BitmapFactory.decodeFile(imagePath, bmOptions);

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
ByteArrayOutputStream bao = new ByteArrayOutputStream();

bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bao);
byte[] bytes = bao.toByteArray();

builder.addPart("uploadedfile", new ByteArrayBody(bytes, "name" + ".jpg"));

For example image's size is 300kb but size of uploaded image is 800kb.

How can I send image (selected by path) without size increasing?

SOULUTION

@greenapps right. I converted image as file:

public static byte[] fullyReadFileToBytes(File f) throws IOException {
    int size = (int) f.length();
    byte bytes[] = new byte[size];
    byte tmpBuff[] = new byte[size];
    FileInputStream fis= new FileInputStream(f);;
    try {

        int read = fis.read(bytes, 0, size);
        if (read < size) {
            int remain = size - read;
            while (remain > 0) {
                read = fis.read(tmpBuff, 0, remain);
                System.arraycopy(tmpBuff, 0, bytes, size - remain, read);
                remain -= read;
            }
        }
    }  catch (IOException e){
        throw e;
    } finally {
        fis.close();
    }

    return bytes;
}


问:
CPU usage: Bullet vs Box2d engines
I've been using the 2d library jbox2d for some time now and been recently looking into the bullet 3d physics engine.

What I'm wondering is what the CPU consumption on a typical quad core, say i5 (I assume bullet is multi threaded?) is going to be.

Even in jbox, it is very easy to create lag and even completely crash a simulation with too much processing and I'm wondering how much more processing power will be lost in a switch to 3d physics using the Bullet engine.

答:
Large Disclaimer :-

I have never used multi-thread for both Physic Engine.

I have never used them to create the same application either, because one is 2D, another one is 3D.

I will answer from my past memory instead of benchmark them.  I accept that it is not a good practice.

If I have to simulate ~100 amount of bodies (2D-rectange in JBox2d, 3D-cube in Bullet) :-

C++ compiled with Release mode (optimization turn on)

Java compiled with Release mode (not debug mode), using ctrl+F11 Eclipse

Computer is not in a stress condition (minium program opened)

No constraint (joint for Box2D, btConstraint in Bullet) for both Physic Engines.

Body are scattering around (sometimes collide with each other), no stacking.

All bodies are not too far away. All with in 1 screen, roughly speaking.

I have some game logic, but not too heavy.

C++ program is coded well in C++ style (not abuse new/delete, share_ptr much)

Windows 7 with specification that can play most current PC games (2017).

I can expect C++ & Bullet-program run faster than Java & Box2D around :-
 3 times (quite conservative) - 10 times (common).

Edit:-

I have just remembered a real test case in my old computer a few years ago.

When I ran 400 rectangles in JBox2D, I could barely reach 60 fps with 10-30% CPU in Physic's part .

However, I could add around 4000 cubes in C++ Bullet, and I can get around 60 fps with 10-30% CPU in Physic's part (profiled).

(I note 10-30% because I can't remember the exact number.)

Title: CPU usage: Bullet vs Box2d engines


问:
Structs and Multidimensional Array Global Declaration in C
My intention is to create a multidimensional array of structs. However, the problem is that it needs to be a global variable, but I don't know the size at compile time (it is user input).

Lets say I have a Struct like so:

```<code>typedef struct abc abc;
struct abc {
  int test;
  char* color;
};
</code>```

I need to declare a global multidimensional array for this.

```<code>abc** board;
</code>```

Within a function later in the code, I then want to initialise the size and fill it with values:

```<code>board[height][width];

for(int i = 0; i < height; i++) {
    for(int x = 0; x <width; x++) {
        board[i][x].test = 0;
    }
}
</code>```

Where am I going wrong? It seem's this part is the issue: board[height][width] ?

答:
There are two ways of doing this. The first stage is the same in both cases: allocate an array of pointers to abc (assume the user has already typed values for height and width and you have validated them).

```<code>board = calloc(height, sizeof *board);
</code>```

Now you have an array of height null pointers (purists would say this is not guaranteed by the C standard, but we'll ignore them because it doesn't matter).

Now, either you allocate height arrays of width structs

```<code>for (size_t i = 0 ; i < height ; ++i)
{
    board[i] = calloc(width, sizeof **board);
}
</code>```

Or you alllocate one enormous array for the whole thing and set the pointers in board to the right offsets.

```<code>abc *temp = calloc(width * height, sizeof *board);

for (size_t i = 0 ; i < height ; ++i)
{
    board[i] = &temp[i * width];
}
</code>```

The use of calloc means that each struct will already be initialised with a zero bit pattern which means that on most platforms, test will be 0 and color will be a null pointer for every single abc in the array.

The second option is a bit more opaque but more efficient if you need to do the allocation a lot or if height is likely to be large. It's also easier to deallocate requiring only two calls to free().

On the subject of freeing, if this global array is allocated once and has a life time of the entire program, you don't need to bother about freeing it since all the memory will be returned to the OS when the program terminates anyway (unless you are on an embedded platform or a retro environment without virtual memory)

Body:
My intention is to create a multidimensional array of structs. However, the problem is that it needs to be a global variable, but I don't know the size at compile time (it is user input).

Lets say I have a Struct like so:

typedef struct abc abc;
struct abc {
  int test;
  char* color;
};

I need to declare a global multidimensional array for this.

abc** board;

Within a function later in the code, I then want to initialise the size and fill it with values:

board[height][width];

for(int i = 0; i < height; i++) {
    for(int x = 0; x <width; x++) {
        board[i][x].test = 0;
    }
}

Where am I going wrong? It seem's this part is the issue: board[height][width] ?

Body:
There are two ways of doing this. The first stage is the same in both cases: allocate an array of pointers to abc (assume the user has already typed values for height and width and you have validated them).

board = calloc(height, sizeof *board);

Now you have an array of height null pointers (purists would say this is not guaranteed by the C standard, but we'll ignore them because it doesn't matter).

Now, either you allocate height arrays of width structs

for (size_t i = 0 ; i < height ; ++i)
{
    board[i] = calloc(width, sizeof **board);
}

Or you alllocate one enormous array for the whole thing and set the pointers in board to the right offsets.

abc *temp = calloc(width * height, sizeof *board);

for (size_t i = 0 ; i < height ; ++i)
{
    board[i] = &temp[i * width];
}

The use of calloc means that each struct will already be initialised with a zero bit pattern which means that on most platforms, test will be 0 and color will be a null pointer for every single abc in the array.

The second option is a bit more opaque but more efficient if you need to do the allocation a lot or if height is likely to be large. It's also easier to deallocate requiring only two calls to free().

On the subject of freeing, if this global array is allocated once and has a life time of the entire program, you don't need to bother about freeing it since all the memory will be returned to the OS when the program terminates anyway (unless you are on an embedded platform or a retro environment without virtual memory)


问:
Subversion adding unversioned project files to working copy
I have a project, calendars, that has been worked on by a number of different developers. I decided to place the project under version control using Subversion, but in the meantime these different developers continued to work on their unversioned files independently of me.

```
Developer A      Developer B       Me

header.h         header.h          header.h
timer.c          timer.c           timer.c
timezones.c                        timezones.c
calendars.c                        .svn
```

My question is, how do I bring their changes in line with mine, where the repository is on a remote server?

My thinking is that Developers A and B would have to check out from the repository, but then how would they merge their own files with the ones they have checked out before then committing back to the repository?

答:
Because their projects are not versioned they must merge changes manually. It is unavoidable, but it is only done once. It should be done as soon as possible.

rename current project X to X_old

checkout X

compare each file individually (WinMerge is good for that), and bring changes from X_old to X, taking care of each different line in each file

in the end commit changes

Developers should bring their projects to version control sequentially to minimize conflicts.

Body:
I have a project, calendars, that has been worked on by a number of different developers. I decided to place the project under version control using Subversion, but in the meantime these different developers continued to work on their unversioned files independently of me.

Developer A      Developer B       Me

header.h         header.h          header.h
timer.c          timer.c           timer.c
timezones.c                        timezones.c
calendars.c                        .svn

My question is, how do I bring their changes in line with mine, where the repository is on a remote server?

My thinking is that Developers A and B would have to check out from the repository, but then how would they merge their own files with the ones they have checked out before then committing back to the repository?


问:
$ctrl in data binding is not working
I want to make a dynamic page using angular where the user after  he logged-in see his user picture and some information charged by json file throught an http request.
This is the module where i do the http requestes:

```<code>         'user strict';

angular.
 module('userIssue').
 component('userIssue',{
    templateUrl: 'user-issue/user-issue.html',
    controller: 'userIssueCtrl'
 })

.controller('userIssueCtrl',['$scope','$http','$routeParams',function       userIssueCtrl($scope,$http,$routeParams){
var self = this;
var percorso;
$scope.utente=$routeParams.username;
document.title="Benvenuto"+" "+$routeParams.username;

$http.get('user/'+ $routeParams.username+'.json').then(function(response){
  self.utenti = response.data;

});

$http.get('user/'+$routeParams.username+'.info.json').then(function(qualcosa){
  self.d = qualcosa.data;
});

self.show = function(){
  $scope.showForm='false';
}

}]);
</code>```

and this is the part of the html page not working:

```<code> <div class="col-sm-4">
 <img  style="position:center;" ng-src="{{$ctrl.d.imgUrl}}" class="img-circle" alt="user image"></div>
</code>```

I'm using the same approch in this part of the code:

```<code><div  class="col-md-9 col-sm-9" id="issueColumn" >
<div id="issue" ng-repeat='utenti in $ctrl.utenti'>
               <li>
<dt>CODICE OPERAZIONE</dt>
<dd>{{utenti.id}}</dd>
<dt>DESCRIZIONE PROBLEMA</dt>
<dd>{{utenti.description}}</dd>
<dt>DATA SEGNALAZIONE</dt>
<dd>{{utenti.forward}}</dd>
<dt>IL PROBLEMA SARà RISOLTO ENTRO IL:</dt>
<dd>{{utenti.endstimed}}</dd>
<dt>STATO DEL PROBLEMA:</dt>
<dd>{{utenti.stato}}</dd>
</li> </br>
</div>
</div>
</code>```

and here it is working! So why does the data binding not work for the image?
Could someone gently explain me why?

Here is the json file I use for the image:

```<code>   [
 {
   "imgUrl": "img/Filippo.png",
   "ciao": "ciao_calro"
 }
   ]
</code>```

答:
As you want to use 1st element of d array object, you should be accessing 1st element of imgUrl property explicitly.

```<code>ng-src="{{$ctrl.d[0].imgUrl}}"
</code>```

Title: $ctrl in data binding is not working

Body:
I want to make a dynamic page using angular where the user after  he logged-in see his user picture and some information charged by json file throught an http request.
This is the module where i do the http requestes:

         'user strict';

angular.
 module('userIssue').
 component('userIssue',{
    templateUrl: 'user-issue/user-issue.html',
    controller: 'userIssueCtrl'
 })

.controller('userIssueCtrl',['$scope','$http','$routeParams',function       userIssueCtrl($scope,$http,$routeParams){
var self = this;
var percorso;
$scope.utente=$routeParams.username;
document.title="Benvenuto"+" "+$routeParams.username;

$http.get('user/'+ $routeParams.username+'.json').then(function(response){
  self.utenti = response.data;

});

$http.get('user/'+$routeParams.username+'.info.json').then(function(qualcosa){
  self.d = qualcosa.data;
});

self.show = function(){
  $scope.showForm='false';
}

}]);

and this is the part of the html page not working:

I'm using the same approch in this part of the code:

CODICE OPERAZIONE

{{utenti.id}}

DESCRIZIONE PROBLEMA

{{utenti.description}}

DATA SEGNALAZIONE

{{utenti.forward}}

IL PROBLEMA SARà RISOLTO ENTRO IL:

{{utenti.endstimed}}

STATO DEL PROBLEMA:

{{utenti.stato}}

and here it is working! So why does the data binding not work for the image?
Could someone gently explain me why?

Here is the json file I use for the image:

   [
 {
   "imgUrl": "img/Filippo.png",
   "ciao": "ciao_calro"
 }
   ]

Body:
As you want to use 1st element of d array object, you should be accessing 1st element of imgUrl property explicitly.

ng-src="{{$ctrl.d[0].imgUrl}}"


问:
How to Intent into specific Tab Fragment?
T have two Activities: MainActivity and LoginActivity. I have one Fragment too, the name is TabFragment (with a TabLayout), its parent is MainActivity. How can I intent into the specific TabFragment from my Login Activity.

This is my Main Activity:

```<code> protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        id = getIntent().getStringExtra("id");

        if (savedInstanceState == null) {
     getSupportFragmentManager().beginTransaction().replace(R.id.confrag, new FragmentUtama()).commit();
            getSupportFragmentManager().beginTransaction().replace(R.id.confrag, new TabFragment()).commit();
        }
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        sharedPreferences = getSharedPreferences("login.conf", MODE_PRIVATE);
        editor = sharedPreferences.edit();
        String username = sharedPreferences.getString("username", "");
        String password = sharedPreferences.getString("password", "");
        Log.d(TAG, "Username:"+username+"\npassword:"+password);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

    }
</code>```

And This my Tab Fragment:

```<code>  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.viewpager, null);

        tabLayout = (TabLayout)view.findViewById(R.id.tabs);
        viewPager = (ViewPager)view.findViewById(R.id.viewpager);
        viewPager.setAdapter(new Adapterbaru(getChildFragmentManager()));
         tabLayout.post(new Runnable() {
            @Override
            public void run() {
                tabLayout.setupWithViewPager(viewPager);
            }
        });
        Long tsLong = System.currentTimeMillis()/1000;
        String ts = tsLong.toString();

        return view;
    }

    public interface OnFragmentInteractionListener {

        void onFragmentInteraction(Uri uri);
    }
    public class Adapterbaru extends FragmentPagerAdapter{
        public Adapterbaru(FragmentManager fm){
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0 : {
                    return new Fragmentone();
                }
                case 1 : {
                    return new FragmentTwo();

                }
                case 2 : {
                    return new Fragmenttree();

                }
            }
            return null;
        }

        @Override
        public int getCount() {
           return jumlah_tab;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch(position){
                case 0 : {
                    return "First";

                }
                case 1 : {
                    return "Second";

                }
                case 2 : {
                    return "Third";
                }
            }
            return null;
        }
</code>```

答:
From your LoginActivity, pass tabs fragment (FragmentOne, FragmentTwo, FragmentThree) id as 0, 1, 2 through Intent.

```<code>Intent intent  = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("FRAGMENT_ID", 0);
startActivity(intent);
</code>```

In your MainActivity, get the fragment id from Intent

```<code>// Inside OnCreate()
int fragmentId = getIntent().getIntExtra("FRAGMENT_ID", 0);
</code>```

From MainActivity, show TabFragment using FragmentManager and pass fragmentId to TabFragment using Bundle

```<code>// Inside OnCreate()
Bundle bundle = new Bundle();
bundle.putString("TARGET_FRAGMENT_ID", fragmentId);
TabFragment tabFragment = new TabFragment();
tabFragment.setArguments(bundle);

getSupportFragmentManager().beginTransaction().replace(R.id.confrag, tabFragment).commit();
</code>```

In TabFragment, get target fragment (FragmentOne, FragmentTwo, FragmentThree) id from Bundle and finally show desired fragment using ViewPager.setCurrentItem(POSITION) method.

```<code>// Inside OnCreateView()
int position = getArguments().getInt("TARGET_FRAGMENT_ID");
viewpager.setCurrentItem(position);
</code>```

Hope this will help~

Body:
T have two Activities: MainActivity and LoginActivity. I have one Fragment too, the name is TabFragment (with a TabLayout), its parent is MainActivity. How can I intent into the specific TabFragment from my Login Activity.

This is my Main Activity:

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        id = getIntent().getStringExtra("id");

        if (savedInstanceState == null) {
     getSupportFragmentManager().beginTransaction().replace(R.id.confrag, new FragmentUtama()).commit();
            getSupportFragmentManager().beginTransaction().replace(R.id.confrag, new TabFragment()).commit();
        }
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        sharedPreferences = getSharedPreferences("login.conf", MODE_PRIVATE);
        editor = sharedPreferences.edit();
        String username = sharedPreferences.getString("username", "");
        String password = sharedPreferences.getString("password", "");
        Log.d(TAG, "Username:"+username+"\npassword:"+password);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

    }

And This my Tab Fragment:

  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.viewpager, null);

        tabLayout = (TabLayout)view.findViewById(R.id.tabs);
        viewPager = (ViewPager)view.findViewById(R.id.viewpager);
        viewPager.setAdapter(new Adapterbaru(getChildFragmentManager()));
         tabLayout.post(new Runnable() {
            @Override
            public void run() {
                tabLayout.setupWithViewPager(viewPager);
            }
        });
        Long tsLong = System.currentTimeMillis()/1000;
        String ts = tsLong.toString();

        return view;
    }

    public interface OnFragmentInteractionListener {

        void onFragmentInteraction(Uri uri);
    }
    public class Adapterbaru extends FragmentPagerAdapter{
        public Adapterbaru(FragmentManager fm){
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0 : {
                    return new Fragmentone();
                }
                case 1 : {
                    return new FragmentTwo();

                }
                case 2 : {
                    return new Fragmenttree();

                }
            }
            return null;
        }

        @Override
        public int getCount() {
           return jumlah_tab;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch(position){
                case 0 : {
                    return "First";

                }
                case 1 : {
                    return "Second";

                }
                case 2 : {
                    return "Third";
                }
            }
            return null;
        }

Body:
From your LoginActivity, pass tabs fragment (FragmentOne, FragmentTwo, FragmentThree) id as 0, 1, 2 through Intent.

Intent intent  = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("FRAGMENT_ID", 0);
startActivity(intent);

In your MainActivity, get the fragment id from Intent

// Inside OnCreate()
int fragmentId = getIntent().getIntExtra("FRAGMENT_ID", 0);

From MainActivity, show TabFragment using FragmentManager and pass fragmentId to TabFragment using Bundle

// Inside OnCreate()
Bundle bundle = new Bundle();
bundle.putString("TARGET_FRAGMENT_ID", fragmentId);
TabFragment tabFragment = new TabFragment();
tabFragment.setArguments(bundle);

getSupportFragmentManager().beginTransaction().replace(R.id.confrag, tabFragment).commit();

In TabFragment, get target fragment (FragmentOne, FragmentTwo, FragmentThree) id from Bundle and finally show desired fragment using ViewPager.setCurrentItem(POSITION) method.

// Inside OnCreateView()
int position = getArguments().getInt("TARGET_FRAGMENT_ID");
viewpager.setCurrentItem(position);

Hope this will help~


问:
WatchService (Windows 7): when deleting a file, it fires both ENTRY_MODIFY and ENTRY_DELETE events?
In working with the WatchService, I found that if I delete a file in the directory being watched, it fires an ENTRY_MODIFY followed by an ENTRY_DELETE event.

I realize that technically, a file may be modified before deleted, but is it really the expected behavior that deleting a file will trigger ENTRY_MODIFY  (which presumably no one cares about)?

To handle this, I had to add a condition to check before firing passing along the ENTRY_MODIFY event:

```<code>            if (eventKind == ENTRY_CREATE) {
                listener.fileCreated(file);
            } else if (eventKind == ENTRY_MODIFY) {
                if (Files.exists(fullPath, LinkOption.NOFOLLOW_LINKS)) {
                    listener.fileChanged(file);
                }
            } else if (eventKind == ENTRY_DELETE) {
                listener.fileDeleted(file);
            }
</code>```

Is this there a better way to handle this issue (feature)?

答:
I can only confirm the issue. From the comments and from my own observations, the ENTRY_MODIFY event is fired just before the file is deleted and you have to deal with it.

Suppose we have two threads. One is doing Files.delete(), the other is watching the directory and trying to read modified files. Any of the following can happen:

Files.delete() just manages to modify and delete the file, before the event is picked up by the watching thread. Then the technique to check the file existence after ENTRY_MODIFY works.

the Files.delete() call can fail (return false), as the file is already opened by the watching thread.

The only resolution seems to be to ignore all IOExceptions in the watching thread and to retry the Files.delete() call few times.

I only tried to delete the files from the same JVM with Files.delete(). I did not try to delete from other process on the system. Problem reproduces on Windows 7~10 with NTFS, probably not on other OSes.

I encourage others to edit this answer and add their observations.

Body:
In working with the WatchService, I found that if I delete a file in the directory being watched, it fires an ENTRY_MODIFY followed by an ENTRY_DELETE event.

I realize that technically, a file may be modified before deleted, but is it really the expected behavior that deleting a file will trigger ENTRY_MODIFY  (which presumably no one cares about)?

To handle this, I had to add a condition to check before firing passing along the ENTRY_MODIFY event:

            if (eventKind == ENTRY_CREATE) {
                listener.fileCreated(file);
            } else if (eventKind == ENTRY_MODIFY) {
                if (Files.exists(fullPath, LinkOption.NOFOLLOW_LINKS)) {
                    listener.fileChanged(file);
                }
            } else if (eventKind == ENTRY_DELETE) {
                listener.fileDeleted(file);
            }

Is this there a better way to handle this issue (feature)?


问:
Does Windows 7 still assign Event Log permissions via the Registry?
Very simple question that I've been having trouble answering.

In Windows XP and Server 2003, I have occasionally come across a problem when trying to write to the event log.

"The source was not found, but some or all event logs could not be searched.  Inaccessible logs: Security."

The solution to this that has worked in the past on XP and Server 2003 has been to give the correct user or user group Read or Full Control permissions to the registry key for the offending event log group. For example:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\  or

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\Security

This has always worked. But I've come up against Windows 7, with which I'm still very inexperienced.

I'm vaguely aware that Windows 7 and Vista do interesting things to try and downgrade the prominence of the Registry, virtualization and so forth. That gives me a tiny question mark as to whether or not Windows 7 still handles event log security in the same way.

I've done some searching on the topic, but haven't managed to find an answer to what (I thought) would have been a very simple question.

Any help pointing me in the right direction would be great.

答:
I'll follow up Igor with some clarification.

I forgot about this question altogether. Since posting it I had this issue clarified by a sysadmin at a client site.

He pointed out that the Event Source should be created in an installer package. The installer should require administrative permissions to run, which ensures that the current windows user will be allowed to create the event source.

My actual problem was that I was attempting to create the source from within the code itself. Giving the user group permission to do so was a hack work-around that I shouldn't have been doing in the first place.

The production code for this now still attempts to detect the source. On failure it will use the generic 'Application' source in place of the application-specific source.

The application-specific source is now created in the installer, and an entry about this has been included in the administrative documentation for the product.


问:
How to get the total sum
I have this code to school assignment, it works with no errors but it won't "sum" the number it's just show them together!
for example it shows like this:

Total:
2
3

and it suppose to be:
Total:
5

```<code>enter code here
public void getTotalPower()
{
   for (BigGun oneGun : gun)
   {
       System.out.println(oneGun.getNumberPower());
   }
}
</code>```

答:
if youre using java 8 you can use streams</p>

```<code>public void getTotalPower(){

    int totalPower = gun.stream()
                        .mapToInt(BigGun::getNumberPower)
                        .sum();
    System.out.println(totalPower);
}
</code>```

Title: How to get the total sum

Body:
I have this code to school assignment, it works with no errors but it won't "sum" the number it's just show them together!
for example it shows like this:

Total:
2
3

and it suppose to be:
Total:
5

enter code here
public void getTotalPower()
{
   for (BigGun oneGun : gun)
   {
       System.out.println(oneGun.getNumberPower());
   }
}

Body:
if youre using java 8 you can use streams

public void getTotalPower(){

    int totalPower = gun.stream()
                        .mapToInt(BigGun::getNumberPower)
                        .sum();
    System.out.println(totalPower);
}


问:
Android Studio 2.3 not deploying ui changes
since today im not able to deploy my UI changes anymore. The app runs fine but i cant change anything on the UI side. Whatever I do the app keeps the same UI every time. I changed nothing since my last dev session and now im stuck with this problem for hours.

What I tried so far:

Clean and Rebuild several Times

Disabled Instant Run

Deleted the Build folder

Checked for different Layout versions

Complete uninstall and reinstall of the app

Gradle Sync

Different Smartphones and Emulators

I can see all changes inside the preview of Android Studio but for some reason they dont appear in the deployed app.

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_send_media);
</code>```

答:
As you havent uploaded java file i am assuming This Might be your problem:
in your oncreate method please make sure that You havent used this by mistake

```<code>public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        setContentView();
    }
</code>```

it will persist your ui changes and wont update it.. so instead of this use following

```<code>@Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }
</code>```

Body:
since today im not able to deploy my UI changes anymore. The app runs fine but i cant change anything on the UI side. Whatever I do the app keeps the same UI every time. I changed nothing since my last dev session and now im stuck with this problem for hours.

What I tried so far:

Clean and Rebuild several Times

Disabled Instant Run

Deleted the Build folder

Checked for different Layout versions

Complete uninstall and reinstall of the app

Gradle Sync

Different Smartphones and Emulators

I can see all changes inside the preview of Android Studio but for some reason they dont appear in the deployed app.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_send_media);

Body:
As you havent uploaded java file i am assuming This Might be your problem:
in your oncreate method please make sure that You havent used this by mistake

public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        setContentView();
    }

it will persist your ui changes and wont update it.. so instead of this use following

@Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答:
The first Fortran code I wrote had an if statement in it, and was one of the most fascinating things I had seen at the time.  Something like this one</p>

```<code>     integer n

     n = 1
  20 if (n .le. 100) then
        n = 2*n
        write (*,*) n
        goto 20
     endif
</code>```

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Triptych

Body:
The first Fortran code I wrote had an if statement in it, and was one of the most fascinating things I had seen at the time.  Something like this one

     integer n

     n = 1
  20 if (n .le. 100) then
        n = 2*n
        write (*,*) n
        goto 20
     endif

OwnerDisplayName: mndoci

LastEditorDisplayName: mndoci


问:
routing with tollroad + motorway give bad request
Hie,
I use the following request with mode parameter

&mode = 'fastest;car;tollroad:-2'       ==>   Ok
&mode = 'fastest;car;mototorway:-2'     ==>   Ok

&mode = 'fastest;car;tollroad:-2;mototorway:-2' ==> Bad request

I didnt found my error? parameters exclusive? coding error? restriction?
Thanks for your help.

答:
The mode features are comma-separated:</p>

```<code>&mode = 'fastest;car;tollroad:-2,mototorway:-2'
</code>```

Body:
The mode features are comma-separated:

&mode = 'fastest;car;tollroad:-2,mototorway:-2'


问:
Horizontal aligment WPF expander header
I want to show my GroupName on left and button "ShowOnly" on the right of header row.
I tried with this code but doesn't works.
Could anyone help me?
Thx

My code :

```<code><Expander IsExpanded="True" >
    <Expander.Header>
        <DockPanel HorizontalAlignment="Stretch">
            <TextBlock Text="{Binding Path=Name}" FontSize="18"></TextBlock>
            <Button Style="{StaticResource ButtonStyle}" Content="Show Only" HorizontalAlignment="Right" Padding="15,0,15,0" Click="Button_Click"></Button>
        </DockPanel>
    </Expander.Header>
    <Expander.Style>
        <Style TargetType="{x:Type Expander}">
            <Setter Property="Background" Value="#f0f0f5"></Setter>
            <Setter Property="TextElement.FontFamily" Value="Arial Nova"/>
        </Style>
    </Expander.Style>
    <Expander.Content>
        <ItemsPresenter />
    </Expander.Content>
</Expander>
</code>```

My ButtonStyle :

```<code><Style x:Key="ButtonStyle" TargetType="Button">

            <Setter Property="Background" Value="#66e0ff" />
            <Setter Property="Foreground" Value="White" />
            <Setter Property="FontSize" Value="15" />
            <Setter Property="SnapsToDevicePixels" Value="True" />

            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border CornerRadius="4" Background="{TemplateBinding Background}">
                            <Grid>
                                <ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" />
                            </Grid>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Background" Value="White" />
                                <Setter Property="Foreground" Value="#66e0ff" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>

    </Style>
</code>```

I tried also with an DockPanel, but same result.

答:
Set width of DockPanel to width of expander so that it will stretch properly.</p>

```<code><DockPanel HorizontalAlignment="Stretch" Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Expander}}, Path=ActualWidth}">
</code>```

Title: Horizontal aligment WPF expander header

Body:
I want to show my GroupName on left and button "ShowOnly" on the right of header row.
I tried with this code but doesn't works.
Could anyone help me?
Thx

My code :

<Expander IsExpanded="True" >
    <Expander.Header>
        <DockPanel HorizontalAlignment="Stretch">
            <TextBlock Text="{Binding Path=Name}" FontSize="18"></TextBlock>
            <Button Style="{StaticResource ButtonStyle}" Content="Show Only" HorizontalAlignment="Right" Padding="15,0,15,0" Click="Button_Click"></Button>
        </DockPanel>
    </Expander.Header>
    <Expander.Style>

    </Expander.Style>
    <Expander.Content>
        <ItemsPresenter />
    </Expander.Content>
</Expander>

My ButtonStyle :

I tried also with an DockPanel, but same result.

Body:
Set width of DockPanel to width of expander so that it will stretch properly.

<DockPanel HorizontalAlignment="Stretch" Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Expander}}, Path=ActualWidth}">


问:
Beginner help Netlogo, Output-print
I am an absolute beginner to this Netlogo software and have no programming experience whatsoever on it. I am using a sample program provided with the software to run a science experiment and I just want the raw data to use for a project but I do not know how to acquire it. I heard I need to use an output-print command but I am not sure how to do this. Any help would be appreciated.</p>

答:
Dana, if you need to run multiple replicates I would check out Behavior Space. It is part of Netlogo (Tools -> Behavior Space) and allows you to easily save the output to a .csv file.

If you just want a quick and not-so-pretty data out, you could do something like:

```<code>to setup
  ca
  reset-ticks
end

to go
  tick
  print-to-file
end

to print-to-file

  file-open "example.csv"
  file-type (word ticks ",\n");; replace ticks with the variable you want out
  file-close

end
</code>```

Which appends your output to the file "example.csv".

Title: Beginner help Netlogo, Output-print

Body:
Dana, if you need to run multiple replicates I would check out Behavior Space. It is part of Netlogo (Tools -> Behavior Space) and allows you to easily save the output to a .csv file.

If you just want a quick and not-so-pretty data out, you could do something like:

to setup
  ca
  reset-ticks
end

to go
  tick
  print-to-file
end

to print-to-file

  file-open "example.csv"
  file-type (word ticks ",\n");; replace ticks with the variable you want out
  file-close

end

Which appends your output to the file "example.csv".


问:
Apache Camel - Calling method from autowired object in @Produce
I have the following in a unit test for a Camel route:

RouteUnitTest.java

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {RouteUnitTestConfig.class})
public class RouteUnitTest extends CamelTestSupport {
    @Autowired
    MQProperties mqProps;
    @Autowired
    Route route;

    @Produce(uri="...")
    ProducerTempalte template;

    @Test
    //rest of test class

}
</code>```

The MQProperties object pulls properties from property files, and for unit tests it reads the application-unit-test.properties file, which uses SEDA endpoints for unit testing. I can't seem to get the expression correct in the @Produce tag; I want to set the ProducerTemplates uri to mqProps.getReceiveQueue(), but out of the formats I've tried, I get an exception regarding setting a default endpoint for the producer. I know that it's not an issue with the value that should be passed in, calling template.send(mqProps.getReceiveQueue(), exchange); for example works just fine. I have tried the following formats:

```<code>@Produce(uri="#{@mqProps.getReceiveQueue}")
@Produce(uri="{{mqProps.getReceiveQueue}}")
@Produce(uri="#{mqProps.getReceiveQueue}")
</code>```

These have thrown the exception mentioned. Am I getting the EL format wrong, or is it an issue with the autowiring?i.e. Maybe the object isn't populated by the time the producer uri stuff is all hooked up? I can't find much else on this, Camel resources talk more around Bean injction etc, but any resources I've seen thus far on the @Produce annotation usually use a hardcoded string, or read from a property file directly

答:
I believe the problem is with the BeanExpressionContext

Spring needs this to evaluate SPEL. Here is a simpleexample to solve this issue. Adapt it to your project.

```<code>  public class TestingSupport {

  @Bean
  public BeanExpressionContext setBeanExpressionContext(@Autowired MQProperties mqProps, @Autowired ApplicationContext applicationContext){
    return new BeanExpressionContext((ConfigurableBeanFactory) applicationContext.getAutowireCapableBeanFactory(), null);
  }
}
</code>```

And the testing class would look like this.

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {RouteUnitTestConfig.class, MQProperties.class, TestingSupport.class})
@TestPropertySource("classpath:application-test.properties")
public class RouteUnitTest extends CamelTestSupport {

  @Value("#{MQProperties['receiveQueue']}")
  String recieveQueue;

  @Test
  public void test(){
      assertEquals(1, 1);
  }

}
</code>```

Body:
I have the following in a unit test for a Camel route:

RouteUnitTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {RouteUnitTestConfig.class})
public class RouteUnitTest extends CamelTestSupport {
    @Autowired
    MQProperties mqProps;
    @Autowired
    Route route;

    @Produce(uri="...")
    ProducerTempalte template;

    @Test
    //rest of test class

}

The MQProperties object pulls properties from property files, and for unit tests it reads the application-unit-test.properties file, which uses SEDA endpoints for unit testing. I can't seem to get the expression correct in the @Produce tag; I want to set the ProducerTemplates uri to mqProps.getReceiveQueue(), but out of the formats I've tried, I get an exception regarding setting a default endpoint for the producer. I know that it's not an issue with the value that should be passed in, calling template.send(mqProps.getReceiveQueue(), exchange); for example works just fine. I have tried the following formats:

@Produce(uri="#{@mqProps.getReceiveQueue}")
@Produce(uri="{{mqProps.getReceiveQueue}}")
@Produce(uri="#{mqProps.getReceiveQueue}")

These have thrown the exception mentioned. Am I getting the EL format wrong, or is it an issue with the autowiring?i.e. Maybe the object isn't populated by the time the producer uri stuff is all hooked up? I can't find much else on this, Camel resources talk more around Bean injction etc, but any resources I've seen thus far on the @Produce annotation usually use a hardcoded string, or read from a property file directly

Body:
I believe the problem is with the BeanExpressionContext

Spring needs this to evaluate SPEL. Here is a simpleexample to solve this issue. Adapt it to your project.

  public class TestingSupport {

  @Bean
  public BeanExpressionContext setBeanExpressionContext(@Autowired MQProperties mqProps, @Autowired ApplicationContext applicationContext){
    return new BeanExpressionContext((ConfigurableBeanFactory) applicationContext.getAutowireCapableBeanFactory(), null);
  }
}

And the testing class would look like this.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {RouteUnitTestConfig.class, MQProperties.class, TestingSupport.class})
@TestPropertySource("classpath:application-test.properties")
public class RouteUnitTest extends CamelTestSupport {

  @Value("#{MQProperties['receiveQueue']}")
  String recieveQueue;

  @Test
  public void test(){
      assertEquals(1, 1);
  }

}


问:
Substring comparision with std::memcmp or string::compare?
I want to find a given string within another string. Possible start poisition in known by previous calculations. Example:

```<code>int main()
{
    std::string input("Foo Bar Hash Bang");
    std::string keyword("Bar");

    const char* inputStart = input.c_str() + 4; // at 'B'
    std::cout << "memcmp=" << std::memcmp(inputStart, keyword.c_str(), keyword.length()) << "\n";

    std::cout << "compare=" << input.compare(4, keyword.length(), keyword) << "\n";

    return 0;
}
</code>```

Ideone

Are both equivalent? If the keyword length would exceed the input length from the start position the comparision with memcmp would be still correct. Is strncmp the safer approach?

答:
You could use std::string_view:

```<code>bool matchSubstring(std::string_view haystack,
                    std::string_view needle,
                    std::size_t pos)
{
    if(haystack.size() < pos + needle.size()) return false;
    return haystack.compare(pos, needle.size(), needle) == 0;
}
</code>```

Usage:

```<code>std::string input("Foo Bar Hash Bang");
std::string keyword("Bar");

std::cout << std::boolalpha << matchSubstring(input, keyword, 4) << "\n"
                            << matchSubstring(input, keyword, 5) << "\n"
                            << matchSubstring(input, keyword, 1000) << "\n";
</code>```

true false false

live wandbox example

Body:
I want to find a given string within another string. Possible start poisition in known by previous calculations. Example:

int main()
{
    std::string input("Foo Bar Hash Bang");
    std::string keyword("Bar");

    const char* inputStart = input.c_str() + 4; // at 'B'
    std::cout << "memcmp=" << std::memcmp(inputStart, keyword.c_str(), keyword.length()) << "\n";

    std::cout << "compare=" << input.compare(4, keyword.length(), keyword) << "\n";

    return 0;
}

Ideone

Are both equivalent? If the keyword length would exceed the input length from the start position the comparision with memcmp would be still correct. Is strncmp the safer approach?

Body:
You could use std::string_view:

bool matchSubstring(std::string_view haystack,
                    std::string_view needle,
                    std::size_t pos)
{
    if(haystack.size() < pos + needle.size()) return false;
    return haystack.compare(pos, needle.size(), needle) == 0;
}

Usage:

std::string input("Foo Bar Hash Bang");
std::string keyword("Bar");

std::cout << std::boolalpha << matchSubstring(input, keyword, 4) << "\n"
                            << matchSubstring(input, keyword, 5) << "\n"
                            << matchSubstring(input, keyword, 1000) << "\n";

true false false

live wandbox example


问:
How do I know when a copy job is done?
I'm using

```<code>File.Copy(source, dest);
</code>```

I need to know when this copy job is done processing so that it can move on to another task.

Is there any callback function I could use in this particular case?

答: File.Copy is blocking so execution should wait until the operation has complete.</p>

Title: How do I know when a copy job is done?

Body:
I'm using

File.Copy(source, dest);

I need to know when this copy job is done processing so that it can move on to another task.

Is there any callback function I could use in this particular case?


问:
sed: replace many lines from a file with single notification
I'm looking for a solution in GNU sed, but POSIX sed is OK and awk will be OK but probably more complicated than necessary. I prefer sed for this, it should be easy but I'm stuck. Seems like a one-liner can do this, no need to create a python/bash script or anything.

my attempted solution

```<code>  sed -i '218,226140d; 218i ...REMOVED...' psql.log
</code>```

This deletes the desired rows, but the insert gets lost. If I move the insert to line 217 I get:

```<code>  sed -i '218,226140d; 217i ...REMOVED...' psql.log
</code>```

result:

```<code>  ┌────────────┬─────────────────────┬─────────────────┐
  │ col_one    │     col_two         │ column_three    │
  ├────────────┼─────────────────────┼─────────────────┤
  │ CC00CBSNRY │           553854451 │       15003.44  │
  │ CC00CBSNRY │          1334177150 │        5159.57  │
  ...REMOVED...
  │ CC6XDSQGH2 │         42385958605 │ [null]          │ (line 217 in original file)
  │ CC6XJ8YG5C │         24661013005 │ [null]          │ (line 226141 in original file)
  │ CC6XJ9HGRG │         44946564505 │ [null]          │
  │ CC6XMQW6SJ │         34496719615 │ [null]          │
  └────────────┴─────────────────────┴─────────────────┘
</code>```

I know - this should be good enough, but I'm annoyed that I can't get this simple one-liner to work right. What am I missing?

the problem

I keep the psql.log file as a reference for work I am doing developing SQL code. It's very useful to see iterations of the query and the results.

The problem is that sometimes I forget to limit the output and the query will generate 100k+ rows of results that aren't a helpful reference, and I'd like to delete them from my file, leaving a note that reminds me the query output has been excised.

It would be nice to match the pattern, say every output more than 50 rows I could squash down to just the first 5 rows and the last 5.  However, its easy for me to mark the line numbers where I've blown up the file, so I'd be happy with just using sed to delete lines N through M, and insert the message ...REMOVED... where line N was.

Here is an example log file, added notes are in parentheses. The query text can change and the number of columns can be from 1 to 100 or more:

```<code>  ...
  ********* QUERY **********
  select      *
  from        table
  where       rnk <= 3
  **************************

  ┌────────────┬─────────────────────┬─────────────────┐
  │ col_one    │     col_two         │ column_three    │
  ├────────────┼─────────────────────┼─────────────────┤
  │ CC00CBSNRY │           553854451 │       15003.44  │
  │ CC00CBSNRY │          1334177150 │        5159.57  │
  │ CC6XDSQGH2 │         42385958605 │ [null]          │ (line 217)
  │ CC6XF2SVWT │         13182280615 │ [null]          │
  (many rows)

  │ CC6XF2XWDT │           995086081 │ [null]          │
  │ CC6XFX3TL1 │         25195177405 │ [null]          │
  │ CC6XJ8YG5C │         24661013005 │ [null]          │  (line 226141)
  │ CC6XJ9HGRG │         44946564505 │ [null]          │
  │ CC6XMQW6SJ │         34496719615 │ [null]          │
  └────────────┴─────────────────────┴─────────────────┘
  (225926 rows)

  ********* QUERY **********
  /* another query begins */

  select * from table where X = 1 limit 20;

  /* well done you remembered to limit the output */
  **************************
  ...
</code>```

acceptable output

the query text should all be untouched, and the top/bottom three rows of output kept. The annotation ...REMOVED... has been added and rows 218 through 226140 have been deleted:

```<code>  ********* QUERY **********
  select      *
  from        table
  where       rnk <= 3
  **************************

  ┌────────────┬─────────────────────┬─────────────────┐
  │ col_one    │     col_two         │ column_three    │
  ├────────────┼─────────────────────┼─────────────────┤
  │ CC00CBSNRY │           553854451 │       15003.44  │
  │ CC00CBSNRY │          1334177150 │        5159.57  │
  │ CC6XDSQGH2 │         42385958605 │ [null]          │ (line 217 in original file)
  ...REMOVED...
  │ CC6XJ8YG5C │         24661013005 │ [null]          │ (line 226141 in original file)
  │ CC6XJ9HGRG │         44946564505 │ [null]          │
  │ CC6XMQW6SJ │         34496719615 │ [null]          │
  └────────────┴─────────────────────┴─────────────────┘
  (225926 rows)

  ********* QUERY **********
  (etc just like example above)
</code>```

update

the border comes from my .psqlrc with \pset border 2

therefore solutions depending on the ┌ character are fragile but OK

over time i've learned that manually flagging the line numbers is too time consuming, so the best solution needs a pattern match

答:
This might work for you (GNU sed):

```<code>sed -r '/\o342[^\n]*$/{:a;N;//ba;s/^(([^\n]*\n){6}).*((\n[^\n]*){5})$/\1  ... REMOVED ...\3/}' file
</code>```

Focus only on table data which will always contains the octal value 342. Gather up table lines in the pattern space, substitute the required value ... REMOVED ... and print. The number of lines above and below the required string can be altered here 6 (headings + 3 rows) and 5 (required string + 3 rows + table count).

To change a range use:

```<code>sed 'm,nc ... REMOVE ...' file # where m,n from and to line numbers
</code>```

or:

```<code>sed -e 'ma ...REMOVE ...' -e 'm,nd' file
</code>```

N.B. the d command terminates any following commands.

Body:
I'm looking for a solution in GNU sed, but POSIX sed is OK and awk will be OK but probably more complicated than necessary. I prefer sed for this, it should be easy but I'm stuck. Seems like a one-liner can do this, no need to create a python/bash script or anything.

my attempted solution

  sed -i '218,226140d; 218i ...REMOVED...' psql.log

This deletes the desired rows, but the insert gets lost. If I move the insert to line 217 I get:

  sed -i '218,226140d; 217i ...REMOVED...' psql.log

result:

  ┌────────────┬─────────────────────┬─────────────────┐
  │ col_one    │     col_two         │ column_three    │
  ├────────────┼─────────────────────┼─────────────────┤
  │ CC00CBSNRY │           553854451 │       15003.44  │
  │ CC00CBSNRY │          1334177150 │        5159.57  │
  ...REMOVED...
  │ CC6XDSQGH2 │         42385958605 │ [null]          │ (line 217 in original file)
  │ CC6XJ8YG5C │         24661013005 │ [null]          │ (line 226141 in original file)
  │ CC6XJ9HGRG │         44946564505 │ [null]          │
  │ CC6XMQW6SJ │         34496719615 │ [null]          │
  └────────────┴─────────────────────┴─────────────────┘

I know - this should be good enough, but I'm annoyed that I can't get this simple one-liner to work right. What am I missing?

the problem

I keep the psql.log file as a reference for work I am doing developing SQL code. It's very useful to see iterations of the query and the results.

The problem is that sometimes I forget to limit the output and the query will generate 100k+ rows of results that aren't a helpful reference, and I'd like to delete them from my file, leaving a note that reminds me the query output has been excised.

It would be nice to match the pattern, say every output more than 50 rows I could squash down to just the first 5 rows and the last 5.  However, its easy for me to mark the line numbers where I've blown up the file, so I'd be happy with just using sed to delete lines N through M, and insert the message ...REMOVED... where line N was.

Here is an example log file, added notes are in parentheses. The query text can change and the number of columns can be from 1 to 100 or more:

  ...
  ********* QUERY **********
  select      *
  from        table
  where       rnk <= 3
  **************************

  ┌────────────┬─────────────────────┬─────────────────┐
  │ col_one    │     col_two         │ column_three    │
  ├────────────┼─────────────────────┼─────────────────┤
  │ CC00CBSNRY │           553854451 │       15003.44  │
  │ CC00CBSNRY │          1334177150 │        5159.57  │
  │ CC6XDSQGH2 │         42385958605 │ [null]          │ (line 217)
  │ CC6XF2SVWT │         13182280615 │ [null]          │
  (many rows)

  │ CC6XF2XWDT │           995086081 │ [null]          │
  │ CC6XFX3TL1 │         25195177405 │ [null]          │
  │ CC6XJ8YG5C │         24661013005 │ [null]          │  (line 226141)
  │ CC6XJ9HGRG │         44946564505 │ [null]          │
  │ CC6XMQW6SJ │         34496719615 │ [null]          │
  └────────────┴─────────────────────┴─────────────────┘
  (225926 rows)

  ********* QUERY **********
  /* another query begins */

  select * from table where X = 1 limit 20;

  /* well done you remembered to limit the output */
  **************************
  ...

acceptable output

the query text should all be untouched, and the top/bottom three rows of output kept. The annotation ...REMOVED... has been added and rows 218 through 226140 have been deleted:

  ********* QUERY **********
  select      *
  from        table
  where       rnk <= 3
  **************************

  ┌────────────┬─────────────────────┬─────────────────┐
  │ col_one    │     col_two         │ column_three    │
  ├────────────┼─────────────────────┼─────────────────┤
  │ CC00CBSNRY │           553854451 │       15003.44  │
  │ CC00CBSNRY │          1334177150 │        5159.57  │
  │ CC6XDSQGH2 │         42385958605 │ [null]          │ (line 217 in original file)
  ...REMOVED...
  │ CC6XJ8YG5C │         24661013005 │ [null]          │ (line 226141 in original file)
  │ CC6XJ9HGRG │         44946564505 │ [null]          │
  │ CC6XMQW6SJ │         34496719615 │ [null]          │
  └────────────┴─────────────────────┴─────────────────┘
  (225926 rows)

  ********* QUERY **********
  (etc just like example above)

update

the border comes from my .psqlrc with \pset border 2

therefore solutions depending on the ┌ character are fragile but OK

over time i've learned that manually flagging the line numbers is too time consuming, so the best solution needs a pattern match

Body:
This might work for you (GNU sed):

sed -r '/\o342[^\n]*$/{:a;N;//ba;s/^(([^\n]*\n){6}).*((\n[^\n]*){5})$/\1  ... REMOVED ...\3/}' file

Focus only on table data which will always contains the octal value 342. Gather up table lines in the pattern space, substitute the required value ... REMOVED ... and print. The number of lines above and below the required string can be altered here 6 (headings + 3 rows) and 5 (required string + 3 rows + table count).

To change a range use:

sed 'm,nc ... REMOVE ...' file # where m,n from and to line numbers

or:

sed -e 'ma ...REMOVE ...' -e 'm,nd' file

N.B. the d command terminates any following commands.


问:
How to Initialize adapter in RecycleVIew?
Before this i am using ListView and it is working fine. But i want to set the ListView in Horizontal. so i came to know that RecycleView is more reliable then listview.

am trying to work with Recycle View and getting error like

```<code> No adapter attached; skipping layout
</code>```

It means that the problem is in my adapter class i don't know what the code is required in my adapter class i just tried this way.

main.java

```<code>public class DynamicButon extends Fragment {
    public DynamicButon(){};
    JSONObject jsonobject;
    JSONArray ownerObj;
     private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;

    ListViewAdapterDynamic mAdapter;
    ArrayList<HashMap<String, String>> arraylist;
    String uid = "0";
    SessionManager session;
    private static String url_visitor = "";
    JSONParser jParser = new JSONParser();
    ArrayList<String> itemwod = new ArrayList<String>();

    View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_dynamic_buton, container, false);
        getActivity().setTitle("Complete Order");
        // listview = (ListView) view.findViewById(R.id.lvvisit);

        session = new SessionManager(getActivity());
        HashMap<String, String> user = session.getUserDetails();
        uid = user.get(SessionManager.KEY_ID);
        new DownloadJSON().execute();
        return view;
    }

    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
          //  avi.show();
        }

        @Override
        protected Void doInBackground(Void... args) {
            try {
                arraylist = new ArrayList<HashMap<String, String>>();
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", uid));
                JSONObject json = jParser.makeHttpRequest(url_visitor, "GET", params);

                int success1 = Integer.parseInt(json.getString("success4"));
                Log.d("success4", json.toString());

                if (success1 == 0) {
                    Snackbar.make(view, "Not Data Found", Snackbar.LENGTH_LONG).show();
                }
                if (success1 == 1) {
                    ownerObj = json.getJSONArray("cy");

                    for (int i = 0; i < ownerObj.length(); i++) {
                        jsonobject = ownerObj.getJSONObject(i);

                        item.add(jsonobject.getString("company"));
                    }
                }
            } catch (Exception e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {

 mRecyclerView = (RecyclerView)getActivity().findViewById(R.id.mylist);
        mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);

        mAdapter = new ListViewAdapterDynamic(getActivity(), itemwod);
        mRecyclerView.setAdapter(mAdapter);
        }
    }
}
</code>```

ListViewAdapter

```<code>import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by sachin on 3/15/2017.
 */

public class ListViewAdapterDynamic extends BaseAdapter {
    Context cntx;

    View view;

    ArrayList<String> itemwod = new ArrayList<String>();

    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    HashMap<String, String> resultp = new HashMap<String, String>();

    public ListViewAdapterDynamic(Context context,
                                        ArrayList<String> o_parties
    ) {
        // TODO Auto-generated constructor stub
        cntx = context;
        itemwod = o_parties;
    }

    @Override
    public int getCount() {
        return itemwod.size();
    }

    @Override
    public Object getItem(int position) {
        return itemwod.get(position);
    }

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

    @SuppressWarnings("deprecation")
    public View getView(final int position, View convertView, ViewGroup parent) {

        Button cancel;

        inflater = (LayoutInflater) cntx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        LayoutInflater inflater = LayoutInflater.from(cntx);

        convertView = inflater.inflate(R.layout.raw_dynamic, parent,
                false);

         cancel=(Button)convertView.findViewById(R.id.btn) ;
        cancel.setText(itemwod.get(position));
        return convertView;
    }

}
</code>```

Like this way i try but not working in ListViewAdapterDynamic i tried to implement

```<code>  RecyclerView.Adapter<MyViewHolder>
</code>```

then getting errors that's why i just kept extends Baseadapter what i did i listview.

答:
Use RecyclerView to set your list Items.

reference https://acadgild.com/blog/horizontal-listview-android/

Body:
Before this i am using ListView and it is working fine. But i want to set the ListView in Horizontal. so i came to know that RecycleView is more reliable then listview.

am trying to work with Recycle View and getting error like

 No adapter attached; skipping layout

It means that the problem is in my adapter class i don't know what the code is required in my adapter class i just tried this way.

main.java

public class DynamicButon extends Fragment {
    public DynamicButon(){};
    JSONObject jsonobject;
    JSONArray ownerObj;
     private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;

    ListViewAdapterDynamic mAdapter;
    ArrayList<HashMap<String, String>> arraylist;
    String uid = "0";
    SessionManager session;
    private static String url_visitor = "";
    JSONParser jParser = new JSONParser();
    ArrayList<String> itemwod = new ArrayList<String>();

    View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_dynamic_buton, container, false);
        getActivity().setTitle("Complete Order");
        // listview = (ListView) view.findViewById(R.id.lvvisit);

        session = new SessionManager(getActivity());
        HashMap<String, String> user = session.getUserDetails();
        uid = user.get(SessionManager.KEY_ID);
        new DownloadJSON().execute();
        return view;
    }

    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
          //  avi.show();
        }

        @Override
        protected Void doInBackground(Void... args) {
            try {
                arraylist = new ArrayList<HashMap<String, String>>();
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", uid));
                JSONObject json = jParser.makeHttpRequest(url_visitor, "GET", params);

                int success1 = Integer.parseInt(json.getString("success4"));
                Log.d("success4", json.toString());

                if (success1 == 0) {
                    Snackbar.make(view, "Not Data Found", Snackbar.LENGTH_LONG).show();
                }
                if (success1 == 1) {
                    ownerObj = json.getJSONArray("cy");

                    for (int i = 0; i < ownerObj.length(); i++) {
                        jsonobject = ownerObj.getJSONObject(i);

                        item.add(jsonobject.getString("company"));
                    }
                }
            } catch (Exception e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {

 mRecyclerView = (RecyclerView)getActivity().findViewById(R.id.mylist);
        mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);

        mAdapter = new ListViewAdapterDynamic(getActivity(), itemwod);
        mRecyclerView.setAdapter(mAdapter);
        }
    }
}

ListViewAdapter

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by sachin on 3/15/2017.
 */

public class ListViewAdapterDynamic extends BaseAdapter {
    Context cntx;

    View view;

    ArrayList<String> itemwod = new ArrayList<String>();

    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    HashMap<String, String> resultp = new HashMap<String, String>();

    public ListViewAdapterDynamic(Context context,
                                        ArrayList<String> o_parties
    ) {
        // TODO Auto-generated constructor stub
        cntx = context;
        itemwod = o_parties;
    }

    @Override
    public int getCount() {
        return itemwod.size();
    }

    @Override
    public Object getItem(int position) {
        return itemwod.get(position);
    }

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

    @SuppressWarnings("deprecation")
    public View getView(final int position, View convertView, ViewGroup parent) {

        Button cancel;

        inflater = (LayoutInflater) cntx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        LayoutInflater inflater = LayoutInflater.from(cntx);

        convertView = inflater.inflate(R.layout.raw_dynamic, parent,
                false);

         cancel=(Button)convertView.findViewById(R.id.btn) ;
        cancel.setText(itemwod.get(position));
        return convertView;
    }

}

Like this way i try but not working in ListViewAdapterDynamic i tried to implement

  RecyclerView.Adapter<MyViewHolder>

then getting errors that's why i just kept extends Baseadapter what i did i listview.


问:
Adding cookie to HttpServletRequest and retrieving cookie from HttpServletResponse using Mockito
I am using Mockito to mock HttpServletRequest and HttpServletResponse. I want to add cookie in the the mock request I am creating. How can I do so?

Also I am setting the cookie in the response at the server side. How can I retrieve the cookie from the mock response sent by the server?

答: Use MockHttpServletResponse that implements HttpServletResponse. It has getCookies / getCookie method on which assertions can be done. </p>


问:
Is there another way of running your created UI using GUI Builder in eclipse(Codenameone) beside this line of code: "new MyGuiBuilderForm().show()"?
Is there another way of running your created UI using GUI Builder in eclipse(Codenameone) beside this line of code: new MyGuiBuilderForm().show()?

答:
Beside using theme , you can create form  by coding as shown below </p>

```<code>Form form = new Form("Hello");
form.add(new Button("Test"));
form.show();
</code>```

Body:
Beside using theme , you can create form  by coding as shown below

Form form = new Form("Hello");
form.add(new Button("Test"));
form.show();


问:
OData PHP Producer
I need to create a PHP OData producer supporting both GET and PUT. Up to now I've only found this library, unfortunately this not support PUT operation.
Any suggestions?
Thank's</p>

答:
Just released. Documentation is coming.

https://packagist.org/packages/falseclock/dbd-php

```<code>    $cache = DBD\Cache\MemCache::me()->create(array(['host' => '127.0.0.1', 'port' => 11211]),false,"15 min")->open();

    $odata_options = array(
        'RaiseError'        => true,
        'PrintError'        => true,
        'HTMLError'         => true,
        'CacheDriver'       => $cache
    );

    $od = (new DBD\OData())->create('http://crm.beta.virtex.kz/odata/', "user", "password", $odata_options);

    $sth = $od->prepare("
        SELECT
            Ref_Key, Number, Date
        FROM
            Document_Invoices
        ORDER BY
            Date аsc
        LIMIT 10
    ");
    $sth->cache('CacheKey','24h');
    $sth->execute();

    while ($row = $sth->fetchrow()) {
        print_r($row);
    }

$od->update(
    'Document_Invoices',
    array('Date' => $data['Date']),
    "(guid?)",
    $data['Ref_Key'] // for ?-placeholder
);
</code>```

Title: OData PHP Producer

Body:
Just released. Documentation is coming.

https://packagist.org/packages/falseclock/dbd-php

    $cache = DBD\Cache\MemCache::me()->create(array(['host' => '127.0.0.1', 'port' => 11211]),false,"15 min")->open();

    $odata_options = array(
        'RaiseError'        => true,
        'PrintError'        => true,
        'HTMLError'         => true,
        'CacheDriver'       => $cache
    );

    $od = (new DBD\OData())->create('http://crm.beta.virtex.kz/odata/', "user", "password", $odata_options);

    $sth = $od->prepare("
        SELECT
            Ref_Key, Number, Date
        FROM
            Document_Invoices
        ORDER BY
            Date аsc
        LIMIT 10
    ");
    $sth->cache('CacheKey','24h');
    $sth->execute();

    while ($row = $sth->fetchrow()) {
        print_r($row);
    }

$od->update(
    'Document_Invoices',
    array('Date' => $data['Date']),
    "(guid?)",
    $data['Ref_Key'] // for ?-placeholder
);


问:
Strange Memory Behavoir in JNI
I have found some strange behavior concerning multidimensional arrays in JNI and after hours of research I still have no idea how to solve my problem. I have the following JNI code:

```<code>JNIEXPORT jobject JNICALL Java_leaktest_NativeClass_nativeCalculation
  (JNIEnv *env, jobject thiz, jobjectArray arr) {

    double** multidimArray = new double*[512];

    for (int i = 0;i < 512;i++) {
        multidimArray[i] = new double[512];

        for (int j = 0;j < 512;j++) {
            multidimArray[i][j] = i * j;
        }
    }

    jobjectArray jMultidimArray = env->NewObjectArray(512, env->FindClass("[D"), 0);

    for (int i = 0;i < 512;i++) {
        jdoubleArray row = env->NewDoubleArray(512);

        jdouble* elems = (jdouble*)multidimArray[i];

        env->SetDoubleArrayRegion(row, 0, 512, elems);
        env->SetObjectArrayElement(jMultidimArray, i, row);

        env->DeleteLocalRef(row);
    }

    jclass arrayClass = env->FindClass("leaktest/ArrayClass");

    jobject arrObj = env->NewObject(arrayClass, env->GetMethodID(arrayClass, "<init>", "(II[[D)V"), 512, 512, jMultidimArray);

    for (int i = 0;i < 512;i++) {
        delete multidimArray[i];
    }

    delete multidimArray;

    return arrObj;
}
</code>```

In Java, I simply call this native Method repeatedly. With every call the displayed amount of RAM occupied by the JVM increases by about 1 to 2 MB. It appears to me that I am somewhere allocating memory in the C++ part and never releasing it, but I have no idea where that should occur.

Michael

答:
My guess is it would be here

jclass arrayClass = env->FindClass("leaktest/ArrayClass");

```<code>jobject arrObj = env->NewObject(arrayClass, env->GetMethodID(arrayClass, "<init>", "(II[[D)V"), 512, 512, jMultidimArray);
</code>```

Title: Strange Memory Behavoir in JNI

Body:
I have found some strange behavior concerning multidimensional arrays in JNI and after hours of research I still have no idea how to solve my problem. I have the following JNI code:

JNIEXPORT jobject JNICALL Java_leaktest_NativeClass_nativeCalculation
  (JNIEnv *env, jobject thiz, jobjectArray arr) {

    double** multidimArray = new double*[512];

    for (int i = 0;i < 512;i++) {
        multidimArray[i] = new double[512];

        for (int j = 0;j < 512;j++) {
            multidimArray[i][j] = i * j;
        }
    }

    jobjectArray jMultidimArray = env->NewObjectArray(512, env->FindClass("[D"), 0);

    for (int i = 0;i < 512;i++) {
        jdoubleArray row = env->NewDoubleArray(512);

        jdouble* elems = (jdouble*)multidimArray[i];

        env->SetDoubleArrayRegion(row, 0, 512, elems);
        env->SetObjectArrayElement(jMultidimArray, i, row);

        env->DeleteLocalRef(row);
    }

    jclass arrayClass = env->FindClass("leaktest/ArrayClass");

    jobject arrObj = env->NewObject(arrayClass, env->GetMethodID(arrayClass, "<init>", "(II[[D)V"), 512, 512, jMultidimArray);

    for (int i = 0;i < 512;i++) {
        delete multidimArray[i];
    }

    delete multidimArray;

    return arrObj;
}

In Java, I simply call this native Method repeatedly. With every call the displayed amount of RAM occupied by the JVM increases by about 1 to 2 MB. It appears to me that I am somewhere allocating memory in the C++ part and never releasing it, but I have no idea where that should occur.

Michael

Body:
My guess is it would be here

jclass arrayClass = env->FindClass("leaktest/ArrayClass");

jobject arrObj = env->NewObject(arrayClass, env->GetMethodID(arrayClass, "<init>", "(II[[D)V"), 512, 512, jMultidimArray);


问:
Make directory in android
Im trying to build a directory called "images" on the SD card on android. This is my code but its not working? Can anyone give me some advice?</p>

```<code>File picDirectory = new File("mnt/sdcard/images");
picDirectory.mkdirs();
</code>```

答:
To create file inside sd card you have to use Environment.getExternalStorageDirectory()

```<code>   /**
     * Creates a new directory inside external storage if not already exist.
     *
     * @param name The directory name
     */
    public static void createNewDirectory(String name) {
            // create a directory before creating a new file inside it.
            File directory = new File(Environment.getExternalStorageDirectory(), name);
            if (!directory.exists()) {
                directory.mkdirs();
            }
        }
</code>```

Following two important parameter which helps you to create directory
 1. directory.mkdirs() :

Creates the directory named by this file, creating missing parent
      directories if necessary.
 2. directory.mkdir() :

Creates the directory named by this file, assuming its parents exist.

For more you can how getExternalStorageDirectory() works please see link

Title: Make directory in android

Body:
Im trying to build a directory called "images" on the SD card on android. This is my code but its not working? Can anyone give me some advice?

File picDirectory = new File("mnt/sdcard/images");
picDirectory.mkdirs();

Body:
To create file inside sd card you have to use Environment.getExternalStorageDirectory()

   /**
     * Creates a new directory inside external storage if not already exist.
     *
     * @param name The directory name
     */
    public static void createNewDirectory(String name) {
            // create a directory before creating a new file inside it.
            File directory = new File(Environment.getExternalStorageDirectory(), name);
            if (!directory.exists()) {
                directory.mkdirs();
            }
        }

Following two important parameter which helps you to create directory
 1. directory.mkdirs() :

Creates the directory named by this file, creating missing parent
      directories if necessary.
 2. directory.mkdir() :

Creates the directory named by this file, assuming its parents exist.

For more you can how getExternalStorageDirectory() works please see link


问:
How can I move all files and directories from disk to the folder on this disk?
I have disk D with the files and directories. I want to move all files and directories including the root of disk D to the new folder saving the tree.

For example, I have file D:\1.txt. I want to move it to D:\new_folder\1.txt

The second example. I have file D:\1\1\1.txt. I want to move it to D:\new_folder\1\1\1.txt

As you can see, I want to move all contents of disk D to the folder  D:\new_folder\.

I tried robocopy, but it can't move from root of disk.

答:
This will copy all files and folders and preserve the folder structure:</p>

```<code>$sourcePath = "D:\"
$destPath = "D:\new_folder\"

Get-ChildItem $sourcePath -Recurse | Foreach-Object {
    $destDir = Split-Path ($_.FullName -Replace [regex]::Escape($sourcePath), $destPath)
    if (!(Test-Path $destDir)) {
        New-Item -ItemType directory $destDir | Out-Null
    }
    Copy-Item $_.FullName -Destination $destDir
}
</code>```

Body:
This will copy all files and folders and preserve the folder structure:

$sourcePath = "D:\"
$destPath = "D:\new_folder\"

Get-ChildItem $sourcePath -Recurse | Foreach-Object {
    $destDir = Split-Path ($_.FullName -Replace [regex]::Escape($sourcePath), $destPath)
    if (!(Test-Path $destDir)) {
        New-Item -ItemType directory $destDir | Out-Null
    }
    Copy-Item $_.FullName -Destination $destDir
}


问:
shellsort algorithm isn't working
I wanted to implement shellsort myself instead of copy pasting the ones online, I would appreciate if anyone could help me find the mistake and improve my silly lil code I will put down my code down below

```<code>#include <iostream>
#include <cmath>

using namespace std;

void swap(int p, int j, int *arr);
void shellSort(int arr[], int gap, int size);

int main() {
    int array[] = {12, 2, 4, 23, 5, 1, 6, 8, 16, 64, 32, 7, 43, 243, 76};
    int size = 15;
    for (int i = 15; i >= 1; i /= 2) {
        shellSort(array,i,size);
        cout << i << endl;
    }

    print(array, 15);
    // shellSortwhile(array, 15);
    print(array, 15);
}

void shellSort(int arr[], int gap, int size) {
    for (int i = 0; i < size; i += gap) {
        if (arr[i] > arr[i + gap]) {
            swap(i, i + gap, arr);
            for(int j = i; j >= 0; j -= gap) {
                if (arr[j] < arr[j - gap]) {
                    swap(j-gap, j, arr);
                }
            }
        }
    }
}
</code>```

My output is:

```<code>Now the array will be printed
2
4
5
6
7
7
8
1076814756
12
15
16
23
32
43
64
</code>```

答:
```<code>#include <iostream>
#include <cmath>
using namespace std;
void swap(int p, int j, int* arr );
void shellSortwhile(int arr[], int size);
void shellSort(int arr[], int gap,int size);
void print(int* arr, int size);
int main() {
    int array[]={12,2,4,23,5,1,6,8,16,64,32,7,43,243,76};
    int size=15;
    for (int i=size/2;i>=1;i/=2)#include <iostream>
#include <cmath>
using namespace std;
void swap(int p, int j, int* arr );
void shellSortwhile(int arr[], int size);
void shellSort(int arr[], int gap,int size);
void print(int* arr, int size);
int main() {
    int array[]={12,2,4,23,5,1,6,8,16,64,32,7,43,243,76};
    int size=15;
    print(array,15);
    for (int i=size/2;i>=1;i/=2)
   { shellSort(array,i,size);
    cout<<i<<endl;

   }
    print(array,15);
   // shellSortwhile(array,15);

}
void print(int* arr, int size)
{
    cout<<"Now the array will be printed"<<endl;
    for (int i=0;i<size;i++)
        cout<<arr[i]<<endl;
}
void swap(int p, int j, int* arr )
{
    int temp=arr[p];
    arr[p]=arr[j];
    arr[j]=temp;
}
void shellSortwhile(int arr[], int size) {
    int i, j, gap, temp;
    gap = size/2;

    while(gap > 0) {
        i = gap;

        while(i < size) {
            temp = arr[i];

for(j = i; (j >= gap) && (arr[j - gap] > temp); j -=gap) {
                arr[j] = arr[j - gap];
            }
            arr[j] = temp;
            i++;
        }
        gap = gap / 2;
    }
}

void shellSort(int arr[], int gap,int size)
{
    for (int i=0;i<size-(gap);i++)

    {
    if (arr[i]>arr[i+gap])
    {
        swap(i,i+gap,arr);

        for(int j=i;j>=0+gap;j-=gap)
        {if (arr[j]<arr[j-gap])
            swap(j-gap,j,arr);
        }
    }
    }
}
   { shellSort(array,i,size);
    cout<<i<<endl;

   }
    print(array,15);
   // shellSortwhile(array,15);
        print(array,15);

}
void print(int* arr, int size)
{
    cout<<"Now the array will be printed"<<endl;
    for (int i=0;i<size;i++)
        cout<<arr[i]<<endl;
}
void swap(int p, int j, int* arr )
{
    int temp=arr[p];
    arr[p]=arr[j];
    arr[j]=temp;
}
void shellSortwhile(int arr[], int size) {
    int i, j, gap, temp;
    gap = size/2;

    while(gap > 0) {
        i = gap;

        while(i < size) {
            temp = arr[i];

for(j = i; (j >= gap) && (arr[j - gap] > temp); j -=gap) {
                arr[j] = arr[j - gap];
            }
            arr[j] = temp;
            i++;
        }
        gap = gap / 2;
    }
}

void shellSort(int arr[], int gap,int size)
{
    for (int i=0;i<size-(gap);i++)

    {
    if (arr[i]>arr[i+gap])
    {
        swap(i,i+gap,arr);
        print(arr,size);

        for(int j=i;j>=0+gap;j-=gap)
        {if (arr[j]<arr[j-gap])
            swap(j-gap,j,arr);
             print(arr,size);
        }
    }
    }
}
</code>```

Title: shellsort algorithm isn't working

Body:
I wanted to implement shellsort myself instead of copy pasting the ones online, I would appreciate if anyone could help me find the mistake and improve my silly lil code I will put down my code down below

#include <iostream>
#include <cmath>

using namespace std;

void swap(int p, int j, int *arr);
void shellSort(int arr[], int gap, int size);

int main() {
    int array[] = {12, 2, 4, 23, 5, 1, 6, 8, 16, 64, 32, 7, 43, 243, 76};
    int size = 15;
    for (int i = 15; i >= 1; i /= 2) {
        shellSort(array,i,size);
        cout << i << endl;
    }

    print(array, 15);
    // shellSortwhile(array, 15);
    print(array, 15);
}

void shellSort(int arr[], int gap, int size) {
    for (int i = 0; i < size; i += gap) {
        if (arr[i] > arr[i + gap]) {
            swap(i, i + gap, arr);
            for(int j = i; j >= 0; j -= gap) {
                if (arr[j] < arr[j - gap]) {
                    swap(j-gap, j, arr);
                }
            }
        }
    }
}

My output is:

Now the array will be printed
2
4
5
6
7
7
8
1076814756
12
15
16
23
32
43
64


问:
How to set the color of a cell or range to transparent?
I know how to set the color to red for example:

```<code>row.Interior.Color = Color.FromArgb(255, 0, 0);
</code>```

But how to set the background to transparent?

答:
It can be done by using System.Drawing.Color instead of Spreadsheetgear.Drawing.Color:</p>

```<code>row.Interior.Color = System.Drawing.Color.Transparent;
</code>```

Body:
I know how to set the color to red for example:

row.Interior.Color = Color.FromArgb(255, 0, 0);

But how to set the background to transparent?

Body:
It can be done by using System.Drawing.Color instead of Spreadsheetgear.Drawing.Color:

row.Interior.Color = System.Drawing.Color.Transparent;


问:
Link 2 in-cell data validation lists
I have 2 in-cell data validation lists in Excel. Both cells contain dropdown arrows pointing to 2 columns of a table. What I would like is for when 1 cell contains a value, the other cell contains the value from the corresponding row in the table, but its own column, and vice-versa.
So if I select a value from the dropdown in cell1 it overwrites cell2, if I select a value from the dropdown in cell2 it overwrites cell1

i.e. for a table GoalTbl with columns cl and d; a cell named cl_val contains a data validation list pointing to GoalTbl[cl]. Another cell called d_val points to GoalTbl[d]

And so to get a d_val based on cl_val I use a formula like =INDEX(GoalTbl[d],MATCH(cl_val,GoalTbl[cl],0))

Similarly to get a value for cl_val based on d_val, =INDEX(GoalTbl[cl],MATCH(d_val,GoalTbl[d],0))

I can't put these formulae in their respective cells for 2 reasons:

Since each formula refers to the other cell, I would get a circular reference

If I use the drop-down arrow to select a value, it overwrites the formula in that cell

So can I get this linked functionality by changing the lists that the data validation points to - or with a VBA approach?
I suppose this is a combination of a dynamic default formula for a validation, and an overwriting mechanism for 1 cell based on the other - 2 areas I'm not sure how to tackle simultaneously with formulae.

答:
Thanks for the pointer towards Worksheet_Change, I have a VBA approach;

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, [cl_val]) Is Nothing Then
    With Application.WorksheetFunction
    UI False
    [d_val] = .Index([Goaltbl[d]], .Match([cl_val], [Goaltbl[cl]], 0))
    UI True
    End With
ElseIf Not Intersect(Target, [d_val]) Is Nothing Then
    With Application.WorksheetFunction
    UI False
    [cl_val] = .Index([Goaltbl[cl]], .Match([d_val], [Goaltbl[d]], 0))
    UI True
    End With
End If
End Sub
</code>```

Where UI is simply a Sub* to turn on/off screen updating and events (I have a Worksheet_Calculate macro elsewhere which I don't want triggered)

Still, a function approach would be nice to know about - I'm sure something can be done by changing the list input

*UI code for reference

```<code>Public Sub UI(t As Boolean)
    Application.EnableEvents = t
    Application.ScreenUpdating = t
End Sub
</code>```

Title: Link 2 in-cell data validation lists

Body:
Thanks for the pointer towards Worksheet_Change, I have a VBA approach;

Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, [cl_val]) Is Nothing Then
    With Application.WorksheetFunction
    UI False
    [d_val] = .Index([Goaltbl[d]], .Match([cl_val], [Goaltbl[cl]], 0))
    UI True
    End With
ElseIf Not Intersect(Target, [d_val]) Is Nothing Then
    With Application.WorksheetFunction
    UI False
    [cl_val] = .Index([Goaltbl[cl]], .Match([d_val], [Goaltbl[d]], 0))
    UI True
    End With
End If
End Sub

Where UI is simply a Sub* to turn on/off screen updating and events (I have a Worksheet_Calculate macro elsewhere which I don't want triggered)

Still, a function approach would be nice to know about - I'm sure something can be done by changing the list input

*UI code for reference

Public Sub UI(t As Boolean)
    Application.EnableEvents = t
    Application.ScreenUpdating = t
End Sub


问:
import font internet explorer
I would like to import some fonts for using in my website, I'm using this code that Google made.

HTML

```<code><link href='http://fonts.googleapis.com/css?family=Droid+Sans:400,700|Cuprum:400,700' rel='stylesheet' type='text/css'>
</code>```

CSS

```<code>font-family: "Droid Sans", sans-serif;
</code>```

It's works in Firefox and Google Chrome but IE8 no, why ?

EDITED: Adobe create something like Google and the script is better than google and work perfect in Internet Explorer (more in http://html.adobe.com/edge/webfonts/)

答:
Just add sans-serif as your font.

Like this:

```<code>font-family:'fontname', sans-serif;
</code>```

Sans-Serif makes it work on every browser

Title: import font internet explorer

Body:
I would like to import some fonts for using in my website, I'm using this code that Google made.

HTML

<link href='http://fonts.googleapis.com/css?family=Droid+Sans:400,700|Cuprum:400,700' rel='stylesheet' type='text/css'>

CSS

font-family: "Droid Sans", sans-serif;

It's works in Firefox and Google Chrome but IE8 no, why ?

EDITED: Adobe create something like Google and the script is better than google and work perfect in Internet Explorer (more in http://html.adobe.com/edge/webfonts/)

Body:
Just add sans-serif as your font.

Like this:

font-family:'fontname', sans-serif;

Sans-Serif makes it work on every browser