问:
Trying to create dynamic cascading selects from a single JSON array using jQuery
I am sure this has been done and I suspect I am just not searching for the correct terms so please don't blast me for asking something that has already been answered.

I have an array of item attributes (dynamic) and I want to drill down with select boxes to a final item.

```<code>var JSONarray = [
 {'itemAtID':1,
  'attribute1':'sm',
  'attribute2':'blue',
  'attribute3':'short sleeved'
 },
 {'itemAtID':2,
  'attribute1':'med',
  'attribute2':'blue',
  'attribute3':'short sleeved'
 },
 {'itemAtID':3,
  'attribute1':'lg',
  'attribute2':'white',
  'attribute3':'short sleeved'
 },
 {'itemAtID':4,
  'attribute1':'med',
  'attribute2':'white',
  'attribute3':'short sleeved'
 },
 {'itemAtID':5,
  'attribute1':'lg',
  'attribute2':'blue',
  'attribute3':'long sleeved'
 }];
</code>```

UPDATED ARRAYS

```<code>var JSONarray = [
 {'itemAtID':1,
  'attribute1':'sm',
  'attribute2':'blue',
  'attribute3':'short sleeved',
  'QoH': 3,
  'image': '101001506-1.jpg'
 },
 {'itemAtID':2,
  'attribute1':'med',
  'attribute2':'blue',
  'attribute3':'short sleeved',
  'QoH': 3,
  'image': '101001506-2.jpg'
 },
 {'itemAtID':3,
  'attribute1':'lg',
  'attribute2':'white',
  'attribute3':'short sleeved',
  'QoH': 3,
  'image': '101001506-3.jpg'
 },
 {'itemAtID':4,
  'attribute1':'med',
  'attribute2':'white',
  'attribute3':'short sleeved',
  'QoH': 3,
  'image': '101001506-4.jpg'
 },
 {'itemAtID':5,
  'attribute1':'lg',
  'attribute2':'blue',
  'attribute3':'long sleeved',
  'QoH': 3,
  'image': '101001506-5.jpg'
 }];

var formFields =  [
  {'name':'itemAt1',
   'label': 'Size',
   'fieldOpts': ['sm','med','lg','xl']
  },
  {'name':'itemAt2',
   'label': 'Color',
   'fieldOpts': ['blue','white','black']
  },
  {'name':'itemAt3',
   'label': 'Style',
   'fieldOpts': ['short sleeve','long sleeve']
  }
 ];
</code>```

I have three dynamically generated select boxes:

UPDATED TO REFLECT INITIAL OPTIONS IN ALL SELECT BOXES

```<code> <form>
  <label>Size</label>
  <select name="attribute1" id="id_attribute1">
   <option value="">Select Size</option>
   <option value="sm">sm</option>
   <option value="md">md</option>
   <option value="lg">lg</option>
  </select>

  <label>Color</label>
  <select name="attribute2" id="id_attribute2">
   <option value="">Select Color</option>
   <option value="blue">blue</option>
   <option value="white">white</option>
  </select>

  <label>Style</label>
  <select name="attribute3" id="id_attribute3">
   <option value="">Select Style</option>
   <option value="short sleeve">short sleeve</option>
   <option value="long sleeve">long sleeve</option>
  </select>
 </form>
</code>```

When a user selects the size, I want to query the array and return the available colors. When the user selects style, I want to return the itemAtID.

This is a very simplified representation of what I am trying to accomplish, but if I can make this work, I can scale it up to suit my purpose. I am sure there has to be a plugin for this but I have not been able to find one that doesn't require AJAX which puts an unnecessary load on the server as the data has already been passed in the original array of objects.

UPDATE
I have realize that I need to refine my original plan a little to make it more useable. The user should be able to select any of the select boxes first and the options for the remaining unselected boxes should be updated as enabled or disabled based on either their existence or the QoH (quantity on hand). Options that don't exist in the JSONarray (like the black color) should not appear, but options that exist but not in the selected size/color/style or with a 0 QoH should be disabled.

When selections for all boxes have been made, the JSONarray should be queried for the itemAtID matching those options and a hidden field (itemAtID) should be updated and the submit button should be enabled.

So my plan is to use a class based onChange to trigger the function.

Create empty array (formSelects).

Loop through the formFields array and 1)enable or disable options based on the the current field selection and 2)when a selection exists, push it to the formSelects array.

If the formSelects.length equals the formFields.length, search the JSONarray for the row that matches the criteria and update the hidden itemAtID field and enable the submit button (and eventually update the image).

I think that will address my problems. If anyone sees any flaws in this plan, please let me know. I am not very fluent in jQuery so it would be nice to find out my plan won't work before I spend the next day trying to sort out the proper syntax.

UPDATE: just realize the first flaw. I have to figure out a way to deal with resetting the form so you don't get pigeon holed by your selections...in other words, if you style selection disables a size or color you would rather have, you would be stuck...not sure how to handle that.

Thanks for your help and your patience with my shifting plan.

答:
For the id_attribute2 id select values you could do.

```<code>$(document).on('change','#id_attribute1',function(){
     let tmpVal = $(this).find("option:selected").val();
     $("#id_attribute2").html('<option value="">please select color</option>');
     for(var z = 0 ; z < JSONarray.length ; z++)
     {
        if(JSONarray[z]['attribute1'] == tmpVal)
           $("#id_attribute2").append('<option value="'+JSONarray[z]['attribute2']+'">'+JSONarray[z]['attribute2']+'</option>');
     }
});
</code>```

Body:
I am sure this has been done and I suspect I am just not searching for the correct terms so please don't blast me for asking something that has already been answered.

I have an array of item attributes (dynamic) and I want to drill down with select boxes to a final item.

var JSONarray = [
 {'itemAtID':1,
  'attribute1':'sm',
  'attribute2':'blue',
  'attribute3':'short sleeved'
 },
 {'itemAtID':2,
  'attribute1':'med',
  'attribute2':'blue',
  'attribute3':'short sleeved'
 },
 {'itemAtID':3,
  'attribute1':'lg',
  'attribute2':'white',
  'attribute3':'short sleeved'
 },
 {'itemAtID':4,
  'attribute1':'med',
  'attribute2':'white',
  'attribute3':'short sleeved'
 },
 {'itemAtID':5,
  'attribute1':'lg',
  'attribute2':'blue',
  'attribute3':'long sleeved'
 }];

UPDATED ARRAYS

var JSONarray = [
 {'itemAtID':1,
  'attribute1':'sm',
  'attribute2':'blue',
  'attribute3':'short sleeved',
  'QoH': 3,
  'image': '101001506-1.jpg'
 },
 {'itemAtID':2,
  'attribute1':'med',
  'attribute2':'blue',
  'attribute3':'short sleeved',
  'QoH': 3,
  'image': '101001506-2.jpg'
 },
 {'itemAtID':3,
  'attribute1':'lg',
  'attribute2':'white',
  'attribute3':'short sleeved',
  'QoH': 3,
  'image': '101001506-3.jpg'
 },
 {'itemAtID':4,
  'attribute1':'med',
  'attribute2':'white',
  'attribute3':'short sleeved',
  'QoH': 3,
  'image': '101001506-4.jpg'
 },
 {'itemAtID':5,
  'attribute1':'lg',
  'attribute2':'blue',
  'attribute3':'long sleeved',
  'QoH': 3,
  'image': '101001506-5.jpg'
 }];

var formFields =  [
  {'name':'itemAt1',
   'label': 'Size',
   'fieldOpts': ['sm','med','lg','xl']
  },
  {'name':'itemAt2',
   'label': 'Color',
   'fieldOpts': ['blue','white','black']
  },
  {'name':'itemAt3',
   'label': 'Style',
   'fieldOpts': ['short sleeve','long sleeve']
  }
 ];

I have three dynamically generated select boxes:

UPDATED TO REFLECT INITIAL OPTIONS IN ALL SELECT BOXES

 <form>
  Size
  <select name="attribute1" id="id_attribute1">
   <option value="">Select Size</option>
   <option value="sm">sm</option>
   <option value="md">md</option>
   <option value="lg">lg</option>
  </select>

  Color
  <select name="attribute2" id="id_attribute2">
   <option value="">Select Color</option>
   <option value="blue">blue</option>
   <option value="white">white</option>
  </select>

  Style
  <select name="attribute3" id="id_attribute3">
   <option value="">Select Style</option>
   <option value="short sleeve">short sleeve</option>
   <option value="long sleeve">long sleeve</option>
  </select>
 </form>

When a user selects the size, I want to query the array and return the available colors. When the user selects style, I want to return the itemAtID.

This is a very simplified representation of what I am trying to accomplish, but if I can make this work, I can scale it up to suit my purpose. I am sure there has to be a plugin for this but I have not been able to find one that doesn't require AJAX which puts an unnecessary load on the server as the data has already been passed in the original array of objects.

UPDATE
I have realize that I need to refine my original plan a little to make it more useable. The user should be able to select any of the select boxes first and the options for the remaining unselected boxes should be updated as enabled or disabled based on either their existence or the QoH (quantity on hand). Options that don't exist in the JSONarray (like the black color) should not appear, but options that exist but not in the selected size/color/style or with a 0 QoH should be disabled.

When selections for all boxes have been made, the JSONarray should be queried for the itemAtID matching those options and a hidden field (itemAtID) should be updated and the submit button should be enabled.

So my plan is to use a class based onChange to trigger the function.

Create empty array (formSelects).

Loop through the formFields array and 1)enable or disable options based on the the current field selection and 2)when a selection exists, push it to the formSelects array.

If the formSelects.length equals the formFields.length, search the JSONarray for the row that matches the criteria and update the hidden itemAtID field and enable the submit button (and eventually update the image).

I think that will address my problems. If anyone sees any flaws in this plan, please let me know. I am not very fluent in jQuery so it would be nice to find out my plan won't work before I spend the next day trying to sort out the proper syntax.

UPDATE: just realize the first flaw. I have to figure out a way to deal with resetting the form so you don't get pigeon holed by your selections...in other words, if you style selection disables a size or color you would rather have, you would be stuck...not sure how to handle that.

Thanks for your help and your patience with my shifting plan.

Body:
For the id_attribute2 id select values you could do.

$(document).on('change','#id_attribute1',function(){
     let tmpVal = $(this).find("option:selected").val();
     $("#id_attribute2").html('<option value="">please select color</option>');
     for(var z = 0 ; z < JSONarray.length ; z++)
     {
        if(JSONarray[z]['attribute1'] == tmpVal)
           $("#id_attribute2").append('<option value="'+JSONarray[z]['attribute2']+'">'+JSONarray[z]['attribute2']+'</option>');
     }
});


来源: stackexchange

问:
collectionView didSelectItemAt indexPath not being called
When attempting to select a cell in my collection view, nothing happens. I have my delegate set up but it does not get called when the user taps.

```<code>func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    print("cell selected")
}
</code>```

The cell is a custom cell containing a CAShapeLayer and a UILabel. I have attempted to mess around with the isUserInteractionEnabled method to no avail.

In addition, I can sometimes get the "cell selected" message to print if I tap really fast but it is very seldom. Let me know if you have any suggestions!

```<code>func drawCircle() {
    var circleLayer: CAShapeLayer!

    let arcCenter = CGPoint(x: frame.size.width / 2.0, y: (frame.size.height / 2.0) - 15)
    let circlePath = UIBezierPath(arcCenter: arcCenter, radius: (frame.size.width - 20) / 2, startAngle: 0.0, endAngle: CGFloat(.pi * 2.0), clockwise: true)

    circleLayer = CAShapeLayer()
    circleLayer.path = circlePath.cgPath
    circleLayer.fillColor = UIColor.clear.cgColor
    circleLayer.strokeColor = UIColor(named: "Fourth")?.cgColor
    circleLayer.lineWidth = 8.0

    circleLayer.strokeEnd = 1.0

    // Add the circleLayer to the view's layer's sublayers
    layer.addSublayer(circleLayer)
}
</code>```

答:
This was fixed by setting cancelsTouchesInViewmethod to false on a UITapGestureRecognizer I have. Full code below.

```<code>let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.hideKeyboardByTappingOutside))
    tap.cancelsTouchesInView = false
    self.view.addGestureRecognizer(tap)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When attempting to select a cell in my collection view, nothing happens. I have my delegate set up but it does not get called when the user taps.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    print("cell selected")
}

The cell is a custom cell containing a CAShapeLayer and a UILabel. I have attempted to mess around with the isUserInteractionEnabled method to no avail.

In addition, I can sometimes get the "cell selected" message to print if I tap really fast but it is very seldom. Let me know if you have any suggestions!

func drawCircle() {
    var circleLayer: CAShapeLayer!

    let arcCenter = CGPoint(x: frame.size.width / 2.0, y: (frame.size.height / 2.0) - 15)
    let circlePath = UIBezierPath(arcCenter: arcCenter, radius: (frame.size.width - 20) / 2, startAngle: 0.0, endAngle: CGFloat(.pi * 2.0), clockwise: true)

    circleLayer = CAShapeLayer()
    circleLayer.path = circlePath.cgPath
    circleLayer.fillColor = UIColor.clear.cgColor
    circleLayer.strokeColor = UIColor(named: "Fourth")?.cgColor
    circleLayer.lineWidth = 8.0

    circleLayer.strokeEnd = 1.0

    // Add the circleLayer to the view's layer's sublayers
    layer.addSublayer(circleLayer)
}

Body:
This was fixed by setting cancelsTouchesInViewmethod to false on a UITapGestureRecognizer I have. Full code below.

let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.hideKeyboardByTappingOutside))
    tap.cancelsTouchesInView = false
    self.view.addGestureRecognizer(tap)


问:
How would I make this credit card validator /identifier output to an array
I'm working on a project for credit card identification and validation, I'm trying to use nodes fs to write to another file and my goal to do that is use an array, fill with each line that this function outputs. Here is my full code block:

```<code>import { createReadStream } from 'fs'
import { createInterface } from 'readline'
import { getCompanyName } from './cardType'
import cardValidator from './cardValidator'
import * as fs from 'fs'

const lineReader = createInterface({
input: createReadStream('data/input.txt')
})

const output: string[] = []

lineReader.on('line', (creditCard: string) => {
var company = `${getCompanyName(creditCard)}: ${creditCard} (${
cardValidator(creditCard) ? 'valid' : 'invalid'
})`

//make company output an array called results then use results to
//wright lines to the output file

fs.writeFile('./data/output.txt', results[0, 1, 2, 3, etc], err => {
if (err) throw err && console.log('it broke as heck')
console.log('The file has been saved!')
})
})
</code>```

How would I make this happen?

答:
Assuming you get a done event, something like a simple callback would work:

```<code>const read = (cb: (lines: string) => void) => { // Wrap in a new function
  const lineReader = createInterface({
    input: createReadStream('data/input.txt')
  })

  const output: string[] = []

  lineReader.on('line', (creditCard: string) => {
    output.push(creditCard);
  });

  lineReader.on('done', (creditCard: string) => {
    cb(output)
  });
}
</code>```

This is similar to how you would use setTimeout etc.

Body:
I'm working on a project for credit card identification and validation, I'm trying to use nodes fs to write to another file and my goal to do that is use an array, fill with each line that this function outputs. Here is my full code block:

import { createReadStream } from 'fs'
import { createInterface } from 'readline'
import { getCompanyName } from './cardType'
import cardValidator from './cardValidator'
import * as fs from 'fs'

const lineReader = createInterface({
input: createReadStream('data/input.txt')
})

const output: string[] = []

lineReader.on('line', (creditCard: string) => {
var company = `${getCompanyName(creditCard)}: ${creditCard} (${
cardValidator(creditCard) ? 'valid' : 'invalid'
})`

//make company output an array called results then use results to
//wright lines to the output file

fs.writeFile('./data/output.txt', results[0, 1, 2, 3, etc], err => {
if (err) throw err && console.log('it broke as heck')
console.log('The file has been saved!')
})
})

How would I make this happen?

Body:
Assuming you get a done event, something like a simple callback would work:

const read = (cb: (lines: string) => void) => { // Wrap in a new function
  const lineReader = createInterface({
    input: createReadStream('data/input.txt')
  })

  const output: string[] = []

  lineReader.on('line', (creditCard: string) => {
    output.push(creditCard);
  });

  lineReader.on('done', (creditCard: string) => {
    cb(output)
  });
}

This is similar to how you would use setTimeout etc.


问:
Microsoft graph v/s azure ad graph api v/s office 365 api
I have started exploring these technologies and gone through some documentations. But its hard to figure out the limitations, advantages and which is best in what scenario.

Can anyone tell me the differences, advantages and disadvantages of each?

答:
Dan Kershaw wrote an excellent article comparing the Microsoft Graph and Azure AD Graph.  It was updated in May 2017 to reflect new functionality we've brought to Microsoft Graph API.

In general, we recommend the use of Microsoft Graph over Azure AD Graph, as Microsoft Graph is where we are investing for Microsoft cloud services.

The Microsoft Graph continues to see new features and has nearly closed the gap. Through the Microsoft Graph, you can access Office APIs (like calendar, mail, contacts, etc) and Azure AD APIs (organization hierarchy, users, etc.).  It's highly recommended that you use the Microsoft Graph API in your application but the Azure AD Graph API is still available if you need it.

Also, be sure to check out the Microsoft Graph client libraries and code samples that are available in many languages.


问:
Gulp CSS syntax errors fail silently using gulp-concat and gulp-plumber
I am using gulp-concat and the sourcemap functionality for some CSS files. I am using plumber to catch any syntax errors in the source files. My problem is plumber doesn't warn me of errors when using gulp-concat. If I switch to gulp-concat-css error handling works fine, but then I lose sourcemap functionality. My code is below:</p>

```<code>var concat = require('gulp-concat');
var concatCss = require('gulp-concat-css');
var gulp = require('gulp');
var plumber = require('gulp-plumber');
var sourcemaps = require('gulp-sourcemaps');
var watch = require('gulp-watch');

gulp.task('styles', function() {
    return gulp.src('src/*.css')
    .pipe(plumber())
    .pipe(sourcemaps.init())
    .pipe(concat('styles.css'))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('dist/css'))
});

gulp.task('watch', function() {
    gulp.watch('src/*.css', ['styles'])
});

gulp.task('default', ['styles', 'watch']);
</code>```

答:
In the past, I've used the errorHandler option that plumber provides. It would look something like this in your code:

```<code>var onError = function (err) {
  console.log(err);
};

gulp.task('styles', function() {
    return gulp.src('src/*.css')
    .pipe(plumber({
      errorHandler: onError
    }))
    .pipe(sourcemaps.init())
    .pipe(concat('styles.css'))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('dist/css'))
});
</code>```

Hope it helps.

Body:
I am using gulp-concat and the sourcemap functionality for some CSS files. I am using plumber to catch any syntax errors in the source files. My problem is plumber doesn't warn me of errors when using gulp-concat. If I switch to gulp-concat-css error handling works fine, but then I lose sourcemap functionality. My code is below:

var concat = require('gulp-concat');
var concatCss = require('gulp-concat-css');
var gulp = require('gulp');
var plumber = require('gulp-plumber');
var sourcemaps = require('gulp-sourcemaps');
var watch = require('gulp-watch');

gulp.task('styles', function() {
    return gulp.src('src/*.css')
    .pipe(plumber())
    .pipe(sourcemaps.init())
    .pipe(concat('styles.css'))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('dist/css'))
});

gulp.task('watch', function() {
    gulp.watch('src/*.css', ['styles'])
});

gulp.task('default', ['styles', 'watch']);

Body:
In the past, I've used the errorHandler option that plumber provides. It would look something like this in your code:

var onError = function (err) {
  console.log(err);
};

gulp.task('styles', function() {
    return gulp.src('src/*.css')
    .pipe(plumber({
      errorHandler: onError
    }))
    .pipe(sourcemaps.init())
    .pipe(concat('styles.css'))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('dist/css'))
});

Hope it helps.


问:
Div tag's layering question
Suppose i am having two Div layer

```<code><div id="div1"> One </div>
<div id="div2"> Two </div>
</code>```

I want them both to be overlapped

and when i click the Button
i want that the Div1 layer to go in the background and the top layer should become Div2.

How can i achieve it through JavaScript ?

答:
So, from what I read, you just want to show one and hide the other? You can do that with display in css. Here is a way you can do that.

```<code><div id="div1">One</div>
<div id="div2" style="display:none;">Two</div>
<button onClick="change_layer()">Change the Layer</button>

function change_layer(){
   document.getElementById("div1").style.display = "none";
   document.getElementById("div2").style.display = "block";
}
</code>```

You can also use JQuery, but if that is all you need to do, JQuery probably isn't needed. If you actually want them layered, you would have to use z-index in css.

ContentLicense: CC BY-SA 2.5

Title: Div tag's layering question

Body:
Suppose i am having two Div layer

 One

 Two

I want them both to be overlapped

and when i click the Button
i want that the Div1 layer to go in the background and the top layer should become Div2.

How can i achieve it through JavaScript ?

Body:
So, from what I read, you just want to show one and hide the other? You can do that with display in css. Here is a way you can do that.

<div id="div1">One</div>
<div id="div2" style="display:none;">Two</div>
<button onClick="change_layer()">Change the Layer</button>

function change_layer(){
   document.getElementById("div1").style.display = "none";
   document.getElementById("div2").style.display = "block";
}

You can also use JQuery, but if that is all you need to do, JQuery probably isn't needed. If you actually want them layered, you would have to use z-index in css.


问:
Return Column Based on Another Specific Value
I'm trying to show which products our company offers have been purchased by a certain point in time. I would like to show each product's name and then a simple Y or N next to each product indicating if it was sold by a certain date. I'm not sure how to structure the query - this is my attempt

```<code>SELECT product_offering as Product
CASE WHEN date_key='2017-03-30' THEN product_sold ELSE product_sold END as Sold
FROM table1
</code>```

It should look like, if, as a shortened example

1st product sold 2017-03-27

2nd product sold 2017-04-03

3rd product sold 2017-3-28

```<code>|Product | Sold |
|1st Prod|   Y  |
|2nd Prod|   N  |
|3rd Prod|   Y  |
</code>```

Instead, the "Sold" column isn't entirely accurate. I think this has something to do with the date being equal to a certain date instead of a range leading up to, but i'm not sure how to fix this.

答:
If i understand your problem correctly i.e. You need to compare column date_key to a date value (which in your example is 2017-03-30)  and if its less, then return Y else N. In that case, i don't think aggregation is needed.

You just need case.

```<code>select product_offering as Product,
       case when date_key <= DATE '2017-03-30' then 'Y' else 'N' end as Sold
from table1
order by product_offering
</code>```

<= or < in above query depending whether you want to include date value or not.

Result:

```<code>+-------------+------+
|   PRODUCT   | SOLD |
+-------------+------+
| 1st product | Y    |
| 2nd product | N    |
| 3rd product | Y    |
+-------------+------+
</code>```

DEMO

P.S. Above demo is also valid for teradata (and has already been tested)

Body:
I'm trying to show which products our company offers have been purchased by a certain point in time. I would like to show each product's name and then a simple Y or N next to each product indicating if it was sold by a certain date. I'm not sure how to structure the query - this is my attempt

SELECT product_offering as Product
CASE WHEN date_key='2017-03-30' THEN product_sold ELSE product_sold END as Sold
FROM table1

It should look like, if, as a shortened example

1st product sold 2017-03-27

2nd product sold 2017-04-03

3rd product sold 2017-3-28

|Product | Sold |
|1st Prod|   Y  |
|2nd Prod|   N  |
|3rd Prod|   Y  |

Instead, the "Sold" column isn't entirely accurate. I think this has something to do with the date being equal to a certain date instead of a range leading up to, but i'm not sure how to fix this.

Body:
If i understand your problem correctly i.e. You need to compare column date_key to a date value (which in your example is 2017-03-30)  and if its less, then return Y else N. In that case, i don't think aggregation is needed.

You just need case.

select product_offering as Product,
       case when date_key <= DATE '2017-03-30' then 'Y' else 'N' end as Sold
from table1
order by product_offering

<= or < in above query depending whether you want to include date value or not.

Result:

+-------------+------+
|   PRODUCT   | SOLD |
+-------------+------+
| 1st product | Y    |
| 2nd product | N    |
| 3rd product | Y    |
+-------------+------+

DEMO

P.S. Above demo is also valid for teradata (and has already been tested)


问:
How to read two columns using python
How to read two columns the first of which contains letters and the second of the values.

```<code>C0      -0.158040
C1      -0.157117
C2      -0.143805
C3      -0.140561
S4      0.059175
H5      0.128940
H6      0.129007
H7      0.142421
H8      0.139979
</code>```

I often used this script below (it works for two or more columns), but not for this time !!

```<code>with open('file.csv') as f:
    f=[x.strip() for x in f if x.strip()]
    data=[tuple(map(float,x.split())) for x in f[2:]]
    oX=[x[0] for x in data]
    oY=[x[1] for x in data]
</code>```

Thanks for your help.

Title: How to read two columns using python

Body:
How to read two columns the first of which contains letters and the second of the values.

C0      -0.158040
C1      -0.157117
C2      -0.143805
C3      -0.140561
S4      0.059175
H5      0.128940
H6      0.129007
H7      0.142421
H8      0.139979

I often used this script below (it works for two or more columns), but not for this time !!

with open('file.csv') as f:
    f=[x.strip() for x in f if x.strip()]
    data=[tuple(map(float,x.split())) for x in f[2:]]
    oX=[x[0] for x in data]
    oY=[x[1] for x in data]

Thanks for your help.

Body:
Here is another solution:

import csv

with open('file.csv') as f:
    reader = csv.reader(f)
    for row in reader:
        res = row[0].split()
        oX = res[0]
        oY = res[1]
        print (oX, oY)

output:

('C0', '-0.158040')
('C1', '-0.157117')
('C2', '-0.143805')
('C3', '-0.140561')
('S4', '0.059175')
('H5', '0.128940')
('H6', '0.129007')
('H7', '0.142421')
('H8', '0.139979')


问:
Set label font with bold and italic
I'm trying to set a specific part of my label to bold and italic with NSMutableAttributedString, but I can only get one or the other. The font that I'm using is Clear Sans. Setting the entire label's font on the storyboard to Bold Italic works fine, but I only need part of it. So I used

```<code>for family in UIFont.familyNames() {
    print("\(family)\n\t\(UIFont.fontNamesForFamilyName(family))")
}
</code>```

to make sure it's there, and I found

```<code>Clear Sans
    ["ClearSans", "ClearSans-Bold", "ClearSans-Italic"]
</code>```

For some reason, it's not in here but it is in the storyboard. So I tried to use this answer, but it crashes, I assume for the same reason that I didn't find ClearSans-BoldItalic, but I don't know why it's not in there.

Finally, I tried to just "stack" the two, like so

```<code>let bold = UIFont(name: "ClearSans-Bold", size: 20)
let italic = UIFont(name: "ClearSans-Italic", size: 20)

attributedCaption.addAttribute(NSFontAttributeName, value: bold!, range: (imageContainer.caption as NSString).rangeOfString(matchString))
attributedCaption.addAttribute(NSFontAttributeName, value: italic!, range: (imageContainer.caption as NSString).rangeOfString(matchString))
</code>```

but all this does is use the last attribute, which is what I had expected it to do.

Is there some other method I can use to do this so that I get both bold and italic to show on the same part of the label?

Edit

I wanted to include my fonts that are in the project, so it's clear that I've already imported them. The second image is the list of fonts on the storyboard. While it's covered up, the family is in fact Clear Sans.

答:
```<code>UIFont.italicSystemFont(ofSize: 15.0)
UIFont.boldSystemFont(ofSize: 15)
</code>```

<p>if you want to custom font of label like fond system . you can try my solution .
it works good for swift 3 </p>

Title: Set label font with bold and italic

Body:
I'm trying to set a specific part of my label to bold and italic with NSMutableAttributedString, but I can only get one or the other. The font that I'm using is Clear Sans. Setting the entire label's font on the storyboard to Bold Italic works fine, but I only need part of it. So I used

for family in UIFont.familyNames() {
    print("\(family)\n\t\(UIFont.fontNamesForFamilyName(family))")
}

to make sure it's there, and I found

Clear Sans
    ["ClearSans", "ClearSans-Bold", "ClearSans-Italic"]

For some reason, it's not in here but it is in the storyboard. So I tried to use this answer, but it crashes, I assume for the same reason that I didn't find ClearSans-BoldItalic, but I don't know why it's not in there.

Finally, I tried to just "stack" the two, like so

let bold = UIFont(name: "ClearSans-Bold", size: 20)
let italic = UIFont(name: "ClearSans-Italic", size: 20)

attributedCaption.addAttribute(NSFontAttributeName, value: bold!, range: (imageContainer.caption as NSString).rangeOfString(matchString))
attributedCaption.addAttribute(NSFontAttributeName, value: italic!, range: (imageContainer.caption as NSString).rangeOfString(matchString))

but all this does is use the last attribute, which is what I had expected it to do.

Is there some other method I can use to do this so that I get both bold and italic to show on the same part of the label?

Edit

I wanted to include my fonts that are in the project, so it's clear that I've already imported them. The second image is the list of fonts on the storyboard. While it's covered up, the family is in fact Clear Sans.

Body:
UIFont.italicSystemFont(ofSize: 15.0)
UIFont.boldSystemFont(ofSize: 15)

if you want to custom font of label like fond system . you can try my solution .
it works good for swift 3


问:
Java StringTemplate Iterating over List of Complex Object
I have a class like so:

```<code>public class Foo {
    private String s;
}
</code>```

And I have a list of said objects. I want to be able to iterate over this list and print out the string property s. I have the following code to render the string template:

```<code>Map<String, Object> params = new HashMap<>();
List<Foo> foos = new ArrayList<>();
foos.add(new Foo("A"));
foos.add(new Foo("B"));
foos.add(new Foo("C"));
params.put("foos", foos);
ST st = new ST("Hello, $data.(\"foos\") : {foo | $foo.s;separator=\", \"$}$", '$', '$');
st.add("data", params);
template = st.render();
System.out.println(template);
</code>```

But the output is just:

```<code>Hello, ABC
</code>```

How do I properly iterate over that list and print it out with comma separation?

答:
Your separator separates the elemnets of foo.s, not those of foo. Try

```<code>ST st = new ST("Hello, $data.(\"foos\") : {foo | $foo.s$};separator=\", \"$", '$', '$');
</code>```

Body:
I have a class like so:

public class Foo {
    private String s;
}

And I have a list of said objects. I want to be able to iterate over this list and print out the string property s. I have the following code to render the string template:

Map<String, Object> params = new HashMap<>();
List<Foo> foos = new ArrayList<>();
foos.add(new Foo("A"));
foos.add(new Foo("B"));
foos.add(new Foo("C"));
params.put("foos", foos);
ST st = new ST("Hello, $data.(\"foos\") : {foo | $foo.s;separator=\", \"$}$", '$', '$');
st.add("data", params);
template = st.render();
System.out.println(template);

But the output is just:

Hello, ABC

How do I properly iterate over that list and print it out with comma separation?

Body:
Your separator separates the elemnets of foo.s, not those of foo. Try

ST st = new ST("Hello, $data.(\"foos\") : {foo | $foo.s$};separator=\", \"$", '$', '$');


问:
What is the advantage of using Continuous Archiving and Point-In-Time Recovery over a SQL Dump?
It seems like Continuous Archiving and Point-In-Time Recovery for PostgreSQL is much more complicated to backup and restore.  What would the advantages be over using the SQL dump method?  My environment is Windows Server 2008.</p>

答: If you're OK with a snapshot of the database you get every week or two, and don't mind losing any activity since the last pg_dump if your server dies, than pg_dump is a reasonable solution.  If you want to get to where the most data you'll lose in a crash is minutes or possibly seconds of information, you have to use something real time like PITR log-shipping.  Not only does this keep your backup more up to date, you can also bring that backup server up much, much faster to replace the master if it fails.  Reloading your database from a pg_dump file can take days if it's big, whereas you can configure PostgreSQL using Warm Standby to make switching to the backup almost instant.</p>


问:
Incorrect value print out MySQL+PHP
My problem is that when I want to print out a column with mysqli_fetch_assoc in PHP, I have to use the same column name, but the tables are different, and it's printing out a wrong tables column.

lekerdezesek2.php

```<code>$lekerdezes2 = lekerdezes2_leker();

while( $egySor = mysqli_fetch_assoc($lekerdezes2) ) {
    echo '<tr>';
    echo '<td>'. $egySor["nev"] .'</td>';
    echo '<td>'. $egySor["szoveg"] .'</td>';
    echo '<td>'. $egySor["elerheto_maxpontszam"] .'</td>';
    echo '<td>'. $egySor["szoveg"] .'</td>';
    echo '</tr>';
}

mysqli_free_result($lekerdezes2);
</code>```

db_functions.php

```<code>function lekerdezes2_leker() {
if ( !($conn = moodle_csatlakozas()) ) {
    return false;
}

$result = mysqli_query( $conn,"SELECT teszt.nev, kerdesek.szoveg, kerdesek.elerheto_maxpontszam, valaszok.szoveg FROM teszt,kerdesek,valaszok WHERE teszt.ID=kerdesek.tesztID AND kerdesek.ID=valaszok.kerdesekID AND valaszok.helyes=1");

mysqli_close($conn);
return $result;
}
</code>```

The final result is the "valaszok.szoveg" value is the same as "kerdesek.szoveg" after print, but it should not.

Final result looks like this:
image link

But it's need be to looks like this:
image link

答:
It looks like the column name szoveg is ambiguous.

You can add an alias name to the column in the select clause and use it.

Syntax

```<code>SELECT
 [column_1 | expression] AS descriptive_name
FROM table_name;
</code>```

Example

```<code>SELECT
 kerdesek.szoveg AS kerdesek_szoveg
FROM kerdesek;
</code>```

Modified Query

```<code>SELECT
    teszt.nev,
    kerdesek.szoveg AS kerdesek_szoveg,
    kerdesek.elerheto_maxpontszam,
    valaszok.szoveg
FROM
    teszt,
    kerdesek,
    valaszok
WHERE
    teszt.ID = kerdesek.tesztID
    AND kerdesek.ID = valaszok.kerdesekID
    AND valaszok.helyes = 1
</code>```

Modified Code

lekerdezesek2.php

```<code>$lekerdezes2 = lekerdezes2_leker();

while( $egySor = mysqli_fetch_assoc($lekerdezes2) ) {
    echo '<tr>';
    echo '<td>'. $egySor["nev"] .'</td>';
    echo '<td>'. $egySor["kerdesek_szoveg"] .'</td>';
    echo '<td>'. $egySor["elerheto_maxpontszam"] .'</td>';
    echo '<td>'. $egySor["szoveg"] .'</td>';
    echo '</tr>';
}

mysqli_free_result($lekerdezes2);
</code>```

db_functions.php

```<code>function lekerdezes2_leker() {
    if ( !($conn = moodle_csatlakozas()) ) {
        return false;
    }

    $result = mysqli_query( $conn,"SELECT teszt.nev, kerdesek.szoveg AS kerdesek_szoveg, kerdesek.elerheto_maxpontszam, valaszok.szoveg FROM teszt,kerdesek,valaszok WHERE teszt.ID=kerdesek.tesztID AND kerdesek.ID=valaszok.kerdesekID AND valaszok.helyes=1");

    mysqli_close($conn);
    return $result;
}
</code>```

Title: Incorrect value print out MySQL+PHP

Body:
My problem is that when I want to print out a column with mysqli_fetch_assoc in PHP, I have to use the same column name, but the tables are different, and it's printing out a wrong tables column.

lekerdezesek2.php

$lekerdezes2 = lekerdezes2_leker();

while( $egySor = mysqli_fetch_assoc($lekerdezes2) ) {
    echo '
';
    echo ''. $egySor["nev"] .'	';
    echo ''. $egySor["szoveg"] .'	';
    echo ''. $egySor["elerheto_maxpontszam"] .'	';
    echo ''. $egySor["szoveg"] .'	';
    echo '
';
}

mysqli_free_result($lekerdezes2);

db_functions.php

function lekerdezes2_leker() {
if ( !($conn = moodle_csatlakozas()) ) {
    return false;
}

$result = mysqli_query( $conn,"SELECT teszt.nev, kerdesek.szoveg, kerdesek.elerheto_maxpontszam, valaszok.szoveg FROM teszt,kerdesek,valaszok WHERE teszt.ID=kerdesek.tesztID AND kerdesek.ID=valaszok.kerdesekID AND valaszok.helyes=1");

mysqli_close($conn);
return $result;
}

The final result is the "valaszok.szoveg" value is the same as "kerdesek.szoveg" after print, but it should not.

Final result looks like this:
image link

But it's need be to looks like this:
image link

Body:
It looks like the column name szoveg is ambiguous.

You can add an alias name to the column in the select clause and use it.

Syntax

SELECT
 [column_1 | expression] AS descriptive_name
FROM table_name;

Example

SELECT
 kerdesek.szoveg AS kerdesek_szoveg
FROM kerdesek;

Modified Query

SELECT
    teszt.nev,
    kerdesek.szoveg AS kerdesek_szoveg,
    kerdesek.elerheto_maxpontszam,
    valaszok.szoveg
FROM
    teszt,
    kerdesek,
    valaszok
WHERE
    teszt.ID = kerdesek.tesztID
    AND kerdesek.ID = valaszok.kerdesekID
    AND valaszok.helyes = 1

Modified Code

lekerdezesek2.php

$lekerdezes2 = lekerdezes2_leker();

while( $egySor = mysqli_fetch_assoc($lekerdezes2) ) {
    echo '<tr>';
    echo '<td>'. $egySor["nev"] .'</td>';
    echo '<td>'. $egySor["kerdesek_szoveg"] .'</td>';
    echo '<td>'. $egySor["elerheto_maxpontszam"] .'</td>';
    echo '<td>'. $egySor["szoveg"] .'</td>';
    echo '</tr>';
}

mysqli_free_result($lekerdezes2);

db_functions.php

function lekerdezes2_leker() {
    if ( !($conn = moodle_csatlakozas()) ) {
        return false;
    }

    $result = mysqli_query( $conn,"SELECT teszt.nev, kerdesek.szoveg AS kerdesek_szoveg, kerdesek.elerheto_maxpontszam, valaszok.szoveg FROM teszt,kerdesek,valaszok WHERE teszt.ID=kerdesek.tesztID AND kerdesek.ID=valaszok.kerdesekID AND valaszok.helyes=1");

    mysqli_close($conn);
    return $result;
}


问:
Framelayout doesn't persist in recyclerview cell
In my layout, I have a recyclerview containing cells that are cardviews that, in theory, contains a framelayout. Ideally, the framelayout within the cardview can be populated with a fragment that is dependent on Object used to populate the view. However, when I have multiple cells, only one cell contains the framelayout. This phenomenon shows on the screen as so:

the code used to intialize the viewholder for the recyclerview cell is shown below:

```<code>public class JokesViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView userName;
    TextView likeCounterTextView;
    TextView commentCounterTextView;
    TextView timeStampTextView;
    CircleImageView profileImg;
    ImageButton likeButton;
    ImageButton options;
    ImageButton comments;
    FrameLayout frameLayout;

    public JokesViewHolder(View view) {
        super(view);
        timeStampTextView = view.findViewById(R.id.time_date_textView);
        frameLayout = view.findViewById(R.id.post_content);
        profileImg = view.findViewById(R.id.profile_imageview);
        userName = view.findViewById(R.id.username_textView);

        options = view.findViewById(R.id.options_imageButton);
        options.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //todo open custom dialog
            }
        });

        likeButton = view.findViewById(R.id.favorite_imageButton);
        likeCounterTextView = view.findViewById(R.id.likes_counter_textView);

        comments = view.findViewById(R.id.comment_imageButton);
        commentCounterTextView = view.findViewById(R.id.comment_counter_textView);

        view.setOnClickListener(this);
        view.setTag(this);
    }

    @Override
    public void onClick(View view) {
        //todo open fragment to show all post data plus comments
    }
}

 @Override
public void onBindViewHolder(final JokesViewHolder holder, int position) {
    final Joke joke = jokes.get(position);
    holder.userName.setText(joke.getUser());

    Constants.DATABASE.child("users/" + joke.getUID() + "/urlString")
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    String url = dataSnapshot.getValue(String.class);
                    Glide.with(context).load(url).into(holder.profileImg);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
    Constants.DATABASE.child("userpostslikescomments/" + joke.getUID() + "/" + joke.getPushId() + "/likes/num")
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    Integer num = dataSnapshot.getValue(Integer.class);
                    holder.likeCounterTextView.setText(Integer.toString(0));
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
    Constants.DATABASE.child("userpostslikescomments/" + joke.getUID() + "/" + joke.getPushId() + "/comments/num")
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    Integer num = dataSnapshot.getValue(Integer.class);
                    holder.commentCounterTextView.setText(Integer.toString(0));
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
    Constants.DATABASE.child("userpostslikescomments/" + joke.getUID() + "/" + joke.getPushId() + "/likes/list/" + Constants.UID)
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (dataSnapshot.exists()) {
                        holder.likeButton.setImageResource(R.drawable.ic_favorite_black_24dp);
                    } else {
                        holder.likeButton.setImageResource(R.drawable.ic_favorite_border_black_24dp);
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {}
            });

    if (joke.getMediaURL().equals("")) {
        Bundle bundle = new Bundle();
        bundle.putString("jokeTitle", joke.getJokeTitle());
        bundle.putString("jokeBody", joke.getJokeBody());
        bundle.putString("tagline", joke.getTagline());
        //may not work
        TextPostContent tpc = new TextPostContent();
        tpc.setArguments(bundle);
        ((android.support.v4.app.FragmentActivity) context).getSupportFragmentManager()
                .beginTransaction().add(holder.frameLayout.getId(), tpc).commit();
    } else if (joke.getMediaURL().contains(".png")) {//may need to take into account more file types
        Bundle bundle = new Bundle();
        bundle.putString("media_url", joke.getMediaURL());
        bundle.putString("tagline", joke.getTagline());
        ImagePostContent ipc = new ImagePostContent();
        ipc.setArguments(bundle);
        ((android.support.v4.app.FragmentActivity) context).getSupportFragmentManager()
                .beginTransaction().add(holder.frameLayout.getId(), ipc).commit();
    } else {
        Bundle bundle = new Bundle();
        bundle.putString("media_url", joke.getMediaURL());
        bundle.putString("tagline", joke.getTagline());
        VideoPostContent vpc = new VideoPostContent();
        vpc.setArguments(bundle);
        ((android.support.v4.app.FragmentActivity) context).getSupportFragmentManager()
                .beginTransaction().add(holder.frameLayout.getId(), vpc).commit();
    }

    holder.timeStampTextView.setText(joke.getTimeStamp());

    holder.likeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final String path = "userpostslikescomments/" + joke.getUID() + "/" + joke.getPushId() + "/likes/list/" + Constants.UID;
            Constants.DATABASE.child(path)
                    .addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            if (dataSnapshot.exists()) {
                                Constants.DATABASE.child(path).removeValue();
                                holder.likeButton.setImageResource(R.drawable.ic_favorite_border_black_24dp);
                            } else {
                                Constants.DATABASE.child(path).setValue(true);
                                holder.likeButton.setImageResource(R.drawable.ic_favorite_black_24dp);
                            }
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {}
                    });
        }
    });

    holder.comments.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //todo start animation between fragments
            //todo show recyclerview of comments
        }
    });
}
</code>```

My gut tells me that instead of doing a fragment transaction I should add views (like textviews and imageviews) programmtically. But I was wondering if there was a way to populate the framelayout of the cardviews using the fragment classes I already created?

答: In order to ensure that each cell within the recyclerview has a framelayout that is populated with either text, an image, or a video (versus having only one cell having a framelayout populated with information that should be split into multiple cells) you should call frameLayout.setId(View.generateViewId()) after finding a reference to the framelayout via findViewById(int). Fast scrolling leads to a fatal error though. Another solution is to create mulitple view holders for the different types of cells.

Body:
In my layout, I have a recyclerview containing cells that are cardviews that, in theory, contains a framelayout. Ideally, the framelayout within the cardview can be populated with a fragment that is dependent on Object used to populate the view. However, when I have multiple cells, only one cell contains the framelayout. This phenomenon shows on the screen as so:

the code used to intialize the viewholder for the recyclerview cell is shown below:

public class JokesViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView userName;
    TextView likeCounterTextView;
    TextView commentCounterTextView;
    TextView timeStampTextView;
    CircleImageView profileImg;
    ImageButton likeButton;
    ImageButton options;
    ImageButton comments;
    FrameLayout frameLayout;

    public JokesViewHolder(View view) {
        super(view);
        timeStampTextView = view.findViewById(R.id.time_date_textView);
        frameLayout = view.findViewById(R.id.post_content);
        profileImg = view.findViewById(R.id.profile_imageview);
        userName = view.findViewById(R.id.username_textView);

        options = view.findViewById(R.id.options_imageButton);
        options.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //todo open custom dialog
            }
        });

        likeButton = view.findViewById(R.id.favorite_imageButton);
        likeCounterTextView = view.findViewById(R.id.likes_counter_textView);

        comments = view.findViewById(R.id.comment_imageButton);
        commentCounterTextView = view.findViewById(R.id.comment_counter_textView);

        view.setOnClickListener(this);
        view.setTag(this);
    }

    @Override
    public void onClick(View view) {
        //todo open fragment to show all post data plus comments
    }
}

 @Override
public void onBindViewHolder(final JokesViewHolder holder, int position) {
    final Joke joke = jokes.get(position);
    holder.userName.setText(joke.getUser());

    Constants.DATABASE.child("users/" + joke.getUID() + "/urlString")
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    String url = dataSnapshot.getValue(String.class);
                    Glide.with(context).load(url).into(holder.profileImg);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
    Constants.DATABASE.child("userpostslikescomments/" + joke.getUID() + "/" + joke.getPushId() + "/likes/num")
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    Integer num = dataSnapshot.getValue(Integer.class);
                    holder.likeCounterTextView.setText(Integer.toString(0));
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
    Constants.DATABASE.child("userpostslikescomments/" + joke.getUID() + "/" + joke.getPushId() + "/comments/num")
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    Integer num = dataSnapshot.getValue(Integer.class);
                    holder.commentCounterTextView.setText(Integer.toString(0));
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
    Constants.DATABASE.child("userpostslikescomments/" + joke.getUID() + "/" + joke.getPushId() + "/likes/list/" + Constants.UID)
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (dataSnapshot.exists()) {
                        holder.likeButton.setImageResource(R.drawable.ic_favorite_black_24dp);
                    } else {
                        holder.likeButton.setImageResource(R.drawable.ic_favorite_border_black_24dp);
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {}
            });

    if (joke.getMediaURL().equals("")) {
        Bundle bundle = new Bundle();
        bundle.putString("jokeTitle", joke.getJokeTitle());
        bundle.putString("jokeBody", joke.getJokeBody());
        bundle.putString("tagline", joke.getTagline());
        //may not work
        TextPostContent tpc = new TextPostContent();
        tpc.setArguments(bundle);
        ((android.support.v4.app.FragmentActivity) context).getSupportFragmentManager()
                .beginTransaction().add(holder.frameLayout.getId(), tpc).commit();
    } else if (joke.getMediaURL().contains(".png")) {//may need to take into account more file types
        Bundle bundle = new Bundle();
        bundle.putString("media_url", joke.getMediaURL());
        bundle.putString("tagline", joke.getTagline());
        ImagePostContent ipc = new ImagePostContent();
        ipc.setArguments(bundle);
        ((android.support.v4.app.FragmentActivity) context).getSupportFragmentManager()
                .beginTransaction().add(holder.frameLayout.getId(), ipc).commit();
    } else {
        Bundle bundle = new Bundle();
        bundle.putString("media_url", joke.getMediaURL());
        bundle.putString("tagline", joke.getTagline());
        VideoPostContent vpc = new VideoPostContent();
        vpc.setArguments(bundle);
        ((android.support.v4.app.FragmentActivity) context).getSupportFragmentManager()
                .beginTransaction().add(holder.frameLayout.getId(), vpc).commit();
    }

    holder.timeStampTextView.setText(joke.getTimeStamp());

    holder.likeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final String path = "userpostslikescomments/" + joke.getUID() + "/" + joke.getPushId() + "/likes/list/" + Constants.UID;
            Constants.DATABASE.child(path)
                    .addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            if (dataSnapshot.exists()) {
                                Constants.DATABASE.child(path).removeValue();
                                holder.likeButton.setImageResource(R.drawable.ic_favorite_border_black_24dp);
                            } else {
                                Constants.DATABASE.child(path).setValue(true);
                                holder.likeButton.setImageResource(R.drawable.ic_favorite_black_24dp);
                            }
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {}
                    });
        }
    });

    holder.comments.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //todo start animation between fragments
            //todo show recyclerview of comments
        }
    });
}

My gut tells me that instead of doing a fragment transaction I should add views (like textviews and imageviews) programmtically. But I was wondering if there was a way to populate the framelayout of the cardviews using the fragment classes I already created?


问:
NodeJS multiple topic listener for Firebase

I am trying to register listener for multiple nodes in the Firebase, currently, my mobile app is only listening to one node, and it is working fine, But i wanted it to listen to other topic/node too, how to achieve that?</p>

```<code>const functions = require('firebase-functions');

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
//  response.send("Hello from Firebase!");
// });

// imports firebase-functions module
// const functions = require('firebase-functions');
// imports firebase-admin module
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

/* Listens for new messages added to /messages/:pushId and sends a
notification to subscribed users */
exports.pushNotification =
functions.database.ref('/user_appointments/{userId}').onWrite( event => {
console.log('Push notification event triggered');
/* Grab the current value of what was written to the Realtime Database */
    var valueObject = event.data.key;
    if (!event.data.exists()) {return}
    console.log(valueObject);

/* Create a notification and data payload. They contain the notification
information, and message to be sent respectively */
    const payload = {
        data: {
            title: String(valueObject),
            message: String(valueObject)
         }
    };
 /* Create an options object that contains the time to live for the
notification and the priority. */
    const options = {
        priority: "high",
        timeToLive: 60 * 60 * 24 //24 hours
        };
      return admin.messaging().sendToTopic("user_appointments", payload,
options);
     });
</code>```

答:
If the nodes have a similar structure, but are at a different location, you should separate the actual code into a helper function:

```<code>function sendNotification(event => {
console.log('Push notification event triggered');
/* Grab the current value of what was written to the Realtime Database */
    var valueObject = event.data.key;
    if (!event.data.exists()) {return}
    console.log(valueObject);

/* Create a notification and data payload. They contain the notification
information, and message to be sent respectively */
    const payload = {
        data: {
            title: String(valueObject),
            message: String(valueObject)
         }
    };
 /* Create an options object that contains the time to live for the
notification and the priority. */
    const options = {
        priority: "high",
        timeToLive: 60 * 60 * 24 //24 hours
        };
      return admin.messaging().sendToTopic("user_appointments", payload,
options);
     });
</code>```

You then tie this helper function to the two location in the database:

```<code>exports.pushNotification =
functions.database.ref('/user_appointments/{userId}').onWrite( event => {
  sendNotification(event);
});
exports.pushNotification2 =
functions.database.ref('/doctor_appointments/{doctorId}').onWrite( event => {
  sendNotification(event);
});
</code>```

Body:
I am trying to register listener for multiple nodes in the Firebase, currently, my mobile app is only listening to one node, and it is working fine, But i wanted it to listen to other topic/node too, how to achieve that?

const functions = require('firebase-functions');

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
//  response.send("Hello from Firebase!");
// });

// imports firebase-functions module
// const functions = require('firebase-functions');
// imports firebase-admin module
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

/* Listens for new messages added to /messages/:pushId and sends a
notification to subscribed users */
exports.pushNotification =
functions.database.ref('/user_appointments/{userId}').onWrite( event => {
console.log('Push notification event triggered');
/* Grab the current value of what was written to the Realtime Database */
    var valueObject = event.data.key;
    if (!event.data.exists()) {return}
    console.log(valueObject);

/* Create a notification and data payload. They contain the notification
information, and message to be sent respectively */
    const payload = {
        data: {
            title: String(valueObject),
            message: String(valueObject)
         }
    };
 /* Create an options object that contains the time to live for the
notification and the priority. */
    const options = {
        priority: "high",
        timeToLive: 60 * 60 * 24 //24 hours
        };
      return admin.messaging().sendToTopic("user_appointments", payload,
options);
     });

Body:
If the nodes have a similar structure, but are at a different location, you should separate the actual code into a helper function:

function sendNotification(event => {
console.log('Push notification event triggered');
/* Grab the current value of what was written to the Realtime Database */
    var valueObject = event.data.key;
    if (!event.data.exists()) {return}
    console.log(valueObject);

/* Create a notification and data payload. They contain the notification
information, and message to be sent respectively */
    const payload = {
        data: {
            title: String(valueObject),
            message: String(valueObject)
         }
    };
 /* Create an options object that contains the time to live for the
notification and the priority. */
    const options = {
        priority: "high",
        timeToLive: 60 * 60 * 24 //24 hours
        };
      return admin.messaging().sendToTopic("user_appointments", payload,
options);
     });

You then tie this helper function to the two location in the database:

exports.pushNotification =
functions.database.ref('/user_appointments/{userId}').onWrite( event => {
  sendNotification(event);
});
exports.pushNotification2 =
functions.database.ref('/doctor_appointments/{doctorId}').onWrite( event => {
  sendNotification(event);
});


问:
User registration form without Entity Framework
```<code>[HttpPost]
public ActionResult Create(UserModel userModel)
{

    using (SqlConnection sqlCon= new SqlConnection(connectionString))
    {
        sqlCon.Open();

        String query = "INSERT INTO User VALUES(@UserName, @UserPassword, @UserAddress)";

        SqlCommand sqlCmd = new SqlCommand(query,sqlCon);

        sqlCmd.Parameters.AddWithValue("@UserName",userModel.username);
        sqlCmd.Parameters.AddWithValue("@UserPassword", userModel.userpassword);
        sqlCmd.Parameters.AddWithValue("@UserAddress", userModel.useraddress);

        sqlCmd.ExecuteNonQuery();
    }

    return RedirectToAction("Index");
}
</code>```

I'm learning C#. I tried to code CURD operations. In this code there is is a Open() method. I want to know why it used and explain line by line what is code  flow.

答:
In your code Open() method is use for database connection open. You can refer https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open(v=vs.110).aspx Microsoft document.

```<code> sqlCon.Open();
</code>```

To open database connection

```<code>    String query = "INSERT INTO User VALUES(@UserName,@UserPassword,@UserAddress)";
</code>```

Database query

```<code>    SqlCommand sqlCmd = new SqlCommand(query,sqlCon);
</code>```

To create database command

```<code>    sqlCmd.Parameters.AddWithValue("@UserName",userModel.username);
    sqlCmd.Parameters.AddWithValue("@UserPassword", userModel.userpassword);
    sqlCmd.Parameters.AddWithValue("@UserAddress", userModel.useraddress);
</code>```

These are the parameters to pass with command

```<code>    sqlCmd.ExecuteNonQuery();
</code>```

This will execute your command to open database

Body:
[HttpPost]
public ActionResult Create(UserModel userModel)
{

    using (SqlConnection sqlCon= new SqlConnection(connectionString))
    {
        sqlCon.Open();

        String query = "INSERT INTO User VALUES(@UserName, @UserPassword, @UserAddress)";

        SqlCommand sqlCmd = new SqlCommand(query,sqlCon);

        sqlCmd.Parameters.AddWithValue("@UserName",userModel.username);
        sqlCmd.Parameters.AddWithValue("@UserPassword", userModel.userpassword);
        sqlCmd.Parameters.AddWithValue("@UserAddress", userModel.useraddress);

        sqlCmd.ExecuteNonQuery();
    }

    return RedirectToAction("Index");
}

I'm learning C#. I tried to code CURD operations. In this code there is is a Open() method. I want to know why it used and explain line by line what is code  flow.

Body:
In your code Open() method is use for database connection open. You can refer https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open(v=vs.110).aspx Microsoft document.

 sqlCon.Open();

To open database connection

    String query = "INSERT INTO User VALUES(@UserName,@UserPassword,@UserAddress)";

Database query

    SqlCommand sqlCmd = new SqlCommand(query,sqlCon);

To create database command

    sqlCmd.Parameters.AddWithValue("@UserName",userModel.username);
    sqlCmd.Parameters.AddWithValue("@UserPassword", userModel.userpassword);
    sqlCmd.Parameters.AddWithValue("@UserAddress", userModel.useraddress);

These are the parameters to pass with command

    sqlCmd.ExecuteNonQuery();

This will execute your command to open database


问:
Best practice for px-to-rem mixins
I am creating some mixins to make me easier to convert px to rem values in margin which has 4 parameters top, right, bottom and left. In my code below, I make 16 mixins which is checking whether if the parameter is pixel or not.

```<code>// TODO --> margin

// T T T T
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right)), (ispixel(@bottom)), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem unit(@right)/@base-font*1rem unit(@bottom)/@base-font*1rem unit(@left)/@base-font*1rem;
}

// T F T T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right) = false), (ispixel(@bottom)), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem @right unit(@bottom)/@base-font*1rem unit(@left)/@base-font*1rem;
}

// T T F T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right)), (ispixel(@bottom) = false), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem unit(@right)/@base-font*1rem @bottom unit(@left)/@base-font*1rem;
}

// T F F T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right) = false), (ispixel(@bottom) = false), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem @right @bottom unit(@left)/@base-font*1rem;
}

// T T T F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right)), (ispixel(@bottom)), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem unit(@right)/@base-font*1rem unit(@bottom)/@base-font*1rem @left;
}

// T F T F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right) = false), (ispixel(@bottom)), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem @right unit(@bottom)/@base-font*1rem @left;
}

// T T F F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right)), (ispixel(@bottom) = false), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem unit(@right)/@base-font*1rem @bottom @left;
}

// T F F F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right) = false), (ispixel(@bottom) = false), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem @right @bottom @left;
}

// F T T T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right)), (ispixel(@bottom)), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: @top unit(@right)/@base-font*1rem unit(@bottom)/@base-font*1rem unit(@left)/@base-font*1rem;
}

// F F T T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right) = false), (ispixel(@bottom)), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: @top @right unit(@bottom)/@base-font*1rem unit(@left)/@base-font*1rem;
}

// F T F T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right)), (ispixel(@bottom) = false), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: @top unit(@right)/@base-font*1rem @bottom unit(@left)/@base-font*1rem;
}

// F F F T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right) = false), (ispixel(@bottom) = false), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: @top @right @bottom unit(@left)/@base-font*1rem;
}

// F T T F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right)), (ispixel(@bottom)), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: @top unit(@right)/@base-font*1rem unit(@bottom)/@base-font*1rem @left;
}

// F F T F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right) = false), (ispixel(@bottom)), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: @top @right unit(@bottom)/@base-font*1rem @left;
}

// F T F F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right)), (ispixel(@bottom) = false), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: @top unit(@right)/@base-font*1rem @bottom @left;
}

// F F F F
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right) = false), (ispixel(@bottom) = false), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
}
</code>```

I have a problem when passing auto or not-a-number type of variables but it works with number and number with unit like px, rem, em, etc.

and when I see in developer mode it looks like this

Is there a better way to make my code clearer and not make a much junk in compiled css?

UPDATE

I forgot that I used , instead of and

Thank you, and sorry for my English

答: I forgot that I used , instead of and

Title: Best practice for px-to-rem mixins

Body:
I am creating some mixins to make me easier to convert px to rem values in margin which has 4 parameters top, right, bottom and left. In my code below, I make 16 mixins which is checking whether if the parameter is pixel or not.

// TODO --> margin

// T T T T
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right)), (ispixel(@bottom)), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem unit(@right)/@base-font*1rem unit(@bottom)/@base-font*1rem unit(@left)/@base-font*1rem;
}

// T F T T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right) = false), (ispixel(@bottom)), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem @right unit(@bottom)/@base-font*1rem unit(@left)/@base-font*1rem;
}

// T T F T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right)), (ispixel(@bottom) = false), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem unit(@right)/@base-font*1rem @bottom unit(@left)/@base-font*1rem;
}

// T F F T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right) = false), (ispixel(@bottom) = false), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem @right @bottom unit(@left)/@base-font*1rem;
}

// T T T F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right)), (ispixel(@bottom)), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem unit(@right)/@base-font*1rem unit(@bottom)/@base-font*1rem @left;
}

// T F T F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right) = false), (ispixel(@bottom)), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem @right unit(@bottom)/@base-font*1rem @left;
}

// T T F F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right)), (ispixel(@bottom) = false), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem unit(@right)/@base-font*1rem @bottom @left;
}

// T F F F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top)), (ispixel(@right) = false), (ispixel(@bottom) = false), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: unit(@top)/@base-font*1rem @right @bottom @left;
}

// F T T T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right)), (ispixel(@bottom)), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: @top unit(@right)/@base-font*1rem unit(@bottom)/@base-font*1rem unit(@left)/@base-font*1rem;
}

// F F T T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right) = false), (ispixel(@bottom)), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: @top @right unit(@bottom)/@base-font*1rem unit(@left)/@base-font*1rem;
}

// F T F T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right)), (ispixel(@bottom) = false), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: @top unit(@right)/@base-font*1rem @bottom unit(@left)/@base-font*1rem;
}

// F F F T
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right) = false), (ispixel(@bottom) = false), (ispixel(@left)){
  margin: @top @right @bottom @left;
  margin: @top @right @bottom unit(@left)/@base-font*1rem;
}

// F T T F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right)), (ispixel(@bottom)), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: @top unit(@right)/@base-font*1rem unit(@bottom)/@base-font*1rem @left;
}

// F F T F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right) = false), (ispixel(@bottom)), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: @top @right unit(@bottom)/@base-font*1rem @left;
}

// F T F F
//noinspection CssOverwrittenProperties
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right)), (ispixel(@bottom) = false), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
  margin: @top unit(@right)/@base-font*1rem @bottom @left;
}

// F F F F
.margin(@top,@right,@bottom,@left) when (ispixel(@top) = false), (ispixel(@right) = false), (ispixel(@bottom) = false), (ispixel(@left) = false){
  margin: @top @right @bottom @left;
}

I have a problem when passing auto or not-a-number type of variables but it works with number and number with unit like px, rem, em, etc.

and when I see in developer mode it looks like this

Is there a better way to make my code clearer and not make a much junk in compiled css?

UPDATE

I forgot that I used , instead of and

Thank you, and sorry for my English

Body: I forgot that I used , instead of and


问:
jQuery: Result of script gets deleted after execution - removeData() running on the background?
I have a modal window used to update or add a new object Store.

This modal has a cascading dropdownlist for two properties: Department and District.

How should it work:

We first identify if we are in the situation of creating or updating a Store.

In case is a new Store the modal opens and using jQuery we present a default value for the District dropdownlists (since no Department has been chosen yet).

```<code>    <script type="text/javascript">

        var wasclicked = 0;
        var $this = this;

        $(document).ready(function () {

            document.getElementById("modalbutton").onclick = function () {
                //is AddNew Store button is hitted, this var = 1
                wasclicked = 1;
            };

            $('#modal-action-store').on('hidden.bs.modal', function () {
                //global.wasclicked = 0;
                wasclicked = 0;
                $(this).removeData('bs.modal');
            });

            $('#modal-action-store').on('shown.bs.modal', function (e) {
                console.log($('#DistrictID').length);
                //if wasclicked equals 1 that means we are in the AddNew Store scenario.
                if (wasclicked == 1) {
                    //a default value is sent to District dropdownlist
                    var items = "<option value='0'>-- Seleccione Distrito --</option>";
                    $('#DistrictID').html(items);
                };

            });
        });

</script>
</code>```

However, at this moment, after the default value is added, after a fraction of a second, the value gets deleted.

What I've tried

I've noticed that when I remove this line of code:

```<code>$(this).removeData('bs.modal');
</code>```

From the previous script, it works ok, but I need that code in order to clear the data from the modal if I need to use the modal to edit another Store.

Plus, when I debug the project the debugger did not stop at the breakpoint of that line, so I'm not sure why it's somehow executing in the background? Is it because it's wrapped inside the function document.ready()?

I've been struggling with this for days. I thank for any helpful comment.

Aditional info:

Online version of the project:

There is an online version for this for debugging:

http://plataformafantasypark.azurewebsites.net/

user: adelgado password: $Adelgado33

Under the menu 'Tiendas' -> 'Registro'

Button that calls the modal:

```<code><div class="btn-group" id="modalbutton">
    <a id="createEditStoreModal" data-toggle="modal" asp-action="Create"
         data-target="#modal-action-store" class="btn btn-primary">
            <i class="glyphicon glyphicon-plus"></i>  NEW STORE
        </a>
</div>
</code>```

The Modal:

```<code>@model Application.Models.ApplicationviewModels.StoreIndexData
@using Application.Models

<form asp-action="Create" role="form">
        @await Html.PartialAsync("_ModalHeader", new ModalHeader
    { Heading = String.Format("Actualización de Modelo: Tiendas") })

        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="modal-body form-horizontal">
            <div class="form-group">
                <label asp-for="DepartmentID" class="col-md-2 control-label"></label>
                <div class="col-md-10">
                    <select asp-for="DepartmentID" class="form-control"
                            asp-items="@(new SelectList(@ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-2 control-label">Distrito</label>
                <div class="col-md-10">
                    <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
                            asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
                </div>
            </div>
            {... more elements}
       </div>
</form>
</code>```

答:
The idea is to take manual control of the loading and inserting of the remote content received from /Stores/Create.  I'm not set up to test this but give it a try.

You will need to get rid of/comment out the existing .on('showN.bs.modal') handler, and you might have to get rid of the href on the  tag that invokes the modal, not sure.

```<code>$('#modal-action-store').on('show.bs.modal', function (e) {
    if (wasclicked == 1) {
        // load the form, once it's done loading modify it as needed
        $('#modal-action-store').find('.modal-content').load('/Stores/Create', function () {
            $('#DistrictID').html('<option value='0'>-- Seleccione Distrito --</option>');
        });
    }
});
</code>```

Body:
I have a modal window used to update or add a new object Store.

This modal has a cascading dropdownlist for two properties: Department and District.

How should it work:

We first identify if we are in the situation of creating or updating a Store.

In case is a new Store the modal opens and using jQuery we present a default value for the District dropdownlists (since no Department has been chosen yet).

However, at this moment, after the default value is added, after a fraction of a second, the value gets deleted.

What I've tried

I've noticed that when I remove this line of code:

$(this).removeData('bs.modal');

From the previous script, it works ok, but I need that code in order to clear the data from the modal if I need to use the modal to edit another Store.

Plus, when I debug the project the debugger did not stop at the breakpoint of that line, so I'm not sure why it's somehow executing in the background? Is it because it's wrapped inside the function document.ready()?

I've been struggling with this for days. I thank for any helpful comment.

Aditional info:

Online version of the project:

There is an online version for this for debugging:

http://plataformafantasypark.azurewebsites.net/

user: adelgado password: $Adelgado33

Under the menu 'Tiendas' -> 'Registro'

Button that calls the modal:

              NEW STORE

The Modal:

@model Application.Models.ApplicationviewModels.StoreIndexData
@using Application.Models

<form asp-action="Create" role="form">
        @await Html.PartialAsync("_ModalHeader", new ModalHeader
    { Heading = String.Format("Actualización de Modelo: Tiendas") })

                    <select asp-for="DepartmentID" class="form-control"
                            asp-items="@(new SelectList(@ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>

                Distrito

                    <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
                            asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>

            {... more elements}

</form>

Body:
The idea is to take manual control of the loading and inserting of the remote content received from /Stores/Create.  I'm not set up to test this but give it a try.

You will need to get rid of/comment out the existing .on('showN.bs.modal') handler, and you might have to get rid of the href on the <a> tag that invokes the modal, not sure.

$('#modal-action-store').on('show.bs.modal', function (e) {
    if (wasclicked == 1) {
        // load the form, once it's done loading modify it as needed
        $('#modal-action-store').find('.modal-content').load('/Stores/Create', function () {
            $('#DistrictID').html('<option value='0'>-- Seleccione Distrito --</option>');
        });
    }
});


问:
Php error in code while updating the data in sql
I get an error Undefined variable name, address, and id though I have defined it. I have used isset function but it is not working. Also, some HTML code appears in the name and address field.

```<code> <?php
$link=mysqli_connect("localhost","root","");
$select=mysqli_select_db($link,'first_db');

if(isset($_POST['update'])){
     $id=$_POST['id'];
     $query="SELECT * FROM list WHERE id='$id'";
     $run=mysqli_query($link,$query);
     $row=mysqli_fetch_array($run);
 }
if(isset($_POST['name'])&& isset($_POST['address'])){
    $name=$_POST['name'];
    $address=$_POST['address'];
    $id = $_POST['id'];
    $query="UPDATE list SET name='$name',address='$address' WHERE id='$id'";
    $result=mysqli_query($link,$query);
}
else{
    echo"The fields cannot be empty";
}

?>
</code>```

The HTML code is:

```<code>  <html>
    <head>
        <title>Edit Data</title>
    </head>

    <body>
        <a href="index.php">Home</a>
        <br/><br/>

        <form name="form1" method="post" action="update.php">
            <table border="0">
                <tr>
                    <td>Name</td>
                    <td><input type="text" name="name" value="<?php echo $name;?>"></td>
                </tr>
                <tr>
                    <td>address</td>
                    <td><input type="text" name="address" value="<?php echo $address;?>"></td>
                </tr>

                <tr>
                   <td><input type="hidden" name="id" value="<?php echo $_GET['id'];?>"></td>
                    <td><input type="submit" name="update" value="Update"></td>
                </tr>
            </table>
        </form>
    </body>
    </html>
</code>```

答:
```<code>if(isset($_POST['id']))
{
$name=$_POST['name'];
$address=$_POST['address'];
$id = $_POST['id'];
$query="UPDATE list SET name='".$name."',address='".$address."' WHERE id='".$id."'";
$result=mysqli_query($link,$query);
}
</code>```

Body:
I get an error Undefined variable name, address, and id though I have defined it. I have used isset function but it is not working. Also, some HTML code appears in the name and address field.

 <?php
$link=mysqli_connect("localhost","root","");
$select=mysqli_select_db($link,'first_db');

if(isset($_POST['update'])){
     $id=$_POST['id'];
     $query="SELECT * FROM list WHERE id='$id'";
     $run=mysqli_query($link,$query);
     $row=mysqli_fetch_array($run);
 }
if(isset($_POST['name'])&& isset($_POST['address'])){
    $name=$_POST['name'];
    $address=$_POST['address'];
    $id = $_POST['id'];
    $query="UPDATE list SET name='$name',address='$address' WHERE id='$id'";
    $result=mysqli_query($link,$query);
}
else{
    echo"The fields cannot be empty";
}

?>

The HTML code is:

        <title>Edit Data</title>

        Home

        <form name="form1" method="post" action="update.php">

                    Name
                    <input type="text" name="name" value="<?php echo $name;?>">

                    address
                    <input type="text" name="address" value="<?php echo $address;?>">

                   <input type="hidden" name="id" value="<?php echo $_GET['id'];?>">
                    <input type="submit" name="update" value="Update">

        </form>


答:
Your solution is as below</p>

```<code>if(isset($_GET['update'])){
         $id=$_POST['id'];//use this insted of $id=$_GET['update'] in your form name of id parameter is id
         $query="SELECT * FROM list WHERE id='$id'";
         $run=mysqli_query($link,$query);
         $row=mysqli_fetch_array($run);
     }

if(isset($_POST['name'])&& isset($_POST['address'])){
        $id=$_POST['id'];
        $name=$_POST['name'];
        $address=$_POST['address'];
        $query="UPDATE list SET name='$name',address='$address' WHERE id='$id'";
        $result=mysqli_query($link,$query);

    }
</code>```

Title: Php error in code while updating the data in sql

Body:
Your solution is as below

if(isset($_GET['update'])){
         $id=$_POST['id'];//use this insted of $id=$_GET['update'] in your form name of id parameter is id
         $query="SELECT * FROM list WHERE id='$id'";
         $run=mysqli_query($link,$query);
         $row=mysqli_fetch_array($run);
     }

if(isset($_POST['name'])&& isset($_POST['address'])){
        $id=$_POST['id'];
        $name=$_POST['name'];
        $address=$_POST['address'];
        $query="UPDATE list SET name='$name',address='$address' WHERE id='$id'";
        $result=mysqli_query($link,$query);

    }


问:
Gulp - Can gulp be used without node?
Is it possible to use
gulp without node?
The setup that requires - npm install -g gulp.
Is there a way to use gulp without using node?

答: No, you can't use gulp without node. Gulp is written in javascript and it runs with NodeJS. </p>

Title: Gulp - Can gulp be used without node?


问:
Remove array from json object stored in SQL Server column
If I have the following JSON stored in a column in SQL Server:

```<code>declare @json nvarchar(max) = '[{"id": "1", "name": "test1"},{"id": "2", "name": "test2"},{"id": "3", "name": "test4"}]'
</code>```

how can I remove an array where Id:=1 ?

I want to get the following result:

```<code>[{"id": "2", "name": "test2"},{"id": "3", "name": "test4"}]
</code>```

答:
try this:</p>

```<code>    declare @json nvarchar(max) = '[{"id": "1", "name": "test1"},{"id": "2", "name": "test2"},{"id": "3", "name": "test4"}]';

    DECLARE @IdTobeRemoved INT =1;
    DECLARE @StartIndex INT
    DECLARE @EndIndex INT
    DECLARE @tempjson nvarchar(max)

    SELECT @StartIndex = CHARINDEX('"id": "'+CONVERT(VARCHAR(10),@IdTobeRemoved)+'"',@json)-2

    SELECT @tempjson = STUFF(@json, 1, @StartIndex, '')

    SELECT @EndIndex =
                CASE WHEN SUBSTRING(@tempjson,CHARINDEX('}',@tempjson)+1,1)=']'
                    THEN CHARINDEX('}',@tempjson)+1
                    ELSE CHARINDEX('}',@tempjson)+2
                END

    SELECT REPLACE(REPLACE(@json,SUBSTRING(@tempjson,0,@EndIndex),''),'},]','}]')
</code>```

Body:
If I have the following JSON stored in a column in SQL Server:

declare @json nvarchar(max) = '[{"id": "1", "name": "test1"},{"id": "2", "name": "test2"},{"id": "3", "name": "test4"}]'

how can I remove an array where Id:=1 ?

I want to get the following result:

[{"id": "2", "name": "test2"},{"id": "3", "name": "test4"}]

Body:
try this:

    declare @json nvarchar(max) = '[{"id": "1", "name": "test1"},{"id": "2", "name": "test2"},{"id": "3", "name": "test4"}]';

    DECLARE @IdTobeRemoved INT =1;
    DECLARE @StartIndex INT
    DECLARE @EndIndex INT
    DECLARE @tempjson nvarchar(max)

    SELECT @StartIndex = CHARINDEX('"id": "'+CONVERT(VARCHAR(10),@IdTobeRemoved)+'"',@json)-2

    SELECT @tempjson = STUFF(@json, 1, @StartIndex, '')

    SELECT @EndIndex =
                CASE WHEN SUBSTRING(@tempjson,CHARINDEX('}',@tempjson)+1,1)=']'
                    THEN CHARINDEX('}',@tempjson)+1
                    ELSE CHARINDEX('}',@tempjson)+2
                END

    SELECT REPLACE(REPLACE(@json,SUBSTRING(@tempjson,0,@EndIndex),''),'},]','}]')


问:
Trouble with comparing 2 dimensional arrays
I keep getting a false boolean value from the following comparison:

```<code>public boolean getHz1() {
    return board[0][0] == board[0][1]
           && board[0][1] == board[0][2]
           && board[0][0] != null
           && board[0][1] != null
           && board[0][2] != null;
 }
</code>```

The relevant call in the driver class is:

```<code>do {
        System.out.println("Your turn: ");
        g1.play(s.nextInt(), s.nextInt(), s.next());
        System.out.println(g1.getHz1());
} while (g1.getHz1() == false)
</code>```

The "play" method takes 2 integers and a string value to put in the array, in this case "x".  When I print out the board[0][0], board[0][1] and board[0][2], all contain the string "x", but getHz1 still returns false.

答:
As mentioned in the comments you should compare objects using the equals method instead of ==.

```<code>public boolean getHz1() {
    return board[0][0] != null
           && board[0][1] != null
           && board[0][2] != null
           && board[0][0].equals(board[0][1])
           && board[0][1].equals(board[0][2]);
}
</code>```

== is only true if two objects have the same pointer.

Body:
I keep getting a false boolean value from the following comparison:

public boolean getHz1() {
    return board[0][0] == board[0][1]
           && board[0][1] == board[0][2]
           && board[0][0] != null
           && board[0][1] != null
           && board[0][2] != null;
 }

The relevant call in the driver class is:

do {
        System.out.println("Your turn: ");
        g1.play(s.nextInt(), s.nextInt(), s.next());
        System.out.println(g1.getHz1());
} while (g1.getHz1() == false)

The "play" method takes 2 integers and a string value to put in the array, in this case "x".  When I print out the board[0][0], board[0][1] and board[0][2], all contain the string "x", but getHz1 still returns false.

Body:
As mentioned in the comments you should compare objects using the equals method instead of ==.

public boolean getHz1() {
    return board[0][0] != null
           && board[0][1] != null
           && board[0][2] != null
           && board[0][0].equals(board[0][1])
           && board[0][1].equals(board[0][2]);
}

== is only true if two objects have the same pointer.