问:
How can I change image tintColor in iOS and WatchKit
I have an UIImageView called "theImageView", with UIImage in a single color (transparent background) just like the left black heart below. How can I change the tint color of this image programmatically in iOS 7 or above, as per the tint method used in the iOS 7+ Navigation Bar icons?

Can this method also work in WatchKit for an Apple Watch app?

答:
This is my UIImage extension and you can directly use changeTintColor function for an image.

```<code>extension UIImage {

    func changeTintColor(color: UIColor) -> UIImage {
        var newImage = self.withRenderingMode(.alwaysTemplate)
        UIGraphicsBeginImageContextWithOptions(self.size, false, newImage.scale)
        color.set()
        newImage.draw(in: CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height))
        newImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return newImage
    }

    func changeColor(color: UIColor) -> UIImage {
        let backgroundSize = self.size
        UIGraphicsBeginImageContext(backgroundSize)
        guard let context = UIGraphicsGetCurrentContext() else {
            return self
        }
        var backgroundRect = CGRect()
        backgroundRect.size = backgroundSize
        backgroundRect.origin.x = 0
        backgroundRect.origin.y = 0

        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        var alpha: CGFloat = 0
        color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
        context.setFillColor(red: red, green: green, blue: blue, alpha: alpha)
        context.translateBy(x: 0, y: backgroundSize.height)
        context.scaleBy(x: 1.0, y: -1.0)
        context.clip(to: CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height),
                 mask: self.cgImage!)
        context.fill(backgroundRect)

        var imageRect = CGRect()
        imageRect.size = self.size
        imageRect.origin.x = (backgroundSize.width - self.size.width) / 2
        imageRect.origin.y = (backgroundSize.height - self.size.height) / 2

        context.setBlendMode(.multiply)
        context.draw(self.cgImage!, in: imageRect)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }

}
</code>```

Example usage like this

```<code>let image = UIImage(named: "sample_image")
imageView.image = image.changeTintColor(color: UIColor.red)
</code>```

And you can use change changeColor function to change the image color

Body:
This is my UIImage extension and you can directly use changeTintColor function for an image.

extension UIImage {

    func changeTintColor(color: UIColor) -> UIImage {
        var newImage = self.withRenderingMode(.alwaysTemplate)
        UIGraphicsBeginImageContextWithOptions(self.size, false, newImage.scale)
        color.set()
        newImage.draw(in: CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height))
        newImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return newImage
    }

    func changeColor(color: UIColor) -> UIImage {
        let backgroundSize = self.size
        UIGraphicsBeginImageContext(backgroundSize)
        guard let context = UIGraphicsGetCurrentContext() else {
            return self
        }
        var backgroundRect = CGRect()
        backgroundRect.size = backgroundSize
        backgroundRect.origin.x = 0
        backgroundRect.origin.y = 0

        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        var alpha: CGFloat = 0
        color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
        context.setFillColor(red: red, green: green, blue: blue, alpha: alpha)
        context.translateBy(x: 0, y: backgroundSize.height)
        context.scaleBy(x: 1.0, y: -1.0)
        context.clip(to: CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height),
                 mask: self.cgImage!)
        context.fill(backgroundRect)

        var imageRect = CGRect()
        imageRect.size = self.size
        imageRect.origin.x = (backgroundSize.width - self.size.width) / 2
        imageRect.origin.y = (backgroundSize.height - self.size.height) / 2

        context.setBlendMode(.multiply)
        context.draw(self.cgImage!, in: imageRect)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }

}

Example usage like this

let image = UIImage(named: "sample_image")
imageView.image = image.changeTintColor(color: UIColor.red)

And you can use change changeColor function to change the image color


来源: stackexchange

问:
how to input data array looping to database
i have a code like this, i dont know what wrong with my code

```<code>$peringkat=0;
//pencarian ranking terbesar ke terkecil berdasarkan value
$ranking = array("$ATTT[0]" => "$HA[0]", "$ATTT[1]" => "$HA[1]");
arsort($ranking);
foreach ($ranking as $alternatif => $nilaialternatif) {
$peringkat++;
echo "
<th class='akhir'><input class='rankingakhir' type='text' name='alternatif'
value='$alternatif' size='12' readonly></th>
<td class='akhir'><input class='nilaiakhir' type='text'
name='nilaialternatif' value=".number_format($nilaialternatif, 3, '.', ',')." size='12' readonly></td>
<td class='akhir'><input class='rankakhir' type='text'
name='rankingalternatif' value='$peringkat' size='12' readonly></td></tr>";
}
echo '</table><div class="akhir"><input class="akhir" type="submit"
value="Simpan Ranking ke Database"></div></div></div>
</code>```

i run var dump but just record data from alternatif 2

```<code>array(3) { ["alternatif"]=> string(12) "Alternatif 2" ["nilaialternatif"]=> string(5) "0.223" ["rankingalternatif"]=> string(1) "2" }
</code>```

table in live design

my database code

```<code>$Host = "localhost";         //Memilih host, Localhost berarti komputer itu sendiri
$User = "root";             //Memilih user/pengguna
$Password = "";             //Password, Biasanya Kosong
$db       = "spkjazuly";         //Memilih Database
$konek=mysql_connect($Host,$User,$Password)or die (mysql_error());
mysql_select_db ($db,$konek) or die (mysql_error("TIdak Terhubung Ke Server
Mysql")); //Menghubungkan ke Mysql dan memilih Database
mysql_query("replace INTO ranking VALUE(DEFAULT,'$_GET[B11]','$_GET[alternatif]','$_GET[nilaialternatif]','$_GET[rankingalternatif]')") //Perintah Mysql untuk mengisi tabel Tamu
or die(mysql_error("Tidak Berhasil Menyimpan !"));  //Or Die (mysql_error()) Pesan Error
echo "<h1>Berhasil Menyimpan Data</h1>";
</code>```

sory for my english, i try my best.

答:
to connect to your DB try this and dont uppercase variables</p>

```<code>// Connection to DB
    $konek = new PDO('mysql:host=localhost;$db', $User, $Password);
    if ($db){
        echo('Connected to: "'.$db.'"');
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i have a code like this, i dont know what wrong with my code

$peringkat=0;
//pencarian ranking terbesar ke terkecil berdasarkan value
$ranking = array("$ATTT[0]" => "$HA[0]", "$ATTT[1]" => "$HA[1]");
arsort($ranking);
foreach ($ranking as $alternatif => $nilaialternatif) {
$peringkat++;
echo "
<input class='rankingakhir' type='text' name='alternatif'
value='$alternatif' size='12' readonly>
<input class='nilaiakhir' type='text'
name='nilaialternatif' value=".number_format($nilaialternatif, 3, '.', ',')." size='12' readonly>
<input class='rankakhir' type='text'
name='rankingalternatif' value='$peringkat' size='12' readonly>
";
}
echo '

<input class="akhir" type="submit"
value="Simpan Ranking ke Database">

i run var dump but just record data from alternatif 2

array(3) { ["alternatif"]=> string(12) "Alternatif 2" ["nilaialternatif"]=> string(5) "0.223" ["rankingalternatif"]=> string(1) "2" }

table in live design

my database code

$Host = "localhost";         //Memilih host, Localhost berarti komputer itu sendiri
$User = "root";             //Memilih user/pengguna
$Password = "";             //Password, Biasanya Kosong
$db       = "spkjazuly";         //Memilih Database
$konek=mysql_connect($Host,$User,$Password)or die (mysql_error());
mysql_select_db ($db,$konek) or die (mysql_error("TIdak Terhubung Ke Server
Mysql")); //Menghubungkan ke Mysql dan memilih Database
mysql_query("replace INTO ranking VALUE(DEFAULT,'$_GET[B11]','$_GET[alternatif]','$_GET[nilaialternatif]','$_GET[rankingalternatif]')") //Perintah Mysql untuk mengisi tabel Tamu
or die(mysql_error("Tidak Berhasil Menyimpan !"));  //Or Die (mysql_error()) Pesan Error
echo "
Berhasil Menyimpan Data
";

sory for my english, i try my best.

Body:
to connect to your DB try this and dont uppercase variables

// Connection to DB
    $konek = new PDO('mysql:host=localhost;$db', $User, $Password);
    if ($db){
        echo('Connected to: "'.$db.'"');
    }


问:
How to dynamically change the field order of a class in FileHelpers
On a daily basis - I need to process 5 files in a c# application using the FileHelpers library. Each file comes from a different client.

The files all represent the same entity - so I have an "Individual" class in my program that contains all the fields and I need to load the data from the files into this object. (the files are delimited files)

The problem is that each file arrives with it's columns in it's own order.
So:
Client 1 sends: Name, Surname, SSN, Age
Client 2 sends: Name, Age, Surname, SSN
Client 3 sends: Name,  SSN ,Surname (age is optional - so this client doesn't send it)

I'd really like to handle this using a single class and not create one class for each client - since my client base will hopefully grow :-)

Does anyone have any clever ideas for handling this situation with FileHelpers?

Thanks

答: The solutions could be to insert a header row with field name for each csv file and manage it in your class</p>


问:
SSH to debian server instantly logs out
I'm trying to help someone with their Debian server.

They have Plesk. I made myself an user with Plesk and enabled SSH access.

I can log on ... but only for one second. I see the MOTD, I see a Debian disclaimer, then I'm logged out again. "Connection closed".

The only thing I could think to try is to change the shell settings, Plesk has a dropdown list of bash, csh, tcsh and so on next to the "allow ssh using:" option. But none of them works.

Any ideas gratefully received.

答: The way I fixed this problem is, unfortunately, to manually change the last parameter in /etc/passwd for users I want to give shell access. It is /bin/bash instead of /bin/false.

OwnerDisplayName: Ambrose

ContentLicense: CC BY-SA 2.5

Title: SSH to debian server instantly logs out


问:
Is there a more efficient way to replace NULL with NA in a list?
I quite often come across data that is structured something like this:

```<code>employees <- list(
    list(id = 1,
             dept = "IT",
             age = 29,
             sportsteam = "softball"),
    list(id = 2,
             dept = "IT",
             age = 30,
             sportsteam = NULL),
    list(id = 3,
             dept = "IT",
             age = 29,
             sportsteam = "hockey"),
    list(id = 4,
             dept = NULL,
             age = 29,
             sportsteam = "softball"))
</code>```

In many cases such lists could be tens of millions of items long, so memory concerns and efficiency are always a concern.

I would like to turn the list into a dataframe but if I run:

```<code>library(data.table)
employee.df <- rbindlist(employees)
</code>```

I get errors because of the NULL values. My normal strategy is to use a function like:

```<code>nullToNA <- function(x) {
    x[sapply(x, is.null)] <- NA
    return(x)
}
</code>```

and then:

```<code>employees <- lapply(employees, nullToNA)
employee.df <- rbindlist(employees)
</code>```

which returns

```<code>   id dept age sportsteam
1:  1   IT  29   softball
2:  2   IT  30         NA
3:  3   IT  29     hockey
4:  4   NA  29   softball
</code>```

However, the nullToNA function is very slow when applied to 10 million cases so it'd be good if there was a more efficient approach.

One point that seems to slow the process down it the is.null function can only be applied to one item at a time (unlike is.na which can scan a full list in one go).

Any advice on how to do this operation efficiently on a large dataset?

答:
All of these solutions (I think) are hiding the fact that the data table is still a lost of lists and not a list of vectors (I did not notice in my application either until it started throwing unexpected errors during :=).
Try this:

data.table(t(sapply(employees, function(x) unlist(lapply(x, function(x) ifelse(is.null(x),NA,x))))))

I believe it works fine, but I am not sure if it will suffer from slowness and can be optimized further.

Body:
I quite often come across data that is structured something like this:

employees <- list(
    list(id = 1,
             dept = "IT",
             age = 29,
             sportsteam = "softball"),
    list(id = 2,
             dept = "IT",
             age = 30,
             sportsteam = NULL),
    list(id = 3,
             dept = "IT",
             age = 29,
             sportsteam = "hockey"),
    list(id = 4,
             dept = NULL,
             age = 29,
             sportsteam = "softball"))

In many cases such lists could be tens of millions of items long, so memory concerns and efficiency are always a concern.

I would like to turn the list into a dataframe but if I run:

library(data.table)
employee.df <- rbindlist(employees)

I get errors because of the NULL values. My normal strategy is to use a function like:

nullToNA <- function(x) {
    x[sapply(x, is.null)] <- NA
    return(x)
}

and then:

employees <- lapply(employees, nullToNA)
employee.df <- rbindlist(employees)

which returns

   id dept age sportsteam
1:  1   IT  29   softball
2:  2   IT  30         NA
3:  3   IT  29     hockey
4:  4   NA  29   softball

However, the nullToNA function is very slow when applied to 10 million cases so it'd be good if there was a more efficient approach.

One point that seems to slow the process down it the is.null function can only be applied to one item at a time (unlike is.na which can scan a full list in one go).

Any advice on how to do this operation efficiently on a large dataset?


问:
Retrieving documents via SDK with certificate and only if signed
I'm using the C# SDK. In the even that a document is not delivered to the webhook address for whatever reason, or an end user accidentally deletes the document from the system on our end, I want to give them the ability to re-download it. I only want to download it if it was completed and I want to include the certificate.

As I understand it, if I get the envelope to check status and then immediately get the document, that is an API limit violation. So using two back to back calls is out. However, getting the status and making the user wait 15 minutes makes for a sub-optimal user experience.

I did find this link that says to append certificate=true to the querystring to include the certificate, however, I don't see an option for that in the C# SDK.

Any suggestions how I can accomplish these goals, hopefully in a single call, using the C# SDK? If it can't be done in the C# SDK is there a way to do it in a single call via a direct api call?

答:
Your understanding of DocuSign api limit violation is slightly wrong

As per the documentation

You may not exceed 1 GET request per unique envelope endpoint per 15 minutes.

So it is perfectly fine to make the following api calls in a 15 minute window as they are calling unique envelope endpoints.

Get status of an envelope

Download combined document for the envelope.

Unfortunately you will not be able to accomplish the above two actions in a single api call. There is no api at this point that supports it.

API Violation

```<code>[12:00:00] GET  /accounts/12345/envelopes/AAA
[12:10:00] GET  /accounts/12345/envelopes/AAA  (*api rule violation)
</code>```

Not an API Violation

```<code>[12:00:00] GET  /accounts/12345/envelopes/AAA
[12:10:00] GET  /accounts/12345/envelopes/AAA//documents/combined?certificate=true
</code>```

Body:
Your understanding of DocuSign api limit violation is slightly wrong

As per the documentation

You may not exceed 1 GET request per unique envelope endpoint per 15 minutes.

So it is perfectly fine to make the following api calls in a 15 minute window as they are calling unique envelope endpoints.

Get status of an envelope

Download combined document for the envelope.

Unfortunately you will not be able to accomplish the above two actions in a single api call. There is no api at this point that supports it.

API Violation

[12:00:00] GET  /accounts/12345/envelopes/AAA
[12:10:00] GET  /accounts/12345/envelopes/AAA  (*api rule violation)

Not an API Violation

[12:00:00] GET  /accounts/12345/envelopes/AAA
[12:10:00] GET  /accounts/12345/envelopes/AAA//documents/combined?certificate=true


问:
Java 8 Stream groupingby
I have List<Map<String, String>> each item in the list is a map e.g

```<code>companyName - IBM
firstName - James
country - USA
...
</code>```

I would like create a Map<String, List<String>> where it maps companyName to a list of of firstName
e.g

```<code>IBM -> James, Mark
ATT -> Henry, Robert..

private Map<String,List<String>> groupByCompanyName(List<Map<String, String>> list) {
    return list.stream().collect(Collectors.groupingBy(item->item.get("companyName")));
}
</code>```

but this will create Map<String, List<Map<String, String>> (mapping comanyName to a list of maps)

how to create a Map<String, List<String>>?

答:
The groupingBy method yields a map whose values are lists. If you want to process those lists in some way, supply a "downstream collector"
In you case, you don't want a List as the value, so you need to provide a downstream collector.

To manipulate the Map, you can use the static method mapping in Collectors file:

```<code>Collector<T, ?, R> mapping(Function<? super T, ? extends U> mapper,
                           Collector<? super U, A, R> downstream)
</code>```

It basically generates a collector by applying a function to the downstream results and passes the function to another collector.

```<code>Collectors.mapping(item->item.get("firstName"), Collectors.toList())
</code>```

This will return a downstream collector which will achieve what you want.

Title: Java 8 Stream groupingby

Body:
I have List<Map<String, String>> each item in the list is a map e.g

companyName - IBM
firstName - James
country - USA
...

I would like create a Map<String, List<String>> where it maps companyName to a list of of firstName
e.g

IBM -> James, Mark
ATT -> Henry, Robert..

private Map<String,List<String>> groupByCompanyName(List<Map<String, String>> list) {
    return list.stream().collect(Collectors.groupingBy(item->item.get("companyName")));
}

but this will create Map<String, List<Map<String, String>> (mapping comanyName to a list of maps)

how to create a Map<String, List<String>>?

Body:
The groupingBy method yields a map whose values are lists. If you want to process those lists in some way, supply a "downstream collector"
In you case, you don't want a List as the value, so you need to provide a downstream collector.

To manipulate the Map, you can use the static method mapping in Collectors file:

Collector<T, ?, R> mapping(Function<? super T, ? extends U> mapper,
                           Collector<? super U, A, R> downstream)

It basically generates a collector by applying a function to the downstream results and passes the function to another collector.

Collectors.mapping(item->item.get("firstName"), Collectors.toList())

This will return a downstream collector which will achieve what you want.


问:
Force the number of outputs from function call without setting output variables
For any function, I am able to dictate the variables to be returned by explicitly defining how many outputs I am expecting [out1,out2,...,outn] = ...

Edit: Being able to maximize potential # of outputs would also be useful

Example problem

The following code does exactly what is expected (yes, it is redundant with myArray(IND) = 1;)

```<code>[I,J] = ind2sub(size(myArray),IND)
myArray(I,J) = 1;
</code>```

When I try to pass the function arguments directly, I don't get the results I wannt

```<code>myArray(ind2sub(size(myArray),IND)) = 1;
</code>```

I effectively get myArray(I) = 1; when I wanted myArray(I,J) = 1;

Question

How can I dictate how many output variables are returned without explicitly defining my output arguments?

I expect some function in the eval() family or some typecasting [],{},(:), etc. will do the trick but I have not seen any documentation or gotten any of them to work.

答:
The immediate issue with using the output of ind2sub directly as an index into myArray without an intermediate variable is that only the first output of ind2sub is requested by subsindex when indexing into myArray. The first output is then used as a linear index to index into myArray and assign values which resulting in your unexpected behavior.

Instead, you can use a cell array to capture as many outputs as you want and then rely on {} indexing to yield a comma-separated list.

```<code>[outputs{1:ndims(myArray)}] = ind2sub(size(myArray), IND);
</code>```

You can then use this cell array containing all outputs to then forward all values as inputs or subscripts elsewhere:

```<code>myArray(outputs{:}) = 1;
</code>```

That being said, in the example that you've shown, you really don't need to do any of this as you can use the linear indices IND to index into myArray directly. In fact, using the output of ind2sub will likely give you the incorrect assignment as every permutation of the subscripts will be used when assigning values rather than the element-wise pairing of subscripts.

```<code>myArray(IND) = 1;
</code>```

In general, you can use this technique along with nargout to request all output arguments if there is a non-variable number of outputs.

```<code>[outputs{1:nargout('func')}] = func(inputs);
</code>```

Body:
For any function, I am able to dictate the variables to be returned by explicitly defining how many outputs I am expecting [out1,out2,...,outn] = ...

Edit: Being able to maximize potential # of outputs would also be useful

Example problem

The following code does exactly what is expected (yes, it is redundant with myArray(IND) = 1;)

[I,J] = ind2sub(size(myArray),IND)
myArray(I,J) = 1;

When I try to pass the function arguments directly, I don't get the results I wannt

myArray(ind2sub(size(myArray),IND)) = 1;

I effectively get myArray(I) = 1; when I wanted myArray(I,J) = 1;

Question

How can I dictate how many output variables are returned without explicitly defining my output arguments?

I expect some function in the eval() family or some typecasting [],{},(:), etc. will do the trick but I have not seen any documentation or gotten any of them to work.

Body:
The immediate issue with using the output of ind2sub directly as an index into myArray without an intermediate variable is that only the first output of ind2sub is requested by subsindex when indexing into myArray. The first output is then used as a linear index to index into myArray and assign values which resulting in your unexpected behavior.

Instead, you can use a cell array to capture as many outputs as you want and then rely on {} indexing to yield a comma-separated list.

[outputs{1:ndims(myArray)}] = ind2sub(size(myArray), IND);

You can then use this cell array containing all outputs to then forward all values as inputs or subscripts elsewhere:

myArray(outputs{:}) = 1;

That being said, in the example that you've shown, you really don't need to do any of this as you can use the linear indices IND to index into myArray directly. In fact, using the output of ind2sub will likely give you the incorrect assignment as every permutation of the subscripts will be used when assigning values rather than the element-wise pairing of subscripts.

myArray(IND) = 1;

In general, you can use this technique along with nargout to request all output arguments if there is a non-variable number of outputs.

[outputs{1:nargout('func')}] = func(inputs);


问:
IList.Cast<typeof(T)>() returns error, syntax looks ok
```<code>public static IList<T> LoadObjectListAll<T>()
{
    ISession session = CheckForExistingSession();
    var cfg = new NHibernate.Cfg.Configuration().Configure();
    var returnList = session.CreateCriteria(typeof(T));
    var list = returnList.List();
    var castList = list.Cast<typeof(T)>();
    return castList;
}
</code>```

<p>So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here? </p>

答: CLI only supports generic arguments for covariance and contravariance when using delegates, but when using generics there are some limitations, for example, you can cast a string to an object so most people will assume that you can do the same with List<string> to a List<object> but you can't do that because there is no covariance between generic parameters however you can simulate covariance as you can see in this article. So it depends on the runtime type that it is generated by the abstract factory.

OwnerDisplayName: Sara Chipps

Body:
public static IList<T> LoadObjectListAll<T>()
{
    ISession session = CheckForExistingSession();
    var cfg = new NHibernate.Cfg.Configuration().Configure();
    var returnList = session.CreateCriteria(typeof(T));
    var list = returnList.List();
    var castList = list.Cast<typeof(T)>();
    return castList;
}

So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here?


问:
A Captive Portal to Handle My Needs
I am looking into captive portals for my organization.  I see a lot of them out there that will allow a user to pass once they a.)enter credentials or b.)pay money.  What I'm looking for is a bit different.  Let me go into some basics about my system, I am running a windows based network using active directory and an internal DNS.  I have an intranet in which our employees use daily and it uses the person's Windows credentials to authenticate them on the system.

The employees have to enter time daily, and if they don't then I would like to have a captive portal redirect them to their time entry page and not let them out into the vast internet world until their time is entered.

I am a developer so I can write a script that returns a True or False to the system, but what I need is a system that can interact with AD logons and that can run this script once a user requests access outside out network.

EDIT:
I accepted an answer as the answer to my question, however, after looking into the coding for the sockets based method I do not have the time.

as a workaround, I have found that my firewall has a customizable disclaimer page that allows javascript.  I will query a webservice to see if time is entered then trigger the disclaimer page's "Allow" function, otherwise i will redirect to the time entry page.  seems like a simple enough solution, the only issue is if the person keeps their browser session open overnight.

答:
Christopher Edwards is more or less right. A Captive portal is basically a firewall that transparently forwards all connections to a local Web Server asking for user authentication. After successful authentication the firewall rules are reconfigured for the IP of the authenticated user so he/she can access Internet or other network.

You could setup your own Captive portal by means of scripts and a web server or a proxy, but what is mandatory is that physically all the network traffic crosses the machine acting as firewall.

I have experience with an OSS distribution called m0n0wall that is based on a BSD distribution and it can be embedded directly on dedicated hardware or be installed on any PC. This distribution, though OSS, is really professional and offers basically the same or more functinality than any commercial FW appliance (i.e. Watchguard products, or Cisco Products). It offers a web administration interface to completly administer the firewall.

The only issue if you decide to go this way is that m0n0wall Captive portal has only two ways of authentication: local user database list or external Radius Server. In your case what you need is to setup an external Radius server that integrates in the AD authentication services. Here is an example of how to do it.

OwnerDisplayName: Russ

Title: A Captive Portal to Handle My Needs

LastEditorDisplayName: Russ

OwnerDisplayName: Fernando Miguélez


问:
Angular2 Height Animation - same state transition
I have the following animation code attached to my component

```<code>animations:[
        trigger('slide', [
            state('show', style({
                height: '*'
            })),
            state('hide', style({
                position: 'relative',
                height: 0,
                overflow: 'hidden'
            })),
            transition('show <=> hide',animate('130ms ease-out'))
        ])
    ]
</code>```

This is quite hard to explain, (and I can't seem to get animations to work on plunker) but here goes.

The current functionality is as follows:

User clicks a button to display table.

Table smoothly slides into view from below a div.

User click button again.

Table smoothly slides out of the view up into the div.

The desired functionality is as follows:

User clicks a button to display table.

Table smoothly slides into view from below a div.

More rows are added to table (could be a large number of rows)

Animation handles the new table height and instead of just instantly being displayed there is a smoothing animation to gradually move to the new height.

User Clicks button.

Table slides back up under div again.

Edit: here is a plunker demo. You can see when you add/remove rows from the table the animation does not smoothly move to the new height.

The problem is caused because if you are in true state and rows are added.

The animation will not transition to true again, because it is already in true state.

So how will I trigger a transition to the "newHeight" state when items are added?

答:
I made a quick, rough, animation example using angular animations API:

https://embed.plnkr.co/7qWuHmbFFie4p8Y9h53T/

I would play around with that plnkr until you get the animations right. You can hide the element behind something by either removing the table entirely after animating it down by toggling the animation with an *ngIf in your template, or do it the way I show in the plnkr, but toggle the visibility of the table after the animation is complete. I prefer the *ngIf way.

For individual rows being added or removed:

I would add an @animation to every row of the table and enable the up animation if the number of rows increases, or down if it decreases.

Body:
I have the following animation code attached to my component

animations:[
        trigger('slide', [
            state('show', style({
                height: '*'
            })),
            state('hide', style({
                position: 'relative',
                height: 0,
                overflow: 'hidden'
            })),
            transition('show <=> hide',animate('130ms ease-out'))
        ])
    ]

This is quite hard to explain, (and I can't seem to get animations to work on plunker) but here goes.

The current functionality is as follows:

User clicks a button to display table.

Table smoothly slides into view from below a div.

User click button again.

Table smoothly slides out of the view up into the div.

The desired functionality is as follows:

User clicks a button to display table.

Table smoothly slides into view from below a div.

More rows are added to table (could be a large number of rows)

Animation handles the new table height and instead of just instantly being displayed there is a smoothing animation to gradually move to the new height.

User Clicks button.

Table slides back up under div again.

Edit: here is a plunker demo. You can see when you add/remove rows from the table the animation does not smoothly move to the new height.

The problem is caused because if you are in true state and rows are added.

The animation will not transition to true again, because it is already in true state.

So how will I trigger a transition to the "newHeight" state when items are added?


问:
SQL Server continue series of inserts from Select statements despite errors(?)
I have a large file of SQL statements that are lined up as follows:

```<code> INSERT INTO [table here]
    SELECT [columns]
    FROM OPENROWSET(xlsx tab 1)

INSERT INTO [table here]
    SELECT [columns]
    FROM OPENROWSET(xlsx tab 2)

... etc etc...
</code>```

The problem is that sometimes XLSX tab #2 (or 22) does not exist and may cause an error and the entire series of statements fails.

Is there a way to get each statement to execute as though they were their own query or ignore the error and continue?

Thanks!

答:
Error Handling in SQLServer is tricky.There some errors that abort entire batch,some which abort entire session,errors which abort session can't be caught and can't be retried from SSMS itself

In your case,if you want one insert ,not to be affected by another..Try separating them with BATCH SEPARATOR GO

```<code>INSERT INTO
SELECT
GO

INSERT
SELECT
GO
</code>```

Reference and further reading :

Error and Transaction Handling in SQL Server

Body:
I have a large file of SQL statements that are lined up as follows:

 INSERT INTO [table here]
    SELECT [columns]
    FROM OPENROWSET(xlsx tab 1)

INSERT INTO [table here]
    SELECT [columns]
    FROM OPENROWSET(xlsx tab 2)

... etc etc...

The problem is that sometimes XLSX tab #2 (or 22) does not exist and may cause an error and the entire series of statements fails.

Is there a way to get each statement to execute as though they were their own query or ignore the error and continue?

Thanks!

Body:
Error Handling in SQLServer is tricky.There some errors that abort entire batch,some which abort entire session,errors which abort session can't be caught and can't be retried from SSMS itself

In your case,if you want one insert ,not to be affected by another..Try separating them with BATCH SEPARATOR GO

INSERT INTO
SELECT
GO

INSERT
SELECT
GO

Reference and further reading :

Error and Transaction Handling in SQL Server


问:
How to pass arguments to system call at xv6?
I am trying to implement a new system call at xv6.
Had some trouble to pass arguments.
Lets say this is my system call.

```<code>sys_mySystemcall(int* x ,struct myStruct * y);
</code>```

How do I get these 2 pointers at sysproc.c?
Thanks,

答: The helper functions argint, argptr, argstr,and argfd retrieve the n’th system call argument, as either an integer, pointer, a string,or a file descriptor.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am trying to implement a new system call at xv6.
Had some trouble to pass arguments.
Lets say this is my system call.

sys_mySystemcall(int* x ,struct myStruct * y);

How do I get these 2 pointers at sysproc.c?
Thanks,


问:
Eclipse is freezing itself before getting started
I've been trying to open Eclipse to start my work today, and it freezes everytime during load.

My Eclipse is Helios. Someone told me I should remove a file called .lock from .metadata folder, but still didn't work.

Does anyone have any idea of how do I "melt" this thing up?

ps: I opened it yesterday with no problems.

答:
I would suggest a (big) problem with a plugin in Eclipse.. because project plugins or runtimes will execute later.

Create a new workspace and repimport your projects from your old workspace. If you have a vcs, you can re-checkout them.


问:
Can someone explain the use of JTexPane in a GUI and if it affects the output of the program if not used correctly?
I am working on an assignment for my Java class and I wrote a code that works similar to Microsoft word's word counter.  Everything on my code works, the problem is when I run the program I need to click on the window in order for my output to appear or else nothing will show up.  It acts as if it is hidden.

```<code>public static void main(String[] args) {
    //JPanel contentPane = null;
    //JTextField textField;
    int length;
    String msg;

    Scanner scan = new Scanner (System.in);

    System.out.println("Enter a sentence: ");
    msg = scan.nextLine();

    length = msg.length();

    JFrame frame = new JFrame("Word Count");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(null);
    frame.setSize(400, 300);

    JLabel label1 = new JLabel("Statistics");
    label1.setFont(new Font("Onyx", Font.BOLD, 12));
    label1.setBounds(30, 10, 135, 15);
    frame.add(label1);

    JButton ex = new JButton("Close");
    ex.setBounds(30, 200, 50, 50);
    ex.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){
        System.exit(0);
    }});

    frame.add(ex);
    frame.setVisible(true);

    JTextPane lbl = new JTextPane();
    lbl.setBounds(30, 30, 310, 150);
    lbl.setText(getStats(msg));
    frame.getContentPane().add(lbl);
    frame.setVisible(true);

}
public static String getStats(String msg){

    int spcCount = 0;
    int aCount = 0;
    String tmpMsg = "";

    for(int i = 0; i < msg.length(); i++){

        if(msg.charAt(i) == ' '){
            spcCount++;
        }else if(msg.charAt(i) == 'a'){
            aCount++;
        }
    }

        tmpMsg += "Characters (with spaces)\t\t" + msg.length() + "\n";
        tmpMsg += "Characters (without spaces)\t\t" + (msg.length()-spcCount) + "\n";
        tmpMsg += "Spaces\t\t\t\t" + spcCount + "\n";
        tmpMsg += "Words\t\t\t\t" + (spcCount+1) + "\n";
        tmpMsg += "Vowels\t\t\t\t" + (msg.length() - msg.toLowerCase().replaceAll("a|e|i|o|u", "").length()) + "\n";

        return tmpMsg;

    }
</code>```

}

This problem is obviously annoying and not efficient.  So does the use of TextPane here cause this issue?  Thank you in advance and don't hesitate to make edits if it helps with wording the question better.

答:
Added few lines of code for setting it in front and deleted frame.setVisible(true); duplicate, main should look like this:   </p>

```<code>public static void main(String[] args) {
    //JPanel contentPane = null;
    //JTextField textField;
    int length;
    String msg;

    Scanner scan = new Scanner(System.in);

    System.out.println("Enter a sentence: ");
    msg = scan.nextLine();

    length = msg.length();

    JFrame frame = new JFrame("Word Count");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(null);
    frame.setSize(400, 300);

    JLabel label1 = new JLabel("Statistics");
    label1.setFont(new Font("Onyx", Font.BOLD, 12));
    label1.setBounds(30, 10, 135, 15);

    JButton ex = new JButton("Close");
    ex.setBounds(30, 200, 50, 50);
    ex.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }

    });
    frame.add(label1);
    frame.add(ex);

    JTextPane lbl = new JTextPane();
    lbl.setBounds(30, 30, 310, 150);
    lbl.setText(getStats(msg));
    frame.getContentPane().add(lbl);

    frame.setVisible(true);
    frame.setAlwaysOnTop(true);
    frame.toFront();
    frame.requestFocus();
    frame.setAlwaysOnTop(false);

}
</code>```

Body:
I am working on an assignment for my Java class and I wrote a code that works similar to Microsoft word's word counter.  Everything on my code works, the problem is when I run the program I need to click on the window in order for my output to appear or else nothing will show up.  It acts as if it is hidden.

public static void main(String[] args) {
    //JPanel contentPane = null;
    //JTextField textField;
    int length;
    String msg;

    Scanner scan = new Scanner (System.in);

    System.out.println("Enter a sentence: ");
    msg = scan.nextLine();

    length = msg.length();

    JFrame frame = new JFrame("Word Count");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(null);
    frame.setSize(400, 300);

    JLabel label1 = new JLabel("Statistics");
    label1.setFont(new Font("Onyx", Font.BOLD, 12));
    label1.setBounds(30, 10, 135, 15);
    frame.add(label1);

    JButton ex = new JButton("Close");
    ex.setBounds(30, 200, 50, 50);
    ex.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){
        System.exit(0);
    }});

    frame.add(ex);
    frame.setVisible(true);

    JTextPane lbl = new JTextPane();
    lbl.setBounds(30, 30, 310, 150);
    lbl.setText(getStats(msg));
    frame.getContentPane().add(lbl);
    frame.setVisible(true);

}
public static String getStats(String msg){

    int spcCount = 0;
    int aCount = 0;
    String tmpMsg = "";

    for(int i = 0; i < msg.length(); i++){

        if(msg.charAt(i) == ' '){
            spcCount++;
        }else if(msg.charAt(i) == 'a'){
            aCount++;
        }
    }

        tmpMsg += "Characters (with spaces)\t\t" + msg.length() + "\n";
        tmpMsg += "Characters (without spaces)\t\t" + (msg.length()-spcCount) + "\n";
        tmpMsg += "Spaces\t\t\t\t" + spcCount + "\n";
        tmpMsg += "Words\t\t\t\t" + (spcCount+1) + "\n";
        tmpMsg += "Vowels\t\t\t\t" + (msg.length() - msg.toLowerCase().replaceAll("a|e|i|o|u", "").length()) + "\n";

        return tmpMsg;

    }

}

This problem is obviously annoying and not efficient.  So does the use of TextPane here cause this issue?  Thank you in advance and don't hesitate to make edits if it helps with wording the question better.

Body:
Added few lines of code for setting it in front and deleted frame.setVisible(true); duplicate, main should look like this:

public static void main(String[] args) {
    //JPanel contentPane = null;
    //JTextField textField;
    int length;
    String msg;

    Scanner scan = new Scanner(System.in);

    System.out.println("Enter a sentence: ");
    msg = scan.nextLine();

    length = msg.length();

    JFrame frame = new JFrame("Word Count");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(null);
    frame.setSize(400, 300);

    JLabel label1 = new JLabel("Statistics");
    label1.setFont(new Font("Onyx", Font.BOLD, 12));
    label1.setBounds(30, 10, 135, 15);

    JButton ex = new JButton("Close");
    ex.setBounds(30, 200, 50, 50);
    ex.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }

    });
    frame.add(label1);
    frame.add(ex);

    JTextPane lbl = new JTextPane();
    lbl.setBounds(30, 30, 310, 150);
    lbl.setText(getStats(msg));
    frame.getContentPane().add(lbl);

    frame.setVisible(true);
    frame.setAlwaysOnTop(true);
    frame.toFront();
    frame.requestFocus();
    frame.setAlwaysOnTop(false);

}


问:
Creating QIcon from SVG contents in memory
How can we create the QIcon object having SVG icon contents in the memory buffer?

P.S. Initially wanted to create QSvgIconEngine, but it is hidden on the plugins layer, and I can not create it explicitly. How can I do it with loading from plugin (taking in account, that plugin is loaded)?

答:
How can we create the QIcon object having SVG icon contents in the
  memory buffer?

For that all the required functionality is delivered via external interface of QSvgRenderer class. To construct that type of renderer we need to use either of:

```<code>QSvgRenderer(const QByteArray &contents, QObject *parent = Q_NULLPTR);
QSvgRenderer(QXmlStreamReader *contents, QObject *parent = Q_NULLPTR);
</code>```

or we can just load the content with:

```<code>bool QSvgRenderer::load(const QByteArray &contents)
bool QSvgRenderer::load(QXmlStreamReader *contents)
</code>```

And to create the actual icon:

```<code>QIcon svg2Icon(const QByteArray& svgContent, QPainter::CompositionMode mode =
   QPainter::CompositionMode_SourceOver)
{
    return QIcon(util::svg2Pixmap(svgContent, QSize(128, 128), mode));
}

QPixmap svg2Pixmap(const QByteArray& svgContent,
   const QSize& size,
   QPainter::CompositionMode mode)
{
    QSvgRenderer rr(svgContent);
    QImage image(size.width(), size.height(), QImage::Format_ARGB32);
    QPainter painter(&image);
    painter.setCompositionMode(mode);
    image.fill(Qt::transparent);
    rr.render(&painter);
    return QPixmap::fromImage(image);
}
</code>```

We can also use other composition modes as well, say,
QPainter::RasterOp_NotSourceOrDestination to invert the icon color.

Body:
How can we create the QIcon object having SVG icon contents in the
  memory buffer?

For that all the required functionality is delivered via external interface of QSvgRenderer class. To construct that type of renderer we need to use either of:

QSvgRenderer(const QByteArray &contents, QObject *parent = Q_NULLPTR);
QSvgRenderer(QXmlStreamReader *contents, QObject *parent = Q_NULLPTR);

or we can just load the content with:

bool QSvgRenderer::load(const QByteArray &contents)
bool QSvgRenderer::load(QXmlStreamReader *contents)

And to create the actual icon:

QIcon svg2Icon(const QByteArray& svgContent, QPainter::CompositionMode mode =
   QPainter::CompositionMode_SourceOver)
{
    return QIcon(util::svg2Pixmap(svgContent, QSize(128, 128), mode));
}

QPixmap svg2Pixmap(const QByteArray& svgContent,
   const QSize& size,
   QPainter::CompositionMode mode)
{
    QSvgRenderer rr(svgContent);
    QImage image(size.width(), size.height(), QImage::Format_ARGB32);
    QPainter painter(&image);
    painter.setCompositionMode(mode);
    image.fill(Qt::transparent);
    rr.render(&painter);
    return QPixmap::fromImage(image);
}

We can also use other composition modes as well, say,
QPainter::RasterOp_NotSourceOrDestination to invert the icon color.


问:
Creating "background running" children with fork() and kill each of them with signals
I need to create n children from the same parent, and have them running while the parent asks infinitely for a signal to send to some child. I made the parent create those n children, but they finished executing, so I made them enter a while(1) loop. The problem is, when I try to kill any child, it  becomes a zombie process instead of actually terminating its execution. I'm guessing that's because the parent is still waiting for the children to terminate execution and they don't send the exit status. So... First of all, do I really need to make the children enter an infinite while loop to make them be running while the parent is asking for the signals? If I do, how do I avoid this "never terminating execution" problem? I need to find a way for the children to exit that while loop and send the actual "finished execution" signal since I think I can't use wait() because the children never actually finish running, they are just terminated by the parent.

Thanks.
PS: Running in Linux. This is my code

```<code>int main(){
    int i;
    pid_t parent = getpid();
    pid_t pid[4];
    printf("parent with pid %d\n", parent);

    for(i = 0; i < 5; i++){
        pid[i] = fork();
        if(pid[i] < 0){
            perror("Error in fork.");
            exit(1);
        } else if(pid[i] == 0 && getppid() == padre) {
            printf("Number: %d   pid %d, parent: %d\n", i, getpid(), getppid());
            while(1);
        }
    }

    if(getpid() == padre){
        while(1){
            printf("Enter pid and signal:\n");
            int x, y;
            scanf("%d", &x); // pid
            scanf("%d", &y); // signal
            printf("you did: kill(%d, %d)\n", x, y);
            kill(x, y);
        }
    }
    return 0;
}
</code>```

EDIT:
Final code with answer implemented: https://github.com/sebasura/sistope

答:
The problem is, when I try to kill any child, it becomes a zombie process instead of actually terminating its execution.

Well, yes and no.  Becoming a zombie is normally what happens when a process terminates, until that process is collected by its parent.  A zombie takes up a bit of space in the process table, but it is not running, and therefore consumes no CPU.

I'm guessing that's because the parent is still waiting for the children to terminate execution and they don't send the exit status.

No, it's because kill() just sends a signal.  You need to use one of the wait() functions -- perhaps waitpid() -- to actually collect the terminated child.

So... First of all, do I really need to make the children enter an infinite while loop to make them be running while the parent is asking for the signals?

No.  The child can use sigwait() or one of its variants to wait for a signal from a designated set, or pause() to suspend execution pending receipt of any signal that terminates the process or triggers a signal handler function.  Note, however, that there are some signals that by default do neither of those, so sigwait() is probably the better alternative.

If I do, how do I avoid this "never terminating execution" problem?

The child must terminate as a result of receiving the signal.  That's already happening for you, because the children are becoming zombies.  With your present code it may depend on which signal you send, however, for there are some whose default handling does not terminate the process.

Body:
I need to create n children from the same parent, and have them running while the parent asks infinitely for a signal to send to some child. I made the parent create those n children, but they finished executing, so I made them enter a while(1) loop. The problem is, when I try to kill any child, it  becomes a zombie process instead of actually terminating its execution. I'm guessing that's because the parent is still waiting for the children to terminate execution and they don't send the exit status. So... First of all, do I really need to make the children enter an infinite while loop to make them be running while the parent is asking for the signals? If I do, how do I avoid this "never terminating execution" problem? I need to find a way for the children to exit that while loop and send the actual "finished execution" signal since I think I can't use wait() because the children never actually finish running, they are just terminated by the parent.

Thanks.
PS: Running in Linux. This is my code

int main(){
    int i;
    pid_t parent = getpid();
    pid_t pid[4];
    printf("parent with pid %d\n", parent);

    for(i = 0; i < 5; i++){
        pid[i] = fork();
        if(pid[i] < 0){
            perror("Error in fork.");
            exit(1);
        } else if(pid[i] == 0 && getppid() == padre) {
            printf("Number: %d   pid %d, parent: %d\n", i, getpid(), getppid());
            while(1);
        }
    }

    if(getpid() == padre){
        while(1){
            printf("Enter pid and signal:\n");
            int x, y;
            scanf("%d", &x); // pid
            scanf("%d", &y); // signal
            printf("you did: kill(%d, %d)\n", x, y);
            kill(x, y);
        }
    }
    return 0;
}

EDIT:
Final code with answer implemented: https://github.com/sebasura/sistope


问:
Connecting to MySql gear on another gear
so I have two free gears on OpenShift.
One is a PHP with MySql 5.7 from:

https://github.com/icflorescu/openshift-cartridge-mysql

To which I can remote login from my PC without any problem by SSH tunnel.

Now on the second gear I wanted to create Spring Boot app that would connect to DB on the first gear. Using env | grep MYSQL on first gear I receive:

OPENSHIFT_MYSQL_DB_PORT=13306

OPENSHIFT_MYSQL_DB_HOST=127.10.104.130

So this + my logging data was put into Spring application.properties, after successfull build Spring crashed at data pool creation because it could not connect to database so I SSHed into second hear and tried accessing MySQL instance from first gear via:

mysql -u root -h 127.10.104.130 -P 13306 but I get error message:

Can not connect to MySQL Server on '127.10.104.130' (113)

After that I tried:

mysql -u root -h myAppName-domain.rhcloud.com -P 13306 which results in longer time of connection but ultimatelly failling with:

Can not connect to MySQL Server on 'myAppName-domain.rhcloud.com' (110)

And I can easly ping gear#1 from gear#2 so I am confused - do I need some extra sql config or firewall settings? I am also doing tail on mysql logs and nothing is showing up like connection is not even made.

答:
I'm the author of the openshift-cartridge-mysql mentioned above.

It's been a while since I've published that cartridge, but if I remember correctly, the setup script is quite unassuming and there's nothing created by default, so you have to create your own users, databases and explicitly grant the appropriate privileges.

Connect from your PC either by ssh or by Workbench over ssh tunnel, create your user and database, then execute something like:

```<code>GRANT ... ; FLUSH PRIVILEGES;
</code>```

You can learn more on MySQL's GRANT command in the official manual.

There's a line in the repo README exemplifying how you could grant remote access to root, which is not as unsafe as it looks because you can only access the DB gear from your main application gear.

But ideally you'd want to limit the access as much as possible (to a specific user coming from a specific host/IP, such as your main application gear). Something like this:

```<code>GRANT ALL ON appdb.* TO 'appuser'@'appgear';
</code>```

Don't forget to FLUSH PRIVILEGES when you're done.

I hope this helps,

@icflorescu

Body:
I'm the author of the openshift-cartridge-mysql mentioned above.

It's been a while since I've published that cartridge, but if I remember correctly, the setup script is quite unassuming and there's nothing created by default, so you have to create your own users, databases and explicitly grant the appropriate privileges.

Connect from your PC either by ssh or by Workbench over ssh tunnel, create your user and database, then execute something like:

GRANT ... ; FLUSH PRIVILEGES;

You can learn more on MySQL's GRANT command in the official manual.

There's a line in the repo README exemplifying how you could grant remote access to root, which is not as unsafe as it looks because you can only access the DB gear from your main application gear.

But ideally you'd want to limit the access as much as possible (to a specific user coming from a specific host/IP, such as your main application gear). Something like this:

GRANT ALL ON appdb.* TO 'appuser'@'appgear';

Don't forget to FLUSH PRIVILEGES when you're done.

I hope this helps,

@icflorescu


问:
Output to a text file
I need to output lots of different datasets to different text files. The datasets share some common variables that need to be output but also have quite a lot of different ones. I have loaded these different ones into a macro variable separated by blanks so that I can macroize this.

So I created a macro which loops over the datasets and outputs each into a different text file.

For this purpose, I used a put statement inside a data step. The PUT statement looks like this:

```<code>PUT (all the common variables shared by all the datasets), (macro variable containing all the dataset-specific variables);
</code>```

E.g.:

```<code>%MACRO OUTPUT();
    %DO N=1 %TO &TABLES_COUNT;
        DATA _NULL_;
            SET &&TABLE&N;
            FILE 'PATH/&&TABLE&N..txt';
            PUT a b c d "&vars";
        RUN;
    %END;
%MEND OUTPUT;
</code>```

Where &vars is the macro variable containing all the variables needed for outputting for a dataset in the current loop.
Which gets resolved, for example, to:

```<code>PUT a b c d special1 special2 special5 ... special329;
</code>```

Now the problem is, the quoted string can only be 262 characters long. And some of my datasets I am trying to output have so many variables to be output that this macro variable which is a quoted string and holds all those variables will be much longer than that. Is there any other way how I can do this?

答:
Do not include quotes around the list of variable names.

```<code>put a b c d &vars ;
</code>```

There should not be any limit to the number of variables you can output, but if the length of the output line gets too long SAS will wrap to a new line. The default line length is currently 32,767 (but older versions of SAS use 256 as the default line length). You can actually set that much higher if you want. So you could use 1,000,000 for example.  The upper limit probably depends on your operating system.

```<code>FILE "PATH/&&TABLE&N..txt" lrecl=1000000 ;
</code>```

If you just want to make sure that the common variables appear at the front (that is you are not excluding any of the variables) then perhaps you don't need the list of variables for each table at all.

```<code>DATA _NULL_;
  retain a b c d ;
  SET &&TABLE&N;
  FILE "&PATH/&&TABLE&N..txt" lrecl=1000000;
  put (_all_) (+0) ;
RUN;
</code>```

Title: Output to a text file

Body:
I need to output lots of different datasets to different text files. The datasets share some common variables that need to be output but also have quite a lot of different ones. I have loaded these different ones into a macro variable separated by blanks so that I can macroize this.

So I created a macro which loops over the datasets and outputs each into a different text file.

For this purpose, I used a put statement inside a data step. The PUT statement looks like this:

PUT (all the common variables shared by all the datasets), (macro variable containing all the dataset-specific variables);

E.g.:

%MACRO OUTPUT();
    %DO N=1 %TO &TABLES_COUNT;
        DATA _NULL_;
            SET &&TABLE&N;
            FILE 'PATH/&&TABLE&N..txt';
            PUT a b c d "&vars";
        RUN;
    %END;
%MEND OUTPUT;

Where &vars is the macro variable containing all the variables needed for outputting for a dataset in the current loop.
Which gets resolved, for example, to:

PUT a b c d special1 special2 special5 ... special329;

Now the problem is, the quoted string can only be 262 characters long. And some of my datasets I am trying to output have so many variables to be output that this macro variable which is a quoted string and holds all those variables will be much longer than that. Is there any other way how I can do this?

Body:
Do not include quotes around the list of variable names.

put a b c d &vars ;

There should not be any limit to the number of variables you can output, but if the length of the output line gets too long SAS will wrap to a new line. The default line length is currently 32,767 (but older versions of SAS use 256 as the default line length). You can actually set that much higher if you want. So you could use 1,000,000 for example.  The upper limit probably depends on your operating system.

FILE "PATH/&&TABLE&N..txt" lrecl=1000000 ;

If you just want to make sure that the common variables appear at the front (that is you are not excluding any of the variables) then perhaps you don't need the list of variables for each table at all.

DATA _NULL_;
  retain a b c d ;
  SET &&TABLE&N;
  FILE "&PATH/&&TABLE&N..txt" lrecl=1000000;
  put (_all_) (+0) ;
RUN;


问:
One to Many Relationship mongoDB
I have a quick question regarding one to many relationships in mongoDB. I have mainly used SQL before this so im getting confused about how to approach relationships. I have viewed all the documentation online and it does not give a good example of how to set up and query a one to many relationship.

Say I have a table of Users and each user has many products. This means that in an SQL situation multiple products in the table would have the same user foreign_key. In mongoDB I have tried to replicate this by placing each users object id into the corresponding product that they are selling much like a foreign key.

Im getting confused on how I would query it. For example how would I do  SELECT * FROM USERS, PRODUCTS WHERE USER_ID = USERFK_ID;?

Ive read about document references, embedded document but its just confusing me more. Does anyone have a straight explanation please.

答:
Assuming I understood your question, I will have a users collection and a products collection.

The users collection will contain users and their details. E.g.

{id: '007', name: 'john'}
{id: '010', name: 'paul'}

The products collection will contain products linked to given users. E.g.

{id: '432738', name: 'apple', price: '100', owner: '007'} i.e. owner is john

As pertaining the query, I will do something like this:

db.collection('products').find({owner: user_id_here})

Title: One to Many Relationship mongoDB


问:
Python 3.5 'list' object has no attribute 'min' and unorderable types: str() < int() and
I'm trying to follow this tutorial here using python 3.5, however I'm getting errors instead of the expected results. Also, I would appreciate if you explain what the indicated line below does. </p>

```<code>import matplotlib.pyplot as plt
x=[1,2,3,4,5]
y=[1,2,3,4,5]

list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]
print ("min value element : ", min(list1))
print ("min value element : ", min(list2))

plt.scatter(x, y,  color='red')
#please explain this line:
plt.plot([y.min(), y.max()], [y.min(), y.max()], color='blue', linewidth=3)

plt.show()
</code>```

答:
The issue is probably that you need to pass the lists into min and max like this:

```<code>plt.plot([min(y), max(y)], [min(y), max(y)], color='blue', linewidth=3)
</code>```

Right now this will just plot a line between [1,1] and [5,5].

If you want to plot x and y against each other you could do this:

```<code>plt.plot(x, y, color='blue', linewidth=3)
</code>```

In the case of list1 you have a list with ints and strings so the strings will just be ignored by min and max.

Body:
I'm trying to follow this tutorial here using python 3.5, however I'm getting errors instead of the expected results. Also, I would appreciate if you explain what the indicated line below does.

import matplotlib.pyplot as plt
x=[1,2,3,4,5]
y=[1,2,3,4,5]

list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]
print ("min value element : ", min(list1))
print ("min value element : ", min(list2))

plt.scatter(x, y,  color='red')
#please explain this line:
plt.plot([y.min(), y.max()], [y.min(), y.max()], color='blue', linewidth=3)

plt.show()

Body:
The issue is probably that you need to pass the lists into min and max like this:

plt.plot([min(y), max(y)], [min(y), max(y)], color='blue', linewidth=3)

Right now this will just plot a line between [1,1] and [5,5].

If you want to plot x and y against each other you could do this:

plt.plot(x, y, color='blue', linewidth=3)

In the case of list1 you have a list with ints and strings so the strings will just be ignored by min and max.


问:
Using IntelliJ IDEA and the Dart plugin, where does the Dart exceptions end up?
I've been playing with Angular2 using IntelliJ IDEA (2016.3.5) and the latest Dart plugin, and I just can't figure out where the errors, exceptions, assert failures etc. ends up.

I am running Dartium with DART_FLAGS="--checked" and pub serve seems to default to debug mode as far as I can read. Dart2js is configured to run in checked mode as well and the analysis server is configured for strong mode. I have also tried using the JetBrains Chrome extension so I get everything shown directly in IDEA, including the console saying Observatory listening at http://127.0.0.1:35517/.

When there are no errors the Angular2 Dart app runs just fine in Dartium but if I add an assert some where in the code, ie. on a button trigger, the app just stops working at that point with no error output anywhere. Same goes if there's some other error somewhere that pub serve didn't detect.

Dart and Dartium are both at the currently latest version, 1.22.1.

答: This will be fixed in Angular3 beta.x due to be released the next days it seems.</p>


问:
NewtonSoft Json Deserializing error - Could not convert string to decimal: /Date(1490721584000-0500)/
In my ASP.Net MVC project, using NewtonSoft json deserializer, I'm consuming a json web service sending date in /Date()/ format. I'm receiveing json as (showing first of many array elements):

```<code>[
  {
    "Prop1": false,
    "Prop2": false,
    "TimeDtlList": [
      {
        "CustName": null,
        "tranDate": null,
        "startTime": "/Date(1490721584000-0500)/",
        "endTime": "/Date(1490734813000-0500)/",
      }
    ],
    "name": "Bill, Jack F.",
  }
]
</code>```

In my code, I'm using DateFormatHandling.MicrosoftDateFormat, however I'm still getting error:

Could not convert string to decimal: /Date(1490721584000-0500)/. Path
  '[0].times[0].startTime', line 1, position 337.

I'm deserializing the object using:

```<code>JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings{DateFormatHandling = DateFormatHandling.MicrosoftDateFormat};
List<Times> timesList = JsonConvert.DeserializeObject <List<Times>>(text, microsoftDateFormatSettings);
</code>```

and my model classes are defined as:

```<code>public class Times
{
    public Boolean prop1 { get; set; }
    public Boolean prop2 { get; set; }
    public List<TimeDtl> TimeDtlList { get; set; }
    public String name { get; set; }
}
public class TimeDtl
{
    public String CustName { get; set; }
    public DateTime? tranDate { get; set; }
    public Decimal? startTime { get; set; }
    public Decimal? endTime { get; set; }
}
</code>```

How can I deserialize the time correctly?

答:
according to your json its just object of Times not List<Times>

```<code>string json = "{\"startTime\": \"/Date(1490721584000-0500)/\",\r\n\"endTime\": \"/Date(1490734813000-0500)/\"}";
dynamic stuff = JsonConvert.DeserializeObject(json);
Times result = stuff.ToObject<Times>();
</code>```

and you can access values like

result.startTime  for documentation of ToObject you can check this ToObject

Edit

so according to your new model json should be

```<code>var result = stuff.ToObject<List<Times>>();
</code>```

and in your model you need to correct the type from

```<code>public Decimal? startTime { get; set; }
public Decimal? endTime { get; set; }
</code>```

to

```<code>public DateTime? startTime { get; set; }
public DateTime? endTime { get; set; }
</code>```

since the startTime and endTime is of type DateTime

Body:
In my ASP.Net MVC project, using NewtonSoft json deserializer, I'm consuming a json web service sending date in /Date()/ format. I'm receiveing json as (showing first of many array elements):

[
  {
    "Prop1": false,
    "Prop2": false,
    "TimeDtlList": [
      {
        "CustName": null,
        "tranDate": null,
        "startTime": "/Date(1490721584000-0500)/",
        "endTime": "/Date(1490734813000-0500)/",
      }
    ],
    "name": "Bill, Jack F.",
  }
]

In my code, I'm using DateFormatHandling.MicrosoftDateFormat, however I'm still getting error:

Could not convert string to decimal: /Date(1490721584000-0500)/. Path
  '[0].times[0].startTime', line 1, position 337.

I'm deserializing the object using:

JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings{DateFormatHandling = DateFormatHandling.MicrosoftDateFormat};
List<Times> timesList = JsonConvert.DeserializeObject <List<Times>>(text, microsoftDateFormatSettings);

and my model classes are defined as:

public class Times
{
    public Boolean prop1 { get; set; }
    public Boolean prop2 { get; set; }
    public List<TimeDtl> TimeDtlList { get; set; }
    public String name { get; set; }
}
public class TimeDtl
{
    public String CustName { get; set; }
    public DateTime? tranDate { get; set; }
    public Decimal? startTime { get; set; }
    public Decimal? endTime { get; set; }
}

How can I deserialize the time correctly?

Body:
according to your json its just object of Times not List<Times>

string json = "{\"startTime\": \"/Date(1490721584000-0500)/\",\r\n\"endTime\": \"/Date(1490734813000-0500)/\"}";
dynamic stuff = JsonConvert.DeserializeObject(json);
Times result = stuff.ToObject<Times>();

and you can access values like

result.startTime  for documentation of ToObject you can check this ToObject

Edit

so according to your new model json should be

var result = stuff.ToObject<List<Times>>();

and in your model you need to correct the type from

public Decimal? startTime { get; set; }
public Decimal? endTime { get; set; }

to

public DateTime? startTime { get; set; }
public DateTime? endTime { get; set; }

since the startTime and endTime is of type DateTime


问:
CSS custom font vertical offset (bug?)
I use custom font in my CSS with this method:

```<code>@font-face {
    font-family: 'Gabriola';
    src: url('Gabriola.eot');
    src: url('Gabriola.eot?#iefix') format('embedded-opentype'),
         url('Gabriola.woff') format('woff'),
         url('Gabriola.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}
.gabriola {
  font-size: 20px;
  line-height: 20px;
  height: 20px;
  background: red;
}

<div class="gabriola">Some texty text here</div>
</code>```

Each browser renders this fonts by it's own way with vertical offset top and bottom like this

What am I doing wrong? Thanks

答:
I know it's been 5 years since the OP asked the question, but I found this great technique on getting text baseline-aligned correctly.

Basically, the text container must be an inline-block with line-height: 0;
Then, you create an inline-block pseudo-element and set its height according to the line-height you wanted:

span {
  font-size: 2em;
  background: red;
}
span.baseline-align {
  vertical-align: baseline;
}

span.true-baseline-align {
  display: inline-block;
  line-height: 0;
}
span.true-baseline-align::after {
  content: '';
  display: inline-block;
  height: 1em; // this is where you control line-height
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span>Normal text</span>
<br><br>
<span class="baseline-align">With vertical-align: baseline</span>
<br><br>
<span class="true-baseline-align">with trick to really baseline-align</span></code>```

http://blogs.adobe.com/webplatform/2014/08/13/one-weird-trick-to-baseline-align-text/

Title: CSS custom font vertical offset (bug?)

Body:
I use custom font in my CSS with this method:

@font-face {
    font-family: 'Gabriola';
    src: url('Gabriola.eot');
    src: url('Gabriola.eot?#iefix') format('embedded-opentype'),
         url('Gabriola.woff') format('woff'),
         url('Gabriola.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}
.gabriola {
  font-size: 20px;
  line-height: 20px;
  height: 20px;
  background: red;
}

Some texty text here

Each browser renders this fonts by it's own way with vertical offset top and bottom like this

What am I doing wrong? Thanks

Body:
I know it's been 5 years since the OP asked the question, but I found this great technique on getting text baseline-aligned correctly.

Basically, the text container must be an inline-block with line-height: 0;
Then, you create an inline-block pseudo-element and set its height according to the line-height you wanted:

span {
  font-size: 2em;
  background: red;
}
span.baseline-align {
  vertical-align: baseline;
}

span.true-baseline-align {
  display: inline-block;
  line-height: 0;
}
span.true-baseline-align::after {
  content: '';
  display: inline-block;
  height: 1em; // this is where you control line-height
}

<span>Normal text</span>
<br><br>
<span class="baseline-align">With vertical-align: baseline</span>
<br><br>
<span class="true-baseline-align">with trick to really baseline-align</span>

http://blogs.adobe.com/webplatform/2014/08/13/one-weird-trick-to-baseline-align-text/


问:
How does a broadcast receiver work among activities?
I have multiple activities suppose A , B , C , D and all are register to same BroadCastReceiver. While sending the broadcast message in which order activities will receive the broadcast intents. Is it in order like A , B , C , D or random.

Please let me know, give me some suggestions.

答: There are possibilities to have ordered broadcasts. It depends if you are the one broadcasting. If you are broadcasting use sendOrderedBroadcast(Intent, String) and give priority to your receivers. If someone else is the broadcaster you have to know if he is sending ordered or not. If he doesnt, you have no chance, otherwise you can priotize your receivers.


问:
Null-Conditional Operator

var a = b?.c.d;

Shouldn't this expression always give a compile error? If b is null, the null value is propagated through so c will also be null and thus also need this operator. In my understanding usage of this operator in an expression spreads viral.

But neither Visual Studio 2015 nor Resharper says anything to me, am I missing something here?

答:
Note that:

```<code>var a1 = b?.c.d;
</code>```

is entirely different from:

```<code>var a2 = (b?.c).d;
</code>```

It is not very easy to explain in short how the unary operator ?. works (yes, unary!). But the idea is that the rest of the "chain" of "operations" is skipped if the expression before ?. is null.

So for a1, you get a null of the compile-time type carried by member d (or Nullable<> of that type if necessary) whenever b happens to be null. When b happens to be non-null, you get the same as b.c.d which may fail if b.c is null.

But a2 is quite different. It will always blow up if b is null, because then the parenthesis (b?.c) will be a null reference, and the next . operator will lead to NullReferenceException. (I am assuming here that c has a reference-type at compile-time.)

So do not think there is a kind of "left-associativity" that makes b?.c.d equivalent to (b?.c).d!

You can find a link to the preliminary C# Language Specification in this answer in another thread; they mention Null-conditional operator as an unary operator in § 7.7.1.

Title: Null-Conditional Operator

Body:
Note that:

var a1 = b?.c.d;

is entirely different from:

var a2 = (b?.c).d;

It is not very easy to explain in short how the unary operator ?. works (yes, unary!). But the idea is that the rest of the "chain" of "operations" is skipped if the expression before ?. is null.

So for a1, you get a null of the compile-time type carried by member d (or Nullable<> of that type if necessary) whenever b happens to be null. When b happens to be non-null, you get the same as b.c.d which may fail if b.c is null.

But a2 is quite different. It will always blow up if b is null, because then the parenthesis (b?.c) will be a null reference, and the next . operator will lead to NullReferenceException. (I am assuming here that c has a reference-type at compile-time.)

So do not think there is a kind of "left-associativity" that makes b?.c.d equivalent to (b?.c).d!

You can find a link to the preliminary C# Language Specification in this answer in another thread; they mention Null-conditional operator as an unary operator in § 7.7.1.


问:
difference between composer install and composer install -o
Can you help me to find the difference between composer install and composer install -o.

Normally composer install -o generate an optimized autoloder file, but when i generates it it was like the other file with composer install.

my classmapfile have many path but the result of composer install -o and composer install steel the same can you explain this for me ?
can you help me ?

答:
You are on the right track: The -o option creates an "optimized" autoloader that essentially is a classmap for every class that otherwise would be loaded through PSR-0 or PSR-4. Composer will scan all directories that are mentioned for PSR-0 and PSR-4 just like it would always to with classmap entries.

This might already answer your question: If your project only has a classmap entry and nothing else, there is no difference in the result.

Note that it is not the best idea to prematurely optimize the autoloading by forcing the classmap if you could also use one of the PSR schemes. Using only the classmap will hinder development because every time a new class is created, you'd have to dump the autoloader with that new entry. Also note that creating huge classmaps might actually be slower than PSR-based class loading, because you trade code execution time for allocated memory, and at some point allocating memory for all classes in every request even if they are not being used will be slower than executing PSR autoloading. You'd have to measure your individual application performance with both a normal and an optimized autoloader to decide which one is actually better.

More info in the docs


问:
How to join multiple columns with only one foreign key using linq
hello stackoverflow community, thats my first question on stack over flow. Thanks for help in advance.
Please help to join 2 tables where one table have list of specialties with thier ids as primary key and second table have 3 columns contains ids of specialties as foreign keys.

that's my code

```<code>var q = (from u in db.Providers
                         join v in db.PracticeSpeciality
                         on new { p1 = u.prSpecId1, p2 = u.prSpecId2, p3 = u.prSpecId3 }
                         equals new { p1 = v.pracSpecId, p2 = v.pracSpecId, p3 = v.pracSpecId }
                         where (u.prId == pc.stprId)
                         select new
                         {
                             u.prFname,
                             u.prLname,
                             u.prMI,
                             u.prTitle,
                             v.
                         }).FirstOrDefault();
</code>```

答:
If you want to return the data of specialists for a provider this will work.</p>

```<code>var q = (from prov in providers
          join esp1 in praEspec on prov.prSpecId1 equals esp1.pracSpecId
          join esp2 in praEspec on prov.prSpecId2 equals esp2.pracSpecId
          join esp3 in praEspec on prov.prSpecId3 equals esp3.pracSpecId
          where prov.prId == pc.stprId
          select new
          {
             esp1,
             esp2,
             esp3
          }).FirstOrDefault();
</code>```

Body:
hello stackoverflow community, thats my first question on stack over flow. Thanks for help in advance.
Please help to join 2 tables where one table have list of specialties with thier ids as primary key and second table have 3 columns contains ids of specialties as foreign keys.

that's my code

var q = (from u in db.Providers
                         join v in db.PracticeSpeciality
                         on new { p1 = u.prSpecId1, p2 = u.prSpecId2, p3 = u.prSpecId3 }
                         equals new { p1 = v.pracSpecId, p2 = v.pracSpecId, p3 = v.pracSpecId }
                         where (u.prId == pc.stprId)
                         select new
                         {
                             u.prFname,
                             u.prLname,
                             u.prMI,
                             u.prTitle,
                             v.
                         }).FirstOrDefault();

Body:
If you want to return the data of specialists for a provider this will work.

var q = (from prov in providers
          join esp1 in praEspec on prov.prSpecId1 equals esp1.pracSpecId
          join esp2 in praEspec on prov.prSpecId2 equals esp2.pracSpecId
          join esp3 in praEspec on prov.prSpecId3 equals esp3.pracSpecId
          where prov.prId == pc.stprId
          select new
          {
             esp1,
             esp2,
             esp3
          }).FirstOrDefault();


问:
CSS: Make the width of auto div to expand till positioned element
I'm facing a problem.

How to make a div expand till the end of the positioned element.

.apple {
  background: #ccc;
  width: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="apple">
  A for aplle
  <br>B for Ball
</div></code>```

Here, the div doesn't accept the width of the position changed element. How to make it work. Thanks.

答:
position: relative moves the element away from its original position (if there are top, bottom, right or left settings), but still reserves the space it originally had, at its original (non-moved) position, which you see in your example. It does NOT change the dimensions of the parent element as opposed to static positioning.

To solve the issue, you can make the a tag an inline-block, erase the relative positioning and use margin-top instead of top. This will be wrapped by the parent:

.apple {
  background: #ccc;
  width: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="apple">
  A for aplle
  <br>B for Ball
</div></code>```

Body:
I'm facing a problem.

How to make a div expand till the end of the positioned element.

.apple {
  background: #ccc;
  width: auto;
}

  A for aplle

B for Ball

Here, the div doesn't accept the width of the position changed element. How to make it work. Thanks.

Body:
position: relative moves the element away from its original position (if there are top, bottom, right or left settings), but still reserves the space it originally had, at its original (non-moved) position, which you see in your example. It does NOT change the dimensions of the parent element as opposed to static positioning.

To solve the issue, you can make the a tag an inline-block, erase the relative positioning and use margin-top instead of top. This will be wrapped by the parent:

.apple {
  background: #ccc;
  width: auto;
}

<div class="apple">
  A for aplle
  <br><a style="display: inline-block; margin-top:20px;">B for Ball</a>
</div>


问:
AngularJS Bootstrap Popover Button Ignoring

We have an Angular Bootstrap popover tooltip that contains some html content and scope variables along with a button inside the popover.

Currently we have a small version running in Plunkr and the popover html is being displayed correctly including all break tags.

The problem seems to occur when we run in locally in Visual Studio where all of the break tags are recognized until the button is rendered, then it seems to be completely ignored and the button gets dropped at the top of the popover:

```<code><div>
    Name: {{ person.fullName }}
    <br />
    Dept: {{ person.deptId }}
    <br />
    Job Desc: {{ person.jobDesc}}
    <br />
    Phone:{{ person.phone}}
    <br />
    One!<br />
    Two!<br />
    Three!<br />
    <input type="button" value="Click Me" class="btn btn-default" ng-click="changeName()">
</code>```

We saw a couple of posts where $sce.trustAsHtml was used and added that as well as data-html='true'

```<code>scope.htmlPopover = $sce.trustAsHtml('./HTML/popoverTemplate.html');
element[0].setAttribute('data-html', 'true');
element[0].setAttribute('uib-popover-template', "htmlPopover");
element[0].setAttribute('popover-append-to-body', 'true');
element[0].setAttribute('popover-trigger', "'click'");
</code>```

This did not solve our problem.

Both the Plunk and our local project are running Angular 1.6.2 and Angular Bootstrap 2.5.0.

Can't figure out why this would work in Plunkr and not in Visual Studio.

Am I missing something?

Thanks.

答:
We had a css in our cshtml page where there was an existing .btn class that was causing a conflict.

Since I think the last css entry wins, I suspect that was causing the issue.

Once we removed that style, the button was displayed correctly.

Thanks.

Title: AngularJS Bootstrap Popover Button Ignoring <BR />

Body:
We have an Angular Bootstrap popover tooltip that contains some html content and scope variables along with a button inside the popover.

Currently we have a small version running in Plunkr and the popover html is being displayed correctly including all break tags.

The problem seems to occur when we run in locally in Visual Studio where all of the break tags are recognized until the button is rendered, then it seems to be completely ignored and the button gets dropped at the top of the popover:

    Name: {{ person.fullName }}

    Dept: {{ person.deptId }}

    Job Desc: {{ person.jobDesc}}

    Phone:{{ person.phone}}

    One!

    Two!

    Three!

    <input type="button" value="Click Me" class="btn btn-default" ng-click="changeName()">

We saw a couple of posts where $sce.trustAsHtml was used and added that as well as data-html='true'

scope.htmlPopover = $sce.trustAsHtml('./HTML/popoverTemplate.html');
element[0].setAttribute('data-html', 'true');
element[0].setAttribute('uib-popover-template', "htmlPopover");
element[0].setAttribute('popover-append-to-body', 'true');
element[0].setAttribute('popover-trigger', "'click'");

This did not solve our problem.

Both the Plunk and our local project are running Angular 1.6.2 and Angular Bootstrap 2.5.0.

Can't figure out why this would work in Plunkr and not in Visual Studio.

Am I missing something?

Thanks.


问:
C# generics: How to specify type constraint and return instance of generic type
In java I can make a method with the following signature:

```<code>public <E extends Form> E makeForm(Class<E> formType) {
    //return new instance of formType
}
</code>```

You pass a class to the method that is constrained, and return an instance of that generic type. This way you can do things like:

```<code>makeForm(SomeForm.class).specificSomeFormMethod();
</code>```

How can I do this in C#? From what I've found so far it's not possible?
I can make the generic type for the form instance OR for the type parameter, but not for both, and I also don't know how to constrain a Type parameter to be only of a specific class.

I'm not quite sure how to label this, so that might be my issue as well. Perhaps I'm overthinking it? I need another person's view!

答:
You can use the new() type constraint which allows calls to the generic type's default constructor.</p>

```<code>public class MakeForm<E> where E : FormType, new()
{
    // Method which returns a new E
    public E MakeForm()
    {
        return new E();   // this works because of the new() constraint
    }
}
</code>```

Body:
In java I can make a method with the following signature:

public <E extends Form> E makeForm(Class<E> formType) {
    //return new instance of formType
}

You pass a class to the method that is constrained, and return an instance of that generic type. This way you can do things like:

makeForm(SomeForm.class).specificSomeFormMethod();

How can I do this in C#? From what I've found so far it's not possible?
I can make the generic type for the form instance OR for the type parameter, but not for both, and I also don't know how to constrain a Type parameter to be only of a specific class.

I'm not quite sure how to label this, so that might be my issue as well. Perhaps I'm overthinking it? I need another person's view!

Body:
You can use the new() type constraint which allows calls to the generic type's default constructor.

public class MakeForm<E> where E : FormType, new()
{
    // Method which returns a new E
    public E MakeForm()
    {
        return new E();   // this works because of the new() constraint
    }
}


问:
recognize users with PHPSESSID and cookies
As far as I know webapps use session_start(); that implicitly create the session cookie PHPSESSID to recognize his users,

but when analysing the outgoing HTTP requests toward differents web applications (yahoo, facebook, gmail, youtube) I didn't see this cookie in the HTTP header but another ones :

sid, ssid, gmail_at, apisid, sapisid   in gmail

datr, lu, c_user, xs, fr   in facebook...

is one of these cookies is the same as PHPSESSID/JSESSID and they rename it ? (I don't think so, they don't have the same length)

is there another way that session_start() and URL Rewriting to distinguish sessions ?

or they create manually the session IDs with setcookie(); ? what is the advantage then ?

答:
You can rename the session cookie and alter the hash algo

Try session_name($newName) to change PHPSESSID.

Or change the cookie value itself with session_id($string)

Also its a server configuration/app behaviour thing. You can safe your cookie to user relation in a file, or in a table.


问:
Inno Setup custom page
I would like to create a custom wizard page after the page where you select the install location.

I have seen how to create custom pages and add them to the wizard in the InitializeWizard procedure.

My problem is that when I create a custom page the default page for install location selection does not appear any more.

What options do I have to keep the default page(install location selection) and also add a my new custom page?

Thanks

My code looks something like this (CodeClasses.iss example provided by inno ):

```<code>procedure CreateTheWizardPages;
var
  Page: TWizardPage;
  Button, FormButton: TButton;
  CheckBox: TCheckBox;
  Edit: TEdit;
  PasswordEdit: TPasswordEdit;
  Memo: TMemo;
  Lbl, ProgressBarLabel: TLabel;
  ComboBox: TComboBox;
  ListBox: TListBox;
  StaticText: TNewStaticText;
  ProgressBar: TNewProgressBar;
  CheckListBox, CheckListBox2: TNewCheckListBox;
  FolderTreeView: TFolderTreeView;
  BitmapImage, BitmapImage2, BitmapImage3: TBitmapImage;
  BitmapFileName: String;
  RichEditViewer: TRichEditViewer;
begin
  { TButton and others }

  Page := CreateCustomPage(wpWelcome, 'Custom wizard page controls', 'TButton and others');

  Button := TButton.Create(Page);
  Button.Width := ScaleX(75);
  Button.Height := ScaleY(23);
  Button.Caption := 'TButton';
  Button.OnClick := @ButtonOnClick;
  Button.Parent := Page.Surface;

  CheckBox := TCheckBox.Create(Page);
  CheckBox.Top := Button.Top + Button.Height + ScaleY(8);
  CheckBox.Width := Page.SurfaceWidth;
  CheckBox.Height := ScaleY(17);
  CheckBox.Caption := 'TCheckBox';
  CheckBox.Checked := True;
  CheckBox.Parent := Page.Surface;

  Edit := TEdit.Create(Page);
  Edit.Top := CheckBox.Top + CheckBox.Height + ScaleY(8);
  Edit.Width := Page.SurfaceWidth div 2 - ScaleX(8);
  Edit.Text := 'TEdit';
  Edit.Parent := Page.Surface;

  PasswordEdit := TPasswordEdit.Create(Page);
  PasswordEdit.Left := Page.SurfaceWidth - Edit.Width;
  PasswordEdit.Top := CheckBox.Top + CheckBox.Height + ScaleY(8);
  PasswordEdit.Width := Edit.Width;
  PasswordEdit.Text := 'TPasswordEdit';
  PasswordEdit.Parent := Page.Surface;

  Memo := TMemo.Create(Page);
  Memo.Top := Edit.Top + Edit.Height + ScaleY(8);
  Memo.Width := Page.SurfaceWidth;
  Memo.Height := ScaleY(89);
  Memo.ScrollBars := ssVertical;
  Memo.Text := 'TMemo';
  Memo.Parent := Page.Surface;

  Lbl := TLabel.Create(Page);
  Lbl.Top := Memo.Top + Memo.Height + ScaleY(8);
  Lbl.Caption := 'TLabel';
  Lbl.AutoSize := True;
  Lbl.Parent := Page.Surface;

  FormButton := TButton.Create(Page);
  FormButton.Top := Lbl.Top + Lbl.Height + ScaleY(8);
  FormButton.Width := ScaleX(75);
  FormButton.Height := ScaleY(23);
  FormButton.Caption := 'TSetupForm';
  FormButton.OnClick := @FormButtonOnClick;
  FormButton.Parent := Page.Surface;
</code>```

......

```<code>procedure InitializeWizard();
var
  AboutButton, CancelButton: TButton;
  URLLabel: TNewStaticText;
  BackgroundBitmapImage: TBitmapImage;
  BackgroundBitmapText: TNewStaticText;
begin
  { Custom wizard pages }

  CreateTheWizardPages;

  { Other custom controls }

  CancelButton := WizardForm.CancelButton;

  AboutButton := TButton.Create(WizardForm);
  AboutButton.Left := WizardForm.ClientWidth - CancelButton.Left - CancelButton.Width;
  AboutButton.Top := CancelButton.Top;
  AboutButton.Width := CancelButton.Width;
  AboutButton.Height := CancelButton.Height;
  AboutButton.Caption := '&About...';
  AboutButton.OnClick := @AboutButtonOnClick;
  AboutButton.Parent := WizardForm;

  URLLabel := TNewStaticText.Create(WizardForm);
  URLLabel.Caption := 'www.innosetup.com';
  URLLabel.Cursor := crHand;
  URLLabel.OnClick := @URLLabelOnClick;
  URLLabel.Parent := WizardForm;
  { Alter Font *after* setting Parent so the correct defaults are inherited first }
  URLLabel.Font.Style := URLLabel.Font.Style + [fsUnderline];
  URLLabel.Font.Color := clBlue;
  URLLabel.Top := AboutButton.Top + AboutButton.Height - URLLabel.Height - 2;
  URLLabel.Left := AboutButton.Left + AboutButton.Width + ScaleX(20);

  BackgroundBitmapImage := TBitmapImage.Create(MainForm);
  BackgroundBitmapImage.Left := 50;
  BackgroundBitmapImage.Top := 90;
  BackgroundBitmapImage.AutoSize := True;
  BackgroundBitmapImage.Bitmap := WizardForm.WizardBitmapImage.Bitmap;
  BackgroundBitmapImage.Parent := MainForm;

  BackgroundBitmapText := TNewStaticText.Create(MainForm);
  BackgroundBitmapText.Left := BackgroundBitmapImage.Left;
  BackgroundBitmapText.Top := BackgroundBitmapImage.Top + BackgroundBitmapImage.Height + ScaleY(8);
  BackgroundBitmapText.Caption := 'TBitmapImage';
  BackgroundBitmapText.Parent := MainForm;
end;
</code>```

答:
The first parameter  wpWelcome in this case, specifies after witch page our custom page is displayed.

```<code>Page := CreateCustomPage(wpWelcome, 'Custom wizard page controls', 'TButton and others');
</code>```

Title: Inno Setup custom page

Body:
I would like to create a custom wizard page after the page where you select the install location.

I have seen how to create custom pages and add them to the wizard in the InitializeWizard procedure.

My problem is that when I create a custom page the default page for install location selection does not appear any more.

What options do I have to keep the default page(install location selection) and also add a my new custom page?

Thanks

My code looks something like this (CodeClasses.iss example provided by inno ):

procedure CreateTheWizardPages;
var
  Page: TWizardPage;
  Button, FormButton: TButton;
  CheckBox: TCheckBox;
  Edit: TEdit;
  PasswordEdit: TPasswordEdit;
  Memo: TMemo;
  Lbl, ProgressBarLabel: TLabel;
  ComboBox: TComboBox;
  ListBox: TListBox;
  StaticText: TNewStaticText;
  ProgressBar: TNewProgressBar;
  CheckListBox, CheckListBox2: TNewCheckListBox;
  FolderTreeView: TFolderTreeView;
  BitmapImage, BitmapImage2, BitmapImage3: TBitmapImage;
  BitmapFileName: String;
  RichEditViewer: TRichEditViewer;
begin
  { TButton and others }

  Page := CreateCustomPage(wpWelcome, 'Custom wizard page controls', 'TButton and others');

  Button := TButton.Create(Page);
  Button.Width := ScaleX(75);
  Button.Height := ScaleY(23);
  Button.Caption := 'TButton';
  Button.OnClick := @ButtonOnClick;
  Button.Parent := Page.Surface;

  CheckBox := TCheckBox.Create(Page);
  CheckBox.Top := Button.Top + Button.Height + ScaleY(8);
  CheckBox.Width := Page.SurfaceWidth;
  CheckBox.Height := ScaleY(17);
  CheckBox.Caption := 'TCheckBox';
  CheckBox.Checked := True;
  CheckBox.Parent := Page.Surface;

  Edit := TEdit.Create(Page);
  Edit.Top := CheckBox.Top + CheckBox.Height + ScaleY(8);
  Edit.Width := Page.SurfaceWidth div 2 - ScaleX(8);
  Edit.Text := 'TEdit';
  Edit.Parent := Page.Surface;

  PasswordEdit := TPasswordEdit.Create(Page);
  PasswordEdit.Left := Page.SurfaceWidth - Edit.Width;
  PasswordEdit.Top := CheckBox.Top + CheckBox.Height + ScaleY(8);
  PasswordEdit.Width := Edit.Width;
  PasswordEdit.Text := 'TPasswordEdit';
  PasswordEdit.Parent := Page.Surface;

  Memo := TMemo.Create(Page);
  Memo.Top := Edit.Top + Edit.Height + ScaleY(8);
  Memo.Width := Page.SurfaceWidth;
  Memo.Height := ScaleY(89);
  Memo.ScrollBars := ssVertical;
  Memo.Text := 'TMemo';
  Memo.Parent := Page.Surface;

  Lbl := TLabel.Create(Page);
  Lbl.Top := Memo.Top + Memo.Height + ScaleY(8);
  Lbl.Caption := 'TLabel';
  Lbl.AutoSize := True;
  Lbl.Parent := Page.Surface;

  FormButton := TButton.Create(Page);
  FormButton.Top := Lbl.Top + Lbl.Height + ScaleY(8);
  FormButton.Width := ScaleX(75);
  FormButton.Height := ScaleY(23);
  FormButton.Caption := 'TSetupForm';
  FormButton.OnClick := @FormButtonOnClick;
  FormButton.Parent := Page.Surface;

......

procedure InitializeWizard();
var
  AboutButton, CancelButton: TButton;
  URLLabel: TNewStaticText;
  BackgroundBitmapImage: TBitmapImage;
  BackgroundBitmapText: TNewStaticText;
begin
  { Custom wizard pages }

  CreateTheWizardPages;

  { Other custom controls }

  CancelButton := WizardForm.CancelButton;

  AboutButton := TButton.Create(WizardForm);
  AboutButton.Left := WizardForm.ClientWidth - CancelButton.Left - CancelButton.Width;
  AboutButton.Top := CancelButton.Top;
  AboutButton.Width := CancelButton.Width;
  AboutButton.Height := CancelButton.Height;
  AboutButton.Caption := '&About...';
  AboutButton.OnClick := @AboutButtonOnClick;
  AboutButton.Parent := WizardForm;

  URLLabel := TNewStaticText.Create(WizardForm);
  URLLabel.Caption := 'www.innosetup.com';
  URLLabel.Cursor := crHand;
  URLLabel.OnClick := @URLLabelOnClick;
  URLLabel.Parent := WizardForm;
  { Alter Font *after* setting Parent so the correct defaults are inherited first }
  URLLabel.Font.Style := URLLabel.Font.Style + [fsUnderline];
  URLLabel.Font.Color := clBlue;
  URLLabel.Top := AboutButton.Top + AboutButton.Height - URLLabel.Height - 2;
  URLLabel.Left := AboutButton.Left + AboutButton.Width + ScaleX(20);

  BackgroundBitmapImage := TBitmapImage.Create(MainForm);
  BackgroundBitmapImage.Left := 50;
  BackgroundBitmapImage.Top := 90;
  BackgroundBitmapImage.AutoSize := True;
  BackgroundBitmapImage.Bitmap := WizardForm.WizardBitmapImage.Bitmap;
  BackgroundBitmapImage.Parent := MainForm;

  BackgroundBitmapText := TNewStaticText.Create(MainForm);
  BackgroundBitmapText.Left := BackgroundBitmapImage.Left;
  BackgroundBitmapText.Top := BackgroundBitmapImage.Top + BackgroundBitmapImage.Height + ScaleY(8);
  BackgroundBitmapText.Caption := 'TBitmapImage';
  BackgroundBitmapText.Parent := MainForm;
end;

Body:
The first parameter  wpWelcome in this case, specifies after witch page our custom page is displayed.

Page := CreateCustomPage(wpWelcome, 'Custom wizard page controls', 'TButton and others');