问:
Resizing Checkboxes in Windows Universal Application
I have crowded Page in my project and I want to place too many Checkbox control in a single page, so I'm looking for a way to resize my checkboxes.
When I change height and width of my checkbox, some part of its text disappear, In other word I need to scale my checkbox and make some tiny checkbox.

答:
You can of course scale it down by using ScaleTransform but modifying its style gives you more flexibility.

Here's an example -

```<code><Style x:Key="TinyCheckBoxStyle"
               TargetType="CheckBox">
            <Setter Property="Padding"
                    Value="4,0,0,0" />
            <Setter Property="HorizontalContentAlignment"
                    Value="Left" />
            <Setter Property="FontSize"
                    Value="11" />
            <Setter Property="MinWidth"
                    Value="0" />
            <Setter Property="MinHeight"
                    Value="0" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="CheckBox">
                        <Grid x:Name="RootGrid"
                              BorderBrush="{TemplateBinding BorderBrush}"
                              BorderThickness="{TemplateBinding BorderThickness}"
                              Background="{TemplateBinding Background}">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto" />
                                <ColumnDefinition Width="*" />
                            </Grid.ColumnDefinitions>

                            <VisualStateManager.VisualStateGroups>
                                <!-- Add default visual states back in here -->
                            </VisualStateManager.VisualStateGroups>

                            <Grid>
                                <Rectangle x:Name="NormalRectangle"
                                           Fill="{ThemeResource CheckBoxCheckBackgroundFillUnchecked}"
                                           Height="12"
                                           Stroke="{ThemeResource CheckBoxCheckBackgroundStrokeUnchecked}"
                                           StrokeThickness="{ThemeResource CheckBoxBorderThemeThickness}"
                                           UseLayoutRounding="False"
                                           Width="12" />
                                <FontIcon x:Name="CheckGlyph"
                                          Foreground="{ThemeResource CheckBoxCheckGlyphForegroundUnchecked}"
                                          FontSize="{TemplateBinding FontSize}"
                                          FontFamily="{ThemeResource SymbolThemeFontFamily}"
                                          Glyph=""
                                          Opacity="0" />
                            </Grid>
                            <ContentPresenter x:Name="ContentPresenter"
                                              AutomationProperties.AccessibilityView="Raw"
                                              ContentTemplate="{TemplateBinding ContentTemplate}"
                                              ContentTransitions="{TemplateBinding ContentTransitions}"
                                              Content="{TemplateBinding Content}"
                                              Grid.Column="1"
                                              HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                              Margin="{TemplateBinding Padding}"
                                              TextWrapping="Wrap"
                                              VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
</code>```

Basically, you need to reduce the size of NormalRectangle, CheckGlyph and the FontSize. Note I have removed the visual states to simplify the answer, you just need to add them back from the default style.

Body:
You can of course scale it down by using ScaleTransform but modifying its style gives you more flexibility.

Here's an example -

<Style x:Key="TinyCheckBoxStyle"
               TargetType="CheckBox">
            <Setter Property="Padding"
                    Value="4,0,0,0" />
            <Setter Property="HorizontalContentAlignment"
                    Value="Left" />
            <Setter Property="FontSize"
                    Value="11" />
            <Setter Property="MinWidth"
                    Value="0" />
            <Setter Property="MinHeight"
                    Value="0" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="CheckBox">
                        <Grid x:Name="RootGrid"
                              BorderBrush="{TemplateBinding BorderBrush}"
                              BorderThickness="{TemplateBinding BorderThickness}"
                              Background="{TemplateBinding Background}">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto" />
                                <ColumnDefinition Width="*" />
                            </Grid.ColumnDefinitions>

                            <VisualStateManager.VisualStateGroups>
                                <!-- Add default visual states back in here -->
                            </VisualStateManager.VisualStateGroups>

                            <Grid>
                                <Rectangle x:Name="NormalRectangle"
                                           Fill="{ThemeResource CheckBoxCheckBackgroundFillUnchecked}"
                                           Height="12"
                                           Stroke="{ThemeResource CheckBoxCheckBackgroundStrokeUnchecked}"
                                           StrokeThickness="{ThemeResource CheckBoxBorderThemeThickness}"
                                           UseLayoutRounding="False"
                                           Width="12" />
                                <FontIcon x:Name="CheckGlyph"
                                          Foreground="{ThemeResource CheckBoxCheckGlyphForegroundUnchecked}"
                                          FontSize="{TemplateBinding FontSize}"
                                          FontFamily="{ThemeResource SymbolThemeFontFamily}"
                                          Glyph="&#xE001;"
                                          Opacity="0" />
                            </Grid>
                            <ContentPresenter x:Name="ContentPresenter"
                                              AutomationProperties.AccessibilityView="Raw"
                                              ContentTemplate="{TemplateBinding ContentTemplate}"
                                              ContentTransitions="{TemplateBinding ContentTransitions}"
                                              Content="{TemplateBinding Content}"
                                              Grid.Column="1"
                                              HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                              Margin="{TemplateBinding Padding}"
                                              TextWrapping="Wrap"
                                              VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

Basically, you need to reduce the size of NormalRectangle, CheckGlyph and the FontSize. Note I have removed the visual states to simplify the answer, you just need to add them back from the default style.


来源: stackexchange

问:
AJAX form submit to PHP not returning correct data
I have a form that I would like to send data from to a php script using AJAX. However I am running into an issue with actually passing the data across. The $_POST array is empty for some reason.

Currently the HTML is:

```<code><form>
    <label>Email Address:</label>
    <input type='text' name='email' value='jackc@test.com'/>
    <input type='submit' name='submit' value='Check subscription status'/>
</form>
</code>```

The JQuery is:

```<code> $(document).ready(function() {
        $('form').submit(function(e){
            e.preventDefault();
            var url = 'request.php';
            $.ajax({
                type: 'POST',
                url: url,
                contentType: "json",
                data: $('form').serialize(),
                success: function(data){
                    console.log(data);
                    $('#results').html(data);
                }
            });

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

The PHP is:

```<code>        $emailAddress = $_POST['email'];
        echo "EMAIL: " . $emailAddress;
</code>```

However it's not returning anything. It's blank each time. When I do a console log for $('form').serialize() I see email=jackc%40@test.com which I would expect to see returned from my PHP.

I'd appreciate some help on this. Many thanks.

答:
test this :</p>

```<code>$('form').submit(function(e){
            e.preventDefault();
            var url = 'request.php';
            var $form = $(this);
            var request ={
                email : $form.find("[name=email]").val(),
            };
            $.ajax({
                type: 'POST',
                url: url,
                data: request,
                success: function(data){
                    console.log(data);
                    $('#results').html(data);
                }
            });
        });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a form that I would like to send data from to a php script using AJAX. However I am running into an issue with actually passing the data across. The $_POST array is empty for some reason.

Currently the HTML is:

<form>
    Email Address:
    <input type='text' name='email' value='jackc@test.com'/>
    <input type='submit' name='submit' value='Check subscription status'/>
</form>

The JQuery is:

 $(document).ready(function() {
        $('form').submit(function(e){
            e.preventDefault();
            var url = 'request.php';
            $.ajax({
                type: 'POST',
                url: url,
                contentType: "json",
                data: $('form').serialize(),
                success: function(data){
                    console.log(data);
                    $('#results').html(data);
                }
            });

        });
    });

The PHP is:

        $emailAddress = $_POST['email'];
        echo "EMAIL: " . $emailAddress;

However it's not returning anything. It's blank each time. When I do a console log for $('form').serialize() I see email=jackc%40@test.com which I would expect to see returned from my PHP.

I'd appreciate some help on this. Many thanks.

Body:
test this :

$('form').submit(function(e){
            e.preventDefault();
            var url = 'request.php';
            var $form = $(this);
            var request ={
                email : $form.find("[name=email]").val(),
            };
            $.ajax({
                type: 'POST',
                url: url,
                data: request,
                success: function(data){
                    console.log(data);
                    $('#results').html(data);
                }
            });
        });


问:
android comparing dates I couldn't compare two dates...I referred many tutorials
I am using the datepicker dialog and am trying to compare the  current date  with the date specified in the dialog.
if the date is before the current date I wish to display invalid date.

Both current date and date entered are in same format. but I am getting error. when printing in console both current date and entered date are coming the the same format

```<code>if(date1.before(currDate))
{
     Toast.makeText(getApplicationContext(), "Enter the valid Date", Toast.LENGTH_LONG).show();
}
</code>```

result:

current date 5/7/2017

picked date 5-7-2017

答:
You can try like this,</p>

```<code>try {
    String currentDateString = "5/7/2017";
    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");

    Date currDate = formatter.parse(currentDateString);

    String pickDateString = "5-7-2017";
    formatter = new SimpleDateFormat("dd-MM-yyyy");

    Date pickDate = formatter.parse(pickDateString);

    if (pickDate.before(currDate)) {
        Toast.makeText(getApplicationContext(), "Enter the valid Date", Toast.LENGTH_LONG).show();
    }
} catch (ParseException e) {
    e.printStackTrace();
}
</code>```

Body:
I am using the datepicker dialog and am trying to compare the  current date  with the date specified in the dialog.
if the date is before the current date I wish to display invalid date.

Both current date and date entered are in same format. but I am getting error. when printing in console both current date and entered date are coming the the same format

if(date1.before(currDate))
{
     Toast.makeText(getApplicationContext(), "Enter the valid Date", Toast.LENGTH_LONG).show();
}

result:

current date 5/7/2017

picked date 5-7-2017

Body:
You can try like this,

try {
    String currentDateString = "5/7/2017";
    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");

    Date currDate = formatter.parse(currentDateString);

    String pickDateString = "5-7-2017";
    formatter = new SimpleDateFormat("dd-MM-yyyy");

    Date pickDate = formatter.parse(pickDateString);

    if (pickDate.before(currDate)) {
        Toast.makeText(getApplicationContext(), "Enter the valid Date", Toast.LENGTH_LONG).show();
    }
} catch (ParseException e) {
    e.printStackTrace();
}


问:
How to make UITableView ignore UINavigationController
So I have this screen:

Current TableViewController

This image is a subview of a UIView, which I use as a header for a table:

```<code>class CoursesDetailPageHeader: UITableViewHeaderFooterView {

    @IBOutlet weak var imageView: UIImageView!

    override func awakeFromNib() {
        super.awakeFromNib()

        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
    }

    func setDefaultImage() {
        imageView.image = UIImage(named: "header")
    }
}
</code>```

And my tableView:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    let headerNib = UINib(nibName: "CoursesDetailPageHeader", bundle: nil)
    tableView.register(headerNib, forHeaderFooterViewReuseIdentifier: "pageHeader")
}

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 220
}

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let pageHeader = tableView.dequeueReusableHeaderFooterView(withIdentifier: "pageHeader") as! CoursesDetailPageHeader
    pageHeader.setDefaultImage()

    return pageHeader
}
</code>```

What should I do, to bring the tableView to the top, so that there is no empty space (where the transparent navController)?

UPD:
To show what I want to have:
Desired TableViewController

SOLVED:
Thank to @kathayatnk issue was solved with the following code:

```<code>let statusBarHeight = UIApplication.shared.statusBarFrame.height
let navigationBarHeight = navigationController!.navigationBar.frame.size.height
let insets = UIEdgeInsets(top: -(statusBarHeight + navigationBarHeight), left: 0, bottom: 0, right: 0)
self.tableView.contentInset = insets
</code>```

答:
For this you have to do UINavigationBar Translucent

AppDelegate.swift

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    UINavigationBar.appearance().isTranslucent = true
    UINavigationBar.appearance().shadowImage = UIImage()
    UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)

    return true
}
</code>```

Body:
So I have this screen:

Current TableViewController

This image is a subview of a UIView, which I use as a header for a table:

class CoursesDetailPageHeader: UITableViewHeaderFooterView {

    @IBOutlet weak var imageView: UIImageView!

    override func awakeFromNib() {
        super.awakeFromNib()

        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
    }

    func setDefaultImage() {
        imageView.image = UIImage(named: "header")
    }
}

And my tableView:

override func viewDidLoad() {
    super.viewDidLoad()

    let headerNib = UINib(nibName: "CoursesDetailPageHeader", bundle: nil)
    tableView.register(headerNib, forHeaderFooterViewReuseIdentifier: "pageHeader")
}

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 220
}

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let pageHeader = tableView.dequeueReusableHeaderFooterView(withIdentifier: "pageHeader") as! CoursesDetailPageHeader
    pageHeader.setDefaultImage()

    return pageHeader
}

What should I do, to bring the tableView to the top, so that there is no empty space (where the transparent navController)?

UPD:
To show what I want to have:
Desired TableViewController

SOLVED:
Thank to @kathayatnk issue was solved with the following code:

let statusBarHeight = UIApplication.shared.statusBarFrame.height
let navigationBarHeight = navigationController!.navigationBar.frame.size.height
let insets = UIEdgeInsets(top: -(statusBarHeight + navigationBarHeight), left: 0, bottom: 0, right: 0)
self.tableView.contentInset = insets

Body:
For this you have to do UINavigationBar Translucent

AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    UINavigationBar.appearance().isTranslucent = true
    UINavigationBar.appearance().shadowImage = UIImage()
    UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)

    return true
}


问:
Are infinite lists useful for any real world applications?
I've been using haskell for quite a while now, and I've read most of Real World Haskell and Learn You a Haskell. What I want to know is whether there is a point to a language using lazy evaluation, in particular the "advantage" of having infinite lists, is there a task which infinite lists make very easy, or even a task that is only possible with infinite lists?</p>

答:
Infinite/lazy structures permit the idiom of "tying the knot": http://www.haskell.org/haskellwiki/Tying_the_Knot

The canonically simple example of this is the Fibonacci sequence, defined directly as a recurrence relation. (Yes, yes, hold the efficiency complaints/algorithms discussion -- the point is the idiom.): fibs = 1:1:zipwith (+) fibs (tail fibs)

Here's another story. I had some code that only worked with finite streams -- it did some things to create them out to a point, then did a whole bunch of nonsense that involved acting on various bits of the stream dependent on the entire stream prior to that point, merging it with information from another stream, etc. It was pretty nice, but I realized it had a whole bunch of cruft necessary for dealing with boundary conditions, and basically what to do when one stream ran out of stuff. I then realized that conceptually, there was no reason it couldn't work on infinite streams. So I switched to a data type without a nil -- i.e. a genuine stream as opposed to a list, and all the cruft went away. Even though I know I'll never need the data past a certain point, being able to rely on it being there allowed me to safely remove lots of silly logic, and let the mathematical/algorithmic part of my code stand out more clearly.

ContentLicense: CC BY-SA 2.5


问:
Firebase Database retrieve delay
I have an app that registers a username and some other info from the user, But when I try to load the users info in his/her profile in onCreateView() there is a little delay for 3.5 seconds. Is there any efficient and reliable way when retrieving a users data from Firebase and adding it to a TextView or some any other views?

Here is what I have done so far, I am using a Fragment

```<code>@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment, container, false);
    //Some views initialized here

    FirebaseUser user = FirebaseAuth.getInstance()
            .getCurrentUser();
    DatabaseReference ref= FirebaseDatabase.getInstance()
            .getReference();
    ref.child(path)
            .child(user.getUid())
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    init(dataSnapshot);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                   Log.e(TAG, "onCancelled " + databaseError.getMessage());
                }
            });

    return view;
}
</code>```

答: you can activate the firebase offline for the user data FirebaseDatabase.getInstance().setPersistenceEnabled(true); but you must be careful cause if the auth token expires while your app is offline, the client pauses write operations until your app re-authenticates the user, otherwise the write operations might fail due to security rules. check the documentation

Title: Firebase Database retrieve delay

Body:
I have an app that registers a username and some other info from the user, But when I try to load the users info in his/her profile in onCreateView() there is a little delay for 3.5 seconds. Is there any efficient and reliable way when retrieving a users data from Firebase and adding it to a TextView or some any other views?

Here is what I have done so far, I am using a Fragment

@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment, container, false);
    //Some views initialized here

    FirebaseUser user = FirebaseAuth.getInstance()
            .getCurrentUser();
    DatabaseReference ref= FirebaseDatabase.getInstance()
            .getReference();
    ref.child(path)
            .child(user.getUid())
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    init(dataSnapshot);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                   Log.e(TAG, "onCancelled " + databaseError.getMessage());
                }
            });

    return view;
}


问:
Microsoft One Drive solution for Files and Folders - Around 300 Systems
I need Files and Folders backup of 300 Windows 8+ System. I opted One Drive Solution. So do i need to buy 300 License of One Drive for Business or Can i buy 1 license and can create and share 300 folders for each person?

In any of the option, the user can upload data to their space but admin can see all the folders.

答:
You can map your OneDrive as a shared Drive on each machine. But in this case all data can be overlooked by administrator. Yes, like you said.

Have a look at OneDrive For Business probably. They have a licensing model per user. From security perspective this is much better for you.


问:
issues with reading data from csv
I am working on a code in c that needs to read csv data and enter it into a structure.  Admittedly I both am more familiar with c++ and haven't done much with reading from files before so I could be missing something really obvious.  But when I check the structure array after it supposedly loaded the data, I get the right number of lines but all but the second one are blank- and that one for some reason just has a smiley face...

Here is my code:

```<code>void load_items(){
char file_name[20], buffer[MAX_LINE_LENGTH];
FILE *file;
int i;

printf("Enter the file to load data from: ");       //data.csv for here
scanf("%s", file_name);

file=fopen(file_name,"r");

if(file==NULL)
{
    printf("Can't open %s\n",file_name);
    //exit(EXIT_FAILURE);
}
else {
    printf("Congrats! you opened %s as your data source!\n", file_name);        //test to make sure opened file
    while((fgets(buffer, sizeof(buffer),file)) !=NULL)          //while the line isn't blank
    {
        scanf(buffer,"%s,%s,%d,%d",&places[i].name,&places[i].category,&places[i].x,&places[i].y);      //enter data into proper place
        printf("|%-23s|%-20s\t| ( %d, %d) |\n",places[i].name, places[i].category, places[i].x,places[i].y);    //test to see data
        i++;
    }
}
fclose(file);
}
</code>```

Here is what the info it is reading from looks like:

```<code>STARBUCKS COFFEE,cafeteria,7,11
Restaurant UNIVERSAL CLUB,cafeteria,18,16
PHONON CAFE ROOM,cafeteria,7,12
Craig's Cafe SEATTLE ESPRESS,cafeteria,18,11
Cafeteria NANAMI-TEI,cafeteria,11,7
IB Cafe,cafeteria,11,9
Restaurant Chez Jiroud,cafeteria,15,10
Labo Shop (NU CO-OP Shop),shop,29,19
NU CO-OP North,shop,11,5
Family Mart,shop,13,11
South Cafeteria,cafeteria,4,17
NU CO-OP South,shop,5,17
Amenity House,shop,6,17
FOREST Books & Cafe,cafeteria,19,7
Green Salon Higashiyama,cafeteria,21,8
Toyoda Auditorium / Symposion,Convention facility,17,15
Noyori Conference Hall,Convention facility,21,14
E & S Hall,Convention facility,16,9
Sakata & Hirata Hall,Convention facility,19,11
</code>```

And here is what I am actually getting:

```<code>|                       |                       | ( 0, 0) |
|☺                      |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
</code>```

If it wasn't for that weird smiley I would think it just wasn't reading anything, or not transfering it into the struct right, but as it is I am baffeled.  Any advice would be very welcome, thank you for your time!

答:
Try fscanf to read from file instead of scanf and also use %[^,](read all except ',') instead of %s.

Codesnip: while(fscanf(file, "%[^,],%[^,],%d,%d", &places[i].name, &places[i].category, &places[i].x, &places[i].y) == 4)

Title: issues with reading data from csv

Body:
I am working on a code in c that needs to read csv data and enter it into a structure.  Admittedly I both am more familiar with c++ and haven't done much with reading from files before so I could be missing something really obvious.  But when I check the structure array after it supposedly loaded the data, I get the right number of lines but all but the second one are blank- and that one for some reason just has a smiley face...

Here is my code:

void load_items(){
char file_name[20], buffer[MAX_LINE_LENGTH];
FILE *file;
int i;

printf("Enter the file to load data from: ");       //data.csv for here
scanf("%s", file_name);

file=fopen(file_name,"r");

if(file==NULL)
{
    printf("Can't open %s\n",file_name);
    //exit(EXIT_FAILURE);
}
else {
    printf("Congrats! you opened %s as your data source!\n", file_name);        //test to make sure opened file
    while((fgets(buffer, sizeof(buffer),file)) !=NULL)          //while the line isn't blank
    {
        scanf(buffer,"%s,%s,%d,%d",&places[i].name,&places[i].category,&places[i].x,&places[i].y);      //enter data into proper place
        printf("|%-23s|%-20s\t| ( %d, %d) |\n",places[i].name, places[i].category, places[i].x,places[i].y);    //test to see data
        i++;
    }
}
fclose(file);
}

Here is what the info it is reading from looks like:

STARBUCKS COFFEE,cafeteria,7,11
Restaurant UNIVERSAL CLUB,cafeteria,18,16
PHONON CAFE ROOM,cafeteria,7,12
Craig's Cafe SEATTLE ESPRESS,cafeteria,18,11
Cafeteria NANAMI-TEI,cafeteria,11,7
IB Cafe,cafeteria,11,9
Restaurant Chez Jiroud,cafeteria,15,10
Labo Shop (NU CO-OP Shop),shop,29,19
NU CO-OP North,shop,11,5
Family Mart,shop,13,11
South Cafeteria,cafeteria,4,17
NU CO-OP South,shop,5,17
Amenity House,shop,6,17
FOREST Books & Cafe,cafeteria,19,7
Green Salon Higashiyama,cafeteria,21,8
Toyoda Auditorium / Symposion,Convention facility,17,15
Noyori Conference Hall,Convention facility,21,14
E & S Hall,Convention facility,16,9
Sakata & Hirata Hall,Convention facility,19,11

And here is what I am actually getting:

|                       |                       | ( 0, 0) |
|☺                      |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |
|                       |                       | ( 0, 0) |

If it wasn't for that weird smiley I would think it just wasn't reading anything, or not transfering it into the struct right, but as it is I am baffeled.  Any advice would be very welcome, thank you for your time!


问:
Create web service using Eclipse
I am trying to create my first webservice using eclipse javaEE under Axis2,
i am following this turorial eclipse tutorial
 to learn how to make it.I make the webservice but when i want to assure that the ws has been deployed through viewing it through URL, an HTTP status 400 occure. How can I know what is the error??
here what i make exactly:

i make the settings in preferences [ ant , axis2, tomcat and java ].

New -> New dynamic web page

new ->java (I create the class i want to convert to ws)

new ->web service (i want to create  bottom up ws).

type http://localhost:8080/Axis2/services/listservices in the url of browser

this what return HTTP Status 404 - /services/listservices

can some one tell me how can i know what is the error? or how can i define it?

EDIT:
an exception happen in the console of eclipse which is :

```<code>org.apache.axis2.transport.http.AxisAdminServlet java.lang.ClassNotFoundException: org.apache.axis2.transport.http.AxisAdminServlet
</code>```

what should I do ,in the configuration i specify where is axis2 and eclipse shows

```<code>Axis2 runtime loaded successfully
</code>```

after creating new work space and create webservice again, this is the output appears in console

```<code> Dec 20, 2010 8:32:04 PM org.apache.catalina.core.AprLifecycleListener init
 INFO: The APR based Apache Tomcat Native library which allows optimal performance in
production environments was not found on the java.library.path: C:\Program
 Files\Java\jdk1.6.0_18\bin;.;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;F:/alaa college/year 4/1st
 semester/Advance sw/Libraries/eclipse/jre/bin/client;F:/alaa college/year 4/1st
semester/Advance sw/Libraries/eclipse/jre/bin;D:\app\AloOoSh\product\11.1.0\db_1\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Java\jdk1.6.0_18\bin;%ANT_HOME%\bin;%AXIS2_HOME%\bin;%CATALINA_HOME%\bin;C:\Program Files\MATLAB\R2008a\bin;C:\Program Files\MATLAB\R2008a\bin\win32;
Dec 20, 2010 8:32:05 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source'
to 'org.eclipse.jst.jee.server:testFirst' did not find a matching property.
 Dec 20, 2010 8:32:05 PM org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8080
Dec 20, 2010 8:32:05 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 401 ms
Dec 20, 2010 8:32:05 PM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina

Dec 20, 2010 8:32:05 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.29
[INFO] Deploying module: addressing-1.4 -     file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testF
 irst/WEB-INF/modules/addressing-1.4.mar
[INFO] Deploying module: metadataExchange-1.4 -
 file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/modules/mex-1.4.mar
 [INFO] Deploying module: ping-1.4 -
 file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/modules/ping-1.4.mar
 [INFO] Deploying module: script-1.4 -  file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/modules/scripting-1.4.mar
 [INFO] Deploying module: smtpfault - file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/modules/smtpfault.mar
[INFO] Deploying module: soapmonitor-1.4 - file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/modules/soapmonitor-1.4.mar
 [INFO] Deploying Web service: Converter - file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/services/Converter/
[INFO] Deploying Web service: version.aar - file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/services/version.aar
 Dec 20, 2010 8:32:06 PM org.apache.coyote.http11.Http11Protocol start
 INFO: Starting Coyote HTTP/1.1 on http-8080
 Dec 20, 2010 8:32:06 PM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
Dec 20, 2010 8:32:06 PM org.apache.jk.server.JkMain start
 INFO: Jk running ID=0 time=0/19  config=null
Dec 20, 2010 8:32:06 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1383 ms
</code>```

答:
The 404 error occurs because there is nothing at the desired url.  So there must have been something wrong with your deployment.

Have you set up a server in eclipse and actually published the WS at all?  Note that this is different from running Tomcat from a directory somewhere else on your computer!  You can add a server instance by selecting New => Server.

If the server configuration is otherwise correct, the server output should appear in eclipse's console, and if anything is wrong with your WS setup, there should be error messages you can use to track down the problem.

Title: Create web service using Eclipse

Body:
I am trying to create my first webservice using eclipse javaEE under Axis2,
i am following this turorial eclipse tutorial
 to learn how to make it.I make the webservice but when i want to assure that the ws has been deployed through viewing it through URL, an HTTP status 400 occure. How can I know what is the error??
here what i make exactly:

i make the settings in preferences [ ant , axis2, tomcat and java ].

New -> New dynamic web page

new ->java (I create the class i want to convert to ws)

new ->web service (i want to create  bottom up ws).

type http://localhost:8080/Axis2/services/listservices in the url of browser

this what return HTTP Status 404 - /services/listservices

can some one tell me how can i know what is the error? or how can i define it?

EDIT:
an exception happen in the console of eclipse which is :

org.apache.axis2.transport.http.AxisAdminServlet java.lang.ClassNotFoundException: org.apache.axis2.transport.http.AxisAdminServlet

what should I do ,in the configuration i specify where is axis2 and eclipse shows

Axis2 runtime loaded successfully

after creating new work space and create webservice again, this is the output appears in console

 Dec 20, 2010 8:32:04 PM org.apache.catalina.core.AprLifecycleListener init
 INFO: The APR based Apache Tomcat Native library which allows optimal performance in
production environments was not found on the java.library.path: C:\Program
 Files\Java\jdk1.6.0_18\bin;.;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;F:/alaa college/year 4/1st
 semester/Advance sw/Libraries/eclipse/jre/bin/client;F:/alaa college/year 4/1st
semester/Advance sw/Libraries/eclipse/jre/bin;D:\app\AloOoSh\product\11.1.0\db_1\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Java\jdk1.6.0_18\bin;%ANT_HOME%\bin;%AXIS2_HOME%\bin;%CATALINA_HOME%\bin;C:\Program Files\MATLAB\R2008a\bin;C:\Program Files\MATLAB\R2008a\bin\win32;
Dec 20, 2010 8:32:05 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source'
to 'org.eclipse.jst.jee.server:testFirst' did not find a matching property.
 Dec 20, 2010 8:32:05 PM org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8080
Dec 20, 2010 8:32:05 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 401 ms
Dec 20, 2010 8:32:05 PM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina

Dec 20, 2010 8:32:05 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.29
[INFO] Deploying module: addressing-1.4 -     file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testF
 irst/WEB-INF/modules/addressing-1.4.mar
[INFO] Deploying module: metadataExchange-1.4 -
 file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/modules/mex-1.4.mar
 [INFO] Deploying module: ping-1.4 -
 file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/modules/ping-1.4.mar
 [INFO] Deploying module: script-1.4 -  file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/modules/scripting-1.4.mar
 [INFO] Deploying module: smtpfault - file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/modules/smtpfault.mar
[INFO] Deploying module: soapmonitor-1.4 - file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/modules/soapmonitor-1.4.mar
 [INFO] Deploying Web service: Converter - file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/services/Converter/
[INFO] Deploying Web service: version.aar - file:/D:/EclipseExcercises/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/testFirst/WEB-INF/services/version.aar
 Dec 20, 2010 8:32:06 PM org.apache.coyote.http11.Http11Protocol start
 INFO: Starting Coyote HTTP/1.1 on http-8080
 Dec 20, 2010 8:32:06 PM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
Dec 20, 2010 8:32:06 PM org.apache.jk.server.JkMain start
 INFO: Jk running ID=0 time=0/19  config=null
Dec 20, 2010 8:32:06 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1383 ms


问:
Best way to understand complex SQL statements?
Does anyone have a method to understand complex SQL statements?  When reading structural / OO code there are usually layers of abstraction that help you break it down into manageable chunks.  Often in SQL, though, it seems that you have to keep track of what's going on in multiple parts of a query all at the same time.

The impetus for this question is the SQL query discussed in this question about a complex join.  After staring at the answer queries for a number of minutes I finally decided to step through the query using particular records to see what was going on.  That was the only way I could think of to understand the query piece by piece.

Is there a better way to break a SQL query down into manageable pieces?

答:
I find going back to the logical query processing phases and unpicking the query bit by bit with sample data is often helpful.

(The following is borrowed from Inside Microsoft SQL Server 2005: T-SQL Querying, by Itzik Ben-Gan.)

```<code>(8) SELECT (9) DISTINCT (11) <TOP_specification> <select_list>
(1) FROM <left_table>
(3) <join_type> JOIN <right_table>
(2) ON <join_condition>
(4) WHERE <where_condition>
(5) GROUP BY <group_by_list>
(6) WITH {CUBE | ROLLUP}
(7) HAVING <having_condition>
(10) ORDER BY <order_by_list>
</code>```

FROM: A Cartesian product (cross join) is performed between the first two tables in the
FROM clause, and as a result, virtual table VT1 is generated.

ON: The ON filter is applied to VT1. Only rows for which the  is TRUE
are inserted to VT2.

OUTER (join): If an OUTER JOIN is specified (as opposed to a CROSS JOIN or an
INNER JOIN), rows from the preserved table or tables for which a match was not found
are added to the rows from VT2 as outer rows, generating VT3. If more than two tables
appear in the FROM clause, steps 1 through 3 are applied repeatedly between the result
of the last join and the next table in the FROM clause until all tables are processed.

WHERE: The WHERE filter is applied to VT3. Only rows for which the
is TRUE are inserted to VT4.

GROUP BY: The rows from VT4 are arranged in groups based on the column list specified
in the GROUP BY clause. VT5 is generated.

CUBE | ROLLUP: Supergroups (groups of groups) are added to the rows from VT5,
generating VT6.

HAVING: The HAVING filter is applied to VT6. Only groups for which the
 is TRUE are inserted to VT7.

SELECT: The SELECT list is processed, generating VT8.

DISTINCT: Duplicate rows are removed from VT8. VT9 is generated.

ORDER BY: The rows from VT9 are sorted according to the column list specified in the
ORDER BY clause. A cursor is generated (VC10).

TOP: The specified number or percentage of rows is selected from the beginning of
VC10. Table VT11 is generated and returned to the caller.

OwnerDisplayName: Eric Ness

Body:
I find going back to the logical query processing phases and unpicking the query bit by bit with sample data is often helpful.

(The following is borrowed from Inside Microsoft SQL Server 2005: T-SQL Querying, by Itzik Ben-Gan.)

(8) SELECT (9) DISTINCT (11) <TOP_specification> <select_list>
(1) FROM <left_table>
(3) <join_type> JOIN <right_table>
(2) ON <join_condition>
(4) WHERE <where_condition>
(5) GROUP BY <group_by_list>
(6) WITH {CUBE | ROLLUP}
(7) HAVING <having_condition>
(10) ORDER BY <order_by_list>

FROM: A Cartesian product (cross join) is performed between the first two tables in the
FROM clause, and as a result, virtual table VT1 is generated.

ON: The ON filter is applied to VT1. Only rows for which the  is TRUE
are inserted to VT2.

OUTER (join): If an OUTER JOIN is specified (as opposed to a CROSS JOIN or an
INNER JOIN), rows from the preserved table or tables for which a match was not found
are added to the rows from VT2 as outer rows, generating VT3. If more than two tables
appear in the FROM clause, steps 1 through 3 are applied repeatedly between the result
of the last join and the next table in the FROM clause until all tables are processed.

WHERE: The WHERE filter is applied to VT3. Only rows for which the
is TRUE are inserted to VT4.

GROUP BY: The rows from VT4 are arranged in groups based on the column list specified
in the GROUP BY clause. VT5 is generated.

CUBE | ROLLUP: Supergroups (groups of groups) are added to the rows from VT5,
generating VT6.

HAVING: The HAVING filter is applied to VT6. Only groups for which the
 is TRUE are inserted to VT7.

SELECT: The SELECT list is processed, generating VT8.

DISTINCT: Duplicate rows are removed from VT8. VT9 is generated.

ORDER BY: The rows from VT9 are sorted according to the column list specified in the
ORDER BY clause. A cursor is generated (VC10).

TOP: The specified number or percentage of rows is selected from the beginning of
VC10. Table VT11 is generated and returned to the caller.

ContentLicense: CC BY-SA 4.0


问:
Create a User and ExtendedUser object in one form using an Inline formset?
I have a model Sachbearbeiter which extends my User model.

```<code>from django.contrib.auth.models import User

class Sachbearbeiter(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    verein = models.ForeignKey(Verein)
</code>```

Now I need CreateView form to create a new Sachbearbeiter instance that is immediately linked to a new User instance.

The form should have the following fields:

```<code>First Name:    [textfield]
Last Name:     [textfield]
Email Address: [textfield]
Verein:        [Dropdown that lists `Vereine`]
</code>```

What I tried is this:

```<code>class SachbearbeiterForm(ModelForm):
    class Meta:
        model = Sachbearbeiter
        fields = '__all__'  # Go into detail once it's working

class UserForm(ModelForm):
    class Meta:
        model = User
        fields = '__all__'  # Go into detail once it's working

SachbearbeiterFormSet = inlineformset_factory(User, Sachbearbeiter, fields='__all__')

class SachbearbeiterCreate(CreateView):
    form_class = SachbearbeiterFormSet
</code>```

But this gives me a form that looks like this:

```<code>Verein:        [Dropdown that lists `Vereine`]
Delete?        [checkbox]
</code>```

Is this even possible, or do I have to create a custom form for that?

答:
This is not the solution I was looking for, but works well. Because of that, I won't mark it as an answer, though.

I had to create a custom view and was able to simply use both forms inside it. (In the code example I omitted the unimportant stuff.

In the ModelForms I only changed the fields attribute to have only the fields I want to show.

```<code>def my_view(request):
    ...
    if request.method == 'POST':
        if user_form.is_valid() and sachbearbeiter_form.is_valid():
            user = user_form.save(commit=False)
            user.username = user.email
            user.save()
            sachbearbeiter = sachbearbeiter_form.save(commit=False)
            sachbearbeiter.user = user
            sachbearbeiter.save()
    ...
    return redirect('sachbearbeiter_create_or_edit', username=user.username)
</code>```

The template looks something like that:

```<code>{% if user_form.errors or sachbearbeiter_form.errors %}
    <div class="alert alert-danger" role="alert">
        Please correct the errors indicated by red color.
    </div>
{% endif %}

<form method="post" action="#">
{{ user_form.as_p }}
{{ sachbearbeiter_form.as_p }}
</form>
</code>```

Body:
I have a model Sachbearbeiter which extends my User model.

from django.contrib.auth.models import User

class Sachbearbeiter(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    verein = models.ForeignKey(Verein)

Now I need CreateView form to create a new Sachbearbeiter instance that is immediately linked to a new User instance.

The form should have the following fields:

First Name:    [textfield]
Last Name:     [textfield]
Email Address: [textfield]
Verein:        [Dropdown that lists `Vereine`]

What I tried is this:

class SachbearbeiterForm(ModelForm):
    class Meta:
        model = Sachbearbeiter
        fields = '__all__'  # Go into detail once it's working

class UserForm(ModelForm):
    class Meta:
        model = User
        fields = '__all__'  # Go into detail once it's working

SachbearbeiterFormSet = inlineformset_factory(User, Sachbearbeiter, fields='__all__')

class SachbearbeiterCreate(CreateView):
    form_class = SachbearbeiterFormSet

But this gives me a form that looks like this:

Verein:        [Dropdown that lists `Vereine`]
Delete?        [checkbox]

Is this even possible, or do I have to create a custom form for that?

Body:
This is not the solution I was looking for, but works well. Because of that, I won't mark it as an answer, though.

I had to create a custom view and was able to simply use both forms inside it. (In the code example I omitted the unimportant stuff.

In the ModelForms I only changed the fields attribute to have only the fields I want to show.

def my_view(request):
    ...
    if request.method == 'POST':
        if user_form.is_valid() and sachbearbeiter_form.is_valid():
            user = user_form.save(commit=False)
            user.username = user.email
            user.save()
            sachbearbeiter = sachbearbeiter_form.save(commit=False)
            sachbearbeiter.user = user
            sachbearbeiter.save()
    ...
    return redirect('sachbearbeiter_create_or_edit', username=user.username)

The template looks something like that:

{% if user_form.errors or sachbearbeiter_form.errors %}
    <div class="alert alert-danger" role="alert">
        Please correct the errors indicated by red color.
    </div>
{% endif %}

<form method="post" action="#">
{{ user_form.as_p }}
{{ sachbearbeiter_form.as_p }}
</form>


答: you don't send json data so you need to remove the "contentType" from the ajax request.</p>

Title: AJAX form submit to PHP not returning correct data


问:
How to use correctly Myanmar font in SQL 'where' clause?
select * from item where Item_type like 'ဆဆဆ';
This is the data that I want to retrieve using Myanmar font</p>

答:
Select * from item where Item_type like N'ဆဆဆ';

The data type is nvarchar type so ! Sorry for my bad language.


问:
WPF close secondary window before main window
I have 2 windows in a WPF application, and If I close the Main one, I want to close the other too.

I achieved this by setting in my App.xaml:

```<code>ShutdownMode="OnMainWindowClose"
</code>```

The 2 windows have a Window_Closing event in which I de-initialise some components. Now what I want to achieve is: if I close the MainWindow, the Window_Closing event of the second window must execute before the closing event of the Main one, because the de-init of the second one has to be executed before the first. Any idea on how can I achive this?

答:
Close all windows but the MainWindow in the Closing event handler. This should work:

```<code>void MainWindow_Closing(object sender, CancelEventArgs e)
{
    foreach (Window w in Application.Current.Windows)
    {
        if (w != this)
            w.Close();
    }

    //handle clean up for MainWindow here...
}
</code>```

You might also want to consider to handle the Application.Current.Exit event to perform the cleanup of all windows in one place.

Body:
I have 2 windows in a WPF application, and If I close the Main one, I want to close the other too.

I achieved this by setting in my App.xaml:

ShutdownMode="OnMainWindowClose"

The 2 windows have a Window_Closing event in which I de-initialise some components. Now what I want to achieve is: if I close the MainWindow, the Window_Closing event of the second window must execute before the closing event of the Main one, because the de-init of the second one has to be executed before the first. Any idea on how can I achive this?

Body:
Close all windows but the MainWindow in the Closing event handler. This should work:

void MainWindow_Closing(object sender, CancelEventArgs e)
{
    foreach (Window w in Application.Current.Windows)
    {
        if (w != this)
            w.Close();
    }

    //handle clean up for MainWindow here...
}

You might also want to consider to handle the Application.Current.Exit event to perform the cleanup of all windows in one place.


问:
Logging Framework for the ASP.NET application
My application needs to log informations about user actions (inserts, updates, deletes, etc) and exceptions and i want to store de log on Oracle10, so i'am searching some log framework to use.
I read a little bit about:

1 -Log4Net

2 - Logging Application Block

3 - Elmah

Whats your opinion about these log tools?
Whats a good framework (or way to implement) log on my application?

*After a discussion with the project manager, Logging Application Block
 will be our choice, but, lets comment about this =)

答:
My opinions about the different frameworks:

Log4Net - Love it. This is the logging system that I use most often. Everything is fairly easy to get started. It's also very flexible and allows you to log just about anything.

Logging Application Block - Also a good option. I still prefer Log4Net (but the reasons are mostly personal).

Elman - Great for dropping in to an ASP.NET application to log Exceptions. For general message logging though, I would still go with Log4Net.

And I'm guessing based on my opinions what I would suggest you do...

And if not, use Log4Net and create an Adapter you can use in your application to make logging simple.


问:
Download SSL certificate from website and send it
We are developing a security conscious application and we need are application to send us the certificate that was used for connection.

Is it possible to download the certificate and send it on Android. We need to do this so that we can check to see if the certificate has been compromised. Or would be better to retreive details from the certificate write it to a log and then send it. We have an api that can send the details

答:
I see you have asked for pinning previously...

You can pin the certificate in the following way

```<code>Certificate[] certs = conn.getServerCertificates();
MessageDigest md = MessageDigest.getInstance("SHA-256");
for (Certificate cert : certs) {
    X509Certificate x509Certificate = (X509Certificate) cert;
    byte[] key = x509Certificate.getPublicKey().getEncoded();
    md.update(key, 0, key.length);
    byte[] hashBytes = md.digest();
    StringBuilder hexHash = new StringBuilder();
    for (byte hashByte : hashBytes) {
        int k = 0xFF & hashByte;
        String tmp = (k < 16) ? "0" : "";
        tmp += Integer.toHexString(0xFF & hashByte);
        hexHash.append(tmp);
    }
    // You can even log cert.toString()
    Log.d(TAG, hexHash.toString()); get the hash from here
    // If you create `pins` as a Set with all the valid pins from above
    if (pins.contains(hexHash.toString())) {
        return true;
    }
}
</code>```

You can run this after the connection conn has been connected then if the pin does not match you can abort before sending data. Note: the above code pins the public key of the certificate not the certificate.

If you just want the certificate you can just get cert.toString()

Body:
I see you have asked for pinning previously...

You can pin the certificate in the following way

Certificate[] certs = conn.getServerCertificates();
MessageDigest md = MessageDigest.getInstance("SHA-256");
for (Certificate cert : certs) {
    X509Certificate x509Certificate = (X509Certificate) cert;
    byte[] key = x509Certificate.getPublicKey().getEncoded();
    md.update(key, 0, key.length);
    byte[] hashBytes = md.digest();
    StringBuilder hexHash = new StringBuilder();
    for (byte hashByte : hashBytes) {
        int k = 0xFF & hashByte;
        String tmp = (k < 16) ? "0" : "";
        tmp += Integer.toHexString(0xFF & hashByte);
        hexHash.append(tmp);
    }
    // You can even log cert.toString()
    Log.d(TAG, hexHash.toString()); get the hash from here
    // If you create `pins` as a Set with all the valid pins from above
    if (pins.contains(hexHash.toString())) {
        return true;
    }
}

You can run this after the connection conn has been connected then if the pin does not match you can abort before sending data. Note: the above code pins the public key of the certificate not the certificate.

If you just want the certificate you can just get cert.toString()


问:
Do you search in breadth- or depth-first in a recursive algorithm?
Depth-first search uses LIFO/Stack.
Breadth-first search uses FIFO/Queue.
What does a recursive algorithm use? A combination of both?</p>

答:
a recursive algorithm always use Depth-first Search (DFS)

Pseudocode

Input: A graph G and a vertex v of G

Output: All vertices reachable from v labeled as discovered

A recursive implementation of DFS:

```<code>1  procedure DFS(G,v):
2      label v as discovered
3      for all edges from v to w in G.adjacentEdges(v) do
4          if vertex w is not labeled as discovered then
5              recursively call DFS(G,w)
</code>```

Wiki source here

Body:
a recursive algorithm always use Depth-first Search (DFS)

Pseudocode

Input: A graph G and a vertex v of G

Output: All vertices reachable from v labeled as discovered

A recursive implementation of DFS:

1  procedure DFS(G,v):
2      label v as discovered
3      for all edges from v to w in G.adjacentEdges(v) do
4          if vertex w is not labeled as discovered then
5              recursively call DFS(G,w)

Wiki source here


问:
List comprehension with condition on a list
I have two lists:

```<code>a=[1,0,0,1,0]
b=[23,10]
</code>```

I want to create a list c where I want the result to be a list of length(a) and if b[i]>a[i] -> c[i] = b[i]. Ie the result on this example should be:

```<code>c=[23,0,0,10,0]
</code>```

I have a code to do that but it depends on loop and clearly not efficient:

```<code>count=0
c=[0]*len(a)
for i in np.arange(len(a)):
    if a[i]==1:
        c[i]= b[count]
        count=count+1
    else:
        c[i]=a[i]
</code>```

Thanks guys

答:
You can use a list comprehension and an iterator on b:

```<code>>>> it = iter(b)
>>> [next(it) if x else x for x in a]
[23, 0, 0, 10, 0]
</code>```

If the values are not always binary, you can do an explicit equality comparison in the ternary conditional, as in your code:

```<code>[next(it) if x==1 else x for x in a]
</code>```

Body:
I have two lists:

a=[1,0,0,1,0]
b=[23,10]

I want to create a list c where I want the result to be a list of length(a) and if b[i]>a[i] -> c[i] = b[i]. Ie the result on this example should be:

c=[23,0,0,10,0]

I have a code to do that but it depends on loop and clearly not efficient:

count=0
c=[0]*len(a)
for i in np.arange(len(a)):
    if a[i]==1:
        c[i]= b[count]
        count=count+1
    else:
        c[i]=a[i]

Thanks guys

Body:
You can use a list comprehension and an iterator on b:

>>> it = iter(b)
>>> [next(it) if x else x for x in a]
[23, 0, 0, 10, 0]

If the values are not always binary, you can do an explicit equality comparison in the ternary conditional, as in your code:

[next(it) if x==1 else x for x in a]


问:
Displaying a custom div inline with a h5
I know it sounds simple, but this is really annoying me. I have researched online and not found a perfect answer for me yet.

I have this html code:

```<code><h5 class="start-online"><div id="online_ajax">0</div> Clients online </h5>
</code>```

I want the online_ajax div to display inline before the Client online text.

My current css is:

```<code>h5.start-online {
    text-align: center;
    font-size: 11px;
}

.online_ajax {
    position: relative;
    display: inline-block;
}
</code>```

答:
You cannot nest
 inside
. Period. Make it  instead.

```<code><h5 class="start-online"><span id="online_ajax">0</span> Clients online </h5>
</code>```

You don't even need to style it! The  tag is the inline version of
 tag (as how
 tag is the inline version of ).

Also, in your CSS, you are supposed to select the id and # is the ID selector.

#online_ajax {
  position: relative;
  display: inline-block;
}
```

But yeah, as I said you before, please don't use
.

Body:
I know it sounds simple, but this is really annoying me. I have researched online and not found a perfect answer for me yet.

I have this html code:

0
 Clients online

I want the online_ajax div to display inline before the Client online text.

My current css is:

h5.start-online {
    text-align: center;
    font-size: 11px;
}

.online_ajax {
    position: relative;
    display: inline-block;
}

Body:
You cannot nest <div> inside <h5>. Period. Make it <span> instead.

<h5 class="start-online"><span id="online_ajax">0</span> Clients online </h5>

You don't even need to style it! The <span> tag is the inline version of <div> tag (as how <div> tag is the inline version of <span>).

Also, in your CSS, you are supposed to select the id and # is the ID selector.

#online_ajax {
  position: relative;
  display: inline-block;
}

But yeah, as I said you before, please don't use <div>.


问:
Creating an overlay in CSS?
I have div that I display dynamically when certain conditions arise.

When I display the div, how can I create the effect of the background dimming and my div appearing to be prominent? much like a number of AJAX lightboxes or popups. (Thickbox, ColorBox, PrettyPhoto, etc)

I don;t quite get how they do it. I have everything else working in my own custom code except that piece.

Can anyone help me learn how?

答:
Place a div over the content and set an opacity. I use this in one of my sites.</p>

```<code><div id="error_wrapper">
    <div id="site_error">
        Error:
    </div>
</div>

div#error_wrapper {
    z-index: 100;
    position: fixed;
    width: 100%;
    height: 100%;
    background-color: #000000;
    top: 0px;
    left: 0px;
    opacity: 0.7;
    filter: alpha(opacity=70);

}

div#site_error {
    position: fixed;
    top: 200px;
    width: 400px;
    left: 50%;
    margin-left: -200px;
}
</code>```

Title: Creating an overlay in CSS?

Body:
Place a div over the content and set an opacity. I use this in one of my sites.

<div id="error_wrapper">
    <div id="site_error">
        Error:
    </div>
</div>

div#error_wrapper {
    z-index: 100;
    position: fixed;
    width: 100%;
    height: 100%;
    background-color: #000000;
    top: 0px;
    left: 0px;
    opacity: 0.7;
    filter: alpha(opacity=70);

}

div#site_error {
    position: fixed;
    top: 200px;
    width: 400px;
    left: 50%;
    margin-left: -200px;
}


问:
Calling an excel file via a macro
I want to create a macro that pulls a file by allowing the user to browse and locate the file from his/her local and then perform some functions on the pulled file.

I am not sure how to incorporate the browsing file feature in the macro.

答: Use Application.FileDialog, there are lot's of examples in SO and elsewhere on the internet, for example here

Title: Calling an excel file via a macro


问:
Tinymce not working in angularjs mdDialog
I'm trying to use TinyMCE editor in angularjs mdDialog.

Worling Plukr: http://embed.plnkr.co/s3NsemdcDAtG7AoQRvLh/

Plunkr with issues: http://embed.plnkr.co/fL8kGLl3b4TNdxW1AtKG/

All features are working normally instead of drop down:
http://prntscr.com/fop9u0

 It works fine if I increase the top position of drop down around 100px. http://prntscr.com/fope8o

I noticed that this problem appearing due to page scroll..

Can someone help me out to get these drop downs in right position.

答:
A CSS conflict possible a forced margin on all divs. So this is more of a integration issue than a tinymce bug. We have a few reset rules to remove the common conflicts.

   ```

Its not working perfectly. But it might help you to do something.

Body:
A CSS conflict possible a forced margin on all divs. So this is more of a integration issue than a tinymce bug. We have a few reset rules to remove the common conflicts.

   <style>
   .mce-tooltip
  {
    position: fixed !important;
  }
  .mce-panel.mce-floatpanel.mce-menu
  {
    position: fixed !important;
  }
    </style>

Its not working perfectly. But it might help you to do something.


问:
Why is curl using HTTP/1.1 rather than HTTP/2 on mac?
According to this https://curl.haxx.se/docs/http2.html

Since 7.47.0, the curl tool enables HTTP/2 by default for HTTPS connections.

Installing the latest version with homebrew and checking:

```<code>curl --version
curl 7.54.1 (x86_64-apple-darwin15.6.0) libcurl/7.54.1 SecureTransport zlib/1.2.5
</code>```

but running curl on an HTTP2 enabled URL (e.g. test with https://tools.keycdn.com/http2-test) I get:

```<code>curl -I http://www.google.co.uk
HTTP/1.1 200 OK
</code>```

and

```<code>curl --http2 -v http://www.google.co.uk
curl: (1) Unsupported protocol
</code>```

Any idea why it's using HTTP/1.1 rather than HTTP/2?

答:
You can build curl to use one of many different TLS/SSL libraries, each of those has slightly different feature sets and offer slightly different conditions for curl to work with.

The curl you show in your question lists SecureTransport as the TLS library it was built to use, the macOS native TLS library.

Secure Transport simply does not provide the necessary means for curl to negotiate HTTP/2 over TLS - or at least it hasn't, as I've been told that the very latest version now supports ALPN so a future curl version should be able to do HTTP/2 over TLS even with Secure Transport.

In addition to the proper TLS negotiation, curl also needs to speak HTTP/2, which it does thanks using the venerable nghttp2 library so that's a second dependency that needs to be there for curl to be able to speak HTTP/2. With nghttp2 present, curl can actually speak HTTP/2 over plain-text HTTP even when the TLS library can't negotiate ALPN properly.

Fix?

Later macOS versions ship curl built with libreSSL and HTTP/2 support built-in.

If you opt to instead rebuild curl with another TLS library, such as OpenSSL, GnuTLS or NSS it can speak HTTP/2 fine over HTTPS already today.

Body:
According to this https://curl.haxx.se/docs/http2.html

Since 7.47.0, the curl tool enables HTTP/2 by default for HTTPS connections.

Installing the latest version with homebrew and checking:

curl --version
curl 7.54.1 (x86_64-apple-darwin15.6.0) libcurl/7.54.1 SecureTransport zlib/1.2.5

but running curl on an HTTP2 enabled URL (e.g. test with https://tools.keycdn.com/http2-test) I get:

curl -I http://www.google.co.uk
HTTP/1.1 200 OK

and

curl --http2 -v http://www.google.co.uk
curl: (1) Unsupported protocol

Any idea why it's using HTTP/1.1 rather than HTTP/2?


问:
Slick generating query with backtick for Oracle
I am using slick with oracle. Things are fine except, slick generated queries are having backticks in the query which oracle does not support. Any idea/pointer from anyone how to remove those backticks please?

Example Query:

```<code>select `merchant_code`, `merchant_name`, `merchant_address`, `merchant_mcc`, `account_number`, `ifsc` from `merchant_details` where `merchant_code` = '1024';
</code>```

Help appreciated.

答: Fixed it... Seems I was using MysqlProfile instead of OracleProfile.</p>

Body:
I am using slick with oracle. Things are fine except, slick generated queries are having backticks in the query which oracle does not support. Any idea/pointer from anyone how to remove those backticks please?

Example Query:

select `merchant_code`, `merchant_name`, `merchant_address`, `merchant_mcc`, `account_number`, `ifsc` from `merchant_details` where `merchant_code` = '1024';

Help appreciated.


问:
AJAX form submit to PHP not returning correct data
I have a form that I would like to send data from to a php script using AJAX. However I am running into an issue with actually passing the data across. The $_POST array is empty for some reason.

Currently the HTML is:

```<code><form>
    <label>Email Address:</label>
    <input type='text' name='email' value='jackc@test.com'/>
    <input type='submit' name='submit' value='Check subscription status'/>
</form>
</code>```

The JQuery is:

```<code> $(document).ready(function() {
        $('form').submit(function(e){
            e.preventDefault();
            var url = 'request.php';
            $.ajax({
                type: 'POST',
                url: url,
                contentType: "json",
                data: $('form').serialize(),
                success: function(data){
                    console.log(data);
                    $('#results').html(data);
                }
            });

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

The PHP is:

```<code>        $emailAddress = $_POST['email'];
        echo "EMAIL: " . $emailAddress;
</code>```

However it's not returning anything. It's blank each time. When I do a console log for $('form').serialize() I see email=jackc%40@test.com which I would expect to see returned from my PHP.

I'd appreciate some help on this. Many thanks.

答:
Add dataType: "json", instead contentType: "json", to send data as form data and receive data as json:

```<code>$(document).ready(function() {
    $('form').submit(function(e){
        e.preventDefault();
        var url = '';
        $.ajax({
            type: 'POST',
            url: url,
            dataType: "json",
            data: $('form').serialize(),
            success: function(data){
                console.log(data);
                $('#results').html(data);
            }
        });

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

If you don't want to receive json data, remove contentType at all:

```<code>$(document).ready(function() {
    $('form').submit(function(e){
        e.preventDefault();
        var url = '';
        $.ajax({
            type: 'POST',
            url: url,
            data: $('form').serialize(),
            success: function(data){
                console.log(data);
                $('#results').html(data);
            }
        });

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

Body:
I have a form that I would like to send data from to a php script using AJAX. However I am running into an issue with actually passing the data across. The $_POST array is empty for some reason.

Currently the HTML is:

<form>
    Email Address:
    <input type='text' name='email' value='jackc@test.com'/>
    <input type='submit' name='submit' value='Check subscription status'/>
</form>

The JQuery is:

 $(document).ready(function() {
        $('form').submit(function(e){
            e.preventDefault();
            var url = 'request.php';
            $.ajax({
                type: 'POST',
                url: url,
                contentType: "json",
                data: $('form').serialize(),
                success: function(data){
                    console.log(data);
                    $('#results').html(data);
                }
            });

        });
    });

The PHP is:

        $emailAddress = $_POST['email'];
        echo "EMAIL: " . $emailAddress;

However it's not returning anything. It's blank each time. When I do a console log for $('form').serialize() I see email=jackc%40@test.com which I would expect to see returned from my PHP.

I'd appreciate some help on this. Many thanks.

Body:
Add dataType: "json", instead contentType: "json", to send data as form data and receive data as json:

$(document).ready(function() {
    $('form').submit(function(e){
        e.preventDefault();
        var url = '';
        $.ajax({
            type: 'POST',
            url: url,
            dataType: "json",
            data: $('form').serialize(),
            success: function(data){
                console.log(data);
                $('#results').html(data);
            }
        });

    });
});

If you don't want to receive json data, remove contentType at all:

$(document).ready(function() {
    $('form').submit(function(e){
        e.preventDefault();
        var url = '';
        $.ajax({
            type: 'POST',
            url: url,
            data: $('form').serialize(),
            success: function(data){
                console.log(data);
                $('#results').html(data);
            }
        });

    });
});


问:
does try catch clause affect performance?
does try/catch affects performance if no exception thrown in try block?

how about try/catch/finally?

答:
Neither try/catch nor try/catch/finally affects performance to any significant degree. Exceptions being created do affect performance, of course (and that is whether they are caught, or not)

Do try/catch blocks hurt performance when exceptions are not thrown?


问:
Removing points from a pcl::PointCloud<pcl::PointXYZRGB>
I'm new in PCL. I'm using the PCL library and I'm looking for a way to extract points from a point cloud or copying particular points to a new one. I want to verify for each point if it respects a condition and I want to obtain a point cloud with only the good points.Thank you!</p>

答:
If you are new to PCL. It should be a good idea to take a look at at the documentation:

http://pointclouds.org/documentation/tutorials/

I think that what you are looking for is explained in this tutorial:

http://pointclouds.org/documentation/tutorials/remove_outliers.php#remove-outliers

Try to reproduce the example on your machine and then modify it to fit your needs.


问:
Formatting date view in jsp after returning a page because of errors in bindingresult
i have a silly question. I want to change the format of the date displayed in the form after the user input.
i got this situation:
The user insert two dates using a datepicker

Then if there is an error in bindingResult the same page is returned but the date is displayed like this:

I just want to display the dates in the second image like the dates in the first image. Thanks!

EDIT

this is the model that contain the date

```<code>@Entity
public class Booking implements Serializable {
//
private Date startDate;

private Date finishDate;
//
</code>```

They are stored in a table through Hibernate
In the controller i have to do a conversion for the validation because of the date returned from mysql(i suppose). The one i get from db is in format like this "Sat Jul 01 00:00:00 CEST 2017", while the one i get from datepicker is in format like "yyyy-mm-dd HH:mm:ss".

```<code>@PostMapping("/rent")
    public ModelAndView vehicleRent(@RequestParam("id") long id, @ModelAttribute("newBooking") Booking booking, BindingResult bindingResult) throws ParseException {

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
        String stringStartDate = dateFormat.format(booking.getStartDate());
        Date formattedStartDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(stringStartDate);

        if (booking.getStartDate() != null || booking.getFinishDate() != null || booking != null) {
            for (Booking b : vehicleBookings) {
                if (formattedStartDate.before(b.getFinishDate()) || formattedStartDate.equals(b.getFinishDate())) {
                    bindingResult.rejectValue("startDate", "validation.booking.startdate.exists");
                    break;
                }
            }
        }
//
</code>```

the jsp

```<code><%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
      integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
    $(function () {
        $("#startDate,#finishDate").datepicker();
    });
<form:form action="${pageContext.request.contextPath}/rent" method="POST" modelAttribute="newBooking">
    <div>
        <table class="table">

            <input id="id" name="id" type="hidden" value="${vehicle.id}"/>

            <tr>

                <td><form:label  path="startDate">Data Inizio</form:label></td>
                <td><form:input type="text" id="startDate" name="startDate" path="startDate" data-format="dd/MM/yyyy" /> </td>
                <td><form:errors path="startDate" cssStyle="color: #ff0000" /></td>
            </tr>
            <tr>
                <td><form:label  path="finishDate">Data Fine</form:label></td>
                <td><form:input type="text" id="finishDate" name="finishDate" path="finishDate" /></td>
                <td><form:errors path="finishDate" cssStyle="color: #ff0000" /></td>
            </tr>
        </table>

        <input  type="submit" value="Invia" />

        <br>
        <br>

        <a href="${pageContext.request.contextPath}/">Torna alla Home</a>

    </div>
</form:form>
</code>```

答:
You could try to add this annotation to you bear @DateTimeFormat</p>

```<code>@Entity
public class Booking implements Serializable {

    @DateTimeFormat(pattern = "MM/dd/yyyy")
    private Date startDate;

    @DateTimeFormat(pattern = "MM/dd/yyyy")
    private Date finishDate;
</code>```

Body:
i have a silly question. I want to change the format of the date displayed in the form after the user input.
i got this situation:
The user insert two dates using a datepicker

Then if there is an error in bindingResult the same page is returned but the date is displayed like this:

I just want to display the dates in the second image like the dates in the first image. Thanks!

EDIT

this is the model that contain the date

@Entity
public class Booking implements Serializable {
//
private Date startDate;

private Date finishDate;
//

They are stored in a table through Hibernate
In the controller i have to do a conversion for the validation because of the date returned from mysql(i suppose). The one i get from db is in format like this "Sat Jul 01 00:00:00 CEST 2017", while the one i get from datepicker is in format like "yyyy-mm-dd HH:mm:ss".

@PostMapping("/rent")
    public ModelAndView vehicleRent(@RequestParam("id") long id, @ModelAttribute("newBooking") Booking booking, BindingResult bindingResult) throws ParseException {

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
        String stringStartDate = dateFormat.format(booking.getStartDate());
        Date formattedStartDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(stringStartDate);

        if (booking.getStartDate() != null || booking.getFinishDate() != null || booking != null) {
            for (Booking b : vehicleBookings) {
                if (formattedStartDate.before(b.getFinishDate()) || formattedStartDate.equals(b.getFinishDate())) {
                    bindingResult.rejectValue("startDate", "validation.booking.startdate.exists");
                    break;
                }
            }
        }
//

the jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
      integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

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

Body:
You could try to add this annotation to you bear @DateTimeFormat

@Entity
public class Booking implements Serializable {

    @DateTimeFormat(pattern = "MM/dd/yyyy")
    private Date startDate;

    @DateTimeFormat(pattern = "MM/dd/yyyy")
    private Date finishDate;


问:
How to hide first Y Axis line on an nvd3 chart?
Plnkr example:
http://plnkr.co/edit/19D5cnrVYdUrMlblQARy?p=preview

Screenshot from my app:

I've tried modifying the CSS, however I was only able to remove the 2nd (right Y axis line), but not the first left Y axis line.

What I've tried:

```<code>.nv-y {
    display: none;
}
</code>```

As well as all the lines from this answer: Alter first vertical grid line in nvd3

```<code>d3.selectAll('.nv-y').attr('display','none')

d3.selectAll('.nv-y path').attr('opacity','0.1')

d3.selectAll('.nv-y path').attr('display','none')
</code>```

My current drawChart function:

```<code>function drawChart(res) {
    console.log(' ');
    console.log('drawChart res = ',res);
    nv.addGraph(function() {
        var chart = nv.models.linePlusBarChart()
            .margin({top: 30, right: 40, bottom: 50, left: 40})
            .x(function(d,i) { return i })
            .y(function(d) { return d[1] })
            .color(d3.scale.category10().range());

        chart.xAxis.tickFormat(function(d) {
            var dx = res[0].values[d] && res[0].values[d][0] || 0;
            return d3.time.format('%x')(new Date(dx))
        });

        chart.y1Axis
            .tickFormat(d3.format(',f'));

        chart.y2Axis
            .tickFormat(function(d) { return '$' + d3.format(',f')(d) });

        chart.bars.forceY([0]);
        // https://stackoverflow.com/questions/23754188/nvd3-js-how-to-disable-tooltips-for-one-serie-only
        chart.lines.interactive(false);
        // http://nvd3-community.github.io/nvd3/examples/documentation.html#line
        chart.height(280);
        // If not chart data is avaliable to display:
        chart.noData("There is no Data to display at the moment.");

        // Remove legend:
        chart.showLegend(false);

        d3.select('#chart svg')
            .datum(res)
            .transition().duration(500)
            .call(chart);

        d3.selectAll('.nv-y path').attr('display','none');

        nv.utils.windowResize(chart.update);

        return chart;
    });
}
</code>```

答:
Use this :</p>

```<code>.domain {
  display: none;
}
</code>```

Body:
Plnkr example:
http://plnkr.co/edit/19D5cnrVYdUrMlblQARy?p=preview

Screenshot from my app:

I've tried modifying the CSS, however I was only able to remove the 2nd (right Y axis line), but not the first left Y axis line.

What I've tried:

.nv-y {
    display: none;
}

As well as all the lines from this answer: Alter first vertical grid line in nvd3

d3.selectAll('.nv-y').attr('display','none')

d3.selectAll('.nv-y path').attr('opacity','0.1')

d3.selectAll('.nv-y path').attr('display','none')

My current drawChart function:

function drawChart(res) {
    console.log(' ');
    console.log('drawChart res = ',res);
    nv.addGraph(function() {
        var chart = nv.models.linePlusBarChart()
            .margin({top: 30, right: 40, bottom: 50, left: 40})
            .x(function(d,i) { return i })
            .y(function(d) { return d[1] })
            .color(d3.scale.category10().range());

        chart.xAxis.tickFormat(function(d) {
            var dx = res[0].values[d] && res[0].values[d][0] || 0;
            return d3.time.format('%x')(new Date(dx))
        });

        chart.y1Axis
            .tickFormat(d3.format(',f'));

        chart.y2Axis
            .tickFormat(function(d) { return '$' + d3.format(',f')(d) });

        chart.bars.forceY([0]);
        // https://stackoverflow.com/questions/23754188/nvd3-js-how-to-disable-tooltips-for-one-serie-only
        chart.lines.interactive(false);
        // http://nvd3-community.github.io/nvd3/examples/documentation.html#line
        chart.height(280);
        // If not chart data is avaliable to display:
        chart.noData("There is no Data to display at the moment.");

        // Remove legend:
        chart.showLegend(false);

        d3.select('#chart svg')
            .datum(res)
            .transition().duration(500)
            .call(chart);

        d3.selectAll('.nv-y path').attr('display','none');

        nv.utils.windowResize(chart.update);

        return chart;
    });
}

Body:
Use this :

.domain {
  display: none;
}


问:
Drop pin and get adress from where the user tap on map
I'm trying to get the address and showing an annotation where the user presses on my map.

I'm new to swift and don't know where to begin any ideas?

答:
If you want to getAdress where the user taps that is a tricky part,

By following this link

OR

You can do with dragging by pin:

Step 1: Drop pin on current location. By following this

Step 2: By dragging pin you can get the current pin position address. By following this:


问:
SOAP-ERROR: Parsing WSDL: Couldn't load from : failed to load external entity
We are getting the following error

SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://www.example.com/api/v2_soap?wsdl=1' : failed to load external entity "https://www.example.com/api/v2_soap?wsdl=1"

What could possibly be the reason for this SOAP error?

Curlwrappers are already disabled.

As suggested, I checked out this post soap api : Start tag expected, '<' not found' I found that ini_set('display_errors',0); is already turned off. Still unable to overcome the SOAP error.

答:
I figured why I experienced this issue. Actually, that was a firewall issue. I did add correctly the rules to allow the secondary server to attack the magento's api but this one needs to reach out itself !
So after some headaches, I did just add a rule on the magento server's firewall to allow itself (the magento server) to reach its own api (kind of external lookup)...</p>


问:
Why do string indices (albeit representing integers) work in arrays?
Why does the following enumerate correctly?

```<code>var arr = [];
arr[0] = 'foo';
arr['1'] = 'bar';

arr.forEach(v => console.log(v)); // foo, bar
</code>```

Both arr[1] and arr['1'] also work. Is this a feature of Array that strings corresponding to integers are mapped to their integer value?

答:
It's due to the fact that arrays in Javascript are just objects with some dedicated syntactic sugar.

Compare:

```<code>var arr = [];
arr[0] = 'foo';
arr['1'] = 'bar';
console.log(arr['0']);
console.log(arr[1]);
</code>```

... to:

```<code>var obj = {};
obj[0] = 'foo';
obj['1'] = 'bar';
console.log(obj['0']);
console.log(obj[1]);
</code>```

Basically, Array is a type of Object, with array specific methods and non-enumerable properties, such as length, which can be instantiated with the dedicated shorthand syntax [ items... ]

The indices of an array are actually strings, just like all keys in any object, it works because referencing an object property using a number as a key will coerce that number into its string representation (in principle, that is. I assume most modern browsers have internally optimized this heavily).

Example:

```<code>var obj = {};
obj[1.5] = 'foo';
console.log('1.5' in obj);
console.log(obj[1.5]);

var arr = [];
arr[0.5] = 'foo';
console.log('0.5' in arr);
console.log(arr[0.5]);

arr[0] = 'bar';
arr[1] = 'baz';
console.log(arr.length);
console.log(Object.keys(arr));
</code>```

Body:
Why does the following enumerate correctly?

var arr = [];
arr[0] = 'foo';
arr['1'] = 'bar';

arr.forEach(v => console.log(v)); // foo, bar

Both arr[1] and arr['1'] also work. Is this a feature of Array that strings corresponding to integers are mapped to their integer value?

Body:
It's due to the fact that arrays in Javascript are just objects with some dedicated syntactic sugar.

Compare:

var arr = [];
arr[0] = 'foo';
arr['1'] = 'bar';
console.log(arr['0']);
console.log(arr[1]);

... to:

var obj = {};
obj[0] = 'foo';
obj['1'] = 'bar';
console.log(obj['0']);
console.log(obj[1]);

Basically, Array is a type of Object, with array specific methods and non-enumerable properties, such as length, which can be instantiated with the dedicated shorthand syntax [ items... ]

The indices of an array are actually strings, just like all keys in any object, it works because referencing an object property using a number as a key will coerce that number into its string representation (in principle, that is. I assume most modern browsers have internally optimized this heavily).

Example:

var obj = {};
obj[1.5] = 'foo';
console.log('1.5' in obj);
console.log(obj[1.5]);

var arr = [];
arr[0.5] = 'foo';
console.log('0.5' in arr);
console.log(arr[0.5]);

arr[0] = 'bar';
arr[1] = 'baz';
console.log(arr.length);
console.log(Object.keys(arr));


问:
Compare matrices in Python and store results
I would like to compare a 70x1 matrix with a 1000x3 matrix. What i want to do is compare the first column of the second matrix with the first matrix, find all the common values and then store the results in a new third matrix which is going to have all 3 columns.

I used np.intersect1d to find the common values between the two matrices but that is about it.

I can't find a way to import the other two columns of the second matrix to the new one.

Matrix1

```<code>[1.0

4.7

4.8

4.9

5.0

5.1]
</code>```

Matrix2

```<code>[[3.0, 1.8, -3.0]

[3.1, 2.2, -3.0]

[4.7, 2.4, -3.0]

[3.3, 2.8, -3.0]

[3.40, 3.0, -3.0]]
</code>```

Matrix3

```<code>[4.7, 2.4, -3.0]
</code>```

答:
Take the first column values of each matrix, convert to set, intersect and convert back to list (or np.array):

matrix3 = list(set(y for x in matrix1[:,:1] for y in x) & set(y for x in matrix2[:,:1] for y in x))
```

Body:
I would like to compare a 70x1 matrix with a 1000x3 matrix. What i want to do is compare the first column of the second matrix with the first matrix, find all the common values and then store the results in a new third matrix which is going to have all 3 columns.

I used np.intersect1d to find the common values between the two matrices but that is about it.

I can't find a way to import the other two columns of the second matrix to the new one.

Matrix1

[1.0

4.7

4.8

4.9

5.0

5.1]

Matrix2

[[3.0, 1.8, -3.0]

[3.1, 2.2, -3.0]

[4.7, 2.4, -3.0]

[3.3, 2.8, -3.0]

[3.40, 3.0, -3.0]]

Matrix3

[4.7, 2.4, -3.0]


答:
Creating an exception does incur some performance cost.  Generally, you want to catch an exception only when there's something you actually need to do with that exception at that point in the code.

Note that, for the purpose of closing resources or performing other necessary tasks after a potential failure, you can employ simply a try/finally block.  The finally will still execute as it should, you're just not catching the exception in the process.  Rather, you let it bubble up to wherever it needs to go.

Title: does try catch clause affect performance?

Body:
does try/catch affects performance if no exception thrown in try block?

how about try/catch/finally?


问:
using getOpenFileName in a handler
I have implemented the getOPenFileName in a handler in qt (in a when_pushbutton_clicked more specifically). How can I save the produced string in a QString in main rather than inside the handler?

答:
You can use a signal connection to save in a QString variable the path of your file name.

```<code>const QString fileName = QFileDialog::getOpenFileName(0, tr("Select the file"), getLastDirectory(), "Txt Files (*.txt)");
if (fileName.isEmpty()) {
    // No file was selected
    return;
}
// then emit the signal
emit fileWasSelected(fileName);
</code>```

In your main function you cant handle the event in the main class by a simple connection:

```<code>QObject::connect(yourClass, &YourClass::fileWasSelected, [&](const QString& filename) {
  // Now, do what you want with your path
}):
</code>```

Another way, its to save the file in a private variable, and set up a getter:

```<code>class MyClass {
   ....
public:
    inline QString path() const { return _path; }
private:
    QString _path;
}
</code>```

And then access to the variable from the main.

Title: using getOpenFileName in a handler

Body:
You can use a signal connection to save in a QString variable the path of your file name.

const QString fileName = QFileDialog::getOpenFileName(0, tr("Select the file"), getLastDirectory(), "Txt Files (*.txt)");
if (fileName.isEmpty()) {
    // No file was selected
    return;
}
// then emit the signal
emit fileWasSelected(fileName);

In your main function you cant handle the event in the main class by a simple connection:

QObject::connect(yourClass, &YourClass::fileWasSelected, [&](const QString& filename) {
  // Now, do what you want with your path
}):

Another way, its to save the file in a private variable, and set up a getter:

class MyClass {
   ....
public:
    inline QString path() const { return _path; }
private:
    QString _path;
}

And then access to the variable from the main.