问:
Changed Database Default Locations now I can't create database
I changed database default locations using Microsoft SQL Server Management Studio and now, when I start my application, which should create a database using Visual Studio, so I have admin rights it says this:

```<code>Directory lookup for the file "D:\MSSQL\DATA\DatabaseNameE.mdf" failed with the operating system error 3(The system cannot find the path specified.).
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
</code>```

I am 100% that the path is right and the folders exists.

答: I solved it by looking at security properties of default folder of database default locations. It had mssql$sqlexpress as user with full control. So I added it to security properties of the new folder of database default locations.</p>

Body:
I changed database default locations using Microsoft SQL Server Management Studio and now, when I start my application, which should create a database using Visual Studio, so I have admin rights it says this:

Directory lookup for the file "D:\MSSQL\DATA\DatabaseNameE.mdf" failed with the operating system error 3(The system cannot find the path specified.).
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.

I am 100% that the path is right and the folders exists.


来源: stackexchange

问:
Right-align CSS sprite list
Please look at the Facebook/YouTube/Twitter icons at the top of http://live-fenfast.pantheonsite.io/. I'm trying to align them to the right like they are on http://fenfast.com. The difference on the "live-fenfast.pantheonsite.io" site is that I've converted plain img a hrefs with a styled list that uses CSS to reveal parts of a single image for clicking in the list (CSS sprites).

How do I right-align this list? I've tried a bunch of obvious CSS properties but none of them work.

答:
Use bootstraps pull-right class</p>

```<code><ul id="socialnavlist" class="clearfix pull-right">
</code>```

ContentLicense: CC BY-SA 3.0

Title: Right-align CSS sprite list

Body:
Use bootstraps pull-right class

<ul id="socialnavlist" class="clearfix pull-right">


问:
Get the sum of maximum subarray in a given input array of elements using modulus
I am trying to solve a subarray problem using BruteForce technique with O(n^2) complexity. The code works for small data sets but for some reason it doesn't go right for large numbers. What am I doing wrong with the logic. Can someone help me with this.

Question explanation :-

Sample Input :-

```<code>1
50 1804289384
846930887 1681692778 1714636916 1957747794 424238336 719885387 1649760493 596516650 1189641422 1025202363 1350490028 783368691 1102520060 2044897764 1967513927 1365180541 1540383427 304089173 1303455737 35005212 521595369 294702568 1726956430 336465783 861021531 278722863 233665124 2145174068 468703136 1101513930 1801979803 1315634023 635723059 1369133070 1125898168 1059961394 2089018457 628175012 1656478043 1131176230 1653377374 859484422 1914544920 608413785 756898538 1734575199 1973594325 149798316 2038664371 1129566414
</code>```

Expected Output :-

```<code>1802192837
</code>```

Actual output ( what I am getting ) :-

```<code>1802467240
</code>```

Code :-

```<code>import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    static long maximumSum(long[] a, long m) {

        long sum = 0;
        long val = 0;

        for ( int i=0;i<a.length;i++ ) {
             for( int j=i;j<a.length;j++ ) {
                 val = val + a[i];
                 if( val%m > sum )
                 sum = val%m;
             }
            val = 0;
        }
        return sum;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int q = in.nextInt();
        for(int a0 = 0; a0 < q; a0++){
            int n = in.nextInt();
            long m = in.nextLong();
            long[] a = new long[n];
            for(int a_i = 0; a_i < n; a_i++){
                a[a_i] = in.nextLong();
            }
            long result = maximumSum(a, m);
            System.out.println(result);
        }
        in.close();
    }
}
</code>```

Compilation successful but getting a run time exception as below :-

```<code>Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:907)
    at java.util.Scanner.next(Scanner.java:1530)
    at java.util.Scanner.nextInt(Scanner.java:2160)
    at java.util.Scanner.nextInt(Scanner.java:2119)
    at Solution.main(Solution.java:29)
</code>```

答:
I think J loop is problem you are filling entire sub array with same element</p>

```<code> for ( int i=0;i<a.length;i++ ) {
             for( int j=i;j<a.length;j++ ) {
                 val = val + **a[i]**;
                 if( val%m > sum )
                 sum = val%m;
             }
            val = 0;
        }

Change
val = val + a[i];
to
val = val + a[J];
</code>```

Body:
I am trying to solve a subarray problem using BruteForce technique with O(n^2) complexity. The code works for small data sets but for some reason it doesn't go right for large numbers. What am I doing wrong with the logic. Can someone help me with this.

Question explanation :-

Sample Input :-

1
50 1804289384
846930887 1681692778 1714636916 1957747794 424238336 719885387 1649760493 596516650 1189641422 1025202363 1350490028 783368691 1102520060 2044897764 1967513927 1365180541 1540383427 304089173 1303455737 35005212 521595369 294702568 1726956430 336465783 861021531 278722863 233665124 2145174068 468703136 1101513930 1801979803 1315634023 635723059 1369133070 1125898168 1059961394 2089018457 628175012 1656478043 1131176230 1653377374 859484422 1914544920 608413785 756898538 1734575199 1973594325 149798316 2038664371 1129566414

Expected Output :-

1802192837

Actual output ( what I am getting ) :-

1802467240

Code :-

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    static long maximumSum(long[] a, long m) {

        long sum = 0;
        long val = 0;

        for ( int i=0;i<a.length;i++ ) {
             for( int j=i;j sum )
                 sum = val%m;
             }
            val = 0;
        }
        return sum;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int q = in.nextInt();
        for(int a0 = 0; a0 < q; a0++){
            int n = in.nextInt();
            long m = in.nextLong();
            long[] a = new long[n];
            for(int a_i = 0; a_i < n; a_i++){
                a[a_i] = in.nextLong();
            }
            long result = maximumSum(a, m);
            System.out.println(result);
        }
        in.close();
    }
}

Compilation successful but getting a run time exception as below :-

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:907)
    at java.util.Scanner.next(Scanner.java:1530)
    at java.util.Scanner.nextInt(Scanner.java:2160)
    at java.util.Scanner.nextInt(Scanner.java:2119)
    at Solution.main(Solution.java:29)

Body:
I think J loop is problem you are filling entire sub array with same element

 for ( int i=0;i<a.length;i++ ) {
             for( int j=i;j<a.length;j++ ) {
                 val = val + **a[i]**;
                 if( val%m > sum )
                 sum = val%m;
             }
            val = 0;
        }

Change
val = val + a[i];
to
val = val + a[J];


问:
local URL for apache ErrorDocument directive not working in .htaccess file
I want to use local URL (relative path) to show my custom 404 error message and it doesn't seem to be working as expected. As apache documentation stated here :

The syntax of the ErrorDocument directive is:

ErrorDocument <3-digit-code> <action>

where the action will be treated as:

A local URL to redirect to (if the action begins with a "/").

An external URL to redirect to (if the action is a valid URL).

Text to be displayed (if none of the above). The text must be wrapped in quotes (") if it consists of more than one word.

Methods 2 and 3 are working correctly. For testing purpose imagine a folder named test with 3 files.

index.php: main page

404.php: a custom 404 page

.htaccess:

```<code>RewriteEngine On

ErrorDocument 404 /404.php
</code>```

Now accessing this URL http://localhost/test/blah-blah does not show my 404.php page instead a default Not Found page is displayed with this message:

```<code>The requested URL /tests/test-htaccess/asdasd was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an
ErrorDocument to handle the request.
</code>```

Any idea how to fix this?

答:
You probably found the solution to your problem since the time you asked, but for anyone having the same kind of issue, I would say the problem is that you are running your site with localhost.

The message says that Apache encountered a 404 error when trying to get the file specified for Errordocument 404, so it doesn't see

```<code>/404.php
</code>```

I suggest you create a fake domain in your hosts file and set up a vhost with it.

Hosts on OSX :

```<code>sudo nano /etc/hosts
</code>```

Hosts on Windows, Right-click this file to edit in administrator mode :

```<code> C:\WINDOWS\System32\Drivers\Etc\Hosts
</code>```

and enter something like this:

```<code>127.0.0.1 myfakedomain.com
</code>```

To set up virtual hosts, you must uncomment the call to httpd-vhosts.conf in httpd.conf (near the end, using MAMP in this case)

```<code># Virtual hosts
Include /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf
</code>```

but the location of this file depends of the stack you are using (Wamp, Mamp, Xampp, etc) so search with the keyword "Virtual host" in its documentation.

Then you will be able to run your site using

```<code>myfakedomain.com/
</code>```

in your browser and 404 errors should be handled the right way.

Body:
I want to use local URL (relative path) to show my custom 404 error message and it doesn't seem to be working as expected. As apache documentation stated here :

The syntax of the ErrorDocument directive is:

ErrorDocument <3-digit-code> <action>

where the action will be treated as:

A local URL to redirect to (if the action begins with a "/").

An external URL to redirect to (if the action is a valid URL).

Text to be displayed (if none of the above). The text must be wrapped in quotes (") if it consists of more than one word.

Methods 2 and 3 are working correctly. For testing purpose imagine a folder named test with 3 files.

index.php: main page

404.php: a custom 404 page

.htaccess:

RewriteEngine On

ErrorDocument 404 /404.php

Now accessing this URL http://localhost/test/blah-blah does not show my 404.php page instead a default Not Found page is displayed with this message:

The requested URL /tests/test-htaccess/asdasd was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an
ErrorDocument to handle the request.

Any idea how to fix this?

Body:
You probably found the solution to your problem since the time you asked, but for anyone having the same kind of issue, I would say the problem is that you are running your site with localhost.

The message says that Apache encountered a 404 error when trying to get the file specified for Errordocument 404, so it doesn't see

/404.php

I suggest you create a fake domain in your hosts file and set up a vhost with it.

Hosts on OSX :

sudo nano /etc/hosts

Hosts on Windows, Right-click this file to edit in administrator mode :

 C:\WINDOWS\System32\Drivers\Etc\Hosts

and enter something like this:

127.0.0.1 myfakedomain.com

To set up virtual hosts, you must uncomment the call to httpd-vhosts.conf in httpd.conf (near the end, using MAMP in this case)

# Virtual hosts
Include /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf

but the location of this file depends of the stack you are using (Wamp, Mamp, Xampp, etc) so search with the keyword "Virtual host" in its documentation.

Then you will be able to run your site using

myfakedomain.com/

in your browser and 404 errors should be handled the right way.


问:
Inserting VARCHAR like '10/14/2017' into another table as a DATE datatype
SQL Server 2008 R2

Problem: I need to convert VARCHAR values that look like '10/17/2017', or '3/3/2017' into DATE datatype values while INSERTing them into another table.

Scenario - I have an intermediate table that is populated using BULK INSERT from a csv file, requiring that the datatype for all columns in the intermediate table be VARCHAR (unlike SQL Server 2012, where I was able to use the DATE datatype). This is why the VARCHAR dates look like '3/3/2017'.

I have read many similar questions on StackOverflow and have not found a solution.

Some obvious things I've tried:

These examples successfully convert the VARCHAR to DATE properly, when tested outside of an INSERT operation:

```<code>SELECT CAST (importantDate AS DATE)
SELECT CAST(convert(datetime, '8/15/2007', 101) AS DATE)
</code>```

result: 2007-08-15

However, these conversions fail when used inside an INSERT/SELECT statement:

```<code>INSERT into finalTable
( convertedDate )
SELECT CAST(convert(datetime, importantDate, 101) AS DATE)
FROM intermediateTable

INSERT into finalTable
( convertedDate )
SELECT CAST(importantDate AS DATE)
FROM intermediateTable
</code>```

The resulting error is:
Conversion failed when converting date and/or time from character string.

This is unexpected behavior; I am not sure why this doesn't work. Perhaps I am overlooking something?

Thanks in advance.

答:
The problem was in the data. My co-worker has pointed out that there was a space in the varchar that I didn't catch. The space needs removed, and you need to account for values with different lengths such as 1/1/2017 or 11/11/2017.
Here is his solution:

select cast(ltrim(replace(replace(replace(allocationDate,char(9),' '),char(10),' '),char(13),' ')) as date)

to remove this extra space and successfully insert that value.

Body:
SQL Server 2008 R2

Problem: I need to convert VARCHAR values that look like '10/17/2017', or '3/3/2017' into DATE datatype values while INSERTing them into another table.

Scenario - I have an intermediate table that is populated using BULK INSERT from a csv file, requiring that the datatype for all columns in the intermediate table be VARCHAR (unlike SQL Server 2012, where I was able to use the DATE datatype). This is why the VARCHAR dates look like '3/3/2017'.

I have read many similar questions on StackOverflow and have not found a solution.

Some obvious things I've tried:

These examples successfully convert the VARCHAR to DATE properly, when tested outside of an INSERT operation:

SELECT CAST (importantDate AS DATE)
SELECT CAST(convert(datetime, '8/15/2007', 101) AS DATE)

result: 2007-08-15

However, these conversions fail when used inside an INSERT/SELECT statement:

INSERT into finalTable
( convertedDate )
SELECT CAST(convert(datetime, importantDate, 101) AS DATE)
FROM intermediateTable

INSERT into finalTable
( convertedDate )
SELECT CAST(importantDate AS DATE)
FROM intermediateTable

The resulting error is:
Conversion failed when converting date and/or time from character string.

This is unexpected behavior; I am not sure why this doesn't work. Perhaps I am overlooking something?

Thanks in advance.


问:
Retrieve DataFrame of all but one specified column
Is there a way to select all but one column in a pandas DataFrame object? I've seen ways to delete a column, but I don't want to do that.</p>

答:
```<code>df[ df.columns[df.columns!='not_this_column'] ]
</code>```


问:
How to find the minimum 10th percent of data in Matlab?
I have a vector [224x1] of data and another matching vector of time [224x1]. I want to find the minimum values occupying the lowest 10 percent of the data. How can I do that and find the matching times?

I tried using the sort function (from here: https://www.mathworks.com/matlabcentral/answers/249619-how-do-i-get-the-top-10-percent-of-the-matrix-value) but the times are no longer in chronological order. This is the code I used:

```<code>[sortedValues,sortIndex] = sort(THUL_ST_JJA(:),'ascend'); %Sort Ascending
[sortedDTValues,sortDTIndex] = sort(THUL_dt_JJA(:),'ascend'); %Sort Ascending

idx = sortIndex(1:ceil(length(sortIndex)*0.1)); %Minimum 10th percent STs
THUL_ST_min = THUL_ST_JJA(idx);
THUL_dt_min = THUL_dt_JJA(idx); %Find matching 10th percent minimum times
</code>```

Here's a sample of time (mm/dd/yyyy hh:mm:ss) and temperature out of order:

```<code>06/08/2012 07:00:00 -5.26
06/08/2012 10:00:00 -5.18
06/08/2012 09:00:00 -5.1
06/08/2012 08:00:00 -5.07
06/08/2012 06:00:00 -4.84
06/08/2012 11:00:00 -4.84
06/09/2012 06:00:00 -4.84
06/09/2012 07:00:00 -4.82
06/09/2012 05:00:00 -4.79
06/09/2012 08:00:00 -4.65
08/29/2012 05:00:00 -4.61
06/09/2012 09:00:00 -4.49
08/29/2012 06:00:00 -4.47
</code>```

答:
Sort the data.  Then sort the time using the same index.  This keeps the pairs together.

Then get your index to the data you want & apply the same index to the time.

```<code>[sortData, sortIDX] = sort(rawData,'ascend');
sortTime            = rawTime(sortIDX);

bottom10IDX = 1:ceil(length(sortData)*0.1);
bottom10Data = sortData(bottom10IDX);
bottom10Time = sortTime(bottom10IDX);
</code>```

Body:
I have a vector [224x1] of data and another matching vector of time [224x1]. I want to find the minimum values occupying the lowest 10 percent of the data. How can I do that and find the matching times?

I tried using the sort function (from here: https://www.mathworks.com/matlabcentral/answers/249619-how-do-i-get-the-top-10-percent-of-the-matrix-value) but the times are no longer in chronological order. This is the code I used:

[sortedValues,sortIndex] = sort(THUL_ST_JJA(:),'ascend'); %Sort Ascending
[sortedDTValues,sortDTIndex] = sort(THUL_dt_JJA(:),'ascend'); %Sort Ascending

idx = sortIndex(1:ceil(length(sortIndex)*0.1)); %Minimum 10th percent STs
THUL_ST_min = THUL_ST_JJA(idx);
THUL_dt_min = THUL_dt_JJA(idx); %Find matching 10th percent minimum times

Here's a sample of time (mm/dd/yyyy hh:mm:ss) and temperature out of order:

06/08/2012 07:00:00 -5.26
06/08/2012 10:00:00 -5.18
06/08/2012 09:00:00 -5.1
06/08/2012 08:00:00 -5.07
06/08/2012 06:00:00 -4.84
06/08/2012 11:00:00 -4.84
06/09/2012 06:00:00 -4.84
06/09/2012 07:00:00 -4.82
06/09/2012 05:00:00 -4.79
06/09/2012 08:00:00 -4.65
08/29/2012 05:00:00 -4.61
06/09/2012 09:00:00 -4.49
08/29/2012 06:00:00 -4.47

Body:
Sort the data.  Then sort the time using the same index.  This keeps the pairs together.

Then get your index to the data you want & apply the same index to the time.

[sortData, sortIDX] = sort(rawData,'ascend');
sortTime            = rawTime(sortIDX);

bottom10IDX = 1:ceil(length(sortData)*0.1);
bottom10Data = sortData(bottom10IDX);
bottom10Time = sortTime(bottom10IDX);


问:
Why can't a class member's name be the same as one of its nested classes?
Or why is the following impossible:

```<code>class Material
{
    class Keys
    {
        ...
    }

    Material.Keys Keys { get; set; } // Illegal
}
</code>```

I don't see any possible ambiguity. When accessed by instance, return the property. When access statically, return the class. Or am I missing something?

I'm not asking for a "fix" (I know I could just name it differently, like MaterialKeys or the like), but more of a technical reason behind this limit.

答:
But imagine you had this:

```<code>class Material
{
    class Keys
    {
        ...
    }

    static Material.Keys Keys = new Keys();
}
</code>```

Now both are at "static" scope.  Now, can the compiler disambiguate in all cases?  If not, then this can't be allowed.

I suppose it's possible that the disambiguation would work for static fields/properties/methods, and not for instance members.  Or the other way around.  If that were the case, would you want the language specification to allow an instance member to have the same name as an internal class, but disallow it for statics?  That would just be confusing.

But then, having a member match the name of an internal class is pretty confusing anyway.

ContentLicense: CC BY-SA 2.5

Body:
Or why is the following impossible:

class Material
{
    class Keys
    {
        ...
    }

    Material.Keys Keys { get; set; } // Illegal
}

I don't see any possible ambiguity. When accessed by instance, return the property. When access statically, return the class. Or am I missing something?

I'm not asking for a "fix" (I know I could just name it differently, like MaterialKeys or the like), but more of a technical reason behind this limit.

Body:
But imagine you had this:

class Material
{
    class Keys
    {
        ...
    }

    static Material.Keys Keys = new Keys();
}

Now both are at "static" scope.  Now, can the compiler disambiguate in all cases?  If not, then this can't be allowed.

I suppose it's possible that the disambiguation would work for static fields/properties/methods, and not for instance members.  Or the other way around.  If that were the case, would you want the language specification to allow an instance member to have the same name as an internal class, but disallow it for statics?  That would just be confusing.

But then, having a member match the name of an internal class is pretty confusing anyway.


问:
add icon with UI-grid celltemplate
Here is the tutorial link for angular ui-grid editable feature.
UI-Grid Editable Link

Every row is editable (not header). But I want to add icon to let the user know that this row or cell is editable.

答:
You can display using cellTemplate.

```<code> cellTemplate: '<i class="fa fa-pencil-square-o"></i>'
</code>```

Here is an working Plunkr where the gender icon is placed.

You can replace the icon as per your requirement. Hope this helps.

Title: add icon with UI-grid celltemplate

Body:
You can display using cellTemplate.

 cellTemplate: '<i class="fa fa-pencil-square-o"></i>'

Here is an working Plunkr where the gender icon is placed.

You can replace the icon as per your requirement. Hope this helps.


问:
p4 revert -w option not deleting file properly
According to the p4 help revert, I get:

```<code>    The -w flag causes files that are open for add to be deleted from the
    workspace when they are reverted.
</code>```

But, when I try to use the -w, I get the following:

```<code>> p4 revert -w ./dir1/newfile.c
//depot/test/dir1/newfile.c#1 - was add, reverted
> ls ./dir1/newfile.c
./dir1/newfile.c
</code>```

Am I missing something, or is this a bug in p4?  (Note: my version is as follows):

```<code>Proxy version: P4P/LINUX26X86_64/2014.2/1099171 (2015/06/16)
</code>```

答:
"p4 revert" only undoes the operations that haven't been submitted yet.
It will not delete the file from disk. You should delete the file separately after reverting. </p>

Body:
According to the p4 help revert, I get:

    The -w flag causes files that are open for add to be deleted from the
    workspace when they are reverted.

But, when I try to use the -w, I get the following:

> p4 revert -w ./dir1/newfile.c
//depot/test/dir1/newfile.c#1 - was add, reverted
> ls ./dir1/newfile.c
./dir1/newfile.c

Am I missing something, or is this a bug in p4?  (Note: my version is as follows):

Proxy version: P4P/LINUX26X86_64/2014.2/1099171 (2015/06/16)


问:
how to get values of field form class object nested in another clas
```<code>public void Fill()
    {
        List<testowa1> lista = new List<testowa1>();
        var item = new testowa1()
        {
            ID = 1,
            Nazwa = "Pierwszy",
            Cena = new testowa2()
            {
                Cena = 32.22M
            }
        };
        lista.Add(item);
        lista.Add(item);
        lista.Add(item);
        lista.Add(item);

        dataGridView1.DataSource = lista;
    }

    public class testowa1
    {
        public int ID { get; set; }
        public string Nazwa { get; set; }
        public testowa2 Cena { get; set; }
    }
    public class testowa2
    {
        public decimal Cena { get; set; }
    }
</code>```

that is result:

So, how i can get value of testowa2.Cena into data grid ?
I don't know what to do. I was looking in google but nothing found

答:
I couldn't understand your question completely.

Do you want something like that;

```<code>var cenaValues = dataGridView1.DataSource.Items.Where(x => x.Cena != null)
.Select(x => x.Cena.Cena).ToList();
</code>```

Body:
public void Fill()
    {
        List<testowa1> lista = new List<testowa1>();
        var item = new testowa1()
        {
            ID = 1,
            Nazwa = "Pierwszy",
            Cena = new testowa2()
            {
                Cena = 32.22M
            }
        };
        lista.Add(item);
        lista.Add(item);
        lista.Add(item);
        lista.Add(item);

        dataGridView1.DataSource = lista;
    }

    public class testowa1
    {
        public int ID { get; set; }
        public string Nazwa { get; set; }
        public testowa2 Cena { get; set; }
    }
    public class testowa2
    {
        public decimal Cena { get; set; }
    }

that is result:

So, how i can get value of testowa2.Cena into data grid ?
I don't know what to do. I was looking in google but nothing found

Body:
I couldn't understand your question completely.

Do you want something like that;

var cenaValues = dataGridView1.DataSource.Items.Where(x => x.Cena != null)
.Select(x => x.Cena.Cena).ToList();


问:
Change color of a word in html
I have a .html document that looks like this:

```<code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Change color</title>
  <style>
   .colortext {
     color: red;
   }
  </style>
 </head>
 <body>
  <p>bla bla lbla <span class="colortext">the</span>,
 the balfds of .</p>
 </body>
</html>
</code>```

In this document I give to the a red color. But how should I go in order to change color of every thein my huge text? Is there a way to change color in order not to write

for every word, I need?

答: You can use Javascript to do this. I am not writing the whole code just giving you hints. Get by this var code = document.getElementById("demo") or ByTagName or ByName or any method. Details: https://www.w3schools.com/jsref/met_document_getelementbyid.asp . then replace value "the" with 'the' using javascript replace method. Details: https://www.w3schools.com/jsref/jsref_replace.asp

Title: Change color of a word in html

Body:
I have a .html document that looks like this:

<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>Change color</title>

bla bla lbla the,
 the balfds of .

In this document I give to the a red color. But how should I go in order to change color of every thein my huge text? Is there a way to change color in order not to write

for every word, I need?

Body: You can use Javascript to do this. I am not writing the whole code just giving you hints. Get by this var code = document.getElementById("demo") or ByTagName or ByName or any method. Details: https://www.w3schools.com/jsref/met_document_getelementbyid.asp . then replace value "the" with '<span class="colortext">the</span>' using javascript replace method. Details: https://www.w3schools.com/jsref/jsref_replace.asp


问:
Why can't I pass a const object in a const argument function/method?
EDIT:

Sorry, I'm trying to understand a sample of code, which uses QList::indexOf method, declared as in here.

Actually I'm trying to figure out why I need to use const_cast in this specific case:

```<code>int ProjTreeItem::row() const
{
    if (parentItem) {
            // instance of const object to test
        const ProjTreeItem *item = new ProjTreeItem(QList<QVariant>(), NULL);
            // Called indexOf here to test
        parentItem->childItems.indexOf(item);
            // This works fine
        return parentItem->childItems.indexOf(const_cast<ProjTreeItem*>(this));
    }
    return 0;
}
</code>```

EDIT2:

I was looking at the wrong places, then I started to suspect that the issue had to do with the use of templates and the const modifier. I found this thread here. Please, look at Jon 's answer, which I think clarifies the point I reached. Sorry for the misleadings on my question.

答:
You are making the wrong assumption that the type of item is equal to the type of this, and I believe this is confusing you.

Inside a const function, the type of this is ProjTreeItem const * const item.  But your pointer that works is declared const ProjTreeItem * item:

```<code>// `this` is a constant-pointer-to-a-constant-ProjTreeItem
ProjTreeItem const * const this;   // obviously not valid code, just illustrating type

// `item` is simply a pointer-to-a-constant-ProjTreeItem
const ProjTreeItem * item;
</code>```

It helps to read the declaration right to left.

So, declare you item pointer like this and I suspect you'll need a cast as well.

```<code>const ProjTreeItem * const item = new ProjTreeItem(QList<QVariant>(), NULL);
</code>```

Body:
EDIT:

Sorry, I'm trying to understand a sample of code, which uses QList::indexOf method, declared as in here.

Actually I'm trying to figure out why I need to use const_cast in this specific case:

int ProjTreeItem::row() const
{
    if (parentItem) {
            // instance of const object to test
        const ProjTreeItem *item = new ProjTreeItem(QList<QVariant>(), NULL);
            // Called indexOf here to test
        parentItem->childItems.indexOf(item);
            // This works fine
        return parentItem->childItems.indexOf(const_cast<ProjTreeItem*>(this));
    }
    return 0;
}

EDIT2:

I was looking at the wrong places, then I started to suspect that the issue had to do with the use of templates and the const modifier. I found this thread here. Please, look at Jon 's answer, which I think clarifies the point I reached. Sorry for the misleadings on my question.

Body:
You are making the wrong assumption that the type of item is equal to the type of this, and I believe this is confusing you.

Inside a const function, the type of this is ProjTreeItem const * const item.  But your pointer that works is declared const ProjTreeItem * item:

// `this` is a constant-pointer-to-a-constant-ProjTreeItem
ProjTreeItem const * const this;   // obviously not valid code, just illustrating type

// `item` is simply a pointer-to-a-constant-ProjTreeItem
const ProjTreeItem * item;

It helps to read the declaration right to left.

So, declare you item pointer like this and I suspect you'll need a cast as well.

const ProjTreeItem * const item = new ProjTreeItem(QList<QVariant>(), NULL);


问:
How does Log.wtf() differ from Log.e()?
I have looked at the documentation for android.util.Log and I'm not sure exactly what the difference between Log.e() and Log.wtf() is. Is one preferred over the other? Is there a functionality difference? Surely they aren't redundant.

Note to future readers: At the time this question was asked, the documentation for this was much less clear. If you follow the link above, they have fixed the problem.

答:
TL;DR

Log.wtf() might call onTerribleFailure() and can cause termination of your application.

COMMON MISTAKE

Official docs say:

Log.e() logs with priority ERROR. However, Log.wtf() logs with priority ASSERT.

ASSERT has priority constant = 7

ERROR has priority constant = 6

So Log.wtf() has higher priority with respect to Log.e()

However source code conflicts with above information.

```<code>static int wtf(int logId, String tag, String msg, Throwable tr,boolean localStack, boolean system) {

    TerribleFailure what = new TerribleFailure(msg, tr);
    // Only mark this as ERROR, do not use ASSERT since that should be
    // reserved for cases where the system is guaranteed to abort.
    // The onTerribleFailure call does not always cause a crash.
    int bytes = printlns(logId, ERROR, tag, msg, localStack ? what : tr);
    ...
}
</code>```

It looks like there is a mistake in Official docs. Because both Log.wtf() and Log.e() logs with priority ERROR.

REAL DIFFERENCE

Source Code for Log.e():

```<code>public static int e(@Nullable String tag, @Nullable String msg,@Nullable Throwable tr) {
    return printlns(LOG_ID_MAIN, ERROR, tag, msg, tr);
}
</code>```

The difference is that Log.wtf() might call onTerribleFailure() call back.

onTerribleFailure() may or may not cause the process to terminate (depends on system settings).

Title: How does Log.wtf() differ from Log.e()?

Body:
TL;DR

Log.wtf() might call onTerribleFailure() and can cause termination of your application.

COMMON MISTAKE

Official docs say:

Log.e() logs with priority ERROR. However, Log.wtf() logs with priority ASSERT.

ASSERT has priority constant = 7

ERROR has priority constant = 6

So Log.wtf() has higher priority with respect to Log.e()

However source code conflicts with above information.

static int wtf(int logId, String tag, String msg, Throwable tr,boolean localStack, boolean system) {

    TerribleFailure what = new TerribleFailure(msg, tr);
    // Only mark this as ERROR, do not use ASSERT since that should be
    // reserved for cases where the system is guaranteed to abort.
    // The onTerribleFailure call does not always cause a crash.
    int bytes = printlns(logId, ERROR, tag, msg, localStack ? what : tr);
    ...
}

It looks like there is a mistake in Official docs. Because both Log.wtf() and Log.e() logs with priority ERROR.

REAL DIFFERENCE

Source Code for Log.e():

public static int e(@Nullable String tag, @Nullable String msg,@Nullable Throwable tr) {
    return printlns(LOG_ID_MAIN, ERROR, tag, msg, tr);
}

The difference is that Log.wtf() might call onTerribleFailure() call back.

onTerribleFailure() may or may not cause the process to terminate (depends on system settings).

ContentLicense: CC BY-SA 4.0


问:
Is using output buffering considered a bad practice?
Are ob_start / ob_get_clean() considered bad practice by php programmers in general?

Are there any disadvantages of output buffering?

答:
output buffering is NOT a bad practice. For example it can speed up the loading of your website by using GZIP compression(although if possible it is better to do this inside .htaccess).

```<code><?php
    if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip'))
        ob_start("ob_gzhandler");
    else
        ob_start();
?>
</code>```

Disadvantages: I don't know. Good question.

P.S: also I found this topic about output buffering.

Body:
output buffering is NOT a bad practice. For example it can speed up the loading of your website by using GZIP compression(although if possible it is better to do this inside .htaccess).

<?php
    if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip'))
        ob_start("ob_gzhandler");
    else
        ob_start();
?>

Disadvantages: I don't know. Good question.

P.S: also I found this topic about output buffering.


问:
How to count items in csv file python?
I'm using kaggle imdb 5000 dataset you can see details here.
I'm trying to make new csv file look like .
But the genre row also has to split.

Genre row:

  [{"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"}, {"id": 14, "name": "Fantasy"}, {"id": 878, "name": "Science Fiction"}]

How can I take name attributes in Genre row?

```<code>with open(filename) as myFile:
    reader = csv.DictReader(myFile)
    for row in reader:
        print(row['genres'].'name')
</code>```

print(row['genres'].'name') doesn't work.

答:
Look more carefully to your own example:
you have a list of dictionaries with two keys : they are not nested.

```<code>{"id": 28, "name": "Action"}
</code>```

row['genres'].'name' is wrong for the syntax and for what you are trying to do:

row['genres']['name'] would mean: {"id": { "name": "Action"} }

So try take name attributes like:

```<code>print(row['genres'], row['name'])
</code>```

for a neat example, see also the doc: https://docs.python.org/2/library/csv.html#csv.DictReader

Title: How to count items in csv file python?

Body:
I'm using kaggle imdb 5000 dataset you can see details here.
I'm trying to make new csv file look like .
But the genre row also has to split.

Genre row:

  [{"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"}, {"id": 14, "name": "Fantasy"}, {"id": 878, "name": "Science Fiction"}]

How can I take name attributes in Genre row?

with open(filename) as myFile:
    reader = csv.DictReader(myFile)
    for row in reader:
        print(row['genres'].'name')

print(row['genres'].'name') doesn't work.

Body:
Look more carefully to your own example:
you have a list of dictionaries with two keys : they are not nested.

{"id": 28, "name": "Action"}

row['genres'].'name' is wrong for the syntax and for what you are trying to do:

row['genres']['name'] would mean: {"id": { "name": "Action"} }

So try take name attributes like:

print(row['genres'], row['name'])

for a neat example, see also the doc: https://docs.python.org/2/library/csv.html#csv.DictReader


问:
Syntax issues in OS detection
I'm working on a script using bash to determine the os being used and print to the screen the version.

The only line giving me issues is this one, could you please help me?:

答:
```<code>source /etc/os-release
current_os=$PRETTY_NAME
</code>```

or if you don't want to pull everything in

```<code>current_os=$(source /etc/os-release && echo $PRETTY_NAME)
</code>```

Title: Syntax issues in OS detection

Body:
source /etc/os-release
current_os=$PRETTY_NAME

or if you don't want to pull everything in

current_os=$(source /etc/os-release && echo $PRETTY_NAME)


问:
Azure Storage Queue - Trigger on empty
I have a nodejs Azure Function reading for a Storage Queue which is being filled once a day. When all messages have been processed and the results are stored in a table I'd like to call a final function doing some work with the gathered data.

What's the best way to achieve this? Can I get the remaining messages in the queue inside my nodejs bindings? Do I have to peek the queue through the nodejs azure sdk? Can I trigger a different function when the queue runs empty?

答:
The problem for your business scenario is how the function knows, that the received message is the last one from the queue. There is no direct property/method to obtain this value such as a number of visible messages in the queue.
Your question is interesting, you ask about the "Trigger on empty". It not easy to implemented this kind of event in the queue comparing to the "Trigger on message".

However, for distributed event-driven architecture (serverless architecture) can help a pattern using a distributed Watchdog, when each business processor (function/microservice/etc.) can fire a Watchdog Event such as a ScheduleMessage, for instance, 30 seconds. Within this time, this Watchdog Event can be canceled or retriggered, otherwise the Watchdog Event Message will be visible in the watchdog queue/topic entity.

Watchdog usage for your case is very straightforward. Your QueueTrigger Function is sending a Watchdog Event message to indicate a business processing. If this business process has been finished, the Watchdog is not any more retriggered and it will expire after its configured time (30s), so the Watchdog Event message is visible for its reader/subscriber.

The following screen snippets shows this model:

As you can see, the Watchdog is based on the Azure Service Bus Schedule/CancelScheduled messages. There is no something like RetriggerScheduledMessage, basically the retriggering scheduled message in the Service Bus Entity is done in the two steps such as CancelScheduledMessage based on its sequence number and create new one using a ScheduleMessage call (new sequence number).
Handling these steps is done in the QueueTrigger Function calls as Watchdog with a Lease Blob for keeping a counter and sequence number of the ScheduleMessage.

It will be nice, if the Azure Service Bus Entity Queue/Topic has built-in this kind of Watchdog with a capability to retrigger already scheduled message, so we can keep the same sequence number for all business process/task.

Anyway, if you are interesting about this Watchdog Function, I can update my answer with its implementation in C#.

Title: Azure Storage Queue - Trigger on empty


问:
C++ - Object slicing even after using pointers
I have a base class Shape, and a derived class Circle which inherits Shape publically:

```<code>class Circle : public Shape
</code>```

I made a C++ vector of Shape pointers, and I assigned Circle pointers to them. I'd read up a lot on object slicing so expected the code to treat the Circle in the vector as a Circle, not a Shape.

Can anyone point out what's wrong with this, given the output?

```<code>int main(void) {
vector<Shape*> shapes;

Circle* ncl = new Circle(-8, -8, 0.2f);
shapes.push_back(ncl);

cout << "Expected: " << *ncl << endl;
cout << "Reality: " << *shapes[0] << endl;
}
</code>```

outputs:

```<code>Expected: Circle is at: -8,-8 and has a radius of: 0.2
Reality: Shape centered at point: -8,-8
</code>```

I have overridden the << operator for both classes out of scope, so I think that's not the problem, but still - here's the code context of my overrides:

```<code>inline std::ostream& operator<< (std::ostream& stream, const Shape& shape) {
    std::cout << "Shape centered at point: " << shape.getX() << "," << shape.getY();
    return stream;
}

inline std::ostream& operator<< (std::ostream& stream, const Circle& circle) {
    std::cout << "Circle is at: " << circle.getX() << "," << circle.getY() <<
        " and has a radius of: " << circle.getR();
    return stream;
}
</code>```

All in all - I want to be able to access my Circle variables properly while they're stored in the Shape vector (with pointers or otherwise).

答:
There's no slicing involved, it just looks like it.

Overloads are selected at compile time, from the static type as it is known to the compiler.

Since shapes is a vector<Shape*>, *shapes[0] is a Shape&, and that overload is chosen.

The common solution is to only write an operator<< for the base class, and that in turn calls a virtual function on the object.

This will let the dynamic function dispatch select the function at runtime.

For instance:

```<code>struct Shape  { virtual ostream& print(ostream& os) const { ... } };
struct Circle { ostream& print(ostream& os) const override { ... } };

ostream& operator<<(ostream& os, const Shape& s) { return s.print(os); }
</code>```

Body:
I have a base class Shape, and a derived class Circle which inherits Shape publically:

class Circle : public Shape

I made a C++ vector of Shape pointers, and I assigned Circle pointers to them. I'd read up a lot on object slicing so expected the code to treat the Circle in the vector as a Circle, not a Shape.

Can anyone point out what's wrong with this, given the output?

int main(void) {
vector<Shape*> shapes;

Circle* ncl = new Circle(-8, -8, 0.2f);
shapes.push_back(ncl);

cout << "Expected: " << *ncl << endl;
cout << "Reality: " << *shapes[0] << endl;
}

outputs:

Expected: Circle is at: -8,-8 and has a radius of: 0.2
Reality: Shape centered at point: -8,-8

I have overridden the << operator for both classes out of scope, so I think that's not the problem, but still - here's the code context of my overrides:

inline std::ostream& operator<< (std::ostream& stream, const Shape& shape) {
    std::cout << "Shape centered at point: " << shape.getX() << "," << shape.getY();
    return stream;
}

inline std::ostream& operator<< (std::ostream& stream, const Circle& circle) {
    std::cout << "Circle is at: " << circle.getX() << "," << circle.getY() <<
        " and has a radius of: " << circle.getR();
    return stream;
}

All in all - I want to be able to access my Circle variables properly while they're stored in the Shape vector (with pointers or otherwise).

Body:
There's no slicing involved, it just looks like it.

Overloads are selected at compile time, from the static type as it is known to the compiler.

Since shapes is a vector<Shape*>, *shapes[0] is a Shape&, and that overload is chosen.

The common solution is to only write an operator<< for the base class, and that in turn calls a virtual function on the object.

This will let the dynamic function dispatch select the function at runtime.

For instance:

struct Shape  { virtual ostream& print(ostream& os) const { ... } };
struct Circle { ostream& print(ostream& os) const override { ... } };

ostream& operator<<(ostream& os, const Shape& s) { return s.print(os); }


问:
Socket.io behind load balancer
I am using socket.io behind nginx which is behind azure load balancer. How ever On the client side I am constantly getting errors like

```<code>WebSocket connection to 'ws://**********/socket.io/?    session_id=i9bk_iqkVrUveKwvIBz4fMNDbkoYuaITQ_APO73sgQd6-tQBaRkjp8RR8N9LTA5LnqMeKXzZg5AXXgjEevFKqSKRJJI8iaK3&id=dc978ae038af4746baf68ead35d182f4&EIO=3&transport=websocket&sid=61LGLpdw53xaMYqBAAJR' failed: Error during WebSocket handshake: Unexpected response code: 502
</code>```

Also nginx gives the error below

```<code>[error] 15348#0: *84812 upstream prematurely closed connection while reading response header from upstream, client: 10.100.50.14, server: _, request: "GET /prod/socket.io/?session_id=nR0P30IDeUutoavDyjcqAQ8hUw_3l7dtAHQ3tqzW4zVT8eBOxwbHZq_7mWd9K7qRNO2Aq45QXm8w2KSvzyFlq3O4w7P2tl2q&id=955bb63a4f804b42b9d85ac8cf9172a7&EIO=3&transport=websocket&sid=xXGRnAsjKX6Gj-SAAAls HTTP/1.1", upstream: "http://127.0.0.1:3000/socket.io/?session_id=nR0P30IDeUutoavDyjcqAQ8hUw_3l7dtAHQ3tqzW4zVT8eBOxwbHZq_7mWd9K7qRNO2Aq45QXm8w2KSvzyFlq3O4w7P2tl2q&id=955bb63a4f804b42b9d85ac8cf9172a7&EIO=3&transport=websocket&sid=xXGRnAsjKX6Gj-SAAAls"
</code>```

Anyone have an idea about the reason?

Nginx conf:

```<code>proxy_pass http://lb-prod/; # Load balance the URL location "/" to the upstream lb1
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
</code>```

答: The problem here was about session stickyness. Configuring my load balancer to use sticky session solved the problem!

Title: Socket.io behind load balancer

Body:
I am using socket.io behind nginx which is behind azure load balancer. How ever On the client side I am constantly getting errors like

WebSocket connection to 'ws://**********/socket.io/?    session_id=i9bk_iqkVrUveKwvIBz4fMNDbkoYuaITQ_APO73sgQd6-tQBaRkjp8RR8N9LTA5LnqMeKXzZg5AXXgjEevFKqSKRJJI8iaK3&id=dc978ae038af4746baf68ead35d182f4&EIO=3&transport=websocket&sid=61LGLpdw53xaMYqBAAJR' failed: Error during WebSocket handshake: Unexpected response code: 502

Also nginx gives the error below

[error] 15348#0: *84812 upstream prematurely closed connection while reading response header from upstream, client: 10.100.50.14, server: _, request: "GET /prod/socket.io/?session_id=nR0P30IDeUutoavDyjcqAQ8hUw_3l7dtAHQ3tqzW4zVT8eBOxwbHZq_7mWd9K7qRNO2Aq45QXm8w2KSvzyFlq3O4w7P2tl2q&id=955bb63a4f804b42b9d85ac8cf9172a7&EIO=3&transport=websocket&sid=xXGRnAsjKX6Gj-SAAAls HTTP/1.1", upstream: "http://127.0.0.1:3000/socket.io/?session_id=nR0P30IDeUutoavDyjcqAQ8hUw_3l7dtAHQ3tqzW4zVT8eBOxwbHZq_7mWd9K7qRNO2Aq45QXm8w2KSvzyFlq3O4w7P2tl2q&id=955bb63a4f804b42b9d85ac8cf9172a7&EIO=3&transport=websocket&sid=xXGRnAsjKX6Gj-SAAAls"

Anyone have an idea about the reason?

Nginx conf:

proxy_pass http://lb-prod/; # Load balance the URL location "/" to the upstream lb1
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;


问:
Java generics in List return type on a method inherited from multiple interfaces
I'm currently working at a company that has a diverse set of modules. In that company if you want to provide module internals you provide it via a java interface, that hides the actual implementing type and gives an interface for the requesting module. Now I want to have one provider to be able to provide data for multiple modules that expose different fields or methods of the actual internal data.

Therefore I have an internal Object, which has some data and I have an interface for each module that needs access to some but not strictly all fields. Finally I have an external object that implements all those interfaces and holds an instance of the internal object to delegate the method calls:

```<code>public class InternalObject {
    public int getA() { return 0; }
    public int getB() { return 0; }
}

public interface ModuleXObject {
   int getA();
}

public interface ModuleYObject {
    int getA();
    int getB();
}

public class ExternalObject implements ModuleXObject, ModuleYObject {
    private InternalObject _internal;

    public int getA() { return _internal.getA(); }
    public int getB() { return _internal.getB(); }
}
</code>```

Now that is all fine and dandy, but if I want to provide - lets say - repository methods for finding a list of said objects typed for the correct module, I run into problems with how I can achieve that. I would wish for something like the following:

```<code>public interface ModuleXObjectRepository {
    List<ModuleXObject> loadAllObjects();
}

public interface ModuleYObjectRepository {
    List<ModuleYObject> loadAllObjects();
}

public class ExternalObjectRepository implements ModuleXObjectRepository, ModuleYObjectRepository {
    public List<ExternalObject> loadAllObjects() {
        // ...
    }
}
</code>```

This doesn't compile saying the return type is incompatible.
So my question is, if it is possible to achieve something like that and if, how?

I should note that I tried some different approaches which I want to include for completeness and to portray their downsides (in my eyes).

Approach 1:

```<code>public interface ModuleXObjectRepository {
    List<? extends ModuleXObject> loadAllObjects();
}

public interface ModuleYObjectRepository {
    List<? extends ModuleYObject> loadAllObjects();
}

public class ExternalObjectRepository implements ModuleXObjectRepository, ModuleYObjectRepository {
    public List<ExternalObject> loadAllObjects() {
        // ...
    }
}
</code>```

This approach is quite close to the solution I would prefer, but results in code like this:

```<code>List<? extends ModuleXObject> objects = repository.loadAllObjects();
</code>```

Therefore requiring the user to include the "? extends" into each List-Declaration regarding to an invocation of loadAllObjects().

Approach 2:

```<code>public interface ModuleXObjectRepository {
    List<ModuleXObject> loadAllObjects();
}

public interface ModuleYObjectRepository {
    List<ModuleYObject> loadAllObjects();
}

public class ExternalObjectRepository implements ModuleXObjectRepository, ModuleYObjectRepository {
    public List loadAllObjects() {
        // ...
    }
}
</code>```

This approach just omits the generic in the ExternalObjectRepository and therefore reduces the type safety too much in my opinion. Also I haven't tested if this actually works.

Just to reharse, is there any possible way to define the loadAllObjects-method in a way that enables users to get lists that are typed with the objects for their respective module without

requiring "? extends" in the users code

degrading type safety in the repository implementation

using class/interface level generics

答:
The challenge with allowing it to be typed as List<ModuleXObject> is that other code may hold is as a List<ExternalObject>.

All ExternalObject instances are ModuleXObject instances but the inverse is not true.

Consider the following additional class:

```<code>public class MonkeyWrench implements ModuleXObject{
    //STUFF
}
</code>```

MonkeyWrench instances are NOT ExternalObject instances but if one could cast a List<ExternalObject> to a List<ModuleXObject> one could add MonkeyWrench instances to this collection, and this causes a risk of run time class cast exceptions and ruins type safety.

Other code could very easily have:

```<code>for(ExternalObject externalObject:externalObjectRepository.loadAllObjects())
</code>```

If one of those instances is a MonkeyWrench instance, run time class cast, which is what generics are meant to avoid.

The implication of ? extends ModuleXObject is that you can read any object from the collection as a ModuleXObject but you can't add anything to the collection as other code may have additional constraints on the collection that are not obvious/available at compile time.

I'd suggest in your case to use ? extends ModuleXObject as its semantics seem to align with what you want, namely pulling out ModuleXObject instances, e.g.

```<code>ModuleXObjectRepository repo = //get repo however
for(ModuleXObject obj : repo.loadAllObjects()){
    //do stuff with obj
}
</code>```

Body:
I'm currently working at a company that has a diverse set of modules. In that company if you want to provide module internals you provide it via a java interface, that hides the actual implementing type and gives an interface for the requesting module. Now I want to have one provider to be able to provide data for multiple modules that expose different fields or methods of the actual internal data.

Therefore I have an internal Object, which has some data and I have an interface for each module that needs access to some but not strictly all fields. Finally I have an external object that implements all those interfaces and holds an instance of the internal object to delegate the method calls:

public class InternalObject {
    public int getA() { return 0; }
    public int getB() { return 0; }
}

public interface ModuleXObject {
   int getA();
}

public interface ModuleYObject {
    int getA();
    int getB();
}

public class ExternalObject implements ModuleXObject, ModuleYObject {
    private InternalObject _internal;

    public int getA() { return _internal.getA(); }
    public int getB() { return _internal.getB(); }
}

Now that is all fine and dandy, but if I want to provide - lets say - repository methods for finding a list of said objects typed for the correct module, I run into problems with how I can achieve that. I would wish for something like the following:

public interface ModuleXObjectRepository {
    List<ModuleXObject> loadAllObjects();
}

public interface ModuleYObjectRepository {
    List<ModuleYObject> loadAllObjects();
}

public class ExternalObjectRepository implements ModuleXObjectRepository, ModuleYObjectRepository {
    public List<ExternalObject> loadAllObjects() {
        // ...
    }
}

This doesn't compile saying the return type is incompatible.
So my question is, if it is possible to achieve something like that and if, how?

I should note that I tried some different approaches which I want to include for completeness and to portray their downsides (in my eyes).

Approach 1:

public interface ModuleXObjectRepository {
    List<? extends ModuleXObject> loadAllObjects();
}

public interface ModuleYObjectRepository {
    List<? extends ModuleYObject> loadAllObjects();
}

public class ExternalObjectRepository implements ModuleXObjectRepository, ModuleYObjectRepository {
    public List<ExternalObject> loadAllObjects() {
        // ...
    }
}

This approach is quite close to the solution I would prefer, but results in code like this:

List<? extends ModuleXObject> objects = repository.loadAllObjects();

Therefore requiring the user to include the "? extends" into each List-Declaration regarding to an invocation of loadAllObjects().

Approach 2:

public interface ModuleXObjectRepository {
    List<ModuleXObject> loadAllObjects();
}

public interface ModuleYObjectRepository {
    List<ModuleYObject> loadAllObjects();
}

public class ExternalObjectRepository implements ModuleXObjectRepository, ModuleYObjectRepository {
    public List loadAllObjects() {
        // ...
    }
}

This approach just omits the generic in the ExternalObjectRepository and therefore reduces the type safety too much in my opinion. Also I haven't tested if this actually works.

Just to reharse, is there any possible way to define the loadAllObjects-method in a way that enables users to get lists that are typed with the objects for their respective module without

requiring "? extends" in the users code

degrading type safety in the repository implementation

using class/interface level generics

Body:
The challenge with allowing it to be typed as List<ModuleXObject> is that other code may hold is as a List<ExternalObject>.

All ExternalObject instances are ModuleXObject instances but the inverse is not true.

Consider the following additional class:

public class MonkeyWrench implements ModuleXObject{
    //STUFF
}

MonkeyWrench instances are NOT ExternalObject instances but if one could cast a List<ExternalObject> to a List<ModuleXObject> one could add MonkeyWrench instances to this collection, and this causes a risk of run time class cast exceptions and ruins type safety.

Other code could very easily have:

for(ExternalObject externalObject:externalObjectRepository.loadAllObjects())

If one of those instances is a MonkeyWrench instance, run time class cast, which is what generics are meant to avoid.

The implication of ? extends ModuleXObject is that you can read any object from the collection as a ModuleXObject but you can't add anything to the collection as other code may have additional constraints on the collection that are not obvious/available at compile time.

I'd suggest in your case to use ? extends ModuleXObject as its semantics seem to align with what you want, namely pulling out ModuleXObject instances, e.g.

ModuleXObjectRepository repo = //get repo however
for(ModuleXObject obj : repo.loadAllObjects()){
    //do stuff with obj
}


答:
```<code>import json
with open(filename) as myFile:
    reader = csv.DictReader(myFile)
    for row in reader:
        if not isinstance(row, dict):  # The row might be a string, in that case, parse it to a dict.
            row = json.loads(row)  # Parse the json row and convert it to dict.
        print([o['name'] for o in row])  # Iterate over every entry in the row and access the value 'name', will return a list of genre names.

        print(', '.join([o['name'] for o in row]))  # Will return a string of comma separated genre names.

        print([{'name': o['name']} for o in row])  # Will return a list of Genre objects, deleting all keys but 'name'
</code>```

Title: How to count items in csv file python?


问:
Sorting an array of more than 10 objects in Chrome
```<code>[
{"tag":"fujairah","count":1},
{"tag":"worldwide","count":3},
{"tag":"saudi","count":1},
{"tag":"miami","count":1},
{"tag":"rwo-dealer","count":7},
{"tag":"new york","count":2},
{"tag":"surabaya","count":1},
{"tag":"phillippines","count":1},
{"tag":"vietnam","count":1},
{"tag":"norway","count":1},
{"tag":"x","count":1}
].sort(function(a,b){return a.tag>b.tag})
</code>```

Sorting an array of 10 objects works fine, once the number of objects exceeds 10, the sort fails in Chrome for Mac. Safari fails at any array size. (Works fine in Firefox)

What is the correct way of sorting arrays of objects by javascript?

答:
As noted in the accepted answer the only way to assure the compare function results in expected sort order is to return a number other than 0.

The reasoning for this though is important and should be noted for reference purposes. ECMA standards allow for browser implementations to be unstable. As such there can be no expectation that a function returning 0 will result in the original sort order.

http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.11

The sort is not necessarily stable (that is, elements that compare equal do not necessarily remain in their original order). If comparefn is not undefined, it should be a function that accepts two arguments x and y and returns a negative value if x < y, zero if x = y, or a positive value if x > y.

Now for Chrome (and others). Browsers can use whatever sort algorithms they want based on whatever criteria they choose. Since certain algorithms are more efficient based on array size the vendor can choose to change the underlying algo dynamically based on the array size. This is why you're seeing this behavior.

At the time of writing the Chromium source uses length <= 10 as the deciding factor.

https://cs.chromium.org/chromium/src/v8/src/js/array.js?l=707&rcl=9c7cccf55126353a101f194bcf1f8826bc263804

```<code>function InnerArraySort(array, length, comparefn) {
  // In-place QuickSort algorithm.
  // For short (length <= 10) arrays, insertion sort is used for efficiency.
  ...
  if (to - from <= 10) {
    InsertionSort(a, from, to);
    return;
  }
 ...
</code>```

Body:
[
{"tag":"fujairah","count":1},
{"tag":"worldwide","count":3},
{"tag":"saudi","count":1},
{"tag":"miami","count":1},
{"tag":"rwo-dealer","count":7},
{"tag":"new york","count":2},
{"tag":"surabaya","count":1},
{"tag":"phillippines","count":1},
{"tag":"vietnam","count":1},
{"tag":"norway","count":1},
{"tag":"x","count":1}
].sort(function(a,b){return a.tag>b.tag})

Sorting an array of 10 objects works fine, once the number of objects exceeds 10, the sort fails in Chrome for Mac. Safari fails at any array size. (Works fine in Firefox)

What is the correct way of sorting arrays of objects by javascript?

Body:
As noted in the accepted answer the only way to assure the compare function results in expected sort order is to return a number other than 0.

The reasoning for this though is important and should be noted for reference purposes. ECMA standards allow for browser implementations to be unstable. As such there can be no expectation that a function returning 0 will result in the original sort order.

http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.11

The sort is not necessarily stable (that is, elements that compare equal do not necessarily remain in their original order). If comparefn is not undefined, it should be a function that accepts two arguments x and y and returns a negative value if x < y, zero if x = y, or a positive value if x > y.

Now for Chrome (and others). Browsers can use whatever sort algorithms they want based on whatever criteria they choose. Since certain algorithms are more efficient based on array size the vendor can choose to change the underlying algo dynamically based on the array size. This is why you're seeing this behavior.

At the time of writing the Chromium source uses length <= 10 as the deciding factor.

https://cs.chromium.org/chromium/src/v8/src/js/array.js?l=707&rcl=9c7cccf55126353a101f194bcf1f8826bc263804

function InnerArraySort(array, length, comparefn) {
  // In-place QuickSort algorithm.
  // For short (length <= 10) arrays, insertion sort is used for efficiency.
  ...
  if (to - from <= 10) {
    InsertionSort(a, from, to);
    return;
  }
 ...


问:
MongoDb C# driver - serializing List<enum> as string[]
I have a class with a property of type List<SomeEnum>. Something like this:

```<code>public enum MyEnum
{
  A,
  B
}

public class MyClass
{
    public string Id { get; set; }
    public List<MyEnum> Values { get; set; }
}
</code>```

I'm already using the EnumRepresentationConvention in this way:

```<code>ConventionRegistry.Register("EnumStringConvention", new ConventionPack { new EnumRepresentationConvention(BsonType.String) }, t => true);
</code>```

Still, the Values property gets serialized as an array of ints (simple enum properties are correctly handled as ints). It seem the convention is not used in the context of the list serialization.

How can I enforce the serializer to write strings instead of ints?

答:
Instead of calling ConventionRegistry.Register(), add data annotation [BsonRepresentation(BsonType.String)] to the property Values of MyClass.

```<code>public class MyClass
{
    public string Id { get; set; }

    [BsonRepresentation(BsonType.String)]
    public List<MyEnum> Values { get; set; }
}
</code>```

After that change collection.InsertOne(obj); is saving this:

```<code>{
    "_id" : "1",
    "Values" : [
        "A",
        "B"
    ]
}
</code>```

Body:
I have a class with a property of type List<SomeEnum>. Something like this:

public enum MyEnum
{
  A,
  B
}

public class MyClass
{
    public string Id { get; set; }
    public List<MyEnum> Values { get; set; }
}

I'm already using the EnumRepresentationConvention in this way:

ConventionRegistry.Register("EnumStringConvention", new ConventionPack { new EnumRepresentationConvention(BsonType.String) }, t => true);

Still, the Values property gets serialized as an array of ints (simple enum properties are correctly handled as ints). It seem the convention is not used in the context of the list serialization.

How can I enforce the serializer to write strings instead of ints?

Body:
Instead of calling ConventionRegistry.Register(), add data annotation [BsonRepresentation(BsonType.String)] to the property Values of MyClass.

public class MyClass
{
    public string Id { get; set; }

    [BsonRepresentation(BsonType.String)]
    public List<MyEnum> Values { get; set; }
}

After that change collection.InsertOne(obj); is saving this:

{
    "_id" : "1",
    "Values" : [
        "A",
        "B"
    ]
}


问:
What tools are available to edit manpages, i.e. GUI WYSIWYG editors (any platform)
Is there any decent GUI(Graphical User Interface) WYSIWYG(What You See is What You Get) editor (on any platform) that can be used for authoring/editing manpages?  An app that can export to the troff format would also be fine.</p>

答:
There is an online editor for man pages in mdoc format: http://roperzh.github.io/grapse/

Mdoc is a semantic markup for man pages. It has been around for about two decades and supported by Linux and other Unix-like OSes. You should prefer mdoc to troff.


问:
Default value at the same time possibility seding whole object item with ngrepeat to function AngularJS
I am trying to pass parameter to function changeBoard whole variable item but If i dont set value="item._id" i can't have default value. If I set i can only pass item._id.

Can someone help me how can I pass whole parametere item at the same time have default selected?

```<code>demo
</code>```

https://codepen.io/Turqus/pen/LOjvLL?editors=1111

```<code>var app = angular.module('test', []);
</code>```

template html

```<code><div ng-app="test" ng-controller="select">

 <select class="form-control" ng-model="selectedBoard" ng-change="changeBoard(selectedBoard)">
     <option ng-repeat="item in arrayItems" value="{{item.id}}">{{item.name}}</option>
 </select>

</div>
</code>```

controller

```<code>  var app = angular.module('test', []);

app.controller('select', $scope=>{
  $scope.arrayItems = [
    {'id': '133', 'name':'first', 'lists':[{'name': 1}, {'name': 2}]},
    {'id': '134', 'name':'second', 'lists':[{'name': 1}, {'name': 2}]},
    {'id': '135', 'name':'third', 'lists':[{'name': 1}, {'name': 2}]},
    {'id': '136', 'name':'fourth', 'lists':[{'name': 1}, {'name': 2}]}
  ];

  $scope.selectedBoard = '134';

  $scope.changeBoard = (selectedBoard) => {
    console.log(selectedBoard)
  }
});
</code>```

答:
You can use the Javascript function .filter(). It's kind of like an SQL WHERE statement, but for Javascript arrays. It'll just filter out anything based on the function given for it.

In my example, you can remove the pass of selectedBoard to the function call in your ng-change method. Since you are already binding to the model $scope.selectedBoard.

! function() {

  var app = angular.module('test', []);

  var select = function($scope) {
    $scope.arrayItems = [{
        'id': '133',
        'name': 'first',
        'lists': [{
          'name': 1
        }, {
          'name': 2
        }]
      },
      {
        'id': '134',
        'name': 'second',
        'lists': [{
          'name': 1
        }, {
          'name': 2
        }]
      },
      {
        'id': '135',
        'name': 'third',
        'lists': [{
          'name': 1
        }, {
          'name': 2
        }]
      },
      {
        'id': '136',
        'name': 'fourth',
        'lists': [{
          'name': 1
        }, {
          'name': 2
        }]
      }
    ];

    $scope.selectedBoard = '';

    $scope.changeBoard = () => {
      var obj = $scope.arrayItems.filter(item => item.id == $scope.selectedBoard);
      // var obj = $scope.arrayItems.filter(function(item) { // Can also be written as this
      //   return item.id == $scope.selectedBoard;
      // });
      console.log(obj);
    }
  };

  app.controller("select", ["$scope", select]);
}();```
<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="test" ng-controller="select">

  <select class="form-control" ng-model="selectedBoard" ng-change="changeBoard()">
     <option ng-repeat="item in arrayItems" value="{{item.id}}">{{item.name}}</option>
 </select>

</div></code>```

Body:
I am trying to pass parameter to function changeBoard whole variable item but If i dont set value="item._id" i can't have default value. If I set i can only pass item._id.

Can someone help me how can I pass whole parametere item at the same time have default selected?

demo

https://codepen.io/Turqus/pen/LOjvLL?editors=1111

var app = angular.module('test', []);

template html

 <select class="form-control" ng-model="selectedBoard" ng-change="changeBoard(selectedBoard)">
     <option ng-repeat="item in arrayItems" value="{{item.id}}">{{item.name}}</option>
 </select>

controller

  var app = angular.module('test', []);

app.controller('select', $scope=>{
  $scope.arrayItems = [
    {'id': '133', 'name':'first', 'lists':[{'name': 1}, {'name': 2}]},
    {'id': '134', 'name':'second', 'lists':[{'name': 1}, {'name': 2}]},
    {'id': '135', 'name':'third', 'lists':[{'name': 1}, {'name': 2}]},
    {'id': '136', 'name':'fourth', 'lists':[{'name': 1}, {'name': 2}]}
  ];

  $scope.selectedBoard = '134';

  $scope.changeBoard = (selectedBoard) => {
    console.log(selectedBoard)
  }
});

Body:
You can use the Javascript function .filter(). It's kind of like an SQL WHERE statement, but for Javascript arrays. It'll just filter out anything based on the function given for it.

In my example, you can remove the pass of selectedBoard to the function call in your ng-change method. Since you are already binding to the model $scope.selectedBoard.

! function() {

  var app = angular.module('test', []);

  var select = function($scope) {
    $scope.arrayItems = [{
        'id': '133',
        'name': 'first',
        'lists': [{
          'name': 1
        }, {
          'name': 2
        }]
      },
      {
        'id': '134',
        'name': 'second',
        'lists': [{
          'name': 1
        }, {
          'name': 2
        }]
      },
      {
        'id': '135',
        'name': 'third',
        'lists': [{
          'name': 1
        }, {
          'name': 2
        }]
      },
      {
        'id': '136',
        'name': 'fourth',
        'lists': [{
          'name': 1
        }, {
          'name': 2
        }]
      }
    ];

    $scope.selectedBoard = '';

    $scope.changeBoard = () => {
      var obj = $scope.arrayItems.filter(item => item.id == $scope.selectedBoard);
      // var obj = $scope.arrayItems.filter(function(item) { // Can also be written as this
      //   return item.id == $scope.selectedBoard;
      // });
      console.log(obj);
    }
  };

  app.controller("select", ["$scope", select]);
}();

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="test" ng-controller="select">

  <select class="form-control" ng-model="selectedBoard" ng-change="changeBoard()">
     <option ng-repeat="item in arrayItems" value="{{item.id}}">{{item.name}}</option>
 </select>

</div>


问:
Cannot use SD card in Android Emulator Device
I am trying to use default android AVD emulator. It works fine, however I have a problem with using external storage/sdcard.

It seems that the sdcard image is not mounted at all.

```<code>Environment.getExternalStorageState()
External: removed
</code>```

Here is my configuration

And the config file itself

```<code>avd.ini.encoding=UTF-8
AvdId=Nexus_4_API_16
PlayStore.enabled=false
abi.type=x86
avd.ini.displayname=Nexus 4 API 16
disk.dataPartition.size=800M
hw.accelerometer=yes
hw.audioInput=yes
hw.battery=yes
hw.camera.back=emulated
hw.camera.front=emulated
hw.cpu.arch=x86
hw.cpu.ncore=4
hw.dPad=no
hw.device.hash2=MD5:6930e145748b87e87d3f40cabd140a41
hw.device.manufacturer=Google
hw.device.name=Nexus 4
hw.gps=yes
hw.gpu.enabled=yes
hw.gpu.mode=auto
hw.initialOrientation=Portrait
hw.keyboard=yes
hw.lcd.density=320
hw.mainKeys=no
hw.ramSize=1536
hw.sdCard=yes
hw.sensors.orientation=yes
hw.sensors.proximity=yes
hw.trackBall=no
image.sysdir.1=system-images/android-16/google_apis/x86/
runtime.network.latency=none
runtime.network.speed=full
sdcard.size=1000M
showDeviceFrame=yes
skin.dynamic=yes
skin.name=nexus_4
skin.path=/Users/user/Library/Android/sdk/skins/nexus_4
tag.display=Google APIs
tag.id=google_apis
vm.heapSize=80
</code>```

Please help to solve this problem. I have tried to recreate a virtual device, however this didn't solve the problem

UPDATE

This doesn't work as well

```<code>  ./emulator -avd Nexus_4_API_16 -sdcard ~/Temp/mainSdCard.img
</code>```

答:
The only one solution I have found is just to test different emulators.
Currently I am using Nexus 5x with Android 4.3 and it works fine.

Another possible solution that may help someone is after you have created an emulator, stop it and change the size of the sdcard generated by default by Android Studio.

I hope this will help.

Body:
I am trying to use default android AVD emulator. It works fine, however I have a problem with using external storage/sdcard.

It seems that the sdcard image is not mounted at all.

Environment.getExternalStorageState()
External: removed

Here is my configuration

And the config file itself

avd.ini.encoding=UTF-8
AvdId=Nexus_4_API_16
PlayStore.enabled=false
abi.type=x86
avd.ini.displayname=Nexus 4 API 16
disk.dataPartition.size=800M
hw.accelerometer=yes
hw.audioInput=yes
hw.battery=yes
hw.camera.back=emulated
hw.camera.front=emulated
hw.cpu.arch=x86
hw.cpu.ncore=4
hw.dPad=no
hw.device.hash2=MD5:6930e145748b87e87d3f40cabd140a41
hw.device.manufacturer=Google
hw.device.name=Nexus 4
hw.gps=yes
hw.gpu.enabled=yes
hw.gpu.mode=auto
hw.initialOrientation=Portrait
hw.keyboard=yes
hw.lcd.density=320
hw.mainKeys=no
hw.ramSize=1536
hw.sdCard=yes
hw.sensors.orientation=yes
hw.sensors.proximity=yes
hw.trackBall=no
image.sysdir.1=system-images/android-16/google_apis/x86/
runtime.network.latency=none
runtime.network.speed=full
sdcard.size=1000M
showDeviceFrame=yes
skin.dynamic=yes
skin.name=nexus_4
skin.path=/Users/user/Library/Android/sdk/skins/nexus_4
tag.display=Google APIs
tag.id=google_apis
vm.heapSize=80

Please help to solve this problem. I have tried to recreate a virtual device, however this didn't solve the problem

UPDATE

This doesn't work as well

  ./emulator -avd Nexus_4_API_16 -sdcard ~/Temp/mainSdCard.img


问:
Should I be worried that my site crashes IE9 and how to fix?
I've downloaded the latest version of IE9 beta and my site wrecks it.  No problems on any other browser, but on IE9 it freezes on every page.  The thing is, many other sites also make it gag.

Should I worry?

IE's fault or do my site and I need to do some serious soul searching?

How does one debug this stuff and are there a list of common culprits?  Is it most likely a Javascript issue?  jQuery?

答:
If your site is dying on IE9 (assuming it's not the result of known IE9 bugs), you definitely need to address it. You can download tools like the IE Developer Toolbar to help you move about within your page once it's loaded, and there are other resources online like jslint that will help you examine some of your javascript and work on its quality.

If you find any specific issues that you're unsure of how to address, please don't hesitate to return here and post more questions - there are (literally) thousands upon thousands of brilliant minds waiting to assist you.

Update - You mentioned in the comments below that IE9 dies before you can even determine what is causing it to die. This is (unfortunately) the case with much software. Often times you can try to repeat the same actions in Chrome, Firefox, Opera or some other browser and see how it responds. Many times you'll find that another browser may provide an error without crashing entirely. This could give you some insight into what may be causing IE to crash.


问:
Block textbox for input in userform
I am using a userform for the first time and I want a textbox to be blocked for input. I have tried a lot of different things, but still without a proper result.
Can anybody help me with this matter ?</p>

答: Change the Enabled property to False for the textbox.</p>

Title: Block textbox for input in userform


问:
How do I copy code from the console to the editor/source pane in Rstudio
User interface = Rstudio.
Is there a short-cut key that will paste code from my console in Rstudio to a R Markdown file that I am developing in the workspace above the console?

In the picture above, I would like to move the read1_file <- read.table("C:/Users/perdue/Desktop/Adv. MicroEconometrics/HA 3/data/read1.sas", header= FALSE, skip = 1, sep = ",", dec=".") code from the console into the R2b_Michael.Rmdfile using a short-cut key.

答:
You can easily copy lines of code from the history pane in Rstudio to either the console or to the editor.

First show the history pane. In the default layout it is a tab next to the environment tab in the top right pane.

Then highlight the commands you want to copy. You can click on a single command. Or shift-click selects a range or ctrl-click selects multiple commands.

Then shift-Enter copies the selected commands to the editor.

Alternatively, just pressing Enter copies the commands to the console


问:
Unexpected Character $ - Java Binding error
I am trying java binding to a Xamarin forms project and the jar contains class name having $ and also variable names with $. I am getting "Unexpected Character $" error. I am trying to solve it by editing the metadata.xml file. It seems that I am doing it wrong, please check the following entries,

For the class names containing $. I am using,

```<code><attr path="/api/package[@name='com.wed.therace']/class[@name='CarDetails$']"
    name="obfuscated">false</attr>
</code>```

for the variables containing $,

```<code><attr path="/api/package[@name='com.wed.therace']/class[@name='CarDetails$']/fie    ld[@name='machineParts$']"
name="obfuscated">false</attr>
</code>```

What is the correct way? I got this from https://developer.xamarin.com/guides/android/advanced_topics/binding-a-java-library/customizing-bindings/java-bindings-metadata

Thanks in advance,

答:
The sample you tried disables obfuscation for certain types or members. But $ doesn't necessary mean the code has been obfuscated. Here's the common flow for you of what to do in such cases:

Navigate to the error source to see the generated output C# code. In your error message you'll most likely see something like Error: obj/Debug/src/234.cs (30, 50). Look into this file and see what happens in it on line 30. In your case you'll see a field containing $ in its name which leads to compilation error. Pay attention there is a generator comment line in this file starting with // Metadata.xml XPath ... path="/api/package[@name=...]", like this. You can just copy the path="..." part to use it for configurations in manifest.xml.

Look into generated api.xml file located in obj/Debug (or obj/Release depending or your current config). Try looking for the member definition you have issue in. You should be able to find your field, method or another member there with all its attributes like static, deprecated, obfuscated etc. That's what you can affect with metadata transformations.

Now depending on your situation try one of the following:

If you don't need this type or member in your code, just get rid of it by using remove-node metadata element. Get the path value from the generated sources as described above. Remember you can either remove the error member or the whole type if you don't need it.

If you do need this member, define a rename transformation in metadata like this: <attr path="<copied_from_sources>" name="managedName">ValidNameHere</attr>.

Sometimes you'll need to clean the obj folder to make changes applied. Usually it works correct though.

Body:
I am trying java binding to a Xamarin forms project and the jar contains class name having $ and also variable names with $. I am getting "Unexpected Character $" error. I am trying to solve it by editing the metadata.xml file. It seems that I am doing it wrong, please check the following entries,

For the class names containing $. I am using,

<attr path="/api/package[@name='com.wed.therace']/class[@name='CarDetails$']"
    name="obfuscated">false</attr>

for the variables containing $,

<attr path="/api/package[@name='com.wed.therace']/class[@name='CarDetails$']/fie    ld[@name='machineParts$']"
name="obfuscated">false</attr>

What is the correct way? I got this from https://developer.xamarin.com/guides/android/advanced_topics/binding-a-java-library/customizing-bindings/java-bindings-metadata

Thanks in advance,


问:
Shell sort Java example
Can anyone give me example about shell sort?  I'm a new person in here who must learn about shell sort, but first I must find a Java shell sort example. I found one example in Google but it's too difficult.</p>

答:
Here is a video link: https://youtu.be/SCBf7aqKQEY
The guy has made a good video of shell sort!!

And a simple code:

```<code>int sort(int arr[])
{
    int n = arr.length;
    int gap = n/2;
    int i,j;

    while(gap>0)
     {  for (i=0,j=i+gap; j<n; i++,++j)
        {
           if(arr[i]>arr[j])                   //swap
              { int temp = arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
              }

        }
        gap=gap/2;
     }
    return 0;
}
</code>```

Title: Shell sort Java example

Body:
Here is a video link: https://youtu.be/SCBf7aqKQEY
The guy has made a good video of shell sort!!

And a simple code:

int sort(int arr[])
{
    int n = arr.length;
    int gap = n/2;
    int i,j;

    while(gap>0)
     {  for (i=0,j=i+gap; j<n; i++,++j)
        {
           if(arr[i]>arr[j])                   //swap
              { int temp = arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
              }

        }
        gap=gap/2;
     }
    return 0;
}


问:
Change color of a word in html
I have a .html document that looks like this:

```<code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Change color</title>
  <style>
   .colortext {
     color: red;
   }
  </style>
 </head>
 <body>
  <p>bla bla lbla <span class="colortext">the</span>,
 the balfds of .</p>
 </body>
</html>
</code>```

In this document I give to the a red color. But how should I go in order to change color of every thein my huge text? Is there a way to change color in order not to write

for every word, I need?

答:
I would use </p>

```<code><font color="red">the</font>
</code>```

Title: Change color of a word in html

Body:
I have a .html document that looks like this:

<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>Change color</title>

bla bla lbla the,
 the balfds of .

In this document I give to the a red color. But how should I go in order to change color of every thein my huge text? Is there a way to change color in order not to write

for every word, I need?

Body:
I would use

<font color="red">the</font>


问:
Calling variables from another function
Trying to call a variable from a sub function, but "sheet" is not defined. Any suggestions on how to call it? </p>

```<code>function getDate(){
var mnthYearDate = Utilities.formatDate(new Date,"EST","MMM yyyy");
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(mnthYearDate);
}

function getValue(){
getDate();
var target = sheet.getRange("A1").getValue();
}
</code>```

答: Return it from your getValue() function and pass it as parameter to getValue(sheet) function.</p>

Title: Calling variables from another function

Body:
Trying to call a variable from a sub function, but "sheet" is not defined. Any suggestions on how to call it?

function getDate(){
var mnthYearDate = Utilities.formatDate(new Date,"EST","MMM yyyy");
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(mnthYearDate);
}

function getValue(){
getDate();
var target = sheet.getRange("A1").getValue();
}