问:
Replacing words in text file using a dictionary
I'm trying to open a text file and then read through it replacing certain strings with strings stored in a dictionary.

Based on answers to How do I edit a text file in Python? I could pull out the dictionary values before doing the replacing, but looping through the dictionary seems more efficient.

The code doesn't produce any errors, but also doesn't do any replacing.

```<code>import fileinput

text = "sample file.txt"
fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}

for line in fileinput.input(text, inplace=True):
    line = line.rstrip()
    for i in fields:
         for field in fields:
             field_value = fields[field]

             if field in line:
                  line = line.replace(field, field_value)

             print line
</code>```

答:
If you can find a regex pattern covering all your keys, you could use re.sub for a very efficient solution : you only need one pass instead of parsing your whole text for each search term.

In your title, you mention "replacing words". In that case, '\w+' would work just fine.

```<code>import re

fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}

words_to_replace = r'\bpattern \d+\b'

text = """Based on answers to How do I edit a text file in Python? pattern 1 I could pull out
the dictionary values before doing the replacing, but looping through the dictionary seems more efficient.
Test pattern 2
The code doesn't produce any errors, but also doesn't do any replacing. pattern 3"""

def replace_words_using_dict(matchobj):
    key = matchobj.group(0)
    return fields.get(key, key)

print(re.sub(words_to_replace, replace_words_using_dict, text))
</code>```

It outputs :

```<code>Based on answers to How do I edit a text file in Python? replacement text 1 I could pull out
the dictionary values before doing the replacing, but looping through the dictionary seems more efficient.
Test replacement text 2
The code doesn't produce any errors, but also doesn't do any replacing. pattern 3
</code>```

Also, be very careful when modifying a file in place. I'd advice you to write a second file with the replacements. Once you are 100% sure that it works perfectly, you could switch to inplace=True.

Body:
I'm trying to open a text file and then read through it replacing certain strings with strings stored in a dictionary.

Based on answers to How do I edit a text file in Python? I could pull out the dictionary values before doing the replacing, but looping through the dictionary seems more efficient.

The code doesn't produce any errors, but also doesn't do any replacing.

import fileinput

text = "sample file.txt"
fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}

for line in fileinput.input(text, inplace=True):
    line = line.rstrip()
    for i in fields:
         for field in fields:
             field_value = fields[field]

             if field in line:
                  line = line.replace(field, field_value)

             print line

Body:
If you can find a regex pattern covering all your keys, you could use re.sub for a very efficient solution : you only need one pass instead of parsing your whole text for each search term.

In your title, you mention "replacing words". In that case, '\w+' would work just fine.

import re

fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}

words_to_replace = r'\bpattern \d+\b'

text = """Based on answers to How do I edit a text file in Python? pattern 1 I could pull out
the dictionary values before doing the replacing, but looping through the dictionary seems more efficient.
Test pattern 2
The code doesn't produce any errors, but also doesn't do any replacing. pattern 3"""

def replace_words_using_dict(matchobj):
    key = matchobj.group(0)
    return fields.get(key, key)

print(re.sub(words_to_replace, replace_words_using_dict, text))

It outputs :

Based on answers to How do I edit a text file in Python? replacement text 1 I could pull out
the dictionary values before doing the replacing, but looping through the dictionary seems more efficient.
Test replacement text 2
The code doesn't produce any errors, but also doesn't do any replacing. pattern 3

Also, be very careful when modifying a file in place. I'd advice you to write a second file with the replacements. Once you are 100% sure that it works perfectly, you could switch to inplace=True.


来源: stackexchange

问:
How to use foreach in codeigniter
I am trying to get values from database table with use of foreach , as i am getting result but it is showing all value from table as i am using it for slide show how can i get 1 detail at single time...    This is my code

```<code> <div class="col-md-10">
  <div class="carousel slide" data-ride="carousel">
    <div class="carousel-inner">
        <?php
        $result_array = $this->db->get('vm_feedback')->result_array();
        foreach ($result_array as $key => $v) {?>
         <div class="item active">
         <div class="col-md-12">
            <div class="testimonial-text">
                <p style="color:black;"><?php  echo $v['feed_desc'];?></p>
                <span class="testimonial-by"><?php echo $v['feed_name'];?></span>
            </div>
         </div>
         </div>
        <?php   } ?>
    </div>
   </div>
  </div>
</code>```

Result i am geting:

what i need :

答:
You have to put a condition on  as currently all the items div are active so it is not looking as you want. So use another variable to add active at once.

```<code><div class="col-md-10">
  <div class="carousel slide" data-ride="carousel">
    <div class="carousel-inner">
        <?php
        $result_array = $this->db->get('vm_feedback')->result_array();
        $i = 1;
        foreach ($result_array as $key => $v) {?>
         <div class="item <?php if($i == 1) echo "active"; ?>">
         <div class="col-md-12">
            <div class="testimonial-text">
                <p style="color:black;"><?php  echo $v['feed_desc'];?></p>
                <span class="testimonial-by"><?php echo $v['feed_name'];?></span>
            </div>
         </div>
         </div>
        <?php $i++;  } ?>
    </div>
   </div>
  </div>
</code>```

This will give you the exact result what you want.

Thanks

ContentLicense: CC BY-SA 4.0

Title: How to use foreach in codeigniter

Body:
I am trying to get values from database table with use of foreach , as i am getting result but it is showing all value from table as i am using it for slide show how can i get 1 detail at single time...    This is my code

        <?php
        $result_array = $this->db->get('vm_feedback')->result_array();
        foreach ($result_array as $key => $v) {?>

<?php  echo $v['feed_desc'];?>

                <?php echo $v['feed_name'];?>

        <?php   } ?>

Result i am geting:

what i need :

Body:
You have to put a condition on  as currently all the items div are active so it is not looking as you want. So use another variable to add active at once.

<div class="col-md-10">
  <div class="carousel slide" data-ride="carousel">
    <div class="carousel-inner">
        <?php
        $result_array = $this->db->get('vm_feedback')->result_array();
        $i = 1;
        foreach ($result_array as $key => $v) {?>
         <div class="item <?php if($i == 1) echo "active"; ?>">
         <div class="col-md-12">
            <div class="testimonial-text">
                <p style="color:black;"><?php  echo $v['feed_desc'];?></p>
                <span class="testimonial-by"><?php echo $v['feed_name'];?></span>
            </div>
         </div>
         </div>
        <?php $i++;  } ?>
    </div>
   </div>
  </div>

This will give you the exact result what you want.

Thanks

ContentLicense: CC BY-SA 3.0


问:
CodeIgniter URL Query String Manipulation
I have a E-Commerce Website build using CodeIgniter 2.3.

Please suggest how can I manipulate the URLs in the given sequence:-

Say a Person Searches for "Mobile Phones".
URL must be xyz.com/search/mobile-phone, which displays all the Mobile Phones from our Database.
I am already aware of the Search controller and use Routing to exclude the function name from the URL

Next the Person uses filtering by name of Mobile Phone Companies. Suppose he chooses "Apple". The URL must become xyz.com/search/mobile-phones/apple

Next the Person again filters by Condition ie "New" or "Refurbished". The URL must become xyz.com/search/mobile-phones/apples/new

The URLs need to be Functional URLs so that, if I pass the URL xyz.com/search/mobile-phones/apples/new to someone externally, he/she should be able to see the same result set as the person who came after Search & Filtering.

I am non-technical so may be I couldnt explain my problem very technically, but be assured, my Tech Person would be reading your suggestions.

Further Details

We are already using URI Segmentation, Routing & Post Method. But that way we are facing issues wrt Point #4 mentioned above

答:
You can use a controller like this suppose your controller file name is Search.php

add this route to config/route.php to this
$route['search/(.+)']='search/index/$1';

then in your search php specify index function

```<code>function index($search_type,$brand=null,$category=null){
    //write something here
}
</code>```

so when you access

xyz.com/search/mobile-phones/apple

The route will redirect this too xyz.com/search/index/mobile-phones/apple

The mobile-phones will be stored to $search_type and apple will be stored to $brand.

if you search xyz.com/search/mobile-phones/apple/new

The route will redirect this too

xyz.com/search/index/mobile-phones/apple

The mobile-phones will be stored to $search_type,
apple will be stored to $brand,
and new will be passed to $category.

References on routing

https://www.codeigniter.com/userguide3/general/routing.html

References on Controller parameter passing

https://www.codeigniter.com/userguide3/general/controllers.html#passing-uri-segments-to-your-methods

Body:
You can use a controller like this suppose your controller file name is Search.php

add this route to config/route.php to this
$route['search/(.+)']='search/index/$1';

then in your search php specify index function

function index($search_type,$brand=null,$category=null){
    //write something here
}

so when you access

xyz.com/search/mobile-phones/apple

The route will redirect this too xyz.com/search/index/mobile-phones/apple

The mobile-phones will be stored to $search_type and apple will be stored to $brand.

if you search xyz.com/search/mobile-phones/apple/new

The route will redirect this too

xyz.com/search/index/mobile-phones/apple

The mobile-phones will be stored to $search_type,
apple will be stored to $brand,
and new will be passed to $category.

References on routing

https://www.codeigniter.com/userguide3/general/routing.html

References on Controller parameter passing

https://www.codeigniter.com/userguide3/general/controllers.html#passing-uri-segments-to-your-methods


问:
Javascript dynamic input fields on a dynamic inputfield
I added a field for text input between the 2 Drop downs if Option number 3 is selected, the text box will appear.

This new text box should get numbers from the User and add new text fields under the Element for options.

For example: if the user adds the number 3 in the text box the radio button created, 3 new text boxes will show up under the Element row and look like this:

Option 1 _____________
Option 2 _____________
Option 3 _____________

// Funkcija za pravljenje Elemenata
var i = 0;
var a = 1;
function mojaFunkcija() {
    var type1 = document.getElementById('type1').value;
    var type2 = document.getElementById('type2').value;
    var question = document.getElementById('question').value;
    var counter = 'Element';
    counter+= a;
    var prviElement=document.createElement('span');
    prviElement.textContent= counter + ':' +'  ';
    document.body.appendChild(prviElement);
    var pitanje= document.createElement('span');
    var unos='unos';
    unos += i;
    pitanje.id=unos;
    pitanje.textContent=question + ' ';
    document.body.appendChild(pitanje);
    var tip1 = document.createElement("input");
    var element='element';
    element += i;
    tip1.id=element;
    if (type1=='textbox') {
        tip1.type=type2
    } else {
        tip1.type=type1
    }
    document.body.appendChild(tip1);
    var linija1= document.createElement("br");
    document.body.appendChild(linija1);
    var linija2= document.createElement("br");
    document.body.appendChild(linija2);
    i++;
    a++;
}

function AddTextBox(elm) {
    var v = elm.value;
    var iCounter = elm.id.replace('type1', '');

    if (v == 'radio') {
        var textbox = document.createElement('input');
        textbox.type = 'text';
        textbox.id = 'txtSecond' + iCounter;
        elm.parentNode.insertBefore(textbox, elm.nextSibling);
    } else {
        //Ovaj kod ce da izbrise Textbox u slucaju da se izabere druga opcija.
        var rmv = document.getElementById('txtSecond' + iCounter);
        if (rmv != undefined) {
            rmv.remove();
        }
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="pepo.css">
    <meta charset="UTF-8">
    <script src="basa.js"></script>
    <title>OnlineForms</title>
    </head>
<body>
    <!--Ovaj kod je za Main Page-->
    <Main class="kocka">
        <div align="left">
            <input type="button" class="dropbtn" value="Administration" onClick="window.location.reload();return false;"/>

            <button class="dropbtn" id="getAllButton">Forms</button>
        </div>
        <br>
        <div align="left">
            <input type="number" id="key" class="dropbtn"  Placeholder="Type the key value"/>
            <button class="dropbtn" id="getButton"> Search </button>
            <br>
            <br>
        </div>
    </Main>
    <!--Ovaj kod je za Elemente-->
    <div id="element" class="hide">
            <h1>Element <input type="text" class="dropbtn" id="question" value="" Placeholder="Type your question here"/>
            <select title="ddmenu" class="dropbtn" id="type1" onChange="AddTextBox(this)">
                <option selected disabled hidden value="Please select">Please select</option>
                <option value="textbox">textbox</option>
                <option value="checkbox">checkbox</option>
                <option value="radio">radio button</option>
                </select>
            <select title="ddmenu" class="dropbtn" id="type2">
                <option selected disabled hidden value="Please select">Please select</option>
                <option value="none">none</option>
                <option value="mandatory">mandatory</option>
                <option value="number">numeric</option>
            </select>
            </h1>
        <input type="button"  id="adddugme" class="dropbtn2" value="Add"  onclick="mojaFunkcija()"/>
        <br>
        <br>
        <button id="addButton" class='dropbtn'>Save</button>
        </div>
    <br>
    <br>
<div id="status"></div>
    <br>
<div id="status2"></div>
</body>
</html></code>```

答:
The issue is that you are executing the code only one time.

Put it inside a loop.

Here, I made a loop to execute the same code x times where x is the number user entered in the form

Check the snippet

var i = 0;
var a = 1;
function mojaFunkcija() {
    var type1 = document.getElementById('type1').value;
    var type2 = document.getElementById('type2').value;
    var question = document.getElementById('question').value;
    var i=0;
    while(i<question){
       var counter = 'Element';
       counter+= a;
       var prviElement=document.createElement('span');
       prviElement.textContent= counter + ':' +'  ';
       document.body.appendChild(prviElement);
       var pitanje= document.createElement('span');
       var unos='unos';
        unos += i;
        pitanje.id=unos;
       pitanje.textContent=(i+1) + ' ';
        document.body.appendChild(pitanje);
        var tip1 = document.createElement("input");
        var element='element';
        element += i;
        tip1.id=element;
        if (type1=='textbox') {
           tip1.type=type2
        } else {
            tip1.type=type1
         }
          document.body.appendChild(tip1);
          var linija1= document.createElement("br");
          document.body.appendChild(linija1);
          var linija2= document.createElement("br");
          document.body.appendChild(linija2);
          i++;
          a++;
       }
     }

function AddTextBox(elm) {
    var v = elm.value;
    var iCounter = elm.id.replace('type1', '');

    if (v == 'radio') {
        var textbox = document.createElement('input');
        textbox.type = 'text';
        textbox.id = 'txtSecond' + iCounter;
        elm.parentNode.insertBefore(textbox, elm.nextSibling);
    } else {
        //Ovaj kod ce da izbrise Textbox u slucaju da se izabere druga opcija.
        var rmv = document.getElementById('txtSecond' + iCounter);
        if (rmv != undefined) {
            rmv.remove();
        }
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="pepo.css">
    <meta charset="UTF-8">
    <script src="basa.js"></script>
    <title>OnlineForms</title>
    </head>
<body>
    <!--Ovaj kod je za Main Page-->
    <Main class="kocka">
        <div align="left">
            <input type="button" class="dropbtn" value="Administration" onClick="window.location.reload();return false;"/>

            <button class="dropbtn" id="getAllButton">Forms</button>
        </div>
        <br>
        <div align="left">
            <input type="number" id="key" class="dropbtn"  Placeholder="Type the key value"/>
            <button class="dropbtn" id="getButton"> Search </button>
            <br>
            <br>
        </div>
    </Main>
    <!--Ovaj kod je za Elemente-->
    <div id="element" class="hide">
            <h1>Element <input type="text" class="dropbtn" id="question" value="" Placeholder="Type your question here"/>
            <select title="ddmenu" class="dropbtn" id="type1" onChange="AddTextBox(this)">
                <option selected disabled hidden value="Please select">Please select</option>
                <option value="textbox">textbox</option>
                <option value="checkbox">checkbox</option>
                <option value="radio">radio button</option>
                </select>
            <select title="ddmenu" class="dropbtn" id="type2">
                <option selected disabled hidden value="Please select">Please select</option>
                <option value="none">none</option>
                <option value="mandatory">mandatory</option>
                <option value="number">numeric</option>
            </select>
            </h1>
        <input type="button"  id="adddugme" class="dropbtn2" value="Add"  onclick="mojaFunkcija()"/>
        <br>
        <br>
        <button id="addButton" class='dropbtn'>Save</button>
        </div>
    <br>
    <br>
<div id="status"></div>
    <br>
<div id="status2"></div>
</body>
</html></code>```

Body:
I added a field for text input between the 2 Drop downs if Option number 3 is selected, the text box will appear.

This new text box should get numbers from the User and add new text fields under the Element for options.

For example: if the user adds the number 3 in the text box the radio button created, 3 new text boxes will show up under the Element row and look like this:

Option 1 _____________
Option 2 _____________
Option 3 _____________

// Funkcija za pravljenje Elemenata
var i = 0;
var a = 1;
function mojaFunkcija() {
    var type1 = document.getElementById('type1').value;
    var type2 = document.getElementById('type2').value;
    var question = document.getElementById('question').value;
    var counter = 'Element';
    counter+= a;
    var prviElement=document.createElement('span');
    prviElement.textContent= counter + ':' +'  ';
    document.body.appendChild(prviElement);
    var pitanje= document.createElement('span');
    var unos='unos';
    unos += i;
    pitanje.id=unos;
    pitanje.textContent=question + ' ';
    document.body.appendChild(pitanje);
    var tip1 = document.createElement("input");
    var element='element';
    element += i;
    tip1.id=element;
    if (type1=='textbox') {
        tip1.type=type2
    } else {
        tip1.type=type1
    }
    document.body.appendChild(tip1);
    var linija1= document.createElement("br");
    document.body.appendChild(linija1);
    var linija2= document.createElement("br");
    document.body.appendChild(linija2);
    i++;
    a++;
}

function AddTextBox(elm) {
    var v = elm.value;
    var iCounter = elm.id.replace('type1', '');

    if (v == 'radio') {
        var textbox = document.createElement('input');
        textbox.type = 'text';
        textbox.id = 'txtSecond' + iCounter;
        elm.parentNode.insertBefore(textbox, elm.nextSibling);
    } else {
        //Ovaj kod ce da izbrise Textbox u slucaju da se izabere druga opcija.
        var rmv = document.getElementById('txtSecond' + iCounter);
        if (rmv != undefined) {
            rmv.remove();
        }
    }
}

<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="pepo.css">
    <meta charset="UTF-8">

    <title>OnlineForms</title>

            <input type="button" class="dropbtn" value="Administration" onClick="window.location.reload();return false;"/>

            <button class="dropbtn" id="getAllButton">Forms</button>

            <input type="number" id="key" class="dropbtn"  Placeholder="Type the key value"/>
            <button class="dropbtn" id="getButton"> Search </button>

Element <input type="text" class="dropbtn" id="question" value="" Placeholder="Type your question here"/>
            <select title="ddmenu" class="dropbtn" id="type1" onChange="AddTextBox(this)">
                <option selected disabled hidden value="Please select">Please select</option>
                <option value="textbox">textbox</option>
                <option value="checkbox">checkbox</option>
                <option value="radio">radio button</option>
                </select>
            <select title="ddmenu" class="dropbtn" id="type2">
                <option selected disabled hidden value="Please select">Please select</option>
                <option value="none">none</option>
                <option value="mandatory">mandatory</option>
                <option value="number">numeric</option>
            </select>

        <input type="button"  id="adddugme" class="dropbtn2" value="Add"  onclick="mojaFunkcija()"/>

        <button id="addButton" class='dropbtn'>Save</button>

Body:
The issue is that you are executing the code only one time.

Put it inside a loop.

Here, I made a loop to execute the same code x times where x is the number user entered in the form

Check the snippet

var i = 0;
var a = 1;
function mojaFunkcija() {
    var type1 = document.getElementById('type1').value;
    var type2 = document.getElementById('type2').value;
    var question = document.getElementById('question').value;
    var i=0;
    while(i<question){
       var counter = 'Element';
       counter+= a;
       var prviElement=document.createElement('span');
       prviElement.textContent= counter + ':' +'  ';
       document.body.appendChild(prviElement);
       var pitanje= document.createElement('span');
       var unos='unos';
        unos += i;
        pitanje.id=unos;
       pitanje.textContent=(i+1) + ' ';
        document.body.appendChild(pitanje);
        var tip1 = document.createElement("input");
        var element='element';
        element += i;
        tip1.id=element;
        if (type1=='textbox') {
           tip1.type=type2
        } else {
            tip1.type=type1
         }
          document.body.appendChild(tip1);
          var linija1= document.createElement("br");
          document.body.appendChild(linija1);
          var linija2= document.createElement("br");
          document.body.appendChild(linija2);
          i++;
          a++;
       }
     }

function AddTextBox(elm) {
    var v = elm.value;
    var iCounter = elm.id.replace('type1', '');

    if (v == 'radio') {
        var textbox = document.createElement('input');
        textbox.type = 'text';
        textbox.id = 'txtSecond' + iCounter;
        elm.parentNode.insertBefore(textbox, elm.nextSibling);
    } else {
        //Ovaj kod ce da izbrise Textbox u slucaju da se izabere druga opcija.
        var rmv = document.getElementById('txtSecond' + iCounter);
        if (rmv != undefined) {
            rmv.remove();
        }
    }
}

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="pepo.css">
    <meta charset="UTF-8">
    <script src="basa.js"></script>
    <title>OnlineForms</title>
    </head>
<body>
    <!--Ovaj kod je za Main Page-->
    <Main class="kocka">
        <div align="left">
            <input type="button" class="dropbtn" value="Administration" onClick="window.location.reload();return false;"/>
            &emsp;&emsp;&emsp;&emsp;&emsp;&emsp;
            <button class="dropbtn" id="getAllButton">Forms</button>
        </div>
        <br>
        <div align="left">
            <input type="number" id="key" class="dropbtn"  Placeholder="Type the key value"/>
            <button class="dropbtn" id="getButton"> Search </button>
            <br>
            <br>
        </div>
    </Main>
    <!--Ovaj kod je za Elemente-->
    <div id="element" class="hide">
            <h1>Element <input type="text" class="dropbtn" id="question" value="" Placeholder="Type your question here"/>
            <select title="ddmenu" class="dropbtn" id="type1" onChange="AddTextBox(this)">
                <option selected disabled hidden value="Please select">Please select</option>
                <option value="textbox">textbox</option>
                <option value="checkbox">checkbox</option>
                <option value="radio">radio button</option>
                </select>
            <select title="ddmenu" class="dropbtn" id="type2">
                <option selected disabled hidden value="Please select">Please select</option>
                <option value="none">none</option>
                <option value="mandatory">mandatory</option>
                <option value="number">numeric</option>
            </select>
            </h1>
        <input type="button"  id="adddugme" class="dropbtn2" value="Add"  onclick="mojaFunkcija()"/>
        <br>
        <br>
        <button id="addButton" class='dropbtn'>Save</button>
        </div>
    <br>
    <br>
<div id="status"></div>
    <br>
<div id="status2"></div>
</body>
</html>


问:
Project Reference Problem, Visual Studio 2010
I have a solution that has one class library project, and the others are WPF applications.   I have added class library's reference the but, but both of them cannot use its classes.

So, what is the problem?

NOTE: sorry for tags, it's safari's problem.

答:
Things to check:

The class library classes are public

You have an appropriate using directive in your calling code:

```<code>using MyCompany.ClassLibrary;
</code>```

If that doesn't help, please post what happens when you try to use the classes from the library.

ContentLicense: CC BY-SA 2.5

Body:
Things to check:

The class library classes are public

You have an appropriate using directive in your calling code:

using MyCompany.ClassLibrary;

If that doesn't help, please post what happens when you try to use the classes from the library.


问:
Bootstrap font scaling too small on mobile
I've spent a lot of time working with Foundation and less time working with Bootstrap.  I'm having an issue with responsiveness in Bootstrap that I don't understand because this just seems to work in Foundation.  The issue is that, while the grid responsiveness works as expected, my fonts are getting scaled so tiny that it is almost illegible on mobile.  Notice in my example below that I set the font size to 14px, but on mobile this is becoming very tiny.  You can see this by clicking on the mobile button in the Chrome dev tools.

The html to reproduce this is very simple, here is a jsbin: http://jsbin.com/lumepumufu/1/

And here's the html:

```<code><html>
  <head>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
  </head>
  <body style="font-size:14px">
    <div class="container">
      <div class="row">
        <div class="col-lg-4">col-lg-4</div>
        <div class="col-lg-4">col-lg-4</div>
        <div class="col-lg-4">col-lg-4</div>
      </div>
    </div>
  </body>
</html>
</code>```

答: If you are running a rails app, you can try the gem rails_layout</p>

Body:
I've spent a lot of time working with Foundation and less time working with Bootstrap.  I'm having an issue with responsiveness in Bootstrap that I don't understand because this just seems to work in Foundation.  The issue is that, while the grid responsiveness works as expected, my fonts are getting scaled so tiny that it is almost illegible on mobile.  Notice in my example below that I set the font size to 14px, but on mobile this is becoming very tiny.  You can see this by clicking on the mobile button in the Chrome dev tools.

The html to reproduce this is very simple, here is a jsbin: http://jsbin.com/lumepumufu/1/

And here's the html:

    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

col-lg-4

col-lg-4

col-lg-4


问:
CSS3 Rounded corner for input element without js/images
Who I can make the rounded corner for input elements?

I need a way without using javascript and images..

Added:

```<code><!DOCTYPE html>
<html>
<head>
    <title>xx</title>
<style type="text/css">
input
{
    -webkit-border-radius: 15px;
    -moz-border-radius: 15px;
    border-radius: 15px;
}
</style>
</head>
<body>
<input type="text" value="test" />
</body>
</html>
</code>```

It does not work in firefox 3.6.12!

答:
CSS3 has many new features that benefit web designers. This includes border rounding:

```<code>input
{
    -webkit-border-radius: 5px; //For Safari, etc.
    -moz-border-radius: 5px; //For Mozilla, etc.
    border-radius: 5px; //CSS3 Feature
}
</code>```

You can add a class to your input fields and use that class in this CSS snippet to target certain input elements.

Internet Explorer 8 does not support CSS3. Internet Explorer 9 will hopefully include all of its features.

In regard to your edited question:

"text/css/" should be "text/css".

Body:
Who I can make the rounded corner for input elements?

I need a way without using javascript and images..

Added:

<!DOCTYPE html>

    <title>xx</title>

<input type="text" value="test" />

It does not work in firefox 3.6.12!

Body:
CSS3 has many new features that benefit web designers. This includes border rounding:

input
{
    -webkit-border-radius: 5px; //For Safari, etc.
    -moz-border-radius: 5px; //For Mozilla, etc.
    border-radius: 5px; //CSS3 Feature
}

You can add a class to your input fields and use that class in this CSS snippet to target certain input elements.

Internet Explorer 8 does not support CSS3. Internet Explorer 9 will hopefully include all of its features.

In regard to your edited question:

"text/css/" should be "text/css".


问:
No known class method for selector 'circleOfButtons:buttonSize:radius:'
A function circleOfButtons:buttonSize:radius: in SGView (below) is called from ParentView and I want ParentView to define the values inside SGView whenever ParentView sends a message to SGView.

This is the implementation file.

```<code>#import <UIKit/UIKit.h>
#import “ParentView.h"
#import "SGView.h"

@implementation ParentView : UIView

- (id)initWithFrame:(CGRect)frame {
    self                        = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {

    self.backgroundColor        = [UIColor lightGrayColor];

    int     count               = 5;
    CGFloat size                = 80.0;
    CGFloat radius              = 68;

    SGView *myView              = [SGView circleOfButtons:count buttonSize:size radius:radius];
    [self addSubview:myView];
    }
return self;
}
</code>```

SGView arranges multiple UIButtons in a circle and is essentially like this

```<code>#import "SGView.h"

@implementation SGView : UIView

+(id)circleOfButtons:(int)buttonCount buttonSize:(CGFloat)buttonSize circleRadius:(CGFloat)circleRadius
    {
    UIView *multipleViews       = [self new];

    // … circular geometry …
    [multipleViews addSubview:circleButton];
    }
    return multipleViews;
}
@end
</code>```

The error message - at the line SGView *myView - is:

No known class method for selector
  'circleOfButtons:buttonSize:radius:'

My guess is the compiler wants a declaration in the interface. I’m working through these tutorials trying to decide what the interface file should look like and though there are 6 SO questions that may already have answered my question, only this one had an example that seemed vaguely relevant.

This is my interface file.

```<code>#import <UIKit/UIKit.h>
#import "ViewController.h"
#import "SGView.h"

@interface ParentView : UIView {
}

+(id)circleOfButtons:(int)buttonCount buttonSize:(CGFloat)buttonSize circleRadius:(CGFloat)circleRadius;

@end
</code>```

Can anyone please give an example showing what this interface file should look like ? Thanks.

UPDATE

Here is SGView.h (revised)

```<code>#import <UIKit/UIKit.h>
@interface SGView : UIView {
}
+(id)circleOfButtons:(int)buttonCount buttonSize:(CGFloat)buttonSize circleRadius:(CGFloat)circleRadius;
@end
</code>```

I also noticed if the statement

```<code>        SGView *myView              = [SGView circleOfButtons:count buttonSize:size radius:radius];
</code>```

is changed to

```<code>        SGView *myView              = [self circleOfButtons:count buttonSize:size radius:radius];
</code>```

the error changes to

No visible @interface for 'ParentView' declares the selector 'circleOfButtons:buttonSize:radius:'

it was previously

No known class method for selector 'circleOfButtons:buttonSize:radius:'

答:
You are calling </p>

```<code>  SGView *myView              = [SGView circleOfButtons:count buttonSize:size radius:radius];
</code>```

<p>It should be </p>

```<code>SGView *myView              = [SGView circleOfButtons:count buttonSize:size circleRadius:radius];
</code>```

Body:
A function circleOfButtons:buttonSize:radius: in SGView (below) is called from ParentView and I want ParentView to define the values inside SGView whenever ParentView sends a message to SGView.

This is the implementation file.

#import <UIKit/UIKit.h>
#import “ParentView.h"
#import "SGView.h"

@implementation ParentView : UIView

- (id)initWithFrame:(CGRect)frame {
    self                        = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {

    self.backgroundColor        = [UIColor lightGrayColor];

    int     count               = 5;
    CGFloat size                = 80.0;
    CGFloat radius              = 68;

    SGView *myView              = [SGView circleOfButtons:count buttonSize:size radius:radius];
    [self addSubview:myView];
    }
return self;
}

SGView arranges multiple UIButtons in a circle and is essentially like this

#import "SGView.h"

@implementation SGView : UIView

+(id)circleOfButtons:(int)buttonCount buttonSize:(CGFloat)buttonSize circleRadius:(CGFloat)circleRadius
    {
    UIView *multipleViews       = [self new];

    // … circular geometry …
    [multipleViews addSubview:circleButton];
    }
    return multipleViews;
}
@end

The error message - at the line SGView *myView - is:

No known class method for selector
  'circleOfButtons:buttonSize:radius:'

My guess is the compiler wants a declaration in the interface. I’m working through these tutorials trying to decide what the interface file should look like and though there are 6 SO questions that may already have answered my question, only this one had an example that seemed vaguely relevant.

This is my interface file.

#import <UIKit/UIKit.h>
#import "ViewController.h"
#import "SGView.h"

@interface ParentView : UIView {
}

+(id)circleOfButtons:(int)buttonCount buttonSize:(CGFloat)buttonSize circleRadius:(CGFloat)circleRadius;

@end

Can anyone please give an example showing what this interface file should look like ? Thanks.

UPDATE

Here is SGView.h (revised)

#import <UIKit/UIKit.h>
@interface SGView : UIView {
}
+(id)circleOfButtons:(int)buttonCount buttonSize:(CGFloat)buttonSize circleRadius:(CGFloat)circleRadius;
@end

I also noticed if the statement

        SGView *myView              = [SGView circleOfButtons:count buttonSize:size radius:radius];

is changed to

        SGView *myView              = [self circleOfButtons:count buttonSize:size radius:radius];

the error changes to

No visible @interface for 'ParentView' declares the selector 'circleOfButtons:buttonSize:radius:'

it was previously

No known class method for selector 'circleOfButtons:buttonSize:radius:'

Body:
You are calling

  SGView *myView              = [SGView circleOfButtons:count buttonSize:size radius:radius];

It should be

SGView *myView              = [SGView circleOfButtons:count buttonSize:size circleRadius:radius];


答:
You can do these stuff by give route to every method call of your controller
methods like this -:

For example your controller is
Mobile.php

```<code>defined('BASEPATH') OR exit('No direct script access allowed');
class Mobile extends CI_Controller {
public function getMobiles()
{
    $uri_3 = $this->uri->segment(3);
    $uri_4 = $this->uri->segment(4);

    if($uri_3 !="" &&  $uri_4 =="" ){
        //make search by mobile brand ,like apple
        echo $uri_3;die;
    }else if($uri_3 !="" & $uri_4 !=""){
        echo $uri_3.'-'.$uri_4; die;
        //make search by brand and new , like apple/new
    }else{
        //make search for all mobile brand by default
        echo 'All';die;
    }
  }
}
</code>```

and the route.php file should be like this-:

```<code>$route['search/mobile-phone'] = 'Mobile/getMobiles';
$route['search/mobile-phone/(:any)'] = 'Mobile/getMobiles';
$route['search/mobile-phone/(:any)/(:any)'] = 'Mobile/getMobiles';
</code>```

Url should be like this -:

```<code>http://localhost:90/ci_test/index.php/search/mobile-phone/apple/new
</code>```

if you are not using index.php in url then your uri segments would be change so be care full for that

```<code>http://localhost:90/ci_test/index.php/search/mobile-phone/apple/new
O/P- apple-new

http://localhost:90/ci_test/index.php/search/mobile-phone/apple/
O/P- apple

http://localhost:90/ci_test/index.php/search/mobile-phone/
O/P- All
</code>```

Title: CodeIgniter URL Query String Manipulation

Body:
I have a E-Commerce Website build using CodeIgniter 2.3.

Please suggest how can I manipulate the URLs in the given sequence:-

Say a Person Searches for "Mobile Phones".
URL must be xyz.com/search/mobile-phone, which displays all the Mobile Phones from our Database.
I am already aware of the Search controller and use Routing to exclude the function name from the URL

Next the Person uses filtering by name of Mobile Phone Companies. Suppose he chooses "Apple". The URL must become xyz.com/search/mobile-phones/apple

Next the Person again filters by Condition ie "New" or "Refurbished". The URL must become xyz.com/search/mobile-phones/apples/new

The URLs need to be Functional URLs so that, if I pass the URL xyz.com/search/mobile-phones/apples/new to someone externally, he/she should be able to see the same result set as the person who came after Search & Filtering.

I am non-technical so may be I couldnt explain my problem very technically, but be assured, my Tech Person would be reading your suggestions.

Further Details

We are already using URI Segmentation, Routing & Post Method. But that way we are facing issues wrt Point #4 mentioned above

Body:
You can do these stuff by give route to every method call of your controller
methods like this -:

For example your controller is
Mobile.php

defined('BASEPATH') OR exit('No direct script access allowed');
class Mobile extends CI_Controller {
public function getMobiles()
{
    $uri_3 = $this->uri->segment(3);
    $uri_4 = $this->uri->segment(4);

    if($uri_3 !="" &&  $uri_4 =="" ){
        //make search by mobile brand ,like apple
        echo $uri_3;die;
    }else if($uri_3 !="" & $uri_4 !=""){
        echo $uri_3.'-'.$uri_4; die;
        //make search by brand and new , like apple/new
    }else{
        //make search for all mobile brand by default
        echo 'All';die;
    }
  }
}

and the route.php file should be like this-:

$route['search/mobile-phone'] = 'Mobile/getMobiles';
$route['search/mobile-phone/(:any)'] = 'Mobile/getMobiles';
$route['search/mobile-phone/(:any)/(:any)'] = 'Mobile/getMobiles';

Url should be like this -:

http://localhost:90/ci_test/index.php/search/mobile-phone/apple/new

if you are not using index.php in url then your uri segments would be change so be care full for that

http://localhost:90/ci_test/index.php/search/mobile-phone/apple/new
O/P- apple-new

http://localhost:90/ci_test/index.php/search/mobile-phone/apple/
O/P- apple

http://localhost:90/ci_test/index.php/search/mobile-phone/
O/P- All


问:
Loop through hosts with ansible
I have a problem to find a working solution to loop over my inventory.
I start my playbook with linking a intentory file:

ansible-playbook -i inventory/dev.yml playbook.yml

My playbook looks like this:

```<code>---
- hosts: localhost
  tasks:
    - name: Create VM if enviro == true
      include_role:
        name: local_vm_creator
      when: enviro == 'dev'
</code>```

So when loading the playbook the variable enviro is read from host_vars and sets the when condition to dev. The inventory file dev.yml looks like this:

```<code>[local_vm]
192.168.99.100
192.168.99.101
192.168.99.102

[local_vm_manager_1]
192.168.99.103

[local_vm_manager_2]
192.168.99.104

[local-all:children]
local_vm
local_vm_manager_1
local_vm_manager_2
</code>```

My main.yml in my role local_vm_creator looks like this:

```<code>---
- name: Create test host
  local_action: shell docker-machine create -d virtualbox {{ item }}
  with_items:
    - node-1
    - node-2
    - node-3
    - node-4
    - node-5

- debug: msg="host is {{item}}"
  with_items:  groups['local_vm']
</code>```

And the problem is that i can't get the listed servers from the dev.yml inventory file.

it just returns:

ok: [localhost] => (item=groups['local_vm']) => {
      "item": "groups['local_vm']",
      "msg": "host is groups['local_vm']" }

答:
If the only problem is with_items loop, replace it with:

```<code>with_items: "{{ groups['local_vm'] }}"
</code>```

and you are good to go. Bare variables are not supported in with_ any more.

Title: Loop through hosts with ansible

Body:
I have a problem to find a working solution to loop over my inventory.
I start my playbook with linking a intentory file:

ansible-playbook -i inventory/dev.yml playbook.yml

My playbook looks like this:

---
- hosts: localhost
  tasks:
    - name: Create VM if enviro == true
      include_role:
        name: local_vm_creator
      when: enviro == 'dev'

So when loading the playbook the variable enviro is read from host_vars and sets the when condition to dev. The inventory file dev.yml looks like this:

[local_vm]
192.168.99.100
192.168.99.101
192.168.99.102

[local_vm_manager_1]
192.168.99.103

[local_vm_manager_2]
192.168.99.104

[local-all:children]
local_vm
local_vm_manager_1
local_vm_manager_2

My main.yml in my role local_vm_creator looks like this:

---
- name: Create test host
  local_action: shell docker-machine create -d virtualbox {{ item }}
  with_items:
    - node-1
    - node-2
    - node-3
    - node-4
    - node-5

- debug: msg="host is {{item}}"
  with_items:  groups['local_vm']

And the problem is that i can't get the listed servers from the dev.yml inventory file.

it just returns:

ok: [localhost] => (item=groups['local_vm']) => {
      "item": "groups['local_vm']",
      "msg": "host is groups['local_vm']" }

Body:
If the only problem is with_items loop, replace it with:

with_items: "{{ groups['local_vm'] }}"

and you are good to go. Bare variables are not supported in with_ any more.


问:
Java: how to trace/monitor GC times for the CMS garbage collector?
I'm having trouble figuring out a way to monitor the JVM GC for memory exhaustion issues.

With the serial GC, we could just look at the full GC pause times and have a pretty good notion if the JVM was in trouble (if it took more than a few seconds, for example).

CMS seems to behave differently.

When querying lastGcInfo from the java.lang:type=GarbageCollector,name=ConcurrentMarkSweep MXBean (via JMX), the reported duration is the sum of all GC steps, and is usually several seconds long. This does not indicate an issue with GC, to the contrary, I've found that too short GC times are usually more of an indicator of trouble (which happens, for example, if the JVM goes into a CMS-concurrent-mark-start-> concurrent mode failure loop).

I've tried jstat as well, which gives the cumulative time spent garbage collecting (unsure if it's for old or newgen GC). This can be graphed, but it's not trivial to use for monitoring purposes. For example, I could parse jstat -gccause output and calculate differences over time, and trace+monitor that (e.g. amount of time spent GC'ing over the last X minutes).

I'm using the following JVM arguments for GC logging:

```<code>-Xloggc:/xxx/gc.log
-XX:+PrintGCDetails
-verbose:gc
-XX:+PrintGCDateStamps
-XX:+PrintReferenceGC
-XX:+PrintPromotionFailure
</code>```

Parsing gc.log is also an option if nothing else is available, but the optimal solution would be to have a java-native way to get at the relevant information.

The information must be machine-readable (to send to monitoring platforms) so visual tools are not an option. I'm running a production environment with a mix of JDK 6/7/8 instances, so version-agnostic solutions are better.

Is there a simple(r) way to monitor CMS garbage collection? What indicators should I be looking at?

答:
Fundamentally one wants two things from the CMS concurrent collector

the throughput of the concurrent cycle to keep up with the promotion rate, i.e. the objects surviving into the old gen per unit of time

enough room in the old generation for objects promoted during a concurrent cycle

So let's say the IHOP is fixed to 70% then you probably are approaching a problem when it reaches >90% at some point. Maybe even earlier if you do some large allocations that don't fit into the young generation or outlive it (that's entirely application-specific).
Additionally you usually want it to spend more time outside the concurrent cycle than in it, although that depends on how tightly you tune the collector, in principle you could have the concurrent cycle running almost all the time, but then you have very little throughput margin and burn a lot of CPU time on concurrent collections.

If you really really want to avoid even the occasional Full GC then you'll need even more safety margins due to fragmentation (CMS is non-compacting). I think this can't be monitored via MX beans, you'll have to to enable some CMS-specific GC logging to get fragmentation info.

Body:
I'm having trouble figuring out a way to monitor the JVM GC for memory exhaustion issues.

With the serial GC, we could just look at the full GC pause times and have a pretty good notion if the JVM was in trouble (if it took more than a few seconds, for example).

CMS seems to behave differently.

When querying lastGcInfo from the java.lang:type=GarbageCollector,name=ConcurrentMarkSweep MXBean (via JMX), the reported duration is the sum of all GC steps, and is usually several seconds long. This does not indicate an issue with GC, to the contrary, I've found that too short GC times are usually more of an indicator of trouble (which happens, for example, if the JVM goes into a CMS-concurrent-mark-start-> concurrent mode failure loop).

I've tried jstat as well, which gives the cumulative time spent garbage collecting (unsure if it's for old or newgen GC). This can be graphed, but it's not trivial to use for monitoring purposes. For example, I could parse jstat -gccause output and calculate differences over time, and trace+monitor that (e.g. amount of time spent GC'ing over the last X minutes).

I'm using the following JVM arguments for GC logging:

-Xloggc:/xxx/gc.log
-XX:+PrintGCDetails
-verbose:gc
-XX:+PrintGCDateStamps
-XX:+PrintReferenceGC
-XX:+PrintPromotionFailure

Parsing gc.log is also an option if nothing else is available, but the optimal solution would be to have a java-native way to get at the relevant information.

The information must be machine-readable (to send to monitoring platforms) so visual tools are not an option. I'm running a production environment with a mix of JDK 6/7/8 instances, so version-agnostic solutions are better.

Is there a simple(r) way to monitor CMS garbage collection? What indicators should I be looking at?


问:
How to make "assign places to people" editor as usable as possible
So we have places and we have people. the added complexity is additional metadata attached to each link between each pair. Like date range when a person spent at a particular place.

I know. Lots of data and many possibilities.

One way of doing this is by having a list of people and when you click on one, a modal dialog opens, where a list of places is displayed. When you select a place, you also have to enter a date range.

From a usability perspective and quick relation editor this is almost definitely not the optimal solution. User focus changes several times and that slows things down + makes users tired since they have to be very concentrated and focused = higher rate of human error.

I would like to avoid dialogs. Do you maybe know of a website where a similar thing is done = two entities need to be related with additional metadata.

The main requirements of this page are:

simplicity

avoid modal dialogs if possible

What I'm trying to do: many-to-many editor with additional metadata data on each pair.

Questions

What would you suggest? Provide any ideas (even dumn ones).

Do you know of a public site (so it can be checked) that has this kind of scenario implemented?

答:
doesn't this come down to two operations select and connect. you'd select some group of people or places via a number of different paths string search, time, space, or such and then you'd connect them by creating some record

note that useful relations aren't just between one person and another or one place and a person or just one place and another although when storing these they can all be reduced to a->b tuples but this can be ignored if the relations you have only have one person place and time

this sort of reminds me of Entity Workspace but in that case they were dealing with data collection in the domain of crime investigation so they had names addresses phone numbers dates and such as base types which in their setup were drag and drop on to cards

so if you took that you could have a center file and a list of people after some filtering to add that one to this set you'd drag it from the list and like wise from the places you'd have another list to drag from

commonly referenced ones might be shown in another place and this would work a bit like putting the toppings on a pizza and when your done you put it in the oven or commit it if you want to later undo this it would keep the set together so you can remove it later if you didn't want it or you can add something

and this wouldn't have any of the dialogs you suggest and as such it could be called mode-less


问:
How to create a rule-based access control unit for different user types
I'm trying to implement a Role-based Access Control Unit for my app but don't know how to do it given my constraints.

I use Devise for my sign in/up operations. I have only one model User but every user has a different user_type. I have eight unique user types with different authentication levels (integer).

These are the constraints on how users interact with the site:

Users with higher authentication levels can perform their related user types with lower authentication levels functions, i.e., access to their related controllers and do stuff.

Not every user type with the same authentication levels can access the same controller: user1 with auth_level = 2 can access to controller C1 but user2 with the same auth_level = 2 can access controller C2. Other way to say it is that they are doing different jobs at the same level.

Is there any gem to implement such things? I've looked into CanCan it does not satisfy my needs.

If there is no gem, what approach/design do you suggest to implement such access control unit?

答:
Since I asked this question a couple of days ago, for some time I wonder around and evaluating available gems, suitable for my purpose but I couldn't find any simple, easy-to-use and lightweight enough to import it into my application; So I accepted the fight and wrote my own gem named ACU (Access Control Unit), which satisfies my constraints in the question + it's very lightweight and easy-to-use and general for any purposes.

In this gem, every request is either gets passed through or not, and the access rules can cover any aspect of the rails app. the following is an example of the rules set, for more details you can see the documentation provided at here.

```<code># config/initializers/acu_rules.rb
Acu::Rules.define do
  # anyone makes a request could be count as everyone!
  whois :everyone { true }

  whois :admin, args: [:user] { |c| c and c.user_type == :ADMIN.to_s }

  whois :client, args: [:user] { |c| c and c.user_type == :CLIENT.to_s }

  # any request that doesn't match with a rule will be denied by default;
  # but this can be configured to not to!

  # the default namespace
  namespace do
    controller :home, except: [:some_secret_action] do
      allow :everyone
    end
    controller :home do
      allow [:admin, :client], on: [:some_secret_action]
    end
  end

  # the admin namespace
  namespace :admin do
    allow :admin

    controller :contact, only: [:send_message] do
      allow :everyone
    end

    controller :contact do
      action :support {
        allow :client
      }
    end
  end
end
</code>```

Body:
Since I asked this question a couple of days ago, for some time I wonder around and evaluating available gems, suitable for my purpose but I couldn't find any simple, easy-to-use and lightweight enough to import it into my application; So I accepted the fight and wrote my own gem named ACU (Access Control Unit), which satisfies my constraints in the question + it's very lightweight and easy-to-use and general for any purposes.

In this gem, every request is either gets passed through or not, and the access rules can cover any aspect of the rails app. the following is an example of the rules set, for more details you can see the documentation provided at here.

# config/initializers/acu_rules.rb
Acu::Rules.define do
  # anyone makes a request could be count as everyone!
  whois :everyone { true }

  whois :admin, args: [:user] { |c| c and c.user_type == :ADMIN.to_s }

  whois :client, args: [:user] { |c| c and c.user_type == :CLIENT.to_s }

  # any request that doesn't match with a rule will be denied by default;
  # but this can be configured to not to!

  # the default namespace
  namespace do
    controller :home, except: [:some_secret_action] do
      allow :everyone
    end
    controller :home do
      allow [:admin, :client], on: [:some_secret_action]
    end
  end

  # the admin namespace
  namespace :admin do
    allow :admin

    controller :contact, only: [:send_message] do
      allow :everyone
    end

    controller :contact do
      action :support {
        allow :client
      }
    end
  end
end


问:
How can i load a custom component in another component dynamically in the same view rather than just use its elememt selector in template
For example, if I have written a popup component,and now I want to use it in another component in which case it will be triggered and loaded dynamically in the same view when I trigger a wrong action. But now I find no good way to handle it.</p>

答: You can use <router-outlet></router-outlet> to render any custom component in a view.


问:
Light-weight Continuous Integration Server for .NET
I want to set up a CI server for a personal project I'm doing with some colleagues as a learning exercise.

I've a virtual server we can use for the CI server but its rather low on resources (CPU/RAM and HDD).

Which .NET CI solution has the smallest footprint (I'm thinking Hudson)? I've seen plenty of threads comparing them, but nothing really on the resource usage.

答: I will confirm your statement for using Hudson. It is very easy to configure and use, it will take no more than an hour to have it up and running. For more serious projects (again open source) i will go with CruiseControl.NET. One constraint of using Hudson as CI is the small number of plug-ins that are available for .NET code. But. the major ones are there. Go with it.</p>


问:
How to distribute a 200MB database to a locally executed HTML5 web page
I am building a search tool that is designed to be run at my organization. My deployment strategy is:

HTML5 web page that's stored on the file server.

200MB JSON or JavaScript file that's in another file.

Right now the 200MB file is a .js file with statements like:

```<code>var data = {....};
</code>```

Where {....} is about 200MB in size. This is working on Apple Safari on a Mac but it causes performance problems on Chrome. Firefox takes several minutes to load, but then it's fine. It seems like a memory problem.

Another option is to store it in a .json file and to load it with JQuery.

Is there a better way to do this?  The 200MB file contains several hundred thousand records.

EDIT YES, the entire database must be local, because I do not have a web server with backend logic.

ALSO, it is unclear to me at the moment if the 200MB object is better distributed as a JSON Object or as an Array.

EDIT I've now determined that I can't store it in a JSON object, because you can't use JQuery to read a file:// URL (even if the HTML comes from a file:// URL). So now my plan is to encode the 200MB file as 200,000 1K statements that insert the values into a {}.

答:
I suggest you to store data in some database in this case.

Your search-tool must send input data from client's browser and then your server must return response in json format that you need. This is most common solution for big data

Body:
I am building a search tool that is designed to be run at my organization. My deployment strategy is:

HTML5 web page that's stored on the file server.

200MB JSON or JavaScript file that's in another file.

Right now the 200MB file is a .js file with statements like:

var data = {....};

Where {....} is about 200MB in size. This is working on Apple Safari on a Mac but it causes performance problems on Chrome. Firefox takes several minutes to load, but then it's fine. It seems like a memory problem.

Another option is to store it in a .json file and to load it with JQuery.

Is there a better way to do this?  The 200MB file contains several hundred thousand records.

EDIT YES, the entire database must be local, because I do not have a web server with backend logic.

ALSO, it is unclear to me at the moment if the 200MB object is better distributed as a JSON Object or as an Array.

EDIT I've now determined that I can't store it in a JSON object, because you can't use JQuery to read a file:// URL (even if the HTML comes from a file:// URL). So now my plan is to encode the 200MB file as 200,000 1K statements that insert the values into a {}.


问:
Error using ASSERT in pig
I'm trying to use ASSERT operator in Pig, but facing issue.

```<code>A = LOAD 'data' AS (a0:int,a1:int,a2:int);
DUMP A;

(1,2,3)
(4,2,1)
(8,3,4)
(4,3,3)
(7,2,5)
(8,4,3)

ASSERT A by a0 > 0 'a0 should be greater than 0';
</code>```

Below is the log:

ERROR 1000: Error during parsing. Encountered "  "ASSERT
  "" at line 3, column 1.`  Was expecting one of:

"cat" ...

"clear" ...

.... org.apache.pig.tools.pigscript.parser.ParseException: Encountered "   "ASSERT "" at line 3, column 1.

Kindly help

答:
ASSERT operator keywords has been developed since 0.12.0. However, it did not work and was fixed with Patch PIG-3367.patch. Though, it's still claimed that ASSERT is supported from 0.12.0, the patch was only released to 0.12.1 and 0.13.0. So, updated your pig if you want to use ASSERT.

https://issues.apache.org/jira/browse/PIG-3670

Title: Error using ASSERT in pig

Body:
I'm trying to use ASSERT operator in Pig, but facing issue.

A = LOAD 'data' AS (a0:int,a1:int,a2:int);
DUMP A;

(1,2,3)
(4,2,1)
(8,3,4)
(4,3,3)
(7,2,5)
(8,4,3)

ASSERT A by a0 > 0 'a0 should be greater than 0';

Below is the log:

ERROR 1000: Error during parsing. Encountered "  "ASSERT
  "" at line 3, column 1.`  Was expecting one of:

"cat" ...

"clear" ...

.... org.apache.pig.tools.pigscript.parser.ParseException: Encountered "   "ASSERT "" at line 3, column 1.

Kindly help


问:
Freecharge wallet integration in android
I am working in Freecharge wallet integration in android. we purchased an merchant id and integration key too.

I followed the instruction given in the Freecharge guide but I stuck with an error message in my log as "Invalid checksum/Checksum mismatch"

At present I am waiting for the freecharge customer care to reply for the error

Kindly help me to get through this issue if any of you as integrated this freecharge wallet integration.

I cameup with the screenshot of the code and the error log

Code

Code Continue...

Error Log

答:
Hi I got the same issue.

Generate the checksum through this code.

```<code>private void generateChecksum(String merchantKey) {

    JSONObject jsonObject = new JSONObject();

    checksumObj = new ChecksumObj(mEdtAmount.getText().toString(), "ANDROID", mEdtEmail.getText().toString(),
            "https://www.google.com", "merchantID", getTransactionID(), mEdtMobile.getText().toString(), "auth", "https://www.google.com");

    try {
        jsonObject.put("amount", checksumObj.getAmount());
        jsonObject.put("channel", checksumObj.getChannel());
        jsonObject.put("email", checksumObj.getEmail());
        jsonObject.put("furl", checksumObj.getFurl());
        jsonObject.put("merchantId", checksumObj.getMerchantId());
        jsonObject.put("merchantTxnId", checksumObj.getMerchantTxnId());
        jsonObject.put("mobile", checksumObj.getMobile());
        jsonObject.put("productInfo", checksumObj.getProductInfo());
        jsonObject.put("surl", checksumObj.getSurl());

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

    String plainText = jsonObject.toString().concat(merchantKey).replace("\\/", "/");

    MessageDigest md = null;

    try {
        md = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    md.update(plainText.getBytes(Charset.defaultCharset()));
    byte[] mdbytes = md.digest();

    // convert the byte to hex format method 1

    StringBuffer checksum = new StringBuffer();
    for (int i = 0; i < mdbytes.length; i++) {
        checksum.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
    }

    jsonCheckSum = checksum.toString();

    requestMap();

}
</code>```

CheckSumObj which implements Serializable.

```<code>public class ChecksumObj implements Serializable {
String amount, channel, customerName, email, furl, merchantId, merchantTxnId, mobile, productInfo, surl;

public ChecksumObj(String amount, String channel, String email, String furl, String merchantId, String merchantTxnId, String mobile, String productInfo, String surl) {
    this.amount = amount;
    this.channel = channel;
    this.email = email;
    this.furl = furl;
    this.merchantId = merchantId;
    this.merchantTxnId = merchantTxnId;
    this.mobile = mobile;
    this.productInfo = productInfo;
    this.surl = surl;
}

public String getAmount() {
    return amount;
}

public void setAmount(String amount) {
    this.amount = amount;
}

public String getChannel() {
    return channel;
}

public void setChannel(String channel) {
    this.channel = channel;
}

public String getCustomerName() {
    return customerName;
}

public void setCustomerName(String customerName) {
    this.customerName = customerName;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getFurl() {
    return furl;
}

public void setFurl(String furl) {
    this.furl = furl;
}

public String getMerchantId() {
    return merchantId;
}

public void setMerchantId(String merchantId) {
    this.merchantId = merchantId;
}

public String getMerchantTxnId() {
    return merchantTxnId;
}

public void setMerchantTxnId(String merchantTxnId) {
    this.merchantTxnId = merchantTxnId;
}

public String getMobile() {
    return mobile;
}

public void setMobile(String mobile) {
    this.mobile = mobile;
}

public String getProductInfo() {
    return productInfo;
}

public void setProductInfo(String productInfo) {
    this.productInfo = productInfo;
}

public String getSurl() {
    return surl;
}

public void setSurl(String surl) {
    this.surl = surl;
}}
</code>```

HashMap of request.

```<code>    private void requestMap() {
    checkoutRequestMap = new HashMap<>();
    checkoutRequestMap.put("amount", checksumObj.getAmount());
    checkoutRequestMap.put("channel", "ANDROID");
    checkoutRequestMap.put("email", checksumObj.getEmail());
    checkoutRequestMap.put("furl", "https://www.google.com");
    checkoutRequestMap.put("merchantId", "MerchantID");
    checkoutRequestMap.put("merchantTxnId", checksumObj.getMerchantTxnId());
    checkoutRequestMap.put("mobile", checksumObj.getMobile());
    checkoutRequestMap.put("productInfo", "auth");
    checkoutRequestMap.put("surl", "https://www.google.com");
    checkoutRequestMap.put("checksum", jsonCheckSum);

    FreeChargePaymentSdk.startSafePayment(FreeChargeMainActivity.this, checkoutRequestMap, freeChargePaymentCallback);

}
</code>```

TransactionID random.

```<code> private String getTransactionID() {

    SecureRandom random = new SecureRandom();

    return new BigInteger(48, random).toString(16) + mEdtMobile.getText().toString().substring(0, 5);

}
</code>```

FreeCharge callback.

```<code>  FreeChargePaymentCallback freeChargePaymentCallback = new FreeChargePaymentCallback() {

    @Override
    public void onTransactionFailed(HashMap<String, String> txnFailResponse) {
        Toast.makeText(FreeChargeMainActivity.this, txnFailResponse.get("errorMessage"), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onTransactionCancelled() {
        Toast.makeText(FreeChargeMainActivity.this, "user cancelled the transaction", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onTransactionSucceeded(HashMap<String, String> txnSuccessResponse) {
        Toast.makeText(FreeChargeMainActivity.this, txnSuccessResponse.get("status"), Toast.LENGTH_SHORT).show();
        mEdtMobile.setText("");
        mEdtAmount.setText("");
        mEdtEmail.setText("");
        clearFreeChargeCache();
    }

    @Override
    public void onErrorOccurred(FreechargeSdkException sdkError) {
        Toast.makeText(FreeChargeMainActivity.this, sdkError.getErrorMessage(), Toast.LENGTH_SHORT).show();
    }
};
</code>```

build.gradle(Project-level)

```<code>allprojects {
repositories {
    jcenter()
    maven {
        url "https://s3-ap-southeast-1.amazonaws.com/godel-release/godel/"
    }
}}
</code>```

build.gradle(app-level)

```<code>dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'in.freecharge.checkout.android:freecharge-checkout-android-sdk:2.2@aar'
compile 'in.juspay:godel:0.6.12.1423'
testCompile 'junit:junit:4.12'}
</code>```

Hope this help.Happy Coding.

Body:
Hi I got the same issue.

Generate the checksum through this code.

private void generateChecksum(String merchantKey) {

    JSONObject jsonObject = new JSONObject();

    checksumObj = new ChecksumObj(mEdtAmount.getText().toString(), "ANDROID", mEdtEmail.getText().toString(),
            "https://www.google.com", "merchantID", getTransactionID(), mEdtMobile.getText().toString(), "auth", "https://www.google.com");

    try {
        jsonObject.put("amount", checksumObj.getAmount());
        jsonObject.put("channel", checksumObj.getChannel());
        jsonObject.put("email", checksumObj.getEmail());
        jsonObject.put("furl", checksumObj.getFurl());
        jsonObject.put("merchantId", checksumObj.getMerchantId());
        jsonObject.put("merchantTxnId", checksumObj.getMerchantTxnId());
        jsonObject.put("mobile", checksumObj.getMobile());
        jsonObject.put("productInfo", checksumObj.getProductInfo());
        jsonObject.put("surl", checksumObj.getSurl());

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

    String plainText = jsonObject.toString().concat(merchantKey).replace("\\/", "/");

    MessageDigest md = null;

    try {
        md = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    md.update(plainText.getBytes(Charset.defaultCharset()));
    byte[] mdbytes = md.digest();

    // convert the byte to hex format method 1

    StringBuffer checksum = new StringBuffer();
    for (int i = 0; i < mdbytes.length; i++) {
        checksum.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
    }

    jsonCheckSum = checksum.toString();

    requestMap();

}

CheckSumObj which implements Serializable.

public class ChecksumObj implements Serializable {
String amount, channel, customerName, email, furl, merchantId, merchantTxnId, mobile, productInfo, surl;

public ChecksumObj(String amount, String channel, String email, String furl, String merchantId, String merchantTxnId, String mobile, String productInfo, String surl) {
    this.amount = amount;
    this.channel = channel;
    this.email = email;
    this.furl = furl;
    this.merchantId = merchantId;
    this.merchantTxnId = merchantTxnId;
    this.mobile = mobile;
    this.productInfo = productInfo;
    this.surl = surl;
}

public String getAmount() {
    return amount;
}

public void setAmount(String amount) {
    this.amount = amount;
}

public String getChannel() {
    return channel;
}

public void setChannel(String channel) {
    this.channel = channel;
}

public String getCustomerName() {
    return customerName;
}

public void setCustomerName(String customerName) {
    this.customerName = customerName;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getFurl() {
    return furl;
}

public void setFurl(String furl) {
    this.furl = furl;
}

public String getMerchantId() {
    return merchantId;
}

public void setMerchantId(String merchantId) {
    this.merchantId = merchantId;
}

public String getMerchantTxnId() {
    return merchantTxnId;
}

public void setMerchantTxnId(String merchantTxnId) {
    this.merchantTxnId = merchantTxnId;
}

public String getMobile() {
    return mobile;
}

public void setMobile(String mobile) {
    this.mobile = mobile;
}

public String getProductInfo() {
    return productInfo;
}

public void setProductInfo(String productInfo) {
    this.productInfo = productInfo;
}

public String getSurl() {
    return surl;
}

public void setSurl(String surl) {
    this.surl = surl;
}}

HashMap of request.

    private void requestMap() {
    checkoutRequestMap = new HashMap<>();
    checkoutRequestMap.put("amount", checksumObj.getAmount());
    checkoutRequestMap.put("channel", "ANDROID");
    checkoutRequestMap.put("email", checksumObj.getEmail());
    checkoutRequestMap.put("furl", "https://www.google.com");
    checkoutRequestMap.put("merchantId", "MerchantID");
    checkoutRequestMap.put("merchantTxnId", checksumObj.getMerchantTxnId());
    checkoutRequestMap.put("mobile", checksumObj.getMobile());
    checkoutRequestMap.put("productInfo", "auth");
    checkoutRequestMap.put("surl", "https://www.google.com");
    checkoutRequestMap.put("checksum", jsonCheckSum);

    FreeChargePaymentSdk.startSafePayment(FreeChargeMainActivity.this, checkoutRequestMap, freeChargePaymentCallback);

}

TransactionID random.

 private String getTransactionID() {

    SecureRandom random = new SecureRandom();

    return new BigInteger(48, random).toString(16) + mEdtMobile.getText().toString().substring(0, 5);

}

FreeCharge callback.

  FreeChargePaymentCallback freeChargePaymentCallback = new FreeChargePaymentCallback() {

    @Override
    public void onTransactionFailed(HashMap<String, String> txnFailResponse) {
        Toast.makeText(FreeChargeMainActivity.this, txnFailResponse.get("errorMessage"), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onTransactionCancelled() {
        Toast.makeText(FreeChargeMainActivity.this, "user cancelled the transaction", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onTransactionSucceeded(HashMap<String, String> txnSuccessResponse) {
        Toast.makeText(FreeChargeMainActivity.this, txnSuccessResponse.get("status"), Toast.LENGTH_SHORT).show();
        mEdtMobile.setText("");
        mEdtAmount.setText("");
        mEdtEmail.setText("");
        clearFreeChargeCache();
    }

    @Override
    public void onErrorOccurred(FreechargeSdkException sdkError) {
        Toast.makeText(FreeChargeMainActivity.this, sdkError.getErrorMessage(), Toast.LENGTH_SHORT).show();
    }
};

build.gradle(Project-level)

allprojects {
repositories {
    jcenter()
    maven {
        url "https://s3-ap-southeast-1.amazonaws.com/godel-release/godel/"
    }
}}

build.gradle(app-level)

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'in.freecharge.checkout.android:freecharge-checkout-android-sdk:2.2@aar'
compile 'in.juspay:godel:0.6.12.1423'
testCompile 'junit:junit:4.12'}

Hope this help.Happy Coding.


问:
Skips zero's, but display label value as Zero
Since I do not have 50 reputations, I was unable to ask my question on the same post here (Remove Duplicate and Count only one in a y:axis).

I am working on a similar project, everything on the post (Remove Duplicate and Count only one in a y:axis) looks good. The output is also perfect however, I need one extra thing added to the output.

The Present Input:

```<code>var list = [
  {y:0,label:'Computers'},
  {y:0,label:'Computers'},
  {y:0,label:'Computers'},
  {y:1,label:'Computers'},
  {y:0,label:'Math'},
  {y:0,label:'Math'},
  {y:1,label:'Math'},
  {y:1,label:'Math'},
]
</code>```

What I am already getting is:

```<code>[{y: 1, label: "Computers"}, {y: 2, label: "Math"}]
</code>```

This is perfect to me, this solution on the URL I mentioned, skips zero's, removes duplicates .. I need all of this, I do not need any change in these, however, if all the values of one subject are zero's then I want the output to display  a single output for zero. To make it clear below is my input and

New Input:
If all the values of 'Computers' are y: is Zero, then I want the output at least to inform me that it is all Zero.

```<code>var list = [
  {y:0,label:'Computers'},
  {y:0,label:'Computers'},
  {y:0,label:'Computers'},
  {y:0,label:'Computers'}, //here all the values are zero for computers

  {y:0,label:'Math'},
  {y:0,label:'Math'},
  {y:1,label:'Math'},
  {y:1,label:'Math'},
]
</code>```

Present Output:

```<code>[{y: 2, label: "Math"}] //this is perfect but, with skip of zeros, I need an output like the below expected output
</code>```

Expected Output:

```<code>[{y: 0, label: "Computers"}, {y: 2, label: "Math"}]
</code>```

答:
If I understand you correctly (you want to count the number of positive y values for each label) this should do it

```<code>var data = [
  {y:0,label:'Computers'},
  {y:0,label:'Computers'},
  {y:0,label:'Computers'},
  {y:0,label:'Computers'}, //here all the values are zero for computers

  {y:0,label:'Math'},
  {y:0,label:'Math'},
  {y:1,label:'Math'},
  {y:2,label:'Math'},
]

var output = data.reduce(function(acc, val){
    if (val.label in acc) {
        acc[val.label].y += 1 ? val.y > 0 : 0;
    } else {
        acc[val.label] = {y: 1 ? val.y > 0 : 0, label:val.label};
    }
    return acc;
}, {});

// and to make it into an array of results
var res = [];
for (var key in output) {
    res.push(output[key]);
}

// [{y:0, label:'Computers'}, {y:2, label:'Math'}]
</code>```

If however, you care about the value of y and want to use their sum, a slight modification would do the trick

```<code>var output = data.reduce(function(acc, val){
    if (val.label in acc) {
        acc[val.label].y += val.y;
    } else {
        acc[val.label] = {y:val.y, label:val.label};
    }
    return acc;
}, {});

var res = [];
for (var key in output) {
    res.push(output[key]);
}

// [{y:0, label:'Computers'}, {y:3, label:'Math'}]
</code>```

Reduce is nice here I think because it has an accumulator (a variable that it remembers) and uses a function on all the elements of an array.

Using reduce, we have an accumulator object {} (initial value) and add to it our labels, {'Math':{y:x, label:'Math'}, ..} and increment their y values depending on our data. The last step of making it into an array is only necessary if that is the desired output format, all the results are in the output variable.

Looking at Hendry's answer, perhaps reduce is overkill. But a fun exercise at least.

Body:
Since I do not have 50 reputations, I was unable to ask my question on the same post here (Remove Duplicate and Count only one in a y:axis).

I am working on a similar project, everything on the post (Remove Duplicate and Count only one in a y:axis) looks good. The output is also perfect however, I need one extra thing added to the output.

The Present Input:

var list = [
  {y:0,label:'Computers'},
  {y:0,label:'Computers'},
  {y:0,label:'Computers'},
  {y:1,label:'Computers'},
  {y:0,label:'Math'},
  {y:0,label:'Math'},
  {y:1,label:'Math'},
  {y:1,label:'Math'},
]

What I am already getting is:

[{y: 1, label: "Computers"}, {y: 2, label: "Math"}]

This is perfect to me, this solution on the URL I mentioned, skips zero's, removes duplicates .. I need all of this, I do not need any change in these, however, if all the values of one subject are zero's then I want the output to display  a single output for zero. To make it clear below is my input and

New Input:
If all the values of 'Computers' are y: is Zero, then I want the output at least to inform me that it is all Zero.

var list = [
  {y:0,label:'Computers'},
  {y:0,label:'Computers'},
  {y:0,label:'Computers'},
  {y:0,label:'Computers'}, //here all the values are zero for computers

  {y:0,label:'Math'},
  {y:0,label:'Math'},
  {y:1,label:'Math'},
  {y:1,label:'Math'},
]

Present Output:

[{y: 2, label: "Math"}] //this is perfect but, with skip of zeros, I need an output like the below expected output

Expected Output:

[{y: 0, label: "Computers"}, {y: 2, label: "Math"}]

Body:
If I understand you correctly (you want to count the number of positive y values for each label) this should do it

var data = [
  {y:0,label:'Computers'},
  {y:0,label:'Computers'},
  {y:0,label:'Computers'},
  {y:0,label:'Computers'}, //here all the values are zero for computers

  {y:0,label:'Math'},
  {y:0,label:'Math'},
  {y:1,label:'Math'},
  {y:2,label:'Math'},
]

var output = data.reduce(function(acc, val){
    if (val.label in acc) {
        acc[val.label].y += 1 ? val.y > 0 : 0;
    } else {
        acc[val.label] = {y: 1 ? val.y > 0 : 0, label:val.label};
    }
    return acc;
}, {});

// and to make it into an array of results
var res = [];
for (var key in output) {
    res.push(output[key]);
}

// [{y:0, label:'Computers'}, {y:2, label:'Math'}]

If however, you care about the value of y and want to use their sum, a slight modification would do the trick

var output = data.reduce(function(acc, val){
    if (val.label in acc) {
        acc[val.label].y += val.y;
    } else {
        acc[val.label] = {y:val.y, label:val.label};
    }
    return acc;
}, {});

var res = [];
for (var key in output) {
    res.push(output[key]);
}

// [{y:0, label:'Computers'}, {y:3, label:'Math'}]

Reduce is nice here I think because it has an accumulator (a variable that it remembers) and uses a function on all the elements of an array.

Using reduce, we have an accumulator object {} (initial value) and add to it our labels, {'Math':{y:x, label:'Math'}, ..} and increment their y values depending on our data. The last step of making it into an array is only necessary if that is the desired output format, all the results are in the output variable.

Looking at Hendry's answer, perhaps reduce is overkill. But a fun exercise at least.


问:
Parse XML values and insert into Postgresql using Java
I have been reading lot of post on Stack Overflow and was wondering if I could really find the way how can I parse XML document and retrieve the data from it and insert it into my PostgreSQL database table which have exact column name as the XML schema tag have, but I failed to get the approx scenario. I have a following XML schema-

```<code><?xml version="1.0">
    <request uuid = 'xyz'>
        <app hash='', name='', package = '', version='', filesize='',create_date='', upate_date=''>
            <url>
                <name>---</name>
                <score>--</score>
            </url>
            <url>
                <name>---</name>
                <score>--</score>
            </url>
        </app>
    </request>
</code>```

and have two tables in PostgreSQL database name "app" and "url" shown below:

```<code>app
-----------------------------
appid(serial) | hash | name | package | version | filesize | create_date | update_date
</code>```

and

```<code>url
--------------------
urlid(serial) | name | score

Note: urlid & appid are made as Primary Key in both the tables.
</code>```

I needed to learn something that helps me insert the values inside these two tables with respect to their column ( example parse and insert) from the above given XML schema. I am using a PostgreSQL 9.2 version and I needed to do it using JAVA.

Anyone who could provide me a example of how should I parse the single XML document and have it inserted into two different tables would be really helpful.

Thank you in advance!

UPDATE

Do we suppose to use SAX parser here for parsing and insert likewise? Please help me understand the method to do this insertion.

答:
This is an old question but I recently had the same problem with reading XML and updating postgresql with the same column names. Here's the code that I wrote and worked fine for me. I had trouble finding the solution so this might help people.

```<code>    public class readXmlToPostgres {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {

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

allcols = getcolnames();
boolean hasvalue=false;
boolean colbool[] = new boolean[allcols.size()];
for(int i=0; i<allcols.size(); i++){
    colbool[i] = false;
}

try {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLEventReader eventReader =
    factory.createXMLEventReader(
    new FileReader("path/to/xml/file"));
    String columnName = "";
    String columnValue="";
    String attrval="";
    String insertStatement_A = "";
    String insertStatement_B = "";
    String insertStatement_C="";
    String insertStatement_full="";
    boolean isnull = false;
    ArrayList<String> insertColnames = new ArrayList<String>();
    ArrayList<String> insertValues = new ArrayList<String>();
    Connection ds             = null;
    String dbName = "";

    ds = createConnection();

    int count = 0;
    while(eventReader.hasNext()){

        XMLEvent event = eventReader.nextEvent();
        switch(event.getEventType()){
        case XMLStreamConstants.START_ELEMENT:
        StartElement startElement = event.asStartElement();
        String qName = startElement.getName().getLocalPart();
        if (qName.equalsIgnoreCase("records")) {
        insertColnames.clear();
        insertValues.clear();

        insertStatement_A="insert into \"Tablename\"(";
        insertStatement_B=") values(";
        insertStatement_C=" )";
        insertStatement_full="";
    }

    for(int i=0; i<allcols.size(); i++)

    { if (qName.equalsIgnoreCase(allcols.get(i))) {
        colbool[i] = true;

        Iterator<Attribute> attributes = startElement.getAttributes();
        columnName = allcols.get(i);
        attrval="false";
        if(attributes.hasNext()){
        isnull = true;
        colbool[i] = false;
        columnName=allcols.get(i);
        columnValue=null;
        insertColnames.add(columnName);
        insertValues.add(columnValue);

    }

    }
    }
    break;
    case XMLStreamConstants.CHARACTERS:
    Characters characters = event.asCharacters();
    for(int i=0; i<allcols.size(); i++){
    if(colbool[i]){

    columnName=allcols.get(i);
    columnValue=characters.getData();

    insertColnames.add(columnName);
    insertValues.add(columnValue);

    colbool[i] = false;

    }

    }
    break;
    case  XMLStreamConstants.END_ELEMENT:
    EndElement endElement = event.asEndElement();
    if(endElement.getName().getLocalPart().equalsIgnoreCase("records")){

    System.out.println(": "+count);
    count = count + 1;

    for(int a=0; a<2;a++){
    if((insertColnames.get(0).equals("Id")) || (insertColnames.get(0).equals("Type"))){
    insertColnames.remove(0);
    insertValues.remove(0);
    }
    }

    //make query
    for(int i=0; i<insertColnames.size(); i++){

    insertStatement_A += "\""+insertColnames.get(i)+"\", ";
    if(insertValues.get(i)==null){
    //   System.out.println("value is null");
    insertStatement_B += ""+insertValues.get(i)+", ";
    }
    else{
    //insertValues.get(i) = insertValues.get(i).replace("'", "");
    insertStatement_B += "'"+insertValues.get(i).replace("'", "")+"', ";
    }
    }//for end

    insertStatement_A=insertStatement_A.replaceAll(", $", "");

    insertStatement_B=insertStatement_B.replaceAll(", $", "");

    insertStatement_full = insertStatement_A + insertStatement_B + insertStatement_C;

    insertData(insertStatement_full, ds);

    }
    break;
    }
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
}
}

public static void insertData(String insertQuery, Connection ds) throws SQLException{
java.sql.Statement  stmt  = null;
stmt = ds.createStatement();

stmt.executeUpdate(insertQuery);

}

public static ArrayList<String> getcolnames() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException{

ArrayList<String> allcols = new ArrayList<String>();
allcols.clear();

Connection ds             = null;
java.sql.Statement  stmt  = null;
String dbName = "";

ds = createConnection();
stmt = ds.createStatement();

String colQuery="SELECT column_name FROM information_schema.columns WHERE table_schema = 'public'  AND table_name   = 'tablename'";

ResultSet rs = stmt.executeQuery(colQuery);
while(rs.next()){

String colname=rs.getString("column_name");

allcols.add(colname);

System.out.println("column size : "+allcols.size());
return allcols;

}

public static Connection createConnection()
throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
Connection         c;

String DbName = "Databasename";

Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection("jdbc:postgresql://host/" + DbName , "user", "password");

System.out.println("connection established.");
return c;
}

}
</code>```

1: It uses StAX to read the xml.

2: It gets your column names from database.

3: Reads xml and gets value of required columns, creates an insert statement for you and finally updates you database.

Body:
I have been reading lot of post on Stack Overflow and was wondering if I could really find the way how can I parse XML document and retrieve the data from it and insert it into my PostgreSQL database table which have exact column name as the XML schema tag have, but I failed to get the approx scenario. I have a following XML schema-

<?xml version="1.0">
    <request uuid = 'xyz'>
        <app hash='', name='', package = '', version='', filesize='',create_date='', upate_date=''>
            <url>
                <name>---</name>
                <score>--</score>
            </url>
            <url>
                <name>---</name>
                <score>--</score>
            </url>
        </app>
    </request>

and have two tables in PostgreSQL database name "app" and "url" shown below:

app
-----------------------------
appid(serial) | hash | name | package | version | filesize | create_date | update_date

and

url
--------------------
urlid(serial) | name | score

Note: urlid & appid are made as Primary Key in both the tables.

I needed to learn something that helps me insert the values inside these two tables with respect to their column ( example parse and insert) from the above given XML schema. I am using a PostgreSQL 9.2 version and I needed to do it using JAVA.

Anyone who could provide me a example of how should I parse the single XML document and have it inserted into two different tables would be really helpful.

Thank you in advance!

UPDATE

Do we suppose to use SAX parser here for parsing and insert likewise? Please help me understand the method to do this insertion.

Body:
This is an old question but I recently had the same problem with reading XML and updating postgresql with the same column names. Here's the code that I wrote and worked fine for me. I had trouble finding the solution so this might help people.

    public class readXmlToPostgres {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {

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

allcols = getcolnames();
boolean hasvalue=false;
boolean colbool[] = new boolean[allcols.size()];
for(int i=0; i<allcols.size(); i++){
    colbool[i] = false;
}

try {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLEventReader eventReader =
    factory.createXMLEventReader(
    new FileReader("path/to/xml/file"));
    String columnName = "";
    String columnValue="";
    String attrval="";
    String insertStatement_A = "";
    String insertStatement_B = "";
    String insertStatement_C="";
    String insertStatement_full="";
    boolean isnull = false;
    ArrayList<String> insertColnames = new ArrayList<String>();
    ArrayList<String> insertValues = new ArrayList<String>();
    Connection ds             = null;
    String dbName = "";

    ds = createConnection();

    int count = 0;
    while(eventReader.hasNext()){

        XMLEvent event = eventReader.nextEvent();
        switch(event.getEventType()){
        case XMLStreamConstants.START_ELEMENT:
        StartElement startElement = event.asStartElement();
        String qName = startElement.getName().getLocalPart();
        if (qName.equalsIgnoreCase("records")) {
        insertColnames.clear();
        insertValues.clear();

        insertStatement_A="insert into \"Tablename\"(";
        insertStatement_B=") values(";
        insertStatement_C=" )";
        insertStatement_full="";
    }

    for(int i=0; i<allcols.size(); i++)

    { if (qName.equalsIgnoreCase(allcols.get(i))) {
        colbool[i] = true;

        Iterator<Attribute> attributes = startElement.getAttributes();
        columnName = allcols.get(i);
        attrval="false";
        if(attributes.hasNext()){
        isnull = true;
        colbool[i] = false;
        columnName=allcols.get(i);
        columnValue=null;
        insertColnames.add(columnName);
        insertValues.add(columnValue);

    }

    }
    }
    break;
    case XMLStreamConstants.CHARACTERS:
    Characters characters = event.asCharacters();
    for(int i=0; i<allcols.size(); i++){
    if(colbool[i]){

    columnName=allcols.get(i);
    columnValue=characters.getData();

    insertColnames.add(columnName);
    insertValues.add(columnValue);

    colbool[i] = false;

    }

    }
    break;
    case  XMLStreamConstants.END_ELEMENT:
    EndElement endElement = event.asEndElement();
    if(endElement.getName().getLocalPart().equalsIgnoreCase("records")){

    System.out.println(": "+count);
    count = count + 1;

    for(int a=0; a<2;a++){
    if((insertColnames.get(0).equals("Id")) || (insertColnames.get(0).equals("Type"))){
    insertColnames.remove(0);
    insertValues.remove(0);
    }
    }

    //make query
    for(int i=0; i<insertColnames.size(); i++){

    insertStatement_A += "\""+insertColnames.get(i)+"\", ";
    if(insertValues.get(i)==null){
    //   System.out.println("value is null");
    insertStatement_B += ""+insertValues.get(i)+", ";
    }
    else{
    //insertValues.get(i) = insertValues.get(i).replace("'", "");
    insertStatement_B += "'"+insertValues.get(i).replace("'", "")+"', ";
    }
    }//for end

    insertStatement_A=insertStatement_A.replaceAll(", $", "");

    insertStatement_B=insertStatement_B.replaceAll(", $", "");

    insertStatement_full = insertStatement_A + insertStatement_B + insertStatement_C;

    insertData(insertStatement_full, ds);

    }
    break;
    }
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
}
}

public static void insertData(String insertQuery, Connection ds) throws SQLException{
java.sql.Statement  stmt  = null;
stmt = ds.createStatement();

stmt.executeUpdate(insertQuery);

}

public static ArrayList<String> getcolnames() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException{

ArrayList<String> allcols = new ArrayList<String>();
allcols.clear();

Connection ds             = null;
java.sql.Statement  stmt  = null;
String dbName = "";

ds = createConnection();
stmt = ds.createStatement();

String colQuery="SELECT column_name FROM information_schema.columns WHERE table_schema = 'public'  AND table_name   = 'tablename'";

ResultSet rs = stmt.executeQuery(colQuery);
while(rs.next()){

String colname=rs.getString("column_name");

allcols.add(colname);

System.out.println("column size : "+allcols.size());
return allcols;

}

public static Connection createConnection()
throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
Connection         c;

String DbName = "Databasename";

Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection("jdbc:postgresql://host/" + DbName , "user", "password");

System.out.println("connection established.");
return c;
}

}

1: It uses StAX to read the xml.

2: It gets your column names from database.

3: Reads xml and gets value of required columns, creates an insert statement for you and finally updates you database.