问:
Host multiple Symfony projects on the same domain
I have one domain and i need to host many symfony 3 projects in differents folder. For example :

www.domain.com/project1
www.domain.com/project2
...

My current nginx conf is :

```<code>server {
    server_name domain.fr www.domain.fr;
    root /var/proximiteclient/www/web;

    location / {
        # try to serve file directly, fallback to app.php
        try_files $uri /app.php$is_args$args;
    }

    # PROD
    location ~ ^/app\.php(/|$) {
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        # Prevents URIs that include the front controller. This will 404:
        # http://domain.tld/app.php/some-path
        # Remove the internal directive to allow URIs like this
        #internal;
    }

    # return 404 for all other php files not matching the front controller
    # this prevents access to other php files you don't want to be accessible.
    location ~ \.php$ {
      return 404;
    }

    error_log /var/log/nginx/domain_error.log;
    access_log /var/log/nginx/domain_access.log;

    listen 80; # managed by Certbot

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/domain.fr/fullchain.pem; # manag$
    ssl_certificate_key /etc/letsencrypt/live/domain.fr/privkey.pem; # man$
    ssl_session_cache shared:le_nginx_SSL:1m; # managed by Certbot
    ssl_session_timeout 1440m; # managed by Certbot
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # managed by Certbot
    ssl_prefer_server_ciphers on; # managed by Certbot

    ssl_ciphers "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE$

    #Redirect non-https traffic to https
    if ($scheme != "https") {
         return 301 https://$host$request_uri;
    } # managed by Certbot
}
</code>```

Sorry, i can't put in text mode it didn't work :(

Thansk very much !

答:
A simple way to do this is to duplicate your server blocks and specify a different listening port and root path.

project 1 url: http://www.domain.fr

```<code>server {
  listen 80;
  server_name domain.fr www.domain.fr;
  root /var/project1/www/web;
  ...
}
</code>```

project 2 url: http://www.domain.fr:801

```<code>server {
  listen 801;
  server_name domain.fr www.domain.fr;
  root /var/project2/www/web;
  ...
}
</code>```

Body:
I have one domain and i need to host many symfony 3 projects in differents folder. For example :

www.domain.com/project1
www.domain.com/project2
...

My current nginx conf is :

server {
    server_name domain.fr www.domain.fr;
    root /var/proximiteclient/www/web;

    location / {
        # try to serve file directly, fallback to app.php
        try_files $uri /app.php$is_args$args;
    }

    # PROD
    location ~ ^/app\.php(/|$) {
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        # Prevents URIs that include the front controller. This will 404:
        # http://domain.tld/app.php/some-path
        # Remove the internal directive to allow URIs like this
        #internal;
    }

    # return 404 for all other php files not matching the front controller
    # this prevents access to other php files you don't want to be accessible.
    location ~ \.php$ {
      return 404;
    }

    error_log /var/log/nginx/domain_error.log;
    access_log /var/log/nginx/domain_access.log;

    listen 80; # managed by Certbot

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/domain.fr/fullchain.pem; # manag$
    ssl_certificate_key /etc/letsencrypt/live/domain.fr/privkey.pem; # man$
    ssl_session_cache shared:le_nginx_SSL:1m; # managed by Certbot
    ssl_session_timeout 1440m; # managed by Certbot
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # managed by Certbot
    ssl_prefer_server_ciphers on; # managed by Certbot

    ssl_ciphers "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE$

    #Redirect non-https traffic to https
    if ($scheme != "https") {
         return 301 https://$host$request_uri;
    } # managed by Certbot
}

Sorry, i can't put in text mode it didn't work :(

Thansk very much !

Body:
A simple way to do this is to duplicate your server blocks and specify a different listening port and root path.

project 1 url: http://www.domain.fr

server {
  listen 80;
  server_name domain.fr www.domain.fr;
  root /var/project1/www/web;
  ...
}

project 2 url: http://www.domain.fr:801

server {
  listen 801;
  server_name domain.fr www.domain.fr;
  root /var/project2/www/web;
  ...
}


来源: stackexchange

问:
How do I sanitize a dynamic table name using Dapper?
I'm new to Dapper, and writing a query that will pull from a provided schema and table, along with using dynamic ordering and filtering.

Dapper make dynamic parameters very simple, however, I'm not sure how to do this with tables in the order by and where clauses.  Here's my method below, and I see the issues with SQL injection:

```<code>    public GridData GetGridData(string schema, string table, TableDataParameters tableDataParameters)
    {
        using (var dbConnection = VarConnection)
        {
            dbConnection.Open();

            if (!this.TableExists(dbConnection, schema, table))
            {
                throw new ItemNotFoundException($"Could not locate table {schema}.{table}.");
            }

            string orderyByClause = string.Join(",", tableDataParameters.SortModel.Select(s => $"[{s.ColId}] {(s.Sort.ToLower() == "asc" ? "asc" : "desc")}"));

            var parameters = new DynamicParameters();

            string whereClause;
            if (tableDataParameters.FilterModel == null || !tableDataParameters.FilterModel.Any())
            {
                whereClause = "1=1";
            }
            else
            {
                whereClause = string.Join(" AND ", tableDataParameters.FilterModel.Select((fm, i) =>
                {
                    string whereParam = $"whereParam{i}";
                    parameters.Add(whereParam, fm.Filter);

                    if (fm.Operation == "startsWith")
                    {
                        return $"[{fm.Column}] LIKE @{whereParam} + '%'";
                    }
                    throw new InvalidOperationException($"Unsupported filter operation '{fm.Operation}'");
                }));
            }

            var query = $"SELECT COUNT(1) [total] " +
                        $"FROM [{schema}].[{table}] " +
                        $"WHERE {whereClause} " +
                        $"SELECT * " +
                        $"FROM [{schema}].[{table}] " +
                        $"WHERE {whereClause} " +
                        $"ORDER BY {orderyByClause} " +
                        $"OFFSET {tableDataParameters.StartIndex.Value} ROWS " +
                        $"FETCH NEXT {tableDataParameters.StopIndex.Value - tableDataParameters.StartIndex.Value} ROWS ONLY";
            int total = 0;
            using (var reader = dbConnection.ExecuteReader(query, parameters))
            {
                //  First batch, it's the count
                if (reader.Read())
                {
                    total = reader.GetInt32(0);
                }

                var gridColumns = new List<GridColumn>();
                var gridRows = new List<string[]>();
                if (reader.NextResult() && reader.Read())
                {
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        string key = reader.GetName(i);
                        gridColumns.Add(new GridColumn(key, key, null, ""));
                    }

                    var items = new object[reader.FieldCount];
                    reader.GetValues(items);
                    gridRows.Add(items.Select(i => i.ToString()).ToArray());
                }

                while (reader.Read())
                {
                    var items = new object[reader.FieldCount];
                    reader.GetValues(items);
                    gridRows.Add(items.Select(i => i.ToString()).ToArray());
                }

                return new GridData(tableDataParameters.StartIndex.Value, tableDataParameters.StopIndex.Value, total, gridRows.Count(), gridColumns.ToArray(), gridRows.ToArray());
            }
        }
    }
</code>```

Should I use something like DbCommandBuilder.QuoteIdentifier, https://msdn.microsoft.com/en-us/library/system.data.common.dbcommandbuilder.quoteidentifier(v=vs.110).aspx
in this case?  That doesn't seem like it would help so much here.

Thanks!

答:
Dynamic parameters is an oxymoron! Dapper makes parameters easy, but you can't paramaterize table and column names. This is a restriction of SQL, not dapper. If you really want to do this, you have to use dynamic sql and string methods, and you're on your own as regards SQL injection.

You will be happier and live longer if you don't do this. It's just a bad road. You're not adding much value, and you're potentially introducing a load of problems and limitations.

It looks like you're writing an app to browse a database. Good tools already exist for this!

ContentLicense: CC BY-SA 3.0

Body:
I'm new to Dapper, and writing a query that will pull from a provided schema and table, along with using dynamic ordering and filtering.

Dapper make dynamic parameters very simple, however, I'm not sure how to do this with tables in the order by and where clauses.  Here's my method below, and I see the issues with SQL injection:

    public GridData GetGridData(string schema, string table, TableDataParameters tableDataParameters)
    {
        using (var dbConnection = VarConnection)
        {
            dbConnection.Open();

            if (!this.TableExists(dbConnection, schema, table))
            {
                throw new ItemNotFoundException($"Could not locate table {schema}.{table}.");
            }

            string orderyByClause = string.Join(",", tableDataParameters.SortModel.Select(s => $"[{s.ColId}] {(s.Sort.ToLower() == "asc" ? "asc" : "desc")}"));

            var parameters = new DynamicParameters();

            string whereClause;
            if (tableDataParameters.FilterModel == null || !tableDataParameters.FilterModel.Any())
            {
                whereClause = "1=1";
            }
            else
            {
                whereClause = string.Join(" AND ", tableDataParameters.FilterModel.Select((fm, i) =>
                {
                    string whereParam = $"whereParam{i}";
                    parameters.Add(whereParam, fm.Filter);

                    if (fm.Operation == "startsWith")
                    {
                        return $"[{fm.Column}] LIKE @{whereParam} + '%'";
                    }
                    throw new InvalidOperationException($"Unsupported filter operation '{fm.Operation}'");
                }));
            }

            var query = $"SELECT COUNT(1) [total] " +
                        $"FROM [{schema}].[{table}] " +
                        $"WHERE {whereClause} " +
                        $"SELECT * " +
                        $"FROM [{schema}].[{table}] " +
                        $"WHERE {whereClause} " +
                        $"ORDER BY {orderyByClause} " +
                        $"OFFSET {tableDataParameters.StartIndex.Value} ROWS " +
                        $"FETCH NEXT {tableDataParameters.StopIndex.Value - tableDataParameters.StartIndex.Value} ROWS ONLY";
            int total = 0;
            using (var reader = dbConnection.ExecuteReader(query, parameters))
            {
                //  First batch, it's the count
                if (reader.Read())
                {
                    total = reader.GetInt32(0);
                }

                var gridColumns = new List<GridColumn>();
                var gridRows = new List<string[]>();
                if (reader.NextResult() && reader.Read())
                {
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        string key = reader.GetName(i);
                        gridColumns.Add(new GridColumn(key, key, null, ""));
                    }

                    var items = new object[reader.FieldCount];
                    reader.GetValues(items);
                    gridRows.Add(items.Select(i => i.ToString()).ToArray());
                }

                while (reader.Read())
                {
                    var items = new object[reader.FieldCount];
                    reader.GetValues(items);
                    gridRows.Add(items.Select(i => i.ToString()).ToArray());
                }

                return new GridData(tableDataParameters.StartIndex.Value, tableDataParameters.StopIndex.Value, total, gridRows.Count(), gridColumns.ToArray(), gridRows.ToArray());
            }
        }
    }

Should I use something like DbCommandBuilder.QuoteIdentifier, https://msdn.microsoft.com/en-us/library/system.data.common.dbcommandbuilder.quoteidentifier(v=vs.110).aspx
in this case?  That doesn't seem like it would help so much here.

Thanks!


问:
Changing Spaces Per Tab in PHPStorm
I have a SCSS file I am currently working on.  The indentation is 4 spaces, but for some reason PHPStorm only moves the cursor 2 spaces every time I tab.  Is there a way to change this?  Strange thing is I have other files in the project (mostly JS) and they are tabbed 4 spaces.</p>

答: You can set the tab and indent for each language you code in.

Title: Changing Spaces Per Tab in PHPStorm


问:
Spark - Exception in task
Using Spark, I am analysing a YouTube dataset to find the top five categories with the maximum number of videos uploaded.

Load the data:

```<code>val textRDD = sc.textFile("hdfs://quickstart.cloudera:8020/user/cloudera/spark/youtubedata.txt")
</code>```

First Line of the RDD

```<code>textRDD.first
res268: String = QuRYeRnAuXM    EvilSquirrelPictures    1135    Pets & Animals  252 1075    4.96    46  86  gFa1YMEJFag nRcovJn9xHg 3TYqkBJ9YRk rSJ8QZWBegU 0TZqX5MbXMA UEvVksP91kg ZTopArY7Nbg 0RViGi2Rne8 HT_QlOJbDpg YZev1imoxX8 8qQrrfUTmh0 zQ83d_D2MGs u6_DQQjLsAw 73Wz9CQFDtE
</code>```

Created a RDD by extracting the 4th column

```<code>val countRDD = textRDD.map( line => line.split("\t")(3))
</code>```

Created a pair

```<code>val pairRDD = countRDD.map(x => (x,1))
</code>```

Till here everything was working fine.
The final step is to retrieve the top 5 from the list

```<code>val result = pairRDD.reduceByKey(_ + _).sortByKey(false).take(5)
</code>```

The above step is returning the below error:

```<code>17/06/07 07:55:59 ERROR executor.Executor: Exception in task 0.0 in stage 262.0 (TID 245) java.lang.ArrayIndexOutOfBoundsException: 3
at $line486.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1.apply(<console>:32)
at $line486.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1.apply(<console>:32)
at scala.collection.Iterator$$anon$11.next(Iterator.scala:328)
.
.
.
</code>```

Where could I have gone wrong?

答:
The error is not in the final line where you perform take but in the following line

```<code>val countRDD = textRDD.map( line => line.split("\t")(3))
</code>```

When a file is read using textFile api, all the lines are converted to string, thus the \t (tab) is not preserved. And you cannot split using "\t"

Above statement is just a transformation so no error was thrown but when take, an action, was performed error was thrown.

You will have to either edit the input file by inserting splitting characters (Strings) on sides of expected string for K or you will have to find appropriate method for splitting the lines read.

Title: Spark - Exception in task

Body:
Using Spark, I am analysing a YouTube dataset to find the top five categories with the maximum number of videos uploaded.

Load the data:

val textRDD = sc.textFile("hdfs://quickstart.cloudera:8020/user/cloudera/spark/youtubedata.txt")

First Line of the RDD

textRDD.first
res268: String = QuRYeRnAuXM    EvilSquirrelPictures    1135    Pets & Animals  252 1075    4.96    46  86  gFa1YMEJFag nRcovJn9xHg 3TYqkBJ9YRk rSJ8QZWBegU 0TZqX5MbXMA UEvVksP91kg ZTopArY7Nbg 0RViGi2Rne8 HT_QlOJbDpg YZev1imoxX8 8qQrrfUTmh0 zQ83d_D2MGs u6_DQQjLsAw 73Wz9CQFDtE

Created a RDD by extracting the 4th column

val countRDD = textRDD.map( line => line.split("\t")(3))

Created a pair

val pairRDD = countRDD.map(x => (x,1))

Till here everything was working fine.
The final step is to retrieve the top 5 from the list

val result = pairRDD.reduceByKey(_ + _).sortByKey(false).take(5)

The above step is returning the below error:

17/06/07 07:55:59 ERROR executor.Executor: Exception in task 0.0 in stage 262.0 (TID 245) java.lang.ArrayIndexOutOfBoundsException: 3
at $line486.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1.apply(<console>:32)
at $line486.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1.apply(<console>:32)
at scala.collection.Iterator$$anon$11.next(Iterator.scala:328)
.
.
.

Where could I have gone wrong?

Body:
The error is not in the final line where you perform take but in the following line

val countRDD = textRDD.map( line => line.split("\t")(3))

When a file is read using textFile api, all the lines are converted to string, thus the \t (tab) is not preserved. And you cannot split using "\t"

Above statement is just a transformation so no error was thrown but when take, an action, was performed error was thrown.

You will have to either edit the input file by inserting splitting characters (Strings) on sides of expected string for K or you will have to find appropriate method for splitting the lines read.


问:
How to get random value from specific ranges of dictionary content
If this way I can get random value from given range:

```<code> int r = ran.Next(1, 4);
 string v;
 if (dict.TryGetValue(r, out v))
 {
    ///...
 }
</code>```

how to properly get random value of <int, string> dictionary content from specific range, for example only from 4 to 6 and 1 and 2 and avoid look for 3:

```<code>Dictionary<int, string> dict = new Dictionary<int, string>()
{
    { 1, "word1" },
    { 2, "word2" },
    { 3, "word3" },
    { 4, "word4" },
    { 5, "word5" },
    { 6, "word6" }
};
</code>```

答:
You can collect all the values which can be taken and then choose random one from them:</p>

```<code>   private static Random s_Random = new Random();

   ...

   var values = dict
      .Where(pair => pair.Key >= 4 && pair.Key <= 6 || // conditions on key
                     pair.Key >= 1 && pair.Key <= 2)
      .ToArray();

   var result = values[s_Random.Next(values.Length)];
</code>```

Body:
If this way I can get random value from given range:

 int r = ran.Next(1, 4);
 string v;
 if (dict.TryGetValue(r, out v))
 {
    ///...
 }

how to properly get random value of <int, string> dictionary content from specific range, for example only from 4 to 6 and 1 and 2 and avoid look for 3:

Dictionary<int, string> dict = new Dictionary<int, string>()
{
    { 1, "word1" },
    { 2, "word2" },
    { 3, "word3" },
    { 4, "word4" },
    { 5, "word5" },
    { 6, "word6" }
};

Body:
You can collect all the values which can be taken and then choose random one from them:

   private static Random s_Random = new Random();

   ...

   var values = dict
      .Where(pair => pair.Key >= 4 && pair.Key <= 6 || // conditions on key
                     pair.Key >= 1 && pair.Key <= 2)
      .ToArray();

   var result = values[s_Random.Next(values.Length)];


问:
Copy/Move cells by id
How can I move values from Worksheet 1 column B to Worksheet 2 column B, based on a unique ID in column A? Some IDs are duplicates and some values are empty, I would like to ignore empty values.

Worksheet 1:

```<code>A      B
23452  value1
23452
53252  value2
67452  value3
</code>```

Worksheet 2:

```<code>A      B
53252
23452
67452
</code>```

Wanted Result (Worksheet 2):

```<code>A      B
53252  value2
23452  value1
67452  value3
</code>```

What I have tried

Merging data in Open/Libreoffice calc - could not figure this out for my specific requirements.

答:
You can try this simple INDEX-MATCH formula,

In column B of sheet2,

```<code>=INDEX('Sheet1'.A:B;MATCH(A1;'Sheet1'.A:A;0);2)
</code>```

Title: Copy/Move cells by id

Body:
How can I move values from Worksheet 1 column B to Worksheet 2 column B, based on a unique ID in column A? Some IDs are duplicates and some values are empty, I would like to ignore empty values.

Worksheet 1:

A      B
23452  value1
23452
53252  value2
67452  value3

Worksheet 2:

A      B
53252
23452
67452

Wanted Result (Worksheet 2):

A      B
53252  value2
23452  value1
67452  value3

What I have tried

Merging data in Open/Libreoffice calc - could not figure this out for my specific requirements.

Body:
You can try this simple INDEX-MATCH formula,

In column B of sheet2,

=INDEX('Sheet1'.A:B;MATCH(A1;'Sheet1'.A:A;0);2)


问:
How to slide in text and push another text to the right (CSS)
I'm trying to make the > move in from the side and push the "Lorem" to the right. I'm trying to make it within my CSS.

答:
try something like :
HTML CODE :

```<code><p id ="lo"> > Lorem </p>
<span id="ipsum"> Ipsum </span>
</code>```

CSS :

```<code>#lo {
margin-left : 10px;
}
</code>```

Body:
try something like :
HTML CODE :

<p id ="lo"> > Lorem </p>
<span id="ipsum"> Ipsum </span>

CSS :

#lo {
margin-left : 10px;
}


问:
Rename property of an object inside array
This is my input JSON

```<code>{
"uuid":123,
"description": [
    {
        "car_name":"Toyota",
        "saleDate":"23 May 2017"
    }
  ]
}
</code>```

Expected output:

```<code>{
"uuid":123,
"description": [
    {
        "name":"Toyota",
        "saleDate":"23 May 2017"
    }
  ]
}
</code>```

Rule : .description[]|={name:.car_name,saleDate}

I am able to achieve the desired result with this rule. However, is there a way I can rename the 'car_name' property to 'name' and also not mention all the other properties ( in this case, 'saleDate') in the rule. I might end up having 50+ properties inside the object and I do not want to mention all of them in the rule.

There can be more than one object in the array.

答:
This seems to work while preserving the order.

```<code>jq '.description[] |= with_entries( .key |= gsub("car_name"; "name") )'
</code>```

The jq manual explains what with_entries does.

Credit goes to an answer to a similar question by peak.

Body:
This is my input JSON

{
"uuid":123,
"description": [
    {
        "car_name":"Toyota",
        "saleDate":"23 May 2017"
    }
  ]
}

Expected output:

{
"uuid":123,
"description": [
    {
        "name":"Toyota",
        "saleDate":"23 May 2017"
    }
  ]
}

Rule : .description[]|={name:.car_name,saleDate}

I am able to achieve the desired result with this rule. However, is there a way I can rename the 'car_name' property to 'name' and also not mention all the other properties ( in this case, 'saleDate') in the rule. I might end up having 50+ properties inside the object and I do not want to mention all of them in the rule.

There can be more than one object in the array.

Body:
This seems to work while preserving the order.

jq '.description[] |= with_entries( .key |= gsub("car_name"; "name") )'

The jq manual explains what with_entries does.

Credit goes to an answer to a similar question by peak.


问:
fb:visible-to-connection not working in IE7 standards
I have the following code in a Facebook application:

```<code>    <table width="520" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td style="background:url(comp-scd-like.jpg) no-repeat;height:380px;width:260px;">
<fb:visible-to-connection><a href="competitions/facebook.htm"><img src="comp-scd-lg.jpg"  border="0" style="display:block;" /></a></fb:visible-to-connection></td>
  </tr>
</table>
</code>```

In IE8, Firefox, Chrome etc it works fine, however in IE7 Standards, using the developer mode, it doesn't show any content whatsoever.

Any ideas why this may be?

答:
More of a caution than a fix.

Ensure you are not an administrator of your page as being one fires both visible-to-connection and the else.

Very annoying!

ContentLicense: CC BY-SA 2.5

Body:
I have the following code in a Facebook application:

<fb:visible-to-connection></fb:visible-to-connection>

In IE8, Firefox, Chrome etc it works fine, however in IE7 Standards, using the developer mode, it doesn't show any content whatsoever.

Any ideas why this may be?


问:
Xamarin.Forms change UI language at runtime (XAML)
I am using Strings.resx, Strings.de.resx, etc. to localize Xamarin.Forms app.
I need to be able to change interface language at run time, and it (allmost) works.

Xamarin generates static class Strings in namespace MyProject.Resources from resource files, and I use those values to display strings on UI.
When doing it from code, it works flawlessly:

```<code>await DisplayAlert(Strings.lblConfirmDelete, Strings.lblDeleteMessage, Strings.lblOK, Strings.lblCancel));
</code>```

Problem is - not all attributes defined this way from XAML are updated when I change UI culture during runtime.
Buttons, Labels, Entry properties (Placeholder etc.) change as they should, but PageTitle, Toolbaritems, and some other properties remain in previous language.

I presume that some of these are populated when Page is first created, and are not updated on culture (and UI culture) change.
So, basically, I need a way to combine {DynamicResource ...} with values from resources.
I know that DynamicResource is ment to be used with Resource dictionary, but that is not a good way to store language translations for localization.

I tried

```<code>Text="{DynamicResource {x:Static lr:Strings.lblAddNew}}"
</code>```

also not working.

Is there a way of refreshing page dynamicaly?

I also tried calling

```<code>global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(MainListPage));
</code>```

from Appearing event for that page, but that also does not work.

Any ideas?

Part of XAML file

```<code><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:MyProject.View"
    xmlns:rs="clr-namespace:MMPI"
    x:Class="MyProject.MainListPage"
    xmlns:lr="clr-namespace:MyProject.Resources"

    Title="{x:Static lr:Strings.appName}"
    >

<ContentPage.ToolbarItems>
    <ToolbarItem
     Name="New"
     Order="Primary"
     Priority="0"
     Text="{x:Static lr:Strings.lblAddNew}"
     Clicked="New_Clicked"
>
</code>```

答:
When i encountered that challenge in a project I resolved it by using a simple class ResourceLoader and making use of INotifyPropertyChanged.

You can access the Instanceproperty from anywhere and change the culture. All String that are bound to the index would update.

The ResourceManager instance injected into the constructor must be set up appropriately.

public class ResourceLoader : INotifyPropertyChanged
{
    private readonly ResourceManager manager;
    private CultureInfo cultureInfo;

    public ResourceLoader(ResourceManager resourceManager)
    {
        this.manager = resourceManager;
        Instance = this;
        this.cultureInfo = CultureInfo.CurrentUICulture;
    }

    public static ResourceLoader Instance { get; private set; }

    public string GetString(string resourceName)
    {
        string stringRes = this.manager.GetString(resourceName, this.cultureInfo);
        return stringRes;
    }

    public string this[string key] => this.GetString(key);

    public void SetCultureInfo(CultureInfo cultureInfo)
    {
        this.cultureInfo = cultureInfo;
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(null));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
```

<hr>

<p>To display the localized strings in your application you need to bind through the indexer like so:</p>

```
```

<p>Since it is now bound it should update when you call <code>ResourceLoader.SetCultureInfo</code> because the <code>Item[]</code> 'PropertyName' is causing bound controls to re-fetch the values to their bound keys.</p>

<hr>

<h2>Update</h2>

<p>I just tested it if i was talking bogus and for some reason the property changed didn't work. I've added a different approach below, which is close to what i'm using in production <strong>i urge you to add some kind of weak reference 'caching' instead of the simple list holding all the string resources</strong> (otherwise they will be kept forever)</p>

<p>I'm keeping above for reference.</p>

<pre class="lang-cs prettyprint-override"><code>public class ResourceLoader
{

    public ResourceLoader(ResourceManager resourceManager)
    {
        this.manager = resourceManager;
        Instance = this;
        this.cultureInfo = CultureInfo.CurrentUICulture;
    }

    private readonly ResourceManager manager;
    private CultureInfo cultureInfo;

    private readonly List<StringResource> resources = new List<StringResource>();

    public static ResourceLoader Instance { get; private set; }

    public StringResource this[string key] {
        get { return this.GetString(key); }
    }

    public StringResource GetString(string resourceName)
    {
        string stringRes = this.manager.GetString(resourceName, this.cultureInfo);
        var stringResource = new StringResource(resourceName, stringRes);
        this.resources.Add(stringResource);
        return stringResource;
    }

    public void SetCultureInfo(CultureInfo cultureInfo)
    {
        this.cultureInfo = cultureInfo;
        foreach (StringResource stringResource in this.resources) {
            stringResource.Value = this.manager.GetString(stringResource.Key, cultureInfo);
        }
    }

}
</code>```

StringResource:

public class StringResource : INotifyPropertyChanged
{

    public StringResource(string key, string value)
    {
        this.Key = key;
        this.Value = value;
    }

    private string value;

    public string Key { get; }

    public string Value {
        get { return this.value; }
        set {
            this.value = value;
            this.OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

}
```

<p>XAML Binding</p>

```
```

Update 2

Came across this link where they implemented it similarly to my first approach. Maybe you can give it a try.

Update 3

Fixed the first approach. Both are working now. What was needed was this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(null)); instead of this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(Item[]));

Body:
I am using Strings.resx, Strings.de.resx, etc. to localize Xamarin.Forms app.
I need to be able to change interface language at run time, and it (allmost) works.

Xamarin generates static class Strings in namespace MyProject.Resources from resource files, and I use those values to display strings on UI.
When doing it from code, it works flawlessly:

await DisplayAlert(Strings.lblConfirmDelete, Strings.lblDeleteMessage, Strings.lblOK, Strings.lblCancel));

Problem is - not all attributes defined this way from XAML are updated when I change UI culture during runtime.
Buttons, Labels, Entry properties (Placeholder etc.) change as they should, but PageTitle, Toolbaritems, and some other properties remain in previous language.

I presume that some of these are populated when Page is first created, and are not updated on culture (and UI culture) change.
So, basically, I need a way to combine {DynamicResource ...} with values from resources.
I know that DynamicResource is ment to be used with Resource dictionary, but that is not a good way to store language translations for localization.

I tried

Text="{DynamicResource {x:Static lr:Strings.lblAddNew}}"

also not working.

Is there a way of refreshing page dynamicaly?

I also tried calling

global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(MainListPage));

from Appearing event for that page, but that also does not work.

Any ideas?

Part of XAML file

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:MyProject.View"
    xmlns:rs="clr-namespace:MMPI"
    x:Class="MyProject.MainListPage"
    xmlns:lr="clr-namespace:MyProject.Resources"

    Title="{x:Static lr:Strings.appName}"
    >

<ContentPage.ToolbarItems>
    <ToolbarItem
     Name="New"
     Order="Primary"
     Priority="0"
     Text="{x:Static lr:Strings.lblAddNew}"
     Clicked="New_Clicked"
>

Body:
When i encountered that challenge in a project I resolved it by using a simple class ResourceLoader and making use of INotifyPropertyChanged.

You can access the Instanceproperty from anywhere and change the culture. All String that are bound to the index would update.

The ResourceManager instance injected into the constructor must be set up appropriately.

public class ResourceLoader : INotifyPropertyChanged
{
    private readonly ResourceManager manager;
    private CultureInfo cultureInfo;

    public ResourceLoader(ResourceManager resourceManager)
    {
        this.manager = resourceManager;
        Instance = this;
        this.cultureInfo = CultureInfo.CurrentUICulture;
    }

    public static ResourceLoader Instance { get; private set; }

    public string GetString(string resourceName)
    {
        string stringRes = this.manager.GetString(resourceName, this.cultureInfo);
        return stringRes;
    }

    public string this[string key] => this.GetString(key);

    public void SetCultureInfo(CultureInfo cultureInfo)
    {
        this.cultureInfo = cultureInfo;
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(null));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

To display the localized strings in your application you need to bind through the indexer like so:

<Label Text="{Binding [Test], Source={x:Static ResourceLoader.Instance}}" />

Since it is now bound it should update when you call ResourceLoader.SetCultureInfo because the Item[] 'PropertyName' is causing bound controls to re-fetch the values to their bound keys.

Update

I just tested it if i was talking bogus and for some reason the property changed didn't work. I've added a different approach below, which is close to what i'm using in production i urge you to add some kind of weak reference 'caching' instead of the simple list holding all the string resources (otherwise they will be kept forever)

I'm keeping above for reference.

public class ResourceLoader
{

    public ResourceLoader(ResourceManager resourceManager)
    {
        this.manager = resourceManager;
        Instance = this;
        this.cultureInfo = CultureInfo.CurrentUICulture;
    }

    private readonly ResourceManager manager;
    private CultureInfo cultureInfo;

    private readonly List<StringResource> resources = new List<StringResource>();

    public static ResourceLoader Instance { get; private set; }

    public StringResource this[string key] {
        get { return this.GetString(key); }
    }

    public StringResource GetString(string resourceName)
    {
        string stringRes = this.manager.GetString(resourceName, this.cultureInfo);
        var stringResource = new StringResource(resourceName, stringRes);
        this.resources.Add(stringResource);
        return stringResource;
    }

    public void SetCultureInfo(CultureInfo cultureInfo)
    {
        this.cultureInfo = cultureInfo;
        foreach (StringResource stringResource in this.resources) {
            stringResource.Value = this.manager.GetString(stringResource.Key, cultureInfo);
        }
    }

}

StringResource:

public class StringResource : INotifyPropertyChanged
{

    public StringResource(string key, string value)
    {
        this.Key = key;
        this.Value = value;
    }

    private string value;

    public string Key { get; }

    public string Value {
        get { return this.value; }
        set {
            this.value = value;
            this.OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

}

XAML Binding

<Label  Text="{Binding [ResourceKey].Value, Mode=OneWay, Source={x:Static local:ResourceLoader.Instance}}"
           />

Update 2

Came across this link where they implemented it similarly to my first approach. Maybe you can give it a try.

Update 3

Fixed the first approach. Both are working now. What was needed was this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(null)); instead of this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(Item[]));


问:
Working in IE 11 but not working Google Chrome - excel file download using jquery
here is the fiddle

https://jsfiddle.net/ym4egje0/13/

File download is happening for IE (internet explorer) not working for google chrome .

I cant change the HTML and CSS part  .

Cant Use any external library

I Think i have to change the part

```<code> else {
                $('#test').attr('href', data_type + ', ' + encodeURIComponent(tab_text));
                $('#test').attr('download', 'Test file.xls');
            }
</code>```

But what to chnage so that it works for both google chrome and IE

HTML

```<code><input type="button" id="test" onClick="fnExcelReport();" value="download" />

<div id='MessageHolder'></div>
</code>```

JS

```<code>function CreateHiddenTable(ListOfMessages)
{
var ColumnHead = "Column Header Text";
var TableMarkUp='<table id="myModifiedTable" class="visibilityHide"><thead><tr><td><b>'+ColumnHead+'</b></td>  </tr></thead><tbody>';
console.log(ListOfMessages);
console.log(ListOfMessages.length);
for(i=0; i<ListOfMessages.length; i++){
    TableMarkUp += '<tr><td>' + ListOfMessages[i] +'</td></tr>';
}
TableMarkUp += "</tbody></table>";
$('#MessageHolder').append(TableMarkUp);
}

function fnExcelReport() {
var Messages = "\n message1.\n message2.";
var ListOfMessages = Messages.split(".");

CreateHiddenTable(ListOfMessages);

    var tab_text = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
    tab_text = tab_text + '<head><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>';

    tab_text = tab_text + '<x:Name>Error Messages</x:Name>';

    tab_text = tab_text + '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet>';
    tab_text = tab_text + '</x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>';

    tab_text = tab_text + "<table border='1px'>";
    tab_text = tab_text + $('#myModifiedTable').html();;
    tab_text = tab_text + '</table></body></html>';

    var data_type = 'data:application/vnd.ms-excel';

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
        if (window.navigator.msSaveBlob) {
            var blob = new Blob([tab_text], {
                type: "application/csv;charset=utf-8;"
            });
            navigator.msSaveBlob(blob, 'Test file.xls');
        }
    } else {
        $('#test').attr('href', data_type + ', ' + encodeURIComponent(tab_text));
        $('#test').attr('download', 'Test file.xls');
    }
$('

#MessageHolder').html("");
}
</code>```

CSS

```<code>.visibilityHide
{
  visibility:hidden;
}
</code>```

答:
The encodeURIComponent call isn't going to do the trick.  To do what you're trying to do, you have to Base64-encode the tab_text variable and then stick that into the href attribute.  The A tag will end up looking like this:

```<code><a href="data:application/vnd.ms-excel;base64,dmFyIHNjT2JqMSA9IG5ldyBzY3Jv...">Click here to download</a>
</code>```

According to another SO post, you're correct in using the download attribute to specify the filename.

Body:
here is the fiddle

https://jsfiddle.net/ym4egje0/13/

File download is happening for IE (internet explorer) not working for google chrome .

I cant change the HTML and CSS part  .

Cant Use any external library

I Think i have to change the part

 else {
                $('#test').attr('href', data_type + ', ' + encodeURIComponent(tab_text));
                $('#test').attr('download', 'Test file.xls');
            }

But what to chnage so that it works for both google chrome and IE

HTML

<input type="button" id="test" onClick="fnExcelReport();" value="download" />

JS

function CreateHiddenTable(ListOfMessages)
{
var ColumnHead = "Column Header Text";
var TableMarkUp='

'+ColumnHead+'

';
console.log(ListOfMessages);
console.log(ListOfMessages.length);
for(i=0; i<ListOfMessages.length; i++){
    TableMarkUp += '
' + ListOfMessages[i] +'
';
}
TableMarkUp += "

";
$('#MessageHolder').append(TableMarkUp);
}

function fnExcelReport() {
var Messages = "\n message1.\n message2.";
var ListOfMessages = Messages.split(".");

CreateHiddenTable(ListOfMessages);

    var tab_text = '';
    tab_text = tab_text + '<xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>';

    tab_text = tab_text + '<x:Name>Error Messages</x:Name>';

    tab_text = tab_text + '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet>';
    tab_text = tab_text + '</x:ExcelWorksheets></x:ExcelWorkbook></xml>';

    tab_text = tab_text + "
";
    tab_text = tab_text + $('#myModifiedTable').html();;
    tab_text = tab_text + '
';

    var data_type = 'data:application/vnd.ms-excel';

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
        if (window.navigator.msSaveBlob) {
            var blob = new Blob([tab_text], {
                type: "application/csv;charset=utf-8;"
            });
            navigator.msSaveBlob(blob, 'Test file.xls');
        }
    } else {
        $('#test').attr('href', data_type + ', ' + encodeURIComponent(tab_text));
        $('#test').attr('download', 'Test file.xls');
    }
$('

#MessageHolder').html("");
}

CSS

.visibilityHide
{
  visibility:hidden;
}

Body:
The encodeURIComponent call isn't going to do the trick.  To do what you're trying to do, you have to Base64-encode the tab_text variable and then stick that into the href attribute.  The A tag will end up looking like this:

<a href="data:application/vnd.ms-excel;base64,dmFyIHNjT2JqMSA9IG5ldyBzY3Jv...">Click here to download</a>

According to another SO post, you're correct in using the download attribute to specify the filename.


问:
Spring switch property value
Let's say I've a property file where I've the following properties

name= harry,andy,robert

email.harry = harry@xyz.com

email.andy = andy@xyz.com

email.robert = robert@xyz.com

The requirement is to display the e-mail addresses by filtering the name property.

So in the above case all the e-mail addresses should be displayed.

Let's say if in future if I remove "robert" from name property, then only the email addresses of harry and andy should be displayed.

is there a way to do the same using spring dependency injection?

P.S.: I want to make the name property configurable. I dont want to add a new bean property everytime.

答:
Use the @ConfigurationProperties("email") annotation on your component to bind to the name and a list of emails. You'll have to rejig your properties a bit:

```<code>Properties:

email.names = harry,andy,robert
email.addresses.harry = harry@xyz.com
email.addresses.andy = andy@xyz.com
email.addresses.robert = robert@xyz.com
</code>```

Your class:

```<code>@Component
@ConfigurationProperties("email") // prefix email, find email.* values
public class AppProperties {

    private String names;
    private List<String> addresses = new ArrayList<>();
</code>```

and Spring should bind it all for you. Have a look at this tutorial that says more or less the same:  https://www.mkyong.com/spring-boot/spring-boot-configurationproperties-example/

Spring Boot only though, but yet another good reason to use it if you aren' already.

Title: Spring switch property value

Body:
Use the @ConfigurationProperties("email") annotation on your component to bind to the name and a list of emails. You'll have to rejig your properties a bit:

Properties:

email.names = harry,andy,robert
email.addresses.harry = harry@xyz.com
email.addresses.andy = andy@xyz.com
email.addresses.robert = robert@xyz.com

Your class:

@Component
@ConfigurationProperties("email") // prefix email, find email.* values
public class AppProperties {

    private String names;
    private List<String> addresses = new ArrayList<>();

and Spring should bind it all for you. Have a look at this tutorial that says more or less the same:  https://www.mkyong.com/spring-boot/spring-boot-configurationproperties-example/

Spring Boot only though, but yet another good reason to use it if you aren' already.


问:
C# - NUnit - 'dependsOnMethods' from TestNG
With TestNG we have the "dependsOnMethods" feature that cheks if another TC has passed to execute the current TC and if it has a fail it does not execute unless you add alwaysRun label, as shown below:

```<code>@Test(dependsOnMethods={ "testMethod2" }, alwaysRun=true)
public void testMethod1() {
    System.out.println("testMethod1");
}

@Test
public void testMethod2() {
    System.out.println("testMethod2");
    int result = 3;
    Assert.assertEquals(result, 2);
}
</code>```

Is there any way to have the same behaviour using NUnit?

答:
Using NUnit's own facilties, there is no way to do this. There has been a lot of discussion around adding this sort of dependency, but it does not yet exist. Maybe TestNG is a good model for a future Attribute.

Currently, all you can do is order tests in NUnit. So, if you gave testMethod2 the attribute [Order(1)] it would run before any other tests in the fixture. This has some limitations:

Ordering has to do with starting tests, not waiting for them to finish. In a parallel environment, both tests could still run together. So, to use this workaround, you should not run the tests in the fixture in parallel. Fixtures can still run in parallel against one another, of course.

There is no provision that testMethod2 must pass in order for testMethod1 to be run. You could handle this yourself by setting an instance field in testMethod2 and testing it in testMethod1. I would probably test it using Assume.That so that test method 1 is not displayed as a warning or error in the case that test method 2 failed.

Body:
With TestNG we have the "dependsOnMethods" feature that cheks if another TC has passed to execute the current TC and if it has a fail it does not execute unless you add alwaysRun label, as shown below:

@Test(dependsOnMethods={ "testMethod2" }, alwaysRun=true)
public void testMethod1() {
    System.out.println("testMethod1");
}

@Test
public void testMethod2() {
    System.out.println("testMethod2");
    int result = 3;
    Assert.assertEquals(result, 2);
}

Is there any way to have the same behaviour using NUnit?


问:
How to avoid rendering directive element
Is it possible to hide my directive html element?
I mean if I have this directive:

app.js

```<code>angular.module("myApp", [])
    .directive("myDirective", function() {
        return {
            restrict: "E",
            template: "<div><p>Some text...</p></div>"
    }
);
</code>```

Only render the content of the template.

```<code><div>
    <p>Some text...</p>
</div>
</code>```

Not the directives element:

```<code><my-directive>
    <div>
        <p>Some text...</p>
    </div>
</my-directive>
</code>```

答:
yes just put the replace: true in the directive. it will remove the element

```<code>angular.module("myApp", [])
    .directive("myDirective", function() {
        return {
            restrict: "E",
            template: "<div><p>Some text...</p></div>",
            replace: true
    }
);
</code>```

Demo

angular.module("app",[])
.controller("ctrl",function($scope){

}).directive("myDirective", function() {
        return {
            restrict: "E",
            template: "

Some text...

",
            replace : true
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <my-directive>
</my-directive>
</div></code>```

Body:
Is it possible to hide my directive html element?
I mean if I have this directive:

app.js

angular.module("myApp", [])
    .directive("myDirective", function() {
        return {
            restrict: "E",
            template: "

Some text...

"
    }
);

Only render the content of the template.

Some text...

Not the directives element:

<my-directive>

Some text...

</my-directive>

Body:
yes just put the replace: true in the directive. it will remove the element

angular.module("myApp", [])
    .directive("myDirective", function() {
        return {
            restrict: "E",
            template: "<div><p>Some text...</p></div>",
            replace: true
    }
);

Demo

angular.module("app",[])
.controller("ctrl",function($scope){

}).directive("myDirective", function() {
        return {
            restrict: "E",
            template: "<div><p>Some text...</p></div>",
            replace : true
    }
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <my-directive>
</my-directive>
</div>


问:
VB.NET to C# Linq
I have the following LINQ

```<code>            Dim z = (From d In db.GPSdevice
                     Where d.CompanyId = currentuser.CompanyId And d.Type = "Truck" Or d.Type = "Trailer"
                     Order By d.ListOrder Descending
                     Group d By d.Driver Into g = Group
                     Select g.FirstOrDefault())
</code>```

I try to convert it to c#

```<code>        var z = db.GPSdevices
            .Where(p => p.CompanyId == companyID && p.Type == "Truck" || p.Type == "Trailer")
            .OrderByDescending(p => p.ListOrder)
            .GroupBy(p => p.Driver)
            .Select(g => new { Group = g });
</code>```

but not sure, how to convert Select g.FirstOrDefault()...

答:
Just call g.FirstOrDefault() in your Select

```<code>    var z = db.GPSdevices
        .Where(p => p.CompanyId == companyID && p.Type == "Truck" || p.Type == "Trailer")
        .OrderByDescending(p => p.ListOrder)
        .GroupBy(p => p.Driver)
        .Select(g => g.FirstOrDefault());
</code>```

Title: VB.NET to C# Linq

Body:
I have the following LINQ

            Dim z = (From d In db.GPSdevice
                     Where d.CompanyId = currentuser.CompanyId And d.Type = "Truck" Or d.Type = "Trailer"
                     Order By d.ListOrder Descending
                     Group d By d.Driver Into g = Group
                     Select g.FirstOrDefault())

I try to convert it to c#

        var z = db.GPSdevices
            .Where(p => p.CompanyId == companyID && p.Type == "Truck" || p.Type == "Trailer")
            .OrderByDescending(p => p.ListOrder)
            .GroupBy(p => p.Driver)
            .Select(g => new { Group = g });

but not sure, how to convert Select g.FirstOrDefault()...

Body:
Just call g.FirstOrDefault() in your Select

    var z = db.GPSdevices
        .Where(p => p.CompanyId == companyID && p.Type == "Truck" || p.Type == "Trailer")
        .OrderByDescending(p => p.ListOrder)
        .GroupBy(p => p.Driver)
        .Select(g => g.FirstOrDefault());


问:
multiple alarm clock in javascript using dynamic generated input elements in javascript
I am trying to make a web page which will allow to set multiple alarms using dynamic element creation property of javascript but I'm not able to get the values of these multiple elements and create a alert on that time.
This is my code so far</p>

```<code><div id="TextBoxContainer">
     <!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />

<script type="text/javascript">
        var room = 0;
        var i = 0;
        function GetDynamicTextBox(){
            return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
        }
        function AddTextBox() {
            var div = document.createElement('DIV');
            div.innerHTML = GetDynamicTextBox("");
            document.getElementById("TextBoxContainer").appendChild(div);
        }

        function RemoveTextBox(div) {
            document.getElementById("TextBoxContainer").removeChild(div.parentNode);
        }

        function RecreateDynamicTextboxes() {
                var html = "";
                html += "<div>" + GetDynamicTextBox() + "</div>";
                document.getElementById("TextBoxContainer").innerHTML = html;
                room++;
        }
        window.onload = RecreateDynamicTextboxes;

        function AddAlarm(values){
            var hour = document.getElementById('');
            var minute = document.getElementById('');
            var date = document.getElementById('');
        }
</script>
</code>```

答:
You forgot the ID attribute on the date input and you were collecting the input elements in AddAlarm instead of their values.

EDIT: To check the alarms you have to store them and check every minute, if the current date matches one of the alarms. I added a short implementation there.

<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />

```

Body:
I am trying to make a web page which will allow to set multiple alarms using dynamic element creation property of javascript but I'm not able to get the values of these multiple elements and create a alert on that time.
This is my code so far

<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />

Body:
You forgot the ID attribute on the date input and you were collecting the input elements in AddAlarm instead of their values.

EDIT: To check the alarms you have to store them and check every minute, if the current date matches one of the alarms. I added a short implementation there.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="TextBoxContainer">
     <!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />

<script type="text/javascript">
        var alarms = {};
        var room = 0;
        var i = 0;

        setInterval(function() {
          var current = new Date();
          for (var nr in alarms) {
             var alarm = alarms[nr];
             console.log("checking alarm " + nr + " (" + alarm + ")");
             if(current.getHours() == alarm.getHours()
              && current.getMinutes() == alarm.getMinutes()) { // also check for day, month and year
                alert("ALERT\n"+alarm);
             } else{
                console.log('Alarm ' + nr + '('+alarm+') not matching current date ' + current);
             }
          }
        }, 60000);

        function GetDynamicTextBox(){
            return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px" id="c'+room+'"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
        }
        function AddTextBox() {
            var div = document.createElement('DIV');
            div.innerHTML = GetDynamicTextBox("");
            document.getElementById("TextBoxContainer").appendChild(div);
        }

        function RemoveTextBox(div) {
            document.getElementById("TextBoxContainer").removeChild(div.parentNode);
        }

        function RecreateDynamicTextboxes() {
                var html = "";
                html += "<div>" + GetDynamicTextBox() + "</div>";
                document.getElementById("TextBoxContainer").innerHTML = html;
                room++;
        }
        window.onload = RecreateDynamicTextboxes;

        function AddAlarm(values){
            var hour = $('#a'+values).val();
            var minute = $('#b'+values).val();
            var date = $('#c'+values).val();
            console.log(hour + ':' + minute + ' on ' + date);
            var dateObj = new Date(date);
            dateObj.setMinutes(minute);
            dateObj.setHours(hour);
            console.log(dateObj);
            alarms[values] = dateObj;
        }
</script>


问:
Password-checker JavaScript and HTML <form>
I am trying to have a website display different messages depending on whether the password entered is correct or not (correct password is thePassword). So far, no luck.

According to Chrome, the error is in this line (first line of the function):

if (document.getElementById("psw") = "thePassword") {

JSFiddle: https://jsfiddle.net/5grtmxd4/

Thanks in advance!

```<code><!DOCTYPE html>
<html>
<head>
</head>
<body>
  <form>
    Password<br>
    <input id="psw" type="password" name="password" size="45" autofocus></input><br><br>
    <input type="submit" value="Submit" onclick="message();"></input>
  </form>
<script>
function message () {
  if (document.getElementById("psw") = "thePassword") {
    document.getElementById("display").innerHTML = "Logged in";
  } else {
    document.getElementById("display").innerHTML = "Try again!";
  }}
</script>
<p id="display"></p>
</body>
</html>
</code>```

EDIT: I would appreciate that instead of trying to rewrite the entire code, only neccessary changes are made. Thanks!

答:
Use double equals(==) in if statement instead of single equal(=)

```<code>if (document.getElementById("psw").value == "thePassword")
</code>```

Instead of

```<code>if (document.getElementById("psw") = "thePassword")
</code>```

Body:
I am trying to have a website display different messages depending on whether the password entered is correct or not (correct password is thePassword). So far, no luck.

According to Chrome, the error is in this line (first line of the function):

if (document.getElementById("psw") = "thePassword") {

JSFiddle: https://jsfiddle.net/5grtmxd4/

Thanks in advance!

<!DOCTYPE html>

  <form>
    Password

    <input id="psw" type="password" name="password" size="45" autofocus></input>

    <input type="submit" value="Submit" onclick="message();"></input>
  </form>

EDIT: I would appreciate that instead of trying to rewrite the entire code, only neccessary changes are made. Thanks!

Body:
Use double equals(==) in if statement instead of single equal(=)

if (document.getElementById("psw").value == "thePassword")

Instead of

if (document.getElementById("psw") = "thePassword")


问:
Why doesn't django's model.save() call full_clean()?
I'm just curious if anyone knows if there's good reason why django's orm doesn't call 'full_clean' on a model unless it is being saved as part of a model form.

Note that full_clean() will not be called automatically when you call your model’s save() method. You’ll need to call it manually when you want to run one-step model validation for your own manually created models.
  django's full clean doc

(NOTE: quote updated for Django 1.6... previous django docs had a caveat about ModelForms as well.)

Are there good reasons why people wouldn't want this behavior? I'd think if you took the time to add validation to a model, you'd want that validation run every time the model is saved.

I know how to get everything to work properly, I'm just looking  for an explanation.

答:
AFAIK, this is because of backwards compatibility. There are also problems with ModelForms with excluded fields, models with default values, pre_save() signals, etc.

Sources you might be intrested in:

http://code.djangoproject.com/ticket/13100

http://groups.google.com/group/django-developers/browse_frm/thread/b888734b05878f87


问:
Close status bar when opened: Android
I am trying to come up with some ways of disabling the status bar without hiding it completely. This is an introlude attempt at disabling status bars in 3rd party apps. For now, I want to disable it in my own app, and then eventually create a background service to see if I can do so in other apps. The app I am creating is an operating system for children, and I am trying to develop a closed system.

Here is what I have tried. My initial idea was to monitor when status bar was accessed and then closing it.

```<code>@Override
public void onWindowFocusChanged(boolean hasFocus) {
    Log.i(TAG, "onWindowFocusChanged()");
    try {
        if (!hasFocus) {
            Log.d(TAG, "close status bar attempt");
            Object service = getSystemService("statusbar");
            Class<?> statusbarManager = Class
                    .forName("android.app.StatusBarManager");
            Method collapse = statusbarManager.getMethod("collapse");
            collapse.setAccessible(true);
            collapse.invoke(service);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
</code>```

This is the method I used. It works for detecting when status bar is being accessed, however, it does not close the status bar once it has focus. What am I missing? Thanks in advance.

答:
Here's an updated answer if anyone is still looking for a solution to something like this: https://developer.android.com/training/system-ui/immersive.html

For me, I added the following in my onResume() method:

```<code>View decorView = getWindow().getDecorView();
    int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
    decorView.setSystemUiVisibility(uiOptions);
</code>```

This allows the status bar to stay hidden but the user can still access it by swiping the edge of the screen.  Then after a few seconds of inactivity it will collapse and disappear again!

Title: Close status bar when opened: Android

Body:
I am trying to come up with some ways of disabling the status bar without hiding it completely. This is an introlude attempt at disabling status bars in 3rd party apps. For now, I want to disable it in my own app, and then eventually create a background service to see if I can do so in other apps. The app I am creating is an operating system for children, and I am trying to develop a closed system.

Here is what I have tried. My initial idea was to monitor when status bar was accessed and then closing it.

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    Log.i(TAG, "onWindowFocusChanged()");
    try {
        if (!hasFocus) {
            Log.d(TAG, "close status bar attempt");
            Object service = getSystemService("statusbar");
            Class<?> statusbarManager = Class
                    .forName("android.app.StatusBarManager");
            Method collapse = statusbarManager.getMethod("collapse");
            collapse.setAccessible(true);
            collapse.invoke(service);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

This is the method I used. It works for detecting when status bar is being accessed, however, it does not close the status bar once it has focus. What am I missing? Thanks in advance.

Body:
Here's an updated answer if anyone is still looking for a solution to something like this: https://developer.android.com/training/system-ui/immersive.html

For me, I added the following in my onResume() method:

View decorView = getWindow().getDecorView();
    int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
    decorView.setSystemUiVisibility(uiOptions);

This allows the status bar to stay hidden but the user can still access it by swiping the edge of the screen.  Then after a few seconds of inactivity it will collapse and disappear again!


问:
How to partition table rows get the min and max for each process
Can someone please let me know how to get the output from first table. please note that I am not allowed to use loops. I tried with window functions and no luck yet. </p>

```<code>CUSTOMER_NUMBER ORDER_NO PROCESS
100             1001        1
100             1002        1
100             1003        2
100             1004        2
100             1005        2
100             1006        3
100             1007        3
100             1008        3
101             1009        1
101             1010        1
101             1011        2
101             1012        2
101             1013        2

CUSTOMER_NUMBER MIN_VALUE, MAX_VALUE, PROCESS
100             1001        1002            1
100             1003        1005            2
100             1006        1008            3
101             1009        1010            1
101             1011        1013            2
</code>```

答:
if you would like to get the results by window functions you could use max() over() and min() over() window functions:

```<code> SELECT
  customer_number,
  order_no,
  min(order_no)
  OVER (
    PARTITION BY customer_number, process ) AS min_value,
  max(order_no)
  OVER (
    PARTITION BY customer_number, process ) AS max_value,
  process
FROM table_1
</code>```

This will yield the original table with additional 2 columns (min_value, max_value).

Body:
Can someone please let me know how to get the output from first table. please note that I am not allowed to use loops. I tried with window functions and no luck yet.

CUSTOMER_NUMBER ORDER_NO PROCESS
100             1001        1
100             1002        1
100             1003        2
100             1004        2
100             1005        2
100             1006        3
100             1007        3
100             1008        3
101             1009        1
101             1010        1
101             1011        2
101             1012        2
101             1013        2

CUSTOMER_NUMBER MIN_VALUE, MAX_VALUE, PROCESS
100             1001        1002            1
100             1003        1005            2
100             1006        1008            3
101             1009        1010            1
101             1011        1013            2

Body:
if you would like to get the results by window functions you could use max() over() and min() over() window functions:

 SELECT
  customer_number,
  order_no,
  min(order_no)
  OVER (
    PARTITION BY customer_number, process ) AS min_value,
  max(order_no)
  OVER (
    PARTITION BY customer_number, process ) AS max_value,
  process
FROM table_1

This will yield the original table with additional 2 columns (min_value, max_value).


问:
Issues adding a Custom FXML object to another
Introduction:

This is simply a "Table" where cards can be "placed" on, by right clicking on the table.

I have 2 FXML objects:

Card

UI

Problem:

In short, a Card needs to be added to the UI "Table", this is where my problem lies.

The adding Card method simply adds the card to a Pane object (which is not null), and we know that Pane's add objects which extend a Node

I tried 2 solutions, of which both failed.

Solution 1

Using the FXMLLoader to load the Card.fxml file into a Card object:

Having the Card definition as follows

```<code>public class Card implements Initializable
</code>```

causes issues:

```<code>FXMLLoader loader = new FXMLLoader(getClass().getResource("/Layouts/Card.fxml"));
Card card = loader.load();
card.setLayoutX(mouseEvent.getSceneX() - (card.getLayoutX() / 2));      <--------here setLayoutX
card.setLayoutY(mouseEvent.getSceneY() - (card.getLayoutY() / 2));      <--------here setLayoutY
card.isFaceDown.addListener((observable, oldValue, newValue) -> {
    if (newValue) {
        facedownCount.add(1);
    } else {
        facedownCount.subtract(1);
    }
});
totalCount.add(1);
gamePane.getChildren().add(card);                                       <--------here card does not extend Node
</code>```

The issue is I am unable to set layout properties of the Card object if it doesn't extend a stackpane, and also I am unable to add it to another object as a child

Solution 2: (more likely to be correct)

Changing the Card definition to

```<code>public class Card extends StackPane implements Initializable
</code>```

followed by attempting to add it:

```<code>        FXMLLoader loader = new FXMLLoader(getClass().getResource("/Layouts/Card.fxml"));
        Card card = loader.load();                 < -------- PROBLEM
</code>```

which gives me this exception error:

```<code>Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:417)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at com.sun.glass.ui.gtk.GtkApplication.lambda$null$49(GtkApplication.java:139)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
    ... 29 more
Caused by: java.lang.ClassCastException: javafx.scene.layout.StackPane cannot be cast to Game.Controller.Card
    at Game.Controller.UI.HandleClick(UI.java:60)
    ... 39 more
</code>```

Card.fxml

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.StackPane?>

<?import javafx.scene.image.ImageView?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.effect.DropShadow?>

<StackPane maxHeight="-Infinity"
           maxWidth="-Infinity"
           minHeight="-Infinity"
           minWidth="-Infinity"
           prefHeight="400.0"
           prefWidth="600.0"
           xmlns="http://javafx.com/javafx/8.0.112"
           fx:controller="Game.Controller.Card"
           xmlns:fx="http://javafx.com/fxml/1">
    <children>
        <ImageView fx:id="imgSuit" fitHeight="275.0" fitWidth="183.0" layoutX="10.0" layoutY="10.0" pickOnBounds="true" preserveRatio="true" />
        <ImageView fx:id="imgValue" fitHeight="275.0" fitWidth="183.0" pickOnBounds="true" preserveRatio="true">
            <image>
                <Image url="@../suits/back.png" />
            </image>
        </ImageView>
    </children>
    <effect>
        <DropShadow />
    </effect>

</StackPane>
</code>```

Card Controller

```<code>public class Card implements Initializable {

    public static HashMap cardSuit, cardValue;

    public BooleanProperty isFaceDown = new SimpleBooleanProperty(true);
    private IntegerProperty value = new SimpleIntegerProperty(-1);
    public StringProperty suit = new SimpleStringProperty("");
    public ImageView imgValue = new ImageView();
    public ImageView imgSuit = new ImageView();

    public Card(){
        super();
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        initImages();
        setupBindings();
        setDefaults();
    }

    private void setDefaults() {
        isFaceDown.set(true);
    }

    private void setupBindings() {
        isFaceDown.addListener((observable, oldValue, newValue) -> {
            if (newValue){
                imgValue.setImage(null);
                imgSuit.setImage((Image) cardSuit.get("B"));
            }
            else {
                imgValue.setImage((Image) cardValue.get(value.get()));
                imgSuit.setImage((Image) cardSuit.get(suit.get()));
            }
        });
    }

    private void initImages() {
        if (cardSuit == null) {
            cardSuit = new HashMap<String, Image>();
            cardSuit.put("B", new Image("/suits/back.png"));
            cardSuit.put("C", new Image("/suits/clubs.png"));
            cardSuit.put("D", new Image("/suits/diamonds.png"));
            cardSuit.put("S", new Image("/suits/spades.png"));
            cardSuit.put("H", new Image("/suits/hearts.png"));
        }

        if (cardValue == null) {
            cardValue = new HashMap<Integer, Image>();
            for (int i = 1; i <= 13; i++) {
                cardValue.put(i, new Image("/values/" + String.valueOf(i) + ".png"));
            }
        }
    }
}
</code>```

UI fxml

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>

<?import javafx.scene.layout.StackPane?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" onMousePressed="#HandleClick" prefHeight="750.0" prefWidth="702.0" xmlns="http://javafx.com/javafx/8.0.112" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Game.Controller.UI">
   <children>
      <MenuBar prefHeight="29.0" prefWidth="700.0">
         <menus>
            <Menu mnemonicParsing="false" text="Menu">
               <items>
                  <MenuItem fx:id="mmReset" mnemonicParsing="false" text="Reset" />
                  <MenuItem fx:id="mmClose" mnemonicParsing="false" onAction="#CloseApp" text="Close" />
               </items>
            </Menu>
            <Menu mnemonicParsing="false" text="Help">
               <items>
                  <MenuItem fx:id="mmAbout" mnemonicParsing="false" text="About" />
               </items>
            </Menu>
            <Menu fx:id="mInstruct" mnemonicParsing="false" text="Instructions" />
         </menus>
      </MenuBar>
      <StackPane fx:id="gamePane" layoutX="1.0" layoutY="29.0" prefHeight="700.0" prefWidth="700.0" style="-fx-background-color: green;" />
      <HBox layoutX="7.0" layoutY="731.0" prefHeight="15.0" prefWidth="693.0">
         <children>
            <Label fx:id="lblHearts" text="Hearts = " />
            <Label fx:id="lblDiamonds" text="Diamonds = " />
            <Label fx:id="lblSpades" text="Spades = " />
            <Label fx:id="lblClubs" text="Clubs = " />
            <Label fx:id="lblFaceUp" text="Facing Up =" />
         </children>
      </HBox>
   </children>
</AnchorPane>
</code>```

What am I doing wrong, I think that solution #2 is more 'correct', but why doesn't the loader allow loading into the Card, with the StackPane cast exception

p.s. As a sub question, what difference does the root node make in this case, when loading the fxml object, will it allow me to e.g. setlayoutX property if I don't explicitly extends StackPane in the definition?

答:
You could create a custom component that extends StackPane and is used as the controller class controller by using the <fx:root> element

```<code>public class Card extends StackPane implements Initializable {
    public Card() {
        FXMLLoader loader = new FXMLLoader(getClass().getResouce("card.fxml"));
        loader.setRoot(this);
        loader.setController(this);
        try {
            loader.load();
        } catch (Exception e) {
            throw new IllegalStateException("Could not load fxml", e);
        }
    }

    ...

}
</code>```

card.fxml

<fx:root type="javafx.scene.layout.StackPane"
       maxHeight="-Infinity"
       maxWidth="-Infinity"
       minHeight="-Infinity"
       minWidth="-Infinity"
       prefHeight="400.0"
       prefWidth="600.0"
       xmlns="http://javafx.com/javafx/8.0.112"
       xmlns:fx="http://javafx.com/fxml/1">
    <children>
        <ImageView fx:id="imgSuit" fitHeight="275.0" fitWidth="183.0" layoutX="10.0" layoutY="10.0" pickOnBounds="true" preserveRatio="true" />
        <ImageView fx:id="imgValue" fitHeight="275.0" fitWidth="183.0" pickOnBounds="true" preserveRatio="true">
            <image>
                <Image url="@../suits/back.png" />
            </image>
        </ImageView>
    </children>
    <effect>
        <DropShadow />
    </effect>
</fx:root>
```

Body:
Introduction:

This is simply a "Table" where cards can be "placed" on, by right clicking on the table.

I have 2 FXML objects:

Card

UI

Problem:

In short, a Card needs to be added to the UI "Table", this is where my problem lies.

The adding Card method simply adds the card to a Pane object (which is not null), and we know that Pane's add objects which extend a Node

I tried 2 solutions, of which both failed.

Solution 1

Using the FXMLLoader to load the Card.fxml file into a Card object:

Having the Card definition as follows

public class Card implements Initializable

causes issues:

FXMLLoader loader = new FXMLLoader(getClass().getResource("/Layouts/Card.fxml"));
Card card = loader.load();
card.setLayoutX(mouseEvent.getSceneX() - (card.getLayoutX() / 2));      <--------here setLayoutX
card.setLayoutY(mouseEvent.getSceneY() - (card.getLayoutY() / 2));      <--------here setLayoutY
card.isFaceDown.addListener((observable, oldValue, newValue) -> {
    if (newValue) {
        facedownCount.add(1);
    } else {
        facedownCount.subtract(1);
    }
});
totalCount.add(1);
gamePane.getChildren().add(card);                                       <--------here card does not extend Node

The issue is I am unable to set layout properties of the Card object if it doesn't extend a stackpane, and also I am unable to add it to another object as a child

Solution 2: (more likely to be correct)

Changing the Card definition to

public class Card extends StackPane implements Initializable

followed by attempting to add it:

        FXMLLoader loader = new FXMLLoader(getClass().getResource("/Layouts/Card.fxml"));
        Card card = loader.load();                 < -------- PROBLEM

which gives me this exception error:

Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:417)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at com.sun.glass.ui.gtk.GtkApplication.lambda$null$49(GtkApplication.java:139)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
    ... 29 more
Caused by: java.lang.ClassCastException: javafx.scene.layout.StackPane cannot be cast to Game.Controller.Card
    at Game.Controller.UI.HandleClick(UI.java:60)
    ... 39 more

Card.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.StackPane?>

<?import javafx.scene.image.ImageView?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.effect.DropShadow?>

<StackPane maxHeight="-Infinity"
           maxWidth="-Infinity"
           minHeight="-Infinity"
           minWidth="-Infinity"
           prefHeight="400.0"
           prefWidth="600.0"
           xmlns="http://javafx.com/javafx/8.0.112"
           fx:controller="Game.Controller.Card"
           xmlns:fx="http://javafx.com/fxml/1">
    <children>
        <ImageView fx:id="imgSuit" fitHeight="275.0" fitWidth="183.0" layoutX="10.0" layoutY="10.0" pickOnBounds="true" preserveRatio="true" />
        <ImageView fx:id="imgValue" fitHeight="275.0" fitWidth="183.0" pickOnBounds="true" preserveRatio="true">
            <image>
                <Image url="@../suits/back.png" />
            </image>
        </ImageView>
    </children>
    <effect>
        <DropShadow />
    </effect>

</StackPane>

Card Controller

public class Card implements Initializable {

    public static HashMap cardSuit, cardValue;

    public BooleanProperty isFaceDown = new SimpleBooleanProperty(true);
    private IntegerProperty value = new SimpleIntegerProperty(-1);
    public StringProperty suit = new SimpleStringProperty("");
    public ImageView imgValue = new ImageView();
    public ImageView imgSuit = new ImageView();

    public Card(){
        super();
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        initImages();
        setupBindings();
        setDefaults();
    }

    private void setDefaults() {
        isFaceDown.set(true);
    }

    private void setupBindings() {
        isFaceDown.addListener((observable, oldValue, newValue) -> {
            if (newValue){
                imgValue.setImage(null);
                imgSuit.setImage((Image) cardSuit.get("B"));
            }
            else {
                imgValue.setImage((Image) cardValue.get(value.get()));
                imgSuit.setImage((Image) cardSuit.get(suit.get()));
            }
        });
    }

    private void initImages() {
        if (cardSuit == null) {
            cardSuit = new HashMap<String, Image>();
            cardSuit.put("B", new Image("/suits/back.png"));
            cardSuit.put("C", new Image("/suits/clubs.png"));
            cardSuit.put("D", new Image("/suits/diamonds.png"));
            cardSuit.put("S", new Image("/suits/spades.png"));
            cardSuit.put("H", new Image("/suits/hearts.png"));
        }

        if (cardValue == null) {
            cardValue = new HashMap<Integer, Image>();
            for (int i = 1; i <= 13; i++) {
                cardValue.put(i, new Image("/values/" + String.valueOf(i) + ".png"));
            }
        }
    }
}

UI fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>

<?import javafx.scene.layout.StackPane?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" onMousePressed="#HandleClick" prefHeight="750.0" prefWidth="702.0" xmlns="http://javafx.com/javafx/8.0.112" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Game.Controller.UI">
   <children>
      <MenuBar prefHeight="29.0" prefWidth="700.0">
         <menus>
            <Menu mnemonicParsing="false" text="Menu">
               <items>
                  <MenuItem fx:id="mmReset" mnemonicParsing="false" text="Reset" />
                  <MenuItem fx:id="mmClose" mnemonicParsing="false" onAction="#CloseApp" text="Close" />
               </items>
            </Menu>
            <Menu mnemonicParsing="false" text="Help">
               <items>
                  <MenuItem fx:id="mmAbout" mnemonicParsing="false" text="About" />
               </items>
            </Menu>
            <Menu fx:id="mInstruct" mnemonicParsing="false" text="Instructions" />
         </menus>
      </MenuBar>
      <StackPane fx:id="gamePane" layoutX="1.0" layoutY="29.0" prefHeight="700.0" prefWidth="700.0" style="-fx-background-color: green;" />
      <HBox layoutX="7.0" layoutY="731.0" prefHeight="15.0" prefWidth="693.0">
         <children>

         </children>
      </HBox>
   </children>
</AnchorPane>

What am I doing wrong, I think that solution #2 is more 'correct', but why doesn't the loader allow loading into the Card, with the StackPane cast exception

p.s. As a sub question, what difference does the root node make in this case, when loading the fxml object, will it allow me to e.g. setlayoutX property if I don't explicitly extends StackPane in the definition?

Body:
You could create a custom component that extends StackPane and is used as the controller class controller by using the <fx:root> element

public class Card extends StackPane implements Initializable {
    public Card() {
        FXMLLoader loader = new FXMLLoader(getClass().getResouce("card.fxml"));
        loader.setRoot(this);
        loader.setController(this);
        try {
            loader.load();
        } catch (Exception e) {
            throw new IllegalStateException("Could not load fxml", e);
        }
    }

    ...

}

card.fxml

<fx:root type="javafx.scene.layout.StackPane"
       maxHeight="-Infinity"
       maxWidth="-Infinity"
       minHeight="-Infinity"
       minWidth="-Infinity"
       prefHeight="400.0"
       prefWidth="600.0"
       xmlns="http://javafx.com/javafx/8.0.112"
       xmlns:fx="http://javafx.com/fxml/1">
    <children>
        <ImageView fx:id="imgSuit" fitHeight="275.0" fitWidth="183.0" layoutX="10.0" layoutY="10.0" pickOnBounds="true" preserveRatio="true" />
        <ImageView fx:id="imgValue" fitHeight="275.0" fitWidth="183.0" pickOnBounds="true" preserveRatio="true">
            <image>
                <Image url="@../suits/back.png" />
            </image>
        </ImageView>
    </children>
    <effect>
        <DropShadow />
    </effect>
</fx:root>


问:
Powershell [system.reflection.assembly].loadfile() Exception Access is denied when run by Jenkins
I have a very simple Powershell script which I want to use as part of a Jenkins build to return Assembly information. The script contains the following:

```<code>Write-Host([system.reflection.assembly]::loadfile($args[0])).FullName
</code>```

When I try and call this script as part of the Jenkins build I get the following errors:

```<code>.\GetAssemblyInfo.ps1
Exception calling "LoadFile" with "1" argument(s): "Access is denied.
(Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"

At C:\Jenkins\workspace\Tools\NuGetBuildSupport\GetAssemblyInfo.ps1:1    char:50
+ Write-Host([system.reflection.assembly]::loadfile <<<< ($args[0])).FullName
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException
</code>```

The command runs fine when it is not executing as part of the Jenkins build.

The DLL that is being passed to loadfile is not marked as Blocked

The execution policy I am using to invoke Powershell is Bypass

答:
I recommend navigating to your servers "Services" select the Jenkins service and you can assign a specific user.  As a test try giving Jenkins administrator access and if that works create another user and restrict access.  The fact that it runs fine outside of the Jenkins infrastructure is an indicator for this issue.

Services: (Search for services in the start menu or the common location: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools)

Navigate to the Jenkins Service

Open the properties

Select the Log in tab and set it to a user with proper permissions (E.g: administrator)

Body:
I have a very simple Powershell script which I want to use as part of a Jenkins build to return Assembly information. The script contains the following:

Write-Host([system.reflection.assembly]::loadfile($args[0])).FullName

When I try and call this script as part of the Jenkins build I get the following errors:

.\GetAssemblyInfo.ps1
Exception calling "LoadFile" with "1" argument(s): "Access is denied.
(Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"

At C:\Jenkins\workspace\Tools\NuGetBuildSupport\GetAssemblyInfo.ps1:1    char:50
+ Write-Host([system.reflection.assembly]::loadfile <<<< ($args[0])).FullName
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

The command runs fine when it is not executing as part of the Jenkins build.

The DLL that is being passed to loadfile is not marked as Blocked

The execution policy I am using to invoke Powershell is Bypass


问:
Laravel getQueryString() without &
I'm trying to output a variable containing part of a URL into Javascript on my page. When I do this, it changes any & into &, which breaks the URL.

I've tried using str_replace, html_entity_decode, htmlspecialchars_decode but the result was always same & instead of &.

How i can get it with & instead of & ?

This is my controller:

```<code>//here we catch the query
public function index(Request $request)
    {
        $input   = $request->getQueryString();

        return view('lots.browse')->withInput($input);
    }

// here we filter the ajax request
public function indexData(LotFilters $filters)
    {
       $lots  = Lot::filter($filters);

        return Datatables::eloquent($lots)->make(true);
    }
</code>```

This is my view:

```<code><!-- Datatables -->
    <script type="text/javascript">
        $(document).ready(function(){
            $('#table').DataTable({
                searching: false,
                processing: true,
                serverSide: true,
                ajax: '{{  url("/data") . "?" .  html_entity_decode($input) }}',
                columns: [
                    { data: 'date', name: 'date' },
                    { data: 'bid', name: 'bid' },
                    { data: 'auction_name', name: 'auction_name' },
                    { data: 'pics_urls', name: 'pics_urls' },
                    { data: 'company', name: 'company' },
                    { data: 'model_name_en', name: 'model_name_en' },
                    { data: 'model_type_en', name: 'model_type_en' },
                    { data: 'grade_en', name: 'grade_en' },
                    { data: 'mileage_en', name: 'mileage_en' },
                    { data: 'model_year_en', name: 'model_year_en' },
                    { data: 'color_en', name: 'color_en' },
                    { data: 'displacement', name: 'displacement' },
                    { data: 'transmission_en', name: 'transmission_en' },
                    { data: 'scores_en', name: 'scores_en' },
                    { data: 'start_price_en', name: 'start_price_en' },
                    { data: 'result_en', name: 'result_en' }
                ]
            });
        });
    </script>
</code>```

And this is the result:

答:
When using a blade template, {{ $variable }} will properly encode any characters that should not be placed directly in HTML. Since you're placing this variable in Javascript, you don't want this to happen.

The simplest solution is to disable HTML-encoding: {{!! $variable !!}}.

But this is not the full solution. You need to ensure that the variable isn't blindly output, since if it contains a single quote, it will break your Javascript.

The full solution is to escape the string for single quotes:

```<code>{{!! addcslashes($input, "'") !!}}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Laravel getQueryString() without &

Body:
I'm trying to output a variable containing part of a URL into Javascript on my page. When I do this, it changes any & into &, which breaks the URL.

I've tried using str_replace, html_entity_decode, htmlspecialchars_decode but the result was always same & instead of &.

How i can get it with & instead of & ?

This is my controller:

//here we catch the query
public function index(Request $request)
    {
        $input   = $request->getQueryString();

        return view('lots.browse')->withInput($input);
    }

// here we filter the ajax request
public function indexData(LotFilters $filters)
    {
       $lots  = Lot::filter($filters);

        return Datatables::eloquent($lots)->make(true);
    }

This is my view:

And this is the result:

Body:
When using a blade template, {{ $variable }} will properly encode any characters that should not be placed directly in HTML. Since you're placing this variable in Javascript, you don't want this to happen.

The simplest solution is to disable HTML-encoding: {{!! $variable !!}}.

But this is not the full solution. You need to ensure that the variable isn't blindly output, since if it contains a single quote, it will break your Javascript.

The full solution is to escape the string for single quotes:

{{!! addcslashes($input, "'") !!}}