Q: Error 'class HotelRoom' has no member named 'menu' even though it is there I am attempting to build a hotel reservation program in C++. however, I have an issue. I keep getting the above error message and I can't seem to find a fix.
Please provide some assistance. Anything would be greatly appreciated. Below is what I have written thus far.
using namespace std;
class HotelRoom{
    private:
        int roomnum; //Room numbers
        int roomcap; //Room capacity
        int roomoccuoystst = 0;
        int maxperperroom;
        double dailyrate;
    public:
        HotelRoom()
        {
           roomcap = 0;
           maxperperroom = 2;
           dailyrate = 175;
        }

            int gettotal  = 0;
            int gettotallist  = 0;
            string room;
            string guestroom,message;

    void viewrooms()
    {
        char viewselect, back;
        cout<<"Which room list would you like to view ?. 1 - Add rooms, 2 - Reserved rooms : " ;
        cin>>viewselect;
        switch(viewselect)
        {
        case '1':
            viewaddromm();
            break;
        case '2':
            viewresromm();
            break;
        default:
            cout<<"Please select from the option provided or go back to the main menu. 1 - view rooms, 2 - to the mail menu or any other key to exit the program : ";
            cin>>back;
            switch(back)
            {
                case '1':
                    viewrooms();
                    break;
                case '2':
                    hotelmenu();
                    break;
                default:
                    exitpro();

            }
        }
    }

    void viewresromm()
    {
                int occup,rmchoose,up;
                string roomtochange, items;
                string guestroomdb;
                int newaccupancy;
                char decisionmade,savinf;
                string fname, lname, nationality;
                string checkaddroom;
                ifstream getdatafromaddroom; //creation of the ifstream object
                getdatafromaddroom.open("reserveroom.out");

                  if(getdatafromaddroom.fail()) //if statement used for error checking
                    {
                        cout<<"Could not open file"<<endl; //message that will be printed if the program cannot open the file
                    }

                                cout<<endl;
                                cout<<"First Name"<<'-'<<"Last Name"<<'-'<<"Nationality"<<'-'<<"Guest(s)"<<'-'<<"Room #"<<endl;
                                cout<<"-------------------------------------------------------"<<endl;
                                string items;
                     while(!getdatafromaddroom.eof())
                            {

                           //     getdatafromaddroom >>fname>>lname>>nationality>>occup>>guestroomdb;
                           getline(getdatafromaddroom, items);
                               //cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<' '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<' '<<setw(9)<<guestroomdb<<endl;
                               gettotallist++;

                                      if( getdatafromaddroom.eof() ) break;
                                      cout<<items<<endl;
                            }

                                 for(int getlist = 0; getlist < gettotallist; getlist++ )
                                    {
                                        cout<<items<<endl;
                                       // cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<' '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<' '<<setw(9)<<guestroomdb<<endl;
                                    }
    }

    void viewaddromm()
    {
                int occup,rmchoose,up;
                string roomtochange;
                string guestroomdb;
                int newaccupancy;
                char decisionmade,savinf;
                string fname, lname, nationality;
                string checkaddroom;
                fstream getdatafromaddroom; //creation of the ifstream object
                getdatafromaddroom.open("addroom.out");

                 if(getdatafromaddroom.fail()) //if statement used for error checking
                    {
                        cout<<"Could not open file"<<endl; //message that will be printed if the program cannot open the file
                    }

                                cout<<endl;
                                cout<<"First Name"<<'-'<<"Last Name"<<'-'<<"Nationality"<<'-'<<"Guest(s)"<<'-'<<"Room #"<<endl;
                                cout<<"-------------------------------------------------------"<<endl;
                                string items;
                     while(!getdatafromaddroom.eof())
                            {

                           //     getdatafromaddroom >>fname>>lname>>nationality>>occup>>guestroomdb;
                           getline(getdatafromaddroom, items);
                               //cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<' '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<' '<<setw(9)<<guestroomdb<<endl;
                               gettotallist++;

                                      if( getdatafromaddroom.eof() ) break;
                                      cout<<items<<endl;
                            }

                                 for(int getlist = 0; getlist < gettotallist; getlist++ )
                                    {
                                        cout<<items<<endl;
                                       // cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<' '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<' '<<setw(9)<<guestroomdb<<endl;
                                    }

    }

    void exitpro()
    {
        cout<<"Program closing......Goodbye"<<endl;
        system("Pause");
        exit(0);
    }

    menu()
    {
        char menuchoice;
         cout<<"[-------------------------------------------------------]"<<endl;
        cout<<"[-Welcome to the hotel booking and reseration menu-]"<<endl;
        cout<<"[--------------------------------------------------------]"<<endl;

        cout<<setw(30)<<"Addroom -- 1"<<endl;
        cout<<setw(32)<<"Reserve a room -- 2"<<endl;
        cout<<setw(34)<<" Modify a room -- 3"<<endl;
        cout<<setw(36)<<"View roms -- 4"<<endl;
        cout<<setw(38)<<" Exist -- 5"<<endl;
        cin>>menuchoice;
        switch(menuchoice)
        {
        case '1':
            Addroom();
            break;
        case '2':
            reserveroom();
            break;
        case '3':
            modifyroom();
            break;
        case '4':
            viewrooms();
            break;
        }
    }
};

#endif

A: #include<string>
#include<iostream>
#include<fstream>
#include<iomanip>

using namespace std;
class HotelRoom
{
  private:
    int roomnum;                // Room numbers
    int roomcap;                // Room capacity
    int roomoccuoystst = 0;
    int maxperperroom;
    double dailyrate;
  public:

      HotelRoom()
    {
        roomcap = 0;
        maxperperroom = 2;
        dailyrate = 175;
    }

    int gettotal = 0;
    int gettotallist = 0;
    string room;
    string guestroom, message;

    void viewrooms()
    {
        char viewselect, back;
        cout << "Which room list would you like to view ?. 1 - Add rooms, 2 - Reserved rooms : ";
        cin >> viewselect;
        switch (viewselect)
        {
        case '1':
            viewaddromm();
            break;
        case '2':
            viewresromm();
            break;
        default:
            cout <<
                "Please select from the option provided or go back to the main menu. 1 - view rooms, 2 - to the mail menu or any other key to exit the program : ";
            cin >> back;
            switch (back)
            {
            case '1':
                viewrooms();
                break;
            case '2':
                 menu();
                break;
            default:
                exitpro();

            }
        }
    }

    void viewresromm()
    {

        string roomtochange, items;
        string guestroomdb;
        // int newaccupancy;
        // char decisionmade,savinf;
        string fname, lname, nationality;
        string checkaddroom;
        ifstream getdatafromaddroom;    // creation of the ifstream object
        getdatafromaddroom.open("reserveroom.out");

        if (getdatafromaddroom.fail())  // if statement used for error
                                        // checking
        {
            cout << "Could not open file" << endl;  // message that will be
                                                    // printed if the program
                                                    // cannot open the file
                                                    return;
        }

        cout << endl;
        cout << "First Name" << '-' << "Last Name" << '-' << "Nationality" << '-' << "Guest(s)" <<
            '-' << "Room #" << endl;
        cout << "-------------------------------------------------------" << endl;
        // string items;
        while (!getdatafromaddroom.eof())
        {

            // getdatafromaddroom
            // >>fname>>lname>>nationality>>occup>>guestroomdb;
            getline(getdatafromaddroom, items);
            // cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<'
            // '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<'
            // '<<setw(9)<<guestroomdb<<endl;
            gettotallist++;

            if (getdatafromaddroom.eof())
                break;
            cout << items << endl;
        }

        for (int getlist = 0; getlist < gettotallist; getlist++)
        {
            cout << items << endl;
            // cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<'
            // '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<'
            // '<<setw(9)<<guestroomdb<<endl;
        }
    }

    void viewaddromm()
    {
        // int occup,rmchoose,up;
        string roomtochange;
        string guestroomdb;
        // int newaccupancy;
        // char decisionmade,savinf;
        string fname, lname, nationality;
        string checkaddroom;
        fstream getdatafromaddroom; // creation of the ifstream object
        getdatafromaddroom.open("addroom.out");

        if (getdatafromaddroom.fail())  // if statement used for error
                                        // checking
        {
            cout << "Could not open file" << endl;  // message that will be
                                                    // printed if the program
                                                    // cannot open the file
                                                    return;
        }

        cout << endl;
        cout << "First Name" << '-' << "Last Name" << '-' << "Nationality" << '-' << "Guest(s)" <<
            '-' << "Room #" << endl;
        cout << "-------------------------------------------------------" << endl;
        string items;
        while (!getdatafromaddroom.eof())
        {

            // getdatafromaddroom
            // >>fname>>lname>>nationality>>occup>>guestroomdb;
            getline(getdatafromaddroom, items);
            // cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<'
            // '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<'
            // '<<setw(9)<<guestroomdb<<endl;
            gettotallist++;

            if (getdatafromaddroom.eof())
                break;
            cout << items << endl;
        }

        for (int getlist = 0; getlist < gettotallist; getlist++)
        {
            cout << items << endl;
            // cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<'
            // '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<'
            // '<<setw(9)<<guestroomdb<<endl;
        }

    }

    void exitpro()
    {
        cout << "Program closing......Goodbye" << endl;
    //  system("Pause");
        exit(0);
    }

    void Addroom()
    {
        std::string mess = __func__;
        mess += " is not yet implimented.";
        throw new std::logic_error(mess.c_str());
    }

    void reserveroom()
    {
        std::string mess = __func__;
        mess += " is not yet implimented.";
        throw new std::logic_error(mess.c_str());
    }

    void modifyroom()
    {
        std::string mess = __func__;
        mess += " is not yet implimented.";
        throw new std::logic_error(mess.c_str());
    }

    void menu()
    {
        while (true)
        {
            char menuchoice;
            cout << "[-------------------------------------------------------]" << endl;
            cout << "[-Welcome to the hotel booking and reseration menu-]" << endl;
            cout << "[--------------------------------------------------------]" << endl;

            cout << setw(30) << "Addroom -- 1" << endl;
            cout << setw(30) << "Reserve a room -- 2" << endl;
            cout << setw(30) << "Modify a room -- 3" << endl;
            cout << setw(30) << "View rooms -- 4" << endl;
            cout << setw(30) << "Exit -- 5" << endl;
            cin >> menuchoice;
            switch (menuchoice)
            {
            case '1':
                Addroom();
                break;
            case '2':
                reserveroom();
                break;
            case '3':
                modifyroom();
                break;
            case '4':
                viewrooms();
                break;
            case '5':
                exitpro();
            }
        }
    }
};

int main()
{
    try
    {
        HotelRoom room;
        room.menu();
    }
    catch(std::logic_error * ex)
    {
        std::cout << ex->what();
    }

}

you have a lot more to go with this project. I've fixed the portion you specifically asked about and its now a runninng application with somewhat approperate diagnostics. I'm not going to get too deep into how this language works but you have several functions that were not implimented, missing return types, and just general logic errors like trying to use a file after you determined it wasnt open. it runs now, and you can get a clear indication of what you need to complete. You also had several unused varables.
i added , at minimal,
void Addroom()
    {
        std::string mess = __func__;
        mess += " is not yet implimented.";
        throw new std::logic_error(mess.c_str());
    }

    void reserveroom()
    {
        std::string mess = __func__;
        mess += " is not yet implimented.";
        throw new std::logic_error(mess.c_str());
    }

    void modifyroom()
    {
        std::string mess = __func__;
        mess += " is not yet implimented.";
        throw new std::logic_error(mess.c_str());

    }

and a return type to menu.
`void menu()
you cannot call functions you have not yet written, and all functions have a return type even if they return nothing.
Good luck!


Q: How to use a Variable in Jmeter Regex Extractor I am new to jMeter. I am recording a script for creating a shift. For every transaction New shift ID is generated. I have tried to extract it by using regx Exp extractor but not getting anything. Pls see below information.
*Reference Name: strgenShiftId
Regular Expression: end="${strWeekEndDate}" gs="(.+?)"
Template: $1$
Match No.
Default Value:
Where ${strWeekEndDate} is a variable which extracts the date from some other previous response.
My Response code is as following-
week start="07/27/2015" end="08/02/2015" gs="61530" unitSkey="811" fy="2015" fw="30" ac="Y">
I want to extract the gs="61531".
The full response is:
<data>
<weeks selWkIndex="5">
<week start="06/29/2015" end="07/05/2015" gs="71526" unitSkey="811" fy="2015" fw="26" ac="N">
</week>
<week start="07/06/2015" end="07/12/2015" gs="71527" unitSkey="811" fy="2015" fw="27" ac="N">
</week>
<week start="07/13/2015" end="07/19/2015" gs="71528" unitSkey="811" fy="2015" fw="28" ac="N">
</weeks>
</data>

A: You can extract gs value using following regular expression: gs=\"([^"]+)\". Always remember to escape " with \ in regular epressions, unless you want " to be evaluated as part of regular expression.


Q: MySQL - How to combine the column data into one row I am making an employee attendance record and I have trouble merging the
raw data into time in and time out combination format.
From the given "Raw Data" Table below
I need to combine the time in and time out of the employee into one row
like the "Merge Time in/out" sample below.
Also consider that the employee has two shifting schedule the day shift and night shift.
Take note that if the employee is in night shift schedule
the time out date is different to time in date.
Day shift empid(ID001,ID002)
Night shift empid(ID003)
Raw Data Table
--------------------------------------------
empid      date      time[in/out] in_out
--------------------------------------------
ID001     2014-08-01   7:00am       IN
ID002     2014-08-01   7:01am       IN
ID003     2014-08-01   8:05pm       IN   <--Night Shift

ID001     2014-08-01   5:00pm       OUT
ID002     2014-08-01   5:01pm       OUT
ID003     2014-08-02   6:01am       OUT  <--take note of date

Merge Time in/out Table
--------------------------------------------
empid      date       time_in       time_out
--------------------------------------------
ID001     2014-08-01   7:00am       5:00pm
ID002     2014-08-01   7:01am       5:01pm
ID003     2014-08-01   8:05pm       6:01am

A: select r1.empid,
       r1.date,
       r1.time as time_in,
       r2.time as time_out
from raw_Data r1
inner join raw_data r2   on r1.empid = r2.empid
where r1.in_out = 'IN'
  and r2.in_out = 'OUT';

A: Ok, so you can tell if the employee worked the night shift when his time_out was AM. In this case, it's the last row's case.

What I did was determinate a real date field. It is the day before when you're out from the night shift, and the current date in any other case
select empid,
       IF(RIGHT(timeinout,2)='am' AND in_out='OUT',
          DATE_ADD(date, INTERVAL -1 DAY),
          date) as realdate,
       MAX(if(in_out='IN',timeinout,null)) as time_in,
       MAX(if(in_out='OUT',timeinout,null)) as time_out
from shifts
group by empid, realdate

Outputs

depending on the table size it might be worth using this way just for saving yourself a join. In almost any other case, a join is cleaner.
I guess you have no control over the format of the input, so you'll have to stick to times as text and make a comparison for the am/pm suffix in the last 2 characters. I find that rather  error prone, but let's pray the raw data will stick to that format.
This solution makes a few assumptions that I rather explain here to avoid further misunderstandings

*

*The workers can't work the night shift if they worked the day shift (since we're grouping by date, you would need an extra field to distinguish day shift and night shift for a given day)

*Input will never list an OUT time earlier than a IN time for a given day/employee tuple (if it happens, this would need an extra verification step to guarantee consistent output)

*Input will always include timein and timeout for a given shift (if it didn't, you would need an extra step to discard orfan timeentries).

A: Try this query and tell me if it works
SELECT empid,
       date,
       MAX(CASE WHEN in_out = 'IN' THEN time ELSE '' END) time_in,
       MAX(CASE WHEN in_out = 'OUT' THEN time ELSE '' END) time_out
FROM  Raw Data
GROUP BY empid, date


Q: Having a developer-specific configuration for Apache Ivy I'm using Apache Ivy to manage dependencies in the project with several developers. They will share most of the Ivy configuration, but some pieces (like corporate proxy username and password) should be developer-specific. I've created a reference file for everyone to place in the ~/.ivy2/ivysettings.xml (this is where developer could specify his password), but cannot include it from the ivy:configure on Windows machines (Ivy does not expand environment variables there, and pointing to every developer's ~ is problematic).
Any suggestions on how could I allow developer-wide configuration in this setup?

A: The java property user.home performs the same role as the ~ from *NIX systems.
(Note: On windows, the USERPROFILE environment variable fills this role)
Ivy can work with java system properties, just use the ${user.home} notation as you would in Ant.
References:

*

*http://www.mindspring.com/~mgrand/java-system-properties.htm

*http://www.wilsonmar.com/1envvars.htm#WinVars

*http://ant.apache.org/ivy/history/2.0.0-rc1/settings.html


Q: How to find the string from string array in firestore I have a list of documents and each document has a field of a string array named "fav", it has more than 50k emails, there are almost 1000 documents and in each document's "fav" array has variable length including 50k, 20k,10, etc. I was fetching all documents
 Firestore.instance.collection("save").snapshots();

through StreamBuilder
StreamBuilder(
      stream: Firestore.instance.collection("save").snapshots();,
      builder: (context, snapshot) {
        if (!snapshot.hasData)
          return Text("Loading Data.............");
        else {
          listdata = snapshot.data.documents;

          return _buildBody(snapshot.data.documents);
        }
      },
    )

Now How I can search my required email from each document's field "fav"? I have to perform an operation after finding the required id in the array locally.

A: The question is not very clear, but for my understanding, this is what you are looking for
Firestore.instance.collection('save')
.where('fav', arrayContains: 'abc@gmail.com').snapshots()

A: The question is not very clear, but for my understanding, you want to find one e-mail in the array field. This array is contained on each document, and all the documents are "streamed" in a collection of snapshots.
Contains Method: https://api.dartlang.org/stable/2.0.0/dart-core/Iterable/contains.html
bool contains (
Object element
)

Returns true if the collection contains an element equal to element.
This operation will check each element in order for being equal to element, unless it has a more efficient way to find an element equal to element.
The equality used to determine whether element is equal to an element of the iterable defaults to the Object.== of the element.
Some types of iterable may have a different equality used for its elements. For example, a Set may have a custom equality (see Set.identity) that its contains uses. Likewise the Iterable returned by a Map.keys call should use the same equality that the Map uses for keys.
Implementation
bool contains(Object element) {
  for (E e in this) {
    if (e == element) return true;
  }
  return false;
}


Q: Rails using Websockets with Nginx and Unicorn? I am considering implementing chess (which needs websockets) with Rails, and in production deployment using Nginx as a reverse proxy to a bunch of Unicorn processes.
In thinking about how to make that work led me to have the following questions:
As far as I understand websockets are a persistent connection. Since everything goes through the reverse proxy Nginx how exactly would a Unicorn worker process maintain a websocket connection to a client browser? Would Nginx maintain state about which Unicorn process each browser websocket is connected to and act as a kind of intermediary? Does keeping a persistent websocket connection in a Unicorn process block the entire worker process?
Is there a recommended way to implementing chess (with websockets) using Rails?

A: Connecting synchronous processing by Unicorn with asynchronous delivery using nginx would imply some logic on nginx side that seems at least awkward to me. At most - impossible.
There is a Railscast about Private Pub gem that makes use of Thin webserver. It's way more suitable for this task: it's asynchronous, it's able to handle many concurrent requests with event-based IO. So I suggest you replace Unicorn with Thin or install Thin side-by-side.
Puma webserver might also be an option, however, I can't give more info about that.

A: nginx won't do websockets. Are you sure you can't do this with AJAX? If you really need push capability you could try something built around the Comet approach: http://en.wikipedia.org/wiki/Comet_(programming)
Faye is a pretty good gem for implementing comet in rails:
http://faye.jcoglan.com/


Q: HTML & case sensitive HTML in general is case insensitive. However I`ve noticed some escape names are case sensitive. For example , Á and á.
Is & case sensitive regarding HTML standard?

A: Yes, reserved entities in HTML are case sensitive.
Browsers will be nice to you and accept whatever you give them, but you should be using the proper casing.
See also:  https://www.w3.org/TR/html52/syntax.html#named-character-references

A: From the below resource:
https://www.tutorialrepublic.com/html-tutorial/html-entities.php

Note: HTML entities names are case-sensitive! Please check out the
HTML character entities reference for a complete list of character
entities of special characters and symbols

And From https://www.youth4work.com/Talent/html/Forum/117977-is-html-case-sensitive

Generally, HTML is case-insensitive, but there are a few exceptions.
Entity names (the things that follow ampersands) are case-senstive,
but many browsers will accept many of them entirely in uppercase or
entirely in lowercase; a few must be cased in particular ways. For
example, Ç is Ç and ç is ç. Other combinations of upper
and lower case are no good.


Q: Finding the indexPath of a cell with a gesture recogniser in handler method I have a pan gesture recogniser on a UITableViewCell which is attached to a method called didPan(sender: UIPanGestureRecognizer).
How can I use this method to determine which cell in a tableView this was activated from?

A: A good way to do this is to add the gesture recognizer in the UITableViewCell subclass and also have a delegate property in that class as well. So in your subclass:
protocol MyCustomCellDelegate {
    func cell(cell: MyCustomCell, didPan sender: UIPanGestureRecognizer)
}

class MyCustomCell: UITableViewCell {

    var delegate: MyCustomCellDelegate?

    override func awakeFromNib() {
        let gesture = UIPanGestureRecognizer(target: self, action: "panGestureFired:")
        contentView.addGestureRecognizer(gesture)
    }

    func panGestureFired(sender: UIPanGestureRecognizer) {
        delegate?.cell(self, didPan: sender)
    }
}

Then in cellForRowAtIndexPath you just assign you view controller as the cells delegate.

A: You could add your pan gesture to the UITableViewCell in cellForRowAtIndexPath.
Then extract the optional UITableViewCell and look up the indexPath in the tableView.
Make sure you setup the UITableView as an IBOutlet so you can get to it in didPan:
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("PanCell", forIndexPath: indexPath)
        let panGesture = UIPanGestureRecognizer(target: self, action: "didPan:")
        cell.addGestureRecognizer(panGesture)
        return cell
    }

    func didPan(sender: UIPanGestureRecognizer) {
        // Sender will be the UITableViewCell
        guard let cell = sender.view as? UITableViewCell else {
            return
        }

        let indexPathForPan = tableView.indexPathForCell(cell)
    }


Q: Enable/Disable command buttons in CK Editor I am new to CK Editor. I have a created a plugin that shows a button on UI. I want to disable and enable based on some condition.
So I am using the following code to enable
var command = editorInstance.getCommand('myButton')
command.enable()

and to disable
var command = editorInstance.getCommand('myButton')
command.disable()

functionality-wise this works fine but it shows button in disable mode always on UI(always greyed button)
Am I missing something?

A: You can hide a button with CSS by using the class names that CKEditor creates for toolbar buttons. Try this (tested with v4.5.11):
// hide
document.getElementsByClassName('cke_button__myButton')[0].style.display = 'none';
//show
document.getElementsByClassName('cke_button__myButton')[0].style.display = 'block';


Q: How to migrate Oracle View to Teradata I am working on migration project of Oracle to Teradata.
The tables have been migrated using datastage jobs.
How do I migrate Oracle Views to Teradata?
Direct script copying is not working due to SQL statements difference of both databases
Please help?

A: The DECODE() Oracle function is available as part of the Oracle UDF Library on the Teradata Developer Exchange Downloads section. Otherwise, you are using the DECODE function in your example in the same manner in which the ANSI COALESCE() function behaves:
COALESCE(t.satisfaction, 'Not Evaluated')

It should be noted that the data types of the COALESCE() function must be implicitly compatible or you will receive an error. Therefore, t.satisfaction would need to be at least CHAR(13) or VARCHAR(13) in order for the COALESCE() to evaluate. If it is not, you can explicitly cast the operand(s).
COALESCE(CAST(t.satisfaction AS VARCHAR(13)), 'Not Evaluated')

If your use of DECODE() includes more evaluations than what is in your example I would suggest implementing the UDF or replacing it with a more standard evaluated CASE statement. That being said, with Teradata 14 (or 14.1) you will find that many of the Oracle functions that are missing from Teradata will be made available as standard functions to help ease the migration path from Oracle to Teradata.


Q: Linq to Entities - Subquery in the where statement This must be simple, but I've been searching for 2 hours, and can't find an answer. How do I write this in Linq to Entities:
SELECT Reg4, Reg5, Reg6
FROM dbo.Table1
WHERE Reg1 = 15
AND Reg2 = ( SELECT MAX(Reg2) FROM dbo.Table2 WHERE Reg1 = 15);

Is it possible to do it both in query expressions and method based syntaxes?
Tks

A: var r1 = 15;
var q = from t in Context.Table1
        where t.Reg1 == r1 &&
              t.Reg2 == Context.Table2
                               .Where(t2 => t2.Reg1 == r1)
                               .Max(t2 => t2.Reg2)
        select t;

Easier still if you have a navigation/association from Table1 to Table2. But you didn't show that, so neither will I....


Q: How to store list of objects that have different properties in django db? It is straightforward to store in mysql data like
[
    {
        'name': 'Object1',
        'color': 'red',
        'shape': 'ellipse'
    },
    {
        'name': 'Object2',
        'color': 'green',
        'shape': 'circle'
    }
]

But what if object has different number of attributes (attributes are flat, they are not nested)?
[
    {
        'name': 'Object1',
        'color': 'red',
        'shape': 'ellipse',
        'eccentricity': 0.5
    },
    {
        'name': 'Object2',
        'color': 'green',
        'shape': 'circle'
        'radius': 5
    }
]

There are many attributes, so sub-classing is not solution.
How do I handle it in mysql? Or if this is not possible, maybe postgresql?
What about non-relational databases, what is the best to use?
I need to make queries based on those attributes.
Thanks in advance.

A: There is JsonField in postgres which can be used for this kind of tasks. Also there is many apps for django which add JsonField that can work with mysql like django-extensions for example

A: I'm not sure why you're avoiding subclassing, it's built pretty much for this purpose. The best way to do this is subclassing. For this example, it looks like you'd probably want to use the shape attribute as the major class. For example, you could create a Shape class thusly:
class Shape(models.Model):
    color = models.CharField(max_length=20)
    class Meta:
        abstract = True

class Circle(Shape):
    radius = FloatField()

class Ellipse(Shape):
    eccentricity = FloatField()

This would create two tables in your model, a Circle table with a color and radius column, as well as a Ellipse table with a color and a eccentricity column.
If you really want to avoid subclassing for some reason, and you are using PostgreSQL, you can declare a JSONField (probably called attributes or something similar) of the different values. They would be harder to access programmatically, though. That would look like this:
class Shape(models.Model):
    color = models.CharField(max_length=20)
    attributes = models.JSONField()


Q: Unable to install WSO2 Enterprise Mobility Manager Hi i am unable to install the WSO2 Enterprise mobility Manager platform , followed the installation provided in the website, java environment variable is set, but getting error as below
[2014-05-02 11:27:41,150] ERROR {JAGGERY.config.app:js} -
[2014-05-02 11:27:41,151] ERROR {JAGGERY.config.app:js} -
[2014-05-02 11:27:41,151] ERROR {JAGGERY.config.app:js} -  Database is not confgured or has not started up

it is saying database is not configured, in the website they never mentioned about the database during the installation, can someone help me with this issue and als how to setup and database and run this platform.

A: this issue arise with mysql database setup. please follow below listed link to sorted out that issue..
https://docs.wso2.org/display/EMM100/General+Server+Configurations
there are few mistakes on documentation. On step 6, type exit;  and Step 9. add given config values within <datasources> </datasources>

A: Please check using MySQL console whether the admin has permission to access EMM_DB. Meanwhile you can try WSO2 EMM 1.1.0 http://wso2.com/products/enterprise-mobility-manager/


Q: How to depict non-grid 3D data as heat map? I have 3 columns of numbers x, y, z, where x and y are coordinates and z is intencity. I would like to represent the data as heat map in gnuplot.

A: You can set dgrid3d to fill in missing values:
set dgrid3d
splot 'input.txt' with pm3d


Q: Android onTouch Listener Background Color Change I'm using onTouchListener to change the background color when the user's finger is down and change back to default when the user's finger is up. The problem is that when the user's finger is down the background color changes but if the user doesn't takes the finger up and starts scrolling the background color doesn't change to default. Please help.
Below is my code:
    V.setOnTouchListener(new OnTouchListener() {
    @Override
       public boolean onTouch(View v, MotionEvent event) {
           switch(event.getAction()) {
               case MotionEvent.ACTION_DOWN:
                    V.setBackgroundColor(Color.BLUE);
                    break;
               case MotionEvent.ACTION_UP:
                    V.setBackgroundColor(Color.BLACK);
                    break;
           }
        return true;
      }
   });

I've also tried to return false but the result is the same

A: There are a few different approaches you can use.  You can look at MotionEvent.ACTION_MOVE and act when  you receive that in your onTouch.  You can look at MotionEvent.ACTION_OUTSIDE
and see if they have left the region your are checking.
You can also put a listener on your scroll View and change the background when it moves. Synchronise ScrollView scroll positions - android
Alternately, you could use a gestureListener and detect that.


Q: Encrypting Signed Data I'm submitting a file with the sensitive data to a 3rd party, could anyone explain what is the point in signing it and encrypting at the same time? Does just encrypting not verify my identity (the 3rd party requested it to be signed and then encrypted)?

A: You sign with your private key. Signature is proof of origin, it proves that you were in possession of the private key therefore the data must be from you, and the data was not altered.
You encrypt with the destination public key. This is to ensure that only the destination can decrypt it.
As you see, the signature and encryption serve different purposes.

A: Signing is putting your signature on a letter, and encrypting is putting the letter in an envelope. The envelope keeps other people from reading the letter. The signature proves that you wrote the letter.
Additionally, you sign and then encrypt, in that order, because if you instead put the letter in the envelope first, and then sign the envelope, this doesn't really prove that you wrote letter. You could argue in front of a judge that you didn't get to see the letter before the envelope was sealed.
Finally, you should not use the same key for both signing and encrypting. There are cryptographic reasons, but another, simpler reason is that the key that you use for encrypting can be held in escrow by other people (for example, the company you work for) to have access to the contents of all of your envelopes if needed, but the key you use for signing should only be given to people you would trust to legally sign in your place, as if a power of attorney.


Q: How can you create in Netbeans a new PHP project with source files located in local network? I'm trying to create a new PHP project in a situation where our client gave us only remote desktop connection to to their files.
How does it work usually in Netbeans:
To put it simple when a project is created with external sources we can click in our project on the single file and upload and download it (via ftp).

I'd like to be able to do this also on remote files located in a server which can be reached by our local network but which hasn't ftp installed.
Extra details
Until now we have been able to work normally with this setup by using Dreamweaver which allows to set in the server options an address located in the local network.
I really would like to switch to Netbeans and being able to click on upload and download on the local files to sync with their server but I can't find a way to achieve this.
There seem to be no option when creating a new project that allows this kind of setup. Selecting remote website seem to allow only ftp synch.

On the other hand if i select "Local web site" i can select the files in the local network, but NB doesn't allow me to make a local copy of them.
note 1: the server we're accessing hasn't ftp installed.
note 2: the "copy files from sources folder to another location" isn't really an option for me since I'd like to keep separated my local copy from what's on the server (and this setup I think would just copy the files without giving me any control on them).
note 3: creating a project with existing sources seem to allow only to have remote files reachable via ftp.

A: It would be useful to have some versioning system (git, mercurial, svn...). Can you mount the network drive in Windows? (see here ). This would at least allow you to easily create project from existing sources (although working via network could be quite slow)
One hacky way I can think of is to:

*

*mount the network drive as described above and map it to some letter, say Z

*install local FTP server (e.g. FileZilla)

*configure FileZilla FTP server to use the network drive as "ftp home" (aka the folder which FileZilla will use for saving files sent over FTP) - simply use Z:\ path to point to the mounted network drive mapped to letter Z

*in NetBeans, create a new PHP project from remote server (where remote server is actually your local FileZilla server)

In theory, this should work.

A: Here is the fragment from NetBeans site:

To set up a NetBeans project for an existing web application:

Choose File > New Project (Ctrl-Shift-N on Windows/Cmd-Shift-N on OS X).
Choose Java Web > Web Application with Existing Sources. Click Next.
In the Name and Location page of the wizard, follow these steps:
    In the Location field, enter the folder that contains the web application's source root folders and web page folders.
    Type a project name.
    (Optional) Change the location of the project folder.
(Optional) Select the Use Dedicated Folder for Storing Libraries checkbox and specify the location for the libraries folder. See Sharing Project Libraries in NetBeans IDE for more information on this option.
(Optional) Select the Set as Main Project checkbox. When you select this option, keyboard shortcuts for commands such as Clean and Build Main Project (Shift-F11) apply to this project.
Click Next to advance to the Server and Settings page of the wizard.
(Optional) Add the project to an existing enterprise application.
Select a server to which to deploy. If the server that you want does not appear, click Add to register the server in the IDE.
Set the source level to the Java version on which you want the application to run.
(Optional) Adjust the context path. By default, the context path is based on the project name.
Click Next to advance to the Existing Sources and Libraries page of the wizard.
Verify all of the fields on the page, such as the values for the Web Pages Folder and Source Package Folders.
Click Finish.


Q: how to link 1st collection's item property with item from 2nd collection enter image description here
Dim stations As New Collection
            Dim trains As New Collection
            For i = 1 To 60
                Dim new_station As New station
                With new_station
                    .id = S_stationsDataSet.Node_Table.Rows(i - 1)(0)
                    .name = S_stationsDataSet.Node_Table.Rows(i - 1)(1)
                    .t = S_stationsDataSet.Node_Table.Rows(i - 1)(4)
                    .name_t = new_station.name & new_station.t
                    .x = S_stationsDataSet.Node_Table.Rows(i - 1)(2)
                    .y = S_stationsDataSet.Node_Table.Rows(i - 1)(3)
                End With
                stations.Add(new_station, new_station.name_t)
            Next
            Dim a, c, l, n As String
            Dim m, b As Single
            For i = 1 To 78 Step 2
                a = S_trainsDataSet.T.Rows(1)(i)
                b = S_trainsDataSet.T.Rows(1)(i + 1)
                c = a & b
                l = S_trainsDataSet.T.Rows(2)(i)
                m = S_trainsDataSet.T.Rows(2)(i + 1)
                n = l & m
                Dim new_train As New train
                With new_train
                    .id = S_trainsDataSet.T.Rows(0)(i)
                    .src_t = S_trainsDataSet.T.Rows(1)(i + 1)
                    .dst_t = S_trainsDataSet.T.Rows(2)(i + 1)
                    .src = stations.Item(c)
                    .dst = stations.Item(n)
                End With
                trains.Add(new_train, new_train.id.ToString())
            Next

            For Each station In stations
                station.come = New Collection
                station.go = New Collection
                For Each train In trains
                    If train.src.name_t = station.name_t Then
                        station.go.add(train, train.id.ToString())
                    End If
                    If train.dst.name_t = station.name_t Then
                        station.come.add(train, train.id.ToString())
                    End If
                Next
            Next

vb : property of item in the 1st item is item in the 2nd collection and vise versa .. when I delete an item .. it isn't updated as null in the other collection
how can we link items of the two collections with each other

A: After a very long wait I finally got some time over to finish this. Very sorry for the extremely long wait.
I don't know if it's fully what you're looking for, but it will make the train and station classes work more together.

As you have so many collections (as they're even within your classes) it's hard to update them all. I'd recommend you to use a Dictionary(Of TKey, TValue) and just having Boolean properties in your train classes. Your Dictionary would look like this: Dictionary(Of station, List(Of train)).
First we'll need some extensions methods to later help us find and iterate through the stations and trains. We'll start with a function that will find a station by specifying it's name.
Create a new Module and add this code within:
''' <summary>
''' Finds a station by it's name.
''' </summary>
''' <param name="StationCollection">The dictionary to look for the station in.</param>
''' <param name="Name">The name of the station to find.</param>
''' <remarks></remarks>
<System.Runtime.CompilerServices.Extension()> _
Public Function FindStationByName(ByRef StationCollection As Dictionary(Of station, List(Of train)), ByVal Name As String) As station
    Name = Name.ToLower() 'ToLower() provides case-insensitive checking.

    'Iterating through a Dictionary requires iterating through it's keys, as it's not index based.
    For Each k As station In StationCollection.Keys
        If k.name_t.ToLower() = Name Then
            Return k
        End If
    Next

    Return Nothing
End Function

Then we need extension methods for finding a train by it's id or it's name. We also an extension for finding all trains linked to a specific station. In the same module as above add:
''' <summary>
''' Finds a train by it's ID.
''' </summary>
''' <param name="TrainCollection">The list to look for the train in.</param>
''' <param name="Id">The ID of the train to find.</param>
''' <remarks></remarks>
<System.Runtime.CompilerServices.Extension()> _
Public Function FindTrainById(ByRef TrainCollection As List(Of train), ByVal Id As Integer) As train
    For Each t As train In TrainCollection
        If t.id = Id Then
            Return t
        End If
    Next

    Return Nothing
End Function

''' <summary>
''' Finds a train by it's name.
''' </summary>
''' <param name="TrainCollection">The list to look for the train in.</param>
''' <param name="TrainName">The name of the train to find.</param>
''' <remarks></remarks>
<System.Runtime.CompilerServices.Extension()> _
Public Function FindTrainByName(ByRef TrainCollection As List(Of train), ByVal TrainName As String) As train
    TrainName = TrainName.ToLower()

    For Each t As train In TrainCollection
        If t.name_t = TrainName Then
            Return t
        End If
    Next

    Return Nothing
End Function

''' <summary>
''' Finds all trains linked to the specified station.
''' </summary>
''' <param name="StationCollection">The dictionary to look for the station in.</param>
''' <param name="StationName">The name of the station which's trains to find.</param>
''' <remarks></remarks>
<System.Runtime.CompilerServices.Extension()> _
Public Function FindTrainsByStation(ByRef StationCollection As Dictionary(Of station, List(Of train)), ByVal StationName As String) As List(Of train)
    StationName = StationName.ToLower()

    For Each k As station In StationCollection.Keys
        If k.name_t.ToLower() = StationName Then
            Return StationCollection(k)
        End If
    Next

    Return Nothing
End Function

Finally we'll need an extension method to remove a train from all the stations. This extension method will be used by the RemoveAll() and RemoveAllByName() methods in the train class later.
''' <summary>
''' Removes a trains link from all stations.
''' </summary>
''' <param name="StationCollection">The dictionary of stations which's links to this train to remove.</param>
''' <param name="train">The train to remove.</param>
''' <param name="MatchName">If true, match by the train's name instead of it's ID.</param>
''' <remarks></remarks>
<System.Runtime.CompilerServices.Extension()> _
Public Sub RemoveTrainFromAllStations(ByVal StationCollection As Dictionary(Of station, List(Of train)), ByVal train As train, ByVal MatchName As Boolean)
    For Each k As station In StationCollection.Keys

        For i = 0 To StationCollection(k).Count - 1
            Dim t As train = StationCollection(k)(i)

            If MatchName = False Then 'Wether to match against the train's name or id.
                If t.id = train.id Then
                    t.Remove()
                End If

            Else
                If t.name_t = train.name_t Then
                    t.Remove()
                End If

            End If
        Next

    Next
End Sub

Now onto your classes.
Passing the Dictionary reference to your station and train classes can also help you create functions for checking which train belongs to which station, etc. By doing this you have the classes working together with the Dictionary, you can even make another wrapper class around this to reduce "messieness" even more.
You will also need to override the Equals and GetHashCode methods in order for dictionaries and hash tables to be able to lookup your key correctly.
This is just example code, so I haven't included your properties here:
Public Class train
    Private StationCollection As Dictionary(Of station, List(Of train)) 'Storing the main dictionary.
    Private _parent As station

    ''' <summary>
    ''' Wether this train is departing or arriving.
    ''' </summary>
    ''' <remarks></remarks>
    Public Property Departing As Boolean = False

    ''' <summary>
    ''' The station that owns this train (multiple stations can own trains with the same names and IDs).
    ''' This is mainly used for internal functions.
    ''' </summary>
    ''' <remarks></remarks>
    Public ReadOnly Property ParentStation As station
        Get
            Return _parent
        End Get
    End Property

    ''' <summary>
    ''' Initializes a new instance of the train class.
    ''' </summary>
    ''' <param name="StationCollection">The main dictionary containing this train and it's station.</param>
    ''' <param name="ParentStation">The station that owns this train (multiple stations can own trains with the same names and IDs).</param>
    ''' <remarks></remarks>
    Public Sub New(ByRef StationCollection As Dictionary(Of station, List(Of train)), ByVal ParentStation As station)
        Me.StationCollection = StationCollection
        Me._parent = ParentStation
    End Sub

    ''' <summary>
    ''' Removes this train from it's station.
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub Remove()
        Me.StationCollection(ParentStation).Remove(Me)
    End Sub

    ''' <summary>
    ''' Removes this, and all other trains having the same ID as this, from all stations in the main dictionary.
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub RemoveAll()
        Me.StationCollection.RemoveTrainFromAllStations(Me, False)
    End Sub

    ''' <summary>
    ''' Removes this, and all other trains having the same name as this, from all stations in the main dictionary.
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub RemoveAllByName()
        Me.StationCollection.RemoveTrainFromAllStations(Me, True)
    End Sub

    'the rest of your code...

    'Overriding Equals() and GetHashCode(), comparison will be performed by comparing two trains' id's.
    Public Overrides Function Equals(obj As Object) As Boolean
        Return obj IsNot Nothing AndAlso obj.GetType() Is GetType(train) AndAlso DirectCast(obj, train).id = Me.id
    End Function

    Public Overrides Function GetHashCode() As Integer
        Return Me.id.GetHashCode()
    End Function
End Class

And the station class:
Public Class station
    Private StationCollection As Dictionary(Of station, List(Of train)) 'Linking this station to the main Dictionary.

    ''' <summary>
    ''' Gets a list of trains arriving at this station. Modifying the returned list will NOT affect the main dictionary or it's stations.
    ''' </summary>
    ''' <remarks></remarks>
    Public ReadOnly Property ArrivingTrains As List(Of train)
        Get
            Return Me.GetTrainsByType(False)
        End Get
    End Property

    ''' <summary>
    ''' Gets a list of trains departing from this station. Modifying the returned list will NOT affect the main dictionary or it's stations.
    ''' </summary>
    ''' <remarks></remarks>
    Public ReadOnly Property DepartingTrains As List(Of train)
        Get
            Return Me.GetTrainsByType(True)
        End Get
    End Property

    ''' <summary>
    ''' Gets all trains of the specified type that are linked to this station.
    ''' </summary>
    ''' <param name="Departing">Wether to get all departing trains or all arriving trains.</param>
    ''' <remarks></remarks>
    Private Function GetTrainsByType(ByVal Departing As Boolean) As List(Of train)
        Dim TrainList As List(Of train) = StationCollection(Me) 'Getting all trains for this station.
        Dim ReturnList As New List(Of train)

        For Each t As train In TrainList
            If t.Departing = Departing Then
                ReturnList.Add(t)
            End If
        Next

        Return ReturnList
    End Function

    ''' <summary>
    ''' Removes this station and all links to trains arriving or departing from it.
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub Remove()
        For Each t As train In StationCollection(Me) 'Iterate though all the trains for this station.
            GetType(train).GetField("_parent", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic).SetValue(t, Nothing) 'Use reflection to set the train's parent to Nothing.
        Next

        StationCollection.Remove(Me)
    End Sub

    ''' <summary>
    ''' Initializes a new instance of the station class.
    ''' </summary>
    ''' <param name="StationCollection">The main dictionary containing this train and it's station.</param>
    ''' <remarks></remarks>
    Public Sub New(ByRef StationCollection As Dictionary(Of station, List(Of train)))
        Me.StationCollection = StationCollection
    End Sub

    'the rest of your code...

    'Overriding Equals() and GetHashCode(), comparison will be performed by comparing two stations' names.
    Public Overrides Function Equals(obj As Object) As Boolean
        Return obj IsNot Nothing AndAlso obj.GetType() Is GetType(station) AndAlso DirectCast(obj, station).name_t = Me.name_t
    End Function

    Public Overrides Function GetHashCode() As Integer
        Return Me.name_t.GetHashCode()
    End Function
End Class

Adding new stations/trains
When adding items to the dictionary you would first have to initialize a new station class, then you create new train classes where you point the ParentStation parameter to the station you just created.
For example:
Dim MainDictionary As New Dictionary(Of station, List(Of train)) 'Create the dictionary (only do this once, unless you need multiple of course).

Dim new_station As New station(MainDictionary) 'Create a new station.
new_station.name = "Station 1"

MainDictionary.Add(new_station, New List(Of train))

Dim new_train As New train(MainDictionary, new_station) 'Create a new train.
new_train.id = 3
new_train.name_t = "Train 1"
new_train.Departing = True 'This train is leaving from the station.

MainDictionary(new_station).Add(new_train) 'Add the train to the station.

Extension methods
The extension methods are used when...

*

*You want to find a specific station by it's name.
For example:
Dim st As station = MainDictionary.FindStationByName("Station 1")

*You want to find a train by it's id or name.
For example:
Dim t As train = MainDictionary.FindStationByName("Station 1").ArrivingTrains.FindTrainById(3)
Dim t2 As train = MainDictionary.FindStationByName("Station 1").ArrivingTrains.FindTrainByName("Train 1")

*Or when you want to get all trains from a specific station (by it's name).
For example:
Dim trains As List(Of train) = MainDictionary.FindTrainsByStation("Station 1")

Overview of the methods, fields and properties:
- The train class -
StationCollection

*

*A private field holding the reference to your main dictionary of all stations.

_parent

*

*A private field holding the station this train is "linked" to.

Departing

*

*A public property indicating if this train is departing (leaving) or arriving (coming)

ParentStation

*

*A public read-only property returning the value of _parent.

Remove()

*

*Removes this train from the station it's linked to.

RemoveAll()

*

*Removes this train, and all other trains having the same ID as this, from all stations in the main dictionary.

RemoveAllByName()

*

*Same as RemoveAll(), but matches against the trains' names instead of their IDs.

- The station class -
StationCollection

*

*Same as in the train class.

ArrivingTrains

*

*A read-only property returning all trains arriving at (coming to) this station.

DepartingTrains

*

*A read-only property returning all trains departing (leaving) from this station.

GetTrainsByType()

*

*A private method for getting arriving/departing trains. Used by the above properties.

Remove()

*

*Removes this station and all links to arriving or departing trains (by nullifying their _parent field) that are in the main dictionary.

Hope this helps! And sorry again for taking so long.


Q: 2D Platformer multiple classes without code duplication I'm working on a 2D platformer in c#, as most people are, but I have got a decent start to the project I have a class called Player, I then handle all collision for that player as well as the scrolling of the blocks in the background within the gamescreen class. I have just added another player (as a different class in this case a warrior), but all of my collision is based around the players positions and velocity, how would I change the blocks movement and collision to be around the warrior's velocity and positions instead (without duplicating or creating quite a lot of code).
Thanks for any help Sam.

A: Inheritance is your friend.  You should probably have a base Player class, or even something more low level than that.  The base class implements the colision detection and movement code.  Your Warrior and other player types should inherit that class and override different parts to change the behavior.

A: My strategy works approximately like this:
I have a Character class. It contains a HitboxSet. The HitboxSet exposes an active Hitbox. All my collision is done based on Hitbox instances. Depending on what kind of character I need, I pass in different sprites, hitboxes, movements, etc.
The result is a high degree of flexibility, while allowing you to keep your concerns thoroughly separated. This strategy is known as Composition, and is widely considered superior to inheritance based strategies in almost all cases.
The main advantage of this strategy over inheritance is the ability to mix and match components. If, one day, you decide that you need a new projectile that's smaller than a previous one, and moves in a sine pattern, you simply use a new sine movement. You can reuse such things infinitely, in any combination.
You can do something like this with inheritance: a child class can override a method and do something differently. The problem is that you either keep adding new child classes with different combinations and end up with a terrifyingly complex tree, or you limit your options.
In short, if something is naturally going to vary, as it almost certainly will in a game, those variations should be distinct classes that can be combined in different ways rather than mutually exclusive overrides.


Q: How to return blank or zero when 'On Error Resume Next' leaves previous value in variable? I have VBA code that gets the stock price in a loop.
There are stock symbols not found in this API source. It will result to error for those stocks.
I'm using On Error Resume Next so the VBA code will continue to the next symbol.
My problem is the symbol in error will return a stock price of the last stock symbol not in error.
I would like to make the result blank or zero for the stock symbols in error.
Current Result - the italicized symbols are those that are in error.
Stock Symbol Price
BDO 158.00
ABS 15.80
GREEN 1.87
ALHI 1.87
LAND 1.87
PLC 0.57
LBC 0.57
EVER 0.57
Desired Result - the italicized symbols those that are in error will result or will give return of 0
Stock Symbol Price
BDO 158.00
ABS 15.80
GREEN 1.87
ALHI 0
LAND 0
PLC 0.57
LBC 0
EVER 0
    Set myrequest = CreateObject("WinHttp.WinHttpRequest.5.1")
    myrequest.Open "Get", "http://phisix-api.appspot.com/stocks/" & symbol & ".json"
    myrequest.Send

    Dim Json As Object
    Set Json = JsonConverter.ParseJson(myrequest.ResponseText)

    i = Json("stock")(1)("price")("amount")
    ws.Range(Cells(n, 2), Cells(n, 2)) = i

    n = n + 1

    On Error Resume Next

Next X

ws.Columns("B").AutoFit
MsgBox ("Stock Quotes Refreshed.")

ws.Range("B4:B" & lastrow).HorizontalAlignment = xlGeneral
ws.Range("B4:B" & lastrow).NumberFormat = "#,##0.00"

Application.DisplayAlerts = True
Application.ScreenUpdating = True

End Sub

A: Your code as it stands sets On Error Resume Next at the end of the first time through the loop, and from that point on ignores any and all errors. That's bad.
The general method of using OERN should be
Other non error causing code
Optionally initialise variables in preparation for error trap
On Error Resume Next
   Execute the instruction that might cause an error
On Error GoTo 0
If (test if instruction succeeded) Then
    Process the result
Else
    Optionally handle the error case
End If

A: You can always put a conditional check statement based on the error you receive for invalid stocks, if you are getting empty value in myrequest on invalid stock. You can write your logic like below and update price value to 0.
If myrequest is Nothing Then
    'For Invalid Stocks
End

or
If myrequest.ResponseText = "" Then
    'For Invalid Stocks
End

Let me know if it helps. Otherwise share the JSON response for both valid and invalid stocks.
Update:
Based on the value of myrequest.ResponseStatus for invalid response, update the <add-condition> condition in If statement according to your requirement.
For Each X In rng

    Dim Json As Object
    Dim i
    symbol = X

    Set myrequest = CreateObject("WinHttp.WinHttpRequest.5.1")
    myrequest.Open "Get", "http://phisix-api.appspot.com/stocks/" & symbol & ".json"
    On Error Resume Next
    myrequest.Send
    On Error GoTo 0

    Debug.Print myrequest.ResponseStatus

    If <add-condition> Then
        Set Json = JsonConverter.ParseJson(myrequest.ResponseText)
        i = Json("stock")(1)("price")("amount")
    Else
        i = 0
    End If

    ws.Range(Cells(n, 2), Cells(n, 2)) = i
    n = n + 1

Next X


Q: convert Cartesian width and height to Isometric I'm trying to create an Isometric game in the SDL graphics library.
When you render in SDL you require a source rectangle and a destination rectangle. The source rectangle is the portion of the texture you have loaded that you wish to render and the destination rectangle is the area on the screen you are rendering to. Rectangles simply consist of 4 properties, X position, Y position, Width, and Height.
Now say I have a Cartesian destination rectangle with these coordinates:

X=20, Y=10, Width=16, Height=16

Now say I wanted to convert this to Isometric. To convert the X and Y coordinates I would use:
isometricX = cartX - cartY;
isometricY = (cartX + cartY) / 2;

Now what I don't understand is what I would do to convert the Cartesian Width and Height to Isometric Width and Height to create the illusion that the view port is being moved 45 degrees to one side and 30 degrees down, creating the Isometric look.
EDIT:
I'd like to clarify my question a little, so when I convert the Cartesian Coordinates to Isometric I change this:http://i.stack.imgur.com/I79yK.png
to this:http://i.stack.imgur.com/ZCJg1.png. So now I am trying to figure out how to rotate the tiles so they all fit together and how I need to adjust the Height and Width to get this to happen.

A: To start with you'll need these operations to convert to and from isometric coordinates:
isoX = carX + carY;
isoY = carY - carX / 2.0;

carX = (isoX - isoY) / 1.5;
carY = isoX / 3.0 + isoY / 1.5;

right-angled corners in the top-left and bottom-right become 120 degrees, the other two corners become 60 degrees. the bottom-right corner becomes the bottom corner, the top-left corner becomes the top. this also assumes that y increases going up, and x increases going right (if your system is different, flip the signs accordingly). you can verify via substitution that these operations are eachothers inverse.
for a rectangle you need 4 points transformed - the corners - as they will not be 'rectangular' for the purposes of SDL (it will be a parallelogram). this is easier to see numerically.
first, assign the corners names of some sort. i prefer clockwise starting with the bottom-left - this coordinate shall be known as C1, and has an associated X1 and Y1, the others will be C2-4.
C2 - C3
|    |
C1 - C4

then compute their cartesian coordinates...
X1 = RECT.X;
Y1 = RECT.Y;

X2 = X1; // moving vertically
Y2 = RECT.Y + RECT.HEIGHT;

X3 = RECT.X + RECT.WIDTH;
Y3 = Y2; // moving horizontally

X4 = X3; // moving vertically
Y4 = RECT.Y;

and lastly apply the transform individually to each coordinate, to get I1, I2, I3, I4 coordinates...
iX1 = X1 + Y1;
iY1 = Y1 - X1 / 2.0;
// etc

and what you end up with is on-screen coordinates I1-4, that take this shape:
    I2
  /    \
I1      I3
  \    /
    I4

But unlike this shoddy depiction, the angles for I4 and I2 will be ~127 deg, and for I1 and I3 it should be ~53 deg. (this could be fine-tuned to be exactly 60/120, and depends on the 2.0 factor for carX when computing isoY - it should be sqrt(3) rather than 2.0 but meh, close enough)
if you use the inverse transform, you can turn back the I1-4 coordinates into C1-4, or locate a world coordinate from a screen coordinate etc.
implementing a camera / viewport gets a little tricky if only at first but it's beyond what was asked so i won't go there (without further prodding)...
(Edit) Regarding SDL...
SDL does not appear to "play nice" with generalized transforms. I haven't used it but its interface is remarkably similar to GDI (windows) which I've played around with for a game engine before and ran into this exact issue (rotating + scaling textures).
There is one (looks to be non-standard) SDL function that does both scaling and rotating of textures, but it does it in the wrong order so it always maintains the perspective of the image, and that's not what is needed here.
Basic geometry will be fine, as you've seen, because it's fills and lines which don't need to be scaled, only positioned. But for textures... You're going to have to either write code to render the texture one pixel at a time, or use a combination of transforms (scale after rotate), or layering (drawing an alpha-masked isometric square and rendering a pre-computed texture) and so on...
Or of course, if it's an option for you, use something suited for raw geometry and texture data like OpenGL / Direct3D. Personally I'd go with OpenGL / SFML for something like this.

A: Unfortunately I cannot comment to ask for clarification so I must answer with a question: can you not convert all four points then from those points calculate the width and height from the transformed points?

X=20, Y=10, Width=16, Height=16

as you've said
isometricX = cartX - cartY;
isometricY = (cartX + cartY) / 2;

so
isometricX1 = cartX1 - cartY1;
isometricY1 = (cartX1 + cartY1) / 2;

and
isometricWidth = std::abs(isometricY - isometricY1)

There's probably a more efficient route though but as I do not know Cartesian geometry I can't find that solution
EDITisometricWidth found the distance between the two points not the width and hieght
another note is you'd need opposite corners (yes I realize the other guy probably as a much better answer :P)


Q: Dynamic prop value in react? I want a dynamic prop value for react.  I already have a list of Fruits, but my prop value should be Fruits[0] + 'prop'
For example: ApplesProp
index.js
const ApplesProp = { Name: "Green", Age: 34 }

const Fruits = ["Apples", "Pears", "Oranges"]

<App prop={dynamic-fruit+'Prop'} />

Tried
<App prop={Fruits[0]+'Prop'}/>

but this results in passing the string: 'ApplesProp' not the ApplesProp object (i.e. Name: Green, Age: 34).

A: Fruits[0]+'Prop'

Adding a string to a string returns a string.
To accomplish what you need, you can create an object with fruits as keys and props as values:
const fruitVsProps = {
 Apples: ApplesProp
 // add more as you like
}

<App prop={fruitVsProps[Fruits[0]]} />

A: there is two way you can Do it.
1.better way use array.map() then pass to your props.
 let Fruits = ["Apples", "Pears", "Oranges"];
<ff> {Fruits.map((item)=>{<App props={item} /> })} </ff>

2.second way you can use literal template

A: Create an object and add your object in that

const props = {
    ApplesProp: { Name: "Green", Age: 34 }
  }

const Fruits = ["Apples", "Pears", "Oranges"]

console.log(props[Fruits[0]+'Prop'])

and now you could use it like
<App prop={props[Fruits[0]+'Prop']} />

A: To accomplish the above task you need to create an object with fruits as keys and props as values
const AppleProps = {Name : "Green }
const Fruits = {"Apples", "Banana"}
const FruitsAndProps = {
 Apples: AppleProps
}

A: You need to consider passing your dynamic string inside backticks => `` instead of quotes and use eval() method to convert your string to variable (so that IDE knows you are refering to a variable not a string). The result should look like this:
const ApplesProp = { Name: "Green", Age: 34 }
const Fruits = ["Apples", "Pears", "Oranges"]
console.log(eval(`${Fruits[0]}Prop`))
//the console returns an object. so passing it through props should be fine.
<App prop={eval(`${Fruits[0]}Prop`)}/>

Although there are cleaner ways to solve this, since i don't want to mess with your logic i come up with the above code.


Q: Items not being found in search box even though they exist So basically I have a search box setup in Sheet 2 where I use a barcode scanner to scan the item IDs and when I hit search it populates the information about that item that is found in Sheet 1. I have 2 types of item IDs in the system, one which consists of letters and numbers and the other strictly numbers. The problem I am currently encountering is that when I scan the strictly number ID into my search box, it cannot find it, but it can find it if I just copy and paste the ID from sheet 1 into the search box. I feel as if it has something to do with formatting of my search, like maybe its just looking for text and when I copy and paste into the search box they are formatted as text? I'm not too sure but any insight would be greatly appreciated. Attached below is my code.
Sub SearchBox()
Dim lastrow As Long
Dim i As Long, x As Long
Dim count As Integer

lastrow = Sheets("Charlotte Gages").Cells(rows.count, 1).End(xlUp).Row
i = Sheets("Gages").Cells(rows.count, 1).End(xlUp).Row + 1
For x = 2 To lastrow

If Sheets("Charlotte Gages").Cells(x, 1) = Sheets("Gages").Range("A1") Then
    Sheets("Gages").Cells(i, 1).Resize(, 7).Value = Sheets("Charlotte Gages").Cells(x, 1).Resize(, 7).Value
    i = i + 1
    count = count + 1
End If

Next x

If count = 0 Then
    MsgBox ("Cannot Find Gage, Please check Gage ID")
End If

End Sub

A: Somewhere the text/value isn't equal. I inserted a msgbox in your code so you can see exactly what's being compared.
UPDATED WITH TRUE/FALSE DISPLAYED IN MESSAGE BOX TITLE
    Sub SearchBox()
Dim lastrow As Long
Dim i As Long, x As Long
Dim count As Integer

lastrow = Sheets("Charlotte Gages").Cells(Rows.count, 1).End(xlUp).Row
i = Sheets("Gages").Cells(Rows.count, 1).End(xlUp).Row + 1
For x = 2 To lastrow

'try with this to test
Dim anSwer As Integer

Dim TrueOrFalse As String
TrueOrFalse = Sheets("Charlotte Gages").Cells(x, 1) = Sheets("Gages").Range("A1")

anSwer = MsgBox("your value in Charlotte Gauges Cell " & Sheets("Charlotte Gages").Cells(x, 1).Address & " is """ & Sheets("Charlotte Gages").Cells(x, 1).Value & _
 """ while your other value in cell " & Sheets("Gages").Range("A1").Address & " is """ & Sheets("Gages").Range("A1").Value & """. Continue?", vbYesNo, Title:=TrueOrFalse)
If anSwer = vbNo Then
Exit Sub
End If
'End of test code, this can be deleted once you figure out your issue

If Sheets("Charlotte Gages").Cells(x, 1) = Sheets("Gages").Range("A1") Then
    Sheets("Gages").Cells(i, 1).Resize(, 7).Value = Sheets("Charlotte Gages").Cells(x, 1).Resize(, 7).Value
    i = i + 1
    count = count + 1
End If

Next x

If count = 0 Then
    MsgBox ("Cannot Find Gage, Please check Gage ID")
End If

End Sub

A: So I figured out what was wrong. The number-only ID's were stored as text in Sheet 1, therefore not allowing my search box to find it. All I had to do was convert them all to numbers and it fixed everything.


Q: How to write If statement and For loop programatically with Robot Framework API I have been exploring Robot framework and came across this example which I am trying to use. This example works great except I wanted to try adding a for loop and if statement. I haven't even began the if statement yet as I am stuck with the for loop. Please may I have help to suggest how to construct a for loop and if statement.
This is a basic attempt of a for loop to add at the end of the script to test:
test.keywords.create('For', args=['1','IN','10'], type='for')
error - TypeError: __init__() got an unexpected keyword argument 'flavor'

The code below just shows i am trying to add basic for loop but compiles with above error
from robot.api import TestSuite

suite = TestSuite('Activate Skynet')
suite.imports.library('OperatingSystem')
test = suite.tests.create('Should Activate Skynet', tags=['smoke'])
test.keywords.create('Set Environment Variable', args=['SKYNET', 'activated'], type='setup')
test.keywords.create('Environment V`enter code here`ariable Should Be Set', args=['SKYNET'])
test.keywords.create('For', args=['1','IN','10'], type='for')

origin - https://robot-framework.readthedocs.io/en/2.8.1/autodoc/robot.running.html
test.keywords.create('Create List', args=['a', 'b', 'c'], assign=['@{list}'])
for_kw = ForLoop(['${l}'], ['@{list}'], flavor='IN')
for_kw.keywords.create('log', args=['${l}'])
test.keywords.create()
test.keywords.append(for_kw)

A: UPDATE: With Robot Framework this has changed and became easier to do.
Release note: Running and result models have been changed.

*

*TestSuite, TestCase and Keyword objects used to have keywords attribute containing keywords used in them. This name is misleading
now when they also have FOR and IF objects. With TestCase and
Keyword the attribute was renamed to body and with TestSuite it
was removed altogether. The keywords attribute still exists but it is
read-only and deprecated.

*The new body does not have create() method for creating keywords, like the old keywords had, but instead it has separate
create_keyword(), create_for() and create_if() methods. This
means that old usages like test.keywords.create() need to be changed
to test.body.create_keyword().

For examples check out this other answer: How to write FOR loop and IF statement programmatically with Robot Framework 4.0?.

BEFORE Robot Framework 4.0:
IF statement
The if statement should be a Run Keyword If keyword with the arguments you need. It is a keyword like any other so you should list everything else in its args list.

*

*The condition.

*The keyword name for the True branch.

*Separately any args to the keyword for the True branch if there is any. Listed separately.

*

*The ELSE IF keyword if needed.

*The ELSE IF condition.

*The keyword name for the ELSE IF branch.

*Separately any args to the keyword for the ELSE IF branch if there is any. Listed separately.

*

*The ELSE keyword.

*The keyword name for the ELSE branch.

*Separately any args to the keyword for the ELSE branch if there is any. Listed separately.

from robot.api import TestSuite

suite = TestSuite('Activate Skynet')
test = suite.tests.create('Should Activate Skynet', tags=['smoke'])

test.keywords.create('Run Keyword If', args=[True, 'Log To Console', 'Condition was TRUE', 'ELSE', 'Log To Console', 'Condition was FALSE'])
test.keywords.create('Run Keyword If', args=[False, 'Log To Console', 'Condition was TRUE', 'ELSE', 'Log To Console', 'Condition was FALSE'])

suite.run()

This is how it looks like in the logs:

FOR loop
As for the for loop. It is a special keyword implemented by robot.running.model.ForLoop class that bases on the robot.running.model.Keyword class. Here is the constructor:

It has a flavor parameter, which is the loop type to be say. So it is IN, IN RANGE, IN ZIP, etc.
Now you instantiating a robot.running.model.Keyword which despite you could set its type to for, it won't have flavor attribute. So when you execute your code it will throw the error you see. It is because the ForRunner will try to access the flavor attribute.
  File "/usr/local/lib/python3.7/site-packages/robot/running/steprunner.py", line 52, in run_step
    runner = ForRunner(context, self._templated, step.flavor)
AttributeError: 'Keyword' object has no attribute 'flavor'

So you have to use the ForLoop class. Also I am using Robot Framework 3.1.2 so the errors might be different in my case but the approach should be the same.
Here is how it should look like:
from robot.running.model import ForLoop

for_kw = ForLoop(['${i}'], ['10'], flavor='IN RANGE')
test.keywords.append(for_kw)

No this will still fail with error:

FOR loop contains no keywords.

So you have to populate it like:
for_kw.keywords.create('No Operation')

The complete example:
from robot.api import TestSuite
from robot.running.model import ForLoop

suite = TestSuite('Activate Skynet')
test = suite.tests.create('Should Activate Skynet', tags=['smoke'])
test.keywords.create('Log Many', args=['SKYNET', 'activated'], type='setup')
test.keywords.create('Log', args=['SKYNET'])

for_kw = ForLoop(['${i}'], ['10'], flavor='IN RANGE')
for_kw.keywords.create('No Operation')
test.keywords.append(for_kw)
suite.run()

If you run this it will only produce an output XML, you have to run rebot manually to have a log and report HTML file.


Q: Get total from table input as grand total in jquery I have a table that makes automatically 2 calculations:

*

*Calculation of numbers of days after the selection of date started and date end from two input date field with calendar, result is stored is field (days)

*Multiplication of 3 fields (horse* days* price), result is stored ind field (total).
There is a button that when we click on it a new row is added.

How can i calculate the grand total of numbers of days and the grand total of the total to display the results in a row below the table?
And i want to grasp the input values in post so that i store them in table using php.
1- table

  Nbr/horses
  dateStart
  dateEnd
  Nbr/days
  Price
  Total

  <input type='number' min='1' name='horse' class='horse'/>
  <input type='date' name='dateStart' class='datepicker dateStart'/>
  <input type='date' name='dateEnd' class='datepicker dateEnd'/>
  <input type='text' name='days'/>0
  <input type='number' min='1' name='price' class='price'/>
   <input type='text' name='total1'/>
  <button type='button' class='button'>+</button>

2- functions
 let update = function(lineNode){
let dateStart = $(lineNode).find('.dateStart').datepicker('getDate');
let dateEnd = $(lineNode).find('.dateEnd').datepicker('getDate');
let days = Math.floor( (dateEnd - dateStart) / (3600*24*1000) );
days = days >= 0 ? days : 0;

$( lineNode ).find('.days').text( days );

let horse = parseInt( $(lineNode).find('.horse').val() );
let price = parseInt( $(lineNode).find('.price').val() );
let total = horse * days * price;

$( lineNode ).find('.total').text( total+' €' );
 }

  // add line after click
  let addRow = function(lineNode){
   let clone = lineNode.cloneNode(true);
   $(clone).insertAfter(lineNode);
   reloadEffects();
   }

  let reloadEffects = function(){
  $('.hasDatepicker').removeClass('hasDatepicker').attr('id', '');

$('.datepicker').datepicker();
$('.horse, .price, .datepicker').change( e => {
  update(e.target.parentNode.parentNode);
});
$('.button').click( e => {
  addRow(e.target.parentNode.parentNode);
});

};
// Start

 reloadEffects();

A: for the total
var sum = 0;
$(".total").each(function(index,value){
sum = sum + parseFloat($(this).find('input[name="total1"]').val());
});
//Sum in sum variable
console.log(sum);

Apply the same for days !
Working Fiddle : Fiddle


Q: Bad performance of MobileVLCKit? I have i problem. I builded MobileVLCKit and use in my project. All works, but video playing has bad performance (lagging). Where is the problem? Console says only:
creating player instance using shared library
shader program 1: WARNING: Output of vertex shader 'TexCoord1' not read by fragment shader
WARNING: Output of vertex shader 'TexCoord2' not read by fragment shader

Thanks! :)


Q: Collapsing multiple navbar bootstrap I have followed this example http://jsfiddle.net/rDN3P/98/ to create a collapsing navbar. It is working fine as long as I have one level in my menu. The collapsing seems not to work if I have multiple level of menu.
In this example, if you open the collapsible menu and click on the second 'dropdown2' item in the menu you will know what I mean.
This structure is the issue I assume

          Dropdown

                    Dropdown2

Action sub

A: Solved: jsfiddle
Based on this answer to add the third level menu with a little modification of the js code to close the third level menu on click:
$('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {
    // Avoid following the href location when clicking
    event.preventDefault();

    // Avoid having the menu to close when clicking
    event.stopPropagation();

// If a menu is already open we close it
if($(this).parent().hasClass('open')){
    $('ul.dropdown-menu [data-toggle=dropdown]').parent().removeClass('open');
}else{
    // opening the one you clicked on
$(this).parent().addClass('open');

var menu = $(this).parent().find("ul");
var menupos = menu.offset();

if ((menupos.left + menu.width()) + 30 > $(window).width()) {
    var newpos = - menu.width();
} else {
    var newpos = $(this).parent().width();
}
menu.css({ left:newpos });
}

});

A:

      Dropdown

                Dropdown2

Action sub

The nesting should be done properly I guess, with the correct classes.


Q: What is the CURRENT official/recommended MIME type for Javascript? I need to know what could be the correct current/future proof Javascript MIME type.
References
RFC 4329- April 2006, seems to say text/javascript is obsolete and recommends to use application/javascript :

Use of the "text" top-level type for this kind of content is known to
be problematic.  This document thus defines text/javascript and text/ecmascript but marks them as "obsolete".

HTML Living Standard — Updated 2 July 2019 I guess says text/javascript is fine :

The term "JavaScript" is used to refer to ECMA-262, rather than the official term ECMAScript, since the term JavaScript is more widely known. Similarly, the MIME type used to refer to JavaScript in this specification is text/javascript, since that is the most commonly used type, despite it being an officially obsoleted type according to RFC 4329. [RFC4329]

So at this point text/javascript is correct?
Internet Draft - ECMAScript Media Types Updates to RFC4329, which is said to expire on December 21, 2019, says

This document updates the existing media types for the ECMAScript
programming language.  It supersedes the media types registrations in
[RFC4329] for "application/javascript" and "text/javascript".

application/javascript - Intended usage:  OBSOLETE

The first version of the same draft on October 7, 2017, also says

text/javascript has been moved intended usage from OBSOLETE to COMMON.

Also MDN - Incomplete list of MIME types mention JavaScript MIME type ad text/javascript
Question
Part 1. What would be the correct MIME type at present/after December 21, 2019, if the draft expires/does not expire?
Part 2. Should the drafts be followed before they are finalized?
PS :
This is NOT a duplicate of the following questions. I have gone through most of the main discussions in these questions.

*

*text/javascript vs application/javascript ~ 5+ years old.

*When to use the JavaScript MIME type application/javascript instead of text/javascript? ~ 8+ years old.

*When serving JavaScript files, is it better to use the application/javascript or application/x-javascript - 10+ years old

*What is the javascript MIME type for the type attribute of a script tag? ~ 10+ years old.


Q: unable to retrieve HTML form data running on Localhost:port python I am running a simple form input on my localhost:port using socket programming.
Currently, I have a form running on my chrome, just a text box on localhost:2333, I am able to see the text box input on my wireshark like this

The input message I typed is testesest.
After which, I put the <form action="http://localhost:2333"> such that the entered form data can flow back to my localhost:port. However, my 2nd r= recv(1024)is not receiving anything.
import socket
import sys
import os

Addr = ''
PORT = 2333
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((Addr, PORT))
s.listen()

The above is the standard part.
while(1):
    try:
        print("waiting for connection")
        conn, address = s.accept()
        print("New client connected from IP address {} and port number {}".format(*address))

        received = conn.recv(1024)
        #print("Request received")

        #This is what i am hosting
        #A webpage with a form

        conn.send(b'\r\n')

        #This is the webpage content

        #The code will stuck here at recv
        print("Waiting for form input from client")
        r = conn.recv(1024)
        print(r.decode())

        print("Form input received")
        print("HTTP response sent")

    except KeyboardInterrupt:
        conn.close()
        s.close()

    conn.close()
    s.close()
    break

Can I get some help please?

A: Input data sent via GET is attached to the URI (/?work=<data>), which is sent as a new request:
import socket
import sys
import os

Addr = ''
PORT = 2333
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((Addr, PORT))
s.listen()

while (1):
    try:
        print("waiting for connection")
        conn, address = s.accept()
        print(
            "New client connected from IP address {} and port number {}".format(
                *address
            )
        )

        request = conn.recv(1024)
        print("Request received")
        method, uri, _ = request.decode().split(' ', 2)
        print(method, uri)

        #This is what i am hosting
        #A webpage with a form

        response = ""
        conn.send(b'HTTP/1.1 200 OK\r\n')
        conn.send(b'Content-Type: text/html\r\n')
        conn.send(b'Host: localhost:2333\n')
        conn.send(b'\r\n')

        if uri == '/':
            response = """
                <form action="http://localhost:2333/" method="GET">
                <input type="text" name="work"></form>
                """
        elif uri.startswith('/?work'):
            response = f"
recevied: {uri[uri.find('/?work=')+7:]}
"

        conn.send(response.encode())
        conn.send(b"\r\n")

        print("Form input received")
        #print("HTTP response sent")

    except KeyboardInterrupt:
        conn.close()
        s.close()

    #conn.close()
    #s.close()
    #break

Out:
waiting for connection
New client connected from IP address 127.0.0.1 and port number 55941
Request received
GET /?work=TestInput

recevied: TestInput

Form input received
waiting for connection
...

Note:
You might want to have a look at the protocol specs and/or use any existing library to get rid of this low level stuff.

A: Whenever we submit any form, browser makes new http request instead of using the existing connection, so you need to handle it in new http request/connection.
Another thing is, r = conn.recv(1024) is not letting the current connection close, that's why pressing enter in textfield is also not working.


Q: Using WHERE with unknown amount of OR I have a table with some integer column A.
I need to select rows where A equals 1 or 2 or 4 (for example), but i don't know how many values i need to compare. I have an array of values as input with unknown amount of values.
I tried this:
myTable.Where(x=> myArray.Contains(x.A))
but it doesn't work (i also tried Any)
Then i tried to build SQL query with foreach cycle and then use .FromSqlRaw() but it throws an exception:

'FromSqlRaw' or 'FromSqlInterpolated' was called with non-composable SQL and with a query composing over it.


Q: Performance groupBy I have a code similar to this:
df = transformation(df)
df = df.groupBy("f1").agg(agg1, agg2, agg3)
df.collect()

The aggregation functions do not contain any window (we could assume they are the F.sumof three different fields). Is there any case in which the operations in the method transformation are performed more than once if there is nothing persisted?

A: You can use the link and perform groupby operation:

*

*https://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html


Q: ERROR: aggregate function calls cannot be nested I am trying to include one more column in my following query to show the average of two columns within. I am new to SQL and PostgreSQL, but referring the following link http://www.postgresql.org/docs/9.3/interactive/index.html
select ad.col1, ad.col2, md.col3, ad.col4, mcd.col5,
       AVG(md.col3/mcd.col4) as cb
from month_date as md
 JOIN active_date as ad ON ad.col1=md.col1 AND ad.col2=md.col2
 JOIN mdata1 as mcd ON mcd.col1=md.col1 AND mcd.col2=md.col2;

but I am getting the following error while performing the same
ERROR:  aggregate function calls cannot be nested
LINE 1: ...col2,md.col3,ad.col4,mcd.col5, AVG(md.col3/m...
                                                             ^

********** Error **********

ERROR: aggregate function calls cannot be nested
SQL state: 42803
Character: 77

can anyone guide where am I doing wrong and what I need to correct to make it work.
Output needed:
col1 | col2 | col3 |col4 | col5| cb|

where cb is average column of other two columns.
Any help would be appreciated.
[EDIT]
Tried to Group By but still getting the same error, can anyone correct me what wrong I am also doing in my below query
select ad.col1, ad.col2, md.col3, ad.col4, mcd.col5,
       AVG(md.col3/mcd.col4) as cb
from month_date as md
 JOIN active_date as ad ON ad.col1=md.col1 AND ad.col2=md.col2
 JOIN mdata1 as mcd ON mcd.col1=md.col1 AND mcd.col2=md.col2 GROUP BY ad.col1,ad.col2,md.col3,ad.col4,mcd.col5;

A: To use AVG() or any sort of aggregate functions in SQL, you need to have a GROUP BY for the other columns you're displaying.
Think of it this way, when you SELECT a column, you display rows. When you show an average, you show a single output. You can't put rows and a single output together.
You'll need to try something along the lines of:
SELECT col1, col2, AVG(col3)
FROM table1
GROUP BY col1, col2

A: I created a fiddle with your example, and you can see that the query as it is works. It is probably an error in a wrapping query, store procedure or function.


Q: Observing Task exceptions within a ContinueWith There are various ways in which to observe exceptions thrown within tasks.  One of them is in a ContinueWith with OnlyOnFaulted:
var task = Task.Factory.StartNew(() =>
{
    // Throws an exception
    // (possibly from within another task spawned from within this task)
});

var failureTask = task.ContinueWith((t) =>
{
    // Flatten and loop (since there could have been multiple tasks)
    foreach (var ex in t.Exception.Flatten().InnerExceptions)
        Console.WriteLine(ex.Message);
}, TaskContinuationOptions.OnlyOnFaulted);

My question:  Do the exceptions become automatically observed once failureTask begins or do they only become observed once I 'touch' ex.Message?

A: sample
Task.Factory.StartNew(testMethod).ContinueWith(p =>
            {
                if (p.Exception != null)
                    p.Exception.Handle(x =>
                        {
                            Console.WriteLine(x.Message);
                            return false;
                        });
            });

A: They are viewed as observed once you access the Exception property.
See also AggregateException.Handle.  You can use t.Exception.Handle instead:
t.Exception.Handle(exception =>
            {
            Console.WriteLine(exception);
            return true;
            }
    );


Q: Mongodb findOne - return value I need to fetch id of user from collection 'users' by calling a function and return it's value.
fetchId = (name) => {
        User.findOne({name: name}, (err, user) => {
            return user._id;
        });
    };

But this implementation returns null. What is the way to fix it?

A: following your example, if you don't want to use promises, you can simply pass a callback from the caller and invoke the callback when you have the result since the call to mongo is asynchronous.
fetchId = (name, clb) => {
  User.findOne({name: name}, (err, user) => {
    clb(user._id);
  });
};

fetchId("John", id => console.log(id));

Otherwise you can use the promise based mechanism omitting the first callback and return the promise to the caller.
fetchId = name => {
  return User.findOne({name: name}).then(user => user.id);
};

fetchId("John")
 .then(id => console.log(id));

A: A third way is a variation of suggestion #2 in @Karim's (perfectly good) answer.  If the OP wants to code it as if results are being assigned from async code, an improvement would be to declare fetchId as async and await its result...
fetchId = async (name) => {
    return User.findOne({name: name}).then(user => user.id);
};

let someId = await fetchId("John");
console.log(id)

edit
For any method on an object -- including a property getter -- that works asynchronously, the calling code needs to be aware and act accordingly.
This tends to spread upward in your system to anything that depends on caller's callers, and so on.  We can't avoid this, and there's no syntactic fix (syntax is what the compiler sees). It's physics: things that take longer, just take longer.  We can use syntax to partially conceal the complexity, but we're stuck with the extra complexity.
Applying this to your question, say we have an object representing a User which is stored remotely by mongo. The simplest approach is to think of the in-memory user object as unready until an async fetch (findOne) operation has completed.
Under this approach, the caller has just one extra thing to remember: tell the unready user to get ready before using it.  The code below employs async/await style syntax which is the the most modern and does the most to conceal -- but not eliminate :-( -- the async complexity...
class MyMongoUser {
    // after new, this in-memory user is not ready
    constructor(name) {
        this.name = name;
        this.mongoUser = null;  // optional, see how we're not ready?
    }

    // callers must understand: before using, tell it to get ready!
    async getReady() {
        this.mongoUser = await myAsyncMongoGetter();
        // if there are other properties that are computed asynchronously, do those here, too
    }

    async myAsyncMongoGetter() {
        // call mongo
        const self = this;
        return User.findOne({name: self.name}).then(result => {
            // grab the whole remote object. see below
            self.mongoUser = result;
        });
    }

    // the remaining methods can be synchronous, but callers must
    // understand that these won't work until the object is ready
    mongoId() {
        return (this.mongoUser)? this.mongoUser._id : null;
    }

    posts() {
        return [ { creator_id: this.mongoId() } ];
    }
}

Notice, instead of just grabbing the mongo _id from the user, we put away the whole mongo object.  Unless this is a huge memory hog, we might as well have it hanging around so we can get any of the remotely stored properties.
Here's what the caller looks like...
let joe = new MyMongoUser('joe');
console.log(joe.posts()) // isn't ready, so this logs [ { creator_id: null } ];
await joe.getReady();
console.log(joe.posts()) // logs [ { creator_id: 'the mongo id' } ];


Q: Overwrite data frame value I have two data frame  df and ddff
df data frame have 3 row and 5 columns
import pandas as pd
import numpy as np
df = pd.DataFrame(np.array([[0,1,0,0,1], [1,0,0,1,0], [0,1,1,0,0]]))
df

     0   1   2   3   4
0    0   1   0   0   1
1    1   0   0   1   0
2    0   1   1   0   0

ddff data frame consist of neighbour columns of a particular columns which have 5 row and 3 column where the value of ddff data frame represent the column name of df
ddff = pd.DataFrame(np.array([[3,2,1], [4,2,3], [3,1,4], [4,1,2], [2,3,1]]))
ddff

    0   1   2
0   3   2   1
1   4   2   3
2   3   1   4
3   4   1   2
4   2   3   1

Now I need a final data frame where where df column neighbour's set to 1 (overwrite previous value)
expected output
    0  1  2  3  4
0   0  1  1  1  0
1   1  0  0  1  0
2   0  1  1  0  0

A: You can filter the relevant column numbers from ddff, and set the values in those columns in the first row equal to 1 and set the values in the remaining columns to 0:
relevant_columns = ddff.loc[0]
df.loc[0,relevant_columns] = 1
df.loc[0,df.columns[~df.columns.isin(relevant_columns)]] = 0

Output:
   0  1  2  3  4
0  0  1  1  1  0
1  1  0  0  1  0
2  0  1  1  0  0

A: You can use:
s = ddff.loc[0].values
df.loc[0] = np.where(df.loc[[0]].columns.isin(s),1,0)

>>> df

   0  1  2  3  4
0  0  1  1  1  0
1  1  0  0  1  0
2  0  1  1  0  0

Breaking it down:
>>> np.where(df.loc[[0]].columns.isin(s),1,0)
array([0, 1, 1, 1, 0])

# Before the update
>>> df.loc[0]
 0    0
1    1
2    0
3    0
4    1

# After the assignment back
0    0
1    1
2    1
3    1
4    0