问:
ListView inside Gridview
I would like to use a GridView layout, so that every item of the Gridlayout has its own ListView. I have been looking for code sample but I haven't found any. Should I use different adapter classes for the GridView and the ListView?
Thank you in advance!

Edit: I have created a GridView that displays all the some tiles, and I want every grid item to include a list, so I have added a ListView to the layout of the GridView items. Unfortunately I 'm having problems connecting the listview to the adapter.

This is the adapter of the gridView:

```<code>public class MainViewAdapter extends ArrayAdapter<Category> {
private Context mContext;
private int layoutResourceId;
private ArrayList<Category> mGridData = new ArrayList<Category>();
ArrayAdapter adapter;

public MainViewAdapter(Context mContext, int layoutResourceId, ArrayList<Category> mGridData) {
    super(mContext, layoutResourceId, mGridData);
    this.layoutResourceId = layoutResourceId;
    this.mContext = mContext;
    this.mGridData = mGridData;
}

public void setGridData(ArrayList<Category> mGridData) {
    this.mGridData = mGridData;
    notifyDataSetChanged();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    ViewHolder holder;
    String imageUrl;

    if (row == null) {
        LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new ViewHolder();
        holder.SubListView = (ListView) row.findViewById(R.id.SubList);
        holder.titleTextView = (TextView) row.findViewById(R.id.category_title);
        holder.simpleDraweeView = (SimpleDraweeView) row.findViewById(R.id.category_image);
        row.setTag(holder);
    } else {
        holder = (ViewHolder) row.getTag();
    }

    Category category = mGridData.get(position);
    Log.i("position", "" + position);
    holder.titleTextView.setText(Html.fromHtml(category.getTitle()));
    imageUrl = category.getImage();
    Log.i("image url",imageUrl );
    Uri imageUri = Uri.parse(imageUrl);
    holder.simpleDraweeView.setImageURI(imageUri);

    List SubCategories = category.getSubCateg();
    Log.i("@MainViewAdapter - SubCategories", category.getSubCateg().toString());

    //list SubCategories to ArrayList
    ArrayList<SubCategory> listOfSub = new ArrayList<>(SubCategories.size());
    listOfSub.addAll(SubCategories);
    Log.i("listOfSub",listOfSub.toString());

    //ArrayList to ListView
    holder.SubListView.setAdapter(adapter);

    return row;
}

static class ViewHolder {
    TextView titleTextView;
    SimpleDraweeView simpleDraweeView;
    ListView SubListView;
}}
</code>```

And here is the adapter of the listview:

```<code>public class SubListAdapter extends ArrayAdapter<SubCategory> {
private int layoutResourceId;
private ArrayList<SubCategory> mSubGridData = new ArrayList<SubCategory>();
ArrayAdapter adapter;

private final Context mContext;

public SubListAdapter(Context mContext, int layoutResourceId, ArrayList<SubCategory> mSubGridData) {
    super(mContext, R.layout.subcategory_item, mSubGridData);

    this.layoutResourceId = layoutResourceId;
    this.mContext = mContext;
    this.mSubGridData = mSubGridData;
}

public void setSubGridData(ArrayList<SubCategory> mSubGridData) {
    this.mSubGridData = mSubGridData;
    notifyDataSetChanged();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View row = convertView;
    SubListAdapter.ViewHolder holder;
    String imageUrl;

    if (row == null) {
        LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new ViewHolder();
        holder.SubTitleTextView = (TextView) row.findViewById(R.id.subCatItemTitle);
        row.setTag(holder);
    } else {
        holder = (SubListAdapter.ViewHolder) row.getTag();

    return rowView;
}

static class ViewHolder {
    TextView SubTitleTextView;
    ListView SubListView;
}}
</code>```

I am having some problems with the second adapter.

答:
The Answer is Yes.
and also there is another solution.

Add Relative/Linear Layout as items of GridView.

In adapter class of GridView, add subItems to in @getView()
dynamically.
but I don't recommend it because of performance. it will take too long for this type view to load.

Write what do you need then I will update to my answer for another solution (if possible)
Good Luck

Title: ListView inside Gridview

Body:
I would like to use a GridView layout, so that every item of the Gridlayout has its own ListView. I have been looking for code sample but I haven't found any. Should I use different adapter classes for the GridView and the ListView?
Thank you in advance!

Edit: I have created a GridView that displays all the some tiles, and I want every grid item to include a list, so I have added a ListView to the layout of the GridView items. Unfortunately I 'm having problems connecting the listview to the adapter.

This is the adapter of the gridView:

public class MainViewAdapter extends ArrayAdapter<Category> {
private Context mContext;
private int layoutResourceId;
private ArrayList<Category> mGridData = new ArrayList<Category>();
ArrayAdapter adapter;

public MainViewAdapter(Context mContext, int layoutResourceId, ArrayList<Category> mGridData) {
    super(mContext, layoutResourceId, mGridData);
    this.layoutResourceId = layoutResourceId;
    this.mContext = mContext;
    this.mGridData = mGridData;
}

public void setGridData(ArrayList<Category> mGridData) {
    this.mGridData = mGridData;
    notifyDataSetChanged();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    ViewHolder holder;
    String imageUrl;

    if (row == null) {
        LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new ViewHolder();
        holder.SubListView = (ListView) row.findViewById(R.id.SubList);
        holder.titleTextView = (TextView) row.findViewById(R.id.category_title);
        holder.simpleDraweeView = (SimpleDraweeView) row.findViewById(R.id.category_image);
        row.setTag(holder);
    } else {
        holder = (ViewHolder) row.getTag();
    }

    Category category = mGridData.get(position);
    Log.i("position", "" + position);
    holder.titleTextView.setText(Html.fromHtml(category.getTitle()));
    imageUrl = category.getImage();
    Log.i("image url",imageUrl );
    Uri imageUri = Uri.parse(imageUrl);
    holder.simpleDraweeView.setImageURI(imageUri);

    List SubCategories = category.getSubCateg();
    Log.i("@MainViewAdapter - SubCategories", category.getSubCateg().toString());

    //list SubCategories to ArrayList
    ArrayList<SubCategory> listOfSub = new ArrayList<>(SubCategories.size());
    listOfSub.addAll(SubCategories);
    Log.i("listOfSub",listOfSub.toString());

    //ArrayList to ListView
    holder.SubListView.setAdapter(adapter);

    return row;
}

static class ViewHolder {
    TextView titleTextView;
    SimpleDraweeView simpleDraweeView;
    ListView SubListView;
}}

And here is the adapter of the listview:

public class SubListAdapter extends ArrayAdapter<SubCategory> {
private int layoutResourceId;
private ArrayList<SubCategory> mSubGridData = new ArrayList<SubCategory>();
ArrayAdapter adapter;

private final Context mContext;

public SubListAdapter(Context mContext, int layoutResourceId, ArrayList<SubCategory> mSubGridData) {
    super(mContext, R.layout.subcategory_item, mSubGridData);

    this.layoutResourceId = layoutResourceId;
    this.mContext = mContext;
    this.mSubGridData = mSubGridData;
}

public void setSubGridData(ArrayList<SubCategory> mSubGridData) {
    this.mSubGridData = mSubGridData;
    notifyDataSetChanged();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View row = convertView;
    SubListAdapter.ViewHolder holder;
    String imageUrl;

    if (row == null) {
        LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new ViewHolder();
        holder.SubTitleTextView = (TextView) row.findViewById(R.id.subCatItemTitle);
        row.setTag(holder);
    } else {
        holder = (SubListAdapter.ViewHolder) row.getTag();

    return rowView;
}

static class ViewHolder {
    TextView SubTitleTextView;
    ListView SubListView;
}}

I am having some problems with the second adapter.


来源: stackexchange

问:
PDO prepared statement insert not working
I absolutely have no clues about why this prepared statement doesn't work returning false but without giving me any error. I've read similar questions here on StackOverflow but I didn't find any tip to solve this unknown problem.

The errors are activated

```<code>public function PDOconn() {
    try {
        return new PDO($this->getDsn(), $this->username, $this->password, [PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION]);
    } catch (PDOException $e) {
        echo "Errore di connessione al database";
        throw $e->getCode();
    }
}
</code>```

This is the PHP file that handles the AJAX request. I inserted the query into a try {} ... catch() but it actually didn't help since it doesn't report any error. execute() just returns false

```<code>/* ***** CLASSES AUTOLOAD fn ***** */
spl_autoload_register(function ($class_name) {
    require_once '../classes/' . $class_name . '.php';
});

$db     = new database();
$conn   = $db->PDOconn();

$name   = postGet::post('name');
$email  = postGet::post('email');
$commercial = postGet::post('commercial');

try {
    $stmt = $conn->prepare('INSERT INTO newsletter_subscription(name, email, commercial) VALUES(:name, :email, :commercial)');
    $stmt->execute(array(':name' => $name, ':email' => $email, ':commercial' => $commercial));
} catch (PDOException $e) {
    $return = $e->getCode();
}

header('Content-Type: application/json; charset=utf-8');
echo json_encode($return);
</code>```

The variables string $name, string $email and int $commercial are correctly passed, I printed them into the php file.

This is the table structure where subscriptorID is PRIMARY AI and email is UNIQUE

[SOLUTION] Shame on me and on my short memory but maybe it can help someone else: I had the flash that that DB user didn't have INSERT priviledges, that's why the query returned just false without any error.

答: bool $commercial is passed as integer and not boolean. Change it in your sql to boolean which is True or False

ContentLicense: CC BY-SA 3.0

Body:
I absolutely have no clues about why this prepared statement doesn't work returning false but without giving me any error. I've read similar questions here on StackOverflow but I didn't find any tip to solve this unknown problem.

The errors are activated

public function PDOconn() {
    try {
        return new PDO($this->getDsn(), $this->username, $this->password, [PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION]);
    } catch (PDOException $e) {
        echo "Errore di connessione al database";
        throw $e->getCode();
    }
}

This is the PHP file that handles the AJAX request. I inserted the query into a try {} ... catch() but it actually didn't help since it doesn't report any error. execute() just returns false

/* ***** CLASSES AUTOLOAD fn ***** */
spl_autoload_register(function ($class_name) {
    require_once '../classes/' . $class_name . '.php';
});

$db     = new database();
$conn   = $db->PDOconn();

$name   = postGet::post('name');
$email  = postGet::post('email');
$commercial = postGet::post('commercial');

try {
    $stmt = $conn->prepare('INSERT INTO newsletter_subscription(name, email, commercial) VALUES(:name, :email, :commercial)');
    $stmt->execute(array(':name' => $name, ':email' => $email, ':commercial' => $commercial));
} catch (PDOException $e) {
    $return = $e->getCode();
}

header('Content-Type: application/json; charset=utf-8');
echo json_encode($return);

The variables string $name, string $email and int $commercial are correctly passed, I printed them into the php file.

This is the table structure where subscriptorID is PRIMARY AI and email is UNIQUE

[SOLUTION] Shame on me and on my short memory but maybe it can help someone else: I had the flash that that DB user didn't have INSERT priviledges, that's why the query returned just false without any error.


问:
Table cells flushed white
Upon running the below SQL statement (which works perfectly) I've found that all tables in my database are flushed white.

Any idea as to why this happening?

```<code>        // check database for necessary updates

$update = mysql_query("SELECT * FROM rent WHERE colour='3C0'");

while($row_update = mysql_fetch_array( $update )) {

$datetime_lower   = DateTime::createFromFormat('d/m/Y', $min);
$datetime_upper   = DateTime::createFromFormat('d/m/Y', $max);
$datetime_compare = DateTime::createFromFormat('d/m/Y g:i a', $row_update['pDate']);

if ($datetime_lower < $datetime_compare && $datetime_upper > $datetime_compare) {

    // date is between do nothing

        mysql_close($update);

    } else {

    // date is not between so update

    echo "date is not between";

    $update_result = mysql_query("UPDATE rent SET colour='F0F0F0' WHERE substr(pDate, 0, 10) NOT BETWEEN $min AND $max && colour='3C0'");

    mysql_close($update_result);
}
}
</code>```

I've included a few pictures.

This is how it is meant to look like (above code omitted):

http://i51.tinypic.com/143gpef.jpg

This is how it currently looks like (above code present):

http://i54.tinypic.com/2lwm4xg.jpg

答:
Your while loop appears to go through all the results from your table. It appears that on each iteration of the loop, you check the date first in PHP, then you check the date again in your update query, and update all matching rows to F0F0F0.

I don't know why your code is changing the colour to white instead of #F0F0F0, since there is no white or fff in your code, so all I can do is suggest something to make your code more efficient.

Instead of updating all rows on each iteration of the while loop, if you have an id column (Primary Key with Auto-increment) in your rent table, you can use this value in your while loop instead of having to test the date a second time.

```<code>$update = mysql_query("SELECT * FROM rent WHERE colour='3C0'");
while($row_update = mysql_fetch_array( $update )) {
    $datetime_lower   = DateTime::createFromFormat('d/m/Y', $min);
    $datetime_upper   = DateTime::createFromFormat('d/m/Y', $max);
    $datetime_compare = DateTime::createFromFormat('d/m/Y g:i a', $row_update['pDate']);
    if ($datetime_lower < $datetime_compare && $datetime_upper > $datetime_compare) {
        // date is between do nothing
        mysql_close($update);
    } else {
        // date is not between so update
        echo "date is not between";
        $update_result = mysql_query("UPDATE rent SET colour='F0F0F0' WHERE id=" . $row_update['id'] . " && colour='3C0'");
        mysql_close($update_result);
    }
}
</code>```

Title: Table cells flushed white

Body:
Upon running the below SQL statement (which works perfectly) I've found that all tables in my database are flushed white.

Any idea as to why this happening?

        // check database for necessary updates

$update = mysql_query("SELECT * FROM rent WHERE colour='3C0'");

while($row_update = mysql_fetch_array( $update )) {

$datetime_lower   = DateTime::createFromFormat('d/m/Y', $min);
$datetime_upper   = DateTime::createFromFormat('d/m/Y', $max);
$datetime_compare = DateTime::createFromFormat('d/m/Y g:i a', $row_update['pDate']);

if ($datetime_lower < $datetime_compare && $datetime_upper > $datetime_compare) {

    // date is between do nothing

        mysql_close($update);

    } else {

    // date is not between so update

    echo "date is not between";

    $update_result = mysql_query("UPDATE rent SET colour='F0F0F0' WHERE substr(pDate, 0, 10) NOT BETWEEN $min AND $max && colour='3C0'");

    mysql_close($update_result);
}
}

I've included a few pictures.

This is how it is meant to look like (above code omitted):

http://i51.tinypic.com/143gpef.jpg

This is how it currently looks like (above code present):

http://i54.tinypic.com/2lwm4xg.jpg

Body:
Your while loop appears to go through all the results from your table. It appears that on each iteration of the loop, you check the date first in PHP, then you check the date again in your update query, and update all matching rows to F0F0F0.

I don't know why your code is changing the colour to white instead of #F0F0F0, since there is no white or fff in your code, so all I can do is suggest something to make your code more efficient.

Instead of updating all rows on each iteration of the while loop, if you have an id column (Primary Key with Auto-increment) in your rent table, you can use this value in your while loop instead of having to test the date a second time.

$update = mysql_query("SELECT * FROM rent WHERE colour='3C0'");
while($row_update = mysql_fetch_array( $update )) {
    $datetime_lower   = DateTime::createFromFormat('d/m/Y', $min);
    $datetime_upper   = DateTime::createFromFormat('d/m/Y', $max);
    $datetime_compare = DateTime::createFromFormat('d/m/Y g:i a', $row_update['pDate']);
    if ($datetime_lower < $datetime_compare && $datetime_upper > $datetime_compare) {
        // date is between do nothing
        mysql_close($update);
    } else {
        // date is not between so update
        echo "date is not between";
        $update_result = mysql_query("UPDATE rent SET colour='F0F0F0' WHERE id=" . $row_update['id'] . " && colour='3C0'");
        mysql_close($update_result);
    }
}

ContentLicense: CC BY-SA 2.5


问:
Infinite scrolling with will_paginate. Issue removing element
I'm implementing infinite scroll with will_paginate and ajax. Whenever I press the 'load more' elements, it brings me the next 4 elements in the collection. At the moment, everything is ok. But when I remove some element of some page, the next page has been already established in the 'load more' button; because of this, the next time I press the 'load more' button, one element is skipped. Does anybody know how can I solve this? (Sorry about my english)</p>

答:
Pagination gems don't work very well in your use case. </p>

<p>The easiest way to solve this is: if you have a list of elements ordered by e.g. id, on your next page request send the id of the last element on the current page, and use it to offset the next page. </p>

Body:
Pagination gems don't work very well in your use case.

The easiest way to solve this is: if you have a list of elements ordered by e.g. id, on your next page request send the id of the last element on the current page, and use it to offset the next page.


问:
How to extract value
i have called following data from the quantopian api and received following data:

```<code>{Equity(25600, symbol=u'LPHI', asset_name=u'LIFE PARTNERS HOLDINGS INC', exchange=u'NASDAQ', start_date=Timestamp('2003-10-21 00:00:00+0000', tz='UTC'), end_date=Timestamp('2015-03-27 00:00:00+0000', tz='UTC'), first_traded=None, auto_close_date=Timestamp('2015-04-01 00:00:00+0000', tz='UTC'), exchange_full=u'NASDAQ GLOBAL SELECT MARKET'): [Event({'status': 0, 'created': Timestamp('2010-04-01 13:31:00+0000', tz='UTC'), 'limit_reached': False, 'stop': None, 'reason': None, 'stop_reached': False, 'commission': 0, 'amount': 8923, 'limit': None, 'sid': Equity(25600, symbol=u'LPHI', asset_name=u'LIFE PARTNERS HOLDINGS INC', exchange=u'NASDAQ', start_date=Timestamp('2003-10-21 00:00:00+0000', tz='UTC'), end_date=Timestamp('2015-03-27 00:00:00+0000', tz='UTC'), first_traded=None, auto_close_date=Timestamp('2015-04-01 00:00:00+0000', tz='UTC'), exchange_full=u'NASDAQ GLOBAL SELECT MARKET'), 'dt': Timestamp('2010-04-01 13:31:00+0000', tz='UTC'), 'id': 'effc428d025c4bf69ec59cd6f225d8a7', 'filled': 0})]}
</code>```

Now i only need the first number of the data. In this case it is the 25600
Can you guys let me know how i can extract it ?

Thanks a lot and kind regards

答:
A dirty way to do this is

```<code>s = a.find('Equity') # where a is your string you get from quantopian

e = a.find('symbol')

print(a[s+7:e-2])
</code>```

I find the indices of Equity and Symbol and then just get whatever is in the middle using the slicing operator after appropriate indexing.

you can cast the return value from quantopian to a string by using str(response) to perform the indexing

Title: How to extract value

Body:
i have called following data from the quantopian api and received following data:

{Equity(25600, symbol=u'LPHI', asset_name=u'LIFE PARTNERS HOLDINGS INC', exchange=u'NASDAQ', start_date=Timestamp('2003-10-21 00:00:00+0000', tz='UTC'), end_date=Timestamp('2015-03-27 00:00:00+0000', tz='UTC'), first_traded=None, auto_close_date=Timestamp('2015-04-01 00:00:00+0000', tz='UTC'), exchange_full=u'NASDAQ GLOBAL SELECT MARKET'): [Event({'status': 0, 'created': Timestamp('2010-04-01 13:31:00+0000', tz='UTC'), 'limit_reached': False, 'stop': None, 'reason': None, 'stop_reached': False, 'commission': 0, 'amount': 8923, 'limit': None, 'sid': Equity(25600, symbol=u'LPHI', asset_name=u'LIFE PARTNERS HOLDINGS INC', exchange=u'NASDAQ', start_date=Timestamp('2003-10-21 00:00:00+0000', tz='UTC'), end_date=Timestamp('2015-03-27 00:00:00+0000', tz='UTC'), first_traded=None, auto_close_date=Timestamp('2015-04-01 00:00:00+0000', tz='UTC'), exchange_full=u'NASDAQ GLOBAL SELECT MARKET'), 'dt': Timestamp('2010-04-01 13:31:00+0000', tz='UTC'), 'id': 'effc428d025c4bf69ec59cd6f225d8a7', 'filled': 0})]}

Now i only need the first number of the data. In this case it is the 25600
Can you guys let me know how i can extract it ?

Thanks a lot and kind regards

Body:
A dirty way to do this is

s = a.find('Equity') # where a is your string you get from quantopian

e = a.find('symbol')

print(a[s+7:e-2])

I find the indices of Equity and Symbol and then just get whatever is in the middle using the slicing operator after appropriate indexing.

you can cast the return value from quantopian to a string by using str(response) to perform the indexing


问:
Python Issue Making a Game
Im a new python learner and Im reading Zed Shaw book called :
Learn python the hardway
Im doing very well at following the instructions and doing the study drills as well .
Recently I've tried to make a little game by myself but i got stuck and i need a little help
this is my script :

```<code>from sys import exit

def starting():
    print "Welcome to the abyss of dark"
    print "The game is about choosing"
    print "if you lose you die if you win you live"

    choose_door = raw_input("> ")

    if "1" in choose_door or "door 1" or "D1" or "d1":
        no_weapon()
    elif "2" in choose_door or "door 2" or "D2" or "d2":
        Weapon_room()
    elif "3" in choose_door or "door 3" or "D3" or "d3":
        shortcut()
    elif "4" in choose_door or "door 4" or "D4" or "d4":
        princess_room()
    elif "5" in choose_door or "door 5" or "D5" or "d5":
        princess_room()
    elif "6" in choose_door or "door 6" or "D6" or "d6":
        gards_room()
    else:
        "7" in choose_door or "door7" or "D7" or "d7"
        suicide_room()

start()

def map():
    print """"
    |------------------------------------------------------------------------------------|
    |   shortcut     D|room of the | room of the|                                        |
    |     to D4      O|princess    | gards      | S U I C I D E      R O  O M            |
    |                O|            |            |                                        |
    |                R|            |            |                                        |
    |                4|            |            |                                        |
    |-----DOOR 3---|------DOOR 5-------DOOR 6---------------------DOOR 7----------------|
    |Weapon ROOM |                                                                      |
    |            | DOOR 2               YOUR                                            |
    |            |                            ARE                                       |
    |            |                                 HERE                                 |
    |------------|                                                                      |
    |No Weapon   | DOOR 1                                                               |
    |            |                                                                      |
    |------------|------------------------------------------------------------------------

    """
    start()

def no_weapon():
    print "You've choosed to continue with no Weapons"
    print "What a BRAVE PLAYER!"
    print "Choose your door"
    print "3 , 5 , 6 , 7"
    no_weapon_door = raw_input("> ")
    if no_weapon_door == "3":
        shortcut
    elif no_weapon_door == "5":
        princess_room
    elif no_weapon_door == "6":
        gards_room
    else:
        suicide_room

def Weapon_room():
    print "You are armed now"
    print "Which door you choose type just the number"
    print "Door 3 or Door 4"
    Weapon_room_door = raw_input("> ")
    if Weapon_room_door == "3":
        shortcut
    else:
        princess_room

def shortcut():
    princess_room

def princess_room():
    print "You won"

def gards_room():
    print "fight with gards"
    print "Yes or No"
    fighting = raw_input("> ")
    if fighing == "Yes":
            princess_room
    else:
        fighting == "No"
        lost
def suicide_room():
    print "Die in peace"
    lost

def lost():
    print "You lost"
    print "If you want to reapeat Press R if you wanna exit tye E"
    losing = raw_input ("> ")
    if losing == "R":
        start()
    else:
        exit()
</code>```

for me i think everything i written as it should be but when i run my script i get an error :

```Traceback (most recent call last):
  File "newgame.py", line 26, in
    start()
NameError: name 'start' is not defined```

couldn't figure out
Help me Please and thank you

答: You should probably fix the formatting of your code, but I believe you meant to put starting() instead of start() because you don't have a method named start().</p>

Title: Python Issue Making a Game

Body:
Im a new python learner and Im reading Zed Shaw book called :
Learn python the hardway
Im doing very well at following the instructions and doing the study drills as well .
Recently I've tried to make a little game by myself but i got stuck and i need a little help
this is my script :

from sys import exit

def starting():
    print "Welcome to the abyss of dark"
    print "The game is about choosing"
    print "if you lose you die if you win you live"

    choose_door = raw_input("> ")

    if "1" in choose_door or "door 1" or "D1" or "d1":
        no_weapon()
    elif "2" in choose_door or "door 2" or "D2" or "d2":
        Weapon_room()
    elif "3" in choose_door or "door 3" or "D3" or "d3":
        shortcut()
    elif "4" in choose_door or "door 4" or "D4" or "d4":
        princess_room()
    elif "5" in choose_door or "door 5" or "D5" or "d5":
        princess_room()
    elif "6" in choose_door or "door 6" or "D6" or "d6":
        gards_room()
    else:
        "7" in choose_door or "door7" or "D7" or "d7"
        suicide_room()

start()

def map():
    print """"
    |------------------------------------------------------------------------------------|
    |   shortcut     D|room of the | room of the|                                        |
    |     to D4      O|princess    | gards      | S U I C I D E      R O  O M            |
    |                O|            |            |                                        |
    |                R|            |            |                                        |
    |                4|            |            |                                        |
    |-----DOOR 3---|------DOOR 5-------DOOR 6---------------------DOOR 7----------------|
    |Weapon ROOM |                                                                      |
    |            | DOOR 2               YOUR                                            |
    |            |                            ARE                                       |
    |            |                                 HERE                                 |
    |------------|                                                                      |
    |No Weapon   | DOOR 1                                                               |
    |            |                                                                      |
    |------------|------------------------------------------------------------------------

    """
    start()

def no_weapon():
    print "You've choosed to continue with no Weapons"
    print "What a BRAVE PLAYER!"
    print "Choose your door"
    print "3 , 5 , 6 , 7"
    no_weapon_door = raw_input("> ")
    if no_weapon_door == "3":
        shortcut
    elif no_weapon_door == "5":
        princess_room
    elif no_weapon_door == "6":
        gards_room
    else:
        suicide_room

def Weapon_room():
    print "You are armed now"
    print "Which door you choose type just the number"
    print "Door 3 or Door 4"
    Weapon_room_door = raw_input("> ")
    if Weapon_room_door == "3":
        shortcut
    else:
        princess_room

def shortcut():
    princess_room

def princess_room():
    print "You won"

def gards_room():
    print "fight with gards"
    print "Yes or No"
    fighting = raw_input("> ")
    if fighing == "Yes":
            princess_room
    else:
        fighting == "No"
        lost
def suicide_room():
    print "Die in peace"
    lost

def lost():
    print "You lost"
    print "If you want to reapeat Press R if you wanna exit tye E"
    losing = raw_input ("> ")
    if losing == "R":
        start()
    else:
        exit()

for me i think everything i written as it should be but when i run my script i get an error :

Traceback (most recent call last):
  File "newgame.py", line 26, in
    start()
NameError: name 'start' is not defined

couldn't figure out
Help me Please and thank you


问:
Bootstrap 3: Nested tabs disappear when another tab is made active
https://jsfiddle.net/Miega/Lmn1490b/

I'm attempting to program a nested tab display using Bootstrap and some extra jQuery. Whenever I try to select another item inside the "Unit Selection" category, the content vanishes. However, the content DOES load if you switch over to another tab that isn't nested.

The jQuery code in question:

```<code>$('#unitTabs').on('click', 'a[data-toggle="tab"]', function(e) {
      e.preventDefault();

      var $link = $(this);

      if (!$link.parent().hasClass('active')) {

        //remove active class from other tab-panes
        $('.tab-content:not(.' + $link.attr('href').replace('#','') + ') .tab-pane').removeClass('active');

        // click first submenu tab for active section
        $('a[href="' + $link.attr('href') + '_all"][data-toggle="tab"]').click();

        // activate tab-pane for active section
        $('.tab-content.' + $link.attr('href').replace('#','') + ' .tab-pane:first').addClass('active');
      }
});
</code>```

Any help is greatly appreciated.

答:
```<code>$('#unitTabs').on('click', 'a[data-toggle="tab"]', function(e) {
  e.preventDefault();

  var $link = $(this);
  var $parent = $link.parent();
  if (!$parent.hasClass('active')) {
    $parent.addClass('active');
    $parent.siblings().removeClass('active')

    $('#unit .tab-pane').removeClass('active')
    $($link.attr('href')).addClass('active')
  }
});
</code>```

JSFiddle

Body:
https://jsfiddle.net/Miega/Lmn1490b/

I'm attempting to program a nested tab display using Bootstrap and some extra jQuery. Whenever I try to select another item inside the "Unit Selection" category, the content vanishes. However, the content DOES load if you switch over to another tab that isn't nested.

The jQuery code in question:

$('#unitTabs').on('click', 'a[data-toggle="tab"]', function(e) {
      e.preventDefault();

      var $link = $(this);

      if (!$link.parent().hasClass('active')) {

        //remove active class from other tab-panes
        $('.tab-content:not(.' + $link.attr('href').replace('#','') + ') .tab-pane').removeClass('active');

        // click first submenu tab for active section
        $('a[href="' + $link.attr('href') + '_all"][data-toggle="tab"]').click();

        // activate tab-pane for active section
        $('.tab-content.' + $link.attr('href').replace('#','') + ' .tab-pane:first').addClass('active');
      }
});

Any help is greatly appreciated.

Body:
$('#unitTabs').on('click', 'a[data-toggle="tab"]', function(e) {
  e.preventDefault();

  var $link = $(this);
  var $parent = $link.parent();
  if (!$parent.hasClass('active')) {
    $parent.addClass('active');
    $parent.siblings().removeClass('active')

    $('#unit .tab-pane').removeClass('active')
    $($link.attr('href')).addClass('active')
  }
});

JSFiddle


问:
How to create array of object in node.js
My Class look like this:

```<code>var Coin = {
    _id: null,
    createGame: function(id) {
     this._id = id;
    },
    start: function() {

    }
};
</code>```

I'm trying to create an array of objects, but I can create only one.
Could someone tell what i'm doing wrong?

I create array like this:

```<code>CoinArray = [];
CoinArray['123'] = new Coin.createGame(123);
CoinArray['333'] = new Coin.createGame(333);
CoinArray['333'].start
</code>```

At the end I want to have array with object and for example I will take first el of array, and execute other method from Coin class.

答:
```<code>class Coin {
  constructor(id) {
    this._id = id;
  }
  start() {
    console.log('starting');
  }
}

CoinArray = [];
CoinArray['123'] = new Coin(123);
CoinArray['333'] = new Coin(333);
CoinArray['123'].start();
</code>```

Also i would suggest managing id's that way:

```<code>let id = 0;
class Coin {
  constructor() {
    this._id = id++;
  }
  start() {
    console.log('starting');
  }
}

CoinArray = [];
CoinArray.push(new Coin());
CoinArray.push(new Coin());
CoinArray[0].start();
</code>```

Body:
My Class look like this:

var Coin = {
    _id: null,
    createGame: function(id) {
     this._id = id;
    },
    start: function() {

    }
};

I'm trying to create an array of objects, but I can create only one.
Could someone tell what i'm doing wrong?

I create array like this:

CoinArray = [];
CoinArray['123'] = new Coin.createGame(123);
CoinArray['333'] = new Coin.createGame(333);
CoinArray['333'].start

At the end I want to have array with object and for example I will take first el of array, and execute other method from Coin class.

Body:
class Coin {
  constructor(id) {
    this._id = id;
  }
  start() {
    console.log('starting');
  }
}

CoinArray = [];
CoinArray['123'] = new Coin(123);
CoinArray['333'] = new Coin(333);
CoinArray['123'].start();

Also i would suggest managing id's that way:

let id = 0;
class Coin {
  constructor() {
    this._id = id++;
  }
  start() {
    console.log('starting');
  }
}

CoinArray = [];
CoinArray.push(new Coin());
CoinArray.push(new Coin());
CoinArray[0].start();


答:
Using global vars is the only way to communicate data between your main program loop and interrupt handlers.

While writing this response I've spotted that you should really consider using signed values in your sine tables.  Signed addition is needed for the maths to work properly.

This line:

```<code>OCR0A = values[val];
</code>```

can only produce a monophonic sound.

You are on the right path with this:

```<code>int values[7] = {sin_C[C],sin_D[D],sin_E[E],sin_F[F],sin_G[G],sin_A[A],sin_B[B]};
</code>```

though.

So, yes, another global var should do the trick:

```<code>unsigned char notes_played;  // bits 0-7 map C-D notes
</code>```

And in your ISR:

```<code>ISR(TIMER0_COMPA_vect)
{
    //...

    int values[7] = {sin_C[C],sin_D[D],sin_E[E],sin_F[F],sin_G[G],sin_A[A],sin_B[B]};

    int ocr_value = 0;
    for (unsigned char mask = 1, i = 0; mask < 0x80; mask <<= 1, ++i)
    {
        if (mask & note_played)
           ocr_value += (signed char)(values[i] - 16);  // hints that using signed values
                                                        // in sine tables may be more
                                                        // efficient.
    }

    // need to 'clip' OCR here?
    if (ocr_value < -(OCR_RANGE / 2))
        ocr_value = -(OCR_RANGE / 2);
    if (ocr_value > (OCR_RANGE / 2))
        ocr_value = (OCR_RANGE / 2);

    OCRA0 = (unsigned char)((ocr_value + OCR_ZERO) & 0xFF);
}
</code>```

I've added OCR_RANGE and OCR_ZERO, which controls to the AC voltage range of the filtered output. range: 0-255.  (OCR_RANGE = 256 may overflow).  OCR_ZERO controls the mid-range point (typically 127), you should set the initial OCRA0 to OCR_ZERO in setup().

One final note.  When declaring your sine tables:

```<code>static uint8_t sin_B[65] =       //...  This gets store in data space, which is limited
static const uint8_t sin_B[65] = //... This gets stored on flash, which has plenty of room.
</code>```

Making the sine tables as big as possible, and the interrupt as fast as possible can really make a big difference in sound quality.

Title: Attiny85 using global variables in timer interrupts

Body:
I'm pretty new to Arduino programming. I have however been coding for a while. I'm currently trying to code a polyphonic piano using the Arduino IDE and a Digispark Attiny85 development board. To play multiple notes at once I'm using sine tables and fast PWM. This is my code:

int val = 1;
uint8_t C = 0;
uint8_t D = 0;
uint8_t E = 0;
uint8_t F = 0;
uint8_t G = 0;
uint8_t A = 0;
uint8_t B = 0;

static uint8_t  sin_C[123] = {16,16,17,18,19,20,20,21,22,23,23,24,25,25,26,27,27,28,28,29,29,30,30,30,31,31,31,31,31,31,31,31,31,31,31,31,31,31,30,30,30,29,29,28,28,27,27,26,25,25,24,23,23,22,21,20,20,19,18,17,16,16,15,14,13,12,11,11,10,9,8,8,7,6,6,5,4,4,3,3,2,2,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,3,3,4,4,5,6,6,7,8,8,9,10,11,11,12,13,14,15,15};
static uint8_t sin_D[110] = {16,16,17,18,19,20,21,22,23,23,24,25,26,26,27,28,28,29,29,30,30,30,31,31,31,31,31,31,31,31,31,31,31,31,30,30,30,29,29,28,27,27,26,25,25,24,23,22,21,20,20,19,18,17,16,15,14,13,12,11,11,10,9,8,7,6,6,5,4,4,3,2,2,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,3,3,4,5,5,6,7,8,8,9,10,11,12,13,14,15,15};
static uint8_t sin_E[98] = {16,17,18,19,20,21,22,23,23,24,25,26,27,27,28,29,29,30,30,31,31,31,31,31,31,31,31,31,31,31,30,30,30,29,28,28,27,26,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,5,4,3,3,2,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,2,2,3,4,4,5,6,7,8,8,9,10,11,12,13,14,15};
static uint8_t sin_F[92] = {16,17,18,19,20,21,22,23,24,25,26,27,27,28,29,29,30,30,31,31,31,31,31,31,31,31,31,31,30,30,30,29,28,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,3,2,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,2,2,3,4,4,5,6,7,8,9,10,11,12,13,14,15};
static uint8_t sin_G[82] = {16,17,18,19,20,22,23,24,25,26,27,28,28,29,30,30,31,31,31,31,31,31,31,31,31,30,30,29,29,28,27,26,25,24,23,22,21,20,19,17,16,15,14,12,11,10,9,8,7,6,5,4,3,2,2,1,1,0,0,0,0,0,0,0,0,0,1,1,2,3,3,4,5,6,7,8,9,11,12,13,14,15};
static uint8_t sin_A[73] = {16,17,18,20,21,22,24,25,26,27,28,29,29,30,31,31,31,31,32,31,31,31,31,30,29,29,28,27,26,25,24,22,21,20,18,17,16,14,13,11,10,9,7,6,5,4,3,2,2,1,0,0,0,0,0,0,0,0,0,1,2,2,3,4,5,6,7,9,10,11,13,14,15};
static uint8_t sin_B[65] = {16,17,19,20,22,23,24,26,27,28,29,30,30,31,31,31,32,31,31,31,30,30,29,28,27,26,24,23,22,20,19,17,16,14,12,11,9,8,7,5,4,3,2,1,1,0,0,0,0,0,0,0,1,1,2,3,4,5,7,8,9,11,12,14,15};

ISR(TIMER0_COMPA_vect) {
  C++;
  D++;
  E++;
  F++;
  G++;
  A++;
  B++;
  if(C>122) {
    C = 0;
  }
  if(D>109) {
    D = 0;
  }
  if(E>97) {
    E = 0;
  }
  if(F>91) {
    F = 0;
  }
  if(G>81) {
    G = 0;
  }
  if(A>72) {
    A = 0;
  }
  if(B>64) {
    B = 0;
  }
  int values[7] = {sin_C[C],sin_D[D],sin_E[E],sin_F[F],sin_G[G],sin_A[A],sin_B[B]};
  OCR0A = values[val];
}

void setup() {
  DDRB |= (1<<PB0);
  TCNT0 = 0;
  TCCR0A=0;
  TCCR0B=0;
  TCCR0A |=(1<<COM0A1);
  TCCR0A |=(1<<WGM01);
  TCCR0A |=(1<<WGM00);
  TCCR0B |= (1 << CS00);
  OCR0A=254;
  TIMSK |= (1<<OCIE0A);
}

void loop() {
}

Currently I'm not able to use a variable to control what note I should play, i.e this line doesn't work even though it compiles:

OCR0A = values[val];

where val is a global variable that I set.

I'm wondering if there is a certain way to do this or to achieve the same effect as if I substitute the line

OCR0A = values[1] + values[3] + values[5];

for the previously mentioned one the Attiny85 outputs a D chord like it should. However I want the notes to be controlled by buttons so I need to be able to change them as the program is running and a global variable is the only way I can think of doing that. Any solutions would be much appreciated.

Body:
Using global vars is the only way to communicate data between your main program loop and interrupt handlers.

While writing this response I've spotted that you should really consider using signed values in your sine tables.  Signed addition is needed for the maths to work properly.

This line:

OCR0A = values[val];

can only produce a monophonic sound.

You are on the right path with this:

int values[7] = {sin_C[C],sin_D[D],sin_E[E],sin_F[F],sin_G[G],sin_A[A],sin_B[B]};

though.

So, yes, another global var should do the trick:

unsigned char notes_played;  // bits 0-7 map C-D notes

And in your ISR:

ISR(TIMER0_COMPA_vect)
{
    //...

    int values[7] = {sin_C[C],sin_D[D],sin_E[E],sin_F[F],sin_G[G],sin_A[A],sin_B[B]};

    int ocr_value = 0;
    for (unsigned char mask = 1, i = 0; mask < 0x80; mask <<= 1, ++i)
    {
        if (mask & note_played)
           ocr_value += (signed char)(values[i] - 16);  // hints that using signed values
                                                        // in sine tables may be more
                                                        // efficient.
    }

    // need to 'clip' OCR here?
    if (ocr_value < -(OCR_RANGE / 2))
        ocr_value = -(OCR_RANGE / 2);
    if (ocr_value > (OCR_RANGE / 2))
        ocr_value = (OCR_RANGE / 2);

    OCRA0 = (unsigned char)((ocr_value + OCR_ZERO) & 0xFF);
}

I've added OCR_RANGE and OCR_ZERO, which controls to the AC voltage range of the filtered output. range: 0-255.  (OCR_RANGE = 256 may overflow).  OCR_ZERO controls the mid-range point (typically 127), you should set the initial OCRA0 to OCR_ZERO in setup().

One final note.  When declaring your sine tables:

static uint8_t sin_B[65] =       //...  This gets store in data space, which is limited
static const uint8_t sin_B[65] = //... This gets stored on flash, which has plenty of room.

Making the sine tables as big as possible, and the interrupt as fast as possible can really make a big difference in sound quality.


问:
No templates in Visual Studio 2017
After a Visual Studio 2017 (RC) installation from scratch, I can't find a standard list of templates. I'm specifically interested in the Console Application (C#) template and the Windows Form (C#) template. I'm pretty sure I'm missing one of the Individual Components. I'm not sure which one is supposed to be installed and I don't want to install all of them.

Please see my list with components installed.

答:
My personal experience was that I had installed the Team Foundation Server client for 2017 first (was using it as a Proof of Concept for our QA team, while I was still using VS2015), then followed it up with Installing Visual Studio 2017 later to begin development.

What I ended up with on my Start Menu was a Visual Studio 2017 and a Visual Studio 2017 (2). The Visual Studio 2017 (2) had all the templates I was missing. Following the steps found in the First answer to this question (which were clear and easy to follow) did not fix my issue.  I had thought that launching the client would upgrade to the Development Client, but it did not. I renamed it to Visual Studio Professional, and now have everything I need. Not sure if this happens to anyone else, but it was what happened to me, so I hope this helps someone.

Title: No templates in Visual Studio 2017


问:
I am unable to get value from div tag
```<code><!DOCTYPE html>
<html>
<body>

<p>Write something in the text field to trigger a function.</p>

<div id="myInput" oninput="myFunction()" contenteditable>100</div>

<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementById("myInput").value;
    document.getElementById("demo").innerHTML = "You wrote: " + x;
}
</script>

</body>
</html>
</code>```

Please give me some solution on this. In output i get value for x is "undefined".

答:
Change:

```<code><div id="myInput" oninput="myFunction()" contenteditable>100</div>
</code>```

To:

```<code><input id="myInput" oninput="myFunction()"></input>
</code>```

Title: I am unable to get value from div tag

Body:
<!DOCTYPE html>

Write something in the text field to trigger a function.

100

Please give me some solution on this. In output i get value for x is "undefined".

Body:
Change:

<div id="myInput" oninput="myFunction()" contenteditable>100</div>

To:

<input id="myInput" oninput="myFunction()"></input>


问:
Reading multiple txt files and saving them into one numpy array: how to concatenate numpy arrays
a) Here's my try. It works but I'm wondering if I can do it without if else conditions and indexing - more pythonic way.   </p>

```<code>sensor_files = ['file1.csv', 'file2.csv']

for idx,sensor_file in enumerate(sensor_files):
    with open(file, 'rb') as f:
        clean_lines = (line.replace(b';',b',')
        sensors = np.genfromtxt(clean_lines, dtype=int, delimiter=',')
        if idx == 0:
            acc_measurements = sensors
        else:
            acc_measurements = np.concatenate((acc_measurements, sensors))
</code>```

答:
You may create an empty array with required columns and then in cycle use numpy.vstack.

Like:

```<code> arr = numpy.array([[]]*5)   ## real length of sensors
 for idx,sensor_file in enumerate(sensor_files):
     ....
     arr = numpy.vstack((arr, sensors))
</code>```

Body:
a) Here's my try. It works but I'm wondering if I can do it without if else conditions and indexing - more pythonic way.

sensor_files = ['file1.csv', 'file2.csv']

for idx,sensor_file in enumerate(sensor_files):
    with open(file, 'rb') as f:
        clean_lines = (line.replace(b';',b',')
        sensors = np.genfromtxt(clean_lines, dtype=int, delimiter=',')
        if idx == 0:
            acc_measurements = sensors
        else:
            acc_measurements = np.concatenate((acc_measurements, sensors))

Body:
You may create an empty array with required columns and then in cycle use numpy.vstack.

Like:

 arr = numpy.array([[]]*5)   ## real length of sensors
 for idx,sensor_file in enumerate(sensor_files):
     ....
     arr = numpy.vstack((arr, sensors))


问:
I cannot get pagify.js to work
I want to use the pagify.js plugin

I've downloaded the repo from Github and I'm aware of the steps I have to take in order to add this to my own site.

However just to see how it works, I've opened the index page on chrome and inspected the page and errors have already occurred (see image).

What's causing this error

How would I successfully add this plugin to my site, the steps don't seem to be working for me.

Many thanks.

答:
Hey it looks like your having an issue similar to the one described on this page.

"Cross origin requests are only supported for HTTP." error when loading a local file

You're using either file:// or C:/, which stays true to the error message as they are not http://

So you can either install a webserver in your local PC or upload the files to a server somewhere, such as DO or AWS.

Title: I cannot get pagify.js to work


问:
Modify RTMP inside FFmpeg's libavformat
I need to send a Stream Dry message to the RTMP server my application is streaming to. I created a new function declared on avformat.h and defined on rtmpproto.c which contains the following:

```<code>int av_send_rtmp_streamdry(struct URLContext *s) {
RTMPContext *rt = s->priv_data;
PutByteContext pbc;
RTMPPacket spkt = { 0 };
int ret;
uint8_t *p;

av_log(s, AV_LOG_INFO, "%p", rt);

// Create StreamDry packet
// The packet type is the same as the PING response type. From RTMP spec,
// packet type 4 belongs to User Control Messages.
// The packet size is Event Type (16 bits / 2 bytes) + Stream ID (4 bytes)
if ((ret = ff_rtmp_packet_create(&spkt, RTMP_NETWORK_CHANNEL,
                                 RTMP_PT_PING, 0, 6)) < 0) {
    av_log(s, AV_LOG_ERROR, "Unable to create response packet\n");
    return ret;
}
p = spkt.data;
bytestream2_init_writer(&pbc, spkt.data, spkt.size);
bytestream2_put_be16(&pbc, 2);          // 2 -> Stream Dry
bytestream2_put_be32(&pbc, rt->stream_id);
spkt.size = p - spkt.data;
ret = ff_rtmp_packet_write(rt->stream, &spkt, rt->out_chunk_size,
                           &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);

if(ret != 0){
    av_log(NULL, AV_LOG_ERROR, "Stream Dry packet could not be sent");
    return ret;
}

ff_rtmp_packet_destroy(&spkt);

return 0;}
</code>```

I get URLContext via static_cast<URLContext*>(ofmt_ctx->pb->opaque) where ofmt is my AVFormatContext.
I call this method directly from my program but the problem is the s->priv_data content hardly ever is a valid pointer.

How can I implement this?

答:
Finally I could implement that function. The problem was a casting issue trying to get the RTMPContext from the AVFormatContext.

AVFormatContext field 'pb' contains a AVIOContext*.

AVIOContext field 'opaque' contains a void*, but in my case (I don't know if it is always like this) is a AVIOInternal*. The AVIOInternal contains the URLContext* I need but since it is defined on 'aviobuf.c' file I cannot access it but it only contains a single field. So the solution is to bypass the AVIOInternal struct casting the 'opaque' field from AVIOContext to URLContext**.
So the following code is the solution:

```<code>AVIOContext *io = output->pb;
URLContext *url = *((URLContext**)(io->opaque));
RTMPContext *rt =(RTMPContext*)(url->priv_data);
</code>```

EDIT: This is the complete working code.

```<code>int av_send_rtmp_streamdry(AVFormatContext *output) {
    AVIOContext *io = output->pb;
    URLContext *url = *((URLContext**)(io->opaque));
    RTMPContext *rt =(RTMPContext*)(url->priv_data);
    PutByteContext pbc;
    RTMPPacket spkt = { 0 };
    int ret;
    uint8_t *p;

    // Create StreamDry packet
    // The packet type is the same as the PING response type. From RTMP spec,
    // packet type 4 belongs to User Control Messages.
    // The packet size is Event Type (16 bits / 2 bytes) + Stream ID (4 bytes)
    if ((ret = ff_rtmp_packet_create(&spkt, RTMP_NETWORK_CHANNEL,
                                     RTMP_PT_PING, 0, 6)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Unable to create response packet\n");
        return ret;
    }
    bytestream2_init_writer(&pbc, spkt.data, spkt.size);
    bytestream2_put_be16(&pbc, 2);          // 2 -> Stream Dry
    bytestream2_put_be32(&pbc, rt->stream_id);
    ret = ff_rtmp_packet_write(rt->stream, &spkt, rt->out_chunk_size,
                               &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);
    ff_rtmp_packet_destroy(&spkt);

    if(ret < 0){
        av_log(NULL, AV_LOG_ERROR, "Stream Dry packet could not be sent");
        return ret;
    }

    return 0;
}
</code>```

Title: Modify RTMP inside FFmpeg's libavformat

Body:
I need to send a Stream Dry message to the RTMP server my application is streaming to. I created a new function declared on avformat.h and defined on rtmpproto.c which contains the following:

int av_send_rtmp_streamdry(struct URLContext *s) {
RTMPContext *rt = s->priv_data;
PutByteContext pbc;
RTMPPacket spkt = { 0 };
int ret;
uint8_t *p;

av_log(s, AV_LOG_INFO, "%p", rt);

// Create StreamDry packet
// The packet type is the same as the PING response type. From RTMP spec,
// packet type 4 belongs to User Control Messages.
// The packet size is Event Type (16 bits / 2 bytes) + Stream ID (4 bytes)
if ((ret = ff_rtmp_packet_create(&spkt, RTMP_NETWORK_CHANNEL,
                                 RTMP_PT_PING, 0, 6)) < 0) {
    av_log(s, AV_LOG_ERROR, "Unable to create response packet\n");
    return ret;
}
p = spkt.data;
bytestream2_init_writer(&pbc, spkt.data, spkt.size);
bytestream2_put_be16(&pbc, 2);          // 2 -> Stream Dry
bytestream2_put_be32(&pbc, rt->stream_id);
spkt.size = p - spkt.data;
ret = ff_rtmp_packet_write(rt->stream, &spkt, rt->out_chunk_size,
                           &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);

if(ret != 0){
    av_log(NULL, AV_LOG_ERROR, "Stream Dry packet could not be sent");
    return ret;
}

ff_rtmp_packet_destroy(&spkt);

return 0;}

I get URLContext via static_cast<URLContext*>(ofmt_ctx->pb->opaque) where ofmt is my AVFormatContext.
I call this method directly from my program but the problem is the s->priv_data content hardly ever is a valid pointer.

How can I implement this?

Body:
Finally I could implement that function. The problem was a casting issue trying to get the RTMPContext from the AVFormatContext.

AVFormatContext field 'pb' contains a AVIOContext*.

AVIOContext field 'opaque' contains a void*, but in my case (I don't know if it is always like this) is a AVIOInternal*. The AVIOInternal contains the URLContext* I need but since it is defined on 'aviobuf.c' file I cannot access it but it only contains a single field. So the solution is to bypass the AVIOInternal struct casting the 'opaque' field from AVIOContext to URLContext**.
So the following code is the solution:

AVIOContext *io = output->pb;
URLContext *url = *((URLContext**)(io->opaque));
RTMPContext *rt =(RTMPContext*)(url->priv_data);

EDIT: This is the complete working code.

int av_send_rtmp_streamdry(AVFormatContext *output) {
    AVIOContext *io = output->pb;
    URLContext *url = *((URLContext**)(io->opaque));
    RTMPContext *rt =(RTMPContext*)(url->priv_data);
    PutByteContext pbc;
    RTMPPacket spkt = { 0 };
    int ret;
    uint8_t *p;

    // Create StreamDry packet
    // The packet type is the same as the PING response type. From RTMP spec,
    // packet type 4 belongs to User Control Messages.
    // The packet size is Event Type (16 bits / 2 bytes) + Stream ID (4 bytes)
    if ((ret = ff_rtmp_packet_create(&spkt, RTMP_NETWORK_CHANNEL,
                                     RTMP_PT_PING, 0, 6)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Unable to create response packet\n");
        return ret;
    }
    bytestream2_init_writer(&pbc, spkt.data, spkt.size);
    bytestream2_put_be16(&pbc, 2);          // 2 -> Stream Dry
    bytestream2_put_be32(&pbc, rt->stream_id);
    ret = ff_rtmp_packet_write(rt->stream, &spkt, rt->out_chunk_size,
                               &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);
    ff_rtmp_packet_destroy(&spkt);

    if(ret < 0){
        av_log(NULL, AV_LOG_ERROR, "Stream Dry packet could not be sent");
        return ret;
    }

    return 0;
}


问:
Finding if an element is in an array using C (syntax issue)
I'm trying to write a function that checks if an element is an array in C. I have a function here, but it always returns 0, so any debugging help would be appreciated:</p>

```<code>#include <stdio.h>
int array[] = {1, 2, 3};
int *parray = &array;
int j;
int n = sizeof(array)/sizeof(array[0]);

int ifInList(int array[], int n){
    for (j = 0; j < n; j++){
        if (array[j] == n){
           return 1;
        }
    }
    return 0;
}

int main(){
    printf("The number is %d \n", ifInList(&array[n], 1));
    return 0;
}
</code>```

答:
There are two issues in your code:

You are accessing a memory address which you have not reserved: array[n]

Within ifInList you intend to use the name n for both the size of the array (your global variable) and the value you are looking for.

In particular:

Accessing a memory address you do not own

In this line:

```<code>printf("The number is %d \n", ifInList(&array[n], 1));
</code>```

You are passing &array[n] as an argument to ifInList. This introduces two types of errors:

Addressing error: array[n] does not exist. It refers to the n+1-th element of the array, a memory address which you have not reserved. In other words, you are "out of bounds".

Logical error: you are not passing the address of the first element of the array. If you fixed it to, say, array[n-1], your function will only look at the last element of your array. In order to start searching from the first element, you need to pass either array or &array[0]; both are identical and refer to the memory address of the first element.

Conflicting variable names

First things first: global variables are almost always a bad idea, they should only be used in "quick and dirty" programs and/or for quick debugging purposes, as they can introduce confusion.

You are defining n as a global variable, which refers to the size of array. Nevertheless, within function ifInList, variable n has a different meaning: it's the key you are looking for. Therefore, if you are looking for "42" in a array with 3 elements, your function will look up to 42 different elements, instead of 3!

To avoid this confusion, give a different name to the key you are looking for:

```<code>int ifInList(int array[], int k){
    for (j = 0; j < n; j++){
        if (array[j] == k){
           return 1;
        }
    }
    return 0;
}
</code>```

And the recommended approach is to provide the size with the key as arguments, thus eliminating completely the need for a global variable and any other potential conflicts. Furthermore, it's a clean programming practice. Note how I am also defining j within the function:

```<code>int ifInList(int array[], int n, int k){
    int j;
    for (j = 0; j < n; j++){
        if (array[j] == k){
           return 1;
        }
    }
    return 0;
}
</code>```

Body:
I'm trying to write a function that checks if an element is an array in C. I have a function here, but it always returns 0, so any debugging help would be appreciated:

#include <stdio.h>
int array[] = {1, 2, 3};
int *parray = &array;
int j;
int n = sizeof(array)/sizeof(array[0]);

int ifInList(int array[], int n){
    for (j = 0; j < n; j++){
        if (array[j] == n){
           return 1;
        }
    }
    return 0;
}

int main(){
    printf("The number is %d \n", ifInList(&array[n], 1));
    return 0;
}

Body:
There are two issues in your code:

You are accessing a memory address which you have not reserved: array[n]

Within ifInList you intend to use the name n for both the size of the array (your global variable) and the value you are looking for.

In particular:

Accessing a memory address you do not own

In this line:

printf("The number is %d \n", ifInList(&array[n], 1));

You are passing &array[n] as an argument to ifInList. This introduces two types of errors:

Addressing error: array[n] does not exist. It refers to the n+1-th element of the array, a memory address which you have not reserved. In other words, you are "out of bounds".

Logical error: you are not passing the address of the first element of the array. If you fixed it to, say, array[n-1], your function will only look at the last element of your array. In order to start searching from the first element, you need to pass either array or &array[0]; both are identical and refer to the memory address of the first element.

Conflicting variable names

First things first: global variables are almost always a bad idea, they should only be used in "quick and dirty" programs and/or for quick debugging purposes, as they can introduce confusion.

You are defining n as a global variable, which refers to the size of array. Nevertheless, within function ifInList, variable n has a different meaning: it's the key you are looking for. Therefore, if you are looking for "42" in a array with 3 elements, your function will look up to 42 different elements, instead of 3!

To avoid this confusion, give a different name to the key you are looking for:

int ifInList(int array[], int k){
    for (j = 0; j < n; j++){
        if (array[j] == k){
           return 1;
        }
    }
    return 0;
}

And the recommended approach is to provide the size with the key as arguments, thus eliminating completely the need for a global variable and any other potential conflicts. Furthermore, it's a clean programming practice. Note how I am also defining j within the function:

int ifInList(int array[], int n, int k){
    int j;
    for (j = 0; j < n; j++){
        if (array[j] == k){
           return 1;
        }
    }
    return 0;
}


问:
Classification Accuracy Only 5% Higher Than Random Picking
I am trying to predict a public DotA 2 match outcome with given hero picks. It is usually possible for a human. There could only be 2 outcomes for a given side: it is either a win or a loss.

In fact, I am new to machine learning. I wanted to do this mini-project as an exercise but it already took 2 days of my time.

So, I made a dataset of around 2000 matches with about the same skill bracket.  Each match contains exactly 13 000 features. Each feature is either 0 or 1 and specifies whether radiant have certain hero or not, whether dire have certain hero or not, whether radiant have one and dire another at a time (and vice versa). All combinations sum up to around 13000 features. Most of them are 0, of course. Labels are also 0 or 1 and indicate whether Radiant team won.

I used different sets for training and for testing.
Logistic regression classifier gave me 100% accuracy on training set and around 58% accuracy for test set.

SVM on the other hand scored 55% on training and 53% on test.
When I decreased number of examples by 1000 I've got 54.5% on training and 55% on test.

Should I continue increasing number of examples?
Should I select different features?

If I add more combinations of heroes feature number will explode. Or maybe there is no way to predict match outcome judging only on the heroes selected and I need to gain data about each players online rating and hero they selected and so on?

Plot of prediction accurace based on number of training examples:

Check out 2 latest graphs I added. I  think I've got pretty decent results.
Also:

1. I asked 2 friends of mine to predict 10 matches and they both predicted 6 right. This amounts to 60% just as you said. 10 matches is not a big set, but they wont bother with bigger ones.

2. I downloaded 400 000 latest dota matches. MMR >3000, only all pick mode. Assuming that 1 billion dota matches are played each year 400k are from the same patch.

3. Concatenating hero picks of both sides was the orginal idea. Also, there are 114 heroes in dota, so I have 228 features now

4. In most matches odds are more or less equal, but there is fraction of picks, where one of the teams has advantage.From small up to critical.

What I ask you to do is to verify my conclusions, because results I've got are too bright for linear model.

[Probabilities test][2]

Actual probabilites and predicted probability ranges

distribution of predictions by probability range

答:
The issue here is with your assertion that predicting a dota 2 match based on hero picks is "usually possible for a human". For this particular task it's likely more that there's a low cap on possible accuracy than anything. I watch a lot of dota, and even when you focus on the pro scene the accuracy of casters based on hero picks is quite low. My very preliminary analysis puts their accuracy at within spitting distance of 60%.

Secondly, how many dota matches are actually determined by hero picks? It's not many. In the vast majority of cases, especially in pub matches where skill levels are highly variable, team play matters much more than hero picks.

That's the first issue with your problem, but there are definitely other large issues with the way you've structured the problem that could help you get another couple of accuracy points (though again I doubt you can get far above 60%)

My first suggestion would be to change the way you're generating features. Feeding 13k features into an LR model with 2k examples is a recipe for disaster. Especially in the case of dota, where individual heroes don't matter very much and synergies and counters are drastically more important. I would start by reducing your feature count to ~200 by just concatenating hero picks by both sides. 111 for Radiant, 111 for Dire, 1 if hero is picked, 0 otherwise. This will help with overfitting, but then you run into the issue with LR is not a particularly good fit for the problem because individual heroes don't matter as much.

My second suggestion would be to constrain your match search for a single patch, ideally a later one where there's sufficient data. If you can get different data for different patches so much the better. An LR approach will give you decent accuracy for patches where specific heroes are overpowered, and especially at small data sizes you're a bit hosed if you dealing between patches as the heroes are actually changing.

My third suggestion would be to change models to one that's better at model inter-dependencies between your features. Random forest models are a pretty easy and straightforward approach that should give you better performance than straight LR for a problem like this, and has a built-in in sklearn.

If you want to go a bit further, then using an MLP-style network model could be relatively effective. I don't see an obvious framing of the problem to take advantage of modern network models though (CNNs and RNNs), so unless you change the problem definition a bit I think that this is going to be more hassle than it's worth.

Always, when in doubt get more data, and don't forget that people are very, very bad at this problem as well.


问:
Looking for ideas for Multipart Form Handling on Web Service
I'm playing around with writing a web service that runs on Android
that handles uploading photos.  I am only writing the server, and do
not have any control over the client.

Inside of the message is a small SOAP message, and then the binary
data.  I am trying to figure out if there's a library that can do the
parsing of the two pieces.  Apache Commons FileUpload looked like the
obvious choice, however, it seems to be heavily intertwined with
servlet libraries, and I don't know if it's possible (or if it's a
good idea) to put too much J2EE infrastructure on a phone.

Parsing it myself doesn't seem too bad.  I'm not too familiar with the
raw HTTP layers/protocol, but it looks like the the boundary delimiter
string is given in the content type header.  If I find and index past
those, I should be able to find the two halves of the multi-part
message that I need to deal with.  At least that's what I seem to
think after looking at a wireshark trace of the client talking to the
real server.

答:
Although not exactly answering your question, I'm pretty confused to why you are trying to do this. You say you don't have any control over the client, yet you are trying to write a client-resident http server with multipart form handling. How would the client know to connect to this http server, vs one hosted somewhere else?

On android, IIRC, you have access to photos captured by the camera. So why would you want to transfer them over http from a local client to a local server? Basically, this seems insane.

From recently looking at multipart form handling in java, it's (a) in a sad state, (b) the open source options have lots of large third-party dependencies, and (c) it's way more complex than what you need for single file at a time uploading.

I realize this doesn't answer your question, but it will be easier with some more context on what you are trying to accomplish.

ContentLicense: CC BY-SA 4.0


问:
BigQuery UDF to find max values in another table
I have some data that looks something like this, where I have a list of events of different types, the time the event occurred, and the user the event is associated with. Event A only occurs once per user but event B can occur multiple times.

and I want to turn it into this:

The logic is as follows:

I query the table to extract a list of the times event A occurred for each user

For each row I then find the most recent time that event B occurred prior to event A

The first point is easy enough, something along the lines of

```<code>SELECT User, Time AS Event_A_Time FROM Raw_Data WHERE Event = 'Event A'
</code>```

Where I get stuck is working out how to get the third column. It will need to be something like

```<code>SELECT MAX(Time) FROM Raw_Data WHERE Time < [Event_A_Time for this user]
</code>```

I'm assuming I need to use a UDF for this, but I'm struggling with how to fit this into the syntax (using standard SQL). Any help appreciated!

答:
You shouldn't need a UDF for this kind of calculation. Try this:</p>

```<code>SELECT * EXCEPT(Event_B_Times),
  (SELECT MAX(time) FROM UNNEST(Event_B_Times) AS Time
   WHERE Time < Event_A_Time) AS Event_B_Time
FROM (
  SELECT
    User,
    MAX(IF(Event = 'Event A', Time, NULL)) AS Event_A_Time,
    ARRAY_AGG(IF(Event = 'Event B', Time, NULL) IGNORE NULLS) AS Event_B_Times
  FROM Raw_Data
  GROUP BY User
);
</code>```

Body:
I have some data that looks something like this, where I have a list of events of different types, the time the event occurred, and the user the event is associated with. Event A only occurs once per user but event B can occur multiple times.

and I want to turn it into this:

The logic is as follows:

I query the table to extract a list of the times event A occurred for each user

For each row I then find the most recent time that event B occurred prior to event A

The first point is easy enough, something along the lines of

SELECT User, Time AS Event_A_Time FROM Raw_Data WHERE Event = 'Event A'

Where I get stuck is working out how to get the third column. It will need to be something like

SELECT MAX(Time) FROM Raw_Data WHERE Time < [Event_A_Time for this user]

I'm assuming I need to use a UDF for this, but I'm struggling with how to fit this into the syntax (using standard SQL). Any help appreciated!

Body:
You shouldn't need a UDF for this kind of calculation. Try this:

SELECT * EXCEPT(Event_B_Times),
  (SELECT MAX(time) FROM UNNEST(Event_B_Times) AS Time
   WHERE Time < Event_A_Time) AS Event_B_Time
FROM (
  SELECT
    User,
    MAX(IF(Event = 'Event A', Time, NULL)) AS Event_A_Time,
    ARRAY_AGG(IF(Event = 'Event B', Time, NULL) IGNORE NULLS) AS Event_B_Times
  FROM Raw_Data
  GROUP BY User
);


答:
Ah I see commercial is a boolean.

When you use this method of passing parameter, the parameters are all assumed to be strings.

```<code>$stmt->execute(array(':name' => $name, ':email' => $email, ':commercial' => $commercial));
</code>```

You may have to bind the values like this in the case of a boolean.

```<code>$stmt->bindValue(':name', $name, PDO::PARAM_STR);
$stmt->bindValue(':email', $email, PDO::PARAM_STR);
$stmt->bindValue(':commercial', $commercial, PDO::PARAM_BOOL);

$stmt->execute();
</code>```

Title: PDO prepared statement insert not working

Body:
I absolutely have no clues about why this prepared statement doesn't work returning false but without giving me any error. I've read similar questions here on StackOverflow but I didn't find any tip to solve this unknown problem.

The errors are activated

public function PDOconn() {
    try {
        return new PDO($this->getDsn(), $this->username, $this->password, [PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION]);
    } catch (PDOException $e) {
        echo "Errore di connessione al database";
        throw $e->getCode();
    }
}

This is the PHP file that handles the AJAX request. I inserted the query into a try {} ... catch() but it actually didn't help since it doesn't report any error. execute() just returns false

/* ***** CLASSES AUTOLOAD fn ***** */
spl_autoload_register(function ($class_name) {
    require_once '../classes/' . $class_name . '.php';
});

$db     = new database();
$conn   = $db->PDOconn();

$name   = postGet::post('name');
$email  = postGet::post('email');
$commercial = postGet::post('commercial');

try {
    $stmt = $conn->prepare('INSERT INTO newsletter_subscription(name, email, commercial) VALUES(:name, :email, :commercial)');
    $stmt->execute(array(':name' => $name, ':email' => $email, ':commercial' => $commercial));
} catch (PDOException $e) {
    $return = $e->getCode();
}

header('Content-Type: application/json; charset=utf-8');
echo json_encode($return);

The variables string $name, string $email and int $commercial are correctly passed, I printed them into the php file.

This is the table structure where subscriptorID is PRIMARY AI and email is UNIQUE

[SOLUTION] Shame on me and on my short memory but maybe it can help someone else: I had the flash that that DB user didn't have INSERT priviledges, that's why the query returned just false without any error.

Body:
Ah I see commercial is a boolean.

When you use this method of passing parameter, the parameters are all assumed to be strings.

$stmt->execute(array(':name' => $name, ':email' => $email, ':commercial' => $commercial));

You may have to bind the values like this in the case of a boolean.

$stmt->bindValue(':name', $name, PDO::PARAM_STR);
$stmt->bindValue(':email', $email, PDO::PARAM_STR);
$stmt->bindValue(':commercial', $commercial, PDO::PARAM_BOOL);

$stmt->execute();


问:
scala spark how to get latest day's record
```<code>data=
"""
user date      item1 item2
1    2015-12-01 14  5.6
1    2015-12-01 10  0.6
1    2015-12-02 8   9.4
1    2015-12-02 90  1.3
2    2015-12-01 30  0.3
2    2015-12-01 89  1.2
2    2015-12-30 70  1.9
2    2015-12-31 20  2.5
3    2015-12-01 19  9.3
3    2015-12-01 40  2.3
3    2015-12-02 13  1.4
3    2015-12-02 50  1.0
3    2015-12-02 19  7.8
"""
</code>```

if I have some data like above, how can I get each user's latest day's record?
I tried to use the groupByKey, but have no idea.

```<code>val user = data.map{
case(user,date,item1,item2)=>((user,date),Array(item1,item2))
}.groupByKey()
</code>```

and then I don't know how to deal with it. Can anyone give me some suggestions? Thanks a lot:)

update:

I changed my data,and now user has several records in the latest day, and I want to get all of them. Thx:)

second update:

I want to get the result is:

```<code>user1 (2015-12-02,Array(8,9.4),Array(90,1.3))
user2 (2015-12-31,Array(20,2.5))
user3 (2015-12-02,Array(13,1.4),Array(50,1.0),Array(19,7,8))
</code>```

and now I write some code:

```<code>val data2=data.trim.split("\\n").map(_split("\\s+")).map{
f=>{(f(0),ArrayBuffer(
                    f(1),
                    f(2).toInt,
                    f(3).toDouble)
    )}
}
val data3 = sc.parallelize(data2)
data3.reduceByKey((x,y)=>
             if(x(0).toString.compareTo(y(0).toString)>=0) x++=y
                  else y).foreach(println)
</code>```

result is:

```<code>(2,ArrayBuffer(2015-12-31, 20, 2.5))
(1,ArrayBuffer(2015-12-02, 8, 9.4, 2015-12-02, 90, 1.3))
(3,ArrayBuffer(2015-12-02, 13, 1.4, 2015-12-02, 50, 1.0, 2015-12-02, 19, 7.8))
</code>```

Is there anything can do to improve it? :)

Body:
data=
"""
user date      item1 item2
1    2015-12-01 14  5.6
1    2015-12-01 10  0.6
1    2015-12-02 8   9.4
1    2015-12-02 90  1.3
2    2015-12-01 30  0.3
2    2015-12-01 89  1.2
2    2015-12-30 70  1.9
2    2015-12-31 20  2.5
3    2015-12-01 19  9.3
3    2015-12-01 40  2.3
3    2015-12-02 13  1.4
3    2015-12-02 50  1.0
3    2015-12-02 19  7.8
"""

if I have some data like above, how can I get each user's latest day's record?
I tried to use the groupByKey, but have no idea.

val user = data.map{
case(user,date,item1,item2)=>((user,date),Array(item1,item2))
}.groupByKey()

and then I don't know how to deal with it. Can anyone give me some suggestions? Thanks a lot:)

update:

I changed my data,and now user has several records in the latest day, and I want to get all of them. Thx:)

second update:

I want to get the result is:

user1 (2015-12-02,Array(8,9.4),Array(90,1.3))
user2 (2015-12-31,Array(20,2.5))
user3 (2015-12-02,Array(13,1.4),Array(50,1.0),Array(19,7,8))

and now I write some code:

val data2=data.trim.split("\\n").map(_split("\\s+")).map{
f=>{(f(0),ArrayBuffer(
                    f(1),
                    f(2).toInt,
                    f(3).toDouble)
    )}
}
val data3 = sc.parallelize(data2)
data3.reduceByKey((x,y)=>
             if(x(0).toString.compareTo(y(0).toString)>=0) x++=y
                  else y).foreach(println)

result is:

(2,ArrayBuffer(2015-12-31, 20, 2.5))
(1,ArrayBuffer(2015-12-02, 8, 9.4, 2015-12-02, 90, 1.3))
(3,ArrayBuffer(2015-12-02, 13, 1.4, 2015-12-02, 50, 1.0, 2015-12-02, 19, 7.8))

Is there anything can do to improve it? :)

Body:
The question goes in traditional windowing fictions concept. The answer to your question is partition by user and order by date using the rank function. If you rank all the records in the same day gets the same rank and then you can simply filter out the latest record with rank = 1 filter.

 val data = sc.textFile("/user/hadoop/data.txt");

    val df=data.map(_.split("\\s+")).map{f=>{(f(0),f(1),f(2).toInt,f(3).toDouble)}}.toDF();

    import org.apache.spark.sql.expressions.Window

    import org.apache.spark.sql.functions._

    val w = Window.partitionBy("_1").orderBy("_2");

    df.withColumn("Rank",rank().over(w)).show()

+---+----------+---+---+----+
| _1|        _2| _3| _4|Rank|
+---+----------+---+---+----+
|  3|2015-12-01| 19|9.3|   1|
|  3|2015-12-01| 40|2.3|   1|
|  3|2015-12-02| 13|1.4|   3|
|  3|2015-12-02| 50|1.0|   3|
|  3|2015-12-02| 19|7.8|   3|
|  1|2015-12-01| 14|5.6|   1|
|  1|2015-12-01| 10|0.6|   1|
|  1|2015-12-02|  8|9.4|   3|
|  1|2015-12-02| 90|1.3|   3|
|  2|2015-12-01| 30|0.3|   1|
|  2|2015-12-01| 89|1.2|   1|
|  2|2015-12-30| 70|1.9|   3|
|  2|2015-12-31| 20|2.5|   4|
+---+----------+---+---+----+

Now you can filter the rank =1 record.


问:
How to restrict multiple file selection in PickerView
I'm using WKWebView to load one URL. And that URL will open a registration form, in that we have a provision to picking images and videos from device and upload.
Here it is presenting picker view.

But the problem is we are able to select multiple files at a time. But I want to restrict multiple file selection. How can I restrict of selecting multiple files. (I'm using Swift 3.0)

答:
You do not have a lot of control over the content from a WKWebView. Single or multi selection is more like a server side thing. For example I have the following html code

```<code><!DOCTYPE html>
<html lang="en">
  <head>

  </head>
  <body>
    <input type="file" multiple /> test multi <br/>
    <input type="file" /> test single
  </body>
</html>
</code>```

When I run it on web view, I see this

So if you own the site, you really need to make this change to your HTML code, not doing stuff with your webview.

Body:
You do not have a lot of control over the content from a WKWebView. Single or multi selection is more like a server side thing. For example I have the following html code

<!DOCTYPE html>
<html lang="en">
  <head>

  </head>
  <body>
    <input type="file" multiple /> test multi <br/>
    <input type="file" /> test single
  </body>
</html>

When I run it on web view, I see this

So if you own the site, you really need to make this change to your HTML code, not doing stuff with your webview.


问:
twisted clientConnectionLost catch/suppress Exception
I have a project that uses twisted. In a child class from twisted.internet.protocol.ClientFactory, there are methods for clientConnectionLost / clientConnectionFailed. When an error occurs in the data exchange, this method execution with connector and reason. I can look at the type and value of exception. But I did not find information on how to suppress it. After processing, it is raise up as Unhandled Error. And I can not make a global exception handler, I need to handle exceptions depending on the type and value in this context(and re-connect etc).

```<code>class MyProtocol(Protocol):
    def connectionMade(self):
        raise Exception('Connect error')

class Client(ClientFactory):
    protocol = MyProtocol

    def clientConnectionLost(self, connector, reason):
        print reason.type, reason.value  # show type and message, OK
        reason.cleanFailure()  # ???

reactor.connectTCP('127.0.0.1', 80, Client())
reactor.run()

# Unhandled Error
# Traceback (most recent call last): ...............
</code>```

Any ideas?

答:
This code:

```<code>class MyProtocol(Protocol):
    def connectionMade(self):
        raise Exception('Connect error')
</code>```

is basically broken.  The reactor does you a favor and logs the exception for you (it would be pretty terrible if it didn't at least do that).  You can "handle" this exception by way of the logging system but the reactor does not give you any other facilities for handling it.

This is because raising an exception from connectionMade is a violation of the protocol interface.

The solution is to handle the exception inside connectionMade (or dataReceived or any of the other protocol methods you might be using).  For example:

```<code>class MyProtocol(Protocol):
    def connectionMade(self):
        try:
            raise Exception('Connect error')
        except ...:
            ...
</code>```

Note that cleanFailure doesn't do anything related to what you want here.  It just scrapes some references out of the Failure to make garbage collection proceed more easily.

Body:
I have a project that uses twisted. In a child class from twisted.internet.protocol.ClientFactory, there are methods for clientConnectionLost / clientConnectionFailed. When an error occurs in the data exchange, this method execution with connector and reason. I can look at the type and value of exception. But I did not find information on how to suppress it. After processing, it is raise up as Unhandled Error. And I can not make a global exception handler, I need to handle exceptions depending on the type and value in this context(and re-connect etc).

class MyProtocol(Protocol):
    def connectionMade(self):
        raise Exception('Connect error')

class Client(ClientFactory):
    protocol = MyProtocol

    def clientConnectionLost(self, connector, reason):
        print reason.type, reason.value  # show type and message, OK
        reason.cleanFailure()  # ???

reactor.connectTCP('127.0.0.1', 80, Client())
reactor.run()

# Unhandled Error
# Traceback (most recent call last): ...............

Any ideas?

Body:
This code:

class MyProtocol(Protocol):
    def connectionMade(self):
        raise Exception('Connect error')

is basically broken.  The reactor does you a favor and logs the exception for you (it would be pretty terrible if it didn't at least do that).  You can "handle" this exception by way of the logging system but the reactor does not give you any other facilities for handling it.

This is because raising an exception from connectionMade is a violation of the protocol interface.

The solution is to handle the exception inside connectionMade (or dataReceived or any of the other protocol methods you might be using).  For example:

class MyProtocol(Protocol):
    def connectionMade(self):
        try:
            raise Exception('Connect error')
        except ...:
            ...

Note that cleanFailure doesn't do anything related to what you want here.  It just scrapes some references out of the Failure to make garbage collection proceed more easily.


问:
What are good APIs or search method for tagging objects into categories and searching them?
i want to tag many user created content and have multiple types of categories (project tags, desc tag, style/inspiration tag etc). I seen horrible search engines where the more words you use the worse your result is and i dont want that with tagging.

What are good APIs or search method for tagging objects into categories and searching them?

答:
You might want to check these questions out:

How do you recommend implementing tags or tagging

What is the most efficient way to store tags in a database?

They both describe the same approach which should be easily tweakable to allow you to organize your tags into different categories.

LastEditorDisplayName: Rich B

OwnerDisplayName: Kevin Loney


问:
AutoMocker Question
I'm trying to test my controllers, but each of them have a dependency on a service which has a dependency on a repository.  I have the following code...

```<code>Mock.Get(controller.Get<ServiceInterface>())
            .Setup(s => s.GetData())
            .Returns(FakeData.Create<Entity>(25));
</code>```

I keep getting an error related to the ServiceInterface concrete class not having a default instance for its repository (injected).  I'm trying to avoid creating a FakeService, but its looking like that's what I'm going to have to do.  Can anyone offer some suggestions?

答:
What classes are you trying to test and what classes are you trying to stub out? I would guess that you are trying to test your controller, and want to stub out your service. If that is the case, the concrete implementation of your service, and therefore its dependencies, should not participate in your test at all and should be irrelevant. You should only need to stub out the behavior of the service interface that is needed to test your controller.

I'm only guessing at your intention, so if my answer doesn't make sense, you may need to post more code showing what you are trying to test.

Title: AutoMocker Question

Body:
I'm trying to test my controllers, but each of them have a dependency on a service which has a dependency on a repository.  I have the following code...

Mock.Get(controller.Get<ServiceInterface>())
            .Setup(s => s.GetData())
            .Returns(FakeData.Create<Entity>(25));

I keep getting an error related to the ServiceInterface concrete class not having a default instance for its repository (injected).  I'm trying to avoid creating a FakeService, but its looking like that's what I'm going to have to do.  Can anyone offer some suggestions?


问:
XMPP, <message failed="1">
I'm using psi to connect to an xmpp server at chrome.pl. I was talking, when suddenly my messages started instantly coming back from my server xmpp address. The typical exchange looks like this (this is from psi XML console):

My message:

```<code><message type="chat" to="…@jabbim.pl/…" id="accfa">
<body>nie wiem</body>
<active xmlns="http://jabber.org/protocol/chatstates"/>
</message>
</code>```

Server response:

```<code><message type="chat" id="accfa" to="…@jabbim.pl/…" failed="1">
<body>nie wiem</body>
<active xmlns="http://jabber.org/protocol/chatstates"/>
</message>
</code>```

I cannot find anything regarding this failed="1" in any XMPP specification. What's that?

答: As @Flow said in his comment, that isn't a valid attribute for a message stanza (see https://www.rfc-editor.org/rfc/rfc6120#appendix-A.5). From the looks of it, the server should be returning a message stanza with the 'type' attribute set to "error", and a relevant <error/> element (see https://www.rfc-editor.org/rfc/rfc6120#section-8.3.3 for a list of conditions).</p>

Title: XMPP, <message failed="1">

Body:
I'm using psi to connect to an xmpp server at chrome.pl. I was talking, when suddenly my messages started instantly coming back from my server xmpp address. The typical exchange looks like this (this is from psi XML console):

My message:

<message type="chat" to="…@jabbim.pl/…" id="accfa">
nie wiem
<active xmlns="http://jabber.org/protocol/chatstates"/>
</message>

Server response:

<message type="chat" id="accfa" to="…@jabbim.pl/…" failed="1">
nie wiem
<active xmlns="http://jabber.org/protocol/chatstates"/>
</message>

I cannot find anything regarding this failed="1" in any XMPP specification. What's that?


问:
How to disable or change IntelliJ IDEA splash screen?
Can anyone help, how to disable or change the splash screen of IntelliJ IDEA?

答:
File->Setting then "Appearance & Behavior"->"System Settings". uncheck "Reopen last project at startup"

Let me add this is Intellij 2017.1.3