问:
Android - How do I get sharedpreferences from another activity?
In my app there is a button (activity1). When user clicks it, I want no sound in the game. I thought I should do this by using sharedpreferences in activity1 in the onClick method of the button:

```<code>SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("sound","1");
editor.commit();
</code>```

The sound and the game starts in another activity (activity2). I need to read the set sharedpreferences there, but I don't know how to do it.

Thanks

Edit

I have left this line out:

```<code>SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Activity1.this);
</code>```

Based on your help in the Activity2.class I read the preferences like this:

```<code>SharedPreferences myPrefs = getSharedPreferences("Activity1", MODE_PRIVATE);  //Activity1.class
String ifsound = myPrefs.getString("sound","");

 if (ifsound.equals("1"))
 {
     Toast.makeText(Activity1.this, "1", Toast.LENGTH_LONG).show();
 }
 else
 {
      Toast.makeText(Activity1.this, "0", Toast.LENGTH_LONG).show();
 }
</code>```

In Activity1.class i click on the button to set the "sound" to "1".

I click on another btn that opens Activity2.class where I always get always "0" in the Toast msg.

答:
First create method in MainActivity for geting Context:

```<code> public  Context getContext(){
        Context mContext = MainActivity.this;
        return mContext;
    }
</code>```

and

use this in every Class you want:

```<code>MainActivity mContext = new MainActivity();
        SharedPreferences sharedPrefs =
PreferenceManager.getDefaultSharedPreferences(mContext.getContext());
</code>```

Body:
In my app there is a button (activity1). When user clicks it, I want no sound in the game. I thought I should do this by using sharedpreferences in activity1 in the onClick method of the button:

SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("sound","1");
editor.commit();

The sound and the game starts in another activity (activity2). I need to read the set sharedpreferences there, but I don't know how to do it.

Thanks

Edit

I have left this line out:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Activity1.this);

Based on your help in the Activity2.class I read the preferences like this:

SharedPreferences myPrefs = getSharedPreferences("Activity1", MODE_PRIVATE);  //Activity1.class
String ifsound = myPrefs.getString("sound","");

 if (ifsound.equals("1"))
 {
     Toast.makeText(Activity1.this, "1", Toast.LENGTH_LONG).show();
 }
 else
 {
      Toast.makeText(Activity1.this, "0", Toast.LENGTH_LONG).show();
 }

In Activity1.class i click on the button to set the "sound" to "1".

I click on another btn that opens Activity2.class where I always get always "0" in the Toast msg.

Body:
First create method in MainActivity for geting Context:

 public  Context getContext(){
        Context mContext = MainActivity.this;
        return mContext;
    }

and

use this in every Class you want:

MainActivity mContext = new MainActivity();
        SharedPreferences sharedPrefs =
PreferenceManager.getDefaultSharedPreferences(mContext.getContext());


来源: stackexchange

问:
Speed up Linq Query
I have my class structure as follows

```<code>public class Email
{
    public string Subject {get;set;}
    public string Message {get;set;}
    public Contact Sender {get;set;}
    public string SenderEmail {get;set;}
}
public class Contact
{
    public string Email {get;set;}
    public string Name {get;set;}
}
</code>```

and I run my Linq query in two parts
First i select all the emails.

```<code>var query = from msg in context.Email
            select msg;
</code>```

Then i assign the Contact details to the Email Class

```<code>List<Email> outputList = new List<Email>();
foreach (var item in query.ToList())
{
    var q = from contact in context.Contact
            where contact.Email = item.SenderEmail
            select contact;
    item.Sender = q.SingleOrDefault();
    outputList.Add(item);
}

return outputList;
</code>```

Is there anyway i can run a join query and simply output the List without having to run multiple queries

答:
I suspect this should work:

```<code>var query = from msg in context.Email
            join contact in context.Contact
                 on msg.SenderEmail equals contact.Email
                 into contacts
            select new { msg, contacts };

var list = query.ToList();
foreach (var pair in list)
{
    pair.msg.Sender = pair.contacts.FirstOrDefault();
}

var messages = list.Select(pair => pair.msg);
</code>```

This uses a group join. You haven't said which LINQ provider you're using, but I expect it should work for most providers...

ContentLicense: CC BY-SA 2.5

Title: Speed up Linq Query

Body:
I have my class structure as follows

public class Email
{
    public string Subject {get;set;}
    public string Message {get;set;}
    public Contact Sender {get;set;}
    public string SenderEmail {get;set;}
}
public class Contact
{
    public string Email {get;set;}
    public string Name {get;set;}
}

and I run my Linq query in two parts
First i select all the emails.

var query = from msg in context.Email
            select msg;

Then i assign the Contact details to the Email Class

List<Email> outputList = new List<Email>();
foreach (var item in query.ToList())
{
    var q = from contact in context.Contact
            where contact.Email = item.SenderEmail
            select contact;
    item.Sender = q.SingleOrDefault();
    outputList.Add(item);
}

return outputList;

Is there anyway i can run a join query and simply output the List without having to run multiple queries

Body:
I suspect this should work:

var query = from msg in context.Email
            join contact in context.Contact
                 on msg.SenderEmail equals contact.Email
                 into contacts
            select new { msg, contacts };

var list = query.ToList();
foreach (var pair in list)
{
    pair.msg.Sender = pair.contacts.FirstOrDefault();
}

var messages = list.Select(pair => pair.msg);

This uses a group join. You haven't said which LINQ provider you're using, but I expect it should work for most providers...


问:
Determine DRM system supported by browser
I've trying to find out how to determine which DRM system browser is using. And in fact, only chrome say it is use 'com.widevine.alpha' where IE & Safari (Win) throw error on 'requestMediaKeySystemAccess', and firefox do not even try to say it use 'com.adobe.acccess' =]

```<code> function isKeySystemSupported(keySystem) {

    var dfd = Q.defer();
    console.log('check: ', keySystem);
    navigator.requestMediaKeySystemAccess(keySystem, [{contentType: 'video/webm; codecs="vp9"'}]).then(function() {
        dfd.resolve(true);
    }, function() { dfd.resolve(false); } );

    return dfd.promise;
}
</code>```

is there any solution, like Modernizr or similar to get which keySystem I should use?

答:
In addition to the information listed here, I want to mention that in Chrome, whether you are using https or not will affect the availability of navigator.requestMediaKeySystemAccess function.

In your development environment that probably is running on http, navigator.requestMediaKeySystemAccess will return undefined for Chrome whereas the same code will return a function in Firefox.

In your prod environment that has https, navigator.requestMediaKeySystemAccess will return a function both in Chrome and Firefox.

ContentLicense: CC BY-SA 3.0

Body:
I've trying to find out how to determine which DRM system browser is using. And in fact, only chrome say it is use 'com.widevine.alpha' where IE & Safari (Win) throw error on 'requestMediaKeySystemAccess', and firefox do not even try to say it use 'com.adobe.acccess' =]

 function isKeySystemSupported(keySystem) {

    var dfd = Q.defer();
    console.log('check: ', keySystem);
    navigator.requestMediaKeySystemAccess(keySystem, [{contentType: 'video/webm; codecs="vp9"'}]).then(function() {
        dfd.resolve(true);
    }, function() { dfd.resolve(false); } );

    return dfd.promise;
}

is there any solution, like Modernizr or similar to get which keySystem I should use?


问:
How should I format a post_filter query to match a string inside of a string in Elasticsearch?
I have an array of articles in a MongoDB database that is indexed into Elasticsearch. Each article in MongoDB contains an array of author names like so: ['Michael Jordan', '...']. Each article is then indexed into Es.

In Es, I have aggregation by author working, but I also want to apply a post_filter to filter results by author. How should a post_filter query be designed to handle this?

Es Schema (can be changed):

```<code>{
  authors: ['Michael Jordan', 'Kobe Bryant'],
  authorsString: 'Michael Jordan;Kobe Bryant;'
}
</code>```

This is an example query before applying the post_filter:

```<code>{
  ...
  aggs: {
    authors: {
      terms: {
        field: 'authorsArray.keyword',
      },
    },
  },
  post_filter: {},
}
</code>```

If I want to find articles of which at least one of the authors is "Michael Jordan", how do I use post_filter to do so?

答:
The following is what worked to match the author name inside of a single string containing many author names. (Es 5.6):</p>

```<code>"post_filter": {
    "bool": {
        "should": [{
            "match_phrase": {
                authorsString: author
            }
        }]
    }
 }
</code>```

Body:
I have an array of articles in a MongoDB database that is indexed into Elasticsearch. Each article in MongoDB contains an array of author names like so: ['Michael Jordan', '...']. Each article is then indexed into Es.

In Es, I have aggregation by author working, but I also want to apply a post_filter to filter results by author. How should a post_filter query be designed to handle this?

Es Schema (can be changed):

{
  authors: ['Michael Jordan', 'Kobe Bryant'],
  authorsString: 'Michael Jordan;Kobe Bryant;'
}

This is an example query before applying the post_filter:

{
  ...
  aggs: {
    authors: {
      terms: {
        field: 'authorsArray.keyword',
      },
    },
  },
  post_filter: {},
}

If I want to find articles of which at least one of the authors is "Michael Jordan", how do I use post_filter to do so?

Body:
The following is what worked to match the author name inside of a single string containing many author names. (Es 5.6):

"post_filter": {
    "bool": {
        "should": [{
            "match_phrase": {
                authorsString: author
            }
        }]
    }
 }


问:
Android KeyStore get raw bytes/string of stored key
I can generate a key to be stored in the Android Keystore like so:

```<code>private static final String AndroidKeyStore = "AndroidKeyStore";
private static final String AES_MODE = "AES/GCM/NoPadding";
keyStore = KeyStore.getInstance(AndroidKeyStore);
keyStore.load(null);

if (!keyStore.containsAlias(KEY_ALIAS)) {
    KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, AndroidKeyStore);
    keyGenerator.init(
            new KeyGenParameterSpec.Builder(KEY_ALIAS,
                    KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                    .setBlockModes(KeyProperties.BLOCK_MODE_GCM)                   .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                    .setRandomizedEncryptionRequired(false)
                    .build());
    keyGenerator.generateKey();
}
</code>```

Similarly, I can retrieve it like so:

```<code>keyStore.getKey(KEY_ALIAS, null);
</code>```

I know that the getKey() function returns a Key object, but I haven't found a way to reveal the key itself. It does not seem to have a toString() or getBytes() or something like that.

How can I get the bytes of the key, or at least print out the string version of it? Is it even possible?

答:
The "AndroidKeyStore" is specifically designed to make this impossible or at least very difficult. There is a more complete discussion here, but in summary:

Android Keystore system protects key material from unauthorized use.
  Firstly, Android Keystore mitigates unauthorized use of key material
  outside of the Android device by preventing extraction of the key
  material from application processes and from the Android device as a
  whole.

Continuing along the lines of your example, the following additional lines of code:

```<code>Key key = keyStore.getKey(KEY_ALIAS, null);
String algorithm = key.getAlgorithm();
String format = key.getFormat();
byte[] encoded = key.getEncoded();
</code>```

should cause key to be a valid non-null reference to Key object, algorithm should return "AES", but format should be null as should encoded.

Body:
I can generate a key to be stored in the Android Keystore like so:

private static final String AndroidKeyStore = "AndroidKeyStore";
private static final String AES_MODE = "AES/GCM/NoPadding";
keyStore = KeyStore.getInstance(AndroidKeyStore);
keyStore.load(null);

if (!keyStore.containsAlias(KEY_ALIAS)) {
    KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, AndroidKeyStore);
    keyGenerator.init(
            new KeyGenParameterSpec.Builder(KEY_ALIAS,
                    KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                    .setBlockModes(KeyProperties.BLOCK_MODE_GCM)                   .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                    .setRandomizedEncryptionRequired(false)
                    .build());
    keyGenerator.generateKey();
}

Similarly, I can retrieve it like so:

keyStore.getKey(KEY_ALIAS, null);

I know that the getKey() function returns a Key object, but I haven't found a way to reveal the key itself. It does not seem to have a toString() or getBytes() or something like that.

How can I get the bytes of the key, or at least print out the string version of it? Is it even possible?

Body:
The "AndroidKeyStore" is specifically designed to make this impossible or at least very difficult. There is a more complete discussion here, but in summary:

Android Keystore system protects key material from unauthorized use.
  Firstly, Android Keystore mitigates unauthorized use of key material
  outside of the Android device by preventing extraction of the key
  material from application processes and from the Android device as a
  whole.

Continuing along the lines of your example, the following additional lines of code:

Key key = keyStore.getKey(KEY_ALIAS, null);
String algorithm = key.getAlgorithm();
String format = key.getFormat();
byte[] encoded = key.getEncoded();

should cause key to be a valid non-null reference to Key object, algorithm should return "AES", but format should be null as should encoded.


问:
PHP Mail Function 404 Error
HTML Code:

```<code>    <html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>BuddyTeam | Website</title>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
    <div id="page-wrap">
        <img src="images/title.png" alt="BuddyTeam | Website" /><br /><br />

        <div id="contact-area">

            <form method="post" action="contactengine.php">
                <p style="text-align:right" onclick="alert('Só podes registar uma conta secundária se tiveres uma principal!        Neste espaço escreve o Nickname da tua conta registada no Servidor.')"><font color="blue">Precisas de ajuda? Clica Aqui!</font></p>
                <label for="Nickname"></label>
                <p><font face="serif"></font></p><input type="text" name="Nickname" id="Nickname" placeholder="Informa o Nickname da conta principal registada no Servidor." required />
                <p style="text-align:right" onclick="alert('Para não haver fraudes precisamos de saber que és mesmo tu!                   Vai ao Servidor com a tua conta registada, usa o comando ( /meuid ) e escreve os números neste espaço.')"><font color="blue">Precisas de ajuda? Clica Aqui!</font></p>

                <label for="ID"></label>
                <p><font face="serif"></font></p><input type="text" name="ID" id="ID" placeholder="Informa o ID da conta principal registada no Servidor." required />
                <p style="text-align:right" onclick="alert('Contas nunca são demais!                                                                        Neste espaço escreve o Nickname da nova conta que queres registar.')"><font color="blue">Precisas de ajuda? Clica Aqui!</font></p>

                <label for="Novo"></label>
                <input type="text" name="Novo" id="Novo" placeholder="Informa o Nickname da conta que pretendes registar." required />
                <p style="text-align:right" onclick="alert('Segurança em primeiro lugar!                                                                  Neste espaço escreve uma senha para a nova conta que queres registar.')"><font color="blue">Precisas de ajuda? Clica Aqui!</font></p>

                <label for="Senha"></label>
                <input type="text" name="Senha" id="Senha" placeholder="Informa uma senha para a tua nova conta." required />
                <p style="text-align:right" onclick="alert('Depois entra em contacto!                                                                      Coloca aqui o teu Email para seres contacto quando a conta for registada.')"><font color="blue">Precisas de ajuda? Clica Aqui!</font></p>

                <label for="Email"></label>
                <input type="text" name="Email" id="Email" placeholder="Informa um Email para contacto.">

                <input type="submit" name="submit" value="Enviar" class="submit-button" />
            </form>

            <div style="clear: both;"></div>

        </div>

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

PHP Code:

```<code>    <?php

$EmailFrom = "geral@buddyplays.net";
$EmailTo = "geral@buddyplays.net";
$Subject = "Novo Pedido de Registo de Conta";
$Nickname = Trim(stripslashes($_POST['Nickname']));
$ID = Trim(stripslashes($_POST['ID']));
$Novo = Trim(stripslashes($_POST['Novo']));
$Senha = Trim(stripslashes($_POST['Senha']));
$Email = Trim(stripslashes($_POST['Email']));

// validation
$validationOK=true;
if (!$validationOK) {
  print "<meta http-equiv=\"refresh\" content=\"0;URL=erro.html\">";
  exit;
}

// prepare email body text
$Body = "";
$Body .= "Conta Registada: ";
$Body .= $Nickname;
$Body .= "\n";
$Body .= "ID da Conta Registada: ";
$Body .= $ID;
$Body .= "\n";
$Body .= "Nova Conta: ";
$Body .= $Novo;
$Body .= "\n";
$Body .= "Senha: ";
$Body .= $Senha;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";

// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");

// redirect to success page
if ($success){
  print "<meta http-equiv=\"refresh\" content=\"0;URL=concluido.php\">";
}
else{
  print "<meta http-equiv=\"refresh\" content=\"0;URL=erro.html\">";
}
?>
</code>```

When I fill out the form and submit, I'm redirected to "erro.html" and the email is not sent. What is wrong?

The system stops working from one moment to another without me doing any kind of editing.

What do I need to change for the system to work again?

答:
The problem is that your mail() function isn't working because you have supplied an invalid fourth parameter (as your From address). "From: <$EmailFrom>" shouldn't have the brackets around the email address. If you do make use of the brackets, you need to supply a name in front of them.

Instead of $success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");

What you're looking to do is add it as a header:

```<code>$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'From: ' . $Nickname. ' <' . $EmailFrom . '>';
$success = mail($EmailTo, $Subject, $Body, $headers);`
</code>```

This will evaluate to: From: $Nickname <$EmailFrom>.

Also note that some mail servers prevent the From address from being manipulated in order to prevent phishing.

You're getting a 404 simply because erro.html doesn't exist on your server. Creating the relevant file will resolve the error and redirect you there automatically when there's an error sending of the email.

Hope this helps! :)

Title: PHP Mail Function 404 Error

Body:
HTML Code:

    <title>BuddyTeam | Website</title>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <link rel="stylesheet" type="text/css" href="style.css" />

            <form method="post" action="contactengine.php">

Precisas de ajuda? Clica Aqui!

<input type="text" name="Nickname" id="Nickname" placeholder="Informa o Nickname da conta principal registada no Servidor." required />

Precisas de ajuda? Clica Aqui!

<input type="text" name="ID" id="ID" placeholder="Informa o ID da conta principal registada no Servidor." required />

Precisas de ajuda? Clica Aqui!

                <input type="text" name="Novo" id="Novo" placeholder="Informa o Nickname da conta que pretendes registar." required />

Precisas de ajuda? Clica Aqui!

                <input type="text" name="Senha" id="Senha" placeholder="Informa uma senha para a tua nova conta." required />

Precisas de ajuda? Clica Aqui!

                <input type="text" name="Email" id="Email" placeholder="Informa um Email para contacto.">

                <input type="submit" name="submit" value="Enviar" class="submit-button" />
            </form>

PHP Code:

    <?php

$EmailFrom = "geral@buddyplays.net";
$EmailTo = "geral@buddyplays.net";
$Subject = "Novo Pedido de Registo de Conta";
$Nickname = Trim(stripslashes($_POST['Nickname']));
$ID = Trim(stripslashes($_POST['ID']));
$Novo = Trim(stripslashes($_POST['Novo']));
$Senha = Trim(stripslashes($_POST['Senha']));
$Email = Trim(stripslashes($_POST['Email']));

// validation
$validationOK=true;
if (!$validationOK) {
  print "<meta http-equiv=\"refresh\" content=\"0;URL=erro.html\">";
  exit;
}

// prepare email body text
$Body = "";
$Body .= "Conta Registada: ";
$Body .= $Nickname;
$Body .= "\n";
$Body .= "ID da Conta Registada: ";
$Body .= $ID;
$Body .= "\n";
$Body .= "Nova Conta: ";
$Body .= $Novo;
$Body .= "\n";
$Body .= "Senha: ";
$Body .= $Senha;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";

// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");

// redirect to success page
if ($success){
  print "<meta http-equiv=\"refresh\" content=\"0;URL=concluido.php\">";
}
else{
  print "<meta http-equiv=\"refresh\" content=\"0;URL=erro.html\">";
}
?>

When I fill out the form and submit, I'm redirected to "erro.html" and the email is not sent. What is wrong?

The system stops working from one moment to another without me doing any kind of editing.

What do I need to change for the system to work again?

Body:
The problem is that your mail() function isn't working because you have supplied an invalid fourth parameter (as your From address). "From: <$EmailFrom>" shouldn't have the brackets around the email address. If you do make use of the brackets, you need to supply a name in front of them.

Instead of $success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");

What you're looking to do is add it as a header:

$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'From: ' . $Nickname. ' <' . $EmailFrom . '>';
$success = mail($EmailTo, $Subject, $Body, $headers);`

This will evaluate to: From: $Nickname <$EmailFrom>.

Also note that some mail servers prevent the From address from being manipulated in order to prevent phishing.

You're getting a 404 simply because erro.html doesn't exist on your server. Creating the relevant file will resolve the error and redirect you there automatically when there's an error sending of the email.

Hope this helps! :)


问:
What's the best approach for modifying PDF interactive form fields on iOS?
I've been doing some head banging on this one and solicit your advice.

I am building an app that as part of it's features is to present PDF forms; meaning display them, allow fields to be changed and save the modified PDF file back out.  UIWebViews do not support PDF interactive forms.

Using the CGPDF apis (and benefit from other questions posted here and elsewhere), I can certainly present the PDF (without the form fields/widgets), scan and find the fields in the document, figure out where on the screen to draw something and make them interactive.

What I can't seem to figure out is how to change the CGPDFDictionary objects and write them back out to a file.  One could use the CGPDF Apis to create a new PDF document from whole cloth, but how do you use it to modify an existing file?

Should I be looking elsewhere such as 3rd party PDF libs like PoDoFo or libHaru?

I'd love to hear from anyone who has successfully modified a PDF and written it back out as to your approach.

答:
I once did this incredibly cheaply by munging through the PDF -- I mean using regular expressions -- and just dirtily changing the actual raw text of the raw PDF data file.

It can work perfectly in simple situations where you are easily able to find the value in question.

No idea what you're trying to do here but a lateral thought!  Hope it helps!


问:
Error in code wont allow me to progress
I get an error when i run this code

```<code>cost = float(prices[strs[0]][0])
</code>```

TypeError: float() argument must be a string or a number, not 'list'

i dont know how to fix the error

```<code>prices = {}
groceries = []

file = open("grocery_store_price_list.txt", "r")
for strx in file:
    strs = list(filter(None, strx.strip().split(" ")))
    prices[strs[0]] = [strs[1]], [strs[2]]
file.close()

file = open("my_personal_gro_list.txt", "r")
for strx in file :
    strs = list(filter(None, strx.strip().split(" ")))
    groceries.append([strs[1], strs[0]])

headings = "{:15s} {:3s} {:10s} {:5s} {:6s}".format("item", "qty", "unit",
"cost", "total")

print(headings)
finalCost = 0

for strs in groceries
    item = strs[0]
    qty = int(strs[1])
    unit = prices[strs[0]][1]
    cost = float(prices[strs[0]][0])
</code>```

答:
prices[strs[0]][0] is a list that contains two prices. So you'll want to cast both values separately or using cost = [float(v) for v in prices[strs[0]][0]].

```<code>prices = {}
groceries = []

file = open("grocery_store_price_list.txt", "r")
for strx in file:
    strs = list(filter(None, strx.strip().split(" ")))
    prices[strs[0]] = [strs[1]], [strs[2]]  # List of two prices, why you get the error.
file.close()

file = open("my_personal_gro_list.txt", "r")
for strx in file :
    strs = list(filter(None, strx.strip().split(" ")))
    groceries.append([strs[1], strs[0]])

headings = "{:15s} {:3s} {:10s} {:5s} {:6s}".format("item", "qty", "unit",
"cost", "total")

print(headings)
finalCost = 0

for strs in groceries
    item = strs[0]
    qty = int(strs[1])
    unit = prices[strs[0]][1]
    cost = [float(v) for v in prices[strs[0]][0]]
    # OR  cost = [float(prices[strs[0]][0][0]), float(prices[strs[0]][0][1])]
</code>```

Title: Error in code wont allow me to progress

Body:
I get an error when i run this code

cost = float(prices[strs[0]][0])

TypeError: float() argument must be a string or a number, not 'list'

i dont know how to fix the error

prices = {}
groceries = []

file = open("grocery_store_price_list.txt", "r")
for strx in file:
    strs = list(filter(None, strx.strip().split(" ")))
    prices[strs[0]] = [strs[1]], [strs[2]]
file.close()

file = open("my_personal_gro_list.txt", "r")
for strx in file :
    strs = list(filter(None, strx.strip().split(" ")))
    groceries.append([strs[1], strs[0]])

headings = "{:15s} {:3s} {:10s} {:5s} {:6s}".format("item", "qty", "unit",
"cost", "total")

print(headings)
finalCost = 0

for strs in groceries
    item = strs[0]
    qty = int(strs[1])
    unit = prices[strs[0]][1]
    cost = float(prices[strs[0]][0])

Body:
prices[strs[0]][0] is a list that contains two prices. So you'll want to cast both values separately or using cost = [float(v) for v in prices[strs[0]][0]].

prices = {}
groceries = []

file = open("grocery_store_price_list.txt", "r")
for strx in file:
    strs = list(filter(None, strx.strip().split(" ")))
    prices[strs[0]] = [strs[1]], [strs[2]]  # List of two prices, why you get the error.
file.close()

file = open("my_personal_gro_list.txt", "r")
for strx in file :
    strs = list(filter(None, strx.strip().split(" ")))
    groceries.append([strs[1], strs[0]])

headings = "{:15s} {:3s} {:10s} {:5s} {:6s}".format("item", "qty", "unit",
"cost", "total")

print(headings)
finalCost = 0

for strs in groceries
    item = strs[0]
    qty = int(strs[1])
    unit = prices[strs[0]][1]
    cost = [float(v) for v in prices[strs[0]][0]]
    # OR  cost = [float(prices[strs[0]][0][0]), float(prices[strs[0]][0][1])]


问:
Kotlin - accessing companion object members in derived types
Given the following code:

```<code>open class Foo {
    companion object {
        fun fez() {}
    }
}

class Bar : Foo() {
    companion object {
        fun baz() { fez() }
    }
}
</code>```

baz() can call fez()

I can call Foo.fez()

I can call Bar.baz()

But, I cannot call Bar.fez()

How do I achieve the final behaviour?

答:
A companion object is a static member of its surrounding class:

```<code>public class Foo {
   public static final Foo.Companion Companion;

   public static final class Companion {
      public final void fez() {
      }

     //constructors
   }
}
</code>```

The call to fez() is compiled to :

```<code>Foo.Companion.fez();
</code>```

FYI: The shown Java code shows a representation of the bytecode generated by Kotlin.

As a result, you cannot call Bar.fez() because the Companion object in Bar does not have that method.

Body:
Given the following code:

open class Foo {
    companion object {
        fun fez() {}
    }
}

class Bar : Foo() {
    companion object {
        fun baz() { fez() }
    }
}

baz() can call fez()

I can call Foo.fez()

I can call Bar.baz()

But, I cannot call Bar.fez()

How do I achieve the final behaviour?

Body:
A companion object is a static member of its surrounding class:

public class Foo {
   public static final Foo.Companion Companion;

   public static final class Companion {
      public final void fez() {
      }

     //constructors
   }
}

The call to fez() is compiled to :

Foo.Companion.fez();

FYI: The shown Java code shows a representation of the bytecode generated by Kotlin.

As a result, you cannot call Bar.fez() because the Companion object in Bar does not have that method.


问:
Firebase rules - secure user data
I cant't find any topic about secure user data with firebase rules.
I'm programming an app with ionic-angular and firebase (auth + database).

My structure in database is:

Database structure

What I want to achieve is, that every authenticated user can only see his own contacts.

At first i tried something like this. But the permission had been denied.

So i had to read the firebase api again and again.
My next idea was this. And it's working. I tested it, every user only has access to his own contacts, can add new ones, delete them, update them etc. It's just about the firebase rules.

My question is now, is my user data secured enough with the the second idea? I know that ".write & .read = true" gives the whole world access to data, but they first had to be authenticated and the authenticated user must have the matching uid. Am i right or is there a problem?

答:
I'm assuming this is a mockup? Assuming you are using the uid as the key value this should work:

```<code> "rules": {
    "profiles": {
      "$uid": {
        ".read": "auth.uid == $uid,
        ".write": "auth.uid == $uid',
      },
</code>```

I'm assuming under profiles you have the actual user id instead of 'user1,' 'user2', etc. And if you only want them accessing (not changing) change write to false.

Title: Firebase rules - secure user data

Body:
I'm assuming this is a mockup? Assuming you are using the uid as the key value this should work:

 "rules": {
    "profiles": {
      "$uid": {
        ".read": "auth.uid == $uid,
        ".write": "auth.uid == $uid',
      },

I'm assuming under profiles you have the actual user id instead of 'user1,' 'user2', etc. And if you only want them accessing (not changing) change write to false.


问:
Pandas - Split dataframe into multiple dataframes based on dates?
I have a dataframe with multiple columns along with a date column. The date format is 12/31/15 and I have set it as a datetime object.

I set the datetime column as the index and want to perform a regression calculation for each month of the dataframe.

I believe the methodology to do this would be to split the dataframe into multiple dataframes based on month, store into a list of dataframes, then perform regression on each dataframe in the list.

I have used groupby which successfully split the dataframe by month, but am unsure how to correctly convert each group in the groupby object into a dataframe to be able to run my regression function on it.

Does anyone know how to split a dataframe into multiple dataframes based on date, or a better approach to my problem?

Here is my code I've written so far

```<code>import pandas as pd
import numpy as np
import statsmodels.api as sm
from patsy import dmatrices

df = pd.read_csv('data.csv')
df['date'] = pd.to_datetime(df['date'], format='%Y%m%d')
df = df.set_index('date')

# Group dataframe on index by month and year
# Groupby works, but dmatrices does not
for df_group in df.groupby(pd.TimeGrouper("M")):
    y,X = dmatrices('value1 ~ value2 + value3', data=df_group,
    return_type='dataframe')
</code>```

答:
This is a split per year. </p>

```<code>import pandas as pd
import dateutil.parser
dfile = 'rg_unificado.csv'
df = pd.read_csv(dfile, sep='|', quotechar='"', encoding='latin-1')
df['FECHA'] = df['FECHA'].apply(lambda x: dateutil.parser.parse(x))
#http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases
#use to_period
per = df['FECHA'].dt.to_period("Y")
#group by that period
agg = df.groupby([per])
for year, group in agg:
    #this simple save the data
    datep =  str(year).replace('-', '')
    filename = '%s_%s.csv' % (dfile.replace('.csv', ''), datep)
    group.to_csv(filename, sep='|', quotechar='"', encoding='latin-1', index=False, header=True)
</code>```

Body:
I have a dataframe with multiple columns along with a date column. The date format is 12/31/15 and I have set it as a datetime object.

I set the datetime column as the index and want to perform a regression calculation for each month of the dataframe.

I believe the methodology to do this would be to split the dataframe into multiple dataframes based on month, store into a list of dataframes, then perform regression on each dataframe in the list.

I have used groupby which successfully split the dataframe by month, but am unsure how to correctly convert each group in the groupby object into a dataframe to be able to run my regression function on it.

Does anyone know how to split a dataframe into multiple dataframes based on date, or a better approach to my problem?

Here is my code I've written so far

import pandas as pd
import numpy as np
import statsmodels.api as sm
from patsy import dmatrices

df = pd.read_csv('data.csv')
df['date'] = pd.to_datetime(df['date'], format='%Y%m%d')
df = df.set_index('date')

# Group dataframe on index by month and year
# Groupby works, but dmatrices does not
for df_group in df.groupby(pd.TimeGrouper("M")):
    y,X = dmatrices('value1 ~ value2 + value3', data=df_group,
    return_type='dataframe')

Body:
This is a split per year.

import pandas as pd
import dateutil.parser
dfile = 'rg_unificado.csv'
df = pd.read_csv(dfile, sep='|', quotechar='"', encoding='latin-1')
df['FECHA'] = df['FECHA'].apply(lambda x: dateutil.parser.parse(x))
#http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases
#use to_period
per = df['FECHA'].dt.to_period("Y")
#group by that period
agg = df.groupby([per])
for year, group in agg:
    #this simple save the data
    datep =  str(year).replace('-', '')
    filename = '%s_%s.csv' % (dfile.replace('.csv', ''), datep)
    group.to_csv(filename, sep='|', quotechar='"', encoding='latin-1', index=False, header=True)


答:
```<code>>>> prices = {}
>>> prices['a'] = [1], [2]
>>> prices
{'a': ([1], [2])}
</code>```

Taking above as an example, your prices contains a tuple and each is a list that contains 1 element

```<code>  prices[strs[0]] = [strs[1]], [strs[2]]
</code>```

You either apply float() on one of the values or modify your prices let each key has one value

Title: Error in code wont allow me to progress

Body:
>>> prices = {}
>>> prices['a'] = [1], [2]
>>> prices
{'a': ([1], [2])}

Taking above as an example, your prices contains a tuple and each is a list that contains 1 element

  prices[strs[0]] = [strs[1]], [strs[2]]

You either apply float() on one of the values or modify your prices let each key has one value


问:
C# Which Event should I use to display data in a textbox when I select an item in a listbox?
C# Which Event should I use to display data in a textbox when I select an item in a listbox?

I want to select an item in a list box (winforms) and then a textbox near by show some data related to that item but I don't know which event to use. I'll need to be able to click down the list and watch the textbox text update with each click.

Thanks

答: I think this will help you out.</p>

OwnerDisplayName: Steve

Body: I think this will help you out.

OwnerDisplayName: JPunyon


问:
mongodump ignore some specified collections
I was trying to backup my mongo database on the product sever.and then restore then back to the staging server.
and here comes some problem, there are a lot of collections in db, I want to igonre some collections that I don't want to restore on staging server.

I can approach this by dumpping the staging db, dumpping the producting db, and then restore the prodct to staging useing --drop option. and restore the specified collections in staging db. uh..it's really bad.

1. dump producting db

```<code>mongodump --host product-server-host --username abcd --password bcda -d db -o pruduct-dump-dir
</code>```

2. dump staging db

```<code>mongodump --host staging-server-host --username abcd --password bcda -d db -o staging -dump-dir
</code>```

3. restore all collection, then restore the collection back
restore pruduct-dump-dir to staging server

```<code>mongorestore --host staging-server-host --username abcd --password bcda --drop pruduct-dump-dir

mongorestore --host staging-server-host --username abcd --password bcda --drop --collection coll pruducting-dump-dir
</code>```

Is there any option like ignore-collection when I'm dumpping?
any suggestion will be appreciated :3

答:
As of Mongo 3.4, you can now specify an --nsExclude <namespace pattern> option when restoring from a Mongo database dump, which will exclude the specified namespaces from the restore operation. This is particularly useful when the mongodump operation has already occurred.

Official documentation here: https://docs.mongodb.com/manual/reference/program/mongorestore/#cmdoption-nsexclude

You can exclude multiple collections with wildcards:

```<code>mongorestore --db test --nsExclude 'test.*_tmp'
</code>```

Or alternatively, specifying multiple --nsExclude options work as well:

```<code>mongorestore --db test --nsExclude 'test.collection1' --nsExclude 'test.collection2'
</code>```

Body:
I was trying to backup my mongo database on the product sever.and then restore then back to the staging server.
and here comes some problem, there are a lot of collections in db, I want to igonre some collections that I don't want to restore on staging server.

I can approach this by dumpping the staging db, dumpping the producting db, and then restore the prodct to staging useing --drop option. and restore the specified collections in staging db. uh..it's really bad.

1. dump producting db

mongodump --host product-server-host --username abcd --password bcda -d db -o pruduct-dump-dir

2. dump staging db

mongodump --host staging-server-host --username abcd --password bcda -d db -o staging -dump-dir

3. restore all collection, then restore the collection back
restore pruduct-dump-dir to staging server

mongorestore --host staging-server-host --username abcd --password bcda --drop pruduct-dump-dir

mongorestore --host staging-server-host --username abcd --password bcda --drop --collection coll pruducting-dump-dir

Is there any option like ignore-collection when I'm dumpping?
any suggestion will be appreciated :3

Body:
As of Mongo 3.4, you can now specify an --nsExclude <namespace pattern> option when restoring from a Mongo database dump, which will exclude the specified namespaces from the restore operation. This is particularly useful when the mongodump operation has already occurred.

Official documentation here: https://docs.mongodb.com/manual/reference/program/mongorestore/#cmdoption-nsexclude

You can exclude multiple collections with wildcards:

mongorestore --db test --nsExclude 'test.*_tmp'

Or alternatively, specifying multiple --nsExclude options work as well:

mongorestore --db test --nsExclude 'test.collection1' --nsExclude 'test.collection2'


问:
Prolog: searching if 2 elements in a list occur equally
I am new to Prolog and not a native speaker, so if you do not understand me,  I am sorry.

My question is how can I find if a and b from a list appears equally?

For example, [a,a,b,b] should give me true but if either one appears more than the other it should give false. ex: [a,a,a,b,b].

Can anyone help me please? This is what I have so far and I know it is wrong but I am trying.

```<code>count(N,[],0).
count(N,[N|T],U) :-
   !,
   count(N,T,U1),
   U is U1+1.
count(N,[H|T],U) :-
   count(N,T,U).

occurrences([],[]).
occurrences([H|T],[[H,X]|Y]) :-
   count(H,[H|T],X),
   occurrences(T1,Y).
</code>```

答:
Instead of counting, you could pick a matching element from list' tail - it must exist - while visiting.

The recursion base case will be the simplest you can think of...
and select/3 is the built in that will enable a really compact solution to your problem.

edit

well, the code is easy...

```<code>occurrences([],[]).
occurrences([H|T],R) :- select(H,T,U), occurrences(U,R).
</code>```

note: on success, R will be the empty list

Body:
I am new to Prolog and not a native speaker, so if you do not understand me,  I am sorry.

My question is how can I find if a and b from a list appears equally?

For example, [a,a,b,b] should give me true but if either one appears more than the other it should give false. ex: [a,a,a,b,b].

Can anyone help me please? This is what I have so far and I know it is wrong but I am trying.

count(N,[],0).
count(N,[N|T],U) :-
   !,
   count(N,T,U1),
   U is U1+1.
count(N,[H|T],U) :-
   count(N,T,U).

occurrences([],[]).
occurrences([H|T],[[H,X]|Y]) :-
   count(H,[H|T],X),
   occurrences(T1,Y).

Body:
Instead of counting, you could pick a matching element from list' tail - it must exist - while visiting.

The recursion base case will be the simplest you can think of...
and select/3 is the built in that will enable a really compact solution to your problem.

edit

well, the code is easy...

occurrences([],[]).
occurrences([H|T],R) :- select(H,T,U), occurrences(U,R).

note: on success, R will be the empty list


问:
Python 2 - How to fix TypeError: an integer is required (got type str)
When i try to get my save it gives me this error i've been searching up other peoples answers but i cant find anything to solve my problem.

Traceback (most recent call last):

```<code>  File "C:\Users\user\Downloads\game.py", line 13, in <module>
    with open('objs.pickle', "latin1", "r") as f:  # Python 3: open(..., 'r')
TypeError: an integer is required (got type str)
</code>```

How can i fix this? This is my whole text game below

```<code>################################################################################
# python C:\Users\user\Downloads\game.py                                       #
#                                                                              #
#                                                                              #
#                                                                              #
################################################################################
import datetime
import time
from random import randint
import pickle
user_input = input ("Would you like to continue your save? (1=Yes) (2=No)")
if int(user_input) == 1:
    with open('objs.pickle', "latin1", "r") as f:  # Python 3: open(..., 'r')
        money = pickle.load(f)
else:
    start = 1
    timer2 = 0
    now = datetime.datetime.now()
    timer = ('{0}{1}'.format(now.hour, now.minute))
    hunger = 10
    thirst = 10
    energy = 10
    drinks = 0
    foods = 0
    money = 0
    plan = 150
    drink = 1
    food = 1.25
    wanted = 0
    gun = 0

print ("Chapter 1")
print ("The Big City")
time.sleep(1)
print ("You lost your brother recently and are very sad about it but something about his death bugs you the doctors told you that he died of a heart attack but you dont belive this and think he was murdered he used to write in a diary and he would keep it with him whenever he went to Mcdonalds You decide to move to the Big City")
def Eat():
    try:
        global money, plan, drink, food, drinks, foods, wanted, gun
        print (" ")
        print (" Hello welcome to Mcdonald's how may I help you")
        print ("\r Type 1 for food")
        print ("\r Type 2 for drinks")
        print ("\r Type 3 for money")
        user_input = input ("\r Type 4 to walk over to the shady guy")
        print (" ")
        if int(user_input) == 1:
            print (" ")
            print (" We have Hamburgers, fries, and cancer")
            print ("\r Type 1 for hamburgers")
            print ("\r Type 2 for fries")
            user_input = input ("\r Type 3 cancer")
            print (" ")
            if int(user_input) == 1:
                print (" ")
                print (" That will cost you $1.25")
                print ("\r Type 1 to pay")
                user_input = input ("Type 2 to steal")
                print (" ")
                if int(user_input) == 1:
                    print (" ")
                    print ("Thank you for comming")
                    money = float(money) - float(food)
                    print('You now have {0} Dollars '.format(money))
                    print (" ")
                foods = float(foods) + (1)
                if int(user_input) == 2:
                    print (" ")
                    print ("HEY COME BACK AND PAY!")
                    wanted = float(wanted) + (1)
                    print('Your wanted level is now {0}'.format(wanted))
                    print (" ")
            elif int(user_input) == 2:
                print (" ")
                print ("Potato!")
                print (" ")
            elif int(user_input) == 3:
                print (" ")
                print ("Sorry we are out of cancer")
                print (" ")
        elif int(user_input) == 2:
            print (" ")
            print ("We have Coke, and Pepsi")
            print ("Type 1 for Coke")
            user_input = input ("Type 2 for Pepsi")
            print (" ")
            if int(user_input) == 1:
                print (" ")
                print ("COKE SUCKS NO DRINKS FOR YOU!!!!!")
                print (" ")
            elif int(user_input) == 2:
                print (" ")
                print ("Nice I LOVE Pepsi Coke sucks that will cost you $1.00")
                print ("Type 1 to pay")
                user_input = input ("Type 2 to steal")
                print (" ")
                if int(user_input) == 1:
                    print (" ")
                    print ("Thank you for comming")
                    print (" ")
                    money = float(money) - float(drink)
                    print (" ")
                    print('You now have {0} Dollars '.format(money))
                    print (" ")
                elif int(user_input) == 2:
                    print (" ")
                    print ("HEY COME BACK AND PAY!")
                    wanted = float(wanted) + (1)
                    print('Your wanted level is now {0}'.format(wanted))
                    print (" ")
                drinks = float(drinks) + (1)
        elif int(user_input) == 3:
            print (" ")
            print ("So heres the plan you take the register ill destract the others.")
            user_input = input ("Type 1 to do the plan")
            print (" ")
            if int(user_input) == 1:
                plan = (randint(1,20))
                money = float(money) + float(plan)
                print (" ")
                print('You got {0} Dollars for doing the plan'.format(plan))
                print('You now have {0} Dollars '.format(money))
                wanted = float(wanted) + (1)
                print('Your wanted level is now {0}'.format(wanted))
                print (" ")
        elif int(user_input) == 4:
            print (" ")
            print ("Heres the deal I can sell you a Gun or Hack the wanted list.")
            print ("Type 1 to buy a gun for 500$")
            user_input = input ("Type 2 to hack for 100$")
            print (" ")
            if int(user_input) == 1:
                if money > 500:
                    print (" ")
                    print ("Here take it now run off before the cops come")
                    print (" ")
                    gun = 1
                    money = float(money) - (500)
            if int(user_input) == 2:
                if money > 100:
                    print (" ")
                    print ("Here im done now run off before the cops come")
                    print (" ")
                    wanted = 0
                    money = float(money) - (100)

        print (" ")
        print ("Type 1 to order")
        user_input = input ("Type 2 for main menu")
        print (" ")
        if int(user_input) == 1 and (money) > 1:
            Eat()
        elif int(user_input) == 2:
            menu()
        else:
            menu()
    except ValueError:
        Eat()

def work():
    global gain
    global money
    global energy
    gain = 1
    from random import randint
    work1 = (randint(1,20))
    hours = (randint(1,8))
    answer = float(work1) * float(hours)
    print (" ")
    print('Bob worked {0} hours and got {1} dollars per hour '.format(hours,work1))
    work2 = input('How much money did bob make')
    print (" ")
    if int(work2) == int(answer):
        print (" ")
        print ("you gained 1 Dollars")
        money = float(money) + float(gain)
        print('You now have {0} Dollars '.format(money))
        print("Type 1 to work again")
        user_input = input ("Type 2 to go to main menu")
        print (" ")
        energy = float(energy) - float(gain)
        if int(user_input) == 1:
            work()
        if int(user_input) == 2:
            menu()
    else:
        print (" ")
        print ("You lost 1 Dollar")
        if money > 0:
            money = float(money) - float(gain)
            print('You now have {0} Dollars '.format(money))
            print("Type 1 to work again")
            user_input = input ("Type 2 to go to main menu")
            print (" ")
            energy = float(energy) - float(gain)
            if int(user_input) == 1:
                work()
            if int(user_input) == 2:
                menu()
        else:
            print (" ")
            print('You now have {0} Dollars '.format(money))
            print("Type 1 to work again")
            user_input = input ("Type 2 to go to main menu")
            print (" ")
            energy = float(energy) - float(gain)
            if int(user_input) == 1:
                work()
            if int(user_input) == 2:
                menu()

def items():
    global energy
    global money
    global hunger
    global thirst
    global foods
    global drinks
    global gun
    print (" ")
    print('You have a wallet (${0})  '.format(money))
    if int(gun) > 0:
        print('You have a gun')
    if int(foods) > 0:
        print('You have {0} hamburgers type 1 to eat hamburger'.format(foods))
    if int(drinks) > 0:
        print('You have {0} Pepsi type 2 to drink Pepsi'.format(drinks))
    user_input = input('Type 3 to go to main menu')
    if int(user_input) == 1 and int(foods) > 0:
        hunger = float(hunger) + (3)
        energy = float(energy) + (3)
        foods = float(foods) - (1)
    if int(user_input) == 2 and int(drinks) > 0:
        thirst = float(thirst) + (2)
        energy = float(energy) + (1)
        drinks = float(drinks) - (1)
    if int(user_input) == 3:
        menu()
    print (" ")
    menu()
def dead():
    input("gg dude you ded")

def menu():
    global wanted
    global now
    global timer
    global hunger
    global thirst
    global money
    global gun
    now = datetime.datetime.now()
    timer2 = ('{0}{1}'.format(now.hour, now.minute))
    if (0) > (hunger) or (0) > (thirst):
        dead()
    if (wanted) > (9):
        if gun == 1:
            wanted = 9
            print (" ")
            print ("You shot the cops but you are not off their radar")
            print (" ")
        else:
            money = float(thirst) - float(money) * .5
            wanted = 0
            print (" ")
            print ("You got caught by the cops")
            print (" ")
    if (timer2) > (timer):
        thirst = float(thirst) - (1)
        hunger = float(hunger) - (1)
        timer = float(timer) + (1)
        timer = ('{0}{1}'.format(now.hour, now.minute))
        menu()
    print (" ")
    print ("Type 1 to Work")
    print ("Type 2 to go to Mcdonalds")
    print ("Type 3 to see your inventory")
    print('You have {0} / 10 hunger'.format(hunger))
    print('You have {0} / 10 thirst'.format(thirst))
    print('You have {0} / 10 energy'.format(energy))
    print('You have {0} / 10 wanted'.format(wanted))
    user_input = input('You have {0} dollars '.format(money))
    print (" ")
    if int(user_input) == 1:
        work()
    elif int(user_input) == 2 and (money) > 1:
        Eat()
    elif int(user_input) == 3:
        items()
    elif int(user_input) == 795535:
        money = float(money) + (1000)
        menu()
    elif int(user_input) == 4:
        with open('objs.pickle', 'ab') as f:  # Python 3: open(..., 'wb')
            pickle.dump([money], f)

    else:
        print (" ")
        print ("You need more money")
        print (" ")
        menu()
menu()
</code>```

答:
Syntax for Open:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Use this : encoding='UTF-8'

```<code>open('objs.pickle','r',encoding='latin1')
</code>```

Body:
When i try to get my save it gives me this error i've been searching up other peoples answers but i cant find anything to solve my problem.

Traceback (most recent call last):

  File "C:\Users\user\Downloads\game.py", line 13, in <module>
    with open('objs.pickle', "latin1", "r") as f:  # Python 3: open(..., 'r')
TypeError: an integer is required (got type str)

How can i fix this? This is my whole text game below

################################################################################
# python C:\Users\user\Downloads\game.py                                       #
#                                                                              #
#                                                                              #
#                                                                              #
################################################################################
import datetime
import time
from random import randint
import pickle
user_input = input ("Would you like to continue your save? (1=Yes) (2=No)")
if int(user_input) == 1:
    with open('objs.pickle', "latin1", "r") as f:  # Python 3: open(..., 'r')
        money = pickle.load(f)
else:
    start = 1
    timer2 = 0
    now = datetime.datetime.now()
    timer = ('{0}{1}'.format(now.hour, now.minute))
    hunger = 10
    thirst = 10
    energy = 10
    drinks = 0
    foods = 0
    money = 0
    plan = 150
    drink = 1
    food = 1.25
    wanted = 0
    gun = 0

print ("Chapter 1")
print ("The Big City")
time.sleep(1)
print ("You lost your brother recently and are very sad about it but something about his death bugs you the doctors told you that he died of a heart attack but you dont belive this and think he was murdered he used to write in a diary and he would keep it with him whenever he went to Mcdonalds You decide to move to the Big City")
def Eat():
    try:
        global money, plan, drink, food, drinks, foods, wanted, gun
        print (" ")
        print (" Hello welcome to Mcdonald's how may I help you")
        print ("\r Type 1 for food")
        print ("\r Type 2 for drinks")
        print ("\r Type 3 for money")
        user_input = input ("\r Type 4 to walk over to the shady guy")
        print (" ")
        if int(user_input) == 1:
            print (" ")
            print (" We have Hamburgers, fries, and cancer")
            print ("\r Type 1 for hamburgers")
            print ("\r Type 2 for fries")
            user_input = input ("\r Type 3 cancer")
            print (" ")
            if int(user_input) == 1:
                print (" ")
                print (" That will cost you $1.25")
                print ("\r Type 1 to pay")
                user_input = input ("Type 2 to steal")
                print (" ")
                if int(user_input) == 1:
                    print (" ")
                    print ("Thank you for comming")
                    money = float(money) - float(food)
                    print('You now have {0} Dollars '.format(money))
                    print (" ")
                foods = float(foods) + (1)
                if int(user_input) == 2:
                    print (" ")
                    print ("HEY COME BACK AND PAY!")
                    wanted = float(wanted) + (1)
                    print('Your wanted level is now {0}'.format(wanted))
                    print (" ")
            elif int(user_input) == 2:
                print (" ")
                print ("Potato!")
                print (" ")
            elif int(user_input) == 3:
                print (" ")
                print ("Sorry we are out of cancer")
                print (" ")
        elif int(user_input) == 2:
            print (" ")
            print ("We have Coke, and Pepsi")
            print ("Type 1 for Coke")
            user_input = input ("Type 2 for Pepsi")
            print (" ")
            if int(user_input) == 1:
                print (" ")
                print ("COKE SUCKS NO DRINKS FOR YOU!!!!!")
                print (" ")
            elif int(user_input) == 2:
                print (" ")
                print ("Nice I LOVE Pepsi Coke sucks that will cost you $1.00")
                print ("Type 1 to pay")
                user_input = input ("Type 2 to steal")
                print (" ")
                if int(user_input) == 1:
                    print (" ")
                    print ("Thank you for comming")
                    print (" ")
                    money = float(money) - float(drink)
                    print (" ")
                    print('You now have {0} Dollars '.format(money))
                    print (" ")
                elif int(user_input) == 2:
                    print (" ")
                    print ("HEY COME BACK AND PAY!")
                    wanted = float(wanted) + (1)
                    print('Your wanted level is now {0}'.format(wanted))
                    print (" ")
                drinks = float(drinks) + (1)
        elif int(user_input) == 3:
            print (" ")
            print ("So heres the plan you take the register ill destract the others.")
            user_input = input ("Type 1 to do the plan")
            print (" ")
            if int(user_input) == 1:
                plan = (randint(1,20))
                money = float(money) + float(plan)
                print (" ")
                print('You got {0} Dollars for doing the plan'.format(plan))
                print('You now have {0} Dollars '.format(money))
                wanted = float(wanted) + (1)
                print('Your wanted level is now {0}'.format(wanted))
                print (" ")
        elif int(user_input) == 4:
            print (" ")
            print ("Heres the deal I can sell you a Gun or Hack the wanted list.")
            print ("Type 1 to buy a gun for 500$")
            user_input = input ("Type 2 to hack for 100$")
            print (" ")
            if int(user_input) == 1:
                if money > 500:
                    print (" ")
                    print ("Here take it now run off before the cops come")
                    print (" ")
                    gun = 1
                    money = float(money) - (500)
            if int(user_input) == 2:
                if money > 100:
                    print (" ")
                    print ("Here im done now run off before the cops come")
                    print (" ")
                    wanted = 0
                    money = float(money) - (100)

        print (" ")
        print ("Type 1 to order")
        user_input = input ("Type 2 for main menu")
        print (" ")
        if int(user_input) == 1 and (money) > 1:
            Eat()
        elif int(user_input) == 2:
            menu()
        else:
            menu()
    except ValueError:
        Eat()

def work():
    global gain
    global money
    global energy
    gain = 1
    from random import randint
    work1 = (randint(1,20))
    hours = (randint(1,8))
    answer = float(work1) * float(hours)
    print (" ")
    print('Bob worked {0} hours and got {1} dollars per hour '.format(hours,work1))
    work2 = input('How much money did bob make')
    print (" ")
    if int(work2) == int(answer):
        print (" ")
        print ("you gained 1 Dollars")
        money = float(money) + float(gain)
        print('You now have {0} Dollars '.format(money))
        print("Type 1 to work again")
        user_input = input ("Type 2 to go to main menu")
        print (" ")
        energy = float(energy) - float(gain)
        if int(user_input) == 1:
            work()
        if int(user_input) == 2:
            menu()
    else:
        print (" ")
        print ("You lost 1 Dollar")
        if money > 0:
            money = float(money) - float(gain)
            print('You now have {0} Dollars '.format(money))
            print("Type 1 to work again")
            user_input = input ("Type 2 to go to main menu")
            print (" ")
            energy = float(energy) - float(gain)
            if int(user_input) == 1:
                work()
            if int(user_input) == 2:
                menu()
        else:
            print (" ")
            print('You now have {0} Dollars '.format(money))
            print("Type 1 to work again")
            user_input = input ("Type 2 to go to main menu")
            print (" ")
            energy = float(energy) - float(gain)
            if int(user_input) == 1:
                work()
            if int(user_input) == 2:
                menu()

def items():
    global energy
    global money
    global hunger
    global thirst
    global foods
    global drinks
    global gun
    print (" ")
    print('You have a wallet (${0})  '.format(money))
    if int(gun) > 0:
        print('You have a gun')
    if int(foods) > 0:
        print('You have {0} hamburgers type 1 to eat hamburger'.format(foods))
    if int(drinks) > 0:
        print('You have {0} Pepsi type 2 to drink Pepsi'.format(drinks))
    user_input = input('Type 3 to go to main menu')
    if int(user_input) == 1 and int(foods) > 0:
        hunger = float(hunger) + (3)
        energy = float(energy) + (3)
        foods = float(foods) - (1)
    if int(user_input) == 2 and int(drinks) > 0:
        thirst = float(thirst) + (2)
        energy = float(energy) + (1)
        drinks = float(drinks) - (1)
    if int(user_input) == 3:
        menu()
    print (" ")
    menu()
def dead():
    input("gg dude you ded")

def menu():
    global wanted
    global now
    global timer
    global hunger
    global thirst
    global money
    global gun
    now = datetime.datetime.now()
    timer2 = ('{0}{1}'.format(now.hour, now.minute))
    if (0) > (hunger) or (0) > (thirst):
        dead()
    if (wanted) > (9):
        if gun == 1:
            wanted = 9
            print (" ")
            print ("You shot the cops but you are not off their radar")
            print (" ")
        else:
            money = float(thirst) - float(money) * .5
            wanted = 0
            print (" ")
            print ("You got caught by the cops")
            print (" ")
    if (timer2) > (timer):
        thirst = float(thirst) - (1)
        hunger = float(hunger) - (1)
        timer = float(timer) + (1)
        timer = ('{0}{1}'.format(now.hour, now.minute))
        menu()
    print (" ")
    print ("Type 1 to Work")
    print ("Type 2 to go to Mcdonalds")
    print ("Type 3 to see your inventory")
    print('You have {0} / 10 hunger'.format(hunger))
    print('You have {0} / 10 thirst'.format(thirst))
    print('You have {0} / 10 energy'.format(energy))
    print('You have {0} / 10 wanted'.format(wanted))
    user_input = input('You have {0} dollars '.format(money))
    print (" ")
    if int(user_input) == 1:
        work()
    elif int(user_input) == 2 and (money) > 1:
        Eat()
    elif int(user_input) == 3:
        items()
    elif int(user_input) == 795535:
        money = float(money) + (1000)
        menu()
    elif int(user_input) == 4:
        with open('objs.pickle', 'ab') as f:  # Python 3: open(..., 'wb')
            pickle.dump([money], f)

    else:
        print (" ")
        print ("You need more money")
        print (" ")
        menu()
menu()

Body:
Syntax for Open:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Use this : encoding='UTF-8'

open('objs.pickle','r',encoding='latin1')


问:
Using spread correctly in R: Error
I have a dataframe inputData with columns acc_id, attrName, attrValue and timeStamp. The acc_id column will have duplicate entries because an example head of the data will be like this:

```<code>acc_id, attr_name, attr_value, timeStamp
123      abcVar1    138         Nov 1 2017
123      abcVar2    10          Nov 1 2017
123      abcVar3    2124        Nov 1 2017
468      abcVar1    13         Nov 9 2017
468      abcVar2    13458         Nov 9 2017
468      abcVar3    1238         Nov 9 2017
</code>```

The situation can be generalized where attr_name will have a lot more than just 3 unique variables as well.

It needs to be converted into the format

```<code>acc_id abcVar1 abcVar2 abcVar3 timeStamp
123     138      10      2124  Nov 1 2017
468     13       13458   1238  Nov 9 2017
</code>```

I tried spread(inputData,attr_name, attr_val) to get error

答:
Based on your example above I get this:

```<code>library(tidyr)

df = read.table(text = "
acc_id attr_name attr_value timeStamp
123      abcVar1    138         Nov_1_2017
123      abcVar2    10          Nov_1_2017
123      abcVar3    2124        Nov_1_2017
468      abcVar1    13          Nov_9_2017
468      abcVar2    13458       Nov_9_2017
468      abcVar3    1238        Nov_9_2017
", header=T, stringsAsFactors=F)

spread(df, attr_name, attr_value)

#   acc_id  timeStamp abcVar1 abcVar2 abcVar3
# 1    123 Nov_1_2017     138      10    2124
# 2    468 Nov_9_2017      13   13458    1238
</code>```

Maybe your example dataframe is not representative of your actual dataset.
I cannot replicate your problem.

However, it seems to break when there are duplicate rows like this:

```<code>library(tidyr)
library(dplyr)

df = read.table(text = "
acc_id attr_name attr_value timeStamp
123      abcVar1    138         Nov_1_2017
123      abcVar2    10          Nov_1_2017
123      abcVar3    2124        Nov_1_2017
468      abcVar1    13          Nov_9_2017
468      abcVar1    13          Nov_9_2017
468      abcVar2    13458       Nov_9_2017
468      abcVar3    1238        Nov_9_2017
", header=T, stringsAsFactors=F)

spread(df, attr_name, attr_value)

# Error: Duplicate identifiers for rows (4, 5)

# deduplicate and reshape
df %>%
  distinct() %>%
  spread(attr_name, attr_value)

#   acc_id  timeStamp abcVar1 abcVar2 abcVar3
# 1    123 Nov_1_2017     138      10    2124
# 2    468 Nov_9_2017      13   13458    1238
</code>```

Title: Using spread correctly in R: Error

Body:
I have a dataframe inputData with columns acc_id, attrName, attrValue and timeStamp. The acc_id column will have duplicate entries because an example head of the data will be like this:

acc_id, attr_name, attr_value, timeStamp
123      abcVar1    138         Nov 1 2017
123      abcVar2    10          Nov 1 2017
123      abcVar3    2124        Nov 1 2017
468      abcVar1    13         Nov 9 2017
468      abcVar2    13458         Nov 9 2017
468      abcVar3    1238         Nov 9 2017

The situation can be generalized where attr_name will have a lot more than just 3 unique variables as well.

It needs to be converted into the format

acc_id abcVar1 abcVar2 abcVar3 timeStamp
123     138      10      2124  Nov 1 2017
468     13       13458   1238  Nov 9 2017

I tried spread(inputData,attr_name, attr_val) to get error

Body:
Based on your example above I get this:

library(tidyr)

df = read.table(text = "
acc_id attr_name attr_value timeStamp
123      abcVar1    138         Nov_1_2017
123      abcVar2    10          Nov_1_2017
123      abcVar3    2124        Nov_1_2017
468      abcVar1    13          Nov_9_2017
468      abcVar2    13458       Nov_9_2017
468      abcVar3    1238        Nov_9_2017
", header=T, stringsAsFactors=F)

spread(df, attr_name, attr_value)

#   acc_id  timeStamp abcVar1 abcVar2 abcVar3
# 1    123 Nov_1_2017     138      10    2124
# 2    468 Nov_9_2017      13   13458    1238

Maybe your example dataframe is not representative of your actual dataset.
I cannot replicate your problem.

However, it seems to break when there are duplicate rows like this:

library(tidyr)
library(dplyr)

df = read.table(text = "
acc_id attr_name attr_value timeStamp
123      abcVar1    138         Nov_1_2017
123      abcVar2    10          Nov_1_2017
123      abcVar3    2124        Nov_1_2017
468      abcVar1    13          Nov_9_2017
468      abcVar1    13          Nov_9_2017
468      abcVar2    13458       Nov_9_2017
468      abcVar3    1238        Nov_9_2017
", header=T, stringsAsFactors=F)

spread(df, attr_name, attr_value)

# Error: Duplicate identifiers for rows (4, 5)

# deduplicate and reshape
df %>%
  distinct() %>%
  spread(attr_name, attr_value)

#   acc_id  timeStamp abcVar1 abcVar2 abcVar3
# 1    123 Nov_1_2017     138      10    2124
# 2    468 Nov_9_2017      13   13458    1238


问:
Using Model.create() and save() inside for loop
Hey so I'm pretty new to Javascript and Node but I'm running into an issue that's been bothering me for a while.

I have a User model and an Image model, I'm using Multer to upload an array of images and trying to loop through this array, create a new Image model for each, then unshift that Image into my User's photos. I have Multer set up to successfully fills req.files. Here's the code.

```<code>router.post("/users/:user/photos/upload", middle.isLoggedIn, upload.array("photos", 4), function(req, res) {
    User.findById(req.params.user, function(err, foundUser) {
        for(var i = 0, len = req.files.length; i < len; i++) {
            Image.create(req.files[i], function(err, newImage) {
                if(err) {
                    return console.log(err.message);
                }
                newImage.human = foundUser;
                newImage.save();
                console.log(newImage);
                foundUser.photos.unshift(newImage);
                foundUser.save();
            });
        }
        console.log(foundUser);
    });
});
</code>```

console.log(foundUser); seems to execute and print before console.log(newImage);

User Model

```<code>var mongoose                = require("mongoose"),
    passportLocalMongoose   = require("passport-local-mongoose");

var UserSchema = new mongoose.Schema({
    username: String,
    password: String,
    firstName: String,
    lastName: String,
    city: String,
    photos: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Image"
        }
    ]
});

HumanSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
</code>```

Image Model

```<code>var mongoose            = require("mongoose");

var ImageSchema = new mongoose.Schema({
    fieldname: String,
    originalname: String,
    mimetype: String,
    filename: String,
    destination: String,
    size: Number,
    path: String,
    human: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Human"
        }
    }
});

module.exports = mongoose.model("Image", ImageSchema);
</code>```

This is my first stackoverflow question so let me know if I didn't post enough code.

I think it have something to do with Image.create() being asynchronous, and I'm still trying to learn more about this and promises, but I still don't fully understand how it's relevant in my code.

答:
Use Mongoose's promise support.

Promise.all allows you to resolve an array of promises.

async/await control flow for Promises.

I'm not sure your code as it is structured will work without a serial loop due the async code that can execute in any order. I'm not sure that triggering multiple foundUser.save()s on the same object at different times will work out very well. Holding database objects in memory for a long time can open up more concurrency data issues too.

The Bluebird promise library includes some additional helpers like Promise.each which will serially complete promises before the next starts which may be of use here.

```<code>const Promise = require('bluebird')

router.post("/users/:user/photos/upload", middle.isLoggedIn, upload.array("photos", 4), async function(req, res, next) {
    try {
        let foundUser = await User.findById(req.params.user)
        await Promise.each(req.files, async file => {
            let newImage = await Image.create(file)
            newImage.human = foundUser;
            await newImage.save()
            console.log(newImage)
            foundUser.photos.unshift(newImage)
            await foundUser.save()
        }
        console.log(foundUser)
    }
    catch (err) {
        next(err)
    }
})
</code>```

Other methods like .map and .reduce help make standard array/loop type operations with Promises easier to do.

Atomic Updates

In regards to the concurrency issue, any updates you can do in MongoDB that are "atomic" are a good thing. So instead of selecting something, modifying it in JS, then saving it back, you send the update to Mongo and let the db server deal with it. No matter what order you send the updates to the database, they will always be updating the latest copy of data.

In this case the array unshift can be completed without the initial select by using findByIdAndUpdate and $push (it can be made to push at position 0, there is no $unshift in mongo).

If you add a method to your User model for the adding the photo:

```<code>addPhoto(user_id, newImage){
    return User.findByIdAndUpdate(
        user_id,
        { $push: { photos: { $each: [newImage], $position: 0 } } } }
        { safe: true, new: true }
    )
}
</code>```

So the code would look like

```<code>const Promise = require('bluebird')

router.post("/users/:user/photos/upload", middle.isLoggedIn, upload.array("photos", 4), async function(req, res, next) {
    try {
        let foundUser = await User.findById(req.params.user)
        if (!foundUser) throw new Error(`No user found: $user`)
        let results = await Promise.map(req.files, async file => {
            let newImage = await Image.create(file)
            newImage.human = foundUser
            await newImage.save()
            console.log(newImage)
            let user_update = await User.addPhoto(req.params.user, newImage)
            console.log(user_update)
        }
    }
    catch (err) {
        next(err)
    }
})
</code>```

Body:
Hey so I'm pretty new to Javascript and Node but I'm running into an issue that's been bothering me for a while.

I have a User model and an Image model, I'm using Multer to upload an array of images and trying to loop through this array, create a new Image model for each, then unshift that Image into my User's photos. I have Multer set up to successfully fills req.files. Here's the code.

router.post("/users/:user/photos/upload", middle.isLoggedIn, upload.array("photos", 4), function(req, res) {
    User.findById(req.params.user, function(err, foundUser) {
        for(var i = 0, len = req.files.length; i < len; i++) {
            Image.create(req.files[i], function(err, newImage) {
                if(err) {
                    return console.log(err.message);
                }
                newImage.human = foundUser;
                newImage.save();
                console.log(newImage);
                foundUser.photos.unshift(newImage);
                foundUser.save();
            });
        }
        console.log(foundUser);
    });
});

console.log(foundUser); seems to execute and print before console.log(newImage);

User Model

var mongoose                = require("mongoose"),
    passportLocalMongoose   = require("passport-local-mongoose");

var UserSchema = new mongoose.Schema({
    username: String,
    password: String,
    firstName: String,
    lastName: String,
    city: String,
    photos: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Image"
        }
    ]
});

HumanSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);

Image Model

var mongoose            = require("mongoose");

var ImageSchema = new mongoose.Schema({
    fieldname: String,
    originalname: String,
    mimetype: String,
    filename: String,
    destination: String,
    size: Number,
    path: String,
    human: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Human"
        }
    }
});

module.exports = mongoose.model("Image", ImageSchema);

This is my first stackoverflow question so let me know if I didn't post enough code.

I think it have something to do with Image.create() being asynchronous, and I'm still trying to learn more about this and promises, but I still don't fully understand how it's relevant in my code.

Body:
Use Mongoose's promise support.

Promise.all allows you to resolve an array of promises.

async/await control flow for Promises.

I'm not sure your code as it is structured will work without a serial loop due the async code that can execute in any order. I'm not sure that triggering multiple foundUser.save()s on the same object at different times will work out very well. Holding database objects in memory for a long time can open up more concurrency data issues too.

The Bluebird promise library includes some additional helpers like Promise.each which will serially complete promises before the next starts which may be of use here.

const Promise = require('bluebird')

router.post("/users/:user/photos/upload", middle.isLoggedIn, upload.array("photos", 4), async function(req, res, next) {
    try {
        let foundUser = await User.findById(req.params.user)
        await Promise.each(req.files, async file => {
            let newImage = await Image.create(file)
            newImage.human = foundUser;
            await newImage.save()
            console.log(newImage)
            foundUser.photos.unshift(newImage)
            await foundUser.save()
        }
        console.log(foundUser)
    }
    catch (err) {
        next(err)
    }
})

Other methods like .map and .reduce help make standard array/loop type operations with Promises easier to do.

Atomic Updates

In regards to the concurrency issue, any updates you can do in MongoDB that are "atomic" are a good thing. So instead of selecting something, modifying it in JS, then saving it back, you send the update to Mongo and let the db server deal with it. No matter what order you send the updates to the database, they will always be updating the latest copy of data.

In this case the array unshift can be completed without the initial select by using findByIdAndUpdate and $push (it can be made to push at position 0, there is no $unshift in mongo).

If you add a method to your User model for the adding the photo:

addPhoto(user_id, newImage){
    return User.findByIdAndUpdate(
        user_id,
        { $push: { photos: { $each: [newImage], $position: 0 } } } }
        { safe: true, new: true }
    )
}

So the code would look like

const Promise = require('bluebird')

router.post("/users/:user/photos/upload", middle.isLoggedIn, upload.array("photos", 4), async function(req, res, next) {
    try {
        let foundUser = await User.findById(req.params.user)
        if (!foundUser) throw new Error(`No user found: $user`)
        let results = await Promise.map(req.files, async file => {
            let newImage = await Image.create(file)
            newImage.human = foundUser
            await newImage.save()
            console.log(newImage)
            let user_update = await User.addPhoto(req.params.user, newImage)
            console.log(user_update)
        }
    }
    catch (err) {
        next(err)
    }
})


问:
Debugging a Scrollbar code that's not working properly on Blogger
I've been trying to get this scrollbar code to work on Blogger, but haven't been able to figure out how to. Can someone see if they are able to figure out what the issue is, and how to resolve it.

Same Code, Both look and act different,

Jsfiddle:

https://jsfiddle.net/xuc92tt3/

Screenshot

vs.

Blogger:

https://debugscroll.blogspot.com/

Screenshot

Also, there shouldn't be a horizontal line below the div blocks either.

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

```

答:
Looks like in the blogspot example your
 elements are inheriting a 15px padding from a global style declared in the page head section.

Try overriding that with the following css:

```<code>.test li {
    padding-bottom: 20px;
    padding-left: 0;
    padding-right: 0;
}
</code>```

Body:
Looks like in the blogspot example your <li> elements are inheriting a 15px padding from a global style declared in the page head section.

Try overriding that with the following css:

.test li {
    padding-bottom: 20px;
    padding-left: 0;
    padding-right: 0;
}


问:
Plot the most (n) occurring values of a column with all of data of other column
I have following data in a Pandas DataFrame from a sql query:

```<code>      latin_brands   group phone_brand_chinese_match only_latin_brands
0           xiaomi  M32-38                        小米            xiaomi
1           xiaomi  M32-38                        小米            xiaomi
2           xiaomi  M32-38                        小米            xiaomi
3           xiaomi  M29-31                        小米            xiaomi
4           xiaomi  M29-31                        小米            xiaomi
5             None  F24-26                      OPPO              OPPO
6          coolpad  M32-38                        酷派           coolpad
7           xiaomi  M32-38                        小米            xiaomi
8             None  M32-38                      vivo              vivo
9          samsung  F33-42                        三星           samsung
10          huawei  M29-31                        华为            huawei
11          huawei  F33-42                        华为            huawei
12         samsung  F27-28                        三星           samsung
13          huawei  M32-38                        华为            huawei
14         aiyouni    M39+                       艾优尼           aiyouni
15          huawei  F27-28                        华为            huawei
16          xiaomi  M32-38                        小米            xiaomi
17          xiaomi  M32-38                        小米            xiaomi
18           meizu    M39+                        魅族             meizu
19          xiaomi  M32-38                        小米            xiaomi
20         samsung  F33-42                        三星           samsung
21          xiaomi  M23-26                        小米            xiaomi
22          huawei  M23-26                        华为            huawei
23         samsung  M27-28                        三星           samsung
24          xiaomi  M29-31                        小米            xiaomi
25         samsung  M32-38                        三星           samsung
26         samsung  M32-38                        三星           samsung
27         samsung  F33-42                        三星           samsung
28         samsung  M32-38                        三星           samsung
29         samsung  M32-38                        三星           samsung
...            ...     ...                       ...               ...
74809       huawei  M27-28                        华为            huawei
74810         None  M29-31                       TCL               TCL
</code>```

I want to map two columns and plot this on a line chart.
My approach:

```<code>phones = phones.groupby(['only_latin_brands', 'group']).size()
phones = phones.unstack()
phones = phones.fillna(0)
phones.head()
phones.plot(kind='line')
plt.show()
</code>```

I want to plot the relation between the group and the only_latin_brands.

How can I plot only the most occurring 20 only_latin_brands column with their groups?

答:
Using @AndyHayden start:

```<code>df[df.only_latin_brands.isin(df.groupby('only_latin_brands').size().nlargest(3).index)]\
  .groupby(['group','only_latin_brands']).size().unstack().fillna(0)\
  .plot(kind='line')
</code>```

Edit to show all groups:

```<code>df[df.only_latin_brands.isin(df.groupby('only_latin_brands').size().nlargest(3).index)]\
  .groupby(['group','only_latin_brands']).size().unstack()\
  .reindex(df.group.unique()).fillna(0).plot(kind='line')
</code>```

Body:
I have following data in a Pandas DataFrame from a sql query:

      latin_brands   group phone_brand_chinese_match only_latin_brands
0           xiaomi  M32-38                        小米            xiaomi
1           xiaomi  M32-38                        小米            xiaomi
2           xiaomi  M32-38                        小米            xiaomi
3           xiaomi  M29-31                        小米            xiaomi
4           xiaomi  M29-31                        小米            xiaomi
5             None  F24-26                      OPPO              OPPO
6          coolpad  M32-38                        酷派           coolpad
7           xiaomi  M32-38                        小米            xiaomi
8             None  M32-38                      vivo              vivo
9          samsung  F33-42                        三星           samsung
10          huawei  M29-31                        华为            huawei
11          huawei  F33-42                        华为            huawei
12         samsung  F27-28                        三星           samsung
13          huawei  M32-38                        华为            huawei
14         aiyouni    M39+                       艾优尼           aiyouni
15          huawei  F27-28                        华为            huawei
16          xiaomi  M32-38                        小米            xiaomi
17          xiaomi  M32-38                        小米            xiaomi
18           meizu    M39+                        魅族             meizu
19          xiaomi  M32-38                        小米            xiaomi
20         samsung  F33-42                        三星           samsung
21          xiaomi  M23-26                        小米            xiaomi
22          huawei  M23-26                        华为            huawei
23         samsung  M27-28                        三星           samsung
24          xiaomi  M29-31                        小米            xiaomi
25         samsung  M32-38                        三星           samsung
26         samsung  M32-38                        三星           samsung
27         samsung  F33-42                        三星           samsung
28         samsung  M32-38                        三星           samsung
29         samsung  M32-38                        三星           samsung
...            ...     ...                       ...               ...
74809       huawei  M27-28                        华为            huawei
74810         None  M29-31                       TCL               TCL

I want to map two columns and plot this on a line chart.
My approach:

phones = phones.groupby(['only_latin_brands', 'group']).size()
phones = phones.unstack()
phones = phones.fillna(0)
phones.head()
phones.plot(kind='line')
plt.show()

I want to plot the relation between the group and the only_latin_brands.

How can I plot only the most occurring 20 only_latin_brands column with their groups?

Body:
Using @AndyHayden start:

df[df.only_latin_brands.isin(df.groupby('only_latin_brands').size().nlargest(3).index)]\
  .groupby(['group','only_latin_brands']).size().unstack().fillna(0)\
  .plot(kind='line')

Edit to show all groups:

df[df.only_latin_brands.isin(df.groupby('only_latin_brands').size().nlargest(3).index)]\
  .groupby(['group','only_latin_brands']).size().unstack()\
  .reindex(df.group.unique()).fillna(0).plot(kind='line')


问:
jwplayer v7.xx _.getVideoData is not a function issue
From today I have the following issue on youtube hosted videos when I want to change dynamically the video on my site.

_.getVideoData is not a function

```<code>Uncaught TypeError: _.getVideoData is not a function
at M (ssl.p.jwpcdn.com/player/v/7.12.11/provider.youtube.js:1)
at load (ssl.p.jwpcdn.com/player/v/7.12.11/provider.youtube.js:1)
at l.a (ssl.p.jwpcdn.com/player/v/7.12.11/provider.youtube.js:1)
at l.<anonymous>
(ssl.p.jwpcdn.com/player/v/7.12.11/provider.youtube.js:1)
at P (ssl.p.jwpcdn.com/player/v/7.12.11/provider.youtube.js:1)
at K.f.I (s.ytimg.com/yts/jsbin/www-widgetapi-vflnzpyZ4/www-
widgetapi.js:66)
at W.f.l (s.ytimg.com/yts/jsbin/www-widgetapi-vflnzpyZ4/www-
widgetapi.js:114)
at W.f.J (s.ytimg.com/yts/jsbin/www-widgetapi-vflnzpyZ4/www-
widgetapi.js:127)
at S.g (s.ytimg.com/yts/jsbin/www-widgetapi-vflnzpyZ4/www-
widgetapi.js:143)
at g (s.ytimg.com/yts/jsbin/www-widgetapi-vflnzpyZ4/www-
widgetapi.js:95)
</code>```

Until today it worked fine. (The jwplayer 8 version show the same issue)

答:
While you wait for word from Google, I've created a plugin to fix it in the meantime. Download it from here:

https://www.dev.powered-by-haiku.co.uk/solutions/getvideodata/code/getvideodata.js

(NOTE: You'll need to copy & paste the URL into the browser to get the code as hotlinking is not allowed)

Apply it as you would any other JW plugin:

```<code>"plugins":{
     "getvideodata.js":{}
}
</code>```

EDIT: This has now been updated to cater for the "autostart":true scenario.
Please note that recent versions of Chrome now block media plays that are not initiated via a user gesture, and because JW Player doesn't handle the resulting error state gracefully (when trying to autostart YouTube for example), the player will get into an apparent endless buffering state. This plugin resolves this by cancelling the autostart request on Chrome and leaves it to the user to initiate playback.

Body:
From today I have the following issue on youtube hosted videos when I want to change dynamically the video on my site.

_.getVideoData is not a function

Uncaught TypeError: _.getVideoData is not a function
at M (ssl.p.jwpcdn.com/player/v/7.12.11/provider.youtube.js:1)
at load (ssl.p.jwpcdn.com/player/v/7.12.11/provider.youtube.js:1)
at l.a (ssl.p.jwpcdn.com/player/v/7.12.11/provider.youtube.js:1)
at l.<anonymous>
(ssl.p.jwpcdn.com/player/v/7.12.11/provider.youtube.js:1)
at P (ssl.p.jwpcdn.com/player/v/7.12.11/provider.youtube.js:1)
at K.f.I (s.ytimg.com/yts/jsbin/www-widgetapi-vflnzpyZ4/www-
widgetapi.js:66)
at W.f.l (s.ytimg.com/yts/jsbin/www-widgetapi-vflnzpyZ4/www-
widgetapi.js:114)
at W.f.J (s.ytimg.com/yts/jsbin/www-widgetapi-vflnzpyZ4/www-
widgetapi.js:127)
at S.g (s.ytimg.com/yts/jsbin/www-widgetapi-vflnzpyZ4/www-
widgetapi.js:143)
at g (s.ytimg.com/yts/jsbin/www-widgetapi-vflnzpyZ4/www-
widgetapi.js:95)

Until today it worked fine. (The jwplayer 8 version show the same issue)

Body:
While you wait for word from Google, I've created a plugin to fix it in the meantime. Download it from here:

https://www.dev.powered-by-haiku.co.uk/solutions/getvideodata/code/getvideodata.js

(NOTE: You'll need to copy & paste the URL into the browser to get the code as hotlinking is not allowed)

Apply it as you would any other JW plugin:

"plugins":{
     "getvideodata.js":{}
}

EDIT: This has now been updated to cater for the "autostart":true scenario.
Please note that recent versions of Chrome now block media plays that are not initiated via a user gesture, and because JW Player doesn't handle the resulting error state gracefully (when trying to autostart YouTube for example), the player will get into an apparent endless buffering state. This plugin resolves this by cancelling the autostart request on Chrome and leaves it to the user to initiate playback.


问:
Selenium Webscraping Twitter - Getting hold of tweet timestamp?
When inspecting a twitter results page, within the following class:

```<code>    <small class="time">
         ....
    </small>
</code>```

Is a timestamp for each tweet 'data-time':

```<code><span class="_timestamp js-short-timestamp js-relative-timestamp" data-time="1510698047" data-time-ms="1510698047000" data-long-form="true" aria-hidden="true">12m</span>
</code>```

Within selenium i am using the following code:

```<code>tweet_date = browser.find_elements_by_class_name('_timestamp')
</code>```

But looking at a single entry only returns, in this case, 12m.

How is it possible to access one of the other properties within the class within selenium?

答:
I usually use find_elements_by_xpath, this will let you grab a specific element from a page without worrying about names. Or so that's how it seems to work.

EDIT

Alright so I think I've got it figured out. First, find element by xpath and assign.

```<code>ts=browser.find_elements_by_xpath('//*[@id="stream-item-tweet-929138668551380992"]/div/div[2]/div[1]/small/a/span')
</code>```

Forgot that if you use "elements" instead of "element" you'll need to add something like this.

```<code>ts=ts[0]
</code>```

Then you can use the get_attribute method to get the info associated with 'data-time' in the html.

```<code>raw_time=ts.get_attribute('data-time')
</code>```

Returns

```<code>raw_time == '1510358895'
</code>```

Body:
When inspecting a twitter results page, within the following class:

         ....

Is a timestamp for each tweet 'data-time':

12m

Within selenium i am using the following code:

tweet_date = browser.find_elements_by_class_name('_timestamp')

But looking at a single entry only returns, in this case, 12m.

How is it possible to access one of the other properties within the class within selenium?

Body:
I usually use find_elements_by_xpath, this will let you grab a specific element from a page without worrying about names. Or so that's how it seems to work.

EDIT

Alright so I think I've got it figured out. First, find element by xpath and assign.

ts=browser.find_elements_by_xpath('//*[@id="stream-item-tweet-929138668551380992"]/div/div[2]/div[1]/small/a/span')

Forgot that if you use "elements" instead of "element" you'll need to add something like this.

ts=ts[0]

Then you can use the get_attribute method to get the info associated with 'data-time' in the html.

raw_time=ts.get_attribute('data-time')

Returns

raw_time == '1510358895'


问:
Android app for a web application without an API
Is it possible to create an Android app for an existing web application which doesn't provide any API?

Webview just provides a crude view of the same web app in Android, but interface with webview looks crappy.

答:
What you're asking is very possible.  Just load up your URL in the webview and then redirect all clicks to go back to the same view.  There you have an embedded website into an application. </p>

<p>What do you mean by interface for WebView looks crappy?  You can make it look like anything native on the phone.  </p>

Body:
What you're asking is very possible.  Just load up your URL in the webview and then redirect all clicks to go back to the same view.  There you have an embedded website into an application.

What do you mean by interface for WebView looks crappy?  You can make it look like anything native on the phone.