问:
(C++) CURL_STATICLIB: No such file or directory
I've installed and configured my curl library and linked it to MinGW through CodeBlocks. Everything went fine, but when I built the code, I get an error:

```<code>CURL_STATICLIB        No such file or directory
</code>```

Here's a screenshot of the error:
CURL_STATICLIB Error

I've defined CURL_STATICLIB in #defines:
CURL_STATICLIB in #defines

Also here's a build log:

```<code>-------------- Build: Debug in CurlTest (compiler: GNU GCC Compiler)---------------

mingw32-g++.exe -Wall -fexceptions -g CURL_STATICLIB -DCURL_STATICLIB -std=c++11 -lcurl -DCURL_STATICLIB -IC:\libs\curl\include -c C:\Users\ondre\OneDrive\Documents\Projects++\CurlTest\main.cpp -o obj\Debug\main.o
mingw32-g++.exe: error: CURL_STATICLIB: No such file or directory
Process terminated with status 1 (0 minute(s), 0 second(s))
1 error(s), 0 warning(s) (0 minute(s), 0 second(s))
</code>```

My compiler info:

```<code>MinGW gcc (GCC) 5.3.0
</code>```

答:
From your failing compile command:

```<code>mingw32-g++.exe -Wall -fexceptions -g CURL_STATICLIB -DCURL_STATICLIB -std=c++11 \
-lcurl -DCURL_STATICLIB -IC:\libs\curl\include \
-c C:\Users\ondre\OneDrive\Documents\Projects++\CurlTest\main.cpp-o obj\Debug\main.o
</code>```

we can see that as well as adding CURL_STATICLIB to the preprocessor
defines (-DCURL_STATICLIB), you have also in fact added it to your
Other compiler options (-g CURL_STATICLIB). And since of course
the string CURL_STATICLIB is not a g++ option and does not
begin with -, g++ interprets it as the name of an input file
for the compilation, which explains your error.

Futhermore you have added -lcurl to your compile options,
indicating that your want to link libcurl with your program. This isn't
a compile option, it is a linkage option. The compiler will ignore it
and, if you have not also added it to your linker options, then your
program will fail to link once you have succeeded in compiling it.

To fix this, remove -lcurl from your compiler options and add it
to Other linker options

Body:
I've installed and configured my curl library and linked it to MinGW through CodeBlocks. Everything went fine, but when I built the code, I get an error:

CURL_STATICLIB        No such file or directory

Here's a screenshot of the error:
CURL_STATICLIB Error

I've defined CURL_STATICLIB in #defines:
CURL_STATICLIB in #defines

Also here's a build log:

-------------- Build: Debug in CurlTest (compiler: GNU GCC Compiler)---------------

mingw32-g++.exe -Wall -fexceptions -g CURL_STATICLIB -DCURL_STATICLIB -std=c++11 -lcurl -DCURL_STATICLIB -IC:\libs\curl\include -c C:\Users\ondre\OneDrive\Documents\Projects++\CurlTest\main.cpp -o obj\Debug\main.o
mingw32-g++.exe: error: CURL_STATICLIB: No such file or directory
Process terminated with status 1 (0 minute(s), 0 second(s))
1 error(s), 0 warning(s) (0 minute(s), 0 second(s))

My compiler info:

MinGW gcc (GCC) 5.3.0

Body:
From your failing compile command:

mingw32-g++.exe -Wall -fexceptions -g CURL_STATICLIB -DCURL_STATICLIB -std=c++11 \
-lcurl -DCURL_STATICLIB -IC:\libs\curl\include \
-c C:\Users\ondre\OneDrive\Documents\Projects++\CurlTest\main.cpp-o obj\Debug\main.o

we can see that as well as adding CURL_STATICLIB to the preprocessor
defines (-DCURL_STATICLIB), you have also in fact added it to your
Other compiler options (-g CURL_STATICLIB). And since of course
the string CURL_STATICLIB is not a g++ option and does not
begin with -, g++ interprets it as the name of an input file
for the compilation, which explains your error.

Futhermore you have added -lcurl to your compile options,
indicating that your want to link libcurl with your program. This isn't
a compile option, it is a linkage option. The compiler will ignore it
and, if you have not also added it to your linker options, then your
program will fail to link once you have succeeded in compiling it.

To fix this, remove -lcurl from your compiler options and add it
to Other linker options


来源: stackexchange

问:
Could someone please provide a walkthrough on how to setup a self signing ssl certificate on cloud 9?
I am migrating my personal hobby python web application from 127.0.0.1 to cloud 9 lately, but found myself completely new to the idea of setting up ssl certificate. I did some online research on openssl and its python wrapper but still couldn't find any definitive guide on how to set it up in practice, specifically for the cloud 9 IDE platform.

Could someone please give a walkthough, or point out some references link here? Thanks.

By the way, I'm using cherrypy for the python server.

EDIT: specifically, I have the following questions:

is it requred to run openssl from the server(in my case, cloud9 bash), or I can run openssl from my local laptop then upload the generated key and cert?

does it make any sense to use passphrase to protect the key? I don't see any point here, correct me if I'm wrong please

how to install it to cloud9?

答: Cloud9 runs your app behind an https proxy, so you need to just use http, since cloud9 proxy won't accept your self signed certificate. </p>

ContentLicense: CC BY-SA 3.0


问:
Using callback for ajax
I want to prevent a function to execute before get a value from ajax, I'm trying using async:false it works but deprecated. So, I'm using callback like what I found on internet. It's works too, but the browser still tell me if the callback is not the function. Here's my code

function User() {
    this.nama;
    this.nis;
    this.pass;
    this.role;
    this.url = "http://localhost/elearning-web/";

    this.Login = function(call) {
        $.ajax({
            type:"POST",url:this.url+"dologin.php",data:"nis="+this.nis+"&pass="+this.pass,
            success:function(e){
                call(e);
            }
        });
    }
}```

When I check the console.log it's show what I want to display, but the browser tell me if the call (callback) is not a function. Thanks in advance

答:
What you want to do is already achievable using Promise API, and yes, jQuery supports it too.

You just need to change the Login function as below:

```<code>function User() {
  // .. other code truncated for brevity

  this.Login = function() {
    return $.ajax({
      type: 'POST',
      url: 'your_url'
      // Note that `success` function has been removed from here
    });
  }
}
</code>```

Now this solves a lot of problems. First of all, the caller of User.Login doesn't need to pass a callback function. The login function can just be used like this:

```<code>var user = new User();

user.Login()
  .then(function(e) {
    // `e` is accessible here
  });
</code>```

Second, there can be unlimited number of .then() chained with each other, providing better code readability.

Third, you need not to validate the callback to be a function since .then accepts a function as its argument (validates it for free).

Fourth, success callbacks are deprecated by jQuery. .then() uses the new syntax.

Title: Using callback for ajax

Body:
I want to prevent a function to execute before get a value from ajax, I'm trying using async:false it works but deprecated. So, I'm using callback like what I found on internet. It's works too, but the browser still tell me if the callback is not the function. Here's my code

function User() {
    this.nama;
    this.nis;
    this.pass;
    this.role;
    this.url = "http://localhost/elearning-web/";

    this.Login = function(call) {
        $.ajax({
            type:"POST",url:this.url+"dologin.php",data:"nis="+this.nis+"&pass="+this.pass,
            success:function(e){
                call(e);
            }
        });
    }
}

When I check the console.log it's show what I want to display, but the browser tell me if the call (callback) is not a function. Thanks in advance

Body:
What you want to do is already achievable using Promise API, and yes, jQuery supports it too.

You just need to change the Login function as below:

function User() {
  // .. other code truncated for brevity

  this.Login = function() {
    return $.ajax({
      type: 'POST',
      url: 'your_url'
      // Note that `success` function has been removed from here
    });
  }
}

Now this solves a lot of problems. First of all, the caller of User.Login doesn't need to pass a callback function. The login function can just be used like this:

var user = new User();

user.Login()
  .then(function(e) {
    // `e` is accessible here
  });

Second, there can be unlimited number of .then() chained with each other, providing better code readability.

Third, you need not to validate the callback to be a function since .then accepts a function as its argument (validates it for free).

Fourth, success callbacks are deprecated by jQuery. .then() uses the new syntax.


问:
Group duplicate column IDs in pandas dataframe
Now there are a lot of similar questions but most of them answer how to delete the duplicate columns. However, I want to know how can I make a list of tuples where each tuple contains the column names of duplicate columns. I am assuming that each column has a unique name. Just to further illustrate my question:

```<code>df = pd.DataFrame({'A': [1, 2, 3, 4, 5],'B': [2, 4, 2, 1, 9],
                   'C': [1, 2, 3, 4, 5],'D': [2, 4, 2, 1, 9],
                   'E': [3, 4, 2, 1, 2],'F': [1, 1, 1, 1, 1]},
                   index = ['a1', 'a2', 'a3', 'a4', 'a5'])
</code>```

then I want the output:

```<code>[('A', 'C'), ('B', 'D')]
</code>```

And if you are feeling great today then also extend the same question to rows. How to get a list of tuples where each tuple contains duplicate rows.

答:
Here's a single-liner

```<code>In [22]: from itertools import combinations

In [23]: [x for x in combinations(df.columns, 2) if (df[x[0]] == df[x[-1]]).all()]
Out[23]: [('A', 'C'), ('B', 'D')]
</code>```

Alternatively, using NumPy broadcasting. Better, look at Divakar's solution

```<code>In [124]: cols = df.columns

In [125]: dftv = df.T.values

In [126]: cross = pd.DataFrame((dftv == dftv[:, None]).all(-1), cols, cols)

In [127]: cross
Out[127]:
       A      B      C      D      E      F
A   True  False   True  False  False  False
B  False   True  False   True  False  False
C   True  False   True  False  False  False
D  False   True  False   True  False  False
E  False  False  False  False   True  False
F  False  False  False  False  False   True

# Only take values from lower triangle
In [128]: s = cross.where(np.tri(*cross.shape, k=-1)).unstack()

In [129]: s[s == 1].index.tolist()
Out[129]: [('A', 'C'), ('B', 'D')]
</code>```

Body:
Now there are a lot of similar questions but most of them answer how to delete the duplicate columns. However, I want to know how can I make a list of tuples where each tuple contains the column names of duplicate columns. I am assuming that each column has a unique name. Just to further illustrate my question:

df = pd.DataFrame({'A': [1, 2, 3, 4, 5],'B': [2, 4, 2, 1, 9],
                   'C': [1, 2, 3, 4, 5],'D': [2, 4, 2, 1, 9],
                   'E': [3, 4, 2, 1, 2],'F': [1, 1, 1, 1, 1]},
                   index = ['a1', 'a2', 'a3', 'a4', 'a5'])

then I want the output:

[('A', 'C'), ('B', 'D')]

And if you are feeling great today then also extend the same question to rows. How to get a list of tuples where each tuple contains duplicate rows.

Body:
Here's a single-liner

In [22]: from itertools import combinations

In [23]: [x for x in combinations(df.columns, 2) if (df[x[0]] == df[x[-1]]).all()]
Out[23]: [('A', 'C'), ('B', 'D')]

Alternatively, using NumPy broadcasting. Better, look at Divakar's solution

In [124]: cols = df.columns

In [125]: dftv = df.T.values

In [126]: cross = pd.DataFrame((dftv == dftv[:, None]).all(-1), cols, cols)

In [127]: cross
Out[127]:
       A      B      C      D      E      F
A   True  False   True  False  False  False
B  False   True  False   True  False  False
C   True  False   True  False  False  False
D  False   True  False   True  False  False
E  False  False  False  False   True  False
F  False  False  False  False  False   True

# Only take values from lower triangle
In [128]: s = cross.where(np.tri(*cross.shape, k=-1)).unstack()

In [129]: s[s == 1].index.tolist()
Out[129]: [('A', 'C'), ('B', 'D')]


问:
Python using sum() in a user made list
So, the part of this project I cannot get to work is the sum() function.
It works during:

```<code>    a = [1, 2, 3, 4, 5]
    b = sum(a)
    print b
</code>```

But in my program, I have a user created list and the sum() keeps getting an error. len() works, but I also need the sum to obtain an average.

```<code>     namelist = []
     agelist = []

     while True:
        name = raw_input("Enter a name or type Exit to end data entry: ")
        namelist.append(name)

        if name == "Exit":      #creates an exit point from data entry
            break

        age = raw_input("How old is " + name + "? ")
        agelist.append(age)

    lenage = len(agelist)
    sumage = sum(agelist)   #here is the problem -<<
    avgage = sumage / lenage

    print avgage
</code>```

How can I get the sumage to work?
Is it not working because I did not define how long the list is?

答:
The variable age has type string, so you need to convert it to an integer:

```<code>agelist.append(int(age))
</code>```

Title: Python using sum() in a user made list

Body:
So, the part of this project I cannot get to work is the sum() function.
It works during:

    a = [1, 2, 3, 4, 5]
    b = sum(a)
    print b

But in my program, I have a user created list and the sum() keeps getting an error. len() works, but I also need the sum to obtain an average.

     namelist = []
     agelist = []

     while True:
        name = raw_input("Enter a name or type Exit to end data entry: ")
        namelist.append(name)

        if name == "Exit":      #creates an exit point from data entry
            break

        age = raw_input("How old is " + name + "? ")
        agelist.append(age)

    lenage = len(agelist)
    sumage = sum(agelist)   #here is the problem -<<
    avgage = sumage / lenage

    print avgage

How can I get the sumage to work?
Is it not working because I did not define how long the list is?

Body:
The variable age has type string, so you need to convert it to an integer:

agelist.append(int(age))


问:
Live jQuery events not firing for dynamic element
Why are none of the live (or dead) events I bind to a dynamic element firing?

```<code>(function ($) {
    $.fn.myPlugin = function () {

    var $filterBox = $("<input type='text'>").live("click", function () {
        alert("Clicked");
    });
    this.before($filterBox); // insert into DOM before current element
    return this; // keep chain
    };
})(jQuery);
</code>```

I am calling myPlugin on several <select> elements. I thought it would work without the Live plugin if I bound it before adding the element to the DOM, but not even the live events are firing. Is it because my element has no ID?

Edit:
The following does not work either:

```<code>var $filterBox = $("<input type='text'>").bind("click", function () {
        alert("Clicked");
});
</code>```

答: Why not just bind it?  http://jsfiddle.net/9WvpA/</p>

ContentLicense: CC BY-SA 2.5

Body:
Why are none of the live (or dead) events I bind to a dynamic element firing?

(function ($) {
    $.fn.myPlugin = function () {

    var $filterBox = $("<input type='text'>").live("click", function () {
        alert("Clicked");
    });
    this.before($filterBox); // insert into DOM before current element
    return this; // keep chain
    };
})(jQuery);

I am calling myPlugin on several <select> elements. I thought it would work without the Live plugin if I bound it before adding the element to the DOM, but not even the live events are firing. Is it because my element has no ID?

Edit:
The following does not work either:

var $filterBox = $("<input type='text'>").bind("click", function () {
        alert("Clicked");
});


问:
submenus in php using json
```<code><?php
    $jsondata = file_get_contents('js/brand.json');
    $data = json_decode($jsondata, true);
    $menuonesublinks = $data['menuonesublinks']['links'];
    foreach ($menuonesublinks as $menu_sublink) {
        ?>
        <?php
            echo $menu_sublink['title'];
        ?>
        <?php
    }
?>
</code>```

o/p i am getting : usa,uk

how can i get inside subcities of city values ("subcities":[{"city":"dubai"},{'city':"london"}])

brand.json

```<code>{
    "menuonesublinks": {
        "links": [
            {
                "title": "usa",
                "subcities":[{"city":"dubai"},{'city':"london"}]
            },
            {
                "title": uk
            }
        ]
    }
}
</code>```

答:
You need to change your foreach loop in the following way,

```<code>// your code
foreach ($menuonesublinks as $menu_sublink) {
    echo $menu_sublink['title'];
    if(array_key_exists('subcities', $menu_sublink)){
        foreach($menu_sublink['subcities'] as $subcity){
            // Now access subcities like this: $subcity['city']
        }
    }
}
</code>```

Here's the relevant reference:

http://php.net/manual/en/function.array-key-exists.php

Title: submenus in php using json

Body:
<?php
    $jsondata = file_get_contents('js/brand.json');
    $data = json_decode($jsondata, true);
    $menuonesublinks = $data['menuonesublinks']['links'];
    foreach ($menuonesublinks as $menu_sublink) {
        ?>
        <?php
            echo $menu_sublink['title'];
        ?>
        <?php
    }
?>

o/p i am getting : usa,uk

how can i get inside subcities of city values ("subcities":[{"city":"dubai"},{'city':"london"}])

brand.json

{
    "menuonesublinks": {
        "links": [
            {
                "title": "usa",
                "subcities":[{"city":"dubai"},{'city':"london"}]
            },
            {
                "title": uk
            }
        ]
    }
}

Body:
You need to change your foreach loop in the following way,

// your code
foreach ($menuonesublinks as $menu_sublink) {
    echo $menu_sublink['title'];
    if(array_key_exists('subcities', $menu_sublink)){
        foreach($menu_sublink['subcities'] as $subcity){
            // Now access subcities like this: $subcity['city']
        }
    }
}

Here's the relevant reference:

http://php.net/manual/en/function.array-key-exists.php


问:
How can I return a variable from a $.getJSON function
I want to return StudentId to use elsewhere outside of the scope of the $.getJSON()

```<code>j.getJSON(url, data, function(result)
{
    var studentId = result.Something;
});

//use studentId here
</code>```

I would imagine this has to do with scoping, but it doesn't seem to work the same way c# does

答:
```<code>var context;
$.ajax({
  url: 'file.json',
  async: false,
  dataType: 'json',
  success: function (json) {
    assignVariable(json);
  }
});

function assignVariable(data) {
  context = data;
}
alert(context);
</code>```

OwnerDisplayName: Sean Chambers

Body:
I want to return StudentId to use elsewhere outside of the scope of the $.getJSON()

j.getJSON(url, data, function(result)
{
    var studentId = result.Something;
});

//use studentId here

I would imagine this has to do with scoping, but it doesn't seem to work the same way c# does

LastEditorDisplayName: JasonBunting


问:
write on invalid address to RAM in VHDL, Verilog, sim behaviour
Lets have a BRAM or any other memory under Verilog or VHDL.
For example this:

```<code>module raminfr (clk, we, a, di, do);

input clk;
input we;
input  [4:0] a;
input  [3:0] di;
output [3:0] do;
reg    [3:0] ram [31:0];

  always @(posedge clk) begin
    if (we)
      ram[a] <= di;
  end
  assign do = ram[a];
endmodule
</code>```

Now lets assume that we have already write valid data to "ram".

Does simulators invavalidate all items in "ram" if address "a" will have invalid value (4'bxxxx) ("we"=1 and clk will have posedge)?
Or it lets values in ram as they were?

答:
Simulator will not invalidate anything. Instead the write will be ignored.

For reads in such a situation, it will return 'x' though.

Body:
Lets have a BRAM or any other memory under Verilog or VHDL.
For example this:

module raminfr (clk, we, a, di, do);

input clk;
input we;
input  [4:0] a;
input  [3:0] di;
output [3:0] do;
reg    [3:0] ram [31:0];

  always @(posedge clk) begin
    if (we)
      ram[a] <= di;
  end
  assign do = ram[a];
endmodule

Now lets assume that we have already write valid data to "ram".

Does simulators invavalidate all items in "ram" if address "a" will have invalid value (4'bxxxx) ("we"=1 and clk will have posedge)?
Or it lets values in ram as they were?


问:
MdBootstrap with Angular
How to make bootstrap material design with Angular.

Here is what i have tried so far .
I am using cli to build my angular project.

angular-cli.json file

I have installed MDB using npm and added these to my angular cli json file.

```<code>"styles": [
        "styles.css",
        "../node_modules/mdbootstrap/css/bootstrap.css",
        "../node_modules/mdbootstrap/css/mdb.css"
      ],
      "scripts": [
        "../node_modules/mdbootstrap/js/jquery-3.1.1.js",
        "../node_modules/mdbootstrap/js/tether.js",
        "../node_modules/mdbootstrap/js/bootstrap.js",
        "../node_modules/mdbootstrap/js/mdb.js"
      ],
</code>```

Now i add the code to the component.

```<code><button type="button" class="btn btn-warning">Warning</button>
</code>```

The code throws no error but the click wave and click are not functioning. Please help

答:
To use mdbootstrap in Angular you should install the Angular version via npm:

npm i angular-bootstrap-md -save

FontAwesome is used as well, so be sure to add it to your styles:

"../node_modules/font-awesome/scss/font-awesome.scss"

And finally, in your app.module.ts you need to include:

```<code>import { MDBBootstrapModule } from 'angular-bootstrap-md';
import { NO_ERRORS_SCHEMA } from '@angular/core';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
   ...,
    MDBBootstrapModule.forRoot()
  ],
  schemas: [NO_ERRORS_SCHEMA]
})
</code>```

See more on their github page:

https://github.com/mdbootstrap/Angular-Bootstrap-with-Material-Design

Title: MdBootstrap with Angular

Body:
How to make bootstrap material design with Angular.

Here is what i have tried so far .
I am using cli to build my angular project.

angular-cli.json file

I have installed MDB using npm and added these to my angular cli json file.

"styles": [
        "styles.css",
        "../node_modules/mdbootstrap/css/bootstrap.css",
        "../node_modules/mdbootstrap/css/mdb.css"
      ],
      "scripts": [
        "../node_modules/mdbootstrap/js/jquery-3.1.1.js",
        "../node_modules/mdbootstrap/js/tether.js",
        "../node_modules/mdbootstrap/js/bootstrap.js",
        "../node_modules/mdbootstrap/js/mdb.js"
      ],

Now i add the code to the component.

<button type="button" class="btn btn-warning">Warning</button>

The code throws no error but the click wave and click are not functioning. Please help

Body:
To use mdbootstrap in Angular you should install the Angular version via npm:

npm i angular-bootstrap-md -save

FontAwesome is used as well, so be sure to add it to your styles:

"../node_modules/font-awesome/scss/font-awesome.scss"

And finally, in your app.module.ts you need to include:

import { MDBBootstrapModule } from 'angular-bootstrap-md';
import { NO_ERRORS_SCHEMA } from '@angular/core';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
   ...,
    MDBBootstrapModule.forRoot()
  ],
  schemas: [NO_ERRORS_SCHEMA]
})

See more on their github page:

https://github.com/mdbootstrap/Angular-Bootstrap-with-Material-Design


问:
Parse Server Two Factor Authentication or Additional Admin Security
I am running the open source parse-server and have well secured my database. However, my application requires administrator users which need to have the power to read and write nearly all the data. This is a security concern which I would like to address with two-factor authentication, though I am open to other ideas (IP whitelisting, cookies, or whatnot).

Setting this up on my client apps is straightforward enough and I have done that, but I would like to be even more secure so that if malicious agents have my Application ID (which is basically public) and somehow obtain an admin's credentials, they still cannot gain access.

I am puzzled as to how to accomplish this with the parse server as it is today. There are no Cloud Code triggers for User sign-in, so I can't enforce any MFA on the Parse server itself, as far as I can tell.

One possibility I see is to use check some MFA token in various Cloud Code routines, such as beforeSave, beforeDelete, and beforeFind, denying access to an admin user lacking proper MFA. Would that completely prevent a false admin from reading or writing all data?

The above option does not prevent the attacker from trying to brute force the MFA (assuming it's a 6-digit code). I also don't see any way of rate-limiting the login attempts of an attacker with the App ID and admin password. Any ideas here?

Thanks for any tips!

答:
I really like the idea of adding 2FA and a small script to manage user accounts on the dashboard.
Can you open a feature request on https://github.com/parse-community/parse-dashboard ?

Also, for use authentication, you could probably use a custom auth adapter which would validate the username, email and 2FA token


问:
Styling nested navigators on Android with React Navigation
I've prepared this small demo: https://snack.expo.io/B1kOKaJSZ

If you turn on Preview down there and use iOS, everything works as expected. That means navigating to nested scenes shows green background.

Now if you switch to Android, the nested scenes are just white and not even aligned, like the style is ignored.

I am still pretty much rookie to RN so there is probably some gotcha, but I am currently clueless.

I've tried this on a real device also and behavior is the same.

Update: Cleaned up the demo little bit: https://snack.expo.io/Byo0_feH-

Edit: I've filed the issue with React-Navigation: https://github.com/react-community/react-navigation/issues/2106

答: I am not getting green screen neither on preview iOS nor on my personal iOS device.</p>


问:
Formal definition of a unicode string
I am trying to understand what is a "Unicode string" is, and the more I read the unicode standard the less I understand it. Let's start from a definition coming from the unicode standard.

A unicode scalar value is any integer in between 0x0 and 0xD7FF included, or in between 0xE000 and 0x10FFFF included (D76, p:119)

My feeling was that a unicode string is a sequence of unicode scalar values. I would define a UTF-8 unicode string as a sequence of unicode scalar values encoded in UTF-8. But I am not sure that it is the case. Here is one of the many definitions we can see in the standard.

"Unicode string: A code unit sequence containing code units of a particular Unicode encoding form" (D80, p:120)

But to me this definition is very fuzzy. Just too understand how bad it is, here are a few other "definitions" or strange things in the standard.

(p: 43) "A Unicode string data type is simply an ordered sequence of code units. Thus a Unicode 8- bit string is an ordered sequence of 8-bit code units."
According to this definition, any sequence of uint8 is a valid UTF-8. I would rule out this definition as it would accept anything as a unicode string!!!

(p: 122) "Unicode strings need not contain well-formed code unit sequences under all conditions. This is equivalent to saying that a particular Unicode string need not be in a Unicode encoding form. For example, it is perfectly reasonable to talk about an operation that takes the two Unicode 16-bit strings, <004D D800> and , each of which contains an ill-formed UTF-16 code unit sequence, and concatenates them to form another Unicode string <004D D800 DF02 004D>, which contains a well- formed UTF-16 code unit sequence. The first two Unicode strings are not in UTF-16, but the resultant Unicode string is."
I would rule out this definition as it would be impossible to define a sequence of unicode scalar values for a unicode string encoded in UTF-16 as this definition would allow to cut surrogate pairs!!!

For a start, let's seek for a clear definition of an UTF-8 unicode string. So far, I can propose 3 definitions, but the real one (if there is) might be different:

(1) Any array of uint8

(2) Any array of uint8 that comes from the sequence of unicode scalar value encoded in UTF-8

(3) Any subarray of an array of uint8 that comes from the sequence of unicode scalar value encoded in UTF-8

To make things concrete, here are a few examples:

[ 0xFF ] would be a UTF-8 unicode string according to definition 1, but not to definition 2 and 3 as no 0xFF can appear in a sequence of code units that comes from an UTF-8 encoded unicode scalar value.

[ 0xB0 ] would be a UTF-8 unicode string according to definition 3, but not according to definition 2 as it is the leading byte of a multi-byte code unit.

I am just lost with this "standard". Do you have any clear definition?

答:
My feeling was that a unicode string is a sequence of unicode scalar values.

No, a Unicode string is a sequence of code units. The standard doesn't contain "many definitions", but only a single one:

D80 Unicode string: A code unit sequence containing code units of a particular Unicode encoding form.

This doesn't require the string to be well-formed (see the following definitions). None of your other quotes from the standard contradict this definition. To the contrary, they only illustrate that a Unicode string, as defined by the standard, can be ill-formed.

An application shall only create well-formed strings, of course:

If a Unicode string purports to be in a Unicode encoding form, then it must not contain any ill-formed code unit subsequence.

But the standard also contains some sections on how to deal with ill-formed input sequences.

Title: Formal definition of a unicode string


问:
How to send an HTML email, what contains a php echo command?
I searched for this everywhere, but I couldn't find it. I want to echo some variables. My message:  </p>

```<code>$mailMsg ='<table class="head-wrap" bgcolor="#999999"  width: 100%; margin: 0; padding: 0;">
   <tr  margin: 0; padding: 0;">
   <td  margin: 0; padding: 0;"></td>
   <td class="header container" align=""  display: block !important; max-width: 600px !important; clear: both !important; margin: 0 auto; padding: 0;">

   </td>
   <td  margin: 0; padding: 0;"></td>
   </tr>
   </table>

   <table class="body-wrap" bgcolor=""  width: 100%; margin: 0; padding: 0;">
   <tr  margin: 0; padding: 0;">
   <td  margin: 0; padding: 0;"></td>
   <td class="container" align="" bgcolor="#FFFFFF"  display: block !important; max-width: 600px !important; clear: both !important; margin: 0 auto; padding: 0;">

     <div class="content"  max-width: 600px; display: block; margin: 0 auto; padding: 15px;">
       <table  width: 100%; margin: 0; padding: 0;">
         <tr  margin: 0; padding: 0;">
           <td  margin: 0; padding: 0;">
             <h1 line-height: 1.1; color: #000; font-weight: 200; font-size: 44px; margin: 0 0 15px; padding: 0;">New purchase at Cali client!</h1>
     <p  font-weight: normal; font-size: 14px; line-height: 1.6; margin: 0 0 10px; padding: 0;">Email: </p>
     '
      + echo $useremail +
     '

  <br  margin: 0; padding: 0;" />
        <p  font-weight: normal; font-size: 14px; line-height: 1.6; margin: 0 0 10px; padding: 0;">Discord: </p>
        '+ echo $userdiscord +'
  <br  margin: 0; padding: 0;" />
        <p  font-weight: normal; font-size: 14px; line-height: 1.6; margin: 0 0 10px; padding: 0;">Ip: </p>
  '
  + echo $ip;
</code>```

答:
Do not use + to connect strings in PHP. Use . instead.

And there is no need to echo the variable.

So instead of

```<code>' + echo $useremail + '
</code>```

do

```<code>' . $useremail . '
</code>```

then the common way of sending mail in PHP: How to send an email using PHP?

You may also use placeholders in your HTML template and replace them with your vars then.

For example:

```<code>$mail_template = '<table><tr><td>##USERNAME##</td></tr></table>';
$mail_final = str_replace('##USERNAME##', $username, $mail_template);
// ...
mail($to, $subject, $mail_final, $headers);
</code>```

Body:
I searched for this everywhere, but I couldn't find it. I want to echo some variables. My message:

$mailMsg ='

New purchase at Cali client!

Email:

     '
      + echo $useremail +
     '

Discord:

        '+ echo $userdiscord +'

Ip:

  '
  + echo $ip;

Body:
Do not use + to connect strings in PHP. Use . instead.

And there is no need to echo the variable.

So instead of

' + echo $useremail + '

do

' . $useremail . '

then the common way of sending mail in PHP: How to send an email using PHP?

You may also use placeholders in your HTML template and replace them with your vars then.

For example:

$mail_template = '<table><tr><td>##USERNAME##</td></tr></table>';
$mail_final = str_replace('##USERNAME##', $username, $mail_template);
// ...
mail($to, $subject, $mail_final, $headers);


问:
Set different color of CardView for newly added items in recycler view
I want to set a different color to the Items added in a Firebase Recycler view. I am using a Card View to display data. What I want is : suppose I already have some data in the list, and they will be having white background. Now suppose some new values are added in the list. I want the newly added items to have a different background tint(Say green) than the items already present. I am fetching data from Firebase. Now after I view the card details or after viewing the new data for first time,the color of these new cards should now be white because now they are old.It would be helpful if I the card retain their color until the card details are read (The card details are accessed by tapping the card which starts a new activity with detailed info).</p>

答:
You've to implement getItemViewType method of Adapter class like below

```<code>@Override
public int getItemViewType(int position) {
    // here i'm assuming that you've some method isNewItem(position)
    // which returns item type as integer and
    // ITEM_TYPE_NEW and ITEM_TYPE_OLD are declared as constants
    if (isNewItem(position)) {
        return ITEM_TYPE_NEW;
    } else {
        return ITEM_TYPE_OLD;
    }
}
</code>```

In method onBindViewHolder you should change background colour if it is of type new.

```<code>@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    final int itemType = getItemViewType(position);
    if (itemType == ITEM_TYPE_NEW) {
        // here I'm assuming that there is setNewItemBackColor method
        // present in your adapter class which changes background color
        // of card view of ViewHolder
        ((YourViewHolderClassNameHere)holder).setNewItemBackColor();
    }
}
</code>```

Refer this answer for more detailed implementation.

Body:
You've to implement getItemViewType method of Adapter class like below

@Override
public int getItemViewType(int position) {
    // here i'm assuming that you've some method isNewItem(position)
    // which returns item type as integer and
    // ITEM_TYPE_NEW and ITEM_TYPE_OLD are declared as constants
    if (isNewItem(position)) {
        return ITEM_TYPE_NEW;
    } else {
        return ITEM_TYPE_OLD;
    }
}

In method onBindViewHolder you should change background colour if it is of type new.

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    final int itemType = getItemViewType(position);
    if (itemType == ITEM_TYPE_NEW) {
        // here I'm assuming that there is setNewItemBackColor method
        // present in your adapter class which changes background color
        // of card view of ViewHolder
        ((YourViewHolderClassNameHere)holder).setNewItemBackColor();
    }
}

Refer this answer for more detailed implementation.


问:
Is it secure to get new csrf hash token from ajax response?
I use zend 1 framework and I have form that use ajax multiple time, I secured it with csrf, but after first request csrf token will expire and I need new One. Is it secure to pass new csrf token from server side and use it in front side for new ajax call?</p>

答:
Having a rolling CSRF token is always a bad design because if the user has multiple windows open then a race condition occurs on which CSRF token is currently valid.

When implementing any security system try and use an existing library or a well documented technique. Don't shoot from the hip, read the CSRF prevention Cheat sheet.

A rotating CSRF token does not improve security because the same bypass techniques will always obtain the current CSRF token.  All CSRF mitigations rely upon the Same-Origin Policy - and if your application has a SOP bypass - such as a weak crossdomain.xml file or an insecure CORS ruleset, or XSS - then an attacker can use this vulnerability to read any HTTP response. For any given web application some HTTP response must have the CSRF token, and an SOP bypass can be used to read this token and forge interactions between the browser and web application.

It doesn't matter what type of CSRF mitigation is in place - XSS can always be used to force the browser into performing any action that the user can perform.  If a request that is vulnerability to reflective XSS, also requires a CSRF token then it will be very difficult or impossible to exploit.  For this reason, CSRF & XSS have a kind of rock paper scissors relationship.


问:
Laravel 5 oauth with both social and local accounts
everyone!

In my app I want to have an abily to login from account in social networks as well as from accounts registered localy and have access to the same database on my server.

What I mean:

Scenario 1:
User pressed "login with facebook"
-> Get access to application features

Scenario 2:
User pressed "login with account registred localy on my server"
-> Get access to application features

If I login from local account then it's easy to check auth data and grant access.
If I login in my app from twitter for example and got their tokens, how could I use them to access data on my server?

I found information only about how to make local login using Passport or using social services using Socialite but not both at the same time.

答: Well, turns out, it's actually easy to implement using only Socialite with standart auth. I misunderstood the concept of oauth so there is no need for passport at all.</p>


问:
How to generate JSON-Schema from Swagger API Declaration
I have Swagger API Declaration for services using Swagger v 1.2.

My original feeling about Swagger was that it is very close to JSON Schema (Draft 3 and lately Draft 4) and it shall be relatively easy to generate JSON Schema for request and response objects.

However, while part of the Swagger reuses JSON Schema structures, it turned out that it uses only a subset of features, and it also introduces its own inheritance in Models (using subTypes and discriminator).

Question: Is there any existing project or piece of code which can generate usable JSON Schema from Swagger API Declaration?

Optimally JSON Schema Draft 4 and using Python (but I will be happy to find anything).

答:
I've had some success doing it like this:

swagger.yaml -> proto -> jsonschema

I used openapi2proto to generate proto files from Swagger yaml, then protoc-gen-jsonschema to generate the JSONSchemas from that. It's good enough to get a typed JSONSchema, but proto3 doesn't support "required" types so you miss out on this.

ContentLicense: CC BY-SA 4.0


问:
Best Free MySQL Profiler in 2017
I'm currently developing an asp.net application and it is slow.
I just want to find out if it is making unnecessary multiple db calls.

What is the best free mysql profiler?

[I know this question will likely be closed for 'off-topic' reason]

答:
"Unnecessary" calls is far too complex a question to begin to answer.

The SlowLog will tell you which types of queries are the biggest burden on the server; those are the first to consider rewriting/indexing/removing/consolidating/etc.  Hence, I see this as a possible alternative.

Some 3rd party software tends to do a lot of SHOWs and other junk.  But removing such would require a redesign of their software.

Title: Best Free MySQL Profiler in 2017


答: Can it be just because "<input type='text'>" is not a valid HTML? You have not closed your tag. However, I am not sure whether jQuery is unable to close it for you.

Title: Live jQuery events not firing for dynamic element


问:
import all the required react-native components in a single and file and then export it
Instead of writing the following code in every reactnative's ".js" file, is it possible to write it in a single file and the export it so that i can use it in other js files just by importing this one file (containing all the component that I need to use)

```<code>import React from 'react';

import {
    StyleSheet,
    Text,
    Image,
    View
} from 'react-native';
</code>```

Now instead of writing the above code in page1.js, page2.js, page3.js, how do i write it in a single file called "comp.js" and export it from there so that i only have to import comp.js in the page1.js, page2.js and page3.js file

答:
It is possible but I recommend using index.js for that folder instead of that comp.js

In a folder you can create index.js and import all related js in that folder so you can import very easy

For example: I have my folder called Components

Create index.js in the folder Components

Import and export files

```<code>import comp1 from './comp1'
import comp2 from './comp2'
import comp3 from './comp3'

export { comp1, comp2, comp3 }
</code>```

Import folder instead of each file and select only needed files import { comp1, comp2 } from '../Components'

Body:
Instead of writing the following code in every reactnative's ".js" file, is it possible to write it in a single file and the export it so that i can use it in other js files just by importing this one file (containing all the component that I need to use)

import React from 'react';

import {
    StyleSheet,
    Text,
    Image,
    View
} from 'react-native';

Now instead of writing the above code in page1.js, page2.js, page3.js, how do i write it in a single file called "comp.js" and export it from there so that i only have to import comp.js in the page1.js, page2.js and page3.js file

Body:
It is possible but I recommend using index.js for that folder instead of that comp.js

In a folder you can create index.js and import all related js in that folder so you can import very easy

For example: I have my folder called Components

Create index.js in the folder Components

Import and export files

import comp1 from './comp1'
import comp2 from './comp2'
import comp3 from './comp3'

export { comp1, comp2, comp3 }

Import folder instead of each file and select only needed files import { comp1, comp2 } from '../Components'


问:
My Custom EditText not working correctly
I am working on a EditText which can take Bold, Italics and Underline characters as mentioned in this question.

I have extended EditText and overrided the onTextChanged() method.
My code works fine for the first occcurence of any bold, italics, underlined input but after my second occurence the first occurence gets changed to normal text.

Here is a gif depecting the problem

Here is the MainActivity.java

```<code>    package com.example.syed.andtexteditor;

import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    int helperCounterB = 0;
    int helperCounterI = 0;
    int helperCounterU = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button boldButton = (Button) findViewById(R.id.bold_button);
        boldButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Button boldButton = (Button) findViewById(R.id.bold_button);
                helperCounterB++;

                if (helperCounterB % 2 != 0)
                //The EditText is in Bold mode when the Bold button is pressed odd-th time
                    boldButton.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.black));
                else

                    boldButton.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.grey));

                TextArea t = (TextArea) findViewById(R.id.textInput);
                t.applyTypeface(helperCounterI, helperCounterB, helperCounterU);

            }

        });

        Button italicsButton = (Button) findViewById(R.id.italics_button);
        italicsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Button italicsButton = (Button) findViewById(R.id.italics_button);
                helperCounterI++;
                if (helperCounterI % 2 != 0) //The EditText is in Italics mode when the Italics button is pressed odd-th time
                    italicsButton.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.black));
                else
                    italicsButton.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.grey));

                TextArea t = (TextArea) findViewById(R.id.textInput);
                t.applyTypeface(helperCounterI, helperCounterB, helperCounterU);

            }

        });

        Button underlineButton = (Button) findViewById(R.id.underline_button);
        underlineButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Button underlineButton = (Button) findViewById(R.id.underline_button);
                helperCounterU++;
                if (helperCounterU % 2 != 0)//The EditText is in Underline mode when the Underline button is pressed odd-th time

                    underlineButton.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.black));
                else

                    underlineButton.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.grey));

                TextArea t = (TextArea) findViewById(R.id.textInput);
                t.applyTypeface(helperCounterI, helperCounterB, helperCounterU);

            }
        });

    }
}
</code>```

And here is the extended EditText class i.e TextArea.java

```<code>package com.example.syed.andtexteditor;

import android.content.Context;
import android.graphics.Typeface;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.CharacterStyle;
import android.text.style.StyleSpan;
import android.text.style.UnderlineSpan;
import android.util.AttributeSet;
import android.util.Log;

/**
 * Created by Syed on 29-05-2017.
 */

public class TextArea extends AppCompatEditText {
    Context c;
    public static final int TYPEFACE_NORMAL = 0;
    public static final int TYPEFACE_BOLD = 1;
    public static final int TYPEFACE_ITALICS = 2;
    public static final int TYPEFACE_BOLD_ITALICS = 3;
    public static final int TYPEFACE_UNDERLINE = 4;
    public static final int TYPEFACE_BOLD_UNDERLINE = 5;
    public static final int TYPEFACE_ITALICS_UNDERLINE = 6;
    public static final int TYPEFACE_BOLD_ITALICS_UNDERLINE = 7;

    private int currentTypeface;
    private int lastCursorPosition;

    private StyleSpan normalspan = new StyleSpan(Typeface.NORMAL);
    private StyleSpan boldspan = new StyleSpan(Typeface.BOLD);
    private StyleSpan italicspan = new StyleSpan(Typeface.ITALIC);
    private StyleSpan boldItalicspan = new StyleSpan(Typeface.BOLD_ITALIC);
    private UnderlineSpan underlinespan = new UnderlineSpan();

    public TextArea(Context context) {
        super(context);
        c = context;
        lastCursorPosition = this.getSelectionStart();

    }

    public TextArea(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void changeTypeface(int tfId) {
        currentTypeface = tfId;
        lastCursorPosition = this.getSelectionStart();
    }

    public void applyTypeface(int helperCounterI, int helperCounterB, int helperCounterU) {
        int min = 0;
        int max = this.getText().length();
        if (this.isFocused()) {
            final int selStart = this.getSelectionStart();
            final int selEnd = this.getSelectionEnd();

            min = Math.max(0, Math.min(selStart, selEnd));
            max = Math.max(0, Math.max(selStart, selEnd));
        }
        Spannable s = this.getText();
        Editable selectedText = new SpannableStringBuilder(s, min, max);

        SpannableStringBuilder s1 = new SpannableStringBuilder(s, 0, min);

        String selectedTextString = selectedText.toString();
        SpannableStringBuilder selectedSpannedString = new SpannableStringBuilder(selectedTextString);
        Log.d(VIEW_LOG_TAG, "Helper Counter I: " + helperCounterI + " Helper Counter B: " + helperCounterB);
        if (helperCounterI % 2 != 0 && helperCounterB % 2 != 0 && helperCounterU % 2 == 0) {
            if (this.getSelectionEnd() == this.getSelectionStart()) {
                this.changeTypeface(TextArea.TYPEFACE_BOLD_ITALICS);

            }
            //ignore this part as there are no issues with this
            else {

                StyleSpan styleSpan = new StyleSpan(Typeface.BOLD_ITALIC);
                selectedSpannedString.setSpan(styleSpan, min, max, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                SpannableStringBuilder s3 = new SpannableStringBuilder(s, max, s.length());
                CharSequence finalSpannable = TextUtils.concat(s1, selectedSpannedString, s3);
                this.setText(finalSpannable);
            }

        } else if (helperCounterI % 2 != 0 && helperCounterB % 2 == 0 && helperCounterU % 2 == 0) {
            if (this.getSelectionEnd() == this.getSelectionStart()) {
                this.changeTypeface(TextArea.TYPEFACE_ITALICS);

            }
            //ignore this part as there are no issues with this
            else {
                StyleSpan styleSpan = new StyleSpan(Typeface.ITALIC);
                selectedSpannedString.setSpan(styleSpan, min, max, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                SpannableStringBuilder s3 = new SpannableStringBuilder(s, max, s.length());
                CharSequence finalSpannable = TextUtils.concat(s1, selectedSpannedString, s3);
                this.setText(finalSpannable);
            }
        } else if (helperCounterI % 2 == 0 && helperCounterB % 2 != 0 && helperCounterU % 2 == 0) {
            if (this.getSelectionEnd() == this.getSelectionStart()) {

                this.changeTypeface(TextArea.TYPEFACE_BOLD);

            }
            //ignore this part as there are no issues with this
            else {
                StyleSpan styleSpan = new StyleSpan(Typeface.BOLD);
                selectedSpannedString.setSpan(styleSpan, min, max, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                SpannableStringBuilder s3 = new SpannableStringBuilder(s, max, s.length());
                CharSequence finalSpannable = TextUtils.concat(s1, selectedSpannedString, s3);
                this.setText(finalSpannable);
            }
        } else if (helperCounterB % 2 == 0 && helperCounterI % 2 == 0 && helperCounterU % 2 == 0) {

            this.changeTypeface(TextArea.TYPEFACE_NORMAL);

        } else if (helperCounterU % 2 != 0 && helperCounterI % 2 == 0 && helperCounterB % 2 == 0) {
            if (this.getSelectionEnd() == this.getSelectionStart()) {
                this.changeTypeface(TYPEFACE_UNDERLINE);

            }
            //ignore this part as there are no issues with this
            else {
                selectedSpannedString.setSpan(new UnderlineSpan(), min, max, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                SpannableStringBuilder s3 = new SpannableStringBuilder(s, max, s.length());
                CharSequence finalSpannable = TextUtils.concat(s1, selectedSpannedString, s3);
                this.setText(finalSpannable);
            }
        } else if (helperCounterU % 2 != 0 && helperCounterI % 2 == 0 && helperCounterB % 2 != 0) {
            if (this.getSelectionEnd() == this.getSelectionStart()) {
                this.changeTypeface(TYPEFACE_BOLD_UNDERLINE);

            }
            //ignore this part as there are no issues with this
            else {
                selectedSpannedString.setSpan(new StyleSpan(Typeface.BOLD), min, max, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                selectedSpannedString.setSpan(new UnderlineSpan(), min, max, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                SpannableStringBuilder s3 = new SpannableStringBuilder(s, max, s.length());
                CharSequence finalSpannable = TextUtils.concat(s1, selectedSpannedString, s3);
                this.setText(finalSpannable);
            }
        } else if (helperCounterU % 2 != 0 && helperCounterI % 2 != 0 && helperCounterB % 2 == 0) {
            if (this.getSelectionEnd() == this.getSelectionStart()) {

                this.changeTypeface(TYPEFACE_ITALICS_UNDERLINE);

            } else
            //ignore this part as there are no issues with this
            {
                selectedSpannedString.setSpan(new StyleSpan(Typeface.ITALIC), min, max, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                selectedSpannedString.setSpan(new UnderlineSpan(), min, max, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                SpannableStringBuilder s3 = new SpannableStringBuilder(s, max, s.length());
                CharSequence finalSpannable = TextUtils.concat(s1, selectedSpannedString, s3);
                this.setText(finalSpannable);
            }
        } else if (helperCounterU % 2 != 0 && helperCounterI % 2 != 0 && helperCounterB % 2 != 0) {
            if (this.getSelectionEnd() == this.getSelectionStart()) {
                this.changeTypeface(TYPEFACE_BOLD_ITALICS_UNDERLINE);

            }
            //ignore this part as there are no issues with this
            else {
                selectedSpannedString.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), min, max, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                selectedSpannedString.setSpan(new UnderlineSpan(), min, max, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                SpannableStringBuilder s3 = new SpannableStringBuilder(s, max, s.length());
                CharSequence finalSpannable = TextUtils.concat(s1, selectedSpannedString, s3);
                this.setText(finalSpannable);
            }
        }
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {

        Log.d(VIEW_LOG_TAG, "Start: " + start + " Length before: " + lengthBefore + " Length After: " + lengthAfter + " TextLength: " + text.length());

        CharacterStyle ss = null;
        UnderlineSpan ss1 = null;
        int endLength = text.toString().length();

        switch (currentTypeface) {
            case TYPEFACE_NORMAL:
                ss = normalspan;
                break;
            case TYPEFACE_BOLD:
                ss = boldspan;
                break;
            case TYPEFACE_ITALICS:
                ss = italicspan;
                break;
            case TYPEFACE_BOLD_ITALICS:
                ss = boldItalicspan;
                break;
            case TYPEFACE_UNDERLINE:
                ss = underlinespan;
                break;
            case TYPEFACE_BOLD_UNDERLINE:
                ss = boldspan;
                ss1 = underlinespan;
                break;
            case TYPEFACE_ITALICS_UNDERLINE:
                ss = italicspan;
                ss1 = underlinespan;
                break;
            case TYPEFACE_BOLD_ITALICS_UNDERLINE:
                ss = boldItalicspan;
                ss1 = underlinespan;
                break;
        }
        if (lastCursorPosition > endLength)
            return;
        Log.d(TextArea.class.getSimpleName(), new Integer(lastCursorPosition).toString() + new Integer(endLength).toString());
        this.getText().setSpan(ss, lastCursorPosition, endLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        this.getText().setSpan(ss1, lastCursorPosition, endLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    }
}
</code>```

答:
Your problem is that you are re-using instances of the spans. Per the documentation of setSpan (emphasis mine):

Attach the specified markup object to the range start…end of the text, or move the object to that range if it was already attached elsewhere.

So you simply need to create new Spans each time you want to attribute text.

Hope that helps!

Body:
I am working on a EditText which can take Bold, Italics and Underline characters as mentioned in this question.

I have extended EditText and overrided the onTextChanged() method.
My code works fine for the first occcurence of any bold, italics, underlined input but after my second occurence the first occurence gets changed to normal text.

Here is a gif depecting the problem

Here is the MainActivity.java

    package com.example.syed.andtexteditor;

import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    int helperCounterB = 0;
    int helperCounterI = 0;
    int helperCounterU = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button boldButton = (Button) findViewById(R.id.bold_button);
        boldButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Button boldButton = (Button) findViewById(R.id.bold_button);
                helperCounterB++;

                if (helperCounterB % 2 != 0)
                //The EditText is in Bold mode when the Bold button is pressed odd-th time
                    boldButton.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.black));
                else

                    boldButton.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.grey));

                TextArea t = (TextArea) findViewById(R.id.textInput);
                t.applyTypeface(helperCounterI, helperCounterB, helperCounterU);

            }

        });

        Button italicsButton = (Button) findViewById(R.id.italics_button);
        italicsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Button italicsButton = (Button) findViewById(R.id.italics_button);
                helperCounterI++;
                if (helperCounterI % 2 != 0) //The EditText is in Italics mode when the Italics button is pressed odd-th time
                    italicsButton.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.black));
                else
                    italicsButton.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.grey));

                TextArea t = (TextArea) findViewById(R.id.textInput);
                t.applyTypeface(helperCounterI, helperCounterB, helperCounterU);

            }

        });

        Button underlineButton = (Button) findViewById(R.id.underline_button);
        underlineButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Button underlineButton = (Button) findViewById(R.id.underline_button);
                helperCounterU++;
                if (helperCounterU % 2 != 0)//The EditText is in Underline mode when the Underline button is pressed odd-th time

                    underlineButton.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.black));
                else

                    underlineButton.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.grey));

                TextArea t = (TextArea) findViewById(R.id.textInput);
                t.applyTypeface(helperCounterI, helperCounterB, helperCounterU);

            }
        });

    }
}

And here is the extended EditText class i.e TextArea.java

package com.example.syed.andtexteditor;

import android.content.Context;
import android.graphics.Typeface;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.CharacterStyle;
import android.text.style.StyleSpan;
import android.text.style.UnderlineSpan;
import android.util.AttributeSet;
import android.util.Log;

/**
 * Created by Syed on 29-05-2017.
 */

public class TextArea extends AppCompatEditText {
    Context c;
    public static final int TYPEFACE_NORMAL = 0;
    public static final int TYPEFACE_BOLD = 1;
    public static final int TYPEFACE_ITALICS = 2;
    public static final int TYPEFACE_BOLD_ITALICS = 3;
    public static final int TYPEFACE_UNDERLINE = 4;
    public static final int TYPEFACE_BOLD_UNDERLINE = 5;
    public static final int TYPEFACE_ITALICS_UNDERLINE = 6;
    public static final int TYPEFACE_BOLD_ITALICS_UNDERLINE = 7;

    private int currentTypeface;
    private int lastCursorPosition;

    private StyleSpan normalspan = new StyleSpan(Typeface.NORMAL);
    private StyleSpan boldspan = new StyleSpan(Typeface.BOLD);
    private StyleSpan italicspan = new StyleSpan(Typeface.ITALIC);
    private StyleSpan boldItalicspan = new StyleSpan(Typeface.BOLD_ITALIC);
    private UnderlineSpan underlinespan = new UnderlineSpan();

    public TextArea(Context context) {
        super(context);
        c = context;
        lastCursorPosition = this.getSelectionStart();

    }

    public TextArea(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void changeTypeface(int tfId) {
        currentTypeface = tfId;
        lastCursorPosition = this.getSelectionStart();
    }

    public void applyTypeface(int helperCounterI, int helperCounterB, int helperCounterU) {
        int min = 0;
        int max = this.getText().length();
        if (this.isFocused()) {
            final int selStart = this.getSelectionStart();
            final int selEnd = this.getSelectionEnd();

            min = Math.max(0, Math.min(selStart, selEnd));
            max = Math.max(0, Math.max(selStart, selEnd));
        }
        Spannable s = this.getText();
        Editable selectedText = new SpannableStringBuilder(s, min, max);

        SpannableStringBuilder s1 = new SpannableStringBuilder(s, 0, min);

        String selectedTextString = selectedText.toString();
        SpannableStringBuilder selectedSpannedString = new SpannableStringBuilder(selectedTextString);
        Log.d(VIEW_LOG_TAG, "Helper Counter I: " + helperCounterI + " Helper Counter B: " + helperCounterB);
        if (helperCounterI % 2 != 0 && helperCounterB % 2 != 0 && helperCounterU % 2 == 0) {
            if (this.getSelectionEnd() == this.getSelectionStart()) {
                this.changeTypeface(TextArea.TYPEFACE_BOLD_ITALICS);

            }
            //ignore this part as there are no issues with this
            else {

                StyleSpan styleSpan = new StyleSpan(Typeface.BOLD_ITALIC);
                selectedSpannedString.setSpan(styleSpan, min, max, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                SpannableStringBuilder s3 = new SpannableStringBuilder(s, max, s.length());
                CharSequence finalSpannable = TextUtils.concat(s1, selectedSpannedString, s3);
                this.setText(finalSpannable);
            }

        } else if (helperCounterI % 2 != 0 && helperCounterB % 2 == 0 && helperCounterU % 2 == 0) {
            if (this.getSelectionEnd() == this.getSelectionStart()) {
                this.changeTypeface(TextArea.TYPEFACE_ITALICS);

            }
            //ignore this part as there are no issues with this
            else {
                StyleSpan styleSpan = new StyleSpan(Typeface.ITALIC);
                selectedSpannedString.setSpan(styleSpan, min, max, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                SpannableStringBuilder s3 = new SpannableStringBuilder(s, max, s.length());
                CharSequence finalSpannable = TextUtils.concat(s1, selectedSpannedString, s3);
                this.setText(finalSpannable);
            }
        } else if (helperCounterI % 2 == 0 && helperCounterB % 2 != 0 && helperCounterU % 2 == 0) {
            if (this.getSelectionEnd() == this.getSelectionStart()) {

                this.changeTypeface(TextArea.TYPEFACE_BOLD);

            }
            //ignore this part as there are no issues with this
            else {
                StyleSpan styleSpan = new StyleSpan(Typeface.BOLD);
                selectedSpannedString.setSpan(styleSpan, min, max, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                SpannableStringBuilder s3 = new SpannableStringBuilder(s, max, s.length());
                CharSequence finalSpannable = TextUtils.concat(s1, selectedSpannedString, s3);
                this.setText(finalSpannable);
            }
        } else if (helperCounterB % 2 == 0 && helperCounterI % 2 == 0 && helperCounterU % 2 == 0) {

            this.changeTypeface(TextArea.TYPEFACE_NORMAL);

        } else if (helperCounterU % 2 != 0 && helperCounterI % 2 == 0 && helperCounterB % 2 == 0) {
            if (this.getSelectionEnd() == this.getSelectionStart()) {
                this.changeTypeface(TYPEFACE_UNDERLINE);

            }
            //ignore this part as there are no issues with this
            else {
                selectedSpannedString.setSpan(new UnderlineSpan(), min, max, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                SpannableStringBuilder s3 = new SpannableStringBuilder(s, max, s.length());
                CharSequence finalSpannable = TextUtils.concat(s1, selectedSpannedString, s3);
                this.setText(finalSpannable);
            }
        } else if (helperCounterU % 2 != 0 && helperCounterI % 2 == 0 && helperCounterB % 2 != 0) {
            if (this.getSelectionEnd() == this.getSelectionStart()) {
                this.changeTypeface(TYPEFACE_BOLD_UNDERLINE);

            }
            //ignore this part as there are no issues with this
            else {
                selectedSpannedString.setSpan(new StyleSpan(Typeface.BOLD), min, max, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                selectedSpannedString.setSpan(new UnderlineSpan(), min, max, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                SpannableStringBuilder s3 = new SpannableStringBuilder(s, max, s.length());
                CharSequence finalSpannable = TextUtils.concat(s1, selectedSpannedString, s3);
                this.setText(finalSpannable);
            }
        } else if (helperCounterU % 2 != 0 && helperCounterI % 2 != 0 && helperCounterB % 2 == 0) {
            if (this.getSelectionEnd() == this.getSelectionStart()) {

                this.changeTypeface(TYPEFACE_ITALICS_UNDERLINE);

            } else
            //ignore this part as there are no issues with this
            {
                selectedSpannedString.setSpan(new StyleSpan(Typeface.ITALIC), min, max, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                selectedSpannedString.setSpan(new UnderlineSpan(), min, max, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                SpannableStringBuilder s3 = new SpannableStringBuilder(s, max, s.length());
                CharSequence finalSpannable = TextUtils.concat(s1, selectedSpannedString, s3);
                this.setText(finalSpannable);
            }
        } else if (helperCounterU % 2 != 0 && helperCounterI % 2 != 0 && helperCounterB % 2 != 0) {
            if (this.getSelectionEnd() == this.getSelectionStart()) {
                this.changeTypeface(TYPEFACE_BOLD_ITALICS_UNDERLINE);

            }
            //ignore this part as there are no issues with this
            else {
                selectedSpannedString.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), min, max, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                selectedSpannedString.setSpan(new UnderlineSpan(), min, max, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                SpannableStringBuilder s3 = new SpannableStringBuilder(s, max, s.length());
                CharSequence finalSpannable = TextUtils.concat(s1, selectedSpannedString, s3);
                this.setText(finalSpannable);
            }
        }
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {

        Log.d(VIEW_LOG_TAG, "Start: " + start + " Length before: " + lengthBefore + " Length After: " + lengthAfter + " TextLength: " + text.length());

        CharacterStyle ss = null;
        UnderlineSpan ss1 = null;
        int endLength = text.toString().length();

        switch (currentTypeface) {
            case TYPEFACE_NORMAL:
                ss = normalspan;
                break;
            case TYPEFACE_BOLD:
                ss = boldspan;
                break;
            case TYPEFACE_ITALICS:
                ss = italicspan;
                break;
            case TYPEFACE_BOLD_ITALICS:
                ss = boldItalicspan;
                break;
            case TYPEFACE_UNDERLINE:
                ss = underlinespan;
                break;
            case TYPEFACE_BOLD_UNDERLINE:
                ss = boldspan;
                ss1 = underlinespan;
                break;
            case TYPEFACE_ITALICS_UNDERLINE:
                ss = italicspan;
                ss1 = underlinespan;
                break;
            case TYPEFACE_BOLD_ITALICS_UNDERLINE:
                ss = boldItalicspan;
                ss1 = underlinespan;
                break;
        }
        if (lastCursorPosition > endLength)
            return;
        Log.d(TextArea.class.getSimpleName(), new Integer(lastCursorPosition).toString() + new Integer(endLength).toString());
        this.getText().setSpan(ss, lastCursorPosition, endLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        this.getText().setSpan(ss1, lastCursorPosition, endLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    }
}


问:
How to combine two boost::filesystem::path's?
I need to combine an absolute path A with path B, given that B may be relative as well as absolute, preferably using boost::filesystem.

In other words, I want to have:

/usr/home/ + abc = /usr/home/abc

/usr/home/ + ../abc = /usr/home/../abc (or, even better /usr/abc - this is not my question)

/usr/home/ + /abc = /abc

The first two are easy with the / operator but I can't get the third one to work.

I tried:

```<code>std::cout << boost::filesystem::path("/usr/home/") / "/abc";
</code>```

Prints /usr/home//abc.

```<code>std::cout << boost::filesystem::path("/usr/home/") + "/abc";
</code>```

Still prints /usr/home//abc.

Of course I can "see" when path B is absolute by looking at it and just use that, but I don't want to hardcode the check for the leading / because on Windows it can be different (e.g. C:\\ or \\).

答:
boost::filesystem::path has a member function is_absolute(). So you can choose your operation (either concatenation or replacement) based on that.

```<code>path a = "/usr/home/";
path b = "/abc";
path c;

if (b.is_absolute())
    c = b;
else
    c = a / b;
</code>```

There's also is_relative(), which does the opposite.

Body:
I need to combine an absolute path A with path B, given that B may be relative as well as absolute, preferably using boost::filesystem.

In other words, I want to have:

/usr/home/ + abc = /usr/home/abc

/usr/home/ + ../abc = /usr/home/../abc (or, even better /usr/abc - this is not my question)

/usr/home/ + /abc = /abc

The first two are easy with the / operator but I can't get the third one to work.

I tried:

std::cout << boost::filesystem::path("/usr/home/") / "/abc";

Prints /usr/home//abc.

std::cout << boost::filesystem::path("/usr/home/") + "/abc";

Still prints /usr/home//abc.

Of course I can "see" when path B is absolute by looking at it and just use that, but I don't want to hardcode the check for the leading / because on Windows it can be different (e.g. C:\\ or \\).

Body:
boost::filesystem::path has a member function is_absolute(). So you can choose your operation (either concatenation or replacement) based on that.

path a = "/usr/home/";
path b = "/abc";
path c;

if (b.is_absolute())
    c = b;
else
    c = a / b;

There's also is_relative(), which does the opposite.


问:
Python using sum() in a user made list
So, the part of this project I cannot get to work is the sum() function.
It works during:

```<code>    a = [1, 2, 3, 4, 5]
    b = sum(a)
    print b
</code>```

But in my program, I have a user created list and the sum() keeps getting an error. len() works, but I also need the sum to obtain an average.

```<code>     namelist = []
     agelist = []

     while True:
        name = raw_input("Enter a name or type Exit to end data entry: ")
        namelist.append(name)

        if name == "Exit":      #creates an exit point from data entry
            break

        age = raw_input("How old is " + name + "? ")
        agelist.append(age)

    lenage = len(agelist)
    sumage = sum(agelist)   #here is the problem -<<
    avgage = sumage / lenage

    print avgage
</code>```

How can I get the sumage to work?
Is it not working because I did not define how long the list is?

答:
The reason for the error is that agelist is a list of strings (inputs from the user) and before you can "add" those inputs you need to convert them either to an integer number or (probably) to a floating number (depending on what kind of average you want: an integer or floating point in Python 2):

```<code>sumage = sum(map(int, agelist)) # OR, replace int with float
</code>```

Title: Python using sum() in a user made list

Body:
So, the part of this project I cannot get to work is the sum() function.
It works during:

    a = [1, 2, 3, 4, 5]
    b = sum(a)
    print b

But in my program, I have a user created list and the sum() keeps getting an error. len() works, but I also need the sum to obtain an average.

     namelist = []
     agelist = []

     while True:
        name = raw_input("Enter a name or type Exit to end data entry: ")
        namelist.append(name)

        if name == "Exit":      #creates an exit point from data entry
            break

        age = raw_input("How old is " + name + "? ")
        agelist.append(age)

    lenage = len(agelist)
    sumage = sum(agelist)   #here is the problem -<<
    avgage = sumage / lenage

    print avgage

How can I get the sumage to work?
Is it not working because I did not define how long the list is?

Body:
The reason for the error is that agelist is a list of strings (inputs from the user) and before you can "add" those inputs you need to convert them either to an integer number or (probably) to a floating number (depending on what kind of average you want: an integer or floating point in Python 2):

sumage = sum(map(int, agelist)) # OR, replace int with float