text:
Q: Intersection of two `std::map`s Given that I have two std::maps, say:
map<int, double> A;
map<int, double> B;

I'd like to get the intersection of the two maps, something of the form:
map<int, pair<double,double> > C;

Where the keys are the values in both A and B and the value is a pair of the values from A and B respectively.
Is there a clean way using the standard-library?

A: #include <map>
using namespace std;
typedef int KeyType;
typedef double ValueType;
typedef map< KeyType, ValueType > MyMap;
typedef MyMap::iterator MyMapIter;
typedef MyMap::const_iterator MyMapConstIter;
typedef pair< ValueType, ValueType > ValueTypePair;
typedef map< KeyType, ValueTypePair > MyMapIntersection;

int main() {
    MyMap A;
    MyMap B;
    MyMapIntersection C;

    // fill up A, B

    for( MyMapConstIter cit = A.begin(); cit != A.end(); ++cit ) {
        const KeyType x = cit->first;
        MyMapConstIter found = B.find( x );
        if( found != B.end() ) {
            ValueTypePair valuePair =
                ValueTypePair( cit->second, found->second );
            C.insert( pair< KeyType, ValueTypePair>( x, valuePair ) );
        }
    }
}

A: #include <map>
#include <utility>
template <typename KeyType, typename LeftValue, typename RightValue>
std::map<KeyType, std::pair<LeftValue, RightValue>>
IntersectMaps(const std::map<KeyType, LeftValue>& left,
              const std::map<KeyType, RightValue>& right) {
    std::map<KeyType, std::pair<LeftValue, RightValue>> result;
    typename std::map<KeyType, LeftValue>::const_iterator il  = left.begin();
    typename std::map<KeyType, RightValue>::const_iterator ir = right.begin();
    while (il != left.end() && ir != right.end()) {
        if (il->first < ir->first)
            ++il;
        else if (ir->first < il->first)
            ++ir;
        else {
            result.insert(std::make_pair(il->first, std::make_pair(il->second, ir->second)));
            ++il;
            ++ir;
        }
    }
    return result;
}

I haven't tested this, or even compiled it... but it should be O(n). Because it's templated it should work with any two maps that share the same key type.

A: I don't think there is a pure STL way of implementing what you want. Manual implementation should not be too complicated.
Note that std::set_intersection is not a solution. The main reason being that it compares the dereferenced iterators and then copies one of the elements to the output iterator.
While comparison of the full dereferenced iterator includes the associated value (which I understand you do not want to consider as part of the key), can be solved by providing a comparison functor that would only test the key (std::pair<const Key, Value>::first), the problem of the algorithm copying only one of the two values and not composing the solution cannot be tackled externally.
EDIT: A simple linear time implementation of the function:
Note, as @Mark Ransom comments, that this solution adds an extra requirement: the keys must be equality comparable. That is not an issue with his solution here, or similarly in the answer by @Matthiew M here. It would be shameful to modify this algorithm with that fix :)
Another great advantage of @Mark's implementation is that it can compose from maps that store different value types as long as the keys are the same (which seems like an obvious requirement). I wish I would upvote more than once there..
template <typename Key, typename Value>
std::map<Key,std::pair<Value,Value> >
merge_maps( std::map<Key,Value> const & lhs, std::map<Key,Value> const & rhs )
{
    typedef typename std::map<Key,Value>::const_iterator input_iterator;
    std::map<Key, std::pair<Value,Value> > result;
    for ( input_iterator it1 = lhs.begin(), it2 = rhs.begin(),
                         end1 = lhs.end(), end2 = rhs.end();
            it1 != end1 && it2 != end2; )
    {
        if ( it1->first == it2->first )
        {
            result[it1->first] = std::make_pair( it1->second, it2->second );
            ++it1; ++it2;
        }
        else
        {
            if ( it1->first < it2->first )
                ++it1;
            else
                ++it2;
        }
    }
    return result;
}

A: EDIT: Since I was pretty sure there was a better STL-like solution to this, I figured one out. It's different enough that I'm posting it as a separate answer.
There are a few tricks to this. Firstly, you'd like to use set_intersection, but you have two maps. The solution is a custom comparator and the std::transform algorithm. Someone more familiar with the standard library than me can probably optimize this, but it works. Note that boost::bind would allow you to cut down on the silly helper functions that make this work.
#include <algorithm>
#include <map>
#include <set>

bool myLess(const std::map<int,double>::value_type &v1,
            const std::map<int,double>::value_type &v2) {
    return v1.first < v2.first;
}
int getKey(const std::map<int,double>::value_type &v) {
    return v.first;
}

struct functor {
    std::map<int,double> &m1,&m2;
    functor(std::map<int,double> &im1, std::map<int,double> &im2) : m1(im1), m2(im2) {}
    std::pair<int,std::pair<double,double> > operator() (int x) {
        return std::make_pair(x, std::make_pair(m1[x],m2[x]));
    }
};

int main() {
    std::map<int,double> m1, m2;
    m1[0]=0;m1[1]=1; m1[2]=2; m1[3]=3;
            m2[1]=11;m2[2]=12;m2[3]=13;m2[4]=14;

    std::set<int> keys1,keys2,keys;
    //Extract the keys from each map with a transform
    std::transform(m1.begin(),m1.end(),std::inserter(keys1,keys1.begin()),getKey);
    std::transform(m2.begin(),m2.end(),std::inserter(keys2,keys2.begin()),getKey);
    //set_intersection to get the common keys
    std::set_intersection(keys1.begin(),keys1.end(),keys2.begin(),keys2.end(),
            std::inserter(keys,keys.begin()));

    std::map<int, std::pair<double,double> > result;
    functor f(m1,m2);  //stash our maps into the functor for later use
    //transform from the key list to the double-map
    std::transform(keys.begin(),keys.end(),std::inserter(result,result.begin()),f);
    return 0;
}

Like much of C++, the final use of everything is fairly slick (everything in main()), but the setup is more verbose than we would really like.

A: A (better) solution based on the fact that the maps are sorted. (Shame on me that I overlooked it.) Thanks to David Rodríguez - dribeas for the suggestion.
#include <map>
using namespace std;
typedef int KeyType;
typedef double ValueType;

typedef map< KeyType, ValueType > MyMap;
typedef MyMap::iterator MyMapIter;
typedef MyMap::const_iterator MyMapConstIter;

typedef pair< ValueType, ValueType > ValueTypePair;

typedef map< KeyType, ValueTypePair > MyMapIntersection;

void constructInsert( MyMapIntersection & c, MyMapConstIter const & acit,
    MyMapConstIter const & bcit ) {

    ValueTypePair valuePair = ValueTypePair( acit->second, bcit->second );

    c.insert( pair< KeyType, ValueTypePair>( acit->first, valuePair ) );
}

int main() {

    MyMap A;
    MyMap B;
    MyMapIntersection C;

    // fill up A, B

    MyMapConstIter acit, bcit;
    for( acit = A.begin(), bcit = B.begin();
        (acit != A.end()) && (bcit != B.end()); /* Inside loop */ ) {

        const KeyType aKey = acit->first;
        const KeyType bKey = bcit->first;

        if( aKey < bKey ) {

            ++acit;
        }
        else if( aKey == bKey ) {

            constructInsert( C, acit, bcit );

            ++acit;
            ++bcit;
        }
        else {

            ++bcit;
        }
    }

}

A: Okay, let's get ready to get your hands dirty :)
I'll be using std::mismatch and std::transform
First of all, some types:
typedef std::map<int, double> input_map;
typedef input_map::const_reference const_reference;
typedef input_map::const_iterator const_iterator;
typedef std::pair<const_iterator,const_iterator> const_pair;

typedef std::map<int, std::pair<double,double> > result_map;

Then predicates
bool less(const_reference lhs, const_reference rhs)
{
  return lhs.first < rhs.first;
}

result_map::value_type pack(const_reference lhs, const_reference rhs)
{
  assert(lhs.first == rhs.first);
  return std::make_pair(lhs.first, std::make_pair(lhs.second, rhs.second));
}

Now main:
result_map func(input_map const& m1, input_map const& m2)
{
  if (m1.empty() || m2.empty()) { return result_map(); }

  // mismatch unfortunately only checks one range
  // god do I hate those algorithms sometimes...
  if (*(--m1.end()) < *(--m2.end()) { return func(m2, m1); }

  const_pair current = std::make_pair(m1.begin(), m2.begin()),
             end = std::make_pair(m1.end(), m2.end());

  result_map result;

  // Infamous middle loop, the check is middle-way in the loop
  while(true)
  {
    const_pair next = std::mismatch(p.first, end.first, p.second, less);

    std::transform(current.first, next.first, current.second,
      std::inserter(result, result.begin()), pack);

    // If any of the iterators reached the end, then the loop will stop
    if (next.first == end.first || next.second == end.second) { break; }

    // Advance the lesser "next"
    if (less(*next.first, *next.second)) { ++next.first; }
    else                                 { ++next.second; }

    current = next;
  }

  return result;
}

I find this solution quite elegant... notwithstanding the awkard setup part since we need to ensure that the first range ends up quicker than the second because of mismatch...
Notice that the advance is really stupid, we could loop specifically here until we had *next.first.key == *next.second.key but it would complicate the loop.
I really don't find this better than a handcrafted loop though... consider:
result_map func2(input_map const& lhs, input_map const& rhs)
{
  result_map result;

  for (const_iterator lit = lhs.begin(), lend = lhs.end(),
                      rit = rhs.begin(), rend = rhs.end();
       lit != lend && rit != rend;)
  {
    if (lit->first < rit->first)      { ++lit; }
    else if (rit->first < lit->first) { ++rit; }
    else
    {
      result[lit->first] = std::make_pair(lit->second, rit->second);
      ++lit, ++rit;
    }
  }

  return result;
}

It's much more compact, probably more efficient... sometimes the functions you're looking are not general enough to be in the STL :)

A: The following is a simplification of my previous answer, mostly taking advantage of the fact that set_intersection CAN be used with maps as input, but only if you make the output a set of std::pairs. The result also cuts down intermediates to a single "common keys" list.
#include <algorithm>
#include <map>
#include <set>

struct cK { //This function object does double duty, the two argument version is for
            //the set_intersection, the one argument version is for the transform
    std::map<int,double> &m1,&m2;
    cK(std::map<int,double> &im1, std::map<int,double> &im2) : m1(im1), m2(im2)
    std::pair<int,std::pair<double,double> > operator() (std::pair<int,double> v
        return std::make_pair(v.first, std::make_pair(m1[v.first],m2[v.first]));
    }
    bool operator() (std::pair<int,double> v1, std::pair<int,double> v2) {
        return v1.first < v2.first;
    }
};

int main() {
    std::map<int,double> m1, m2;
    m1[0]=0;m1[1]=1; m1[2]=2; m1[3]=3;
            m2[1]=11;m2[2]=12;m2[3]=13;m2[4]=14;

    // Get the subset of map1 that has elements in map2
    std::set<std::pair<int,double> > sIntersection;
    cK compareKeys(m1,m2);
    std::set_intersection(m1.begin(),m1.end(),m2.begin(),m2.end(),
            std::inserter(sIntersection,sIntersection.begin()),compareKeys);

    // Use a custom transform to produce an output set
    std::map<int, std::pair<double,double> > result;
    std::transform(sIntersection.begin(),sIntersection.end(),
            std::inserter(result,result.begin()), compareKeys);
    return 0;
}

A: Almost a year after... but nevertheless :)
This one is for a set container, but you can easily change it to use a map:
template <class InputIterator, class OutputIterator>
OutputIterator intersect(InputIterator lf, InputIterator ll,
                         InputIterator rf, InputIterator rl,
                         OutputIterator result)
{
    while(lf != ll && rf != rl)
    {
        if(*lf < *rf)
            ++lf;
        else if(*lf > *rf)
            ++rf;
        else
        {
            *result = *lf;
            ++lf;
            ++rf;
        }
    }
    return result;
}

Usage:
intersect(set1.begin(), set1.end(),
          set2.begin(), set2.end(),
          inserter(output_container, output_container.begin()));

set1 and set2 are both set containers whilst output_container can be set, list, array etc..
inserter generates an insert iterator

A: template<typename K, typename V>
std::map<K, V> UnionMaps(const std::map<K, V> & left, const std::map<K, V> & right)
{
    std::map<K, V > result;
    typename std::map<K, V>::const_iterator il = left.begin();
    typename std::map<K, V>::const_iterator ir = right.begin();
    while (il != left.end() && ir != right.end())
    {
        if ((il->first < ir->first)){
            result.insert(make_pair(il->first, il->second));
            ++il;
        }else if ((ir->first < il->first)){
            result.insert(make_pair(ir->first, ir->second));
            ++ir;
        }else{
            result.insert(make_pair(il->first, il->second+ir->second));//add
            ++il;
            ++ir;
        }
    }
    while (il != left.end() ){
        result.insert(make_pair(il->first, il->second));
        il++;
    }
    while (ir != right.end() ){
        result.insert(make_pair(ir->first, ir->second));
        ir++;
    }
    return result;
}


text:
Q: Creating MOCK UP Data for Neo4j Unit testing I want to do unit testing for my application in neo4j with java code .We are writing junit test cases for it. But we want when we run the junit test cases it should not communicate it to the main database rather then some other mockup data.
We are using neo4j server and no embedded database is used.

How could this be achieved?
How can we create mockup data for testing neo4j related code?
How to create a mocked database for unit testing so that main database
  not be touched.
Is there any tool to mock the main database or we have to do it
  manually through the code?

A: We've got a great article on testing your Neo4j-based Java application that should give you a few options for testing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Camel from(mail) loose headers? I have a problem with camel route using IMAP.
from("imap://mail.server?username=aaa&password=zzz&copyTo=out&delete=true&unseen=false&folderName=in&mapMailMessage=false")
.tracing()
.setHeader("copyTo", simple("works"))
.bean(MyTest.class, "setBodyWithHardcodedJson")
.unmarshal(new JacksonDataFormat(Reply.class))
.log("copyTo=${header[copyTo]}")

The call to setBodyWithHardcodedJson override the body with a valid json, the unmarshall is done correctly.
The last instruction prints me null value. (My header is lost between the unmarshall and the log steps)
I tried the same route, but replacing the from(imap) with a from(direct) and send something from unit test.
The last instruction prints me "works" value, as expected.
Please, can somebody explain me why the exchange loose the headers i set by code when i start the route with a mail ?
EDIT : Here is a reduced version of my code to show the problem.
public class MyTest extends CamelTestSupport {
@Test
public void testInjectRequest() throws Exception {
    //just here to start the route and wait result...
    String response = "x";
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedMessageCount(1);
    template.sendBody("direct:start", response);
    assertMockEndpointsSatisfied();
}
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            // activate next line to start with direct -> works
            //from("direct:start")
            // activate next line to start with mail : test fails (not important)
            // BUT PROBLEM : different result of .log("copyTo=${header[copyTo]}")
            from("imap://server?username=aaa&password=bbb&copyTo=out&delete=true&unseen=false&folderName=in&mapMailMessage=false")
                .tracing()
                     .onException(Exception.class)
                     .log("exception here ${exception.message}")
                .end()
                .setHeader("copyTo", simple("works"))
                .bean(MyTest.class, "hardcodeJson")
                .unmarshal(new JacksonDataFormat(Reply.class))
                .log("body=${body.id}")
                .log("copyTo=${header[copyTo]}")
            ;
        }
    };
}
protected void hardcodeJson(Exchange exchange) {
    String jsonInputString = "{\n" +
            "   \"id\": \"Corresp_Rest:3e9a525d-fc64-\"\n" +
            "}";
    exchange.getIn().setBody(jsonInputString);
}
}

public class Reply {
String id;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}
}

Info following questions from  @kladderradatsch
in the traces i find :
INFO  route1 - body=Corresp_Rest:3e9a525d-fc64-
INFO  route1 - copyTo=

if i do it with from(direct) i have
INFO  route1 - body=Corresp_Rest:3e9a525d-fc64-
INFO  route1 - copyTo=works

I hardcoded the json body in the bean to be sure it should unmarshal the same way, independent of the from().
After the unmarshal, the body is a Reply object with the content OK, but the headers modified are resetted only on from("imap"), not on from("direct").
Maybe i'm wrong, but i imagine the unmarshall provoques something in camel-mail to recreate the exchange from original message, losing the changes in headers made by my code...

A: Rename your header copyTo to any other name because copyTo is an option of the imap: component so this clashes.


text:
Q: on-hover marker icons get change on google map I have seen their are several such type of question already asked according to those answers one more new issue is raised,
I have shown multiple markers on map, now I need if I hover to specific marker then icon get changed and when I remove my cursor from the marker then set previous icon, below is my code
for (i = 0; i < Object.size(locations); i++) {
      marker = new google.maps.Marker({
        position : new google.maps.LatLng(locations[i][1], locations[i][2]),
        icon     : site_url+'/assets/front/images/'+locations[i][4],
        map      : map,
        url      : site_url+'/detail/'+locations[i][3],
        draggable: false,
        hovericon: site_url+'/assets/front/images/'+hovericon,
      });
      google.maps.event.addListener(marker, 'click', function() {
          window.location.href = this.url;
      });
      google.maps.event.addListener(marker, "mouseover", function() {
           marker.setIcon(this.hovericon);
      });
      google.maps.event.addListener(marker, "mouseout", function() {
         marker.setIcon(this.icon);
      });
      markers.push(marker);

    function AutoCenter() {
      var bounds = new google.maps.LatLngBounds();
      $.each(markers, function (index, marker) {
      bounds.extend(marker.position);
      });
      map.fitBounds(bounds);
    }
    AutoCenter();
  }

Above code is showing multiple markers that is good but when I hover to specific marker then it changing always last marker icon, but I need that icon should be changed only which I hover not the last one.

If I hover to any marker always last icon get changed see in attached image If I hover to first, second last icon is changing.
What I am doing wrong, any help ?

A: this happend because when the for ends you have the last marker to change attached to the listener.
You can use this insetead of marker inside the addListeners to get the intended one.
for (i = 0; i < Object.size(locations); i++) {
      marker = new google.maps.Marker({
        position : new google.maps.LatLng(locations[i][1], locations[i][2]),
        icon     : site_url+'/assets/front/images/'+locations[i][4],
        map      : map,
        url      : site_url+'/detail/'+locations[i][3],
        draggable: false,
        originalicon: site_url+'/assets/front/images/'+locations[i][4],
        hovericon: site_url+'/assets/front/images/'+hovericon
      });
      google.maps.event.addListener(marker, 'click', function() {
          window.location.href = this.url;
      });
      google.maps.event.addListener(marker, "mouseover", function() {
           this.setIcon(this.hovericon);
      });
      google.maps.event.addListener(marker, "mouseout", function() {
           //you have to retreive the original icon cause with the mouse hover you change the marker icon attribute
           this.setIcon(this.originalicon);
      });
      markers.push(marker);

    function AutoCenter() {
      var bounds = new google.maps.LatLngBounds();
      $.each(markers, function (index, marker) {
      bounds.extend(marker.position);
      });
      map.fitBounds(bounds);
    }
    AutoCenter();
  }

This way you refer the element that you are interacting with(mouseover and mouseout) and not the last one in the for loop.
I didn't tested the code so I'm not sure is working.
look at this fiddle for working sample
hope this helps


text:
Q: Paging GridView Issues I just read some articles about paging gridview but I couldn't make it...
There is my full gridview's code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" style="font-family: Verdana, Arial, Sans-Serif;"

            CssClass="gridview" OnSorting="GridView_Sorting"
            DataKeyNames="id"
            AllowSorting ="True" BackColor="#CCCCCC"
            BorderStyle="Inset" BorderWidth="2px" BorderColor="GrayText"
            CellPadding="1"
            CellSpacing="5"
            HeaderStyle-HorizontalAlign="Center"
            OnRowDataBound="GridView1_RowDataBound"
            ForeColor = "Black" RowStyle-CssClass="gridview"
            OnRowCommand="GridView1_RowCommand" AllowPaging="True"
            OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="5">
            <AlternatingRowStyle BackColor="#CCCCCC" />
                <columns>

                    <asp:BoundField HeaderText="ID" DataField="id"  />
                    <asp:BoundField HeaderText="PRIORIDADE" DataField="prioridade"
                        ItemStyle-HorizontalAlign="Center">
                    <ItemStyle HorizontalAlign="Center" />
                    </asp:BoundField>
                    <asp:BoundField  HeaderText="SITUAÇÃO"  DataField="situacao" ItemStyle-HorizontalAlign="Center" >
                    <ItemStyle HorizontalAlign="Center" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="RESPONSAVEL" DataField="responsavel" HeaderStyle-Width="65px" ItemStyle-HorizontalAlign="Center">
                    <HeaderStyle Width="65px" />
                    <ItemStyle HorizontalAlign="Center" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="DATA DE CADASTRO" DataField="dt_cadastro" DataFormatString="{0:dd/MM/yyyy}" HeaderStyle-Width="60px" SortExpression="dt_cadastro"
                    ItemStyle-HorizontalAlign="Center" >
                    <HeaderStyle Width="60px" />
                    <ItemStyle HorizontalAlign="Center" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="PREVISÃO DE TÉRMINO" DataField="previsao_termino" DataFormatString="{0:dd/MM/yyyy}" HeaderStyle-Width="60px"
                    ItemStyle-HorizontalAlign="Center">
                    <HeaderStyle Width="60px" />
                    <ItemStyle HorizontalAlign="Center" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="PROJETO" DataField="projeto"  ItemStyle-HorizontalAlign="Center">
                    <ItemStyle HorizontalAlign="Center" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="FUNCIONALIDADE" DataField="funcionalidade"
                        ItemStyle-HorizontalAlign="Center" >
                    <ItemStyle HorizontalAlign="Center" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="CLUBE" DataField="clube"
                        ItemStyle-HorizontalAlign="Center" >
                    <ItemStyle HorizontalAlign="Center" />
                    </asp:BoundField>

                    <asp:TemplateField HeaderStyle-Width="70px" HeaderText="VISUALIZAR" >
                        <ItemTemplate>
                            <asp:Button ID="Btn_Visualizar" runat="server" Text="VISUALIZAR" CssClass="Btn_Grid"  Font-Size="7pt" Font-Names="Verdana, Arial"  OnClick="Btn_Visualizar_Click"
                            CommandName="visualizar" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
                        </ItemTemplate>
                        <HeaderStyle Width="70px" />
                    </asp:TemplateField>
                    <asp:TemplateField HeaderStyle-Width="66px" HeaderText="ALTERAR">
                        <ItemTemplate>
                            <asp:Button ID="Btn_Alterar" runat="server" Text="ALTERAR" CssClass="Btn_Grid" Font-Size="7pt" Font-Names="Verdana, Arial"
                            CommandName="editar" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
                        </ItemTemplate>
                        <HeaderStyle Width="66px" />
                    </asp:TemplateField>
                    <asp:TemplateField HeaderStyle-Width="66px" HeaderText="FEEDBACK">
                        <ItemTemplate>
                            <asp:Button ID="Btn_Feedback" runat="server" Text="ADICIONAR" CssClass="Btn_Grid" Font-Size="7pt" Font-Names="Verdana,Arial"
                            CommandName="feedback" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
                        </ItemTemplate>
                        <HeaderStyle Width="66px" />
                    </asp:TemplateField>

                </columns>
            <EditRowStyle ForeColor="Black" CssClass="GridViewEditRow" />
            <FooterStyle BackColor="#CCCCCC" />
            <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" BorderColor="White" BorderStyle="Solid" BorderWidth="1px" />
            <PagerSettings Mode="NumericFirstLast" FirstPageText="First" LastPageText="Last" PageButtonCount="5" />
            <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
            <RowStyle BackColor="White" />
            <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
            </asp:GridView>

CodeBehind:
public partial class TodosChamados : System.Web.UI.Page
  {
    BDUsuarios usr = new BDUsuarios();
    BDFuncionalidades func = new BDFuncionalidades();
    BDChamados ch = new BDChamados();

protected void Page_Load(object sender, EventArgs e)
  {
    if (!IsPostBack)
       {
          GridView1.DataSource = ch.BuscaTodosChamados();
          GridView1.DataBind();
        }
  }

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.Cells[1].Text == "ALTA")
            {
                e.Row.Cells[1].BackColor = System.Drawing.Color.Red;
                e.Row.ControlStyle.Font.Bold = true;
            }
        }
        if (e.Row.Cells[0].Visible = e.Row.RowType == DataControlRowType.Pager)
        {
            e.Row.Cells[0].Visible = false;
        }
    }

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
 {
    if (e.CommandName != "Sort")
       {
          if (e.CommandName == "visualizar")
                {
                 Session["id"] = GridView1.Rows[Convert.ToInt32(e.CommandArgument.ToString())].Cells[0].Text;
                    Session["editar"] = null;
                }
                else if (e.CommandName == "editar")
                {
                    Session["id"] = GridView1.Rows[Convert.ToInt32(e.CommandArgument.ToString())].Cells[0].Text; //Grava o ID do chamado da linha correspondente.
                    Session["editar"] = 1; // 1 - Editar   2 - Não Editar .
                }

                else if (e.CommandName == "feedback")
                {
                    Session["id"] = GridView1.Rows[Convert.ToInt32(e.CommandArgument.ToString())].Cells[0].Text; //Grava o ID do chamado da linha correspondente.
                    Response.Redirect("~/Adm/Feedback.aspx");
                }
                Response.Redirect("~/Adm/DetalhesChamado.aspx");
            }
        }

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
  {
      GridView1.PageIndex = e.NewPageIndex;
      GridView1.DataSource = ch.BuscaTodosChamados();
      GridView1.DataBind();
  }

A: Update 2
Now i hopefully have found the reason for your pager not being shown. You are making the first colum invisible, even for the pager-row in RowDataBound, but the pager is sitting in the first cell by default:
e.Row.Cells[0].Visible = false;

You have to check the correct RowType:
e.Row.Cells[0].Visible = e.Row.RowType == DataControlRowType.Pager;

or even better on the aspx markup:
<asp:BoundField HeaderText="ID" DataField="id" Visible="False" />

A silly question, have you set AllowPaging to true?
<asp:GridView Id="GridView1" runat="server" AllowPaging="True" >
    <PagerSettings Mode="NumericFirstLast" FirstPageText="First" LastPageText="Last" PageButtonCount="5" />
</asp:gridview>

GridView.AllowPaging Property
true if the paging feature is enabled; otherwise, false. The default is false.
You should also databind the GridView only if(!IsPostBack) when viwstate is enabled(default).
So wrap your databind code from Page_Load(i guess) into this check:
protected void Page_Load(Object sender, EventArgs e)
{
    if(!IsPostBack)
    {
         GridView1.DataSource = ch.BuscaTodosChamados();
         GridView1.DataBind();
    }
}

Otherwise events won't be triggered and changes will be overwritten when you reload data on postback.
Update According to your last edit:
I assume that your RowCommand is the reason for this issue. It is called before the PageIndexChanging event and it is triggered also when the page changes(if i remember correctly). So have a look at your Response.Redirect which happens when no if/else-if will catch it which seems to be the case.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName != "Sort")
    {
        if (e.CommandName == "visualizar")
        {
            // ..
        }
        else if (e.CommandName == "editar")
        {
           //..
        }

        else if (e.CommandName == "feedback")
        {
           //..
        }
        Response.Redirect("~/Adm/DetalhesChamado.aspx");
    }
}

A: You must specify the event for OnPageIndexChanging in your .aspx. It should be:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
        OnPageIndexChanging = "GridView1_PageIndexChanging"
        AutoGenerateColumns="False" DataKeyNames="LastName,FirstName"
        EnablePersistedSelection="True" SelectedRowStyle-BackColor="Yellow"
        DataSourceID="SqlDataSource1" AllowSorting="True">

You might be having the same problem here
UPDATE
Make sure that the data that's being bound to the GridView is more that 5 since PageSize="5". If the number of rows is less than 5, then the pager will not be shown.


text:
Q: Limpiar formulario después de un envío $_POST en PHP Saludos y mil gracias por responder.
Tengo un código con un botón que elimina datos de una tabla mysql, la pregunta que me surge es: Como puedo hacer para que después que elimine, limpie el formulario en el que estoy trabajando, ya intente redireccionando y también intente hacer un input tipo reset y no logro hacerlo funcionar.
Estoy trabajando con HTML 5, Bootstrap, php, MySQL.
case 'eliminar':
         try {
             $sql  = "DELETE FROM cuentas WHERE id=:id";
             $consulta = $conexionBD->prepare($sql);
             $consulta->bindParam(':id', $id);
             $consulta->execute();
             echo '<script language="javascript">
             alert("Cuenta Eliminada Exitosamente...");
               </script>';
             break;
         } catch (\PDOException $lista) {
             echo '<script language="javascript">
                 alert("Lo sentimos, a ocurrido un error...");
               </script>';
         }
         break;


text:
Q: Is there any way to use pug compiler in template section of .vue file As per title, is there a method to use pug in nativescript-vue?
i tried adding pug and pug-plain-loader to project and modify webpack.config.js with
            {
              test: /\.pug$/,
              loader: 'pug-plain-loader'
            }

but it doesn't work


text:
Q: How to get total, min and max values from category I am trying to create a custom visual for Power BI.
Using these capabilities categories and values are accepted:
dataRoles: [
    {
        name: 'Category',
        kind: VisualDataRoleKind.Grouping,
    },
    {
        name: 'Values',
        kind: VisualDataRoleKind.Measure,
    }],
dataViewMappings: [{
    categorical: {
        categories: {
            for: { in: 'Category' },
            dataReductionAlgorithm: { top: {} }
        },
        values: {
            select: [{ bind: { to: 'Values' } }]
        },
    }
}],

Using dataView.categorical.values[0].values I am able to access the values of the first measure. However, dataView.categorical.values[0].subtotal, .min and .max are not set.
Min and max values can be determined using D3.Base.min/max but not the total values. How can I get those?

A: Categorical data views don't provide you with subtotals. To get subtotals, you need to use a Table data view or a Matrix data view. Table data views give you row subtotals only. Matrix data views give you row and column subtotals.


text:
Q: Google Maps iframe in Ionic with Dynamic Coordinates I want to show Google maps pin with dynamic Coordinates like whenever user update his coordinates map will be updated
here is my code
for eg dynamic coordinates {{artist_latitude}} {{artist_longitude}}

A: Try to add url in your ts file and then bind it to your iframe tag like this.
In your .html file:
In your .ts file:
import { DomSanitizer } from '@angular/platform-browser';
constructor(private sanitize: DomSanitizer){
let address = "https://www.google.com/maps/embed/v1/place?q=40.7127837,-74.0059413&key=abcxyz"
url = this.sanitize.bypassSecurityTrustResourceUrl(address);
}


text:
Q: How to filter web links in a nested python dictionaries and lists I have used a recursive function to list web links from a list of nested python dictionaries. I want to know how to filter the web links using the the web link as a string criteria. That is, I want to filter web links that contain the word-"question". A simple list comprehension might do it, but how?
Input json (truncated):
{
  "items": [
    {
      "tags": [
        "python-3.x",
        "web-scraping",
        "beautifulsoup",
        "urllib2",
        "urllib"
      ],
      "owner": {
        "reputation": 6,
        "user_id": 7726653,
        "user_type": "registered",
        "profile_image": "https://lh3.googleusercontent.com/-KAJHpZe2R2c/AAAAAAAAAAI/AAAAAAAAD54/UfehMYOIApw/photo.jpg?sz=128",
        "display_name": "Dhanush M",
        "link": "https://stackoverflow.com/users/7726653/dhanush-m"
      },
      "is_answered": false,
      "view_count": 24,
      "answer_count": 1,
      "score": 1,
      "last_activity_date": 1524279738,
      "creation_date": 1524243890,
      "last_edit_date": 1524279738,
      "question_id": 49946597,
      "link": "https://stackoverflow.com/questions/49946597/python-web-scraping-on-large-html-webpages",
      "title": "Python web scraping on large html webpages"
    },
    {
      "tags": [
        "python",
        "string",
        "encoding",
        "python-2.x",
        "python-internals"
      ],
      "owner": {
        "reputation": 16,
        "user_id": 3742872,
        "user_type": "registered",
        "profile_image": "https://i.stack.imgur.com/jx8Ij.jpg?s=128&g=1",
        "display_name": "Cortex",
        "link": "https://stackoverflow.com/users/3742872/cortex"
      },
      "is_answered": true,
      "view_count": 57,
      "answer_count": 3,
      "score": 3,
      "last_activity_date": 1524275907,
      "creation_date": 1524225161,
      "last_edit_date": 1524225665,
      "question_id": 49941052,
      "link": "https://stackoverflow.com/questions/49941052/which-encoding-is-used-for-strings-in-python-2-x",
      "title": "Which encoding is used for strings in Python 2.x?"
    },
    {
      "tags": [
        "python",
        "unicode",
        "ascii",
        "decode"
      ],
      "owner": {
        "reputation": 8,
        "user_id": 6835833,
        "user_type": "registered",
        "profile_image": "https://www.gravatar.com/avatar/1d2ff8635bc92955344c0affc23fe731?s=128&d=identicon&r=PG&f=1",
        "display_name": "double_negative",
        "link": "https://stackoverflow.com/users/6835833/double-negative"
      },
      "is_answered": true,
      "view_count": 28,
      "accepted_answer_id": 49945731,
      "answer_count": 3,
      "score": 0,
      "last_activity_date": 1524240482,
      "creation_date": 1524216785,
      "last_edit_date": 1524221387,
      "question_id": 49938517,
      "link": "https://stackoverflow.com/questions/49938517/python-unreproducible-unicodedecodeerror",
      "title": "Python Unreproducible UnicodeDecodeError"
    },
    {
      "tags": [
        "python",
        "list",
        "unicode"
      ],
      "owner": {
        "reputation": 1,
        "user_id": 9158477,
        "user_type": "registered",
        "profile_image": "https://lh6.googleusercontent.com/-SiMJZAP0eNU/AAAAAAAAAAI/AAAAAAAAA24/pWt8jygFt1w/photo.jpg?sz=128",
        "display_name": "Erwin Schleier",
        "link": "https://stackoverflow.com/users/9158477/erwin-schleier"
      },
      "is_answered": false,
      "view_count": 47,
      "answer_count": 0,
      "score": 0,
      "last_activity_date": 1524232267,
      "creation_date": 1524174371,
      "last_edit_date": 1524180439,
      "question_id": 49930710,
      "link": "https://stackoverflow.com/questions/49930710/python-unicode-to-list-reciving-double-double-quotes",
      "title": "python unicode to list, reciving double double quotes"
    }

import json

data=r'C:\Users\Kaleab\Desktop\GISN24\Python Programming\Python_Real_World_Exercises\unicode_json.json'
def js_r(data):
   with open(data, encoding='utf-8') as f_in:
       return(json.load(f_in))

my_dic_data = js_r(data)
def get_recursively(search_dict=my_dic_data,is_answered='True',field='link'):
    '''Takes a dict with nested lists and dicts,and searches all dicts for a key of the field provided'''
    fields_found=[]
    for key, value in search_dict.items():

            if key == field:
                fields_found.append(value)
            elif isinstance(value,dict):
                results=get_recursively(value,field)
                for result in results:
                    fields_found.append(result)
            elif isinstance(value,list):
                 for item in value:
                     if isinstance(item,dict):
                         more_results=get_recursively(item,field)
                         for another_result in more_results:
                            fields_found.append(another_result)
    return fields_found
if __name__ == "__main__":
    my_dic_data = js_r(data)
    print("This is my dictionary", my_dic_data)
    my_search_field=get_recursively()
    print("Searching field='link' yielded",my_search_field)
    final=[print(x) for x in my_search_field if 'questions' in my_search_field]
    print (final)

Searching field='link' yielded ['https://www.example.com/users/123456/abbe-m', 'https://example.com/questions/125678/python-web-scraping-on-large-html-webpages']
Expected Result: 'https://stackoverflow.com/questions/125678/python-web-scraping-on-large-html-webpages']
I want to filter the links that are questions, not users. How can I do that?

A: SOLUTION
final=[x for x in my_search_field if 'questions' in x]

EXPLANATION
1) Use x instead my_search_field in condition in that line:
final=[print(x) for x in my_search_field if 'questions' in my_search_field]

2) The list comprehansion is invalid. Try remove the "print".


text:
Q: Convergence in some measure implies convergence in some other measure absolutely continuous to the first Suppose that $f_n$ converges to $f$ in measure $\mu$ and $\nu$ is a different measure absolutely continuous with respect to $\mu$ (which of course means that both $\mu$ and $\nu$ are defined on the same measure space and  $\mu(E)=0\Longrightarrow \nu(E)=0$ for all sets $E$ in the sigma field). Then I'm trying to prove that $f_n$ converges to $f$ in $\nu$ also.
I think a proof using the Radon-Nikodym theorem may exist, but I tried doing this from the first principles. So I argued that since $f_n$ converges to $f$ in $\mu$, it has a subsequence $f_{n_k}$ that converges to $f$ almost everywhere w.r.t $\mu$ and hence also w.r.t $\nu$ as $\nu$ is absolutely continuous with respect to $\mu$. So if I assume that all measures are finite, then convergence of $f_{n_k}$ almost everywhere w.r.t $\nu$ implies convergence of $f_{n_k}$ to $f$ in measure $\nu$. I can't finish the argument after this. Can a proof on these lines be completed?
Also in hindsight, I assumed finiteness of all involved measures, so a general question is whether it works for $\sigma-$finite measures. I think not, but would a appreciate a counterexample.

A: As of the first question, this characterisation

Let $\mu$ be a finite measure. A sequence $f_n$ converges to $f$ in measure with respect to $\mu$ if and only if any subsequence $f_{n_k}$ admits a sub-subsequence $f_{n_{k_h}}$ that converges to $f$ almost everywhere.

provides far more than a solid path. It's almost a proof, because the $f_{n_{k_h}}$ given by the convergence in the measure $\mu$ works for the measure $\nu$ too.
For the second question, recall the following result:

Let $\mu$ be a $\sigma$-finite measure on $(\Omega,E)$. Then, there exists a probability $\mathbb{P}$ on the same space that is equivalent to $\mu$, i.e. such that $\forall A\in E\ (\mu(A)=0\leftrightarrow\mathbb{P}(A)=0).$

An example of this is $\Omega:=\mathbb{R}$, $\mu:=$Lebesgue measure, $\mathbb{P}:=\frac{1}{\sqrt{2\pi}}e^{-\frac{x^2}{2}}\cdot\mu$
In this example you can show that $f_n:=1_{[n,+\infty)}$ convergese in measure for $\mathbb{P}$ but not for $\mu$
The idea behind this is that, while the notion of almost-everywhere convergence depends only on negligible sets, it implies convergence in measure for finite ones, but not for $\sigma$-finite ones.

A: I happened to come across this awhile ago when I was reading a textbook on semimartingales. The author mentioned and used this as a minor fact without proof. This is how I think about this, hope it helps.
Suppose $\nu$ and $\mu$ are two finite measures on a measurable space $ ( \Omega, \mathscr{F} ) $ such that $\nu << \mu$. Then by the Radon-Nikodym theorem, there exists a measurable function $ \xi $ such that for every $ A \in \mathscr{F} $  $$ \nu(A) = \int_A \xi d\mu. $$
Note that since $\nu$ is finite, $ \int \xi d\mu \leq M $ for some $M > 0$.
Now, given $ \varepsilon > 0 $, let $A_n$ be the set $ \{ \omega \in \Omega : \left|f_n(\omega) - f(\omega)\right| > \varepsilon \} $. Then, choose a $c > 0$, \begin{align} \nu(A_n) &= \int_{A_n} \xi d\mu \\
&= \int_{A_n} \xi \mathbb{1}_{\{\xi \leq c\}} d\mu + \int_{A_n} \xi \mathbb{1}_{\{\xi > c\}} d\mu \\ &\leq c \mu(A_n) + \int_{A_n} \xi \mathbb{1}_{\{\xi \leq c\}} d\mu.
\end{align}
By the dominated convergence and the fact that $ \mathbb{1}_{A_n} \rightarrow 0 $ $\mu$-$a.e$ as $ n \to \infty$, the second term in the last inequality vanished as $n$ tends to infinity. Thus $$ \lim_{n \to \infty} \nu(A_n) \leq c \lim_{n \to \infty}\mu(A_n) = 0, $$
proving the assertion.


text:
Q: What's the relationship between concentration and refraction rate in a solution? I am supposed to determine the concentration of a solution of ethyl alcohol and cyclohexane by measuring its refraction rate. Now I have some standard sample of the solution at concentrations 10%, 20%, ... , 100% and I measured their refraction rates respectively. I'm now supposed to perform a non-linear fit to the data, but which fitting model should I use? Someone had suggested exponential, and the data look like an exponential growth, but is there a theoretical equation for this?

A: The theoretical equation you are looking for is actually referred to as a model, which you must hypothesise based on sound reason. The exponential model is one that allows for a rate of change proportional to the current value--for experiments such as objects being decelerated by air resistance (air resistance depends on how fast the object is moving), or amount of radiation emitted by a small radioactive source (amount of radiation depends on how much radioactive material remains), etc. To me this doesn't suit the behaviour of light in media, I would hypothesis a power law instead..of which an example is the inverse square law($r^{-2})$ of light intensity at a distance for example, or inverse square root law ($\rho^{-0.5})$ for terminal velocity due to air density.

I hypothesise that the speed of light decreases as the density of the
  medium increases according to some exponent. Paraphrased, the
  hypothesis suggests a power law relation between solute concentration
  of a liquid medium and its refractive index.

With concentration(x) and refractive index(n), the power model is $n=Ax^B+D$. This opposed to a linear model $n=Ax+B$ (a.k.a y=mx+c), where $A$ $B$ and $D$ are constants. Note that you can swap n with x here, the polarity of B will flip automatically as a result.
The trick is to transform the nonlinear equation by applying $lg$ to both sides of $n=Ax^B+D$:
$\lg (n)=B \lg(x)+ E$, where $E=\lg(A^BD)$, itself a constant since it involves neither $n$ or $C$.
Clearly plotting $ \lg(n)$ vs $\lg(x)$ produces a straight line with $B$ instantly found by calculating gradient of best fit line, and $E$ also immediately known from the y-intercept of that line. Then it is just a few more steps to obtain A and D.
The exponential form would be $n=n_0 exp(Ax)$, where $n_0$ is the starting refractive index (which increases exponentially with concentration as alternately hypothesized) at zero concentration. To transform this model to linear form, apply natural log to both sides to obtain:
$\lg(n)=Ax + \lg(n_0)$, where $A$ is the gradient and $\lg(n_0)$ is the y-intercept of the graph of $\lg(n)$ vs $x$. Note the difference...
Lastly, both power law and exponential models may seem to be able to fit the data. With few data points this is very possible--and also dangerous (it is tempting to choose exponential model because of ease of manipulation). But the advantage of the power law is that it allows for diminishing growth (exponent <1), whereas exponential model leads to always increasing values for positive arguments. This is another reason in hindsight where I wouldn't use a exponential model, since it predicts boundless growth of refractive index with increasing solute concentration--something which I find will be easily refuted by inspection of your data.
suggestion:


text:
Q: Convert MVC Website to be Responsive While investigating the Google SEO issue with respect to not having a mobile web site. I've learned recently that lack of proper mobile site would reduce the search ratings, and a different content for a mobile and a desktop sites might hurt your SEO as well.
Currently we have a MVC site that wasn't designed to be responsive. I don't want to create something that will require more maintenance. (IE new mobile site or creating new views for mobile versions..).
I've learned that converting the site to be responsive is technically possible but not recommended for the following two reasons:

*

*The current site might not work well on small screens.(CSS issues, modifying the CSS might be a pain and risky).

*We have too much stuff on the current site.

While googling, I found that this would be the best way to go.
Use the same controllers and views for both desktop and mobile browsers, but render the views with different Razor layouts depending on the device type. This option will require new CSS and new _Layout page for mobile devices.
and then modify the _ViewStart to be
Layout = Request.Browser.IsMobileDevice ? "~/Views/Shared/_LayoutMobile.cshtml" :"~/Views/Shared/_Layout.cshtml";

I would like to proceed with above approach, but If any one has any experience in this area, I would like to know the best practices, recommended approaches, and technical possibilities to achieve this.

A: There are typically three methods for handling Responsive Design :

*

*Using A Responsive Design Framework

*Using CSS Media Queries

*Using Percentages
The ease of using each of these will ultimately be based on how complex your existing Project is and how much you are willing to do and change to make it responsive.
Consider a Responsive Design Framework (basically revising and updating all of the markup of your existing project)
This will allow your site or application to run on basically any device (and look nice doing so) regardless of platform as long as it had an internet browser to access it and will make it much easier to develop as you will only need to create your page within one area and the beauty of Responsive Design is that it will style your pages appropriately based on the current platform and device.
It isn't really automatic and you will likely have to tinker with it a bit to get everything working and looking just as it should, but it is probably the best method of handling a situation like this (depending on the controls that you are using). There are Reponsive Design frameworks and boilerplates that you can use to implement these into your site such as Twitter Bootstrap.
These could fairly easily be integrated into a Web Forms, MVC or Web Pages and would basically be all that you would need to use :

*

*Great MSDN Article on Responsive Design

*Tutorial on Integrating Twitter Boostrap into ASP.NET Web Forms

*Beautify your ASP.NET Application with Twitter Bootstrap
The primary issue with using a framework here is that you already have your site designed and up and running. These frameworks work incredibly well when you use them from the beginning of the development of a project, however they will require a great deal more work when attempting to migrate an existing project to use them.
These frameworks have very specific classes and styles that actually do a ton of different things regarding responsive design and you'll have to use these new classes to replace basically all of your existing ones. It won't be the easiest migration, but it is certainly isn't impossible by any means and would be my recommendation.
Using CSS Media Queries (a neccessity if you want to handle creating this responsiveness without a framework, but more work on your part)
You can also accomplish this using CSS Media Queries, which target specific resolutions and screen sizes and style elements accordingly, however this is a bit more manual and you would have to write queries for each of the sizes that you are targeting.
These will take a quite a bit more work than using a framework as you will have to write queries to target all of the different major resolutions that you want and then within each of these actually resize some of your elements manually. You'll have to basically create a mini-stylesheet or media query for each of the resolutions that you want to target and manually enter the values that you want to use for that specific resolution.
I've done this more "hands-on" form of Responsive Design previously, but it is much easier to let something tried and proven like one of the frameworks handle it for you. Check out the very simple example below that will demonstrate how CSS Media Queries work :
        <style type='text/css'>
  /* Only affects 1600px width */
  @media only screen and (max-width: 1600px){ body { background: green; }}
  /* Only affects 1200px width */
  @media only screen and (max-width: 1200px){ body { background: blue; }}
  /* Only affects 900px width */
  @media only screen and (max-width: 900px){ body { background: yellow; }}
  /* Only affects 600px width */
  @media only screen and (max-width: 600px){ body { background: purple; }}
  /* Only affects 400px width */
  @media only screen and (max-width: 400px){ body { background: orange; }}
     </style>

and as you resize your browser / window, the styles will be applied accordingly.
Example (Editable Example)
Using Percentages (another option to provide a "responsive" feel, but it will require CSS Media Queries as well to be truly "responsive")
You could also consider migrating everything to use percentage-based sizing instead of explicit pixel sizes, but this is will be even more work than implementing the above media queries.
This will basically require you to scale everything on your site using percentages and defining minimum and maximum heights and widths for items. You'll likely have to use this in combination with media queries to get a truly effective solution.

A: ASP.NET MVC applications by default is responsive using Bootstrap.
http://weblogs.asp.net/jongalloway/two-free-video-courses-intro-to-asp-net-mvc-and-responsive-ui-with-bootstrap


text:
Q: Haskell list of pairs to pairs of lists I have seen here, that there are several approaches to solve it, but I am struggling to solve it with recursion.
Example:  [("a",1), ("b",2)] to (["a","b"] ,[1,2])
I have so far:
listOfPairs :: [ ( String , Int ) ] -> ( [ String ] , [ Int ] )
listOfPairs((a,b): xs) = ([a], [b]) -- and here I don't know how to call the function again with the rest xs

I have tried listOfPairs((a,b): xs) = ([a], [b]) + listOfPairs xs but obviously it doesn't work.
Maybe someone has an idea.
Thank you

A: This is the idea behind unzipping:
listOfPairs :: [(a, b)] -> ([a], [b])
listOfPairs = unzip

As for a recursive approach, you should make a recursive call and then append the elements to the the two items of the 2-tuple, so:
listOfPairs :: [(a, b)] -> ([a], [b])
listOfPairs [] = …
listOfPairs ((a, b):xs) = (a : …, b : …)
    where ~(as, bs) = listOfPairs …
Where I leave filling in the … parts as an exercise.


text:
Q: Getting Java mysql SQL Syntax error but my query seems normal I am developing a simple java mysql based application and during data insertion into the database I'm getting an SQL error mentioned below.
Here is my code:
public DBConnection() {
    try {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase?useUnicode=true&useLegacyDatetimeCode=false&serverTimezone=Turkey", "root", "");

        st = con.createStatement();

        System.out.println("CONNECTED!");

    } catch (Exception e) {
        System.out.println("Error  : " + e);
    }
}

public void addCustomer(String name, String surname, String company, String adress, String adressTwo){

  String addQuery = "insert into musteri (name,surname,company,adress,adressTwo) values (?,?,?,?,?)" ;

  try {
      st.executeUpdate(addQuery);
  System.out.println("Data Added");
  } catch (Exception e) {
      System.out.println("Error occured when adding value to database : " + e );
  }
}

Here is my java main method that add's the data:
public static void main(String[] args) {
    // TODO code application logic here

    Customers c1 = new Customers();

    c1.setIsim("test");
    c1.setSoyisim("test");
    c1.setSirket("test");
    c1.setAdres("test");
    c1.setIletisim("test");

    DBConnection db = new DBConnection();

    db.addCustomer(c1.isim, c1.soyisim, c1.sirket, c1.adres, c1.iletisim);
}

The error I'm getting is:

Error occured when adding value to database : java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''insert into musteri (ad,soyad,sirket,adres,iletisim) values (?,?,?,?,?)'' at line 1

A: May I suggest you implement addCustomer like this. Use a local Statement and create it by using try-with-resource style and then set your parameters for the query
public void addCustomer(String name, String surname, String company, String adress, String adressTwo){
    String addQuery = "insert into musteri (name,surname,company,adress,adressTwo) values (?,?,?,?,?)" ;

    try (PreparedStatement stmt = con.prepareStatement(addQuery)) {
        stmt.setString(1, name);
        stmt.setString(2, surname);
        stmt.setString(3, company);
        stmt.setString(4, adress);
        stmt.setString(5, adressTwo);
        stmt.executeUpdate();
        System.out.println("Data Added");
    } catch (Exception e) {
        System.out.println("Error occured when adding value to database : " + e );
    }
}

A: You are mixing statements with prepared statements. You should use a prepared statement and set the values to it:
public void addCustomer(String name, String surname, String company, String address, String adressTwo) {
    String addQuery = "insert into musteri (name, surname, company, adress, adressTwo) values (?,?,?,?,?)" ;

    // Shown here for simplicitly.
    // The query could be prepared once and stored in a data member
    try (PreparedStatement ps = con.prepareStatement(addQuery)) {
        ps.setString(1, name);
        ps.setString(2, surname);
        ps.setString(3, company);
        ps.setString(4, address);
        ps.setString(5, addressTwo);
        ps.executeUpdate();
        System.out.println("Data Added");
    } catch (Exception e) {
        System.out.println("Error occured when adding value to database : " + e );
    }
}


text:
Q: Discord Bots in Python I was following a tutorial on making discord bots when I came across a problem.
I'm trying to connect the client to discord using my token, using the code below:
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

client = discord.Client()

@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')

client.run(TOKEN)

`
I also have a separate .env file which looks like this:
DISCORD_TOKEN="***" ## yeah I'm not giving anyone my token

I ran this in the command prompt and I got this error:
  File "discordBot.py", line 15, in <module>
    client.run(***)
NameError: name '***' is not defined ## Once again not actually my token

The only thing I've noticed is that the name that isn't defined isn't actually the full token and it stops after a ".", I tried putting the entire thing in quotes on the .env file but that didn't fix it.

A: This is a client side problem. It would be useful if you could post in your question what service you are using to host the bot. It is a problem with either your server or something with your API key. Make sure the key is right. I don't see anything wrong with your program, if you are saving the responses in a file on your computer make sure its in RB or WB format. Other formats will cause your program to glitch. Best of luck with your bot! This also might be because you are asking the user for an API key and he does not have one. You should switch your async data.


text:
Q: JavaFx ListView for load Messages in chat application i wanna write a chat app with a listview for messages item.
it's load messages at top and bottom of listview.
i want when messages added at top and bottom of listview scrollbar doesn't move.
(maybe this is because of javafx doesn't support  'cells of different lengths').

A: Try check ScrollTo Method tabWiew also ScrollTo Method ListView you just tell witch index should be showed always


text:
Q: Admob is not displayed during the app's first execution I made an Android app with Phonegap (Cordova 2.5.0). And I put admob in my app using this plugin.
Admob is displayed in my app. But there's a problem. During the first execution, admob's not showing up. After closing the app and re-starting it, admob is displayed. From the second execution onwards, admob is displayed.
If I don't use the app for a while (about one hour), then run the app, the problem comes up again.
What can I do to fix problem?
Thanks for your advice.


text:
Q: Custom search filter in angular JS I have listed some invoice in my listing page. I have multiple search input. I want to search related data which I will upload in related field.
I have Invoice Number, Customer Name, From Date, To Date and status search input box. if I enter something in Invoice Number field This text should be search from the Invoice Number column from invoice listing data.
Same as other field.
See my screenshot. There have only two search field Invoice Number and Customer Name I will add more filter.

Please say me how to filter it?
I have tried with below filter. But that one not working.
Filter Input:
<input name="invoice_number" placeholder="Invoice Number" class="form-control ng-model="invoice_name" type="text">
<input name="customer_name" placeholder="Customer Name" class="form-control" ng-model="customer_name" type="text">

Listing:

     {{ x.invoice_number}}
     {{ x.customer_name}}
     {{ x.company_name}}
     {{ x.total_invoice | currency : $}}

     {{ x.created | datetime }}

         <button class="btn btn-success btn-xs" uib-tooltip="Preview Invoices" tooltip-placement="top"></button>
         <button class="btn btn-warning btn-xs" uib-tooltip="Download Invoices" tooltip-placement="top"></button>

If I searched 2016113CC in Customer Name field I am getting wrong filter. See screenshot:

A: You should define on what property your input will be used
<input name="invoice_number" placeholder="Invoice Number" class="form-control ng-model="invoice_name" type="text">
<input name="customer_name" placeholder="Customer Name" class="form-control" ng-model="customer_name" type="text">

     {{ x.invoice_number}}
     {{ x.customer_name}}
     {{ x.company_name}}
     {{ x.total_invoice | currency : $}}

     {{ x.created | datetime }}

         <button class="btn btn-success btn-xs" uib-tooltip="Preview Invoices" tooltip-placement="top"></button>
         <button class="btn btn-warning btn-xs" uib-tooltip="Download Invoices" tooltip-placement="top"></button>

A: What you need to do is something like this, you'll bind the search to an overall name:
<input name="invoice_number" placeholder="Invoice Number" class="form-control ng-model="search.invoice_number" type="text">
<input name="customer_name" placeholder="Customer Name" class="form-control" ng-model="search.customer_name" type="text">

    //more code here

A: After follow the @Weedoze answer I have created multiple filter with sorting. Please check this link -
https://github.com/AngularJScript/AngularJS-Search-Multiple-Sort-column-Filter-Example
Demo


text:
Q: Cumulative distribution of sum of two uniformly distributed random variables with a trapezoidal PDF Let $P$ and $B$ be two independent random variables with $P\sim U(\alpha,1)$ and $B\sim U(0,\alpha)$, where $\alpha \in[\frac{1}{2},1]$. I am interested in the distribution of the sum $Z=\frac{P+B}{2}$, and specifically, the probability that $(1-\alpha) \le Z \le \alpha$.
Following the steps from this post, I believe that the pdf of $Z$ might be the trapezoid given by:
$ f(Z) = \begin{cases}
\frac{4}{\alpha(1-\alpha)}Z-\frac{2}{1-\alpha}&, \frac{\alpha}{2}\le Z\le\frac{1}{2} \\
\frac{2}{\alpha}&, \frac{1}{2}\le Z\le \alpha \\
\frac{-4}{\alpha(1-\alpha)}Z+\frac{2(1+\alpha)}{\alpha(1-\alpha)}&, \alpha \le Z \le \frac{1+\alpha}{2} \\
0&, otherwise
\end{cases} $
...in which case, the probability that $(1-\alpha) \le Z \le \alpha$ would include parts of the first two cases. Is this geometric way the best approach, or is it possible to compute the CDF of $Z$ more generally?


text:
Q: Why does my if and elif statements only work for one button at a time? I have my program display a list of buttons stored in a json file. I have each button's stored time, honey, compared to the current time, time.time() and the delay that the user inputs.
For some reason the conditional only works when there is one button. Once I add an additional button the program turns the first button green to indicate its early and the new button turns yellow to indicate that it is early. Once the new button turns red the first button turns red as well.
I have timed the program and the program runs at the correct time. Why am I having this problem and how would I fix it? Code:
class MainApp(App):
    def build(self): # build() returns an instance
        self.store = JsonStore("streak.json") # file that stores the streaks:
        Clock.schedule_interval(self.check_streak, 1/30.)

        return presentation

    def check_streak(self, dt):

        for child in reversed(self.root.screen_two.ids.streak_zone.children):
            honey = float(child.id)

            with open("streak.json", "r") as read_file:
                data = json.load(read_file)

            for value in data.values():
                if value['delay'] is not None:
                    delay = int(value['delay'])

                    if delay > time.time() < honey: # early (yellow)
                        child.background_normal = ''
                        child.background_color = [1, 1, 0, 1]

                    elif delay > time.time() > honey: # on time (green)
                        child.background_normal = ''
                        child.background_color = [0, 1, 0, 1]

                    elif delay < time.time() > honey: # late (red)
                        child.background_normal = ''
                        child.background_color = [1, 0, 0, 1]

def display_btn(self):
        # display the names of the streaks in a list on PageTwo
        with open("streak.json", "r") as read_file:
            data = json.load(read_file)

        for value in data.values():
            if value['delta'] is not None:
                print(f"action={value['action']}, delta={value['delta']}, grace={value['delay']}")
                streak_button = StreakButton(id=str(value['delta']), text=value['action'],
                                            on_press=self.third_screen, size=(400,50),
                                            size_hint=(None,None))
                self.root.screen_two.ids.streak_zone.add_widget(streak_button)

total = ((int(self.streak.day) * 86400) + (int(self.streak.hour) * 3600) +
                    (int(self.streak.minute) * 60)) # convert into seconds

            self.current_time = time.time()
            self.count = self.current_time + total
            grace = (int(self.streak.delay) * 60) + self.count # aka delay

            parsed = True

            # delete later just used to test
            print("[seconds:", total,']' , "[action:", self.streak.action,']',
                 "[grace:", grace,']')

            # store streak attributes inside "streak.json"
            self.store.put(self.streak.action, action=self.streak.action,
                          delay=grace, seconds=total,
                          score=0, delta=self.count)

streak.json file: {"one": {"action": "one", "delay": 1557095861.2131674, "seconds": 60, "score": 0, "delta": 1557095801.2131674}, "two": {"action": "two", "delay": 1557096131.7338686, "seconds": 60, "score": 0, "delta": 1557096071.7338686}}

A: It works for only one button because the if...elif statements are outside the for loop.
Solution
Move the if...elif block into the if value['delay'] is not None: block inside the  for loop.
Snippets
def check_streak(self, dt):

    for child in reversed(self.root.screen_two.ids.streak_zone.children):
        honey = float(child.id)

        with open("streak.json", "r") as read_file:
            data = json.load(read_file)

        for value in data.values():
            if value['delay'] is not None:
                delay = int(value['delay'])

                # fix for later
                if delay > time.time() < honey: # early (yellow)
                    child.background_normal = ''
                    child.background_color = [1, 1, 0, 1]

                elif delay > time.time() > honey: # on time (green)
                    child.background_normal = ''
                    child.background_color = [0, 1, 0, 1]

                elif delay < time.time() > honey: # late (red)
                    child.background_normal = ''
                    child.background_color = [1, 0, 0, 1]

A: The problem was that having two loops caused my data to get mismatched. I needed to be able to either iterate over the button objects and only use the correct json file dictionary entry for each, or iterate over the json file and only modify the corresponding child. I decided to use the former.
I set up the code so that for every child in the streak_zone name = child.text
I then compare every key in my json file to the name of the button aka child
if the name of the key is equal to name then we get the value of the nested key delay
New code:
def check_streak(self, dt):

        for child in reversed(self.root.screen_two.ids.streak_zone.children):
            honey = float(child.id)
            name = child.text

            with open("streak.json", "r") as read_file:
                data = json.load(read_file)

            for key in data.keys():
                if key == name:
                    delay = data.get(key, {}).get('delay')

                if delay > time.time() < honey: # early (yellow)
                    child.background_normal = ''
                    child.background_color = [1, 1, 0, 1]

                elif delay > time.time() > honey: # on time (green)
                    child.background_normal = ''
                    child.background_color = [0, 1, 0, 1]

                elif delay < time.time() > honey: # late (red)
                    child.background_normal = ''
                    child.background_color = [1, 0, 0, 1]


text:
Q: Merge specific XML elements if element values are equal I want to sum the values of  "TotalAmount" and "Tax" with //Category/ID and //Category/Percent as unique value. The XSLT has to delete the duplicate(s) and sum the values of "TotalAmount and "Tax". So for this example, ID "S" AND Percent "21" is a duplicate and should be deleted. The required values should be added to the other record of  "S" and "21".
At this moment, I'm able to succeed for a part of the written requirements
Example 1: https://xsltfiddle.liberty-development.net/93F8dUD/2
First merge is working fine. "S" and "21" are duplicates and the XSLT merge part is working for the first 2 records. However, it also merges the TotalAmount and Tax of the last 2 records, which shouldn't happen.
Example 2: https://xsltfiddle.liberty-development.net/3MXNWNA
XSLT is working for the first 2 records. No merge, ID "S" is a duplicate, but Percent isn't. For the last 2 records, the same issue as described in example 1.
Seems like a minor change would fix this issue, unfortunately, I'm not able to find it by myself.

A: It seems a single key that concatenates the two values and then simply an empty template for the duplicates and a sum for the relevant elements suffices:
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:key name="group" match="Total" use="concat(Category/ID, '|', number(Category/Percent))"/>

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Total[not(generate-id() = generate-id(key('group', concat(Category/ID, '|', number(Category/Percent)))[1]))]"/>

    <xsl:template match="TotalAmount">
      <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:value-of select="sum(key('group', concat(../Category/ID, '|', number(../Category/Percent)) )/TotalAmount)"/>
      </xsl:copy>
    </xsl:template>

    <xsl:template match="Tax">
      <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:value-of select="sum(key('group', concat(../Category/ID, '|', number(../Category/Percent)) )/Tax)"/>
      </xsl:copy>
    </xsl:template>

</xsl:stylesheet>


text:
Q: Oracle HTTP Server Ubuntu Installation I have a problem about Oracle HTTP Server installation on Ubuntu system.I read release notes and installation guides all information about Linux EE editions Redhat atc. I have an error during the installation process said Checking installation system certification (unchecked).I saw required package information about Linux EE versions but cant find about Ubuntu distro. Anyone know which package I need?
This is my error message during my installation:
Check complete. The overall result of this check is: Failed
Problem: Some recommended packages are missing (see above).
Recommendation: You may actually have installed packages which have obsoleted these, in which case you can successfully continue with the install. If you have not, it is recommended that you do not continue. Refer to the product release notes to find out how to get the missing packages and update the system.


text:
Q: Application id in the blackberry push notification is expired For push notification in blackberry, i got application id from rim. It will valid only 4 months. For getting permanent application id what i do.

A: You have to contact the person who gave you the push credentials. And request them to upgrade your EVAL credentials to Production push credentials.


text:
Q: Using Matplotlib and numpy to plot a system of equations I'm trying to learn how to use matplotlib and numpy to plot systems of equations for one of my classes. We haven't been given much guidance, and I'm not too great with programming and I can't really understand how to do this, although i don't think its too complicated. Basically, I have a system of equations like this:
4x -2y + z =11
-2x +4y -2z = -16
x -2y + 4z = 17

How can I use matplotlib to plot the graphs for each of these equations?
Thanks!
Edit: The instructions also say to use mplot3d as well.
EDIT: SOLUTION: How to draw planes from a set of linear equations in Python?

A: You can eliminate z from the first two equations to give x=1 and the line of intersection of the first two planes z=7+2y, and then solve with the remaining equation to give the point (1,-2,3). You can verify this with numpy.linalg.solve:
In [11]: M = np.array([[4., -2., 1.], [-2., 4., -2.], [1., -2., 4.]])

In [12]: b = np.array([11., -16., 17.])

In [13]: np.linalg.solve(M, b)
Out[13]: array([ 1., -2.,  3.])

In Matplotlib, the planes can be plotted with plot_surface, the line of intersection of the first two (in blue) with plot and a marker used for the point at which the third plane (in green) intersects the line.
Make the planes a bit transparent with alpha=0.5 and because the planes re flat, there's no need for marker lines to tile the surfaces (you can set the row strides and column strides to something large):
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x, y = np.linspace(-8,8,100), np.linspace(-8,8,100)
X, Y = np.meshgrid(x,y)
Z1 = 11 - 4*X + 2*Y
Z2 = (16 - 2*X + 4*Y) / 2
Z3 = (17 - X + 2*Y) / 4

ax.plot_surface(X,Y,Z1, alpha=0.5, rstride=100, cstride=100)
ax.plot_surface(X,Y,Z2, alpha=0.5, rstride=100, cstride=100)

ax.plot((1,1),(-8,8),(-9,23), lw=2, c='b')
ax.plot_surface(X,Y,Z3, alpha=0.5, facecolors='g', rstride=100, cstride=100)
ax.plot((1,),(-2,),(3,), lw=2, c='k', marker='o')

plt.show()


text:
Q: Unable to fetch webpage content from https://play.google.com/store/apps/ programatically on AWS I have a java application running on AWS EC2 which scrapes app information from https://play.google.com/store/apps/
Everything was running fine until today.
Seems google has started blocking server because of frequent hits.
I tried from another server it was running fine, and that was blocked as well after few hours
Here is my code:
Document doc = Jsoup.connect("https://play.google.com/store/apps/details?id=" +appId).timeout(10000).get();

I get all page content in doc and parse it.
What should I do to get access?
Thanks in Advance

A: you have been throttled by google. They do so to block crawler and robots, so you have to limit your calls to google (or contact them to partner with them, but I doubt you want to do so)


text:
Q: How to process only last event in a period? I receive a lot of events with interval of a second. I want to precess the most recent event each second. eg
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15. 5 events per second.Thus i want proceed only events 5 on second 1, 10 on second 2,15 on second 3. I tohught about flowable  but it just introduce delay between events, and debounce will not trigger if event stream is constant

A: Seems that throttleLast(1, TimeUnit.SECONDS) is what you need. It emits only the last item emitted by a reactive source during sequential time windows of a specified duration.
sample() operator rx docs
throttleLast() description


text:
Q: Disaster recovery set up for Azure Data Factory service I just added azure data factory service to my subscription. During the setup I was able to select only one region, what happens if disaster happens in this region? How does ADF guarantees high availability?
Do we need to wait till recovery or is there any similar setup like in ADLS2(GRS & RA-GRS).

A: No statements of Disaster Recovery could be found in the ADF official document.Based on my researching,ADF only provides cloud-based data integration work flow, the DR is affected by the supported data stores in ADF actually. I provide some clues for your reference:
1.The statement of Location option when you create ADF:

2.High availability for Azure Integration Runtime,it is affected by DU setting(allocation of compute resources):https://learn.microsoft.com/en-us/azure/data-factory/copy-activity-performance-features#data-integration-units
3.High availability for Self-Hosted Integration Runtime,it could be better if you create multiple nodes in  the on-premise environment:https://learn.microsoft.com/en-us/azure/data-factory/create-self-hosted-integration-runtime#high-availability-and-scalability


text:
Q: About the singularity of $z^{-2}\sin z$ at $\infty$ On Priestly's Introduction to Complex Analysis, second edition, at page 206 it says that $z^{-2}\sin z$ has removable singularity at $\infty$. If this is not a typo, what's the reasoning behind it?

A: $\sin(z)$ has an essential singularity at infinity (it is periodic so it takes lots of value (in fact all of $\Bbb C$) infinitely often)
Since $z^2$ doesn't have an essential singularity there, $z^{-2}\sin(z)$ also has an essential singularity at $\infty$.
Saying what is the typo and what he meant to be writing is hard to tell without more context.

A: It is not a typo. We refer to points at infinite as singularity points on complex analysis, because their substance revolves around a lot of calculations and crucial stuff.
For your specific example, we have the function :
$$f(z) = \frac{1}{z^2}\sin(z)$$
The function $f(z)$ has an essential singularity because of $\sin(z)$ which can take infinitely many values at some point $\infty$ due to its periodic nature.
So, the point at $\infty$ acts like a singularity point to your function $z$. More specifically, you'll see about singularities at $\infty$ when you'll be learning about residues (shortly if not already, judging on your "residue-calculus" tag), which are important there. For example, here is a formal statement for a residue at $\infty$ and the condition that shall be met (the singularity at infinity) :

Residue at infinity :
  $$\text{Res}(f(z),\infty) = -\text{Res}\bigg(\frac{1}{z^2}f\bigg(\frac{1}{z}\bigg),0\bigg)$$
  If the condition :
  $$\lim_{|z| \to \infty}f(z) = 0$$
  is met, then the residue at infinity can be computed using the following formula :
  $$\text{Res}(f,\infty)= -\lim_{|z|\to \infty}zf(z)$$
  If instead :
  $$\lim_{|z| \to \infty}f(z) = c \neq 0$$
  then the residue at infinity is :
  $$\text{Res}(f,\infty)= -\lim_{|z|\to \infty}z^2f'(z)$$

It's also interesting to note, that every non-constant entire function $f:\mathbb C \to \mathbb C$ has a singularity at infinity. Technically, $f$ has a singularity at $\infty$ by virtue of not being defined there.  What is really meant is that a non-constant entire function $f$ has a non-removable singularity at $\infty$, and this follows directly from Liouville's theorem: if the singularity at $\infty$ was removable, $f$ would be bounded in a neighbourhood of $\infty$, say $\{z: |z| \ge r\}$, and since $f$ is also bounded on $\{z: |z| \le r\}$ (because a continuous function is bounded on a compact set) $f$ would be bounded on $\mathbb C$, therefore constant by Liouville's theorem.


text:
Q: Web API 2 returning text/plain responses Really struggling with something I hope people here can help with.  I'm writing a RESTful API in Web API 2.  Whenever I send a request to this service, the response is consistently being sent with a Content-Type of text/plain.  Obviously this is no good, my response needs to be Content-Type of application/json.  I've tried a few suggestions that I found from Google but I don't think I'm understanding the whole picture.
Is there something special I need to do in order to have my web service respond with application/json content?  Note that I want this to work globally across the whole app, so I'm not after a way to modify a given response and set its content type - I want this to be a default behaviour for the whole web service:  If a request contains an Accept header for application/json I want my web service to return that Content-Type instead of text/plain.
Edit to clarify:
My response contains an object called "responseData" that should be serialized into JSON and included in the body.  I'm currently putting together my response like this:
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, responseData);
return response;

responseData is a POCO.  This get's correctly serialized as JSON and returned in the response - the only missing part is the Content-Type which is incorrectly set to "text/plain".  I could manually change this on every single response I compose, but I'm wanting to configure this on a global level.

A: OK, assuming that your responseData is a string, the Content-type header will be text/plain when you create the HttpResponseMessage.  Doesn't matter what the contents of the string are, since no attempt is made to determine this.
The solution is to create the appropriate Content object for your message, initialized with the media type you're returning:
HttpResponseMessage response = new HttpResponseMessage()
    {
        Content = new StringContent(
                responseData,
                Encoding.UTF8,
                "application/json"
            )
    };

There are other methods that amount to returning a particular object type and letting the API libraries serialize to JSON or XML for you as required.  I prefer to let the framework do the work for me where possible, but this is how you'd achieve it with a string you've created yourself.

For a strict JSON-only result, remove the XML formatter from the WebAPI configuration and return your POCO.
In App_Start\WebApiConfig.cs, add the following to the WebApiConfig.Register method:
config.Formatters.Remove(config.Formatters.XmlFormatter);

And for your API:
public class MyObject
{
    public bool result;
    public string reason;
}

public class TestController : ApiController
{
    public MyObject GetData()
    {
        MyObject result = new MyObject { result = "true", reason = "Testing POCO return" };
        return result;
    }
}

I ran this up and requested /api/Test from Chrome, which doesn't even mention application/json in the Accept header.  Here are the response headers up until it hits Content-Type:
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8

And the body:
{"result":true,"reason":"Testing POCO return"}

Since I disabled XML it defaulted to JSON.

A: Add the following to Global.asax file.
protected void Application_Start()
{

JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
serializerSettings.Converters.Add(new IsoDateTimeConverter());
var jsonFormatter = new JsonNetFormatter(serializerSettings);
jsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
GlobalConfiguration.Configuration.Formatters.Insert(0, jsonFormatter);

}

A: Another possible source of the issue described is that there may be an authorization redirect in play as was the case for us when one of the engineers thought to re-use user authentication for an api.
This means incoming requests were being redirected to a login page which was the text/html response that couldn't be parsed by ReadAsync<>. A silly mistake to be sure, but not an easy one to spot.
The solution in that case was to remove the user authentication and implement HMAC based authentication for the api.


text:
Q: Python: Store HDF works first time, but no second I have a dataframe which I store in a HDF file with the following command:
# store data in HDF5 format
store = pd.HDFStore('data.h5')
store.put('data',data)
store.close()

It works all fine.
In another code, I load the dataframe again, which also works fine, and store it again after adding two columns.
Load:
df = pd.read_hdf('data.h5', key=None, mode='r')

And save again:
store = pd.HDFStore('data.h5')
store.put('data',data)
store.close()

However, when saving the second time, I get the following warning:

PerformanceWarning:  your performance may suffer as PyTables will
  pickle object types that it cannot map directly to c-types
  [inferred_type->mixed,key->block3_values] [items->['a', 'b', 'c']]
if self.run_code(code, result):

Interestingly, the warning does not refer to the two added columns, but to columns that were saved completely fine the first time and not touched in the code. Is there something that pd.read_hdf does to the column types or so? Or am I missing something?
Thank you


text:
Q: Remove span outside of div on input due to Rails 3 `field_with_errors` In my Rails 3 app I remove a  that I use as a placeholder on input with jQuery. If I submit the form and I have errors, the form reloads and the errors are shown. However, for the fields where there were errors, the  won't clear on input because the  is no longer within the
 containing the input. (This is due to the field_with_errors
 added from the error.) How can I work around this and still remove the  despite field_with_errors?
Here's my jQuery:
// placeholder label for text
$(function() {
    $("span.holder + input").keyup(function() {
        if($(this).val().length) {
            $(this).prev('span.holder').hide();
        } else {
            $(this).prev('span.holder').show();
        }
    });
    $("span.holder").click(function() {
        $(this).next().focus();
    });
});

My html with field_with_errors (jQuery doesn't work):

  Email

    <input autocomplete="off" id="user_email" name="user[email]" size="38" type="text" value="">

My html without field_with_errors (jQuery works):

  Last name
  <input autocomplete="off" class="inner" id="user_profile_attributes_last_name" name="user[profile_attributes][last_name]" size="18" type="text">

A: What about
$('.holds').find('input').keyup(function ()
{
    if ($(this).val().length)
    {
        $(this).closest('.holds').find('.holder').hide();
    }
    else
    {
        $(this).closest('.holds').find('.holder').show();
    }
});

$('span.holder').click(function ()
{
    $(this).parent().find('input').focus();
});

jsFiddle


text:
Q: preserving whitespace with svg.js I would like to draw text with SVG.JS and preserve whitespace
var draw = SVG('drawing')
var text = draw.text("040: .P .E       .L 01                         ")

just prints:
040: .P .E .L 01

I was suggested
this.el.lines.each(function() {
      this.exportAttr({
        'xml:space': 'preserve'
      })
    })

but this doesn't seem to work, as https://raw.github.com/wout/svg.js/master/dist/svg.js doesn't contain exportAttr.

A: I see my suggestion was wrong because it targets the export plugin.
It should be this of course:
var text = draw.text(' with     a lot of    white t e    s p a c e')
text.lines.attr('xml:space', 'preserve', 'http://www.w3.org/XML/1998/namespace')


text:
Q: Browserify + gulp becoming slow We've been using gulp and browserify to create builds of our project whenever a js file changes. As the project has grown this process has become incredibly slow, from 200ms -> ~5s. The project has 69 directories, 173 files, and a max depth of 4 folders. We are applying a few transforms. Here's our build code.
var buildJS = function (entryPoint, name, cb) {
    var browserify = require('browserify');
    var uglify = require('gulp-uglify');
    var source = require('vinyl-source-stream');
    var buffer = require('vinyl-buffer');
    var reactify = require('reactify');
    var literalify = require('literalify');
    var brfs = require('brfs');

    browserify()
        .require(entryPoint + '/' + name + '.jsx')
        .transform({
           global: true
        }, reactify)
        .transform({
           global: true
        }, brfs)
        .transform({
           global: true
        }, literalify.configure(literalifyConfig))
        .external(config.libs)
        .bundle({
            debug: config.DEV,
            //detectGlobals : false
        })
        .on('error', handleError)
        .pipe(source('bundle.js'))
        .pipe(buffer())
        .pipe(gulpIf(!config.DEV, uglify()))
        .pipe(gulp.dest(config.buildPath + '/' + name))
        .on('finish', cb)
};

Is this just normal behavior based on our project size? Or are we doing something wrong?

A: That's because browserify always recompile everything. You should be using incremental builds instead if you want good perfs.
I've developed a gulp plugin precisely for that: https://github.com/ngryman/gulp-bro.


text:
Q: Should rpc.statd write anything into wtmp? On several linux machines (some old custom variant of gentoo) I have huge wtmp files, up to gigabyte in size. After some experiments I know that there is rpc.statd daemon running on all servers and there is monitoring running with rup command. Monitoring server runs rup every minute with list of all machines; so statistics are collected.
After each run of rup the wtmp file is getting bit larger.
My question: Should rpc.statd update wtmp and what will it write into wtmp? My last command does not extract anything about rup, rpc.statd from wtmp.


text:
Q: In $ΔABC$, if $(a+b+c)(a−b+c)=3ac$, then what can be say about the angles of the triangle? In $ΔABC$, if $(a+b+c)(a−b+c)=3ac$, then which of the following is $\color{green}{\text{True}}$?

*

*$\angle B=60^\circ $

*$\angle B=30^\circ $

*$\angle C=60^\circ $

*$\angle A + \angle B=120^\circ $

A: $(a+b+c)(a-b+c)=3ac$
 $(a+c)^2$ - $b^2$ = 3ac
 $\frac{a^2+c^2-b^2}{2ac}$ = $\frac{1}{2}$
 Hence by the cosine rule for triangles,
 $cos B$ = $\frac{1}{2}$ which implies that B=$60^o$ because B cannot exceed $180^o$. Thus, A+C = $120^o$ and not A+B.

A: You must show your attempts here first before any help can be given to you. As a hint: expand the left side and use the identity: $b^2=a^2+c^2-2ac\cos B$ to solve for $\cos B$ and then for $B$.


text:
Q: How to change default discount in python using classes and inheriance? I was trying to change the discount rate of a particular sub class, while the default is set at 0, and in subclass it changes to 5, however, this is not refelected.
I cannot switch the discount scheme on Class B, because all class need to have access on it.
class A:
    def __init__(self, x, y, discount=0):
        self.discount=0
        if self.discount>0:
            discount = self.discount
        else:
            discount=0
        self.discount=discount
        self.x=x
        self.y=y
        self.discount=discount
        discount=5
class B(A):
    def __init__ (self,x,y,z):
        super().__init__(x,y)
        B.z=z
        B.discount=5

class C(A):
    def __init__ (self,x,y,a):
        super().__init__(x,y)
        C.a=a
        C.discount = 10
        a = y*10

one=A(1,2)
print(one.x)
print(one.discount)
two = B(1,2,3)
print(two.x)
print(two.z)
print(two.discount)
three = C(4,5,6)
print(three.x)
print(three.discount)

Output:
1
0
1
3
0
4
0

Tried to do some calculations and integrate methods, but it only works for methoid but not on the class, as you can see, the discount is set to 0 and doesn't change.

A: The constructor of your A class seems quite confusing. If the only thing you need is to check if the discount parameter is greater than 0 and set it to your instance's discount variable, you can simplify your code like this:
class A:
    def __init__(self, x, y, discount=0):
        self.discount=0
        if discount>0:
            self.discount = discount
        self.x=x
        self.y=y

Moreover, when you try to modify an instance variable in a subclass, you can still use self:
class B(A):
    def __init__ (self,x,y,z):
        super().__init__(x,y)
        self.z=z
        self.discount=5

class C(A):
    def __init__ (self,x,y,a):
        super().__init__(x,y)
        self.a=a
        self.discount = 10
        a = y*10

Running the commands again, you 'll get:
1
0
1
3
5
4
10

You can find more about instance and class variables here and inheritance here.


text:
Q: Problem predicting caret::train random forest ("rf") model I´ve been working in a random forest model for credit scoring in R. I've trained a model using caret::train.
My data "df_samples_rf" has the next structure:

control <- trainControl(method="repeatedcv",
                    number = 10,
                    repeats = 5,
                    search = "grid",
                    classProbs = T,
                    savePredictions = T,
                    summaryFunction = twoClassSummary,
                    allowParallel = T)

tune_grid <- expand.grid(.mtry = c(3:15))#1

rf_gridsearch <- NULL

rf_gridsearch <- train(bad ~.,
                       data = df_samples_rf[-27],
                       method = "rf",
                       metric = "ROC",
                       tuneGrid = tune_grid,
                       trControl = control)

I get the next results:

And:

So I assume the model can perform well.
Then I try to predict like this:
rf_predictions <- predict(rf_gridsearch$finalModel,
                          newdata = df_no_yes)

Data "df_no_yes" has exactly the same structure and class variables as "df_samples_rf", predicted variable also have the same class and levels.
results <- data.frame(real = df_no_yes$bad,
                      rf_predictions)

I run a confusionMatrix and get:
confusionMatrix(results$rf_predictions, results$real)

Why does caret::train have models with good ROC-AUC and classification metrics, and when predicting over a new set of data, I get so bad results? Am I doing something wrong? Applying the predict in the wrong way?


text:
Q: Error when passing parameters in components in react using Typescript When I pass the value parameter from App component to App2 component in react using typescript, it is giving an error
Property 'value' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<App2> & Readonly<{ children?: ReactNode; }> & Read...

The code of App.tsx is
import * as React from "react";
import './App.css';
 import App2 from './App2';

class App extends React.Component<any,any>{

  public render(){
    return(

            <App2 value = {5}/>

    )
  }

}
export default App;

and the code of App2 component is :-
import * as React from "react";

class App2 extends React.Component{

    public render(){
        return(

Hello world

        )
    }
}
export default App2;

A: You need to specify the type for the properties to tell the compiler what properties are valid on the App2 component and what their types are:
class App2 extends React.Component<{ value: number }>{

  public render() {
    return (

Hello world

    )
  }
}