问:
How to find a color in a string that contains part of another color
I am trying to find a color in a string that contains part of another color.
i.e. Some string will contain Rose Gold and others will contain just Gold or
sometimes the string will contain Black and other times Jet Black or Midnight Black.
and when I use the CONTAINS keyword it works randomly. </p>

```<code>Galaxy S8 64GB artic Silver                      Just get Silver
Galaxy S7 edge in Black Onyx 32GB (CPO)          Just get Black
Galaxy S7 edge in Silver Titanium 32GB (CPO)     Just gets Silver
Galaxy S7 edge in Blue Coral 32GB                Just gets Blue
Moto Z2 Play - Fine Gold                         Just gets Gold
iPad Mini 4 32GB in Space Gray                   I got Space Gray oddly enough
iPad Pro (9.7) 32GB in Rose Gold                 I got Rose Gold oddly enough
Galaxy Note 8 in Midnight Black                  I got Midnight Black oddly enough

 sProductDescription = Row["ProductDescription"].ToString().Trim().Replace("  ", " ");
 Products pa = db.Products.Single(p => p.ModelNumber == sModelNumber);
 foreach (string x in SharedFunctions.GetColors())
 {
   if (sProductDescription.ToUpper().Contains(x.ToUpper()))
   {
       pa.Color = x;
   }
 }

public static List<string> GetColors()
{
    List<string> lColors = new List<string>();
    lColors.Add("Artic Silver");
    lColors.Add("Black Leather");
    lColors.Add("Black Onyx");
    lColors.Add("Black Sapphire");
    lColors.Add("Black Slate");
    lColors.Add("Black");
    lColors.Add("Blue Coral");
    lColors.Add("Blue");
    lColors.Add("Carbon");
    lColors.Add("Fine Gold");
    lColors.Add("Gold Platinum");
    lColors.Add("Gold");
    lColors.Add("Gray");
    lColors.Add("Green");
    lColors.Add("Grey");
    lColors.Add("Jet Black");
    lColors.Add("Lunar Grey");
    lColors.Add("Midnight Black");
    lColors.Add("Orchid Gray");
    lColors.Add("Pearl");
    lColors.Add("Pink");
    lColors.Add("Platinum");
    lColors.Add("Rose Gold");
    lColors.Add("Silver Titanium");
    lColors.Add("Silver");
    lColors.Add("Slate");
    lColors.Add("Space Gray");
    lColors.Add("Sugar White");
    lColors.Add("Titan");
    lColors.Add("White");
    lColors.Add("Yellow");

    return lColors;
}
</code>```

答:
I'd make 2 word lists containing the colours; A basic and advanced list. Your first should contain words such as "Rose Gold" and "Titanium White" for example - essentially just all of the colours you intend to use that have 'names'. In your second list, put words that are just plain colours such as "Gold", "Green" or "Silver". Have the program first iterate through your complex colour names, and then your simple one if no match was found in the first one.

```<code>var complexList = ColourLists.ComplexList;
var simpleList  = ColourLists.SimpleList;
var productName = "iPad Pro(9.7) 32GB in Rose Gold";
var productColour = string.Empty;

foreach(var colour in complexList)
{
    if(productName.Contains(colour, StringComparison.Ordinal))
    {
        productColour = colour;
        break;
    }
}

if(string.IsNullOrEmpty(productColour))
{
    foreach (var colour in simpleList)
    {
        if (productName.Contains(colour, StringComparison.Ordinal))
        {
            productColour = colour;
            break;
        }
    }
}
</code>```

This would return your complex colour (in this scenario, Rose Gold would be found in the first foreach loop). If no complex colour was found, then it would return a simple colour (assuming there is one). You can set your productName variable to pull it directly from a model or object instead of being a string like how I've done it.

Body:
I am trying to find a color in a string that contains part of another color.
i.e. Some string will contain Rose Gold and others will contain just Gold or
sometimes the string will contain Black and other times Jet Black or Midnight Black.
and when I use the CONTAINS keyword it works randomly.

Galaxy S8 64GB artic Silver                      Just get Silver
Galaxy S7 edge in Black Onyx 32GB (CPO)          Just get Black
Galaxy S7 edge in Silver Titanium 32GB (CPO)     Just gets Silver
Galaxy S7 edge in Blue Coral 32GB                Just gets Blue
Moto Z2 Play - Fine Gold                         Just gets Gold
iPad Mini 4 32GB in Space Gray                   I got Space Gray oddly enough
iPad Pro (9.7) 32GB in Rose Gold                 I got Rose Gold oddly enough
Galaxy Note 8 in Midnight Black                  I got Midnight Black oddly enough

 sProductDescription = Row["ProductDescription"].ToString().Trim().Replace("  ", " ");
 Products pa = db.Products.Single(p => p.ModelNumber == sModelNumber);
 foreach (string x in SharedFunctions.GetColors())
 {
   if (sProductDescription.ToUpper().Contains(x.ToUpper()))
   {
       pa.Color = x;
   }
 }

public static List<string> GetColors()
{
    List<string> lColors = new List<string>();
    lColors.Add("Artic Silver");
    lColors.Add("Black Leather");
    lColors.Add("Black Onyx");
    lColors.Add("Black Sapphire");
    lColors.Add("Black Slate");
    lColors.Add("Black");
    lColors.Add("Blue Coral");
    lColors.Add("Blue");
    lColors.Add("Carbon");
    lColors.Add("Fine Gold");
    lColors.Add("Gold Platinum");
    lColors.Add("Gold");
    lColors.Add("Gray");
    lColors.Add("Green");
    lColors.Add("Grey");
    lColors.Add("Jet Black");
    lColors.Add("Lunar Grey");
    lColors.Add("Midnight Black");
    lColors.Add("Orchid Gray");
    lColors.Add("Pearl");
    lColors.Add("Pink");
    lColors.Add("Platinum");
    lColors.Add("Rose Gold");
    lColors.Add("Silver Titanium");
    lColors.Add("Silver");
    lColors.Add("Slate");
    lColors.Add("Space Gray");
    lColors.Add("Sugar White");
    lColors.Add("Titan");
    lColors.Add("White");
    lColors.Add("Yellow");

    return lColors;
}

Body:
I'd make 2 word lists containing the colours; A basic and advanced list. Your first should contain words such as "Rose Gold" and "Titanium White" for example - essentially just all of the colours you intend to use that have 'names'. In your second list, put words that are just plain colours such as "Gold", "Green" or "Silver". Have the program first iterate through your complex colour names, and then your simple one if no match was found in the first one.

var complexList = ColourLists.ComplexList;
var simpleList  = ColourLists.SimpleList;
var productName = "iPad Pro(9.7) 32GB in Rose Gold";
var productColour = string.Empty;

foreach(var colour in complexList)
{
    if(productName.Contains(colour, StringComparison.Ordinal))
    {
        productColour = colour;
        break;
    }
}

if(string.IsNullOrEmpty(productColour))
{
    foreach (var colour in simpleList)
    {
        if (productName.Contains(colour, StringComparison.Ordinal))
        {
            productColour = colour;
            break;
        }
    }
}

This would return your complex colour (in this scenario, Rose Gold would be found in the first foreach loop). If no complex colour was found, then it would return a simple colour (assuming there is one). You can set your productName variable to pull it directly from a model or object instead of being a string like how I've done it.


来源: stackexchange

问:
mockito.AdditionalAnswers.returnsFirstArg() for overloaded methods
I have a problem with returnsFirstArg for overloaded methods, where the firstArg is not nessessarily the same type as the return type.

I want both methods to return the string value of the first argument.

Even better they always return the value of key

Is there anyway to achieve this and get these Tests green?

This is a minimum NOT working example, in real live Translator is more complex and can't be modified.

package test;

import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.mock;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.AdditionalAnswers.returnsFirstArg;

import java.util.Locale;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class TranslatorTest {

    private class Translator {

        String getText(final String key) {
            return "translated " + key;
        }

        String getText(final Locale locale, final String key) {
            return "translated " + key + " for locale " + locale;
        }
    }

    @Test
    public void test_withoutToString() throws Exception {
        final String key = "com.stackoverflow.translator.label";
        Translator translator = mock(Translator.class,  returnsFirstArg());

        assertThat(translator.getText(key), is(key));

        final Locale locale = new Locale("en_GB"); // java.lang.ClassCastException: java.util.Locale cannot be cast to java.lang.String
        assertThat(translator.getText(locale, key), is(key));
    }

    @Test
    public void test_withToString() throws Exception {
        final String key = "com.stackoverflow.translator.label";
        Translator translator = mock(Translator.class,  returnsFirstArg().toString());

        assertThat(translator.getText(key), is(key));
        /*
         * java.lang.AssertionError:
         *  Expected: is "com.stackoverflow.translator.label"
         *  but: was null
         */

        final Locale locale = new Locale("en_GB");
        assertThat(translator.getText(locale, key), is(key));
    }
}
```

答:
I wouldn't bend over backwards to try to define some generic default behavior when creating the mock object. You have two different methods, and could just specify two different behaviors explicitly:

```<code>@Before
public void setUp() {
    translator = mock(Translator.class);
    when(translator.getText(any(), any()))
        .thenAnswer(AdditionalAnswers.returnsSecondArg());
    when(translator.getText(any()))
        .thenAnswer(AdditionalAnswers.returnsFirstArg());
}
</code>```

EDIT:

Addressing the added/clarified requirement in the comments could be problematic, unless you have a good way to recognize argument you want to return.

Assuming you can use some straight-forward logic, like returning the first string argument, you could implement your own Answer:

```<code>Answer<Object> returnsFirstString =
        invocationOnMock -> Arrays.stream(invocationOnMock.getArguments())
                .filter(String.class::isInstance)
                .findFirst()
                .orElse(null);

translator = mock(Translator.class, returnsFirstString);
</code>```

This can, of course, be refined with some different logic like applying to getText methods only, etc.

ContentLicense: CC BY-SA 3.0

Body:
I wouldn't bend over backwards to try to define some generic default behavior when creating the mock object. You have two different methods, and could just specify two different behaviors explicitly:

@Before
public void setUp() {
    translator = mock(Translator.class);
    when(translator.getText(any(), any()))
        .thenAnswer(AdditionalAnswers.returnsSecondArg());
    when(translator.getText(any()))
        .thenAnswer(AdditionalAnswers.returnsFirstArg());
}

EDIT:

Addressing the added/clarified requirement in the comments could be problematic, unless you have a good way to recognize argument you want to return.

Assuming you can use some straight-forward logic, like returning the first string argument, you could implement your own Answer:

Answer<Object> returnsFirstString =
        invocationOnMock -> Arrays.stream(invocationOnMock.getArguments())
                .filter(String.class::isInstance)
                .findFirst()
                .orElse(null);

translator = mock(Translator.class, returnsFirstString);

This can, of course, be refined with some different logic like applying to getText methods only, etc.


问:
How to link static page in Rails 4
I have a method in controller as def match which is in JobsController.

```<code>def match
end
</code>```

I have created match.html.erb in /views/jobs/match.html.erb, I want this code output to come as it is a static page.
I have given a link in index page to render this match.html.erb file like this:

```<code><td><%= link_to 'Match', jobs_match_path %></td>
</code>```

I have defined match path in route file like this:

```<code>  get 'jobs/match', :to => redirect('jobs/match.html')
</code>```

But I am getting an error as:

ActiveRecord::RecordNotFound in JobsController#show Couldn't find Job
  with 'id'=match

答:
As the others said. But I'd do this way

```<code>resources :jobs do
  get 'match', to: 'jobs#match', on: :collection
end
</code>```

So your routes definitions are order-independent

Title: How to link static page in Rails 4

Body:
I have a method in controller as def match which is in JobsController.

def match
end

I have created match.html.erb in /views/jobs/match.html.erb, I want this code output to come as it is a static page.
I have given a link in index page to render this match.html.erb file like this:

<%= link_to 'Match', jobs_match_path %>

I have defined match path in route file like this:

  get 'jobs/match', :to => redirect('jobs/match.html')

But I am getting an error as:

ActiveRecord::RecordNotFound in JobsController#show Couldn't find Job
  with 'id'=match

Body:
As the others said. But I'd do this way

resources :jobs do
  get 'match', to: 'jobs#match', on: :collection
end

So your routes definitions are order-independent


问:
Java equivalent of Perl's hash
I've been using a lot Perl hashes due to super flexibility and convenient.
for instance, in Perl I can do the following:

```<code>$hash{AREA_CODE}->{PHONE}->{STREET_ADDR}
</code>```

I wondering how can I accomplish the same thing with Java, I guess it has something to do with HashMap?

Thanks,

答:
See the Map interface and its implementations, specially HashMap.

Beware that Java doesn't have Perl's auto-vivification (handy but dangerous feature)  so that

```<code>hash.get("areaCode").get("phone").get("streetAdr")
</code>```

will throw an exception if, eg, get(phone) returns null.
Beware also that you should not uses hashes for things that have fixed names ("properties"), you should define your own classes with its getters and setters.

Title: Java equivalent of Perl's hash

Body:
I've been using a lot Perl hashes due to super flexibility and convenient.
for instance, in Perl I can do the following:

$hash{AREA_CODE}->{PHONE}->{STREET_ADDR}

I wondering how can I accomplish the same thing with Java, I guess it has something to do with HashMap?

Thanks,

Body:
See the Map interface and its implementations, specially HashMap.

Beware that Java doesn't have Perl's auto-vivification (handy but dangerous feature)  so that

hash.get("areaCode").get("phone").get("streetAdr")

will throw an exception if, eg, get(phone) returns null.
Beware also that you should not uses hashes for things that have fixed names ("properties"), you should define your own classes with its getters and setters.

ContentLicense: CC BY-SA 2.5


问:
how to display first row data's of excel sheet in userform automatically when clicking on a button
I have a set of 4 rows of data, i need to make the first row data's visible automatically in userform excel using vb , when i click on the button in ribbon. Later by clicking on next row it needs to display the complete data's of next row.

for example,

```<code>stud_id       stud_name      age          gender
 1                a          20            M
 2                b          22            M
 3                c          25            F
 4                d          22            F
</code>```

Public ncurretnrow As Long

Sub Userform_Initialize()
ncurrentrow = Sheet3("2017").Cells(Rows.Count, 1).End(xlDown).Offset(1, 0).Row
traversedata (ncurrentrow)

End Sub

Public Sub traversedata(nrow As Long)

Me.stud_id.Value = ws.Cells(nrow, 1).Value
Me.stud_name.Value = ws.Cells(nrow, 2).Value
Me.age.Value = ws.Cells(nrow, 2).Value
If Optionyes = True Then
    Me.genderm.Value = ws.Cells(nrow, 3).Value
Else
    Me.genderf.Value = ws.Cells(nrow, 3).Value
End If
```

答:
See code below (both Subs inside the User_Form module).

```<code>Public ws As Worksheet

Private Sub UserForm_Initialize()

Dim HeaderRng As Range
Dim ncurretnrow As Long

' set the worksheet object
Set ws = ThisWorkbook.Sheets("2017")

Set HeaderRng = ws.Cells.Find(what:="stud_id") ' look for the header (below it you will find the first row with data)
If Not HeaderRng Is Nothing Then
    ncurretnrow = HeaderRng.Row + 1
Else
    MsgBox "Unable to find stud_id header", vbCritical
    Exit Sub
End If

traversedata ncurretnrow

End Sub
</code>```

```<code>Sub traversedata(nrow As Long)

With Me
    .stud_id.Value = ws.Cells(nrow, 1).Value
    .stud_name.Value = ws.Cells(nrow, 2).Value
    .age.Value = ws.Cells(nrow, 3).Value
    If Optionyes = True Then
        .genderm.Value = ws.Cells(nrow, 4).Value
    Else
        .genderf.Value = ws.Cells(nrow, 4).Value
    End If
End With

End Sub
</code>```

Body:
I have a set of 4 rows of data, i need to make the first row data's visible automatically in userform excel using vb , when i click on the button in ribbon. Later by clicking on next row it needs to display the complete data's of next row.

for example,

stud_id       stud_name      age          gender
 1                a          20            M
 2                b          22            M
 3                c          25            F
 4                d          22            F

Public ncurretnrow As Long

Sub Userform_Initialize()
ncurrentrow = Sheet3("2017").Cells(Rows.Count, 1).End(xlDown).Offset(1, 0).Row
traversedata (ncurrentrow)

End Sub

Public Sub traversedata(nrow As Long)

Me.stud_id.Value = ws.Cells(nrow, 1).Value
Me.stud_name.Value = ws.Cells(nrow, 2).Value
Me.age.Value = ws.Cells(nrow, 2).Value
If Optionyes = True Then
    Me.genderm.Value = ws.Cells(nrow, 3).Value
Else
    Me.genderf.Value = ws.Cells(nrow, 3).Value
End If

Body:
See code below (both Subs inside the User_Form module).

Public ws As Worksheet

Private Sub UserForm_Initialize()

Dim HeaderRng As Range
Dim ncurretnrow As Long

' set the worksheet object
Set ws = ThisWorkbook.Sheets("2017")

Set HeaderRng = ws.Cells.Find(what:="stud_id") ' look for the header (below it you will find the first row with data)
If Not HeaderRng Is Nothing Then
    ncurretnrow = HeaderRng.Row + 1
Else
    MsgBox "Unable to find stud_id header", vbCritical
    Exit Sub
End If

traversedata ncurretnrow

End Sub

Sub traversedata(nrow As Long)

With Me
    .stud_id.Value = ws.Cells(nrow, 1).Value
    .stud_name.Value = ws.Cells(nrow, 2).Value
    .age.Value = ws.Cells(nrow, 3).Value
    If Optionyes = True Then
        .genderm.Value = ws.Cells(nrow, 4).Value
    Else
        .genderf.Value = ws.Cells(nrow, 4).Value
    End If
End With

End Sub


问:
Convert UDP to TCP - Ngrok TCP => UDP
I'm in a hurry at the moment.

My Question is, is there a way to forward UDP to TCP port?
I need this for hosting a game server for my friends, I want to
host Counter-Strike server for example, but it uses UDP (User Datagram Protocol) for server port, but NGROK only supports TCP (Transmission Control Protocl) & HTTP (HyperText Transfer Protocol).

I tried this while ago..

```<code>ngrok tcp 127.0.0.1:27015
</code>```

and as usually it will start :

```<code>ngrok by @inconshreveable                                       (Ctrl+C to quit)

Session Status                online
Account                       Soricy Infinitive (Plan: Free)
Version                       2.2.8
Region                        United States (us)
Web Interface                 http://127.0.0.1:4040
Forwarding                    tcp://0.tcp.ngrok.io:18833 -> 127.0.0.1:27015

Connections                   ttl     opn     rt1     rt5     p50     p90
                              0       0       0.00    0.00    0.00    0.00
</code>```

But fails to connect to 0.tcp.ngrok.io:18833 in the game, and displays that there is no UDP configured on the server side.

Is there any way I could do this differently? UDP=>TCP?

答: One way is to copy the "raw" udp Payload and create a new TCP packet with the raw payload. But you need to set the same data of the other layer except the udp layer. Also: You need a clean configuration of the tcp layer. </p>

Title: Convert UDP to TCP - Ngrok TCP => UDP

Body:
I'm in a hurry at the moment.

My Question is, is there a way to forward UDP to TCP port?
I need this for hosting a game server for my friends, I want to
host Counter-Strike server for example, but it uses UDP (User Datagram Protocol) for server port, but NGROK only supports TCP (Transmission Control Protocl) & HTTP (HyperText Transfer Protocol).

I tried this while ago..

ngrok tcp 127.0.0.1:27015

and as usually it will start :

ngrok by @inconshreveable                                       (Ctrl+C to quit)

Session Status                online
Account                       Soricy Infinitive (Plan: Free)
Version                       2.2.8
Region                        United States (us)
Web Interface                 http://127.0.0.1:4040
Forwarding                    tcp://0.tcp.ngrok.io:18833 -> 127.0.0.1:27015

Connections                   ttl     opn     rt1     rt5     p50     p90
                              0       0       0.00    0.00    0.00    0.00

But fails to connect to 0.tcp.ngrok.io:18833 in the game, and displays that there is no UDP configured on the server side.

Is there any way I could do this differently? UDP=>TCP?


问:
BroadcastReceiver gets 3 ACTION_SCREEN_OFFs whenever I lock the screen and only 1 ACTION_SCREEN_ON
So I'm making an app that sends a message when you press the lock button twice, however when I run the app and check the logs, SCREEN OFF is shown three times in the log. And since SCREEN OFF is shown three times, it means that counter was incremented three times, so the message is sent one just one press if your phone was unlocked. Why is this?</p>

```<code>if (intent.getAction() == Intent.ACTION_SCREEN_OFF)
    {
        Log.d("IT WORKED", "SCREEN OFF");
        if (listen == true)
            counter++;
    }

    else
    {
        if (listen == true)
            counter++;
        Log.d("IT WORKED", "SCREEN ON");
    }
//when counter == 2 (2 lock button presses) send message
</code>```

答:
As per my experiment this works and gives you only two counts </p>

```<code>int counter = 0;
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action != null) {
            switch (action) {
                case Intent.ACTION_SCREEN_OFF:
                    counter++;
                    break;
                case Intent.ACTION_SCREEN_ON:
                    counter++;
                    break;
            }
        }
        Log.i(TAG, "onReceive: " + counter);
    }
};

@Override
protected void onStart() {
    super.onStart();
    IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
    intentFilter.addAction(Intent.ACTION_SCREEN_ON);
    registerReceiver(mBroadcastReceiver, intentFilter);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(mBroadcastReceiver);
}
</code>```

Body:
So I'm making an app that sends a message when you press the lock button twice, however when I run the app and check the logs, SCREEN OFF is shown three times in the log. And since SCREEN OFF is shown three times, it means that counter was incremented three times, so the message is sent one just one press if your phone was unlocked. Why is this?

if (intent.getAction() == Intent.ACTION_SCREEN_OFF)
    {
        Log.d("IT WORKED", "SCREEN OFF");
        if (listen == true)
            counter++;
    }

    else
    {
        if (listen == true)
            counter++;
        Log.d("IT WORKED", "SCREEN ON");
    }
//when counter == 2 (2 lock button presses) send message

Body:
As per my experiment this works and gives you only two counts

int counter = 0;
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action != null) {
            switch (action) {
                case Intent.ACTION_SCREEN_OFF:
                    counter++;
                    break;
                case Intent.ACTION_SCREEN_ON:
                    counter++;
                    break;
            }
        }
        Log.i(TAG, "onReceive: " + counter);
    }
};

@Override
protected void onStart() {
    super.onStart();
    IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
    intentFilter.addAction(Intent.ACTION_SCREEN_ON);
    registerReceiver(mBroadcastReceiver, intentFilter);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(mBroadcastReceiver);
}


问:
Query Check Status from other table
I have following query

```<code>select * from user_profile
</code>```

Now i want to add where condition check user status from other table (users)

```<code>select * from user_profile,users where users.status!=0
</code>```

Please Do Not Recommend Join  i following old join query

Thanks

答:
If you don't want to use join, you have to use a subquery. I guess both tables have a column like userId:

```<code>select * from user_profile where userId in (select userId from users where status != 0)
</code>```

Title: Query Check Status from other table

Body:
I have following query

select * from user_profile

Now i want to add where condition check user status from other table (users)

select * from user_profile,users where users.status!=0

Please Do Not Recommend Join  i following old join query

Thanks

Body:
If you don't want to use join, you have to use a subquery. I guess both tables have a column like userId:

select * from user_profile where userId in (select userId from users where status != 0)


问:
Web applications: servlet thread safety using singleton pattern
I'm looking to hopefully get into web application programming using Java, coming from a PHP/Laravel background (I have some Java experience having studied it around about 8 years ago at university).

I've been playing around for a while and feel fairly comfortable with most of the foundational concepts such as Servlets and Servlet containers as well as some popular web server/servlet container technologies used such as Jetty, Tomcat etc. I've also tried to do quite a bit of research into Java EE.

Now since I want to build up my knowledge on the subject, I don't want to use any frameworks, in fact I would like to look to build my own as a learning exercise. However, I've also looked quite a bit into some of the frameworks around, such as Spring MVC, Struts, Play and Vaadin etc.

So I've got a Maven project set up, I have a web.xml file set up pointing at a servlet that I have created and I am looking to build an entry point into my "framework".

src/main/webapp/WEB-INF/web.xml

```<code><servlet>
    <servlet-name>Application</servlet-name>
    <servlet-class>com.mypackage.Application</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>Application</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>
</code>```

src/main/java/com/mypackage/Application.java

```<code>package com.mypackage;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class Application extends HttpServlet {
    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //
    }
}
</code>```

So now I want to make my own IoC container that uses the singleton pattern (I know this is usually discouraged and is considered an anti-pattern), so it is easy to access it from other parts of my application:

src/main/java/com/mypackage/Container.java

```<code>package com.mypackage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Container {
    private static Container instance;

    public static Container make(HttpServletRequest request, HttpServletResponse response) {
        return instance = new Container();
    }

    public static Container getInstance() {
        if (instance == null) {
            // Throw an exception
        }

        return instance;
    }

    private Container(HttpServletRequest request, HttpServletResponse response) {
        // ...
    }
}
</code>```

I want to create a Container object for every request/response cycle (or every servlet) as the entry point to my application. So I would look to do something like this:

```<code>@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Container container = Container.make(request, response);

    // Do stuff with container and eventually respond to the client
}
</code>```

Now I know that thread safety is a concern when it comes to servlets, and properties on the servlet instance are shared among threads, but my question relates specifically to the Container object I'm creating using the singleton pattern and thread safety.

Is my current approach considered to be thread safe? If not, why, and how can I make it thread safe? Bear in mind that don't actually want my Container instance to be shared among each thread and would like a separate container for each incoming request/response.

Would it be thread safe (or a recommended approach) to create a new object inside the service method of the servlet class and then have that new object create an instance of the Container? e.g.

```<code>public class Something {
    public Something(HttpServletRequest request, HttpServletResponse response) {
        Container.make(request, response);
    }
}

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Something something = new Something(request, response);

    // Do stuff with container and eventually respond to the client
}
</code>```

Finally, would I be correct in assuming that the issue of thread safety arises due to the servlet container re-using servlet instances? As per the Java EE documentation:

The life cycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps.

If an instance of the servlet does not exist, the web container

Loads the servlet class.

Creates an instance of the servlet class.

Initializes the servlet instance by calling the init method. Initialization is covered in Initializing a Servlet.

答:
Creating an instance in the servlet means that it is not thread-safe as a servlet instance is reused.

A Singleton or ApplicationScoped object will only have one copy across your entire application. If you want to make sure that there is only one instance of the object then annotate the class with @ApplicationScoped:

```<code>@ApplicationScoped
public class Something {
   //do stuff
}
</code>```

Then in the servlet inject it:

```<code>public class SomeServlet extends HttpServlet {

   @Inject
   Something obj;

   @Override
   public void service(HttpServletRequest request, HttpServletResponse response) {
     //do stuff
   }

}
</code>```

If instead you want the class to  you are using to be unique per request then make your class RequestScoped instead. Like so:

```<code>@RequestScoped
public class Something {
   //do stuff
}
</code>```

For more information see the CDI tutorial at https://docs.oracle.com/javaee/6/tutorial/doc/giwhl.html. Note that this will require using an application server that has CDI i.e. Payara and not just a servlet container.

Body:
I'm looking to hopefully get into web application programming using Java, coming from a PHP/Laravel background (I have some Java experience having studied it around about 8 years ago at university).

I've been playing around for a while and feel fairly comfortable with most of the foundational concepts such as Servlets and Servlet containers as well as some popular web server/servlet container technologies used such as Jetty, Tomcat etc. I've also tried to do quite a bit of research into Java EE.

Now since I want to build up my knowledge on the subject, I don't want to use any frameworks, in fact I would like to look to build my own as a learning exercise. However, I've also looked quite a bit into some of the frameworks around, such as Spring MVC, Struts, Play and Vaadin etc.

So I've got a Maven project set up, I have a web.xml file set up pointing at a servlet that I have created and I am looking to build an entry point into my "framework".

src/main/webapp/WEB-INF/web.xml

<servlet>
    <servlet-name>Application</servlet-name>
    <servlet-class>com.mypackage.Application</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>Application</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

src/main/java/com/mypackage/Application.java

package com.mypackage;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class Application extends HttpServlet {
    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //
    }
}

So now I want to make my own IoC container that uses the singleton pattern (I know this is usually discouraged and is considered an anti-pattern), so it is easy to access it from other parts of my application:

src/main/java/com/mypackage/Container.java

package com.mypackage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Container {
    private static Container instance;

    public static Container make(HttpServletRequest request, HttpServletResponse response) {
        return instance = new Container();
    }

    public static Container getInstance() {
        if (instance == null) {
            // Throw an exception
        }

        return instance;
    }

    private Container(HttpServletRequest request, HttpServletResponse response) {
        // ...
    }
}

I want to create a Container object for every request/response cycle (or every servlet) as the entry point to my application. So I would look to do something like this:

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Container container = Container.make(request, response);

    // Do stuff with container and eventually respond to the client
}

Now I know that thread safety is a concern when it comes to servlets, and properties on the servlet instance are shared among threads, but my question relates specifically to the Container object I'm creating using the singleton pattern and thread safety.

Is my current approach considered to be thread safe? If not, why, and how can I make it thread safe? Bear in mind that don't actually want my Container instance to be shared among each thread and would like a separate container for each incoming request/response.

Would it be thread safe (or a recommended approach) to create a new object inside the service method of the servlet class and then have that new object create an instance of the Container? e.g.

public class Something {
    public Something(HttpServletRequest request, HttpServletResponse response) {
        Container.make(request, response);
    }
}

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Something something = new Something(request, response);

    // Do stuff with container and eventually respond to the client
}

Finally, would I be correct in assuming that the issue of thread safety arises due to the servlet container re-using servlet instances? As per the Java EE documentation:

The life cycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps.

If an instance of the servlet does not exist, the web container

Loads the servlet class.

Creates an instance of the servlet class.

Initializes the servlet instance by calling the init method. Initialization is covered in Initializing a Servlet.

Body:
Creating an instance in the servlet means that it is not thread-safe as a servlet instance is reused.

A Singleton or ApplicationScoped object will only have one copy across your entire application. If you want to make sure that there is only one instance of the object then annotate the class with @ApplicationScoped:

@ApplicationScoped
public class Something {
   //do stuff
}

Then in the servlet inject it:

public class SomeServlet extends HttpServlet {

   @Inject
   Something obj;

   @Override
   public void service(HttpServletRequest request, HttpServletResponse response) {
     //do stuff
   }

}

If instead you want the class to  you are using to be unique per request then make your class RequestScoped instead. Like so:

@RequestScoped
public class Something {
   //do stuff
}

For more information see the CDI tutorial at https://docs.oracle.com/javaee/6/tutorial/doc/giwhl.html. Note that this will require using an application server that has CDI i.e. Payara and not just a servlet container.


问:
TSQL XML locate particular block(s)
```<code>DECLARE @XMLData XML

SET @XMLData = '<ArrayOfAttributeValueDO>
      <AttributeValueDO>
        <AttributeID>421</AttributeID>
        <AttributeValue>100% cotton pre-shrunk drill</AttributeValue>
      </AttributeValueDO>
      <AttributeValueDO>
        <AttributeID>422</AttributeID>
        <AttributeValue>190gsm</AttributeValue>
      </AttributeValueDO>
      <AttributeValueDO>
        <AttributeID>1221</AttributeID>
        <AttributeValue>Long Sleeve</AttributeValue>
      </AttributeValueDO>
      <AttributeValueDO>
        <AttributeID>1481</AttributeID>
        <AttributeValue>No</AttributeValue>
      </AttributeValueDO>
    </ArrayOfAttributeValueDO>'
</code>```

Given the above example, how can I get a particular <AttributeValueDO> by searching on the <AttributeID> and <AttributeValue>?

I am kind of expecting syntax like this but having error in between "[]"
In fact, I am trying to get any <AttributeValueDO> with attributeID of 422 and attributeValue contains word of 'gsm'

```<code>DECLARE @strAttributeID VARCHAR(1000) = '422'
DECLARE @strAttributeValue VARCHAR(1000) = '190gsm'

SELECT [AttributeValueXML]
FROM [dbo].[tbl_Stock_Master_AttributeValue]
WHERE [AttributeValueXML].exist('(/ArrayOfAttributeValueDO/AttributeValueDO[AttributeID=sql:variable("@strAttributeID") && AttributeValue=sql:variable("@strAttributeValue")])') = 1
</code>```

答:
One chance is to read the whole lot as derived table and place your filter with WHERE at the end (as suggested in the other answer). But - at least in my eyes - it is more efficient to place the filter directly in the XQuery.

If you can be sure, that there is only one occurance try this:

```<code>DECLARE @strAttributeID VARCHAR(1000) = '422'
DECLARE @strAttributeValue VARCHAR(1000) = '190gsm'
SELECT @XMLData.value(N'(/ArrayOfAttributeValueDO
                         /AttributeValueDO[(AttributeID/text())[1]=sql:variable("@strAttributeID")
                                            and contains((AttributeValue/text())[1],sql:variable("@strAttributeValue"))]
                         /AttributeValue/text())[1]','nvarchar(max)');
</code>```

If there might be more occurances use .nodes() to get a derived table of fitting nodes and .value() to get the needed value out of each sub-node:

```<code>SELECT Attr.value('(AttributeValue/text())[1]','nvarchar(max)')
FROM @XMLData.nodes(N'/ArrayOfAttributeValueDO
                      /AttributeValueDO[(AttributeID/text())[1]=sql:variable("@strAttributeID")
                                            and contains((AttributeValue/text())[1],sql:variable("@strAttributeValue"))]') AS Searched(Attr);
</code>```

Hint: Using (SomeElement/text())[1] or SomeElement[1]/text()[1] is slightly faster than a simple SomeElement[1]. In your case it will return the same (with better readability)... But: In general I'd advise to be as specific as possible. Find more details on /text() here

Title: TSQL XML locate particular block(s)

Body:
DECLARE @XMLData XML

SET @XMLData = '<ArrayOfAttributeValueDO>
      <AttributeValueDO>
        <AttributeID>421</AttributeID>
        <AttributeValue>100% cotton pre-shrunk drill</AttributeValue>
      </AttributeValueDO>
      <AttributeValueDO>
        <AttributeID>422</AttributeID>
        <AttributeValue>190gsm</AttributeValue>
      </AttributeValueDO>
      <AttributeValueDO>
        <AttributeID>1221</AttributeID>
        <AttributeValue>Long Sleeve</AttributeValue>
      </AttributeValueDO>
      <AttributeValueDO>
        <AttributeID>1481</AttributeID>
        <AttributeValue>No</AttributeValue>
      </AttributeValueDO>
    </ArrayOfAttributeValueDO>'

Given the above example, how can I get a particular <AttributeValueDO> by searching on the <AttributeID> and <AttributeValue>?

I am kind of expecting syntax like this but having error in between "[]"
In fact, I am trying to get any <AttributeValueDO> with attributeID of 422 and attributeValue contains word of 'gsm'

DECLARE @strAttributeID VARCHAR(1000) = '422'
DECLARE @strAttributeValue VARCHAR(1000) = '190gsm'

SELECT [AttributeValueXML]
FROM [dbo].[tbl_Stock_Master_AttributeValue]
WHERE [AttributeValueXML].exist('(/ArrayOfAttributeValueDO/AttributeValueDO[AttributeID=sql:variable("@strAttributeID") && AttributeValue=sql:variable("@strAttributeValue")])') = 1

Body:
One chance is to read the whole lot as derived table and place your filter with WHERE at the end (as suggested in the other answer). But - at least in my eyes - it is more efficient to place the filter directly in the XQuery.

If you can be sure, that there is only one occurance try this:

DECLARE @strAttributeID VARCHAR(1000) = '422'
DECLARE @strAttributeValue VARCHAR(1000) = '190gsm'
SELECT @XMLData.value(N'(/ArrayOfAttributeValueDO
                         /AttributeValueDO[(AttributeID/text())[1]=sql:variable("@strAttributeID")
                                            and contains((AttributeValue/text())[1],sql:variable("@strAttributeValue"))]
                         /AttributeValue/text())[1]','nvarchar(max)');

If there might be more occurances use .nodes() to get a derived table of fitting nodes and .value() to get the needed value out of each sub-node:

SELECT Attr.value('(AttributeValue/text())[1]','nvarchar(max)')
FROM @XMLData.nodes(N'/ArrayOfAttributeValueDO
                      /AttributeValueDO[(AttributeID/text())[1]=sql:variable("@strAttributeID")
                                            and contains((AttributeValue/text())[1],sql:variable("@strAttributeValue"))]') AS Searched(Attr);

Hint: Using (SomeElement/text())[1] or SomeElement[1]/text()[1] is slightly faster than a simple SomeElement[1]. In your case it will return the same (with better readability)... But: In general I'd advise to be as specific as possible. Find more details on /text() here


问:
Insert Mutiple Record into Database Using Php Mysql
I am running a forecast.This forecast has been successfully implemented and i want to run summary report based on the forecast. To achieve this, i had to allow the user to click a button "Summary Report". Upon clicking the button, it will insert the record into the Database and immediately fetch and analyze the data into summary as required. Question now is that the record are much like 1200 records. This records are not inserted into the DB,perhaps because it is too much. But when i reduce the period of the forecast such that the record is like 100, it will insert the data  and analyze it as required. What should i do for the record of says 5000 to be inserted into the Database. Or is there a better way to achieve multiple insertion to the database?
See below the insertion code:</p>

```<code>if(isset($_POST['exportBtn'])){
        foreach($_POST['sj'] as $key => $value) {
         $eflt = $_POST['sflt'][$key];
         $emodel = $_POST['smodel'][$key];
         $eengine =$_POST['sengine'][$key];
         $eloc = $_POST['sloc'][$key];
         $estye = $_POST['sstye'][$key];
         $ensvr = $_POST['snsvr'][$key];
         $eehd = $_POST['sehd'][$key];
              $inExp = mysqli_query($link,"INSERT INTO table_name(fltno,model,engine,loc,serviceType,nextSvr,usageHr)VALUES('$eflt','$emodel','$eengine','$eloc','$estye','$ensvr','$eehd')");
        }//End for-each loop
</code>```

答:
```<code>     $arr = array();
    foreach($_POST['sj'] as $key => $value) {
         $eflt = $_POST['sflt'][$key];
         $emodel = $_POST['smodel'][$key];
         $eengine =$_POST['sengine'][$key];
         $eloc = $_POST['sloc'][$key];
         $estye = $_POST['sstye'][$key];
         $ensvr = $_POST['snsvr'][$key];
         $eehd = $_POST['sehd'][$key];
         array_push($arr,"('$eflt','$emodel','$eengine','$eloc','$estye','$ensvr','$eehd')");
}
$inExp = mysqli_query($link,"INSERT INTO table_name(fltno,model,engine,loc,serviceType,nextSvr,usageHr) VALUES ".implode(',',$arr));
</code>```

Do it with one query. Also you can do it with prepared statements easily..

Body:
I am running a forecast.This forecast has been successfully implemented and i want to run summary report based on the forecast. To achieve this, i had to allow the user to click a button "Summary Report". Upon clicking the button, it will insert the record into the Database and immediately fetch and analyze the data into summary as required. Question now is that the record are much like 1200 records. This records are not inserted into the DB,perhaps because it is too much. But when i reduce the period of the forecast such that the record is like 100, it will insert the data  and analyze it as required. What should i do for the record of says 5000 to be inserted into the Database. Or is there a better way to achieve multiple insertion to the database?
See below the insertion code:

if(isset($_POST['exportBtn'])){
        foreach($_POST['sj'] as $key => $value) {
         $eflt = $_POST['sflt'][$key];
         $emodel = $_POST['smodel'][$key];
         $eengine =$_POST['sengine'][$key];
         $eloc = $_POST['sloc'][$key];
         $estye = $_POST['sstye'][$key];
         $ensvr = $_POST['snsvr'][$key];
         $eehd = $_POST['sehd'][$key];
              $inExp = mysqli_query($link,"INSERT INTO table_name(fltno,model,engine,loc,serviceType,nextSvr,usageHr)VALUES('$eflt','$emodel','$eengine','$eloc','$estye','$ensvr','$eehd')");
        }//End for-each loop

Body:
     $arr = array();
    foreach($_POST['sj'] as $key => $value) {
         $eflt = $_POST['sflt'][$key];
         $emodel = $_POST['smodel'][$key];
         $eengine =$_POST['sengine'][$key];
         $eloc = $_POST['sloc'][$key];
         $estye = $_POST['sstye'][$key];
         $ensvr = $_POST['snsvr'][$key];
         $eehd = $_POST['sehd'][$key];
         array_push($arr,"('$eflt','$emodel','$eengine','$eloc','$estye','$ensvr','$eehd')");
}
$inExp = mysqli_query($link,"INSERT INTO table_name(fltno,model,engine,loc,serviceType,nextSvr,usageHr) VALUES ".implode(',',$arr));

Do it with one query. Also you can do it with prepared statements easily..


问:
SSRS why my last row's height in last page growing?
I have a trouble with my SSRS page.
I added 1 tablix.
Why my last row on the last page expanded?

答:
Some times it is due to the width of the report/tablix body, if you have space  on with reduce it.

check tablix page break

ContentLicense: CC BY-SA 4.0


问:
Rails: change column type, but keep data
I have a model with a column of type integer which I want to convert to type string. Now I'm looking for the best way to change the column type without losing the data. Is there a painless way to accomplish this?

答:
for postgresql, change table column datatype integer to string,

rails migration like this with up and down actions

```<code>class ChangeAgeToString < ActiveRecord::Migration
  def self.up
    change_column :users, :age, 'varchar USING CAST(age AS varchar)', null: false
  end

  def self.down
    change_column :users, :age, 'integer USING CAST(age AS integer)', null: false, default: 0
  end
end
</code>```

Body:
for postgresql, change table column datatype integer to string,

rails migration like this with up and down actions

class ChangeAgeToString < ActiveRecord::Migration
  def self.up
    change_column :users, :age, 'varchar USING CAST(age AS varchar)', null: false
  end

  def self.down
    change_column :users, :age, 'integer USING CAST(age AS integer)', null: false, default: 0
  end
end


问:
Uncaught TypeError in getting json value
Below the code is working but I am getting

Uncaught TypeError: Cannot read property 'searchname' of undefined

Why am I getting this error message? I do not know how to resolve this issue.

var selectedVal = "calendar";
$.getJSON("/js/datas.json", function(jsonData) {
  for (var j = 0; j <= jsonData.nameSearch.length; j++) {
    if (jsonData.nameSearch[j].searchname == selectedVal) {
      var linkname = jsonData.nameSearch[j].namelink;
      alert(linkname);
    }
  }
});
```

<p>This is the JSON:</p>

```{
  "nameSearch": [{
    "searchname": "calendar",
    "namelink": "holidays"
  }, {
    "searchname": "date",
    "namelink": "kilo"
  }]
}
```

答:
You need to remove = sign from for loop.

For loop should be like:

```<code>for (var j = 0; j < jsonData.nameSearch.length; j++)
</code>```

Body:
Below the code is working but I am getting

Uncaught TypeError: Cannot read property 'searchname' of undefined

Why am I getting this error message? I do not know how to resolve this issue.

var selectedVal = "calendar";
$.getJSON("/js/datas.json", function(jsonData) {
  for (var j = 0; j <= jsonData.nameSearch.length; j++) {
    if (jsonData.nameSearch[j].searchname == selectedVal) {
      var linkname = jsonData.nameSearch[j].namelink;
      alert(linkname);
    }
  }
});

This is the JSON:

{
  "nameSearch": [{
    "searchname": "calendar",
    "namelink": "holidays"
  }, {
    "searchname": "date",
    "namelink": "kilo"
  }]
}

Body:
You need to remove = sign from for loop.

For loop should be like:

for (var j = 0; j < jsonData.nameSearch.length; j++)


问:
how to set setLanguageHints
// Base64 encode the JPEG

```<code>base64EncodedImage.encodeContent(imageBytes);
annotateImageRequest.setImage(base64EncodedImage);

                    // add the features we want
                    annotateImageRequest.setFeatures(new ArrayList<Feature>() {{
                        Feature textDetection = new Feature();
                        textDetection.setType("TEXT_DETECTION");
                        add(textDetection);
                    }});
                    ImageContext ImageCon = new ImageContext();
                    ImageCon.cou("th,us");
                    annotateImageRequest.setImageContext(ImageCon);
                    // Add the list of one thing} to the request
                    add(annotateImageRequest);
                }});
</code>```

答:
An example on how to add language hints to ImageContext should be:

```<code>ImageContext imageContext = new ImageContext();
String [] languages = { "zh-TW" };
imageContext.setLanguageHints(Arrays.asList(languages));
</code>```

Title: how to set setLanguageHints

Body:
// Base64 encode the JPEG

base64EncodedImage.encodeContent(imageBytes);
annotateImageRequest.setImage(base64EncodedImage);

                    // add the features we want
                    annotateImageRequest.setFeatures(new ArrayList<Feature>() {{
                        Feature textDetection = new Feature();
                        textDetection.setType("TEXT_DETECTION");
                        add(textDetection);
                    }});
                    ImageContext ImageCon = new ImageContext();
                    ImageCon.cou("th,us");
                    annotateImageRequest.setImageContext(ImageCon);
                    // Add the list of one thing} to the request
                    add(annotateImageRequest);
                }});

Body:
An example on how to add language hints to ImageContext should be:

ImageContext imageContext = new ImageContext();
String [] languages = { "zh-TW" };
imageContext.setLanguageHints(Arrays.asList(languages));


答:
try this using sub query

```<code>select * from user_profile where status!=(select status from users where id =? or status=?)
</code>```

what you compare id or status in subquery

Title: Query Check Status from other table

Body:
try this using sub query

select * from user_profile where status!=(select status from users where id =? or status=?)

what you compare id or status in subquery


问:
Allocate particular request to different threads through java code
I have one query related to java , as I have got two services which is calling a method  parallely , I want that when my one service on which load is more is running it should serve normally, but if the request comes from the second service it should start processing the request of that service , I mean the threads in service one should not be lost can I achieve this using java 8 .
one solution that I thought was that I can make a thread pool of 100 threads and allocate 80  threads to service one and another 20 to other service, but I had one issue in this that suppose my all 80 threads are in use by service one then I will not have processors to process the request coming from second service,
please do provide solution to this question as we need this, if its in java 8 it would be better</p>

答:
you can create a priority future task.In current java implementation there is no option to provide priority.so You can create your class

```<code>public class PriorityFutureTask<V>  extends FutureTask<V> {

 private long priority;
 //more code
}
</code>```

-Define your thread pool  which will extend ThreadPoolExecutor .In current Thread pool executor also not support priority.Create own thread pool extending
ThreadPoolExecutor i.e.

```<code> public class PriorityThreadpoolImpl extends ThreadPoolExecutor{
     //some code.
   }
</code>```

-In current ThreadPoolExecutor takes blocking queue which provide data in fifo order.You need to modify which will poll the item with highest priority.
 In ThreadPool

```<code>public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler)
</code>```

In your implementation modify your pool code to take priority queue.

```<code> public PriorityThreadpoolImpl(int poolSize, long defaultPriority) {
    super(poolSize, poolSize, 0, TimeUnit.MILLISECONDS,
        new PriorityBlockingQueue<Runnable>(poolSize));
    this.defaultPriority = defaultPriority;
  }
</code>```

-Sample code not fully implemented.

```<code>public class PriorityThreadpoolImpl extends ThreadPoolExecutor {

  public PriorityThreadpoolImpl(int poolSize, long defaultPriority) {
        super(poolSize, poolSize, 0, TimeUnit.MILLISECONDS,
            new PriorityBlockingQueue<Runnable>(poolSize));
        this.defaultPriority = defaultPriority;
      }

     protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
        return new PriorityFutureTask<T>(runnable, value, getPriority(runnable));
      }
    //more code
    }
</code>```

Body:
you can create a priority future task.In current java implementation there is no option to provide priority.so You can create your class

public class PriorityFutureTask<V>  extends FutureTask<V> {

 private long priority;
 //more code
}

-Define your thread pool  which will extend ThreadPoolExecutor .In current Thread pool executor also not support priority.Create own thread pool extending
ThreadPoolExecutor i.e.

 public class PriorityThreadpoolImpl extends ThreadPoolExecutor{
     //some code.
   }

-In current ThreadPoolExecutor takes blocking queue which provide data in fifo order.You need to modify which will poll the item with highest priority.
 In ThreadPool

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler)

In your implementation modify your pool code to take priority queue.

 public PriorityThreadpoolImpl(int poolSize, long defaultPriority) {
    super(poolSize, poolSize, 0, TimeUnit.MILLISECONDS,
        new PriorityBlockingQueue<Runnable>(poolSize));
    this.defaultPriority = defaultPriority;
  }

-Sample code not fully implemented.

public class PriorityThreadpoolImpl extends ThreadPoolExecutor {

  public PriorityThreadpoolImpl(int poolSize, long defaultPriority) {
        super(poolSize, poolSize, 0, TimeUnit.MILLISECONDS,
            new PriorityBlockingQueue<Runnable>(poolSize));
        this.defaultPriority = defaultPriority;
      }

     protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
        return new PriorityFutureTask<T>(runnable, value, getPriority(runnable));
      }
    //more code
    }


问:
How do I fill a rectangle with the exception of a area
I am trying to fill a rectangle in a winforms application less a ellipse in the center that allows the image in the background to show through.

can anyone give me a hint on which way to go on this,

thanks.

this is what I have come up with so far:

```<code>  path.AddRectangle(new Rectangle(30, 30, 100, 100));
  path.AddEllipse(new Rectangle(50, 50, 60, 60));
  gfx.FillPath(new SolidBrush(Color.Black), path);
</code>```

答: It isn't clear enough what kind of transparency is required there.  The simple way is to invert the problem.  Use a TextureBrush to draw the image with Graphics.FillEllipse().</p>

Body:
I am trying to fill a rectangle in a winforms application less a ellipse in the center that allows the image in the background to show through.

can anyone give me a hint on which way to go on this,

thanks.

this is what I have come up with so far:

  path.AddRectangle(new Rectangle(30, 30, 100, 100));
  path.AddEllipse(new Rectangle(50, 50, 60, 60));
  gfx.FillPath(new SolidBrush(Color.Black), path);


问:
Check if text field in collectionView is empty

I have a collection view (CollectionViewController) with 3 cells (each cell has it's own class). In the first cell (TextCell) I have a text field and a button (nextButton). When I press the button I want to check if the text field is empty or not. If it's not empty, I want to switch to the second cell.

CollectionViewController:

```<code>let textCell = TextCell()

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellId, for: indexPath)

    // TextCell
    if indexPath.item == 0 {

        let tCell = collectionView.dequeueReusableCell(withReuseIdentifier: textCellId, for: indexPath)
            let nextButton = textCell.nextButton
                nextButton.addTarget(self, action: #selector(handleNextButton), for: .touchUpInside)
        return tCell
    }
    return cell
}

//Handle Action

@objc func handleNextButton() {
    let text = textCell.TextField.text

    if text?.isEmpty == false {
        scrollToIndex(menuIndex: 1)
    } else {
        print("Text field is empty.")
    }
}
</code>```

The problem is that every time i check if the text field is empty or not, it say's it is empty although it's not.

答:
First - Remove the next line, It's not needed and is definitely wrong!

```<code>let textCell = TextCell()
</code>```

Now replace your func with that:

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    // TextCell
    if indexPath.item == 0 {

        let tCell = collectionView.dequeueReusableCell(withReuseIdentifier: textCellId, for: indexPath) as! TextCell
            let nextButton = tCell.nextButton
                nextButton.addTarget(self, action: #selector(handleNextButton), for: .touchUpInside)
        return tCell
    }

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellId, for: indexPath)
    return cell
}
</code>```

And The Handler

```<code>//Handle Action
@objc func handleNextButton(sender: UIButton) {
    let tCell = sender.superview as! TextCell
    let text = tCell.TextField.text

    if text?.isEmpty == false {
        scrollToIndex(menuIndex: 1)
    } else {
        print("Text field is empty.")
    }
}
</code>```

Body:
I have a collection view (CollectionViewController) with 3 cells (each cell has it's own class). In the first cell (TextCell) I have a text field and a button (nextButton). When I press the button I want to check if the text field is empty or not. If it's not empty, I want to switch to the second cell.

CollectionViewController:

let textCell = TextCell()

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellId, for: indexPath)

    // TextCell
    if indexPath.item == 0 {

        let tCell = collectionView.dequeueReusableCell(withReuseIdentifier: textCellId, for: indexPath)
            let nextButton = textCell.nextButton
                nextButton.addTarget(self, action: #selector(handleNextButton), for: .touchUpInside)
        return tCell
    }
    return cell
}

//Handle Action

@objc func handleNextButton() {
    let text = textCell.TextField.text

    if text?.isEmpty == false {
        scrollToIndex(menuIndex: 1)
    } else {
        print("Text field is empty.")
    }
}

The problem is that every time i check if the text field is empty or not, it say's it is empty although it's not.

Body:
First - Remove the next line, It's not needed and is definitely wrong!

let textCell = TextCell()

Now replace your func with that:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    // TextCell
    if indexPath.item == 0 {

        let tCell = collectionView.dequeueReusableCell(withReuseIdentifier: textCellId, for: indexPath) as! TextCell
            let nextButton = tCell.nextButton
                nextButton.addTarget(self, action: #selector(handleNextButton), for: .touchUpInside)
        return tCell
    }

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellId, for: indexPath)
    return cell
}

And The Handler

//Handle Action
@objc func handleNextButton(sender: UIButton) {
    let tCell = sender.superview as! TextCell
    let text = tCell.TextField.text

    if text?.isEmpty == false {
        scrollToIndex(menuIndex: 1)
    } else {
        print("Text field is empty.")
    }
}


问:
Visitor and double dispatch without overriding "accept" method in c++
Ok: here´s my problem: I have a base composit class which accepts a visitor an then iterates over its nodes. Works like a charm.
But then, I have to used a derived from this composit and recognized that I have to override the "accept()" method in the derived class to have correct double dispatching (which I did not understand).

This brings out two flaws: first, I have to break the hidden structure of the base, and second, I have to duplicate code. To clearify, here´s my pseudo-code:

```<code>struct Visitor
{
    void visit( BaseComposit*)    { throw( "not expected"); };
    void visit( DerivedComposit*) { throw( "ok"); };
};

class BaseComposit
{
private:

    std::vector< BaseComposit*> nodes;

public:

    virtual void accept( Visitor* v)
    {
        v->visit( this);

        for( int i = 0; i < nodes.size(); i++)
            nodes[ i]->accept( v);
    }
};

class DerivedComposit : public BaseComposit
{
public:
};
</code>```

Any ellegant solution on that ?
Thank you !

Edit: added "virtual" to "accept()" to make it more precise...

答:
If you want to force some code to be always executed, use the non-virtual interface (NVI) pattern:</p>

```<code>class BaseComposit
{
private:
    std::vector<BaseComposit*> nodes;

    virtual void call_visit(Visitor* v) { v->visit(this); }

public:

    void accept(Visitor* v)
    {
        call_visit(v);

        for(int i = 0; i < nodes.size(); i++)
            nodes[i]->accept(v);
    }
};

class DerivedComposit : public BaseComposit
{
    void call_visit(Visitor* v) override { v->visit(this); }
public:
};
</code>```

Body:
Ok: here´s my problem: I have a base composit class which accepts a visitor an then iterates over its nodes. Works like a charm.
But then, I have to used a derived from this composit and recognized that I have to override the "accept()" method in the derived class to have correct double dispatching (which I did not understand).

This brings out two flaws: first, I have to break the hidden structure of the base, and second, I have to duplicate code. To clearify, here´s my pseudo-code:

struct Visitor
{
    void visit( BaseComposit*)    { throw( "not expected"); };
    void visit( DerivedComposit*) { throw( "ok"); };
};

class BaseComposit
{
private:

    std::vector< BaseComposit*> nodes;

public:

    virtual void accept( Visitor* v)
    {
        v->visit( this);

        for( int i = 0; i < nodes.size(); i++)
            nodes[ i]->accept( v);
    }
};

class DerivedComposit : public BaseComposit
{
public:
};

Any ellegant solution on that ?
Thank you !

Edit: added "virtual" to "accept()" to make it more precise...

Body:
If you want to force some code to be always executed, use the non-virtual interface (NVI) pattern:

class BaseComposit
{
private:
    std::vector<BaseComposit*> nodes;

    virtual void call_visit(Visitor* v) { v->visit(this); }

public:

    void accept(Visitor* v)
    {
        call_visit(v);

        for(int i = 0; i < nodes.size(); i++)
            nodes[i]->accept(v);
    }
};

class DerivedComposit : public BaseComposit
{
    void call_visit(Visitor* v) override { v->visit(this); }
public:
};


问:
Generic and non-generic interfaces and inheritance - ambiguity while accessing
I have the following setup

Base class

```<code>public class Fruit
{

}
</code>```

Inherited class

```<code>public class Apple : Fruit
{

}
</code>```

Generic Base interface

```<code>public interface IFruitsBase<T> where T : Fruit
{
    T GetItem();
    void ProcessItem(T fruit);
    void Check();
}
</code>```

Non generic Interface that inheritates from generic interface with the base class as the generic

```<code>public interface IFruits : IFruitsBase<Fruit>
{

}
</code>```

Specific interface of the correspoing class

```<code>public interface IApples : IFruitsBase<Apple>, IFruits
{
    void MakeAppleJuice(IEnumerable<Apple> apples);
}
</code>```

Base implementation class

```<code>public class Fruits<T> : IFruitsBase<T>, IFruits where T : Fruit
{
    public T GetItem()
    {
        return null;
    }
    public void ProcessItem(T fruit)
    {

    }
    public void Check()
    {

    }

    Fruit IFruitsBase<Fruit>.GetItem()
    {
        return this.GetItem();
    }
    void IFruitsBase<Fruit>.ProcessItem(Fruit fruit)
    {
        ProcessItem((T)fruit);
    }
}
</code>```

Specific implementation

```<code>public class Apples : Fruits<Apple>, IApples
{
    public void MakeAppleJuice(IEnumerable<Apple> apples)
    {

    }
}
</code>```

The problem I am facing, is at that part:

```<code>public interface IApples : IFruitsBase<Apple>, IFruits
{
    void MakeAppleJuice(IEnumerable<Apple> apples);
}
</code>```

Here I am getting the message:

Possible ambiguity while accessing by this Interface Apple IFruitsBase<Apple> Get() Fruit IFruitsBase<Fruit>.Get()

To fix the problem I could remove the interface IFruits from IApples, but this gives other errors as in:

```<code>public class Context
{
    public IApples Apples { get; set; }

    public Context()
    {
        this.Apples = new Apples();
    }

    public IFruits GetFruits(Type type)
    {
        return this.Apples; //simplified the code here, it should actually get the member of this that fits the type
    }
}

public class Foo
{
    public void Main()
    {
        var context = new Context();
        Check(new IFruits[] { context.Apples }); //can't do that since context.Apples doesnt inherit from IFruits, to fix the above ambiguity
    }

    public void Check(IEnumerable<IFruits> fruits)
    {
        foreach (var fruit in fruits)
            fruit.Check();
    }
}
</code>```

My goal is if someone accesses the objects with:

```<code>var context = new Context();
context.Apples.[only apple relevant methods should be accessable]
</code>```

if someone access it with:

```<code>var context = new Context();
context.GetFruits(item.GetType()).[only fruit relevant methods should be accessable]
</code>```

and no matter if one got it with method a or b, all should be passable to methods with a signature of

```<code>void Foo(IFruits fruits);
</code>```

答:
Well, it doesn't do 100% of your wish (because it seems pretty impossible to accomplish), but it should do the trick.

```<code>public interface IFruits
{
    Fruit GetItem();
    void ProcessItem(Fruit fruit);
    void Check();
}

// I changed the name of your IFruitsBase, because it's the same thing as IFruits
// No need to have 2 differents names to name the same thing
public interface IFruits<T> : IFruits where T : Fruit
{
    T GetItem();
    void ProcessItem(T fruit);
    void Check(); // This one could probably be removed from this interface
}
</code>```

Then:

```<code>public interface IApples : IFruits<Apple>
</code>```

And:

```<code>public class Fruits<T> : IFruits<T> where T : Fruit
</code>```

Now, IFruits inherits from IFruits, so no more conflicts, because you won't implement twice the same interface.

So, if you do:

```<code>var context = new Context();
context.Apples.[You will have access to both IFruits and IFruits<Apple>]
</code>```

And with this:

```<code>var context = new Context();
context.GetFruits(item.GetType()).[only IFruits methods are accessable]
</code>```

Body:
I have the following setup

Base class

public class Fruit
{

}

Inherited class

public class Apple : Fruit
{

}

Generic Base interface

public interface IFruitsBase<T> where T : Fruit
{
    T GetItem();
    void ProcessItem(T fruit);
    void Check();
}

Non generic Interface that inheritates from generic interface with the base class as the generic

public interface IFruits : IFruitsBase<Fruit>
{

}

Specific interface of the correspoing class

public interface IApples : IFruitsBase<Apple>, IFruits
{
    void MakeAppleJuice(IEnumerable<Apple> apples);
}

Base implementation class

public class Fruits<T> : IFruitsBase<T>, IFruits where T : Fruit
{
    public T GetItem()
    {
        return null;
    }
    public void ProcessItem(T fruit)
    {

    }
    public void Check()
    {

    }

    Fruit IFruitsBase<Fruit>.GetItem()
    {
        return this.GetItem();
    }
    void IFruitsBase<Fruit>.ProcessItem(Fruit fruit)
    {
        ProcessItem((T)fruit);
    }
}

Specific implementation

public class Apples : Fruits<Apple>, IApples
{
    public void MakeAppleJuice(IEnumerable<Apple> apples)
    {

    }
}

The problem I am facing, is at that part:

public interface IApples : IFruitsBase<Apple>, IFruits
{
    void MakeAppleJuice(IEnumerable<Apple> apples);
}

Here I am getting the message:

Possible ambiguity while accessing by this Interface Apple IFruitsBase<Apple> Get() Fruit IFruitsBase<Fruit>.Get()

To fix the problem I could remove the interface IFruits from IApples, but this gives other errors as in:

public class Context
{
    public IApples Apples { get; set; }

    public Context()
    {
        this.Apples = new Apples();
    }

    public IFruits GetFruits(Type type)
    {
        return this.Apples; //simplified the code here, it should actually get the member of this that fits the type
    }
}

public class Foo
{
    public void Main()
    {
        var context = new Context();
        Check(new IFruits[] { context.Apples }); //can't do that since context.Apples doesnt inherit from IFruits, to fix the above ambiguity
    }

    public void Check(IEnumerable<IFruits> fruits)
    {
        foreach (var fruit in fruits)
            fruit.Check();
    }
}

My goal is if someone accesses the objects with:

var context = new Context();
context.Apples.[only apple relevant methods should be accessable]

if someone access it with:

var context = new Context();
context.GetFruits(item.GetType()).[only fruit relevant methods should be accessable]

and no matter if one got it with method a or b, all should be passable to methods with a signature of

void Foo(IFruits fruits);

Body:
Well, it doesn't do 100% of your wish (because it seems pretty impossible to accomplish), but it should do the trick.

public interface IFruits
{
    Fruit GetItem();
    void ProcessItem(Fruit fruit);
    void Check();
}

// I changed the name of your IFruitsBase, because it's the same thing as IFruits
// No need to have 2 differents names to name the same thing
public interface IFruits<T> : IFruits where T : Fruit
{
    T GetItem();
    void ProcessItem(T fruit);
    void Check(); // This one could probably be removed from this interface
}

Then:

public interface IApples : IFruits<Apple>

And:

public class Fruits<T> : IFruits<T> where T : Fruit

Now, IFruits inherits from IFruits, so no more conflicts, because you won't implement twice the same interface.

So, if you do:

var context = new Context();
context.Apples.[You will have access to both IFruits and IFruits<Apple>]

And with this:

var context = new Context();
context.GetFruits(item.GetType()).[only IFruits methods are accessable]


问:
CSS Background not working on Codepen
I've been trying to put my code up on Codepen but for some reason, the #left div background just doesn't display. It however, works fine locally. I've tried using image urls, background colors and everything to fix it, but nothing has worked so far. Any help would be appreciated!

Only the #left div is supposed to have a background color.
Following is the code and here's the codepen.

index.html

```<code><link rel="stylesheet" href="style.css"/>
<script src="index.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<body>
  <div id="left">
  <form id="formBox">
    <textarea id="input" placeholder="Enter your LispyHTML"></textarea>
    <input id="renderButton" type="button" onclick="render()" value="Render!">
  </form>
</div>
    <div id="right">
  <div id="target">
  </div>
    </div>
</body>
</code>```

style.css:

```<code>@import url('https://fonts.googleapis.com/css?family=Open+Sans');

html, body {
  margin: 0;
  padding: 0;
  border: 0px;
}

body{
    font-family: 'Open Sans';
}

#left{
    width: 50%;
    height: 100%;
    float: left;
  background: #000000 !important;
    /*background: linear-gradient(to right, #c2e59c, #64b3f4);       */
}

#right{
    width: 50%;
    height: 100%;
    float: right;
}

#formBox{
    position: absolute;
    width:40vw;
    height:240px;
    background-color: #fff;
    margin:auto;
    border-radius: 5px;
    padding:10px;
    left:20%;
    top:50%;
    margin-left:-17%;
    margin-top:-200px;
  box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
}
#target{
    height: 100%;
    float: left;
}

#input{
    height: 100%;
    width: 100%;
    left: 500px;
    margin: auto;
    border-style: none;
    border-color: Transparent;
    overflow: auto;
    resize: none;
    outline: none;
    display:inline-block

}

#renderButton {
    position: absolute;
    top: 280px;
    left: 37%;
    background-color:#9C27B0;
    border-radius:10px;
    border:1px solid #9C27B0;
    display:inline-block;
    cursor:pointer;
    color:#ffffff;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
    font-size:17px;
    padding:10px 20px;
    text-decoration:none;
    text-shadow:0px 1px 0px #2f6627;
    outline: none;
}
#renderButton:hover {
    background-color:#7B1FA2;
    border: none;
}
</code>```

答:
You need to change height 100% to 100vh

```<code>#left{
    width: 50%;
    height: 100vh;
    float: left;
    background: #000000 !important;
    /*background: linear-gradient(to right, #c2e59c, #64b3f4);       */
}
</code>```

or

#formBox change position:relative and margin-top:0px

Title: CSS Background not working on Codepen

Body:
I've been trying to put my code up on Codepen but for some reason, the #left div background just doesn't display. It however, works fine locally. I've tried using image urls, background colors and everything to fix it, but nothing has worked so far. Any help would be appreciated!

Only the #left div is supposed to have a background color.
Following is the code and here's the codepen.

index.html

<link rel="stylesheet" href="style.css"/>

<meta name="viewport" content="width=device-width, initial-scale=1"/>

  <form id="formBox">
    <textarea id="input" placeholder="Enter your LispyHTML"></textarea>
    <input id="renderButton" type="button" onclick="render()" value="Render!">
  </form>

style.css:

@import url('https://fonts.googleapis.com/css?family=Open+Sans');

html, body {
  margin: 0;
  padding: 0;
  border: 0px;
}

body{
    font-family: 'Open Sans';
}

#left{
    width: 50%;
    height: 100%;
    float: left;
  background: #000000 !important;
    /*background: linear-gradient(to right, #c2e59c, #64b3f4);       */
}

#right{
    width: 50%;
    height: 100%;
    float: right;
}

#formBox{
    position: absolute;
    width:40vw;
    height:240px;
    background-color: #fff;
    margin:auto;
    border-radius: 5px;
    padding:10px;
    left:20%;
    top:50%;
    margin-left:-17%;
    margin-top:-200px;
  box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
}
#target{
    height: 100%;
    float: left;
}

#input{
    height: 100%;
    width: 100%;
    left: 500px;
    margin: auto;
    border-style: none;
    border-color: Transparent;
    overflow: auto;
    resize: none;
    outline: none;
    display:inline-block

}

#renderButton {
    position: absolute;
    top: 280px;
    left: 37%;
    background-color:#9C27B0;
    border-radius:10px;
    border:1px solid #9C27B0;
    display:inline-block;
    cursor:pointer;
    color:#ffffff;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
    font-size:17px;
    padding:10px 20px;
    text-decoration:none;
    text-shadow:0px 1px 0px #2f6627;
    outline: none;
}
#renderButton:hover {
    background-color:#7B1FA2;
    border: none;
}

Body:
You need to change height 100% to 100vh

#left{
    width: 50%;
    height: 100vh;
    float: left;
    background: #000000 !important;
    /*background: linear-gradient(to right, #c2e59c, #64b3f4);       */
}

or

#formBox change position:relative and margin-top:0px


问:
Google analytics.js and Content Security Policy
I have a web app using the default html5boilerplate Content Security Policy.

However, we have the new Google analytics.js snippet on the page, which is being blocked by the CSP.

I've been trying to find an example of a CSP and JS include structure that will allow Google analytics.js, but haven't had any luck.

The closest SO post is Google Analytics and Content-Security-Policy header, but this is using the older ga.js.

Unfortunately the Google Docs don't mention CSP.

I've reached the following solution though:

Bottom of my html file:

```<code><script type="text/javascript" src="/js/analytics.js"></script>
</code>```

Content of analytics.js:

```<code>(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function()
{ (i[r].q=i[r].q||[]).push(arguments)}
,i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;        m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-1', 'auto');
ga('send', 'pageview');
</code>```

.htaccess CSP:

```<code>Header set Content-Security-Policy "script-src 'self' https://ssl.google-analytics.com http://www.google-analytics.com; object-src 'self'"
</code>```

This works - but I'm unsure if I will have broken the asyncronous nature of the GA code, or caused some other unintended consequence.

Can someone advise the correct way to allow Google analytics.js through a Content Security Policy?

Author Edit:
In the end I used the solution detailed in Google Analytics and Content-Security-Policy header, reverting back to ga.js. But I'd still like to know if it's possible to use analytics.js in the same way.

Author Edit 2:
Looks like it may be possible using analytics.js direct from Google and the same principles as the other SO post:

Bottom of HTML file:

```<code><script type="text/javascript" src="https://ssl.google-analytics.com/analytics.js"></script>
<script type="text/javascript" src="/js/analytics.js"></script>
</code>```

Contents of analytics.js:

```<code>ga('create', 'UA-XXXX-Y', 'auto');
ga('send', 'pageview');
</code>```

CSP:

```<code>Header set Content-Security-Policy "script-src 'self' https://www.google-analytics.com https://ssl.google-analytics.com; object-src 'self'"
</code>```

This is untested - I've not checked if Google analytics is receiving data, but there are no console or CSP errors. Fingers crossed.

答:
You seem to have CSP headers setup on your web app,
 where Google Analytics domains are not white-listed yet. All the requests that the client makes to external domains should be explicitly white-listed.
(This is a good reference: https://hacks.mozilla.org/2016/02/implementing-content-security-policy/).

The CSP errors you see on the browser console are quite descriptive about what has to be white-listed in your CSP header.

For example, for this case,

Refused to load the image 'https://www.google.co.in/...' because it
  violates the following Content Security Policy directive: "img-src
  ".

this would solve the error:

```<code>img-src https://www.google.co.in <other-domains>
</code>```

Body:
I have a web app using the default html5boilerplate Content Security Policy.

However, we have the new Google analytics.js snippet on the page, which is being blocked by the CSP.

I've been trying to find an example of a CSP and JS include structure that will allow Google analytics.js, but haven't had any luck.

The closest SO post is Google Analytics and Content-Security-Policy header, but this is using the older ga.js.

Unfortunately the Google Docs don't mention CSP.

I've reached the following solution though:

Bottom of my html file:

Content of analytics.js:

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function()
{ (i[r].q=i[r].q||[]).push(arguments)}
,i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;        m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-1', 'auto');
ga('send', 'pageview');

.htaccess CSP:

Header set Content-Security-Policy "script-src 'self' https://ssl.google-analytics.com http://www.google-analytics.com; object-src 'self'"

This works - but I'm unsure if I will have broken the asyncronous nature of the GA code, or caused some other unintended consequence.

Can someone advise the correct way to allow Google analytics.js through a Content Security Policy?

Author Edit:
In the end I used the solution detailed in Google Analytics and Content-Security-Policy header, reverting back to ga.js. But I'd still like to know if it's possible to use analytics.js in the same way.

Author Edit 2:
Looks like it may be possible using analytics.js direct from Google and the same principles as the other SO post:

Bottom of HTML file:

Contents of analytics.js:

ga('create', 'UA-XXXX-Y', 'auto');
ga('send', 'pageview');

CSP:

Header set Content-Security-Policy "script-src 'self' https://www.google-analytics.com https://ssl.google-analytics.com; object-src 'self'"

This is untested - I've not checked if Google analytics is receiving data, but there are no console or CSP errors. Fingers crossed.

Body:
You seem to have CSP headers setup on your web app,
 where Google Analytics domains are not white-listed yet. All the requests that the client makes to external domains should be explicitly white-listed.
(This is a good reference: https://hacks.mozilla.org/2016/02/implementing-content-security-policy/).

The CSP errors you see on the browser console are quite descriptive about what has to be white-listed in your CSP header.

For example, for this case,

Refused to load the image 'https://www.google.co.in/...' because it
  violates the following Content Security Policy directive: "img-src
  ".

this would solve the error:

img-src https://www.google.co.in <other-domains>


问:
How to configure Visual Studio Code extensions from command line
Installing Visual Studio Code extensions from the command line is very simple is very simple. But lots of extensions require additional configuration to work.

Example: https://github.com/shanalikhan/code-settings-sync#upload-your-settings-for-the-first-time

We have to open the command palette, type a specific command, the paste a Gist ID and hit Enter. Only then the extension can work.

Another example: https://github.com/wakatime/vscode-wakatime#installation

Here we have to restart/reload VSCode and then enter an API key before the installation is actually finished.

How can Visual Studio Code extensions be configured from the command line?

答:
Got a reply on one of the extension's Github that this is not possible right now:

Currently its Limitation from Code, editor doesnt allow extension to perform actions from CLI

https://github.com/shanalikhan/code-settings-sync/issues/465#issuecomment-349903682

The related issue for Visual Studio Code was closed :(


问:
CSRF Token in Typescript, showing '{' or ';' expected and Parameter declaration expected
I have a CSRF Token script inside my typescript file,

```<code>getCookie(name) {
    var cookieValue = null;

    if (document.cookie && document.cookie != '') {
      var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i ++) {
          var cookie = jQuery.trim(cookies[i]);

          if (cookie.substring(0, name.length + 1) == (name + '=')) {
            cookieValue = decodeURIComponent(cookie.substring(name.length +1));
            break ;
          }
        }
    }
    return cookieValue;
  }

  csrfSafeMethod(method) {
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  }

  $(document).ready(function() {
    var csrftoken = this.getCookie('csrftoken');
    $.ajaxSetup({
      beforeSend: function(xhr, settings) {
        if(!this.csrfSafeMethod(settings.type) && !this.crossDomain) {
          xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
      }
    });
  });
</code>```

when I try to run it, it gives me this 2 error

Anyone know why ?? Thanks in advance !!!

答:
You have placed all of your jQuery document ready code in a strange location.

This is minimally changed version that compiles.

```<code>class Example {
  constructor() {
    $(document).ready(() => {
      var csrftoken = this.getCookie('csrftoken');
      $.ajaxSetup({
        beforeSend: function (xhr, settings) {
          if (!this.csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
          }
        }
      });
    });
  }

  getCookie(name) {
      var cookieValue = null;

      if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
          for (var i = 0; i < cookies.length; i ++) {
            var cookie = jQuery.trim(cookies[i]);

            if (cookie.substring(0, name.length + 1) == (name + '=')) {
              cookieValue = decodeURIComponent(cookie.substring(name.length +1));
              break ;
            }
          }
      }
      return cookieValue;
  }

  csrfSafeMethod(method) {
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  }

}
</code>```

Body:
I have a CSRF Token script inside my typescript file,

getCookie(name) {
    var cookieValue = null;

    if (document.cookie && document.cookie != '') {
      var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i ++) {
          var cookie = jQuery.trim(cookies[i]);

          if (cookie.substring(0, name.length + 1) == (name + '=')) {
            cookieValue = decodeURIComponent(cookie.substring(name.length +1));
            break ;
          }
        }
    }
    return cookieValue;
  }

  csrfSafeMethod(method) {
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  }

  $(document).ready(function() {
    var csrftoken = this.getCookie('csrftoken');
    $.ajaxSetup({
      beforeSend: function(xhr, settings) {
        if(!this.csrfSafeMethod(settings.type) && !this.crossDomain) {
          xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
      }
    });
  });

when I try to run it, it gives me this 2 error

Anyone know why ?? Thanks in advance !!!

Body:
You have placed all of your jQuery document ready code in a strange location.

This is minimally changed version that compiles.

class Example {
  constructor() {
    $(document).ready(() => {
      var csrftoken = this.getCookie('csrftoken');
      $.ajaxSetup({
        beforeSend: function (xhr, settings) {
          if (!this.csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
          }
        }
      });
    });
  }

  getCookie(name) {
      var cookieValue = null;

      if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
          for (var i = 0; i < cookies.length; i ++) {
            var cookie = jQuery.trim(cookies[i]);

            if (cookie.substring(0, name.length + 1) == (name + '=')) {
              cookieValue = decodeURIComponent(cookie.substring(name.length +1));
              break ;
            }
          }
      }
      return cookieValue;
  }

  csrfSafeMethod(method) {
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  }

}


问:
Use gradle to execute webpack which is not in the root directory of project
The structure of my project is similar to the following:

```<code>-- root
  -- gradlew
  -- build.gradle
  -- src
     -- main
       -- frontend
          -- webpack.config.js
          -- package.json
          -- src
          -- node_modules
       -- java
       -- resources
          -- static
</code>```

I'd like to get gradle run the webpack.config.js located inside the root/src/main/frontend folder, and write it to bundle.js in src/main/java/resources/static. I tried this script:

```<code>task myNpmInstall(type: NodeTask) {
    args = ['install']
    inputs.file file('src/main/frontend/package.json')
    outputs.dir file('src/main/frontend/node_modules')
}

task webpack(type: NodeTask, dependsOn: 'myNpmInstall') {
    script = file('src/main/frontend/node_modules/.bin/webpack')
}

processResources.dependsOn 'webpack'
</code>```

This is a part of my package.json:

```<code>  "engines": {
    "npm": "5.5.1",
    "node": "8.9.1"
  },
  "scripts": {
    "build": "node ./node_modules/webpack/bin/webpack.js",
    "test": "mocha --compilers js:babel-core/register --require ./test/test_helper.js --recursive ./test",
    "test:watch": "npm run test -- --watch"
  },
</code>```

and this is the webpack.config.js:

```<code>module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'babel-loader'
    }]
  }
};
</code>```

I get this error:

```<code>Caused by: java.lang.IllegalStateException: Required script property is not set.
</code>```

I noticed that even when I run ./gradlew myNpmInstall I get the same error. How can I fix this ?

Update 1
I updated the gradle file content to

```<code>node {
    version = '8.9.1'
    npmWorkDir = file('src/main/frontend')
    nodeModulesDir = file('src/main/frontend')
    download = true
}

task webpack(type: NodeTask, dependsOn: 'npmInstall') {
    script = file("$projectDir/src/main/frontend/node_modules/.bin/webpack")
}

processResources.dependsOn 'webpack'
</code>```

and now I get this error:

```<code>No configuration file found and no output filename configured via CLI option.
A configuration file could be named 'webpack.config.js' in the current directory.
Use --help to display the CLI options.

Execution failed for task ':webpack' Caused by: org.gradle.process.internal.ExecException: Process 'command '/home/arian/workspace/myproj/.gradle/nodejs/node-v8.9.1-linux-x64/bin/node'' finished with non-zero exit value 255
</code>```

答:
Try to add configuration section to node:

```<code>node {
    version = '6.11.0'
    npmWorkDir = file('src/main/frontend')
    nodeModulesDir = file('src/main/frontend')
    download = true
}
</code>```

And with node plugin you will already have npmInstall task, so you could remove task myNpmInstall

See examples

Body:
The structure of my project is similar to the following:

-- root
  -- gradlew
  -- build.gradle
  -- src
     -- main
       -- frontend
          -- webpack.config.js
          -- package.json
          -- src
          -- node_modules
       -- java
       -- resources
          -- static

I'd like to get gradle run the webpack.config.js located inside the root/src/main/frontend folder, and write it to bundle.js in src/main/java/resources/static. I tried this script:

task myNpmInstall(type: NodeTask) {
    args = ['install']
    inputs.file file('src/main/frontend/package.json')
    outputs.dir file('src/main/frontend/node_modules')
}

task webpack(type: NodeTask, dependsOn: 'myNpmInstall') {
    script = file('src/main/frontend/node_modules/.bin/webpack')
}

processResources.dependsOn 'webpack'

This is a part of my package.json:

  "engines": {
    "npm": "5.5.1",
    "node": "8.9.1"
  },
  "scripts": {
    "build": "node ./node_modules/webpack/bin/webpack.js",
    "test": "mocha --compilers js:babel-core/register --require ./test/test_helper.js --recursive ./test",
    "test:watch": "npm run test -- --watch"
  },

and this is the webpack.config.js:

module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'babel-loader'
    }]
  }
};

I get this error:

Caused by: java.lang.IllegalStateException: Required script property is not set.

I noticed that even when I run ./gradlew myNpmInstall I get the same error. How can I fix this ?

Update 1
I updated the gradle file content to

node {
    version = '8.9.1'
    npmWorkDir = file('src/main/frontend')
    nodeModulesDir = file('src/main/frontend')
    download = true
}

task webpack(type: NodeTask, dependsOn: 'npmInstall') {
    script = file("$projectDir/src/main/frontend/node_modules/.bin/webpack")
}

processResources.dependsOn 'webpack'

and now I get this error:

No configuration file found and no output filename configured via CLI option.
A configuration file could be named 'webpack.config.js' in the current directory.
Use --help to display the CLI options.

Execution failed for task ':webpack' Caused by: org.gradle.process.internal.ExecException: Process 'command '/home/arian/workspace/myproj/.gradle/nodejs/node-v8.9.1-linux-x64/bin/node'' finished with non-zero exit value 255

Body:
Try to add configuration section to node:

node {
    version = '6.11.0'
    npmWorkDir = file('src/main/frontend')
    nodeModulesDir = file('src/main/frontend')
    download = true
}

And with node plugin you will already have npmInstall task, so you could remove task myNpmInstall

See examples


问:
I have a CSV file with header. Want to remove first 5 row of csv but not header? In Python
I have a below CSV file with the header(A,B,C,D):

```<code>A,B,C,D
1,2,3,4
2,1,3,5
6,8,0,9
4,7,9,2
2,5,4,9
1,1,7,3
2,9,5,6
</code>```

I want output after removing top 5 lines but not header:

```<code>A,B,C,D
1,1,7,3
2,9,5,6
</code>```

Below is my Python code snippet, but am not able to add any header retaining code:

with open(filename.csv , 'rb') as infile:
              data_in = infile.readlines()

with open ('temp.csv', 'wb') as outfile:
              outfile.writelines(data_in[5:])

Please help me in this.In my case header is also deleting, but I want to retain header every time.

答:
You could use islice() to avoid reading the whole file into memory:

```<code>from itertools import islice
import csv

with open('input.csv', 'rb') as f_input, open('output.csv', 'wb') as f_output:
    csv_input = csv.reader(f_input)
    csv_output = csv.writer(f_output)
    csv_output.writerow(next(csv_input))
    csv_output.writerows(islice(csv_input, 5, None))
</code>```

Giving you an output of:

```<code>A,B,C,D
1,1,7,3
2,9,5,6
</code>```

This first reads the first line and writes it to the output. It then uses islice() to skip over 5 lines and then pass the remaining lines to writerows().

Body:
I have a below CSV file with the header(A,B,C,D):

A,B,C,D
1,2,3,4
2,1,3,5
6,8,0,9
4,7,9,2
2,5,4,9
1,1,7,3
2,9,5,6

I want output after removing top 5 lines but not header:

A,B,C,D
1,1,7,3
2,9,5,6

Below is my Python code snippet, but am not able to add any header retaining code:

with open(filename.csv , 'rb') as infile:
              data_in = infile.readlines()

with open ('temp.csv', 'wb') as outfile:
              outfile.writelines(data_in[5:])

Please help me in this.In my case header is also deleting, but I want to retain header every time.

Body:
You could use islice() to avoid reading the whole file into memory:

from itertools import islice
import csv

with open('input.csv', 'rb') as f_input, open('output.csv', 'wb') as f_output:
    csv_input = csv.reader(f_input)
    csv_output = csv.writer(f_output)
    csv_output.writerow(next(csv_input))
    csv_output.writerows(islice(csv_input, 5, None))

Giving you an output of:

A,B,C,D
1,1,7,3
2,9,5,6

This first reads the first line and writes it to the output. It then uses islice() to skip over 5 lines and then pass the remaining lines to writerows().