问:
How to pass a function and a value to the onchange HTML-attribute?
I am working on a project and I would like to know how to pass a function and a value within the onchange attribute.

For example I have the function updateField() and the value $str.

How to pass the function and value "onchange"?

```<code><?php
    $str = "refrescarPruebas(this.form)";
    $rs =   consultaAplicacion();
    echo '<div class="campo">'
        . '<select name="aplicacion" onchange="'.$str.'" class="normal_text">'
        . '<option value = "">Elija tipo de mensaje..</option>';
    while($row = mysql_fetch_array($rs))
        echo'<optionvalue="'.$row["id"],'">'.$row["id"].''.$row['descripcion'].'</option>';
    echo  '</select>'
    . '</div>';
?>
</code>```

答:
There is a syntax mistake.you need to give the space between option and their value.</p>

```<code><?php
    $str = "refrescarPruebas(this.form)";
    $rs =   consultaAplicacion();
    echo '<div class="campo">'
        . '<select name="aplicacion" onchange="'.$str.'" class="normal_text">'
        . '<option value = "">Elija tipo de mensaje..</option>';
    while($row = mysql_fetch_array($rs))
        echo'<option value="'.$row["id"],'">'.$row["id"].''.$row['descripcion'].'</option>';
    echo  '</select>'
    . '</div>';
?>
</code>```

Body:
I am working on a project and I would like to know how to pass a function and a value within the onchange attribute.

For example I have the function updateField() and the value $str.

How to pass the function and value "onchange"?

<?php
    $str = "refrescarPruebas(this.form)";
    $rs =   consultaAplicacion();
    echo '
'
        . '<select name="aplicacion" onchange="'.$str.'" class="normal_text">'
        . '<option value = "">Elija tipo de mensaje..</option>';
    while($row = mysql_fetch_array($rs))
        echo'<optionvalue="'.$row["id"],'">'.$row["id"].''.$row['descripcion'].'</option>';
    echo  '</select>'
    . '
';
?>

Body:
There is a syntax mistake.you need to give the space between option and their value.

<?php
    $str = "refrescarPruebas(this.form)";
    $rs =   consultaAplicacion();
    echo '<div class="campo">'
        . '<select name="aplicacion" onchange="'.$str.'" class="normal_text">'
        . '<option value = "">Elija tipo de mensaje..</option>';
    while($row = mysql_fetch_array($rs))
        echo'<option value="'.$row["id"],'">'.$row["id"].''.$row['descripcion'].'</option>';
    echo  '</select>'
    . '</div>';
?>


来源: stackexchange

问:
VBScript slow byte array copy
I am using the following code to read in a binary file in VBScript and store it in a byte array which I then access from Javascript and copy to a JS array, basically just a sneaky way (the only way!) i've found of reading binary data in my JS.

```<code>Function readBinaryFile(fileName)
    dim inStream,buff

    set inStream=CreateObject("ADODB.Stream")
    inStream.Open
    inStream.type=1

    inStream.LoadFromFile fileName

    buff=inStream.Read()
    inStream.Close

    Dim byteArray()

    Dim i
    Dim len
    len = LenB(buff)

    ReDim byteArray(len)

    For i = 1 To len
        byteArray(i-1) = AscB(MidB(buff, i, 1))
    Next

    readBinaryFile=byteArray
End Function
</code>```

It appears to work exactly as expected, the only problem being it seems extremely slow. For example, reading in a 300kb file can take over 2 minutes. I am expecting to read files up to around 2meg.

Could anyone explain why this is such a slow operation and if there's anything I can do to speed it up?

Thanks.

答: I think its because you are using a high level scripting language to emulate something that should be done by low-level compiled languages.  I guess there's a reason scripts don't support binary data.  They are not designed to deal with data one byte at a time.  Looping through 300,000 bytes of data would take a noticable amount of time in many languages, but a non-compiled (scripting) language makes it even worse.  The only things I can suggest are using a compiled language instead, or using some ActiveX object created in a compiled language that supports the operations you want to perform without having to perform them byte-by-byte in script.  Do you have the option of using compiled components or other languages?</p>

ContentLicense: CC BY-SA 2.5

Title: VBScript slow byte array copy

Body:
I am using the following code to read in a binary file in VBScript and store it in a byte array which I then access from Javascript and copy to a JS array, basically just a sneaky way (the only way!) i've found of reading binary data in my JS.

Function readBinaryFile(fileName)
    dim inStream,buff

    set inStream=CreateObject("ADODB.Stream")
    inStream.Open
    inStream.type=1

    inStream.LoadFromFile fileName

    buff=inStream.Read()
    inStream.Close

    Dim byteArray()

    Dim i
    Dim len
    len = LenB(buff)

    ReDim byteArray(len)

    For i = 1 To len
        byteArray(i-1) = AscB(MidB(buff, i, 1))
    Next

    readBinaryFile=byteArray
End Function

It appears to work exactly as expected, the only problem being it seems extremely slow. For example, reading in a 300kb file can take over 2 minutes. I am expecting to read files up to around 2meg.

Could anyone explain why this is such a slow operation and if there's anything I can do to speed it up?

Thanks.


问:
How to run a sql script file using sqlcmd and output to both shell and file
I'm trying to run a sql script from a file using sqlcmd, using the following command:

```<code>sqlcmd -S <server> -d <database> -i <input file> -o <output file>
      -U <user> -P <password>
</code>```

I run my sql file and output to a log file.

The problem is this change the output of sqlcmd to the file.. and i want to get the output also to the shell.

答:
This code can be used for connection that require authentication</p>

```<code>sqlcmd -S "server_name" -d "database_name" -i "input_file" -o "output_file" -U "user_name" -P "password"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to run a sql script from a file using sqlcmd, using the following command:

sqlcmd -S <server> -d <database> -i <input file> -o <output file>
      -U <user> -P <password>

I run my sql file and output to a log file.

The problem is this change the output of sqlcmd to the file.. and i want to get the output also to the shell.

Body:
This code can be used for connection that require authentication

sqlcmd -S "server_name" -d "database_name" -i "input_file" -o "output_file" -U "user_name" -P "password"


问:
${stacktrace} in log4net.config just writes stacktrace in the log file
I would like to have the stacktrace where the log function is called written to the log file.

I'm using Log4Net 1.2.10.0 and C# .NET 4.0 (I can't change any of these)

the logging is called using

```<code>private static log4net.ILog log = log4net.LogManager.GetLogger(global::System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

log.Info("Show the stacktrace here");
</code>```

The log4net.config file looks like this

```<code><?xml version="1.0" encoding="utf-8" ?>
<log4net debug="true">

  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="${ALLUSERSPROFILE}\Application1\Application1.log" />
    <appendToFile value="true" />
    <rollingStyle value="Date" />
    <datePattern value=" yyyy-MM-dd" />
    <maxSizeRollBackups value="10" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date{ISO8601}|[%thread]|%-5level|%message|%stacktrace{5}%newline" />
    </layout>
  </appender>

  <root>
    <level value="INFO" />
    <appender-ref ref="RollingLogFileAppender" />
  </root>
</log4net>
</code>```

The log file looks like this

2017-07-04 11:18:12,206|[8]|INFO
  |Show the stacktrace here|stacktrace{5}

So instead of showing the actual stack trace I get the word 'stacktrace{5}'

What am I doing wrong?

答:
You need to pass your exception instance, like below</p>

```<code>catch(Exception ex)
{
    // the form that takes two args has an exception as second, prints trace...
    _log.Error("My custom message", ex);
}
</code>```

Body:
I would like to have the stacktrace where the log function is called written to the log file.

I'm using Log4Net 1.2.10.0 and C# .NET 4.0 (I can't change any of these)

the logging is called using

private static log4net.ILog log = log4net.LogManager.GetLogger(global::System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

log.Info("Show the stacktrace here");

The log4net.config file looks like this

<?xml version="1.0" encoding="utf-8" ?>
<log4net debug="true">

  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="${ALLUSERSPROFILE}\Application1\Application1.log" />
    <appendToFile value="true" />
    <rollingStyle value="Date" />
    <datePattern value=" yyyy-MM-dd" />
    <maxSizeRollBackups value="10" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date{ISO8601}|[%thread]|%-5level|%message|%stacktrace{5}%newline" />
    </layout>
  </appender>

  <root>
    <level value="INFO" />
    <appender-ref ref="RollingLogFileAppender" />
  </root>
</log4net>

The log file looks like this

2017-07-04 11:18:12,206|[8]|INFO
  |Show the stacktrace here|stacktrace{5}

So instead of showing the actual stack trace I get the word 'stacktrace{5}'

What am I doing wrong?

Body:
You need to pass your exception instance, like below

catch(Exception ex)
{
    // the form that takes two args has an exception as second, prints trace...
    _log.Error("My custom message", ex);
}


问:
How to copy GridView data into clipboard in DevExpress Winforms
How to copy GridView data into clipboard in DevExpress Winforms</p>

答:
SelectCellAnchorRange() function is used to select cell range. In this methods set both start_column and end_column same  as below

```<code>Grid.SelectCellAnchorRange(0, columndetails, total_rows, columndetails);
</code>```

columndetails - which column you want to copy.

Body:
SelectCellAnchorRange() function is used to select cell range. In this methods set both start_column and end_column same  as below

Grid.SelectCellAnchorRange(0, columndetails, total_rows, columndetails);

columndetails - which column you want to copy.


问:
Binding to collection that exist in other collection
I have ListBox that has binding to the collection (Publishers), every publisher has a name and collection of authors in it, every author has a name. So how can I provide binding to author's name?

```<code><TextBlock Text="{Binding name}" Grid.Column="1" Grid.Row="1"></TextBlock>
<TextBlock Text="{Binding city}" Grid.Column="1" Grid.Row="0"></TextBlock>
</code>```

It is binding to a publisher's name and city.

答:
Something like this provided that the Publisher class, or whatever you call it, exposes the authors using a public collection property that has an indexer:

```<code><ListBox x:Name="listBox" ItemsSource="{Binding Publishers}" .... />

<TextBlock Text="{Binding SelectedItem.Authors[0].Name, ElementName=listBox}" Grid.Column="1" Grid.Row="0"></TextBlock>
</code>```

This will the display the name of the first author at index 0.

If you intend to display all authors of the selected publisher, you should use an ItemsControl:

```<code><ItemsControl ItemsSource="{Binding SelectedItem.Authors, ElementName=listBox}"
                      Grid.Column="1" Grid.Row="0">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"></TextBlock>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
</code>```

Body:
I have ListBox that has binding to the collection (Publishers), every publisher has a name and collection of authors in it, every author has a name. So how can I provide binding to author's name?

<TextBlock Text="{Binding name}" Grid.Column="1" Grid.Row="1"></TextBlock>
<TextBlock Text="{Binding city}" Grid.Column="1" Grid.Row="0"></TextBlock>

It is binding to a publisher's name and city.

Body:
Something like this provided that the Publisher class, or whatever you call it, exposes the authors using a public collection property that has an indexer:

<ListBox x:Name="listBox" ItemsSource="{Binding Publishers}" .... />

<TextBlock Text="{Binding SelectedItem.Authors[0].Name, ElementName=listBox}" Grid.Column="1" Grid.Row="0"></TextBlock>

This will the display the name of the first author at index 0.

If you intend to display all authors of the selected publisher, you should use an ItemsControl:

<ItemsControl ItemsSource="{Binding SelectedItem.Authors, ElementName=listBox}"
                      Grid.Column="1" Grid.Row="0">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"></TextBlock>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>


问:
Python OpenCV 3: how to use cv2.CV_COMP_HELLINGER
I am trying to compare two histograms using compareHist() function, but I can't manage to insert the right comparing method. In the documentation the options are

```<code>CV_COMP_CORREL Correlation
CV_COMP_CHISQR Chi-Square
CV_COMP_CHISQR_ALT Alternative Chi-Square
CV_COMP_INTERSECT Intersection
CV_COMP_BHATTACHARYYA Bhattacharyya distance
CV_COMP_HELLINGER Synonym for CV_COMP_BHATTACHARYYA
CV_COMP_KL_DIV Kullback-Leibler divergence
</code>```

each can be called with cv2.cv.
I am using openCv 3.2.0 and I get the error

```<code>    d = cv2.compareHist(query_hist, input_hist, cv2.CV_COMP_HELLINGER)
 AttributeError: 'module' object has no attribute 'CV_COMP_HELLINGER'
</code>```

I have tried both cv2.cv.CV_COMP_HELLINGER and cv2.CV_COMP_HELLINGER but the error is the same

答:
Use cv2.HISTCMP_HELLINGER.

The name has changed in OpenCV 3. You can find the new names in the documentation:

```<code>HISTCMP_CORREL
HISTCMP_CHISQR
HISTCMP_INTERSECT
HISTCMP_BHATTACHARYYA
HISTCMP_HELLINGER
HISTCMP_CHISQR_ALT
HISTCMP_KL_DIV
</code>```

Body:
I am trying to compare two histograms using compareHist() function, but I can't manage to insert the right comparing method. In the documentation the options are

CV_COMP_CORREL Correlation
CV_COMP_CHISQR Chi-Square
CV_COMP_CHISQR_ALT Alternative Chi-Square
CV_COMP_INTERSECT Intersection
CV_COMP_BHATTACHARYYA Bhattacharyya distance
CV_COMP_HELLINGER Synonym for CV_COMP_BHATTACHARYYA
CV_COMP_KL_DIV Kullback-Leibler divergence

each can be called with cv2.cv.
I am using openCv 3.2.0 and I get the error

    d = cv2.compareHist(query_hist, input_hist, cv2.CV_COMP_HELLINGER)
 AttributeError: 'module' object has no attribute 'CV_COMP_HELLINGER'

I have tried both cv2.cv.CV_COMP_HELLINGER and cv2.CV_COMP_HELLINGER but the error is the same

Body:
Use cv2.HISTCMP_HELLINGER.

The name has changed in OpenCV 3. You can find the new names in the documentation:

HISTCMP_CORREL
HISTCMP_CHISQR
HISTCMP_INTERSECT
HISTCMP_BHATTACHARYYA
HISTCMP_HELLINGER
HISTCMP_CHISQR_ALT
HISTCMP_KL_DIV


问:
tensorflow/C++: when (not) to call Session.Close()?
Looking at the definition of Session I see that its destructor is empty, in particular it does not call Close(). It means that we need to manually call this function before the object gets destroyed.

I was wondering why that is the case. If this function needs to be called every time before the object is destroyed, I suppose it would have been added to the destructor to avoid potential leaks. Therefore I suppose there are situations where Close() should not be called, but what are they?

Another way of asking the same question is, what problems would I face if I wrap a Session in an object that would call Close() upon destruction.

答:
The existence of Close allows for error information to be returned to the caller.

Session is an interface which has multiple implementations. In particular, when using a distributed setup (such as in grpc_session.cc) Close will attempt to clean up resources in other processes. The return value of Close provides an opportunity to be notified of and act on any failures. (FWIW, when not using a distributed setup, the implementation in direct_session.cc is typically used, and that never returns an error). This also means that Close can be expensive (e.g., blocking till the request is sent over the network and a response is received), which may not be something you'd want to wait for in some cases (e.g., when shutting down the application)

If your application won't be acting on such failures, then I don't believe writing a wrapper session that Close()s on destruction would be a problem.

Hope that helps.


问:
Checkboxes in android listview having problem
I have a listview with custom BaseAdapter and each row contains a checkbox and three textviews. I am using Layoutinflater to inflate this row from a xml file. However, everytime I check one checkbox, many other checkboxes get checked in the whole list, whereas the original checkbox I wanted to check sometimes gets checked itself, and sometimes it does not.

Every time a user selects a checkbox, I am storing that checkbox's attached unique value in a collection. Next time the getView method is called, I manually check/uncheck the checkbox before returning the view inside getView() based on if the checkbox's value was already in the collection or not. But despite doing this, it is still marking off those checkboxes, even though the checkedchangelistener for those checkboxes is not firing up. I am doubtful this due to views getting reused in getView, but dont know what is a good way to get this whole thing to work.

答:
Use the OnClickListener instead of OnCheckedChangeListener. The latter is triggered even when you update the recycled view to match the value of the object. In the following piece of code of a getView() I'm using an HashMap to store the check value of the objects (itemMap).

```<code>            boolean checked=itemMap.get(currentObject);
            if(checked!=checkBox.isChecked())
                checkBox.setChecked(checked);
            checkBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CheckBox checkBox1=(CheckBox)v;
                    if(checkBox1.isChecked()) //ckecked
                    {
                        itemMap.put(currentObject,true);
                        if(checkListener!=null)
                            checkListener.onCheck(position,convertView,parent,adapter);
                    }
                    else{ //unchecked
                        itemMap.put(currentObject,false);
                        if(checkListener!=null)
                            checkListener.onUnCheck(position,convertView,parent,adapter);
                    }
                }
            });
</code>```

checkListener is an additional listener that can be added by the user of the class.

Body:
Use the OnClickListener instead of OnCheckedChangeListener. The latter is triggered even when you update the recycled view to match the value of the object. In the following piece of code of a getView() I'm using an HashMap to store the check value of the objects (itemMap).

            boolean checked=itemMap.get(currentObject);
            if(checked!=checkBox.isChecked())
                checkBox.setChecked(checked);
            checkBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CheckBox checkBox1=(CheckBox)v;
                    if(checkBox1.isChecked()) //ckecked
                    {
                        itemMap.put(currentObject,true);
                        if(checkListener!=null)
                            checkListener.onCheck(position,convertView,parent,adapter);
                    }
                    else{ //unchecked
                        itemMap.put(currentObject,false);
                        if(checkListener!=null)
                            checkListener.onUnCheck(position,convertView,parent,adapter);
                    }
                }
            });

checkListener is an additional listener that can be added by the user of the class.


问:
Convert a list of minutes into lists of minutes, hours, days and months in python
I have a list of big numbers in minutes and I would like to convert or get from this four lists of minutes, hours, days and months. Lke for example:

```<code>Minutes
21601
30
0
90000
</code>```

Resulting lists:

```<code>Minutes  Hours  Days  Months
1        0      15    0
30       0      0     0
0        0      0     0
0        12     2     2
</code>```

Assumptions will be that a month has exactly 30 days. Also I know i showed them here as columns for simplicity but those will be lists.

Cheers,

答:
Another way of doing this would be to use datetime.timedelta.

```<code>from datetime import datetime, timedelta

d = timedelta(minutes=90000)
print("DAYS:SECONDS")
print("%d:%d" % (d.days, d.seconds))
</code>```

This gives you:

DAYS:SECONDS 62:43200

You can always convert that to which ever date format you want

Body:
I have a list of big numbers in minutes and I would like to convert or get from this four lists of minutes, hours, days and months. Lke for example:

Minutes
21601
30
0
90000

Resulting lists:

Minutes  Hours  Days  Months
1        0      15    0
30       0      0     0
0        0      0     0
0        12     2     2

Assumptions will be that a month has exactly 30 days. Also I know i showed them here as columns for simplicity but those will be lists.

Cheers,

Body:
Another way of doing this would be to use datetime.timedelta.

from datetime import datetime, timedelta

d = timedelta(minutes=90000)
print("DAYS:SECONDS")
print("%d:%d" % (d.days, d.seconds))

This gives you:

DAYS:SECONDS 62:43200

You can always convert that to which ever date format you want


问:
RelativeLayout.LayoutParams causing app crash in android
I had a recycler view for which I have a linear layout as parent and a relative layout as child. I'm changing the layout params to these dynamically. My code is working pretty well for linear layout but when it comes to relative layout it is crashing.

It is not even showing the line number which is causing crash and after so many runs I figured out the line which is causing crash. This is the recycler view adapter class.

```<code>    @Override
    public void onBindViewHolder(Holder holder, int position) {
        ChatListItem listItem = listdata.get(position);
        LinearLayout parent=holder.parent;
        RelativeLayout chatView=holder.relLayout;
        holder.time.setText(listItem.time);
        holder.message.setText(listItem.message);
        if (!listItem.sentByCustomer) {
            int match_parent= LinearLayout.LayoutParams.MATCH_PARENT;
            int wrap_content= LinearLayout.LayoutParams.WRAP_CONTENT;
            chatView.setBackground(context.getResources().getDrawable(R.drawable.incoming_normal));

            LinearLayout.LayoutParams parentParams=new LinearLayout.LayoutParams(match_parent,wrap_content);
            parentParams.setMarginStart(5);
            parent.setLayoutParams(parentParams);

            int rel_wrap_content=RelativeLayout.LayoutParams.WRAP_CONTENT;
            RelativeLayout.LayoutParams relParams=new RelativeLayout.LayoutParams(rel_wrap_content,rel_wrap_content);
            relParams.setMarginEnd(50);

            chatView.setLayoutParams(relParams); // This line is  causing crash

        }
    }

    class Holder extends RecyclerView.ViewHolder  {
        LinearLayout parent;
        RelativeLayout relLayout;
        TextView message, time;

        public Holder(View itemView) {
            super(itemView);
            parent=(LinearLayout)itemView.findViewById(R.id.chat_view_parent);
            relLayout = (RelativeLayout) itemView.findViewById(R.id.customer_chat_view);
            message = (TextView) itemView.findViewById(R.id.customer_chat_message);
            time = (TextView) itemView.findViewById(R.id.chat_time);
        }
    }
}
</code>```

Everything is fine the layout params belong to relative layout params and I'm setting them to a relative layout and I've also cross checked the xml file and that one is also a relative layout. Still the error log is saying it can't cast the linear layout params to relative layout params. Even the debugger is saying it as relative layout but why am I getting the error ? Here is the error log

```<code>07-04 15:09:13.609 5441-5441/com.motowala E/UncaughtException: java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
                                                                   at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1071)
                                                                   at android.widget.LinearLayout.onMeasure(LinearLayout.java:642)
                                                                   at android.view.View.measure(View.java:19861)
                                                                   at android.support.v7.widget.RecyclerView$LayoutManager.measureChildWithMargins(RecyclerView.java:8636)
                                                                   at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1577)
                                                                   at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1511)
                                                                   at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:570)
                                                                   at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3583)
                                                                   at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3312)
                                                                   at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3844)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                   at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                   at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                   at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                   at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                   at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                   at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                   at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                   at com.android.internal.policy.DecorView.onLayout(DecorView.java:728)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2346)
                                                                   at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2068)
                                                                   at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
                                                                   at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6343)
                                                                   at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
                                                                   at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                                                                   at android.view.Choreographer.doFrame(Choreographer.java:621)
                                                                   at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
                                                                   at android.os.Handler.handleCallback(Handler.java:751)
                                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                   at android.os.Looper.loop(Looper.java:154)
                                                                   at android.app.ActivityThread.main(ActivityThread.java:6176)
                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
07-04 15:09:13.613 5441-5502/com.motowala D/FA: Logging event (FE): _ae, Bundle[{_o=crash, _sc=CustomerChatActivity, _si=6120152536016377641, timestamp=1499161153609, fatal=1}]
07-04 15:09:13.906 5441-5441/com.motowala E/AndroidRuntime: FATAL EXCEPTION: main
                                                            Process: com.motowala, PID: 5441
                                                            java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
                                                                at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1071)
                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:642)
                                                                at android.view.View.measure(View.java:19861)
                                                                at android.support.v7.widget.RecyclerView$LayoutManager.measureChildWithMargins(RecyclerView.java:8636)
                                                                at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1577)
                                                                at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1511)
                                                                at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:570)
                                                                at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3583)
                                                                at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3312)
                                                                at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3844)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                at com.android.internal.policy.DecorView.onLayout(DecorView.java:728)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2346)
                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2068)
                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6343)
                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                                                                at android.view.Choreographer.doFrame(Choreographer.java:621)
                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                at android.os.Looper.loop(Looper.java:154)
                                                                at android.app.ActivityThread.main(ActivityThread.java:6176)
                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
</code>```

Thanks a lot in advance....

答:
```<code>java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
</code>```

you're referencing linear layout but using relative layout, show the xml file you're using or check linear layout

Body:
I had a recycler view for which I have a linear layout as parent and a relative layout as child. I'm changing the layout params to these dynamically. My code is working pretty well for linear layout but when it comes to relative layout it is crashing.

It is not even showing the line number which is causing crash and after so many runs I figured out the line which is causing crash. This is the recycler view adapter class.

    @Override
    public void onBindViewHolder(Holder holder, int position) {
        ChatListItem listItem = listdata.get(position);
        LinearLayout parent=holder.parent;
        RelativeLayout chatView=holder.relLayout;
        holder.time.setText(listItem.time);
        holder.message.setText(listItem.message);
        if (!listItem.sentByCustomer) {
            int match_parent= LinearLayout.LayoutParams.MATCH_PARENT;
            int wrap_content= LinearLayout.LayoutParams.WRAP_CONTENT;
            chatView.setBackground(context.getResources().getDrawable(R.drawable.incoming_normal));

            LinearLayout.LayoutParams parentParams=new LinearLayout.LayoutParams(match_parent,wrap_content);
            parentParams.setMarginStart(5);
            parent.setLayoutParams(parentParams);

            int rel_wrap_content=RelativeLayout.LayoutParams.WRAP_CONTENT;
            RelativeLayout.LayoutParams relParams=new RelativeLayout.LayoutParams(rel_wrap_content,rel_wrap_content);
            relParams.setMarginEnd(50);

            chatView.setLayoutParams(relParams); // This line is  causing crash

        }
    }

    class Holder extends RecyclerView.ViewHolder  {
        LinearLayout parent;
        RelativeLayout relLayout;
        TextView message, time;

        public Holder(View itemView) {
            super(itemView);
            parent=(LinearLayout)itemView.findViewById(R.id.chat_view_parent);
            relLayout = (RelativeLayout) itemView.findViewById(R.id.customer_chat_view);
            message = (TextView) itemView.findViewById(R.id.customer_chat_message);
            time = (TextView) itemView.findViewById(R.id.chat_time);
        }
    }
}

Everything is fine the layout params belong to relative layout params and I'm setting them to a relative layout and I've also cross checked the xml file and that one is also a relative layout. Still the error log is saying it can't cast the linear layout params to relative layout params. Even the debugger is saying it as relative layout but why am I getting the error ? Here is the error log

07-04 15:09:13.609 5441-5441/com.motowala E/UncaughtException: java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
                                                                   at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1071)
                                                                   at android.widget.LinearLayout.onMeasure(LinearLayout.java:642)
                                                                   at android.view.View.measure(View.java:19861)
                                                                   at android.support.v7.widget.RecyclerView$LayoutManager.measureChildWithMargins(RecyclerView.java:8636)
                                                                   at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1577)
                                                                   at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1511)
                                                                   at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:570)
                                                                   at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3583)
                                                                   at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3312)
                                                                   at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3844)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                   at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                   at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                   at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                   at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                   at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                   at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                   at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                   at com.android.internal.policy.DecorView.onLayout(DecorView.java:728)
                                                                   at android.view.View.layout(View.java:17641)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                   at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2346)
                                                                   at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2068)
                                                                   at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
                                                                   at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6343)
                                                                   at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
                                                                   at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                                                                   at android.view.Choreographer.doFrame(Choreographer.java:621)
                                                                   at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
                                                                   at android.os.Handler.handleCallback(Handler.java:751)
                                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                   at android.os.Looper.loop(Looper.java:154)
                                                                   at android.app.ActivityThread.main(ActivityThread.java:6176)
                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
07-04 15:09:13.613 5441-5502/com.motowala D/FA: Logging event (FE): _ae, Bundle[{_o=crash, _sc=CustomerChatActivity, _si=6120152536016377641, timestamp=1499161153609, fatal=1}]
07-04 15:09:13.906 5441-5441/com.motowala E/AndroidRuntime: FATAL EXCEPTION: main
                                                            Process: com.motowala, PID: 5441
                                                            java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
                                                                at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1071)
                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:642)
                                                                at android.view.View.measure(View.java:19861)
                                                                at android.support.v7.widget.RecyclerView$LayoutManager.measureChildWithMargins(RecyclerView.java:8636)
                                                                at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1577)
                                                                at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1511)
                                                                at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:570)
                                                                at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3583)
                                                                at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3312)
                                                                at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3844)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
                                                                at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
                                                                at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                at com.android.internal.policy.DecorView.onLayout(DecorView.java:728)
                                                                at android.view.View.layout(View.java:17641)
                                                                at android.view.ViewGroup.layout(ViewGroup.java:5575)
                                                                at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2346)
                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2068)
                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6343)
                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                                                                at android.view.Choreographer.doFrame(Choreographer.java:621)
                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                at android.os.Looper.loop(Looper.java:154)
                                                                at android.app.ActivityThread.main(ActivityThread.java:6176)
                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)

Thanks a lot in advance....

Body:
java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams

you're referencing linear layout but using relative layout, show the xml file you're using or check linear layout


问:
Angular Component doesn't render
Here's my code:

```<code>import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['../assets/css/app.component.css']
})
export class MainVisualComponent {
  main_visual_img:string = "";
  main_visual_desc:string = "";
  main_visual_title:string = "";
  constructor(main_visual_img:string, main_visual_desc:string, main_visual_title:string){
    this.main_visual_img = main_visual_img;
    this.main_visual_desc = main_visual_desc;
    this.main_visual_title = main_visual_title;
  }
}
</code>```

HTML:

```<code><section style="text-align:center">
  <div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
    <visual-item></visual-item>
    <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
    </a>
    <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
    </a>
  </div>
</section>
</code>```

答:
It was just component <-> template binding problem.

Doesn't work:

```<code><aria-selected="{{first}}" aria-hidden="{{last}}" aria-controls="SliderItem0{{i+1}}" data-target="#carousel-example-generic" data-slide-to="{{i}}">
</code>```

Works:

```<code><[attr.aria-selected]="first" [attr.aria-controls]="'SliderItem0'+(i+1)"  data-target="#carousel-example-generic" [attr.data-slide-to]="i">
</code>```

Title: Angular Component doesn't render

Body:
Here's my code:

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['../assets/css/app.component.css']
})
export class MainVisualComponent {
  main_visual_img:string = "";
  main_visual_desc:string = "";
  main_visual_title:string = "";
  constructor(main_visual_img:string, main_visual_desc:string, main_visual_title:string){
    this.main_visual_img = main_visual_img;
    this.main_visual_desc = main_visual_desc;
    this.main_visual_title = main_visual_title;
  }
}

HTML:

    <visual-item></visual-item>

Body:
It was just component <-> template binding problem.

Doesn't work:

<aria-selected="{{first}}" aria-hidden="{{last}}" aria-controls="SliderItem0{{i+1}}" data-target="#carousel-example-generic" data-slide-to="{{i}}">

Works:

<[attr.aria-selected]="first" [attr.aria-controls]="'SliderItem0'+(i+1)"  data-target="#carousel-example-generic" [attr.data-slide-to]="i">


问:
Python reading mail accounts from txt file
Python...

I have a file of e-mail addresses and i need to create a script to import all these addresses as accounts, so there is some text manipulation going on, and i need to learn more python.

the file is in the form of

user1@domain1.co.uk

user1@domain2.com

user2@domain4.com

user3@domain4.com

This is basically a user name and a domain name that i need to create an account name (same as user) and domain, and e-mail address, with some other date/file path variables into an import file.  once the user and domain have been assigned to variables they can be printed to a file with some other data to create and import list/script.  Then use the import file to create a list of accounts on a new mail server, without going through all 128k of them one by one.
So.  How do i read each line of the file (128,000 entries) one at a time, to put each user name into a variable followed by corresponding domain into an array / tuple / list/ dict ?  to then add the date and some other file path stuff to build an account name with email address from the two variables and append the output to a new file, but doing this per-line before looping onto the next line and repeating??

somthing along the lines of

make output file

read file line 1 and put the user and domain into variables

print user print domain print (otherstuff) print user@domain

append each output loop to same new file (not original)

loop to next line of file and repeat

continue to EOF (128k lines later)

to make one big file to import mail accounts and details for each,

(possibly split output file to smaller chunks for import stability 100 entries per-file?)

so far i have

```<code>#!/usr/bin/python
import time;

input = open('/home/adam/Downloads/mailaccounts.txt', 'r')
fileoutput = open('/tmp/domaintest.txt', 'a' 'w')
sql1 = "INSERT INTO mailbox (username, password, name, storagebasedirectory, maildir, quota, domain, active)"
password = "88888888"
storage_base_directory = '/var/vmail/vmail1'
localtime = time.localtime(time.time())
localtime = localtime[0], ".", localtime[1], ".", localtime[2], ".", localtime[3], ".", localtime[4], ".", localtime[5]
localtime = ''.join(map(str, localtime))
for line in input:
    email = line
    user = line.split("@")[0]
    domain = line.split("@")[1]
    fileoutput.write(domain)
</code>```

now the out file has characters

```<code>^@d^@o^@m^@a^@i^@n^@1^@.^@c^@o.^@u^@k^@^M^@
</code>```

that do not appear with the print command when testing from command line

```<code>domain1.co.uk
</code>```

anyone any ideas?

答:
try replacing 'a' 'w' option with 'a+' as following

```<code>fileoutput = open('/tmp/domaintest.txt', 'a+')
</code>```

after this your script is working good and getting

```<code>domain1.co.uk
domain2.com
domain4.com
domain4.com
</code>```

as output in output file

Body:
Python...

I have a file of e-mail addresses and i need to create a script to import all these addresses as accounts, so there is some text manipulation going on, and i need to learn more python.

the file is in the form of

user1@domain1.co.uk

user1@domain2.com

user2@domain4.com

user3@domain4.com

This is basically a user name and a domain name that i need to create an account name (same as user) and domain, and e-mail address, with some other date/file path variables into an import file.  once the user and domain have been assigned to variables they can be printed to a file with some other data to create and import list/script.  Then use the import file to create a list of accounts on a new mail server, without going through all 128k of them one by one.
So.  How do i read each line of the file (128,000 entries) one at a time, to put each user name into a variable followed by corresponding domain into an array / tuple / list/ dict ?  to then add the date and some other file path stuff to build an account name with email address from the two variables and append the output to a new file, but doing this per-line before looping onto the next line and repeating??

somthing along the lines of

make output file

read file line 1 and put the user and domain into variables

print user print domain print (otherstuff) print user@domain

append each output loop to same new file (not original)

loop to next line of file and repeat

continue to EOF (128k lines later)

to make one big file to import mail accounts and details for each,

(possibly split output file to smaller chunks for import stability 100 entries per-file?)

so far i have

#!/usr/bin/python
import time;

input = open('/home/adam/Downloads/mailaccounts.txt', 'r')
fileoutput = open('/tmp/domaintest.txt', 'a' 'w')
sql1 = "INSERT INTO mailbox (username, password, name, storagebasedirectory, maildir, quota, domain, active)"
password = "88888888"
storage_base_directory = '/var/vmail/vmail1'
localtime = time.localtime(time.time())
localtime = localtime[0], ".", localtime[1], ".", localtime[2], ".", localtime[3], ".", localtime[4], ".", localtime[5]
localtime = ''.join(map(str, localtime))
for line in input:
    email = line
    user = line.split("@")[0]
    domain = line.split("@")[1]
    fileoutput.write(domain)

now the out file has characters

^@d^@o^@m^@a^@i^@n^@1^@.^@c^@o.^@u^@k^@^M^@

that do not appear with the print command when testing from command line

domain1.co.uk

anyone any ideas?

Body:
try replacing 'a' 'w' option with 'a+' as following

fileoutput = open('/tmp/domaintest.txt', 'a+')

after this your script is working good and getting

domain1.co.uk
domain2.com
domain4.com
domain4.com

as output in output file


问:
Scala extends Java Interface with type
I am curious how one would implement a Java Interface in Scala with the following signature;

```<code>public interface MyService<T> { ... }
</code>```

Thanks!!

答:
```<code>object ServiceImplementation extends MyService[String] { ... }
</code>```

would be an example.

Title: Scala extends Java Interface with type

Body:
I am curious how one would implement a Java Interface in Scala with the following signature;

public interface MyService<T> { ... }

Thanks!!

Body:
object ServiceImplementation extends MyService[String] { ... }

would be an example.


问:
To drop an index with psycopg2 takes effect before or after commit?
I'm doing a python script to insert several data into a postgresql database.

Following the postgresql documentation in order to speed up the load process my script has this sort of structure

Connect to the database and create a cursor

Drop all the indexes

Load all the data using the 'copy' command

Recreate back all the indexes

Commit and close of the cursor and connection (only commit in the whole script)

So my question is: Is dropping the indexes before the commit, taking any effect in terms of speeding up the loading, or not ?

答:
commit just commits any ongoing transaction in progress to your database.

What you actually are asking if whether dropping indexes and then copying within the same transaction will provide the same speedup as first dropping indexes in one transaction and then copying data in a new transaction.

The direct quote from docs says that:

If you are adding large amounts of data to an existing table, it might be a win to drop the indexes, load the table, and then recreate the indexes. Of course, the database performance for other users might suffer during the time the indexes are missing. One should also think twice before dropping a unique index, since the error checking afforded by the unique constraint will be lost while the index is missing.

The bolded part indirectly tells that you should commit after dropping the indexes, as dropping indexes without committing (completing the transaction) should not have any impact on other users of the database.

So the solution should be something along these lines:

drop your indexes, commit, copy the data, create new indexes and commit again.

Note that as you split your transaction into two transactions, you lose atomicity. I.e. it's possible that your indexes are dropped, but no data is copied (if power or network for example is lost during the copying transaction) and the indexes would never be recreated.

ContentLicense: CC BY-SA 4.0


问:
What is the opposite command to "git add"?
After merging two git branches, if conflicts exist you can use the command git add * to resolve which accepts the local version of the code as most recent. How can I do the opposite of this command?

To give some background, I have two branches (call them master and develop for sake of ease) and for some reason git decided to remove some files from my develop branch (git status says deleted by us: in front of these files). I've tried to merge master back into develop (because these files are the only differences), now have conflicts and can't use git -add to resolve because I do not want loose these files.

答:
You can use checkout and re-add the file:

```<code>git checkout develop # go to develop branch first
git checkout master -- fileYouWant # getting the file from master
git add fileYouWant
</code>```

Body:
You can use checkout and re-add the file:

git checkout develop # go to develop branch first
git checkout master -- fileYouWant # getting the file from master
git add fileYouWant


答:
You can use the below method</p>

```<code>def format (minutes):
    year = (int) (minutes/(12*30*24*60))
    month = ((int) (minutes/(30*24*60)))%12
    day = ((int) (minutes/(24*60)))%30
    hour = ((int) (minutes/(60)))%24
    min = ((int) (minutes))%60
    return [min,hour,day,month,year]

lis = [21601,30,0,90000]
ans = list(map(lambda x: format(x) , lis))
print(ans)
</code>```

Title: Convert a list of minutes into lists of minutes, hours, days and months in python

Body:
You can use the below method

def format (minutes):
    year = (int) (minutes/(12*30*24*60))
    month = ((int) (minutes/(30*24*60)))%12
    day = ((int) (minutes/(24*60)))%30
    hour = ((int) (minutes/(60)))%24
    min = ((int) (minutes))%60
    return [min,hour,day,month,year]

lis = [21601,30,0,90000]
ans = list(map(lambda x: format(x) , lis))
print(ans)


问:
Graph incidence list implementation
I'm considering graph data structure implementations and am looking at the "incidence list" representation. There is a brief description of it here:

Incidence list

So each vertex in the graph stores a list of those edges upon which it is incident.

Given that my graph is a directed graph, I'm not very clear from this description on a couple of points:

Does the graph itself also store a list of all edges?

Do vertices only store outgoing edges, or incoming and outgoing?

If both, are they in separate lists?

I'm quite familiar with the other graph representations (adjacency list, adjacency matrix, edge list, incidence matrix), so this isn't a question about graph implementations in general, just this particular one.

Any pointers would be much appreciated.

答:
I know I'm perhaps raising an old question from the dead, but I felt it appropriate to comment.

You can make an incidence list graph structure, and you can also tweak it for digraphs.

Consider a LinkedList<Vertex> object and a LinkedList<Edge> object. This would let you iterate over all edges and all vertices, but contains no information about how everything is connected.

Say we add, then, several LinkedList<Connection> objects. In fact, one for each Vertex. A Connection is simply where an Edge and a Vertex Meet. Thus an Edge will have two Connection objects (For an undirected graph), and a Vertex will have one LinkedList<Connection> object, representing connections to every Edge that is connected to it. This is, in essence, an incidence list.

You can modify this to represent a digraph if you delete some of those Connection objects. More specifically, you'll have to choose where to not have those references. You might choose to delete a Connectionfrom the associated LinkedList<Connection> if you don't want to be able to see an Edge from a Vertex (for the example above, N2 would have an empty LinkedList<Connection>). You might instead choose to make the references optional on the Edge(For the example above, E1 would have one Connection pointing at N2 and one Connection null, allowing traversal from  E1 to N2, but not back onto N1. Your choice of how to implement this would be entirely up to you. One is more intuitive - Edges are directed, so removing the connections on Edges to dictate which way they go seems logical. The other might seem a bit more complex at first, but will stop you needlessly hopping onto edges that lead nowhere when doing breadth first and depth first searches.

In point form:

In my implementations of a incidence list, I have. Do you need to for your implementation?

Strictly speaking, you could get by storing only outgoing edges. However, backtracking algorithms might benefit from being able to backtrack along references they traveled. You can implement around this, of course, with some sort of history, so it's probably not much of a consideration.

If you do both, you would probably need some way to differentiate whether it's incoming or outgoing. Whether that's by having two LinkedList<Connection> objects on the Vertex, or by having a boolean pointingToVertex primitive on Connection, or whatever. Maybe your Edge would be directed, and undirected edges would be made of two edges pointing opposite ways. Considerations to be made depending on the needs of your structure.

Title: Graph incidence list implementation


问:
Fortran accepting string(?) from C
I feel like this should be an easy question, but I can't get it to work.  I have some Fortran code that takes an input like:

```<code>      SUBROUTINE TRACE(X,Y,NAME,XX,YY)
      EXTERNAL NAME
      CALL NAME(X,Y,XX,YY)
</code>```

and I'm trying to pass in a name from C++ in the form:

```<code>float x,y,xx,yy;
char * name="IGRF";
trace_(&x,&y,name,&xx,&yy);
</code>```

It compiles, but I always get segfaults when I try to call the NAME subroutine. A subroutine called IGRF is defined in the file, and I can call the IGRF subroutine directly from C++, but need this TRACE routine. When running in gdb, it says the NAME variable comes through as a pointer to void.

I've tried passing NAME, &NAME, &NAME[0], a char NAME[4] that's stripped of its \0 to perfectly fit the name, and they all come back showing the same void pointer. Does anybody know how to get a function name from C++ into that EXTERNAL variable in Fortran?

Thank you

答:
I got it working with CMake as well.

CMakeLists.txt:

```<code>cmake_minimum_required(VERSION 3.5)
project(CppFortran C CXX Fortran)

add_executable(CppFortran
    froutine.f90
    main.cpp
    )
</code>```

main.cpp

```<code>#include <iostream>

extern "C" {
int getString(char *file_name);
}

int main() {
    int l;
    char *name = (char*)"IGRF";

    l = getString(name);
    std::cout << "In C++:"<< std::endl;
    std::cout << "length: " << l << std::endl;

    return 0;
}
</code>```

froutine.f90

```<code>integer(kind=c_int) function getString(instr) bind(C,name='getString')
    use, intrinsic :: iso_c_binding
    character(kind=c_char), dimension(*), intent(IN) :: instr
    integer :: len
    integer :: i

    len=0
    do
        if (instr(len+1) == C_NULL_CHAR) exit
        len = len + 1
    end do

    print *, 'In Fortran:'
    print *, 'Got string: ', (instr(i),i=1,len)
    getstring = len
end function getString
</code>```

Console output:

```<code> In Fortran:
 Got string: IGRF
In C++:
length: 4
</code>```

Title: Fortran accepting string(?) from C

Body:
I feel like this should be an easy question, but I can't get it to work.  I have some Fortran code that takes an input like:

      SUBROUTINE TRACE(X,Y,NAME,XX,YY)
      EXTERNAL NAME
      CALL NAME(X,Y,XX,YY)

and I'm trying to pass in a name from C++ in the form:

float x,y,xx,yy;
char * name="IGRF";
trace_(&x,&y,name,&xx,&yy);

It compiles, but I always get segfaults when I try to call the NAME subroutine. A subroutine called IGRF is defined in the file, and I can call the IGRF subroutine directly from C++, but need this TRACE routine. When running in gdb, it says the NAME variable comes through as a pointer to void.

I've tried passing NAME, &NAME, &NAME[0], a char NAME[4] that's stripped of its \0 to perfectly fit the name, and they all come back showing the same void pointer. Does anybody know how to get a function name from C++ into that EXTERNAL variable in Fortran?

Thank you

Body:
I got it working with CMake as well.

CMakeLists.txt:

cmake_minimum_required(VERSION 3.5)
project(CppFortran C CXX Fortran)

add_executable(CppFortran
    froutine.f90
    main.cpp
    )

main.cpp

#include <iostream>

extern "C" {
int getString(char *file_name);
}

int main() {
    int l;
    char *name = (char*)"IGRF";

    l = getString(name);
    std::cout << "In C++:"<< std::endl;
    std::cout << "length: " << l << std::endl;

    return 0;
}

froutine.f90

integer(kind=c_int) function getString(instr) bind(C,name='getString')
    use, intrinsic :: iso_c_binding
    character(kind=c_char), dimension(*), intent(IN) :: instr
    integer :: len
    integer :: i

    len=0
    do
        if (instr(len+1) == C_NULL_CHAR) exit
        len = len + 1
    end do

    print *, 'In Fortran:'
    print *, 'Got string: ', (instr(i),i=1,len)
    getstring = len
end function getString

Console output:

 In Fortran:
 Got string: IGRF
In C++:
length: 4


问:
How to form shuffled batches in Python?
I have a list of 100k entries and would like to split them into 10k shuffled batches. How to do this?

I found a function shuffle in sklearn, and it has a parameter of n_samples. But I don't see any guarantee, that this batch will cover all set.

I would like to take random batches from the entire set but doesn't repeat them until all samples taken. Is this possible?

答:
Do you mean something like:</p>

```<code>from random import shuffle
def batches(entries):
    shuffle(entries)
    for i in range(0, len(entries), 10000):
        yield entries[i:i+10000]
</code>```

Title: How to form shuffled batches in Python?

Body:
Do you mean something like:

from random import shuffle
def batches(entries):
    shuffle(entries)
    for i in range(0, len(entries), 10000):
        yield entries[i:i+10000]


问:
Use local json file with Cordova/ionic/Angular. Works in browser, but not on device?
I'm attempting to use a JSON object living in a data.json file to be the dataset for a quick prototype I'm working on. This lives in a my_project/www/data/ directory. I have an Angular service that goes and grabs the data within this file using $http, does some stuff to it, and then it's used throughout my app.

I'm using Cordova and Ionic. When using ionic serve on my computer, everything looks perfect in the browser. However, when using ionic view (http://view.ionic.io/) and opening the app on my iPad, I see a:

```<code>{"data":null,"status":0,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"../data/items.json","headers":{"Accept":"application/json,test/plain,*/*}},"statusText":""}
</code>```

for a response. I would think that if it were a relative URL issue, that it would also not work in the browser, but that is not the case.

Here's what I'm doing:

config.xml has this line:

```<code><access origin="*" subdomains="true"/>
</code>```

My service that preforms the simple request is doing:

```<code>return $http.get("../data/data.json").then(function (response) {
    return response.data;
});
</code>```

And finally, in my controller, I ask for the service to preform the request:

```<code> myService.goGetData().then(onComplete, onError);
</code>```

In my browser, onComplete() is invoked and on the iPad, onError() is invoked.
Any guidance?

答:
It is possible to access local resources using $http.get.

If the json file is located in www/js/data.json. You can access using

```<code>js/data.json
</code>```

Do not use ../js/data.json. Using that only works in the local browser. Use js/data.json will work on both local browser and iOS device for Cordova.

Body:
I'm attempting to use a JSON object living in a data.json file to be the dataset for a quick prototype I'm working on. This lives in a my_project/www/data/ directory. I have an Angular service that goes and grabs the data within this file using $http, does some stuff to it, and then it's used throughout my app.

I'm using Cordova and Ionic. When using ionic serve on my computer, everything looks perfect in the browser. However, when using ionic view (http://view.ionic.io/) and opening the app on my iPad, I see a:

{"data":null,"status":0,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"../data/items.json","headers":{"Accept":"application/json,test/plain,*/*}},"statusText":""}

for a response. I would think that if it were a relative URL issue, that it would also not work in the browser, but that is not the case.

Here's what I'm doing:

config.xml has this line:

<access origin="*" subdomains="true"/>

My service that preforms the simple request is doing:

return $http.get("../data/data.json").then(function (response) {
    return response.data;
});

And finally, in my controller, I ask for the service to preform the request:

 myService.goGetData().then(onComplete, onError);

In my browser, onComplete() is invoked and on the iPad, onError() is invoked.
Any guidance?

Body:
It is possible to access local resources using $http.get.

If the json file is located in www/js/data.json. You can access using

js/data.json

Do not use ../js/data.json. Using that only works in the local browser. Use js/data.json will work on both local browser and iOS device for Cordova.


问:
Python/Django - No module named
I try to work with a class from Django views.

sync.py

```<code>import requests

class Sync:

    def do():
        r = requests.post('http://192.168.1.7/api/report_x')
        print(r.response)
</code>```

views.py

```<code>import sync

def index(request):
    s = Sync()
    s.do()
    return HttpResponse("Hello, this is index")
</code>```

When I access index from the browser I get:

global name 'Sync' is not defined

What am I doing wrong?

答:
If you're writing Python, you should actually write Python. Python is not Java.

You should not be using a class here at all. Define a standalone function called sync, import it with from sync import sync, and just call it. No need for an instance of something that has no state.

Title: Python/Django - No module named

Body:
I try to work with a class from Django views.

sync.py

import requests

class Sync:

    def do():
        r = requests.post('http://192.168.1.7/api/report_x')
        print(r.response)

views.py

import sync

def index(request):
    s = Sync()
    s.do()
    return HttpResponse("Hello, this is index")

When I access index from the browser I get:

global name 'Sync' is not defined

What am I doing wrong?


问:
ImageView rounded corners
I wanted image to have rounded corners. I implement this xml code and use this in my image view. but image overlap the shape. I am downloading the image through async task.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
 <shape xmlns:android="http://schemas.android.com/apk/res/android"
 android:shape="rectangle" >
 <corners android:radius="20dip" />
</shape>

<ImageView
    android:id="@+id/trVouchersImage"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:layout_marginLeft="8dp"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:layout_alignParentLeft="true"
    android:background="@drawable/ash_arrow"
 />
</code>```

答:
Your MainActivity.java is like this:

```<code>LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
ImageView iv = (ImageView) findViewById(R.id.iv);
</code>```

You should to first get your image from Resource as Bitmap or Drawable.

If get as Bitmap:

```<code>Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ash_arrow);
bm = new Newreza().setEffect(bm, 0.2f, ((ColorDrawable) ll.getBackground).getColor);
iv.setImageBitmap(bm);
</code>```

Or if get as Drawable:

```<code>Drawable d = getResources().getDrawable(R.drawable.ash_arrow);
d = new Newreza().setEffect(d, 0.2f, ((ColorDrawable) ll.getBackground).getColor);
iv.setImageDrawable(d);
</code>```

Then create new file as Newreza.java near MainActivity.java, and copy bottom codes in Newreza.java:

```<code>package your.package.name;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
//Telegram:@newreza
//mail:newreza7@gmail.com
public class Newreza{
    int a,x,y;
    float bmr;
    public Bitmap setEffect(Bitmap bm,float radius,int color){
        bm=bm.copy(Bitmap.Config.ARGB_8888,true);
        bmr=radius*bm.getWidth();
        for(y=0;y<bmr;y++){
            a=(int)(bmr-Math.sqrt(y*(2*bmr-y)));
            for(x=0;x<a;x++){
                bm.setPixel(x,y,color);
            }
        }
        for(y=0;y<bmr;y++){
            a=(int)(bm.getWidth()-bmr+Math.sqrt(y*(2*bmr-y)));
            for(x=a;x<bm.getWidth();x++){
                bm.setPixel(x,y,color);
            }
        }
        for(y=(int)(bm.getHeight()-bmr);y<bm.getHeight();y++){
            a=(int)(bm.getWidth()-bmr+Math.sqrt(Math.pow(bmr,2)-Math.pow(bmr+y-bm.getHeight(),2)));
            for(x=a;x<bm.getWidth();x++){
                bm.setPixel(x,y,color);
            }
        }
        for(y=(int)(bm.getHeight()-bmr);y<bm.getHeight();y++){
            a=(int)(bmr-Math.sqrt(Math.pow(bmr,2)-Math.pow(bmr+y-bm.getHeight(),2)));
            for(x=0;x<a;x++){
                bm.setPixel(x,y,color);
            }
        }
        return bm;
    }
    public Drawable setEffect(Drawable d,float radius,int color){
        return new BitmapDrawable(Resources.getSystem(),setEffect(((BitmapDrawable)d).getBitmap(),radius,color));
    }
}
</code>```

Just notice that replace your package name with first line in the code.

It %100 works, because is written in details :)

Title: ImageView rounded corners

Body:
I wanted image to have rounded corners. I implement this xml code and use this in my image view. but image overlap the shape. I am downloading the image through async task.

<?xml version="1.0" encoding="utf-8"?>
 <shape xmlns:android="http://schemas.android.com/apk/res/android"
 android:shape="rectangle" >
 <corners android:radius="20dip" />
</shape>

<ImageView
    android:id="@+id/trVouchersImage"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:layout_marginLeft="8dp"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:layout_alignParentLeft="true"
    android:background="@drawable/ash_arrow"
 />

Body:
Your MainActivity.java is like this:

LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
ImageView iv = (ImageView) findViewById(R.id.iv);

You should to first get your image from Resource as Bitmap or Drawable.

If get as Bitmap:

Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ash_arrow);
bm = new Newreza().setEffect(bm, 0.2f, ((ColorDrawable) ll.getBackground).getColor);
iv.setImageBitmap(bm);

Or if get as Drawable:

Drawable d = getResources().getDrawable(R.drawable.ash_arrow);
d = new Newreza().setEffect(d, 0.2f, ((ColorDrawable) ll.getBackground).getColor);
iv.setImageDrawable(d);

Then create new file as Newreza.java near MainActivity.java, and copy bottom codes in Newreza.java:

package your.package.name;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
//Telegram:@newreza
//mail:newreza7@gmail.com
public class Newreza{
    int a,x,y;
    float bmr;
    public Bitmap setEffect(Bitmap bm,float radius,int color){
        bm=bm.copy(Bitmap.Config.ARGB_8888,true);
        bmr=radius*bm.getWidth();
        for(y=0;y<bmr;y++){
            a=(int)(bmr-Math.sqrt(y*(2*bmr-y)));
            for(x=0;x<a;x++){
                bm.setPixel(x,y,color);
            }
        }
        for(y=0;y<bmr;y++){
            a=(int)(bm.getWidth()-bmr+Math.sqrt(y*(2*bmr-y)));
            for(x=a;x<bm.getWidth();x++){
                bm.setPixel(x,y,color);
            }
        }
        for(y=(int)(bm.getHeight()-bmr);y<bm.getHeight();y++){
            a=(int)(bm.getWidth()-bmr+Math.sqrt(Math.pow(bmr,2)-Math.pow(bmr+y-bm.getHeight(),2)));
            for(x=a;x<bm.getWidth();x++){
                bm.setPixel(x,y,color);
            }
        }
        for(y=(int)(bm.getHeight()-bmr);y<bm.getHeight();y++){
            a=(int)(bmr-Math.sqrt(Math.pow(bmr,2)-Math.pow(bmr+y-bm.getHeight(),2)));
            for(x=0;x<a;x++){
                bm.setPixel(x,y,color);
            }
        }
        return bm;
    }
    public Drawable setEffect(Drawable d,float radius,int color){
        return new BitmapDrawable(Resources.getSystem(),setEffect(((BitmapDrawable)d).getBitmap(),radius,color));
    }
}

Just notice that replace your package name with first line in the code.

It %100 works, because is written in details :)


问:
SearchView in Action bar with customize search button
In the menu, I have search view. when I clicked search in menu search view should expand with customized search button.like below image currently it is opening like normal search

I want to change the default submit button with custom button

```<code> SearchManager searchManager =
                (SearchManager) getSystemService(Context.SEARCH_SERVICE);

        searchView =
                (SearchView) menu.findItem(R.id.action_search).getActionView();
        EditText searchEditText = (EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
 searchView.setSubmitButtonEnabled(true);
        searchView.setSearchableInfo(
                searchManager.getSearchableInfo(getComponentName()));
</code>```

Any help much appreciated.

答:
```<code> ImageView b = (ImageView) searchView.findViewById(android.support.v7.appcompat.R.id.search_go_btn);
    b.setImageResource(R.drawable.your_button_drawable);
</code>```

try this one to change default search submit button

Body:
In the menu, I have search view. when I clicked search in menu search view should expand with customized search button.like below image currently it is opening like normal search

I want to change the default submit button with custom button

 SearchManager searchManager =
                (SearchManager) getSystemService(Context.SEARCH_SERVICE);

        searchView =
                (SearchView) menu.findItem(R.id.action_search).getActionView();
        EditText searchEditText = (EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
 searchView.setSubmitButtonEnabled(true);
        searchView.setSearchableInfo(
                searchManager.getSearchableInfo(getComponentName()));

Any help much appreciated.

Body:
 ImageView b = (ImageView) searchView.findViewById(android.support.v7.appcompat.R.id.search_go_btn);
    b.setImageResource(R.drawable.your_button_drawable);

try this one to change default search submit button