问:
Collection view Cells redirecting different ViewController
I Have UICollectionView with Sections. Each Sections have variable cells which is defined by array count. I have declared array of strings for each section in viewDidLoad function.

I want each cell to open a New UIViewController on click of respective cell. How do i get the above result.

I am using Swift3 for coding.

```<code>class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    @IBOutlet weak var collectView: UICollectionView!

    var sectionHeader = [String] ()

    var sectionArr = [Any] ()
    var enquire = [String] ()
    var serviceRequest = [String] ()
    var missedCall = [String] ()
    var settings = [String] ()

    var arr = [String] ()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        sectionHeader = ["Enquire","Service Request","Missed Call Recharge","Settings"]

        enquire = ["Balance Enquiry","Mini Statement","Account Statement","Cheque Status Enquiry","Fixed Deposit Enquiry"]
        serviceRequest = ["Stop Cheque Payment","Cheque Book Request","iPIN Regeneration"]
        missedCall = ["Activate","Deactivate","Set Recharge Amount","Recharge"]
        settings = ["Change Primary Account","Register"]

        sectionArr = [enquire,serviceRequest,missedCall,settings]

        collectView.dataSource = self
        collectView.delegate = self

        collectView.reloadData()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func loadCollectionView(_ sender: Any) {
        collectView.reloadData()
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return sectionArr.count
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if (section == 0) {
            return enquire.count
        }
        else if (section == 1) {
            return serviceRequest.count
        }
        else if (section == 2) {
            return missedCall.count
        }
        else {
            return self.settings.count
        }
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let mycell:CustomCell = collectView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! CustomCell

        arr = sectionArr[indexPath.section] as! [String]

        let imagename = arr[indexPath.row]

        let modified = imagename.replacingOccurrences(of: " ", with: "_")

        let modified_imagename = modified + ".png"

        mycell.functionalityImage.image = UIImage(named : modified_imagename)
        mycell.functionalityName.text = arr[indexPath.row]

        return mycell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        arr = sectionArr[indexPath.section] as! [String]

        showAlert(mesgTitle: "SELECTED CELL", mesgText: arr[indexPath.row])
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        var reusea:UICollectionReusableView? = nil

        if (kind == UICollectionElementKindSectionHeader) {

            let header:HeaderTextHome = collectView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header_Text", for: indexPath) as! HeaderTextHome

            header.headerText.text = sectionHeader[indexPath.section ]

            reusea = header

        }
        return reusea!
    }

    func showAlert(mesgTitle : String, mesgText : String) {

        let alertController = UIAlertController(title: mesgTitle, message: mesgText, preferredStyle: UIAlertControllerStyle.alert)

        let defaultAction = UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil)

        let cancleAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)

        alertController.addAction(defaultAction)
        alertController.addAction(cancleAction)

        present(alertController, animated: true, completion: nil)

    }

}
</code>```

Above code i display an alert on click.

答:
If I understood your question correctly, then one way of doing this would be to set the identifier for each UIViewController in your storyboard and then calling this in your didSelectItemAt:</p>

```<code>let vc = self.storyboard?.instantiateViewController(withIdentifier: sectionArr[indexPath.section]) as! UIViewController
self.present(vc, animated: true, completion: nil)
</code>```

Body:
I Have UICollectionView with Sections. Each Sections have variable cells which is defined by array count. I have declared array of strings for each section in viewDidLoad function.

I want each cell to open a New UIViewController on click of respective cell. How do i get the above result.

I am using Swift3 for coding.

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    @IBOutlet weak var collectView: UICollectionView!

    var sectionHeader = [String] ()

    var sectionArr = [Any] ()
    var enquire = [String] ()
    var serviceRequest = [String] ()
    var missedCall = [String] ()
    var settings = [String] ()

    var arr = [String] ()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        sectionHeader = ["Enquire","Service Request","Missed Call Recharge","Settings"]

        enquire = ["Balance Enquiry","Mini Statement","Account Statement","Cheque Status Enquiry","Fixed Deposit Enquiry"]
        serviceRequest = ["Stop Cheque Payment","Cheque Book Request","iPIN Regeneration"]
        missedCall = ["Activate","Deactivate","Set Recharge Amount","Recharge"]
        settings = ["Change Primary Account","Register"]

        sectionArr = [enquire,serviceRequest,missedCall,settings]

        collectView.dataSource = self
        collectView.delegate = self

        collectView.reloadData()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func loadCollectionView(_ sender: Any) {
        collectView.reloadData()
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return sectionArr.count
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if (section == 0) {
            return enquire.count
        }
        else if (section == 1) {
            return serviceRequest.count
        }
        else if (section == 2) {
            return missedCall.count
        }
        else {
            return self.settings.count
        }
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let mycell:CustomCell = collectView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! CustomCell

        arr = sectionArr[indexPath.section] as! [String]

        let imagename = arr[indexPath.row]

        let modified = imagename.replacingOccurrences(of: " ", with: "_")

        let modified_imagename = modified + ".png"

        mycell.functionalityImage.image = UIImage(named : modified_imagename)
        mycell.functionalityName.text = arr[indexPath.row]

        return mycell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        arr = sectionArr[indexPath.section] as! [String]

        showAlert(mesgTitle: "SELECTED CELL", mesgText: arr[indexPath.row])
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        var reusea:UICollectionReusableView? = nil

        if (kind == UICollectionElementKindSectionHeader) {

            let header:HeaderTextHome = collectView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header_Text", for: indexPath) as! HeaderTextHome

            header.headerText.text = sectionHeader[indexPath.section ]

            reusea = header

        }
        return reusea!
    }

    func showAlert(mesgTitle : String, mesgText : String) {

        let alertController = UIAlertController(title: mesgTitle, message: mesgText, preferredStyle: UIAlertControllerStyle.alert)

        let defaultAction = UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil)

        let cancleAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)

        alertController.addAction(defaultAction)
        alertController.addAction(cancleAction)

        present(alertController, animated: true, completion: nil)

    }

}

Above code i display an alert on click.

Body:
If I understood your question correctly, then one way of doing this would be to set the identifier for each UIViewController in your storyboard and then calling this in your didSelectItemAt:

let vc = self.storyboard?.instantiateViewController(withIdentifier: sectionArr[indexPath.section]) as! UIViewController
self.present(vc, animated: true, completion: nil)


来源: stackexchange

问:
Can I set an unlimited length for maxJsonLength in web.config?
I am using the autocomplete feature of jQuery. When I try to retrieve the list of more then 17000 records (each won't have more than 10 char length), it's exceeding the length and throws the error:

Exception information:

      Exception type: InvalidOperationException

      Exception message: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

Can I set an unlimited length for maxJsonLength in web.config? If not, what is the maximum length I can set?

答:
Simply set MaxJsonLength proprty in MVC's Action method</p>

```<code>JsonResult json= Json(classObject, JsonRequestBehavior.AllowGet);
json.MaxJsonLength = int.MaxValue;
return json;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Simply set MaxJsonLength proprty in MVC's Action method

JsonResult json= Json(classObject, JsonRequestBehavior.AllowGet);
json.MaxJsonLength = int.MaxValue;
return json;


问:
Angular CLI - create a new project choosing Angular2 version
Good morning,
I'm trying to use Angular CLI to start a project in Angular 2 and not in Angular 4, I mean I would like to use version 2.4.10 for example.
There are any way to create it using Angular CLI, can't find which parameters I need to use or if it's possible, I would apreciate any help, Googling I haven't found anything.

I mean, if I type ng new myProject, this project is create in Angular4.

Thank you very much

答:
If you want to use an earlier version of Angular in a project created using the latest version of the CLI, the after creation is complete you'll have to change the @angular versions in the package.json to what you need, and run npm install for that project.

Note: If you go back to 2.4.10, then make sure the @angular/router version you use is 3.4.10.

You can still use the CLI to generate code, and you shouldn't see any insurmountable issues, if you see any at all.

The latest version of the CLI only supports creating new projects with ng4, and newer. What you do with the code after that is entirely up to you.


问:
Extract lines corresponding to the minimum value in the last column
I need help with extracting all the lines from the file that has minimum number in the last column, i.e 7 in in this case.

The sample file is as below:

File-1.txt

```<code>VALID_PATH :  [102, 80, 112, 109, 23, 125, 111] 7
VALID_PATH :  [102, 81, 112, 109, 23, 125, 111] 7
VALID_PATH :  [102, 112, 37, 109, 23, 125, 111] 7
VALID_PATH :  [102, 112, 37, 56, 23, 125, 111]  7
VALID_PATH :  [102, 80, 112, 37, 109, 23, 125, 111] 8
VALID_PATH :  [102, 80, 112, 37, 56, 23, 125, 111]  8
VALID_PATH :  [102, 80, 112, 109, 23, 125, 110, 111]    8
VALID_PATH :  [102, 80, 127, 6, 112, 109, 23, 125, 111] 9
VALID_PATH :  [102, 80, 127, 88, 112, 109, 23, 125, 111]    9
VALID_PATH :  [102, 80, 112, 37, 109, 23, 125, 110, 111]    9
VALID_PATH :  [102, 80, 112, 37, 56, 23, 125, 110, 111] 9
VALID_PATH :  [102, 80, 127, 6, 112, 37, 109, 23, 125, 111] 10
VALID_PATH :  [102, 80, 127, 6, 112, 37, 56, 23, 125, 111]  10
VALID_PATH :  [102, 80, 127, 6, 112, 109, 23, 125, 110, 111]    10
</code>```

Here, I want to extract all the lines that have 7, which is the least value (minimum value) in the last column and save the output into another file File-2.txt by only extracting the values enclosed in [], as shown below.

File-2.txt

```<code>102, 80, 112, 109, 23, 125, 111
102, 81, 112, 109, 23, 125, 111
102, 112, 37, 109, 23, 125, 111
102, 112, 37, 56, 23, 125, 111
</code>```

I could use awk to get the least value as "7" from the last column using the code as below:

```<code>awk 'BEGIN{getline;min=max=$NF}
NF{
    max=(max>$NF)?max:$NF
    min=(min>$NF)?$NF:min
}
END{print min,max}' File-1.txt
</code>```

and to print only the values in square brackets [] buy using the awk code as below:

```<code>awk 'NR > 1 {print $1}' RS='[' FS=']' File-1.txt
</code>```

but, I am stuck in assigning the least value obtained from first awk script, i.e. 7 in this case to extract the corresponding numbers enclosed in [], as shown in File-2.txt.

Any help in resolving this problem will be appreciated.

Body:
I need help with extracting all the lines from the file that has minimum number in the last column, i.e 7 in in this case.

The sample file is as below:

File-1.txt

VALID_PATH :  [102, 80, 112, 109, 23, 125, 111] 7
VALID_PATH :  [102, 81, 112, 109, 23, 125, 111] 7
VALID_PATH :  [102, 112, 37, 109, 23, 125, 111] 7
VALID_PATH :  [102, 112, 37, 56, 23, 125, 111]  7
VALID_PATH :  [102, 80, 112, 37, 109, 23, 125, 111] 8
VALID_PATH :  [102, 80, 112, 37, 56, 23, 125, 111]  8
VALID_PATH :  [102, 80, 112, 109, 23, 125, 110, 111]    8
VALID_PATH :  [102, 80, 127, 6, 112, 109, 23, 125, 111] 9
VALID_PATH :  [102, 80, 127, 88, 112, 109, 23, 125, 111]    9
VALID_PATH :  [102, 80, 112, 37, 109, 23, 125, 110, 111]    9
VALID_PATH :  [102, 80, 112, 37, 56, 23, 125, 110, 111] 9
VALID_PATH :  [102, 80, 127, 6, 112, 37, 109, 23, 125, 111] 10
VALID_PATH :  [102, 80, 127, 6, 112, 37, 56, 23, 125, 111]  10
VALID_PATH :  [102, 80, 127, 6, 112, 109, 23, 125, 110, 111]    10

Here, I want to extract all the lines that have 7, which is the least value (minimum value) in the last column and save the output into another file File-2.txt by only extracting the values enclosed in [], as shown below.

File-2.txt

102, 80, 112, 109, 23, 125, 111
102, 81, 112, 109, 23, 125, 111
102, 112, 37, 109, 23, 125, 111
102, 112, 37, 56, 23, 125, 111

I could use awk to get the least value as "7" from the last column using the code as below:

awk 'BEGIN{getline;min=max=$NF}
NF{
    max=(max>$NF)?max:$NF
    min=(min>$NF)?$NF:min
}
END{print min,max}' File-1.txt

and to print only the values in square brackets [] buy using the awk code as below:

awk 'NR > 1 {print $1}' RS='[' FS=']' File-1.txt

but, I am stuck in assigning the least value obtained from first awk script, i.e. 7 in this case to extract the corresponding numbers enclosed in [], as shown in File-2.txt.

Any help in resolving this problem will be appreciated.

Body:
Reading same file twice, instead of using array practically bit slower, as we read file 2 times, but zero memory overhead.

awk -F'[][]' 'FNR==NR{if(min > $NF || min==""){ min=$NF} next }
     $NF==min{ print $2 }' file file

Explanation

awk -F'[][]' 'FNR==NR{                           # This block we read file
                                                 # and will find whats minimum
             if(min > $NF || min==""){
                min=$NF                          # NF gives no of fields, assign the value of $NF to variable min
             }
              next
     }
     $NF==min{                                   # Here we read file 2nd time, if last field value is equal to minimum
              print $2
     }' file file

Input

$ cat file
VALID_PATH :  [102, 80, 112, 109, 23, 125, 111] 7
VALID_PATH :  [102, 81, 112, 109, 23, 125, 111] 7
VALID_PATH :  [102, 112, 37, 109, 23, 125, 111] 7
VALID_PATH :  [102, 112, 37, 56, 23, 125, 111]  7
VALID_PATH :  [102, 80, 112, 37, 109, 23, 125, 111] 8
VALID_PATH :  [102, 80, 112, 37, 56, 23, 125, 111]  8
VALID_PATH :  [102, 80, 112, 109, 23, 125, 110, 111]    8
VALID_PATH :  [102, 80, 127, 6, 112, 109, 23, 125, 111] 9
VALID_PATH :  [102, 80, 127, 88, 112, 109, 23, 125, 111]    9
VALID_PATH :  [102, 80, 112, 37, 109, 23, 125, 110, 111]    9
VALID_PATH :  [102, 80, 112, 37, 56, 23, 125, 110, 111] 9
VALID_PATH :  [102, 80, 127, 6, 112, 37, 109, 23, 125, 111] 10
VALID_PATH :  [102, 80, 127, 6, 112, 37, 56, 23, 125, 111]  10
VALID_PATH :  [102, 80, 127, 6, 112, 109, 23, 125, 110, 111]    10

Output

$ awk -F'[][]' 'FNR==NR{ if(min > $NF || min==""){ min=$NF } next }
       $NF==min{ print $2 }' file file
102, 80, 112, 109, 23, 125, 111
102, 81, 112, 109, 23, 125, 111
102, 112, 37, 109, 23, 125, 111
102, 112, 37, 56, 23, 125, 111


问:
get exact Value in Setter Property value attribute in ResourceDictionary
I have folllowing resource ResourceDictionary xml file, and I'm trying get Property="Data" setter Value in codebehind

```<code><ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:SampleProject.Layout">

    <!-- User -->
    <Style x:Key="Process" TargetType="Path">
        <Setter Property="Data" Value="M24.5,0 L25.5,0 C39,0 z"/>
    </Style>

</ResourceDictionary>
</code>```

for that I tried following thing

var myStyle = (Style)FindResource("User");

this is getting all the setters and I can get specific setter by like this

```<code>    var myStyle = (Style)FindResource("Process");

    foreach (var item in myStyle.Setters)
    {
        Setter val2 = (Setter)item;

        if (val2.Property.ToString() == "Data")
        {
          string value =  val2.Value.ToString();
        }
    }
</code>```

once I debug this I can see, though its actual value M24.5,0 L25.5,0 C39,0 z after get this from code behind tht value become M24.5,0L25.5,0C39,0z.
which is removed white spaces after 0 ,

how to get exact value without reformat actual value on xaml file ?

答:
how to get exact value without reformat actual value on xaml file ?

I don't know why you actually need the space or the original string but I can tell you that there is no exact string value to get efter the XAML processer has parsed the XAML.

It will create a Geometry object based on the string that you define in the XAML markup and after this there is no string to be retrieved any more.

The only way to get the original string is to look in the uncompiled source file.

Body:
I have folllowing resource ResourceDictionary xml file, and I'm trying get Property="Data" setter Value in codebehind

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:SampleProject.Layout">

</ResourceDictionary>

for that I tried following thing

var myStyle = (Style)FindResource("User");

this is getting all the setters and I can get specific setter by like this

    var myStyle = (Style)FindResource("Process");

    foreach (var item in myStyle.Setters)
    {
        Setter val2 = (Setter)item;

        if (val2.Property.ToString() == "Data")
        {
          string value =  val2.Value.ToString();
        }
    }

once I debug this I can see, though its actual value M24.5,0 L25.5,0 C39,0 z after get this from code behind tht value become M24.5,0L25.5,0C39,0z.
which is removed white spaces after 0 ,

how to get exact value without reformat actual value on xaml file ?


问:
D3js V4 Center Node in Zoomable Tree
I've found this example from Rob Schmuecker for centering a node in a tree which was clicked. This example works with D3js version 3. I ported this example to d3js version 4. But in my example the svg will jump after centering if i try to move svg. Does anybody know whats going wrong? Here some code snippets.</p>

```<code>var baseSvg = d3.select("#tree-container").append("svg").attr("width", viewerWidth)
                                                        .attr("height", viewerHeight)
                                                        .attr("class", "overlay")
                                                        .call(zoomListener);

function zoom() {
  if(d3.event.transform != null) {
    svgGroup.attr("transform", d3.event.transform );
  }
}

function centerNode(source) {
  t = d3.zoomTransform(baseSvg.node());
  x = -source.y0;
  y = -source.x0;
  x = x * t.k + viewerWidth / 2;
  y = y * t.k + viewerHeight / 2;
  d3.select('g').transition().duration(duration).call( zoomListener.transform, d3.zoomIdentity.translate(x,y).scale(t.k) );
}
</code>```

答:
Changing the selection within the centerNode from 'g' to 'svg' seems to do the trick. This is likely because the zoom listener is called on the svg element.

For reference, the centerNode function would now look like this:

```<code>function centerNode(source) {
  t = d3.zoomTransform(baseSvg.node());
  x = -source.y0;
  y = -source.x0;
  x = x * t.k + viewerWidth / 2;
  y = y * t.k + viewerHeight / 2;
  d3.select('svg').transition().duration(duration).call( zoomListener.transform, d3.zoomIdentity.translate(x,y).scale(t.k) );
}
</code>```

Title: D3js V4 Center Node in Zoomable Tree

Body:
I've found this example from Rob Schmuecker for centering a node in a tree which was clicked. This example works with D3js version 3. I ported this example to d3js version 4. But in my example the svg will jump after centering if i try to move svg. Does anybody know whats going wrong? Here some code snippets.

var baseSvg = d3.select("#tree-container").append("svg").attr("width", viewerWidth)
                                                        .attr("height", viewerHeight)
                                                        .attr("class", "overlay")
                                                        .call(zoomListener);

function zoom() {
  if(d3.event.transform != null) {
    svgGroup.attr("transform", d3.event.transform );
  }
}

function centerNode(source) {
  t = d3.zoomTransform(baseSvg.node());
  x = -source.y0;
  y = -source.x0;
  x = x * t.k + viewerWidth / 2;
  y = y * t.k + viewerHeight / 2;
  d3.select('g').transition().duration(duration).call( zoomListener.transform, d3.zoomIdentity.translate(x,y).scale(t.k) );
}

Body:
Changing the selection within the centerNode from 'g' to 'svg' seems to do the trick. This is likely because the zoom listener is called on the svg element.

For reference, the centerNode function would now look like this:

function centerNode(source) {
  t = d3.zoomTransform(baseSvg.node());
  x = -source.y0;
  y = -source.x0;
  x = x * t.k + viewerWidth / 2;
  y = y * t.k + viewerHeight / 2;
  d3.select('svg').transition().duration(duration).call( zoomListener.transform, d3.zoomIdentity.translate(x,y).scale(t.k) );
}


问:
Split and remove particular value in href attribute and add new value using jquery
I have splitted the value in href attribute of a tag.

i splitted the value but i cannot remove the values and append new into it.

My HTML code is

```<code><a class="chapter_video" href="http://localhost/SVE128-portal2/public/video/9/25"></a>
</code>```

And my jquery is

```<code> var new = 4;
 var video_url = $('.chapter_video');
 var href = video_url.attr("href");
 //splitting value of href
 var split = href.split("/");
 if(split[7] !== undefined){
     href.remove(split[7]);
 }

 video_url.attr('href', video_url.attr('href') + '/'+ new);
</code>```

I have tried

```<code> var remove = href.replace('split[7]', '')
</code>```

instead of href.remove(split[7]);

答:
Old version:

While the answer of Muhammad Qasim fixes your problem, it doesn't take in account the possibility that the value of split[7] could occur multiple times in the string. I believe this fixes your problem the correct way:

```<code>var new = 4;
var video_url = $('.chapter_video');
var href = video_url.attr("href");
// Splitting value of href
var split = href.split("/");
if(split[7] !== undefined){
    // This removes the last item of the array
    // You could also use .pop() which also removes the last part of the array
    split.splice(-1, 1);
}
// Pastes all the array parts back together (opposite of split)
href = split.join('/')

video_url.attr('href', href + '/'+ new);
</code>```

New version

After some more tests, it occured to me that splice wouldn't be the smartest way to do this. Replacing the value in the URL directly would be better:

```<code>var new_id = 4;
var video_url = $('.chapter_video');
var href = video_url.attr("href");
// Splitting value of href
var split = href.split("/");
if(split[7] !== undefined){
    split[7] = new_id;
}
else {
    // If there isn't a 8th item in the array, add it to the end
    split.push(new_id)
}
// Pastes all the array parts back together (opposite of split)
href = split.join('/')

video_url.attr('href', href);
</code>```

Body:
I have splitted the value in href attribute of a tag.

i splitted the value but i cannot remove the values and append new into it.

My HTML code is

And my jquery is

 var new = 4;
 var video_url = $('.chapter_video');
 var href = video_url.attr("href");
 //splitting value of href
 var split = href.split("/");
 if(split[7] !== undefined){
     href.remove(split[7]);
 }

 video_url.attr('href', video_url.attr('href') + '/'+ new);

I have tried

 var remove = href.replace('split[7]', '')

instead of href.remove(split[7]);

Body:
Old version:

While the answer of Muhammad Qasim fixes your problem, it doesn't take in account the possibility that the value of split[7] could occur multiple times in the string. I believe this fixes your problem the correct way:

var new = 4;
var video_url = $('.chapter_video');
var href = video_url.attr("href");
// Splitting value of href
var split = href.split("/");
if(split[7] !== undefined){
    // This removes the last item of the array
    // You could also use .pop() which also removes the last part of the array
    split.splice(-1, 1);
}
// Pastes all the array parts back together (opposite of split)
href = split.join('/')

video_url.attr('href', href + '/'+ new);

New version

After some more tests, it occured to me that splice wouldn't be the smartest way to do this. Replacing the value in the URL directly would be better:

var new_id = 4;
var video_url = $('.chapter_video');
var href = video_url.attr("href");
// Splitting value of href
var split = href.split("/");
if(split[7] !== undefined){
    split[7] = new_id;
}
else {
    // If there isn't a 8th item in the array, add it to the end
    split.push(new_id)
}
// Pastes all the array parts back together (opposite of split)
href = split.join('/')

video_url.attr('href', href);


问:
image on collapse button
Can I put an image instead the button to collapse and show the text?

<button class="btn btn-info" style="background-color: #60bf3b; color: white;" type="button" data-toggle="collapse" data-target="#fatture">Per D.D.T. e Fatture:</button>

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.

```

Thanks for the help!

答:
```<code><div class="container">
<img data-toggle="collapse" data-target="#demo" src="button.png" width="50px">
      <div id="demo" class="collapse">
        Lorem ipsum dolor sit amet, consectetur adipisicing elit,
        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
      </div>
</code>```

Title: image on collapse button

Body:
Can I put an image instead the button to collapse and show the text?

<button class="btn btn-info" style="background-color: #60bf3b; color: white;" type="button" data-toggle="collapse" data-target="#fatture">Per D.D.T. e Fatture:</button>

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.

Thanks for the help!


问:
PDO update database field with current value + new value
I have the following code:

```<code>$pdo = new PDO('mysql:host=localhost:3306;dbname=database', 'user', 'password');

$statement = $pdo->prepare("UPDATE channelbro_rss SET links = ? WHERE channel = ?");
$statement->execute(array($links_new, $channel));
</code>```

but how do I set $links_new to the current value of links from the database, plus a new value?

For example:

The value of links in the database is test. Now first of all I want to echo this value and then update the value of links to the current value (test) plus another variable (separated by commas). E.g.: Update links to test, new. And if I do this whole thing again, it will update it to test, new, hello (The new value is always $new).

答:
It is simpler to add the value you wish to amend the old value by like this.

the concat() function will as its name suggests concatenate the new string onto the existing contents of the column.

```<code>$pdo = new PDO('mysql:host=localhost:3306;dbname=web190_db8', 'web190_8', 'password');

// If you want to see the value of links before you amend it
// as your requested, then you will have to get it as a seperate
// SELECT query

$stmt = $pdo->prepare("SELECT links FROM channelbro_rss WHERE channel = ?");
$stmt->execute( array($channel) );
$old_links = $stmt->fetchColumn(0);

echo $old_links;

$statement = $pdo->prepare("UPDATE channelbro_rss SET links = concat(links, ?) WHERE channel = ?");

$concat_text = ', new';
$statement->execute(array($concat_text, $channel));

// If you want to see the value of links AFTER you amend it
// then you will have to get it as a seperate SELECT query also

$stmt = $pdo->prepare("SELECT links FROM channelbro_rss WHERE channel = ?");
$stmt->execute( array($channel) );
$old_links = $stmt->fetchColumn(0);

echo $old_links;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following code:

$pdo = new PDO('mysql:host=localhost:3306;dbname=database', 'user', 'password');

$statement = $pdo->prepare("UPDATE channelbro_rss SET links = ? WHERE channel = ?");
$statement->execute(array($links_new, $channel));

but how do I set $links_new to the current value of links from the database, plus a new value?

For example:

The value of links in the database is test. Now first of all I want to echo this value and then update the value of links to the current value (test) plus another variable (separated by commas). E.g.: Update links to test, new. And if I do this whole thing again, it will update it to test, new, hello (The new value is always $new).

Body:
It is simpler to add the value you wish to amend the old value by like this.

the concat() function will as its name suggests concatenate the new string onto the existing contents of the column.

$pdo = new PDO('mysql:host=localhost:3306;dbname=web190_db8', 'web190_8', 'password');

// If you want to see the value of links before you amend it
// as your requested, then you will have to get it as a seperate
// SELECT query

$stmt = $pdo->prepare("SELECT links FROM channelbro_rss WHERE channel = ?");
$stmt->execute( array($channel) );
$old_links = $stmt->fetchColumn(0);

echo $old_links;

$statement = $pdo->prepare("UPDATE channelbro_rss SET links = concat(links, ?) WHERE channel = ?");

$concat_text = ', new';
$statement->execute(array($concat_text, $channel));

// If you want to see the value of links AFTER you amend it
// then you will have to get it as a seperate SELECT query also

$stmt = $pdo->prepare("SELECT links FROM channelbro_rss WHERE channel = ?");
$stmt->execute( array($channel) );
$old_links = $stmt->fetchColumn(0);

echo $old_links;


问:
Android Localization tool
I have text resources in android, some are already translated whereas others are missing.

Is there a tool that can import e.g. the values xml file in addition to values xml file for Italian and checks what is missing and helps inserting the missing translations?

I tried OmegaT. This program imports the android resource and also writes into it. However, it did not show already translated stuff. Virtaal Translator does not support the xml files as input.

I would like to have a simple tool outside Eclipse, so that I may provide this tools to others helping to translate things.

答:
You should try Lokalise. There is a free plan, and you could upload almost any format from different platforms.

I've been using it myself, and there is virtually no other tool better for managing translations.

Title: Android Localization tool


问:
Java Input from formatted file
I'm trying to getting input from a file which has various different lines.

e.g. the format is   Book title, Author:Borrower second name  First Name:Borrower state

here's some example lines.

```<code>The Lord of the Rings, JRR Tolkien:McInnes Elizabeth:13 11 10

Crime And Punishment, Fyodor Dostoyevsky

The Clan Of The Cave Bear, Jean M Auel

The God Of Small Things, Arundhati Roy:Robins Joshua:20 11 10
</code>```

So I tried to use useDelimiter after setting up a scanner, but since some line are shorter I don't no quite what to do.

答:
I would split each line (using String.split) passing in the colon as the delimiter. Then use lastIndexOf(',') on the first element returned by split in order to separate the author from the book:</p>

```<code>public class ReadCrappyInput {

    public static List<String> testData() {
        List<String> lines = new ArrayList<String>();
        lines.add("The Lord of the Rings, JRR Tolkien:McInnes Elizabeth:13 11 10");
        lines.add("Crime And Punishment, Fyodor Dostoyevsky");
        lines.add("The Clan Of The Cave Bear, Jean M Auel");
        lines.add("The God Of Small Things, Arundhati Roy:Robins Joshua:20 11 10");
        return lines;
    }

    public Map<String, String> readLine(String line) {
        String[] parts = line.split(":");
        int endOfTitleIndex = parts[0].lastIndexOf(',');
        Map<String, String> map = new HashMap<String, String>();
        map.put("title", parts[0].substring(0, endOfTitleIndex));
        map.put("author", parts[0].substring(endOfTitleIndex + 1).trim());
        if (parts.length > 1) {
            map.put("borrower", parts[1]);
        }
        if (parts.length > 2) {
            map.put("data", parts[2]);
        }
        return map;
    }

    public static void main(String[] args) {
        ReadCrappyInput r = new ReadCrappyInput();
        for (String s : testData()) {
            System.out.println(r.readLine(s));
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Java Input from formatted file

Body:
I'm trying to getting input from a file which has various different lines.

e.g. the format is   Book title, Author:Borrower second name  First Name:Borrower state

here's some example lines.

The Lord of the Rings, JRR Tolkien:McInnes Elizabeth:13 11 10

Crime And Punishment, Fyodor Dostoyevsky

The Clan Of The Cave Bear, Jean M Auel

The God Of Small Things, Arundhati Roy:Robins Joshua:20 11 10

So I tried to use useDelimiter after setting up a scanner, but since some line are shorter I don't no quite what to do.

Body:
I would split each line (using String.split) passing in the colon as the delimiter. Then use lastIndexOf(',') on the first element returned by split in order to separate the author from the book:

public class ReadCrappyInput {

    public static List<String> testData() {
        List<String> lines = new ArrayList<String>();
        lines.add("The Lord of the Rings, JRR Tolkien:McInnes Elizabeth:13 11 10");
        lines.add("Crime And Punishment, Fyodor Dostoyevsky");
        lines.add("The Clan Of The Cave Bear, Jean M Auel");
        lines.add("The God Of Small Things, Arundhati Roy:Robins Joshua:20 11 10");
        return lines;
    }

    public Map<String, String> readLine(String line) {
        String[] parts = line.split(":");
        int endOfTitleIndex = parts[0].lastIndexOf(',');
        Map<String, String> map = new HashMap<String, String>();
        map.put("title", parts[0].substring(0, endOfTitleIndex));
        map.put("author", parts[0].substring(endOfTitleIndex + 1).trim());
        if (parts.length > 1) {
            map.put("borrower", parts[1]);
        }
        if (parts.length > 2) {
            map.put("data", parts[2]);
        }
        return map;
    }

    public static void main(String[] args) {
        ReadCrappyInput r = new ReadCrappyInput();
        for (String s : testData()) {
            System.out.println(r.readLine(s));
        }
    }
}


问:
(grails) com.sun.mail.smtp.SMTPSendFailedException: 553 Relaying disallowed as zoho mail
I am trying to configure zoho mail service in grails mail-plugin. Here is my configuration so far,

```<code>    grails {
    mail {
        host = "smtp.zoho.com"
        port = 465
        username = "email@valid.com"
        password = "some-valid-password"
        props = ["mail.smtp.auth":"true",
                 "mail.smtp.starttls.enable":"true",
                 "mail.smtp.socketFactory.port":"465",
                 "mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
                 "mail.smtp.socketFactory.fallback":"false"]
    }
}
</code>```

Here is my service method. The above config works great if I put gmail smtp configuration, so I think there is no problem with service method at all. Also email@valid.com is a registered email in Zoho and I can send email using zoho dashboard.

```

    def sendImageProcessedNotification(User user, imageLink){
            try{
                if(user){
                    def receiver = user.email
                    mailService.sendMail {
                        async true
                        to receiver
                        subject "Subject"
                        html "Html body"
                    }
                }
            }catch(e){
                log.error(e)
            }
        }

```

And here is the stacktrace,

```

    2015-07-19 08:17:37,782 [pool-12-thread-1] ERROR mail.MailMessageBuilder  - Failed to send email
    org.springframework.mail.MailSendException: Failed to close server connection after message failures; nested exception is javax.mail.MessagingException: Can't send command to SMTP host;
      nested exception is:
        java.net.SocketException: Connection closed by remote host. Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 553 Relaying disallowed as
    ; message exception details (1) are:
    Failed message 1:
    com.sun.mail.smtp.SMTPSendFailedException: 553 Relaying disallowed as

        at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2133)
        at com.sun.mail.smtp.SMTPTransport.finishData(SMTPTransport.java:1912)
        at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1135)
        at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:433)
        at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:345)
        at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:340)
        at org.springframework.mail.javamail.JavaMailSender$send$0.call(Unknown Source)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:110)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:122)
        at grails.plugin.mail.MailMessageBuilder$_sendMessage_closure1.doCall(MailMessageBuilder.groovy:112)
        at grails.plugin.mail.MailMessageBuilder$_sendMessage_closure1.doCall(MailMessageBuilder.groovy)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
        at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:324)
        at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1207)
        at groovy.lang.ExpandoMetaClass.invokeMethod(ExpandoMetaClass.java:1121)
        at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1016)
        at groovy.lang.Closure.call(Closure.java:423)
        at groovy.lang.Closure.call(Closure.java:417)
        at groovy.lang.Closure.run(Closure.java:504)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:745)

```

答:
You just have to mention"setFrom()" properties where ever you have added the email logic.
Example: I've used JavaMailSender and using MimeMessage to send an email so in that case, I will have to mention "helper.setFrom()".

P.S: I've tried so many ways and after that I've solved it with this.

Body:
I am trying to configure zoho mail service in grails mail-plugin. Here is my configuration so far,

    grails {
    mail {
        host = "smtp.zoho.com"
        port = 465
        username = "email@valid.com"
        password = "some-valid-password"
        props = ["mail.smtp.auth":"true",
                 "mail.smtp.starttls.enable":"true",
                 "mail.smtp.socketFactory.port":"465",
                 "mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
                 "mail.smtp.socketFactory.fallback":"false"]
    }
}

Here is my service method. The above config works great if I put gmail smtp configuration, so I think there is no problem with service method at all. Also email@valid.com is a registered email in Zoho and I can send email using zoho dashboard.

    def sendImageProcessedNotification(User user, imageLink){
            try{
                if(user){
                    def receiver = user.email
                    mailService.sendMail {
                        async true
                        to receiver
                        subject "Subject"
                        html "Html body"
                    }
                }
            }catch(e){
                log.error(e)
            }
        }

And here is the stacktrace,

    2015-07-19 08:17:37,782 [pool-12-thread-1] ERROR mail.MailMessageBuilder  - Failed to send email
    org.springframework.mail.MailSendException: Failed to close server connection after message failures; nested exception is javax.mail.MessagingException: Can't send command to SMTP host;
      nested exception is:
        java.net.SocketException: Connection closed by remote host. Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 553 Relaying disallowed as
    ; message exception details (1) are:
    Failed message 1:
    com.sun.mail.smtp.SMTPSendFailedException: 553 Relaying disallowed as

        at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2133)
        at com.sun.mail.smtp.SMTPTransport.finishData(SMTPTransport.java:1912)
        at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1135)
        at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:433)
        at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:345)
        at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:340)
        at org.springframework.mail.javamail.JavaMailSender$send$0.call(Unknown Source)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:110)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:122)
        at grails.plugin.mail.MailMessageBuilder$_sendMessage_closure1.doCall(MailMessageBuilder.groovy:112)
        at grails.plugin.mail.MailMessageBuilder$_sendMessage_closure1.doCall(MailMessageBuilder.groovy)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
        at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:324)
        at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1207)
        at groovy.lang.ExpandoMetaClass.invokeMethod(ExpandoMetaClass.java:1121)
        at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1016)
        at groovy.lang.Closure.call(Closure.java:423)
        at groovy.lang.Closure.call(Closure.java:417)
        at groovy.lang.Closure.run(Closure.java:504)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:745)


问:
splitting List<Object> based on the value of a variable in that Object
I am trying to split my list into multiple smaller lists but don't know how i should do it.

```<code>List<Object> list = new List<Object>();
</code>```

This is my original list that contains the object Object. I am trying to split this list based on the variables of this Object.

example:

```<code>public class Object {
   string var1;
   int var2;
   int var3;
}
</code>```

lets say the list Object has 3 possible var1 ("yes","no","maybe") then i want 3 Lists where each list are all the objects that have "yes","no" or "maybe" as var1 (this can be a list of 100 objects long with each object being one of this string) (the amount of possibilities in var1 is not constant)

答:
Use System.Linq:

```<code>List<Object> listYes = list.Where(o => o.var1 == "yes").ToList();
List<Object> listNo = list.Where(o => o.var1 == "no").ToList();
List<Object> listMaybe = list.Where(o => o.var1 == "maybe").ToList();
</code>```

This will give you 3 lists of objects where var1 equals the respective valuein the Where() clause.

Body:
I am trying to split my list into multiple smaller lists but don't know how i should do it.

List<Object> list = new List<Object>();

This is my original list that contains the object Object. I am trying to split this list based on the variables of this Object.

example:

public class Object {
   string var1;
   int var2;
   int var3;
}

lets say the list Object has 3 possible var1 ("yes","no","maybe") then i want 3 Lists where each list are all the objects that have "yes","no" or "maybe" as var1 (this can be a list of 100 objects long with each object being one of this string) (the amount of possibilities in var1 is not constant)

Body:
Use System.Linq:

List<Object> listYes = list.Where(o => o.var1 == "yes").ToList();
List<Object> listNo = list.Where(o => o.var1 == "no").ToList();
List<Object> listMaybe = list.Where(o => o.var1 == "maybe").ToList();

This will give you 3 lists of objects where var1 equals the respective valuein the Where() clause.


问:
Push notifications in Swift iOS
I am working with iOS Swift Notifications Module. I'm not getting the Alert/Banner Notification on the device.

I’m able to get notification when the App is open i.e. in Foreground, but not when app in in Background or Terminated.

Following is my code

```<code>import UIKit

import UserNotifications

import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, FIRMessagingDelegate {

    var window: UIWindow?

    //  MARK: - Application Life Cycle
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        FIRApp.configure()

        askNotificationPermission(application)

        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.getFirebaseInstaceID(_:)), name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)

        connectToFcm()

        return true
    }

    // MARK:- Push Notification Delegate Methods
    @nonobjc func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print(error)
    }

    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
        let appdata = remoteMessage.appData as NSDictionary as! [String: AnyObject]
        print(appdata)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        print(userInfo)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print(userInfo)
        completionHandler(UIBackgroundFetchResult.newData)
    }

    // Receive displayed notifications for iOS 10 devices.
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        let userInfo = notification.request.content.userInfo
        print("Message ID: \(userInfo["gcm.message_id"]!)")
        print("%@", userInfo)
    }

    //  MARK: - Permissions
    func askNotificationPermission(_ application: UIApplication) {
        if #available(iOS 10.0, *) {

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { (finished, error) in

            })

            UNUserNotificationCenter.current().delegate = self

            FIRMessaging.messaging().remoteMessageDelegate = self

        } else {

            let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()
    }

    //  MARK: - Firebase Connection Methods
    @objc func getFirebaseInstaceID(_ notification: Notification) {

        if isNotNull(FIRInstanceID.instanceID().token() as AnyObject?) {
            let strFirebaseInstanceID = FIRInstanceID.instanceID().token()! as String
            if !strFirebaseInstanceID.isEmpty {
                print("Firebase Instance ID - \(strFirebaseInstanceID)")
                setString(strValue: strFirebaseInstanceID, forKey: Default.firebaseInstanceID)

                NotificationCenter.default.post(name: Notification.Name(rawValue: Notifications.nSendFirebaseID), object: nil)
            } else {
                setString(strValue: "", forKey: Default.firebaseInstanceID)
            }
        } else {
            setString(strValue: "", forKey: Default.firebaseInstanceID)
        }

        connectToFcm()
    }

    func connectToFcm() {
        FIRMessaging.messaging().connect { (error) in
            if (error != nil) {
                print("Unable to connect with FCM. \(error)")
            } else {
                print("Connected to FCM.")
            }
        }
    }
}
</code>```

答:
I forgot to add this method</p>

```<code>didReceiveRemoteNotification
</code>```

Title: Push notifications in Swift iOS

Body:
I am working with iOS Swift Notifications Module. I'm not getting the Alert/Banner Notification on the device.

I’m able to get notification when the App is open i.e. in Foreground, but not when app in in Background or Terminated.

Following is my code

import UIKit

import UserNotifications

import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, FIRMessagingDelegate {

    var window: UIWindow?

    //  MARK: - Application Life Cycle
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        FIRApp.configure()

        askNotificationPermission(application)

        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.getFirebaseInstaceID(_:)), name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)

        connectToFcm()

        return true
    }

    // MARK:- Push Notification Delegate Methods
    @nonobjc func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print(error)
    }

    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
        let appdata = remoteMessage.appData as NSDictionary as! [String: AnyObject]
        print(appdata)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        print(userInfo)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print(userInfo)
        completionHandler(UIBackgroundFetchResult.newData)
    }

    // Receive displayed notifications for iOS 10 devices.
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        let userInfo = notification.request.content.userInfo
        print("Message ID: \(userInfo["gcm.message_id"]!)")
        print("%@", userInfo)
    }

    //  MARK: - Permissions
    func askNotificationPermission(_ application: UIApplication) {
        if #available(iOS 10.0, *) {

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { (finished, error) in

            })

            UNUserNotificationCenter.current().delegate = self

            FIRMessaging.messaging().remoteMessageDelegate = self

        } else {

            let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()
    }

    //  MARK: - Firebase Connection Methods
    @objc func getFirebaseInstaceID(_ notification: Notification) {

        if isNotNull(FIRInstanceID.instanceID().token() as AnyObject?) {
            let strFirebaseInstanceID = FIRInstanceID.instanceID().token()! as String
            if !strFirebaseInstanceID.isEmpty {
                print("Firebase Instance ID - \(strFirebaseInstanceID)")
                setString(strValue: strFirebaseInstanceID, forKey: Default.firebaseInstanceID)

                NotificationCenter.default.post(name: Notification.Name(rawValue: Notifications.nSendFirebaseID), object: nil)
            } else {
                setString(strValue: "", forKey: Default.firebaseInstanceID)
            }
        } else {
            setString(strValue: "", forKey: Default.firebaseInstanceID)
        }

        connectToFcm()
    }

    func connectToFcm() {
        FIRMessaging.messaging().connect { (error) in
            if (error != nil) {
                print("Unable to connect with FCM. \(error)")
            } else {
                print("Connected to FCM.")
            }
        }
    }
}

Body:
I forgot to add this method

didReceiveRemoteNotification


问:
3 threads to print alternate values in sequence
I am trying to create an implementation where multiple threads print alternate values of sequence. So here thread1 will print 1,4,7 thread2 will print 2,5,8 thread3 will print 3,6,9. I am using Atomic integer and modulo function.

Below implementation works fine in the sense that first thread prints 1,4,7 while second prints 2,5,8 and third prints 3,6,9 but problem is that sequence is not maintained i.e output can be like 1,3,2,4,5,7,8,6,9 while i want sequence to be maintained as proper threads shld print those values.
One condition is i don't want to use synchronize. [Just for learning purpose]

```<code>import java.util.concurrent.atomic.AtomicInteger;

public class ThreeThreadsOrderedLockLess {

    AtomicInteger sharedOutput = new AtomicInteger(0);

    public static void main(String args[]) {

        ThreeThreadsOrderedLockLess t = new ThreeThreadsOrderedLockLess();

        ThreadTasks t1 = t.new ThreadTasks(0);
        ThreadTasks t2 = t.new ThreadTasks(1);
        ThreadTasks t3 = t.new ThreadTasks(2);

        Thread ts1 = new Thread(t1);
        Thread ts2 = new Thread(t2);
        Thread ts3 = new Thread(t3);
        ts1.start();
        ts2.start();
        ts3.start();

    }

    private class ThreadTasks implements Runnable {

        private final int threadPosition;

        public ThreadTasks(int threadPosition) {
            super();

            this.threadPosition = threadPosition;
        }

        @Override
        public void run() {

            while (sharedOutput.get() < 9) {

                if (sharedOutput.get() % 3 == this.threadPosition) {

                    System.out.println("Printing output for Thread: "
                            + this.threadPosition + "  "
                            + sharedOutput.incrementAndGet());
                }
            }

        }
    }

}
</code>```

答:
You can use below code to print sequential numbers using multiple threads -

```<code>import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ThreadCall extends Thread {

    private BlockingQueue<Integer> bq = new ArrayBlockingQueue<Integer>(10);
    private ThreadCall next;

    public void setNext(ThreadCall t) {
        this.next = t;
    }

    public void addElBQ(int a) {
        this.bq.add(a);
    }

    public ThreadCall(String name) {
        this.setName(name);
    }

    @Override
    public void run() {
        int x = 0;
        while(true) {
            try {
                x = 0;
                x = bq.take();
                if (x!=0) {
                    System.out.println(Thread.currentThread().getName() + " =>" + x);
                    if (x >= 100) System.exit(0); // Need to stop all running threads
                    next.addElBQ(x+1);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        int THREAD_COUNT = 10;
        List<ThreadCall> listThread = new ArrayList<>();

        for (int i=1; i<=THREAD_COUNT; i++) {
            listThread.add(new ThreadCall("Thread " + i));
        }

        for (int i = 0; i < listThread.size(); i++) {
            if (i == listThread.size()-1) {
                listThread.get(i).setNext(listThread.get(0));
            }
            else listThread.get(i).setNext(listThread.get(i+1));
        }

        listThread.get(0).addElBQ(1);

        for (int i = 0; i < listThread.size(); i++) {
            listThread.get(i).start();
        }
    }
}
</code>```

Hope this will resolve your problem.

Body:
I am trying to create an implementation where multiple threads print alternate values of sequence. So here thread1 will print 1,4,7 thread2 will print 2,5,8 thread3 will print 3,6,9. I am using Atomic integer and modulo function.

Below implementation works fine in the sense that first thread prints 1,4,7 while second prints 2,5,8 and third prints 3,6,9 but problem is that sequence is not maintained i.e output can be like 1,3,2,4,5,7,8,6,9 while i want sequence to be maintained as proper threads shld print those values.
One condition is i don't want to use synchronize. [Just for learning purpose]

import java.util.concurrent.atomic.AtomicInteger;

public class ThreeThreadsOrderedLockLess {

    AtomicInteger sharedOutput = new AtomicInteger(0);

    public static void main(String args[]) {

        ThreeThreadsOrderedLockLess t = new ThreeThreadsOrderedLockLess();

        ThreadTasks t1 = t.new ThreadTasks(0);
        ThreadTasks t2 = t.new ThreadTasks(1);
        ThreadTasks t3 = t.new ThreadTasks(2);

        Thread ts1 = new Thread(t1);
        Thread ts2 = new Thread(t2);
        Thread ts3 = new Thread(t3);
        ts1.start();
        ts2.start();
        ts3.start();

    }

    private class ThreadTasks implements Runnable {

        private final int threadPosition;

        public ThreadTasks(int threadPosition) {
            super();

            this.threadPosition = threadPosition;
        }

        @Override
        public void run() {

            while (sharedOutput.get() < 9) {

                if (sharedOutput.get() % 3 == this.threadPosition) {

                    System.out.println("Printing output for Thread: "
                            + this.threadPosition + "  "
                            + sharedOutput.incrementAndGet());
                }
            }

        }
    }

}

Body:
You can use below code to print sequential numbers using multiple threads -

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ThreadCall extends Thread {

    private BlockingQueue<Integer> bq = new ArrayBlockingQueue<Integer>(10);
    private ThreadCall next;

    public void setNext(ThreadCall t) {
        this.next = t;
    }

    public void addElBQ(int a) {
        this.bq.add(a);
    }

    public ThreadCall(String name) {
        this.setName(name);
    }

    @Override
    public void run() {
        int x = 0;
        while(true) {
            try {
                x = 0;
                x = bq.take();
                if (x!=0) {
                    System.out.println(Thread.currentThread().getName() + " =>" + x);
                    if (x >= 100) System.exit(0); // Need to stop all running threads
                    next.addElBQ(x+1);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        int THREAD_COUNT = 10;
        List<ThreadCall> listThread = new ArrayList<>();

        for (int i=1; i<=THREAD_COUNT; i++) {
            listThread.add(new ThreadCall("Thread " + i));
        }

        for (int i = 0; i < listThread.size(); i++) {
            if (i == listThread.size()-1) {
                listThread.get(i).setNext(listThread.get(0));
            }
            else listThread.get(i).setNext(listThread.get(i+1));
        }

        listThread.get(0).addElBQ(1);

        for (int i = 0; i < listThread.size(); i++) {
            listThread.get(i).start();
        }
    }
}

Hope this will resolve your problem.


问:
cordova.js not available while running in chrome
I created an app using ionic-cli and is trying to run the app. I get below warning in chrome (trying to add infinite-schroll to the gallary app)

Native: tried calling Splashscreen.hide, but Cordova is not available.
  Make sure to include cordova.js or run in a device/simulator

How do I include cordova.js only during chrome testing

答:
Cordova is only included once your app is built to be run on a device, and so it's not available while testing in a browser. This of course means that plugins relying on Cordova wont work either. That's a limitation of testing in a browser. You can disregard the error.

To test all functionality you should test in an emulator or a real device.


问:
Issue with Payment while using Production Server- PayU
I have downloaded the asp.net MVC integration KIT from payumoney.com and tested it with test data on test server.It is working fine.

But when I am using the salt and key provided by the payU login and executing the code on the production server it gives me the following error which says Unable to process with the payment Merchant has to use his own email to make payment

Issue With PayU

答:
after purchased payumoney you can implement and make payment for testing by using your own registered email ... because your payumoney account is under activated process.... and it will take 4-7 days... </p>

<p>but if u implement payumoney code and testing your website, then u should have to used your email while payment testing process...  because payu is not approved your account .. it's under process    </p>

Body:
after purchased payumoney you can implement and make payment for testing by using your own registered email ... because your payumoney account is under activated process.... and it will take 4-7 days...

but if u implement payumoney code and testing your website, then u should have to used your email while payment testing process...  because payu is not approved your account .. it's under process


问:
NameNotFoundException injecting EJB in JAX-RS Resouce
I've been trying to inject an EJB into a JAX-RS resource via InitialContext()lookup() getting the following exception:

```<code>    <javax.naming.NameNotFoundException: While trying to look up
comp/env/AServiceLocal
in /app/webapp/wcc/1377099157.; remaining name 'comp/env/AServiceLocal'>
</code>```

My lookup in resource constructor:

```<code>try {

    initialContext = new InitialContext();
    String jndiSubcontext = "java:comp/env/";

    aService = (AServiceLocal) initialContext.lookup(jndiSubcontext+AServiceLocal.class.getSimpleName());
    eSService = (ESServiceLocal) initialContext.lookup(jndiSubcontext+ESServiceLocal.class.getSimpleName());
    eService = (EServiceLocal) initialContext.lookup(jndiSubcontext+EServiceLocal.class.getSimpleName());

} catch (NamingException e) {
    e.printStackTrace();
}
</code>```

Here's the file structure taking into account that they are all maven projects:

```<code>global
|
--shared
  |
  |---src/main/java/com/x/y/z/AServiceLocal.java (ejb)
|
--war-project
  |
  |--src/main/java/comm/x/y/z/TheResource.java (jax-rs)
</code>```

There are more maven projects related and they are all maven-configured through the global project in a hierarchical way.

There is also a resource in the same project as war-project that also performs lookups to the shared project and they do work.

I don't understand what the problem is.

edit

After adding ejb-local-ref to deployment  descriptor:

```<code><ejb-local-ref>
    <ejb-ref-name>AServiceLocal</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
    <local>com.x.y.service.AdminXProfileServiceLocal</local>
    <ejb-link>shared.jar#AdminXProfileService</ejb-link>
</ejb-local-ref>
</code>```

I get the following error:

[J2EE:160101]Error: The ejb-link "shared.jar#AService"
  declared in the ejb-ref or ejb-local-ref "AServiceLocal"
  in the application module "xyz-99.1.0-SNAPSHOT.war" could not be
  resolved. The target EJB for the ejb-ref could not be found. Ensure
  that the link is correct.

The jar shared.jar is a dependency of the war project, but it seems that location is not correct. Must I add the packages also to the ejb-link ?

Something like: <ejb-link>shared.jar#com.x.y.ServiceImpl</ejb-link>

I aslo need to point out that there is a mix of hk2,cdi and lookups as part of the injection due to the fact the project is quite old and also it was migrated to weblogic 12c version recently so normal @Inject or @EJB don't appear to be working.

答:
If I take into account all the variables I am seeing like Maven, project structure, JNDI lookup etc... the best way is to add an entry in the web.xml of the war project referencing your ejbs.

```<code><ejb-local-ref>
   <ejb-ref-name>ejb/adminXProfileService</ejb-ref-name>
   <ejb-ref-type>Session</ejb-ref-type>
   <local>com.myapp.ejb.AdminXProfileServiceLocal</local>
   <ejb-link>YourEJBLibrary.jar#adminXProfileService</ejb-link>
</ejb-local-ref>
</code>```

Then in your lookup you simply look for:

```<code>contenxt.lookup("java:comp/env/ejb/adminXProfileService");
</code>```

Body:
I've been trying to inject an EJB into a JAX-RS resource via InitialContext()lookup() getting the following exception:

    <javax.naming.NameNotFoundException: While trying to look up
comp/env/AServiceLocal
in /app/webapp/wcc/1377099157.; remaining name 'comp/env/AServiceLocal'>

My lookup in resource constructor:

try {

    initialContext = new InitialContext();
    String jndiSubcontext = "java:comp/env/";

    aService = (AServiceLocal) initialContext.lookup(jndiSubcontext+AServiceLocal.class.getSimpleName());
    eSService = (ESServiceLocal) initialContext.lookup(jndiSubcontext+ESServiceLocal.class.getSimpleName());
    eService = (EServiceLocal) initialContext.lookup(jndiSubcontext+EServiceLocal.class.getSimpleName());

} catch (NamingException e) {
    e.printStackTrace();
}

Here's the file structure taking into account that they are all maven projects:

global
|
--shared
  |
  |---src/main/java/com/x/y/z/AServiceLocal.java (ejb)
|
--war-project
  |
  |--src/main/java/comm/x/y/z/TheResource.java (jax-rs)

There are more maven projects related and they are all maven-configured through the global project in a hierarchical way.

There is also a resource in the same project as war-project that also performs lookups to the shared project and they do work.

I don't understand what the problem is.

edit

After adding ejb-local-ref to deployment  descriptor:

<ejb-local-ref>
    <ejb-ref-name>AServiceLocal</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
    <local>com.x.y.service.AdminXProfileServiceLocal</local>
    <ejb-link>shared.jar#AdminXProfileService</ejb-link>
</ejb-local-ref>

I get the following error:

[J2EE:160101]Error: The ejb-link "shared.jar#AService"
  declared in the ejb-ref or ejb-local-ref "AServiceLocal"
  in the application module "xyz-99.1.0-SNAPSHOT.war" could not be
  resolved. The target EJB for the ejb-ref could not be found. Ensure
  that the link is correct.

The jar shared.jar is a dependency of the war project, but it seems that location is not correct. Must I add the packages also to the ejb-link ?

Something like: <ejb-link>shared.jar#com.x.y.ServiceImpl</ejb-link>

I aslo need to point out that there is a mix of hk2,cdi and lookups as part of the injection due to the fact the project is quite old and also it was migrated to weblogic 12c version recently so normal @Inject or @EJB don't appear to be working.

Body:
If I take into account all the variables I am seeing like Maven, project structure, JNDI lookup etc... the best way is to add an entry in the web.xml of the war project referencing your ejbs.

<ejb-local-ref>
   <ejb-ref-name>ejb/adminXProfileService</ejb-ref-name>
   <ejb-ref-type>Session</ejb-ref-type>
   <local>com.myapp.ejb.AdminXProfileServiceLocal</local>
   <ejb-link>YourEJBLibrary.jar#adminXProfileService</ejb-link>
</ejb-local-ref>

Then in your lookup you simply look for:

contenxt.lookup("java:comp/env/ejb/adminXProfileService");


问:
Sum Values of Rows for Duplicate DropDownList Selected Item inside a gridview
I have a GridView inside my inventory application... I am using that grid view for product out... its is working fine but the thing i want is to check that if same product of same vendor is selected multiple times in gridview like i did in the picture then Sum its Quantity to ensure it is less than its Stock.
For single product it will just compare it with its Stock but For Every duplicate products, value of quantity will be added and compare it with its stock..
Any help would be highly appreciated...

e.g Computer Zone's Keyboard is selected twice and its has a stock of 15  ... I want to sum the quantity 10+7= 17 and throw a message if it is greater than its Stock which is 15 else save it as a row...
and Computer Zone's Pen is selected twice (it can be thrice or more)and its has a stock of 50 ...  quantity 10+60= 70 and throw a message if it is greater than its Stock which is 50...

答:
You could use javascript or jQuery to calculate total quantity of same product, then compare it with available stock of this product. The followling sample used jQuery.

To do calculation, first you should assign name or class to all item in your grid. Sample row should look like this.

```<code><tr>
    <td class="no">XX</td>
    <td><select  class="vendor" >... </select></td>
    <td><select  class="product" >...</select></td>
    <td><input class="stock" value="YY" readonly="true"></td>
    <td><input class="quantity" value="ZZ"></td>
</tr>
</code>```

Then you add handler for change event of item Quantity

```<code>$('.quantity').change(function(e){
    var quantity = $(this);
    var row = quantity.closest("tr");
    var selectedVendor = $(".vendor option:selected", row).val();
    var selectedProduct = $(".product option:selected", row).val();

    // Get all row that have the same vendor and product
    var sameRows = $(".product option:selected[value='" + selectedProduct + "']", $(".vendor option:selected[value='" + selectedVendor + "']").closest("tr")).closest("tr");

    // Calculate total quantity of same product
    var total = 0;
    sameRows.each(function() {
        total += parseInt($(".quantity", this).val());
    });

    // Compare total quantity and stock
    var stock = parseInt($(".stock", row).val());
    if (total > stock) {
        alert("Quantity access available stock");
        quantity.focus();
    }
});
</code>```

You should also consider to add similar handler for dropdown Vendor and Product.

I've created a demo here, you could check.

Body:
You could use javascript or jQuery to calculate total quantity of same product, then compare it with available stock of this product. The followling sample used jQuery.

To do calculation, first you should assign name or class to all item in your grid. Sample row should look like this.

<tr>
    <td class="no">XX</td>
    <td><select  class="vendor" >... </select></td>
    <td><select  class="product" >...</select></td>
    <td><input class="stock" value="YY" readonly="true"></td>
    <td><input class="quantity" value="ZZ"></td>
</tr>

Then you add handler for change event of item Quantity

$('.quantity').change(function(e){
    var quantity = $(this);
    var row = quantity.closest("tr");
    var selectedVendor = $(".vendor option:selected", row).val();
    var selectedProduct = $(".product option:selected", row).val();

    // Get all row that have the same vendor and product
    var sameRows = $(".product option:selected[value='" + selectedProduct + "']", $(".vendor option:selected[value='" + selectedVendor + "']").closest("tr")).closest("tr");

    // Calculate total quantity of same product
    var total = 0;
    sameRows.each(function() {
        total += parseInt($(".quantity", this).val());
    });

    // Compare total quantity and stock
    var stock = parseInt($(".stock", row).val());
    if (total > stock) {
        alert("Quantity access available stock");
        quantity.focus();
    }
});

You should also consider to add similar handler for dropdown Vendor and Product.

I've created a demo here, you could check.


问:
How to read a dynamic range?
I am trying to create a macro that reads data and does econometrics on the data. At this point I am trying to implement a latent variable MLE estimation.

The data can be of any length, depending on the user input. Suppose there is data in column O and column P. Ex-ante I have no idea how many rows of data exist.

I would like to first read how many data there are and then upload the data into my array variable before I can do any econometrics/statistics on it.

In this problem, the user has 25 data points for each variable. Some other user may enter different data with different number of data points.

In the code below, I am trying to read the variable "D" into an array. I first count the number of non-empty cells and then create an array of that size and try to read the value of the cells into the array. But I am getting a "type mismatch" error.

I've tried both "Variant" and "Array" types. Variant seems to be working but Array is not.

```<code>Sub SampleStats()

Dim Rng As String

Dim Var1(1 To 100) As Double
Dim Var2() As Double
Dim Var3 As Variant
Dim NumElements2 As Integer
Dim length2 As Integer

NumElements2 = WorksheetFunction.Count(Range("P:P"))
length2 = NumElements2+1

MsgBox NumElements2

ReDim Var2(1 To NumElements2)

Rng = "P2:P" & length2

MsgBox Rng

Var3 = Range(Rng).Value
MsgBox Var3(1,1)

Var2 = Range(Rng).Value

MsgBox Var2(1,1)

End Sub
</code>```

My questions are:

Whats the best way to read data when you don't know how long the columns go?

What the best way to store data (Variant or Array or something else) when the final objective is doing some statistics?

答:
First you get the Range with the column of data you want to pass into the array. Second you use the Application.Transpose function on the data and assign it to a Variant to create a 1-dimensional array from the Range.Value property.

If you just assign the range's Value directly to the Variant you will get a 2-dimensional array of N rows x 1 column. Sample code:

```<code>Option Explicit

Sub GetRangeToArray()

    Dim ws As Worksheet
    Dim rngData As Range
    Dim varData As Variant
    Dim lngCounter As Long

    ' get worksheet reference
    Set ws = ThisWorkbook.Worksheets("Sheet1")

    ' get the column to analyse - example here is A2:A last row
    ' so using 1 in column reference to Cells collection
    Set rngData = ws.Cells(2, 1).Resize(ws.Cells(ws.Rows.Count, 1).End(xlUp))

    ' convert range from 2d to 1d array
    varData = Application.Transpose(rngData.Value)

    ' test array
    For lngCounter = LBound(varData) To UBound(varData)
        Debug.Print varData(lngCounter)
    Next lngCounter

End Sub
</code>```

Title: How to read a dynamic range?

Body:
I am trying to create a macro that reads data and does econometrics on the data. At this point I am trying to implement a latent variable MLE estimation.

The data can be of any length, depending on the user input. Suppose there is data in column O and column P. Ex-ante I have no idea how many rows of data exist.

I would like to first read how many data there are and then upload the data into my array variable before I can do any econometrics/statistics on it.

In this problem, the user has 25 data points for each variable. Some other user may enter different data with different number of data points.

In the code below, I am trying to read the variable "D" into an array. I first count the number of non-empty cells and then create an array of that size and try to read the value of the cells into the array. But I am getting a "type mismatch" error.

I've tried both "Variant" and "Array" types. Variant seems to be working but Array is not.

Sub SampleStats()

Dim Rng As String

Dim Var1(1 To 100) As Double
Dim Var2() As Double
Dim Var3 As Variant
Dim NumElements2 As Integer
Dim length2 As Integer

NumElements2 = WorksheetFunction.Count(Range("P:P"))
length2 = NumElements2+1

MsgBox NumElements2

ReDim Var2(1 To NumElements2)

Rng = "P2:P" & length2

MsgBox Rng

Var3 = Range(Rng).Value
MsgBox Var3(1,1)

Var2 = Range(Rng).Value

MsgBox Var2(1,1)

End Sub

My questions are:

Whats the best way to read data when you don't know how long the columns go?

What the best way to store data (Variant or Array or something else) when the final objective is doing some statistics?

Body:
First you get the Range with the column of data you want to pass into the array. Second you use the Application.Transpose function on the data and assign it to a Variant to create a 1-dimensional array from the Range.Value property.

If you just assign the range's Value directly to the Variant you will get a 2-dimensional array of N rows x 1 column. Sample code:

Option Explicit

Sub GetRangeToArray()

    Dim ws As Worksheet
    Dim rngData As Range
    Dim varData As Variant
    Dim lngCounter As Long

    ' get worksheet reference
    Set ws = ThisWorkbook.Worksheets("Sheet1")

    ' get the column to analyse - example here is A2:A last row
    ' so using 1 in column reference to Cells collection
    Set rngData = ws.Cells(2, 1).Resize(ws.Cells(ws.Rows.Count, 1).End(xlUp))

    ' convert range from 2d to 1d array
    varData = Application.Transpose(rngData.Value)

    ' test array
    For lngCounter = LBound(varData) To UBound(varData)
        Debug.Print varData(lngCounter)
    Next lngCounter

End Sub


答:
Update your query like this:</p>

```<code>$statement = $pdo->prepare("UPDATE channelbro_rss SET links = concat(links, ? ) WHERE channel = ?");
</code>```

Title: PDO update database field with current value + new value

Body:
I have the following code:

$pdo = new PDO('mysql:host=localhost:3306;dbname=database', 'user', 'password');

$statement = $pdo->prepare("UPDATE channelbro_rss SET links = ? WHERE channel = ?");
$statement->execute(array($links_new, $channel));

but how do I set $links_new to the current value of links from the database, plus a new value?

For example:

The value of links in the database is test. Now first of all I want to echo this value and then update the value of links to the current value (test) plus another variable (separated by commas). E.g.: Update links to test, new. And if I do this whole thing again, it will update it to test, new, hello (The new value is always $new).

Body:
Update your query like this:

$statement = $pdo->prepare("UPDATE channelbro_rss SET links = concat(links, ? ) WHERE channel = ?");


问:
How to use Devise with 2 models in Rails?
I have the model User and Seller. I want to replace my authentication system with Devise but I'm not sure how devise handles having 2 different models.

How can I know when signed_in? is for Users or Sellers? And all the other methods like that.

Thanks.

答: You can use as many models as you want with devise.  In your example, you'd have a current_user and current_seller in your controllers that would give you the relevant accounts.  The signed_in? method common to other frameworks is user_signed_in? for devise (and you'd have a seller_signed_in? as well).</p>


问:
Disable manual column editing (input from keyboard) with phpexcel
Here I have a case where I want to make a column to be editable by choosing value through drop-down only so user is not able to edit it manually by typing anything.

Do you have any solution for this by using PHPExcel?

Thanks anyway.

答:
I have accomplish this task by using following code. </p>

```<code>                   $objValidation = $objPHPExcel->getActiveSheet()->getCell('B'.$i)->getDataValidation();
                    $objValidation->setType( PHPExcel_Cell_DataValidation::TYPE_LIST );
                    $objValidation->setErrorStyle( PHPExcel_Cell_DataValidation::STYLE_INFORMATION );
                    $objValidation->setAllowBlank(false);
                    $objValidation->setShowInputMessage(true);
                    $objValidation->setShowErrorMessage(true);
                    $objValidation->setShowDropDown(true);
                    $objValidation->setErrorTitle('Input error');
                    $objValidation->setError('Value is not in list.');
                    $objValidation->setPromptTitle('Pick from list');
                    $objValidation->setPrompt('Please pick a value from the drop-down list.');
                    $objValidation->setFormula1('"Rate,Margin"');
</code>```

Body:
I have accomplish this task by using following code.

                   $objValidation = $objPHPExcel->getActiveSheet()->getCell('B'.$i)->getDataValidation();
                    $objValidation->setType( PHPExcel_Cell_DataValidation::TYPE_LIST );
                    $objValidation->setErrorStyle( PHPExcel_Cell_DataValidation::STYLE_INFORMATION );
                    $objValidation->setAllowBlank(false);
                    $objValidation->setShowInputMessage(true);
                    $objValidation->setShowErrorMessage(true);
                    $objValidation->setShowDropDown(true);
                    $objValidation->setErrorTitle('Input error');
                    $objValidation->setError('Value is not in list.');
                    $objValidation->setPromptTitle('Pick from list');
                    $objValidation->setPrompt('Please pick a value from the drop-down list.');
                    $objValidation->setFormula1('"Rate,Margin"');


问:
Move a child array to parent array and change parent/child name
I know probably this was asked before not sure if was in this form but I did tried some replay from what I found here about this and failed.

ok I have this array

```<code>Array
(
    [0] => Array
        (
            [Data3] => Array
                (
                    [id] => 5
                    [category] => Whiskey
                    [name] => Some name
                    [description] => description
                    [image] => asdf.jpg
                    [price] => 83.99
                )

            [ammount] => 1
            [Data_id] => 3
        )

    [1] => Array
        (
            [Data3] => Array
                (
                    [id] => 4
                    [category] => Tequila
                    [name] => Something Red 75cl
                    [description] => description
                    [image] => sierratequilasilver100.jpg
                    [price] => 92.49
                )

            [ammount] => 2
            [Data_id] => 3
        )

    [2] => Array
        (
            [Data4] => Array
                (
                    [id] => 3
                    [category] => Whiskey
                    [name] => Some name Gold
                    [description] => description
                    [image] => asdf.jpg
                    [price] => 83.99
                )

            [ammount] => 1
            [Data_id] => 4
        )

    [3] => Array
        (
            [Data4] => Array
                (
                    [id] => 5
                    [category] => Vodka
                    [name] => Something Blue 100 cl
                    [description] => description
                    [image] => Something.jpg
                    [price] => 32.44
                )

            [ammount] => 1
            [Data_id] => 4
        )

)
</code>```

What I would like to be the result is something like this:

```<code>Array
(
    [0] => Array
        (
            [id] => 5
            [category] => Whiskey
            [name] => Some name
            [description] => description
            [image] => asdf.jpg
            [price] => 83.99
            [ammount] => 1
            [Data_id] => 3
        )

    [1] => Array
        (
            [id] => 4
            [category] => Tequila
            [name] => Something Red 75cl
            [description] => description
            [image] => sierratequilasilver100.jpg
            [price] => 92.49
            [ammount] => 2
            [Data_id] => 3
        )
    [2] => Array
        (
            [id] => 3
            [category] => Whiskey
            [name] => Some name Gold
            [description] => description
            [image] => asdf.jpg
            [price] => 83.99
            [ammount] => 1
            [Data_id] => 4
        )
    [3] => Array
        (
            [id] => 5
            [category] => Vodka
            [name] => Something Blue 100 cl
            [description] => description
            [image] => Something.jpg
            [price] => 32.44
            [ammount] => 1
            [Data_id] => 4
        )
)
</code>```

or another way I could work with is if I can change Data1, Data2, Data3 and so on ..

can be n Data depends how many producs a user select

into a same name ex simple Data or Info.

ex:

```<code>Array
(
    [0] => Array
        (
            [Info] => Array
                (
                    [id] => 5
                    [category] => Whiskey
                    [name] => Some name
                    [description] => description
                    [image] => asdf.jpg
                    [price] => 83.99
                )

            [ammount] => 1
            [Data_id] => 3
        )

    [1] => Array
        (
            [Info] => Array
                (
                    [id] => 4
                    [category] => Tequila
                    [name] => Something Red 75cl
                    [description] => description
                    [image] => sierratequilasilver100.jpg
                    [price] => 92.49
                )

            [ammount] => 2
            [Data_id] => 3
        )
</code>```

Any solution will be fine for me.

Thanks and regards

答:
your first option:

```<code>foreach($arr as $key => $value){
        foreach($value as $k => $val){
            if(is_array($val)){
                $arr[$key] = $val;
                unset($arr[$key][$k]);
            }
        }
    }
    echo "```"; print_r($arr);
```

Check output here

Body:
I know probably this was asked before not sure if was in this form but I did tried some replay from what I found here about this and failed.

ok I have this array

Array
(
    [0] => Array
        (
            [Data3] => Array
                (
                    [id] => 5
                    [category] => Whiskey
                    [name] => Some name
                    [description] => description
                    [image] => asdf.jpg
                    [price] => 83.99
                )

            [ammount] => 1
            [Data_id] => 3
        )

    [1] => Array
        (
            [Data3] => Array
                (
                    [id] => 4
                    [category] => Tequila
                    [name] => Something Red 75cl
                    [description] => description
                    [image] => sierratequilasilver100.jpg
                    [price] => 92.49
                )

            [ammount] => 2
            [Data_id] => 3
        )

    [2] => Array
        (
            [Data4] => Array
                (
                    [id] => 3
                    [category] => Whiskey
                    [name] => Some name Gold
                    [description] => description
                    [image] => asdf.jpg
                    [price] => 83.99
                )

            [ammount] => 1
            [Data_id] => 4
        )

    [3] => Array
        (
            [Data4] => Array
                (
                    [id] => 5
                    [category] => Vodka
                    [name] => Something Blue 100 cl
                    [description] => description
                    [image] => Something.jpg
                    [price] => 32.44
                )

            [ammount] => 1
            [Data_id] => 4
        )

)

What I would like to be the result is something like this:

Array
(
    [0] => Array
        (
            [id] => 5
            [category] => Whiskey
            [name] => Some name
            [description] => description
            [image] => asdf.jpg
            [price] => 83.99
            [ammount] => 1
            [Data_id] => 3
        )

    [1] => Array
        (
            [id] => 4
            [category] => Tequila
            [name] => Something Red 75cl
            [description] => description
            [image] => sierratequilasilver100.jpg
            [price] => 92.49
            [ammount] => 2
            [Data_id] => 3
        )
    [2] => Array
        (
            [id] => 3
            [category] => Whiskey
            [name] => Some name Gold
            [description] => description
            [image] => asdf.jpg
            [price] => 83.99
            [ammount] => 1
            [Data_id] => 4
        )
    [3] => Array
        (
            [id] => 5
            [category] => Vodka
            [name] => Something Blue 100 cl
            [description] => description
            [image] => Something.jpg
            [price] => 32.44
            [ammount] => 1
            [Data_id] => 4
        )
)

or another way I could work with is if I can change Data1, Data2, Data3 and so on ..

can be n Data depends how many producs a user select

into a same name ex simple Data or Info.

ex:

Array
(
    [0] => Array
        (
            [Info] => Array
                (
                    [id] => 5
                    [category] => Whiskey
                    [name] => Some name
                    [description] => description
                    [image] => asdf.jpg
                    [price] => 83.99
                )

            [ammount] => 1
            [Data_id] => 3
        )

    [1] => Array
        (
            [Info] => Array
                (
                    [id] => 4
                    [category] => Tequila
                    [name] => Something Red 75cl
                    [description] => description
                    [image] => sierratequilasilver100.jpg
                    [price] => 92.49
                )

            [ammount] => 2
            [Data_id] => 3
        )

Any solution will be fine for me.

Thanks and regards

Body:
your first option:

foreach($arr as $key => $value){
        foreach($value as $k => $val){
            if(is_array($val)){
                $arr[$key] = $val;
                unset($arr[$key][$k]);
            }
        }
    }
    echo "<pre>"; print_r($arr);

Check output here


问:
Get matched word count from a variable
I want to get the total count of test word in the $channel variable, but $a returns the same as $channel.

```<code>$channel = "test1 test2 test3 test4 testIgnore1 testIgnore2 testIgnore3"
$a = Select-String -InputObject $channel -Pattern "test"
</code>```

What should be the exact solution here?

答:
```<code>$channel = "test1 test2 test3 test4 testIgnore1 testIgnore2 testIgnore3"
([regex]::Matches($channel, "test" )).count
</code>```

Will give you the count of the matches: 7

Title: Get matched word count from a variable

Body:
I want to get the total count of test word in the $channel variable, but $a returns the same as $channel.

$channel = "test1 test2 test3 test4 testIgnore1 testIgnore2 testIgnore3"
$a = Select-String -InputObject $channel -Pattern "test"

What should be the exact solution here?

Body:
$channel = "test1 test2 test3 test4 testIgnore1 testIgnore2 testIgnore3"
([regex]::Matches($channel, "test" )).count

Will give you the count of the matches: 7