问:
Post JSON data (characteres with accents) with EXTJS and save with PHP
Sorry for my English, I'm Braziliam.

In one of my forms, I send datas in array to php save in db... I type de word "8º ANDAR" and extjs send to php "8\u00ba ANDAR" (no problem until here), but how I revert the "8\u00ba ANDAR" to "8º ANDAR" with php?

I tryed, but no success...
Here my post data with ExtJS
Here is my code in php:

```<code>if(in_array($_POST['action'], array('INSERIR', 'EDITAR')) and isset($_POST['ambientes'])){
    $ambientes = json_decode(stripcslashes('['.$_POST['ambientes'].']'), true);
    foreach ($ambientes as $key => $item) {
        //need to revert the $nome_ambiente....
        $nome_ambiente = mb_strtoupper(trim($item['ambiente']));
        $nome_ambiente = ReformatString($nome_ambiente);
        $nome_ambiente = preg_replace('/\s(?=\s)/', '', $nome_ambiente);
        $nome_ambiente = preg_replace('/[\n\r\t]/', ' ', $nome_ambiente);

        $obs_ambiente = mb_strtoupper($item['observacoes'], 'UTF-8');
        $obs_ambiente = ReformatString($obs_ambiente);

        $sqlA = "SELECT count(*) FROM ambientes_nomes WHERE descricao='$nome_ambiente'";
        $pdoA = $connection->prepare($sqlA);
        $pdoA->execute();
        $num_rows = $pdoA->fetchColumn();

        if($num_rows < 1){
            $sqlB = "INSERT INTO ambientes_nomes (descricao, cadastrado_por, alterado_por, data_cadastro, data_alteracao) VALUES ('$nome_ambiente', $user_id, $user_id, '$data_atual', '$data_atual')";
            $pdoB = $connection->prepare($sqlB);
            $pdoB->execute();
        }
    }
}
</code>```

答:
how I revert the "8\u00ba ANDAR" to "8º ANDAR" with php?

json_decode('['.$_POST['ambientes'].']', true)

Body:
Sorry for my English, I'm Braziliam.

In one of my forms, I send datas in array to php save in db... I type de word "8º ANDAR" and extjs send to php "8\u00ba ANDAR" (no problem until here), but how I revert the "8\u00ba ANDAR" to "8º ANDAR" with php?

I tryed, but no success...
Here my post data with ExtJS
Here is my code in php:

if(in_array($_POST['action'], array('INSERIR', 'EDITAR')) and isset($_POST['ambientes'])){
    $ambientes = json_decode(stripcslashes('['.$_POST['ambientes'].']'), true);
    foreach ($ambientes as $key => $item) {
        //need to revert the $nome_ambiente....
        $nome_ambiente = mb_strtoupper(trim($item['ambiente']));
        $nome_ambiente = ReformatString($nome_ambiente);
        $nome_ambiente = preg_replace('/\s(?=\s)/', '', $nome_ambiente);
        $nome_ambiente = preg_replace('/[\n\r\t]/', ' ', $nome_ambiente);

        $obs_ambiente = mb_strtoupper($item['observacoes'], 'UTF-8');
        $obs_ambiente = ReformatString($obs_ambiente);

        $sqlA = "SELECT count(*) FROM ambientes_nomes WHERE descricao='$nome_ambiente'";
        $pdoA = $connection->prepare($sqlA);
        $pdoA->execute();
        $num_rows = $pdoA->fetchColumn();

        if($num_rows < 1){
            $sqlB = "INSERT INTO ambientes_nomes (descricao, cadastrado_por, alterado_por, data_cadastro, data_alteracao) VALUES ('$nome_ambiente', $user_id, $user_id, '$data_atual', '$data_atual')";
            $pdoB = $connection->prepare($sqlB);
            $pdoB->execute();
        }
    }
}


来源: stackexchange

问:
Does ng-init and ng-repeat bind properly?
```<code><tr data-ng-repeat="x in AList" data-ng-init="loopIndex=$index;">
<select data-ng-model='y.value' style="width:80%;margin-left:20px;" data-ng-change="filter()" data-ng-init="test123=x.name;">
<option data-ng-repeat="y in BList" value="{{y.test123}}">{{y.test123}}></option>
</code>```

The above code has 2 arrays

Alist which has field name, the value of name is a field in Blist, lets suppose value of field name  in Alist is text.

When I directly write y.text instead of y.test123, the value populates on the screen and also in option value, but when I try to fetch the value in test123 and then I write the above code, neither the value populates in option value nor it is displayed on the screen.

答:
the above problem can be solved if we simply write test123 in square brackets, accessing array of objects</p>

```<code>y[test123]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
<select data-ng-model='y.value' style="width:80%;margin-left:20px;" data-ng-change="filter()" data-ng-init="test123=x.name;">
<option data-ng-repeat="y in BList" value="{{y.test123}}">{{y.test123}}></option>

The above code has 2 arrays

Alist which has field name, the value of name is a field in Blist, lets suppose value of field name  in Alist is text.

When I directly write y.text instead of y.test123, the value populates on the screen and also in option value, but when I try to fetch the value in test123 and then I write the above code, neither the value populates in option value nor it is displayed on the screen.

Body:
the above problem can be solved if we simply write test123 in square brackets, accessing array of objects

y[test123]


问:
"mock-heroes.ts' is not a module" error from official Angular doc
I'm trying to follow the official Angular doc:

https://angular.io/tutorial/toh-pt2

but can't proceed due to this error:

Failed to compile.

```<code>C:/Users/username/Desktop/my-app/src/app/heroes/heroes.component.ts (3,24):
File 'C:/Users/username/Desktop/my-app/src/app/mock-heroes.ts' is not a module.
</code>```

My code is exactly the same as in the tutorial, this is really frustrating conming from the official doc and makes me not even want to learn angular :( Anyone have any idea how to get past it?

mock-heroes.ts:

```<code>import { Hero } from './hero';

export const HEROES: Hero[] = [
  { id: 11, name: 'Mr. Nice' },
  { id: 12, name: 'Narco' },
  { id: 13, name: 'Bombasto' },
  { id: 14, name: 'Celeritas' },
  { id: 15, name: 'Magneta' },
  { id: 16, name: 'RubberMan' },
  { id: 17, name: 'Dynama' },
  { id: 18, name: 'Dr IQ' },
  { id: 19, name: 'Magma' },
  { id: 20, name: 'Tornado' }
];
</code>```

hero.ts:

```<code>export class Hero {
  id: number;
  name: string;
}
</code>```

heroes.components.ts:

```<code>import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';
import { HEROES } from '../mock-heroes';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})

export class HeroesComponent implements OnInit {

    heroes = HEROES;

    constructor() { }

    ngOnInit() {
    }

}
</code>```

heroes.component.html:

```<code><h2>My Heroes</h2>
<ul class="heroes">
  <li *ngFor="let hero of heroes">
    <span class="badge">{{hero.id}}</span> {{hero.name}}
  </li>
</ul>
</code>```

答:
Adding to what @JamieBarker said, the said erro happens when you add a new class outside from your editor or keep running your angular cli ng serve.

Actually your editor or 'ng serve' is not able to find the newly created files.

I got the same error while using ng serve --open. I stopped it and used ng serve and it was fixed.

Body:
I'm trying to follow the official Angular doc:

https://angular.io/tutorial/toh-pt2

but can't proceed due to this error:

Failed to compile.

C:/Users/username/Desktop/my-app/src/app/heroes/heroes.component.ts (3,24):
File 'C:/Users/username/Desktop/my-app/src/app/mock-heroes.ts' is not a module.

My code is exactly the same as in the tutorial, this is really frustrating conming from the official doc and makes me not even want to learn angular :( Anyone have any idea how to get past it?

mock-heroes.ts:

import { Hero } from './hero';

export const HEROES: Hero[] = [
  { id: 11, name: 'Mr. Nice' },
  { id: 12, name: 'Narco' },
  { id: 13, name: 'Bombasto' },
  { id: 14, name: 'Celeritas' },
  { id: 15, name: 'Magneta' },
  { id: 16, name: 'RubberMan' },
  { id: 17, name: 'Dynama' },
  { id: 18, name: 'Dr IQ' },
  { id: 19, name: 'Magma' },
  { id: 20, name: 'Tornado' }
];

hero.ts:

export class Hero {
  id: number;
  name: string;
}

heroes.components.ts:

import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';
import { HEROES } from '../mock-heroes';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})

export class HeroesComponent implements OnInit {

    heroes = HEROES;

    constructor() { }

    ngOnInit() {
    }

}

heroes.component.html:

My Heroes

    {{hero.id}} {{hero.name}}


问:
Show interstitial ads after click recyclerview item in fragment
I have a custom recyclerview with many intent that go to new activity in fragment. The concept is like this, when user click the item on recyclerview, I want to display a interstitial ads before the new activity is appear. Then if user close the ads or ads failed to loaded, it automatically close the ads it and appear the next activity..how to do it ?

Remember, i use a fragment not activity.

This is my code so far

```<code>public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ViewHolder> {

    public static class ViewHolder extends RecyclerView.ViewHolder {

        private InterstitialAd interstitialAd;

        private TextView homeTitle, homeDesc;
        ImageView homeImage;

        private Context context;

        public ViewHolder(View itemView) {
            super(itemView);
            createInterstitial();
            context = itemView.getContext();
            homeTitle = (TextView)itemView.findViewById(R.id.homeTitle);
            homeDesc = (TextView)itemView.findViewById(R.id.homeDesc);
            homeImage = (ImageView)itemView.findViewById(R.id.homeImage);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final Intent intent;
                    switch (getAdapterPosition()) {
                        case 0:
                            showInterstitial();
                            intent = new Intent(context, AllBlock.class);
                            break;
                        case 1:
                            showInterstitial();
                            intent = new Intent(context, BasicBlock.class);
                            break;

                        default:
                            intent = new Intent(context, AllBlock.class);
                            break;
                    }
                    context.startActivity(intent);
                }
            });
        }

        public void createInterstitial() {
            interstitialAd = new InterstitialAd(context);
            interstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
            interstitialAd.setAdListener(new AdListener() {
                @Override
                public void onAdLoaded() {

                }
                @Override
                public void onAdClosed() {
                    loadInterstitial();
                }
            });
        }

        public void loadInterstitial() {
            AdRequest interstitialRequest = new AdRequest.Builder().build();
            interstitialAd.loadAd(interstitialRequest);
        }

        public void showInterstitial() {
            if (interstitialAd.isLoaded()) {
                interstitialAd.show();
            } else {
                loadInterstitial();
            }
        }
    }
</code>```

答:
What you have to do is:

1) Extract specific view onClickListener. Let's call it listener.

2) Create a class of your own that implements View.OnClickListener.

3) Add the extracted view to your class listeners.

4) set the view's onClickListener to be your class.

5) Do your logic in the onClick of your class and then call the click events for the normal view.

Body:
I have a custom recyclerview with many intent that go to new activity in fragment. The concept is like this, when user click the item on recyclerview, I want to display a interstitial ads before the new activity is appear. Then if user close the ads or ads failed to loaded, it automatically close the ads it and appear the next activity..how to do it ?

Remember, i use a fragment not activity.

This is my code so far

public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ViewHolder> {

    public static class ViewHolder extends RecyclerView.ViewHolder {

        private InterstitialAd interstitialAd;

        private TextView homeTitle, homeDesc;
        ImageView homeImage;

        private Context context;

        public ViewHolder(View itemView) {
            super(itemView);
            createInterstitial();
            context = itemView.getContext();
            homeTitle = (TextView)itemView.findViewById(R.id.homeTitle);
            homeDesc = (TextView)itemView.findViewById(R.id.homeDesc);
            homeImage = (ImageView)itemView.findViewById(R.id.homeImage);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final Intent intent;
                    switch (getAdapterPosition()) {
                        case 0:
                            showInterstitial();
                            intent = new Intent(context, AllBlock.class);
                            break;
                        case 1:
                            showInterstitial();
                            intent = new Intent(context, BasicBlock.class);
                            break;

                        default:
                            intent = new Intent(context, AllBlock.class);
                            break;
                    }
                    context.startActivity(intent);
                }
            });
        }

        public void createInterstitial() {
            interstitialAd = new InterstitialAd(context);
            interstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
            interstitialAd.setAdListener(new AdListener() {
                @Override
                public void onAdLoaded() {

                }
                @Override
                public void onAdClosed() {
                    loadInterstitial();
                }
            });
        }

        public void loadInterstitial() {
            AdRequest interstitialRequest = new AdRequest.Builder().build();
            interstitialAd.loadAd(interstitialRequest);
        }

        public void showInterstitial() {
            if (interstitialAd.isLoaded()) {
                interstitialAd.show();
            } else {
                loadInterstitial();
            }
        }
    }


问:
Walking filetree throws error even tho the files should exist
I am trying to walk through a zip file and print out all files, but for some reason, it throws a NoSuchFileException as soon as it goes into any subfolder.

```<code>    FileSystem fs = FileSystems.newFileSystem(Paths.get(folder.getRoot().getAbsolutePath(), "test.zip"), null);

    Files.walkFileTree(fs.getPath("/"), new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
            System.out.println(file);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) {
            System.err.println(exc);
            return FileVisitResult.CONTINUE;
        }

    });
</code>```

How come it even wants to go there if they don't exist? Can anyone help me to solve this problem? The files should actually be there, at least they do when the test is executed by hand.

答:
Take extra care, when using FileSystem implementations, as they are especially dependent on the JVM you are using, and on the OS! Cf. the Javadoc of FileSystem

A very good example is ZipFileSystem. Its maiden name is com.sun.nio.zipfs.ZipFileSystem, but the IBM JRE has its own implementation in com.ibm.ws.install.ni.framework.io.ZIPFileSystem. Also for example from a ZIP File you cannot access internals ZIPs, because of the layout of the archive. You have to unzip it, and mount the internal ZIP as another FileSystem. (Afterwards, of course, you have to delete these)

And of course see this SO answer: probably your expectations are false. Debug where exactly the exception occurs and correlate that to your expectations.

Body:
I am trying to walk through a zip file and print out all files, but for some reason, it throws a NoSuchFileException as soon as it goes into any subfolder.

    FileSystem fs = FileSystems.newFileSystem(Paths.get(folder.getRoot().getAbsolutePath(), "test.zip"), null);

    Files.walkFileTree(fs.getPath("/"), new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
            System.out.println(file);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) {
            System.err.println(exc);
            return FileVisitResult.CONTINUE;
        }

    });

How come it even wants to go there if they don't exist? Can anyone help me to solve this problem? The files should actually be there, at least they do when the test is executed by hand.


问:
Use tasks in always @* blocks
I was intended to use a customized task in an always @* block, like:

```<code>input [31:0] a;
input b;
output reg [31:0] c;

task mytask;
begin
    if (b) begin
        c = a;
    end
end
endtask

always @* begin
    // ... (b is not included)
    mytask;
    // ... (b is not included)
end
</code>```

What I think is that when signal b changes from 0 to 1, c will be set to the content of a. Then I found the always block is not sensitive to signal b (using ISim 14.7).

Is this a bug or designed to behave like this?

答: The language is specified to behave like this.  Always @* (or always_comb) blocks are not sensitive to changes in values used in tasks that are not included in the argument list.  Use a function here since your body in not consuming time.</p>

Title: Use tasks in always @* blocks

Body:
I was intended to use a customized task in an always @* block, like:

input [31:0] a;
input b;
output reg [31:0] c;

task mytask;
begin
    if (b) begin
        c = a;
    end
end
endtask

always @* begin
    // ... (b is not included)
    mytask;
    // ... (b is not included)
end

What I think is that when signal b changes from 0 to 1, c will be set to the content of a. Then I found the always block is not sensitive to signal b (using ISim 14.7).

Is this a bug or designed to behave like this?


问:
Kotlin : Save Image to database
I am creating user profile in kotlin,
I want to give the users two option (select from avatar or capture image)
then save profile in "sqlite" database

what is the best solution ?

if you help me in code I will be thankful

答:
I got solution for that:

Create Database class "DatabaseHelper.kt":

```<code> class DatabaseHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, 1) {

override fun onCreate(db: SQLiteDatabase) {

    db.execSQL("Create Table $TABLE_NAME(ID INTEGER PRIMARY KEY AUTOINCREMENT,Category_img BLOB)")

}

override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME)
    onCreate(db)
}

fun insertData(Category_img: ByteArray): Boolean {
    val db = writableDatabase
    val cv = ContentValues()
    cv.put(CAL_NO1, Category_img)

    val result = db.insert(TABLE_NAME, null, cv)

    return if (result .equals( -1))
        false
    else
        true

}

fun getdata(): ByteArray {
    val db = writableDatabase
    val res = db.rawQuery("select * from " + TABLE_NAME, null)

    if (res.moveToFirst()) {
        do {
            return res.getBlob(0)
        } while (res.moveToNext())
    }
    return byteArrayOf()
}

companion object {
    private val DATABASE_NAME = "user.db"
    private val TABLE_NAME = "tbl_user"
    private val CAL_NO1 = "Category_img"
}

}
</code>```

and do code this from where you want to access Camera:

```<code> class MainActivity : AppCompatActivity() {
  var dbSq: DatabaseHelper= DatabaseHelper(this);

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
    startActivityForResult(cameraIntent, 101)

}

public override fun onActivityResult(requestcode: Int, resultcode: Int, intent: Intent) {
    super.onActivityResult(requestcode, resultcode, intent)
    if (resultcode == Activity.RESULT_OK) {
        if (requestcode == 101) {

            val photo = intent.extras!!.get("data") as Bitmap
            val stream = ByteArrayOutputStream()
            photo.compress(Bitmap.CompressFormat.PNG, 100, stream)
            val byteArray = stream.toByteArray()

            Log.d("check",dbSq.insertData(byteArray).toString().plus(" "));

        }
    }
}
</code>```

Edited

"DatabaseHelper.kt":

```<code>class DatabaseHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, 1) {

override fun onCreate(db: SQLiteDatabase) {

    db.execSQL("Create Table $TABLE_NAME(ID INTEGER PRIMARY KEY AUTOINCREMENT,Category_img Text)")

}

override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME)
    onCreate(db)
}

fun insertData(Category_img: String): Boolean {
    val db = writableDatabase
    val cv = ContentValues()
    cv.put(CAL_NO1, Category_img)

    val result = db.insert(TABLE_NAME, null, cv)

    return if (result .equals( -1))
        false
    else
        true

}

companion object {
    private val DATABASE_NAME = "user.db"
    private val TABLE_NAME = "tbl_user"
    private val CAL_NO1 = "Category_img"
}

}
</code>```

and do code this from where you want to access Camera:

```<code>class MainActivity : AppCompatActivity() {

var dbSq: DatabaseHelper= DatabaseHelper(this);

internal var output: File? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)

    val dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)

    val date = Date()
    output = File(dir, "CheckImage " + date.toString()+".jpeg")

    startActivityForResult(cameraIntent, 101)

}

public override fun onActivityResult(requestcode: Int, resultcode: Int, intent: Intent) {
    super.onActivityResult(requestcode, resultcode, intent)
    if (resultcode == Activity.RESULT_OK) {
        if (requestcode == 101) {

            Log.d("check",dbSq.insertData(output!!.absolutePath).toString().plus(" "));

        }
    }
}
}
</code>```

Title: Kotlin : Save Image to database

Body:
I got solution for that:

Create Database class "DatabaseHelper.kt":

 class DatabaseHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, 1) {

override fun onCreate(db: SQLiteDatabase) {

    db.execSQL("Create Table $TABLE_NAME(ID INTEGER PRIMARY KEY AUTOINCREMENT,Category_img BLOB)")

}

override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME)
    onCreate(db)
}

fun insertData(Category_img: ByteArray): Boolean {
    val db = writableDatabase
    val cv = ContentValues()
    cv.put(CAL_NO1, Category_img)

    val result = db.insert(TABLE_NAME, null, cv)

    return if (result .equals( -1))
        false
    else
        true

}

fun getdata(): ByteArray {
    val db = writableDatabase
    val res = db.rawQuery("select * from " + TABLE_NAME, null)

    if (res.moveToFirst()) {
        do {
            return res.getBlob(0)
        } while (res.moveToNext())
    }
    return byteArrayOf()
}

companion object {
    private val DATABASE_NAME = "user.db"
    private val TABLE_NAME = "tbl_user"
    private val CAL_NO1 = "Category_img"
}

}

and do code this from where you want to access Camera:

 class MainActivity : AppCompatActivity() {
  var dbSq: DatabaseHelper= DatabaseHelper(this);

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
    startActivityForResult(cameraIntent, 101)

}

public override fun onActivityResult(requestcode: Int, resultcode: Int, intent: Intent) {
    super.onActivityResult(requestcode, resultcode, intent)
    if (resultcode == Activity.RESULT_OK) {
        if (requestcode == 101) {

            val photo = intent.extras!!.get("data") as Bitmap
            val stream = ByteArrayOutputStream()
            photo.compress(Bitmap.CompressFormat.PNG, 100, stream)
            val byteArray = stream.toByteArray()

            Log.d("check",dbSq.insertData(byteArray).toString().plus(" "));

        }
    }
}

Edited

"DatabaseHelper.kt":

class DatabaseHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, 1) {

override fun onCreate(db: SQLiteDatabase) {

    db.execSQL("Create Table $TABLE_NAME(ID INTEGER PRIMARY KEY AUTOINCREMENT,Category_img Text)")

}

override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME)
    onCreate(db)
}

fun insertData(Category_img: String): Boolean {
    val db = writableDatabase
    val cv = ContentValues()
    cv.put(CAL_NO1, Category_img)

    val result = db.insert(TABLE_NAME, null, cv)

    return if (result .equals( -1))
        false
    else
        true

}

companion object {
    private val DATABASE_NAME = "user.db"
    private val TABLE_NAME = "tbl_user"
    private val CAL_NO1 = "Category_img"
}

}

and do code this from where you want to access Camera:

class MainActivity : AppCompatActivity() {

var dbSq: DatabaseHelper= DatabaseHelper(this);

internal var output: File? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)

    val dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)

    val date = Date()
    output = File(dir, "CheckImage " + date.toString()+".jpeg")

    startActivityForResult(cameraIntent, 101)

}

public override fun onActivityResult(requestcode: Int, resultcode: Int, intent: Intent) {
    super.onActivityResult(requestcode, resultcode, intent)
    if (resultcode == Activity.RESULT_OK) {
        if (requestcode == 101) {

            Log.d("check",dbSq.insertData(output!!.absolutePath).toString().plus(" "));

        }
    }
}
}

ContentLicense: CC BY-SA 4.0


问:
How to order months between two years in SSRS
I have the following table in SQL:

```<code>UniqueUsers YEAR     MONTH     MONTH2
NULL        NULL     January     1
NULL        NULL     February    2
NULL        NULL     July        7
NULL        NULL     August      8
NULL        NULL     September   9
NULL        NULL     October     10
NULL        NULL     November    11
NULL        NULL     December    12
1           2016     March       3
2           2016     April       4
2           2016     May         5
1           2016     June        6
</code>```

In SSRS I have a table grouped by Month with 4 parameters: 1 for Year1 and 1 for Month1; 1 for Year2 and 1 for Month2.

For example, if I select Year1 = 2015 and Month1 = November and December and Year2 = 2016 and Month2 = January and February I need to show the months like this even if the results have NULL values:

```<code>Nov Dec Jan Feb Mar Apr May Jun Jul Aug Sep Oct
</code>```

This is the query than I use:

```<code>SELECT *
FROM
(
SELECT
      [QUARTER]
      ,[CARRIER]
      ,[PLANGROUP]
      ,[UniqueUsers]
      ,[YEAR]
      ,A.[MONTH]
      ,A.[MONTH2]
FROM [ReportUnit].[dbo].[Month_List] A

LEFT JOIN

(SELECT
        [YEAR]
        ,[MONTH2]
        ,[CARRIER]
        ,[PLANGROUP]
        ,[QUARTER]
        ,COUNT(DISTINCT [CONTRACT_NUM]) AS [UniqueUsers]
FROM
(
SELECT *
FROM
(
SELECT
        MIN([YEAR]) AS [YEAR]
        ,MIN([MONTH2]) AS [MONTH2]
        ,DATENAME(MONTH, DATEADD(MONTH, MIN([MONTH2])-1, CAST('2017-01-01' AS datetime))) AS [MONTH]
        ,[CARRIER]
        ,[PLANGROUP]
        ,MIN([QUARTER]) AS [QUARTER]
        ,[CONTRACT_NUM]
FROM MyTable
WHERE
[YEAR] = @YEAR1
AND [PLANGROUP] IN (@ACCOUNT)
GROUP BY [PLANGROUP],[CARRIER],[CONTRACT_NUM]
) Q1
WHERE
[MONTH] IN (@MONTH1) --THIS IS MONTH NAME PARAMETER IN SSRS
--[MONTH2] IN (11,12)

UNION ALL

SELECT *
FROM
(
SELECT
        MIN([YEAR]) AS [YEAR]
        ,MIN([MONTH2]) AS [MONTH2]
        ,DATENAME(MONTH, DATEADD(MONTH, MIN([MONTH2])-1, CAST('2017-01-01' AS datetime))) AS [MONTH]
        ,[CARRIER]
        ,[PLANGROUP]
        ,MIN([QUARTER]) AS [QUARTER]
        ,[CONTRACT_NUM]
FROM MyTable
WHERE
[YEAR] = @YEAR2
AND [PLANGROUP] IN (@ACCOUNT)
GROUP BY [PLANGROUP],[CARRIER],[CONTRACT_NUM]
) Q1
WHERE
[MONTH] IN (@MONTH2)  --THIS IS MONTH NAME PARAMETER IN SSRS
--[MONTH2] IN (1,2,3,4,5,6,7,8,9,10)
) Q1
GROUP BY [YEAR],[MONTH2],[PLANGROUP],[CARRIER],[QUARTER]
) B ON A.MONTH2 = B.MONTH2
) Q4
ORDER BY [PLANGROUP], [YEAR], [MONTH2], [MONTH]
</code>```

答:
This is the query than I use:

```<code>SELECT *
FROM
(
SELECT
      [QUARTER]
      ,[CARRIER]
      ,[PLANGROUP]
      ,[UniqueUsers]
      ,[YEAR]
      ,A.[MONTH]
      ,A.[MONTH2]
FROM [ReportUnit].[dbo].[Month_List] A

LEFT JOIN

(SELECT
        [YEAR]
        ,[MONTH2]
        ,[CARRIER]
        ,[PLANGROUP]
        ,[QUARTER]
        ,COUNT(DISTINCT [CONTRACT_NUM]) AS [UniqueUsers]
FROM
(
SELECT *
FROM
(
SELECT
        MIN([YEAR]) AS [YEAR]
        ,MIN([MONTH2]) AS [MONTH2]
        ,DATENAME(MONTH, DATEADD(MONTH, MIN([MONTH2])-1, CAST('2017-01-01' AS datetime))) AS [MONTH]
        ,[CARRIER]
        ,[PLANGROUP]
        ,MIN([QUARTER]) AS [QUARTER]
        ,[CONTRACT_NUM]
FROM MyTable
WHERE
[YEAR] = @YEAR1
AND [PLANGROUP] IN (@ACCOUNT)
GROUP BY [PLANGROUP],[CARRIER],[CONTRACT_NUM]
) Q1
WHERE
[MONTH] IN (@MONTH1) --THIS IS MONTH NAME PARAMETER IN SSRS
--[MONTH2] IN (11,12)

UNION ALL

SELECT *
FROM
(
SELECT
        MIN([YEAR]) AS [YEAR]
        ,MIN([MONTH2]) AS [MONTH2]
        ,DATENAME(MONTH, DATEADD(MONTH, MIN([MONTH2])-1, CAST('2017-01-01' AS datetime))) AS [MONTH]
        ,[CARRIER]
        ,[PLANGROUP]
        ,MIN([QUARTER]) AS [QUARTER]
        ,[CONTRACT_NUM]
FROM MyTable
WHERE
[YEAR] = @YEAR2
AND [PLANGROUP] IN (@ACCOUNT)
GROUP BY [PLANGROUP],[CARRIER],[CONTRACT_NUM]
) Q1
WHERE
[MONTH] IN (@MONTH2)  --THIS IS MONTH NAME PARAMETER IN SSRS
--[MONTH2] IN (1,2,3,4,5,6,7,8,9,10)
) Q1
GROUP BY [YEAR],[MONTH2],[PLANGROUP],[CARRIER],[QUARTER]
) B ON A.MONTH2 = B.MONTH2
) Q4
ORDER BY [PLANGROUP], [YEAR], [MONTH2], [MONTH]
</code>```

And I don`t know how I can join it in your temp Table

Body:
I have the following table in SQL:

UniqueUsers YEAR     MONTH     MONTH2
NULL        NULL     January     1
NULL        NULL     February    2
NULL        NULL     July        7
NULL        NULL     August      8
NULL        NULL     September   9
NULL        NULL     October     10
NULL        NULL     November    11
NULL        NULL     December    12
1           2016     March       3
2           2016     April       4
2           2016     May         5
1           2016     June        6

In SSRS I have a table grouped by Month with 4 parameters: 1 for Year1 and 1 for Month1; 1 for Year2 and 1 for Month2.

For example, if I select Year1 = 2015 and Month1 = November and December and Year2 = 2016 and Month2 = January and February I need to show the months like this even if the results have NULL values:

Nov Dec Jan Feb Mar Apr May Jun Jul Aug Sep Oct

This is the query than I use:

SELECT *
FROM
(
SELECT
      [QUARTER]
      ,[CARRIER]
      ,[PLANGROUP]
      ,[UniqueUsers]
      ,[YEAR]
      ,A.[MONTH]
      ,A.[MONTH2]
FROM [ReportUnit].[dbo].[Month_List] A

LEFT JOIN

(SELECT
        [YEAR]
        ,[MONTH2]
        ,[CARRIER]
        ,[PLANGROUP]
        ,[QUARTER]
        ,COUNT(DISTINCT [CONTRACT_NUM]) AS [UniqueUsers]
FROM
(
SELECT *
FROM
(
SELECT
        MIN([YEAR]) AS [YEAR]
        ,MIN([MONTH2]) AS [MONTH2]
        ,DATENAME(MONTH, DATEADD(MONTH, MIN([MONTH2])-1, CAST('2017-01-01' AS datetime))) AS [MONTH]
        ,[CARRIER]
        ,[PLANGROUP]
        ,MIN([QUARTER]) AS [QUARTER]
        ,[CONTRACT_NUM]
FROM MyTable
WHERE
[YEAR] = @YEAR1
AND [PLANGROUP] IN (@ACCOUNT)
GROUP BY [PLANGROUP],[CARRIER],[CONTRACT_NUM]
) Q1
WHERE
[MONTH] IN (@MONTH1) --THIS IS MONTH NAME PARAMETER IN SSRS
--[MONTH2] IN (11,12)

UNION ALL

SELECT *
FROM
(
SELECT
        MIN([YEAR]) AS [YEAR]
        ,MIN([MONTH2]) AS [MONTH2]
        ,DATENAME(MONTH, DATEADD(MONTH, MIN([MONTH2])-1, CAST('2017-01-01' AS datetime))) AS [MONTH]
        ,[CARRIER]
        ,[PLANGROUP]
        ,MIN([QUARTER]) AS [QUARTER]
        ,[CONTRACT_NUM]
FROM MyTable
WHERE
[YEAR] = @YEAR2
AND [PLANGROUP] IN (@ACCOUNT)
GROUP BY [PLANGROUP],[CARRIER],[CONTRACT_NUM]
) Q1
WHERE
[MONTH] IN (@MONTH2)  --THIS IS MONTH NAME PARAMETER IN SSRS
--[MONTH2] IN (1,2,3,4,5,6,7,8,9,10)
) Q1
GROUP BY [YEAR],[MONTH2],[PLANGROUP],[CARRIER],[QUARTER]
) B ON A.MONTH2 = B.MONTH2
) Q4
ORDER BY [PLANGROUP], [YEAR], [MONTH2], [MONTH]

Body:
This is the query than I use:

SELECT *
FROM
(
SELECT
      [QUARTER]
      ,[CARRIER]
      ,[PLANGROUP]
      ,[UniqueUsers]
      ,[YEAR]
      ,A.[MONTH]
      ,A.[MONTH2]
FROM [ReportUnit].[dbo].[Month_List] A

LEFT JOIN

(SELECT
        [YEAR]
        ,[MONTH2]
        ,[CARRIER]
        ,[PLANGROUP]
        ,[QUARTER]
        ,COUNT(DISTINCT [CONTRACT_NUM]) AS [UniqueUsers]
FROM
(
SELECT *
FROM
(
SELECT
        MIN([YEAR]) AS [YEAR]
        ,MIN([MONTH2]) AS [MONTH2]
        ,DATENAME(MONTH, DATEADD(MONTH, MIN([MONTH2])-1, CAST('2017-01-01' AS datetime))) AS [MONTH]
        ,[CARRIER]
        ,[PLANGROUP]
        ,MIN([QUARTER]) AS [QUARTER]
        ,[CONTRACT_NUM]
FROM MyTable
WHERE
[YEAR] = @YEAR1
AND [PLANGROUP] IN (@ACCOUNT)
GROUP BY [PLANGROUP],[CARRIER],[CONTRACT_NUM]
) Q1
WHERE
[MONTH] IN (@MONTH1) --THIS IS MONTH NAME PARAMETER IN SSRS
--[MONTH2] IN (11,12)

UNION ALL

SELECT *
FROM
(
SELECT
        MIN([YEAR]) AS [YEAR]
        ,MIN([MONTH2]) AS [MONTH2]
        ,DATENAME(MONTH, DATEADD(MONTH, MIN([MONTH2])-1, CAST('2017-01-01' AS datetime))) AS [MONTH]
        ,[CARRIER]
        ,[PLANGROUP]
        ,MIN([QUARTER]) AS [QUARTER]
        ,[CONTRACT_NUM]
FROM MyTable
WHERE
[YEAR] = @YEAR2
AND [PLANGROUP] IN (@ACCOUNT)
GROUP BY [PLANGROUP],[CARRIER],[CONTRACT_NUM]
) Q1
WHERE
[MONTH] IN (@MONTH2)  --THIS IS MONTH NAME PARAMETER IN SSRS
--[MONTH2] IN (1,2,3,4,5,6,7,8,9,10)
) Q1
GROUP BY [YEAR],[MONTH2],[PLANGROUP],[CARRIER],[QUARTER]
) B ON A.MONTH2 = B.MONTH2
) Q4
ORDER BY [PLANGROUP], [YEAR], [MONTH2], [MONTH]

And I don`t know how I can join it in your temp Table


问:
How to find an object which contains a specific string and a number which is the highest number?
I'm a beginner in Python and I'm trying to use boto (CloudFormation) to list the latest stacks created which contains a string.

```<code>import boto3
client = boto3.client('cloudformation')
stacks = client.list_stacks(
    StackStatusFilter=[
        'CREATE_COMPLETE'
    ]
)

for st in stacks["StackSummaries"]:
    print(st)
</code>```

This is part of the output I get from running the command:

```<code>{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Dev-31/4d501360-d521-11e7-9aff-50a68a0bca9a', u'StackName': 'Company-Dev-31', u'CreationTime': datetime.datetime(2017, 11, 29, 16, 21, 6, 636000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Dev-30/4d501360-c231-11e7-8aca-50a68a0bca9a', u'StackName': 'Company-Dev-30', u'CreationTime': datetime.datetime(2017, 11, 29, 16, 21, 6, 644000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Stg-22/bc2b6c10-d41a-11e7-b1ab-50d5ca789eae', u'StackName': 'Company-Stg-22', u'CreationTime': datetime.datetime(2017, 11, 28, 9, 1, 34, 985000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-64/0e85cc00-9602-11e7-8c08-50d5ca0184d2', u'StackName': 'Company-Prod-US-API-64', u'CreationTime': datetime.datetime(2017, 9, 10, 8, 28, 43, 598000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-63/1ba257c0-9600-11e7-821f-503f20f2ad4a', u'StackName': 'Company-Prod-US-API-63', u'CreationTime': datetime.datetime(2017, 9, 10, 8, 14, 46, 602000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-61/9252a9d0-2ace-11e7-8eea-503ac9ec2461', u'StackName': 'Company-Prod-US-API-61', u'CreationTime': datetime.datetime(2017, 4, 26, 22, 20, 36, 473000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-60/1ba83440-2acd-11e7-a0c3-503a90a9c435', u'StackName': 'Company-Prod-US-API-60', u'CreationTime': datetime.datetime(2017, 4, 26, 22, 10, 7, 890000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}
</code>```

It seems like the output is already sorted with the newest objects first.

I would like to parse the name of the stack which contains the word "Dev" and where the number is the highest among the rest of the stacks of the same environment (Dev), in this case "Company-Dev-31".

How can it be achieved?

答:
Itai,

first make a sublist with those stacks that have Dev in their names, then sort the resulting list using the Dev number as a key.

```<code># make a list of stacks with Dev in stack ID
sublist = [ s for s in stacks if 'Dev' in s['StackId'] ]

# Extract a number from stack ID
REGEX = re.compile("Dev-([0-9]+)")
def extractNum(stack):
    match = REGEX.search(stack['StackId'])
    if match:
        return int(match.group(1))
    else:
        return None

# Sort the stack list in descending order
sublist.sort(key=extractNum, reverse=True)
print(sublist[0])
</code>```

If you wish, it might be compressed to 'one liner', using built-in functions and lambda.

```<code>REGEX = re.compile("Dev-([0-9]+)")
sublist = sorted(filter(lambda s: 'Dev' in s['StackId'],
                        stacks),
    key = lambda s: int(REGEX.search(s['StackId']).group(1)),
    reverse = True
    );
</code>```

filter makes an iterator that contains only those elements of stacks that match the condition

sorted makes a sorted list using the specified function that produces the value for ordering.

Body:
I'm a beginner in Python and I'm trying to use boto (CloudFormation) to list the latest stacks created which contains a string.

import boto3
client = boto3.client('cloudformation')
stacks = client.list_stacks(
    StackStatusFilter=[
        'CREATE_COMPLETE'
    ]
)

for st in stacks["StackSummaries"]:
    print(st)

This is part of the output I get from running the command:

{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Dev-31/4d501360-d521-11e7-9aff-50a68a0bca9a', u'StackName': 'Company-Dev-31', u'CreationTime': datetime.datetime(2017, 11, 29, 16, 21, 6, 636000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Dev-30/4d501360-c231-11e7-8aca-50a68a0bca9a', u'StackName': 'Company-Dev-30', u'CreationTime': datetime.datetime(2017, 11, 29, 16, 21, 6, 644000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Stg-22/bc2b6c10-d41a-11e7-b1ab-50d5ca789eae', u'StackName': 'Company-Stg-22', u'CreationTime': datetime.datetime(2017, 11, 28, 9, 1, 34, 985000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-64/0e85cc00-9602-11e7-8c08-50d5ca0184d2', u'StackName': 'Company-Prod-US-API-64', u'CreationTime': datetime.datetime(2017, 9, 10, 8, 28, 43, 598000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-63/1ba257c0-9600-11e7-821f-503f20f2ad4a', u'StackName': 'Company-Prod-US-API-63', u'CreationTime': datetime.datetime(2017, 9, 10, 8, 14, 46, 602000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-61/9252a9d0-2ace-11e7-8eea-503ac9ec2461', u'StackName': 'Company-Prod-US-API-61', u'CreationTime': datetime.datetime(2017, 4, 26, 22, 20, 36, 473000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-60/1ba83440-2acd-11e7-a0c3-503a90a9c435', u'StackName': 'Company-Prod-US-API-60', u'CreationTime': datetime.datetime(2017, 4, 26, 22, 10, 7, 890000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}

It seems like the output is already sorted with the newest objects first.

I would like to parse the name of the stack which contains the word "Dev" and where the number is the highest among the rest of the stacks of the same environment (Dev), in this case "Company-Dev-31".

How can it be achieved?

Body:
Itai,

first make a sublist with those stacks that have Dev in their names, then sort the resulting list using the Dev number as a key.

# make a list of stacks with Dev in stack ID
sublist = [ s for s in stacks if 'Dev' in s['StackId'] ]

# Extract a number from stack ID
REGEX = re.compile("Dev-([0-9]+)")
def extractNum(stack):
    match = REGEX.search(stack['StackId'])
    if match:
        return int(match.group(1))
    else:
        return None

# Sort the stack list in descending order
sublist.sort(key=extractNum, reverse=True)
print(sublist[0])

If you wish, it might be compressed to 'one liner', using built-in functions and lambda.

REGEX = re.compile("Dev-([0-9]+)")
sublist = sorted(filter(lambda s: 'Dev' in s['StackId'],
                        stacks),
    key = lambda s: int(REGEX.search(s['StackId']).group(1)),
    reverse = True
    );

filter makes an iterator that contains only those elements of stacks that match the condition

sorted makes a sorted list using the specified function that produces the value for ordering.


问:
How query a MySQL in ASP.NET?
I am trying to link my asp.net Formview to a MySQL database, but with no success.

Take a look at my code and please tell my where is my mistake:

```<code><asp:FormView ID="FormView1" runat="server" DataKeyNames="ImageID"
        DataSourceID="SqlDataSource1" EnableModelValidation="True">
        <EditItemTemplate>
            ImageID:
            <asp:Label ID="ImageIDLabel1" runat="server" Text='<%# Eval("ImageID") %>' />
            <br />
            Title:
            <asp:TextBox ID="TitleTextBox" runat="server" Text='<%# Bind("Title") %>' />
            <br />
            Description:
            <asp:TextBox ID="DescriptionTextBox" runat="server"
                Text='<%# Bind("Description") %>' />
            <br />
            <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True"
                CommandName="Update" Text="Update" />
             <asp:LinkButton ID="UpdateCancelButton" runat="server"
                CausesValidation="False" CommandName="Cancel" Text="Cancel" />
        </EditItemTemplate>
        <InsertItemTemplate>
            Title:
            <asp:TextBox ID="TitleTextBox" runat="server" Text='<%# Bind("Title") %>' />
            <br />
            Description:
            <asp:TextBox ID="DescriptionTextBox" runat="server"
                Text='<%# Bind("Description") %>' />
            <br />
            <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True"
                CommandName="Insert" Text="Insert" />
             <asp:LinkButton ID="InsertCancelButton" runat="server"
                CausesValidation="False" CommandName="Cancel" Text="Cancel" />
        </InsertItemTemplate>
        <ItemTemplate>
            ImageID:
            <asp:Label ID="ImageIDLabel" runat="server" Text='<%# Eval("ImageID") %>' />
            <br />
            Title:
            <asp:Label ID="TitleLabel" runat="server" Text='<%# Bind("Title") %>' />
            <br />
            Description:
            <asp:Label ID="DescriptionLabel" runat="server"
                Text='<%# Bind("Description") %>' />
            <br />
            <asp:LinkButton ID="EditButton" runat="server" CausesValidation="False"
                CommandName="Edit" Text="Edit" />
             <asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False"
                CommandName="Delete" Text="Delete" />
             <asp:LinkButton ID="NewButton" runat="server" CausesValidation="False"
                CommandName="New" Text="New" />
        </ItemTemplate>
    </asp:FormView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:cmsConnectionString %>"
        InsertCommand="INSERT INTO [tbimages] ([ImageID], [Title], [Description]) VALUES (ImageID, Title, Description)"
        ProviderName="<%$ ConnectionStrings:cmsConnectionString.ProviderName %>"
        SelectCommand="SELECT ImageID, Title, Description FROM tbimages"
        UpdateCommand="UPDATE [tbimages] SET [Title] = ?, [Description] = ? WHERE [ImageID] = ?">

        <InsertParameters>
            <asp:Parameter Name="ImageID" Type="Int64" />
            <asp:Parameter Name="Title" Type="String" />
            <asp:Parameter Name="Description" Type="String" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter Name="Title" Type="String" />
            <asp:Parameter Name="Description" Type="String" />
            <asp:Parameter Name="ImageID" Type="Int64" />
        </UpdateParameters>
    </asp:SqlDataSource>
</code>```

i already define my connection string in the web config :

```<code>    <connectionStrings>
    <add name="cmsConnectionString" connectionString="server=localhost;User Id=root;password=123;database=cms" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
</code>```

Please if you have any idea to solve this let me know.

答:
You might want to change the Insert Command like so

```<code>InsertCommand="INSERT INTO [tbimages] ([ImageID], [Title], [Description]) VALUES (? , ? , ?)"
</code>```

UPDATED :

```<code>InsertCommand="INSERT INTO [tbimages] ([ImageID], [Title], [Description])
 VALUES (?ImageID , ?Title , ?Description)"
</code>```

ContentLicense: CC BY-SA 2.5

Title: How query a MySQL in ASP.NET?

Body:
I am trying to link my asp.net Formview to a MySQL database, but with no success.

Take a look at my code and please tell my where is my mistake:

<asp:FormView ID="FormView1" runat="server" DataKeyNames="ImageID"
        DataSourceID="SqlDataSource1" EnableModelValidation="True">
        <EditItemTemplate>
            ImageID:
            <asp:Label ID="ImageIDLabel1" runat="server" Text='<%# Eval("ImageID") %>' />

            Title:
            <asp:TextBox ID="TitleTextBox" runat="server" Text='<%# Bind("Title") %>' />

            Description:
            <asp:TextBox ID="DescriptionTextBox" runat="server"
                Text='<%# Bind("Description") %>' />

            <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True"
                CommandName="Update" Text="Update" />
             <asp:LinkButton ID="UpdateCancelButton" runat="server"
                CausesValidation="False" CommandName="Cancel" Text="Cancel" />
        </EditItemTemplate>
        <InsertItemTemplate>
            Title:
            <asp:TextBox ID="TitleTextBox" runat="server" Text='<%# Bind("Title") %>' />

            Description:
            <asp:TextBox ID="DescriptionTextBox" runat="server"
                Text='<%# Bind("Description") %>' />

            <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True"
                CommandName="Insert" Text="Insert" />
             <asp:LinkButton ID="InsertCancelButton" runat="server"
                CausesValidation="False" CommandName="Cancel" Text="Cancel" />
        </InsertItemTemplate>
        <ItemTemplate>
            ImageID:
            <asp:Label ID="ImageIDLabel" runat="server" Text='<%# Eval("ImageID") %>' />

            Title:
            <asp:Label ID="TitleLabel" runat="server" Text='<%# Bind("Title") %>' />

            Description:
            <asp:Label ID="DescriptionLabel" runat="server"
                Text='<%# Bind("Description") %>' />

            <asp:LinkButton ID="EditButton" runat="server" CausesValidation="False"
                CommandName="Edit" Text="Edit" />
             <asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False"
                CommandName="Delete" Text="Delete" />
             <asp:LinkButton ID="NewButton" runat="server" CausesValidation="False"
                CommandName="New" Text="New" />
        </ItemTemplate>
    </asp:FormView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:cmsConnectionString %>"
        InsertCommand="INSERT INTO [tbimages] ([ImageID], [Title], [Description]) VALUES (ImageID, Title, Description)"
        ProviderName="<%$ ConnectionStrings:cmsConnectionString.ProviderName %>"
        SelectCommand="SELECT ImageID, Title, Description FROM tbimages"
        UpdateCommand="UPDATE [tbimages] SET [Title] = ?, [Description] = ? WHERE [ImageID] = ?">

        <InsertParameters>
            <asp:Parameter Name="ImageID" Type="Int64" />
            <asp:Parameter Name="Title" Type="String" />
            <asp:Parameter Name="Description" Type="String" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter Name="Title" Type="String" />
            <asp:Parameter Name="Description" Type="String" />
            <asp:Parameter Name="ImageID" Type="Int64" />
        </UpdateParameters>
    </asp:SqlDataSource>

i already define my connection string in the web config :

    <connectionStrings>
    <add name="cmsConnectionString" connectionString="server=localhost;User Id=root;password=123;database=cms" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>

Please if you have any idea to solve this let me know.

Body:
You might want to change the Insert Command like so

InsertCommand="INSERT INTO [tbimages] ([ImageID], [Title], [Description]) VALUES (? , ? , ?)"

UPDATED :

InsertCommand="INSERT INTO [tbimages] ([ImageID], [Title], [Description])
 VALUES (?ImageID , ?Title , ?Description)"


问:
How do I use Kotlin object by reflection
Let's say I need to set property A given by a String in Kotlin object O given by a String by reflection. If O was a class I could do something like this (disregard it has no sense):

```<code>fun setValue(ownerClassName: String, fieldName: String, value : Any) {
    val enclosingClass = Class.forName(ownerClassName).newInstance()
    val enclosingClassField = enclosingClass.javaClass.getDeclaredField(fieldName)
    enclosingClassField.isAccessible = true
    enclosingClassField.set(enclosingClass, value)
}
</code>```

But how would I do it if O is an object?

答:
KClass has an objectInstance field:

```<code>Class.forName(ownerClassName).kotlin.objectInstance
</code>```

This is built into Kotlin reflection.

Returns: The instance of the object declaration, or null if this class is not an object declaration.

This would be even nicer if KClass had a forName method, but sadly it does not (yet), so we need to instead get the (Java) Class and convert it to KClass.

You can get a KClass instance from a Class by using the .kotlin extension property.

Then you can continue with the rest of your code. I converted this to Kotlin's reflection library:

```<code>val kClass = Class.forName(ownerClassName).kotlin
// Get the object OR a new instance if it doesn't exist
val instance = kClass.objectInstance ?: kClass.java.newInstance()

val member = kClass.memberProperties
// Has to be a mutable property, otherwise we can't set it
        .filterIsInstance<KMutableProperty<*>>()
// Check the name
        .filter { it.name == fieldName }
        .firstOrNull()

// Set the property
member?.setter?.call(instance, value)
</code>```

Here is a working test:

```<code>object TestObject {
    var field = 3
}

fun setValue(ownerClassName: String, fieldName: String, value: Any) {
    val kClass = Class.forName(ownerClassName).kotlin
    val instance = kClass.objectInstance ?: kClass.java.newInstance()

    val member = kClass.memberProperties.filterIsInstance<KMutableProperty<*>>()
            .firstOrNull { it.name == fieldName }

    member?.setter?.call(instance, value)
}

fun main(args: Array<String>) {
    println(TestObject.field) // 3
    setValue("some.package.TestObject", "field", 4)
    println(TestObject.field) // 4
}
</code>```

Body:
Let's say I need to set property A given by a String in Kotlin object O given by a String by reflection. If O was a class I could do something like this (disregard it has no sense):

fun setValue(ownerClassName: String, fieldName: String, value : Any) {
    val enclosingClass = Class.forName(ownerClassName).newInstance()
    val enclosingClassField = enclosingClass.javaClass.getDeclaredField(fieldName)
    enclosingClassField.isAccessible = true
    enclosingClassField.set(enclosingClass, value)
}

But how would I do it if O is an object?

Body:
KClass has an objectInstance field:

Class.forName(ownerClassName).kotlin.objectInstance

This is built into Kotlin reflection.

Returns: The instance of the object declaration, or null if this class is not an object declaration.

This would be even nicer if KClass had a forName method, but sadly it does not (yet), so we need to instead get the (Java) Class and convert it to KClass.

You can get a KClass instance from a Class by using the .kotlin extension property.

Then you can continue with the rest of your code. I converted this to Kotlin's reflection library:

val kClass = Class.forName(ownerClassName).kotlin
// Get the object OR a new instance if it doesn't exist
val instance = kClass.objectInstance ?: kClass.java.newInstance()

val member = kClass.memberProperties
// Has to be a mutable property, otherwise we can't set it
        .filterIsInstance<KMutableProperty<*>>()
// Check the name
        .filter { it.name == fieldName }
        .firstOrNull()

// Set the property
member?.setter?.call(instance, value)

Here is a working test:

object TestObject {
    var field = 3
}

fun setValue(ownerClassName: String, fieldName: String, value: Any) {
    val kClass = Class.forName(ownerClassName).kotlin
    val instance = kClass.objectInstance ?: kClass.java.newInstance()

    val member = kClass.memberProperties.filterIsInstance<KMutableProperty<*>>()
            .firstOrNull { it.name == fieldName }

    member?.setter?.call(instance, value)
}

fun main(args: Array<String>) {
    println(TestObject.field) // 3
    setValue("some.package.TestObject", "field", 4)
    println(TestObject.field) // 4
}


问:
How to declare pointers/references to template class member types?
I hope the title is not too far off. Consider the following piece of code:

```<code>template<class C>
struct Wrapper {
  using type = C;
};

int main()
{
  Wrapper<int>::type *a;
  Wrapper<int*>::type b;
  int i;
  Wrapper<int>::type &c = i;
  Wrapper<int&>::type d = i;
}
</code>```

Here, * and & can either go into the template argument or can be attached to the variable name. While I think both ways of declaring have the same effect, this is just my question:

Are the different ways of declaring pointers/references equivalent or are there situations in which one of them is preferred over the other for whatever reasons (e.g. safer, compiles faster, better style, ...)?

答:
Are the different ways of declaring pointers/references equivalent or are there situations in which one of them is preferred over the other for whatever reasons (e.g. safer, compiles faster, better style, ...)?

Not preferred, but they can yield actually different results. Think of partial specialization:

```<code>template <typename T>
struct Resource_wrapper {
    using type = T;
};

template <typename T>
struct Resource_wrapper<T*> {
   using type = std::unique_ptr<T>;
};
</code>```

Here, it makes a great difference between writing Resource_wrapper<int>::type* and Resource_wrapper<int*>::type.

Or consider std::unique_ptr<>, which also uses partial specialization:

```<code>std::unique_ptr<int[]> ptr; // smart pointer managing integer array
std::unique_ptr<int> ptr[5]; // array of five integer smart pointers
</code>```

Body:
I hope the title is not too far off. Consider the following piece of code:

template<class C>
struct Wrapper {
  using type = C;
};

int main()
{
  Wrapper<int>::type *a;
  Wrapper<int*>::type b;
  int i;
  Wrapper<int>::type &c = i;
  Wrapper<int&>::type d = i;
}

Here, * and & can either go into the template argument or can be attached to the variable name. While I think both ways of declaring have the same effect, this is just my question:

Are the different ways of declaring pointers/references equivalent or are there situations in which one of them is preferred over the other for whatever reasons (e.g. safer, compiles faster, better style, ...)?

Body:
Are the different ways of declaring pointers/references equivalent or are there situations in which one of them is preferred over the other for whatever reasons (e.g. safer, compiles faster, better style, ...)?

Not preferred, but they can yield actually different results. Think of partial specialization:

template <typename T>
struct Resource_wrapper {
    using type = T;
};

template <typename T>
struct Resource_wrapper<T*> {
   using type = std::unique_ptr<T>;
};

Here, it makes a great difference between writing Resource_wrapper<int>::type* and Resource_wrapper<int*>::type.

Or consider std::unique_ptr<>, which also uses partial specialization:

std::unique_ptr<int[]> ptr; // smart pointer managing integer array
std::unique_ptr<int> ptr[5]; // array of five integer smart pointers


问:
DAX query to exclude duplicated rows from table row count
I have a table with columns "RetailId & State". "State" Column is a measure.
In this table column "RetailId" can be duplicated.

So what i want to do is count rows where 'State' equal to 'Success' but also where "RetailId" exists only once (it is not duplicated).

In the row count, i want to ignore rows where "RetailId" exists more than once (is duplicated).

How can i apply the above condition to the DAX query i have below?

```<code>COUNTROWS(FILTER(FactProductHistory,FactProductHistory[State] = "Success"))
</code>```

Sample data below

```<code>RetailId | State
------------------
 3       |Success
------------------
 5       |Success
------------------
 3       |Success
------------------
 4       |Success
------------------
 5       |Success
------------------
 1       |Success
</code>```

In the sample data above, the count would be 2 (row 4 & 6) because "RetailId" for those rows is not duplicated. "RetailId" values 5 & 3 are duplicated so i don't want to include those rows in the count

And below is the DAX expression for the "State" measure column.

```<code>State = RELATED(TaskDetail[State])
</code>```

答:
I would first create a measure which calculates how many times a RetailID with state "success" occurs

cntRetail:=CALCULATE(COUNT([RetailID]),FactProductHistory[State]="Success")

Then I would use this in a filter, to only select the ones with a count of 1

```<code>myMeasure:=CALCULATE(DISTINCTCOUNT(FactProductHistory[RetailID])
,FILTER(all(FactProductHistory[RetailID]),[cntRetail]=1))
</code>```

Body:
I have a table with columns "RetailId & State". "State" Column is a measure.
In this table column "RetailId" can be duplicated.

So what i want to do is count rows where 'State' equal to 'Success' but also where "RetailId" exists only once (it is not duplicated).

In the row count, i want to ignore rows where "RetailId" exists more than once (is duplicated).

How can i apply the above condition to the DAX query i have below?

COUNTROWS(FILTER(FactProductHistory,FactProductHistory[State] = "Success"))

Sample data below

RetailId | State
------------------
 3       |Success
------------------
 5       |Success
------------------
 3       |Success
------------------
 4       |Success
------------------
 5       |Success
------------------
 1       |Success

In the sample data above, the count would be 2 (row 4 & 6) because "RetailId" for those rows is not duplicated. "RetailId" values 5 & 3 are duplicated so i don't want to include those rows in the count

And below is the DAX expression for the "State" measure column.

State = RELATED(TaskDetail[State])

Body:
I would first create a measure which calculates how many times a RetailID with state "success" occurs

cntRetail:=CALCULATE(COUNT([RetailID]),FactProductHistory[State]="Success")

Then I would use this in a filter, to only select the ones with a count of 1

myMeasure:=CALCULATE(DISTINCTCOUNT(FactProductHistory[RetailID])
,FILTER(all(FactProductHistory[RetailID]),[cntRetail]=1))


问:
How can I grab the context variable mid conversation and use it in my swift program?
So I'm writing a chatbot application which requires the intake of parameters and then uses these parameters in post requests sent via a payload.

I'm having problems with grabbing the context value from a context variable within swift and was wondering how I would go about grabbing the value of the context variable and executing an action based on the value of that said context.

An example of this would be the following dialog flow...

Me: Trigger this

Bot: Ok, give me param x

Me: x

Bot: Ok I have x param, will post job now

This is the kind of flow I want to happen in the background of my application under the hood but I'm not sure how to grab value x after my user has input it.

答:
So, suppose that you are using the iOS SDK from Watson Developer Cloud.

In your Conversation, add in your node:

```<code>{
  "context": {
    "myVariable": "<? input.text ?>"
  },
  "output": {
    "text": {
      "values": [
        "My context variable value is $myVariable."
      ],
      "selection_policy": "sequential"
    }, { "etc": "etc" }
</code>```

Obs.: The input.text will capture all that user types, you need to use regex for extract exactly what you want, try to see my examples in this answer.

And, in the iOS SDK you can see this follow example:

```<code>func testMessage() {
    let description1 = "Start a conversation."
    let expectation1 = self.expectation(description: description1)

    let response1 = ["Hi. It looks like a nice drive today. What would you like me to do?"]
    let nodes1 = ["node_1_1467221909631"]

    var context: Context?
    conversation.message(workspaceID: workspaceID, failure: failWithError) {
        response in

        // verify input
        XCTAssertNil(response.input?.text)

        // verify context
        XCTAssertNotNil(response.context.conversationID)
        XCTAssertNotEqual(response.context.conversationID, "")
        XCTAssertNotNil(response.context.system)
        XCTAssertNotNil(response.context.system.additionalProperties)
        XCTAssertFalse(response.context.system.additionalProperties.isEmpty)

        // verify entities
        XCTAssertTrue(response.entities.isEmpty)

        // verify intents
        XCTAssertTrue(response.intents.isEmpty)

        // verify output
        XCTAssertTrue(response.output.logMessages.isEmpty)
        XCTAssertEqual(response.output.text, response1)
        XCTAssertEqual(response.output.nodesVisited!, nodes1)

        context = response.context
        expectation1.fulfill()
    }
</code>```

So, you can access your context variable using:

```<code>context.myVariable
response.context.myVariable
</code>```

See more about methods in Watson Conversation here.

iOS SDK from Watson Developer Cloud.

Body:
So, suppose that you are using the iOS SDK from Watson Developer Cloud.

In your Conversation, add in your node:

{
  "context": {
    "myVariable": "<? input.text ?>"
  },
  "output": {
    "text": {
      "values": [
        "My context variable value is $myVariable."
      ],
      "selection_policy": "sequential"
    }, { "etc": "etc" }

Obs.: The input.text will capture all that user types, you need to use regex for extract exactly what you want, try to see my examples in this answer.

And, in the iOS SDK you can see this follow example:

func testMessage() {
    let description1 = "Start a conversation."
    let expectation1 = self.expectation(description: description1)

    let response1 = ["Hi. It looks like a nice drive today. What would you like me to do?"]
    let nodes1 = ["node_1_1467221909631"]

    var context: Context?
    conversation.message(workspaceID: workspaceID, failure: failWithError) {
        response in

        // verify input
        XCTAssertNil(response.input?.text)

        // verify context
        XCTAssertNotNil(response.context.conversationID)
        XCTAssertNotEqual(response.context.conversationID, "")
        XCTAssertNotNil(response.context.system)
        XCTAssertNotNil(response.context.system.additionalProperties)
        XCTAssertFalse(response.context.system.additionalProperties.isEmpty)

        // verify entities
        XCTAssertTrue(response.entities.isEmpty)

        // verify intents
        XCTAssertTrue(response.intents.isEmpty)

        // verify output
        XCTAssertTrue(response.output.logMessages.isEmpty)
        XCTAssertEqual(response.output.text, response1)
        XCTAssertEqual(response.output.nodesVisited!, nodes1)

        context = response.context
        expectation1.fulfill()
    }

So, you can access your context variable using:

context.myVariable
response.context.myVariable

See more about methods in Watson Conversation here.

iOS SDK from Watson Developer Cloud.


问:
How to show AccessDenied errors on the active page with CanCan in Rails3
I am trying to find a way to display my flash errors on the active page without the redirect_to method.

By the way, the standard flash[:alert] = exception.message didn't show me any error messages, so I changed it to flash[:error].

Thanks for any advice!

```<code>rescue_from CanCan::AccessDenied do |exception|
    flash[:error] = exception.message
    redirect_to deadlines_path
end
</code>```

答:
Try:

```<code>rescue_from CanCan::AccessDenied do |exception|
  flash.now[:alert] = exception.message
  render 'something_else'
  return false
end
</code>```

without a redirect.

Body:
I am trying to find a way to display my flash errors on the active page without the redirect_to method.

By the way, the standard flash[:alert] = exception.message didn't show me any error messages, so I changed it to flash[:error].

Thanks for any advice!

rescue_from CanCan::AccessDenied do |exception|
    flash[:error] = exception.message
    redirect_to deadlines_path
end

Body:
Try:

rescue_from CanCan::AccessDenied do |exception|
  flash.now[:alert] = exception.message
  render 'something_else'
  return false
end

without a redirect.


问:
JQuery - Disable scroll wheel until animation is completed

I am trying to disable mousewheel on mousewheel event and only enable it after the action is completed.

```<code>$(window).on('DOMMouseScroll mousewheel', function (event) {

    //disable mousewhell until the following animation is complete

    $('.box').animate({
        margin: div_offset+'px 0 0 0'
    }, 500);

    //enable mousewhell

    return false;
});
</code>```

I would also like the code to ignore every scroll after the first one, until the animation is complete. In this particular case, I want the animation to complete only once, even if the user scrolls for more than one tick on mouse wheel. Basically in this case, I want the mouse wheel to be disabled for 500 milliseconds after a single mouse scroll "tick", and not register the remaining "ticks" ever (if the user scrolls for 10 ticks during these 500 milliseconds, I only want one animation, while the rest are ignored). After 500 milliseconds, I want the mousewheel to be enabled once again.

I thank you in advance.

答:
What you can do is assign the function to the DOM event and then assign an empty function (or 'off' it) in the first line of that code.  Then when the animation is complete just re-assign the function to the DOM event.
Like so:

```<code>function test(event) {
    $(window).off('DOMMouseScroll mousewheel');
    //perform your scroll event
    $('.box').animate({
         margin: div_offset+'px 0 0 0'
    }, 500);
    sleep(500);
    $(window).on('DOMMouseScroll mousewheel',test);
}
$(window).on('DOMMouseScroll mousewheel',test);
</code>```

This will do the trick but it will hold your JS thread busy, you could also do:

```<code>function test(event) {
        $(window).off('DOMMouseScroll mousewheel');
        //perform your scroll event
        $('.box').animate({
             margin: div_offset+'px 0 0 0'
        }, 500);
        setTimeout(500,function() {$(window).on('DOMMouseScroll mousewheel',test(event));});

    }
    $(window).on('DOMMouseScroll mousewheel',test);
</code>```

And based on Frans answer:

```<code>function test(event) {
            $(window).off('DOMMouseScroll mousewheel');
            //perform your scroll event
            $('.box').animate({
                 margin: div_offset+'px 0 0 0'
            }, 500,function() {$(window).on('DOMMouseScroll mousewheel',test);});

        }
    $(window).on('DOMMouseScroll mousewheel',test);
</code>```

Body:
I am trying to disable mousewheel on mousewheel event and only enable it after the action is completed.

$(window).on('DOMMouseScroll mousewheel', function (event) {

    //disable mousewhell until the following animation is complete

    $('.box').animate({
        margin: div_offset+'px 0 0 0'
    }, 500);

    //enable mousewhell

    return false;
});

I would also like the code to ignore every scroll after the first one, until the animation is complete. In this particular case, I want the animation to complete only once, even if the user scrolls for more than one tick on mouse wheel. Basically in this case, I want the mouse wheel to be disabled for 500 milliseconds after a single mouse scroll "tick", and not register the remaining "ticks" ever (if the user scrolls for 10 ticks during these 500 milliseconds, I only want one animation, while the rest are ignored). After 500 milliseconds, I want the mousewheel to be enabled once again.

I thank you in advance.

Body:
What you can do is assign the function to the DOM event and then assign an empty function (or 'off' it) in the first line of that code.  Then when the animation is complete just re-assign the function to the DOM event.
Like so:

function test(event) {
    $(window).off('DOMMouseScroll mousewheel');
    //perform your scroll event
    $('.box').animate({
         margin: div_offset+'px 0 0 0'
    }, 500);
    sleep(500);
    $(window).on('DOMMouseScroll mousewheel',test);
}
$(window).on('DOMMouseScroll mousewheel',test);

This will do the trick but it will hold your JS thread busy, you could also do:

function test(event) {
        $(window).off('DOMMouseScroll mousewheel');
        //perform your scroll event
        $('.box').animate({
             margin: div_offset+'px 0 0 0'
        }, 500);
        setTimeout(500,function() {$(window).on('DOMMouseScroll mousewheel',test(event));});

    }
    $(window).on('DOMMouseScroll mousewheel',test);

And based on Frans answer:

function test(event) {
            $(window).off('DOMMouseScroll mousewheel');
            //perform your scroll event
            $('.box').animate({
                 margin: div_offset+'px 0 0 0'
            }, 500,function() {$(window).on('DOMMouseScroll mousewheel',test);});

        }
    $(window).on('DOMMouseScroll mousewheel',test);


问:
How to update Gradle dependencies to their latest version
Is there an easy way to get gradle to update dependencies to their latest available version?

For build reproducibility all my dependencies are defined with a version number like this in my build.gradle file:

```<code>dependencies {
    compile 'namespace:package1:version'
    compile 'namespace:package2:version'
    compile 'namespace:package3:version'
}
</code>```

Periodically I want to update every package to their latest version. Typically this is the first thing I do for a new sprint after making a release.

It's a real pain doing this manually for each package. Ideally I would like a command to update the build.gradle file for me but at the very least a command that prints out which package needs an update and what the latest version number is.

In ruby land I would run bundler update.

答:
Add to build.gradle:

```<code>plugins {
  id 'com.github.ben-manes.versions' version '0.17.0'
}
</code>```

Then you can do gradle dependencyUpdates to get a report of new versions. Unlike the eponymous Maven plugin, there doesn't seem to be a way of automatically updating the build.gradle yet.

More documentation: https://github.com/ben-manes/gradle-versions-plugin

Body:
Is there an easy way to get gradle to update dependencies to their latest available version?

For build reproducibility all my dependencies are defined with a version number like this in my build.gradle file:

dependencies {
    compile 'namespace:package1:version'
    compile 'namespace:package2:version'
    compile 'namespace:package3:version'
}

Periodically I want to update every package to their latest version. Typically this is the first thing I do for a new sprint after making a release.

It's a real pain doing this manually for each package. Ideally I would like a command to update the build.gradle file for me but at the very least a command that prints out which package needs an update and what the latest version number is.

In ruby land I would run bundler update.

Body:
Add to build.gradle:

plugins {
  id 'com.github.ben-manes.versions' version '0.17.0'
}

Then you can do gradle dependencyUpdates to get a report of new versions. Unlike the eponymous Maven plugin, there doesn't seem to be a way of automatically updating the build.gradle yet.

More documentation: https://github.com/ben-manes/gradle-versions-plugin


问:
How to work with Restful web service using jersey.Iam new to this Topic
Please suggest spring restful web service ..I have one doubt if iam having web service in one dynamic web project how can i get the value in client side(or)
For Example:
client side(Dynamic web project) iam giving two data 2 and 3 how to send this data to server side(onather Dynamic web project) for addition purpose is that possible.how server get data from client which is in another project.suggest some codes.</p>

答:
You can have any number of projects in single eclipse workspace working individually say WSClient (WS Client code) and WSServer (WS developed and deployed using this) two separate projects.

Here is the sample SpringController using Spring MVC to develop RESTful service:

```<code>import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SpringRestController {
    @RequestMapping(method = { RequestMethod.GET }, value = { "/testApplication" }, consumes = MediaType.ALL_VALUE, produces = MediaType.ALL_VALUE)
    public String getServerInfo() {
        System.out.println("I got hit");
        String message = "Hit the end point";
        return message;
    }
}
</code>```

Once you deployed the above service then you can consume this using even Browser. Once done that then use Service Client to consume the same.

Body:
You can have any number of projects in single eclipse workspace working individually say WSClient (WS Client code) and WSServer (WS developed and deployed using this) two separate projects.

Here is the sample SpringController using Spring MVC to develop RESTful service:

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SpringRestController {
    @RequestMapping(method = { RequestMethod.GET }, value = { "/testApplication" }, consumes = MediaType.ALL_VALUE, produces = MediaType.ALL_VALUE)
    public String getServerInfo() {
        System.out.println("I got hit");
        String message = "Hit the end point";
        return message;
    }
}

Once you deployed the above service then you can consume this using even Browser. Once done that then use Service Client to consume the same.


问:
Can anyone explain why '>>2' shift means 'divided by 4' in C codes?
I know and understand the result.

For example:

```<code><br>
 7 (decimal) = 00000111 (binary) <br>

and 7 >> 2 = 00000001 (binary) <br>
00000001 (binary) is same as 7 / 4 = 1 <br>
So 7 >> 2 = 7 / 4 <br>
<br>
</code>```

But I'd like to know how this logic was created.

Can anyone elaborate on this logic?

(Maybe it just popped up in a genius' head?)

And are there any other similar logics like this ?

Body:
I know and understand the result.

For example:

 7 (decimal) = 00000111 (binary)

and 7 >> 2 = 00000001 (binary)

00000001 (binary) is same as 7 / 4 = 1

So 7 >> 2 = 7 / 4

But I'd like to know how this logic was created.

Can anyone elaborate on this logic?

(Maybe it just popped up in a genius' head?)

And are there any other similar logics like this ?

Body:
Elaborating on Aniket Inge's answer:

Number: 30710 = 1001100112

How multiply by 10 works in decimal system

10 * (30710)

= 10 * (3*102 + 7*100)

= 3*102+1 + 7*100+1

= 3*103 + 7*101

= 307010

= 30710 << 1

Similarly multiply by 2 in binary,

2 * (1001100112)

= 2 * (1*28 + 1*25 + 1*24 + 1*21 1*20)

= 1*28+1 + 1*25+1 + 1*24+1 + 1*21+1 1*20+1

= 1*29 + 1*26 + 1*25 + 1*22 + 1*21

= 10011001102

= 1001100112 << 1


问:
How can I rotate a 3D array?
Currently, if I want to compare pressure under each of the paws of a dog, I only compare the pressure underneath each of the toes. But I want to try and compare the pressures underneath the entire paw.

But to do so I have to rotate them, so the toes overlap (better). Because most of the times the left and right paws are slightly rotated externally, so if you can't simply project one on top of the other. Therefore, I want to rotate the paws, so they are all aligned the same way.

Currently, I calculate the angle of rotation, by looking up the two middle toes and the rear one using the toe detection then I calculate the the angle between the yellow line (axis between toe green and red) and the green line (neutral axis).

Now I want to rotate the array would rotate around the rear toe, such that the yellow and green lines are aligned. But how do I do this?

Note that while this image is just 2D (only the maximal values of each sensor), I want to calculate this on a 3D array (10x10x50 on average). Also a downside of my angle calculation is that its very sensitive to the toe detection, so if somebody has a more mathematically correct proposal for calculating this, I'm all ears.

I have seen one study with pressure measurements on humans, where they used the local geometric inertial axis method, which at least was very reliable. But that still doesn't help me explain how to rotate the array!

 If someone feels the need to experiment, here's a file with all the sliced arrays that contain the pressure data of each paw. To clarfiy: walk_sliced_data is a dictionary that contains ['ser_3', 'ser_2', 'sel_1', 'sel_2', 'ser_1', 'sel_3'], which are the names of the measurements. Each measurement contains another dictionary, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] (example from 'sel_1') which represent the impacts that were extracted.

答:
Using the Python Imaging Library, you can rotate an array with for example:

```<code>array(Image.fromarray(<data>).rotate(<angle>, resample=Image.BICUBIC))
</code>```

From there, you can just create a for loop over the different layers of your 3D array.

If you have your first dimension as the layers, then array[<layer>] would return a 2D layer, thus:

```<code>for x in range(<amount of layers>):
    layer = <array>[i]
    <array>[i] = (Image.fromarray(layer).rotate(<angle>, resample=Image.BICUBIC))
</code>```

Results by @IvoFlipse, with a conversation suggesting:

Putting the array in a bigger array to remedy the darker background.

Look into resampling, perhaps scale the array first.

Moving the rear toe towards the middle allows you to rotate around that instead.

A smaller image can be determined by finding the borders and positioning them in a 15x15 again.

Title: How can I rotate a 3D array?

Body:
Using the Python Imaging Library, you can rotate an array with for example:

array(Image.fromarray(<data>).rotate(<angle>, resample=Image.BICUBIC))

From there, you can just create a for loop over the different layers of your 3D array.

If you have your first dimension as the layers, then array[<layer>] would return a 2D layer, thus:

for x in range(<amount of layers>):
    layer = <array>[i]
    <array>[i] = (Image.fromarray(layer).rotate(<angle>, resample=Image.BICUBIC))

Results by @IvoFlipse, with a conversation suggesting:

Putting the array in a bigger array to remedy the darker background.

Look into resampling, perhaps scale the array first.

Moving the rear toe towards the middle allows you to rotate around that instead.

A smaller image can be determined by finding the borders and positioning them in a 15x15 again.


问:
regex only match a word if it's a suffix of a word with more than 1 letter in front
I have this regex: wine($|\s|,|;)+ this works fine, however I encountered a problem, namely this will match with swine too. Therefore I only want to match it if it's a suffix of a word with at least 2 characters in front of wine, so for illustration it should match words like trwine, thisiswine, thewine and thus not things like swine, this is a swine
Off course I could do something like this:

```<code>import re

word = 'wine'
string = 'wine'
pattern = re.compile(".{}($|\s|,|;)+".format(word)) #word as suffix
match = pattern.search(string)
if match:
    if len(match.group(0)) > len(word) + 1:
        print(match)
    else:
        print('no match')
</code>```

But this is so ugly and I'm sure this can be easily done with a regex, but I don't know how.

答:
You may use a regex like

```<code>pattern = re.compile(r"[^\W\d_]{{2,}}{}\b".format(word))
</code>```

It will look like [^\W\d_]{2,}wine\b, see the regex demo.

Details

[^\W\d_]{2,} - 2 or more letters

wine  - wine substring

\b - word boundary

Python demo:

```<code>import re
word = 'wine'
s = 'words like trwine, thisiswine, thewine and thus not things like swine, this is a swine'
pattern = re.compile(r"[^\W\d_]{{2,}}{}\b".format(word))
match = pattern.search(s)
if match:
    print(match.group())
else:
    print('no match')
</code>```

Body:
I have this regex: wine($|\s|,|;)+ this works fine, however I encountered a problem, namely this will match with swine too. Therefore I only want to match it if it's a suffix of a word with at least 2 characters in front of wine, so for illustration it should match words like trwine, thisiswine, thewine and thus not things like swine, this is a swine
Off course I could do something like this:

import re

word = 'wine'
string = 'wine'
pattern = re.compile(".{}($|\s|,|;)+".format(word)) #word as suffix
match = pattern.search(string)
if match:
    if len(match.group(0)) > len(word) + 1:
        print(match)
    else:
        print('no match')

But this is so ugly and I'm sure this can be easily done with a regex, but I don't know how.

Body:
You may use a regex like

pattern = re.compile(r"[^\W\d_]{{2,}}{}\b".format(word))

It will look like [^\W\d_]{2,}wine\b, see the regex demo.

Details

[^\W\d_]{2,} - 2 or more letters

wine  - wine substring

\b - word boundary

Python demo:

import re
word = 'wine'
s = 'words like trwine, thisiswine, thewine and thus not things like swine, this is a swine'
pattern = re.compile(r"[^\W\d_]{{2,}}{}\b".format(word))
match = pattern.search(s)
if match:
    print(match.group())
else:
    print('no match')


问:
EditText + ImageSpan disappearing when carry over to next line
I'm using a custom EditText class that supports input of image spans via user input for a particular widget, and experiencing a strange issue. When the image span appears at the end of a a line, the carry over to the next line sometimes causes the image span to no longer be visible.

i.e before:

after I finish typing "not working." the edit text appears like so:

Basically, it appears the image span isn't properly handled by the edittext when it comes to moving it to the next line in a multi-line edittext. It is just invisible to the user after being carried over. I can backspace the second image's content until it looks exactly like the first image (to the "n") and we see the image span again.

Anyone know what I can do to solve this? It's a critical component I'd like to keep in my application. I also can't fallback to a single line edit text, the multiline support is also critical.

For reproducibility, here is my code for adding the ImageSpan to my edit text:

```<code>public void appendSpannedText(String s){
    if (textToDrawableMap == null || textToDrawableMap.isEmpty()
            || !textToDrawableMap.containsKey(s)) {
        return;
    }

    // Acquire the mapped drawable
    Drawable drawable = textToDrawableMap.get(s);

    Editable editable = getText();
    int start = getSelectionStart();

    // Insert the a space at the start that's eaten by the image span
    // being set.
    editable = editable.insert(start, SPACE);

    // Insert the new string at the starting point
    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(editable);

    // Create the span and set the new span to the appropriate range
    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
    ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);

    int nextIdx = start + 1;
    spannableStringBuilder.setSpan(span,
            start, nextIdx,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    // Update the spanned text and the cursor
    setText(spannableStringBuilder);
    setSelection(nextIdx);
}
</code>```

I just have a few icons that a user can press and it insert's the image span to the custom edit text via spannable. I use a mapping of text -> drawables that I support so I know which one to use when a user presses a particular button. The main thing is if you have an imagespan in the edittext, it can become invisible on new line when triggered.

答:
I was having the same problem with the EditText.

As a previous comment says, this happens because of the space character. When the EditText turns into a new line, the component removes the last character of the previous line, if this is a space. So, to avoid this to happen, we have to use a different one.

In the previous code we had this:

```<code> editable = editable.insert(start, SPACE);
</code>```

Instead of this, we should write the next code:

```<code>editable = editable.insert(start, anyCharacter);
</code>```

Where anyCharacter is a character different of " ".

Body:
I'm using a custom EditText class that supports input of image spans via user input for a particular widget, and experiencing a strange issue. When the image span appears at the end of a a line, the carry over to the next line sometimes causes the image span to no longer be visible.

i.e before:

after I finish typing "not working." the edit text appears like so:

Basically, it appears the image span isn't properly handled by the edittext when it comes to moving it to the next line in a multi-line edittext. It is just invisible to the user after being carried over. I can backspace the second image's content until it looks exactly like the first image (to the "n") and we see the image span again.

Anyone know what I can do to solve this? It's a critical component I'd like to keep in my application. I also can't fallback to a single line edit text, the multiline support is also critical.

For reproducibility, here is my code for adding the ImageSpan to my edit text:

public void appendSpannedText(String s){
    if (textToDrawableMap == null || textToDrawableMap.isEmpty()
            || !textToDrawableMap.containsKey(s)) {
        return;
    }

    // Acquire the mapped drawable
    Drawable drawable = textToDrawableMap.get(s);

    Editable editable = getText();
    int start = getSelectionStart();

    // Insert the a space at the start that's eaten by the image span
    // being set.
    editable = editable.insert(start, SPACE);

    // Insert the new string at the starting point
    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(editable);

    // Create the span and set the new span to the appropriate range
    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
    ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);

    int nextIdx = start + 1;
    spannableStringBuilder.setSpan(span,
            start, nextIdx,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    // Update the spanned text and the cursor
    setText(spannableStringBuilder);
    setSelection(nextIdx);
}

I just have a few icons that a user can press and it insert's the image span to the custom edit text via spannable. I use a mapping of text -> drawables that I support so I know which one to use when a user presses a particular button. The main thing is if you have an imagespan in the edittext, it can become invisible on new line when triggered.

Body:
I was having the same problem with the EditText.

As a previous comment says, this happens because of the space character. When the EditText turns into a new line, the component removes the last character of the previous line, if this is a space. So, to avoid this to happen, we have to use a different one.

In the previous code we had this:

 editable = editable.insert(start, SPACE);

Instead of this, we should write the next code:

editable = editable.insert(start, anyCharacter);

Where anyCharacter is a character different of " ".


问:
need to be able to add strings (paths) to an XML file using shell script
I need to be able to add strings (paths) to an XML file using shell script,
This is the XML that I have:

```<code><?xml version="1.0" encoding="utf-8" standalone="no"?>
<configurations>
    <smtpHost>smtp3.gmail.com</smtpHost>
    <smtpPort>25</smtpPort>
    <emailFrom>GitPushNotifier@gmail.com</emailFrom>
    <emailSubject>Push notification</emailSubject>
    <!-- Stash general URL-->
    <gitViewerURL>http://server0005.gmail.net:7990/projects/</gitViewerURL>
    <rule>
        <name>test_12.55.4</name>
        <repo>test</repo>
        <branch>refs/heads/12.55.4</branch>
        <emailTo>test@gmail.com</emailTo>
        <path>Server/.*/resources/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/SpringIOC/dataupgrader/v.*/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/test/dataupgrader/v.*/.*/.*\.java,Server/.*/resources/indexes/v.*/.*\.index,Server/.*/resources/SpringIOC/vanilla/.*\.xml</path>
    </rule>
    <rule>
        <name>test_12.55.10</name>
        <repo>test</repo>
        <branch>refs/heads/12.55.10</branch>
        <emailTo>test@gmail.com</emailTo>
        <path>Server/.*/resources/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/SpringIOC/dataupgrader/v.*/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/test/dataupgrader/v.*/.*/.*\.java,Server/.*/resources/indexes/v.*/.*\.index,Server/.*/resources/SpringIOC/vanilla/.*\.xml</path>
    </rule>
    <rule>
        <name>test_12.55.6</name>
        <repo>test</repo>
        <branch>refs/heads/12.55.6</branch>
        <emailTo>test@gmail.com</emailTo>
        <path>Server/.*/resources/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/SpringIOC/dataupgrader/v.*/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/test/dataupgrader/v.*/.*/.*\.java,Server/.*/resources/indexes/v.*/.*\.index,Server/.*/resources/SpringIOC/vanilla/.*\.xml</path>
    </rule>
</configurations>
</code>```

And I need to add additional path to the  subnode only for one version (let's say for test_12.55.10), The path's I want to add are:

Server/./resources/schema/v12_55_10/./.-dbSchemaDescriptor.xml,
Server/./resources/SpringIOC/dataupgrader/v12_55_10/./.-dataUpgrader.xml,
Server/./java/com/hp/mqm/dataupgrader/v12_55_10/./..java,
Server/./resources/indexes/v12_55_10/.*.index

I want to use sed or "xmlstarlet" as I saw other people suggested,
So the output that I want to get is:

```<code><path>Server/.*/resources/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/SpringIOC/dataupgrader/v.*/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/test/dataupgrader/v.*/.*/.*\.java,Server/.*/resources/indexes/v.*/.*\.index,Server/.*/resources/SpringIOC/vanilla/.*\.xml,Server/.*/resources/schema/v12_55_10/.*/.*-dbSchemaDescriptor\.xml,
Server/.*/resources/SpringIOC/dataupgrader/v12_55_10/.*/.*-dataUpgrader\.xml,
Server/.*/java/com/hp/mqm/dataupgrader/v12_55_10/.*/.*\.java,
Server/.*/resources/indexes/v12_55_10/.*\.index</path>
</code>```

答:
It can be done with sed. Here is a small sed script that should work as long as path follows name in a rule:

script.sed

```<code># filter for block from name to end of rule with the version:
/<name>test_12.55.10<\/name>/,/<\/rule>/ {
    /<\/path>/ {
                # this is a multiline second argument to s:
                s+<\/path>+,\
                    Server/./resources/schema/v12_55_10/./.-dbSchemaDescriptor.xml,\
                    Server/./resources/SpringIOC/dataupgrader/v12_55_10/./.-dataUpgrader.xml,\
                    Server/./java/com/hp/mqm/dataupgrader/v12_55_10/./..java,\
                    Server/./resources/indexes/v12_55_10/.*.index\
                </path>\
                +;
                # remove the whitespaces inserted above for readability
                s/,[ \n]+Server//g;
                }
    };
</code>```

You use it like this: sed -rf script.sed yourfile.xml.

You might be able to fill the version number and additional paths from a shell script (note the additional backslashes after each Server line).

Body:
I need to be able to add strings (paths) to an XML file using shell script,
This is the XML that I have:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<configurations>
    <smtpHost>smtp3.gmail.com</smtpHost>
    <smtpPort>25</smtpPort>
    <emailFrom>GitPushNotifier@gmail.com</emailFrom>
    <emailSubject>Push notification</emailSubject>

    <gitViewerURL>http://server0005.gmail.net:7990/projects/</gitViewerURL>
    <rule>
        <name>test_12.55.4</name>
        <repo>test</repo>
        <branch>refs/heads/12.55.4</branch>
        <emailTo>test@gmail.com</emailTo>
        <path>Server/.*/resources/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/SpringIOC/dataupgrader/v.*/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/test/dataupgrader/v.*/.*/.*\.java,Server/.*/resources/indexes/v.*/.*\.index,Server/.*/resources/SpringIOC/vanilla/.*\.xml</path>
    </rule>
    <rule>
        <name>test_12.55.10</name>
        <repo>test</repo>
        <branch>refs/heads/12.55.10</branch>
        <emailTo>test@gmail.com</emailTo>
        <path>Server/.*/resources/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/SpringIOC/dataupgrader/v.*/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/test/dataupgrader/v.*/.*/.*\.java,Server/.*/resources/indexes/v.*/.*\.index,Server/.*/resources/SpringIOC/vanilla/.*\.xml</path>
    </rule>
    <rule>
        <name>test_12.55.6</name>
        <repo>test</repo>
        <branch>refs/heads/12.55.6</branch>
        <emailTo>test@gmail.com</emailTo>
        <path>Server/.*/resources/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/SpringIOC/dataupgrader/v.*/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/test/dataupgrader/v.*/.*/.*\.java,Server/.*/resources/indexes/v.*/.*\.index,Server/.*/resources/SpringIOC/vanilla/.*\.xml</path>
    </rule>
</configurations>

And I need to add additional path to the  subnode only for one version (let's say for test_12.55.10), The path's I want to add are:

Server/./resources/schema/v12_55_10/./.-dbSchemaDescriptor.xml,
Server/./resources/SpringIOC/dataupgrader/v12_55_10/./.-dataUpgrader.xml,
Server/./java/com/hp/mqm/dataupgrader/v12_55_10/./..java,
Server/./resources/indexes/v12_55_10/.*.index

I want to use sed or "xmlstarlet" as I saw other people suggested,
So the output that I want to get is:

<path>Server/.*/resources/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/SpringIOC/dataupgrader/v.*/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/test/dataupgrader/v.*/.*/.*\.java,Server/.*/resources/indexes/v.*/.*\.index,Server/.*/resources/SpringIOC/vanilla/.*\.xml,Server/.*/resources/schema/v12_55_10/.*/.*-dbSchemaDescriptor\.xml,
Server/.*/resources/SpringIOC/dataupgrader/v12_55_10/.*/.*-dataUpgrader\.xml,
Server/.*/java/com/hp/mqm/dataupgrader/v12_55_10/.*/.*\.java,
Server/.*/resources/indexes/v12_55_10/.*\.index</path>

Body:
It can be done with sed. Here is a small sed script that should work as long as path follows name in a rule:

script.sed

# filter for block from name to end of rule with the version:
/<name>test_12.55.10<\/name>/,/<\/rule>/ {
    /<\/path>/ {
                # this is a multiline second argument to s:
                s+<\/path>+,\
                    Server/./resources/schema/v12_55_10/./.-dbSchemaDescriptor.xml,\
                    Server/./resources/SpringIOC/dataupgrader/v12_55_10/./.-dataUpgrader.xml,\
                    Server/./java/com/hp/mqm/dataupgrader/v12_55_10/./..java,\
                    Server/./resources/indexes/v12_55_10/.*.index\
                </path>\
                +;
                # remove the whitespaces inserted above for readability
                s/,[ \n]+Server//g;
                }
    };

You use it like this: sed -rf script.sed yourfile.xml.

You might be able to fill the version number and additional paths from a shell script (note the additional backslashes after each Server line).