Q: Get node value xml with LINQ c# I can't get the value of this XML node.
I need to get the <LimitValue> value and give the user the possibility to change it.
I have already tried this solution, but it doesn't work:
namefile = Files[select].Name;
XDocument document = XDocument.Load(@"C:\Users\lab\Desktop\copy\spectro\" + namefile);

Console.WriteLine("Inserisci lelemento chimico da modificare:");
var chimical = Console.ReadLine();

var nodes = (from n in document.Descendants("ControlItems")
             where n.Element("ControlItem").Attribute("Name").Value == chimical
             select new
             {
                 nodeLimitValueLW = (string)n.Element("LimitValue").Attribute("Type") == "LowerWarningLimit",
                 nodeLimitValueUW = (string)n.Element("LimitValue").Attribute("Type") == "UpperWarningLimit",
                 nodeLimitValueLA = (string)n.Element("LimitValue").Attribute("Type") == "LowerAcceptanceLimit",
                 nodeLimitValueUA = (string)n.Element("LimitValue").Attribute("Type") == "UpperAcceptanceLimit"
             }).ToList();

foreach (var n in nodes)
{
    Console.WriteLine(n.nodeLimitValueLW);
    Console.WriteLine(n.nodeLimitValueUW);
    Console.WriteLine(n.nodeLimitValueLA);
    Console.WriteLine(n.nodeLimitValueUA);
}

This is my XML:
<GradeLimits GradeName="1.5217" GradeDescription="20MnV6" Norm="TXC03" BaseElement="Fe">
    <ControlItems>
        <ControlItem Name="C" DisplayUnit="%">
            <LimitValue Type="LowerWarningLimit" Kind="Absolute" Unit="%">0.15999999642372131</LimitValue>
            <LimitValue Type="UpperWarningLimit" Kind="Absolute" Unit="%">0.2199999988079071</LimitValue>
            <LimitValue Type="LowerAcceptanceLimit" Kind="Absolute" Unit="%">0.15000000596046448</LimitValue>
            <LimitValue Type="UpperAcceptanceLimit" Kind="Absolute" Unit="%">0.23000000417232513</LimitValue>
        </ControlItem>
        <ControlItem Name="Si" DisplayUnit="%">
            <LimitValue Type="LowerWarningLimit" Kind="Absolute" Unit="%">0.10000000149011612</LimitValue>
            <LimitValue Type="UpperWarningLimit" Kind="Absolute" Unit="%">0.5</LimitValue>
            <LimitValue Type="LowerAcceptanceLimit" Kind="Absolute" Unit="%">0.090000003576278687</LimitValue>
            <LimitValue Type="UpperAcceptanceLimit" Kind="Absolute" Unit="%">0.51999998092651367</LimitValue>
        </ControlItem>
        <ControlItem Name="Pb" DisplayUnit="%">
            <LimitValue Type="UpperWarningLimit" Kind="Absolute" Unit="%">0.05000000074505806</LimitValue>
            <LimitValue Type="UpperAcceptanceLimit" Kind="Absolute" Unit="%">0.05000000074505806</LimitValue>
        </ControlItem>
    </ControlItems>
</GradeLimits>

For example:
The user wants to edit the <LimitValue> of the <ControlItem> with the attribute Name="Si"
They would type in the console "Si", and I would need to iterate on all <ControlItem>, until I find the <ControlItem> with the attribute Name="Si". I would then need to take all the  <LimitValue> and give the possibility to edit it.
I hope I have explained it well. Thanks in advance for the help.

A: Does not fully use Linq, but works for what you need.
    public class Limits
    {
        public string LowerWarningLimit = "";
        public string UpperWarningLimit = "";
        public string LowerAcceptanceLimit = "";
        public string UpperAcceptanceLimit = "";
    }

    public static void GetLimits(string nameFile)
    {
        XDocument document = XDocument.Load(nameFile);
        if (document == null)
        {
            Console.WriteLine("Document not found.");
            return;
        }

        XElement root = document.Descendants("ControlItems").FirstOrDefault();
        if (root == null)
        {
            Console.WriteLine("Could not find ControlItems.");
            return;
        }

        Console.WriteLine("Inserisci lelemento chimico da modificare:");
        var chimical = Console.ReadLine();
        XElement nameSearch = root.Descendants("ControlItem").FirstOrDefault(x => x.Attribute("Name") != null && x.Attribute("Name").Value.ToLower() == chimical.ToLower());
        if (nameSearch == null)
        {
            Console.WriteLine("Name not found.");
            return;
        }

        Limits limits = new Limits();
        foreach (XElement elements in nameSearch.Descendants())
        {
            string typeResult = elements.Attribute("Type").Value;
            if (typeResult == null)
            {
                continue;
            }

            switch (typeResult)
            {
                case "LowerWarningLimit":
                    limits.LowerWarningLimit = elements.Value;
                    break;

                case "UpperWarningLimit":
                    limits.UpperWarningLimit = elements.Value;
                    break;

                case "LowerAcceptanceLimit":
                    limits.LowerAcceptanceLimit = elements.Value;
                    break;

                case "UpperAcceptanceLimit":
                    limits.UpperAcceptanceLimit = elements.Value;
                    break;
            }
        }

        Console.WriteLine(limits.LowerWarningLimit);
        Console.WriteLine(limits.UpperWarningLimit);
        Console.WriteLine(limits.LowerAcceptanceLimit);
        Console.WriteLine(limits.UpperAcceptanceLimit);
    }

A:  static void Main(string[] args)
    {
        string xmlFilePath = @"C:\Users\vincenzo.lanera\Desktop\test.xml";
        XmlDocument document = new XmlDocument();
        document.Load(xmlFilePath);

        Console.WriteLine("Inserisci l'elemento chimico da modificare:");
        var chimical = Console.ReadLine();

        //Searches the limit values of the selected element
        XmlNodeList limitValues = document.SelectNodes($"//ControlItem[@Name='{chimical}']/LimitValue");

        //Prints all limit values
        Console.WriteLine($"Limit values of {chimical}:");
        foreach (XmlNode limVal in limitValues)
        {
            Console.WriteLine($"{limVal.Attributes["Type"].Value} {limVal.InnerText}");
        };

        //Ask the user wich limit value wants to edit
        Console.WriteLine("Inserisci il limit value da modificare:");
        var limitValueToEdit = Console.ReadLine();

        //Ask the user the new value
        Console.WriteLine("Inserisci il nuovo valore:");
        var newVal = Console.ReadLine();

        //Edit the limit value
        var nodeToEdit = document.SelectSingleNode($"//ControlItem[@Name='{chimical}']/LimitValue[@Type='{limitValueToEdit}']");
        nodeToEdit.InnerText = newVal;

        //Save the changes to the xml file
        document.Save(xmlFilePath);
    }
}

You should also handle the errors if the user inserts an invalid text.


Q: What PHP/Shell Framework can be used to access HTTP-POST/-GET Forms (besides curl)? I'm searching an abstraction layer from pure HTTP-POST/-GET using curl. It should somehow make it easy to define the Targeted script and it's variables.
I read something exists in the FreeX (german unix/programming magazine), but don't have the named magazine at hand.
What can I do?
Stick with curl?
What alternatives do exist?
Thank you in advance :)

A: As you tagged you question with "perl", you can use Perl. Try LWP - popular module, and much more convenient than curl. For more complex tasks, try WWW::Mechanize.

A: You might want to look at the HTTP Extension.  It looks like a pretty complete abstraction implemented over curl.

A: If you want something more sophisticated, there is the Zend_Http_Client ZF Component.

A: You can use Streams to POST also. I generally prefer that over an extension or even cURL since it's core PHP and more likely to be there.
Though, I build open source software that gets installed on machines where the user has low privileges and likely zero control. Your users' options may be different.


Q: How to dynamically add Proto Members in Protobuf-net Long time ago as @Marc stated in one of the threads that protobuf-net has no support for dynamic. Is that statement still valid? If not then can someone share an example how we can dynamically add the members in Protobuf-net.

A: That is still correct. protobuf-net supports unexpected data via the IExtensible / Extensible API, but this is to support a different scenario. There is currently no support for having the DTO types themselves as dynamic. To do so would require significant work: that isn't a problem if there is a genuine problem to address (for example, the meta-programming re-work to allow for full pre-compilation, to support mobile / metro was significant work - but still happened). But in the case of dynamic it is not obvious to me what scenario this would usefully target.


Q: Calculating Averages and Determining Lowest and Highest Values I have split up a list with names and corresponding scores and have stored them in a dictionary called students. But with these scores, I have been asked to figure out the average score, minimum score and maximum score. I am a beginner and a student so a step by step explanation would be greatly appreciated.
def getStatistics(students):

#  Initialize properly the values of the average score, minimum score, and maximum score.
    average = 0
    lowest = True
    highest = True
    scoreTotal = 0

The reason why the variables above were labeled that way is because in my main function, which calls on this function, had a built in call with those names. But whenever I go to run the program, it doesn't print any of it.
#  loop through the dictionary, and
#  calculate the average score, the highest score and the lowest score
#  of the students in the dictionary.

    i = 0
    for grade in students:
        scoreTotal += grade[i]
        i = i + 1
    average = scoreTotal/i
    lowest = min(grade[i])
    highest = max(grade[i])

#  The function must return back the average, highest and lowest score.
   return average, highest, lowest

In the main function it had this: (the "nameToMarksMap" is the function from the previous part with the dictionary students)
 average, highest, lowest = getStatistics(nameToMarksMap)

 print "Average:", average, "Highest:", highest, "Lowest:", lowest

Nothing is being printed, can anyone explain why? I keep getting errors.

A: finish the function with
def getStatistics(students)
    ...
    # snip
    ...
    return average, highest, lowest


Q: WebLogic 12.1.2 bad record MAC on HTTPS I'm trying to use WebLogic with HTTPS default keystore for development and I get the following error when I try to connect to the server via web browser:
ExecuteThread: '0' for queue: 'weblogic.socket.Muxer', fatal: engine already closed.  Rethrowing javax.net.ssl.SSLException: bad record MAC
<13-nov-2014 11H48' COT> <Debug> <SecuritySSL> <BEA-000000> <[Thread[ExecuteThread: '0' for queue: 'weblogic.socket.Muxer',5,Thread Group fo
r Queue: 'weblogic.socket.Muxer']]weblogic.security.SSL.jsseadapter: SSLENGINE: Exception occurred during SSLEngine.unwrap(ByteBuffer,ByteBu
ffer[]).
javax.net.ssl.SSLException: bad record MAC
at sun.security.ssl.Alerts.getSSLException(Alerts.java:208)
at sun.security.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1605)
at sun.security.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1573)
at sun.security.ssl.SSLEngineImpl.readRecord(SSLEngineImpl.java:971)
at sun.security.ssl.SSLEngineImpl.readNetRecord(SSLEngineImpl.java:876)
at sun.security.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:750)
at javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:664)
at weblogic.security.SSL.jsseadapter.JaSSLEngine$5.run(JaSSLEngine.java:134)
at weblogic.security.SSL.jsseadapter.JaSSLEngine.doAction(JaSSLEngine.java:732)
at weblogic.security.SSL.jsseadapter.JaSSLEngine.unwrap(JaSSLEngine.java:132)
at weblogic.socket.JSSEFilterImpl.unwrap(JSSEFilterImpl.java:603)
at weblogic.socket.JSSEFilterImpl.unwrapAndHandleResults(JSSEFilterImpl.java:507)
at weblogic.socket.JSSEFilterImpl.unwrapAndHandleResults(JSSEFilterImpl.java:474)
at weblogic.socket.JSSEFilterImpl.isMessageComplete(JSSEFilterImpl.java:313)
at weblogic.socket.SocketMuxer.readReadySocketOnce(SocketMuxer.java:991)
at weblogic.socket.SocketMuxer.readReadySocket(SocketMuxer.java:928)
at weblogic.socket.NIOSocketMuxer.process(NIOSocketMuxer.java:507)
at weblogic.socket.NIOSocketMuxer.processSockets(NIOSocketMuxer.java:473)
at weblogic.socket.SocketReaderRequest.run(SocketReaderRequest.java:30)
at weblogic.socket.SocketReaderRequest.execute(SocketReaderRequest.java:43)
at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:147)
at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:119)
>

I found some links about this, but nothing important.
Is there any solution for this?

A: Remove the WebLogic Domain data folder and setup it again. This time I restart the WebLogic server domain after the WebLogic Domain data folder setup and enable the SSL after. Next open the browser with the https address and it work.


Q: Pointer of QVector pointer This is my class constructor:
UndoRedo::UndoRedo(QList<vector_t*> v,
                   QUndoCommand *parent)
    : QUndoCommand(parent)
{
    ...
    QStringList *sl = &v[0][0];
    ...
}

Where vector_t is
typedef QVector<QStringList> vector_t ;

Whwn I try to set "sl" in this way, the IDE raises this error:
no match for ‘operator*’ (operand type is ‘QList<QVector<QStringList>*>’)

Where I’m doing wrong? Can you help me?

A: The biggest problem I see in your questions is that you seem to be severly overcomplicating simple things. First and foremost, Qt's containers are implicitly shared. Thus taking their copies is cheap if said copies are not modified. Thus you can freely pass the outermost container by reference, and have it take the innards by value.
It'd be reasonably cheap, for example, to simply pass QList<vector_t> to your method. It would involve no copying of any kind. Even then, it costs a tiny bit less to pass a const reference instead of a value, namely const QList<vector_t> &.
Why are you taking the address of v? Let's dissect the type of v:
QList<vector_t*> = QList<QVector<QStringList>>*>

To access the innermost element you need to:

*

*Access a list element: v[0]

*Dereference the pointer: *exp

*Access the vector element: exp[0]
By exp I mean the preceding expression, taken as a unit.
Thus:
QStringList & sl = (*(v[0]))[0];

This is C++, not C, you should use a reference instead of a pointer.
If you insist on a pointer:
QStringList * sl = *((*(v[0]))[0]);

But then you can do silly things like delete sl or free(sl) and it will compile but will result in, maybe, your hard drive getting formatted.


Q: TypeError on Angular form submit I'm getting the error TypeError: Cannot set property 'songname' of null, when trying to submit an update to a row in firebase. The console error is saying that its happening with the record.songname in the edit function. I'm able to add, but not edit rows.
myApp.controller('ProductsCtrl', ['$scope', '$firebaseArray', function($scope, $firebaseArray, $http){

  var myProducts = new Firebase('https://url-to-db.firebaseio.com/songs');

  $scope.products = $firebaseArray(myProducts);

  $scope.showForm = function(){
    $scope.addFormShow = true;
    $scope.editFormShow = false;
    clearForm();
    window.scrollTo(0, 0);
  }

  $scope.hideForm = function(){
    $scope.addFormShow = false;
  }

  function clearForm(){
    $scope.songname = '';
    $scope.artist = '';
    $scopt.tags = '';
  }

  $scope.addFormSubmit = function(){
    $scope.products.$add({
      songname:$scope.songname,
      artist:$scope.artist,
      tags:$scope.tags,
      date:Date.now()
    });
    $('.messages').addClass('alert alert-success').slideDown().show().html('The song has been added').fadeOut(2000);
    clearForm();
  }

  $scope.dateFormat = 'MM-dd-yy @ HH:mm:ss';

  $scope.showProduct = function(product){
    $scope.editFormShow = true;
    $scope.addFormShow = false;
    $scope.songname = product.songname;
    $scope.artist = product.artist;
    $scope.tags = product.tags;
    $scope.date = product.date;
  }

  $scope.editFormSubmit = function(){
    var id = $scope.id;
    var record = $scope.products.$getRecord(id);
    record.songname = $scope.songname;
    record.artist = $scope.artist;
    record.tags = $scope.tags;

    $scope.products.$save(record);
    $('.messages').addClass('alert alert-info').slideDown().show().html('The job has been edited').fadeOut(2000);
    clearForm();
    $('.edit-form').toggle();
  }
}]);

A: The $scope.id attribute is probably not getting set.
Try setting the id in the scope in your showProduct function or whichever function initializes the $scope variables for the item.
$scope.showProduct = function(product){
$scope.id = product.id;
..............


Q: How to use a Node.js module in CoffeScript in a JavaScript project I have been recommended this Node.js module.
It is implemented in CoffeeScript, but I want to use it in my JavaScript project. Of course I will get an error message like this:

What do I have to do to use the module in my project?


Q: Assert IsMenu exception when attempting to populate a dynamic menu I'm attempting to populate a "submenu" in my dialog box from an array of strings as shown in this answer.
My attempt looks like the following:
#define ID_APP0 14000
#define ID_APP1 14001
#define ID_APP2 14002
#define ID_APP3 14003
#define ID_APP4 14004
#define ID_APP5 14005
#define ID_APP6 14006
#define ID_APP7 14007

void SoftwareDlg::DynamicAppMenu()
{
    CMenu MyMainMenu;
    VERIFY(MyMainMenu.LoadMenu(IDR_MENU1));

    CMenu* SomeMenu = MyMainMenu.GetSubMenu(0);
    if (SomeMenu)
    {
        for (auto i = 0; i < 1; i++)
        {
            SomeMenu->AppendMenu(MF_STRING, 14000+i, Client::m_vszAppArr[i]);
        }
    }
}

...but I'm getting an exception from the assert below immediately after(during?) the AppendMenu() function.
_AFXWIN_INLINE BOOL CMenu::AppendMenu(UINT nFlags, UINT_PTR nIDNewItem, LPCTSTR lpszNewItem)
    { ASSERT(::IsMenu(m_hMenu)); return ::AppendMenu(m_hMenu, nFlags, nIDNewItem, lpszNewItem); }

I no longer know how to continue debugging this issue because the LoadMenu() function appears to work correctly, and none of the variables are populated where the exception takes place.
Am I possibly just calling this in the wrong place? It's happening(conditionally) inside of a scheduled member function of the dialog box... does it need to happen somewhere like OnDraw(), OnPaint(), or something?
Edit1: Value of SettingsMenu->m_hMenu

Edit2: IDR_MENU1 resource definition:
IDR_MENU1 MENU
BEGIN
    POPUP "Tools"
    BEGIN
        MENUITEM "New Test                  F11", ID_TOOLS_NEWTEST
        MENUITEM "Export Data",                 ID_TOOLS_EXPORTDATA
        MENUITEM "Upload Data",                 ID_TOOLS_UPLOADDATA
        MENUITEM "Test Control",                ID_TOOLS_TESTCONTROL
    END
    POPUP "Settings"
    BEGIN
        POPUP "USB_PORT"
        BEGIN
            MENUITEM "Serial Ports",                ID_PORT_SERIALPORTS, INACTIVE
            MENUITEM "COM1",                        ID_PORT_COM1
            MENUITEM "COM2",                        ID_PORT_COM2
            MENUITEM "COM3",                        ID_PORT_COM3
            MENUITEM "COM4",                        ID_PORT_COM4
            MENUITEM "COM5",                        ID_PORT_COM5
            MENUITEM "COM6",                        ID_PORT_COM6
            MENUITEM "COM7",                        ID_PORT_COM7
            MENUITEM "COM8",                        ID_PORT_COM8
        END
        MENUITEM "Debug Mode",                  ID_SETTINGS_DEBUGMODE
        MENUITEM "Display in OSD",       ID_SETTINGS_DISPLAYINOSD
        MENUITEM "Test Upload Mode",            ID_SETTINGS_TESTUPLOADMODE
        MENUITEM "Preferences",                 ID_SETTINGS_PREFERENCES
        POPUP "Target Window"
        BEGIN
            MENUITEM "Placeholder",                 ID_TARGETWINDOW_PLACEHOLDER
        END
    END
END

A: As hinted to by @Vlad Feinstein's comment, CMenu MyMainMenu; should not have been declared inside the function... That fix allowed me to get past the assertion, but the new menu items were still not appearing. I began catching and logging the return values from the creation and deletion functions which lead me to realize that because I already had an existing menu, I needed to use a pointer to that menu(as opposed to creating my own that I then left un-used).
My final function ended up looking like this:
void SoftwareDlg::DynamicAppMenu(){
    CMenu* MainMenu = GetMenu();
    CMenu* SettingsMenu = MainMenu->GetSubMenu(1);
    CMenu* TargetAppMenu = SettingsMenu->GetSubMenu(5);

    if (TargetAppMenu)
    {
        BOOL appended = false;
        BOOL deleted = false;

        for (auto i = 0; i < Client::m_vszAppArr.size(); i++)
        {
            appended = TargetAppMenu->AppendMenu(MF_STRING, 14000+i, Client::m_vszAppArr[i].c_str());
        }
        deleted = TargetAppMenu->DeleteMenu(ID_TARGETWINDOW_PLACEHOLDER, MF_BYCOMMAND);

        OutputDebugString(("String appended: " + std::to_string(appended)).c_str());
        OutputDebugString(("Placeholder deleted: " + std::to_string(deleted)).c_str());
    }

}


Q: SQL datetime compare I want to get some values from my table an there are some conditions about its datetime columns.
I want to get all hotel values of a stated city from my table, which is named "LocalHotels". Also I should declare two DateTimevalues. First value should be less than or equal to hotel's value in "start" column, which is datetime data type. Second value should be greater than or equal to hotel's value in "deadline" column, which is datetime data type, either.
All datetime values in these two columns are inserted in German CultureInfo format.
When I stated query below, there are no problems;
string query = "SELECT * FROM LocalHotels WHERE city='LONDON' AND start <='5.12.2015 00:00:00' AND deadline >='8.12.2015 00:00:00' ORDER BY city";

However when I changed day value of DateTime values from one digit to two digits, as I stated in below;
string query "SELECT * FROM LocalHotels WHERE city='LONDON' AND start <='15.12.2015 00:00:00' AND deadline >='18.12.2015 00:00:00' ORDER BY city"

I got an SQLException which indicates;

The conversion of a varchar data type to a datetime data type resulted
  in an out-of-range value.

A: Try changing
15.12.2015 00:00:00

to
2015-12-15 00:00:00

and same format for the other date also.

A: You can view SQL Server's date and time format for yourself by running this query:
SELECT
    GETDATE()

As you can see the format is YYYY-MM-DD HH:MM:SS.MMM.  Stick to this and you won't run into any unexpected conversion errors.
EDIT
ISO 8601 is a standard date format.  From MS Docs:

The advantage in using the ISO 8601 format is that it is an international standard with unambiguous specification. Also, this format isn't affected by the SET DATEFORMAT or SET LANGUAGE setting.

For this reason I would recommend it above all other formats.  Examples:
2020-02-25
20200225
2020-02-25T18:37:00

A: SELECT CONVERT(char(10), GetDate(),126)

or
select convert(varchar,getDate(),112)

or
select replace(convert(varchar, getdate(), 111), '/','-')

Test out the queries above to get the date in the desired format (replace GetDate() with your date, or dateColumn).
As others pointed out you need the format YYYY-MM-DD.

A: Even though in Europe and everywhere in the world it makes perfect sense to use the month as the second of three items in the date. In the US and in this case, apparently, SQL's date time is MM.DD.YYYY, so you're going for the 15th month and 18th month
Therefore you should use
string query "SELECT * FROM LocalHotels WHERE city='LONDON' AND start <='12.15.2015 00:00:00' AND deadline >='12.18.2015 00:00:00' ORDER BY city"

or
string query "SELECT * FROM LocalHotels WHERE city='LONDON' AND start <='2015-12-15' AND deadline >='2015-12-18' ORDER BY city"


Q: Stop pandas to_excel() prepending apostrophe on strings I have a pandas dataframe which has only strings, although some are date strings like '2019-01-01', others are ints or bools as strings such as '1084' and 'FALSE'. When I try to write this to a sheet in an xlsx file I find it is prepending apostrophes in some cases, presumably to stop excel trying to evaluate the dates/ints/bools and so on.
Is there a way to stop this? I need to upload this generated .xlsx to a system which will reject it if these apostrophes are there.
Currently I import a xlsx file as a template which has two sheets and I want to overwrite the 2nd one.
Export code snippet:
exp_dict['ScheduleDetails'] = df
with pd.ExcelWriter(f"{uploads_folder}{name}_FORMATTED.xlsx",engine='xlsxwriter', options={'encoding':'utf-8'}) as writer:
   for k,v in exp_dict.items():
       v.to_excel(writer, sheet_name = k, index = False)

A: Not sure what your problem is but if you want to convertdtypes to str the try this:
  df.astype({'col_name': 'str'})


Q: Curl request in python I'm a newbie to python program. I want to get trending topics in google trends. How do i make this curl request from python
curl --data "ajax=1&htd=20131111&pn=p1&htv=l" http://www.google.com/trends/hottrends/hotItems

I tried following code
param = {"data" :"ajax=1&htd=20131111&pn=p1&htv=l"}
value = urllib.urlencode(param)

req = urllib2.Request("https://www.google.co.in/trends/hottrends/hotItems", value)
response = urllib2.urlopen(req)
result = response.read()
print result

But it is not returning expected values, which is the current Google trends.
Any help would be appreciated.
Thanks.

A: You are misinterpreting the data element in your curl command line; that is the already encoded POST body, while you are wrapping it in another data key and encoding again.
Either use just the value (and not encode it again), or put the individual elements in a dictionary and urlencode that:
value = "ajax=1&htd=20131111&pn=p1&htv=l"
req = urllib2.Request("https://www.google.co.in/trends/hottrends/hotItems", value)

or
param = {'ajax': '1', 'htd': '20131111', 'pn': 'p1', 'htv': 'l'}
value = urllib.urlencode(param)
req = urllib2.Request("https://www.google.co.in/trends/hottrends/hotItems", value)

Demo:
>>> import json
>>> import urllib, urllib2
>>> value = "ajax=1&htd=20131111&pn=p1&htv=l"
>>> req = urllib2.Request("https://www.google.co.in/trends/hottrends/hotItems", value)
>>> response = urllib2.urlopen(req)
>>> json.load(response).keys()
[u'trendsByDateList', u'lastPage', u'summaryMessage', u'oldestVisibleDate', u'dataUpdateTime']
>>> param = {'ajax': '1', 'htd': '20131111', 'pn': 'p1', 'htv': 'l'}
>>> value = urllib.urlencode(param)
>>> value
'htv=l&ajax=1&htd=20131111&pn=p1'
>>> req = urllib2.Request("https://www.google.co.in/trends/hottrends/hotItems", value)
>>> response = urllib2.urlopen(req)
>>> json.load(response).keys()
[u'trendsByDateList', u'lastPage', u'summaryMessage', u'oldestVisibleDate', u'dataUpdateTime']

A: Easiest using the requests library in Python. Here's an example using Python 2.7:
import requests
import json

payload = {'ajax': 1, 'htd': '20131111', 'pn':'p1', 'htv':'l'}
req = requests.post('http://www.google.com/trends/hottrends/hotItems', data=payload)

print req.status_code # Prints out status code
print json.loads(req.text) # Prints out json data


Q: Row counter in sub report - Jaspersoft I have a subreport that receives two parameters and therefore generates as many reports as there are combinations of parameters, I have to put a row counter in the sub report but this must not reset every report generated by the sub report but must continue the numbering.
This is a conversion from a crystal report
In crystal report do this:
shared numberVar J;
if trim({field})  <> '' then J:=J+1;

I have a subreport to which I pass in the sql query two parameters whose values are generated by the main report, the combination of these parameters in the subreport generates a series of reports in the main report because the subreport is in the detail band.
In the subreport I have to insert a variable that counts the number of rows, but when I insert this variable the numeric counter is reset and starts counting in the new report generated by the subreport, I would like the counter not to reset
Main report

*

*Detail of the band

*subreport
Subreport

*report 1
1 row
2 rows
3 rows

*report 2

1 row
2 rows
3 rows
I would like to have
- report 1
1 row
2 rows
3 rows
-report 2
4 rows
5 rows
6 rows
I hope I was clear
Do you have any ideas?
Can someone help me?
Please
Thanks a lot to everyone

A: You can pass back and forth a running row count variable to the subreport using parameters and return variables.
You'd need something like this:
(in the master report)
<!-- variable that stores the running row count in the master report -->
        <variable name="SubreportRowCount" class="java.lang.Integer" calculation="System">
            <initialValueExpression>0</initialValueExpression>
        </variable>
...
                <subreport>
...
<!-- pass the current value to the subreport -->
                    <subreportParameter name="InitialRowCount">
                        <subreportParameterExpression>$V{SubreportRowCount}</subreportParameterExpression>
                    </subreportParameter>
...
<!-- get back the updated value from the subreport -->
                    <returnValue subreportVariable="RunningRowCount" toVariable="SubreportRowCount"/>
    ...
                </subreport>

(in the subreport)
<!-- parameter that receives the initial value from the master -->
    <parameter name="InitialRowCount" class="java.lang.Integer"/>
...
<!-- running row count variable -->
    <variable name="RunningRowCount" class="java.lang.Integer">
        <variableExpression>$P{InitialRowCount} + $V{REPORT_COUNT}</variableExpression>
    </variable>
...
<!-- show the running count in a text element -->
            <textField>
...
                <textFieldExpression>$V{RunningRowCount}</textFieldExpression>
            </textField>


Q: How can I delete every n-th row from a dataframe in R, according to grouping variable? I wish to take every second measurement from a data.frame according to a grouping variable. For example, in the data.frame Input, take every second Sample for each ID:
 head(Input, 10)
           Sample    X       ID
    15918      1 -1.326285 EABE_D5
    15919      2 -1.315783 EABE_D5
    15920      3 -1.313245 EABE_D5
    15921      4 -1.304670 EABE_D5
    15922      5 -1.309060 EABE_D5
    15923      1 -1.292412 EABE_D4
    15924      2 -1.294728 EABE_D4
    15925      3 -1.282006 EABE_D4
    15926      4 -1.287245 EABE_D4
    15927      5 -1.278444 EABE_D4

and create a new data.frame named Output:
Output
        Sample   X       ID
15919      2 -1.315783 EABE_D5
15921      4 -1.304670 EABE_D5
15924      2 -1.294728 EABE_D4
15926      4 -1.287245 EABE_D4

Is this possible? Thank you.

A: We can use dplyr.  After grouping by 'ID', we slice the rows based on the even index returned by seq
library(dplyr)
Input %>%
   group_by(ID) %>%
   slice(seq(2, n(), by =2))
#  Sample         X      ID
#   <int>     <dbl>   <chr>
#1      2 -1.294728 EABE_D4
#2      4 -1.287245 EABE_D4
#3      2 -1.315783 EABE_D5
#4      4 -1.304670 EABE_D5

Or we can use data.table for efficiency
library(data.table)
setDT(Input)[Input[, .I[seq(2, .N, by = 2)], by = ID]$V1]

Or with ave from base R, we group by 'ID', apply the modulo operator %% with y as 2, convert to logical by negating (!) and with this logical vector, we subset the rows.
Input[with(Input, !ave(Sample, ID, FUN = function(x) x %%2)),]
#      Sample         X      ID
#15919      2 -1.315783 EABE_D5
#15921      4 -1.304670 EABE_D5
#15924      2 -1.294728 EABE_D4
#15926      4 -1.287245 EABE_D4

A: This might be inefficient. However, you can do this in one more way using lapply
do.call(rbind, lapply(split(df, df$ID), function(x) x[seq(2, nrow(x), by=2),]))

#                Sample   X      ID
#EABE_D4.15924      2 -1.294728 EABE_D4
#EABE_D4.15926      4 -1.287245 EABE_D4
#EABE_D5.15919      2 -1.315783 EABE_D5
#EABE_D5.15921      4 -1.304670 EABE_D5

splitting the dataframe based on ID and then selecting every 2nd row in each group and finally rbinding them using do.call to convert the list returned as dataframe.
If you do not want the row names, you can take the dataframe in one variable (say a) and then
rownames(a) <- NULL


Q: Is there any way to get all product variation prices to display? I have WordPress woo-commerce site with product selling, and i have three variation price for the product like (1 kg -420, 500 grams - 220 and 250 gram- 100). currently it prices are showing like 100-420,  but i need all three variation price to be display below the product, can any one help for this issue
https://imgur.com/a/gJtAU6D
$formatted_price = ( $negative ? '-' : '' ) . sprintf( $args['price_format'], '' . get_woocommerce_currency_symbol( $args['currency'] ) . '', $price );
$return          = '' . $formatted_price . '';

if ( $args['ex_tax_label'] && wc_tax_enabled() ) {
    $return .= ' ' . WC()->countries->ex_tax_or_vat() . '';
}


Q: please help to sort it out  error: Command "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.35.32215\bin\HostX86\x64\cl.exe /c /nologo /O2 /W3 /GL /DNDEBUG /MD -IC:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2800.0_x64__qbz5n2kfra8p0\include -IC:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2800.0_x64__qbz5n2kfra8p0\Include -IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.35.32215\include -IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.35.32215\ATLMFC\include -IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\VS\include -IC:\Program Files (x86)\Windows Kits\10\include\10.0.22000.0\ucrt -IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\um -IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\shared -IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\winrt -IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\cppwinrt /EHsc /Tppystan/_misc.cpp /Fobuild\temp.win-amd64-cpython-310\Release\pystan\_misc.obj /EHsc -DBOOST_DATE_TIME_NO_LIB /std:c++14" failed with exit status 2

note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure
× Encountered error while trying to install package.
╰─> pystan
............................................


Q: Is it good to have all the setter functions return a reference to the object in c++? Is it good to have all the setter functions return a reference to the object in c++?

A: The typical purpose for this style is in use for object construction.
Person* pPerson = &(new Person())->setAge(34).setId(55).setName("Jack");

instead of
Person* pPerson = new Person( 34, 55, "Jack" );

Using the second more traditional style one might forget if the first value passed to the constructor was the age or the id? This may also lead to multiple constructors based on the validity of some properties.
Using the first style one might forget to set some of the object properties and and may lead bugs where objects are not 'fully' constructed. (A class property is added at a later point but not all the construction locations got updated to call the required setter.)
As code evolves I really like the fact that I can use the compiler to help me find all the places where an object is created when changing the signature of a constructor. So for that reason I prefer using regular C++ constructors over this style.
This pattern might work well in applications that maintain their datamodel over time according to rules similar to those used in many database applications:

*

*You can add a field/attribute to a table/class that is NULL by default. (So upgrading existing data requires just a new NULL column in the database.)

*Code that is not changes should still work the same with this NULL field added.

A: Not all the setters, but some of them could return reference to object to be useful.
kind of
a.SetValues(object)(2)(3)(5)("Hello")(1.4);

I used this once long time ago to build SQL expression builder which handles all the Escapes problems and other things.
SqlBuilder builder;

builder.select( column1 )( column2 )( column3 ).
    where( "=" )( column1, value1 )
                ( column2, value2 ).
    where( ">" )( column3, 100 ).
    from( table1 )( "table2" )( "table3" );

I wasn't able to reproduce sources in 10 minutes. So implementation is behind the curtains.

A: If your motivation is related to chaining (e.g. Brian Ensink's suggestion), I would offer two comments:
1.
If you find yourself frequently settings many things at once, that may mean you should produce a struct or class which holds all of these settings so that they can all be passed at once.  The next step might be to use this struct or class in the object itself...but since you're using getters and setters the decision of how to represent it internally will be transparent to the users of the class anyways, so this decision will relate more to how complex the class is than anything.
2.
One alternative to a setter is creating a new object, changing it, and returning it.  This is both inefficient and inappropriate in most types, especially mutable types.  However, it's an option that people sometimes forget, despite it's use in the string class of many languages.

A: This technique is used in the Named parameter Idiom.

A: IMO setters are a code smell that usually indicate one of two things:
Making A Mountian Out Of A Molehill
If you have a class like this:
class Gizmo
{
public:
  void setA(int a) { a_ = a; }
  int getA() const { return a_; }

  void setB(const std::string & b) { v_ = b; }
  std::string getB() const { return b_; }
private:
  std::string b_;
  int a_;
};

... and the values really are just that simple, then why not just make the data members public?:
class Gizmo
{
public:
  std::string b_;
  int a_;
};

...Much simpler and, if the data is that simple you lose nothing.
Another possibility is that you could be
Making A Molehill Out Of A Mountian
Lots of times the data is not that simple: maybe you have to change multiple values, do some computation, notify some other object; who knows what.  But if the data is non-trivial enough that you really do need setters & getters, then it is non-trivial enough to need error handling as well.  So in those cases your getters & setters should be returning some kind of error code or doing something else to indicate something bad has happened.
If you are chaining calls together like this:
A.doA().doB().doC();

... and doA() fails, do you really want to be calling doB() and doC() anyway?  I doubt it.

A: It's a usable enough pattern if there's a lot of things that need to be set on an object.
 class Foo
 {
      int x, y, z;
 public:
      Foo &SetX(int x_) { x = x_;  return *this; }
      Foo &SetY(int y_) { y = y_;  return *this; }
      Foo &SetZ(int z_) { z = z_;  return *this; }
 };

 int main()
 {
      Foo foo;
      foo.SetX(1).SetY(2).SetZ(3);
 }

This pattern replaces a constructor that takes three ints:
 int main()
 {
      Foo foo(1, 2, 3); // Less self-explanatory than the above version.
 }

It's useful if you have a number of values that don't always need to be set.
For reference, a more complete example of this sort of technique is refered to as the "Named Parameter Idiom" in the C++ FAQ Lite.
Of course, if you're using this for named parameters, you might want to take a look at boost::parameter.  Or you might not...

A: You can return a reference to this if you want to chain setter function calls together like this:
obj.SetCount(10).SetName("Bob").SetColor(0x223344).SetWidth(35);

Personally I think that code is harder to read than the alternative:
obj.SetCount(10);
obj.SetName("Bob");
obj.SetColor(0x223344);
obj.SetWidth(35);

A: I would not think so. Typically, you think of 'setter' object as doing just that.
Besides, if you just set the object, dont you have a pointer to it anyway?


Q: Create a function for add_new_field in Python I am trying to create a function for a task I mentioned earlier for adding a new field to some files that are stored in one folder. I read about the function method in Python and followed but it does not work. I would be happy if someone could guide me about it.
def newfield(infile,outfile):
    infile.readlines()
    outfile = ["%s\t%s" %(item.strip(),2) for item in infile]
    outfile.write("\n".join(output))
    outfile.close()
    return outfile

and then I try to call it:
a = open("E:/SAGA/data/2006last/test/325145404.all","r")
b = open("E:/SAGA/data/2006last/test/325145404_edit.all","w")
newfield(a,b)

Moreover, when we create a function, should we call it in a same python shell or we can same it as a file and then call it?

A: Looks like the problem is you're assigning the list you build to the same name as the output file. You're also reading all of the lines out of the file and not assigning the result anywhere, so when your list comprehension iterates over it, it's already at the end of the file. So you can drop the readlines line.
def newfield(infile,outfile):
    output = ["%s\t%s" %(item.strip(),2) for item in infile]
    outfile.write("\n".join(output))
    outfile.close()
    return outfile

A: The line infile.readlines() consumes the whole input file. All lines are read and forgotten because they are not assigned to a variable.
The construct ["%s\t%s" %(item.strip(),2) for item in infile] is a list comprehension. This expression returns a list. By assigning it to the variable outfile the old value of outfile - probably a file object - is forgotten and replaced by the list returned by the list comprehension. This list object does not have a write method. By assigning the list to another variable the file object in outfile is preserved.
Try this:
def newfield(infile,outfile):
    items = ["%s\t%s" %(item.strip(),2) for item in infile]
    outfile.write("\n".join(items))
    outfile.close()
    return outfile


Q: Problems with w3 total cache I installed the plugin W3 total cache but It crashed an important plugin, so I have to delete it. The roblem is that my site is still running a cache version.
I follow the instruction for delete the plugin: unchecked all options, disable and delete the plugin. I look up for the folders: cache and w3cache and proceed to delete it.
I check the .htaccess and is ok. But still the cache version is loading.
The web is: https://noia.pe/

A: I finally solve the problem. I don't know why W3 Total Cache create problems with the jquerys. This was the error on some parts of the web:
Uncaught TypeError: $ is not a function
So I fix it adding this: jQuery(function($)...) instead of function() and now is ok.
I don't know why this happened, all the other pages are working ok, and as I said the only thing that was diferent with this was that plugin.


Q: How to make a MFC Visual Studio C++ program use both CPUs in a dual processor setup I recently built a workstation with a dual Xeon E5-2699v4 CPUs. This provides me with a total of 88 threads. I have a program that can benefit from using these threads. However when I tested it out, it seemed that it was only utilising 1 processor in the setup. Trying to use more than 44 threads, would cause the system to have momentary lockups.
The program uses MFC Visual Studio C++. What would need to be done to code the program to use both processors?

A:
What would need to be done to code the program to use both processors?

You need to understand how the code is spending the cpu-cycles, i.e. benchmark. Read on about simple method duration versus context-switch duration.

"C++ has no notion of cores".  Thus, the idea of associating a thread with a particular core is delegated to the operating system (in which the program is executing), and I have not seen the C++ language semantics for the issue.  I have read of os calls to associate a thread with a core, but I have never grokked why, nor experimented.
On Ubuntu, I simply start the threads, and rely on the OS (Linux) to assign each running thread to an available processor resource.  Linux seems to do a reasonable job.
I have measure two threads to perform the 'same' comparison work on two independent data's to cut the duration in half, and both cores are often fully utilized.  (small to no i/o actions mixed in)

Contexts switches are about an order of magnitude slower than method invocations.  So perhaps your code design should avoid switching.
Or, perhaps it is an effort of balance, code granularity, i.e. how much code to finish for each switch.
On my Ubuntu 17.10 system I have measured the combined duration of '::sem_wait()' and '::sem_post()' (both small methods) to about 31 ns (103.7 M events in 3,237,099 us), [with no context switches, of course].
On my 2 core processor, one of my tests runs 10 threads for 10 seconds, and does not force a context switch, leaving a single critical section for the thread-to-thread interaction.  I was surprised that the same thread often runs multiple times before one of the 'starving' threads gets to run (it is not a problem on that 'Linux minor benchmark' - lmbm).  The code reports 297 ns per context switch.  (33 M switches in 10 secs, 297 ns per).
When I enforce a 'balanced-sharing-of-cores' (by using two semaphores per thread), every thread runs as often as any other.  The switch duration is quite a bit longer (but not available to me at this moment).

I don't have the opportunity to measure 10 threads on 44 cores, it sounds like fun.  I estimate the range of performance would be 'big' - perhaps from "stalled" to "10x" the duration of 1 thread. Depending not on which core the code runs on, but on what the code does when it runs.


Q: Set default 'host' value for `php artisan serve` I am building a Laravel site, and want to test it on other devices as I build it (phone, ipad etc).
As I understand it, the way to do this is to run php artisan serve --host=0.0.0.0.
My question is... is there a way to define a default value for the host, and set it to 0.0.0.0, so that I can simply run php artisan serve and it will automatically run on 0.0.0.0?

A: You can do next thing:

*

*php artisan make:command CustomServeCommand

*Then delete all from file and use this code:
<?php

namespace App\Console\Commands;

use Illuminate\Foundation\Console\ServeCommand;
use Symfony\Component\Console\Input\InputOption;

class CustomServeCommand extends ServeCommand
{
    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['host', null, InputOption::VALUE_OPTIONAL, 'The host address to serve the application on.', '0.0.0.0'],//default 127.0.0.1
            ['port', null, InputOption::VALUE_OPTIONAL, 'The port to serve the application on.', 8000],
        ];
    }
}

*php artisan serve
Link to the core file.
Basically, you will extend default class and adapt method to fit your own needs. This way you can set host and port per requirements.


Q: Angular9: Getting Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays I have created a simple app to call backend services using HttpClientModule,, but  data is not showing into the log, I did the following steps and I am using angular-9
could you please check the code.
Thanks in Advance.

*

*app.module file

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule} from '@angular/common/http';
import {RestAPIServices} from './services/rest-api.service';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [RestAPIServices],
  bootstrap: [AppComponent]
})
export class AppModule { }

*model.ts

export class Employee{
    id:number;
    name:string;
    gender:string;
    email? :string; // ? means optional property
    mobile:string;
    department:string;
    isActive:boolean;
    photo? :string;
}

*service.ts

import {Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import {HttpClient} from '@angular/common/http';
import { Employee } from '../models/employee.model';

@Injectable()
export class RestAPIServices{

    constructor(private httpClient:HttpClient){}

   getEmployee():Observable<Employee[]>{
    //this.httpClient.get<Employee[]>("http://127.0.0.1/angularCRUDservices/user/getEmployees").subscribe(res=>  console.log(res));
    return this.httpClient.get<Employee[]>("http://127.0.0.1/angularCRUDservices/user/getEmployees");
   }

}

*app.component.ts

import { Component } from '@angular/core';
import {RestAPIServices} from './services/rest-api.service';
import {Employee} from './models/employee.model';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  listEmployee : Employee[];
  title = 'simple-rest-app';

  constructor(private _employeeService:RestAPIServices){}
  ngOnInit(){

    this._employeeService.getEmployee().subscribe(
      data=>{
        console.log(data)
        this.listEmployee = data;
      }
    )

    console.log(this.listEmployee);
  }

}

servire is tested from postman and it's working fine
{"response":[{"id":"1","name":"Anand","gender":"Male","email":"a@gmail.com","mobile":"111111111","department":"2","isActive":"1","photo":"assets\/images\/emp1.jpg"},{"id":"2","name":"Kiran","gender":"Female","email":"k@gmail.com","mobile":"2222222222","department":"2","isActive":"1","photo":"assets\/images\/emp1.jpg"},{"id":"3","name":"Ravi","gender":"Male","email":"r@gmail.com","mobile":"3333333333","department":"2","isActive":"1","photo":"assets\/images\/emp2.jpg"},{"id":"4","name":"Kumar","gender":"Male","email":"k@gmail.com","mobile":"4444444444","department":"3","isActive":"1","photo":"assets\/images\/emp4.jpg"}]}

A: Looks like the problem is that the server response is an object, but not an array.
// try to replace
this.httpClient.get<Employee[]>(...);

// by
this.httpClient.get<{ response: Employee[] }>(...).pipe(
  map(response => response.response)
);


Q: I cannot find javadoc or source files for JDK 8 Update 321 on the net In the projects in IntelliJ IDEA I am using JDK 8 Update 321, but I am missing javadoc or source for the SDK.
OS is Windows 10.
I realy tried, but wasn't able to find either on the internet.

A: Javadoc: https://javadl.oracle.com/webapps/download/AutoDL?BundleId=245778_df5ad55fdd604472a86a45a217032c7d
The source should be part of the JDK, search for src.zip in your JDK directory.
How to attach JDK source code to IntelliJ IDEA

A: I didn't know that patch releases don't change the public API, so both Thomas Behr's comment and sinclair's answer are valid.
Only thing to add is that the javadoc zip should be included in IntelliJ IDA via File -> Project Structure -> Platform Settings -> SDKs -> Documentation Paths (instead of Sourcepath).


Q: Facebook OAuth access_token error Full code.
    public function indexAction(){
           echo 'Login met facebook ';
  }

 const FB_GRAPH_URL =  "https://graph.facebook.com/";
    public function fbloginAction() {

            $fbCode = $this->_getParam("code");
            $getStr  = self::FB_GRAPH_URL. 'oauth/access_token?' .http_build_query(array(
                        'client_id'     => 'APP_ID',
                        'type'          => 'client_cred',
                        'client_secret' => 'SECRET_KEY',
                        'code'          => $fbCode)
                    );

            $accessToken = file_get_contents( $getStr );
            krumo($accessToken) ;

            $dbpath = "https://graph.facebook.com/me?$accessToken" ;
            $cont = file_get_contents($dbpath ) ;
            krumo($cont);
        }

When i try make GET query to Facebook.
$dbpath = "https://graph.facebook.com/me?$accessToken" ;
$cont = file_get_contents($dbpath ) ;

I receive the  error :

failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
  in /home.....

When paste manually  the $dbpath value(path) to web browser,  i got next error:
{
   "error": {
      "message": "An active access token must be used to query information about the current user.",
      "type": "OAuthException",
      "code": 2500
   }
}

How fix that error?

A: You probably want to use the Server-Side Authentication flow. By checking the calls in the documentation it is quite clear, which of your calls are wrong.
First, your call to the oauth/access_token endpoint takes no argument 'type' => 'client_cred', but it needs the parameter for your redirect_uri again:
$getStr = self::FB_GRAPH_URL . 'oauth/access_token?' . http_build_query(array(
           'client_id'     => 'APP_ID',
           'redirect_uri'  => 'REDIRECT_URI',
           'client_secret' => 'SECRET_KEY',
           'code'          => $fbCode)
          );

Then, you can't just take the answer of this call as your access_token, as there is much more in it:
access_token=USER_ACCESS_TOKEN&expires=NUMBER_OF_SECONDS_UNTIL_TOKEN_EXPIRES

and you only want the access_token part of it:
$response = file_get_contents($getStr);
$params = null;
parse_str($response, $params);

$dbpath = "https://graph.facebook.com/me?access_token=" . $params['access_token'];


Q: Run a single test with multiple configs in parallel using pytest I have to run the same test against different hosts in parallel. Currently, i'm making a bunchof pytest.main() calls. But this is not run in parallel and results are not aggregated. This is the content of runtest.py:
pytest.main('--conf=c1.txt')
pytest.main('--conf=c2.txt')
pytest.main('--conf=c3.txt')

I have just one test_host.py which looks something like:
test_pinghost(conf):
    # pings a host in config

Is there a way to run this in parallel  and aggregate results?
PS:the config filejust contains the host IP

A: Please use http://pytest.readthedocs.org/en/2.0.3/xdist.html, it enables pytest to run tests across multiple processes/machines


Q: Classes with String Switches  class AddItemOption
{
    //Fields that contain class data
    string input = Console.ReadLine();
   //Methods that define class functionality
    public string myFunction(string Value)
    {
        switch (input)
        {
            case "Umbrella":
               Console.WriteLine("Umbrella is selected");
               break;
            case "Rain Coat":
               Console.WriteLine("Raincoat is selected");
               break;
            case "Boots":
                Console.WriteLine("Boots is selected");
                break;
            case "Hood":
                Console.WriteLine("Hood is selected");
                break;
            default:
                Console.WriteLine("Input not reconized, please choose another item");
                break;

        }

    }

I get the error "Not all code paths return a value". It is from myFunction(string Value). I'm not sure how to return this, or what to put in the parameter to get it to work. Do I need something below it too? I am new to classes. Please tell me if I'm doing this all wrong or if that is where the switch statement should go!
   public AddItemOption(string input)

        {

        }

FROM Shyju I changed it to:
class AddItemOptionOne
{
    //Fields that contain class data
    string input = Console.ReadLine();
   //Methods that define class functionality
    public string myFunction(string Value)
    {
        switch (input)
        {
            case "Key Chain":
               return "Key Chain is selected";
               break;
            case "Leather Armor":
               return "Leather Armor is selected";
               break;
            case "Boots":
                return "Boots is selected";
                break;
            case "Sword":
                return "Sword is selected";
                break;
            default:
                return "Input not reconized, please choose another item";
                break;

        }
    }

However, it does not recognize the breaks. "Unreachable Code Detected"

A: Your method has a return type of string. That means your method should always return some string. But you are not returning a string. instead you are Writing it to the console using WriteLine method.
So Change
Console.WriteLine("Umbrella is selected");

to
return "Umbrella is selected";

OR
You can change your method's return type to void.
 public void myFunction(string Value)
 {
   //your current fancy stuff here
   Console.WriteLine("My method dont have a return type");
 }

EDIT : AS per the question edit.
return statement will take the control out from your method. that means the next line (break) won't be executed. So remove the break statement.
 case "Key Chain":
           return "Key Chain is selected";

A: Well... You don't return anything from your function, so change it to
public void myFunction(string Value)

A: Try this:
class AddItemOptionOne
{
    //Methods that define class functionality
    public string myFunction(string input)
    {
        string result = string.Empty;

        switch (input)
        {
            case "Key Chain":
                result = "Key Chain is selected";
                break;
            case "Leather Armor":
                result = "Leather Armor is selected";
                break;
            case "Boots":
                result = "Boots is selected";
                break;
            case "Sword":
                result = "Sword is selected";
                break;
            default:
                result = "Input not reconized, please choose another item";
                break;
        }

        return result;
    }
}


Q: Does explicit template instantiation go in cpp or header file? Does explicit template instantiation go in cpp or header file?

A: Assuming by "explicit template instantiation" you mean something like
template class Foo<int>; // explicit type instantiation
// or
template void Foo<int>(); // explicit function instantiation

then these must go in source files as they considered definitions and are consequently subject to the ODR.

A: I've always done it in a cpp file. In a header, it would violate the one definition rule, at least (in the usual case) when the header was included in more than one cpp file (though there are ways to avoid that, which can be useful under a few, specific circumstances).

A: Either one.
If you are declaring a specific instance, you might declare it in your cpp file. However, if you are declaring a class member or something that will be referenced from multiple cpp files, that would go in your header file.


Q: How can I supply an AntiForgeryToken when posting JSON data using $.ajax? I am using the code as below of this post:
First I will fill an array variable with the correct values for the controller action.
Using the code below I think it should be very straightforward by just adding the following line to the JavaScript code:
data["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();

The <%= Html.AntiForgeryToken() %> is at its right place, and the action has a [ValidateAntiForgeryToken]
But my controller action keeps saying: "Invalid forgery token"
What am I doing wrong here?
Code
data["fiscalyear"] = fiscalyear;
data["subgeography"] = $(list).parent().find('input[name=subGeography]').val();
data["territories"] = new Array();

$(items).each(function() {
    data["territories"].push($(this).find('input[name=territory]').val());
});

    if (url != null) {
        $.ajax(
        {
            dataType: 'JSON',
            contentType: 'application/json; charset=utf-8',
            url: url,
            type: 'POST',
            context: document.body,
            data: JSON.stringify(data),
            success: function() { refresh(); }
        });
    }

A: You can set $.ajax  's traditional attribute and set it to true, to send json data as url encoded form. Make sure to set type:'POST'. With this method you can even send arrays and you do not have to use JSON.stringyfy or any changes on server side (e.g. creating custom attributes to sniff header )
I have tried this on ASP.NET MVC3 and jquery 1.7 setup and it's working
following is the code snippet.
var data = { items: [1, 2, 3], someflag: true};

data.__RequestVerificationToken = $(':input[name="__RequestVerificationToken"]').val();

$.ajax({
    url: 'Test/FakeAction'
    type: 'POST',
    data: data
    dataType: 'json',
    traditional: true,
    success: function (data, status, jqxhr) {
        // some code after succes
    },
    error: function () {
        // alert the error
    }
});

This will match with MVC action with following signature
[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public ActionResult FakeAction(int[] items, bool someflag)
{
}

A: You don't need the ValidationHttpRequestWrapper solution since MVC 4. According to this link.

*

*Put the token in the headers.

*Create a filter.

*Put the attribute on your method.

Here is my solution:
var token = $('input[name="__RequestVerificationToken"]').val();
var headers = {};
headers['__RequestVerificationToken'] = token;
$.ajax({
    type: 'POST',
    url: '/MyTestMethod',
    contentType: 'application/json; charset=utf-8',
    headers: headers,
    data: JSON.stringify({
        Test: 'test'
    }),
    dataType: "json",
    success: function () {},
    error: function (xhr) {}
});

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class ValidateJsonAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }

        var httpContext = filterContext.HttpContext;
        var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName];
        AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Headers["__RequestVerificationToken"]);
    }
}

[HttpPost]
[AllowAnonymous]
[ValidateJsonAntiForgeryToken]
public async Task<JsonResult> MyTestMethod(string Test)
{
    return Json(true);
}

A: What is wrong is that the controller action that is supposed to handle this request and which is marked with the [ValidateAntiForgeryToken] expects a parameter called __RequestVerificationToken to be POSTed along with the request.
There's no such parameter POSTed as you are using JSON.stringify(data) which converts your form to its JSON representation and so the exception is thrown.
So I can see two possible solutions here:
Number 1: Use x-www-form-urlencoded instead of JSON for sending your request parameters:
data["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
data["fiscalyear"] = fiscalyear;
// ... other data if necessary

$.ajax({
    url: url,
    type: 'POST',
    context: document.body,
    data: data,
    success: function() { refresh(); }
});

Number 2: Separate the request into two parameters:
data["fiscalyear"] = fiscalyear;
// ... other data if necessary
var token = $('[name=__RequestVerificationToken]').val();

$.ajax({
    url: url,
    type: 'POST',
    context: document.body,
    data: { __RequestVerificationToken: token, jsonRequest: JSON.stringify(data) },
    success: function() { refresh(); }
});

So in all cases you need to POST the __RequestVerificationToken value.

A: You can't validate an content of type contentType: 'application/json; charset=utf-8' because your date will be uploaded not in the Form property of the request, but in the InputStream property, and you will never have this Request.Form["__RequestVerificationToken"].
This will be always empty and validation will fail.

A: You won't ever have to validate an AntiForgeryToken when you receive posted JSON.
The reason is that AntiForgeryToken has been created to prevent CSRF. Since you can't post AJAX data to another host and HTML forms can't submit JSON as the request body, you don't have to protect your app against posted JSON.

A: I have resolved it globally with RequestHeader.
$.ajaxPrefilter(function (options, originalOptions, jqXhr) {
    if (options.type.toUpperCase() === "POST") {
        // We need to add the verificationToken to all POSTs
        if (requestVerificationTokenVariable.length > 0)
            jqXhr.setRequestHeader("__RequestVerificationToken", requestVerificationTokenVariable);
    }
});

where the requestVerificationTokenVariable is an variable string that contains the token value.
Then all ajax call send the token to the server, but the default ValidateAntiForgeryTokenAttribute get the Request.Form value.
I have writed and added this globalFilter that copy token from header to request.form, than i can use the default ValidateAntiForgeryTokenAttribute:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
      filters.Add(new GlobalAntiForgeryTokenAttribute(false));
}

public class GlobalAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
    private readonly bool autoValidateAllPost;

    public GlobalAntiForgeryTokenAttribute(bool autoValidateAllPost)
    {
        this.autoValidateAllPost = autoValidateAllPost;
    }

    private const string RequestVerificationTokenKey = "__RequestVerificationToken";
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        var req = filterContext.HttpContext.Request;
        if (req.HttpMethod.ToUpperInvariant() == "POST")
        {
            //gestione per ValidateAntiForgeryToken che gestisce solo il recupero da Request.Form (non disponibile per le chiamate ajax json)
            if (req.Form[RequestVerificationTokenKey] == null && req.IsAjaxRequest())
            {
                var token = req.Headers[RequestVerificationTokenKey];
                if (!string.IsNullOrEmpty(token))
                {
                    req.Form.SetReadOnly(false);
                    req.Form[RequestVerificationTokenKey] = token;
                    req.Form.SetReadOnly(true);
                }
            }

            if (autoValidateAllPost)
                AntiForgery.Validate();
        }
    }
}

public static class NameValueCollectionExtensions
{
    private static readonly PropertyInfo NameObjectCollectionBaseIsReadOnly = typeof(NameObjectCollectionBase).GetProperty("IsReadOnly", BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Instance);

    public static void SetReadOnly(this NameValueCollection source, bool readOnly)
    {
        NameObjectCollectionBaseIsReadOnly.SetValue(source, readOnly);
    }
}

This work for me :)

A: I hold the token in my JSON object and I ended up modifying the ValidateAntiForgeryToken class to check the InputStream of the Request object when the post is json. I've written a blog post about it, hopefully you might find it useful.

A: Check out Dixin's Blog for a great post on doing exactly that.
Also, why not use $.post instead of $.ajax?
Along with the jQuery plugin on that page, you can then do something as simple as:
        data = $.appendAntiForgeryToken(data,null);

        $.post(url, data, function() { refresh(); }, "json");

A: AJAX based model posting with AntiForgerytoken can be made bit easier with Newtonsoft.JSON library
Below approach worked for me:
Keep your AJAX post like this:
$.ajax({
  dataType: 'JSON',
  url: url,
  type: 'POST',
  context: document.body,
  data: {
    '__RequestVerificationToken': token,
    'model_json': JSON.stringify(data)
  };,
  success: function() {
    refresh();
  }
});

Then in your MVC action:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(FormCollection data) {
 var model = JsonConvert.DeserializeObject < Order > (data["model_json"]);
 return Json(1);
}

Hope this helps :)

A: I was just implementing this actual problem in my current project. I did it for all Ajax POSTs that needed an authenticated user.
First off, I decided to hook my jQuery Ajax calls so I do not to repeat myself too often. This JavaScript snippet ensures all ajax (post) calls will add my request validation token to the request. Note: the name __RequestVerificationToken is used by the .NET framework so I can use the standard Anti-CSRF features as shown below.
$(document).ready(function () {
    securityToken = $('[name=__RequestVerificationToken]').val();
    $('body').bind('ajaxSend', function (elm, xhr, s) {
        if (s.type == 'POST' && typeof securityToken != 'undefined') {
            if (s.data.length > 0) {
                s.data += "&__RequestVerificationToken=" + encodeURIComponent(securityToken);
            }
            else {
                s.data = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
            }
        }
    });
});

In your Views where you need the token to be available to the above JavaScript code, just use the common HTML-Helper. You can basically add this code wherever you want. I placed it within a if(Request.IsAuthenticated) statement:
@Html.AntiForgeryToken() // You can provide a string as salt when needed which needs to match the one on the controller

In your controller simply use the standard ASP.NET MVC anti-CSRF mechanism. I did it like this (though I actually used a salt).
[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public JsonResult SomeMethod(string param)
{
    // Do something
    return Json(true);
}

With Firebug or a similar tool you can easily see how your POST requests now have a __RequestVerificationToken parameter appended.

A: I had to be a little shady to validate anti-forgery tokens when posting JSON, but it worked.
//If it's not a GET, and the data they're sending is a string (since we already had a separate solution in place for form-encoded data), then add the verification token to the URL, if it's not already there.
$.ajaxSetup({
    beforeSend: function (xhr, options) {
        if (options.type && options.type.toLowerCase() !== 'get' && typeof (options.data) === 'string' && options.url.indexOf("?__RequestVerificationToken=") < 0 && options.url.indexOf("&__RequestVerificationToken=") < 0) {
            if (options.url.indexOf('?') < 0) {
                options.url += '?';
            }
            else {
                options.url += '&';
            }
            options.url += "__RequestVerificationToken=" + encodeURIComponent($('input[name=__RequestVerificationToken]').val());
        }
    }
});

But, as a few people already mentioned, the validation only checks the form - not JSON, and not the query string. So, we overrode the attribute's behavior. Re-implementing all of the validation would have been terrible (and probably not secure), so I just overrode the Form property to, if the token were passed in the QueryString, have the built-in validation THINK it was in the Form.
That's a little tricky because the form is read-only, but doable.
    if (IsAuth(HttpContext.Current) && !IsGet(HttpContext.Current))
    {
        //if the token is in the params but not the form, we sneak in our own HttpContext/HttpRequest
        if (HttpContext.Current.Request.Params != null && HttpContext.Current.Request.Form != null
            && HttpContext.Current.Request.Params["__RequestVerificationToken"] != null && HttpContext.Current.Request.Form["__RequestVerificationToken"] == null)
        {
            AntiForgery.Validate(new ValidationHttpContextWrapper(HttpContext.Current), null);
        }
        else
        {
            AntiForgery.Validate(new HttpContextWrapper(HttpContext.Current), null);
        }
    }

    //don't validate un-authenticated requests; anyone could do it, anyway
    private static bool IsAuth(HttpContext context)
    {
        return context.User != null && context.User.Identity != null && !string.IsNullOrEmpty(context.User.Identity.Name);
    }

    //only validate posts because that's what CSRF is for
    private static bool IsGet(HttpContext context)
    {
        return context.Request.HttpMethod.ToUpper() == "GET";
    }

...
internal class ValidationHttpContextWrapper : HttpContextBase
{
    private HttpContext _context;
    private ValidationHttpRequestWrapper _request;

    public ValidationHttpContextWrapper(HttpContext context)
        : base()
    {
        _context = context;
        _request = new ValidationHttpRequestWrapper(context.Request);
    }

    public override HttpRequestBase Request { get { return _request; } }

    public override IPrincipal User
    {
        get { return _context.User; }
        set { _context.User = value; }
    }
}

internal class ValidationHttpRequestWrapper : HttpRequestBase
{
    private HttpRequest _request;
    private System.Collections.Specialized.NameValueCollection _form;

    public ValidationHttpRequestWrapper(HttpRequest request)
        : base()
    {
        _request = request;
        _form = new System.Collections.Specialized.NameValueCollection(request.Form);
        _form.Add("__RequestVerificationToken", request.Params["__RequestVerificationToken"]);
    }

    public override System.Collections.Specialized.NameValueCollection Form { get { return _form; } }

    public override string ApplicationPath { get { return _request.ApplicationPath; } }
    public override HttpCookieCollection Cookies { get { return _request.Cookies; } }
}

There's some other stuff that's different about our solution (specifically, we're using an HttpModule so we don't have to add the attribute to every single POST) that I left out in favor of brevity. I can add it if necessary.

A: Unfortunately for me, the other answers rely on some request formatting handled by jquery, and none of them worked when setting the payload directly.  (To be fair, putting it in the header would have worked, but I did not want to go that route.)
To accomplish this in the beforeSend function, the following works.  $.params() transforms the object into the standard form / url-encoded format.
I had tried all sorts of variations of stringifying json with the token and none of them worked.
$.ajax({
...other params...,
beforeSend: function(jqXHR, settings){

    var token = ''; //get token

    data = {
        '__RequestVerificationToken' : token,
        'otherData': 'value'
     };
    settings.data = $.param(data);
    }
});

```

A: You should place AntiForgeryToken in a form tag:
@using (Html.BeginForm(actionName:"", controllerName:"",routeValues:null, method: FormMethod.Get, htmlAttributes: new { @class="form-validator" }))
{
    @Html.AntiForgeryToken();
}

Then in javascript modify the following code to be
var DataToSend = [];
DataToSend.push(JSON.stringify(data), $('form.form-validator').serialize());
$.ajax({
  dataType: 'JSON',
  contentType: 'application/json; charset=utf-8',
  url: url,
  type: 'POST',
  context: document.body,
  data: DataToSend,
  success: function() {
    refresh();
  }
});

Then you should be able to validate the request using ActionResult annotations
[ValidateAntiForgeryToken]
        [HttpPost]

I hope this helps.


Q: Videojs original timeline not coming I am using videojs in my application. I wrapped video tag inside video-wrapper div to make it as the size of parent div which is video-wrapper. But the problem is I am not able to see the actual timeline of videojs which comes with it. Chrome is adding it's own timeline I guess. This is my code
return (

                <video id="example_video_1" controls preload="auto" className="video-js vjs-default-skin" data-setup='{"fluid":true}'>
                    <source src={videoSrc} type="video/mp4"/>
                </video>

)

and this is css
.video-wrapper {
        background: white;
        position: relative;
        padding-bottom: 50% ;
        /* 16:8 */
        padding-top: 25px;
        height: 0;
    }

    .video-wrapper > video {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
    }

This is the result I get (look at the video timeline. It's not videojs's timeline)

This is how I want the player timeline to look like. Also it should fit in the video-wrapper. (In the below picture size is screwed up though)

The code for this was (but not responsive)
render() {
        var props = blacklist(this.props, 'children', 'className', 'src', 'type', 'onPlay');
        props.className = cx(this.props.className, 'videojs', 'video-js vjs-default-skin', 'vjs-big-play-centered');

        assign(props, {
            ref: 'video',
            controls: true,
            height:"650",
            width:"800"
        });

        if (this.props.tags.flag) {
            this.jumpToSpecificMarker();
            console.log("card clicked was" + this.props.card_Reducer.card_id);
        }
        return (

                <video{... props}>
                    <source src={this.props.src} type="video/mp4"/>
                </video>

                {/*<button onClick={this.jumpToSpecificMarker.bind(this)}>next</button>*/}
                {/*<button onClick={this.prev.bind(this)}>prev</button>*/}

)

    }


Q: Why does Rails generate a SQL query for an "include?" call in a view but not in the console? In my app a Position has_many Questions.  In my position edit view, I create a set of checkboxes by looping over an array of Questions and checking those that the current position already includes.
Looks like this:
- @questions.each do |question|
  = check_box_tag :question_ids, question.id, @position.questions.include?(question), name: 'position[question_ids][]', id: "question_check_#{question.id}"
  = label_tag "question_check_#{question.id}", question.text

I noticed loading this page took an unusually long time and my logs had these (I've snipped it for space):
LOG: duration: 827.370 ms statement: SELECT 1 FROM "questions" INNER JOIN "required_questions" ON "questions"."id" = "required_questions"."question_id" WHERE "required_questions"."position_id" IS NULL AND "questions"."id" = 1 ORDER BY account_id desc, "questions".id asc LIMIT 1

LOG: duration: 821.666 ms statement: SELECT 1 FROM "questions" INNER JOIN "required_questions" ON "questions"."id" = "required_questions"."question_id" WHERE "required_questions"."position_id" IS NULL AND "questions"."id" = 2 ORDER BY account_id desc, "questions".id asc LIMIT 1

LOG: duration: 713.379 ms statement: SELECT 1 FROM "questions" INNER JOIN "required_questions" ON "questions"."id" = "required_questions"."question_id" WHERE "required_questions"."position_id" IS NULL AND "questions"."id" = 3 ORDER BY account_id desc, "questions".id asc LIMIT 1

I tracked the problem to this code:
@position.questions.include?(question)

I thought this was a simple Array.include? check so I was surprised by my findings.  I was also surprised when I fixed it by adding an explicit .to_a call:
@position.questions.to_a.include?(question)

I was surprised a third time when I tested the original code in the Rails console and no SQL query was generated.
At this point I'm just curious - why did my original code generate a SQL query for each iteration when the same code in Rails console (albeit without the iteration and inside Rails console) did not?  Why didn't it just do an Array.include? check?

A: This happens because @position.questions is not an array. It's actually an ActiveRecord::Relation. The problem is that the console actually behaves differently from your server application.
For example, in your console position.questions returns an array. That is because the console is actually evaluating this expression as position.questions.all which is equivalent to position.questions.to_a. In your server application the to_a or all is not called until you actually use the query. This is a good thing because it means you can continue to build up a query and it will only actually get executed when it's called.
For instance:
query = @position.questions
query.first
query.last

Will actually generate two queries that return two records in your server application because the query variable will be assigned an ActiveRecord::Relation instead of an Array. In your console this will generate a single query, but the query will load all of the questions into an Array and assign that to query and then select the first and last elements.
The all, first, last, count and even include? keywords are all triggers that actually execute the query, so in your application when you call @position.questions.include? you are executing a single query on the @position.questions relation. Adding the to_a causes this query to be executed immediately.


Q: Vb.net 2 decimals double I want to place all my doubles to 2 decimals after the comma.
At this moment when the value is 0.30, my Datagridview shows 0.3..any idea?
This is my code:
    eenheidsprijs = Math.Round(eenheidsprijs, 2)
    basisbedrag = Math.Round(basisbedrag, 2)
    kortingbedrag = Math.Round(kortingbedrag, 2)
    netto = Math.Round(netto, 2)
    btwbedrag = Math.Round(btwbedrag, 2)
    totaal = Math.Round(totaal, 2)

    Dim streenheidsprijs, strbasisbedrag, strkortingbedrag, strnetto, strbtwbedrag, strtotaal As String

    streenheidsprijs = Format(eenheidsprijs, "0.00")
    strbasisbedrag = Format(basisbedrag, "0.00")
    strkortingbedrag = Format(kortingbedrag, "0.00")
    strnetto = Format(netto, "0.00")
    strbtwbedrag = btwbedrag.ToString("N", CultureInfo.InvariantCulture)
    strtotaal = Format(totaal, "0.00")

    eenheidsprijs = Double.Parse(streenheidsprijs)
    basisbedrag = Double.Parse(strbasisbedrag)
    kortingbedrag = Double.Parse(strkortingbedrag)
    netto = Double.Parse(strnetto)
    btwbedrag = Double.Parse(strbtwbedrag)
    totaal = Double.Parse(strtotaal)

A: Which value is bound to your datagrid? streenheidsprijs or eenheidsprijs? The string value is formatted to 2 decimal places, but the double variable doesn't inherit the number of decimal places to show. In actual fact, there is no value in the lines to re-parse the string values that have been formatted:
eenheidsprijs = Double.Parse(streenheidsprijs)

The data grid columns should either be bound to the string values that have been formatted to 2 dp, or you should configure the display properties of the columns in the data grid so that they only show two decimal places.

A: You can provide a format string to the default cell style of the column. In your case, the format F2 would be preferable.
At run-time:
myDataGridView.Columns("myColumnName").DefaultCellStyle.Format = "F2"

At design-time:

Sample form
Public Class Form1

    Public Sub New()
        Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US")
        Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US")
        Me.InitializeComponent()
        Me.ClientSize = New Size(350, 400)
        Me.column1 = New DataGridViewTextBoxColumn With {.Name = "Column1", .HeaderText = "Double (F2)", .ValueType = GetType(Double), .Width = 100}
        Me.column1.DefaultCellStyle.Format = "F2"
        Me.column2 = New DataGridViewTextBoxColumn With {.Name = "Column2", .HeaderText = "Double (F8)", .ValueType = GetType(Double), .AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill, .MinimumWidth = 100}
        Me.column2.DefaultCellStyle.Format = "F8"
        Me.grid = New DataGridView With {.Dock = DockStyle.Fill}
        Me.grid.Columns.AddRange(Me.column1, Me.column2)
        For i As Double = 0.0R To 9.0R : Me.grid.Rows.Add(i, i) : Next
        Me.Controls.Add(Me.grid)
    End Sub

    Private WithEvents grid As DataGridView
    Private WithEvents column1 As DataGridViewTextBoxColumn
    Private WithEvents column2 As DataGridViewTextBoxColumn

End Class


Q: Unity Google Play Services: Authentication Failed always: I have a problem with authenticate. The authenticate always fail and I can't understand the cause (not only fail in the editor, in my device too). Here is the code:
 using UnityEngine;
 using UnityEngine.SceneManagement;
 using UnityEngine.UI;
 using UnityEngine.Advertisements;
 using System.Collections;
 using System.Collections.Generic;
 using GooglePlayGames;
 using UnityEngine.SocialPlatforms;
 using GooglePlayGames.BasicApi;
 using UnityEngine.Analytics;

 public class Menu : MonoBehaviour {

 public Text record;

 /**
     Menu when the player isn´t authenticate
  */
 public GameObject signIn;

 public GameObject test;

 void Awake()
 {
     PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder ().Build ();
     PlayGamesPlatform.InitializeInstance(config);
     GooglePlayGames.PlayGamesPlatform.DebugLogEnabled = false;
     GooglePlayGames.PlayGamesPlatform.Activate ();
 }

 void Start()
 {
     Advertisement.Initialize ("CORRECT_NUMBER", true);

     if (PlayerPrefs.HasKey("record"))
     {
         record.text = "Record actual: " + PlayerPrefs.GetInt("record");
         Analytics.CustomEvent ("Start Play", new Dictionary<string, object>{ { "Record", PlayerPrefs.GetInt("record")} });
         if (Social.localUser.authenticated)
         {
             Social.ReportScore (PlayerPrefs.GetInt ("record"), "CORRECT_CODE", (bool success) => { });
         }
     } else {
             record.text = "Consigue un record!!";
     }

     if (Social.localUser.authenticated)
     {
         signIn.SetActive (false);
     }
     test.SetActive (false);
 }

 public void OnPlay()
 {
     ShowAd ();
     SceneManager.LoadScene("Play");
     Time.timeScale = 0;
 }

 public void OnArchievements()
 {
     if (Social.localUser.authenticated) {
         Social.ShowAchievementsUI ();
     } else {
         Social.localUser.Authenticate ((bool success) => {
             if (success) {
                 Social.ShowAchievementsUI ();
             }
         });
     }

 }

 public void OnMatching()
 {
     if (Social.localUser.authenticated) {
         Social.ShowLeaderboardUI ();
     } else {
         Social.localUser.Authenticate ((bool success) => {
             if (success) {
                 Social.ShowLeaderboardUI ();
             }
         });
     }
 }

 public void OnExit()
 {
     Analytics.CustomEvent ("Stop Play", new Dictionary<string, object>{ { "Record", PlayerPrefs.GetInt("record")} });
     Application.Quit();
 }

 public void SignIn()
 {
     Social.localUser.Authenticate((bool success) => {
         if (success)
         {
             Debug.Log ("Sign in");
             signIn.SetActive (false);
         }
         else
         {
             Debug.Log ("Fail for some reason...");
             test.SetActive (true);
         }

     });

 }

 public void Later()
 {
     signIn.SetActive (false);
 }

 public void ShowAd()
 {
     if (Advertisement.IsReady())
     {
         Advertisement.Show();
     }
 }
 }

The object "test" is only a white box that appears to know the authentication fail. The console don't show me any type of error, so I don't know where find the problem... Any idea what's the problem? PD: I use version 0.9.34 and Unity 5.3.5f1
Thanks in advance!

A: Not a problem.
I am going to write the response here because it may be quite long.
Unity has the default ISocialPlatform set to Apple. Doing the "PlayGamesClientConfiguration" you change the default ISocialPlatform to Google+.
My comment was talking about your Awake() function. I recommended you to put it in Start() as follows:
    void Start()
         {
    //added code
     PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder ().Build ();
         PlayGamesPlatform.InitializeInstance(config);
         GooglePlayGames.PlayGamesPlatform.DebugLogEnabled = false;

         //GooglePlayGames.PlayGamesPlatform.Activate (); //this is wrong

      //WHAT YOU ARE MISSING
      PlayGamesPlatform.Activate();
      //END OF WHAT YOU ARE MISSING

             Advertisement.Initialize ("CORRECT_NUMBER", true);

             if (PlayerPrefs.HasKey("record"))
             {
                 record.text = "Record actual: " + PlayerPrefs.GetInt("record");
                 Analytics.CustomEvent ("Start Play", new Dictionary<string, object>{ { "Record", PlayerPrefs.GetInt("record")} });

      //you should do this once the user is authenticated and logged in
                 if (Social.localUser.authenticated)
                 {
                     Social.ReportScore (PlayerPrefs.GetInt ("record"), "CORRECT_CODE", (bool success) => { });
                 }
             } else {
                     record.text = "Consigue un record!!";
             }

             if (Social.localUser.authenticated)
             {
                 signIn.SetActive (false);
             }
             test.SetActive (false);
         }

Then, you can create a button in the inspector inside your scene and call this:
 public void SignIn()
 {
     Social.localUser.Authenticate( ProcessAuthentication)
 }

The CallBackFunction is a void function that takes in a bool. (You were doing this correctly) I like making my code readable and easy to understand.
    void ProcessAuthentication (bool success)
        {
            if (true == success)
            {
                Debug.Log ("AUTHENTICATED!");
                if (Social.localUser.authenticated)
                 {
                     Social.ReportScore (PlayerPrefs.GetInt ("record"), "CORRECT_CODE", (bool success) => { });
                 }
             } else {
                     record.text = "Consigue un record!!";
             }

             if (Social.localUser.authenticated)
             {
                 signIn.SetActive (false);

                 //EDIT: you need to load the achievements to use them
                 Social.LoadAchievements (ProcessLoadedAchievements);

                Social.LoadScores(leaderboardID, CALLBACK) // Callback has to be a Action<IScore[]> callback
            }
             test.SetActive (false);
            }
            else
            {
                Debug.Log("Failed to authenticate");
                signIn.SetActive (true);
            }
        }

void ProcessLoadedAchievements (IAchievement[] achievements) {
        if (achievements.Length == 0)
        {
            Debug.Log ("Error: no achievements found");
        }
        else
        {
            Debug.Log ("Got " + achievements.Length + " achievements");
        }
    }

Let me know.
(I can explain it to you in Spanish too if you want)
Saludos!

A: I follow this tutorial: google tutorial in GitHub (README) and the tutorial don't say I must implement that method, in fact, when I read it, I understand these method are part of the engine.
Here is my new code:
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.Advertisements;
using System.Collections;
using System.Collections.Generic;
using GooglePlayGames;
using UnityEngine.SocialPlatforms;
using GooglePlayGames.BasicApi;
using UnityEngine.Analytics;

public class Menu : MonoBehaviour {

public Text record;

public GameObject test;

/**
    Indicador del jugador de que no ha iniciado sesión, y no podrá acceder al  ranking ni a los logros.
 */
public GameObject signIn;

void Start()
{
    PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder ().Build ();
    PlayGamesPlatform.InitializeInstance(config);
    GooglePlayGames.PlayGamesPlatform.DebugLogEnabled = true;
    PlayGamesPlatform.Activate();

    Advertisement.Initialize ("NUMBER", true);
    test.SetActive (false);

    //EDIT:
    SignIn ();

    if (PlayerPrefs.HasKey("record"))
    {
        record.text = "Record actual: " + PlayerPrefs.GetInt("record");
        Analytics.CustomEvent ("Start Play", new Dictionary<string, object>{ { "Record", PlayerPrefs.GetInt("record")} });

    } else {
            record.text = "Consigue un record!!";
    }

}

public void OnPlay()
{
    ShowAd ();
    SceneManager.LoadScene("Jugar");
    Time.timeScale = 0;
}

public void OnArchievements()
{
    if (Social.Active.localUser.authenticated) {
        Social.Active.ShowAchievementsUI ();
    } else {
        Social.Active.localUser.Authenticate ((bool success) => {
            if (success) {
                Social.Active.ShowAchievementsUI ();
            }
        });
    }

}

public void OnMatching()
{
    if (Social.Active.localUser.authenticated) {
        Social.Active.ShowLeaderboardUI ();
    } else {
        Social.Active.localUser.Authenticate ((bool success) => {
            if (success) {
                Social.Active.ShowLeaderboardUI ();
            }
        });
    }
}

public void OnExit()
{
    Analytics.CustomEvent ("Stop Play", new Dictionary<string, object>{ { "Record", PlayerPrefs.GetInt("record")} });
    Application.Quit();
}

public void SignIn()
{
    Social.Active.localUser.Authenticate (ProcessAuthentication);
}

public void Later()
{
    signIn.SetActive (false);
}

public void ShowAd()
{
    if (Advertisement.IsReady())
    {
        Advertisement.Show();
    }
}
//EDIT:
void ProcessAuthentication (bool success)
{
    if (true == success)
    {
        Debug.Log ("AUTHENTICATED!");
        if (Social.Active.localUser.authenticated)
        {
            Social.Active.LoadAchievements (ProcessLoadedAchievements);
            Social.Active.LoadScores (Fireball.GPGSIds.leaderboard_ranking, ProcessLoadedScores );
            if (PlayerPrefs.HasKey ("record"))
            {
                Social.Active.ReportScore (PlayerPrefs.GetInt ("record"),Fireball.GPGSIds.leaderboard_ranking, (bool report) => { });
            }
            signIn.SetActive (false);
            test.SetActive (true);
        }
    } else {
        Debug.Log("Failed to authenticate");
        signIn.SetActive (true);
    }
 }

  void ProcessLoadedAchievements (IAchievement[] achievements)
{
    if (achievements.Length == 0)
    {
        Debug.Log ("Error: no achievements found");
    }
    else
    {
        Debug.Log ("Got " + achievements.Length + " achievements");
    }
}

void ProcessLoadedScores (IScore[] scores)
{
    if (scores.Length == 0)
    {
        Debug.Log ("Error: no scores found");
    }
    else
    {
        Debug.Log ("Got " + scores.Length + " scores");
    }
}
}

EDIT:
Again in the editor I can't authenticate (in my device it fail too), I really don't understand the cause... Here the debug log (I active it, may can help):
DEBUG: Activating PlayGamesPlatform.
DEBUG: PlayGamesPlatform activated: GooglePlayGames.PlayGamesPlatform.
DEBUG: Creating platform-specific Play Games client.
DEBUG: Creating IPlayGamesClient in editor, using DummyClient.
DEBUG: Received method call on DummyClient - using stub implementation.
The last message, is when I try to authenticate, maybe you know the problem with the debug log.
PD: I read de documentation you send me, but is oriented to GameCenter (iOS), but I understand now more thing about that, really thanks.
Again thanks a lot for your time.


Q: Import Excel sheet into database using MVC .net Web Application Im new to programming and i am trying to import excel sheet into my database using mvc. I am able to import into my database but i need to find out how do i add validation for example email and duplicates. It seems like if i upload the same excel sheet twice, the data will be imported twice into my database. Also i would like to display the number of rows on the web page updated after importing . How do i do it ? This is my controller code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Data.OleDb;
using System.IO;

namespace excelimport.Controllers
{
    public class HomeController : Controller
    {
    // GET: /Home/
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
    OleDbConnection Econ;

    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        string filename = Guid.NewGuid() + Path.GetExtension(file.FileName);
        string filepath = "/excelfolder/" + filename;
        file.SaveAs(Path.Combine(Server.MapPath("/excelfolder"), filename));
        InsertExceldata(filepath, filename);
        return View();
    }

    private void ExcelConn(string filepath)
    {
        string constr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", filepath);
        Econ = new OleDbConnection(constr);
    }

    private void InsertExceldata(string fileepath, string filename)
    {
        string fullpath = Server.MapPath("/excelfolder/") + filename;
        ExcelConn(fullpath);
        String query = string.Format("Select * from [{0}]", "Sheet1$");
        OleDbCommand Ecom = new OleDbCommand(query, Econ);
        Econ.Open();

        DataSet ds = new DataSet();
        OleDbDataAdapter oda = new OleDbDataAdapter(query, Econ);
        Econ.Close();
        oda.Fill(ds);

        DataTable dt =ds.Tables[0];

        SqlBulkCopy objbulk = new SqlBulkCopy(con)
        {
            DestinationTableName = "UserInformation"
        };
        objbulk.ColumnMappings.Add("Email", "Email");
        objbulk.ColumnMappings.Add("Name", "Name");
        objbulk.ColumnMappings.Add("PhoneNo", "PhoneNo");
        objbulk.ColumnMappings.Add("Address", "Address");
        objbulk.ColumnMappings.Add("ZipCode", "ZipCode");
        objbulk.ColumnMappings.Add("Country", "Country");
        objbulk.ColumnMappings.Add("State", "State");
        objbulk.ColumnMappings.Add("City", "City");
        con.Open();
        objbulk.WriteToServer(dt);
        con.Close();       }
}

}