问:
Change the underline/style of EditText.....not the link, and scroll the text horizontally
I have created my own custom keyboard using buttons. I was tired of Android's keyboard popping up and taking up half the screen. My keyboard
is part of the Activity's layout. I have 2 EditTexts set to not-focusable to prevent the Android keyboard from popping up and make the EditTexts read-only. When I select buttons on my keyboard, the values of the buttons' text is displayed in the EditText field that I have assigned as focused (I do this using onTouch and setting a flag/boolean). If the flag mIsNameSelected = true, then the name EditText is considered focused, otherwise the email EditText is considered focused. Here's my dilemma;

First side-effect of this implementation is that when my text is longer than the space allotted to the EditText field, the text disappears to the right. I want to ellipsize the beginning as if the EditText was functioning normally but I think by setting it to isFocusable(false) I have eliminated it's ability to do this. Is there a work-around?

Second, to add a visual cue that the user has selected one of the EditTexts, I want to change the color of the underline on the EditText, not the text-link. The text link doesn't show up because the of the not-focusable attribute setting. I know there must be a way to change the EditText's style programmatically, which is what I'm looking for.

Here is a diagram:

The buttons call the type() method in XML

And here are the relevant methods (type() is called in XML):

```<code>public void setActivteListener(final EditText et) {
        et.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int result = event.getAction();
                if (result == MotionEvent.ACTION_DOWN) {
                    if (et.getId() == R.id.et_customer_name) {
                        Log.d(TAG, "here on customer name");
                        mIsNameSelected = true;
                        updateUI();
                    } else if (et.getId() == R.id.et_customer_email) {
                        Log.d(TAG, "here on customer email");
                        mIsNameSelected = false;
                        updateUI();
                    }
                }
                return true;
            }
        });
    }

    public void type(View view) {

        Log.d(TAG, "type method called");

        Button btn = (Button) view;
        String txt = btn.getText().toString();
        char value = txt.charAt(0);

        if (mIsNameSelected) {

            if (mCustomerName.getText().length() > 0) {

                if (txt.equalsIgnoreCase("back")) {

                    char[] text = mCustomerName.getText().toString().toCharArray();
                    char[] temp = Arrays.copyOfRange(text, 0, text.length - 1);
                    mCustomerName.setText(String.valueOf(temp));
                }
            }

            if (txt.equalsIgnoreCase("space")) {
                char[] text = mCustomerName.getText().toString().toCharArray();

                Log.d(TAG, "the value of text now : " + String.valueOf(text));

                char[] temp = Arrays.copyOf(text, text.length + 1);

                Log.d(TAG, "the value of temp now: " + String.valueOf(temp));

                temp[temp.length - 1] = ' ';

                Log.d(TAG, "temp to string: " + String.valueOf(temp));

                mCustomerName.setText(String.valueOf(temp));
            }

            if (!(txt.equalsIgnoreCase("back") || txt.equalsIgnoreCase("space"))) {
                char[] text = mCustomerName.getText().toString().toCharArray();
                char[] temp = Arrays.copyOf(text, text.length + 1);
                temp[temp.length - 1] = value;
                mCustomerName.setText(String.valueOf(temp));
            }

        } else {
            Log.d(TAG, "the length of the et field is : " + mCustomerName.getText().length());

            if (mCustomerEmail.getText().length() > 0) {

                Log.d(TAG, "the text is longer than 0");

                if (txt.equalsIgnoreCase("back")) {

                    Log.d(TAG, "the text = back ");

                    char[] text = mCustomerEmail.getText().toString().toCharArray();
                    char[] temp = Arrays.copyOfRange(text, 0, text.length - 1);
                    mCustomerEmail.setText(String.valueOf(temp));
                }
            }

            if (txt.equalsIgnoreCase("space")) {
                char[] text = mCustomerEmail.getText().toString().toCharArray();

                Log.d(TAG, "the value of text now : " + String.valueOf(text));

                char[] temp = Arrays.copyOf(text, text.length + 1);

                Log.d(TAG, "the value of temp now: " + String.valueOf(temp));

                temp[temp.length - 1] = ' ';

                Log.d(TAG, "temp to string: " + String.valueOf(temp));

                mCustomerEmail.setText(String.valueOf(temp));
            }

            if (!(txt.equalsIgnoreCase("back") || txt.equalsIgnoreCase("space"))) {
                char[] text = mCustomerEmail.getText().toString().toCharArray();
                char[] temp = Arrays.copyOf(text, text.length + 1);
                temp[temp.length - 1] = value;
                mCustomerEmail.setText(String.valueOf(temp));
            }

        }
    }
</code>```

答:
Set

```<code>android:windowSoftInputMode="stateAlwaysHidden"
</code>```

in the activity xml of your manifest. You can have your views as focusable without the keyboard popping up then.

https://developer.android.com/guide/topics/manifest/activity-element.html

Body:
I have created my own custom keyboard using buttons. I was tired of Android's keyboard popping up and taking up half the screen. My keyboard
is part of the Activity's layout. I have 2 EditTexts set to not-focusable to prevent the Android keyboard from popping up and make the EditTexts read-only. When I select buttons on my keyboard, the values of the buttons' text is displayed in the EditText field that I have assigned as focused (I do this using onTouch and setting a flag/boolean). If the flag mIsNameSelected = true, then the name EditText is considered focused, otherwise the email EditText is considered focused. Here's my dilemma;

First side-effect of this implementation is that when my text is longer than the space allotted to the EditText field, the text disappears to the right. I want to ellipsize the beginning as if the EditText was functioning normally but I think by setting it to isFocusable(false) I have eliminated it's ability to do this. Is there a work-around?

Second, to add a visual cue that the user has selected one of the EditTexts, I want to change the color of the underline on the EditText, not the text-link. The text link doesn't show up because the of the not-focusable attribute setting. I know there must be a way to change the EditText's style programmatically, which is what I'm looking for.

Here is a diagram:

The buttons call the type() method in XML

And here are the relevant methods (type() is called in XML):

public void setActivteListener(final EditText et) {
        et.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int result = event.getAction();
                if (result == MotionEvent.ACTION_DOWN) {
                    if (et.getId() == R.id.et_customer_name) {
                        Log.d(TAG, "here on customer name");
                        mIsNameSelected = true;
                        updateUI();
                    } else if (et.getId() == R.id.et_customer_email) {
                        Log.d(TAG, "here on customer email");
                        mIsNameSelected = false;
                        updateUI();
                    }
                }
                return true;
            }
        });
    }

    public void type(View view) {

        Log.d(TAG, "type method called");

        Button btn = (Button) view;
        String txt = btn.getText().toString();
        char value = txt.charAt(0);

        if (mIsNameSelected) {

            if (mCustomerName.getText().length() > 0) {

                if (txt.equalsIgnoreCase("back")) {

                    char[] text = mCustomerName.getText().toString().toCharArray();
                    char[] temp = Arrays.copyOfRange(text, 0, text.length - 1);
                    mCustomerName.setText(String.valueOf(temp));
                }
            }

            if (txt.equalsIgnoreCase("space")) {
                char[] text = mCustomerName.getText().toString().toCharArray();

                Log.d(TAG, "the value of text now : " + String.valueOf(text));

                char[] temp = Arrays.copyOf(text, text.length + 1);

                Log.d(TAG, "the value of temp now: " + String.valueOf(temp));

                temp[temp.length - 1] = ' ';

                Log.d(TAG, "temp to string: " + String.valueOf(temp));

                mCustomerName.setText(String.valueOf(temp));
            }

            if (!(txt.equalsIgnoreCase("back") || txt.equalsIgnoreCase("space"))) {
                char[] text = mCustomerName.getText().toString().toCharArray();
                char[] temp = Arrays.copyOf(text, text.length + 1);
                temp[temp.length - 1] = value;
                mCustomerName.setText(String.valueOf(temp));
            }

        } else {
            Log.d(TAG, "the length of the et field is : " + mCustomerName.getText().length());

            if (mCustomerEmail.getText().length() > 0) {

                Log.d(TAG, "the text is longer than 0");

                if (txt.equalsIgnoreCase("back")) {

                    Log.d(TAG, "the text = back ");

                    char[] text = mCustomerEmail.getText().toString().toCharArray();
                    char[] temp = Arrays.copyOfRange(text, 0, text.length - 1);
                    mCustomerEmail.setText(String.valueOf(temp));
                }
            }

            if (txt.equalsIgnoreCase("space")) {
                char[] text = mCustomerEmail.getText().toString().toCharArray();

                Log.d(TAG, "the value of text now : " + String.valueOf(text));

                char[] temp = Arrays.copyOf(text, text.length + 1);

                Log.d(TAG, "the value of temp now: " + String.valueOf(temp));

                temp[temp.length - 1] = ' ';

                Log.d(TAG, "temp to string: " + String.valueOf(temp));

                mCustomerEmail.setText(String.valueOf(temp));
            }

            if (!(txt.equalsIgnoreCase("back") || txt.equalsIgnoreCase("space"))) {
                char[] text = mCustomerEmail.getText().toString().toCharArray();
                char[] temp = Arrays.copyOf(text, text.length + 1);
                temp[temp.length - 1] = value;
                mCustomerEmail.setText(String.valueOf(temp));
            }

        }
    }

Body:
Set

android:windowSoftInputMode="stateAlwaysHidden"

in the activity xml of your manifest. You can have your views as focusable without the keyboard popping up then.

https://developer.android.com/guide/topics/manifest/activity-element.html


来源: stackexchange

问:
Java servlets - navigate to page
I have the following project structure:

I am trying to navigate to concerts.jsp from index.jsp:

index.jsp

```<code><li class="active"><a href="/ConcertsController">Concerts</a></li>
</code>```

This is my ConcertsController:

```<code>@WebServlet("/ConcertsController")
public class ConcertsController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public ConcertsController() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.getWriter().append("Served at: ").append(request.getContextPath());
        request.getRequestDispatcher("/WEB-INF/pages/concerts.jsp").forward(request, response);
    }
        ...
    }
</code>```

When I run the app, and click on the link in index.jsp, localhost:8080/ConcertsController URL opens and I get the

The requested resource is not available

error.

Edit 1: I am using Tomcat v7.0, servlets v3.0 and Java 8.

Edit 2 (possible duplicate): Well, surely I need to be able to do this without using the jstl library.

Edit 3: When localhost:8080/ConcertsController opens, I get the "resource not found" error. But when I manually edit the url to localhost:8080/AppName/ConcertsController, it works.

答:
Try using the following:

```<code>request.getRequestDispatcher("/pages/concerts.jsp").forward(request, response);
</code>```

instead of:

```<code>request.getRequestDispatcher("/WEB-INF/pages/concerts.jsp").forward(request, response);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Java servlets - navigate to page

Body:
I have the following project structure:

I am trying to navigate to concerts.jsp from index.jsp:

index.jsp

Concerts

This is my ConcertsController:

@WebServlet("/ConcertsController")
public class ConcertsController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public ConcertsController() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.getWriter().append("Served at: ").append(request.getContextPath());
        request.getRequestDispatcher("/WEB-INF/pages/concerts.jsp").forward(request, response);
    }
        ...
    }

When I run the app, and click on the link in index.jsp, localhost:8080/ConcertsController URL opens and I get the

The requested resource is not available

error.

Edit 1: I am using Tomcat v7.0, servlets v3.0 and Java 8.

Edit 2 (possible duplicate): Well, surely I need to be able to do this without using the jstl library.

Edit 3: When localhost:8080/ConcertsController opens, I get the "resource not found" error. But when I manually edit the url to localhost:8080/AppName/ConcertsController, it works.

Body:
Try using the following:

request.getRequestDispatcher("/pages/concerts.jsp").forward(request, response);

instead of:

request.getRequestDispatcher("/WEB-INF/pages/concerts.jsp").forward(request, response);


问:
headermode properties for Custom Processor, Sink and Producer
I am using the following Custom Processor for binding the Message channels.

```<code>package test;

import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.SubscribableChannel;

public interface ProcessorInput {

    String INPUT_CHANNEL = "test1";
    String OUTPUT_CHANNEL = "test2";

    @Input(INPUT_CHANNEL)
    MessageChannel inputchannel();

    @Output(OUTPUT_CHANNEL)
    SubscribableChannel outputchannel();

}
</code>```

I am trying to control header with the following properties but its not being effective.

```<code>spring.cloud.stream.bindings.output.producer.headerMode=raw
spring.cloud.stream.bindings.input.consumer.headerMode=raw
</code>```

i also tried binding producer and consumer in the properties and still not effective.

```<code>spring.cloud.stream.bindings.output.consumer=test1
spring.cloud.stream.bindings.input.producer=test2
spring.cloud.stream.bindings.output.producer.headerMode=raw
spring.cloud.stream.bindings.input.consumer.headerMode=raw
</code>```

Please suggest for any corrections.

答:
The binder knows nothing about your custom channel names.

You need to use the correct channel name in the property, e.g.

```<code>spring.cloud.stream.bindings.test2.producer.headerMode=raw
</code>```

Body:
I am using the following Custom Processor for binding the Message channels.

package test;

import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.SubscribableChannel;

public interface ProcessorInput {

    String INPUT_CHANNEL = "test1";
    String OUTPUT_CHANNEL = "test2";

    @Input(INPUT_CHANNEL)
    MessageChannel inputchannel();

    @Output(OUTPUT_CHANNEL)
    SubscribableChannel outputchannel();

}

I am trying to control header with the following properties but its not being effective.

spring.cloud.stream.bindings.output.producer.headerMode=raw
spring.cloud.stream.bindings.input.consumer.headerMode=raw

i also tried binding producer and consumer in the properties and still not effective.

spring.cloud.stream.bindings.output.consumer=test1
spring.cloud.stream.bindings.input.producer=test2
spring.cloud.stream.bindings.output.producer.headerMode=raw
spring.cloud.stream.bindings.input.consumer.headerMode=raw

Please suggest for any corrections.

Body:
The binder knows nothing about your custom channel names.

You need to use the correct channel name in the property, e.g.

spring.cloud.stream.bindings.test2.producer.headerMode=raw


问:
Can generic type hints like Dict and List be used bare, without square brackets?
The docs on Dict show it being used as a generic type, like this:

```<code>def get_position_in_index(word_list: Dict[str, int], word: str) -> int:
    return word_list[word]
</code>```

It would also, of course, be correct to type-hint word_list above as dict:

```<code>def get_position_in_index(word_list: dict, word: str) -> int:
    return word_list[word]
</code>```

But is it correct to use Dict as a type-hint on its own to indicate a dict with keys and values of any type, like this?

```<code>def get_position_in_index(word_list: Dict, word: str) -> int:
    return word_list[word]
</code>```

(And likewise, can other generic types like List and Sequence be used bare in this way?)

答:
Yes, Dict is considered to be an alias for Dict[Any, Any]. (And dict is also an alias for Dict[Any, Any]).

This is the case for any generic type, whether it's a builtin one or a custom-made one: if you omit the type parameters, they always default to Any. This is specified in the Generics section of PEP 484 (emphasis added):

Additionally, Any is a valid value for every type variable. Consider the following:

```<code>def count_truthy(elements: List[Any]) -> int:
    return sum(1 for elem in elements if element)
</code>```

This is equivalent to omitting the generic notation and just saying elements: List.

That said, I think the general recommendation is that you should fully write out Dict[Any, Any] instead of using just Dict -- explicit is better then implicit, and so forth.

The only downside is that your function type signatures are now longer. But we can work around that by using type aliases:

```<code>from typing import Dict, Any

AnyDict = Dict[Any, Any]
WordDict = Dict[str, int]

# Equivalent to your first code sample
def get_position_in_index_1(word_list: WordDict, word: str) -> int:
    return word_list[word]

# Equivalent to your second and third code samples
def get_position_in_index_2(word_list: AnyDict, word: str) -> int:
    return word_list[word]
</code>```

Body:
The docs on Dict show it being used as a generic type, like this:

def get_position_in_index(word_list: Dict[str, int], word: str) -> int:
    return word_list[word]

It would also, of course, be correct to type-hint word_list above as dict:

def get_position_in_index(word_list: dict, word: str) -> int:
    return word_list[word]

But is it correct to use Dict as a type-hint on its own to indicate a dict with keys and values of any type, like this?

def get_position_in_index(word_list: Dict, word: str) -> int:
    return word_list[word]

(And likewise, can other generic types like List and Sequence be used bare in this way?)

Body:
Yes, Dict is considered to be an alias for Dict[Any, Any]. (And dict is also an alias for Dict[Any, Any]).

This is the case for any generic type, whether it's a builtin one or a custom-made one: if you omit the type parameters, they always default to Any. This is specified in the Generics section of PEP 484 (emphasis added):

Additionally, Any is a valid value for every type variable. Consider the following:

def count_truthy(elements: List[Any]) -> int:
    return sum(1 for elem in elements if element)

This is equivalent to omitting the generic notation and just saying elements: List.

That said, I think the general recommendation is that you should fully write out Dict[Any, Any] instead of using just Dict -- explicit is better then implicit, and so forth.

The only downside is that your function type signatures are now longer. But we can work around that by using type aliases:

from typing import Dict, Any

AnyDict = Dict[Any, Any]
WordDict = Dict[str, int]

# Equivalent to your first code sample
def get_position_in_index_1(word_list: WordDict, word: str) -> int:
    return word_list[word]

# Equivalent to your second and third code samples
def get_position_in_index_2(word_list: AnyDict, word: str) -> int:
    return word_list[word]


问:
converting String YYYY-MM to Date YYYY-MM-DD
I have a set of data below and they are all in string.

```<code>EndDate
--------
2017-04

2017-02
2017-01
2017-03

2017-06
</code>```

I would like to add the last date of the month into it.

```<code>EndDate
--------
2017-04-30

2017-02-28
2017-01-31
2017-03-31

2017-06-30
</code>```

I'm thinking to convert them to date first and use EOMONTH syntax to give the last date of the month. However I have tried to convert the data to date using convert(datetime, EndDate) and it fails.

I tried a the syntax below from a post in stackoverflow however it gives me error message as well.

```<code>EOMONTH(CONVERT(VARCHAR(max),CAST(EndDate + '01' AS DATETIME),120))
</code>```

FYI, the blank value should remain in the column.

I'm using SQL Server 2012

Thanks all for your help.

答:
You were close!

```<code>SELECT EOMONTH(TRY_CONVERT(date, EndDate + '-01', 120)) FROM ...
</code>```

The date style 120 is yyyy-mm-dd, but you were creating a value that was yyyy-mmdd. Also, you were passing a varchar into EOMONTH when you should just give it a date parameter.

Body:
I have a set of data below and they are all in string.

EndDate
--------
2017-04

2017-02
2017-01
2017-03

2017-06

I would like to add the last date of the month into it.

EndDate
--------
2017-04-30

2017-02-28
2017-01-31
2017-03-31

2017-06-30

I'm thinking to convert them to date first and use EOMONTH syntax to give the last date of the month. However I have tried to convert the data to date using convert(datetime, EndDate) and it fails.

I tried a the syntax below from a post in stackoverflow however it gives me error message as well.

EOMONTH(CONVERT(VARCHAR(max),CAST(EndDate + '01' AS DATETIME),120))

FYI, the blank value should remain in the column.

I'm using SQL Server 2012

Thanks all for your help.

Body:
You were close!

SELECT EOMONTH(TRY_CONVERT(date, EndDate + '-01', 120)) FROM ...

The date style 120 is yyyy-mm-dd, but you were creating a value that was yyyy-mmdd. Also, you were passing a varchar into EOMONTH when you should just give it a date parameter.


问:
copy, paste selection based on multiple criteria to another worksheet in VBA
I'm very new to VBA and have been using the Macro recorder to create Macros. The Macro recorder can only take me so far, I'm able to accomplish 2/3 of what I need done.

I'm trying to create a Macro where I need criteria met in three Columns, copy the row that meets the criteria, and paste it onto a workbook. The criteria are "Open" "Critical" and "Date."
Here's the tricky part, the date either needs to be greater than a specific date, either through user input or referencing a cell in a third worksheet. There are a few thousand rows, and about 19 columns, and all the codes I've attempted lead to crashing excel.

Sample of the code to getting the first two criteria:

```<code>Sheets("Sheet1").Select
    ActiveSheet.ListObjects("Table_owssvr").Range.AutoFilter Field:=12, _
    Criteria1:="Open"
ActiveSheet.ListObjects("Table_owssvr").Range.AutoFilter Field:=16, _
    Criteria1:="Critical"
Range("Table_owssvr").Select
Range("Q83").Activate
Selection.Copy
Sheets("Sheet2").Select Worksheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Select
ActiveSheet.Paste
</code>```

A-----------------------------------------------------------------B-----------------------------------------------------------C
Open                       -------------------------------------------------------Critical--------------------------------------------------1/25---Open-------------------------------------------------------High------------------------------------------------------3/25
Closed----------------------------------------------------Critical----------------------------------------------------3/24
Open------------------------------------------------------Critical-----------------------------------------------------1/25

Any help would be great!

答:
If you are going to be writing VBA you will have to eventually stop relying on .Select. Recorded code is fine short term but it is typically verbose and inefficient.

```<code>Option Explicit

Sub wqewqwew()
    Dim col1 As Long, col2 As Long, col3 As Long, dt As Date
    Dim ws2 As Worksheet

    Set ws2 = Worksheets("sheet2")

    With Worksheets("sheet1").ListObjects("Table_owssvr")
        With .HeaderRowRange
            col1 = Application.Match("open", .Cells, 0)
            col2 = Application.Match("critical", .Cells, 0)
            col3 = Application.Match("date", .Cells, 0)
            dt = CDate(Application.InputBox(prompt:="greater then when?", Title:="pick date", Default:=Date))
        End With
        With .Range
            .AutoFilter
            .AutoFilter field:=col1, Criteria1:="open"
            .AutoFilter field:=col2, Criteria1:="critical"
            .AutoFilter field:=col3, Criteria1:=">" & dt
        End With
        With .DataBodyRange
            If CBool(Application.Subtotal(103, .Cells)) Then
                .Copy Destination:=ws2.Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
            End If
        End With
        With .Range
            'turn off filters
            .AutoFilter
        End With
    End With
End Sub
</code>```

You will likely want to research error control and add some to the above.

Recommended reading: How to avoid using Select in Excel VBA.

Body:
I'm very new to VBA and have been using the Macro recorder to create Macros. The Macro recorder can only take me so far, I'm able to accomplish 2/3 of what I need done.

I'm trying to create a Macro where I need criteria met in three Columns, copy the row that meets the criteria, and paste it onto a workbook. The criteria are "Open" "Critical" and "Date."
Here's the tricky part, the date either needs to be greater than a specific date, either through user input or referencing a cell in a third worksheet. There are a few thousand rows, and about 19 columns, and all the codes I've attempted lead to crashing excel.

Sample of the code to getting the first two criteria:

Sheets("Sheet1").Select
    ActiveSheet.ListObjects("Table_owssvr").Range.AutoFilter Field:=12, _
    Criteria1:="Open"
ActiveSheet.ListObjects("Table_owssvr").Range.AutoFilter Field:=16, _
    Criteria1:="Critical"
Range("Table_owssvr").Select
Range("Q83").Activate
Selection.Copy
Sheets("Sheet2").Select Worksheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Select
ActiveSheet.Paste

A-----------------------------------------------------------------B-----------------------------------------------------------C
Open                       -------------------------------------------------------Critical--------------------------------------------------1/25---Open-------------------------------------------------------High------------------------------------------------------3/25
Closed----------------------------------------------------Critical----------------------------------------------------3/24
Open------------------------------------------------------Critical-----------------------------------------------------1/25

Any help would be great!

Body:
If you are going to be writing VBA you will have to eventually stop relying on .Select. Recorded code is fine short term but it is typically verbose and inefficient.

Option Explicit

Sub wqewqwew()
    Dim col1 As Long, col2 As Long, col3 As Long, dt As Date
    Dim ws2 As Worksheet

    Set ws2 = Worksheets("sheet2")

    With Worksheets("sheet1").ListObjects("Table_owssvr")
        With .HeaderRowRange
            col1 = Application.Match("open", .Cells, 0)
            col2 = Application.Match("critical", .Cells, 0)
            col3 = Application.Match("date", .Cells, 0)
            dt = CDate(Application.InputBox(prompt:="greater then when?", Title:="pick date", Default:=Date))
        End With
        With .Range
            .AutoFilter
            .AutoFilter field:=col1, Criteria1:="open"
            .AutoFilter field:=col2, Criteria1:="critical"
            .AutoFilter field:=col3, Criteria1:=">" & dt
        End With
        With .DataBodyRange
            If CBool(Application.Subtotal(103, .Cells)) Then
                .Copy Destination:=ws2.Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
            End If
        End With
        With .Range
            'turn off filters
            .AutoFilter
        End With
    End With
End Sub

You will likely want to research error control and add some to the above.

Recommended reading: How to avoid using Select in Excel VBA.


问:
Problems occurs when removed one object within Cocos CCARRAY_FOREACH
Background:

Cocos Version: 3.0alpha

Language: C++

Problems:

Within one CCARRAY_FOREACH, it returned wrong&duplicated Object when removed one Object from the previous cycle.

Test Codes:

```<code>__Array* test = __Array::create();
test->retain();
Sprite *item1 = Sprite::create();
Sprite *item2 = Sprite::create();
Sprite *item3 = Sprite::create();

test->addObject(item1);
test->addObject(item2);
test->addObject(item3);

Object *it = NULL;
int index = 0;
CCARRAY_FOREACH(test, it)
{
    log("[Enum] Index: %d Get: %X", index++, it);
}
it = NULL;
index = 0;
CCARRAY_FOREACH(test, it)
{
    log("[Rmoved] Index: %d Get: %X", index++, it);
    test->removeObject(it);
}
</code>```

Output:

[Enum] Index: 0 Get: 90DFB88

[Enum] Index: 1 Get: 90E0030

[Enum] Index: 2 Get: 90E04D8

[Rmoved] Index: 0 Get: 90DFB88

[Rmoved] Index: 1 Get: 90E04D8

[Rmoved] Index: 2 Get: 90E04D8

Questions:

Is there anything wrong I did? I checked the codes with other developers' posted on the internet. It seems almost same.

I am curious no one met this problem before.

If not, we have to patch this hole in our codes when using CCARRAY_FOREACH?

答:
Probably the better solution should use std::vector or cocos::Vector.</p>

```<code>Vector<Sprite*>* test = new Vector<Sprite*>();

Sprite *item1 = Sprite::create();
Sprite *item2 = Sprite::create();
Sprite *item3 = Sprite::create();

test->pushBack(item1);
test->pushBack(item2);
test->pushBack(item3);

int index = 0;
Vector<Sprite*>::iterator it = test->begin();
while (it != test->end())
{
    log("[Enum] Index: %d Get: %X", index++, *it);
    ++it;
}

index = 0;
it = test->begin();
while(it != test->end())
{
    log("[Rmoved] Index: %d Get: %X", index++, *it);
    if(isRemovable)
    {
        it = test->erase(it);
    }
    else
    {
        ++it;
    }
}
</code>```

Body:
Background:

Cocos Version: 3.0alpha

Language: C++

Problems:

Within one CCARRAY_FOREACH, it returned wrong&duplicated Object when removed one Object from the previous cycle.

Test Codes:

__Array* test = __Array::create();
test->retain();
Sprite *item1 = Sprite::create();
Sprite *item2 = Sprite::create();
Sprite *item3 = Sprite::create();

test->addObject(item1);
test->addObject(item2);
test->addObject(item3);

Object *it = NULL;
int index = 0;
CCARRAY_FOREACH(test, it)
{
    log("[Enum] Index: %d Get: %X", index++, it);
}
it = NULL;
index = 0;
CCARRAY_FOREACH(test, it)
{
    log("[Rmoved] Index: %d Get: %X", index++, it);
    test->removeObject(it);
}

Output:

[Enum] Index: 0 Get: 90DFB88

[Enum] Index: 1 Get: 90E0030

[Enum] Index: 2 Get: 90E04D8

[Rmoved] Index: 0 Get: 90DFB88

[Rmoved] Index: 1 Get: 90E04D8

[Rmoved] Index: 2 Get: 90E04D8

Questions:

Is there anything wrong I did? I checked the codes with other developers' posted on the internet. It seems almost same.

I am curious no one met this problem before.

If not, we have to patch this hole in our codes when using CCARRAY_FOREACH?

Body:
Probably the better solution should use std::vector or cocos::Vector.

Vector<Sprite*>* test = new Vector<Sprite*>();

Sprite *item1 = Sprite::create();
Sprite *item2 = Sprite::create();
Sprite *item3 = Sprite::create();

test->pushBack(item1);
test->pushBack(item2);
test->pushBack(item3);

int index = 0;
Vector<Sprite*>::iterator it = test->begin();
while (it != test->end())
{
    log("[Enum] Index: %d Get: %X", index++, *it);
    ++it;
}

index = 0;
it = test->begin();
while(it != test->end())
{
    log("[Rmoved] Index: %d Get: %X", index++, *it);
    if(isRemovable)
    {
        it = test->erase(it);
    }
    else
    {
        ++it;
    }
}


问:
error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
Getting error:

error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
  on g++

on the following code:

```<code>void* func(void *s)
{
    int i = 0;
    int self = (int *)s;
    printf("Thread Entered: %d\n", self);

    sm.lock(self);

    // Critical section (Only one thread
    // can enter here at a time)
    for (i=0; i<MAX; i++)
        ans++;

    sm.unlock(self);
}
</code>```

答: In the second line of the function body, I suspect you were trying obtain the value at s (as an int pointer), but you actually cast it directly to an int. That would yield the address in s rather than the value stored there.

Body:
Getting error:

error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
  on g++

on the following code:

void* func(void *s)
{
    int i = 0;
    int self = (int *)s;
    printf("Thread Entered: %d\n", self);

    sm.lock(self);

    // Critical section (Only one thread
    // can enter here at a time)
    for (i=0; i<MAX; i++)
        ans++;

    sm.unlock(self);
}


问:
C# "Assembly.LoadFile" & disable "DllImport" in loaded assembly?
In C#, Is it possible to dynamicaly load a .NET library at runtime with using something like System.Reflection.Assembly.LoadFile & disabling the loaded library from using [DllImport("someCPP.DLL", EntryPoint ="someFunction")] so that you can't call c++ stuff for security reasons??

The reason for this question is i'm thinking about making a generic openSource browser plugin that could run any .NET code & display things like OpenGL or Direct3D or whatever content you want in the browser using .NET. This would need the loaded .NET library to be secure though by disabling "DllImport" & maybe some other things. Is this possible?

答:
You can use an application domain with restricted security permissions.

Here is a general introduction to application domains:

Application Domains (C# and Visual Basic)

And here is the specific permission related to executing unmanaged code:

SecurityPermissionFlag.UnmanagedCode

ContentLicense: CC BY-SA 2.5


问:
Once filtered, save object to component.ts
In my component.ts, I have a service that returns data that I save in the myData variable.

```<code>myData: AllData[]=[];
</code>```

and then on myData I get data from a service.

Now this data I display on a table in my html :

```<code> <tr *ngFor="let row of myData| filterPipe:date ">
</code>```

But as you can see here I filter by date.
Now this filtered object, I want to be able to access in my component.ts, because I need it for exporting.
How do I save the filtered object and send to my component.ts ?

答: I would suggest filtering on the service, instead of using a pipe. Think of pipes more as data formatters.</p>

Body:
In my component.ts, I have a service that returns data that I save in the myData variable.

myData: AllData[]=[];

and then on myData I get data from a service.

Now this data I display on a table in my html :

But as you can see here I filter by date.
Now this filtered object, I want to be able to access in my component.ts, because I need it for exporting.
How do I save the filtered object and send to my component.ts ?


问:
Tableu formula in SQL
I have a tableu formula

```<code>if [ADMIT] = [Date] then [ADMIT]
else ifnull([ADMIT],ifnull([Date],ifnull([EncStrDate],[Usbank_Date])))
end
</code>```

I try to make them in sql view, add those query in my sql view.

[Admit] is date from table [SMS Data file]

[EncStrDate] is date from table [Soarian Data file]

[Date] is date from table [USBank]

答:
Use  Sql  "Case When" sintaxis

Case when Admit = Date then Admit

```<code> when Admit is not null then Admit

 when Date is not null then Date
</code>```

when EncStraDate is not null then EncStraDate

```<code>else UsBankDate
</code>```

End Case

Title: Tableu formula in SQL

Body:
I have a tableu formula

if [ADMIT] = [Date] then [ADMIT]
else ifnull([ADMIT],ifnull([Date],ifnull([EncStrDate],[Usbank_Date])))
end

I try to make them in sql view, add those query in my sql view.

[Admit] is date from table [SMS Data file]

[EncStrDate] is date from table [Soarian Data file]

[Date] is date from table [USBank]

Body:
Use  Sql  "Case When" sintaxis

Case when Admit = Date then Admit

 when Admit is not null then Admit

 when Date is not null then Date

when EncStraDate is not null then EncStraDate

else UsBankDate

End Case


问:
Find list value against certain key in Dictionary
I have a dictionary with int and List(of Type) , How can i check if certain key contains certain list value in dictionary.

I have a value and a key and i want to check if value exists that key.

So in following dictionary, Key 1 and value Result_3 should return true

```<code>  Dim d as new dictionary(of int32, list(of Type))

    d.Add(1,
        New List(Of Type)(New Type() _
                            {GetType(Result_1),
                                GetType(Result_2),
                                GetType(Result_3),
                                GetType(Result_4)}))

    d.Add(2,
        New List(Of Type)(New Type() _
                            {GetType(Result_5),
                                GetType(Result_6)}))

    d.Add(3,
        New List(Of Type)(New Type() _
                            {GetType(Result_7)}))
</code>```

I have tried this so far but no luck;

```<code>     if  d.Where(function(o) o.Value.Contains(GetType(Result_2)) ).Select(Function(n) n.Key = 1)  then

     End If
</code>```

答:
Try with this function

```<code>Function Check(key as int, value as Type) As Boolean

Return d(key).Contains(value)

End Function
</code>```

And your example would be

```<code>If Check(1,GetType(Result_3)) Then...
</code>```

Body:
I have a dictionary with int and List(of Type) , How can i check if certain key contains certain list value in dictionary.

I have a value and a key and i want to check if value exists that key.

So in following dictionary, Key 1 and value Result_3 should return true

  Dim d as new dictionary(of int32, list(of Type))

    d.Add(1,
        New List(Of Type)(New Type() _
                            {GetType(Result_1),
                                GetType(Result_2),
                                GetType(Result_3),
                                GetType(Result_4)}))

    d.Add(2,
        New List(Of Type)(New Type() _
                            {GetType(Result_5),
                                GetType(Result_6)}))

    d.Add(3,
        New List(Of Type)(New Type() _
                            {GetType(Result_7)}))

I have tried this so far but no luck;

     if  d.Where(function(o) o.Value.Contains(GetType(Result_2)) ).Select(Function(n) n.Key = 1)  then

     End If

Body:
Try with this function

Function Check(key as int, value as Type) As Boolean

Return d(key).Contains(value)

End Function

And your example would be

If Check(1,GetType(Result_3)) Then...


问:
Copy and overwrite one database into another using mysqldump differentially
I know that you can use the following command to copy a database from one SQL server to another and overwrite the database in the destination server.

```<code>$ mysqldump -u user --password=pass live_db_name | mysql -u user --password=pass -h localhost duplicate_db_name
</code>```

However, I'm looking for a way to do this where it only does a differential copy.

i.e. If anything is different in the destination database, it is modified to be identical to the source database.

Does there exist an option using mysqldump to do this?

答:
No, there is no option to do this with mysqldump.

Check out the Percona tools, or other MySQL tools, that might get you to the functionality you're looking for.

Body:
I know that you can use the following command to copy a database from one SQL server to another and overwrite the database in the destination server.

$ mysqldump -u user --password=pass live_db_name | mysql -u user --password=pass -h localhost duplicate_db_name

However, I'm looking for a way to do this where it only does a differential copy.

i.e. If anything is different in the destination database, it is modified to be identical to the source database.

Does there exist an option using mysqldump to do this?


问:
Python Web Scraper + Cleanup
So I'm currently trying to export a twitter .html page, and I created this webscraper using BeautifulSoup. The OUTPUT.csv file is currently really messy, and here are my questions (current .py file is below):

What are some steps I can take to clean out the code? My output csv has the tweets, but they're really messy, and separated by commas. Is there any way I can separate them by using a new line? Also, how can I only extract the part of the tweet that says "Bank Of America: Growth Is Back – Bank of
America Corporation" (which I surrounded by stars) in my cleanup() function?

```<code>"<div class=""js-tweet-text-container"">
<p class=""TweetTextSize js-tweet-text tweet-text"" data-aria-label-
part=""0"" lang=""en"">*****Bank Of America: Growth Is Back – Bank of
America Corporation***** (<strong>NYSE:BAC</strong>) <a class=""twitter-
timeline-link u-hidden"" data-expanded-url=""https://good-
stockinvest.com/2017/11/29/bank-of-america-growth-is-back-bank-of-
america-corporation-nysebac/"" dir=""ltr""
href="" rel=""nofollow noopener""
target=""_blank"" title=""https://good-stockinvest.com/2017/11/29/bank-
of-america-growth-is-back-bank-of-america-corporation-nysebac/""><span
class=""tco-ellipsis""></span><span class=""invisible"">https://</span>
<span class=""js-display-url"">good-
stockinvest.com/2017/11/29/ban</span><span class=""invisible"">k-of-
america-growth-is-back-bank-of-america-corporation-nysebac/</span><span
class=""tco-ellipsis""><span class=""invisible""> </span>…</span></a>
</p>
</div>"
</code>```

Below is my code:

```<code>from bs4 import BeautifulSoup
import csv

new = csv.writer(open("OUTPUT", "w"))
new.writerow(["Tweets:"])
new.writerow([ ])       # allowing for a simple space

data = open("bac.html", "r").read()
soup = BeautifulSoup(data, "html.parser")

tweets = soup.find_all('div', class_="js-tweet-text-container")

def writetweets():
    for tweet in tweets:
        new.writerow(tweets)
        new.writerow([ ])
    print "writetweets - open OUTPUT.csv for the tweet divs"

def cleanup():
    print "cleanup - nothing here for now"

def tests():
    print "tests - nothing here for now"

def demo():
    writetweets()
    cleanup()
    tests()

if __name__ == '__main__':
    demo()
</code>```

答:
A quick fix could be if you use the split() function to acquire only the text between the asterisks. Is every tweet you acquire between asterisks or this specific one?

Another solution would be to search more for tags in order to end up with a "cleaner" string as a result.
i.e. further use find_all in your "tweets" string.

Title: Python Web Scraper + Cleanup

Body:
So I'm currently trying to export a twitter .html page, and I created this webscraper using BeautifulSoup. The OUTPUT.csv file is currently really messy, and here are my questions (current .py file is below):

What are some steps I can take to clean out the code? My output csv has the tweets, but they're really messy, and separated by commas. Is there any way I can separate them by using a new line? Also, how can I only extract the part of the tweet that says "Bank Of America: Growth Is Back – Bank of
America Corporation" (which I surrounded by stars) in my cleanup() function?

"

*****Bank Of America: Growth Is Back – Bank of
America Corporation***** (NYSE:BAC) https://
good-
stockinvest.com/2017/11/29/bank-of-
america-growth-is-back-bank-of-america-corporation-nysebac/ …

"

Below is my code:

from bs4 import BeautifulSoup
import csv

new = csv.writer(open("OUTPUT", "w"))
new.writerow(["Tweets:"])
new.writerow([ ])       # allowing for a simple space

data = open("bac.html", "r").read()
soup = BeautifulSoup(data, "html.parser")

tweets = soup.find_all('div', class_="js-tweet-text-container")

def writetweets():
    for tweet in tweets:
        new.writerow(tweets)
        new.writerow([ ])
    print "writetweets - open OUTPUT.csv for the tweet divs"

def cleanup():
    print "cleanup - nothing here for now"

def tests():
    print "tests - nothing here for now"

def demo():
    writetweets()
    cleanup()
    tests()

if __name__ == '__main__':
    demo()


问:
how to get the tag list in wordpress mysql
i want to get the following information from wordpress database relate to Tag

```<code>TagID TagName TagPostCount
</code>```

Are anyone tell me and write a mysql command that give me list of this three detailed.

please don't show me PHP code. i am not really want to know about them and off-course i am relate to PHP.

how i can write a Mysql command who give me these three detailed.

答:
It's a MYSQL query against a wordpress db with "wp_" table prefix (the default)</p>

```<code>SELECT wp_terms.`term_id` AS TagID, wp_terms.`name` AS TagName, SUM( tax.`count` ) AS TagPostCount
FROM `wp_terms`
INNER JOIN wp_term_taxonomy tax ON tax.term_id = wp_terms.term_id
GROUP BY wp_terms.`term_id`
</code>```

OwnerDisplayName: Steven Spielberg

Body:
i want to get the following information from wordpress database relate to Tag

TagID TagName TagPostCount

Are anyone tell me and write a mysql command that give me list of this three detailed.

please don't show me PHP code. i am not really want to know about them and off-course i am relate to PHP.

how i can write a Mysql command who give me these three detailed.

Body:
It's a MYSQL query against a wordpress db with "wp_" table prefix (the default)

SELECT wp_terms.`term_id` AS TagID, wp_terms.`name` AS TagName, SUM( tax.`count` ) AS TagPostCount
FROM `wp_terms`
INNER JOIN wp_term_taxonomy tax ON tax.term_id = wp_terms.term_id
GROUP BY wp_terms.`term_id`


问:
Sending a structure through a socket in c
I want to send a data structure through a socket in a tcp server/client program written in C. However when i try to print the sent data it doesn't print anything. I've realized by now that sending structures this way is a bad idea, the posts i've seen aren't being very helpful in finding a way to actually make this work. Here's the data structure in question:

```<code>#define BUFFSIZE 1024
#define USERLEN 32
#define OPTLEN 16

struct  message{
  char option[OPTLEN];
  char user[USERLEN];
  char buff[BUFFSIZE];
  char target[USERLEN];
  int sockid;
};
</code>```

thanks in advance.

答:
Before, writing a structure, you need to be aware of padding issues. It seems that your structure is well aligned. However, the receiver needs to be on similar architecture and similar compiler structure packaging settings to consume the structure in the same exact way. Alternatively, you can define a message protocol that explicitly packs this data and writes as a byte stream. </p>

<p>That said, a structure could still be written simply by doing
write(sock, &myMessage, sizeof (message)). It will write out all the bytes of the sizeof(message). </p>

Body:
I want to send a data structure through a socket in a tcp server/client program written in C. However when i try to print the sent data it doesn't print anything. I've realized by now that sending structures this way is a bad idea, the posts i've seen aren't being very helpful in finding a way to actually make this work. Here's the data structure in question:

#define BUFFSIZE 1024
#define USERLEN 32
#define OPTLEN 16

struct  message{
  char option[OPTLEN];
  char user[USERLEN];
  char buff[BUFFSIZE];
  char target[USERLEN];
  int sockid;
};

thanks in advance.

Body:
Before, writing a structure, you need to be aware of padding issues. It seems that your structure is well aligned. However, the receiver needs to be on similar architecture and similar compiler structure packaging settings to consume the structure in the same exact way. Alternatively, you can define a message protocol that explicitly packs this data and writes as a byte stream.

That said, a structure could still be written simply by doing
write(sock, &myMessage, sizeof (message)). It will write out all the bytes of the sizeof(message).


问:
Verilog seems to default an option in a case statement

I am writing part of a larger program staring small. I am new to verilog so any advise would be appreciated.

I am trying to write a case statement that will, once one of four buttons is pressed it will write a number (1-4) on the first of four 7 segment displays.

```<code>    module final(CLK,button1,button2,button3,button4,a0,b0,c0,d0,e0,f0,g0,a1,b1,c1,d1,e1,f1,g1,a2,b2,c2,d2,e2,f2,g2,a3,b3,c3,d3,e3,f3,g3);
  input CLK,button1,button2,button3,button4;
  output a0,b0,c0,d0,e0,f0,g0,a1,b1,c1,d1,e1,f1,g1,a2,b2,c2,d2,e2,f2,g2,a3,b3,c3,d3,e3,f3,g3; //What a mess

  integer i = 0;

  reg [6:0] temp;
  reg [6:0] sevenDisp0;
  reg [6:0] sevenDisp1;
  reg [6:0] sevenDisp2;
  reg [6:0] sevenDisp3;
  reg [2:0] place;

  initial begin
   temp = 7'b1110111;
    sevenDisp0 = 7'b1110111;
    sevenDisp1 = 7'b1110111;
    sevenDisp2 = 7'b1110111;
    sevenDisp3 = 7'b1110111;
    i = 0;

  end
    always @(button1 or button2 or button3 or button4)// or sevenDisp0 or sevenDisp1 or sevenDisp2 or sevenDisp3)//bit1 or bit2)
    begin
        case({button1,button2,button3,button4})
            4'b0111: sevenDisp0 = 7'b1001111; //Have tried 4'b1111 to troubleshoot
            4'b1011: sevenDisp0 = 7'b0010010;
            4'b1101: sevenDisp0 = 7'b0000110;
            4'b1110: sevenDisp0 = 7'b1001100;
            //default: sevenDisp0 = 7'b1110111;
        endcase
    end

  assign {a0,b0,c0,d0,e0,f0,g0} = sevenDisp0;
  assign {a1,b1,c1,d1,e1,f1,g1} = sevenDisp1;
  assign {a2,b2,c2,d2,e2,f2,g2} = sevenDisp2;
  assign {a3,b3,c3,d3,e3,f3,g3} = sevenDisp3;

endmodule
</code>```

From my, very limited, understanding whenever one of my four buttons is pressed it runs the always statement. Whatever button is pressed will be written to the sevenDisp0 register.

One thing of note is that buttons register 0 when pressed and the seven segment is 0 for on.

What I see is a number one on the first seven segment. Pressing any other button will show the corresponding number while the button is pressed and switch back to the number one.

I have been trying to solve this for 6 hours now. Any help would be great.

答:
sevenDisp0 in an inferred latch (level-sensitive) because it is not assigned a value in all possible paths. You should try to avoid latches as they can be the cause of unexpected behavior. Most FPGA as limited or no support for latches. You should use pure combiantional logic and flops (clock edge triggered) in your design.

If you do not want sevenDisp0 to store its value, then use combinational logic (use blocking = assignment):

```<code>always @* // auto-sensitivity
  begin
    case({button1,button2,button3,button4})
        4'b0111: sevenDisp0 = 7'b1001111; //Have tried 4'b1111 to troubleshoot
        4'b1011: sevenDisp0 = 7'b0010010;
        4'b1101: sevenDisp0 = 7'b0000110;
        4'b1110: sevenDisp0 = 7'b1001100;
        default: sevenDisp0 = 7'b1110111; //Needed or will be a latch
    endcase
  end
</code>```

If you do want sevenDisp0 to store its value, then use make it sequential by triggering on the clock edge (use non-blocking <= assignment):

```<code>always @(posedge CLK)
  begin
    case({button1,button2,button3,button4})
        4'b0111: sevenDisp0 <= 7'b1001111; //Have tried 4'b1111 to troubleshoot
        4'b1011: sevenDisp0 <= 7'b0010010;
        4'b1101: sevenDisp0 <= 7'b0000110;
        4'b1110: sevenDisp0 <= 7'b1001100;
        //default: //Retain previous value of sevenDisp0
    endcase
  end
</code>```

FYI: For combinational (and intentional latching) logic, you should use auto-sensitivity @* or the synonymous @(*). Hard-coding signals in the sensitivity list is only required when required to follow the Verilog-1995 standard. Since Verilog-2001 @* is preferred as it doesn't run the risk of missing signals leading to behavior mismatches between RTL simulations and gates/FPGA/etc. Plus it is significantly less typing.

Another suggestion is to use ANSI style header (another feature added in Verilog-2001). This allows you to declare the port direction and type inside the port list order. It is also less typing. Example:

```<code>module final(
  input  CLK,
  input  button1,button2,button3,button4,
  output a0,b0,c0,d0,e0,f0,g0,    // much
  output a1,b1,c1,d1,e1,f1,g1,    // easier
  output a2,b2,c2,d2,e2,f2,g2,    // to
  output a3,b3,c3,d3,e3,f3,g3 );  // read

reg [6:0] sevenDisp0;
// ...
</code>```

Body:
I am writing part of a larger program staring small. I am new to verilog so any advise would be appreciated.

I am trying to write a case statement that will, once one of four buttons is pressed it will write a number (1-4) on the first of four 7 segment displays.

    module final(CLK,button1,button2,button3,button4,a0,b0,c0,d0,e0,f0,g0,a1,b1,c1,d1,e1,f1,g1,a2,b2,c2,d2,e2,f2,g2,a3,b3,c3,d3,e3,f3,g3);
  input CLK,button1,button2,button3,button4;
  output a0,b0,c0,d0,e0,f0,g0,a1,b1,c1,d1,e1,f1,g1,a2,b2,c2,d2,e2,f2,g2,a3,b3,c3,d3,e3,f3,g3; //What a mess

  integer i = 0;

  reg [6:0] temp;
  reg [6:0] sevenDisp0;
  reg [6:0] sevenDisp1;
  reg [6:0] sevenDisp2;
  reg [6:0] sevenDisp3;
  reg [2:0] place;

  initial begin
   temp = 7'b1110111;
    sevenDisp0 = 7'b1110111;
    sevenDisp1 = 7'b1110111;
    sevenDisp2 = 7'b1110111;
    sevenDisp3 = 7'b1110111;
    i = 0;

  end
    always @(button1 or button2 or button3 or button4)// or sevenDisp0 or sevenDisp1 or sevenDisp2 or sevenDisp3)//bit1 or bit2)
    begin
        case({button1,button2,button3,button4})
            4'b0111: sevenDisp0 = 7'b1001111; //Have tried 4'b1111 to troubleshoot
            4'b1011: sevenDisp0 = 7'b0010010;
            4'b1101: sevenDisp0 = 7'b0000110;
            4'b1110: sevenDisp0 = 7'b1001100;
            //default: sevenDisp0 = 7'b1110111;
        endcase
    end

  assign {a0,b0,c0,d0,e0,f0,g0} = sevenDisp0;
  assign {a1,b1,c1,d1,e1,f1,g1} = sevenDisp1;
  assign {a2,b2,c2,d2,e2,f2,g2} = sevenDisp2;
  assign {a3,b3,c3,d3,e3,f3,g3} = sevenDisp3;

endmodule

From my, very limited, understanding whenever one of my four buttons is pressed it runs the always statement. Whatever button is pressed will be written to the sevenDisp0 register.

One thing of note is that buttons register 0 when pressed and the seven segment is 0 for on.

What I see is a number one on the first seven segment. Pressing any other button will show the corresponding number while the button is pressed and switch back to the number one.

I have been trying to solve this for 6 hours now. Any help would be great.

Body:
sevenDisp0 in an inferred latch (level-sensitive) because it is not assigned a value in all possible paths. You should try to avoid latches as they can be the cause of unexpected behavior. Most FPGA as limited or no support for latches. You should use pure combiantional logic and flops (clock edge triggered) in your design.

If you do not want sevenDisp0 to store its value, then use combinational logic (use blocking = assignment):

always @* // auto-sensitivity
  begin
    case({button1,button2,button3,button4})
        4'b0111: sevenDisp0 = 7'b1001111; //Have tried 4'b1111 to troubleshoot
        4'b1011: sevenDisp0 = 7'b0010010;
        4'b1101: sevenDisp0 = 7'b0000110;
        4'b1110: sevenDisp0 = 7'b1001100;
        default: sevenDisp0 = 7'b1110111; //Needed or will be a latch
    endcase
  end

If you do want sevenDisp0 to store its value, then use make it sequential by triggering on the clock edge (use non-blocking <= assignment):

always @(posedge CLK)
  begin
    case({button1,button2,button3,button4})
        4'b0111: sevenDisp0 <= 7'b1001111; //Have tried 4'b1111 to troubleshoot
        4'b1011: sevenDisp0 <= 7'b0010010;
        4'b1101: sevenDisp0 <= 7'b0000110;
        4'b1110: sevenDisp0 <= 7'b1001100;
        //default: //Retain previous value of sevenDisp0
    endcase
  end

FYI: For combinational (and intentional latching) logic, you should use auto-sensitivity @* or the synonymous @(*). Hard-coding signals in the sensitivity list is only required when required to follow the Verilog-1995 standard. Since Verilog-2001 @* is preferred as it doesn't run the risk of missing signals leading to behavior mismatches between RTL simulations and gates/FPGA/etc. Plus it is significantly less typing.

Another suggestion is to use ANSI style header (another feature added in Verilog-2001). This allows you to declare the port direction and type inside the port list order. It is also less typing. Example:

module final(
  input  CLK,
  input  button1,button2,button3,button4,
  output a0,b0,c0,d0,e0,f0,g0,    // much
  output a1,b1,c1,d1,e1,f1,g1,    // easier
  output a2,b2,c2,d2,e2,f2,g2,    // to
  output a3,b3,c3,d3,e3,f3,g3 );  // read

reg [6:0] sevenDisp0;
// ...


问:
Changing from varchar to mediumtext causes performance degradation
I have a table which stores product reviews for a website.  The table uses varchar(1000) to store the review comment average response time is 0.5 seconds.  I changed the datatype of the column that holds data to mediumtext and the page response time jumps to 1.5 - 2 seconds. Baring in mind no additional data was added to the column and the PHP code is the same.

I don't think the query time is the issue, as MySQL reports it takes 0.019secs, which is the same whether varchar or mediumtext.

I'm at a loss to understand what's happened here.  I'm using MySQL PDO and PHP.  I don't know if it's a server issue, an inherent issue with mediumtext, or something else entirely.

I tried changing the table type from MyISAM to InnoDB but it made no difference.

Here is the PHP code:

```<code>$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$attrs = array(PDO::ATTR_PERSISTENT => true);
$pdo = new PDO($dsn, $user, $pass, $attrs);

$stmt = $pdo->prepare("SELECT SQL_NO_CACHE comment
       FROM reviews_product_comments
       WHERE part_id =:partid
         and language =:language");

foreach ($parts as $part) {

    // bind the parameters
    $stmt->bindValue(":partid", $part);
    $stmt->bindValue(":language", "en");

    if ($stmt->execute()) {
        if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $comment = $row['comment'];
            echo $comment . "<br>";
        }
    }

}

$pdo = null;
</code>```

Any ideas?

答:
The two datatypes are handled virtually identically.  There are many other possible reasons for sluggishness.  (But none that I know of that would say MEDIUMTEXT is worse than VARHAR.)

So...  Let's see if we can speed up the web page...

Put microtime(true) around the mysql calls -- to make sure it is MySQL, not PHP.  "0.019secs" makes sense; "1.5 - 2 seconds" sounds like something is going on in PHP.

Use InnoDB, not MyISAM.  (In spite of your claims to the contrary.)

Tune correctly; let's see SHOW VARIABLES LIKE '%buffer%';  How much RAM do you have?  (Swapping is terrible for performance.)

How many rows are you returning?  It's not practical to have more than a few dozen on a web page, so add ORDER BY...LIMIT....

If the UI limit is 1000 characters, use TEXT or VARCHAR(1000), not MEDIUMTEXT.  If you are trying to raise up to 64K bytes (potentially 4K utf8mb4 characters), then use TEXT.

You do need this (with the columns in either order):

```<code>INDEX(part_id, language)
</code>```

If there has been a lot of "churn" (deletes and/or updates followed by more inserts) in the MyISAM table, the data can be fragmented, hence slow.  This can happen for both VARCHAR and TEXT.  This does not happen with InnoDB.

Body:
I have a table which stores product reviews for a website.  The table uses varchar(1000) to store the review comment average response time is 0.5 seconds.  I changed the datatype of the column that holds data to mediumtext and the page response time jumps to 1.5 - 2 seconds. Baring in mind no additional data was added to the column and the PHP code is the same.

I don't think the query time is the issue, as MySQL reports it takes 0.019secs, which is the same whether varchar or mediumtext.

I'm at a loss to understand what's happened here.  I'm using MySQL PDO and PHP.  I don't know if it's a server issue, an inherent issue with mediumtext, or something else entirely.

I tried changing the table type from MyISAM to InnoDB but it made no difference.

Here is the PHP code:

$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$attrs = array(PDO::ATTR_PERSISTENT => true);
$pdo = new PDO($dsn, $user, $pass, $attrs);

$stmt = $pdo->prepare("SELECT SQL_NO_CACHE comment
       FROM reviews_product_comments
       WHERE part_id =:partid
         and language =:language");

foreach ($parts as $part) {

    // bind the parameters
    $stmt->bindValue(":partid", $part);
    $stmt->bindValue(":language", "en");

    if ($stmt->execute()) {
        if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $comment = $row['comment'];
            echo $comment . "
";
        }
    }

}

$pdo = null;

Any ideas?

Body:
The two datatypes are handled virtually identically.  There are many other possible reasons for sluggishness.  (But none that I know of that would say MEDIUMTEXT is worse than VARHAR.)

So...  Let's see if we can speed up the web page...

Put microtime(true) around the mysql calls -- to make sure it is MySQL, not PHP.  "0.019secs" makes sense; "1.5 - 2 seconds" sounds like something is going on in PHP.

Use InnoDB, not MyISAM.  (In spite of your claims to the contrary.)

Tune correctly; let's see SHOW VARIABLES LIKE '%buffer%';  How much RAM do you have?  (Swapping is terrible for performance.)

How many rows are you returning?  It's not practical to have more than a few dozen on a web page, so add ORDER BY...LIMIT....

If the UI limit is 1000 characters, use TEXT or VARCHAR(1000), not MEDIUMTEXT.  If you are trying to raise up to 64K bytes (potentially 4K utf8mb4 characters), then use TEXT.

You do need this (with the columns in either order):

INDEX(part_id, language)

If there has been a lot of "churn" (deletes and/or updates followed by more inserts) in the MyISAM table, the data can be fragmented, hence slow.  This can happen for both VARCHAR and TEXT.  This does not happen with InnoDB.


问:
How to programmatically open a website and click buttons
How to use VBScript to implement the following:

Open web browser

Load a URL in web browser after opening

List item

Click buttons in the loaded browser

Is this possible using VBScript. Any examples of code to help get me started would be beneficial. Also, my web browser is Chrome.

答:
If you press F12 in Internet Explorer you can lie about what browser you are using. Use the compatibility tab (a downward direction play icon) and enter your UA string for a browser they support.

See https://msdn.microsoft.com/en-us/library/ms537503(v=vs.85).aspx


问:
angular 2 cli returns error if using --aot
I have this code that works fine:

```<code>samplesInfo: any = [];
selectedSampleType: Object = {};
selectedSampleTypeForModal: string; // pass type as string to the child component
userFormSubmitted: boolean;

ngOnInit() {

    this.SamplesInfoService.getSamplesInfo()
        .map((res: Response) => res)
        .subscribe(
            data => {
                function hasType(value) { return value.hasOwnProperty('type'); }
                this.samplesInfo = data,
                this.selectedSampleType = this.samplesInfo.filter(hasType)[0],
                this.selectedSampleTypeForModal = this.samplesInfo.filter(hasType)[0].type,
                console.log("OLGA " + this.samplesInfo.filter(hasType)[0]);
                },
            err => { console.log(err); return Observable.of(true); }
    );

}
</code>```

But if I try to build within CLI with the "--aot" added to the command, then I have an error: "Property 'type' does not exist on type 'Object'".

What am I doing wrong here?

Thanks,
Olga

答:
My guess is this line is the culprit:

```<code>this.selectedSampleTypeForModal = this.samplesInfo.filter(hasType)[0].type
</code>```

That .type at the end - it looks like TypeScript thinks that property doesn't exist.

Body:
I have this code that works fine:

samplesInfo: any = [];
selectedSampleType: Object = {};
selectedSampleTypeForModal: string; // pass type as string to the child component
userFormSubmitted: boolean;

ngOnInit() {

    this.SamplesInfoService.getSamplesInfo()
        .map((res: Response) => res)
        .subscribe(
            data => {
                function hasType(value) { return value.hasOwnProperty('type'); }
                this.samplesInfo = data,
                this.selectedSampleType = this.samplesInfo.filter(hasType)[0],
                this.selectedSampleTypeForModal = this.samplesInfo.filter(hasType)[0].type,
                console.log("OLGA " + this.samplesInfo.filter(hasType)[0]);
                },
            err => { console.log(err); return Observable.of(true); }
    );

}

But if I try to build within CLI with the "--aot" added to the command, then I have an error: "Property 'type' does not exist on type 'Object'".

What am I doing wrong here?

Thanks,
Olga

Body:
My guess is this line is the culprit:

this.selectedSampleTypeForModal = this.samplesInfo.filter(hasType)[0].type

That .type at the end - it looks like TypeScript thinks that property doesn't exist.


问:
How to Solve Error "object is not a matrix" in fitted(arima_model) when constructing Arima(0,0,0) White Noise
So, here i have a reproducible example on why getting this error:

Time Series Data

```<code>data = c(48,148,284,72,48,24,48,24,48,24,24,0,96,24,48,96,72,24,96,24,48)
time = ts(data, start=c(2015,2), end=c(2016,10), frequency=12)
</code>```

i am trying to construct this time series into Arima Model, auto.arima recommend me Arima(0,0,0) to this time series data which is white noise, but after successfully created the model, the error begin when i try to extract the fitted value of model

Error in getting fitted model

```<code>model = arima(time,order=c(0,0,0))
fitted(model)
</code>```

I didn't understand what is the meaning of this error, because of this, i try using another time series data which is AirPassengers to make sure it can get the fitted value, here is the AirPassengers data i using

Data AirPassengers

```<code>Y= window(AirPassengers, start=c(1949,7), end=c(1950,10))
model2 = arima(Y, order=c(0,0,0))
fitted(model2)
</code>```

Again then i try to create same Arima model and try to get the fitted value of the model, and it worked flawlessly without any trace of error like this

Successfully get fitted value of AirPassengers

with knowing these 2 example, i can't figure out why the first model are getting Error in attr(data, "tsp") <- c(start, end, frequency) object is not a matrix,
anyone can give me a clue/explanation ? is there something i missing or is this some bug?

also i noticed there is a little different from the summary model of the 2 model above like this:

Summary Model

```<code>summary(model)
summary(model2)
</code>```

Thank You for noticing my question, any feedback welcomed :)

答:
Too bad your question was so poorly stated, because I think it actually is pretty interesting, and someone more knowledgeable than me should probably be answering it.

I've been prodding functions, methods and namespaces for hours now, and it turns out to be a case of name masking/conflict/scoping, I think. (I'm not a computer scientist, I don't know all the words and all the things)

The fix is easy enough, you just use Arima() instead of arima(), or use auto.arima() directly.

```<code>library(forecast)

model.ARIMA <- Arima(time, order=c(0,0,0))
fitted(model.ARIMA)

# or
fitted(auto.arima(time))
</code>```

The reason for this working is that Arima() returns an object with both the original time series and the fitted values already included. fitted() then simply returns model.ARIMA$fitted.

arima() on the other hand doesn't include the fitted values in the returned object, so fitted() will have to compute them. That is simple enough, you just subtract the the residuals from the original time series. Only trouble is that while the residuals are included in the model object, the original time series isn't, so some tricks need to be applied. What happens is that fitted() calls another function getResponse(), which searches the environment for an object with the name included in the model object (model.ARIMA$series), in your case time. Problems occur because time already existed before you created it, namely as the function time(). Normally that isn't such an issue, because R tends to understand when you want the variable and when you want the function, e.g:

```<code>c <- 4
c
c(1, c)
c <- base::c
c
</code>```

Inside getResponse() however, evaluation is done differently, but I'm not entirely sure how.

The lesson is the same however: if you name your variable the same as a function, strange things can happen.

Body:
So, here i have a reproducible example on why getting this error:

Time Series Data

data = c(48,148,284,72,48,24,48,24,48,24,24,0,96,24,48,96,72,24,96,24,48)
time = ts(data, start=c(2015,2), end=c(2016,10), frequency=12)

i am trying to construct this time series into Arima Model, auto.arima recommend me Arima(0,0,0) to this time series data which is white noise, but after successfully created the model, the error begin when i try to extract the fitted value of model

Error in getting fitted model

model = arima(time,order=c(0,0,0))
fitted(model)

I didn't understand what is the meaning of this error, because of this, i try using another time series data which is AirPassengers to make sure it can get the fitted value, here is the AirPassengers data i using

Data AirPassengers

Y= window(AirPassengers, start=c(1949,7), end=c(1950,10))
model2 = arima(Y, order=c(0,0,0))
fitted(model2)

Again then i try to create same Arima model and try to get the fitted value of the model, and it worked flawlessly without any trace of error like this

Successfully get fitted value of AirPassengers

with knowing these 2 example, i can't figure out why the first model are getting Error in attr(data, "tsp") <- c(start, end, frequency) object is not a matrix,
anyone can give me a clue/explanation ? is there something i missing or is this some bug?

also i noticed there is a little different from the summary model of the 2 model above like this:

Summary Model

summary(model)
summary(model2)

Thank You for noticing my question, any feedback welcomed :)

Body:
Too bad your question was so poorly stated, because I think it actually is pretty interesting, and someone more knowledgeable than me should probably be answering it.

I've been prodding functions, methods and namespaces for hours now, and it turns out to be a case of name masking/conflict/scoping, I think. (I'm not a computer scientist, I don't know all the words and all the things)

The fix is easy enough, you just use Arima() instead of arima(), or use auto.arima() directly.

library(forecast)

model.ARIMA <- Arima(time, order=c(0,0,0))
fitted(model.ARIMA)

# or
fitted(auto.arima(time))

The reason for this working is that Arima() returns an object with both the original time series and the fitted values already included. fitted() then simply returns model.ARIMA$fitted.

arima() on the other hand doesn't include the fitted values in the returned object, so fitted() will have to compute them. That is simple enough, you just subtract the the residuals from the original time series. Only trouble is that while the residuals are included in the model object, the original time series isn't, so some tricks need to be applied. What happens is that fitted() calls another function getResponse(), which searches the environment for an object with the name included in the model object (model.ARIMA$series), in your case time. Problems occur because time already existed before you created it, namely as the function time(). Normally that isn't such an issue, because R tends to understand when you want the variable and when you want the function, e.g:

c <- 4
c
c(1, c)
c <- base::c
c

Inside getResponse() however, evaluation is done differently, but I'm not entirely sure how.

The lesson is the same however: if you name your variable the same as a function, strange things can happen.


问:
SpriteKit not deallocating all used memory
I have ready many (if not all) articles on SO and other sites about the disasters of dealing with SpriteKit and memory issues. My problem, as many others have had, is after i leave my SpriteKit scene barely any of the memory added during the scene session is released. I've tried to implement all suggested solutions in the articles i've found, including, but not limited to...

1) Confirm the deinit method is called in the SKScene class.

2) Confirm no strong references to the parent VC in the scene class.

3) Forcefully remove all children and actions, and set the scene to nil when the VC disappears. (Setting the scene to nil was what got the deinit method to eventually get called)

However, after all of that, memory still exists. Some background, this app goes between standard UIKit view controllers and a SpriteKit scene (it's a professional drawing app). As an example, the app is using around 400 MB before entering a SpriteKit scene. After entering the scene and creating multiple nodes, the memory grows to over 1 GB (all fine so far). When i leave the scene, the memory drops maybe 100 MB. And if i re-enter the scene, it continues to pile on. Are there any ways or suggestions on how to completely free all memory that was used during a SpriteKit session?  Below is a few of the methods being used to try and fix this.

SKScene class

```<code>func cleanScene() {
    if let s = self.view?.scene {
        NotificationCenter.default.removeObserver(self)
        self.children
            .forEach {
                $0.removeAllActions()
                $0.removeAllChildren()
                $0.removeFromParent()
        }
        s.removeAllActions()
        s.removeAllChildren()
        s.removeFromParent()
    }
}

override func willMove(from view: SKView) {
    cleanScene()
    self.removeAllActions()
    self.removeAllChildren()
}
</code>```

Presenting VC

```<code>var scene: DrawingScene?

override func viewDidLoad(){
    let skView = self.view as! SKView
    skView.ignoresSiblingOrder = true
    scene = DrawingScene(size: skView.frame.size)
    scene?.scaleMode = .aspectFill
    scene?.backgroundColor = UIColor.white
    drawingNameLabel.text = self.currentDrawing?.name!
    scene?.currentDrawing = self.currentDrawing!

    scene?.drawingViewManager = self

    skView.presentScene(scene)
}

override func viewDidDisappear(_ animated: Bool) {
    if let view = self.view as? SKView{
        self.scene = nil //This is the line that actually got the scene to call denit.
        view.presentScene(nil)
    }
}
</code>```

答:
As discussed in the comments, the problem is probably related to a strong reference cycle.

Next steps

Recreate a simple game where the scene is properly deallocated but some of the nodes are not.

I'll reload the scene several time. You'll see the scene is properly deallocated but some nodes into the scene are not. This will cause a bigger memory consumption each time we replace the old scene with a new one.

I'll show you how to find the origin of the problem with Instruments

And finally I'll show you how to fix the problem.

1. Let's create a game with a memory problem

Let's just create a new game with Xcode based on SpriteKit.

We need to create a new file Enemy.swift with the following content

```<code>import SpriteKit

class Enemy: SKNode {
    private let data = Array(0...1_000_000) // just to make the node more memory consuming
    var friend: Enemy?

    override init() {
        super.init()
        print("Enemy init")
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    deinit {
        print("Enemy deinit")
    }
}
</code>```

We also need to replace the content of Scene.swift with the following source code

```<code>import SpriteKit

class GameScene: SKScene {

    override init(size: CGSize) {
        super.init(size: size)
        print("Scene init")
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        print("Scene init")
    }

    override func didMove(to view: SKView) {
        let enemy0 = Enemy()
        let enemy1 = Enemy()

        addChild(enemy0)
        addChild(enemy1)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let newScene = GameScene(size: self.size)
        self.view?.presentScene(newScene)
    }

    deinit {
        print("Scene deinit")
    }
}
</code>```

As you can see the game is designed to replace the current scene with a new one each time the user taps the screen.

Let's start the game and look at the console. Will' see

Scene init
Enemy init
Enemy init

It means we have a total of 3 nodes.

Now let's tap on the screen and let's look again at the console

Scene init
Enemy init
Enemy init
Scene init
Enemy init
Enemy init
Scene deinit
Enemy deinit
Enemy deinit

We can see that a new scene and 2 new enemies have been created (lines 4, 5, 6). Finally the old scene is deallocated (line 7) and the 2 old enemies are deallocated (lines 8 and 9).

So we still have 3 nodes in memory. And this is good, we don't have memory leeks.

If we monitor the memory consumption with Xcode we can verify that there is no increase in the memory requirements each time we restart the scene.

2. Let create a strong reference cycle

We can update the didMove method in Scene.swift like follows

```<code>override func didMove(to view: SKView) {
    let enemy0 = Enemy()
    let enemy1 = Enemy()

    // ☠☠☠ this is a scary strong retain cycle ☠☠☠
    enemy0.friend = enemy1
    enemy1.friend = enemy0
    // **************************************************

    addChild(enemy0)
    addChild(enemy1)
}
</code>```

As you can see we now have a strong cycle between enemy0 and enemy1.

Let's run the game again.

If now we tap on the screen and the look at the console we'll see

Scene init
Enemy init
Enemy init
Scene init
Enemy init
Enemy init
Scene deinit

As you can see the Scene is deallocated but the Enemy(s) are no longer removed from memory.

Let's look at Xcode Memory Report

Now the memory consumption goes up every time we replace the old scene with a new one.

3. Finding the issue with Instruments

Of course we know exactly where the problem is (we added the strong retain cycles 1 minute ago). But how could we detect a strong retain cycle in a big project?

Let click on the Instrument button in Xcode (while the game is running into the Simulator).

And let's click on Transfer on the next dialog.

Now we need to select the Leak Checks

Good, at this point as soon as a leak is detected, it will appear in the bottom of Instruments.

4. Let's make the leak happen

Back to the simulator and tap again. The scene will be replaced again.
Go back to Instruments, wait a few seconds and...

Here it is our leak.

Let's expand it.

Instruments is telling us exactly that 8 objects of type Enemy have been leaked.

We can also select the view Cycles and Root and Instrument will show us this

That's our strong retain cycle!

Specifically Instrument is showing 4 Strong Retain Cycles (with a total of 8 Enemy(s) leaked because I tapped the screen of the simulator 4 times).

5. Fixing the problem

Now that we know the problem is the Enemy class, we can go back to our project and fix the issue.

We can simply make the friend property weak.

Let's update the Enemy class.

```<code>class Enemy: SKNode {
    private let data = Array(0...1_000_000)
    weak var friend: Enemy?
    ...
</code>```

We can check again to verify the problem is gone.

Body:
I have ready many (if not all) articles on SO and other sites about the disasters of dealing with SpriteKit and memory issues. My problem, as many others have had, is after i leave my SpriteKit scene barely any of the memory added during the scene session is released. I've tried to implement all suggested solutions in the articles i've found, including, but not limited to...

1) Confirm the deinit method is called in the SKScene class.

2) Confirm no strong references to the parent VC in the scene class.

3) Forcefully remove all children and actions, and set the scene to nil when the VC disappears. (Setting the scene to nil was what got the deinit method to eventually get called)

However, after all of that, memory still exists. Some background, this app goes between standard UIKit view controllers and a SpriteKit scene (it's a professional drawing app). As an example, the app is using around 400 MB before entering a SpriteKit scene. After entering the scene and creating multiple nodes, the memory grows to over 1 GB (all fine so far). When i leave the scene, the memory drops maybe 100 MB. And if i re-enter the scene, it continues to pile on. Are there any ways or suggestions on how to completely free all memory that was used during a SpriteKit session?  Below is a few of the methods being used to try and fix this.

SKScene class

func cleanScene() {
    if let s = self.view?.scene {
        NotificationCenter.default.removeObserver(self)
        self.children
            .forEach {
                $0.removeAllActions()
                $0.removeAllChildren()
                $0.removeFromParent()
        }
        s.removeAllActions()
        s.removeAllChildren()
        s.removeFromParent()
    }
}

override func willMove(from view: SKView) {
    cleanScene()
    self.removeAllActions()
    self.removeAllChildren()
}

Presenting VC

var scene: DrawingScene?

override func viewDidLoad(){
    let skView = self.view as! SKView
    skView.ignoresSiblingOrder = true
    scene = DrawingScene(size: skView.frame.size)
    scene?.scaleMode = .aspectFill
    scene?.backgroundColor = UIColor.white
    drawingNameLabel.text = self.currentDrawing?.name!
    scene?.currentDrawing = self.currentDrawing!

    scene?.drawingViewManager = self

    skView.presentScene(scene)
}

override func viewDidDisappear(_ animated: Bool) {
    if let view = self.view as? SKView{
        self.scene = nil //This is the line that actually got the scene to call denit.
        view.presentScene(nil)
    }
}

Body:
As discussed in the comments, the problem is probably related to a strong reference cycle.

Next steps

Recreate a simple game where the scene is properly deallocated but some of the nodes are not.

I'll reload the scene several time. You'll see the scene is properly deallocated but some nodes into the scene are not. This will cause a bigger memory consumption each time we replace the old scene with a new one.

I'll show you how to find the origin of the problem with Instruments

And finally I'll show you how to fix the problem.

1. Let's create a game with a memory problem

Let's just create a new game with Xcode based on SpriteKit.

We need to create a new file Enemy.swift with the following content

import SpriteKit

class Enemy: SKNode {
    private let data = Array(0...1_000_000) // just to make the node more memory consuming
    var friend: Enemy?

    override init() {
        super.init()
        print("Enemy init")
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    deinit {
        print("Enemy deinit")
    }
}

We also need to replace the content of Scene.swift with the following source code

import SpriteKit

class GameScene: SKScene {

    override init(size: CGSize) {
        super.init(size: size)
        print("Scene init")
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        print("Scene init")
    }

    override func didMove(to view: SKView) {
        let enemy0 = Enemy()
        let enemy1 = Enemy()

        addChild(enemy0)
        addChild(enemy1)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let newScene = GameScene(size: self.size)
        self.view?.presentScene(newScene)
    }

    deinit {
        print("Scene deinit")
    }
}

As you can see the game is designed to replace the current scene with a new one each time the user taps the screen.

Let's start the game and look at the console. Will' see

Scene init
Enemy init
Enemy init

It means we have a total of 3 nodes.

Now let's tap on the screen and let's look again at the console

Scene init
Enemy init
Enemy init
Scene init
Enemy init
Enemy init
Scene deinit
Enemy deinit
Enemy deinit

We can see that a new scene and 2 new enemies have been created (lines 4, 5, 6). Finally the old scene is deallocated (line 7) and the 2 old enemies are deallocated (lines 8 and 9).

So we still have 3 nodes in memory. And this is good, we don't have memory leeks.

If we monitor the memory consumption with Xcode we can verify that there is no increase in the memory requirements each time we restart the scene.

2. Let create a strong reference cycle

We can update the didMove method in Scene.swift like follows

override func didMove(to view: SKView) {
    let enemy0 = Enemy()
    let enemy1 = Enemy()

    // ☠☠☠ this is a scary strong retain cycle ☠☠☠
    enemy0.friend = enemy1
    enemy1.friend = enemy0
    // **************************************************

    addChild(enemy0)
    addChild(enemy1)
}

As you can see we now have a strong cycle between enemy0 and enemy1.

Let's run the game again.

If now we tap on the screen and the look at the console we'll see

Scene init
Enemy init
Enemy init
Scene init
Enemy init
Enemy init
Scene deinit

As you can see the Scene is deallocated but the Enemy(s) are no longer removed from memory.

Let's look at Xcode Memory Report

Now the memory consumption goes up every time we replace the old scene with a new one.

3. Finding the issue with Instruments

Of course we know exactly where the problem is (we added the strong retain cycles 1 minute ago). But how could we detect a strong retain cycle in a big project?

Let click on the Instrument button in Xcode (while the game is running into the Simulator).

And let's click on Transfer on the next dialog.

Now we need to select the Leak Checks

Good, at this point as soon as a leak is detected, it will appear in the bottom of Instruments.

4. Let's make the leak happen

Back to the simulator and tap again. The scene will be replaced again.
Go back to Instruments, wait a few seconds and...

Here it is our leak.

Let's expand it.

Instruments is telling us exactly that 8 objects of type Enemy have been leaked.

We can also select the view Cycles and Root and Instrument will show us this

That's our strong retain cycle!

Specifically Instrument is showing 4 Strong Retain Cycles (with a total of 8 Enemy(s) leaked because I tapped the screen of the simulator 4 times).

5. Fixing the problem

Now that we know the problem is the Enemy class, we can go back to our project and fix the issue.

We can simply make the friend property weak.

Let's update the Enemy class.

class Enemy: SKNode {
    private let data = Array(0...1_000_000)
    weak var friend: Enemy?
    ...

We can check again to verify the problem is gone.


答:
You can just write the message out on the socket:

```<code>struct message mymess;
...
write(socketfd, &mymess, sizeof(struct message));
</code>```

and then read it back in on the client side. That works if it's always the same hardware / compiler, since the struct will be compiled the same way. If you haven't memset() the whole of mymess, then you are likely to have uninitialized stuff in the write(). It should be safe, but can set off sanity checks.

For more reliable messaging you need to design or adopt a serialization protocol. JSON is an extremely popular one (albeit perhaps not among C programmers), but there are many others.

Title: Sending a structure through a socket in c

Body:
You can just write the message out on the socket:

struct message mymess;
...
write(socketfd, &mymess, sizeof(struct message));

and then read it back in on the client side. That works if it's always the same hardware / compiler, since the struct will be compiled the same way. If you haven't memset() the whole of mymess, then you are likely to have uninitialized stuff in the write(). It should be safe, but can set off sanity checks.

For more reliable messaging you need to design or adopt a serialization protocol. JSON is an extremely popular one (albeit perhaps not among C programmers), but there are many others.


问:
Asking for other collision inside OnCollisionExit2D - Unity
I have two types of grounds tagged with "groundBlack" & "groundWhite". In order to jump, I check if the collider left an object which tag starts with "ground".

```<code>void OnCollisionExit2D(Collision2D col){

    if (col.gameObject.tag.Substring (0, 5) == "ground") {
        playerController.grounded = false;
    }

  }
</code>```

The problem is that each time my player moves from one to another, it sets grounded to false and I don't want to. Is there a way to know inside an OnCollisionExit2D if it is still colliding with other object tagged with ground or there is another way to do that ? Thank in advance!

答:
col.GetContacts will give you all the current contacts. Hopefully it should still be populated in OnCollisionExit. Otherwise you can just keep a list of collisions: add on entry, remove on exit. Then you only set grounded to false when your list is empty.

Also, instead of .Substring (0, 5) == "ground" you should use .StartsWith("ground"). No need to allocate a new string just for a comparison.

Body:
I have two types of grounds tagged with "groundBlack" & "groundWhite". In order to jump, I check if the collider left an object which tag starts with "ground".

void OnCollisionExit2D(Collision2D col){

    if (col.gameObject.tag.Substring (0, 5) == "ground") {
        playerController.grounded = false;
    }

  }

The problem is that each time my player moves from one to another, it sets grounded to false and I don't want to. Is there a way to know inside an OnCollisionExit2D if it is still colliding with other object tagged with ground or there is another way to do that ? Thank in advance!


问:
Support UNION function in BigQuery SQL
BigQuery does not seem to have support for UNION yet:
https://developers.google.com/bigquery/docs/query-reference

(I don't mean unioning tables together for the source. It has that.)

Is it coming soon?

答:
Note that, if you're using standard SQL, the comma operator now means JOIN - you have to use the UNION syntax if you want a union:

In legacy SQL, the comma operator , has the non-standard meaning of UNION ALL when applied to tables. In standard SQL, the comma operator has the standard meaning of JOIN.

For example:

```<code>#standardSQL
SELECT
    column_name,
    count(*)
from
    (SELECT * FROM me.table1 UNION ALL SELECT * FROM me.table2)
group by 1
</code>```

Title: Support UNION function in BigQuery SQL

Body:
Note that, if you're using standard SQL, the comma operator now means JOIN - you have to use the UNION syntax if you want a union:

In legacy SQL, the comma operator , has the non-standard meaning of UNION ALL when applied to tables. In standard SQL, the comma operator has the standard meaning of JOIN.

For example:

#standardSQL
SELECT
    column_name,
    count(*)
from
    (SELECT * FROM me.table1 UNION ALL SELECT * FROM me.table2)
group by 1


问:
Logback logs kept open by application and not deleting from disk
I have an Spring-Boot application on Linux that writes to service logs using Logback. Logback is setup to write to a file (account-service.log) and rotate the file at 10.5MB and finally delete the file on the 8th rotate. This is the default configuration.

The issue I'm having is the first log file created is written to past the 10.5MB size limit (it does rotate at the 10.5MB mark). So it's increasing in size until it becomes the 8th file and then it tries to get deleted. At this point the file is 84MB (10.5MB * 8) size. You can see here the file increasing in size

The main problem with that is that the OS tries to delete the file but since the application, because of Logback, still keeps it open then the filesystem doesn't show the deleted file (like with command find or du) and the system still keeps the space allocated on the disk. Also the file is still written to so it's taking up more and more disk space. I ran sudo lsof | grep deleted to find out that this file isn't being fully deleted.

Also interestingly the group that that first file belongs to is different than the rest. The first file has group root while the rest have the correct group name of account-service. This might be why the application can't close the file but I'm not sure.

The Logback dependency comes from my Spring-Boot pom:

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.1.RELEASE</version>
</parent>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Dalston.SR4</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
</code>```

The subsequent log files do get deleted ok and don't get written to past the 10.5 MB limit.

Has anyone seen this issue or found a way to fix it?

答: As you have mentioned the file as root user access permissions which do not look correct. Can you check the application by doing ps -efw | grep applicationName to see what user permissions it has as your application should have application user permissions only.      </p>

Body:
I have an Spring-Boot application on Linux that writes to service logs using Logback. Logback is setup to write to a file (account-service.log) and rotate the file at 10.5MB and finally delete the file on the 8th rotate. This is the default configuration.

The issue I'm having is the first log file created is written to past the 10.5MB size limit (it does rotate at the 10.5MB mark). So it's increasing in size until it becomes the 8th file and then it tries to get deleted. At this point the file is 84MB (10.5MB * 8) size. You can see here the file increasing in size

The main problem with that is that the OS tries to delete the file but since the application, because of Logback, still keeps it open then the filesystem doesn't show the deleted file (like with command find or du) and the system still keeps the space allocated on the disk. Also the file is still written to so it's taking up more and more disk space. I ran sudo lsof | grep deleted to find out that this file isn't being fully deleted.

Also interestingly the group that that first file belongs to is different than the rest. The first file has group root while the rest have the correct group name of account-service. This might be why the application can't close the file but I'm not sure.

The Logback dependency comes from my Spring-Boot pom:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.1.RELEASE</version>
</parent>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Dalston.SR4</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

The subsequent log files do get deleted ok and don't get written to past the 10.5 MB limit.

Has anyone seen this issue or found a way to fix it?