问:
Any tips for making Hive run faster on Hadoop?
I'm new to Hive and Hadoop. I have Hadoop configured for pseudo-distributed operation with one data node and one name node, all on localhost.

I have a trivial employee table containing 4 records. I can select the records in a reasonable amount of time, but anything beyond that takes really long. For example:

```<code>0: jdbc:hive2://localhost:10000> select * from emp;
+------------+------------+-------------+-------------+------------+
| emp.empno  | emp.ename  |   emp.job   | emp.deptno  | emp.etype  |
+------------+------------+-------------+-------------+------------+
| 7369       | SMITH      | CLERK       | 10          | PART_TIME  |
| 7400       | JONES      | ENGINEER    | 10          | FULL_TIME  |
| 7500       | BROWN      | NIGHTGUARD  | 20          | FULL_TIME  |
| 7510       | LEE        | ENGINEER    | 20          | FULL_TIME  |
+------------+------------+-------------+-------------+------------+
4 rows selected (0.643 seconds)
0: jdbc:hive2://localhost:10000> select * from emp order by empno;
WARNING: Hive-on-MR is deprecated in Hive 2 and may not be available in the future versions. Consider using a different execution engine (i.e. spark, tez) or using Hive 1.X releases.
+------------+------------+-------------+-------------+------------+
| emp.empno  | emp.ename  |   emp.job   | emp.deptno  | emp.etype  |
+------------+------------+-------------+-------------+------------+
| 7369       | SMITH      | CLERK       | 10          | PART_TIME  |
| 7400       | JONES      | ENGINEER    | 10          | FULL_TIME  |
| 7500       | BROWN      | NIGHTGUARD  | 20          | FULL_TIME  |
| 7510       | LEE        | ENGINEER    | 20          | FULL_TIME  |
+------------+------------+-------------+-------------+------------+
4 rows selected (225.852 seconds)
</code>```

What's it doing that's taking so long? Are there polling periods that I could reduce? I know that Hive isn't optimized for small tasks but this seems ridiculous.

Here's the various files:
hive-site.xml

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
  <property>
    <name>hive.mapred.mode</name>
    <value>nostrict</value>
  </property>
  <property>
    <name>javax.jdo.option.ConnectionURL</name>
    <value>jdbc:derby:;databaseName=metastore_db;create=true</value>
  </property>
  <property>
    <name>javax.jdo.option.ConnectionDriverName</name>
    <value>org.apache.derby.jdbc.EmbeddedDriver</value>
  </property>
  <property>
    <name>hive.exec.local.scratchdir</name>
    <value>/home/hadoop/tmp</value>
  </property>
  <property>
    <name>hive.downloaded.resources.dir</name>
    <value>/home/hadoop/tmp/${hive.session.id}_resources</value>
  </property>
  <property>
    <name>hive.querylog.location</name>
    <value>/home/hadoop/tmp</value>
  </property>
  <property>
    <name>hive.server2.logging.operation.log.location</name>
    <value>/home/hadoop/tmp/operation_logs</value>
  </property>
</configuration>
</code>```

hdfs.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
   <property>
      <name>dfs.replication</name>
      <value>1</value>
   </property>
   <property>
      <name>dfs.name.dir</name>
      <value>file:///home/hadoop/hadoopinfra/hdfs/namenode</value>
   </property>
   <property>
      <name>dfs.data.dir</name>
      <value>file:///home/hadoop/hadoopinfra/hdfs/datanode</value>
   </property>
</configuration>
</code>```

core-site.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
   <property>
      <name>fs.default.name</name>
      <value>hdfs://localhost:9000</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hive.groups</name>
      <value>*</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hive.hosts</name>
      <value>*</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hadoop.hosts</name>
      <value>*</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hadoop.groups</name>
      <value>*</value>
   </property>
</configuration>
</code>```

mapred-site.xml

```<code><?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
   <property>
      <name>mapreduce.framework.name</name>
      <value>yarn</value>
   </property>
</configuration>
</code>```

yarn-site.xml

```<code><?xml version="1.0"?>
<configuration>
   <property>
      <name>yarn.nodemanager.aux-services</name>
      <value>mapreduce_shuffle</value>
   </property>
</configuration>
</code>```

答:
```<code>Set hive.fetch.task.conversion=none;
</code>```

Set this property and run it again

Body:
I'm new to Hive and Hadoop. I have Hadoop configured for pseudo-distributed operation with one data node and one name node, all on localhost.

I have a trivial employee table containing 4 records. I can select the records in a reasonable amount of time, but anything beyond that takes really long. For example:

0: jdbc:hive2://localhost:10000> select * from emp;
+------------+------------+-------------+-------------+------------+
| emp.empno  | emp.ename  |   emp.job   | emp.deptno  | emp.etype  |
+------------+------------+-------------+-------------+------------+
| 7369       | SMITH      | CLERK       | 10          | PART_TIME  |
| 7400       | JONES      | ENGINEER    | 10          | FULL_TIME  |
| 7500       | BROWN      | NIGHTGUARD  | 20          | FULL_TIME  |
| 7510       | LEE        | ENGINEER    | 20          | FULL_TIME  |
+------------+------------+-------------+-------------+------------+
4 rows selected (0.643 seconds)
0: jdbc:hive2://localhost:10000> select * from emp order by empno;
WARNING: Hive-on-MR is deprecated in Hive 2 and may not be available in the future versions. Consider using a different execution engine (i.e. spark, tez) or using Hive 1.X releases.
+------------+------------+-------------+-------------+------------+
| emp.empno  | emp.ename  |   emp.job   | emp.deptno  | emp.etype  |
+------------+------------+-------------+-------------+------------+
| 7369       | SMITH      | CLERK       | 10          | PART_TIME  |
| 7400       | JONES      | ENGINEER    | 10          | FULL_TIME  |
| 7500       | BROWN      | NIGHTGUARD  | 20          | FULL_TIME  |
| 7510       | LEE        | ENGINEER    | 20          | FULL_TIME  |
+------------+------------+-------------+-------------+------------+
4 rows selected (225.852 seconds)

What's it doing that's taking so long? Are there polling periods that I could reduce? I know that Hive isn't optimized for small tasks but this seems ridiculous.

Here's the various files:
hive-site.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
  <property>
    <name>hive.mapred.mode</name>
    <value>nostrict</value>
  </property>
  <property>
    <name>javax.jdo.option.ConnectionURL</name>
    <value>jdbc:derby:;databaseName=metastore_db;create=true</value>
  </property>
  <property>
    <name>javax.jdo.option.ConnectionDriverName</name>
    <value>org.apache.derby.jdbc.EmbeddedDriver</value>
  </property>
  <property>
    <name>hive.exec.local.scratchdir</name>
    <value>/home/hadoop/tmp</value>
  </property>
  <property>
    <name>hive.downloaded.resources.dir</name>
    <value>/home/hadoop/tmp/${hive.session.id}_resources</value>
  </property>
  <property>
    <name>hive.querylog.location</name>
    <value>/home/hadoop/tmp</value>
  </property>
  <property>
    <name>hive.server2.logging.operation.log.location</name>
    <value>/home/hadoop/tmp/operation_logs</value>
  </property>
</configuration>

hdfs.xml

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
   <property>
      <name>dfs.replication</name>
      <value>1</value>
   </property>
   <property>
      <name>dfs.name.dir</name>
      <value>file:///home/hadoop/hadoopinfra/hdfs/namenode</value>
   </property>
   <property>
      <name>dfs.data.dir</name>
      <value>file:///home/hadoop/hadoopinfra/hdfs/datanode</value>
   </property>
</configuration>

core-site.xml

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
   <property>
      <name>fs.default.name</name>
      <value>hdfs://localhost:9000</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hive.groups</name>
      <value>*</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hive.hosts</name>
      <value>*</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hadoop.hosts</name>
      <value>*</value>
   </property>
   <property>
      <name>hadoop.proxyuser.hadoop.groups</name>
      <value>*</value>
   </property>
</configuration>

mapred-site.xml

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
   <property>
      <name>mapreduce.framework.name</name>
      <value>yarn</value>
   </property>
</configuration>

yarn-site.xml

<?xml version="1.0"?>
<configuration>
   <property>
      <name>yarn.nodemanager.aux-services</name>
      <value>mapreduce_shuffle</value>
   </property>
</configuration>

Body:
Set hive.fetch.task.conversion=none;

Set this property and run it again


来源: stackexchange

问:
Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent
On application launch, app starts the service that should to do some network task.
After targeting API level 26, my application fails to start service on Android 8.0 on background.

Caused by: java.lang.IllegalStateException: Not allowed to start
  service Intent {
  cmp=my.app.tt/com.my.service
  }: app is in background uid UidRecord{90372b1 u0a136 CEM  idle procs:1
  seq(0,0,0)}

as I understand it related to:
Background execution limits

The startService() method now throws an IllegalStateException if an
  app targeting Android 8.0 tries to use that method in a situation when
  it isn't permitted to create background services.

"in a situation when it isn't permitted" - what it's actually mean?? And how to fix it. I don't want to set my service as "foreground"

答:
I got solution. For pre-8.0 devices, you have to just use startService(), but for post-7.0 devices, you have to use startForgroundService(). Here is sample for code to start service.

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context.startForegroundService(new Intent(context, ServedService.class));
    } else {
        context.startService(new Intent(context, ServedService.class));
    }
</code>```

And in service class, please add the code below for notification:

```<code>@Override
public void onCreate() {
    super.onCreate();
    startForeground(1,new Notification());
}
</code>```

Where O is Android version 26.

If you don't want your service to run in Foreground and want it to run in background instead, post Android O you must bind the service to a connection like below:

```<code>Intent serviceIntent = new Intent(context, ServedService.class);
context.startService(serviceIntent);
context.bindService(serviceIntent, new ServiceConnection() {
     @Override
     public void onServiceConnected(ComponentName name, IBinder service) {
         //retrieve an instance of the service here from the IBinder returned
         //from the onBind method to communicate with
     }

     @Override
     public void onServiceDisconnected(ComponentName name) {
     }
}, Context.BIND_AUTO_CREATE);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I got solution. For pre-8.0 devices, you have to just use startService(), but for post-7.0 devices, you have to use startForgroundService(). Here is sample for code to start service.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context.startForegroundService(new Intent(context, ServedService.class));
    } else {
        context.startService(new Intent(context, ServedService.class));
    }

And in service class, please add the code below for notification:

@Override
public void onCreate() {
    super.onCreate();
    startForeground(1,new Notification());
}

Where O is Android version 26.

If you don't want your service to run in Foreground and want it to run in background instead, post Android O you must bind the service to a connection like below:

Intent serviceIntent = new Intent(context, ServedService.class);
context.startService(serviceIntent);
context.bindService(serviceIntent, new ServiceConnection() {
     @Override
     public void onServiceConnected(ComponentName name, IBinder service) {
         //retrieve an instance of the service here from the IBinder returned
         //from the onBind method to communicate with
     }

     @Override
     public void onServiceDisconnected(ComponentName name) {
     }
}, Context.BIND_AUTO_CREATE);

ContentLicense: CC BY-SA 4.0


问:
Auto scrolling to a cell with a specific value
I have a list of numbers in a table view like this.

As you can see the numbers are repeated. Let's consider a set of repeated numbers as a group. So there are group of 1s, group of 2s and so on.

What I want to do is when the app starts, I need to scroll to the start position of a specified group automatically. Before explaining further, here is my code so far.

```<code>import UIKit

class TableViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {

    private var scrollToTime = true
    private var items = [Int]()
    private var groupNoToScroll = 12

    override func viewDidLoad() {
        super.viewDidLoad()

        items = [1, 1, 2, 2, 2, 3, 4, 4, 4, 4, 4, 5, 5, 6, 7, 7, 8, 8, 8, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 13, 13, 14, 14, 14, 14, 15, 15, 16, 17, 17, 18, 18, 18, 19, 19, 19, 19, 20, 21, 22, 22, 23, 23, 23]
    }

    // MARK: - UITableViewDataSource
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
        cell.textLabel?.text = String(items[indexPath.row])

        return cell
    }

    // MARK: - UITableViewDelegate
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

        let lastRow = tableView.indexPathsForVisibleRows()?.last as NSIndexPath
        if indexPath.row == lastRow.row {
            if scrollToTime == true {
                let indexPath = NSIndexPath(forRow: groupNoToScroll, inSection: 0)
                tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true)
                scrollToTime = false
            }
        }
    }
}
</code>```

I've assigned the value 12 for the variable groupNoToScroll. This means when the app starts I want the table view to be auto scrolled to the start of the cells of the 12s group.

But currently what my code does is scroll to the 12th cell, not the cell that has the value 12. My question is how can I check with the cells' values and scroll to the number which I specify?

答:
Swift 4: </p>

```<code>let indexPath = IndexPath(row: row, section: section)
tableView.scrollToRow(at: indexPath, at: .top, animated: true)
</code>```

<p>(first, of course, you have to assign values to row and section based on which cell you want to scroll to)</p>

Body:
I have a list of numbers in a table view like this.

As you can see the numbers are repeated. Let's consider a set of repeated numbers as a group. So there are group of 1s, group of 2s and so on.

What I want to do is when the app starts, I need to scroll to the start position of a specified group automatically. Before explaining further, here is my code so far.

import UIKit

class TableViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {

    private var scrollToTime = true
    private var items = [Int]()
    private var groupNoToScroll = 12

    override func viewDidLoad() {
        super.viewDidLoad()

        items = [1, 1, 2, 2, 2, 3, 4, 4, 4, 4, 4, 5, 5, 6, 7, 7, 8, 8, 8, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 13, 13, 14, 14, 14, 14, 15, 15, 16, 17, 17, 18, 18, 18, 19, 19, 19, 19, 20, 21, 22, 22, 23, 23, 23]
    }

    // MARK: - UITableViewDataSource
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
        cell.textLabel?.text = String(items[indexPath.row])

        return cell
    }

    // MARK: - UITableViewDelegate
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

        let lastRow = tableView.indexPathsForVisibleRows()?.last as NSIndexPath
        if indexPath.row == lastRow.row {
            if scrollToTime == true {
                let indexPath = NSIndexPath(forRow: groupNoToScroll, inSection: 0)
                tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true)
                scrollToTime = false
            }
        }
    }
}

I've assigned the value 12 for the variable groupNoToScroll. This means when the app starts I want the table view to be auto scrolled to the start of the cells of the 12s group.

But currently what my code does is scroll to the 12th cell, not the cell that has the value 12. My question is how can I check with the cells' values and scroll to the number which I specify?

Body:
Swift 4:

let indexPath = IndexPath(row: row, section: section)
tableView.scrollToRow(at: indexPath, at: .top, animated: true)

(first, of course, you have to assign values to row and section based on which cell you want to scroll to)


问:
function remove a word depending of a number - c programming
I have been stuck with this problem over 4 days:

Write a function skipWords() that takes a string named sentence and an integer named words as arguments. The function should return a pointer
  to a substring of sentence. The function should skip the number of words indicated by the parameter words.

If words is, for instance, 0, then a pointer to the beginning of the string sentence should be returned (that is, no words are skipped). If words is 1, then a pointer to the second word of sentence should be returned (i.e., one word is skipped), etc
 . To see how it should work, see the example below. The function may not print anything on the screen or take any input from the user. If words is greater or equal to the number of words in sentence, then the pointer NULL should be returned.

Example: char *ptr1, *ptr2, *ptr3, *ptr4;
 ptr1 = skipWords(“there you go”, 1); /* ptr1 points to “you go” */
ptr2 = skipWords(“there you go”, 2); /* ptr2 points to “go” */
ptr3 = skipWords(“a string”, 0); /* ptr3 points to “a string” */
ptr4 = skipWords(“a word”, 2); /* ptr4 is NULL */

got the code :

```<code>int skipWords(char sentence[], int words)
{
    int i;
    int len;

    len =strlen(sentence);

    if(words == 0)
    {
        sentence[i];
    }

    if(words == 1 && words<len)
    {

    *newsentence[i]=sentence[i];
    while (isalpha(newsentence[i])) //checking for the first blank space
    {
        i++;
    }
    newsentence[i] = '\0';

    *sentence[i]= newsentence[i]-i++;   //new string without the first word
    }

    if(words == 2 && len<words)
    {

    *newsentence[i]=sentence[i];
    // and i am lost

    else if (words>=len)
        *sentence=NULL;

}

int main()
{

    char *ptr1, *ptr2, *ptr3, *ptr4;
    ptr1= skipWords("there you go", 1);
    ptr2=skipWords("there you go", 2);
    ptr3=skipWords("a string", 0);
    ptr4=skipWords("a word",2);

    printf("%s\n", ptr1);
    printf("%s\n", ptr2);
    printf("%s\n", ptr3);
    printf("%s\n", ptr4);

    return 0;
}
</code>```

but I am completely lost.

答:
First, get rid of those “ from your code, and use " instead.
Secondly,

```<code>if(words == 0)
{
    sentence[i];
}
</code>```

This is dwelling with Undefined Behavior, since i is not initialized.
Additionally, if you compile your code with warning turned on, your compiler will generate a warning stating something like expression has no effect or similar. It means that sentence[i]; has no effect on anything.

Also, with warning turned on, your compiler would have also generated a warning which states something like variable "i" is used before its value is set or similar.

Do you realize that it all boils down to the requirement of locating a white-space in the input string, and then skip it the no. of times specified as a second argument?

All, you need to do is locate a white-space char in string.
For that, read the man page for a standard library function strchr.

There are also ways to do it, without using the strchr function.
This one is the crude way of doing it, remember not the best way, but easier one for you to understand and optimize/improvise going ahead.

```<code>#include<stdio.h>
#include<string.h>

char *skipWords(char* pStr, unsigned int uiWordsToSkip);

int main() {

    char *p1 = NULL, *p2 = NULL, *p3 = NULL, *p4 = NULL;
    char *crap = "I can not code at all!";

    p1 = skipWords(crap, 3);
    if(p1 != NULL)
        printf("\nFirst go: %s", p1);

    p2 = skipWords(crap, 2);
    if(p2 != NULL)
        printf("\nSecond go: %s", p2);

    p3 = skipWords(crap, 1);
    if(p3 != NULL)
        printf("\nThird go: %s", p3);

    p4 = skipWords(crap, 0);
    if(p4 != NULL)
        printf("\nFinal go: %s", p4);
}

char *skipWords(char* pStr, unsigned int uiWordsToSkip)
{
    int i = 0;
    char *p = pStr, *pTemp = NULL;

    const char ch = 0x20; //Hex for White Space in ASCII

    if(pStr == NULL)
    {
        return NULL;
    }

    for(i = 0; i < uiWordsToSkip; i++)
    {
        p = strchr(p, ch);
        if(p== NULL)
        {
            return pTemp ;
        }
        pTemp = p;
        p++;
    }

    return p;
}
</code>```

Produces an output:

```<code>First go: code at all!
Second go: not code at all!
Third go: can not code at all!
Final go: I can not code at all!
</code>```

Body:
I have been stuck with this problem over 4 days:

Write a function skipWords() that takes a string named sentence and an integer named words as arguments. The function should return a pointer
  to a substring of sentence. The function should skip the number of words indicated by the parameter words.

If words is, for instance, 0, then a pointer to the beginning of the string sentence should be returned (that is, no words are skipped). If words is 1, then a pointer to the second word of sentence should be returned (i.e., one word is skipped), etc
 . To see how it should work, see the example below. The function may not print anything on the screen or take any input from the user. If words is greater or equal to the number of words in sentence, then the pointer NULL should be returned.

Example: char *ptr1, *ptr2, *ptr3, *ptr4;
 ptr1 = skipWords(“there you go”, 1); /* ptr1 points to “you go” */
ptr2 = skipWords(“there you go”, 2); /* ptr2 points to “go” */
ptr3 = skipWords(“a string”, 0); /* ptr3 points to “a string” */
ptr4 = skipWords(“a word”, 2); /* ptr4 is NULL */

got the code :

int skipWords(char sentence[], int words)
{
    int i;
    int len;

    len =strlen(sentence);

    if(words == 0)
    {
        sentence[i];
    }

    if(words == 1 && words<len)
    {

    *newsentence[i]=sentence[i];
    while (isalpha(newsentence[i])) //checking for the first blank space
    {
        i++;
    }
    newsentence[i] = '\0';

    *sentence[i]= newsentence[i]-i++;   //new string without the first word
    }

    if(words == 2 && len<words)
    {

    *newsentence[i]=sentence[i];
    // and i am lost

    else if (words>=len)
        *sentence=NULL;

}

int main()
{

    char *ptr1, *ptr2, *ptr3, *ptr4;
    ptr1= skipWords("there you go", 1);
    ptr2=skipWords("there you go", 2);
    ptr3=skipWords("a string", 0);
    ptr4=skipWords("a word",2);

    printf("%s\n", ptr1);
    printf("%s\n", ptr2);
    printf("%s\n", ptr3);
    printf("%s\n", ptr4);

    return 0;
}

but I am completely lost.

Body:
First, get rid of those “ from your code, and use " instead.
Secondly,

if(words == 0)
{
    sentence[i];
}

This is dwelling with Undefined Behavior, since i is not initialized.
Additionally, if you compile your code with warning turned on, your compiler will generate a warning stating something like expression has no effect or similar. It means that sentence[i]; has no effect on anything.

Also, with warning turned on, your compiler would have also generated a warning which states something like variable "i" is used before its value is set or similar.

Do you realize that it all boils down to the requirement of locating a white-space in the input string, and then skip it the no. of times specified as a second argument?

All, you need to do is locate a white-space char in string.
For that, read the man page for a standard library function strchr.

There are also ways to do it, without using the strchr function.
This one is the crude way of doing it, remember not the best way, but easier one for you to understand and optimize/improvise going ahead.

#include<stdio.h>
#include<string.h>

char *skipWords(char* pStr, unsigned int uiWordsToSkip);

int main() {

    char *p1 = NULL, *p2 = NULL, *p3 = NULL, *p4 = NULL;
    char *crap = "I can not code at all!";

    p1 = skipWords(crap, 3);
    if(p1 != NULL)
        printf("\nFirst go: %s", p1);

    p2 = skipWords(crap, 2);
    if(p2 != NULL)
        printf("\nSecond go: %s", p2);

    p3 = skipWords(crap, 1);
    if(p3 != NULL)
        printf("\nThird go: %s", p3);

    p4 = skipWords(crap, 0);
    if(p4 != NULL)
        printf("\nFinal go: %s", p4);
}

char *skipWords(char* pStr, unsigned int uiWordsToSkip)
{
    int i = 0;
    char *p = pStr, *pTemp = NULL;

    const char ch = 0x20; //Hex for White Space in ASCII

    if(pStr == NULL)
    {
        return NULL;
    }

    for(i = 0; i < uiWordsToSkip; i++)
    {
        p = strchr(p, ch);
        if(p== NULL)
        {
            return pTemp ;
        }
        pTemp = p;
        p++;
    }

    return p;
}

Produces an output:

First go: code at all!
Second go: not code at all!
Third go: can not code at all!
Final go: I can not code at all!


问:
Passing extra Intent information from Activity to View
I have an activity that is launched from another activity through an intent. The intent carries an extra "id" information. Now, the launched activity has a custom view (actually, a extension of LinearLayout class). I want to access the "id" information in the custom view. Can the activity pass that value to its contained view? Or can the view get a handle to the activity?</p>

答: make a method in your view that takes the id as a parameter, and then call that method from your activity.</p>

ContentLicense: CC BY-SA 2.5


问:
Tkinter focus on Entry when script run

I am using tkinter to make a small user input sort of thing.
I couldn't find how to set focus to an Entry box when the script is run.
I.e. When the window opens, the first thing that automatically gets focus is the Entry box. set_focus() or focus() doesn't seem to work.

Here is my code:

```<code>root = Tk()
v = StringVar()
text = Entry(root,
        textvariable=v).grid(column=0,row=0)
text.focus_set()
root.mainloop()
</code>```

答:
A geometry manager (.grid(), or .pack(), etc...) returns None. You must not use it on the same line as the assignment to a variable:

Your code was trying to call .focus_set() on a variable text whose value was set to None.

Further, the correct method to set the focus to a widget is focus_set(), not set_focus().

```<code>root = Tk()
v = StringVar()
text = Entry(root, textvariable=v)
text.grid(column=0, row=0)
text. focus_set()
root.mainloop()
</code>```

Title: Tkinter focus on Entry when script run

Body:
I am using tkinter to make a small user input sort of thing.
I couldn't find how to set focus to an Entry box when the script is run.
I.e. When the window opens, the first thing that automatically gets focus is the Entry box. set_focus() or focus() doesn't seem to work.

Here is my code:

root = Tk()
v = StringVar()
text = Entry(root,
        textvariable=v).grid(column=0,row=0)
text.focus_set()
root.mainloop()

Body:
A geometry manager (.grid(), or .pack(), etc...) returns None. You must not use it on the same line as the assignment to a variable:

Your code was trying to call .focus_set() on a variable text whose value was set to None.

Further, the correct method to set the focus to a widget is focus_set(), not set_focus().

root = Tk()
v = StringVar()
text = Entry(root, textvariable=v)
text.grid(column=0, row=0)
text. focus_set()
root.mainloop()


问:
better way than set .git on root directory for Laravel
So I'm setting up my Lavarel website on a shared webhost, as recommended by Laravel, every file but the "public" dir should be above hosts public_html for security reasons, what's the best way to track it with .git ?

My local file structure

```<code>repo
  .git
  laravel_files
    **dirs and files **
  public
    assets
    upload
    vendor
    index.php
</code>```

My webhost file structure

```<code>root
  .git
  .gitignore
  **a bunch of hidden files that cannot be tracked**
  laravel_files
    **dirs and files that need to be tracked **
  public_html
    assets
    upload
    vendor
    index.php
    other folder (subdomain for testing to be ignored)
    other folder (subdomain for testing to be ignored)
    ...
</code>```

As seen above, the git works fine locally with 2 dirs only but on the host the .git would need to be located on the root dir?

I did that by .gitignore'ing all but those 2 Laravel's dirs, the problem is that I have some dirs inside public_html that are their own repos and git doesn't work correctly

My other option would be having 2 repos, 1 for laravel dir and another for public dir (so I can still have my sub domains as it's own repos, but it's not convenient to have 1 project on 2 repos)

Or a 3rd option is to have public dir back inside laravel dir and have apaches
.htaccess pointing to laravel_dir/public/index.php but I suspect that I wouldn't be able to use my sub domains anymore? And is prone to security issues

Any other ideas? What's the best way to accomplish this?
With my file structure but still able to use dirs below repo's location as their own repos?

答:
Depending you your hoster, I can tell what I do on mine:

```<code>public_html
   example.com  // This contains the complete Laravel installation
      .git
      app
      bootstrap
      config
      public
      ...
</code>```

Then I let point the document root of the server to public_html/example.com/public. None of the other document roots point to just public_html.

Another approach might be the following:

```<code>example.com  // This contains the complete Laravel installation
    .git
    app
    bootstrap
    config
    public // symlinked to public_html/example.com
    ...
public_html
    example.com
</code>```

Then your document root should point to public_html/example.com

Body:
So I'm setting up my Lavarel website on a shared webhost, as recommended by Laravel, every file but the "public" dir should be above hosts public_html for security reasons, what's the best way to track it with .git ?

My local file structure

repo
  .git
  laravel_files
    **dirs and files **
  public
    assets
    upload
    vendor
    index.php

My webhost file structure

root
  .git
  .gitignore
  **a bunch of hidden files that cannot be tracked**
  laravel_files
    **dirs and files that need to be tracked **
  public_html
    assets
    upload
    vendor
    index.php
    other folder (subdomain for testing to be ignored)
    other folder (subdomain for testing to be ignored)
    ...

As seen above, the git works fine locally with 2 dirs only but on the host the .git would need to be located on the root dir?

I did that by .gitignore'ing all but those 2 Laravel's dirs, the problem is that I have some dirs inside public_html that are their own repos and git doesn't work correctly

My other option would be having 2 repos, 1 for laravel dir and another for public dir (so I can still have my sub domains as it's own repos, but it's not convenient to have 1 project on 2 repos)

Or a 3rd option is to have public dir back inside laravel dir and have apaches
.htaccess pointing to laravel_dir/public/index.php but I suspect that I wouldn't be able to use my sub domains anymore? And is prone to security issues

Any other ideas? What's the best way to accomplish this?
With my file structure but still able to use dirs below repo's location as their own repos?

Body:
Depending you your hoster, I can tell what I do on mine:

public_html
   example.com  // This contains the complete Laravel installation
      .git
      app
      bootstrap
      config
      public
      ...

Then I let point the document root of the server to public_html/example.com/public. None of the other document roots point to just public_html.

Another approach might be the following:

example.com  // This contains the complete Laravel installation
    .git
    app
    bootstrap
    config
    public // symlinked to public_html/example.com
    ...
public_html
    example.com

Then your document root should point to public_html/example.com


问:
Add the “iCloud containers” entitlement to your App ID
I am trying to fix this issue for hours now.
I have checked the App ID and confirmed the iCloud containers.
Also i have entered the same in the app entitlements.

But there is a always a red mark before  "Add the “iCloud containers” entitlement to your App ID". I created the new provisioning profile and removed the expired provision files also.
This is the first time i am facing this issue.

Is this issue related with the developer certificate signing or something?

答: At least in Xcode 9.1, I had to choose the Team in Signing section (Target -> General pane). The team was already chosen but I had to choose it again to make the error disappear. It might have to do with developer certificate renewal.</p>


问:
Using SwiftMailer to send via Gmail suddenly stopped working?
For years our website has used the SwiftMailer plugin to send emails via Gmail. However, seemingly randomly yesterday morning it no longer works for us; we get a message

Fatal error: Uncaught exception 'Swift_TransportException' with message 'Connection could not be established with host smtp.gmail.com [ #0]'

Any ideas what might have caused this? Did Gmail change something with the settings we need to use? Here's what we have currently:

```<code>require_once 'path/to/swift-mailer/lib/swift_required.php';
        $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com')
          ->setPort(465)
          ->setEncryption('ssl')
          ->setUsername('ouremail@gmail.com')
          ->setPassword('ourpassword')
         ;
     $mailer = Swift_Mailer::newInstance($transport);
</code>```

The problems started around 11AM yesterday morning, and absolutely nothing was changed on our end around that time. Last week I upgraded our PHP version to 5.6.32, but things were working fine since that upgrade until yesterday morning. I even tried reverting back to the old version (only back to 5.6.30), but the error still persisted. I have researched everything on here and elsewhere on the web I could find on this issue and tried everything I could, including trying TLS, changing the port number, using an IP instead of smtp.gmail.com, but nothing has worked. Any ideas?

EDIT: Just discovered the email still works from my local XAMPP setup. This setup is running PHP 5.5.9. So it must be something with our server or domain name provider.

答:
This should be a comment but 1) its a bit long, 2) the comments section is already full of irrelevance.

So you have code which was known to be working but the intended behaviour changed without a change in the code. And you thought to ask why on a site about code problems?

Something has changed outside your code. That's the first place you should be looking.

If gmail had suddenly stopped working or changed its behaviour, I'm fairly sure there would be a lot of people talking about it. Hence the most likely candidate is the infrastucture (including the CAs) supporting your PHP server. But:

1) you've told us nothing about that

2) its off-topic on SO.

Body:
For years our website has used the SwiftMailer plugin to send emails via Gmail. However, seemingly randomly yesterday morning it no longer works for us; we get a message

Fatal error: Uncaught exception 'Swift_TransportException' with message 'Connection could not be established with host smtp.gmail.com [ #0]'

Any ideas what might have caused this? Did Gmail change something with the settings we need to use? Here's what we have currently:

require_once 'path/to/swift-mailer/lib/swift_required.php';
        $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com')
          ->setPort(465)
          ->setEncryption('ssl')
          ->setUsername('ouremail@gmail.com')
          ->setPassword('ourpassword')
         ;
     $mailer = Swift_Mailer::newInstance($transport);

The problems started around 11AM yesterday morning, and absolutely nothing was changed on our end around that time. Last week I upgraded our PHP version to 5.6.32, but things were working fine since that upgrade until yesterday morning. I even tried reverting back to the old version (only back to 5.6.30), but the error still persisted. I have researched everything on here and elsewhere on the web I could find on this issue and tried everything I could, including trying TLS, changing the port number, using an IP instead of smtp.gmail.com, but nothing has worked. Any ideas?

EDIT: Just discovered the email still works from my local XAMPP setup. This setup is running PHP 5.5.9. So it must be something with our server or domain name provider.


问:
Why the background is not showing up? (CSS problem)
I have the following Xul:

```<code><?xml version="1.0"?>

<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<?xml-stylesheet href="chrome://bartest/skin/bartest.css" type="text/css"?>

<window width="400" height="300"
    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

    <vbox id="backBox">
        <hbox id="frontBox">

            <!-- this label is needed, else this box doesn't show up -->
            <label value="" />

        </hbox>
    </vbox>

</window>
</code>```

with the following CSS:

```<code>#backBox {
    background-color: red;
    width: 200px;
    position: fixed;
    left: 0;
}

#frontBox {
    background-color: blue;
    width: 100px;
    position: fixed;
    left: 0;
}
</code>```

I expected to see a 200px red box, and a 100px blue box inside. But what I'm seeing is just the 100px blue box.

Why the red box (id="backBox") is not showing up?

答: What should happen here is that both the boxes should be stretched to the width of the window, because you haven't told them not to, and containers stretch their children by default. If you want their boxes to respect their CSS width then you need to change their alignment which is achieved either by the align="start" attribute or CSS -moz-box-align: start; but note that these belong on the parents i.e. the window and the vbox.</p>

Body:
I have the following Xul:

<?xml version="1.0"?>

<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<?xml-stylesheet href="chrome://bartest/skin/bartest.css" type="text/css"?>

<window width="400" height="300"
    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

    <vbox id="backBox">
        <hbox id="frontBox">

        </hbox>
    </vbox>

</window>

with the following CSS:

#backBox {
    background-color: red;
    width: 200px;
    position: fixed;
    left: 0;
}

#frontBox {
    background-color: blue;
    width: 100px;
    position: fixed;
    left: 0;
}

I expected to see a 200px red box, and a 100px blue box inside. But what I'm seeing is just the 100px blue box.

Why the red box (id="backBox") is not showing up?


问:
Convert seconds to HH-MM-SS with JavaScript?
How can I convert seconds to an HH-MM-SS string using JavaScript?

答:
There are lots of options of solve this problem, and obvious there are good option suggested about, But I wants to add one more optimized code here

```<code>function formatSeconds(sec) {
     return [(sec / 3600), ((sec % 3600) / 60), ((sec % 3600) % 60)]
            .map(v => v < 10 ? "0" + parseInt(v) : parseInt(v))
            .filter((i, j) => i !== "00" || j > 0)
            .join(":");
}
</code>```

if you don't wants formatted zero with less then 10 number, you can use

```<code>function formatSeconds(sec) {
  return parseInt(sec / 3600) + ':' + parseInt((sec % 3600) / 60) + ':' + parseInt((sec % 3600) % 60);
</code>```

}

Sample Code http://fiddly.org/1c476/1

Body:
There are lots of options of solve this problem, and obvious there are good option suggested about, But I wants to add one more optimized code here

function formatSeconds(sec) {
     return [(sec / 3600), ((sec % 3600) / 60), ((sec % 3600) % 60)]
            .map(v => v < 10 ? "0" + parseInt(v) : parseInt(v))
            .filter((i, j) => i !== "00" || j > 0)
            .join(":");
}

if you don't wants formatted zero with less then 10 number, you can use

function formatSeconds(sec) {
  return parseInt(sec / 3600) + ':' + parseInt((sec % 3600) / 60) + ':' + parseInt((sec % 3600) % 60);

}

Sample Code http://fiddly.org/1c476/1


问:
How can I access values of [UIApplicationOpenURLOptionsKey : Any] in Swift 4?
I am new in Swift. I wish to access the sourceApplication value inside the options parameter of this method.

```<code>optional func application(_ app: UIApplication,
                     open url: URL,
                  options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool
</code>```

I checked the documentation and I found out that UIApplicationOpenURLOptionsKey is a structure. It contains a type property: static let sourceApplication: UIApplicationOpenURLOptionsKey

But when I tried to access the sourceApplication value by doing this:

```<code>options.sourceApplication
</code>```

...this error was thrown:

Value of type '[UIApplicationOpenURLOptionsKey : Any]' has no member 'sourceApplication'

I have a thought that this might be a dictionary, But the type of the key is UIApplicationOpenURLOptionsKey. I don't have any idea how to access the value using the key type UIApplicationOpenURLOptionsKey.

I checked out tutorials point and some other sites, but didn't find a solution.

My questions are:

How do I access the value named sourceApplication from options?

What do you call this type of parameter? ([UIApplicationOpenURLOptionsKey : Any] = [:])? Is this a dictionary?

答:
UPDATE for Swift 4.2

The method was changed to:

```<code>func open(_ url: URL,
          options: [UIApplication.OpenExternalURLOptionsKey : Any] = [:],
          completionHandler completion: ((Bool) -> Void)? = nil)
</code>```

You can access the keys in the same way.

options is a dictionary. You should access the sourceApplication key of it.

```<code>if let sourceApp = options[.sourceApplication] as? String {
    //work with the value
}
</code>```

From Apple's documentation about sourceApplication:

Contains the bundle ID of the app that sent the open-URL request to your app. Value is an NSString object.

Body:
I am new in Swift. I wish to access the sourceApplication value inside the options parameter of this method.

optional func application(_ app: UIApplication,
                     open url: URL,
                  options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool

I checked the documentation and I found out that UIApplicationOpenURLOptionsKey is a structure. It contains a type property: static let sourceApplication: UIApplicationOpenURLOptionsKey

But when I tried to access the sourceApplication value by doing this:

options.sourceApplication

...this error was thrown:

Value of type '[UIApplicationOpenURLOptionsKey : Any]' has no member 'sourceApplication'

I have a thought that this might be a dictionary, But the type of the key is UIApplicationOpenURLOptionsKey. I don't have any idea how to access the value using the key type UIApplicationOpenURLOptionsKey.

I checked out tutorials point and some other sites, but didn't find a solution.

My questions are:

How do I access the value named sourceApplication from options?

What do you call this type of parameter? ([UIApplicationOpenURLOptionsKey : Any] = [:])? Is this a dictionary?

Body:
UPDATE for Swift 4.2

The method was changed to:

func open(_ url: URL,
          options: [UIApplication.OpenExternalURLOptionsKey : Any] = [:],
          completionHandler completion: ((Bool) -> Void)? = nil)

You can access the keys in the same way.

options is a dictionary. You should access the sourceApplication key of it.

if let sourceApp = options[.sourceApplication] as? String {
    //work with the value
}

From Apple's documentation about sourceApplication:

Contains the bundle ID of the app that sent the open-URL request to your app. Value is an NSString object.


问:
File google-services.json is missing. The Google Services Plugin cannot function without it ionic 3
I am using FCM for push notification I always get this error message

"File google-services.json is missing. The Google Services Plugin
  cannot function without it ionic 3"

on phone I have placed my google-services.json on every folder and nothings working

答:
From your dropdown select

project

then go to app folder

then paste your file inside app folder.

clean build and rebuild again


问:
How can I get the URL of an internet shortcut (.url)?
My client has some internet shortcuts (*.url) on his desktop and I want to get their URL through a VB application and use them as variables.

Any idea how can I do that?

答:
There's a sample on MSDN for *.lnk and *.appref-ms-files.

But seems to work for *.url-files too.

Quote from the site:

To check if a file is a shortcut and to resolve a shortcut path, the
  COM Library Microsoft Shell Controls And Automation is used. This
  library is added to the References of the Visual Studio project.

Code:

```<code>Public Function IsShortcut(strPath As String) As Boolean
    If Not File.Exists(strPath) Then
        Return False
    End If

    Dim directory As String = Path.GetDirectoryName(strPath)
    Dim strFile As String = Path.GetFileName(strPath)

    Dim shell As Shell32.Shell = New Shell32.Shell()
    Dim folder As Shell32.Folder = shell.NameSpace(directory)
    Dim folderItem As Shell32.FolderItem = folder.ParseName(strFile)

    If folderItem IsNot Nothing Then
        Return folderItem.IsLink
    End If

    Return False
End Function

Public Function ResolveShortcut(strPath As String) As String
    If IsShortcut(strPath) Then
        Dim directory As String = Path.GetDirectoryName(strPath)
        Dim strFile As String = Path.GetFileName(strPath)

        Dim shell As Shell32.Shell = New Shell32.Shell()
        Dim folder As Shell32.Folder = shell.NameSpace(directory)
        Dim folderItem As Shell32.FolderItem = folder.ParseName(strFile)

        Dim link As Shell32.ShellLinkObject = folderItem.GetLink

        Return link.Path
    End If

    Return String.Empty
End Function
</code>```

Body:
There's a sample on MSDN for *.lnk and *.appref-ms-files.

But seems to work for *.url-files too.

Quote from the site:

To check if a file is a shortcut and to resolve a shortcut path, the
  COM Library Microsoft Shell Controls And Automation is used. This
  library is added to the References of the Visual Studio project.

Code:

Public Function IsShortcut(strPath As String) As Boolean
    If Not File.Exists(strPath) Then
        Return False
    End If

    Dim directory As String = Path.GetDirectoryName(strPath)
    Dim strFile As String = Path.GetFileName(strPath)

    Dim shell As Shell32.Shell = New Shell32.Shell()
    Dim folder As Shell32.Folder = shell.NameSpace(directory)
    Dim folderItem As Shell32.FolderItem = folder.ParseName(strFile)

    If folderItem IsNot Nothing Then
        Return folderItem.IsLink
    End If

    Return False
End Function

Public Function ResolveShortcut(strPath As String) As String
    If IsShortcut(strPath) Then
        Dim directory As String = Path.GetDirectoryName(strPath)
        Dim strFile As String = Path.GetFileName(strPath)

        Dim shell As Shell32.Shell = New Shell32.Shell()
        Dim folder As Shell32.Folder = shell.NameSpace(directory)
        Dim folderItem As Shell32.FolderItem = folder.ParseName(strFile)

        Dim link As Shell32.ShellLinkObject = folderItem.GetLink

        Return link.Path
    End If

    Return String.Empty
End Function


问:
Issue with RestSharp installation in Visual-Studio 2013
I am trying to use RestSharp in my C# Visual-Studio 2013 project to POST data at a given URL. When i try to install the package via NuGet it gives me the following error:

```<code>Installing 'RestSharp 106.1.0'.
Successfully installed 'RestSharp 106.1.0'.
Adding 'RestSharp 106.1.0' to WebApplicationJson.
Uninstalling 'RestSharp 106.1.0'.
Successfully uninstalled 'RestSharp 106.1.0'.
Install failed. Rolling back...
Could not install package 'RestSharp 106.1.0'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.
</code>```

As far as I have read in GitHub this is mostly an issue for .NetPortable framework so I am out of ideas. I have also tried to change my framework version to 3.5 but still the same error.

Has anyone encountered a similar issue?

If you need further information please comment.

答:
If anyone encounters this kind of problem in the future. I solved it by installing it via Package Manager Console found in (Tools -> NuGet Package Manager -> Package Manager Console) and running the following command:

```<code>  Install-Package RestSharp -Version 103.1.0
</code>```

Notice that the installation for RestSharp version 106.1.0 always kept failing, so I changed the version to 103.1.0. Hope this helps anyone with a similar issue.

EDIT

Thanks to phuzi in the comments, RestSharp version 106.1.0 requires .Net framework 4.5.2, as for version 103.1.0 no dependencies are listed.

Body:
I am trying to use RestSharp in my C# Visual-Studio 2013 project to POST data at a given URL. When i try to install the package via NuGet it gives me the following error:

Installing 'RestSharp 106.1.0'.
Successfully installed 'RestSharp 106.1.0'.
Adding 'RestSharp 106.1.0' to WebApplicationJson.
Uninstalling 'RestSharp 106.1.0'.
Successfully uninstalled 'RestSharp 106.1.0'.
Install failed. Rolling back...
Could not install package 'RestSharp 106.1.0'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

As far as I have read in GitHub this is mostly an issue for .NetPortable framework so I am out of ideas. I have also tried to change my framework version to 3.5 but still the same error.

Has anyone encountered a similar issue?

If you need further information please comment.

Body:
If anyone encounters this kind of problem in the future. I solved it by installing it via Package Manager Console found in (Tools -> NuGet Package Manager -> Package Manager Console) and running the following command:

  Install-Package RestSharp -Version 103.1.0

Notice that the installation for RestSharp version 106.1.0 always kept failing, so I changed the version to 103.1.0. Hope this helps anyone with a similar issue.

EDIT

Thanks to phuzi in the comments, RestSharp version 106.1.0 requires .Net framework 4.5.2, as for version 103.1.0 no dependencies are listed.


问:
Replace all None's in a Pandas data frame with a tuple of None's
So I am working on some code for an NLP application. An interesting solution on Stackoverflow creates a dataframe from lists of unequal lengths. Taking the code from that solution with tuples in the input:

```<code>import pandas as pd
import itertools

aa = [('aa1',4), ('aa2',3), ('aa3',2), ('aa4',2), ('aa5',1)]
bb = [('bb1',8), ('bb2',6), ('bb3',4), ('bb4',4)]
cc = [('cc1',3), ('cc2',2), ('cc3',1)]
nest = [aa, bb, cc]

df = pd.DataFrame((_ for _ in itertools.zip_longest(*nest)), columns=['aa', 'bb', 'cc'])
df
</code>```

you get a dataframe which looks like this:

A subsequent step requires all elements in the data frame to be tuples.

I have tried this:

```<code>df.replace({None : (None,None)})
</code>```

While it seems to run without error, it does not carry out any replacement.
Any ideas how to accomplish this?

答:
It seems this could work, while I don't know why.

```<code>df = df.where(df!=[None], '(None, None)')
</code>```

It may be better to use "np.nan" than "None" in DataFrame, as fillna could be used.

Body:
So I am working on some code for an NLP application. An interesting solution on Stackoverflow creates a dataframe from lists of unequal lengths. Taking the code from that solution with tuples in the input:

import pandas as pd
import itertools

aa = [('aa1',4), ('aa2',3), ('aa3',2), ('aa4',2), ('aa5',1)]
bb = [('bb1',8), ('bb2',6), ('bb3',4), ('bb4',4)]
cc = [('cc1',3), ('cc2',2), ('cc3',1)]
nest = [aa, bb, cc]

df = pd.DataFrame((_ for _ in itertools.zip_longest(*nest)), columns=['aa', 'bb', 'cc'])
df

you get a dataframe which looks like this:

A subsequent step requires all elements in the data frame to be tuples.

I have tried this:

df.replace({None : (None,None)})

While it seems to run without error, it does not carry out any replacement.
Any ideas how to accomplish this?

Body:
It seems this could work, while I don't know why.

df = df.where(df!=[None], '(None, None)')

It may be better to use "np.nan" than "None" in DataFrame, as fillna could be used.


问:
Check if a user is authenticated in controller
There are many code snippets how to check if authenticated user is authorized to request a resource. But i cannot find a example to check if the user is authenticated at all.

I've got a kernel request listener, in which i'm trying to check if a user is authenticated, using this code:

```<code>if (TRUE === $this->get('security.authorization_checker')->isGranted('ROLE_USER'))
{
    //doing stuff
}
</code>```

I get the following error message:

```<code>AuthenticationCredentialsNotFoundException in classes.php line 5307:
The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL.
</code>```

I guess, this is because the user is not logged in at all, and therefore doesn't have any authentication token.

So my question is: how do i, in a symfony controller, check if a user is authenticated before i check if he is authorized?

答:
You can check it like that : </p>

```<code>$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
</code>```

Body:
There are many code snippets how to check if authenticated user is authorized to request a resource. But i cannot find a example to check if the user is authenticated at all.

I've got a kernel request listener, in which i'm trying to check if a user is authenticated, using this code:

if (TRUE === $this->get('security.authorization_checker')->isGranted('ROLE_USER'))
{
    //doing stuff
}

I get the following error message:

AuthenticationCredentialsNotFoundException in classes.php line 5307:
The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL.

I guess, this is because the user is not logged in at all, and therefore doesn't have any authentication token.

So my question is: how do i, in a symfony controller, check if a user is authenticated before i check if he is authorized?

Body:
You can check it like that :

$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');


问:
RESTful Geocoding API Nokia HERE for whole country
Trying to find addresses in Norway using the Nokia HERE RESTful Geocoding API where I search with only the street name, the API returns locations close to my position. This makes sense in most scenarios, BUT I need all streets with the search name in a wider area ( ex a county og even a country if the street name is not to common ).

How can this be achieved with this API ?

答:
The two options for returning geocode results within a confined area are geocode using partial address information:

Partial Address - Country is critical e.g., NOR

and geocode an address within a Bounding Box:

Bounding Box - Pass comma delimited rectangle coordinates with search text.

The difference is in the results:

Partial Address with NOR and Hasleveien as the street returns 4 results while Bounding Box returns 5.  My experience has been that using the bounding box with search text versus using partial address with a street name will provide more results.  However, bounding boxes are rectangles so bounding the entire country Norway will include Sweden so you will need to filter the results to only Norway.


问:
issue in fetching long list of geolocations in rails
The following script works fine for me but after fetching some records (generally 100 records) it failed and give me error:--

```<code>Invalid JSON string
</code>```

and sometimes after fetching some 500 records it stop fetching coordinates.
I need to fecth some 18000 coordinates any suggestions??

```<code> task :populate_geolocations_reverse => :environment do
  AdvocateDetail.order("id DESC").all.each do |advocate|
  p advocate.id
  if advocate.latitude.nil? or advocate.latitude==0 or advocate.latitude=="0"
     p "fetching geolocations...:-( "
     a = Geocoder.fetch_coordinates(advocate.address)
     unless a.nil?
       p "got geolocations... :-) "
       advocate.latitude=a[0]
       advocate.longitude=a[1]
       p "saving geolocations...:-P "
     advocate.save(false)
  end
else
   p " already have geolocations for this Jumped....:-)"
end
end
p "transformation done... "

end
</code>```

答: Please remember that google has its limit to serve your requests. It is around 1000 unique requests per day and 1 per second. As I know Geokit uses more services than google itself, but it still may be limited. Take a closer look on that.</p>

Body:
The following script works fine for me but after fetching some records (generally 100 records) it failed and give me error:--

Invalid JSON string

and sometimes after fetching some 500 records it stop fetching coordinates.
I need to fecth some 18000 coordinates any suggestions??

 task :populate_geolocations_reverse => :environment do
  AdvocateDetail.order("id DESC").all.each do |advocate|
  p advocate.id
  if advocate.latitude.nil? or advocate.latitude==0 or advocate.latitude=="0"
     p "fetching geolocations...:-( "
     a = Geocoder.fetch_coordinates(advocate.address)
     unless a.nil?
       p "got geolocations... :-) "
       advocate.latitude=a[0]
       advocate.longitude=a[1]
       p "saving geolocations...:-P "
     advocate.save(false)
  end
else
   p " already have geolocations for this Jumped....:-)"
end
end
p "transformation done... "

end


问:
Swift Codable Map Children by ID
I have the following code.

```<code>import Foundation

let jsonData = """
[
    {"id": "1", "firstname": "Tom", "lastname": "Smith", "age": "28"},
    {"id": "2", "firstname": "Bob", "lastname": "Smith"},
    {"id": "3", "firstname": "Jim", "lastname": "Smith", "parentid": "2"},
    {"id": "4", "firstname": "Ray", "lastname": "Smith", "parentid": "3"}
]
""".data(using: .utf8)!

class Person: Codable {
    let id: String
    let firstName, lastName: String
    let age: String?
    let parentid: String?
    let children: [Person]?

    enum CodingKeys : String, CodingKey {
        case firstName = "firstname"
        case lastName = "lastname"
        case age
        case parentid
        case id
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        firstName = try values.decode(String.self, forKey: .firstName)
        lastName = try values.decode(String.self, forKey: .lastName)
        age = try values.decodeIfPresent(String.self, forKey: .age)
        parentid = try values.decodeIfPresent(String.self, forKey: .parentid)
        id = try values.decodeIfPresent(String.self, forKey: .id)
    }

}

let decoded = try JSONDecoder().decode([Person].self, from: jsonData)
print(decoded)
</code>```

So I have that children property. I basically want decoded to be an array with 2 Person objects (Tom and Bob). decoded[1].children should be an array with 1 Person object (Jim). And decoded[1].children[0] should be an array with 1 Person object (Ray).

How can I achieve this using the Swift Codable system?

答:
You can do something like:

```<code>    if let decoded = try? JSONDecoder().decode([Person].self, from: jsonData)
    {
        for person in decoded
        {
            person.children = decoded.filter({ (child) -> Bool in
                return person.id == child.parentid
            })
        }
    }
</code>```

In the above code, after getting decoded array I just traversed it using a for loop to identify the children of each person if exist.

Title: Swift Codable Map Children by ID

Body:
I have the following code.

import Foundation

let jsonData = """
[
    {"id": "1", "firstname": "Tom", "lastname": "Smith", "age": "28"},
    {"id": "2", "firstname": "Bob", "lastname": "Smith"},
    {"id": "3", "firstname": "Jim", "lastname": "Smith", "parentid": "2"},
    {"id": "4", "firstname": "Ray", "lastname": "Smith", "parentid": "3"}
]
""".data(using: .utf8)!

class Person: Codable {
    let id: String
    let firstName, lastName: String
    let age: String?
    let parentid: String?
    let children: [Person]?

    enum CodingKeys : String, CodingKey {
        case firstName = "firstname"
        case lastName = "lastname"
        case age
        case parentid
        case id
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        firstName = try values.decode(String.self, forKey: .firstName)
        lastName = try values.decode(String.self, forKey: .lastName)
        age = try values.decodeIfPresent(String.self, forKey: .age)
        parentid = try values.decodeIfPresent(String.self, forKey: .parentid)
        id = try values.decodeIfPresent(String.self, forKey: .id)
    }

}

let decoded = try JSONDecoder().decode([Person].self, from: jsonData)
print(decoded)

So I have that children property. I basically want decoded to be an array with 2 Person objects (Tom and Bob). decoded[1].children should be an array with 1 Person object (Jim). And decoded[1].children[0] should be an array with 1 Person object (Ray).

How can I achieve this using the Swift Codable system?

Body:
You can do something like:

    if let decoded = try? JSONDecoder().decode([Person].self, from: jsonData)
    {
        for person in decoded
        {
            person.children = decoded.filter({ (child) -> Bool in
                return person.id == child.parentid
            })
        }
    }

In the above code, after getting decoded array I just traversed it using a for loop to identify the children of each person if exist.


问:
Create linked list relationship between nodes having same relation to other nodes in neo4j
As in this figure

is it possible to create a linked-list relationship between all (:B) nodes that share a relationship [:R] with the same (:A) node, for all (:A) nodes in the database. If order is important, then assume there is a property order in all (:B) nodes.

答:
```<code>MATCH (A:A)-[:R]->(B:B)
WITH A,
     B
ORDER BY B.order ASC // Comment out this line if the order is not important
WITH A,
     collect(B) as bnodes // List of all nodes of the desired type
UNWIND RANGE(0, size(bnodes)-2) as i // Go through all the nodes except the last one
WITH bnodes[i] as B,
     bnodes[i+1] as BN
CREATE (B)-[:NEXT]->(BN)
</code>```


问:
Angular 5 routing and navigation with URL Error
I am developing a small project in Angular 5, I made the router configuration in the code, if I click the menu in navbar I can navigate between components, but if I enter a component through the URL it gives me error.

If you enter the link by this https://fit.simpleclouder.com/ it works.

If you enter the link by this https://fit.simpleclouder.com/home it does not work.

If you enter the link by this https://fit.simpleclouder.com/benefics does not work.

If I click through the menu on the website, it works.

In a main folder in ftp i have this project on folder "laravel/public/fit", because i have another project Laravel on main folder.

答:
Instead of  https://fit.simpleclouder.com/home

goto this URL https://fit.simpleclouder.com/#/home .

well for the sake of simplicity we use hash based routing.

In your Router config pass { useHash: true } as the second argument

```<code>const rootRouting: ModuleWithProviders = RouterModule.forRoot([
  {
    path: '',
    component: HomeComponent
  },
  {
    path: 'profile',
    component: ProfileComponent
  }
], { useHash: true });
</code>```

so this would make a hash based routing as its guaranteed to work in virtually any environment setup.

Body:
Instead of  https://fit.simpleclouder.com/home

goto this URL https://fit.simpleclouder.com/#/home .

well for the sake of simplicity we use hash based routing.

In your Router config pass { useHash: true } as the second argument

const rootRouting: ModuleWithProviders = RouterModule.forRoot([
  {
    path: '',
    component: HomeComponent
  },
  {
    path: 'profile',
    component: ProfileComponent
  }
], { useHash: true });

so this would make a hash based routing as its guaranteed to work in virtually any environment setup.


问:
extracting numbers from Bitmap in android using tess-two library
I want to extract a number from a Bitmap. I'm using the tess-two library, but it does not recognize correctly.

Example Code:

```<code>    @Override
        public void onClick(View v) {
        switch (v.getId()){
        case R.id.b2:
        InputStream is = null;
        try {
        is = getApplicationContext().getAssets().open("zak.jpeg");
        } catch (IOException e1) {
        e1.printStackTrace();
        }
         final Drawable drw = Drawable.createFromStream(is, null);
         bmp = ((BitmapDrawable) drw).getBitmap();

        TessBaseAPI baseApi = new TessBaseAPI();
           bmp =BITMAP_RESIZER(bmp,bmp.getWidth(),bmp.getHeight());
            bmp =convertToGrayscale(bmp);
             bmp =RemoveNoise(bmp);
             iv.setImageBitmap(bmp);

          baseApi.init("/mnt/sdcard/Download/", "eng");
          baseApi.setVariable(TessBaseAPI.VAR_CHAR_WHITELIST,"1234567890");
          baseApi.setVariable(TessBaseAPI.VAR_CHAR_BLACKLIST,"!@#$%^&*   ()_+=-[]}{" +";:'\"\\|~`,./<>?");
          baseApi.setDebug(true);
         baseApi.setImage(bmp);

        String recognizedText = baseApi.getUTF8Text();
        tv.setText(" numbers : "+recognizedText.trim());
        Log.d("karim", recognizedText);
        baseApi.end();
             break;
</code>```

Method to convert the Bitmap to grayscale:

```<code> public static Bitmap convertToGrayscale(Bitmap bmpOriginal) {
          int width, height;
           height = bmpOriginal.getHeight();
          width = bmpOriginal.getWidth();

         Bitmap bmpGrayscale = Bitmap.createBitmap(width, height,  Bitmap.Config.ARGB_8888);
         Canvas c = new Canvas(bmpGrayscale);
         Paint paint = new Paint();
         ColorMatrix cm = new ColorMatrix();
         cm.setSaturation(0);
         ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
         paint.setColorFilter(f);
         c.drawBitmap(bmpOriginal, 0, 0, paint);
         return bmpGrayscale;
     }
</code>```

Method to remove the noise from the Bitmap:

```<code>  public Bitmap RemoveNoise(Bitmap bmap) {
        for (int x = 0; x < bmap.getWidth(); x++) {
        for (int y = 0; y < bmap.getHeight(); y++) {
        int pixel = bmap.getPixel(x, y);
        int R = Color.red(pixel);
        int G = Color.green(pixel);
        int B = Color.blue(pixel);
        if (R < 162 && G < 162 && B < 162)
        bmap.setPixel(x, y, Color.BLACK);
        }
    }
        for (int  x = 0; x < bmap.getWidth(); x++) {
        for (int y = 0; y < bmap.getHeight(); y++) {
        int pixel = bmap.getPixel(x, y);
        int R = Color.red(pixel);
        int G = Color.green(pixel);
        int B = Color.blue(pixel);
        if (R > 162 && G > 162 && B > 162)
              bmap.setPixel(x, y, Color.WHITE);
        }
    }
       return bmap;
    }
</code>```

Method to resize the bitmap:

```<code>   public Bitmap BITMAP_RESIZER(Bitmap bitmap,int newWidth,int newHeight)
      {
    Bitmap scaledBitmap = Bitmap.createBitmap(newWidth, newHeight, Config.ARGB_8888);

    float ratioX = newWidth / (float) bitmap.getWidth();
    float ratioY = newHeight / (float) bitmap.getHeight();
    float middleX = newWidth / 2.0f;
    float middleY = newHeight / 2.0f;

    Matrix scaleMatrix = new Matrix();
    scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

    Canvas canvas = new Canvas(scaledBitmap);
    canvas.setMatrix(scaleMatrix);
    canvas.drawBitmap(bitmap, middleX - bitmap.getWidth() / 2, middleY - bitmap.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));

    return scaledBitmap;

    }
</code>```

How do I fix this problem?

Body:
I want to extract a number from a Bitmap. I'm using the tess-two library, but it does not recognize correctly.

Example Code:

    @Override
        public void onClick(View v) {
        switch (v.getId()){
        case R.id.b2:
        InputStream is = null;
        try {
        is = getApplicationContext().getAssets().open("zak.jpeg");
        } catch (IOException e1) {
        e1.printStackTrace();
        }
         final Drawable drw = Drawable.createFromStream(is, null);
         bmp = ((BitmapDrawable) drw).getBitmap();

        TessBaseAPI baseApi = new TessBaseAPI();
           bmp =BITMAP_RESIZER(bmp,bmp.getWidth(),bmp.getHeight());
            bmp =convertToGrayscale(bmp);
             bmp =RemoveNoise(bmp);
             iv.setImageBitmap(bmp);

          baseApi.init("/mnt/sdcard/Download/", "eng");
          baseApi.setVariable(TessBaseAPI.VAR_CHAR_WHITELIST,"1234567890");
          baseApi.setVariable(TessBaseAPI.VAR_CHAR_BLACKLIST,"!@#$%^&*   ()_+=-[]}{" +";:'\"\\|~`,./<>?");
          baseApi.setDebug(true);
         baseApi.setImage(bmp);

        String recognizedText = baseApi.getUTF8Text();
        tv.setText(" numbers : "+recognizedText.trim());
        Log.d("karim", recognizedText);
        baseApi.end();
             break;

Method to convert the Bitmap to grayscale:

 public static Bitmap convertToGrayscale(Bitmap bmpOriginal) {
          int width, height;
           height = bmpOriginal.getHeight();
          width = bmpOriginal.getWidth();

         Bitmap bmpGrayscale = Bitmap.createBitmap(width, height,  Bitmap.Config.ARGB_8888);
         Canvas c = new Canvas(bmpGrayscale);
         Paint paint = new Paint();
         ColorMatrix cm = new ColorMatrix();
         cm.setSaturation(0);
         ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
         paint.setColorFilter(f);
         c.drawBitmap(bmpOriginal, 0, 0, paint);
         return bmpGrayscale;
     }

Method to remove the noise from the Bitmap:

  public Bitmap RemoveNoise(Bitmap bmap) {
        for (int x = 0; x < bmap.getWidth(); x++) {
        for (int y = 0; y < bmap.getHeight(); y++) {
        int pixel = bmap.getPixel(x, y);
        int R = Color.red(pixel);
        int G = Color.green(pixel);
        int B = Color.blue(pixel);
        if (R < 162 && G < 162 && B < 162)
        bmap.setPixel(x, y, Color.BLACK);
        }
    }
        for (int  x = 0; x < bmap.getWidth(); x++) {
        for (int y = 0; y < bmap.getHeight(); y++) {
        int pixel = bmap.getPixel(x, y);
        int R = Color.red(pixel);
        int G = Color.green(pixel);
        int B = Color.blue(pixel);
        if (R > 162 && G > 162 && B > 162)
              bmap.setPixel(x, y, Color.WHITE);
        }
    }
       return bmap;
    }

Method to resize the bitmap:

   public Bitmap BITMAP_RESIZER(Bitmap bitmap,int newWidth,int newHeight)
      {
    Bitmap scaledBitmap = Bitmap.createBitmap(newWidth, newHeight, Config.ARGB_8888);

    float ratioX = newWidth / (float) bitmap.getWidth();
    float ratioY = newHeight / (float) bitmap.getHeight();
    float middleX = newWidth / 2.0f;
    float middleY = newHeight / 2.0f;

    Matrix scaleMatrix = new Matrix();
    scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

    Canvas canvas = new Canvas(scaledBitmap);
    canvas.setMatrix(scaleMatrix);
    canvas.drawBitmap(bitmap, middleX - bitmap.getWidth() / 2, middleY - bitmap.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));

    return scaledBitmap;

    }

How do I fix this problem?

Body: baseApi.SetVariable("tessedit_char_whitelist", "0123456789");


问:
Confirm code that returns nodes with two children
I was given the following code that is supposed to determine the number of nodes in a tree that have two children...

```<code>public int twoChildren(TreeNode<Integer> root){
    int counter= 0;
    if (root == null)
        return 0;
    else if (root.right != null && root.left != null)
        counter++;

    int leftTwoChildren = twoChildren(root.left);
    int rightTwoChildren = twoChildren(root.right);

    return counter + leftTwoChildren + rightTwoChildren;
}
</code>```

My job is to identify if this code is doing that, and if it isn't then figure out what the issue is. It all seems to check out with me, but I just wanted to double check that the counter works on this example. Would I even need the two integers for the left and right? I'm not sure. If someone could confirm this checks out or let me know there's an issue I would greatly appreciate it.

答:
Your code will work fine if you return 0 instead of null </p>

```<code>if(root==null)
   return 0;
</code>```

<p>You don't need the two integers for left and right, you can return the recursive calls explicitly, and also get rid of counter integer. </p>

```<code> public int twoChildren(TreeNode<Integer> root){

   if (root == null)
    return 0;

   if (root.right != null && root.left != null)
    return 1 + twoChildren(root.left) + twoChildren(root.right);

    return twoChildren(root.left) + twoChildren(root.right);
}
</code>```

Body:
I was given the following code that is supposed to determine the number of nodes in a tree that have two children...

public int twoChildren(TreeNode<Integer> root){
    int counter= 0;
    if (root == null)
        return 0;
    else if (root.right != null && root.left != null)
        counter++;

    int leftTwoChildren = twoChildren(root.left);
    int rightTwoChildren = twoChildren(root.right);

    return counter + leftTwoChildren + rightTwoChildren;
}

My job is to identify if this code is doing that, and if it isn't then figure out what the issue is. It all seems to check out with me, but I just wanted to double check that the counter works on this example. Would I even need the two integers for the left and right? I'm not sure. If someone could confirm this checks out or let me know there's an issue I would greatly appreciate it.

Body:
Your code will work fine if you return 0 instead of null

if(root==null)
   return 0;

You don't need the two integers for left and right, you can return the recursive calls explicitly, and also get rid of counter integer.

 public int twoChildren(TreeNode<Integer> root){

   if (root == null)
    return 0;

   if (root.right != null && root.left != null)
    return 1 + twoChildren(root.left) + twoChildren(root.right);

    return twoChildren(root.left) + twoChildren(root.right);
}


问:
Create a variable with jQuery based off the value of a class' HTML value and then passing that variable elsewhere
I'm attempting to do the following.  I need to "grab" the value found in a specific list item, then assign it to a variable name, and then use that variable in a few other places in the code.

Here's what I'm trying to do specifically line by line.  I need to get the Category value from the following list item.

```<code><li class="fc_cart_item_option fc_cart_category_code">Category: SHIP6</li>
</code>```

In this case the value I'm trying to get is "SHIP6".  The values will be either "SHIP1" through "SHIP9" (i.e. SHIP1, SHIP2, SHIP3, etc. up to SHIP9) and that's it.  Then if the value is equal to "SHIP1", I need to assign a value to a variable (I'm assuming).  If the value is "SHIP1", I'd like to have the variable equal to "1.00", if "SHIP2", the variable's value "2.00", if "SHIP3", the variable's value "3.00", and so on up to 9.  If I don't need to store it as a variable, please let me know.  But at this point I'm assuming I do.  So for the sake of this discussion, we'll call it "variable_category_ship".  So now that we've assigned the value to this variable (variable_category_ship), I need to then do the following.

Further down in the code I have this line of jQuery:

```<code>$('#fc_cart_foot_total').before("<tr id='fc_cart_foot_tax'><td class='fc_col1' colspan='2'>Sales Tax:</td><td class='fc_col2'>$0.00</td></tr><tr id='fc_cart_foot_shipping'><td class='fc_col1' colspan='2'>Shipping:</td><td class='fc_col2'>$4.00</td></tr>");
</code>```

I need to replace "4.00" with the variable amount we create from above.  So I'm imagining it will now be the following:

```<code>    $('#fc_cart_foot_total').before("<tr id='fc_cart_foot_tax'><td class='fc_col1' colspan='2'>Sales Tax:</td><td class='fc_col2'>$0.00</td></tr><tr id='fc_cart_foot_shipping'><td class='fc_col1' colspan='2'>Shipping:</td><td class='fc_col2'>$(variable_category_ship)</td></tr>");
</code>```

So to confirm, if:

```<code><li class="fc_cart_item_option fc_cart_category_code">Category: SHIP5</li>
</code>```

Then:

```<code>$('#fc_cart_foot_total').before("<tr id='fc_cart_foot_tax'><td class='fc_col1' colspan='2'>Sales Tax:</td><td class='fc_col2'>$0.00</td></tr><tr id='fc_cart_foot_shipping'><td class='fc_col1' colspan='2'>Shipping:</td><td class='fc_col2'>$5.00</td></tr>");
</code>```

How would I go about doing this?  Thanks!

答:
Try this:</p>

```<code>var val = $("li.fc_cart_category_code").text();
val = "$" + val.replace(/[^0-9]/g, "") + ".00";
$('#fc_cart_foot_total').before("<tr id='fc_cart_foot_tax'><td class='fc_col1' colspan='2'>Sales Tax:</td><td class='fc_col2'>$0.00</td></tr><tr id='fc_cart_foot_shipping'><td class='fc_col1' colspan='2'>Shipping:</td><td class='fc_col2'>" + val + "</td></tr>");
</code>```

Body:
I'm attempting to do the following.  I need to "grab" the value found in a specific list item, then assign it to a variable name, and then use that variable in a few other places in the code.

Here's what I'm trying to do specifically line by line.  I need to get the Category value from the following list item.

Category: SHIP6

In this case the value I'm trying to get is "SHIP6".  The values will be either "SHIP1" through "SHIP9" (i.e. SHIP1, SHIP2, SHIP3, etc. up to SHIP9) and that's it.  Then if the value is equal to "SHIP1", I need to assign a value to a variable (I'm assuming).  If the value is "SHIP1", I'd like to have the variable equal to "1.00", if "SHIP2", the variable's value "2.00", if "SHIP3", the variable's value "3.00", and so on up to 9.  If I don't need to store it as a variable, please let me know.  But at this point I'm assuming I do.  So for the sake of this discussion, we'll call it "variable_category_ship".  So now that we've assigned the value to this variable (variable_category_ship), I need to then do the following.

Further down in the code I have this line of jQuery:

$('#fc_cart_foot_total').before("
Sales Tax:	$0.00

Shipping:	$4.00
");

I need to replace "4.00" with the variable amount we create from above.  So I'm imagining it will now be the following:

    $('#fc_cart_foot_total').before("
Sales Tax:	$0.00

Shipping:	$(variable_category_ship)
");

So to confirm, if:

Category: SHIP5

Then:

$('#fc_cart_foot_total').before("
Sales Tax:	$0.00

Shipping:	$5.00
");

How would I go about doing this?  Thanks!

Body:
Try this:

var val = $("li.fc_cart_category_code").text();
val = "$" + val.replace(/[^0-9]/g, "") + ".00";
$('#fc_cart_foot_total').before("<tr id='fc_cart_foot_tax'><td class='fc_col1' colspan='2'>Sales Tax:</td><td class='fc_col2'>$0.00</td></tr><tr id='fc_cart_foot_shipping'><td class='fc_col1' colspan='2'>Shipping:</td><td class='fc_col2'>" + val + "</td></tr>");


问:
LinkedIn V2 API permission for reading socialActions and Shares
I get no permissions error when i make the following linkedIn V2 Api call
https://api.linkedin.com/v2/socialActions/{share URN}?oauth2_access_token={access token}

LinkedIn Api Response

```<code>{
serviceErrorCode: 100,
message: "Not enough permissions to access /socialActions/{target} GET ",
status: 403
}
</code>```

These are the
Default application Permissions

can someone please help on this. (Need to make this work on V2 api)

答: On using the updated V2 access token, the endpoints were working good.</p>

Body:
I get no permissions error when i make the following linkedIn V2 Api call
https://api.linkedin.com/v2/socialActions/{share URN}?oauth2_access_token={access token}

LinkedIn Api Response

{
serviceErrorCode: 100,
message: "Not enough permissions to access /socialActions/{target} GET ",
status: 403
}

These are the
Default application Permissions

can someone please help on this. (Need to make this work on V2 api)


问:
How to resize website for 1080x1920 Mobile and Monitor?
So I'm trying to resize my webpage in css using the @media query for both monitor and mobile. However, my mobile is 1080x1920 and so is my monitor. So when I use the media query, my mobile inherits my monitor's css.

How do you distinguish from the two?

Thanks.

答:
It's sounds as if your phone is zooming out to display the full website.

Have you got a "responsive meta tag" on the page? This should go in the  of your page.

<meta name="viewport" content="width=device-width">

It tells the browser to match the media query pixels to your devices actual width, and not it's pixel count.

Body:
It's sounds as if your phone is zooming out to display the full website.

Have you got a "responsive meta tag" on the page? This should go in the <head></head> of your page.

<meta name="viewport" content="width=device-width">

It tells the browser to match the media query pixels to your devices actual width, and not it's pixel count.


问:
How to debug into my nuget package deployed from TeamCity?
I have put a library that my team uses into a nuget package that is deployed from TeamCity into a network folder.  I cannot debug into this code though!  SymbolSource is one solution I have read about but I would much rather find some way to have access to the .pdb/source files directly from TeamCity.  Does anyone know how to do this?

Edit.  When I check 'Include Symbols and Source' in the Nuget Pack build step, TeamCity creates a .Symbol.nupkg in addition to the .nupkg file in the network folder.  The .Symbol.nupkg contains the src and the .pdb file.

Edit.  I unchecked 'Include Symbols and Source' on TeamCity and added the following to my nuspec file:

  <files>
    <file src="..\MyLibrary\bin\release\MyLibrary.dll" target="lib\net40" />
    <file src="..\MyLibrary\bin\release\MyLibrary.pdb" target="lib\net40" />
    <file src="..\MyLibrary\*.cs" target="src" />
    <file src="..\MyLibrary\**\*.cs" target="src" />
  </files>
```

This added the dll, the pdb, and the source files for my library in the nuget package and didn't generate a .Symbols file which I think is only needed for symbol servers.

答:
I've found a super simple way to do this, which I have blogged about here:

https://mattfrear.com/2017/11/29/speed-up-development-in-a-nuget-package-centric-solution/

This only works if you're using the new .NET Core style .csproj with <PackageReference> (on either .NET Core or .NET Framework).

This again assumes you have access to the source code of the NuGet package.

Build and compile the NuGet package on your local machine

Copy the .dll you've just compiled into your local NuGet packages feed folder (On my machine, this is C:\Users\matt\.nuget\packages\), overwriting the existing NuGet package .dll.

That's it! You should be able to step into the package while debugging. No messing around with .pdbs or source servers. This has greatly sped up my development cycle.

Body:
I have put a library that my team uses into a nuget package that is deployed from TeamCity into a network folder.  I cannot debug into this code though!  SymbolSource is one solution I have read about but I would much rather find some way to have access to the .pdb/source files directly from TeamCity.  Does anyone know how to do this?

Edit.  When I check 'Include Symbols and Source' in the Nuget Pack build step, TeamCity creates a .Symbol.nupkg in addition to the .nupkg file in the network folder.  The .Symbol.nupkg contains the src and the .pdb file.

Edit.  I unchecked 'Include Symbols and Source' on TeamCity and added the following to my nuspec file:

  <files>
    <file src="..\MyLibrary\bin\release\MyLibrary.dll" target="lib\net40" />
    <file src="..\MyLibrary\bin\release\MyLibrary.pdb" target="lib\net40" />
    <file src="..\MyLibrary\*.cs" target="src" />
    <file src="..\MyLibrary\**\*.cs" target="src" />
  </files>

This added the dll, the pdb, and the source files for my library in the nuget package and didn't generate a .Symbols file which I think is only needed for symbol servers.


问:
E/BeaconManager: Cannot contact service to set scan periods
Hi guys i am using android-beacon-library and  getting  this message  Cannot contact service to set scan periods while start scan  and beacons are not getting scanned.  here is my code `

```<code>@Override
public void onCreate() {
    super.onCreate();
    context = getApplicationContext();
    AxeltaLogger.debug("Application class on create is called");
    mBeaconManager = BeaconManager.getInstanceForApplication(this);
    mBeaconManager.getBeaconParsers().add(AxeltaBeaconParser.getInstance(context));
    allBeaconsRegion = new Region("AxeltaS7", Identifier.parse("e2c56db5-dffb-48d2-b060-d0f5a71096e0"), null, null);

}

public void startScan() {
    try {
        stopScan();
        regionBootstrap = new RegionBootstrap(this, allBeaconsRegion);
        mBeaconManager.setBackgroundScanPeriod(SCAN_PERIOD);
        mBeaconManager.setBackgroundBetweenScanPeriod(SCAN_BETWEEN_PERIOD);
        mBeaconManager.setForegroundScanPeriod(SCAN_PERIOD);
        mBeaconManager.setForegroundBetweenScanPeriod(SCAN_BETWEEN_PERIOD);
        mBeaconManager.setBackgroundMode(true);
    }catch (Exception e){
        AxeltaLogger.err("Error>>>"+e);
    }
}

public void stopScan() {
    if (regionBootstrap != null) {
        regionBootstrap.disable();
        regionBootstrap = null;
    }
}
</code>```

`

答:
Two issues:

When using RegionBootstrap, you must wait for the first call back to didDetermineStateForRegion before setting scan periods or background mode.

RegionBootstrap is not designed to repeatedly stop and start scanning -- you should not keep constructing new RegionBootstrap instances.  If you do not want scanning to start at app startup, do not use this class.  Instead call beaconManager.bind(this) in onCreate  and in the onBeaconServiceConnected callback set up your scan periods.  You can then  start and stop scanning by calling startMonitoringBeaconsInRegion and stopMonitoringBeaconsInRegion

Body:
Hi guys i am using android-beacon-library and  getting  this message  Cannot contact service to set scan periods while start scan  and beacons are not getting scanned.  here is my code `

@Override
public void onCreate() {
    super.onCreate();
    context = getApplicationContext();
    AxeltaLogger.debug("Application class on create is called");
    mBeaconManager = BeaconManager.getInstanceForApplication(this);
    mBeaconManager.getBeaconParsers().add(AxeltaBeaconParser.getInstance(context));
    allBeaconsRegion = new Region("AxeltaS7", Identifier.parse("e2c56db5-dffb-48d2-b060-d0f5a71096e0"), null, null);

}

public void startScan() {
    try {
        stopScan();
        regionBootstrap = new RegionBootstrap(this, allBeaconsRegion);
        mBeaconManager.setBackgroundScanPeriod(SCAN_PERIOD);
        mBeaconManager.setBackgroundBetweenScanPeriod(SCAN_BETWEEN_PERIOD);
        mBeaconManager.setForegroundScanPeriod(SCAN_PERIOD);
        mBeaconManager.setForegroundBetweenScanPeriod(SCAN_BETWEEN_PERIOD);
        mBeaconManager.setBackgroundMode(true);
    }catch (Exception e){
        AxeltaLogger.err("Error>>>"+e);
    }
}

public void stopScan() {
    if (regionBootstrap != null) {
        regionBootstrap.disable();
        regionBootstrap = null;
    }
}

`


问:
Is it possible to add more information/functionality than just a title in a marker in Google Maps?
Using the following line of code (with latlongVariable being coordinates for a location), I can add a marker to a map which will then produce a title of the location when clicked.

```<code>mMap.addMarker(new MarkerOptions().position(latlongVariable).title("Marker Location Title"))
</code>```

My question is, is it possible to add more than simply a title to the marker? For example, could I include a list view displaying more information about the location as well, maybe including a button that will send the user to another activity when clicked?

I've tried to research Android Google Map's onMapReady() method and it's functionality but I can't find the answers I'm looking for. Any suggestions?

答:
Just set InfoWindowAdapter to map and in getInfoContents inflate your custom layout.

mMap.setInfoWindowAdapter(new InfoWindowAdapter() {

```<code>    @Override
    public View getInfoWindow(Marker arg0) {
        return null;
    }

    @Override
    public View getInfoContents(Marker arg0) {

        View v = getLayoutInflater().inflate(R.layout.custom_infowindow, null);
        return v;

    }
});
</code>```

Body:
Using the following line of code (with latlongVariable being coordinates for a location), I can add a marker to a map which will then produce a title of the location when clicked.

mMap.addMarker(new MarkerOptions().position(latlongVariable).title("Marker Location Title"))

My question is, is it possible to add more than simply a title to the marker? For example, could I include a list view displaying more information about the location as well, maybe including a button that will send the user to another activity when clicked?

I've tried to research Android Google Map's onMapReady() method and it's functionality but I can't find the answers I'm looking for. Any suggestions?

Body:
Just set InfoWindowAdapter to map and in getInfoContents inflate your custom layout.

mMap.setInfoWindowAdapter(new InfoWindowAdapter() {

    @Override
    public View getInfoWindow(Marker arg0) {
        return null;
    }

    @Override
    public View getInfoContents(Marker arg0) {

        View v = getLayoutInflater().inflate(R.layout.custom_infowindow, null);
        return v;

    }
});