问:
Conditionals won't work
Okay so me and my friend are programming a small basic torture game and when I try to run my part of the code, some of the if/elif it will not run as if they were False when they seem True

```<code>lives = 5
lives_1 = 13
random_number = random.randint(0,100)
random_number_1 = random.randit(0,1000)
        while lives > 0:
            print random_number # delete in final product
            print "'You have %d chances to save your partner'" % (lives)
            guess_0 = int(raw_input("Guess a number from 1 to 100 "))
            print "You have guessed %d" % (guess_0)
            proceed_2 = raw_input("Press 'Enter' to proceed")
            if guess_0 != random_number: # This works
                print "It is incorrect, your partner loses a finger"
                lives -= 1
                continue
            elif guess_0 == random_number: # This works
                print "It is correct you and your partner get to walk free"
                print "GAME OVER"
                break
            elif guess > random_number: # Doesn't work
                print "'LOWER!'"
            elif guess < random_number: # Doesn't work
                print "'HIGHER!'"
        else:
            print "GAME OVER"

    while lives_1 > 0:
        print random_number_1 # delete in final product
        print "'You ha-- %d ch---e-'" % (lives_1)
        guess_1 = raw_input("What should you do? ")
        proceed_1 = raw_input("Press Enter to proceed")
        print "You decided to shout {}".format(guess_1)
        if guess_1 == random_number_1:
            print "The cult has decided to let you go" # doesn't work
            break
        elif guess_1 != random_number_1: # Works but also works when false
            lives_1 -= 1
            if lives_1 < 5:
                print "Tears begin to blind you as you're nearing death"
            continue
        elif guess_1 < random_number_1: # doesn't work
            print "You squeel in agony as one of your nails were ripped off"
            print "'Higher'"
        elif guess_1 > random_number_1: #doesn't work
            print "You squeel in agony as one of your nails were ripped off"
            print "'LOWER...'"
    else:
        print "GAME OVER"
</code>```

I want it to print out larger or larger than 3 but as you can see it won't. I have the same problem with the other one.

For the second while function, when I enter a number lower or larger than random_number(_1) it won't print out larger or lower and if I enter the value for random_number(_1) it won't run. I can't see anything wrong please help

答:
Perhaps you could try simplifying your conditionals to this?

```<code>if guess_0 == random_number:
   print "It is correct you and your partner get to walk free"
   print "GAME OVER"
   break
else:
   print "It is incorrect, your partner loses a finger"
   lives -= 1
   if guess_0 > random_number:
       print "'LOWER!'"
   else:
       print "'HIGHER!'"
</code>```

This principle should also apply to your second loop that you had asked about.

Title: Conditionals won't work

Body:
Okay so me and my friend are programming a small basic torture game and when I try to run my part of the code, some of the if/elif it will not run as if they were False when they seem True

lives = 5
lives_1 = 13
random_number = random.randint(0,100)
random_number_1 = random.randit(0,1000)
        while lives > 0:
            print random_number # delete in final product
            print "'You have %d chances to save your partner'" % (lives)
            guess_0 = int(raw_input("Guess a number from 1 to 100 "))
            print "You have guessed %d" % (guess_0)
            proceed_2 = raw_input("Press 'Enter' to proceed")
            if guess_0 != random_number: # This works
                print "It is incorrect, your partner loses a finger"
                lives -= 1
                continue
            elif guess_0 == random_number: # This works
                print "It is correct you and your partner get to walk free"
                print "GAME OVER"
                break
            elif guess > random_number: # Doesn't work
                print "'LOWER!'"
            elif guess < random_number: # Doesn't work
                print "'HIGHER!'"
        else:
            print "GAME OVER"

    while lives_1 > 0:
        print random_number_1 # delete in final product
        print "'You ha-- %d ch---e-'" % (lives_1)
        guess_1 = raw_input("What should you do? ")
        proceed_1 = raw_input("Press Enter to proceed")
        print "You decided to shout {}".format(guess_1)
        if guess_1 == random_number_1:
            print "The cult has decided to let you go" # doesn't work
            break
        elif guess_1 != random_number_1: # Works but also works when false
            lives_1 -= 1
            if lives_1 < 5:
                print "Tears begin to blind you as you're nearing death"
            continue
        elif guess_1 < random_number_1: # doesn't work
            print "You squeel in agony as one of your nails were ripped off"
            print "'Higher'"
        elif guess_1 > random_number_1: #doesn't work
            print "You squeel in agony as one of your nails were ripped off"
            print "'LOWER...'"
    else:
        print "GAME OVER"

I want it to print out larger or larger than 3 but as you can see it won't. I have the same problem with the other one.

For the second while function, when I enter a number lower or larger than random_number(_1) it won't print out larger or lower and if I enter the value for random_number(_1) it won't run. I can't see anything wrong please help

Body:
Perhaps you could try simplifying your conditionals to this?

if guess_0 == random_number:
   print "It is correct you and your partner get to walk free"
   print "GAME OVER"
   break
else:
   print "It is incorrect, your partner loses a finger"
   lives -= 1
   if guess_0 > random_number:
       print "'LOWER!'"
   else:
       print "'HIGHER!'"

This principle should also apply to your second loop that you had asked about.


来源: stackexchange

问:
How to get Selected Currency in k2 Store - Joomla 3.x
I am creating a payment plugin for my k2 Store powered by joomla 3.8.2.

I want to get current or selected currency code USD.

basically I am looking some helper function which return selected Currency. something like this  K2Store::currency

I found this K2StoreFactory::getCurrencyObject() but its return all currency instead selected one.

答:
I found it myself, hope its help someone</p>

```<code>$currency = K2StoreFactory::getCurrencyObject();
$currency_code = $currency->getCode();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I found it myself, hope its help someone

$currency = K2StoreFactory::getCurrencyObject();
$currency_code = $currency->getCode();


问:
QThread with QTimer and QSerial - parenting
I'm trying to make a "self contained" communication object allocated in an different Thread, to keep it isolated from the GUI processing delay.

So, in an "AppCore" object creation I create one "CommCore" without parent:

```<code>cAppCore::cAppCore(QObject *parent) : QObject(parent)
{
    ....
    CommCore = new cCommCore;
    (here I do signal-slot connections between CommCore and AppCore)
    ....
}
</code>```

and in the CommCore constructor I do the following:

```<code>cCommCore::cCommCore(QObject *parent) : QObject(parent)
{
    CommThread = new QThread(this);
    CommSerial = new QSerialPort(this);
    CommTimer = new QTimer(this);

    connect(CommSerial,&QSerialPort::readyRead,this,&cCommCore::ProcessRXByte);
    connect(CommSerial, static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>(&QSerialPort::error), this, &cCommCore::HandleSerialError);
    connect(CommTimer, &QTimer::timeout, this,&cCommCore::TimerTimeout);

    CommTimer->start(OFFLINE_POLL_TIME);
    this->moveToThread(CommThread);
    CommThread->start(QThread::HighPriority);
}
</code>```

Now my questions:

1- It's ok to make the Thread handler object a child of the moved object? as it is created in the GUI thread (where the constructor is being called), then moved to the thread that is handled by itself (considering that if I need any control of it I will handle it from inside of the CommCore object)

2- It's ok to start the timer in the constructor (which is in the same thread of the timer constructor, GUI thread), and right after move everything to the new thread?

3- If I wanted to start the timer later, the only way would be thru signal-slot? where a signal emitted in the GUI thread and connected to a CommCore slot (which then would be queued and executed in the CommCore thread)

4- Considering that all my interactions between my CommCore object and the AppCore (GUI thread) are made thru signal-slot (which is thread safe), it is conceptually correct? (the idea of the object move itself and its children to a new thread, etc)

5- My serial communication routines based in pooling (timed by the timer) will be shielded from the GUI processing delays? (I mean, there will be no delays in the generation and processing of events generated by the Serial and Timer objects?)

答:
```<code>this->moveToThread(CommThread);
</code>```

will succeed if the object this has no parent. So you need to change the signature of your constructor. Aside of that it is ok, as the object is moved with its children...

The timer should not be started like this, as it is moved into an different thread. You should use invokeMethod such that it is the correct thread which perfoms the operation

```<code>QMetaObject::invokeMethod(CommTimer, "start");
</code>```

For your remaining questions all the answers are yes. As long as you use signals and call using invokeMethod, it is as if the thread is fetching from a pool of runnable and running them.

So thread safe and unaffected by the the main thread interruptions.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make a "self contained" communication object allocated in an different Thread, to keep it isolated from the GUI processing delay.

So, in an "AppCore" object creation I create one "CommCore" without parent:

cAppCore::cAppCore(QObject *parent) : QObject(parent)
{
    ....
    CommCore = new cCommCore;
    (here I do signal-slot connections between CommCore and AppCore)
    ....
}

and in the CommCore constructor I do the following:

cCommCore::cCommCore(QObject *parent) : QObject(parent)
{
    CommThread = new QThread(this);
    CommSerial = new QSerialPort(this);
    CommTimer = new QTimer(this);

    connect(CommSerial,&QSerialPort::readyRead,this,&cCommCore::ProcessRXByte);
    connect(CommSerial, static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>(&QSerialPort::error), this, &cCommCore::HandleSerialError);
    connect(CommTimer, &QTimer::timeout, this,&cCommCore::TimerTimeout);

    CommTimer->start(OFFLINE_POLL_TIME);
    this->moveToThread(CommThread);
    CommThread->start(QThread::HighPriority);
}

Now my questions:

1- It's ok to make the Thread handler object a child of the moved object? as it is created in the GUI thread (where the constructor is being called), then moved to the thread that is handled by itself (considering that if I need any control of it I will handle it from inside of the CommCore object)

2- It's ok to start the timer in the constructor (which is in the same thread of the timer constructor, GUI thread), and right after move everything to the new thread?

3- If I wanted to start the timer later, the only way would be thru signal-slot? where a signal emitted in the GUI thread and connected to a CommCore slot (which then would be queued and executed in the CommCore thread)

4- Considering that all my interactions between my CommCore object and the AppCore (GUI thread) are made thru signal-slot (which is thread safe), it is conceptually correct? (the idea of the object move itself and its children to a new thread, etc)

5- My serial communication routines based in pooling (timed by the timer) will be shielded from the GUI processing delays? (I mean, there will be no delays in the generation and processing of events generated by the Serial and Timer objects?)

Body:
this->moveToThread(CommThread);

will succeed if the object this has no parent. So you need to change the signature of your constructor. Aside of that it is ok, as the object is moved with its children...

The timer should not be started like this, as it is moved into an different thread. You should use invokeMethod such that it is the correct thread which perfoms the operation

QMetaObject::invokeMethod(CommTimer, "start");

For your remaining questions all the answers are yes. As long as you use signals and call using invokeMethod, it is as if the thread is fetching from a pool of runnable and running them.

So thread safe and unaffected by the the main thread interruptions.


问:
Laravel query builder join not working with selectRaw
I am using laravel's query builder to fetch locations from my database. I need to join 2 tables then query the results by location. It was all working fine until I added the join.

If I just do

```<code>$locations = DB::table('locations')
->join('charities', 'locations.charity', '=', 'charities.charity')
    ->when($charity, function ($query) use ($charity) {
          return $query->where('charity', '=', $charity);
    })
    ->get();
</code>```

Then it return the contents of both tables which I need. If I do

```<code>$locations = DB::table('locations')
            ->select('locations.*')
            ->selectRaw('( 3959 * acos( cos( radians(?) ) *
                               cos( radians( latitude ) )
                               * cos( radians( longitude ) - radians(?)
                               ) + sin( radians(?) ) *
                               sin( radians( latitude ) ) )
                             ) AS distance', [$lat, $lng, $lat])
            ->havingRaw("distance < ?", [$max_distance])
            ->when($charity, function ($query) use ($charity) {
                return $query->where('charity', '=', $charity);
            })
            ->get();
</code>```

Then I get the contents of the locations table and the filter works fine.

I put the both together and it only return the content of locations with no error and the charities table not been joined on.

```<code>$locations = DB::table('locations')
            ->join('charities', 'locations.charity', '=', 'charities.charity')
            ->select('locations.*')
            ->selectRaw('( 3959 * acos( cos( radians(?) ) *
                               cos( radians( latitude ) )
                               * cos( radians( longitude ) - radians(?)
                               ) + sin( radians(?) ) *
                               sin( radians( latitude ) ) )
                             ) AS distance', [$lat, $lng, $lat])
            ->havingRaw("distance < ?", [$max_distance])
            ->when($charity, function ($query) use ($charity) {
                return $query->where('charity', '=', $charity);
            })
            ->get();
</code>```

答:
After MosCH comment I got it working, Pretty simple fix incase any one else has this issue see my code below. You'll notice I have specified locations.charity in the where clause Because the charity is what I join on I guess it was conflicting. </p>

```<code>$locations = DB::table('locations')
            ->join('charities', 'locations.charity', '=', 'charities.charity')
            ->select('*')
            ->selectRaw('( 3959 * acos( cos( radians(?) ) *
                               cos( radians( latitude ) )
                               * cos( radians( longitude ) - radians(?)
                               ) + sin( radians(?) ) *
                               sin( radians( latitude ) ) )
                             ) AS distance', [$lat, $lng, $lat])
            ->havingRaw("distance < ?", [$max_distance])
            ->when($charity, function ($query) use ($charity) {
                return $query->where('locations.charity', '=', $charity);
            })
            ->get();
</code>```

Body:
I am using laravel's query builder to fetch locations from my database. I need to join 2 tables then query the results by location. It was all working fine until I added the join.

If I just do

$locations = DB::table('locations')
->join('charities', 'locations.charity', '=', 'charities.charity')
    ->when($charity, function ($query) use ($charity) {
          return $query->where('charity', '=', $charity);
    })
    ->get();

Then it return the contents of both tables which I need. If I do

$locations = DB::table('locations')
            ->select('locations.*')
            ->selectRaw('( 3959 * acos( cos( radians(?) ) *
                               cos( radians( latitude ) )
                               * cos( radians( longitude ) - radians(?)
                               ) + sin( radians(?) ) *
                               sin( radians( latitude ) ) )
                             ) AS distance', [$lat, $lng, $lat])
            ->havingRaw("distance < ?", [$max_distance])
            ->when($charity, function ($query) use ($charity) {
                return $query->where('charity', '=', $charity);
            })
            ->get();

Then I get the contents of the locations table and the filter works fine.

I put the both together and it only return the content of locations with no error and the charities table not been joined on.

$locations = DB::table('locations')
            ->join('charities', 'locations.charity', '=', 'charities.charity')
            ->select('locations.*')
            ->selectRaw('( 3959 * acos( cos( radians(?) ) *
                               cos( radians( latitude ) )
                               * cos( radians( longitude ) - radians(?)
                               ) + sin( radians(?) ) *
                               sin( radians( latitude ) ) )
                             ) AS distance', [$lat, $lng, $lat])
            ->havingRaw("distance < ?", [$max_distance])
            ->when($charity, function ($query) use ($charity) {
                return $query->where('charity', '=', $charity);
            })
            ->get();

Body:
After MosCH comment I got it working, Pretty simple fix incase any one else has this issue see my code below. You'll notice I have specified locations.charity in the where clause Because the charity is what I join on I guess it was conflicting.

$locations = DB::table('locations')
            ->join('charities', 'locations.charity', '=', 'charities.charity')
            ->select('*')
            ->selectRaw('( 3959 * acos( cos( radians(?) ) *
                               cos( radians( latitude ) )
                               * cos( radians( longitude ) - radians(?)
                               ) + sin( radians(?) ) *
                               sin( radians( latitude ) ) )
                             ) AS distance', [$lat, $lng, $lat])
            ->havingRaw("distance < ?", [$max_distance])
            ->when($charity, function ($query) use ($charity) {
                return $query->where('locations.charity', '=', $charity);
            })
            ->get();


问:
How to put multiple images control in array or list in c#?
I have 60 images control of . I have two requirements:

put all images control in array

I have an roll no of 6 digits. and I want to match first digit to index of first 10 Images control, then 2nd digit to next 10 images and so on...
following is my code:

```<code>protected void Page_Load(object sender, EventArgs e)
{
        //for roll no
        int rollNo = int.Parse(Request.QueryString["RollNo"]);
        var rollNoArray = rollNo.ToString().Select(t =>
           int.Parse(t.ToString())).ToArray();
        int index1=0;
            int index2=0, index3=0, index4 = 0
            ,index5 = 0, index6 = 0;
        for (int i = 0; i < rollNoArray.Length; i++)
        {
            //Response.Write(rollNoArray[i]+"<br>");
            LBLRollNo.Text += "   " +
            rollNoArray[i].ToString();
            if (i == 0)
            {
                index1 = rollNoArray[0];
            }
            if (i == 1)
            {
                index2 = rollNoArray[1];
            }
            if (i == 2)
            {
                index3 = rollNoArray[2];
            }
            if (i == 3)
            {
                index4 = rollNoArray[3];
            }
            if (i == 4)
            {
                index5 = rollNoArray[4];
            }
            if (i == 5)
            {
                index6 = rollNoArray[5];
            }
        }
        Response.Write(index1);

        //index
        matchBubbles(index1);
        }
     }
      public void matchBubbles(int index)
       {
        Image[] a =new Image[10];
        for (int i = 0; i < 10; i++)
        {
            a[0] = Image0;
            a[1] = Image1;
            a[2] = Image2;
            a[3] = Image3;
            a[4] = Image4;
            a[5] = Image5;
            a[6] = Image6;
            a[7] = Image7;
            a[8] = Image8;
            a[9] = Image9;

            if (index == a[i])
            {

            }
        }
}
</code>```

I want to manipulate the psd file in a way that Whatever rollno is return from previous .aspx page an image(in my folder) should be inserted in the exact place against the index of the roll no means there is 10 boxes below for every digit and I want to insert the image there according to each digit of the roll no. Please help me!
Help me Please

答:
Here's a suggestion that also comes with a lot of other tips:
Assuming you have a webforms project, enter this into your default.aspx file (not the default.aspx.cs) If you have all this happening in another file, well then you insert it all into that particular one:

```<code><asp:Panel ID="HeaderPanel" runat="server">
        <h1>Enter image roll sequence here</h1>
        <asp:TextBox ID="RollNo" runat="server" Text="012345"></asp:TextBox><asp:Button ID="Button1" runat="server" Text="send" OnClick="Button1_Click" />
        <asp:Label ID="LBLRollNo" runat="server" Text="Text coming in from QueryString will end up here after postback"></asp:Label>
    </asp:Panel>

    <asp:Panel ID="ImagePanel" runat="server">
    </asp:Panel>
</code>```

Then you can paste this into your default.aspx.cs file (or whatever name you use instead:

```<code>protected void Page_Load(object sender, EventArgs e)
        {
            // This happens whenever there is a rollno variable coming in from the querystring
            if (Request.QueryString["RollNo"] != null)
            {
                string RollNo = Request.QueryString["RollNo"];
                ShowImages(RollNo);
            }
        }

        // this happens when you enter the roll numbers in the text box and hit the send button
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(RollNo.Text))
            {
                LBLRollNo.Text = " Selected roll numbers" + RollNo.Text;
                ShowImages(RollNo.Text);
            }
        }

        // Roll variable is the roll number. Imageno is the image number inside each Roll. And this information is stored in the image ID attribute.
        protected void ShowImages(string RollNumbers)
        {
            LBLRollNo.Text = " Selected roll numbers" + RollNumbers;
            var rollNoArray = RollNumbers.Select(t => int.Parse(t.ToString())).ToArray();

            foreach (int rollno in rollNoArray)
            {
                // add a HTML newline, just to make it more neat
                Literal templiteral = new Literal();
                templiteral.Text = "<br/>";
                ImagePanel.Controls.Add(templiteral);

                Label templabel = new Label();
                templabel.Text = "Images in roll number " + rollno.ToString();
                ImagePanel.Controls.Add(templabel);

                // Lay out the images belonging to this roll number (rollno)
                for (int Imageno = 0; Imageno <= 5; Imageno++)
                {
                    string identity = "ident|" + rollno.ToString() + "|" + Imageno.ToString() + "|"; // The IDs of each image on-screen will bear an ID like this: ident|0_0|
                    Image tempimage = new Image();
                    tempimage.ID = identity;
                    ImagePanel.Controls.Add(tempimage);
                }
            }
        }

        // This routine lays out all rolls and images in one go
        protected void LayOutImages()
        {
            for (int Roll = 0; Roll <= 10; Roll++)
            {
                Label templabel = new Label();
                templabel.Text = "Roll number " + Roll.ToString();
                ImagePanel.Controls.Add(templabel);

                for (int Imageno = 0; Imageno <= 5; Imageno++)
                {
                    string identity = "ident|" + Roll.ToString() + "|" + Imageno.ToString() + "|"; // The IDs of each image on-screen will bear an ID like this: ident|0_0|
                    Image tempimage = new Image();
                    tempimage.ID = identity;
                    ImagePanel.Controls.Add(tempimage);
                }
                Literal templiteral = new Literal();
                templiteral.Text = "<br/>";
                ImagePanel.Controls.Add(templiteral);
            }
        }
</code>```

Run it and observe that you do not need an array of image controls. You can either enter a variable in the querystring, or you can set the roll numbers in the text box. By the way. When parsing a string array starting wqith 0 from the querystring, the leading zero will not be considered, but it is fixed in this one.

The idea is that each image has an identity telling you what roll number it belongs to and what image number the image has in any given roll

Hope this helps

Body:
I have 60 images control of . I have two requirements:

put all images control in array

I have an roll no of 6 digits. and I want to match first digit to index of first 10 Images control, then 2nd digit to next 10 images and so on...
following is my code:

protected void Page_Load(object sender, EventArgs e)
{
        //for roll no
        int rollNo = int.Parse(Request.QueryString["RollNo"]);
        var rollNoArray = rollNo.ToString().Select(t =>
           int.Parse(t.ToString())).ToArray();
        int index1=0;
            int index2=0, index3=0, index4 = 0
            ,index5 = 0, index6 = 0;
        for (int i = 0; i < rollNoArray.Length; i++)
        {
            //Response.Write(rollNoArray[i]+"
");
            LBLRollNo.Text += "   " +
            rollNoArray[i].ToString();
            if (i == 0)
            {
                index1 = rollNoArray[0];
            }
            if (i == 1)
            {
                index2 = rollNoArray[1];
            }
            if (i == 2)
            {
                index3 = rollNoArray[2];
            }
            if (i == 3)
            {
                index4 = rollNoArray[3];
            }
            if (i == 4)
            {
                index5 = rollNoArray[4];
            }
            if (i == 5)
            {
                index6 = rollNoArray[5];
            }
        }
        Response.Write(index1);

        //index
        matchBubbles(index1);
        }
     }
      public void matchBubbles(int index)
       {
        Image[] a =new Image[10];
        for (int i = 0; i < 10; i++)
        {
            a[0] = Image0;
            a[1] = Image1;
            a[2] = Image2;
            a[3] = Image3;
            a[4] = Image4;
            a[5] = Image5;
            a[6] = Image6;
            a[7] = Image7;
            a[8] = Image8;
            a[9] = Image9;

            if (index == a[i])
            {

            }
        }
}

I want to manipulate the psd file in a way that Whatever rollno is return from previous .aspx page an image(in my folder) should be inserted in the exact place against the index of the roll no means there is 10 boxes below for every digit and I want to insert the image there according to each digit of the roll no. Please help me!
Help me Please

Body:
Here's a suggestion that also comes with a lot of other tips:
Assuming you have a webforms project, enter this into your default.aspx file (not the default.aspx.cs) If you have all this happening in another file, well then you insert it all into that particular one:

<asp:Panel ID="HeaderPanel" runat="server">
        <h1>Enter image roll sequence here</h1>
        <asp:TextBox ID="RollNo" runat="server" Text="012345"></asp:TextBox><asp:Button ID="Button1" runat="server" Text="send" OnClick="Button1_Click" />
        <asp:Label ID="LBLRollNo" runat="server" Text="Text coming in from QueryString will end up here after postback"></asp:Label>
    </asp:Panel>

    <asp:Panel ID="ImagePanel" runat="server">
    </asp:Panel>

Then you can paste this into your default.aspx.cs file (or whatever name you use instead:

protected void Page_Load(object sender, EventArgs e)
        {
            // This happens whenever there is a rollno variable coming in from the querystring
            if (Request.QueryString["RollNo"] != null)
            {
                string RollNo = Request.QueryString["RollNo"];
                ShowImages(RollNo);
            }
        }

        // this happens when you enter the roll numbers in the text box and hit the send button
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(RollNo.Text))
            {
                LBLRollNo.Text = " Selected roll numbers" + RollNo.Text;
                ShowImages(RollNo.Text);
            }
        }

        // Roll variable is the roll number. Imageno is the image number inside each Roll. And this information is stored in the image ID attribute.
        protected void ShowImages(string RollNumbers)
        {
            LBLRollNo.Text = " Selected roll numbers" + RollNumbers;
            var rollNoArray = RollNumbers.Select(t => int.Parse(t.ToString())).ToArray();

            foreach (int rollno in rollNoArray)
            {
                // add a HTML newline, just to make it more neat
                Literal templiteral = new Literal();
                templiteral.Text = "<br/>";
                ImagePanel.Controls.Add(templiteral);

                Label templabel = new Label();
                templabel.Text = "Images in roll number " + rollno.ToString();
                ImagePanel.Controls.Add(templabel);

                // Lay out the images belonging to this roll number (rollno)
                for (int Imageno = 0; Imageno <= 5; Imageno++)
                {
                    string identity = "ident|" + rollno.ToString() + "|" + Imageno.ToString() + "|"; // The IDs of each image on-screen will bear an ID like this: ident|0_0|
                    Image tempimage = new Image();
                    tempimage.ID = identity;
                    ImagePanel.Controls.Add(tempimage);
                }
            }
        }

        // This routine lays out all rolls and images in one go
        protected void LayOutImages()
        {
            for (int Roll = 0; Roll <= 10; Roll++)
            {
                Label templabel = new Label();
                templabel.Text = "Roll number " + Roll.ToString();
                ImagePanel.Controls.Add(templabel);

                for (int Imageno = 0; Imageno <= 5; Imageno++)
                {
                    string identity = "ident|" + Roll.ToString() + "|" + Imageno.ToString() + "|"; // The IDs of each image on-screen will bear an ID like this: ident|0_0|
                    Image tempimage = new Image();
                    tempimage.ID = identity;
                    ImagePanel.Controls.Add(tempimage);
                }
                Literal templiteral = new Literal();
                templiteral.Text = "<br/>";
                ImagePanel.Controls.Add(templiteral);
            }
        }

Run it and observe that you do not need an array of image controls. You can either enter a variable in the querystring, or you can set the roll numbers in the text box. By the way. When parsing a string array starting wqith 0 from the querystring, the leading zero will not be considered, but it is fixed in this one.

The idea is that each image has an identity telling you what roll number it belongs to and what image number the image has in any given roll

Hope this helps


问:
Excel-like filtering in Shiny

I have data of the following format:

```   Process       Class Category Template Company
1        A      Master Software       ZZ   Apple
2        B    Addendum Hardware       AA Samsung
3        C       Other Hardware       BB   Nokia
4        D      Master Software       CC    Moto
5        E    Addendum Services       ZZ      Mi
6        F Transaction Services       AA OnePlus
7        G      Master Software       BB   Apple
8        H Transaction     Tele       CC Samsung
9        I Transaction Hardware       ZZ   Nokia
10       J    Addendum     Tele       AA    Moto
```

My aim is to create a list of four selectInputs based on class, category, template and company and filter process using the same.

I have been able to do linear filteration dynamically, as in, in any one specified direction. For example,
on selecting class = "Master", selectInput for Category has choices = "Software".

What I'm attempting now is to create something similar to an Excel filter, where I can select any selectInput in any order and the remaining select inputs should dynamically only have values that reflect my previous choices.

I have the logic down, but I'm facing difficulty preventing selectInputs that have already been selected from re-initializing due to reactivity.

Code:

```<code> cldcheck_ctd <- reactive({
  if(is.null(input$classdrop))
  {cld <- -1}else if(input$classdrop != 0)
  {cld <- 6}else{cld <- 0}
})

cldcheck_td <- reactive({
  if(is.null(input$classdrop))
  {cld <- -1}else if(input$classdrop != 0)
  {cld <- 6}else{cld <- 0}
})

cldcheck_sd <- reactive({
  if(is.null(input$classdrop))
  {cld <- -1}else if(input$classdrop != 0)
  {cld <- 6}else{cld <- 0}
})

ctdcheck_cld <- reactive({
  if(is.null(input$categorydrop))
  {ctd <- -1}else if(input$categorydrop != 0)
  {ctd <- 6}else{ctd <- 0}

})

ctdcheck_td <- reactive({
  if(is.null(input$categorydrop))
  {ctd <- -1}else if(input$categorydrop != 0)
  {ctd <- 6}else{ctd <- 0}

})

ctdcheck_sd <- reactive({
  if(is.null(input$categorydrop))
  {ctd <- -1}else if(input$categorydrop != 0)
  {ctd <- 6}else{ctd <- 0}

})

tdcheck_cld <- reactive({if(is.null(input$templatedrop))
{td <- -1}else if(input$templatedrop != 0)
{td <- 6}else{td <- 0}

})

tdcheck_ctd <- reactive({if(is.null(input$templatedrop))
{td <- -1}else if(input$templatedrop != 0)
{td <- 6}else{td <- 0}

})

tdcheck_sd <- reactive({if(is.null(input$templatedrop))
{td <- -1}else if(input$templatedrop != 0)
{td <- 6}else{td <- 0}

})

sdcheck_cld <- reactive({if(is.null(input$supplierdrop))
{sd <- -1}else if(input$supplierdrop != 0)
{sd <- 6}else{sd <- 0}

})

sdcheck_ctd <- reactive({if(is.null(input$supplierdrop))
{sd <- -1}else if(input$supplierdrop != 0)
{sd <- 6}else{sd <- 0}

})

sdcheck_td <- reactive({if(is.null(input$supplierdrop))
{sd <- -1}else if(input$supplierdrop != 0)
{sd <- 6}else{sd <- 0}

})

output$class <- renderUI({
  result <- first_search()
  if(ctdcheck_cld() > 0)
  {
    result <- result[result$SCM.Category == input$categorydrop,]
  }

  if(tdcheck_cld() > 0)
  {
    result <- result[result$Contract.Template == input$templatedrop,]
  }

  if(sdcheck_cld() > 0)
  {
    result <- result[result$Emptoris.Supplier.Name == input$supplierdrop,]
  }

  y <- unique(result$Contract.Class)
  dropdown('classdrop', y, value = 0)
})

output$category <- renderUI({
  result <- first_search()

  if(cldcheck_ctd() > 0)
  {
    result <- result[result$Contract.Class == input$classdrop,]
  }

      if(tdcheck_ctd() > 0)
      {
        result <- result[result$Contract.Template == input$templatedrop,]
      }

      if(sdcheck_ctd() > 0)
      {
        result <- result[result$Emptoris.Supplier.Name == input$supplierdrop,]
      }
  y <- unique(result$SCM.Category)
  dropdown('categorydrop', y, value = 0)
})

output$template <- renderUI({
  result <- first_search()

  if(ctdcheck_td() > 0)
  {
    result <- result[result$SCM.Category == input$categorydrop,]
  }

  if(cldcheck_td() > 0)
  {
    result <- result[result$Contract.Class == input$classdrop,]
  }

    if(sdcheck_td() > 0)
    {
      result <- result[result$Emptoris.Supplier.Name == input$supplierdrop,]
    }
  y <- unique(result$Contract.Template)
  dropdown('templatedrop', y, value = 0)
})

output$supplier <- renderUI({
  result <- first_search()

  if(ctdcheck_sd() > 0)
  {
    result <- result[result$SCM.Category == input$categorydrop,]
  }

  if(tdcheck_sd() > 0)
  {
    result <- result[result$Contract.Template == input$templatedrop,]
  }

  if(cldcheck_sd() > 0)
  {
    result <- result[result$Contract.Class == input$classdrop,]
  }
  y <- unique(result$Emptoris.Supplier.Name)
  dropdown('supplierdrop', y, value = 0)
})
</code>```

first_search() is a function that returns the table in the format as shown above.

dropdown is a Semantic-UI widget that works exactly similar to selectInput. value = 0 means that the widget is initialized with a value of 0.

Thank you!

答:
Use global variables.

Assuming that you have one selectInput with id = 'classdrop', create a global variable classdropvalue and set it to input$classdrop within a reactive function.

With respect to the problem above,
server.R:

```<code>cldvalue <- 0
ctdvalue <- 0
tdvalue <- 0
sdvalue <- 0
server <- function(input, output){
  cld <- 0
  ctd <- 0
  td <- 0
  sd <- 0

  cldcheck <- reactive({
    if(is.null(input$classdrop))
    {cld <- 0}else if(input$classdrop != 0)
    {cld <- 6
    cldvalue <<- input$classdrop
    return(cld)}else{cld <- 0}
  })

  ctdcheck <- reactive({
    if(is.null(input$categorydrop))
    {ctd <- 0}else if(input$categorydrop != 0)
    {ctd <- 6
     ctdvalue <<- input$categorydrop
     return(ctd)}else{ctd <- 0}

  })

  tdcheck <- reactive({if(is.null(input$templatedrop))
  {td <- 0}else if(input$templatedrop != 0)
  {td <- 6
   tdvalue <<- input$templatedrop
   return(td)}else{td <- 0}

  })

  sdcheck <- reactive({if(is.null(input$supplierdrop))
  {sd <- 0}else if(input$supplierdrop != 0)
  {sd <- 6
   sdvalue <<- input$supplierdrop
   return(sd)}else{sd <- 0}

  })
#
#   output$filter <- renderText({
#     paste(cldcheck(), ctdcheck(), tdcheck(), sdcheck())})

  output$class <- renderUI({input$clear
    result <- first_search()
        if(ctdcheck() != 0)
        {
          result <- result[result$SCM.Category == input$categorydrop,]
        }

        if(tdcheck() != 0)
        {
          result <- result[result$Contract.Template == input$templatedrop,]
        }

        if(sdcheck() != 0)
        {
          result <- result[result$Emptoris.Supplier.Name == input$supplierdrop,]
        }

    y <- unique(result$Contract.Class)
    dropdown('classdrop', y, value = cldvalue)
  })

  output$category <- renderUI({input$clear
    result <- first_search()

    if(cldcheck() != 0)
    {
      result <- result[result$Contract.Class == input$classdrop,]
    }

        if(tdcheck() != 0)
        {
          result <- result[result$Contract.Template == input$templatedrop,]
        }

        if(sdcheck() != 0)
        {
          result <- result[result$Emptoris.Supplier.Name == input$supplierdrop,]
        }
    y <- unique(result$SCM.Category)
    dropdown('categorydrop', y, value = ctdvalue)
  })

  output$template <- renderUI({input$clear
    result <- first_search()

    if(ctdcheck() != 0)
    {
      result <- result[result$SCM.Category == input$categorydrop,]
    }

    if(cldcheck() != 0)
    {
      result <- result[result$Contract.Class == input$classdrop,]
    }

      if(sdcheck() != 0)
      {
        result <- result[result$Emptoris.Supplier.Name == input$supplierdrop,]
      }
    y <- unique(result$Contract.Template)
    dropdown('templatedrop', y, value = tdvalue)
  })

  output$supplier <- renderUI({input$clear
    result <- first_search()

    if(ctdcheck() != 0)
    {
      result <- result[result$SCM.Category == input$categorydrop,]
    }

    if(tdcheck() != 0)
    {
      result <- result[result$Contract.Template == input$templatedrop,]
    }

    if(cldcheck() != 0)
    {
      result <- result[result$Contract.Class == input$classdrop,]
    }
    y <- unique(result$Emptoris.Supplier.Name)
    dropdown('supplierdrop', y, value = sdvalue)
  })
  }
</code>```

By merely changing value (which is exactly the same as selected for selectInput) to the global variable, I was able to achieve Excel - like filtering.
 The caveat with this approach is that there has to be a reset button to set all the global variable to their initial state.

To anyone struggling with reactivity, I would strongly suggest using shiny.reactlog to understand the reactive flow of the shiny app.

Cheers!

Title: Excel-like filtering in Shiny

Body:
I have data of the following format:

   Process       Class Category Template Company
1        A      Master Software       ZZ   Apple
2        B    Addendum Hardware       AA Samsung
3        C       Other Hardware       BB   Nokia
4        D      Master Software       CC    Moto
5        E    Addendum Services       ZZ      Mi
6        F Transaction Services       AA OnePlus
7        G      Master Software       BB   Apple
8        H Transaction     Tele       CC Samsung
9        I Transaction Hardware       ZZ   Nokia
10       J    Addendum     Tele       AA    Moto

My aim is to create a list of four selectInputs based on class, category, template and company and filter process using the same.

I have been able to do linear filteration dynamically, as in, in any one specified direction. For example,
on selecting class = "Master", selectInput for Category has choices = "Software".

What I'm attempting now is to create something similar to an Excel filter, where I can select any selectInput in any order and the remaining select inputs should dynamically only have values that reflect my previous choices.

I have the logic down, but I'm facing difficulty preventing selectInputs that have already been selected from re-initializing due to reactivity.

Code:

 cldcheck_ctd <- reactive({
  if(is.null(input$classdrop))
  {cld <- -1}else if(input$classdrop != 0)
  {cld <- 6}else{cld <- 0}
})

cldcheck_td <- reactive({
  if(is.null(input$classdrop))
  {cld <- -1}else if(input$classdrop != 0)
  {cld <- 6}else{cld <- 0}
})

cldcheck_sd <- reactive({
  if(is.null(input$classdrop))
  {cld <- -1}else if(input$classdrop != 0)
  {cld <- 6}else{cld <- 0}
})

ctdcheck_cld <- reactive({
  if(is.null(input$categorydrop))
  {ctd <- -1}else if(input$categorydrop != 0)
  {ctd <- 6}else{ctd <- 0}

})

ctdcheck_td <- reactive({
  if(is.null(input$categorydrop))
  {ctd <- -1}else if(input$categorydrop != 0)
  {ctd <- 6}else{ctd <- 0}

})

ctdcheck_sd <- reactive({
  if(is.null(input$categorydrop))
  {ctd <- -1}else if(input$categorydrop != 0)
  {ctd <- 6}else{ctd <- 0}

})

tdcheck_cld <- reactive({if(is.null(input$templatedrop))
{td <- -1}else if(input$templatedrop != 0)
{td <- 6}else{td <- 0}

})

tdcheck_ctd <- reactive({if(is.null(input$templatedrop))
{td <- -1}else if(input$templatedrop != 0)
{td <- 6}else{td <- 0}

})

tdcheck_sd <- reactive({if(is.null(input$templatedrop))
{td <- -1}else if(input$templatedrop != 0)
{td <- 6}else{td <- 0}

})

sdcheck_cld <- reactive({if(is.null(input$supplierdrop))
{sd <- -1}else if(input$supplierdrop != 0)
{sd <- 6}else{sd <- 0}

})

sdcheck_ctd <- reactive({if(is.null(input$supplierdrop))
{sd <- -1}else if(input$supplierdrop != 0)
{sd <- 6}else{sd <- 0}

})

sdcheck_td <- reactive({if(is.null(input$supplierdrop))
{sd <- -1}else if(input$supplierdrop != 0)
{sd <- 6}else{sd <- 0}

})

output$class <- renderUI({
  result <- first_search()
  if(ctdcheck_cld() > 0)
  {
    result <- result[result$SCM.Category == input$categorydrop,]
  }

  if(tdcheck_cld() > 0)
  {
    result <- result[result$Contract.Template == input$templatedrop,]
  }

  if(sdcheck_cld() > 0)
  {
    result <- result[result$Emptoris.Supplier.Name == input$supplierdrop,]
  }

  y <- unique(result$Contract.Class)
  dropdown('classdrop', y, value = 0)
})

output$category <- renderUI({
  result <- first_search()

  if(cldcheck_ctd() > 0)
  {
    result <- result[result$Contract.Class == input$classdrop,]
  }

      if(tdcheck_ctd() > 0)
      {
        result <- result[result$Contract.Template == input$templatedrop,]
      }

      if(sdcheck_ctd() > 0)
      {
        result <- result[result$Emptoris.Supplier.Name == input$supplierdrop,]
      }
  y <- unique(result$SCM.Category)
  dropdown('categorydrop', y, value = 0)
})

output$template <- renderUI({
  result <- first_search()

  if(ctdcheck_td() > 0)
  {
    result <- result[result$SCM.Category == input$categorydrop,]
  }

  if(cldcheck_td() > 0)
  {
    result <- result[result$Contract.Class == input$classdrop,]
  }

    if(sdcheck_td() > 0)
    {
      result <- result[result$Emptoris.Supplier.Name == input$supplierdrop,]
    }
  y <- unique(result$Contract.Template)
  dropdown('templatedrop', y, value = 0)
})

output$supplier <- renderUI({
  result <- first_search()

  if(ctdcheck_sd() > 0)
  {
    result <- result[result$SCM.Category == input$categorydrop,]
  }

  if(tdcheck_sd() > 0)
  {
    result <- result[result$Contract.Template == input$templatedrop,]
  }

  if(cldcheck_sd() > 0)
  {
    result <- result[result$Contract.Class == input$classdrop,]
  }
  y <- unique(result$Emptoris.Supplier.Name)
  dropdown('supplierdrop', y, value = 0)
})

first_search() is a function that returns the table in the format as shown above.

dropdown is a Semantic-UI widget that works exactly similar to selectInput. value = 0 means that the widget is initialized with a value of 0.

Thank you!

Body:
Use global variables.

Assuming that you have one selectInput with id = 'classdrop', create a global variable classdropvalue and set it to input$classdrop within a reactive function.

With respect to the problem above,
server.R:

cldvalue <- 0
ctdvalue <- 0
tdvalue <- 0
sdvalue <- 0
server <- function(input, output){
  cld <- 0
  ctd <- 0
  td <- 0
  sd <- 0

  cldcheck <- reactive({
    if(is.null(input$classdrop))
    {cld <- 0}else if(input$classdrop != 0)
    {cld <- 6
    cldvalue <<- input$classdrop
    return(cld)}else{cld <- 0}
  })

  ctdcheck <- reactive({
    if(is.null(input$categorydrop))
    {ctd <- 0}else if(input$categorydrop != 0)
    {ctd <- 6
     ctdvalue <<- input$categorydrop
     return(ctd)}else{ctd <- 0}

  })

  tdcheck <- reactive({if(is.null(input$templatedrop))
  {td <- 0}else if(input$templatedrop != 0)
  {td <- 6
   tdvalue <<- input$templatedrop
   return(td)}else{td <- 0}

  })

  sdcheck <- reactive({if(is.null(input$supplierdrop))
  {sd <- 0}else if(input$supplierdrop != 0)
  {sd <- 6
   sdvalue <<- input$supplierdrop
   return(sd)}else{sd <- 0}

  })
#
#   output$filter <- renderText({
#     paste(cldcheck(), ctdcheck(), tdcheck(), sdcheck())})

  output$class <- renderUI({input$clear
    result <- first_search()
        if(ctdcheck() != 0)
        {
          result <- result[result$SCM.Category == input$categorydrop,]
        }

        if(tdcheck() != 0)
        {
          result <- result[result$Contract.Template == input$templatedrop,]
        }

        if(sdcheck() != 0)
        {
          result <- result[result$Emptoris.Supplier.Name == input$supplierdrop,]
        }

    y <- unique(result$Contract.Class)
    dropdown('classdrop', y, value = cldvalue)
  })

  output$category <- renderUI({input$clear
    result <- first_search()

    if(cldcheck() != 0)
    {
      result <- result[result$Contract.Class == input$classdrop,]
    }

        if(tdcheck() != 0)
        {
          result <- result[result$Contract.Template == input$templatedrop,]
        }

        if(sdcheck() != 0)
        {
          result <- result[result$Emptoris.Supplier.Name == input$supplierdrop,]
        }
    y <- unique(result$SCM.Category)
    dropdown('categorydrop', y, value = ctdvalue)
  })

  output$template <- renderUI({input$clear
    result <- first_search()

    if(ctdcheck() != 0)
    {
      result <- result[result$SCM.Category == input$categorydrop,]
    }

    if(cldcheck() != 0)
    {
      result <- result[result$Contract.Class == input$classdrop,]
    }

      if(sdcheck() != 0)
      {
        result <- result[result$Emptoris.Supplier.Name == input$supplierdrop,]
      }
    y <- unique(result$Contract.Template)
    dropdown('templatedrop', y, value = tdvalue)
  })

  output$supplier <- renderUI({input$clear
    result <- first_search()

    if(ctdcheck() != 0)
    {
      result <- result[result$SCM.Category == input$categorydrop,]
    }

    if(tdcheck() != 0)
    {
      result <- result[result$Contract.Template == input$templatedrop,]
    }

    if(cldcheck() != 0)
    {
      result <- result[result$Contract.Class == input$classdrop,]
    }
    y <- unique(result$Emptoris.Supplier.Name)
    dropdown('supplierdrop', y, value = sdvalue)
  })
  }

By merely changing value (which is exactly the same as selected for selectInput) to the global variable, I was able to achieve Excel - like filtering.
 The caveat with this approach is that there has to be a reset button to set all the global variable to their initial state.

To anyone struggling with reactivity, I would strongly suggest using shiny.reactlog to understand the reactive flow of the shiny app.

Cheers!


问:
In the for-loop, when I use 'append' to add a new element to the list, the one that has added before also change
I want to get transpose of matrix B without using Numpy. When I use 'append' to add a new element to the list, the one that has added before also change. How can I fix it?

```<code>from decimal import *

B = [[1,2,3,5],
     [2,3,3,5],
     [1,2,5,1]]

def shape(M):
    r = len(M)
    c = len(M[0])
    return r,c

def matxRound(M, decPts=4):
    for p in M:
        for index in range(len(M[0])):
            p[index] = round(p[index], decPts)

def transpose(M):
    c_trans, r_trans = shape(M)
    new_row = [0]*c_trans
    trans_M = []
    for i in range(r_trans):
        for j in range(c_trans):
            new_row[j] = M[j][i]
        print 'new_row',new_row
        print 'trans_M before append',trans_M
        trans_M.append(new_row)
        print 'trans_M after append',trans_M
    return trans_M

print transpose(B)
</code>```

The output is here:

```<code>new_row [1, 2, 1]
trans_M before append []
trans_M after append [[1, 2, 1]]
new_row [2, 3, 2]
trans_M before append [[2, 3, 2]]
trans_M after append [[2, 3, 2], [2, 3, 2]]
new_row [3, 3, 5]
trans_M before append [[3, 3, 5], [3, 3, 5]]
trans_M after append [[3, 3, 5], [3, 3, 5], [3, 3, 5]]
new_row [5, 5, 1]
trans_M before append [[5, 5, 1], [5, 5, 1], [5, 5, 1]]
trans_M after append [[5, 5, 1], [5, 5, 1], [5, 5, 1], [5, 5, 1]]
[[5, 5, 1], [5, 5, 1], [5, 5, 1], [5, 5, 1]]
</code>```

答:
The most pythonic way I know to perform matrix transposition without using Numpy (that should be the preferred way), is by using list unpacking (list expansion) and the builtin zip function transposed = list(zip(*B)).

However, zip() return tuples while your original matrix is a list of lists. So, if you want to keep your structure, you can use transposed = [list(i) for i in zip(*B)]

Body:
I want to get transpose of matrix B without using Numpy. When I use 'append' to add a new element to the list, the one that has added before also change. How can I fix it?

from decimal import *

B = [[1,2,3,5],
     [2,3,3,5],
     [1,2,5,1]]

def shape(M):
    r = len(M)
    c = len(M[0])
    return r,c

def matxRound(M, decPts=4):
    for p in M:
        for index in range(len(M[0])):
            p[index] = round(p[index], decPts)

def transpose(M):
    c_trans, r_trans = shape(M)
    new_row = [0]*c_trans
    trans_M = []
    for i in range(r_trans):
        for j in range(c_trans):
            new_row[j] = M[j][i]
        print 'new_row',new_row
        print 'trans_M before append',trans_M
        trans_M.append(new_row)
        print 'trans_M after append',trans_M
    return trans_M

print transpose(B)

The output is here:

new_row [1, 2, 1]
trans_M before append []
trans_M after append [[1, 2, 1]]
new_row [2, 3, 2]
trans_M before append [[2, 3, 2]]
trans_M after append [[2, 3, 2], [2, 3, 2]]
new_row [3, 3, 5]
trans_M before append [[3, 3, 5], [3, 3, 5]]
trans_M after append [[3, 3, 5], [3, 3, 5], [3, 3, 5]]
new_row [5, 5, 1]
trans_M before append [[5, 5, 1], [5, 5, 1], [5, 5, 1]]
trans_M after append [[5, 5, 1], [5, 5, 1], [5, 5, 1], [5, 5, 1]]
[[5, 5, 1], [5, 5, 1], [5, 5, 1], [5, 5, 1]]


问:
Facebook Api only returns 25 events max?
I am testing my new iframe app,

trying to get all events of an user, using the graph api.

```<code>$tempevent = $facebook->api('/me/events', 'get', array("fields"=>"id, name, start_time"));
</code>```

so it only returns 25 events .. the farthest events.

Any ideas?

Just checked out the JS-Version.. same result.

```<code>FB.api('/me/events', function(response) {
    console.log("event id: " + response.data[0].id); //k
    console.log("event id: " + response.data[24].id);  //k
    console.log("event id: " + response.data[25].id); //not k
});
</code>```

答:
I recomment you try to access the following URL https://graph.facebook.com/me/events?access_token=YOUR_ACCESS_TOKEN. Scroll down. You will see that facebook returns paginated results. Beside the data param (which is returned by the sdk) you have another paging param. This one contains links to more results, called next and previous. Use them to retrieve more events.

Also, if you want to retrieve more events per page you can add the limit param among access_token. For example: https://graph.facebook.com/me/events?access_token=YOUR_ACCESS_TOKEN&limit=50.

Good luck.

Body:
I am testing my new iframe app,

trying to get all events of an user, using the graph api.

$tempevent = $facebook->api('/me/events', 'get', array("fields"=>"id, name, start_time"));

so it only returns 25 events .. the farthest events.

Any ideas?

Just checked out the JS-Version.. same result.

FB.api('/me/events', function(response) {
    console.log("event id: " + response.data[0].id); //k
    console.log("event id: " + response.data[24].id);  //k
    console.log("event id: " + response.data[25].id); //not k
});

ContentLicense: CC BY-SA 2.5


问:
Controller action that receives any data in xml json or form-urlencoded
I have a requirement to create a controller action that can accept any data in XML, JSON or form-urlencoded. However, I couldn't make it work.

If my action has a Dictionary<string, object> parameter, it works for JSON and XML data, but not for form-urlencoded. If my action has a FormDataCollection parameter, it works for form-urlencoded but not for JSON and XML.

```<code>[HttpPost]
    public HttpResponseMessage Default(FormDataCollection data /*Dictionary<string,object> data*/)
    {
        try
        {
            if (data == null)
                return Request.CreateResponse(HttpStatusCode.BadRequest, new { ErrorMessage = "The request body is empty" });

            //var collection = GetCollection(data); //used when data=Dictionary<string,object>
            var collection = data.ReadAsNameValueCollection();
            var agent = new ScriptingAgentClient();
            var parameters = ServiceAgentParameters.From(collection);

            var result = agent.Run(parameters);
            if (result.Error)
                return Request.CreateResponse(HttpStatusCode.BadRequest, new { ErrorMessage = result.ErrorMessage, Exception = result.Exception });
            if (result.Data != null && result.Data.Count == 1) //result.Data is byte[]
            {
                //TODO: use the right Serializer
                var resultString = Encoding.UTF8.GetString(result.Data[0]);
                var serializer = new JavaScriptSerializer();
                var dict = serializer.Deserialize<Dictionary<string, string>>(resultString);
                return Request.CreateResponse(HttpStatusCode.OK, dict);
            }

            return Request.CreateResponse(HttpStatusCode.BadRequest, new { ErrorMessage = "Unknown error" });

        }
        catch (Exception ex)
        {
            Logger.Error("Error handling request", ex);
            return Request.CreateResponse(HttpStatusCode.BadRequest, new { ErrorMessage = ex.Unwrap().Message });
        }
    }
</code>```

ScriptingAgentClient will handle the data, whatever it may be.

If this isn't possible, how can I create two actions with same route where one will handle XML/JSON and another will handle form-urlencoded?

Note that I'm using .net40 and I can't change that. Noteworthy to mention that this webapi is a self-hosted api that will run in a windows service.

答:
I was able to make it work reading the Request instead of letting WebApi figuring it out:

```<code>[HttpPost]
    public HttpResponseMessage Default()
    {
        try
        {
            NameValueCollection collection = Request.Content.IsFormData() ?
                Request.Content.ReadAsFormDataAsync().Result :
                GetCollection(Request.Content.ReadAsAsync<IDictionary<string, object>>().Result);

            var parameters = ServiceAgentParameters.From(collection);

            var agent = new ScriptingAgentClient();
            var response = agent.Run(parameters);
            if (response.Error)
                return Request.CreateResponse(HttpStatusCode.BadRequest, new { ErrorMessage = response.ErrorMessage, Exception = response.Exception });

            if (response.Data != null && response.Data.Count == 1) //result.Data is List<byte[]>
            {
               //TODO: use the right Serializer
            var resultString = Encoding.UTF8.GetString(result.Data[0]);
            var serializer = new JavaScriptSerializer();
            var dict = serializer.Deserialize<Dictionary<string, string>>(resultString);
            return Request.CreateResponse(HttpStatusCode.OK, dict);
            }

            return Request.CreateResponse(HttpStatusCode.BadRequest, new { ErrorMessage = "Unknown error" });

        }
        catch (Exception ex)
        {
            Logger.Error("Error handling request", ex);
            return Request.CreateResponse(HttpStatusCode.BadRequest, new { ErrorMessage = ex.Unwrap().Message });
        }
    }
</code>```

Body:
I have a requirement to create a controller action that can accept any data in XML, JSON or form-urlencoded. However, I couldn't make it work.

If my action has a Dictionary<string, object> parameter, it works for JSON and XML data, but not for form-urlencoded. If my action has a FormDataCollection parameter, it works for form-urlencoded but not for JSON and XML.

[HttpPost]
    public HttpResponseMessage Default(FormDataCollection data /*Dictionary<string,object> data*/)
    {
        try
        {
            if (data == null)
                return Request.CreateResponse(HttpStatusCode.BadRequest, new { ErrorMessage = "The request body is empty" });

            //var collection = GetCollection(data); //used when data=Dictionary<string,object>
            var collection = data.ReadAsNameValueCollection();
            var agent = new ScriptingAgentClient();
            var parameters = ServiceAgentParameters.From(collection);

            var result = agent.Run(parameters);
            if (result.Error)
                return Request.CreateResponse(HttpStatusCode.BadRequest, new { ErrorMessage = result.ErrorMessage, Exception = result.Exception });
            if (result.Data != null && result.Data.Count == 1) //result.Data is byte[]
            {
                //TODO: use the right Serializer
                var resultString = Encoding.UTF8.GetString(result.Data[0]);
                var serializer = new JavaScriptSerializer();
                var dict = serializer.Deserialize<Dictionary<string, string>>(resultString);
                return Request.CreateResponse(HttpStatusCode.OK, dict);
            }

            return Request.CreateResponse(HttpStatusCode.BadRequest, new { ErrorMessage = "Unknown error" });

        }
        catch (Exception ex)
        {
            Logger.Error("Error handling request", ex);
            return Request.CreateResponse(HttpStatusCode.BadRequest, new { ErrorMessage = ex.Unwrap().Message });
        }
    }

ScriptingAgentClient will handle the data, whatever it may be.

If this isn't possible, how can I create two actions with same route where one will handle XML/JSON and another will handle form-urlencoded?

Note that I'm using .net40 and I can't change that. Noteworthy to mention that this webapi is a self-hosted api that will run in a windows service.

Body:
I was able to make it work reading the Request instead of letting WebApi figuring it out:

[HttpPost]
    public HttpResponseMessage Default()
    {
        try
        {
            NameValueCollection collection = Request.Content.IsFormData() ?
                Request.Content.ReadAsFormDataAsync().Result :
                GetCollection(Request.Content.ReadAsAsync<IDictionary<string, object>>().Result);

            var parameters = ServiceAgentParameters.From(collection);

            var agent = new ScriptingAgentClient();
            var response = agent.Run(parameters);
            if (response.Error)
                return Request.CreateResponse(HttpStatusCode.BadRequest, new { ErrorMessage = response.ErrorMessage, Exception = response.Exception });

            if (response.Data != null && response.Data.Count == 1) //result.Data is List<byte[]>
            {
               //TODO: use the right Serializer
            var resultString = Encoding.UTF8.GetString(result.Data[0]);
            var serializer = new JavaScriptSerializer();
            var dict = serializer.Deserialize<Dictionary<string, string>>(resultString);
            return Request.CreateResponse(HttpStatusCode.OK, dict);
            }

            return Request.CreateResponse(HttpStatusCode.BadRequest, new { ErrorMessage = "Unknown error" });

        }
        catch (Exception ex)
        {
            Logger.Error("Error handling request", ex);
            return Request.CreateResponse(HttpStatusCode.BadRequest, new { ErrorMessage = ex.Unwrap().Message });
        }
    }


问:
Sonarqube upgrade from 5.6.3 to 6.7
I am trying to upgrade our environment from 5.6.3 (LTS) to 6.7 (LTS) version. It is an H2 database which we are currently using for this (POC) so that actual data does not hamper. I have made all the changes as required for Upgrade.

1) Plugin are moved to the new instance

2) H2 db is the same with part of actual data

3) sonar.conf and wrapper.conf have been changed as required.

When I try to start the services on 6.7 version. We have the below value mentioned in sonar.properties.

```<code>sonar.search.javaOpts=-Xmx1G -Xms256m -Xss256k -Djava.net.preferIPv4Stack=true \
-XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 \
  -XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError
</code>```

When i give the above value for 6.7 I get issue as below:

```<code>jvm 1    | org.sonar.process.MessageException: a JVM option can't overwrite mand
atory JVM options. The following JVM options defined by property 'sonar.search.j
avaOpts' are invalid: -Xss256k overwrites -Xss1m
jvm 1    | 2017.12.07 10:53:38 INFO  app[][o.s.a.SchedulerImpl] Process [es] is
stopped
jvm 1    | 2017.12.07 10:53:38 INFO  app[][o.s.a.SchedulerImpl] SonarQube is sto
pped
jvm 1    |
jvm 1    | WrapperSimpleApp: Encountered an error running main: org.sonar.proces
s.MessageException: a JVM option can't overwrite mandatory JVM options. The foll
owing JVM options defined by property 'sonar.search.javaOpts' are invalid: -Xss2
56k overwrites -Xss1m
jvm 1    | org.sonar.process.MessageException: a JVM option can't overwrite mand
atory JVM options. The following JVM options defined by property 'sonar.search.j
avaOpts' are invalid: -Xss256k overwrites -Xss1m
</code>```

When I dont give the value I get the following issue

```<code>    2017.12.07 10:04:39 INFO  app[][o.s.a.AppFileSystem] Cleaning or creating temp directory E:\Apps\sonarqube-6.7\temp
2017.12.07 10:04:39 INFO  app[][o.s.a.es.EsSettings] Elasticsearch listening on /127.0.0.1:9001
2017.12.07 10:04:39 INFO  app[][o.s.a.p.ProcessLauncherImpl] Launch process[[key='es', ipcIndex=1, logFilenamePrefix=es]] from [E:\Apps\sonarqube-6.7\elasticsearch]: E:\Apps\JRE\8u91\jre\bin\java -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly -XX:+AlwaysPreTouch -server -Xss1m -Djava.awt.headless=true -Dfile.encoding=UTF-8 -Djna.nosys=true -Djdk.io.permissionsUseCanonicalPath=true -Dio.netty.noUnsafe=true -Dio.netty.noKeySetOptimization=true -Dio.netty.recycler.maxCapacityPerThread=0 -Dlog4j.shutdownHookEnabled=false -Dlog4j2.disable.jmx=true -Dlog4j.skipJansi=true -Xms512m -Xmx512m -XX:+HeapDumpOnOutOfMemoryError -Delasticsearch -Des.path.home=E:\Apps\sonarqube-6.7\elasticsearch -cp lib/* org.elasticsearch.bootstrap.Elasticsearch -Epath.conf=E:\Apps\sonarqube-6.7\temp\conf\es
2017.12.07 10:04:39 INFO  app[][o.s.a.SchedulerImpl] Waiting for Elasticsearch to be up and running
2017.12.07 10:04:41 INFO  app[][o.e.p.PluginsService] no modules loaded
2017.12.07 10:04:41 INFO  app[][o.e.p.PluginsService] loaded plugin [org.elasticsearch.transport.Netty4Plugin]
2017.12.07 10:04:41 WARN  app[][o.s.a.p.AbstractProcessMonitor] Process exited with exit value [es]: 1
</code>```

Let me know in case I am missing something

Thanks & Regards

答:
First, migration on H2 database are not supported: the migration won't be triggered in a H2 database.
You must use a dedicated database (Postgresql, Oracle, MySQL or Microsoft SQL Server) to trigger migrations.

Anyway, SonarQube is not starting because you are overwritten a property that it's not authorized anymore. To fix it, just remove -Xss256k on property sonar.search.javaOpts from sonar.properties.

Title: Sonarqube upgrade from 5.6.3 to 6.7

Body:
I am trying to upgrade our environment from 5.6.3 (LTS) to 6.7 (LTS) version. It is an H2 database which we are currently using for this (POC) so that actual data does not hamper. I have made all the changes as required for Upgrade.

1) Plugin are moved to the new instance

2) H2 db is the same with part of actual data

3) sonar.conf and wrapper.conf have been changed as required.

When I try to start the services on 6.7 version. We have the below value mentioned in sonar.properties.

sonar.search.javaOpts=-Xmx1G -Xms256m -Xss256k -Djava.net.preferIPv4Stack=true \
-XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 \
  -XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError

When i give the above value for 6.7 I get issue as below:

jvm 1    | org.sonar.process.MessageException: a JVM option can't overwrite mand
atory JVM options. The following JVM options defined by property 'sonar.search.j
avaOpts' are invalid: -Xss256k overwrites -Xss1m
jvm 1    | 2017.12.07 10:53:38 INFO  app[][o.s.a.SchedulerImpl] Process [es] is
stopped
jvm 1    | 2017.12.07 10:53:38 INFO  app[][o.s.a.SchedulerImpl] SonarQube is sto
pped
jvm 1    |
jvm 1    | WrapperSimpleApp: Encountered an error running main: org.sonar.proces
s.MessageException: a JVM option can't overwrite mandatory JVM options. The foll
owing JVM options defined by property 'sonar.search.javaOpts' are invalid: -Xss2
56k overwrites -Xss1m
jvm 1    | org.sonar.process.MessageException: a JVM option can't overwrite mand
atory JVM options. The following JVM options defined by property 'sonar.search.j
avaOpts' are invalid: -Xss256k overwrites -Xss1m

When I dont give the value I get the following issue

    2017.12.07 10:04:39 INFO  app[][o.s.a.AppFileSystem] Cleaning or creating temp directory E:\Apps\sonarqube-6.7\temp
2017.12.07 10:04:39 INFO  app[][o.s.a.es.EsSettings] Elasticsearch listening on /127.0.0.1:9001
2017.12.07 10:04:39 INFO  app[][o.s.a.p.ProcessLauncherImpl] Launch process[[key='es', ipcIndex=1, logFilenamePrefix=es]] from [E:\Apps\sonarqube-6.7\elasticsearch]: E:\Apps\JRE\8u91\jre\bin\java -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly -XX:+AlwaysPreTouch -server -Xss1m -Djava.awt.headless=true -Dfile.encoding=UTF-8 -Djna.nosys=true -Djdk.io.permissionsUseCanonicalPath=true -Dio.netty.noUnsafe=true -Dio.netty.noKeySetOptimization=true -Dio.netty.recycler.maxCapacityPerThread=0 -Dlog4j.shutdownHookEnabled=false -Dlog4j2.disable.jmx=true -Dlog4j.skipJansi=true -Xms512m -Xmx512m -XX:+HeapDumpOnOutOfMemoryError -Delasticsearch -Des.path.home=E:\Apps\sonarqube-6.7\elasticsearch -cp lib/* org.elasticsearch.bootstrap.Elasticsearch -Epath.conf=E:\Apps\sonarqube-6.7\temp\conf\es
2017.12.07 10:04:39 INFO  app[][o.s.a.SchedulerImpl] Waiting for Elasticsearch to be up and running
2017.12.07 10:04:41 INFO  app[][o.e.p.PluginsService] no modules loaded
2017.12.07 10:04:41 INFO  app[][o.e.p.PluginsService] loaded plugin [org.elasticsearch.transport.Netty4Plugin]
2017.12.07 10:04:41 WARN  app[][o.s.a.p.AbstractProcessMonitor] Process exited with exit value [es]: 1

Let me know in case I am missing something

Thanks & Regards


问:
Passing multiple parameters in a hyperlink in yii2 with clean urls, Html::a() doesnt generate clean url
I am trying to generate a hyper link by the method mentioned in
http://www.yiiframework.com/doc-2.0/guide-helper-html.html#hyperlinks like this

```<code> Html::a('<b>Register</b>',
    ['story/create', array('id' =>39,'usr'=>'11')],
    ['class' => 'profile-link'])
</code>```

I want to get url like  story/create/id/39/usr/11

But it is generating as

```<code>story/create?1%5Bid%5D=39&1%5Busr%5D=1
</code>```

I have enabled the clean url functionality of yii2 like

```<code>  'urlManager' => [
        'class' => 'yii\web\UrlManager',
        // Disable index.php
        'showScriptName' => false,
        // Disable r= routes
        'enablePrettyUrl' => true,
        'rules' => array(
                '<controller:\w+>/<id:\d+>' => '<controller>/view',
                '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
                '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
        ),
        ], also.
</code>```

How this can be achieved?

答:
Another useful method :

Write in urlManager rules in your

```<code>'rules'=>array('/controller/action/<limit>/<offset>'=>'/controller/action/'),
</code>```

Can be accessed in url controller/action/100/20

Body:
I am trying to generate a hyper link by the method mentioned in
http://www.yiiframework.com/doc-2.0/guide-helper-html.html#hyperlinks like this

 Html::a('Register',
    ['story/create', array('id' =>39,'usr'=>'11')],
    ['class' => 'profile-link'])

I want to get url like  story/create/id/39/usr/11

But it is generating as

story/create?1%5Bid%5D=39&1%5Busr%5D=1

I have enabled the clean url functionality of yii2 like

  'urlManager' => [
        'class' => 'yii\web\UrlManager',
        // Disable index.php
        'showScriptName' => false,
        // Disable r= routes
        'enablePrettyUrl' => true,
        'rules' => array(
                '<controller:\w+>/<id:\d+>' => '<controller>/view',
                '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
                '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
        ),
        ], also.

How this can be achieved?

Body:
Another useful method :

Write in urlManager rules in your

'rules'=>array('/controller/action/<limit>/<offset>'=>'/controller/action/'),

Can be accessed in url controller/action/100/20


问:
Get the 1st and next value inside an array
Lets say I have an array like this

var data = [1,2,3,4,5,6,7,8,9,0];

How can I get the output like this?

```<code>console.log(1,2);
console.log(2,3);
console.log(3,4);
</code>```

and so on.. as of now this is my code

```<code>for (var i = 0; i < data.length; i++) {
 /* Dont know what to do */
}
</code>```

答:
```<code>for (var i = 0; i < data.length; i++) {
 if (i+1 < data.length) {
   console.log(data[i], data[i+1]);
 } else {
   console.log("finished")
}
</code>```

or just

```<code> for (var i = 0; i < data.length; i++) {
 if (i+1 < data.length-1) {
   console.log(data[i], data[i+1]);
 }
</code>```

you need the else block to prevent index out of bound exception

Body:
Lets say I have an array like this

var data = [1,2,3,4,5,6,7,8,9,0];

How can I get the output like this?

console.log(1,2);
console.log(2,3);
console.log(3,4);

and so on.. as of now this is my code

for (var i = 0; i < data.length; i++) {
 /* Dont know what to do */
}

Body:
for (var i = 0; i < data.length; i++) {
 if (i+1 < data.length) {
   console.log(data[i], data[i+1]);
 } else {
   console.log("finished")
}

or just

 for (var i = 0; i < data.length; i++) {
 if (i+1 < data.length-1) {
   console.log(data[i], data[i+1]);
 }

you need the else block to prevent index out of bound exception


问:
Spark SQL Dataframe API -build filter condition dynamically
I have two Spark dataframe's, df1 and df2:

+-------+-----+---+
|   name|empNo|age|
+-------+-----+---+
|shankar|12121| 28|
| ramesh| 1212| 29|
| suresh| 1111| 30|
| aarush| 0707| 15|
+-------+-----+---+
```

<pre class="lang-none prettyprint-override"><code>+------+-----+---+-----+
| eName|  eNo|age| city|
+------+-----+---+-----+
|aarush|12121| 15|malmo|
|ramesh| 1212| 29|malmo|
+------+-----+---+-----+
</code>```

I need to get the non matching records from df1, based on a number of columns which is specified in another file.

For example, the column look up file is something like below:

df1col,df2col
name,eName
empNo, eNo
```

<p><strong>Expected output is:</strong></p>

<pre class="lang-none prettyprint-override"><code>+-------+-----+---+
|   name|empNo|age|
+-------+-----+---+
|shankar|12121| 28|
| suresh| 1111| 30|
| aarush| 0707| 15|
+-------+-----+---+
</code>```

The idea is how to build a where condition dynamically for the above scenario, because the lookup file is configurable, so it might have 1 to n fields.

答:
You can use the except dataframe method. I'm assuming that the columns to use are in two lists for simplicity. It's necessary that the order of both lists are correct, the columns on the same location in the list will be compared (regardless of column name). After except, use join to get the missing columns from the first dataframe.

```<code>val df1 = Seq(("shankar","12121",28),("ramesh","1212",29),("suresh","1111",30),("aarush","0707",15))
  .toDF("name", "empNo", "age")
val df2 = Seq(("aarush", "12121", 15, "malmo"),("ramesh", "1212", 29, "malmo"))
  .toDF("eName", "eNo", "age", "city")

val df1Cols = List("name", "empNo")
val df2Cols = List("eName", "eNo")

val tempDf = df1.select(df1Cols.head, df1Cols.tail: _*)
  .except(df2.select(df2Cols.head, df2Cols.tail: _*))
val df = df1.join(broadcast(tempDf), df1Cols)
</code>```

The resulting dataframe will look as wanted:

```<code>+-------+-----+---+
|   name|empNo|age|
+-------+-----+---+
| aarush| 0707| 15|
| suresh| 1111| 30|
|shankar|12121| 28|
+-------+-----+---+
</code>```

Body:
I have two Spark dataframe's, df1 and df2:

+-------+-----+---+
|   name|empNo|age|
+-------+-----+---+
|shankar|12121| 28|
| ramesh| 1212| 29|
| suresh| 1111| 30|
| aarush| 0707| 15|
+-------+-----+---+

+------+-----+---+-----+
| eName|  eNo|age| city|
+------+-----+---+-----+
|aarush|12121| 15|malmo|
|ramesh| 1212| 29|malmo|
+------+-----+---+-----+

I need to get the non matching records from df1, based on a number of columns which is specified in another file.

For example, the column look up file is something like below:

df1col,df2col
name,eName
empNo, eNo

Expected output is:

+-------+-----+---+
|   name|empNo|age|
+-------+-----+---+
|shankar|12121| 28|
| suresh| 1111| 30|
| aarush| 0707| 15|
+-------+-----+---+

The idea is how to build a where condition dynamically for the above scenario, because the lookup file is configurable, so it might have 1 to n fields.

Body:
You can use the except dataframe method. I'm assuming that the columns to use are in two lists for simplicity. It's necessary that the order of both lists are correct, the columns on the same location in the list will be compared (regardless of column name). After except, use join to get the missing columns from the first dataframe.

val df1 = Seq(("shankar","12121",28),("ramesh","1212",29),("suresh","1111",30),("aarush","0707",15))
  .toDF("name", "empNo", "age")
val df2 = Seq(("aarush", "12121", 15, "malmo"),("ramesh", "1212", 29, "malmo"))
  .toDF("eName", "eNo", "age", "city")

val df1Cols = List("name", "empNo")
val df2Cols = List("eName", "eNo")

val tempDf = df1.select(df1Cols.head, df1Cols.tail: _*)
  .except(df2.select(df2Cols.head, df2Cols.tail: _*))
val df = df1.join(broadcast(tempDf), df1Cols)

The resulting dataframe will look as wanted:

+-------+-----+---+
|   name|empNo|age|
+-------+-----+---+
| aarush| 0707| 15|
| suresh| 1111| 30|
|shankar|12121| 28|
+-------+-----+---+


问:
Haskell: accessing lists from back
Today I started learning Haskell. I'm kind of new with functional languages, and I'm enjoying Haskell a lot.

However I've got a question about its design which is bugging me: from what I understood so far it looks like accessing an element to the back of a list is a lot more complicated that accessing the element to the front (something like xs:x where xs::[a] and x::a doesn't seem to be possible).

(From what I understood) it's possible to append a list to another one (xs++[a]), but it'll cost more at run time (it requires to traverse the whole list) and it cannot be used for pattern matching.

Why is Haskell missing such operation?

答: It is the problem with pure List data structure, not with haskell itself. You can read Purely Functional Data Structures paper to learn more about other pure data structures, that can have better performance on such operations</p>

Title: Haskell: accessing lists from back


问:
jQuery not working after an error is thrown into page with validation
I am using the below jquery with a form

```<code>    $( document ).ready(function() {
        $('.alloy-select-one-menu').change(function(){
          $(this).closest( ".packs_cont" ).find('.alloy-select-one-menu').not(this).prop("selectedIndex", 0);
         });
    });
</code>```

This is working first time but jquery not calling after  if any validation failure thrown into the page. Please help how can I resolve this issue

答:
I think that your form reloads(not whole page) after validation errors, you can't do this as normal event, because after reload form, event is not attached to input. Try to do this as delegate

```<code>$(document).ready(function() {
    $('form').on('change', '.alloy-select-one-menu', function() {
        $(this).closest( ".packs_cont" ).find('.alloy-select-one-menu').not(this).prop("selectedIndex", 0);;
    });
});
</code>```

@edit

If attaching this to form doesn't work, try to attach it to body

```<code>$('body').on('change', '.alloy-select-one-menu', function() {
……
</code>```

Body:
I am using the below jquery with a form

    $( document ).ready(function() {
        $('.alloy-select-one-menu').change(function(){
          $(this).closest( ".packs_cont" ).find('.alloy-select-one-menu').not(this).prop("selectedIndex", 0);
         });
    });

This is working first time but jquery not calling after  if any validation failure thrown into the page. Please help how can I resolve this issue

Body:
I think that your form reloads(not whole page) after validation errors, you can't do this as normal event, because after reload form, event is not attached to input. Try to do this as delegate

$(document).ready(function() {
    $('form').on('change', '.alloy-select-one-menu', function() {
        $(this).closest( ".packs_cont" ).find('.alloy-select-one-menu').not(this).prop("selectedIndex", 0);;
    });
});

@edit

If attaching this to form doesn't work, try to attach it to body

$('body').on('change', '.alloy-select-one-menu', function() {
……


问:
Invalid block tag: 'else' - 'extends' inside a if statement
I am trying to extends a template depending of the the existence of the 'custom_nav' variable:

```<code>{% if 'custom_nav' %}
    {% extends custom_nav %}
{% else %}
    {% extends "playexo/default_nav.html" %}
{% endif %}
</code>```

But I get:

```<code>Invalid block tag on line 3: 'else'. Did you forget to register or load this tag?
</code>```

It is probably a dumb error but I can not figure it out, Iam wasting my time on it for 1h now...

I have searched for similar problem and it seems like an old one:
Django Invalid block tag: 'else'

答: You can't do this. extends needs to be the first tag in a model. You should ensure that the variable always exists.

Body:
I am trying to extends a template depending of the the existence of the 'custom_nav' variable:

{% if 'custom_nav' %}
    {% extends custom_nav %}
{% else %}
    {% extends "playexo/default_nav.html" %}
{% endif %}

But I get:

Invalid block tag on line 3: 'else'. Did you forget to register or load this tag?

It is probably a dumb error but I can not figure it out, Iam wasting my time on it for 1h now...

I have searched for similar problem and it seems like an old one:
Django Invalid block tag: 'else'


问:
NodeJS Route redirection after Login Authorization
I am working on a NodeJS Application Login. Four routes that relates to this issue are

```<code>GET /admin/login -- Used to get the Login Page (1)
POST /admin/login -- Used to go to Controller (2)
POST /api/auth/login requireLogin -- Actual login happens here (3)
GET /admin/dashboard requireAuth-- Route to go after successful login (4)
</code>```

Route Definition:

```<code>(1) adminRoutes.get('/admin/login', HomeController.getLoginPage);
(2) adminRoutes.post('/admin/login', AdminController.postLoginPage);
(3) authRoutes.post('/api/auth/login', requireLogin, AuthenticationController.login);
(4) adminRoutes.get('/admin/dashboard', requireAuth, HomeController.index);
</code>```

Values for requireLogin and requireAuth

```<code>var requireAuth = passport.authenticate('jwt', {session: false, failureRedirect: '/admin/login'}),
    requireLogin = passport.authenticate('local', {session: false});
</code>```

From (1) I fill up login details and hit submit, form action takes it to (2). For (2), I have a method written like this;

Method for (2)

```<code> exports.postLoginPage = function(req, res, next){
   request.post({url: 'http://localhost:3006/api/auth/login', form: req.body}, function(err, response, body){
     console.log('outside if');
     if(response.statusCode == '200'){
       console.log('inside if 200');
       var wegot = JSON.parse(response.body);
        console.log(wegot.token);
        res.header('Authorization', wegot.token);
       res.redirect('/admin/dashboard');
     }else{
       console.log('if else err');
       req.flash('error', body);
      // return res.redirect('/admin/login');
      return 'Unauthorized';
     }
   })
 }
</code>```

Method for (3)

```<code>function generateToken(user){
    return jwt.sign(user, authConfig.secret, {
        expiresIn: 10080
    });
}

function setUserInfo(request){
    return {
        _id: request._id,
        email: request.email,
        role: request.role
    };
}

exports.login = function(req, res, next){
    var userInfo = setUserInfo(req.body);
    res.status(200).json({
        token: 'JWT ' + generateToken(userInfo),
        user: userInfo
    });
}
</code>```

After successful login from API (3), I need to be redirected to (4). But I am going back to (1). I know login is successful and I am also getting JWT Token on log.

Log:

```<code>POST /api/auth/login 200 32.445 ms - 330
outside if
inside if 200
JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1YTI5MDQ3MGU4Nzc3YTM1OTQ2Mjk5YWEiLCJlbWFpbCI6InNwb25zb3JAZ21haWwuY29tIiwicm9sZSI6Im5pZ2h0IiwiaWF0IjoxNTEyNjQzODM0LCJleHAiOjE1MTI2NTM5MTR9.J5LqkfeSrRU4ukY9rIsFNUBArTLloynRsle4mkwTgpA
POST /admin/login 302 57.531 ms - 76
GET /admin/dashboard 302 2.690 ms - 68
GET /admin/login 200 1.581 ms - -
</code>```

What might be the issue here? How can I solve this. Let me know if you need more info on this.

答:
POST /admin/login 302 57.531 ms - 76
  GET /admin/dashboard 302 2.690 ms - 68
  GET /admin/login 200 1.581 ms - -

Your response status code is 302, which means you have been redirected. Obviously /admin/dashboard doesn't accept your authorization token.

Body:
I am working on a NodeJS Application Login. Four routes that relates to this issue are

GET /admin/login -- Used to get the Login Page (1)
POST /admin/login -- Used to go to Controller (2)
POST /api/auth/login requireLogin -- Actual login happens here (3)
GET /admin/dashboard requireAuth-- Route to go after successful login (4)

Route Definition:

(1) adminRoutes.get('/admin/login', HomeController.getLoginPage);
(2) adminRoutes.post('/admin/login', AdminController.postLoginPage);
(3) authRoutes.post('/api/auth/login', requireLogin, AuthenticationController.login);
(4) adminRoutes.get('/admin/dashboard', requireAuth, HomeController.index);

Values for requireLogin and requireAuth

var requireAuth = passport.authenticate('jwt', {session: false, failureRedirect: '/admin/login'}),
    requireLogin = passport.authenticate('local', {session: false});

From (1) I fill up login details and hit submit, form action takes it to (2). For (2), I have a method written like this;

Method for (2)

 exports.postLoginPage = function(req, res, next){
   request.post({url: 'http://localhost:3006/api/auth/login', form: req.body}, function(err, response, body){
     console.log('outside if');
     if(response.statusCode == '200'){
       console.log('inside if 200');
       var wegot = JSON.parse(response.body);
        console.log(wegot.token);
        res.header('Authorization', wegot.token);
       res.redirect('/admin/dashboard');
     }else{
       console.log('if else err');
       req.flash('error', body);
      // return res.redirect('/admin/login');
      return 'Unauthorized';
     }
   })
 }

Method for (3)

function generateToken(user){
    return jwt.sign(user, authConfig.secret, {
        expiresIn: 10080
    });
}

function setUserInfo(request){
    return {
        _id: request._id,
        email: request.email,
        role: request.role
    };
}

exports.login = function(req, res, next){
    var userInfo = setUserInfo(req.body);
    res.status(200).json({
        token: 'JWT ' + generateToken(userInfo),
        user: userInfo
    });
}

After successful login from API (3), I need to be redirected to (4). But I am going back to (1). I know login is successful and I am also getting JWT Token on log.

Log:

POST /api/auth/login 200 32.445 ms - 330
outside if
inside if 200
JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1YTI5MDQ3MGU4Nzc3YTM1OTQ2Mjk5YWEiLCJlbWFpbCI6InNwb25zb3JAZ21haWwuY29tIiwicm9sZSI6Im5pZ2h0IiwiaWF0IjoxNTEyNjQzODM0LCJleHAiOjE1MTI2NTM5MTR9.J5LqkfeSrRU4ukY9rIsFNUBArTLloynRsle4mkwTgpA
POST /admin/login 302 57.531 ms - 76
GET /admin/dashboard 302 2.690 ms - 68
GET /admin/login 200 1.581 ms - -

What might be the issue here? How can I solve this. Let me know if you need more info on this.


答:
You could use reduce with returning the last element as new element.

var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

data.reduce((a, b) => (console.log(a, b), b));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Get the 1st and next value inside an array

Body:
You could use reduce with returning the last element as new element.

var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

data.reduce((a, b) => (console.log(a, b), b));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Get element at index of a Array[(Array[String, Long)]
So I have some data:

```<code>val data = Array[(Array[String], Long)]
</code>```

Which is an array of pairs, where each pair consists of another array and a number. I have created a ListBuffer as follows:

```<code>var x = ListBuffer[(Array[String], Long)]
</code>```

I would like to append an element at some index i to x. I do the following:

```<code> x += data(i)
</code>```

However, I get the error:

Type mismatch, expected: String, actual: (Array[String], Long)

What am I doing wrong? I am working in IntelliJ and Scala 2.10.7.

Also this example (which is a concrete example (I cannot provide the original example)) also gives the same error:

```<code>val xData = ListBuffer[(Array[String], Long)]
    var x = ListBuffer[(Array[String], Long)]
    x += xData(0)
</code>```

答:
I have tried the same thing in scala REPL just now, and it is working fine.

What I did is -

```<code>    scala> val arr = Array("Hello", "Bye")
    arr: Array[String] = Array(Hello, Bye)

    scala> var data = Array((arr,1), (arr,2))
    data: Array[(Array[String], Int)] = Array((Array(Hello, Bye),1),
    (Array(Hello, Bye),2))

    scala> import scala.collection.mutable.ListBuffer
    import scala.collection.mutable.ListBuffer

    scala> val list = ListBuffer((arr, 1))
    list: scala.collection.mutable.ListBuffer[(Array[String], Int)] =
    ListBuffer((Array(Hello, Bye),1))

    scala> list += data(0)
    res1: list.type = ListBuffer((Array(Hello, Bye),1), (Array(Hello,
    Bye),1))
</code>```

It did not give any error

Body:
So I have some data:

val data = Array[(Array[String], Long)]

Which is an array of pairs, where each pair consists of another array and a number. I have created a ListBuffer as follows:

var x = ListBuffer[(Array[String], Long)]

I would like to append an element at some index i to x. I do the following:

 x += data(i)

However, I get the error:

Type mismatch, expected: String, actual: (Array[String], Long)

What am I doing wrong? I am working in IntelliJ and Scala 2.10.7.

Also this example (which is a concrete example (I cannot provide the original example)) also gives the same error:

val xData = ListBuffer[(Array[String], Long)]
    var x = ListBuffer[(Array[String], Long)]
    x += xData(0)

Body:
I have tried the same thing in scala REPL just now, and it is working fine.

What I did is -

    scala> val arr = Array("Hello", "Bye")
    arr: Array[String] = Array(Hello, Bye)

    scala> var data = Array((arr,1), (arr,2))
    data: Array[(Array[String], Int)] = Array((Array(Hello, Bye),1),
    (Array(Hello, Bye),2))

    scala> import scala.collection.mutable.ListBuffer
    import scala.collection.mutable.ListBuffer

    scala> val list = ListBuffer((arr, 1))
    list: scala.collection.mutable.ListBuffer[(Array[String], Int)] =
    ListBuffer((Array(Hello, Bye),1))

    scala> list += data(0)
    res1: list.type = ListBuffer((Array(Hello, Bye),1), (Array(Hello,
    Bye),1))

It did not give any error


问:
CMake and Make need to be run twice in order to build code successfully
I am using CMake 3.8.2, GNU make 4.2.1 and GCC 6.4.0 for my C++14 project and I noticed a strange behavior when building. I am using CMake for an out-of-source build in a sub-folder called "build" where I run cmake .. followed by make.

CMake runs fine without any errors and make will build all source files like I expect until it is done compiling and starts linking them. It will then fail with an error

```<code>[ 83%] ...
[100%] Linking CXX executable myproject
/usr/bin/ld: some-source-file.cc.o: undefined reference to symbol '_ZNKSt7__cxx1118basic_stringstreamIcSt11char_traitsIcESaIcEE3strEv@@GLIBCXX_3.4.21'
</code>```

Interestingly it doesn't show any compiler warnings up to this point and only shows the above mentioned linker error.

Now when I ignore the error and simply run cmake .. and then make again (just like I did before) I get all the compiler warnings that my code should produce and everything links perfectly fine, even though I didn't change any code or CMake-related files in the meantime.

I can reproduce this behavior by deleting all files in the build dir by running rm -r *.

Here is my CMakeLists.txt file:

```<code># Define minimum required CMake version
cmake_minimum_required(VERSION 3.8.2)

# Setting compiler related settings
set(CMAKE_CXX_COMPILER "${CMAKE_SOURCE_DIR}/toolchain/binary/gcc-6.4.0/bin/gcc")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wconversion -O2 -lstdc++")
set(CMAKE_CXX_STANDARD 14)

# Define project name
project(MyProject)

# Find source files
file(GLOB_RECURSE SOURCES application/*.cc)

# Adding third-party sources
set(SOURCES ${SOURCES} "third-party/cpp-base64/base64.cpp")

# Executable to be built from which source files
add_executable(myproject ${SOURCES})

# Find and include and link Botan
find_library(BOTAN botan-2 "third-party/botan/build/lib")
include_directories("third-party/botan/build/include/botan-2")

# Includes that are part of the project
include_directories("${CMAKE_SOURCE_DIR}/application/include")

# Include nlohmann/json
include_directories("third-party/json/src")

# Include cpp-base64 by René Nyffenegger
include_directories("third-party/cpp-base64")

find_package(Boost REQUIRED COMPONENTS program_options)
if(Boost_FOUND)
  include_directories(${Boost_INCLUDE_DIRS})
endif()

# Link third-party libraries
target_link_libraries(myproject ${Boost_LIBRARIES} ${BOTAN})
</code>```

Note: I am required to check-in the compiler and libraries I am using, which is why I specified them in the CMake file.

答:
If it only works the second time it has to do with cached variables.

So I'm pretty sure that it will work the first time if you modify CMAKE_CXX_COMPILER setting by adding set(... CACHE INTERNAL "") to:

```<code>set(CMAKE_CXX_COMPILER "${CMAKE_SOURCE_DIR}/toolchain/binary/gcc-6.4.0/bin/gcc" CACHE INTERNAL "")
</code>```

And move set(CMAKE_CXX_FLAGS ...) after the project() command.

But please also be noted that you shouldn't put the compiler into your CMakeLists.txt.

References

CMake: In which Order are Files parsed (Cache, Toolchain, …)?

Passing compiler options cmake

CMake Error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

Body:
I am using CMake 3.8.2, GNU make 4.2.1 and GCC 6.4.0 for my C++14 project and I noticed a strange behavior when building. I am using CMake for an out-of-source build in a sub-folder called "build" where I run cmake .. followed by make.

CMake runs fine without any errors and make will build all source files like I expect until it is done compiling and starts linking them. It will then fail with an error

[ 83%] ...
[100%] Linking CXX executable myproject
/usr/bin/ld: some-source-file.cc.o: undefined reference to symbol '_ZNKSt7__cxx1118basic_stringstreamIcSt11char_traitsIcESaIcEE3strEv@@GLIBCXX_3.4.21'

Interestingly it doesn't show any compiler warnings up to this point and only shows the above mentioned linker error.

Now when I ignore the error and simply run cmake .. and then make again (just like I did before) I get all the compiler warnings that my code should produce and everything links perfectly fine, even though I didn't change any code or CMake-related files in the meantime.

I can reproduce this behavior by deleting all files in the build dir by running rm -r *.

Here is my CMakeLists.txt file:

# Define minimum required CMake version
cmake_minimum_required(VERSION 3.8.2)

# Setting compiler related settings
set(CMAKE_CXX_COMPILER "${CMAKE_SOURCE_DIR}/toolchain/binary/gcc-6.4.0/bin/gcc")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wconversion -O2 -lstdc++")
set(CMAKE_CXX_STANDARD 14)

# Define project name
project(MyProject)

# Find source files
file(GLOB_RECURSE SOURCES application/*.cc)

# Adding third-party sources
set(SOURCES ${SOURCES} "third-party/cpp-base64/base64.cpp")

# Executable to be built from which source files
add_executable(myproject ${SOURCES})

# Find and include and link Botan
find_library(BOTAN botan-2 "third-party/botan/build/lib")
include_directories("third-party/botan/build/include/botan-2")

# Includes that are part of the project
include_directories("${CMAKE_SOURCE_DIR}/application/include")

# Include nlohmann/json
include_directories("third-party/json/src")

# Include cpp-base64 by René Nyffenegger
include_directories("third-party/cpp-base64")

find_package(Boost REQUIRED COMPONENTS program_options)
if(Boost_FOUND)
  include_directories(${Boost_INCLUDE_DIRS})
endif()

# Link third-party libraries
target_link_libraries(myproject ${Boost_LIBRARIES} ${BOTAN})

Note: I am required to check-in the compiler and libraries I am using, which is why I specified them in the CMake file.

Body:
If it only works the second time it has to do with cached variables.

So I'm pretty sure that it will work the first time if you modify CMAKE_CXX_COMPILER setting by adding set(... CACHE INTERNAL "") to:

set(CMAKE_CXX_COMPILER "${CMAKE_SOURCE_DIR}/toolchain/binary/gcc-6.4.0/bin/gcc" CACHE INTERNAL "")

And move set(CMAKE_CXX_FLAGS ...) after the project() command.

But please also be noted that you shouldn't put the compiler into your CMakeLists.txt.

References

CMake: In which Order are Files parsed (Cache, Toolchain, …)?

Passing compiler options cmake

CMake Error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found


问:
Why do MVCs tend to convert objects into arrays when passing them off to a view?
Why do MVCs tend to convert objects into arrays when passing them off to a view?

Just curious if there is a reason for this.

答: Probably because you should not be able to alter the object from within the view. I guess it just has to do with code purity and helping the user follow the MVC pattern.</p>