问:
spark, cassandra, streaming, python, error, database, kafka
im trying to save my streaming data from spark to cassandra, spark is conected to kafka and its working ok, but saving to cassandra its making me become crazy. Im using spark 2.0.2, kafka 0.10 and cassandra 2.23,

this is how im submiting to spark

```<code>spark-submit --verbose --packages org.apache.spark:spark-streaming-kafka-0-8_2.11:2.0.0 --jars /tmp/pyspark-cassandra-0.3.5.jar --driver-class-path /tmp/pyspark-cassandra-0.3.5.jar --py-files /tmp/pyspark-cassandra-0.3.5.jar --conf spark.cassandra.connection.host=localhost /tmp/direct_kafka_wordcount5.py localhost:9092 testing
</code>```

and this is my code it just a little modification from the spark examples, its works but i cant save this data to cassandra....

and this what im trying to do but just with the count result
http://rustyrazorblade.com/2015/05/spark-streaming-with-python-and-kafka/

```<code>    from __future__ import print_function
import sys
import os
import time
import pyspark_cassandra
import pyspark_cassandra.streaming
from pyspark_cassandra import CassandraSparkContext
import urllib
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
from pyspark.sql import SQLContext
from pyspark.sql import Row
from pyspark.sql.types import IntegerType
from pyspark.sql.functions import udf
from pyspark.sql.functions import from_unixtime, unix_timestamp, min, max
from pyspark.sql.types import FloatType
from pyspark.sql.functions import explode
from pyspark.sql.functions import split
if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: direct_kafka_wordcount.py <broker_list> <topic>", file=sys.stderr)
        exit(-1)
    sc = SparkContext(appName="PythonStreamingDirectKafkaWordCount")
    ssc = StreamingContext(sc, 1)
    sqlContext = SQLContext(sc)
    brokers, topic = sys.argv[1:]
    kvs = KafkaUtils.createDirectStream(ssc, [topic], {"metadata.broker.list": brokers})
    lines = kvs.map(lambda x: x[1])
    counts=lines.count()
    counts.saveToCassandra("spark", "count")
    counts.pprint()
    ssc.start()
    ssc.awaitTermination()
</code>```

i got this error,

Traceback (most recent call last):
  File "/tmp/direct_kafka_wordcount5.py", line 88, in
    counts.saveToCassandra("spark", "count")

答:
Pyspark Casasndra stopped being updated a while ago and the latest version only supports up to Spark 1.6
https://github.com/TargetHolding/pyspark-cassandra

Additionally

```<code>counts=lines.count() // Returns data to the driver (not an RDD)
</code>```

counts is now an Integer. This means the function saveToCassandra doesn't apply since that is a function for RDDs

Body:
im trying to save my streaming data from spark to cassandra, spark is conected to kafka and its working ok, but saving to cassandra its making me become crazy. Im using spark 2.0.2, kafka 0.10 and cassandra 2.23,

this is how im submiting to spark

spark-submit --verbose --packages org.apache.spark:spark-streaming-kafka-0-8_2.11:2.0.0 --jars /tmp/pyspark-cassandra-0.3.5.jar --driver-class-path /tmp/pyspark-cassandra-0.3.5.jar --py-files /tmp/pyspark-cassandra-0.3.5.jar --conf spark.cassandra.connection.host=localhost /tmp/direct_kafka_wordcount5.py localhost:9092 testing

and this is my code it just a little modification from the spark examples, its works but i cant save this data to cassandra....

and this what im trying to do but just with the count result
http://rustyrazorblade.com/2015/05/spark-streaming-with-python-and-kafka/

    from __future__ import print_function
import sys
import os
import time
import pyspark_cassandra
import pyspark_cassandra.streaming
from pyspark_cassandra import CassandraSparkContext
import urllib
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
from pyspark.sql import SQLContext
from pyspark.sql import Row
from pyspark.sql.types import IntegerType
from pyspark.sql.functions import udf
from pyspark.sql.functions import from_unixtime, unix_timestamp, min, max
from pyspark.sql.types import FloatType
from pyspark.sql.functions import explode
from pyspark.sql.functions import split
if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: direct_kafka_wordcount.py <broker_list> <topic>", file=sys.stderr)
        exit(-1)
    sc = SparkContext(appName="PythonStreamingDirectKafkaWordCount")
    ssc = StreamingContext(sc, 1)
    sqlContext = SQLContext(sc)
    brokers, topic = sys.argv[1:]
    kvs = KafkaUtils.createDirectStream(ssc, [topic], {"metadata.broker.list": brokers})
    lines = kvs.map(lambda x: x[1])
    counts=lines.count()
    counts.saveToCassandra("spark", "count")
    counts.pprint()
    ssc.start()
    ssc.awaitTermination()

i got this error,

Traceback (most recent call last):
  File "/tmp/direct_kafka_wordcount5.py", line 88, in
    counts.saveToCassandra("spark", "count")

Body:
Pyspark Casasndra stopped being updated a while ago and the latest version only supports up to Spark 1.6
https://github.com/TargetHolding/pyspark-cassandra

Additionally

counts=lines.count() // Returns data to the driver (not an RDD)

counts is now an Integer. This means the function saveToCassandra doesn't apply since that is a function for RDDs


来源: stackexchange

问:
Applying global style across multiple assemblies
My application is composed from quite a few assemblies ("plug-ins") that are loaded by a core executable assembly (which doesn't contain any controls or windows on it own). Now I want to apply styles to controls (such as Menus/ContextMenus, ToolBar(Tray)s etc.) from the central assembly's Application.Resources styles (possibly with the option of users being able to choose from several themes).

I got it to work with named styles (x:Key="StyleName", invoked by DynamicResource, StaticResource wouldn't work), but the prospect of adding the Style="{DynamicResource ...}" to every control in every assembly scares me quire a little bit. But the control-wide styles with TargetType="{x:Type TypeName}" won't work no matter what I do.

How can I style all the controls en masse from one central assembly?

Thanks for help.

答:
Perhaps this great article on WPF skinning might help point you in the right direction?

In the intro, he highlights the "three pillars" for skinning/theming and how hierarchical resources can be leveraged.

Though I do fear (without certainty) that you might still need to change your static resources to dynamic ones.

ContentLicense: CC BY-SA 2.5


问:
Connect to Wifi programmatically not working for Android Marshmallow?
```<code>String BACKSLASH = "\"";
String NETWROK_SECURITY_WEP = "WEP";
String NETWROK_SECURITY_NONE = "NONE";
String NETWROK_SECURITY_WPA = "WPA";
String NETWROK_SECURITY_WPA2 = "WPA2";
String NETWROK_SECURITY_WPA_WPA2 = "WPA/WPA2 PSK";
String NETWROK_ADDITIONAL_SECURITY_TKIP = "TKIP";
String NETWROK_ADDITIONAL_SECURITY_AES = "AES";
String NETWROK_ADDITIONAL_SECURITY_WEP = "WEP";
String NETWROK_ADDITIONAL_SECURITY_NONE = "NONE";
int FAILED_TO_ADD_NETWORK = -1;

WifiConfiguration conf = new WifiConfiguration();
String wifiName = sSid;
conf.SSID = BACKSLASH + wifiName + BACKSLASH;
String securityType = NETWROK_SECURITY_WPA_WPA2;

if (NETWROK_SECURITY_WEP.equalsIgnoreCase(securityType)) {
    conf.wepKeys[0] = pass;
    conf.wepTxKeyIndex = 0;
    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
} else if (NETWROK_SECURITY_NONE.equalsIgnoreCase(securityType)) {
    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
} else if (NETWROK_SECURITY_WPA.equalsIgnoreCase(securityType)
        || NETWROK_SECURITY_WPA2.equalsIgnoreCase(securityType)
        || NETWROK_SECURITY_WPA_WPA2.equalsIgnoreCase(securityType)) {
    conf.preSharedKey = BACKSLASH + pass + BACKSLASH;
    conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    conf.status = WifiConfiguration.Status.ENABLED;
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
}
String wlanAdditionalSecurity = "";
if (NETWROK_ADDITIONAL_SECURITY_TKIP.equalsIgnoreCase(wlanAdditionalSecurity)) {
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
} else if (NETWROK_ADDITIONAL_SECURITY_AES.equalsIgnoreCase(wlanAdditionalSecurity)) {
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
} else if (NETWROK_ADDITIONAL_SECURITY_WEP.equalsIgnoreCase(wlanAdditionalSecurity)) {
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
} else if (NETWROK_ADDITIONAL_SECURITY_NONE.equalsIgnoreCase(wlanAdditionalSecurity)) {
    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.NONE);
}
WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
int res = wifiManager.addNetwork(conf);
wifiManager.disconnect();
wifiManager.reconnect();

if (true) {

    wifiManager.enableNetwork(res, true);

    wifiManager.saveConfiguration();
    wifiManager.setWifiEnabled(true);

    new AppPreferences(mContext).setPrefrenceLong("connectTime", Calendar.getInstance().getTimeInMillis());
}
if (res != -1) {

    setFalseOther(mm);
    notifyDataSetChanged();

    Intent i = new Intent(mContext, Connect.class);
    i.putExtra("networkName", mm.getName());
    i.putExtra("networkId", mm.getId());
    i.putExtra("AdminID", mm.getUserId());
    i.putExtra("networkConnection", "true");

    mContext.startActivity(i);

} else {

}
</code>```

This code is for connecting to WiFi. It's working fine on Android Lollipop but I want to set up configuration programmatically for Marshmallow. I've given all the run time permissions and dangerous permission but still no help and unable to remove saved WiFi passwords. If anyone has done this for Marshmallow it would be helpful.

答:
well I think I have found the solution for this...tested and working fine..

```<code>public boolean connectToWifi(String knownSSID,String key) {

    try{
        //If Wifi is not enabled, enable it
        if (!mWifiManager.isWifiEnabled()) {
            Log.v(LOG_TAG, "Wifi is not enabled, enable it");
            mWifiManager.setWifiEnabled(true);
        }
        WifiConfiguration config = new WifiConfiguration();
        config.SSID = convertToQuotedString(knownSSID);
        // if key is empty means it is open network-- I am considering like this
        if(key.isEmpty()){
            config.allowedKeyManagement.set(KeyMgmt.NONE);
        } else {
            config.preSharedKey = convertToQuotedString(key);
        }

        int networkId = mWifiManager.addNetwork(config);
        // it will return -1 if the config is already saved..
        if(networkId == -1){
            networkId = getExistingNetworkId(config.SSID);
        }
        boolean es = mWifiManager.saveConfiguration();

        mWifiManager.disconnect();
        // giving time to disconnect here.
        Thread.sleep(3*1000);
        boolean bRet = mWifiManager.enableNetwork(networkId, true);
        mWifiManager.reconnect();

    } catch(InterruptedException e) {

    }
</code>```

}

```<code>public int getExistingNetworkId(String SSID){
    List<WifiConfiguration> configuredNetworks = mWifiManager.getConfiguredNetworks();
    if (configuredNetworks != null) {
        for (WifiConfiguration existingConfig : configuredNetworks) {
           if (SSID.equalsIgnoreCase(existingConfig.SSID)) {
               return existingConfig.networkId;
            }
        }
    }
    return -1;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
String BACKSLASH = "\"";
String NETWROK_SECURITY_WEP = "WEP";
String NETWROK_SECURITY_NONE = "NONE";
String NETWROK_SECURITY_WPA = "WPA";
String NETWROK_SECURITY_WPA2 = "WPA2";
String NETWROK_SECURITY_WPA_WPA2 = "WPA/WPA2 PSK";
String NETWROK_ADDITIONAL_SECURITY_TKIP = "TKIP";
String NETWROK_ADDITIONAL_SECURITY_AES = "AES";
String NETWROK_ADDITIONAL_SECURITY_WEP = "WEP";
String NETWROK_ADDITIONAL_SECURITY_NONE = "NONE";
int FAILED_TO_ADD_NETWORK = -1;

WifiConfiguration conf = new WifiConfiguration();
String wifiName = sSid;
conf.SSID = BACKSLASH + wifiName + BACKSLASH;
String securityType = NETWROK_SECURITY_WPA_WPA2;

if (NETWROK_SECURITY_WEP.equalsIgnoreCase(securityType)) {
    conf.wepKeys[0] = pass;
    conf.wepTxKeyIndex = 0;
    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
} else if (NETWROK_SECURITY_NONE.equalsIgnoreCase(securityType)) {
    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
} else if (NETWROK_SECURITY_WPA.equalsIgnoreCase(securityType)
        || NETWROK_SECURITY_WPA2.equalsIgnoreCase(securityType)
        || NETWROK_SECURITY_WPA_WPA2.equalsIgnoreCase(securityType)) {
    conf.preSharedKey = BACKSLASH + pass + BACKSLASH;
    conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    conf.status = WifiConfiguration.Status.ENABLED;
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
}
String wlanAdditionalSecurity = "";
if (NETWROK_ADDITIONAL_SECURITY_TKIP.equalsIgnoreCase(wlanAdditionalSecurity)) {
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
} else if (NETWROK_ADDITIONAL_SECURITY_AES.equalsIgnoreCase(wlanAdditionalSecurity)) {
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
} else if (NETWROK_ADDITIONAL_SECURITY_WEP.equalsIgnoreCase(wlanAdditionalSecurity)) {
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
} else if (NETWROK_ADDITIONAL_SECURITY_NONE.equalsIgnoreCase(wlanAdditionalSecurity)) {
    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.NONE);
}
WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
int res = wifiManager.addNetwork(conf);
wifiManager.disconnect();
wifiManager.reconnect();

if (true) {

    wifiManager.enableNetwork(res, true);

    wifiManager.saveConfiguration();
    wifiManager.setWifiEnabled(true);

    new AppPreferences(mContext).setPrefrenceLong("connectTime", Calendar.getInstance().getTimeInMillis());
}
if (res != -1) {

    setFalseOther(mm);
    notifyDataSetChanged();

    Intent i = new Intent(mContext, Connect.class);
    i.putExtra("networkName", mm.getName());
    i.putExtra("networkId", mm.getId());
    i.putExtra("AdminID", mm.getUserId());
    i.putExtra("networkConnection", "true");

    mContext.startActivity(i);

} else {

}

This code is for connecting to WiFi. It's working fine on Android Lollipop but I want to set up configuration programmatically for Marshmallow. I've given all the run time permissions and dangerous permission but still no help and unable to remove saved WiFi passwords. If anyone has done this for Marshmallow it would be helpful.

Body:
well I think I have found the solution for this...tested and working fine..

public boolean connectToWifi(String knownSSID,String key) {

    try{
        //If Wifi is not enabled, enable it
        if (!mWifiManager.isWifiEnabled()) {
            Log.v(LOG_TAG, "Wifi is not enabled, enable it");
            mWifiManager.setWifiEnabled(true);
        }
        WifiConfiguration config = new WifiConfiguration();
        config.SSID = convertToQuotedString(knownSSID);
        // if key is empty means it is open network-- I am considering like this
        if(key.isEmpty()){
            config.allowedKeyManagement.set(KeyMgmt.NONE);
        } else {
            config.preSharedKey = convertToQuotedString(key);
        }

        int networkId = mWifiManager.addNetwork(config);
        // it will return -1 if the config is already saved..
        if(networkId == -1){
            networkId = getExistingNetworkId(config.SSID);
        }
        boolean es = mWifiManager.saveConfiguration();

        mWifiManager.disconnect();
        // giving time to disconnect here.
        Thread.sleep(3*1000);
        boolean bRet = mWifiManager.enableNetwork(networkId, true);
        mWifiManager.reconnect();

    } catch(InterruptedException e) {

    }

}

public int getExistingNetworkId(String SSID){
    List<WifiConfiguration> configuredNetworks = mWifiManager.getConfiguredNetworks();
    if (configuredNetworks != null) {
        for (WifiConfiguration existingConfig : configuredNetworks) {
           if (SSID.equalsIgnoreCase(existingConfig.SSID)) {
               return existingConfig.networkId;
            }
        }
    }
    return -1;
}


问:
I implemented editActionsForRowAtIndexPath and commitEditingStyle but no edit actions appear on the tableViewCell when swiping the cell
I implemented editActionsForRowAtIndexPath and commitEditingStyle the swipe is working but no edit actions  appear on the UITableViewCell

my implementation for editActionsForRowAtIndexPath and commitEditingStyle as follow:

```<code>func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == UITableViewCellEditingStyle.Delete {
            //I did some work here
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
        }
    }

 func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]?  {

    let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "Delete" , handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
        //I did some work here
        tableView.reloadData()
    })

    return [deleteAction]
}
</code>```

Any help will be appreciated

答:
TLDR:

Necessary Functions to implement:
• commitEditingStyle
• canEditRowAt
• editActionsForRowAt

Note: for editActionsForRowAt you cannot return an empty array here -- it will screw up all the cells. If there is a particular type of row you don't want to allow edit actions for, specify this in canEditRowAt to return false for that type of cell.

Body:
I implemented editActionsForRowAtIndexPath and commitEditingStyle the swipe is working but no edit actions  appear on the UITableViewCell

my implementation for editActionsForRowAtIndexPath and commitEditingStyle as follow:

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == UITableViewCellEditingStyle.Delete {
            //I did some work here
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
        }
    }

 func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]?  {

    let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "Delete" , handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
        //I did some work here
        tableView.reloadData()
    })

    return [deleteAction]
}

Any help will be appreciated


问:
how to assign a method pointer to block variable in objectivec

I typedef a block like below

```<code>typedef void(^cbGeneric)();
</code>```

I define a property using block in a class

```<code>@property(nonatomic, strong)cbGeneric batchLoadStartedEvent;
</code>```

I need to bind a member method address of class to this property.

How to get pointer of member method of class and assign it to block property? thanks

答:
I need to bind a member method address of class to this property.

It is not clear what you are after here. Whether you are calling and instance or class method two implicit parameters need to be passed: a value for self, and a value of type SEL. You mention neither of these.

I suspect what you are trying to do is assign to the property a block value which will call some method, passing any parameters needed. In which case just assign a block value, something like:

```<code>obj.batchLoadStartedEvent = ^{ [someObject someMethod]; };
</code>```

Where obj references the object whose property you wish to set and [someObject someMethod] is whatever method you wish to call, on whatever object or class, and includes any parameters you wish to pass.

HTH

Body:
I typedef a block like below

typedef void(^cbGeneric)();

I define a property using block in a class

@property(nonatomic, strong)cbGeneric batchLoadStartedEvent;

I need to bind a member method address of class to this property.

How to get pointer of member method of class and assign it to block property? thanks

Body:
I need to bind a member method address of class to this property.

It is not clear what you are after here. Whether you are calling and instance or class method two implicit parameters need to be passed: a value for self, and a value of type SEL. You mention neither of these.

I suspect what you are trying to do is assign to the property a block value which will call some method, passing any parameters needed. In which case just assign a block value, something like:

obj.batchLoadStartedEvent = ^{ [someObject someMethod]; };

Where obj references the object whose property you wish to set and [someObject someMethod] is whatever method you wish to call, on whatever object or class, and includes any parameters you wish to pass.

HTH


问:
Lambda variable names - to short name, or not to short name?
Typically, when I use lambdas, I just use "a, b, c, d..." as variable names as the types are easily inferred, and I find short names to be easier to read.  Here is an example:

```<code>var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(a => a.SomeProperty)
                                      .OrderBy(a => a.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(a => new SomeClass(a.Prop1),
                                                    a => a);
</code>```

Some question this naming, and would prefer to see long typed out names, like this:

```<code>var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(importantObj => importantObj.SomeProperty)
                                      .OrderBy(objsInfo => objsInfo.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(theInfoId => new SomeClass(theInfoId.Prop1),
                                                    theInfoId2 => theInfoId2);
</code>```

Since the scope is so narrow (between the parens), unless you're getting stupid and nesting them, I find it easier to read short names.

Without getting caught up in the silly naming examples I used above, what is the general consensus on Lambda variable names?  To short name, or not to short name?

答:
The way I usualy do it depends on the collection you're enumerating over. If the name of the collection implies what type the lambda parameter will be, then I just go with the single letter, however if the collection isn't as descriptive, then I'll use a word.

IE:

```<code>myCollection.Where(person =>....); //non descriptive collection name

myPeopleCollection.Where(p=>...); // descriptive collection name
</code>```

OwnerDisplayName: TheSoftwareJedi

Body:
Typically, when I use lambdas, I just use "a, b, c, d..." as variable names as the types are easily inferred, and I find short names to be easier to read.  Here is an example:

var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(a => a.SomeProperty)
                                      .OrderBy(a => a.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(a => new SomeClass(a.Prop1),
                                                    a => a);

Some question this naming, and would prefer to see long typed out names, like this:

var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(importantObj => importantObj.SomeProperty)
                                      .OrderBy(objsInfo => objsInfo.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(theInfoId => new SomeClass(theInfoId.Prop1),
                                                    theInfoId2 => theInfoId2);

Since the scope is so narrow (between the parens), unless you're getting stupid and nesting them, I find it easier to read short names.

Without getting caught up in the silly naming examples I used above, what is the general consensus on Lambda variable names?  To short name, or not to short name?

LastEditorDisplayName: TheSoftwareJedi

Body:
The way I usualy do it depends on the collection you're enumerating over. If the name of the collection implies what type the lambda parameter will be, then I just go with the single letter, however if the collection isn't as descriptive, then I'll use a word.

IE:

myCollection.Where(person =>....); //non descriptive collection name

myPeopleCollection.Where(p=>...); // descriptive collection name

OwnerDisplayName: BFree


问:
How to assign the output of a program to a variable in a DCL com script on VMS?
For example, I have a perl script p.pl that writes "5" to stdout. I'd like to assign that output to a variable like so:</p>

```<code>$ x = perl p.pl ! not working code
$ ! now x would be 5
</code>```

答: Look up the PIPE command.  It lets you do unix like things.</p>

Body:
For example, I have a perl script p.pl that writes "5" to stdout. I'd like to assign that output to a variable like so:

$ x = perl p.pl ! not working code
$ ! now x would be 5


问:
Spring Frame Work, calling method from JSP without reloading or loading page
I am new to spring. I have a jsp project that does multiple things. Each button click is associated with a method (addMoney, selectItem, confirm, etc). I want to call these java methods using Spring, without reloading the page after each call. Is this possible? If it's impossible, what is the best practice to return every variable needed in the JSP in the model every time? That is how I am handling it now, and my controller methods look all the same, except for one or two lines. Ex below:

```<code>@RequestMapping(value = "/addQuarter", method = RequestMethod.GET)
public String addQuarter(HttpServletRequest request, Model model) {
    service.addQuarter();
    List<Item> itemList = service.getAllItems();
    model.addAttribute("itemList", itemList);
    model.addAttribute("change", service.displayCurrency());
    model.addAttribute("message", "Quarter added");
    model.addAttribute("changeDisplay", "");
    model.addAttribute("selectedItem", service.selectItemById(Integer.parseInt(request.getParameter("id"))));
    return "index";
}

@RequestMapping(value = "/addDime", method = RequestMethod.GET)
public String addQDime(HttpServletRequest request, Model model) {
    service.addDime();
    List<Item> itemList = service.getAllItems();
    model.addAttribute("itemList", itemList);
    model.addAttribute("change", service.displayCurrency());
    model.addAttribute("message", "Dime added");
    model.addAttribute("changeDisplay", "");
    model.addAttribute("selectedItem", service.selectItemById(Integer.parseInt(request.getParameter("id"))));
    return "index";
}
</code>```

答:
The methods in your @Controller returns a page with the information in model that can be used in the jsp this is resolved in server side and return html to browser.

If you want to modify you page without reload complete you page you must use AJAX, for this your methods in the @Controller must change and respond the information in the body of the message for example as a JSON.

Example:

    @ResponseBody
    @RequestMapping(value = "/addQuarter", method = RequestMethod.GET)
    public List<Item> addQuarter(HttpServletRequest request, Model model) {
        service.addQuarter();
        List<Item> itemList = service.getAllItems();
        return itemList;
    }

Here is a good tutorial spring-4-mvc-ajax

Body:
I am new to spring. I have a jsp project that does multiple things. Each button click is associated with a method (addMoney, selectItem, confirm, etc). I want to call these java methods using Spring, without reloading the page after each call. Is this possible? If it's impossible, what is the best practice to return every variable needed in the JSP in the model every time? That is how I am handling it now, and my controller methods look all the same, except for one or two lines. Ex below:

@RequestMapping(value = "/addQuarter", method = RequestMethod.GET)
public String addQuarter(HttpServletRequest request, Model model) {
    service.addQuarter();
    List<Item> itemList = service.getAllItems();
    model.addAttribute("itemList", itemList);
    model.addAttribute("change", service.displayCurrency());
    model.addAttribute("message", "Quarter added");
    model.addAttribute("changeDisplay", "");
    model.addAttribute("selectedItem", service.selectItemById(Integer.parseInt(request.getParameter("id"))));
    return "index";
}

@RequestMapping(value = "/addDime", method = RequestMethod.GET)
public String addQDime(HttpServletRequest request, Model model) {
    service.addDime();
    List<Item> itemList = service.getAllItems();
    model.addAttribute("itemList", itemList);
    model.addAttribute("change", service.displayCurrency());
    model.addAttribute("message", "Dime added");
    model.addAttribute("changeDisplay", "");
    model.addAttribute("selectedItem", service.selectItemById(Integer.parseInt(request.getParameter("id"))));
    return "index";
}


问:
User accessible folder/file in xamarin.forms
I have used System.Environment.SpecialFolder.Personal to create a file and read/ write to that file.

Reference: Working with files

It works as I can read from the file in my app. But I cannot find or browse to that file from my android device.

I want to create a folder and file inside it which should be accessible by the user. User should be allowed to browse to the file. How can I achive this in xamarin.forms?

答:
I actually have a solution to this now (sort of). I didn't manage to get Dropbox working yet (Xamarin are working on a new Dropbox nuget package), but I was able to load external files by using the Xamarin.Plugin.Filepicker nuget package (make sure you use that specific one, as a couple of the others don't work as well, and this one doesn't work that great to start with!). I got this working with both Android and UWP (I found this solution as MicroSoft now recommends using a filepicker for accessing external files). I haven't tried iOS yet.

Note: you won't be able to write to the file, but you can import it for processing from where-ever the user has been editing it. Also note that the tostring() doesn't work - it only returns ASCII codes, so you have to explicitly cast the result to char. The data is returned in an array rather than as a stream.

I believe it IS possible to write to the files too, however you would have to write it all yourself - there is no currently available package that does it. See https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/dependency-service/ to get you started.


问:
Wordpress Meta Box Form Data Not Saving
My plugin is about adding FAQs to your desired page.

I have added a form within a metabox in the 'Add New Question'.

When I feed values in the form, the form data does save in
the    database, but does not retain or show the values (selected)
in the    form when the page updates/publishes.

Instead, the form shows the previous non-selected values (even though the
selected values do    show up in the database).

```<code><?php

function faq_manage_things($post)
{

global $post;
$post_id= $post->ID;
wp_nonce_field(basename(__FILE__),'faqs_questions_nonce');
$faq_stored_meta= get_post_meta($post->ID);

?>
    <div class="wrap">
    <p>
         <label for="meta-select" class="prfx-row-title"><?php _e( 'Example Select Input', 'prfx-textdomain' )?></label>
            <select name="meta-select" id="meta-select">
                <option value="select-one" <?php if ( isset ( $prfx_stored_meta['meta-select'] ) ) selected( $prfx_stored_meta['meta-select'][0], 'select-one' ); ?>><?php _e( 'One', 'prfx-textdomain' )?></option>';
                <option value="select-two" <?php if ( isset ( $prfx_stored_meta['meta-select'] ) ) selected( $prfx_stored_meta['meta-select'][0], 'select-two' ); ?>><?php _e( 'Two', 'prfx-textdomain' )?></option>';
            </select>
    </p>

    <!-- TEXT AREA -->

    <p>
        <label for="meta-textarea" class="prfx-row-title"><?php _e( 'Example Textarea Input', 'prfx-textdomain' )?></label>
        <textarea name="meta-textarea" id="meta-textarea"><?php if ( isset ( $prfx_stored_meta['meta-textarea'] ) ) echo $prfx_stored_meta['meta-textarea'][0]; ?></textarea>
    </p>

        <!-- CHECKBOXES -->

    <p>
        <span class="prfx-row-title"><?php _e( 'Example Checkbox Input', 'prfx-textdomain' )?></span>
            <div class="prfx-row-content">
                <label for="meta-checkbox">
                    <input type="checkbox" name="meta-checkbox" id="meta-checkbox" value="yes" <?php if ( isset ( $prfx_stored_meta['meta-checkbox'] ) ) checked( $prfx_stored_meta['meta-checkbox'][0], 'yes' ); ?> /><?php _e( 'Checkbox label', 'prfx-textdomain' )?>
                </label>
                <label for="meta-checkbox-two">
                    <input type="checkbox" name="meta-checkbox-two" id="meta-checkbox-two" value="yes" <?php if ( isset ( $prfx_stored_meta['meta-checkbox-two'] ) ) checked( $prfx_stored_meta['meta-checkbox-two'][0], 'yes' ); ?> /><?php _e( 'Another checkbox', 'prfx-textdomain' )?>
                </label>
            </div>
    </p>

    </div>
<?php
}

global $post;
function faq_meta_save( $post_id ) {
    global $post;
    $post_id= $post->ID;
    $is_autosave = wp_is_post_autosave( $post_id );
    $is_revision = wp_is_post_revision( $post_id );
    $is_valid_nonce = ( isset( $_POST[ 'faqs_questions_nonce' ] ) && wp_verify_nonce( $_POST['faqs_questions_nonce'],basename(__FILE__)) )? 'true' : 'false';

    if ( $is_autosave || $is_revision || !$is_valid_nonce )
        {return;} //exit

    if( isset( $_POST[ 'meta-select' ] ) )
        {   update_post_meta( $post_id, 'meta-select', $_POST[ 'meta-select' ] );   }

    if( isset( $_POST[ 'meta-textarea' ] ) ) {
        update_post_meta( $post_id, 'meta-textarea', sanitize_text_field($_POST[ 'meta-textarea' ]) );   }

    // Checks for input and saves
    if( isset( $_POST[ 'meta-checkbox' ] ) ) {
        update_post_meta( $post_id, 'meta-checkbox', 'yes' );}
    else {
        update_post_meta( $post_id, 'meta-checkbox', '' );  }

    // Checks for input and saves
    if( isset( $_POST[ 'meta-checkbox-two' ] ) ) {
        update_post_meta( $post_id, 'meta-checkbox-two', 'yes' );}
    else {
        update_post_meta( $post_id, 'meta-checkbox-two', '' );  }

    }

    add_action('save_post','faq_meta_save');
</code>```

答:
You have to check if you have the meta_key duplicated in the database for the same post_id. Also, I recommend you to use underscores instead of hyphens in the meta_key names. Try this code where the meta_data of the post_id is deleted and then is added the new value.

Try this:

```<code><?php

function faq_manage_things($post)
{

    global $post;
    $post_id= $post->ID;
    wp_nonce_field(basename(__FILE__),'faqs_questions_nonce');
    $faq_stored_meta= get_post_meta($post->ID);

    ?>
    <div class="wrap">
        <p>
            <label for="meta-select" class="prfx-row-title"><?php _e( 'Example Select Input', 'prfx-textdomain' )?></label>
            <select name="meta-select" id="meta-select">
                <option value="select-one" <?php if ( isset ( $prfx_stored_meta['meta_select'] ) ) selected( $prfx_stored_meta['meta_select'][0], 'select-one' ); ?>><?php _e( 'One', 'prfx-textdomain' )?></option>';
                <option value="select-two" <?php if ( isset ( $prfx_stored_meta['meta_select'] ) ) selected( $prfx_stored_meta['meta_select'][0], 'select-two' ); ?>><?php _e( 'Two', 'prfx-textdomain' )?></option>';
            </select>
        </p>

        <!-- TEXT AREA -->

        <p>
            <label for="meta-textarea" class="prfx-row-title"><?php _e( 'Example Textarea Input', 'prfx-textdomain' )?></label>
            <textarea name="meta-textarea" id="meta-textarea"><?php if ( isset ( $prfx_stored_meta['meta_textarea'] ) ) echo $prfx_stored_meta['meta_textarea'][0]; ?></textarea>
        </p>

        <!-- CHECKBOXES -->

        <p>
            <span class="prfx-row-title"><?php _e( 'Example Checkbox Input', 'prfx-textdomain' )?></span>
            <div class="prfx-row-content">
                <label for="meta-checkbox">
                    <input type="checkbox" name="meta-checkbox" id="meta-checkbox" value="yes" <?php if ( isset ( $prfx_stored_meta['meta_checkbox'] ) ) checked( $prfx_stored_meta['meta_checkbox'][0], 'yes' ); ?> /><?php _e( 'Checkbox label', 'prfx-textdomain' )?>
                </label>
                <label for="meta-checkbox-two">
                    <input type="checkbox" name="meta-checkbox-two" id="meta-checkbox-two" value="yes" <?php if ( isset ( $prfx_stored_meta['meta_checkbox_two'] ) ) checked( $prfx_stored_meta['meta_checkbox_two'][0], 'yes' ); ?> /><?php _e( 'Another checkbox', 'prfx-textdomain' )?>
                </label>
            </div>
        </p>

    </div>
    <?php
}

global $post;

function faq_meta_save( $post_id ) {
    global $post;
    $post_id= $post->ID;
    $is_autosave = wp_is_post_autosave( $post_id );
    $is_revision = wp_is_post_revision( $post_id );
    $is_valid_nonce = ( isset( $_POST[ 'faqs_questions_nonce' ] ) && wp_verify_nonce( $_POST['faqs_questions_nonce'],basename(__FILE__)) )? 'true' : 'false';

    if ( $is_autosave || $is_revision || !$is_valid_nonce )
        {return;} //exit

    if( isset( $_POST[ 'meta-select' ] ) ) {
        remove_post_meta( $post_id, 'meta_select', $_POST[ 'meta-select' ] );
        add_post_meta( $post_id, 'meta_select', $_POST[ 'meta-select' ] );
    }

    if( isset( $_POST[ 'meta-textarea' ] ) ) {
        remove_post_meta( $post_id, 'meta_textarea', sanitize_text_field($_POST[ 'meta-textarea' ]) );
        add_post_meta( $post_id, 'meta_textarea', sanitize_text_field($_POST[ 'meta-textarea' ]) );
    }

    // Checks for input and saves
    if( isset( $_POST[ 'meta-checkbox' ] ) ) {
        remove_post_meta( $post_id, 'meta_checkbox', 'yes' );
        add_post_meta( $post_id, 'meta_checkbox', 'yes' );
    }
    else {
        remove_post_meta( $post_id, 'meta_checkbox');
    }

    // Checks for input and saves
    if( isset( $_POST[ 'meta-checkbox-two' ] ) ) {
        remove_post_meta( $post_id, 'meta_checkbox-two', 'yes' );
        add_post_meta( $post_id, 'meta_checkbox-two', 'yes' );
    }
    else {
        remove_post_meta( $post_id, 'meta_checkbox-two');
    }
}
add_action('save_post','faq_meta_save');
</code>```

Title: Wordpress Meta Box Form Data Not Saving

Body:
My plugin is about adding FAQs to your desired page.

I have added a form within a metabox in the 'Add New Question'.

When I feed values in the form, the form data does save in
the    database, but does not retain or show the values (selected)
in the    form when the page updates/publishes.

Instead, the form shows the previous non-selected values (even though the
selected values do    show up in the database).

<?php

function faq_manage_things($post)
{

global $post;
$post_id= $post->ID;
wp_nonce_field(basename(__FILE__),'faqs_questions_nonce');
$faq_stored_meta= get_post_meta($post->ID);

?>

         <?php _e( 'Example Select Input', 'prfx-textdomain' )?>
            <select name="meta-select" id="meta-select">
                <option value="select-one" <?php if ( isset ( $prfx_stored_meta['meta-select'] ) ) selected( $prfx_stored_meta['meta-select'][0], 'select-one' ); ?>><?php _e( 'One', 'prfx-textdomain' )?></option>';
                <option value="select-two" <?php if ( isset ( $prfx_stored_meta['meta-select'] ) ) selected( $prfx_stored_meta['meta-select'][0], 'select-two' ); ?>><?php _e( 'Two', 'prfx-textdomain' )?></option>';
            </select>

        <?php _e( 'Example Textarea Input', 'prfx-textdomain' )?>
        <textarea name="meta-textarea" id="meta-textarea"><?php if ( isset ( $prfx_stored_meta['meta-textarea'] ) ) echo $prfx_stored_meta['meta-textarea'][0]; ?></textarea>

        <?php _e( 'Example Checkbox Input', 'prfx-textdomain' )?>

                    <input type="checkbox" name="meta-checkbox" id="meta-checkbox" value="yes" <?php if ( isset ( $prfx_stored_meta['meta-checkbox'] ) ) checked( $prfx_stored_meta['meta-checkbox'][0], 'yes' ); ?> /><?php _e( 'Checkbox label', 'prfx-textdomain' )?>

                    <input type="checkbox" name="meta-checkbox-two" id="meta-checkbox-two" value="yes" <?php if ( isset ( $prfx_stored_meta['meta-checkbox-two'] ) ) checked( $prfx_stored_meta['meta-checkbox-two'][0], 'yes' ); ?> /><?php _e( 'Another checkbox', 'prfx-textdomain' )?>

<?php
}

global $post;
function faq_meta_save( $post_id ) {
    global $post;
    $post_id= $post->ID;
    $is_autosave = wp_is_post_autosave( $post_id );
    $is_revision = wp_is_post_revision( $post_id );
    $is_valid_nonce = ( isset( $_POST[ 'faqs_questions_nonce' ] ) && wp_verify_nonce( $_POST['faqs_questions_nonce'],basename(__FILE__)) )? 'true' : 'false';

    if ( $is_autosave || $is_revision || !$is_valid_nonce )
        {return;} //exit

    if( isset( $_POST[ 'meta-select' ] ) )
        {   update_post_meta( $post_id, 'meta-select', $_POST[ 'meta-select' ] );   }

    if( isset( $_POST[ 'meta-textarea' ] ) ) {
        update_post_meta( $post_id, 'meta-textarea', sanitize_text_field($_POST[ 'meta-textarea' ]) );   }

    // Checks for input and saves
    if( isset( $_POST[ 'meta-checkbox' ] ) ) {
        update_post_meta( $post_id, 'meta-checkbox', 'yes' );}
    else {
        update_post_meta( $post_id, 'meta-checkbox', '' );  }

    // Checks for input and saves
    if( isset( $_POST[ 'meta-checkbox-two' ] ) ) {
        update_post_meta( $post_id, 'meta-checkbox-two', 'yes' );}
    else {
        update_post_meta( $post_id, 'meta-checkbox-two', '' );  }

    }

    add_action('save_post','faq_meta_save');

Body:
You have to check if you have the meta_key duplicated in the database for the same post_id. Also, I recommend you to use underscores instead of hyphens in the meta_key names. Try this code where the meta_data of the post_id is deleted and then is added the new value.

Try this:

<?php

function faq_manage_things($post)
{

    global $post;
    $post_id= $post->ID;
    wp_nonce_field(basename(__FILE__),'faqs_questions_nonce');
    $faq_stored_meta= get_post_meta($post->ID);

    ?>
    <div class="wrap">
        <p>
            <label for="meta-select" class="prfx-row-title"><?php _e( 'Example Select Input', 'prfx-textdomain' )?></label>
            <select name="meta-select" id="meta-select">
                <option value="select-one" <?php if ( isset ( $prfx_stored_meta['meta_select'] ) ) selected( $prfx_stored_meta['meta_select'][0], 'select-one' ); ?>><?php _e( 'One', 'prfx-textdomain' )?></option>';
                <option value="select-two" <?php if ( isset ( $prfx_stored_meta['meta_select'] ) ) selected( $prfx_stored_meta['meta_select'][0], 'select-two' ); ?>><?php _e( 'Two', 'prfx-textdomain' )?></option>';
            </select>
        </p>

        <!-- TEXT AREA -->

        <p>
            <label for="meta-textarea" class="prfx-row-title"><?php _e( 'Example Textarea Input', 'prfx-textdomain' )?></label>
            <textarea name="meta-textarea" id="meta-textarea"><?php if ( isset ( $prfx_stored_meta['meta_textarea'] ) ) echo $prfx_stored_meta['meta_textarea'][0]; ?></textarea>
        </p>

        <!-- CHECKBOXES -->

        <p>
            <span class="prfx-row-title"><?php _e( 'Example Checkbox Input', 'prfx-textdomain' )?></span>
            <div class="prfx-row-content">
                <label for="meta-checkbox">
                    <input type="checkbox" name="meta-checkbox" id="meta-checkbox" value="yes" <?php if ( isset ( $prfx_stored_meta['meta_checkbox'] ) ) checked( $prfx_stored_meta['meta_checkbox'][0], 'yes' ); ?> /><?php _e( 'Checkbox label', 'prfx-textdomain' )?>
                </label>
                <label for="meta-checkbox-two">
                    <input type="checkbox" name="meta-checkbox-two" id="meta-checkbox-two" value="yes" <?php if ( isset ( $prfx_stored_meta['meta_checkbox_two'] ) ) checked( $prfx_stored_meta['meta_checkbox_two'][0], 'yes' ); ?> /><?php _e( 'Another checkbox', 'prfx-textdomain' )?>
                </label>
            </div>
        </p>

    </div>
    <?php
}

global $post;

function faq_meta_save( $post_id ) {
    global $post;
    $post_id= $post->ID;
    $is_autosave = wp_is_post_autosave( $post_id );
    $is_revision = wp_is_post_revision( $post_id );
    $is_valid_nonce = ( isset( $_POST[ 'faqs_questions_nonce' ] ) && wp_verify_nonce( $_POST['faqs_questions_nonce'],basename(__FILE__)) )? 'true' : 'false';

    if ( $is_autosave || $is_revision || !$is_valid_nonce )
        {return;} //exit

    if( isset( $_POST[ 'meta-select' ] ) ) {
        remove_post_meta( $post_id, 'meta_select', $_POST[ 'meta-select' ] );
        add_post_meta( $post_id, 'meta_select', $_POST[ 'meta-select' ] );
    }

    if( isset( $_POST[ 'meta-textarea' ] ) ) {
        remove_post_meta( $post_id, 'meta_textarea', sanitize_text_field($_POST[ 'meta-textarea' ]) );
        add_post_meta( $post_id, 'meta_textarea', sanitize_text_field($_POST[ 'meta-textarea' ]) );
    }

    // Checks for input and saves
    if( isset( $_POST[ 'meta-checkbox' ] ) ) {
        remove_post_meta( $post_id, 'meta_checkbox', 'yes' );
        add_post_meta( $post_id, 'meta_checkbox', 'yes' );
    }
    else {
        remove_post_meta( $post_id, 'meta_checkbox');
    }

    // Checks for input and saves
    if( isset( $_POST[ 'meta-checkbox-two' ] ) ) {
        remove_post_meta( $post_id, 'meta_checkbox-two', 'yes' );
        add_post_meta( $post_id, 'meta_checkbox-two', 'yes' );
    }
    else {
        remove_post_meta( $post_id, 'meta_checkbox-two');
    }
}
add_action('save_post','faq_meta_save');


问:
Adding Number by javascript
```<code><html>
<head>
<title>JavaScript - using function</title>
<script>
function add(){
var value1=document.getElementById("n1").value;
var value2=document.getElementById("n2").value;
document.getElementById("result").value=parseFloat(value1)+parseFloat(value2);
}
</script>
</head>
<body>
<label>First Number:<input type="number" id="n1"/></label>
<label>Second Number:<input type="number" id="n2"/></label>
<input type="button" value="Add" onClick="add()" />
<p>
Result = <span id="result" ></span>
</p>
</body>
</html>
</code>```

I am new to JavaScript and wanted to create a script that add numbers up. After pressing "Add" button, I cannot get the result to be displayed. How to get the result displayed?

答:
First, You Should Change

```<code>document.getElementById("result").value = value1 + value2
</code>```

To This:

```<code>document.getElementById("result").innerHTML = n1 + n2
</code>```

Because value stands for the attribute value for < input >, not the text written

in the tag.

Second, Change The Button Code To:

```<code><input type="button"value="Add"onclick="add()">
</code>```

This "onclick" is something called event in javascript,

It means at clicking on the button "Add" it performs the funtion called "add()".

If You Are New To Javascript You Will Know Everything.

Just Be Patient.

Title: Adding Number by javascript

Body:
<title>JavaScript - using function</title>

First Number:<input type="number" id="n1"/>
Second Number:<input type="number" id="n2"/>
<input type="button" value="Add" onClick="add()" />

Result =

I am new to JavaScript and wanted to create a script that add numbers up. After pressing "Add" button, I cannot get the result to be displayed. How to get the result displayed?

Body:
First, You Should Change

document.getElementById("result").value = value1 + value2

To This:

document.getElementById("result").innerHTML = n1 + n2

Because value stands for the attribute value for < input >, not the text written

in the tag.

Second, Change The Button Code To:

<input type="button"value="Add"onclick="add()">

This "onclick" is something called event in javascript,

It means at clicking on the button "Add" it performs the funtion called "add()".

If You Are New To Javascript You Will Know Everything.

Just Be Patient.


问:
Developing a Codeigniter game
I have a pretty reasonable amount of experience in PHP (around ~5 years of experience with some websites made and two browser games).  This is the first time I’ve really messed around with a core engine instead of just developing a plugin or module for something like Joomla.  I have an extensive amount of experience in other object oriented languages (such as Java).

My question is, I find myself developing the site much like a normal site, but I want it to be more flexible than that and I’m not sure I’m “doing it right”.  In a way, I feel like I’m building half a CMS.

For example, I have the main page set up through a controller that controls what views are currently being displayed.  The main view page looks like this:

```<code><?php $this->load->view("headerview"); ?>
<?php $this->load->view($contentview); ?>
<?php $this->load->view("footerview"); ?>
</code>```

in a view file itself (so I can dynamically load the contentview, the others don’t really change).  This is my first question, since I do ALL the control through my main control file, is this correct?

My index function sets the mainview as the view to be loaded with variables for the “contentview” and “gameview”.  When “contentview” is the game, it has a split pane, one showing the players stats and such, and the other showing whichever page the player is currently on (the merchant shop, in a battle, exploring the world, etc.).  What determines what is being shown here is the “gamecontent” variable (also passed in the “main” controller).

```<code><?php $this->load->view("menubar"); ?>
<?php $this->load->view($gamecontent); ?>
</code>```

In short, all view handling is currently being done in the main controller, i.e. one single controller.

```<code>$data['title'] = "Experimental Page";
$data['maincontent'] = "gameview";
if($page == 1) {
    $data['gamecontent'] = "townview";
} else if ($page == 2) {
    $data['gamecontent'] = "merchantview";
} else if ($page == 3) {
    $data['gamecontent'] = "explorationview";
} else if ($page == 4) {
    $data['gamecontent'] = "hospitalview";
} else if ($page == 5) {
    $data['gamecontent'] = "fightview";
} else if ($page == 6) {
    $data['gamecontent'] = "adminview";
}

$this->load->helper(array('form','url'));
$this->load->library('form_validation');
$this->load->view('mainview', $data);
</code>```

I haven’t started adding the fighting and shopping functions yet, but I can see this controller getting very large, very fast.  This seems wrong to me, but somehow I can’t formulate how to properly arrange the core setup.

My goal is to (hopefully) split up the controllers so that each one handles a separate game function, like healing, fighting, exploring and so on, and is separated much like my models are (user, mobs, items, etc.).

Can anyone help me figure out how to properly arrange this project?

答:
I use the Symfony Event Dispatcher component to do something like this; the component can be installed without using the Symfony Framework, so you can use it with CodeIgniter, but there might already be something similar available to you; I don't know CodeIgniter.

The Event Dispatcher is a generic implementation of the Observer Pattern.

I have a list of modules which register themselves as observers for any actions which they handle

Each request passes through an action (e.g. "townview")

My controller just creates an Event with whatever the action was as the name; the Event Dispatcher system then finds any modules which claim to be able to handle that action and passes over control to them

This way the main controller doesn't have to change, no matter how many actions you have; it just creates an event and throws it out through the dispatcher; if it's not handled it throws a massive error (in DEV) or a nice one (in PROD).

This is especially useful in our application, where we have lots of optional components that can be switched on or off for different users / clients; no complex logic in the controller at all, I just don't register the modules if they aren't enabled for a client.

Title: Developing a Codeigniter game

Body:
I have a pretty reasonable amount of experience in PHP (around ~5 years of experience with some websites made and two browser games).  This is the first time I’ve really messed around with a core engine instead of just developing a plugin or module for something like Joomla.  I have an extensive amount of experience in other object oriented languages (such as Java).

My question is, I find myself developing the site much like a normal site, but I want it to be more flexible than that and I’m not sure I’m “doing it right”.  In a way, I feel like I’m building half a CMS.

For example, I have the main page set up through a controller that controls what views are currently being displayed.  The main view page looks like this:

<?php $this->load->view("headerview"); ?>
<?php $this->load->view($contentview); ?>
<?php $this->load->view("footerview"); ?>

in a view file itself (so I can dynamically load the contentview, the others don’t really change).  This is my first question, since I do ALL the control through my main control file, is this correct?

My index function sets the mainview as the view to be loaded with variables for the “contentview” and “gameview”.  When “contentview” is the game, it has a split pane, one showing the players stats and such, and the other showing whichever page the player is currently on (the merchant shop, in a battle, exploring the world, etc.).  What determines what is being shown here is the “gamecontent” variable (also passed in the “main” controller).

<?php $this->load->view("menubar"); ?>
<?php $this->load->view($gamecontent); ?>

In short, all view handling is currently being done in the main controller, i.e. one single controller.

$data['title'] = "Experimental Page";
$data['maincontent'] = "gameview";
if($page == 1) {
    $data['gamecontent'] = "townview";
} else if ($page == 2) {
    $data['gamecontent'] = "merchantview";
} else if ($page == 3) {
    $data['gamecontent'] = "explorationview";
} else if ($page == 4) {
    $data['gamecontent'] = "hospitalview";
} else if ($page == 5) {
    $data['gamecontent'] = "fightview";
} else if ($page == 6) {
    $data['gamecontent'] = "adminview";
}

$this->load->helper(array('form','url'));
$this->load->library('form_validation');
$this->load->view('mainview', $data);

I haven’t started adding the fighting and shopping functions yet, but I can see this controller getting very large, very fast.  This seems wrong to me, but somehow I can’t formulate how to properly arrange the core setup.

My goal is to (hopefully) split up the controllers so that each one handles a separate game function, like healing, fighting, exploring and so on, and is separated much like my models are (user, mobs, items, etc.).

Can anyone help me figure out how to properly arrange this project?


答:
Two things wrong here...

1)

<input type="button" value="Add" /> change it to

```<code><input type="button" value="Add" onclick="add()" />
</code>```

Also,

2)

```<code>document.getElementById("result").value=parseFloat(value1)+parseFloat(value2);
</code>```

to

```<code>document.getElementById("result").innerHTML=parseFloat(value1)+parseFloat(value2);
</code>```

PS : This is not a assignment solving website :P

Title: Adding Number by javascript

Body:
Two things wrong here...

1)

<input type="button" value="Add" /> change it to

<input type="button" value="Add" onclick="add()" />

Also,

2)

document.getElementById("result").value=parseFloat(value1)+parseFloat(value2);

to

document.getElementById("result").innerHTML=parseFloat(value1)+parseFloat(value2);

PS : This is not a assignment solving website :P


问:
Validate access to an entity: Customizing authorization validation annotations
There are two entities and two service layers in my Spring boot app: User , Group

The following removeMember method is in the service layer:

```<code>/*Remove member with id userId from group with id groupId, if username is the admin of that group*/
public void removeMember(long groupId, long userId, String username) {
    Group group = loadById(groupId);
    validateAdminAccessToGroup(group, username);
    User user = userService.loadById(userId);
    validateMemberAccessToGroup(group, user.getName());
    if (group.isAdmin(user)) {
        throw new BadRequestException("Group admin cannot delete himself/herself from the group");
    }
    group.removeMember(user);
}

private void validateAdminAccessToGroup(Group group, String username) {
    User user = userService.loadByName(username);
    if (!group.isAdmin(user)) {
        throw new AccessDeniedException("User with id " + user.getId() + " was denied to access group with id " + group.getId() + " as an admin");
    }
}

private void validateMemberAccessToGroup(Group group, String username) {
    User user = userService.loadByName(username);
    if (!group.isMember(user)) {
        throw new AccessDeniedException("User with id " + user.getId() + " was denied to access group with id " + group.getId());
    }
}
</code>```

As you can see, only the admin of a group can remove a member from that group.

validateAdminAccessToGroup validates that user has access admin access to a group, otherwise it throughs an error. validateMemberAccessToGroup validates that user is a member of a group.

Should we do this access check inside the method ? or using @PreAuthorize annotations ? Can we say this is a cross-cutting concern ?

答:
In my opinion, it's better to handle checkAccessToGroup in User model object, not passing neither User, GroupId, nor AccessLevel, just handling it inside the model with these values set as the object member variables.

Then call it on User instance in Controller layer. If you called it in Service layer, you would need to call it repeatedly in Service methods when one Controller is utilizing more than one methods in Service, and you would eventually be tightly coupling the Access Checking part with the Service itself, which would decrease the reusability of the Service.

Body:
There are two entities and two service layers in my Spring boot app: User , Group

The following removeMember method is in the service layer:

/*Remove member with id userId from group with id groupId, if username is the admin of that group*/
public void removeMember(long groupId, long userId, String username) {
    Group group = loadById(groupId);
    validateAdminAccessToGroup(group, username);
    User user = userService.loadById(userId);
    validateMemberAccessToGroup(group, user.getName());
    if (group.isAdmin(user)) {
        throw new BadRequestException("Group admin cannot delete himself/herself from the group");
    }
    group.removeMember(user);
}

private void validateAdminAccessToGroup(Group group, String username) {
    User user = userService.loadByName(username);
    if (!group.isAdmin(user)) {
        throw new AccessDeniedException("User with id " + user.getId() + " was denied to access group with id " + group.getId() + " as an admin");
    }
}

private void validateMemberAccessToGroup(Group group, String username) {
    User user = userService.loadByName(username);
    if (!group.isMember(user)) {
        throw new AccessDeniedException("User with id " + user.getId() + " was denied to access group with id " + group.getId());
    }
}

As you can see, only the admin of a group can remove a member from that group.

validateAdminAccessToGroup validates that user has access admin access to a group, otherwise it throughs an error. validateMemberAccessToGroup validates that user is a member of a group.

Should we do this access check inside the method ? or using @PreAuthorize annotations ? Can we say this is a cross-cutting concern ?


问:
Python Class using double underscore and single underscore
I am seeing python class examples inside the class few functions are using double underscore, and  few functions it starts  single underscore and for some functions they does not use underscore.

Is this only to differentiate the code? or If we use differently like double underscore or single underscore code behaves differently.

Below is the script i found it has double underscore, single underscore and without under score.

```<code>import paramiko
import socket

class NetappFiler:

    def __init__(self, host, username, password, port=22):
        # Create ssh client
        self.client=paramiko.SSHClient()
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.client.connect(host, port , username=username, password=password)

    def __del__(self):
        # Close ssh connection
        self.client.close()

    def ssh_cmd(self, cmd):
        #print (cmd)
        stdin, stdout, stderr = self.client.exec_command(cmd)
        stdin.close()
        stdout = stdout.readlines()
        return stdout

    def _ssh_yes_cmd(self, cmd):
        #print (cmd)
        stdin, stdout, stderr = self.client.exec_command(cmd)
        stdin.write('y\n')
        stdin.flush()
        stdin.close()
        stdout = stdout.readlines()
        return stdout

    def _create_volume(self, vserver, vol_name, vol_size, target_aggr):
        # Creates a thick volume
        cmd = ("vol create -vserver %s -volume %s -aggregate %s -size %s "
               "-state online -type RW -policy default -user 0 -group 1 "
               "-security-style unix -unix-permissions ---rwxrwxrwx "
               "-max-autosize 60GB -autosize-increment 2.50GB "
               "-min-autosize 50GB -autosize-mode grow -space-guarantee volume"
               %(vserver, vol_name, target_aggr, vol_size))
        self.ssh_cmd(cmd)
</code>```

答:
Two underscores at the beginning and at the end of a method:

When we see a method like __method__, it means it's a method which python calls.

For example, in your code __init__ and __del__ is such a method. When you do the following.

```<code>obj = NetappFiler(arg1, arg2, arg3) # __init__ gets called
del obj # __del__ gets called
</code>```

Single underscore at the beginning:

Python doesn't have real private methods, so one underscore at the start of a method or attribute name means, it is private to that class.

From PEP-8:

_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

To learn more, please read the Descriptive: Naming Styles section from the document.

Body:
I am seeing python class examples inside the class few functions are using double underscore, and  few functions it starts  single underscore and for some functions they does not use underscore.

Is this only to differentiate the code? or If we use differently like double underscore or single underscore code behaves differently.

Below is the script i found it has double underscore, single underscore and without under score.

import paramiko
import socket

class NetappFiler:

    def __init__(self, host, username, password, port=22):
        # Create ssh client
        self.client=paramiko.SSHClient()
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.client.connect(host, port , username=username, password=password)

    def __del__(self):
        # Close ssh connection
        self.client.close()

    def ssh_cmd(self, cmd):
        #print (cmd)
        stdin, stdout, stderr = self.client.exec_command(cmd)
        stdin.close()
        stdout = stdout.readlines()
        return stdout

    def _ssh_yes_cmd(self, cmd):
        #print (cmd)
        stdin, stdout, stderr = self.client.exec_command(cmd)
        stdin.write('y\n')
        stdin.flush()
        stdin.close()
        stdout = stdout.readlines()
        return stdout

    def _create_volume(self, vserver, vol_name, vol_size, target_aggr):
        # Creates a thick volume
        cmd = ("vol create -vserver %s -volume %s -aggregate %s -size %s "
               "-state online -type RW -policy default -user 0 -group 1 "
               "-security-style unix -unix-permissions ---rwxrwxrwx "
               "-max-autosize 60GB -autosize-increment 2.50GB "
               "-min-autosize 50GB -autosize-mode grow -space-guarantee volume"
               %(vserver, vol_name, target_aggr, vol_size))
        self.ssh_cmd(cmd)

Body:
Two underscores at the beginning and at the end of a method:

When we see a method like __method__, it means it's a method which python calls.

For example, in your code __init__ and __del__ is such a method. When you do the following.

obj = NetappFiler(arg1, arg2, arg3) # __init__ gets called
del obj # __del__ gets called

Single underscore at the beginning:

Python doesn't have real private methods, so one underscore at the start of a method or attribute name means, it is private to that class.

From PEP-8:

_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

To learn more, please read the Descriptive: Naming Styles section from the document.


问:
Format a tbl within a dplyr chain
I am trying to add commas for thousands in my data e.g. 10,000 along with dollars e.g. $10,000.

I'm using several dplyr commands along with tidyr gather and spread functions. Here's what I tried:

Cut n paste this code block to generate the random data "dataset" I'm working with:

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

## Generate some data
channels <- c("Facebook", "Youtube", "SEM", "Organic", "Direct", "Email")
last_month <- Sys.Date() %m+% months(-1) %>% floor_date("month")
mts <- seq(from = last_month %m+% months(-23), to = last_month, by = "1 month") %>% as.Date()
dimvars <- expand.grid(Month = mts, Channel = channels, stringsAsFactors = FALSE)

# metrics
rws <- nrow(dimvars)
set.seed(42)

# generates variablility in the random data
randwalk <- function(initial_val, ...){
  initial_val + cumsum(rnorm(...))
}
Sessions <- ceiling(randwalk(3000, n = rws, mean = 8, sd = 1500)) %>% abs()
Revenue <- ceiling(randwalk(10000, n = rws, mean = 0, sd = 3500)) %>% abs()

# make primary df
dataset <- cbind(dimvars, Revenue)
</code>```

Which looks like:

```<code>> tbl_df(dataset)
# A tibble: 144 × 3
        Month  Channel Revenue
       <date>    <chr>   <dbl>
1  2015-06-01 Facebook    8552
2  2015-07-01 Facebook   12449
3  2015-08-01 Facebook   10765
4  2015-09-01 Facebook    9249
5  2015-10-01 Facebook   11688
6  2015-11-01 Facebook    7991
7  2015-12-01 Facebook    7849
8  2016-01-01 Facebook    2418
9  2016-02-01 Facebook    6503
10 2016-03-01 Facebook    5545
# ... with 134 more rows
</code>```

Now I want to spread the months into columns to show revenue trend by channel, month over month. I can do that like so:

```<code>revenueTable <- dataset %>% select(Month, Channel, Revenue) %>%
  group_by(Month, Channel) %>%
  summarise(Revenue = sum(Revenue)) %>%
  #mutate(Revenue = paste0("$", format(Revenue, big.interval = ","))) %>%
  gather(Key, Value, -Channel, -Month) %>%
  spread(Month, Value) %>%
  select(-Key)
</code>```

And it looks almost exactly as I want:

```<code>> revenueTable
# A tibble: 6 × 25
   Channel `2015-06-01` `2015-07-01` `2015-08-01` `2015-09-01` `2015-10-01` `2015-11-01` `2015-12-01` `2016-01-01` `2016-02-01` `2016-03-01` `2016-04-01`
*    <chr>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>
1   Direct        11910         8417         4012          359         4473         2702         6261         6167         8630         5230         1394
2    Email         7244         3517          671         1339        10788        10575         8567         8406         7856         6345         7733
3 Facebook         8552        12449        10765         9249        11688         7991         7849         2418         6503         5545         3908
4  Organic         4191          978          219         4274         2924         4155         5981         9719         8220         8829         7024
5      SEM         2344         6873        10230         6429         5016         2964         3390         3841         3163         1994         2105
6  Youtube          186         2949         2144         5073         1035         4878         7905         7377         2305         4556         6247
# ... with 13 more variables: `2016-05-01` <dbl>, `2016-06-01` <dbl>, `2016-07-01` <dbl>, `2016-08-01` <dbl>, `2016-09-01` <dbl>, `2016-10-01` <dbl>,
#   `2016-11-01` <dbl>, `2016-12-01` <dbl>, `2017-01-01` <dbl>, `2017-02-01` <dbl>, `2017-03-01` <dbl>, `2017-04-01` <dbl>, `2017-05-01` <dbl>
</code>```

Now the part I'm struggling with. I would like to format the data as currency. I tried adding this inbetween summarise() and gather() within the chain:

```<code>mutate(Revenue = paste0("$", format(Revenue, big.interval = ","))) %>%
</code>```

This half works. The dollar sign is prepended but the comma separators do not show. I tried removing the paste0("$" part to see if I could get the comma formatting to work with no success.

How can I format my tbl as a currency with dollars and commas, rounded to nearest whole dollars (no $1.99, just $2)?

答:
We can use data.table

```<code>library(data.table)
nm1 <- setdiff(names(revenueTable), 'Channel')
setDT(revenueTable)[, (nm1) := lapply(.SD, function(x)
         scales::dollar(round(x))), .SDcols =  nm1]

revenueTable[, 1:3, with = FALSE]
#     Channel `2015-06-01` `2015-07-01`
#1:   Direct      $11,910       $8,417
#2:    Email       $7,244       $3,517
#3: Facebook       $8,552      $12,449
#4:  Organic       $4,191         $978
#5:      SEM       $2,344       $6,873
#6:  Youtube         $186       $2,949
</code>```

Title: Format a tbl within a dplyr chain

Body:
I am trying to add commas for thousands in my data e.g. 10,000 along with dollars e.g. $10,000.

I'm using several dplyr commands along with tidyr gather and spread functions. Here's what I tried:

Cut n paste this code block to generate the random data "dataset" I'm working with:

library(dplyr)
library(tidyr)
library(lubridate)

## Generate some data
channels <- c("Facebook", "Youtube", "SEM", "Organic", "Direct", "Email")
last_month <- Sys.Date() %m+% months(-1) %>% floor_date("month")
mts <- seq(from = last_month %m+% months(-23), to = last_month, by = "1 month") %>% as.Date()
dimvars <- expand.grid(Month = mts, Channel = channels, stringsAsFactors = FALSE)

# metrics
rws <- nrow(dimvars)
set.seed(42)

# generates variablility in the random data
randwalk <- function(initial_val, ...){
  initial_val + cumsum(rnorm(...))
}
Sessions <- ceiling(randwalk(3000, n = rws, mean = 8, sd = 1500)) %>% abs()
Revenue <- ceiling(randwalk(10000, n = rws, mean = 0, sd = 3500)) %>% abs()

# make primary df
dataset <- cbind(dimvars, Revenue)

Which looks like:

> tbl_df(dataset)
# A tibble: 144 × 3
        Month  Channel Revenue
       <date>    <chr>   <dbl>
1  2015-06-01 Facebook    8552
2  2015-07-01 Facebook   12449
3  2015-08-01 Facebook   10765
4  2015-09-01 Facebook    9249
5  2015-10-01 Facebook   11688
6  2015-11-01 Facebook    7991
7  2015-12-01 Facebook    7849
8  2016-01-01 Facebook    2418
9  2016-02-01 Facebook    6503
10 2016-03-01 Facebook    5545
# ... with 134 more rows

Now I want to spread the months into columns to show revenue trend by channel, month over month. I can do that like so:

revenueTable <- dataset %>% select(Month, Channel, Revenue) %>%
  group_by(Month, Channel) %>%
  summarise(Revenue = sum(Revenue)) %>%
  #mutate(Revenue = paste0("$", format(Revenue, big.interval = ","))) %>%
  gather(Key, Value, -Channel, -Month) %>%
  spread(Month, Value) %>%
  select(-Key)

And it looks almost exactly as I want:

> revenueTable
# A tibble: 6 × 25
   Channel `2015-06-01` `2015-07-01` `2015-08-01` `2015-09-01` `2015-10-01` `2015-11-01` `2015-12-01` `2016-01-01` `2016-02-01` `2016-03-01` `2016-04-01`
*    <chr>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>
1   Direct        11910         8417         4012          359         4473         2702         6261         6167         8630         5230         1394
2    Email         7244         3517          671         1339        10788        10575         8567         8406         7856         6345         7733
3 Facebook         8552        12449        10765         9249        11688         7991         7849         2418         6503         5545         3908
4  Organic         4191          978          219         4274         2924         4155         5981         9719         8220         8829         7024
5      SEM         2344         6873        10230         6429         5016         2964         3390         3841         3163         1994         2105
6  Youtube          186         2949         2144         5073         1035         4878         7905         7377         2305         4556         6247
# ... with 13 more variables: `2016-05-01` <dbl>, `2016-06-01` <dbl>, `2016-07-01` <dbl>, `2016-08-01` <dbl>, `2016-09-01` <dbl>, `2016-10-01` <dbl>,
#   `2016-11-01` <dbl>, `2016-12-01` <dbl>, `2017-01-01` <dbl>, `2017-02-01` <dbl>, `2017-03-01` <dbl>, `2017-04-01` <dbl>, `2017-05-01` <dbl>

Now the part I'm struggling with. I would like to format the data as currency. I tried adding this inbetween summarise() and gather() within the chain:

mutate(Revenue = paste0("$", format(Revenue, big.interval = ","))) %>%

This half works. The dollar sign is prepended but the comma separators do not show. I tried removing the paste0("$" part to see if I could get the comma formatting to work with no success.

How can I format my tbl as a currency with dollars and commas, rounded to nearest whole dollars (no $1.99, just $2)?

Body:
We can use data.table

library(data.table)
nm1 <- setdiff(names(revenueTable), 'Channel')
setDT(revenueTable)[, (nm1) := lapply(.SD, function(x)
         scales::dollar(round(x))), .SDcols =  nm1]

revenueTable[, 1:3, with = FALSE]
#     Channel `2015-06-01` `2015-07-01`
#1:   Direct      $11,910       $8,417
#2:    Email       $7,244       $3,517
#3: Facebook       $8,552      $12,449
#4:  Organic       $4,191         $978
#5:      SEM       $2,344       $6,873
#6:  Youtube         $186       $2,949


问:
User input of (string) data in linked list (C++)?
I am trying to make a code that will ask the user how many students they want to accept. After this, the user will input the names of the students.

The code I have made is:

```<code>void acceptingStudents()
{
    node *temp = NULL, *head = NULL, *run = NULL;
    int studentSize;
    char studentName;

    cout << "Number of students to be accepted: ";
    cin >> studentSize;

    for (int x = 1; x <= memberSize; x++)
   {
       cout << "Student's name: ";
       cin >> studentName;
       temp = new node();
       temp->name = studentName;
       temp->next = NULL;
       temp -> prev = NULL;
       if (head == NULL)
       {
           head = temp;
       }
       else
       {
           run = head;
           while (run->next != NULL)
           {
               run = run->next;
           }
           temp -> prev = run;
           run->next = temp;
       }
   }
}

void main ()
{
    node *run = NULL;
    acceptingStudents();
    while (run != NULL)
   {
       printf("%d\n", run->name);
       run= run->next;
   }
    _getch();
}
</code>```

I want the output for this to be something like

```<code>Number of students to be accepted: 3
Student's name: Allison
Student's name: Gerry
Student's name: Sam
</code>```

but my code only outputs:

```<code>Number of students to be accepted: 3
Student's name: Allison
Student's name: Student's name:
</code>```

How can I fix this and make sure that each student name that is inputted by the user becomes the data for each node? I am trying to make the nodes like this:

    [ Allison ] -> [Gerry] -> [Sam] -> NULL

On another note, I was able to make it work with numbers using this:

```<code>void addingNodes()
{
    node *temp = NULL, *head = NULL, *run = NULL;
    int studentSize;
    int studentNumber;

    cout << "Number of students to be accepted: ";
    cin >> studentSize;

    for (int x = 1; x <= studentSize; x++)
   {
       cout << "Student's class number: ";
       cin >> studentNumber;
       temp = new node();
       temp-> value = studentNumber;
       temp->next = NULL;
       temp -> prev = NULL;
       if (head == NULL)
       {
           head = temp;
       }
       else
       {
           run = head;
           while (run->next != NULL)
           {
               run = run->next;
           }
           temp -> prev = run;
           run->next = temp;
       }
   }
}
</code>```

It outputs:

```<code>Number of students to be accepted: 5
Student's class number: 27
Student's class number: 12
Student's class number: 4
Student's class number: 8
Student's class number: 30
</code>```

My only problem with this is making it into a string instead of an int because I need the names and not the class numbers.

答: One issue i am observing is datatype of studentname is character, Make it string and it will work fine. The other issue is with this line "run != NULL". You are not updating the value run. Either pass run in fuctioon "acceptingStudents()" by reference or make the variable "run" global. In your given code you are mentioning it char</p>

Body:
I am trying to make a code that will ask the user how many students they want to accept. After this, the user will input the names of the students.

The code I have made is:

void acceptingStudents()
{
    node *temp = NULL, *head = NULL, *run = NULL;
    int studentSize;
    char studentName;

    cout << "Number of students to be accepted: ";
    cin >> studentSize;

    for (int x = 1; x <= memberSize; x++)
   {
       cout << "Student's name: ";
       cin >> studentName;
       temp = new node();
       temp->name = studentName;
       temp->next = NULL;
       temp -> prev = NULL;
       if (head == NULL)
       {
           head = temp;
       }
       else
       {
           run = head;
           while (run->next != NULL)
           {
               run = run->next;
           }
           temp -> prev = run;
           run->next = temp;
       }
   }
}

void main ()
{
    node *run = NULL;
    acceptingStudents();
    while (run != NULL)
   {
       printf("%d\n", run->name);
       run= run->next;
   }
    _getch();
}

I want the output for this to be something like

Number of students to be accepted: 3
Student's name: Allison
Student's name: Gerry
Student's name: Sam

but my code only outputs:

Number of students to be accepted: 3
Student's name: Allison
Student's name: Student's name:

How can I fix this and make sure that each student name that is inputted by the user becomes the data for each node? I am trying to make the nodes like this:

    [ Allison ] -> [Gerry] -> [Sam] -> NULL

On another note, I was able to make it work with numbers using this:

void addingNodes()
{
    node *temp = NULL, *head = NULL, *run = NULL;
    int studentSize;
    int studentNumber;

    cout << "Number of students to be accepted: ";
    cin >> studentSize;

    for (int x = 1; x <= studentSize; x++)
   {
       cout << "Student's class number: ";
       cin >> studentNumber;
       temp = new node();
       temp-> value = studentNumber;
       temp->next = NULL;
       temp -> prev = NULL;
       if (head == NULL)
       {
           head = temp;
       }
       else
       {
           run = head;
           while (run->next != NULL)
           {
               run = run->next;
           }
           temp -> prev = run;
           run->next = temp;
       }
   }
}

It outputs:

Number of students to be accepted: 5
Student's class number: 27
Student's class number: 12
Student's class number: 4
Student's class number: 8
Student's class number: 30

My only problem with this is making it into a string instead of an int because I need the names and not the class numbers.


问:
Mysql real escape string not working for textarea apostrophe on insert getting syntax error
Whenever I'm trying to insert data that has an apostrophe in it, I receive a

mysql syntax error

Example text in textarea : I'm an alien will throw a syntax error when I try to insert in the database. I'm using real_escape_string and still is not working.

query snippet

```<code>$text=mysqli_real_escape_string($db,stripslashes(strip_tags(trim($_POST['text']))));
</code>```

markup

```<code><textarea name='text' placeholder="Type your message here... " value=''></textarea>
</code>```

答:
I had to use parameterized queries. This did the tricK:</p>

```<code> //get variables
 $id = $_POST['id'];
 $text=trim($_POST['text']);

 $sqlText= "UPDATE table SET text=? WHERE user=?";
 $updateText = $db->prepare($sqlText);
 $updateText->bind_param('si',$text, $id);
 $updateText->execute();
</code>```

Body:
Whenever I'm trying to insert data that has an apostrophe in it, I receive a

mysql syntax error

Example text in textarea : I'm an alien will throw a syntax error when I try to insert in the database. I'm using real_escape_string and still is not working.

query snippet

$text=mysqli_real_escape_string($db,stripslashes(strip_tags(trim($_POST['text']))));

markup

<textarea name='text' placeholder="Type your message here... " value=''></textarea>

Body:
I had to use parameterized queries. This did the tricK:

 //get variables
 $id = $_POST['id'];
 $text=trim($_POST['text']);

 $sqlText= "UPDATE table SET text=? WHERE user=?";
 $updateText = $db->prepare($sqlText);
 $updateText->bind_param('si',$text, $id);
 $updateText->execute();


问:
Why is this invulnerable to styling?
I just want to change it's color to #DD4814 but I can't. It's a "share button" btw.
What could be the reason?</p>

```<code><span class='st_sharethis' st_title='<?php the_title(); ?>' st_url='<?php the_permalink() ?>' displayText='Compartir'></span>

<script type="text/javascript" src="http://w.sharethis.com/button/buttons.js"></script><script type="text/javascript">stLight.options({publisher:'eb2f12b2-11c6-4013-bf2c-e42dcf3112f5'});</script>
</code>```

答:
Usually styling won't work when one selector has precedence over the one you are using.  This is called selector specificity and there is a lot of documentation to help you understand how it works.

Because of the nature of the problem, you probably haven't posted enough code to give you an exact answer.  But, read the answer to this question: CSS problem - an element only works if its has no parent (using jquery) and http://htmldog.com/guides/cssadvanced/specificity/

To figure out how to apply the answer to your problem, use Firebug, right click on the element, and select "Inspect Element".  On the right pane of Firebug should be the Style tab where it will show you which CSS selectors apply to that element.  Find the one that has the style you can't overwrite, and make sure your selector is more specific than that.

Title: Why is this invulnerable to styling?

Body:
I just want to change it's color to #DD4814 but I can't. It's a "share button" btw.
What could be the reason?

<span class='st_sharethis' st_title='<?php the_title(); ?>' st_url='<?php the_permalink() ?>' displayText='Compartir'>


问:
"using namespace std;" without any #include?
I tried following, it worked without problem, but in this situation, std was not defined.</p>

```<code>    using namespace std;

    int main()
    {
       ....
    }
</code>```

答:
Your code is illegal. Directive using can only nominate previously declared namespaces, i.e. namespaces whose names can be found by name lookup.

In this case your compiler apparently gives special treatment to name std. It is a compiler-specific extension, which regards std as an implicitly defined namespace. If your try a different namespace name in your code, it will most likely fail to compile.

Body:
I tried following, it worked without problem, but in this situation, std was not defined.

    using namespace std;

    int main()
    {
       ....
    }


答:
It worked with the following changes
-> calling add function with onclick event
-> using innerhtml in place of value

```<code><html>
<head>
<title>JavaScript - using function</title>
<script>
    function add(){
        var value1=document.getElementById("n1").value;
        var value2=document.getElementById("n2").value;
        console.log(value1,value2)
        document.getElementById("result").innerHTML=parseFloat(value1)+parseFloat(value2);
    }
</script>
</head>
<body>
<label>First Number:<input type="number" id="n1"/></label>
<label>Second Number:<input type="number" id="n2"/></label>
<input type="button" value="Add" onclick="add()"/>
<p>
Result = <span id="result" ></span>
</p>
</body>
</html>
</code>```

Hope this helps

Title: Adding Number by javascript

Body:
It worked with the following changes
-> calling add function with onclick event
-> using innerhtml in place of value

<html>
<head>
<title>JavaScript - using function</title>
<script>
    function add(){
        var value1=document.getElementById("n1").value;
        var value2=document.getElementById("n2").value;
        console.log(value1,value2)
        document.getElementById("result").innerHTML=parseFloat(value1)+parseFloat(value2);
    }
</script>
</head>
<body>
<label>First Number:<input type="number" id="n1"/></label>
<label>Second Number:<input type="number" id="n2"/></label>
<input type="button" value="Add" onclick="add()"/>
<p>
Result = <span id="result" ></span>
</p>
</body>
</html>

Hope this helps


问:
Reload data from database without refreshing page
My Ajax successfully update some information in database and as a result he should update one element, which shows this information. But it doesn't. However, after refreshing page, which cause reconnecting to db, information updating. Here is the function:

```<code>function topUpTheBalance(){
        var d = document.getElementById("numberForm").value;
        $.ajax({
        type: 'POST',
        url: 'handler.php',
        data: {
            'topUpBalance':d,
        },
        success: function () {
            var k = document.getElementById("balanceNumber");
            k.innerHTML ="Your balance: "+ <?php echo $userRow['userBalance']; ?>;
        }
        }
        );
    }
</code>```

and the handler.php

```<code><?php
    ob_start();
    session_start();
    require_once 'dbconnect.php';

    if( !isset($_SESSION['user']) ) {
    header("Location: index.php");
     exit;
    }
    $res=mysqli_query($link, "SELECT * FROM users WHERE userId=".$_SESSION['user']);
    $userRow=mysqli_fetch_array($res);
    //$link =  mysqli_connect("localhost","username","password", "users");
    $bal = $userRow['userBalance']+$_POST['topUpBalance'];
    if($stmt = mysqli_prepare($link, "UPDATE users SET userBalance = ? WHERE userId = ?")){
            mysqli_stmt_bind_param($stmt, "di", $bal, $userRow['userId']);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_bind_result($stmt, $result);
            mysqli_stmt_fetch($stmt);
            mysqli_stmt_close($stmt);
    }
    mysqli_close($link);
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
<?php ob_end_flush(); ?>
</code>```

Can anyone suggest me how to update this information without refreshing the page?

答:
The main thing is you should throw output from php side but you have not sent output and You should use isset($_POST['topUpBalance']) and then go to other process for example :-

```<code>if(isset($_POST['topUpBalance'])){
     $res=mysqli_query($link, "SELECT * FROM users WHERE
     userId=".$_SESSION['user']);
     $userRow=mysqli_fetch_array($res);
    $bal = $userRow['userBalance'] + $_POST['topUpBalance'];

   if($stmt = mysqli_prepare($link, "UPDATE users SET userBalance = ?
     WHERE userId = ?")){
        mysqli_stmt_bind_param($stmt, "di", $bal, $userRow['userId']);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_bind_result($stmt, $result);
       //Send output echo ...... ;
        mysqli_stmt_fetch($stmt);
        mysqli_stmt_close($stmt);
      }
       mysqli_close($link);
}
</code>```

In jquery side :-
receive data using parameter

```<code>function topUpTheBalance(){
    var d = document.getElementById("numberForm").value;
    $.ajax({
    type: 'POST',
    url: 'handler.php',
    data: {
        'topUpBalance':d,
    },
    success: function (data) {
     // use sent data or unsent data for processing
    }
    }
    );
}
</code>```

Body:
My Ajax successfully update some information in database and as a result he should update one element, which shows this information. But it doesn't. However, after refreshing page, which cause reconnecting to db, information updating. Here is the function:

function topUpTheBalance(){
        var d = document.getElementById("numberForm").value;
        $.ajax({
        type: 'POST',
        url: 'handler.php',
        data: {
            'topUpBalance':d,
        },
        success: function () {
            var k = document.getElementById("balanceNumber");
            k.innerHTML ="Your balance: "+ <?php echo $userRow['userBalance']; ?>;
        }
        }
        );
    }

and the handler.php

<?php
    ob_start();
    session_start();
    require_once 'dbconnect.php';

    if( !isset($_SESSION['user']) ) {
    header("Location: index.php");
     exit;
    }
    $res=mysqli_query($link, "SELECT * FROM users WHERE userId=".$_SESSION['user']);
    $userRow=mysqli_fetch_array($res);
    //$link =  mysqli_connect("localhost","username","password", "users");
    $bal = $userRow['userBalance']+$_POST['topUpBalance'];
    if($stmt = mysqli_prepare($link, "UPDATE users SET userBalance = ? WHERE userId = ?")){
            mysqli_stmt_bind_param($stmt, "di", $bal, $userRow['userId']);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_bind_result($stmt, $result);
            mysqli_stmt_fetch($stmt);
            mysqli_stmt_close($stmt);
    }
    mysqli_close($link);
?>
<!DOCTYPE html>

<?php ob_end_flush(); ?>

Can anyone suggest me how to update this information without refreshing the page?

Body:
The main thing is you should throw output from php side but you have not sent output and You should use isset($_POST['topUpBalance']) and then go to other process for example :-

if(isset($_POST['topUpBalance'])){
     $res=mysqli_query($link, "SELECT * FROM users WHERE
     userId=".$_SESSION['user']);
     $userRow=mysqli_fetch_array($res);
    $bal = $userRow['userBalance'] + $_POST['topUpBalance'];

   if($stmt = mysqli_prepare($link, "UPDATE users SET userBalance = ?
     WHERE userId = ?")){
        mysqli_stmt_bind_param($stmt, "di", $bal, $userRow['userId']);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_bind_result($stmt, $result);
       //Send output echo ...... ;
        mysqli_stmt_fetch($stmt);
        mysqli_stmt_close($stmt);
      }
       mysqli_close($link);
}

In jquery side :-
receive data using parameter

function topUpTheBalance(){
    var d = document.getElementById("numberForm").value;
    $.ajax({
    type: 'POST',
    url: 'handler.php',
    data: {
        'topUpBalance':d,
    },
    success: function (data) {
     // use sent data or unsent data for processing
    }
    }
    );
}


问:
Error from server (Forbidden): error when creating .. : clusterroles.rbac.authorization.k8s.io ...: attempt to grant extra privileges:
Failed to create clusterroles. <> already assigned as the roles of "container engine admin" & "container engine cluster admin"</p>

```<code>Error from server (Forbidden): error when creating "prometheus-
operator/prometheus-operator-cluster-role.yaml":
clusterroles.rbac.authorization.k8s.io "prometheus-operator"
is forbidden: attempt to grant extra privileges: [{[create]
[extensions] [thirdpartyresources] [] []} {[*]
[monitoring.coreos.com] [alertmanagers] [] []} {[*]
[monitoring.coreos.com] [prometheuses] [] []} {[*]
[monitoring.coreos.com] [servicemonitors] [] []} {[*]
[apps] [statefulsets] [] []} {[*] [] [configmaps] [] []}
{[*] [] [secrets] [] []} {[list] [] [pods] [] []} {[delete]
[] [pods] [] []} {[get] [] [services] [] []} {[create]
[] [services] [] []} {[update] [] [services] [] []} {[get]
[] [endpoints] [] []} {[create] [] [endpoints] [] []}
{[update] [] [endpoints] [] []} {[list] [] [nodes]
[] []} {[watch] [] [nodes] [] []}]
user=&{<<my_account>>@gmail.com
[system:authenticated] map[]} ownerrules=[{[create]
[authorization.k8s.io] [selfsubjectaccessreviews]
[] []} {[get] [] [] [] [/api /api/* /apis /apis/*
/healthz /swaggerapi /swaggerapi/* /version]}]
ruleResolutionErrors=[]
</code>```

答:
Based on https://cloud.google.com/container-engine/docs/role-based-access-control#setting_up_role-based_access_control

Because of the way Container Engine checks permissions when you create a Role or ClusterRole, you must first create a RoleBinding that grants you all of the permissions included in the role you want to create.

An example workaround is to create a RoleBinding that gives your Google identity a cluster-admin role before attempting to create additional Role or ClusterRolepermissions.

This is a known issue in the Beta release of Role-Based Access Control in Kubernetes and Container Engine version 1.6.

So you need to bind your account to a cluster admin role.

ContentLicense: CC BY-SA 4.0

Body:
Failed to create clusterroles. <> already assigned as the roles of "container engine admin" & "container engine cluster admin"

Error from server (Forbidden): error when creating "prometheus-
operator/prometheus-operator-cluster-role.yaml":
clusterroles.rbac.authorization.k8s.io "prometheus-operator"
is forbidden: attempt to grant extra privileges: [{[create]
[extensions] [thirdpartyresources] [] []} {[*]
[monitoring.coreos.com] [alertmanagers] [] []} {[*]
[monitoring.coreos.com] [prometheuses] [] []} {[*]
[monitoring.coreos.com] [servicemonitors] [] []} {[*]
[apps] [statefulsets] [] []} {[*] [] [configmaps] [] []}
{[*] [] [secrets] [] []} {[list] [] [pods] [] []} {[delete]
[] [pods] [] []} {[get] [] [services] [] []} {[create]
[] [services] [] []} {[update] [] [services] [] []} {[get]
[] [endpoints] [] []} {[create] [] [endpoints] [] []}
{[update] [] [endpoints] [] []} {[list] [] [nodes]
[] []} {[watch] [] [nodes] [] []}]
user=&{<<my_account>>@gmail.com
[system:authenticated] map[]} ownerrules=[{[create]
[authorization.k8s.io] [selfsubjectaccessreviews]
[] []} {[get] [] [] [] [/api /api/* /apis /apis/*
/healthz /swaggerapi /swaggerapi/* /version]}]
ruleResolutionErrors=[]


答:
You need to use a string or a character array to store a name.

char studentName[SIZE];

std::string studentName;

You cannot just assign a character array to another as well.

If you are using the string datatype, you can make use of the assign function.

```<code>std::string str;
str.assign("Hello World");
cout<<str;
</code>```

Apart from this, your code for implementing a linked list seems to be slightly messy. Why do you have two pointers (next and prev) if you want to implement a singly linked list? Why not make a member function to add a node in the node class instead of doing it explicitly in the function?

Title: User input of (string) data in linked list (C++)?

Body:
You need to use a string or a character array to store a name.

char studentName[SIZE];

std::string studentName;

You cannot just assign a character array to another as well.

If you are using the string datatype, you can make use of the assign function.

std::string str;
str.assign("Hello World");
cout<<str;

Apart from this, your code for implementing a linked list seems to be slightly messy. Why do you have two pointers (next and prev) if you want to implement a singly linked list? Why not make a member function to add a node in the node class instead of doing it explicitly in the function?