问:
duktape, modify variable argument in native C code
I'm trying to modify a variable passed in an argument in a native function like this:

```<code>var MyVar = 'foo';
myNativeFunc(MyVar);
</code>```

and inside my native, I can read the content of MyVar, with :

```<code>std::string(duk_to_string(ctx, 0));
</code>```

but, I need to modify the value of this variable inside native function.
what is the best way for does it? (I can't use the return statement) thanks.

答:
That's not possible as it would implement pass-by-reference (which is not supported in JS). Read also the answer to the question Pass Variables by Reference in Javascript

So, either pass in an object reference and change the object properties or use a return value.

Body:
I'm trying to modify a variable passed in an argument in a native function like this:

var MyVar = 'foo';
myNativeFunc(MyVar);

and inside my native, I can read the content of MyVar, with :

std::string(duk_to_string(ctx, 0));

but, I need to modify the value of this variable inside native function.
what is the best way for does it? (I can't use the return statement) thanks.


来源: stackexchange

问:
Label Not In List and KeyError
I'm trying to get the value of a specific cell.

```<code>  main_id   name  code
  0    1345  Jones    32
  1    1543   Jack    62
  2    9874   Buck    86
  3    2456   Slim    94
</code>```

I want the cell that says code=94, as I already know the main_id but nothing else.

```<code>raw_data = {'main_id': ['1345', '1543', '9874', '2456'],
        'name': ['Jones', 'Jack', 'Buck', 'Slim'],
        'code': [32, 62, 86, 94]}

    df=pd.DataFrame(raw_data, columns = ['main_id', 'name', 'code'])

    v=df.loc[str(df['main_id']) == str(2456)]['code'].values
    print(df.loc['name'])
</code>```

The print(df.loc['name']) claims the label is not in index

And the v=df.loc[str(df['main_id']) == str(2456)]['code'].values says 'KeyError False'

答:
Alternative solution:</p>

```<code>In [76]: df.set_index('main_id').at['2456','code']
Out[76]: 94
</code>```

ContentLicense: CC BY-SA 4.0

Title: Label Not In List and KeyError

Body:
I'm trying to get the value of a specific cell.

  main_id   name  code
  0    1345  Jones    32
  1    1543   Jack    62
  2    9874   Buck    86
  3    2456   Slim    94

I want the cell that says code=94, as I already know the main_id but nothing else.

raw_data = {'main_id': ['1345', '1543', '9874', '2456'],
        'name': ['Jones', 'Jack', 'Buck', 'Slim'],
        'code': [32, 62, 86, 94]}

    df=pd.DataFrame(raw_data, columns = ['main_id', 'name', 'code'])

    v=df.loc[str(df['main_id']) == str(2456)]['code'].values
    print(df.loc['name'])

The print(df.loc['name']) claims the label is not in index

And the v=df.loc[str(df['main_id']) == str(2456)]['code'].values says 'KeyError False'

Body:
Alternative solution:

In [76]: df.set_index('main_id').at['2456','code']
Out[76]: 94

ContentLicense: CC BY-SA 3.0


问:
Layering objects in Android Studio
I'm quite new to this whole Android Studio and all, but I'm quickly getting used to it all.

Now here's my problem:

I have my main Activity with two screen-filling buttons and I want a checkbox on top of the first button.

I've looked all around the Internet, but I couldn't find a single clue.

EDIT: Messing with the order of the objects doesn't work.

This is my XML code (I haven't filled in the functionality, yet):

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.ggblbl.example.MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="16dp"
        android:text="@string/button_one"
        app:layout_constraintBottom_toTopOf="@+id/guideline"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <Button
        android:id="@+id/button2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="8dp"
        android:text="@string/button_two"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline"
        app:layout_constraintVertical_bias="0.0" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5" />

    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/checkbox"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        android:layout_marginRight="150dp"
        android:layout_marginLeft="150dp"
        android:layout_marginBottom="20dp"
        app:layout_constraintBottom_toTopOf="@+id/guideline" />
</android.support.constraint.ConstraintLayout>
</code>```

PS: I don't know if this helps, but I use API 15 and Android Studio 2.3.2.

EDIT: I've got this

But I want this

答:
I have removed your margins and non-needed code. Try the following layout

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="32dp"
        android:text="Button 1"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/button2"
        />

    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="CheckBox"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button1"
        />

    <Button
        android:id="@+id/button2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="Button 2"
        app:layout_constraintTop_toBottomOf="@+id/button1"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

Edit: It looks like drawing over button is not possible. In the edited layout you have a bottom margin of button1 equal to height of the checkbox. You can distribute this height equally to bottom margin of button1 and top-margin of button 2. In support of my claim you can see the following layout, which gives what you want. In this example I have replaced upper button by a textview

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/button1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="Button 1"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:background="#ddd"
        app:layout_constraintBottom_toTopOf="@+id/button2"
        />

    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CheckBox"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="@+id/button1"
        />

    <Button
        android:id="@+id/button2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="Button 2"
        app:layout_constraintTop_toBottomOf="@+id/button1"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

Title: Layering objects in Android Studio

Body:
I'm quite new to this whole Android Studio and all, but I'm quickly getting used to it all.

Now here's my problem:

I have my main Activity with two screen-filling buttons and I want a checkbox on top of the first button.

I've looked all around the Internet, but I couldn't find a single clue.

EDIT: Messing with the order of the objects doesn't work.

This is my XML code (I haven't filled in the functionality, yet):

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.ggblbl.example.MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="16dp"
        android:text="@string/button_one"
        app:layout_constraintBottom_toTopOf="@+id/guideline"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <Button
        android:id="@+id/button2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="8dp"
        android:text="@string/button_two"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline"
        app:layout_constraintVertical_bias="0.0" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5" />

    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/checkbox"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        android:layout_marginRight="150dp"
        android:layout_marginLeft="150dp"
        android:layout_marginBottom="20dp"
        app:layout_constraintBottom_toTopOf="@+id/guideline" />
</android.support.constraint.ConstraintLayout>

PS: I don't know if this helps, but I use API 15 and Android Studio 2.3.2.

EDIT: I've got this

But I want this

Body:
I have removed your margins and non-needed code. Try the following layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="32dp"
        android:text="Button 1"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/button2"
        />

    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="CheckBox"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button1"
        />

    <Button
        android:id="@+id/button2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="Button 2"
        app:layout_constraintTop_toBottomOf="@+id/button1"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

</android.support.constraint.ConstraintLayout>

Edit: It looks like drawing over button is not possible. In the edited layout you have a bottom margin of button1 equal to height of the checkbox. You can distribute this height equally to bottom margin of button1 and top-margin of button 2. In support of my claim you can see the following layout, which gives what you want. In this example I have replaced upper button by a textview

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/button1"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="Button 1"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:background="#ddd"
        app:layout_constraintBottom_toTopOf="@+id/button2"
        />

    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CheckBox"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="@+id/button1"
        />

    <Button
        android:id="@+id/button2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="Button 2"
        app:layout_constraintTop_toBottomOf="@+id/button1"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

</android.support.constraint.ConstraintLayout>


问:
Blinking an LED linked through Arduino-Python
I wrote a sample code for blinking an LED linked to Python. The code is not throwing me any error, but the LED is not blinking. Any suggestions?

Python code:

import serial #import the pyserial library
connected = False #this will represent whether or not ardunio is connected to the system
ser = serial.Serial("COM3",9600) #open the serial port on which Ardunio is connected to, this will coommunicate to the serial port where ardunio is connected, the number which is there is called baud rate, this will provide the speed at which the communication happens
while not connected:#you have to loop until the ardunio gets ready, now when the ardunio gets ready, blink the led in the ardunio
    serin = ser.read()
    connected = True
ser.write('1') #this will blink the led in the ardunio
while ser.read() == '1': #now once the led blinks, the ardunio gets message back from the serial port and it get freed from the loop!
    ser.read()
print('Program is done')
ser.close()
```

<p>Arduino code:</p>

<pre class="lang-cpp prettyprint-override"><code>void setup() {
 Serial.begin(9600);
 pinMode(10,OUTPUT);
 Serial.write('1');
}
void loop() {
 if(Serial.available()>0){
  digitalWrite(255,HIGH);
  delay(50);
  digitalWrite(50,LOW);
  delay(50);
  digitalWrite(255,HIGH);
  delay(50);
  digitalWrite(50,LOW);
  delay(50);
  digitalWrite(255,HIGH);
  delay(50);
  digitalWrite(50,LOW);
  Serial.read();
 }
 else{
  Serial.available()==0;
 }
}
</code>```

答:
In the arduino code, you call

```<code>digitalWrite(50,LOW);
</code>```

and

```<code>digitalWrite(255,HIGH);
</code>```

but the first parameter of digitalWrite is the pin number, which you defined as pin 10. Simply change 50 and 255 to 10 as that is where you want your low and high signals to output to.

Body:
I wrote a sample code for blinking an LED linked to Python. The code is not throwing me any error, but the LED is not blinking. Any suggestions?

Python code:

import serial #import the pyserial library
connected = False #this will represent whether or not ardunio is connected to the system
ser = serial.Serial("COM3",9600) #open the serial port on which Ardunio is connected to, this will coommunicate to the serial port where ardunio is connected, the number which is there is called baud rate, this will provide the speed at which the communication happens
while not connected:#you have to loop until the ardunio gets ready, now when the ardunio gets ready, blink the led in the ardunio
    serin = ser.read()
    connected = True
ser.write('1') #this will blink the led in the ardunio
while ser.read() == '1': #now once the led blinks, the ardunio gets message back from the serial port and it get freed from the loop!
    ser.read()
print('Program is done')
ser.close()

Arduino code:

void setup() {
 Serial.begin(9600);
 pinMode(10,OUTPUT);
 Serial.write('1');
}
void loop() {
 if(Serial.available()>0){
  digitalWrite(255,HIGH);
  delay(50);
  digitalWrite(50,LOW);
  delay(50);
  digitalWrite(255,HIGH);
  delay(50);
  digitalWrite(50,LOW);
  delay(50);
  digitalWrite(255,HIGH);
  delay(50);
  digitalWrite(50,LOW);
  Serial.read();
 }
 else{
  Serial.available()==0;
 }
}

Body:
In the arduino code, you call

digitalWrite(50,LOW);

and

digitalWrite(255,HIGH);

but the first parameter of digitalWrite is the pin number, which you defined as pin 10. Simply change 50 and 255 to 10 as that is where you want your low and high signals to output to.


问:
ASPNETDB.MDF file not showing up in APP_DATA
I'm taking Microsoft's walk through on MVC 2 Forms Authentication - http://msdn.microsoft.com/en-us/library/ff398049.aspx

According to the walk through, when I register a user, ASP.NET creates the ASPNETDB.MDF file and it is supposed to show up in my APP_DATA folder upon refreshing in the solution explorer. The problem is, for me it is not and I want to have a look inside so I can understand it's structure.

I can continue to run the project and login as the user I created, yet the ASPNETDB.MDF file is still not visible under the APP_DATA folder.

Am I missing something here? Any help is appreciated as always!

Cheers

Chris

答: Try clicking the "Show All Files" button in the Solution Explorer in Visual Studio.  I believe the file gets generated, but it's not included in the Web Application project automatically.</p>

ContentLicense: CC BY-SA 2.5


问:
Use bootstrap's tooltip with complex html on a table cell
I want to show complex HTML tooltip whenever I hover a table cell(let's call it the outer table).
The complex HTML tooltip is another table(let's call it the inner table).
the actual inner table is being built at runtime, but for the example, i will use a static HTML.
I have set the outer table cells like this:

```<code><td data-toggle="tooltip" data-html="true" data-placement="bottom"></td>
</code>```

and the mouseover event :

```<code>$(#myTable td).on("mouseover", function () {

  $(this).attr("title", "<table><tr><td>some tooltip</td></tr></table>")
  $(this).tooltip({html: true});

}
</code>```

The tooltip popups but without parsing the text as HTML.
what am I doing wrong?

答:
You are initializing tooltip of every mouseover Better to initialize once Look at following code snipset.

Instead of of this

```<code>$(this).tooltip({html: true});
</code>```

To

```<code>$('td[data-toggle="tooltip"]').tooltip({html: true});
</code>```

& Your HTML markup should be

```<code><td data-toggle="tooltip" title="<table><tr><td>some tooltip</td></tr></table>" data-placement="bottom"></td>
</code>```

In case of static html content above code work.

In case of dynamic content below code useful

```<code>$('td[data-toggle="tooltip"]').tooltip({html: true});
</code>```

need to initializing tooltip after appending dynamic data.

& need to change title attribute for dynamic content.

```<code>$(document).on('mouseover','#myTable td', function () {
  var dyanmicContent = 'Hello World';
  $(this).attr("title", "<table><tr><td>" + dyanmicContent + "</td></tr></table>")
}
</code>```

Body:
I want to show complex HTML tooltip whenever I hover a table cell(let's call it the outer table).
The complex HTML tooltip is another table(let's call it the inner table).
the actual inner table is being built at runtime, but for the example, i will use a static HTML.
I have set the outer table cells like this:

and the mouseover event :

$(#myTable td).on("mouseover", function () {

  $(this).attr("title", "

some tooltip

")
  $(this).tooltip({html: true});

}

The tooltip popups but without parsing the text as HTML.
what am I doing wrong?

Body:
You are initializing tooltip of every mouseover Better to initialize once Look at following code snipset.

Instead of of this

$(this).tooltip({html: true});

To

$('td[data-toggle="tooltip"]').tooltip({html: true});

& Your HTML markup should be

<td data-toggle="tooltip" title="<table><tr><td>some tooltip</td></tr></table>" data-placement="bottom"></td>

In case of static html content above code work.

In case of dynamic content below code useful

$('td[data-toggle="tooltip"]').tooltip({html: true});

need to initializing tooltip after appending dynamic data.

& need to change title attribute for dynamic content.

$(document).on('mouseover','#myTable td', function () {
  var dyanmicContent = 'Hello World';
  $(this).attr("title", "<table><tr><td>" + dyanmicContent + "</td></tr></table>")
}


问:
ASP.NET - Error when trying to enable migrations
My ASP.NET Web API 2 application (MVC 6) consists of two projects: Web API server
project and Class Library project where I store all models. Server is very simple, only one controller is there. Server uses connection string to database which is located on Azure.

Now, when I try to enable migrations using Package Manager Console command EntityFramework\Enable-Migrations this error occurs:

Exception calling "SetData" with "2" argument(s): "Type 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProjec
t' in assembly 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
 is not marked as serializable."

Every other command produces the same output.

I got my Server project as Default project in Package Manager Console window and as startup project in Solution Explorer.

My DbContext is in Server project.

答: Please provide the paremeter -StartupProjectName on the Enable-Migrations command. If this still not working check your connection string. If you have more than one DbContext you must provide the DbContext class that you need to create the migrations for.</p>


问:
Where should I put my logic for initializing state in a Redux application
I am developing a React + Redux minesweeper application.

Here is a screenshot of the general look of my directory structure...

In my reducer.js file, I  have a bunch of logic that creates an object that represents the initial state that the reducer uses.

I feel like this is not a good place to put the logic that initializes the state because it's not a good separation of concerns. Where is a good place to factor this code out? Should I have another file that's responsible for generating initial state or something?

答:
Yes, you could confine the code that generates the initial state to its own file, say initialState.js, and put it next to your reducer.js. From initialState.js the generated object could be exported

```<code>export default {... the initial state here ... };
</code>```

And then from reducer.js you could

```<code>import initialState from './initialState';
</code>```

Body:
Yes, you could confine the code that generates the initial state to its own file, say initialState.js, and put it next to your reducer.js. From initialState.js the generated object could be exported

export default {... the initial state here ... };

And then from reducer.js you could

import initialState from './initialState';


问:
How to adjust the size of a plot in PyQt?
I have the following code which I found here. I reduced the code a bit to make it more suitable to my question.

```<code>import sys
import matplotlib
matplotlib.use("Qt5Agg")
from PyQt5 import QtCore
from PyQt5.QtCore import pyqtSlot, pyqtSignal, QObject
from PyQt5.QtWidgets import *
from numpy import arange, sin, pi
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

class MyMplCanvas(FigureCanvas):
    """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
    def __init__(self, parent=None, width = 5, height = 3, dpi=100):

        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)

        self.compute_initial_figure()
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.updateGeometry(self)

class MyStaticMplCanvas(MyMplCanvas):
    """Simple canvas with a sine plot."""
    def compute_initial_figure(self):
        t = arange(0.0, 3.0, 0.01)
        s = sin(2*pi*t)
        self.axes.plot(t, s)
        self.axes.set_ylabel('label2')
        self.axes.set_xlabel('label1')
        self.axes.grid(True)

class ApplicationWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.setMinimumWidth(800)
        self.setMinimumHeight(300)
        self.setMaximumWidth(800)
        self.setMaximumHeight(300)

        self.main_widget = QWidget(self)

        self.sc = MyStaticMplCanvas(self.main_widget, width=5, height=4, dpi=100)

        l = QVBoxLayout(self.main_widget)
        l.addWidget(self.sc)
        self.setCentralWidget(self.main_widget)

if __name__ == '__main__':
    app = QApplication(sys.argv)

    aw = ApplicationWindow()
    aw.setWindowTitle("PyQt5 Matplotlib Example")
    aw.show()
    app.exec_()
</code>```

The problem is that the plot is shown in principle correctly but the x-label is missing (fell out of the frame which is displayed). So, how can I adjust the size of the axes object to make PyQt also display the x-label?

I know that the figure size is adjustable through the 'figsize' argument. But so far I could not find a similar command for a diagram inside of the figure.

Also, I heard of the gridspec package of matplotlib but I think it is not suitable here since I only have one plot to display.

答:
I solved the problem and it turned out that one can simply adjust the axes through the position argument. </p>

```<code>self.ax = self.fig.add_subplot(111, position=[0.15, 0.15, 0.75, 0.75])
</code>```

Body:
I have the following code which I found here. I reduced the code a bit to make it more suitable to my question.

import sys
import matplotlib
matplotlib.use("Qt5Agg")
from PyQt5 import QtCore
from PyQt5.QtCore import pyqtSlot, pyqtSignal, QObject
from PyQt5.QtWidgets import *
from numpy import arange, sin, pi
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

class MyMplCanvas(FigureCanvas):
    """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
    def __init__(self, parent=None, width = 5, height = 3, dpi=100):

        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)

        self.compute_initial_figure()
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.updateGeometry(self)

class MyStaticMplCanvas(MyMplCanvas):
    """Simple canvas with a sine plot."""
    def compute_initial_figure(self):
        t = arange(0.0, 3.0, 0.01)
        s = sin(2*pi*t)
        self.axes.plot(t, s)
        self.axes.set_ylabel('label2')
        self.axes.set_xlabel('label1')
        self.axes.grid(True)

class ApplicationWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.setMinimumWidth(800)
        self.setMinimumHeight(300)
        self.setMaximumWidth(800)
        self.setMaximumHeight(300)

        self.main_widget = QWidget(self)

        self.sc = MyStaticMplCanvas(self.main_widget, width=5, height=4, dpi=100)

        l = QVBoxLayout(self.main_widget)
        l.addWidget(self.sc)
        self.setCentralWidget(self.main_widget)

if __name__ == '__main__':
    app = QApplication(sys.argv)

    aw = ApplicationWindow()
    aw.setWindowTitle("PyQt5 Matplotlib Example")
    aw.show()
    app.exec_()

The problem is that the plot is shown in principle correctly but the x-label is missing (fell out of the frame which is displayed). So, how can I adjust the size of the axes object to make PyQt also display the x-label?

I know that the figure size is adjustable through the 'figsize' argument. But so far I could not find a similar command for a diagram inside of the figure.

Also, I heard of the gridspec package of matplotlib but I think it is not suitable here since I only have one plot to display.

Body:
I solved the problem and it turned out that one can simply adjust the axes through the position argument.

self.ax = self.fig.add_subplot(111, position=[0.15, 0.15, 0.75, 0.75])


问:
Tortoise SVN logging without committing
I normally make multiple small edits to my source code, but I don't want to commit just yet, since the changes are rather trivial. The current method I'm using right now is to log the changes in a text file, then copying the contents into the log when committing.

Is it possible when using Tortoise SVN (or any other SVN tool) to attach log messages to the copy I'm currently working on as I'm editing, then when committing, the log messages are automatically attached to the commit, so I don't have to remember all the changes I've made so far?

答:
Interesting Question.

This answer is probably out of context, but if you are flexible to move towards another version control system, I would suggest moving to Git (allows you to have local commits). I am not saying anything aganist SVN, its great, just that Git might suite you better as per the use case.

Title: Tortoise SVN logging without committing


问:
error: ‘X’ does not name a type X in template functions
I have the following code:

```<code>#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

template< typename X>
X unary(X x)
{
    return x*10;
}

X binary( X x,X y)
{
    return x+y;
}

int main()
{
    vector<int> v1{1,2,3,4,5,6};
    vector<int> v2(v1);

    vector<int>::iterator i;

    for(i=v2.begin();i<v2.end();i++)
        cout<<*i<<endl;

    cout<<"unary "<<unary<int>(2)<<endl;
    cout<<"binary "<<binary<int>(2,7);
}
</code>```

However, it does not compile, and instead I get the following error message:

transform.cpp:12:1: error: ‘X’ does not name a type

  X binary( X x,X y)

  transform.cpp: In function ‘int main()’:

  transform.cpp:28:19: error: expected primary-expression before template’

Which appears on the following line:

```<code>cout<<"binary "<< binary<int,int>(2,7);
</code>```

Why does X name a type for unary, but not binary?

答:
The 'T' in the template is just a placeholder for the type used in the function, the class or the entity it is associated with. And the scope of the template parameter ends with the scope of this entity.

See here: When does a template end?

You have to write another template for binary(X x, X y) as follows:

```<code>template< typename X>
X unary(X x)
{
  return x*10;
}

template< typename X>
X binary( X x,X y)
{
    return x+y;
}
</code>```

Body:
I have the following code:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

template< typename X>
X unary(X x)
{
    return x*10;
}

X binary( X x,X y)
{
    return x+y;
}

int main()
{
    vector<int> v1{1,2,3,4,5,6};
    vector<int> v2(v1);

    vector<int>::iterator i;

    for(i=v2.begin();i<v2.end();i++)
        cout<<*i<<endl;

    cout<<"unary "<<unary<int>(2)<<endl;
    cout<<"binary "<<binary<int>(2,7);
}

However, it does not compile, and instead I get the following error message:

transform.cpp:12:1: error: ‘X’ does not name a type

  X binary( X x,X y)

  transform.cpp: In function ‘int main()’:

  transform.cpp:28:19: error: expected primary-expression before template’

Which appears on the following line:

cout<<"binary "<< binary<int,int>(2,7);

Why does X name a type for unary, but not binary?

Body:
The 'T' in the template is just a placeholder for the type used in the function, the class or the entity it is associated with. And the scope of the template parameter ends with the scope of this entity.

See here: When does a template end?

You have to write another template for binary(X x, X y) as follows:

template< typename X>
X unary(X x)
{
  return x*10;
}

template< typename X>
X binary( X x,X y)
{
    return x+y;
}


问:
RoboBrowser getting type error 'NoneType' object is not subscriptable
I'm trying to make a kahoot spammer which inputs a pin number and a username, decided by the user. I'm getting a type error when I run this code:

```<code>import re
from robobrowser import RoboBrowser

#Getting pin number for kahoot
pin = int(input("What is the pin number of the Kahoot?"))
# Getting number of bots to be deployed
number_of_bots = int(input("How many bots would you like?"))
#Getting base name
name = str(input("What would you like your bots' name to be (number will be added to the end of the name)?"))
#counter
counter = 0
#Number on end of name
num = 1

def joinKahoot(pin, number_of_bots, name):
    browser = RoboBrowser(history = True)
    #Connect to kahoot's website
    browser.open("https://kahoot.it/")
    pin_form = browser.get_form()
    pin_form['inputSession'].value == pin
    browser.submit_form(pin_form)

    name_form = browser.get_form()
    name_form["username"].value == name
    browser.submit_form(name_form)

#While counter is less than number_of_bots flood kahoot
while counter < number_of_bots:
    joinKahoot(pin, number_of_bots, name)
    counter += 1
    num += 1
    name = name + str(num)
</code>```

Error:

```<code>Traceback (most recent call last):
  File "C:\Users\Vincent\Documents\Kahoot Spammer V2\flood.py", line 29, in <module>
    joinKahoot(pin, number_of_bots, name)
  File "C:\Users\Vincent\Documents\Kahoot Spammer V2\flood.py", line 20, in joinKahoot
    pin_form['inputSession'].value == pin
TypeError: 'NoneType' object is not subscriptable
</code>```

What I am doing wrong?

答:
The page you are opening, https://kahoot.it/#/, does not contain an HTML <form> tag. The form you see is created using Javascript, undoubtedly to defeat DoS attacks using elementary HTML parsing techniques.

That is why browser.get_form() returns nothing. The function tries to return an instance of of robobrowser.forms.form.Form, which is a representation of an HTML form, but it can't find one.

I suspect you won't be able to get robobrowser to do what you want on this particular website. Good thing too.

Body:
I'm trying to make a kahoot spammer which inputs a pin number and a username, decided by the user. I'm getting a type error when I run this code:

import re
from robobrowser import RoboBrowser

#Getting pin number for kahoot
pin = int(input("What is the pin number of the Kahoot?"))
# Getting number of bots to be deployed
number_of_bots = int(input("How many bots would you like?"))
#Getting base name
name = str(input("What would you like your bots' name to be (number will be added to the end of the name)?"))
#counter
counter = 0
#Number on end of name
num = 1

def joinKahoot(pin, number_of_bots, name):
    browser = RoboBrowser(history = True)
    #Connect to kahoot's website
    browser.open("https://kahoot.it/")
    pin_form = browser.get_form()
    pin_form['inputSession'].value == pin
    browser.submit_form(pin_form)

    name_form = browser.get_form()
    name_form["username"].value == name
    browser.submit_form(name_form)

#While counter is less than number_of_bots flood kahoot
while counter < number_of_bots:
    joinKahoot(pin, number_of_bots, name)
    counter += 1
    num += 1
    name = name + str(num)

Error:

Traceback (most recent call last):
  File "C:\Users\Vincent\Documents\Kahoot Spammer V2\flood.py", line 29, in <module>
    joinKahoot(pin, number_of_bots, name)
  File "C:\Users\Vincent\Documents\Kahoot Spammer V2\flood.py", line 20, in joinKahoot
    pin_form['inputSession'].value == pin
TypeError: 'NoneType' object is not subscriptable

What I am doing wrong?


问:
Include tag is giving exception at run time in Xamarin .axml layout
I am trying to include/reuse a layout (.axml) in other layout (.axml) but everything seems good at compile time. at run time it's generating an exception as follows:

Unhandled Exception:

Android.Views.InflateException: Binary XML file line #1: You must specify a layout in the include tag: <include layout="@layout/layoutID" /> occurred

Layout having include tag as follows:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="100"
    android:minWidth="25px"
    android:minHeight="25px"
    android:background="@android:color/background_light">
    <include
        android:layout_height="wrap_content"
        android:layout="@layout/header_partial"
        android:id="@+id/layoutHeaderPartial" />

 </LinearLayout>```
</div>
</div>
</p>
<p>Partial/reusable layout code as follows:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:focusable="true"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:clickable="true"
    android:weightSum="100"
    android:orientation="horizontal">
  <LinearLayout
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_weight="20"
      android:gravity="center_horizontal">
    <refractored.controls.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/door_image"
        android:layout_width="70dp"
        android:layout_height="70dp"
        app:civ_border_width="0dp"
        app:civ_border_color="#FF000000"
        android:src="@drawable/img1" />
  </LinearLayout>
  <LinearLayout
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:orientation="horizontal"
      android:layout_weight="55"
      android:paddingLeft="5dp"
      android:gravity="left|center_vertical">
    <TextView
        android:id="@+id/lblStatusFixed"
        android:textColor="@color/year"
        android:textSize="10sp"
        android:gravity="left"
        android:layout_marginLeft="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Status:" />
    <TextView
        android:id="@+id/lblLockedStatus"
        android:gravity="left"
        android:textColor="@color/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10sp"
        android:paddingLeft="10dp"
        android:layout_marginLeft="5dp"
        android:textStyle="bold"
        android:text="working" />
    <refractored.controls.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/door_lockImg"
        android:layout_width="30dp"
        android:layout_height="30dp"
        app:civ_border_width="0dp"
        app:civ_border_color="#FF000000"
        android:paddingLeft="10dp"
        android:layout_marginLeft="10dp"
        android:gravity="left"
        android:src="@drawable/img2" />
  </LinearLayout>
  <LinearLayout
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_weight="25"
      android:gravity="center">
    <TextView
        android:id="@+id/lastuse"
        android:textColor="@color/year"
        android:layout_width="wrap_content"
        android:gravity="right"
        android:textSize="10sp"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        android:text="Last use: 8hrs" />
  </LinearLayout>
</LinearLayout></code>```

Everything seems fine at compile time and I can see designer view is working well, but at run time I don't know what's wrong.

答: The problem is that you include android prefix android:layout="@layout/header_partial" but it should be without it like: include layout="@layout/header_partial".

Body:
I am trying to include/reuse a layout (.axml) in other layout (.axml) but everything seems good at compile time. at run time it's generating an exception as follows:

Unhandled Exception:

Android.Views.InflateException: Binary XML file line #1: You must specify a layout in the include tag: <include layout="@layout/layoutID" /> occurred

Layout having include tag as follows:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="100"
    android:minWidth="25px"
    android:minHeight="25px"
    android:background="@android:color/background_light">
    <include
        android:layout_height="wrap_content"
        android:layout="@layout/header_partial"
        android:id="@+id/layoutHeaderPartial" />

 </LinearLayout>

Partial/reusable layout code as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:focusable="true"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:clickable="true"
    android:weightSum="100"
    android:orientation="horizontal">
  <LinearLayout
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_weight="20"
      android:gravity="center_horizontal">
    <refractored.controls.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/door_image"
        android:layout_width="70dp"
        android:layout_height="70dp"
        app:civ_border_width="0dp"
        app:civ_border_color="#FF000000"
        android:src="@drawable/img1" />
  </LinearLayout>
  <LinearLayout
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:orientation="horizontal"
      android:layout_weight="55"
      android:paddingLeft="5dp"
      android:gravity="left|center_vertical">
    <TextView
        android:id="@+id/lblStatusFixed"
        android:textColor="@color/year"
        android:textSize="10sp"
        android:gravity="left"
        android:layout_marginLeft="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Status:" />
    <TextView
        android:id="@+id/lblLockedStatus"
        android:gravity="left"
        android:textColor="@color/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10sp"
        android:paddingLeft="10dp"
        android:layout_marginLeft="5dp"
        android:textStyle="bold"
        android:text="working" />
    <refractored.controls.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/door_lockImg"
        android:layout_width="30dp"
        android:layout_height="30dp"
        app:civ_border_width="0dp"
        app:civ_border_color="#FF000000"
        android:paddingLeft="10dp"
        android:layout_marginLeft="10dp"
        android:gravity="left"
        android:src="@drawable/img2" />
  </LinearLayout>
  <LinearLayout
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_weight="25"
      android:gravity="center">
    <TextView
        android:id="@+id/lastuse"
        android:textColor="@color/year"
        android:layout_width="wrap_content"
        android:gravity="right"
        android:textSize="10sp"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        android:text="Last use: 8hrs" />
  </LinearLayout>
</LinearLayout>

Everything seems fine at compile time and I can see designer view is working well, but at run time I don't know what's wrong.


问:
Match multiple patterns in Logstash?
I have two types of error messages in the below format:

```<code>[2017-05-25 01:00:00,647][ERROR][marvel.agent.exporter.local] local exporter [default_local] - failed to delete indices
RemoteTransportException[[data-0][10.0.0.8:9300][indices:admin/delete]]; nested: IndexNotFoundException[no such index];

[2017-05-18 00:00:06,339][DEBUG][action.admin.indices.create] [data-2] [data-may-2017,data-apr-2017,data-mar-2017] failed to create
[data-may-2017,data-apr-2017,data-mar-2017]
</code>```

My logstash configuration is like this:

```<code>input {
      file {
            path => "D:\logstash\logstash-2.4.0\bin\logs.txt"
            start_position => "beginning"
        codec => multiline {
            pattern => "^\[%{TIMESTAMP_ISO8601:TIMESTAMP}\]"
            negate => true
            what => "previous"
        }
  }

}
filter {
   grok {
        match => [ "message", "(?m)^\[%{TIMESTAMP_ISO8601:TIMESTAMP}\]\[%{LOGLEVEL:LEVEL}%{SPACE}\]\[%{DATA:ERRORTYPE}\]%{SPACE}\[%{DATA:SERVERNAME}\]%{SPACE}(?<ERRORMESSAGE>(.|\r|\n)*)", "message",  "(?m)^\[%{TIMESTAMP_ISO8601:TIMESTAMP}\]\[%{LOGLEVEL:LEVEL}%{SPACE}\]\[%{DATA:ERRORTYPE}%{SPACE}\]%{SPACE}(?<ERRORMESSAGE>(.|\r|\n)*)"]
   }

}
output {

  stdout { codec => rubydebug }
}
</code>```

For Both the logs it is taking only the first grok pattern. Why it is not taking the second one?

答:
Seems my first grok pattern is matching all the logs , so thats why logstash is taking only the first pattern. So that i had used the below config with if condition which is working fine.</p>

```<code>input {
      file {
            path => "D:\logstash\logstash-2.4.0\bin\logs.txt"
            start_position => "beginning"
             type => "log"
        codec => multiline {
            pattern => "^\[%{TIMESTAMP_ISO8601:TIMESTAMP}\]"
            negate => true
            what => "previous"
        }
  }

}
    filter {
      if [type] == "log" {
        grok {
          match => [ "message", "(?m)^\[%{TIMESTAMP_ISO8601:TIMESTAMP}\]\[%{LOGLEVEL:LEVEL}%{SPACE}\]\[%{DATA:ERRORTYPE}%{SPACE}\]%{SPACE}(?<ERRORMESSAGE>(.|\r|\n)*)"]
        }
    # DEBUG Logs
    if "grokked" not in [tags] and "DEBUG" == [LEVEL] {
    grok { match => [ "ERRORMESSAGE", "(?m)^\[%{DATA:SERVERNAME}\]" ]
    add_tag => [ "Debug Logs", "grokked" ]
    tag_on_failure => [ ]
    }
    }
    }
    }
output {

  stdout { codec => rubydebug }
}
</code>```

Title: Match multiple patterns in Logstash?

Body:
I have two types of error messages in the below format:

[2017-05-25 01:00:00,647][ERROR][marvel.agent.exporter.local] local exporter [default_local] - failed to delete indices
RemoteTransportException[[data-0][10.0.0.8:9300][indices:admin/delete]]; nested: IndexNotFoundException[no such index];

[2017-05-18 00:00:06,339][DEBUG][action.admin.indices.create] [data-2] [data-may-2017,data-apr-2017,data-mar-2017] failed to create
[data-may-2017,data-apr-2017,data-mar-2017]

My logstash configuration is like this:

input {
      file {
            path => "D:\logstash\logstash-2.4.0\bin\logs.txt"
            start_position => "beginning"
        codec => multiline {
            pattern => "^\[%{TIMESTAMP_ISO8601:TIMESTAMP}\]"
            negate => true
            what => "previous"
        }
  }

}
filter {
   grok {
        match => [ "message", "(?m)^\[%{TIMESTAMP_ISO8601:TIMESTAMP}\]\[%{LOGLEVEL:LEVEL}%{SPACE}\]\[%{DATA:ERRORTYPE}\]%{SPACE}\[%{DATA:SERVERNAME}\]%{SPACE}(?<ERRORMESSAGE>(.|\r|\n)*)", "message",  "(?m)^\[%{TIMESTAMP_ISO8601:TIMESTAMP}\]\[%{LOGLEVEL:LEVEL}%{SPACE}\]\[%{DATA:ERRORTYPE}%{SPACE}\]%{SPACE}(?<ERRORMESSAGE>(.|\r|\n)*)"]
   }

}
output {

  stdout { codec => rubydebug }
}

For Both the logs it is taking only the first grok pattern. Why it is not taking the second one?

Body:
Seems my first grok pattern is matching all the logs , so thats why logstash is taking only the first pattern. So that i had used the below config with if condition which is working fine.

input {
      file {
            path => "D:\logstash\logstash-2.4.0\bin\logs.txt"
            start_position => "beginning"
             type => "log"
        codec => multiline {
            pattern => "^\[%{TIMESTAMP_ISO8601:TIMESTAMP}\]"
            negate => true
            what => "previous"
        }
  }

}
    filter {
      if [type] == "log" {
        grok {
          match => [ "message", "(?m)^\[%{TIMESTAMP_ISO8601:TIMESTAMP}\]\[%{LOGLEVEL:LEVEL}%{SPACE}\]\[%{DATA:ERRORTYPE}%{SPACE}\]%{SPACE}(?<ERRORMESSAGE>(.|\r|\n)*)"]
        }
    # DEBUG Logs
    if "grokked" not in [tags] and "DEBUG" == [LEVEL] {
    grok { match => [ "ERRORMESSAGE", "(?m)^\[%{DATA:SERVERNAME}\]" ]
    add_tag => [ "Debug Logs", "grokked" ]
    tag_on_failure => [ ]
    }
    }
    }
    }
output {

  stdout { codec => rubydebug }
}


问:
How to fix add to cart page refresh issue in magento?
I have created one woocommerce site in magento, I am facing one issue in add to cart page. how to add a product in cart without refreshing the page? . Please suggest.</p>

答:
you can try below extension for ajax add to cart.

https://www.magentocommerce.com/magento-connect/ajaxcart-3-15606.html

So, please try this and let me know in case of any query.

Thanks


问:
Setting an xts Index
Build an xts object with two rows.

```<code>library(xts)
junk<-xts(c(1,2),as.Date(c("2010-01-01","2010-05-01")))
junk
>            [,1]
> 2010-01-01    1
> 2010-05-01    2
</code>```

Why doesn't the following change the index for the first row?

```<code>time(junk[1])<-as.Date("2010-02-01")
junk
>            [,1]
> 2010-01-01    1
> 2010-05-01    2
</code>```

I realize that the following works, but why doesn't the above work?

```<code>time(junk)[1]<-as.Date("2010-02-01")
junk
>            [,1]
> 2010-02-01    1
> 2010-05-01    2
</code>```

Thanks,

Bill

答:
The dates in time series are not referenced with "[". They are more like rownames in dataframes. They are stored in the "index" leaf of the attributes list. In addition to that, they are not of Date class but rather the DateTime class so you need to  may use POSIXct:

```<code>> attributes(junk)$index[1] <- as.POSIXct("2010-02-01")
> junk
           [,1]
2010-02-01    1
2010-05-01    2
</code>```

Edit: more accurately the attribute$index is internally in seconds but the time method will accept a variety of assignment classes.

Title: Setting an xts Index

Body:
Build an xts object with two rows.

library(xts)
junk<-xts(c(1,2),as.Date(c("2010-01-01","2010-05-01")))
junk
>            [,1]
> 2010-01-01    1
> 2010-05-01    2

Why doesn't the following change the index for the first row?

time(junk[1])<-as.Date("2010-02-01")
junk
>            [,1]
> 2010-01-01    1
> 2010-05-01    2

I realize that the following works, but why doesn't the above work?

time(junk)[1]<-as.Date("2010-02-01")
junk
>            [,1]
> 2010-02-01    1
> 2010-05-01    2

Thanks,

Bill

Body:
The dates in time series are not referenced with "[". They are more like rownames in dataframes. They are stored in the "index" leaf of the attributes list. In addition to that, they are not of Date class but rather the DateTime class so you need to  may use POSIXct:

> attributes(junk)$index[1] <- as.POSIXct("2010-02-01")
> junk
           [,1]
2010-02-01    1
2010-05-01    2

Edit: more accurately the attribute$index is internally in seconds but the time method will accept a variety of assignment classes.


问:
Entity Framework Validation Error On Entity Not Being Modified
Here's my controller action:

```<code>public JsonResult Add(Mod.Payment payment)
{
    if (ModelState.IsValid)
    {
        Ent.Payment paymentEnt = new Ent.Payment();
        Mapper.Map(payment, paymentEnt);
        db.Payments.Add(paymentEnt);
        db.SaveChanges();
        return Payment(paymentEnt.PaymentId);
    } else
    {
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return Json(new { Message = "Not OK" });
    }

}
</code>```

db.SaveChanges triggers EntityValidationErrors.  The errors are not for the "paymentEnt" entity, but for related entities that are included with the payment View Model and Entity via navigation properties.

I'm not modifying those entities, only "paymentEnt".  So how can I get Entity Framework to not try to validate them or to ignore their errors?

I could create another Payment ViewModel that excludes related entities, but that would violate DRY.

答:
You could explicitly mark the related entities as Unchanged/Detached, if you want EF to skip them:</p>

```<code>db.Entry(paymentEnt.RelatedEntity).State = System.Data.Entity.EntityState.Unchanged;
</code>```

Body:
Here's my controller action:

public JsonResult Add(Mod.Payment payment)
{
    if (ModelState.IsValid)
    {
        Ent.Payment paymentEnt = new Ent.Payment();
        Mapper.Map(payment, paymentEnt);
        db.Payments.Add(paymentEnt);
        db.SaveChanges();
        return Payment(paymentEnt.PaymentId);
    } else
    {
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return Json(new { Message = "Not OK" });
    }

}

db.SaveChanges triggers EntityValidationErrors.  The errors are not for the "paymentEnt" entity, but for related entities that are included with the payment View Model and Entity via navigation properties.

I'm not modifying those entities, only "paymentEnt".  So how can I get Entity Framework to not try to validate them or to ignore their errors?

I could create another Payment ViewModel that excludes related entities, but that would violate DRY.

Body:
You could explicitly mark the related entities as Unchanged/Detached, if you want EF to skip them:

db.Entry(paymentEnt.RelatedEntity).State = System.Data.Entity.EntityState.Unchanged;


问:
pyinstaller not importing chrome webdriver? selenium
I'm using pyinstaller to create a .exe for my script to be used on another computer, the issue is when it gets compiled it imports webdriver/firefox it doesn't import the chrome webdriver which the script uses so the .exe won't run.
I'm just wondering why this is happening and how I can fix this. I am using python 3.5</p>

答:
I get the same issue fixed by explicitly import the selenium.webdriver.Chrome in my script :

```<code>import selenium
from selenium import webdriver
from selenium.webdriver import Chrome
</code>```

I guess pyinstaller will not then forget this Chrome sub-module.

Body:
I get the same issue fixed by explicitly import the selenium.webdriver.Chrome in my script :

import selenium
from selenium import webdriver
from selenium.webdriver import Chrome

I guess pyinstaller will not then forget this Chrome sub-module.


问:
Automatic VM migration
On my google VM, Google "automatically migrate an instance" on my account. After the instance was migrated it was shut down. This happened on two of my instances. I can no longer access my site. Can someone help me troubleshoot this? I've included screenshots to help illustrate my concern.

Compute Engine > Operations

After you click on the "automatically migrate an instance

hero-new-production" line item

Thank you for your help.

答:
Have you set Automatic restart On option for your VM instance?

Are you using Local SSD or persistent disk for your VM? Local SSD data does not persist through instance termination. When the instance restarts, it creates a new Local SSD that you must format and mount.

This troubleshooting guide might be helpful

Title: Automatic VM migration


问:
Matplotlib: coloring axis/tick labels
How would one color y-axis label and tick labels in red?

So for example the "y-label" and values 0 through 40, to be colored in red.

```<code>import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)
ax.set_ylabel("y-label")

for i in xrange(5):
    ax.plot(x, i * x, label='$y = %ix$' % i)

ax.legend()

plt.show()
</code>```

答:
The xlabel can be colorized when setting it,

```<code>ax.set_xlabel("x-label", color="red")
</code>```

For setting the ticklabels' color, one may either use tick_params, which sets the ticklabels' as well as the ticks' color

```<code>ax.tick_params(axis='x', colors='red')
</code>```

Alternatively, plt.setp can be used to only set the ticklabels' color, without changing the ticks' color.

```<code>plt.setp(ax.get_xticklabels(), color="red")
</code>```

Note that for changing the properties on the y-axis, one can replace the x with a y in the above.

Title: Matplotlib: coloring axis/tick labels

Body:
How would one color y-axis label and tick labels in red?

So for example the "y-label" and values 0 through 40, to be colored in red.

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)
ax.set_ylabel("y-label")

for i in xrange(5):
    ax.plot(x, i * x, label='$y = %ix$' % i)

ax.legend()

plt.show()

Body:
The xlabel can be colorized when setting it,

ax.set_xlabel("x-label", color="red")

For setting the ticklabels' color, one may either use tick_params, which sets the ticklabels' as well as the ticks' color

ax.tick_params(axis='x', colors='red')

Alternatively, plt.setp can be used to only set the ticklabels' color, without changing the ticks' color.

plt.setp(ax.get_xticklabels(), color="red")

Note that for changing the properties on the y-axis, one can replace the x with a y in the above.


问:
How to get one records that sorted by date
I have a table like this:

```<code>id    product_id   price      date
1       1001        100     2017-05-29
2       1005        101     2017-03-30
3       1001        102     2017-03-30
4       1003        106     2017-06-07
5       1005        106     2017-04-30
</code>```

I want to group by product_id and get only one latest product for each product_id. I also have a min and max price variable which should be applied to the price column.

the result of my query should be:

```<code>1       1001        100     2017-05-29
4       1003        106     2017-06-07
5       1005        106     2017-04-30
</code>```

Is it possible by SQL or I should use application side?

答:
If you want to order results by date, just use orderBy():

```<code>Model::orderBy('date_column', 'desc')->whereBetween('price', [$min, $max])->groupBy('product_id')->take(3)->get();
</code>```

Or it's shortcuts latest() and oldest():

```<code>Model::latest('date_column')->...
</code>```

Body:
I have a table like this:

id    product_id   price      date
1       1001        100     2017-05-29
2       1005        101     2017-03-30
3       1001        102     2017-03-30
4       1003        106     2017-06-07
5       1005        106     2017-04-30

I want to group by product_id and get only one latest product for each product_id. I also have a min and max price variable which should be applied to the price column.

the result of my query should be:

1       1001        100     2017-05-29
4       1003        106     2017-06-07
5       1005        106     2017-04-30

Is it possible by SQL or I should use application side?

Body:
If you want to order results by date, just use orderBy():

Model::orderBy('date_column', 'desc')->whereBetween('price', [$min, $max])->groupBy('product_id')->take(3)->get();

Or it's shortcuts latest() and oldest():

Model::latest('date_column')->...


答:
When you do a commit and it fails, tortoiseSVN stores the commit message for you to bring it up when you retry. Find that file and append to it would be my suggestion.

vanilla svn is commit.tmp, that's probably a good starting place to look.

EDIT:

EDIT EDIT: You're using tortoise which implies windows. So, you'll probably need something that works on windows. I've quickly rewritten it in python since I suck at cmd scripting

Alternatively, create a directory called logs, store all your notes in there and then do something like this for a commit script

```<code>for i in `ls logs`; do
    echo -n "$i: "
    cat logs/$i >> commitFile
done
svn commit -F commitFile
</code>```

Or in python

```<code>#!/usr/bin/python
import os
dirlisting = os.listdir('logs')
commitFile = open("commitfile.tmp", "w")
for i in dirlisting:
    log = open(i, 'r')
    commitFile.write(log.read())
    log.close()
os.execlp("svn", "svn", "commit", "-F", "commitfile.tmp")
</code>```

You'll need to fix the last line to do something that calls tortoise instead though. I have not tested either of these scripts.

Obviously you'd want to clean this up a little bit and make it a bit smarter, but you can see what I'm driving at.

Title: Tortoise SVN logging without committing

Body:
I normally make multiple small edits to my source code, but I don't want to commit just yet, since the changes are rather trivial. The current method I'm using right now is to log the changes in a text file, then copying the contents into the log when committing.

Is it possible when using Tortoise SVN (or any other SVN tool) to attach log messages to the copy I'm currently working on as I'm editing, then when committing, the log messages are automatically attached to the commit, so I don't have to remember all the changes I've made so far?

Body:
When you do a commit and it fails, tortoiseSVN stores the commit message for you to bring it up when you retry. Find that file and append to it would be my suggestion.

vanilla svn is commit.tmp, that's probably a good starting place to look.

EDIT:

EDIT EDIT: You're using tortoise which implies windows. So, you'll probably need something that works on windows. I've quickly rewritten it in python since I suck at cmd scripting

Alternatively, create a directory called logs, store all your notes in there and then do something like this for a commit script

for i in `ls logs`; do
    echo -n "$i: "
    cat logs/$i >> commitFile
done
svn commit -F commitFile

Or in python

#!/usr/bin/python
import os
dirlisting = os.listdir('logs')
commitFile = open("commitfile.tmp", "w")
for i in dirlisting:
    log = open(i, 'r')
    commitFile.write(log.read())
    log.close()
os.execlp("svn", "svn", "commit", "-F", "commitfile.tmp")

You'll need to fix the last line to do something that calls tortoise instead though. I have not tested either of these scripts.

Obviously you'd want to clean this up a little bit and make it a bit smarter, but you can see what I'm driving at.


答:
You can use subqueries. First select from your table order by date, then use that to group by product_id:

```<code>SELECT * FROM (SELECT * FROM `your_table` t ORDER by date desc) as date_ordered group by product_id ORDER by id
</code>```

Title: How to get one records that sorted by date

Body:
You can use subqueries. First select from your table order by date, then use that to group by product_id:

SELECT * FROM (SELECT * FROM `your_table` t ORDER by date desc) as date_ordered group by product_id ORDER by id


问:
How to Implement SearchView using volley JSON android?
I am working on a android project where I have to implement search view on the action bar . I am able to parse the JSON data into recycler view using volley. when I try to add a search view, and start typing the text the list is getting disappeared.

Activity:

```<code>public class Fragment_Church_News extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private ListView listView;
    Context con;
    private ChurchNewsFeedListAdapter listAdapter;
    private List<ChurchNewsFeedItem> feedItemschurchnews;

    int a = Keys.LANGUGAE_KEY;

    public Fragment_Church_News() {
        // Required empty public constructor
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_church_list);

        con = this;

        if(Keys.LANGUGAE_KEY == 0)
        {
            a = 2;

        }
        else
        {

            a=1;
        }

        Toast.makeText(this, "aaaaaaa"+a+"", Toast.LENGTH_SHORT).show();
        listView = (ListView) findViewById(R.id.list);

        feedItemschurchnews = new ArrayList<ChurchNewsFeedItem>();

        listAdapter = new ChurchNewsFeedListAdapter(this, feedItemschurchnews,con);
        listView.setAdapter(listAdapter);

        Toast.makeText(this, "a", Toast.LENGTH_SHORT).show();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                TextView c = (TextView) view.findViewById(R.id.news_details);
                String idfromtextview = c.getText().toString().trim();

                Intent testIntent = new Intent(Fragment_Church_News.this, MainColapse.class);
                testIntent.putExtra("txtpersonid", idfromtextview);
                startActivity(testIntent);
            }
        });

        /////

        // We first check for cached request
        Cache cache = AppController.getInstance().getRequestQueue().getCache();
        Cache.Entry entry = cache.get("http://52.89.46.93/churchListAppDump/?methodName=church.list&app_language_name="+a+"");
        if (entry != null) {
            // fetch the data from cache
            try {
                String data = new String(entry.data, "UTF-8");
                try {
                    parseJsonFeed(new JSONObject(data));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        } else {
            // making fresh volley request and getting json
            JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
                    "http://52.89.46.93/churchListAppDump/?methodName=church.list&app_language_name="+a+"", null, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    VolleyLog.d(TAG, "Response: " + response.toString());
                    ;
                    if (response != null) {
                        parseJsonFeed(response);
                    }

                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                }
            });

            // Adding request to volley request queue
            AppController.getInstance().addToRequestQueue(jsonReq);
        }

    }

    private void parseJsonFeed(JSONObject response) {
        try {
            JSONArray feedArray = response.getJSONArray("responseMsg");

            for (int i = 0; i < feedArray.length(); i++) {
                JSONObject feedObj = (JSONObject) feedArray.get(i);

                ChurchNewsFeedItem item = new ChurchNewsFeedItem();
                item.setNews_title(feedObj.getString("church_name"));

                String image = feedObj.isNull("church_image") ? null : feedObj
                        .getString("church_image");
                item.setNews_image(image);
                item.setNews_details(feedObj.getString("admin_id"));

              //  String priya = feedObj.getString("admin_id");

                feedItemschurchnews.add(item);
            }

            // notify data changes to list adapater
            listAdapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public static void deleteCache(Context context) {
        try {
            File dir = context.getCacheDir();
            deleteDir(dir);
        } catch (Exception e) {
        }
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
            return dir.delete();
        } else if (dir != null && dir.isFile()) {
            return dir.delete();
        } else {
            return false;

        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater().inflate(R.menu.menu_search, menu);
        MenuInflater inflater = getMenuInflater();
        // Inflate menu to add items to action bar if it is present.
        inflater.inflate(R.menu.search_main, menu);

        SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView search = (SearchView) menu.findItem(R.id.action_search).getActionView();
        search.setSearchableInfo(manager.getSearchableInfo(getComponentName()));
        search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                PerfromSearch(newText);
                return false;
            }
        });
        return true;
    }

    void PerfromSearch(String query) {

        listAdapter.filter(query);
    }

}
</code>```

Adapter:

```<code>public class ChurchNewsFeedListAdapter extends BaseAdapter
{

    private Activity activity;
    private LayoutInflater inflater;
    Context mContext;
    private List<ChurchNewsFeedItem> churhcnewsfeedItems, churchNewsFeedItemssearched=null;
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    //List<ChurchNewsFeedItem> arraylist;

    public ChurchNewsFeedListAdapter(Activity activity, List<ChurchNewsFeedItem> feedItems,Context context) {
        this.activity = activity;
        this.churhcnewsfeedItems = feedItems;

        this.churchNewsFeedItemssearched = new ArrayList<ChurchNewsFeedItem>();
        this.churchNewsFeedItemssearched.addAll(feedItems);

        // mContext = this;
        this.mContext = context;

    }

    @Override
    public int getCount() {
        return churhcnewsfeedItems.size();
    }

    @Override
    public Object getItem(int location) {
        return churhcnewsfeedItems.get(location);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (inflater == null)
            inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
            convertView = inflater.inflate(R.layout.churchnews_feed_item, null);

        if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();

        TextView newstitle = (TextView) convertView.findViewById(R.id.news_title);

        TextView newdetails = (TextView) convertView
                .findViewById(R.id.news_details);

        ChurchNewsFeedImageView feedImageView = (ChurchNewsFeedImageView) convertView
                .findViewById(R.id.news_feedImage);

        ChurchNewsFeedItem item = churhcnewsfeedItems.get(position);

        newstitle.setText(item.getNews_title());

        // Chcek for empty status message
        if (!TextUtils.isEmpty(item.getNews_details())) {
            newdetails.setText(item.getNews_details());
            newdetails.setVisibility(View.VISIBLE);
        } else {
            // status is empty, remove from view
            newdetails.setVisibility(View.GONE);
        }

        // Feed image
        if (item.getNews_image() != null) {
            feedImageView.setImageUrl(item.getNews_image(), imageLoader);
            feedImageView.setVisibility(View.VISIBLE);
            feedImageView
                    .setResponseObserver(new ChurchNewsFeedImageView.ResponseObserver() {
                        @Override
                        public void onError()
                        {

                        }

                        @Override
                        public void onSuccess() {

                        }
                    });
        } else {
            feedImageView.setVisibility(View.GONE);
        }

        return convertView;
    }

    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());

        Toast.makeText(mContext, "divakar"+churchNewsFeedItemssearched, Toast.LENGTH_SHORT).show();
        churhcnewsfeedItems.clear();
        if (charText.length() == 0) {
            churhcnewsfeedItems.addAll(churchNewsFeedItemssearched);

        } else {

            for (ChurchNewsFeedItem wp : churchNewsFeedItemssearched) {
                if (wp.getNews_title().toLowerCase(Locale.getDefault())
                        .contains(charText)) {
                    churhcnewsfeedItems.add(wp);

                }
            }
        }
        notifyDataSetChanged();
    }
}
</code>```

答:
Seems your churchNewsFeedItemssearched list is NULL. Because when you initialize ChurchNewsFeedListAdapter you are passing feedItemschurchnews with 0 items:

```<code>listAdapter = new ChurchNewsFeedListAdapter(this, feedItemschurchnews, con);
</code>```

So, for this your Adapter's constructor works like below:

```<code>public ChurchNewsFeedListAdapter(Activity activity, List<ChurchNewsFeedItem> feedItems,Context context) {
    this.activity = activity;
    this.churhcnewsfeedItems = feedItems; // SIZE 0

    this.churchNewsFeedItemssearched = new ArrayList<ChurchNewsFeedItem>();
    this.churchNewsFeedItemssearched.addAll(feedItems); // SIZE 0
}
</code>```

SOLUTION:

You have to update list churchNewsFeedItemssearched.

Add method updateSearchedList() to your ChurchNewsFeedListAdapter class to update the churchNewsFeedItemssearched and call this method from parseJsonFeed() after adding all items to feedItemschurchnews.

Update your code as below:

ChurchNewsFeedListAdapter:

```<code>public void updateSearchedList() {

    churchNewsFeedItemssearched.addAll(churhcnewsfeedItems);
}
</code>```

Fragment_Church_News:

```<code>private void parseJsonFeed(JSONObject response) {

    try {
        JSONArray feedArray = response.getJSONArray("responseMsg");

        for (int i = 0; i < feedArray.length(); i++) {
            JSONObject feedObj = (JSONObject) feedArray.get(i);

            ChurchNewsFeedItem item = new ChurchNewsFeedItem();
            item.setNews_title(feedObj.getString("church_name"));

            String image = feedObj.isNull("church_image") ? null : feedObj
                    .getString("church_image");
            item.setNews_image(image);
            item.setNews_details(feedObj.getString("admin_id"));

            //  String priya = feedObj.getString("admin_id");

            feedItemschurchnews.add(item);
        }

        // Update
        listAdapter.updateSearchedList();

        // notify data changes to list adapater
        listAdapter.notifyDataSetChanged();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
</code>```

Hope this will work~

Body:
I am working on a android project where I have to implement search view on the action bar . I am able to parse the JSON data into recycler view using volley. when I try to add a search view, and start typing the text the list is getting disappeared.

Activity:

public class Fragment_Church_News extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private ListView listView;
    Context con;
    private ChurchNewsFeedListAdapter listAdapter;
    private List<ChurchNewsFeedItem> feedItemschurchnews;

    int a = Keys.LANGUGAE_KEY;

    public Fragment_Church_News() {
        // Required empty public constructor
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_church_list);

        con = this;

        if(Keys.LANGUGAE_KEY == 0)
        {
            a = 2;

        }
        else
        {

            a=1;
        }

        Toast.makeText(this, "aaaaaaa"+a+"", Toast.LENGTH_SHORT).show();
        listView = (ListView) findViewById(R.id.list);

        feedItemschurchnews = new ArrayList<ChurchNewsFeedItem>();

        listAdapter = new ChurchNewsFeedListAdapter(this, feedItemschurchnews,con);
        listView.setAdapter(listAdapter);

        Toast.makeText(this, "a", Toast.LENGTH_SHORT).show();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                TextView c = (TextView) view.findViewById(R.id.news_details);
                String idfromtextview = c.getText().toString().trim();

                Intent testIntent = new Intent(Fragment_Church_News.this, MainColapse.class);
                testIntent.putExtra("txtpersonid", idfromtextview);
                startActivity(testIntent);
            }
        });

        /////

        // We first check for cached request
        Cache cache = AppController.getInstance().getRequestQueue().getCache();
        Cache.Entry entry = cache.get("http://52.89.46.93/churchListAppDump/?methodName=church.list&app_language_name="+a+"");
        if (entry != null) {
            // fetch the data from cache
            try {
                String data = new String(entry.data, "UTF-8");
                try {
                    parseJsonFeed(new JSONObject(data));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        } else {
            // making fresh volley request and getting json
            JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
                    "http://52.89.46.93/churchListAppDump/?methodName=church.list&app_language_name="+a+"", null, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    VolleyLog.d(TAG, "Response: " + response.toString());
                    ;
                    if (response != null) {
                        parseJsonFeed(response);
                    }

                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                }
            });

            // Adding request to volley request queue
            AppController.getInstance().addToRequestQueue(jsonReq);
        }

    }

    private void parseJsonFeed(JSONObject response) {
        try {
            JSONArray feedArray = response.getJSONArray("responseMsg");

            for (int i = 0; i < feedArray.length(); i++) {
                JSONObject feedObj = (JSONObject) feedArray.get(i);

                ChurchNewsFeedItem item = new ChurchNewsFeedItem();
                item.setNews_title(feedObj.getString("church_name"));

                String image = feedObj.isNull("church_image") ? null : feedObj
                        .getString("church_image");
                item.setNews_image(image);
                item.setNews_details(feedObj.getString("admin_id"));

              //  String priya = feedObj.getString("admin_id");

                feedItemschurchnews.add(item);
            }

            // notify data changes to list adapater
            listAdapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public static void deleteCache(Context context) {
        try {
            File dir = context.getCacheDir();
            deleteDir(dir);
        } catch (Exception e) {
        }
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
            return dir.delete();
        } else if (dir != null && dir.isFile()) {
            return dir.delete();
        } else {
            return false;

        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater().inflate(R.menu.menu_search, menu);
        MenuInflater inflater = getMenuInflater();
        // Inflate menu to add items to action bar if it is present.
        inflater.inflate(R.menu.search_main, menu);

        SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView search = (SearchView) menu.findItem(R.id.action_search).getActionView();
        search.setSearchableInfo(manager.getSearchableInfo(getComponentName()));
        search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                PerfromSearch(newText);
                return false;
            }
        });
        return true;
    }

    void PerfromSearch(String query) {

        listAdapter.filter(query);
    }

}

Adapter:

public class ChurchNewsFeedListAdapter extends BaseAdapter
{

    private Activity activity;
    private LayoutInflater inflater;
    Context mContext;
    private List<ChurchNewsFeedItem> churhcnewsfeedItems, churchNewsFeedItemssearched=null;
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    //List<ChurchNewsFeedItem> arraylist;

    public ChurchNewsFeedListAdapter(Activity activity, List<ChurchNewsFeedItem> feedItems,Context context) {
        this.activity = activity;
        this.churhcnewsfeedItems = feedItems;

        this.churchNewsFeedItemssearched = new ArrayList<ChurchNewsFeedItem>();
        this.churchNewsFeedItemssearched.addAll(feedItems);

        // mContext = this;
        this.mContext = context;

    }

    @Override
    public int getCount() {
        return churhcnewsfeedItems.size();
    }

    @Override
    public Object getItem(int location) {
        return churhcnewsfeedItems.get(location);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (inflater == null)
            inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
            convertView = inflater.inflate(R.layout.churchnews_feed_item, null);

        if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();

        TextView newstitle = (TextView) convertView.findViewById(R.id.news_title);

        TextView newdetails = (TextView) convertView
                .findViewById(R.id.news_details);

        ChurchNewsFeedImageView feedImageView = (ChurchNewsFeedImageView) convertView
                .findViewById(R.id.news_feedImage);

        ChurchNewsFeedItem item = churhcnewsfeedItems.get(position);

        newstitle.setText(item.getNews_title());

        // Chcek for empty status message
        if (!TextUtils.isEmpty(item.getNews_details())) {
            newdetails.setText(item.getNews_details());
            newdetails.setVisibility(View.VISIBLE);
        } else {
            // status is empty, remove from view
            newdetails.setVisibility(View.GONE);
        }

        // Feed image
        if (item.getNews_image() != null) {
            feedImageView.setImageUrl(item.getNews_image(), imageLoader);
            feedImageView.setVisibility(View.VISIBLE);
            feedImageView
                    .setResponseObserver(new ChurchNewsFeedImageView.ResponseObserver() {
                        @Override
                        public void onError()
                        {

                        }

                        @Override
                        public void onSuccess() {

                        }
                    });
        } else {
            feedImageView.setVisibility(View.GONE);
        }

        return convertView;
    }

    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());

        Toast.makeText(mContext, "divakar"+churchNewsFeedItemssearched, Toast.LENGTH_SHORT).show();
        churhcnewsfeedItems.clear();
        if (charText.length() == 0) {
            churhcnewsfeedItems.addAll(churchNewsFeedItemssearched);

        } else {

            for (ChurchNewsFeedItem wp : churchNewsFeedItemssearched) {
                if (wp.getNews_title().toLowerCase(Locale.getDefault())
                        .contains(charText)) {
                    churhcnewsfeedItems.add(wp);

                }
            }
        }
        notifyDataSetChanged();
    }
}

Body:
Seems your churchNewsFeedItemssearched list is NULL. Because when you initialize ChurchNewsFeedListAdapter you are passing feedItemschurchnews with 0 items:

listAdapter = new ChurchNewsFeedListAdapter(this, feedItemschurchnews, con);

So, for this your Adapter's constructor works like below:

public ChurchNewsFeedListAdapter(Activity activity, List<ChurchNewsFeedItem> feedItems,Context context) {
    this.activity = activity;
    this.churhcnewsfeedItems = feedItems; // SIZE 0

    this.churchNewsFeedItemssearched = new ArrayList<ChurchNewsFeedItem>();
    this.churchNewsFeedItemssearched.addAll(feedItems); // SIZE 0
}

SOLUTION:

You have to update list churchNewsFeedItemssearched.

Add method updateSearchedList() to your ChurchNewsFeedListAdapter class to update the churchNewsFeedItemssearched and call this method from parseJsonFeed() after adding all items to feedItemschurchnews.

Update your code as below:

ChurchNewsFeedListAdapter:

public void updateSearchedList() {

    churchNewsFeedItemssearched.addAll(churhcnewsfeedItems);
}

Fragment_Church_News:

private void parseJsonFeed(JSONObject response) {

    try {
        JSONArray feedArray = response.getJSONArray("responseMsg");

        for (int i = 0; i < feedArray.length(); i++) {
            JSONObject feedObj = (JSONObject) feedArray.get(i);

            ChurchNewsFeedItem item = new ChurchNewsFeedItem();
            item.setNews_title(feedObj.getString("church_name"));

            String image = feedObj.isNull("church_image") ? null : feedObj
                    .getString("church_image");
            item.setNews_image(image);
            item.setNews_details(feedObj.getString("admin_id"));

            //  String priya = feedObj.getString("admin_id");

            feedItemschurchnews.add(item);
        }

        // Update
        listAdapter.updateSearchedList();

        // notify data changes to list adapater
        listAdapter.notifyDataSetChanged();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

Hope this will work~