How to calculate taking input from four fields in yii2 dynamic form - yii2

I've five fields- rate, qty. discount, cgst_percent, cgst_amount.
I want to calculate cgst_amount. The formula should be -
cgst_amount = ((rate*qty - (rate*qty*discount)/100)*cgst_percent)/100
To Start with simple steps, I tried cgst_amount = rate*qty
The javascript part is as below -
<?php
/* start getting the cgst */
$script = <<< JS
function getGst(item) {
var index = item.attr("id").replace(/[^0-9.]/g, "");
var qtyvar = ratevar = discvar = cgstpercentvar = cgstvar = 0;
var id = item.attr("id");
var myString = id.split("-").pop();
if (myString == "rate") {
fetch1 = index.concat("-qty");
fetch2 = index.concat("-discount");
fetch3 = index.concat("-cgst_rate");
} else if (myString == "qty") {
fetch1 = index.concat("-rate");
fetch2 = index.concat("-discount");
fetch3 = index.concat("-cgst_rate");
} else if (myString == "discount"){
fetch1 = index.concat("-qty");
fetch2 = index.concat("-rate");
fetch3 = index.concat("-cgst_rate");
} else {
fetch1 = index.concat("-qty");
fetch2 = index.concat("-rate");
fetch3 = index.concat("-discount");
}
temp1 = $("#productsales-"+fetch1+"").val();
temp2 = $("#productsales-"+fetch2+"").val();
temp3 = $("#productsales-"+fetch3+"").val();
//alert (temp2);
if (!isNaN(temp1) && temp1.length != 0) {
ratevar = temp1;
}
if (isNaN(temp2) || temp2.length != 0) {
discvar = temp2;
}
if (isNaN(temp3) || temp3.length != 0) {
cgstpercentvar = temp3;
}
qtyvar = item.val();
if (isNaN(qtyvar) || qtyvar.length == 0) {
qtyvar = 0;
}
//alert (qtyvar);
if (!isNaN(qtyvar) && !isNaN(ratevar) && !isNaN(discvar) && !isNaN(cgstpercentvar)) {
cgstvar = (parseFloat(qtyvar) * parseFloat(ratevar)).toFixed(2);
}
cgstField = "productsales-".concat(index).concat("-cgst_amount");
$("#"+cgstField+"").val(cgstvar);
}
JS;
$this->registerJs($script, View::POS_END);
/* end getting the cgst */
?>
Whn I key in rate and qty I get multiply of them as output in cgst_amount textbox. No problem so far. As soon as I key in anything in discount,the same texts are getting written in cgst_amount as output.
I'm not quite sure about the javascript part.
It is an extension of - Calculate from 3 inputfield in dynamic form yii2 and Calculate 3 fields and display the result in the 4th in yii2 dynamic form
If I work on the full formula, the javascript calculation part becomes - cgstvar = ((((parseFloat(ratevar) * parseFloat(qtyvar)) - (parseFloat(ratevar) * parseFloat(qtyvar) * parseFloat(discvar))/100) * parseFloat(cgstpercentvar))/100).toFixed(2);
And the example is as below image -
The actual result should have been - 5.43. Instead I'm getting -0.00

You meshed up with fields and variables, i have updated a script a bit :
function getGst(item) {
var index = item.attr("id").replace(/[^0-9.]/g, "");
var qtyvar = ratevar = discvar = cgstpercentvar = cgstvar = 0;
var id = item.attr("id");
var myString = id.split("-").pop();
quantity = index.concat("-qty");
rate = index.concat("-rate");
discount = index.concat("-discount");
cgstRate = index.concat("-cgst_rate");
temp1 = $("#productsales-"+quantity+"").val();
temp2 = $("#productsales-"+rate+"").val();
temp3 = $("#productsales-"+discount+"").val();
temp4 = $("#productsales-"+cgstRate+"").val();
if (isNaN(temp1) || temp1.length != 0) {
qtyvar = temp1;
}
if (!isNaN(temp2) && temp2.length != 0) {
ratevar = temp2;
}
if (isNaN(temp3) || temp3.length != 0) {
discvar = temp3;
}
if (isNaN(temp4) || temp4.length != 0) {
cgstpercentvar = temp4;
}
if (!isNaN(qtyvar) && !isNaN(ratevar) && !isNaN(discvar) && !isNaN(cgstpercentvar)) {
cgstvar = ((((parseFloat(ratevar) * parseFloat(qtyvar)) - (parseFloat(ratevar) * parseFloat(qtyvar) * parseFloat(discvar))/100) * parseFloat(cgstpercentvar))/100).toFixed(2);
}
cgstField = "productsales-".concat(index).concat("-cgst_amount");
$("#"+cgstField+"").val(cgstvar);
}

Related

.net core connect to mysql server

I have a issue here for the connect mysql.
I have a vps that contain mysql server have a database name is 'tuyendungbg'. it's had table and data in there. But when i'm connect and query to select data, that have error for 'Table 'tuyendungbg.Careers' doesn't exist'.
here is my controller :
[HttpGet("/nganh-nghe/{slug?}")]
public IActionResult Index(string slug, [FromQuery(Name =
"p")] int currentPage, int
pageSize)
{
if (!string.IsNullOrEmpty(slug))
{
var career = _context.Careers.FirstOrDefault(x =>
x.Slug.Equals(slug));
if (career != null)
{
ViewBag.CareerName = career.CareerName;
//var qr = _context.Careers.ToList();
var qr = (from p in
_context.CompanyCareers.Where(x => x.CareerId ==
career.ID)
from b in _context.Companies.Where(x =>
x.Id == p.CompanyId)
from i in
_context.IndustrialAreas.Where(x => x.ID ==
b.IndustrialAreaId).DefaultIfEmpty()
select new CompanyModelView()
{
Id = b.Id,
CompanyName = b.CompanyName,
BasicSalary = b.BasicSalary,
Allowance = b.Allowance,
DateCreate = b.DateCreate,
JobTitle = b.JobTitle,
Src = b.Src,
_IndustrialArea = i,
Address = b.Address,
Slug = b.Slug,
WorkTypes = (from tc in
_context.CompanyWorkTypes.Where(x =>
x.CompanyId == b.Id)
from type in
_context.WorkTypes.Where(x => x.Id
==
tc.TypeId)
select type)
}
).OrderByDescending(x => x.DateCreate).ToList();
// var worktype = (from w in
_context.CompanyWorkTypes.Where(x =>
x.CompanyId
== qr.))
var totalCate = qr.Count();
if (pageSize <= 0) pageSize = 10;
int countPages =
(int)Math.Ceiling((double)totalCate / pageSize);
if (currentPage > countPages)
currentPage = countPages;
if (currentPage < 1)
currentPage = 1;
var pagingModel = new PagingModel()
{
countpages = countPages,
currentpage = currentPage,
generateUrl = (pageNumber) =>
Url.Action(nameof(Index), new
{
p = pageNumber,
pageSize = pageSize
})
};
ViewBag.pagingModel = pagingModel;
ViewBag.totalPost = totalCate;
ViewBag.cateIndex = (currentPage - 1) * pageSize;
var companies = qr.Skip((currentPage - 1) *
pageSize)
.Take(pageSize).ToList();
ViewBag.JobCount = companies.Count();
//Set slider menu
var leftSlider = new LeftSliderModel()
{
Areas = new SelectList(_context.Areas,
nameof(Area.ID),
nameof(Area.NameArea)),
Careers = new SelectList(_context.Careers,
nameof(Career.ID),
nameof(Career.CareerName)),
WorkTypes = _context.WorkTypes.ToList(),
Experiences = _context.Experiences.ToList()
};
ViewBag.LeftSlider = leftSlider;
return View(companies);
}
}
return NotFound();
}

MYSQL Join and create Distinct json

I have the following select
if ($result = $mysqli->query("SELECT
a.quoteID, a.quoteTitle , a.notes, c.web_path
FROM quotes a
INNER JOIN users_files b on b.user_id = a.quoteID
INNER JOIN files c on c.id = b.file_id ORDER BY quoteID ASC"))
{
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
}
which gets me information I need.
[{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/23.pdf"},{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/22.jpeg"},{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/21.jpeg"},{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/20.jpeg"},{"quoteID":"2","quoteTitle":"Kaitlin","notes":"Smith","web_path":"\/surplusAdmin3\/upload\/24.jpg"},{"quoteID":"8","quoteTitle":"Bryar2","notes":"Long","web_path":"\/surplusAdmin3\/upload\/17.png"},{"quoteID":"11","quoteTitle":"Avram","notes":"Allison","web_path":"\/surplusAdmin3\/upload\/4.jpg"}]
I now need to get my result as:
[{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path1":"\/surplusAdmin3\/upload\/23.pdf","web_path2":"\/surplusAdmin3\/upload\/22.jpeg","web_path3":"\/surplusAdmin3\/upload\/21.jpeg","web_path4":"\/surplusAdmin3\/upload\/20.jpeg"}]
I am not looking to re-do the MYSQL statement I just need to create a new array in the format I need.
I have the following code:
var currentQuoteID =0;
var dataChanged = [];
var arrayRow = -1 ;
var fileCount = 0;
dataReturned.forEach(function(e){
console.log(' current quote '+ currentQuoteID + ' = '+ e["quoteID"] + 'file count = '+ fileCount);
if ( currentQuoteID !== e["quoteID"]) {dataChanged.push(e); arrayRow = arrayRow + 1; fileCount = 1}
else
{
console.log('just add the filename array Row = ' +arrayRow );
// need to insert to the array arrayRow
// dataChanged.push('web_path'+fileCount,e["web_path"]);
toPush = 'web_path'+fileCount+'"'+':'+'"'+ e["web_path"];
var field = 'web_path'+fileCount;
var data = e["web_path"];
var tempArray = [field,data];
dataChanged.push(toPush);
dataChanged.field = data;
//dataChanged = dataChanged.concat(tempArray);
fileCount = fileCount +1;
}
currentQuoteID = e["quoteID"];
console.log('stuff '+ JSON.stringify(dataChanged));
});
The result I am getting is :
dataChanged = [{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"/surplusAdmin3/upload/23.pdf","Type":"image"},"web_path1","/surplusAdmin3/upload/22.jpeg"]
What I need is
dataChanged = [{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"/surplusAdmin3/upload/23.pdf","Type":"image","web_path1","/surplusAdmin3/upload/22.jpeg"}]
But I cannot workout what I need to do here.
Got it working as follows:
// loop through and add field 'Type' can all be done in one loop.
dataReturned.forEach(function(e){
if (typeof e === "object" ){
e["Type"] = "other";
// console.log('stuff '+e['Type'][i] )
}
});
//loop through and workout the file type
dataReturned.forEach(function(e){
if (typeof e === "object" ){
var ext = e['web_path'].substr(e['web_path'].lastIndexOf('.') + 1);
if ( (ext === 'jpeg' ) || ( ext === 'jpg' )|| ( ext === 'png' )|| ( ext === 'gif' ) || ( ext === 'pdf' ))
{ e["Type"] = "image"; }
//console.log(e['web_path']);
// console.log('stuff '+ JSON.stringify(e))
}
});
// create a new array formated as needed
var currentQuoteID =0;
var arrayRow = -1 ;
var fileCount = 0;
dataReturned.forEach(function(e){
e["quoteID"] + 'file count = '+ fileCount);
if ( currentQuoteID !== e["quoteID"]) {dataChanged.push(e); arrayRow = arrayRow + 1; fileCount = 1}
else
{
//console.log('just add the filename array Row = ' +arrayRow );
// need to insert to the array arrayRow
// dataChanged.push('web_path'+fileCount,e["web_path"]);
var field = 'web_path'+fileCount;
var data = webPath+e["web_path"];
var tempArray = [field,data];
dataChanged[arrayRow]['web_path'+fileCount] = data
fileCount = fileCount +1;
}
currentQuoteID = e["quoteID"];
console.log('stuff '+ JSON.stringify(dataChanged));
});

Else if statement executes despite first condition is met

I have a patch of code that is intended to perform a search across a sheet then assign a variable if found.
Here's the code:
for(i=0;i<values.length; i++)
{
rowvalue = values[i];
for (j=l=1;j<rowvalue.length; j++) {
colvalue = rowvalue[j];
colvalue1 = colvalue.toString();
if(colvalue1.indexOf("search1")>-1 && colvalue1.indexOf("search2")==-1
&& rowvalue[j+5] == "") {
rowp = i+1, colp = j+1;
var itemcode = 9;
}
else if(colvalue1.indexOf("search1")>-1 && colvalue1.indexOf("search2")==-1) {
rowp = i+1, colp = j+1;
var itemcode = 9;
}
When executed, it will always return the value that met the 2nd condition(else if), despite the first condition was met. If I remove the else if statements, then I will get the correct return value.
As far as I know, once if statement was fulfilled, it's supposed to skip else or else if. But for some reason this wasn't the case in my situation. I'm not sure if I'm using the function properly or I'm misunderstanding on how the function work.
Try doing the same function this way:
if(colvalue1.indexOf("search1")>-1 && colvalue1.indexOf("search2")==-1 )
{
if (rowvalue[j+5] == "")
{
rowp = i+1, colp = j+1;
var itemcode = 9;
}else{
rowp = i+1, colp = j+1;
var itemcode = 9;
}
}
If you indent your code correctly it becomes rather obvious where it goes wrong
Your code indented.
for(i=0;i<values.length; i++)
{
rowvalue = values[i];
for (j=l=1;j<rowvalue.length; j++)
{
colvalue = rowvalue[j];
colvalue1 = colvalue.toString();
if(colvalue1.indexOf("search1")>-1 && colvalue1.indexOf("search2")==-1 && rowvalue[j+5] == "")
{
rowp = i+1, colp = j+1;
var itemcode = 9;
else if(colvalue1.indexOf("search1")>-1 && colvalue1.indexOf("search2")==-1)
{
rowp = i+1, colp = j+1;
var itemcode = 9;
}
What you probably meant was to as below, please note the "Added missing closing curly bracket"
for(i=0;i<values.length; i++)
{
rowvalue = values[i];
for (j=l=1;j<rowvalue.length; j++)
{
colvalue = rowvalue[j];
colvalue1 = colvalue.toString();
if(colvalue1.indexOf("search1")>-1 && colvalue1.indexOf("search2")==-1 && rowvalue[j+5] == "")
{
rowp = i+1, colp = j+1;
var itemcode = 9;
} // Added missing closing curly bracket
else if(colvalue1.indexOf("search1")>-1 && colvalue1.indexOf("search2")==-1)
{
rowp = i+1, colp = j+1;
var itemcode = 9;
}
}
}
single closing curly brace before the else statement should resolve the issue.

how to convert seconds to minutes:seconds in as3

hi to all i am new in action script 3 in flash cs6 im creating a game with a timer
i want to make the seconds to minutes:seconds format
example:
120 seconds to 2:00
this is my code:
var countDownDec:Number = 1;
var totalSecs = 120;
var countDownSecs = totalSecs;
counter.text = countDownSecs;
var time:Timer = new Timer(countDownDec*1000);
time.addEventListener(TimerEvent.TIMER, tick);
time.reset();
countDownSecs = totalSecs;
counter.text = countDownSecs;
time.start();
var frameLbl:FrameLabel;
function tick(e:TimerEvent):void {
time.start();
if(countDownSecs == 0){
time.stop();
countDownSecs = totalSecs;
gotoAndPlay('timesUp');
TimesUp.play();
}
else{
countDownSecs = countDownSecs - countDownDec;
counter.text = countDownSecs;
}
}
please help me to my problem
Code 100% working :
var count_down_interval:Number = 1
var total_seconds:Number = 120
var count_down_seconds:Number = total_seconds
var timer:Timer = new Timer(count_down_interval * 1000)
timer.addEventListener(TimerEvent.TIMER, timer_on_Tick)
function timer_on_Tick(e:TimerEvent):void {
if(count_down_seconds == 0){
timer.stop()
count_down_seconds = total_seconds
trace('game over')
} else{
count_down_seconds -= count_down_interval
counter.text = convert_time(count_down_seconds)
}
}
timer.start();
counter.text = convert_time(count_down_seconds)
function convert_time(time) {
var h, m, s:Number, t:String, a:Array
if(isNaN(time)){ // 05:37 -> 337 seconds
t = time
a = t.split(':')
if(a.length > 2){
h = int(a[0]), m = int(a[1]), s = int(a[2])
} else {
h = 0, m = int(a[0]), s = int(a[1])
}
return h*3600 + m*60 + s
} else { // 337 -> 05:37
t = ''
h = int(time/3600)
m = int((time-(h*3600))/60)
if(time >= 3600) t += (h<10 ? '0' : '') + h + ':'
t += (m<10 ? '0' : '') + m + ':'
t += (time % 60<10 ? '0' : '') + int(time % 60)
return t
}
}
Divide by 60 and round down for minutes, modulo (%) 60 for seconds
var totalSecs = 120;
var minutes = Math.floor(totalSecs / 60);
var seconds = totalSecs % 60;
var timeInMinutesSeconds = minutes + ":" + seconds;
EDIT:
Try this:
var countDownDec:Number = 1;
var totalSecs:int = 120;
var countDownSecs:int = totalSecs;
counter.text = getCountDownSecsText(countDownSecs);
var time:Timer = new Timer(countDownDec*1000);
time.addEventListener(TimerEvent.TIMER, tick);
var frameLbl:FrameLabel;
function tick(e:TimerEvent):void {
if(countDownSecs == 0) {
time.stop();
countDownSecs = totalSecs;
gotoAndPlay('timesUp');
TimesUp.play();
} else {
countDownSecs = countDownSecs - countDownDec;
counter.text = getCountDownSecsText(countDownSecs);
}
}
private function getCountDownSecsText(currentAmountSecs:int):String{
var minutes:int = Math.floor(currentAmountSecs / 60);
var seconds:int = currentAmountSecs % 60;
var prependString:String = "";
if( minutes > 9 ) {
prependString = "0";
}
return prependString + minutes + ":" + seconds;
}

How to synchronize CUDA threads when they are in the same loop and we need to synchronize them to execute only a limited part

I have written some code, and now I want to implement this on CUDA GPU but I'm new to synchronization. Below I'm presenting the code and I want to that LOOP1 to be executed by all threads (hence I want to this portion to take advantage of CUDA and the remaining portion (the portion other from the LOOP1) is to be executed by only a single thread.
do{
point_set = master_Q[(*num_mas) - 1].q;
List* temp = point_set;
List* pa = point_set;
if(master_Q[num_mas[0] - 1].max)
max_level = (int) (ceilf(il2 * log(master_Q[num_mas[0] - 1].max)));
*num_mas = (*num_mas) - 1;
while(point_set){
List* insert_ele = temp;
while(temp){
insert_ele = temp;
if((insert_ele->dist[insert_ele->dist_index-1] <= pow(2, max_level-1)) || (top_level == max_level)){
if(point_set == temp){
point_set = temp->next;
pa = temp->next;
}
else{
pa->next = temp->next;
}
temp = NULL;
List* new_point_set = point_set;
float maximum_dist = 0;
if(parent->p_index != insert_ele->point_index){
List* tmp = new_point_set;
float *b = &(data[(insert_ele->point_index)*point_len]);
**LOOP 1:** while(tmp){
float *c = &(data[(tmp->point_index)*point_len]);
float sum = 0.;
for(int j = 0; j < point_len; j+=2){
float d1 = b[j] - c[j];
float d2 = b[j+1] - c[j+1];
d1 *= d1;
d2 *= d2;
sum = sum + d1 + d2;
}
tmp->dist[tmp->dist_index] = sqrt(sum);
if(maximum_dist < tmp->dist[tmp->dist_index])
maximum_dist = tmp->dist[tmp->dist_index];
tmp->dist_index = tmp->dist_index+1;
tmp = tmp->next;
}
max_distance = maximum_dist;
}
while(new_point_set || insert_ele){
List* far, *par, *tmp, *tmp_new;
far = NULL;
tmp = new_point_set;
tmp_new = NULL;
float level_dist = pow(2, max_level-1);
float maxdist = 0, maxp = 0;
while(tmp){
if(tmp->dist[(tmp->dist_index)-1] > level_dist){
if(maxdist < tmp->dist[tmp->dist_index-1])
maxdist = tmp->dist[tmp->dist_index-1];
if(tmp == new_point_set){
new_point_set = tmp->next;
par = tmp->next;
}
else{
par->next = tmp->next;
}
if(far == NULL){
far = tmp;
tmp_new = far;
}
else{
tmp_new->next = tmp;
tmp_new = tmp;
}
if(parent->p_index != insert_ele->point_index)
tmp->dist_index = tmp->dist_index - 1;
tmp = tmp->next;
tmp_new->next = NULL;
}
else{
par = tmp;
if(maxp < tmp->dist[(tmp->dist_index)-1])
maxp = tmp->dist[(tmp->dist_index)-1];
tmp = tmp->next;
}
}
if(0 == maxp){
tmp = new_point_set;
aloc_mem[*tree_index].p_index = insert_ele->point_index;
aloc_mem[*tree_index].no_child = 0;
aloc_mem[*tree_index].level = max_level--;
parent->children_index[parent->no_child++] = *tree_index;
parent = &(aloc_mem[*tree_index]);
tree_index[0] = tree_index[0]+1;
while(tmp){
aloc_mem[*tree_index].p_index = tmp->point_index;
aloc_mem[(*tree_index)].no_child = 0;
aloc_mem[(*tree_index)].level = master_Q[(*cur_count_Q)-1].level;
parent->children_index[parent->no_child] = *tree_index;
parent->no_child = parent->no_child + 1;
(*tree_index)++;
tmp = tmp->next;
}
cur_count_Q[0] = cur_count_Q[0]-1;
new_point_set = NULL;
}
master_Q[*num_mas].q = far;
master_Q[*num_mas].parent = parent;
master_Q[*num_mas].valid = true;
master_Q[*num_mas].max = maxdist;
master_Q[*num_mas].level = max_level;
num_mas[0] = num_mas[0]+1;
if(0 != maxp){
aloc_mem[*tree_index].p_index = insert_ele->point_index;
aloc_mem[*tree_index].no_child = 0;
aloc_mem[*tree_index].level = max_level;
parent->children_index[parent->no_child++] = *tree_index;
parent = &(aloc_mem[*tree_index]);
tree_index[0] = tree_index[0]+1;
if(maxp){
int new_level = ((int) (ceilf(il2 * log(maxp)))) +1;
if (new_level < (max_level-1))
max_level = new_level;
else
max_level--;
}
else
max_level--;
}
if( 0 == maxp )
insert_ele = NULL;
}
}
else{
if(NULL == temp->next){
master_Q[*num_mas].q = point_set;
master_Q[*num_mas].parent = parent;
master_Q[*num_mas].valid = true;
master_Q[*num_mas].level = max_level;
num_mas[0] = num_mas[0]+1;
}
pa = temp;
temp = temp->next;
}
}
if((*num_mas) > 1){
List *temp2 = master_Q[(*num_mas)-1].q;
while(temp2){
List* temp3 = master_Q[(*num_mas)-2].q;
master_Q[(*num_mas)-2].q = temp2;
if((master_Q[(*num_mas)-1].parent)->p_index != (master_Q[(*num_mas)-2].parent)->p_index){
temp2->dist_index = temp2->dist_index - 1;
}
temp2 = temp2->next;
master_Q[(*num_mas)-2].q->next = temp3;
}
num_mas[0] = num_mas[0]-1;
}
point_set = master_Q[(*num_mas)-1].q;
temp = point_set;
pa = point_set;
parent = master_Q[(*num_mas)-1].parent;
max_level = master_Q[(*num_mas)-1].level;
if(master_Q[(*num_mas)-1].max)
if( max_level > ((int) (ceilf(il2 * log(master_Q[(*num_mas)-1].max)))) +1)
max_level = ((int) (ceilf(il2 * log(master_Q[(*num_mas)-1].max)))) +1;
num_mas[0] = num_mas[0]-1;
}
}while(*num_mas > 0);
If you want a single kernel to execute parts of its code on only a single thread within a block, use an if statement to execute a portion of code for only a single threadIdx and then barrier synchronize. Perhaps you should take a stab at writing a kernel and posting that for people to look at.