问:
how to show a spinner till the time data recieved from the server in angular2
The project have a service.ts to make ajax call(http.post) and several components(abc.component.ts, bcd.component.ts etc) gets the data from the server through service.ts

I am using

  for the spinner view. But, need a better approach to show loader either gif etc.

I want to show a spinner till the time each component fetch data from the server. How to do that?

service.ts

```<code> getdata(){
      let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        let url = "http://883.82./Ser/soSe";
        return this.http.post(url, clientJson).map((res: Response) => res.json());
    }
</code>```

abc.component.ts

```<code>let clientJson = {
        "aoId": "M_AO_918",
        "viewBys": ["usstate"],
        /* ... */
    };
  this.DataService.getdata(clientJson).subscribe(
        success => this.abcChart(success),
        error => this.errorMessage = error
    );
abcChart(jsonData) {
    /* ... */
}
</code>```

bcd-chart.component.ts

```<code> initData() {
        let clientJson = {
            "aoId": "M_AO_918",
            "viewBys": ["brands"],
            /* ... */
        };
        this.DataService.getdata(clientJson).subscribe(
            success => this.bcdChart(success),
            error => this.errorMessage = error
        );
    }
    bcdChart(jsonData) {
        /* ... */
    }
</code>```

styles.css

```<code>.spinner {
  width: 40px;
  height: 40px;
  background-color: #333;

  margin: 100px auto;
  -webkit-animation: sk-rotateplane 1.2s infinite ease-in-out;
  animation: sk-rotateplane 1.2s infinite ease-in-out;
}

@-webkit-keyframes sk-rotateplane {
  0% { -webkit-transform: perspective(120px) }
  50% { -webkit-transform: perspective(120px) rotateY(180deg) }
  100% { -webkit-transform: perspective(120px) rotateY(180deg)  rotateX(180deg) }
}

@keyframes sk-rotateplane {
  0% {
    transform: perspective(120px) rotateX(0deg) rotateY(0deg);
    -webkit-transform: perspective(120px) rotateX(0deg) rotateY(0deg)
  } 50% {
    transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg);
    -webkit-transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg)
  } 100% {
    transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg);
    -webkit-transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg);
  }
}
.loading{
  background-color: #d35400;
}
</code>```

答:
In your main html file where you keep <router-outlet></router-outlet> you need to keep the html of spinner so you can show it in any component throughout your angular app :

You also need to import service in the app.component.ts:

app.component.ts:

```<code>constructor(
  public serviceName: ServiceName
  ...
)
</code>```

app.component.html:

```<code><router-outlet></router-outlet>
<div *ngIf="serviceName.showSpinner" class="spiner">
    <!-- svg or gif of spinner  -->
</div>
</code>```

In your service.ts:

```<code>public showSpinner: boolean = false;

getdata() {
    // show spinner when we start making request

    this.showLoadingSpinner();
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    let url = "http://883.82./Ser/soSe";
    return this.http.post(url, clientJson,clientJson1).map((res: Response) => {
      // response received so hide spinner now
      this.hideLoadingSpinner();
      return res.json();
    });
}

showLoadingSpinner() {
    this.showSpinner = true;
}

hideLoadingSpinner() {
    this.showSpinner = false;
}
</code>```

Body:
The project have a service.ts to make ajax call(http.post) and several components(abc.component.ts, bcd.component.ts etc) gets the data from the server through service.ts

I am using

  for the spinner view. But, need a better approach to show loader either gif etc.

I want to show a spinner till the time each component fetch data from the server. How to do that?

service.ts

 getdata(){
      let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        let url = "http://883.82./Ser/soSe";
        return this.http.post(url, clientJson).map((res: Response) => res.json());
    }

abc.component.ts

let clientJson = {
        "aoId": "M_AO_918",
        "viewBys": ["usstate"],
        /* ... */
    };
  this.DataService.getdata(clientJson).subscribe(
        success => this.abcChart(success),
        error => this.errorMessage = error
    );
abcChart(jsonData) {
    /* ... */
}

bcd-chart.component.ts

 initData() {
        let clientJson = {
            "aoId": "M_AO_918",
            "viewBys": ["brands"],
            /* ... */
        };
        this.DataService.getdata(clientJson).subscribe(
            success => this.bcdChart(success),
            error => this.errorMessage = error
        );
    }
    bcdChart(jsonData) {
        /* ... */
    }

styles.css

.spinner {
  width: 40px;
  height: 40px;
  background-color: #333;

  margin: 100px auto;
  -webkit-animation: sk-rotateplane 1.2s infinite ease-in-out;
  animation: sk-rotateplane 1.2s infinite ease-in-out;
}

@-webkit-keyframes sk-rotateplane {
  0% { -webkit-transform: perspective(120px) }
  50% { -webkit-transform: perspective(120px) rotateY(180deg) }
  100% { -webkit-transform: perspective(120px) rotateY(180deg)  rotateX(180deg) }
}

@keyframes sk-rotateplane {
  0% {
    transform: perspective(120px) rotateX(0deg) rotateY(0deg);
    -webkit-transform: perspective(120px) rotateX(0deg) rotateY(0deg)
  } 50% {
    transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg);
    -webkit-transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg)
  } 100% {
    transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg);
    -webkit-transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg);
  }
}
.loading{
  background-color: #d35400;
}

Body:
In your main html file where you keep <router-outlet></router-outlet> you need to keep the html of spinner so you can show it in any component throughout your angular app :

You also need to import service in the app.component.ts:

app.component.ts:

constructor(
  public serviceName: ServiceName
  ...
)

app.component.html:

<router-outlet></router-outlet>
<div *ngIf="serviceName.showSpinner" class="spiner">
    <!-- svg or gif of spinner  -->
</div>

In your service.ts:

public showSpinner: boolean = false;

getdata() {
    // show spinner when we start making request

    this.showLoadingSpinner();
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    let url = "http://883.82./Ser/soSe";
    return this.http.post(url, clientJson,clientJson1).map((res: Response) => {
      // response received so hide spinner now
      this.hideLoadingSpinner();
      return res.json();
    });
}

showLoadingSpinner() {
    this.showSpinner = true;
}

hideLoadingSpinner() {
    this.showSpinner = false;
}


来源: stackexchange

问:
VB.net 2017 Change background color of button
I just started using vb.net 2017 instead of the 2010 version and i can't figure out how to change the background color of a button. I used to be able to do

```<code>`but1.BackColor = Colors.Blue`
</code>```

But it seems as if BackColor isn't available anymore. What could be a possible solution?

Edit: added screenshots

Form screenshot VS auto corrects color to ColorInterpolationMode

Designer screenshot

答:
Looks good to me, I just tried this myself and works fine in VS 2017.

```<code>Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Button1.BackColor = Color.Blue
End Sub
</code>```

Image

Check btn1 properties under 'Apperance' If you dont see BackColor there that might help point you into the right direction. Don't think is a VS 2017 issue.

ContentLicense: CC BY-SA 3.0

Body:
I just started using vb.net 2017 instead of the 2010 version and i can't figure out how to change the background color of a button. I used to be able to do

`but1.BackColor = Colors.Blue`

But it seems as if BackColor isn't available anymore. What could be a possible solution?

Edit: added screenshots

Form screenshot VS auto corrects color to ColorInterpolationMode

Designer screenshot

Body:
Looks good to me, I just tried this myself and works fine in VS 2017.

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Button1.BackColor = Color.Blue
End Sub

Image

Check btn1 properties under 'Apperance' If you dont see BackColor there that might help point you into the right direction. Don't think is a VS 2017 issue.


问:
WPF DataGrid, customizing the display with a converter
I have a unique situation. In one class, I have an inner class that acts as pretty much just a "display" class. In the outer class there is a method called GetDisplayObject that returns a type of the inner class.

I'm trying to bind to a datagrid with the outer class, but by using a converter I'd like to get the correct display. This way I won't have to change a bunch of code in our application and just add a few lines in a couple .xaml files.

I made a little test app that pretty much sums up my problem at it's most basic level. Ideally I'd like to solve the problem by using a converter and returning values only as a display, that way when i'm using the SelectedItem I won't have to change a ton of code that is depending on that certain type(In this case would be the DataObject type).

So here is the objects i'm stuck dealing with

```<code>namespace TestApp
{
    public class DataObject
    {
        public class DataObjectDisplay
        {
            public string ObjectDisplay { get; set; }
        }

        // props
        public int Id { get; set; }
        public object Object1 { get; set; }
        public object Object2 { get; set; }

        // method for getting the display
        public DataObjectDisplay GetDisplayObject()
        {
            DataObjectDisplay display = new DataObjectDisplay();

            // logic for determining which object should be displayed
            if(Object1 == null)
            {
                display.ObjectDisplay = "Object1";
            }
            else
            {
                display.ObjectDisplay = "Object2";
            }
            return display;
        }
    }
}
</code>```

Here is the Code Behind of my xaml

```<code>using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;

namespace TestApp
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        this.DataContext = this;
        InitializeComponent();

        this.DataObjectCollection = new ObservableCollection<DataObject>();
        this.DataObjectCollection.Add(new DataObject() { Id = 1, Object1 = "this", Object2 = "that" });
        this.DataObjectCollection.Add(new DataObject() { Id = 1, Object2 = "that" });

        this.SelectedItem = new DataObject();
    }

    private ObservableCollection<DataObject> dataObjectCollection;
    private DataObject selectedItem;

    public ObservableCollection<DataObject> DataObjectCollection
    {
        get { return this.dataObjectCollection; }
        set
        {
            dataObjectCollection = value;
            OnNotifyPropertyChanged("DataObjectCollection");
        }
    }

    public DataObject SelectedItem
    {
        get { return this.selectedItem; }
        set
        {
            selectedItem = value;
            OnNotifyPropertyChanged("SelectedItem");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnNotifyPropertyChanged(string property = "")
    {
        if(PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }
}
}
</code>```

Here is the xaml(This is something like what i'd want to do, using the itemtemplate or something similar, and then a converter to call this GetDisplay function)

```<code><Window x:Class="TestApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TestApp"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <local:DataObjectToDisplayDataObjectConverter x:Key="ToDisplayConverter"/>
</Window.Resources>
<StackPanel>
    <DataGrid ItemsSource="{Binding DataObjectCollection}" SelectedItem="{Binding SelectedItem}" MinHeight="200">
        <DataGrid.ItemTemplate>
            <DataTemplate>
                <ContentPresenter Content="{Binding Converter={StaticResource ToDisplayConverter}}"/>
            </DataTemplate>
        </DataGrid.ItemTemplate>
    </DataGrid>
</StackPanel>
</Window>
</code>```

And Finally the converter

```<code>using System;
using System.Globalization;
using System.Windows.Data;

namespace TestApp
{
public class DataObjectToDisplayDataObjectConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null && value.GetType() == typeof(DataObject))
        {
            DataObject dataObj = (DataObject)value;
            dataObj.GetDisplayObject();
            return dataObj;
        }
        return "Invalid Value";
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
}
</code>```

I am open to suggestions, but this is a small example. In our actual application changing one thing will most likely cascade into a huge ordeal.

答:
If I were you I would have change close coupling of view with ViewModel, Like creating new MainWindowViewModel class & having all properties in it.

Another thing I see GetDisplayObject method, what's the need of calling such a method from converter.

You can re-factor this code & put in the converter something like this.

```<code>public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    DataObject dataObj = value as DataObject;

    if (value == null)
    {
        return "Invalid Value";
    }

    if (dataObj.Object1 == null)
    {
        return "Object1";
    }

    return "Object2";
 }
</code>```

Body:
I have a unique situation. In one class, I have an inner class that acts as pretty much just a "display" class. In the outer class there is a method called GetDisplayObject that returns a type of the inner class.

I'm trying to bind to a datagrid with the outer class, but by using a converter I'd like to get the correct display. This way I won't have to change a bunch of code in our application and just add a few lines in a couple .xaml files.

I made a little test app that pretty much sums up my problem at it's most basic level. Ideally I'd like to solve the problem by using a converter and returning values only as a display, that way when i'm using the SelectedItem I won't have to change a ton of code that is depending on that certain type(In this case would be the DataObject type).

So here is the objects i'm stuck dealing with

namespace TestApp
{
    public class DataObject
    {
        public class DataObjectDisplay
        {
            public string ObjectDisplay { get; set; }
        }

        // props
        public int Id { get; set; }
        public object Object1 { get; set; }
        public object Object2 { get; set; }

        // method for getting the display
        public DataObjectDisplay GetDisplayObject()
        {
            DataObjectDisplay display = new DataObjectDisplay();

            // logic for determining which object should be displayed
            if(Object1 == null)
            {
                display.ObjectDisplay = "Object1";
            }
            else
            {
                display.ObjectDisplay = "Object2";
            }
            return display;
        }
    }
}

Here is the Code Behind of my xaml

using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;

namespace TestApp
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        this.DataContext = this;
        InitializeComponent();

        this.DataObjectCollection = new ObservableCollection<DataObject>();
        this.DataObjectCollection.Add(new DataObject() { Id = 1, Object1 = "this", Object2 = "that" });
        this.DataObjectCollection.Add(new DataObject() { Id = 1, Object2 = "that" });

        this.SelectedItem = new DataObject();
    }

    private ObservableCollection<DataObject> dataObjectCollection;
    private DataObject selectedItem;

    public ObservableCollection<DataObject> DataObjectCollection
    {
        get { return this.dataObjectCollection; }
        set
        {
            dataObjectCollection = value;
            OnNotifyPropertyChanged("DataObjectCollection");
        }
    }

    public DataObject SelectedItem
    {
        get { return this.selectedItem; }
        set
        {
            selectedItem = value;
            OnNotifyPropertyChanged("SelectedItem");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnNotifyPropertyChanged(string property = "")
    {
        if(PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }
}
}

Here is the xaml(This is something like what i'd want to do, using the itemtemplate or something similar, and then a converter to call this GetDisplay function)

<Window x:Class="TestApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TestApp"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <local:DataObjectToDisplayDataObjectConverter x:Key="ToDisplayConverter"/>
</Window.Resources>
<StackPanel>
    <DataGrid ItemsSource="{Binding DataObjectCollection}" SelectedItem="{Binding SelectedItem}" MinHeight="200">
        <DataGrid.ItemTemplate>
            <DataTemplate>
                <ContentPresenter Content="{Binding Converter={StaticResource ToDisplayConverter}}"/>
            </DataTemplate>
        </DataGrid.ItemTemplate>
    </DataGrid>
</StackPanel>
</Window>

And Finally the converter

using System;
using System.Globalization;
using System.Windows.Data;

namespace TestApp
{
public class DataObjectToDisplayDataObjectConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null && value.GetType() == typeof(DataObject))
        {
            DataObject dataObj = (DataObject)value;
            dataObj.GetDisplayObject();
            return dataObj;
        }
        return "Invalid Value";
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
}

I am open to suggestions, but this is a small example. In our actual application changing one thing will most likely cascade into a huge ordeal.

Body:
If I were you I would have change close coupling of view with ViewModel, Like creating new MainWindowViewModel class & having all properties in it.

Another thing I see GetDisplayObject method, what's the need of calling such a method from converter.

You can re-factor this code & put in the converter something like this.

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    DataObject dataObj = value as DataObject;

    if (value == null)
    {
        return "Invalid Value";
    }

    if (dataObj.Object1 == null)
    {
        return "Object1";
    }

    return "Object2";
 }


问:
Selenium Webdriver Java: Unable to perform click operation by Actions in Chrome
I am using Selenium Webdriver(Java) for my Automation. For one of my use-case, I need to click based on co-ordinates. I am using following code to perform this operation:

```<code>Actions act = new Actions(driver);
act.moveByOffset(236, 92).click().perform();
</code>```

Above code is working perfectly in Firefox(Gecko driver). But with Chrome driver, it is not working. Any idea?

Is there any other way to perform this.

答:
I think you can try what Santosh has suggested

```<code>act.moveByOffset(236, 92).click().build().perform();
</code>```

However, this should not make much of a difference as the perform() already contains the build action but this might be a workaround for your problem.

Body:
I am using Selenium Webdriver(Java) for my Automation. For one of my use-case, I need to click based on co-ordinates. I am using following code to perform this operation:

Actions act = new Actions(driver);
act.moveByOffset(236, 92).click().perform();

Above code is working perfectly in Firefox(Gecko driver). But with Chrome driver, it is not working. Any idea?

Is there any other way to perform this.

Body:
I think you can try what Santosh has suggested

act.moveByOffset(236, 92).click().build().perform();

However, this should not make much of a difference as the perform() already contains the build action but this might be a workaround for your problem.


问:
How to get list of available serial ports in my pc using Java?
I just run some codes to get a list of available ports n my cmputer and it returned me false when I have 3 com ports that are free. How do I solve this prob?

My codes:

```<code>public static void main(String[] args) {
        //SerialParameters params=new SerialParameters();
       // System.out.println(CommPortIdentifier.PORT_SERIAL );
        Enumeration portList = CommPortIdentifier.getPortIdentifiers();
        System.out.println(portList.hasMoreElements());
        while(portList.hasMoreElements()){
            System.out.println("Has more elements");
             CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
               if (portId.getPortType() == CommPortIdentifier.PORT_PARALLEL) {
                    System.out.println(portId.getName());
               }
               else{
                     System.out.println(portId.getName());
               }

        }
}
</code>```

Output :
false

答:
It appears your setup of the javax.comm API may not be correct. Make sure you have done the following:

Placed the comm.jar file in the jre/lib/ext directory.

Placed the javax.comm.properties file in the jre/lib directory.

Placed the win32com.dll in the jre/bin directory.

Each of the above components "should" be available here.

Body:
I just run some codes to get a list of available ports n my cmputer and it returned me false when I have 3 com ports that are free. How do I solve this prob?

My codes:

public static void main(String[] args) {
        //SerialParameters params=new SerialParameters();
       // System.out.println(CommPortIdentifier.PORT_SERIAL );
        Enumeration portList = CommPortIdentifier.getPortIdentifiers();
        System.out.println(portList.hasMoreElements());
        while(portList.hasMoreElements()){
            System.out.println("Has more elements");
             CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
               if (portId.getPortType() == CommPortIdentifier.PORT_PARALLEL) {
                    System.out.println(portId.getName());
               }
               else{
                     System.out.println(portId.getName());
               }

        }
}

Output :
false


问:
How to reduce pdf file to convert in special character after reading in asp.net c#.?
Here is my Code method which is m using to read my pdf files from folder. but when i run my code the files are read and it convert the content of pdf file into special character. How could I reduce it to convert in special character.</p>

```<code>foreach (string file in Directory.GetFiles(@"E:\\Rida\","*.pdf"))
{
    string contents = File.ReadAllText(file);
    lblPdfContent.Text = contents.ToString();
}
</code>```

答: File.ReadAllText reads a text file and not a PDF file ( https://msdn.microsoft.com/en-us/library/system.io.file.readalltext(v=vs.110).aspx ).</p>

Body:
Here is my Code method which is m using to read my pdf files from folder. but when i run my code the files are read and it convert the content of pdf file into special character. How could I reduce it to convert in special character.

foreach (string file in Directory.GetFiles(@"E:\\Rida\","*.pdf"))
{
    string contents = File.ReadAllText(file);
    lblPdfContent.Text = contents.ToString();
}


问:
Adding android fragment terminates the app
I am a newbie to Android development and I created a blank fragment, which has a textview by default. I tried to add the fragment to my main activity and I am getting following error:

Connected to process 3689 on device samsung-gt_i9300-32305248b97211f9
Application terminated.

Not getting any other exception reason.

```<code> <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorWhite"
    tools:context="com.ideasurge.winfertility.AccountActivity">

    <ImageView
        android:id="@+id/titleImageView"
        android:layout_width="wrap_content"
        android:layout_height="80dp"
        android:layout_marginLeft="30dp"
        android:layout_marginStart="30dp"
        android:layout_marginRight="30dp"
        android:layout_marginEnd="30dp"
        android:scaleType="centerInside"
        android:background="@color/colorWhite"
        app:srcCompat="@drawable/wftitleimage" />

    <TextView
        android:id="@+id/fertilityTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Your Fertility Companion"
        android:textStyle="bold"
        android:textSize="20sp"
        android:textColor="@color/colorBlack"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:layout_marginTop="20dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/titleImageView"/>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fragmentPlaceholder"
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/fertilityTextView">

        <!-- Fragment will go here eventually, but it's not added in the layout -->

    </LinearLayout>

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

Here is Java code:

```<code> AccountFragment fragment = new AccountFragment();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.fragmentPlaceholder, fragment);
    ft.commit();
</code>```

答:
You can have fragments in a LinearLayout. even you can have multiple fragments in LinearLayout.

you can find some documentation help here

The problem with your code is that because you didn't specify fragment class. so, it's unknown to the 'Activity' what to inflate.

Try something like this when you declare fragment in the layout.

```<code><fragment
    class="com.atwork.demo.ListFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</code>```

create referenced fragment class to inflate it on activity attach.

To attach multiple fragments to LinearLayout, you can find help in this SO answer here

TIP

considering it's your complete layout file, try to create a root Layout and then create subRoot Layouts as you want.

declare the namespace in the parent layout.

Body:
I am a newbie to Android development and I created a blank fragment, which has a textview by default. I tried to add the fragment to my main activity and I am getting following error:

Connected to process 3689 on device samsung-gt_i9300-32305248b97211f9
Application terminated.

Not getting any other exception reason.

 <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorWhite"
    tools:context="com.ideasurge.winfertility.AccountActivity">

    <ImageView
        android:id="@+id/titleImageView"
        android:layout_width="wrap_content"
        android:layout_height="80dp"
        android:layout_marginLeft="30dp"
        android:layout_marginStart="30dp"
        android:layout_marginRight="30dp"
        android:layout_marginEnd="30dp"
        android:scaleType="centerInside"
        android:background="@color/colorWhite"
        app:srcCompat="@drawable/wftitleimage" />

    <TextView
        android:id="@+id/fertilityTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Your Fertility Companion"
        android:textStyle="bold"
        android:textSize="20sp"
        android:textColor="@color/colorBlack"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:layout_marginTop="20dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/titleImageView"/>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fragmentPlaceholder"
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/fertilityTextView">

    </LinearLayout>

</android.support.constraint.ConstraintLayout>

Here is Java code:

 AccountFragment fragment = new AccountFragment();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.fragmentPlaceholder, fragment);
    ft.commit();

Body:
You can have fragments in a LinearLayout. even you can have multiple fragments in LinearLayout.

you can find some documentation help here

The problem with your code is that because you didn't specify fragment class. so, it's unknown to the 'Activity' what to inflate.

Try something like this when you declare fragment in the layout.

<fragment
    class="com.atwork.demo.ListFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

create referenced fragment class to inflate it on activity attach.

To attach multiple fragments to LinearLayout, you can find help in this SO answer here

TIP

considering it's your complete layout file, try to create a root Layout and then create subRoot Layouts as you want.

declare the namespace in the parent layout.


问:
How do I type using my keyboard on the iphone simulator?
I used to be able to type with my real mac keyboard after launching the iPhone Simulator. Typing with the on-screen simulator keyboard is just horrible when testing with large amounts of text.

No matter what I do, I can't get my keyboard to type anymore inside the simulator. Even if I have "Simulate Hardware Keyboard" switched ON, it just won't type anything. Can someone please tell me what I'm doing wrong? Is there no way to type using the real keyboard anymore?

答:
MY PROBLEM WAS KEYBOARD IS SHOWING AND KEYSTROKES NOT DETECTING. AND I FOUND THE SOLUTION:

You don't need to quit the keyboard.

Try Hardware->Keyboard->Connect Hardware Keyboard directly

ContentLicense: CC BY-SA 2.5


问:
Regex to obfuscate substring of a repeating substring
Given a string like:

```<code>abc_1234 xyz def_123aa4a56
</code>```

I want to replace parts of it so the output is:

```<code>abc_*******z def_*******56
</code>```

The rules are:

abc_ and def_ are kind of delimiters, so anything between the two are part of the previous delimiter string.

The string between the abc_ and def_, and the next delimited string should be replaced by *, except for the last 2 characters of that substring. In the above example, abc_1234 xyz  (note trailing space), got turned into abc_*******z

答:
```<code>prefixes = %w|abc_ def_|
input = "Hello abc_111def_frg def_333World abc_444"
input.gsub(/(#{Regexp.union(prefixes)})../, "\\1**")
#⇒ "Hello abc_**1def_**g def_**3World abc_**4"
</code>```

Body:
Given a string like:

abc_1234 xyz def_123aa4a56

I want to replace parts of it so the output is:

abc_*******z def_*******56

The rules are:

abc_ and def_ are kind of delimiters, so anything between the two are part of the previous delimiter string.

The string between the abc_ and def_, and the next delimited string should be replaced by *, except for the last 2 characters of that substring. In the above example, abc_1234 xyz  (note trailing space), got turned into abc_*******z


问:
Is there any way to display a Windows form BEFORE the "Startup" form is loaded in VB.NET?
My company's main software package includes a hefty configuration library which loads on startup. This config library includes some mandatory settings which, if not supplied (via command line arguments), cause the entire application to exit.

This has never been an issue for our users, who launch the software via scripts which have the needed command line arguments supplied automatically. But sometimes when debugging our software we developers forget to specify the necessary arguments in Visual Studio's debug options; it's then very annoying to be greeted with the message Config specification invalid -- missing required parameters X, Y, and Z -- shutting down (I'm paraphrasing, of course).

It's not really a big deal, just an annoyance. Still, I felt it worthwhile to throw together a little form to make this process a little less painful; it notifies the user which parameters are missing and allows him/her to specify values for those parameters directly on the form, without having to restart the application.

My intentions were good (I think?), but it seems I can't get this solution to actually work. The problem is that after I've launched our software with missing settings, the form pops up and prompts me as expected; but after I've entered the required parameters and it's time for the application to "really" start, I get this InvalidOperationException:

SetCompatibleTextRenderingDefault must
  be called before the first
  IWin32Window object is created in the
  application.

I think I understand what's going on here: the VB.NET project I'm working on is doing something like this "behind the scenes"*:

```<code>Sub Main()
    Application.EnableVisualStyles()
    Application.SetCompatibleTextRenderingDefault(False)
    Application.Run(New MainForm)
End Sub
</code>```

That call to SetCompatibleTextRenderingDefault is, apparently, throwing an exception because a form was already created and displayed prior to its execution.

Is there any way around this? Is there perhaps a more "proper" solution to this problem that I'm not thinking of (i.e., should I not be trying to collect user input via a form at all)?

*This is a best guess based on what I've seen in C# WinForms projects. Strangely, unless I'm missing something, it seems that VB.NET WinForms projects completely hide this from the developer.

答:
Do make sure that you have the application framework option turned off and Sub Main selected as the starting method.  Make it look similar to this:</p>

```<code>Sub Main(ByVal args() As String)
    Application.EnableVisualStyles()
    Application.SetCompatibleTextRenderingDefault(False)
    If args.Length = 0 Then
        Using dlg As New OptionsDialog
            If dlg.ShowDialog <> DialogResult.OK Then Return
            '' Use dlg result...
        End Using
    End If
    Application.Run(New MainForm)
End Sub
</code>```

Body:
My company's main software package includes a hefty configuration library which loads on startup. This config library includes some mandatory settings which, if not supplied (via command line arguments), cause the entire application to exit.

This has never been an issue for our users, who launch the software via scripts which have the needed command line arguments supplied automatically. But sometimes when debugging our software we developers forget to specify the necessary arguments in Visual Studio's debug options; it's then very annoying to be greeted with the message Config specification invalid -- missing required parameters X, Y, and Z -- shutting down (I'm paraphrasing, of course).

It's not really a big deal, just an annoyance. Still, I felt it worthwhile to throw together a little form to make this process a little less painful; it notifies the user which parameters are missing and allows him/her to specify values for those parameters directly on the form, without having to restart the application.

My intentions were good (I think?), but it seems I can't get this solution to actually work. The problem is that after I've launched our software with missing settings, the form pops up and prompts me as expected; but after I've entered the required parameters and it's time for the application to "really" start, I get this InvalidOperationException:

SetCompatibleTextRenderingDefault must
  be called before the first
  IWin32Window object is created in the
  application.

I think I understand what's going on here: the VB.NET project I'm working on is doing something like this "behind the scenes"*:

Sub Main()
    Application.EnableVisualStyles()
    Application.SetCompatibleTextRenderingDefault(False)
    Application.Run(New MainForm)
End Sub

That call to SetCompatibleTextRenderingDefault is, apparently, throwing an exception because a form was already created and displayed prior to its execution.

Is there any way around this? Is there perhaps a more "proper" solution to this problem that I'm not thinking of (i.e., should I not be trying to collect user input via a form at all)?

*This is a best guess based on what I've seen in C# WinForms projects. Strangely, unless I'm missing something, it seems that VB.NET WinForms projects completely hide this from the developer.

Body:
Do make sure that you have the application framework option turned off and Sub Main selected as the starting method.  Make it look similar to this:

Sub Main(ByVal args() As String)
    Application.EnableVisualStyles()
    Application.SetCompatibleTextRenderingDefault(False)
    If args.Length = 0 Then
        Using dlg As New OptionsDialog
            If dlg.ShowDialog <> DialogResult.OK Then Return
            '' Use dlg result...
        End Using
    End If
    Application.Run(New MainForm)
End Sub


问:
Global var vs Shared Instance swift
What is the difference between global variable and shared instance in Swift? what are their respective field of use? Could anyone clarify their concept based upon Swift.</p>

答:
Singleton (sharing instance)

Ensure that only one instance of a singleton object is created & It's provide a globally accessible through shared instance of an object that could be shared even across an app.
The dispatch_once function, which executes a block once and only once for the lifetime of an app.

Global variable

Apple documentation says Global variables are variables that are defined outside of any function, method, closure, or type context.

Title: Global var vs Shared Instance swift


答:
Is this what you are looking for?

```<code>str = "Hello abc_111def_frg def_333World abc_444"

str.scan(/(?<=abc_|def_)(?:[[:alpha:]]+|[[:digit:]]+)/)
  # => ["111", "frg", "333", "444"]
</code>```

I've assumed the string following "abc_" or "def_" is either all digits or all letters. It won't work if, for example, you wished to extract "a1b" from "abc_a1b cat". You need to better define the rules for what terminates the strings you want.

The regular expression reads, "Following the string "abc_" or "def_" (a positive lookbehind that is not part of the match), match a string of digits or a string of letters".

Title: Regex to obfuscate substring of a repeating substring

Body:
Is this what you are looking for?

str = "Hello abc_111def_frg def_333World abc_444"

str.scan(/(?<=abc_|def_)(?:[[:alpha:]]+|[[:digit:]]+)/)
  # => ["111", "frg", "333", "444"]

I've assumed the string following "abc_" or "def_" is either all digits or all letters. It won't work if, for example, you wished to extract "a1b" from "abc_a1b cat". You need to better define the rules for what terminates the strings you want.

The regular expression reads, "Following the string "abc_" or "def_" (a positive lookbehind that is not part of the match), match a string of digits or a string of letters".


问:
Can we write a .setOnAction() into another .setOnAction() block in JavaFX?
I am a beginner in Java since I took my first programming class last semester and I am trying to keep practicing this summer. I was working on something very basic and simple but I figured out I had a problem.

```<code>public void start(Stage primaryStage) {
    try {
        BorderPane root = new BorderPane();
        Scene scene = new Scene(root,400,400);

scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.setTitle("My little success story");

        TextInputDialog entername = new TextInputDialog("Your name");
        entername.setTitle("Player Information");
        entername.setHeaderText("What is going to be the name of the `person we'll follow?");`
        entername.setContentText("Please enter your name:");

        Optional<String>result = entername.showAndWait();
        if (result.isPresent()){
            name = result.get();
        }

        Image roleplay1 =new Image("Roleplay - 1.jpg");
        ImageView image1A = new ImageView();

        image1A.setImage(roleplay1);
        image1A.setFitHeight(400);
        image1A.setFitWidth(400);
        image1A.setSmooth(true);
        root.getChildren().add(image1A);

        Label welcome = new Label("Welcome "+name+" it's 2:00 `p.m."+newLine`
                +"You either can go to your bio class or to the gym.");

        HBox HWelcome = new HBox(welcome);
        HWelcome.setAlignment(Pos.BOTTOM_CENTER);
        HWelcome.setStyle("-fx-background-color: #faffff");

        Button goToClass = new Button("Go to class");
        goToClass.setPrefWidth(120.);

        Button goToGym = new Button("Go to the gym");
        goToGym.setPrefWidth(120.);

        HBox choice = new HBox(goToClass, goToGym);
        choice.setAlignment(Pos.BOTTOM_CENTER);
        choice.setSpacing(70.);
        choice.setPadding(new Insets(30));

        root.setBottom(HWelcome);
        root.setCenter(choice);

        goToClass.setOnAction(new EventHandler <ActionEvent>(){

            public void handle1(ActionEvent e){

                BorderPane root = new BorderPane();
                Scene scene = new Scene(root,400,400);

scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
                primaryStage.setScene(scene);
                primaryStage.setTitle("Roleplay");

                Image roleplay2A = new Image("Roleplay - 2A.jpg");
                ImageView image2A = new ImageView();

                image2A.setImage(roleplay2A);
                image2A.setSmooth(true);
                image2A.setFitHeight(400.);
                image2A.setFitWidth(400.);
                root.getChildren().add(image2A);

                Label scenario = new Label("You've arrived to class in `time."+newLine+`
                        "You are lucky, it was very important `today."+newLine+`
                        "You can team up with your best friend or with `the nerd.");`

                HBox HinClass = new HBox(scenario);
                HinClass.setAlignment(Pos.BOTTOM_CENTER);
                HinClass.setStyle("-fx-background-color: #faffff");

                Button yourFriend = new Button("Your friend");
                yourFriend.setPrefWidth(120.);

                Button theNerd = new Button("The nerd");
                theNerd.setPrefWidth(120.);

                HBox choice = new HBox(yourFriend, theNerd);
                choice.setAlignment(Pos.BOTTOM_CENTER);
                choice.setSpacing(70.);
                choice.setPadding(new Insets(30));

                root.setBottom(HinClass);
                root.setCenter(choice);

            }

            yourFriend.setOnAction(new EventHandler <ActionEvent>(){

                public void handle(ActionEvent e){

                            BorderPane root = new BorderPane();
                            Scene scene = new Scene(root,400,400);

scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
                            primaryStage.setScene(scene);
                            primaryStage.setTitle("Roleplay");

                            Image image = new Image("Roleplay 3 - `A.jpg");`
                            ImageView img = new ImageView(image);
                            root.getChildren().add(img);
                            img.setSmooth(true);

                        }

                    });

        });
</code>```

So everything goes fine when I use my first button with

```<code>    goToClass.setOnAction(new EventHandler <ActionEvent>(){
</code>```

But then, when I try to continue using the same technique of creating a new window with two buttons every time the user clicks on a button with this code

```<code>   yourFriend.setOnAction(new EventHandler <ActionEvent>(){
</code>```

it says that there is some kind of syntax error and I can't go further.

I really don't know if I've been clear since this is my first question posted here but I hope you guys will be able to help me!

Thanks a lot,

答:
I haven't tested your code, but I only intend to help you eliminate the compilation errors as you say you're a Java beginner</p>

```<code>package com.test;

import java.util.Optional;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextInputDialog;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class Random
{
    public void start(Stage primaryStage)
    {
        try
        {
            BorderPane root = new BorderPane();
            Scene scene = new Scene(root, 400, 400);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.setTitle("My little success story");

            TextInputDialog entername = new TextInputDialog("Your name");
            entername.setTitle("Player Information");
            entername.setHeaderText("What is going to be the name of the `person we'll follow?");
            entername.setContentText("Please enter your name:");

            Optional<String> result = entername.showAndWait();
            String name = "";
            if (result.isPresent())
            {
                name = result.get();
            }

            Image roleplay1 = new Image("Roleplay - 1.jpg");
            ImageView image1A = new ImageView();

            image1A.setImage(roleplay1);
            image1A.setFitHeight(400);
            image1A.setFitWidth(400);
            image1A.setSmooth(true);
            root.getChildren().add(image1A);

            Label welcome = new Label("Welcome " + name + " it's 2:00 `p.m." + System.lineSeparator() +
                "You either can go to your bio class or to the gym.");

            HBox HWelcome = new HBox(welcome);
            HWelcome.setAlignment(Pos.BOTTOM_CENTER);
            HWelcome.setStyle("-fx-background-color: #faffff");

            Button goToClass = new Button("Go to class");
            goToClass.setPrefWidth(120.);

            Button goToGym = new Button("Go to the gym");
            goToGym.setPrefWidth(120.);

            HBox choice = new HBox(goToClass, goToGym);
            choice.setAlignment(Pos.BOTTOM_CENTER);
            choice.setSpacing(70.);
            choice.setPadding(new Insets(30));

            root.setBottom(HWelcome);
            root.setCenter(choice);

            goToClass.setOnAction(new EventHandler<ActionEvent>()
            {

                Button yourFriend = new Button("Your friend");

                public void handle(ActionEvent e)
                {

                    BorderPane root = new BorderPane();
                    Scene scene = new Scene(root, 400, 400);
                    scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
                    primaryStage.setScene(scene);
                    primaryStage.setTitle("Roleplay");

                    Image roleplay2A = new Image("Roleplay - 2A.jpg");
                    ImageView image2A = new ImageView();

                    image2A.setImage(roleplay2A);
                    image2A.setSmooth(true);
                    image2A.setFitHeight(400.);
                    image2A.setFitWidth(400.);
                    root.getChildren().add(image2A);

                    Label scenario = new Label("You've arrived to class in `time." + System.lineSeparator() +
                        "You are lucky, it was very important `today." + System.lineSeparator() +
                        "You can team up with your best friend or with `the nerd.");

                    HBox HinClass = new HBox(scenario);
                    HinClass.setAlignment(Pos.BOTTOM_CENTER);
                    HinClass.setStyle("-fx-background-color: #faffff");

                    yourFriend.setPrefWidth(120.);

                    Button theNerd = new Button("The nerd");
                    theNerd.setPrefWidth(120.);

                    HBox choice = new HBox(yourFriend, theNerd);
                    choice.setAlignment(Pos.BOTTOM_CENTER);
                    choice.setSpacing(70.);
                    choice.setPadding(new Insets(30));

                    root.setBottom(HinClass);
                    root.setCenter(choice);

                    yourFriend.setOnAction(new EventHandler<ActionEvent>()
                    {
                        public void handle(ActionEvent e)
                        {

                            BorderPane root = new BorderPane();
                            Scene scene = new Scene(root, 400, 400);
                            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
                            primaryStage.setScene(scene);
                            primaryStage.setTitle("Roleplay");

                            Image image = new Image("Roleplay 3 - `A.jpg");
                            ImageView img = new ImageView(image);
                            root.getChildren().add(img);
                            img.setSmooth(true);
                        }
                    });
                }
            });
        }
        finally
        {

        }
    }
}
</code>```

Body:
I am a beginner in Java since I took my first programming class last semester and I am trying to keep practicing this summer. I was working on something very basic and simple but I figured out I had a problem.

public void start(Stage primaryStage) {
    try {
        BorderPane root = new BorderPane();
        Scene scene = new Scene(root,400,400);

scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.setTitle("My little success story");

        TextInputDialog entername = new TextInputDialog("Your name");
        entername.setTitle("Player Information");
        entername.setHeaderText("What is going to be the name of the `person we'll follow?");`
        entername.setContentText("Please enter your name:");

        Optional<String>result = entername.showAndWait();
        if (result.isPresent()){
            name = result.get();
        }

        Image roleplay1 =new Image("Roleplay - 1.jpg");
        ImageView image1A = new ImageView();

        image1A.setImage(roleplay1);
        image1A.setFitHeight(400);
        image1A.setFitWidth(400);
        image1A.setSmooth(true);
        root.getChildren().add(image1A);

        Label welcome = new Label("Welcome "+name+" it's 2:00 `p.m."+newLine`
                +"You either can go to your bio class or to the gym.");

        HBox HWelcome = new HBox(welcome);
        HWelcome.setAlignment(Pos.BOTTOM_CENTER);
        HWelcome.setStyle("-fx-background-color: #faffff");

        Button goToClass = new Button("Go to class");
        goToClass.setPrefWidth(120.);

        Button goToGym = new Button("Go to the gym");
        goToGym.setPrefWidth(120.);

        HBox choice = new HBox(goToClass, goToGym);
        choice.setAlignment(Pos.BOTTOM_CENTER);
        choice.setSpacing(70.);
        choice.setPadding(new Insets(30));

        root.setBottom(HWelcome);
        root.setCenter(choice);

        goToClass.setOnAction(new EventHandler <ActionEvent>(){

            public void handle1(ActionEvent e){

                BorderPane root = new BorderPane();
                Scene scene = new Scene(root,400,400);

scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
                primaryStage.setScene(scene);
                primaryStage.setTitle("Roleplay");

                Image roleplay2A = new Image("Roleplay - 2A.jpg");
                ImageView image2A = new ImageView();

                image2A.setImage(roleplay2A);
                image2A.setSmooth(true);
                image2A.setFitHeight(400.);
                image2A.setFitWidth(400.);
                root.getChildren().add(image2A);

                Label scenario = new Label("You've arrived to class in `time."+newLine+`
                        "You are lucky, it was very important `today."+newLine+`
                        "You can team up with your best friend or with `the nerd.");`

                HBox HinClass = new HBox(scenario);
                HinClass.setAlignment(Pos.BOTTOM_CENTER);
                HinClass.setStyle("-fx-background-color: #faffff");

                Button yourFriend = new Button("Your friend");
                yourFriend.setPrefWidth(120.);

                Button theNerd = new Button("The nerd");
                theNerd.setPrefWidth(120.);

                HBox choice = new HBox(yourFriend, theNerd);
                choice.setAlignment(Pos.BOTTOM_CENTER);
                choice.setSpacing(70.);
                choice.setPadding(new Insets(30));

                root.setBottom(HinClass);
                root.setCenter(choice);

            }

            yourFriend.setOnAction(new EventHandler <ActionEvent>(){

                public void handle(ActionEvent e){

                            BorderPane root = new BorderPane();
                            Scene scene = new Scene(root,400,400);

scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
                            primaryStage.setScene(scene);
                            primaryStage.setTitle("Roleplay");

                            Image image = new Image("Roleplay 3 - `A.jpg");`
                            ImageView img = new ImageView(image);
                            root.getChildren().add(img);
                            img.setSmooth(true);

                        }

                    });

        });

So everything goes fine when I use my first button with

    goToClass.setOnAction(new EventHandler <ActionEvent>(){

But then, when I try to continue using the same technique of creating a new window with two buttons every time the user clicks on a button with this code

   yourFriend.setOnAction(new EventHandler <ActionEvent>(){

it says that there is some kind of syntax error and I can't go further.

I really don't know if I've been clear since this is my first question posted here but I hope you guys will be able to help me!

Thanks a lot,

Body:
I haven't tested your code, but I only intend to help you eliminate the compilation errors as you say you're a Java beginner

package com.test;

import java.util.Optional;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextInputDialog;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class Random
{
    public void start(Stage primaryStage)
    {
        try
        {
            BorderPane root = new BorderPane();
            Scene scene = new Scene(root, 400, 400);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.setTitle("My little success story");

            TextInputDialog entername = new TextInputDialog("Your name");
            entername.setTitle("Player Information");
            entername.setHeaderText("What is going to be the name of the `person we'll follow?");
            entername.setContentText("Please enter your name:");

            Optional<String> result = entername.showAndWait();
            String name = "";
            if (result.isPresent())
            {
                name = result.get();
            }

            Image roleplay1 = new Image("Roleplay - 1.jpg");
            ImageView image1A = new ImageView();

            image1A.setImage(roleplay1);
            image1A.setFitHeight(400);
            image1A.setFitWidth(400);
            image1A.setSmooth(true);
            root.getChildren().add(image1A);

            Label welcome = new Label("Welcome " + name + " it's 2:00 `p.m." + System.lineSeparator() +
                "You either can go to your bio class or to the gym.");

            HBox HWelcome = new HBox(welcome);
            HWelcome.setAlignment(Pos.BOTTOM_CENTER);
            HWelcome.setStyle("-fx-background-color: #faffff");

            Button goToClass = new Button("Go to class");
            goToClass.setPrefWidth(120.);

            Button goToGym = new Button("Go to the gym");
            goToGym.setPrefWidth(120.);

            HBox choice = new HBox(goToClass, goToGym);
            choice.setAlignment(Pos.BOTTOM_CENTER);
            choice.setSpacing(70.);
            choice.setPadding(new Insets(30));

            root.setBottom(HWelcome);
            root.setCenter(choice);

            goToClass.setOnAction(new EventHandler<ActionEvent>()
            {

                Button yourFriend = new Button("Your friend");

                public void handle(ActionEvent e)
                {

                    BorderPane root = new BorderPane();
                    Scene scene = new Scene(root, 400, 400);
                    scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
                    primaryStage.setScene(scene);
                    primaryStage.setTitle("Roleplay");

                    Image roleplay2A = new Image("Roleplay - 2A.jpg");
                    ImageView image2A = new ImageView();

                    image2A.setImage(roleplay2A);
                    image2A.setSmooth(true);
                    image2A.setFitHeight(400.);
                    image2A.setFitWidth(400.);
                    root.getChildren().add(image2A);

                    Label scenario = new Label("You've arrived to class in `time." + System.lineSeparator() +
                        "You are lucky, it was very important `today." + System.lineSeparator() +
                        "You can team up with your best friend or with `the nerd.");

                    HBox HinClass = new HBox(scenario);
                    HinClass.setAlignment(Pos.BOTTOM_CENTER);
                    HinClass.setStyle("-fx-background-color: #faffff");

                    yourFriend.setPrefWidth(120.);

                    Button theNerd = new Button("The nerd");
                    theNerd.setPrefWidth(120.);

                    HBox choice = new HBox(yourFriend, theNerd);
                    choice.setAlignment(Pos.BOTTOM_CENTER);
                    choice.setSpacing(70.);
                    choice.setPadding(new Insets(30));

                    root.setBottom(HinClass);
                    root.setCenter(choice);

                    yourFriend.setOnAction(new EventHandler<ActionEvent>()
                    {
                        public void handle(ActionEvent e)
                        {

                            BorderPane root = new BorderPane();
                            Scene scene = new Scene(root, 400, 400);
                            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
                            primaryStage.setScene(scene);
                            primaryStage.setTitle("Roleplay");

                            Image image = new Image("Roleplay 3 - `A.jpg");
                            ImageView img = new ImageView(image);
                            root.getChildren().add(img);
                            img.setSmooth(true);
                        }
                    });
                }
            });
        }
        finally
        {

        }
    }
}


问:
Calculating confidence intervals for a non-normal distribution
First, I should specify that my knowledge of statistics is fairly limited, so please forgive me if my question seems trivial or perhaps doesn't even make sense.

I have data that doesn't appear to be normally distributed.  Typically, when I plot confidence intervals, I would use the mean +- 2 standard deviations, but I don't think that is acceptible for a non-uniform distribution.  My sample size is currently set to 1000 samples, which would seem like enough to determine if it was a normal distribution or not.

I use Matlab for all my processing, so are there any functions in Matlab that would make it easy to calculate the confidence intervals (say 95%)?

I know there are the 'quantile' and 'prctile' functions, but I'm not sure if that's what I need to use.  The function 'mle' also returns confidence intervals for normally distributed data, although you can also supply your own pdf.

Could I use ksdensity to create a pdf for my data, then feed that pdf into the mle function to give me confidence intervals?

Also, how would I go about determining if my data is normally distributed.  I mean I can currently tell just by looking at the histogram or pdf from ksdensity, but is there a way to quantitatively measure it?

Thanks!

答:
So there are a couple of questions there.  Here are some suggestions

You are right that a mean of 1000 samples should be normally distributed (unless your data is "heavy tailed", which I'm assuming is not the case).  to get a 1-alpha-confidence interval for the mean (in your case alpha = 0.05) you can use the 'norminv' function.  For example say we wanted a 95% CI for the mean a sample of data X,  then we can type

```<code>N = 1000;             % sample size
X = exprnd(3,N,1);    % sample from a non-normal distribution
mu = mean(X);         % sample mean (normally distributed)
sig = std(X)/sqrt(N); % sample standard deviation of the mean
alphao2 = .05/2;      % alpha over 2
CI = [mu + norminv(alphao2)*sig ,...
      mu - norminv(alphao2)*sig  ]

CI =

2.9369    3.3126
</code>```

Testing if a data sample is normally distribution can be done in a lot of ways.  One simple method is with a QQ plot.  To do this, use 'qqplot(X)' where X is your data sample.  If the result is approximately a straight line, the sample is normal.  If the result is not a straight line, the sample is not normal.

For example if X = exprnd(3,1000,1) as above, the sample is non-normal and the qqplot is very non-linear:

```<code>X = exprnd(3,1000,1);
qqplot(X);
</code>```

On the other hand if the data is normal the qqplot will give a straight line:

```<code>qqplot(randn(1000,1))
</code>```

Body:
So there are a couple of questions there.  Here are some suggestions

You are right that a mean of 1000 samples should be normally distributed (unless your data is "heavy tailed", which I'm assuming is not the case).  to get a 1-alpha-confidence interval for the mean (in your case alpha = 0.05) you can use the 'norminv' function.  For example say we wanted a 95% CI for the mean a sample of data X,  then we can type

N = 1000;             % sample size
X = exprnd(3,N,1);    % sample from a non-normal distribution
mu = mean(X);         % sample mean (normally distributed)
sig = std(X)/sqrt(N); % sample standard deviation of the mean
alphao2 = .05/2;      % alpha over 2
CI = [mu + norminv(alphao2)*sig ,...
      mu - norminv(alphao2)*sig  ]

CI =

2.9369    3.3126

Testing if a data sample is normally distribution can be done in a lot of ways.  One simple method is with a QQ plot.  To do this, use 'qqplot(X)' where X is your data sample.  If the result is approximately a straight line, the sample is normal.  If the result is not a straight line, the sample is not normal.

For example if X = exprnd(3,1000,1) as above, the sample is non-normal and the qqplot is very non-linear:

X = exprnd(3,1000,1);
qqplot(X);

On the other hand if the data is normal the qqplot will give a straight line:

qqplot(randn(1000,1))


问:
scipy.optimize.fmin_bfgs single function computes both f and fprime
I'm using scipy.optimize.fmin_bfgs(f, init_theta, fprime) to minimize f, which has gradient fprime. I compute f and fprime in a single function because most of the computation is the same so there's no need to do it twice.

Is there any way to call fmin_bfgs() specifying a single function that returns both f and fprime?

答:
There doesn't seem to be a way to do this directly. But scipy.optimize.minimize does let you do this. You can pass a the value True for fprime instead of a function. This signals that f returns a tuple of the function value and the gradient. You can invoke minimize with method='BFGS' to get the effect you want.

It's enlightening to look at the source code for minimize. Both it and fmin_bfgs eventually call _minimize_bfgs, which takes f and fprime as separate function arguments. When fprime is a boolean,minimize cleverly constructs fprime as an object that remembers the last value returned by f, and caches the gradient information.


问:
NameError: name 'hasattr' is not defined - Python3.6, Django1.11, Ubuntu16-17, Apache2.4, mod_wsgi
I've set up my Python/Django virtual environment, and mod_wsgi in daemon mode,  and am pretty sure (done this before) it's "mostly correct" except I get the following error...

```<code>[Thu Jul 06 00:35:26.986363 2017] [mpm_event:notice] [pid 11442:tid 140557758930432] AH00493: SIGUSR1 received.  Doing graceful restart
Exception ignored in: <object repr() failed>
Traceback (most recent call last):
  File "/home/jamin/www/dev.tir.com/py361ve/lib/python3.6/site-packages/PIL/Image.py", line 572, in __del__
NameError: name 'hasattr' is not defined
[Thu Jul 06 00:35:27.194483 2017] [mpm_event:notice] [pid 11442:tid 140557758930432] AH00489: Apache/2.4.25 (Ubuntu) mod_wsgi/4.5.15 Python/3.6 configured -- resuming normal operations
[Thu Jul 06 00:35:27.194561 2017] [core:notice] [pid 11442:tid 140557758930432] AH00094: Command line: '/usr/sbin/apache2'
</code>```

My django app itself is loading fine through wsgi.py but it seems something to do with core python (error with my setup likely) is going wrong as per: NameError: name 'hasattr' is not defined

In the browser - I get a plain "Server Error (500)" page and not the standard Apache "Internal Server Error" page.

Leaving out my VirtualHost and steps beyond here are the basic steps I put together for myself if you can spot anything... (I've tried all the different python packages as well not just -venv)

```<code>Install Python 3.6 and virtualenv
    sudo apt-get update
    sudo apt-get install python3.6-venv
    sudo apt-get install virtualenv
(or find the latest and greatest python package that includes pip https://packages.ubuntu.com/ )

Install Apache2
    sudo apt-get install apache2 apache2-dev

Make and enter a folder for your project - then build a Virtual Environment in it
    mkdir ~/example.com
    cd ~/example.com
    virtualenv --python=/usr/bin/python3.6 py361ve

Enter your new Virtual Environment to install packages to it
    source py361ve/bin/activate

Install Django, mod_wsgi, and any other needed packages
    pip install django
    pip install mod_wsgi
    pip install ...
(no need for pip3 in virtual environment - django should be the latest release)

Run following command and place output in apache config file ( in /etc/apache2/ )
    mod_wsgi-express module-config

Exit your virtual environment
    deactivate
(You can re-enter your virtual environment any time using the source method in step 8)
</code>```

Here's what happens when I stop/start/restart apache2...

```<code>apache2 stop...

[Thu Jul 06 06:01:34.190940 2017] [mpm_event:notice] [pid 2015:tid 140157449797120] AH00491: caught SIGTERM, shutting down
_______________________________________________________________
apache2 start...

[Thu Jul 06 06:02:39.076741 2017] [mpm_event:notice] [pid 2181:tid 140553545080320] AH00489: Apache/2.4.25 (Ubuntu) mod_wsgi/4.5.15 Python/3.6 configured -- resuming $
[Thu Jul 06 06:02:39.076890 2017] [core:notice] [pid 2181:tid 140553545080320] AH00094: Command line: '/usr/sbin/apache2'
_______________________________________________________________
apache2 restart...

Exception ignored in: <object repr() failed>
Traceback (most recent call last):
  File "/home/jamin/www/dev.tir.com/py361ve/lib/python3.6/site-packages/PIL/Image.py", line 572, in __del__
NameError: name 'hasattr' is not defined
[Thu Jul 06 06:05:43.307877 2017] [mpm_event:notice] [pid 2181:tid 140553545080320] AH00491: caught SIGTERM, shutting down
[Thu Jul 06 06:05:43.492499 2017] [mpm_event:notice] [pid 2301:tid 140353155558912] AH00489: Apache/2.4.25 (Ubuntu) mod_wsgi/4.5.15 Python/3.6 configured -- resuming $
[Thu Jul 06 06:05:43.492705 2017] [core:notice] [pid 2301:tid 140353155558912] AH00094: Command line: '/usr/sbin/apache2'
</code>```

答:
This is likely due to code still running in background threads when the Python interpreter is being destroyed on process shutdown. What happens during interpreter destruction is that all modules get wiped out and attribute access of things often returns None as fallback. In this case looks like builtins module was wiped before the PIL object got destroyed and so it couldn't find hasattr.

Can you confirm this only happens when Apache is being restarted and processes shutdown?

Body:
I've set up my Python/Django virtual environment, and mod_wsgi in daemon mode,  and am pretty sure (done this before) it's "mostly correct" except I get the following error...

[Thu Jul 06 00:35:26.986363 2017] [mpm_event:notice] [pid 11442:tid 140557758930432] AH00493: SIGUSR1 received.  Doing graceful restart
Exception ignored in: <object repr() failed>
Traceback (most recent call last):
  File "/home/jamin/www/dev.tir.com/py361ve/lib/python3.6/site-packages/PIL/Image.py", line 572, in __del__
NameError: name 'hasattr' is not defined
[Thu Jul 06 00:35:27.194483 2017] [mpm_event:notice] [pid 11442:tid 140557758930432] AH00489: Apache/2.4.25 (Ubuntu) mod_wsgi/4.5.15 Python/3.6 configured -- resuming normal operations
[Thu Jul 06 00:35:27.194561 2017] [core:notice] [pid 11442:tid 140557758930432] AH00094: Command line: '/usr/sbin/apache2'

My django app itself is loading fine through wsgi.py but it seems something to do with core python (error with my setup likely) is going wrong as per: NameError: name 'hasattr' is not defined

In the browser - I get a plain "Server Error (500)" page and not the standard Apache "Internal Server Error" page.

Leaving out my VirtualHost and steps beyond here are the basic steps I put together for myself if you can spot anything... (I've tried all the different python packages as well not just -venv)

Install Python 3.6 and virtualenv
    sudo apt-get update
    sudo apt-get install python3.6-venv
    sudo apt-get install virtualenv
(or find the latest and greatest python package that includes pip https://packages.ubuntu.com/ )

Install Apache2
    sudo apt-get install apache2 apache2-dev

Make and enter a folder for your project - then build a Virtual Environment in it
    mkdir ~/example.com
    cd ~/example.com
    virtualenv --python=/usr/bin/python3.6 py361ve

Enter your new Virtual Environment to install packages to it
    source py361ve/bin/activate

Install Django, mod_wsgi, and any other needed packages
    pip install django
    pip install mod_wsgi
    pip install ...
(no need for pip3 in virtual environment - django should be the latest release)

Run following command and place output in apache config file ( in /etc/apache2/ )
    mod_wsgi-express module-config

Exit your virtual environment
    deactivate
(You can re-enter your virtual environment any time using the source method in step 8)

Here's what happens when I stop/start/restart apache2...

apache2 stop...

[Thu Jul 06 06:01:34.190940 2017] [mpm_event:notice] [pid 2015:tid 140157449797120] AH00491: caught SIGTERM, shutting down
_______________________________________________________________
apache2 start...

[Thu Jul 06 06:02:39.076741 2017] [mpm_event:notice] [pid 2181:tid 140553545080320] AH00489: Apache/2.4.25 (Ubuntu) mod_wsgi/4.5.15 Python/3.6 configured -- resuming $
[Thu Jul 06 06:02:39.076890 2017] [core:notice] [pid 2181:tid 140553545080320] AH00094: Command line: '/usr/sbin/apache2'
_______________________________________________________________
apache2 restart...

Exception ignored in: <object repr() failed>
Traceback (most recent call last):
  File "/home/jamin/www/dev.tir.com/py361ve/lib/python3.6/site-packages/PIL/Image.py", line 572, in __del__
NameError: name 'hasattr' is not defined
[Thu Jul 06 06:05:43.307877 2017] [mpm_event:notice] [pid 2181:tid 140553545080320] AH00491: caught SIGTERM, shutting down
[Thu Jul 06 06:05:43.492499 2017] [mpm_event:notice] [pid 2301:tid 140353155558912] AH00489: Apache/2.4.25 (Ubuntu) mod_wsgi/4.5.15 Python/3.6 configured -- resuming $
[Thu Jul 06 06:05:43.492705 2017] [core:notice] [pid 2301:tid 140353155558912] AH00094: Command line: '/usr/sbin/apache2'


问:
jQuery Search and Hightlight, 2 Colors - 2 Lists
I have some old code that I use to hightlight a list of words:

```<code>jQuery.fn.highlight = function(pat) {
 function innerHighlight(node, pat) {
  var skip = 0;
  if (node.nodeType == 3) {
   var pos = node.data.toUpperCase().indexOf(pat);
   if (pos >= 0) {
    var spannode = document.createElement('span');
    spannode.className = 'highlight';
    var middlebit = node.splitText(pos);
    var endbit = middlebit.splitText(pat.length);
    var middleclone = middlebit.cloneNode(true);
    spannode.appendChild(middleclone);
    middlebit.parentNode.replaceChild(spannode, middlebit);
    skip = 1;
   }
  }
  else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
   for (var i = 0; i < node.childNodes.length; ++i) {
    i += innerHighlight(node.childNodes[i], pat);
   }
  }
  return skip;
 }
 return this.length && pat && pat.length ? this.each(function() {
  innerHighlight(this, pat.toUpperCase());
 }) : this;
};

$(document).ready(function(){
 $("td").highlight("car")
 $("td").highlight("sales");
 $("td").highlight("income");
});

</script>;
</code>```

Very similar to this post: Search and Highlight in jQuery

But now I need the same script to highlight a 2nd list with a different color on the same page. What I am asking for is very similar to this post: Using multiple colors for highlighting

Can't seem to get it.

答:
(Updated answer based on OP's feedback...)

The quickest solution for you is to modify your existing function so that it accepts a 2nd argument specifying which CSS className to add to the highlight span.

(Or more specifically in my example below, not the entire CSS className, but just the color portion.  This is appended to the stem "highlight-" automatically to save you having to type the whole thing every time you call the function.)

So...

```<code>// 1. Change: jQuery.fn.highlight = function(pat) {
// to...
jQuery.fn.highlight = function(pat, color) {

// 2. Change: spannode.className = 'highlight';
// to...
spannode.className = 'highlight-'+color;
</code>```

Your function now accepts a 2nd argument called 'color' and spannode.className is dynamic according to the color specified.

```<code>// 3. Add some classes like these to your CSS...
//
.highlight-red {background-color:red;}
.highlight-green {background-color:green;}
.highlight-pink {color:white;font-weight:bold; background-color:pink;}

// 4. Then call your function like this...
//
$("td").highlight("car", 'red')
$("td").highlight("sales", 'green');
$("td").highlight("income", 'pink');
</code>```

Demo: Run it in JSFiddle...

Body:
I have some old code that I use to hightlight a list of words:

jQuery.fn.highlight = function(pat) {
 function innerHighlight(node, pat) {
  var skip = 0;
  if (node.nodeType == 3) {
   var pos = node.data.toUpperCase().indexOf(pat);
   if (pos >= 0) {
    var spannode = document.createElement('span');
    spannode.className = 'highlight';
    var middlebit = node.splitText(pos);
    var endbit = middlebit.splitText(pat.length);
    var middleclone = middlebit.cloneNode(true);
    spannode.appendChild(middleclone);
    middlebit.parentNode.replaceChild(spannode, middlebit);
    skip = 1;
   }
  }
  else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
   for (var i = 0; i < node.childNodes.length; ++i) {
    i += innerHighlight(node.childNodes[i], pat);
   }
  }
  return skip;
 }
 return this.length && pat && pat.length ? this.each(function() {
  innerHighlight(this, pat.toUpperCase());
 }) : this;
};

$(document).ready(function(){
 $("td").highlight("car")
 $("td").highlight("sales");
 $("td").highlight("income");
});

</script>;

Very similar to this post: Search and Highlight in jQuery

But now I need the same script to highlight a 2nd list with a different color on the same page. What I am asking for is very similar to this post: Using multiple colors for highlighting

Can't seem to get it.

Body:
(Updated answer based on OP's feedback...)

The quickest solution for you is to modify your existing function so that it accepts a 2nd argument specifying which CSS className to add to the highlight span.

(Or more specifically in my example below, not the entire CSS className, but just the color portion.  This is appended to the stem "highlight-" automatically to save you having to type the whole thing every time you call the function.)

So...

// 1. Change: jQuery.fn.highlight = function(pat) {
// to...
jQuery.fn.highlight = function(pat, color) {

// 2. Change: spannode.className = 'highlight';
// to...
spannode.className = 'highlight-'+color;

Your function now accepts a 2nd argument called 'color' and spannode.className is dynamic according to the color specified.

// 3. Add some classes like these to your CSS...
//
.highlight-red {background-color:red;}
.highlight-green {background-color:green;}
.highlight-pink {color:white;font-weight:bold; background-color:pink;}

// 4. Then call your function like this...
//
$("td").highlight("car", 'red')
$("td").highlight("sales", 'green');
$("td").highlight("income", 'pink');

Demo: Run it in JSFiddle...


问:
Warning and get error in admin modification page OpenCart 2.1.0.2
When I hit the refresh button in the admin > Extensions > Modifications page the page crashes and produces a page of failure errors in OpenCart 2.1.0.2

Following error got. Please help me. how can i fixed this issue.

Warning:
  fopen(/home/onlybrands1/public_html/system/modification/system/engine/action.php)
  failed to open stream: No such file or directory in
  /home/onlybrands1/public_html/admin/controller/extension/modification.php
  on line 408

Warning: fwrite() expects parameter 1 to be resource, boolean given in
  /home/onlybrands1/public_html/admin/controller/extension/modification.php
  on line 410

Warning: fclose() expects parameter 1 to be resource,  boolean given
  in
  /home/onlybrands1/public_html/admin/controller/extension/modification.php
  on line 412

Warning:
  fopen(/home/onlybrands1/public_html/system/modification/system/engine/loader.php):
  failed to open stream: No such file or directory in
  /home/onlybrands1/public_html/admin/controller/extension/modification.php
  on line 408

Warning: fwrite() expects parameter 1 to be resource,  boolean given
  in
  /home/onlybrands1/public_html/admin/controller/extension/modification.php
  on line 410

Warning: fclose() expects parameter 1 to be resource,
           boolean given in
           /home/onlybrands1/public_html/admin/controller/extension/modification.php
          on line 412

Warning:
  fopen(/home/onlybrands1/public_html/system/modification/system/library/config.php):
  failed to open stream: No such file or directory in
  /home/onlybrands1/public_html/admin/controller/extension/modification.php
  on line 408

Warning: fwrite() expects parameter 1 to be resource,
       boolean given in
       /home/onlybrands1/public_html/admin/controller/extension/modification.php
       on line 410

Warning: fclose() expects parameter 1 to be resource,  boolean given
  in
  /home/onlybrands1/public_html/admin/controller/extension/modification.php
  on line 412

Warning:
  fopen(/home/onlybrands1/public_html/system/modification/system/library/language.php):
  failed to open stream: No such file or directory in
  /home/onlybrands1/public_html/admin/controller/extension/modification.php
  on line 408

Warning: fwrite() expects parameter 1 to be resource,  boolean given
  in
  /home/onlybrands1/public_html/admin/controller/extension/modification.phpon
  line 410

Warning: fclose() expects parameter 1 to be resource,  boolean given
  in
  /home/onlybrands1/public_html/admin/controller/extension/modification.php
  on line 412

Warning: Cannot modify header information - headers already  sent by
  (output started at  /home/onlybrands1/public_html/admin/index.php:80)
  in  /home/onlybrands1/public_html/system/library/response.php on line
  12

答:
I have realized. this issue happen with wrong path in config.php file. has been modification folder location change(inside storage folder) than older version in OpenCart 2.1.0.2 by OpenCart.

and, Some user install OpenCart with quick setup feature from Hosting provider services. So, there, The proper path is not set in the config.php file with Hosting quick install feature in OpenCart 2.1.x. Version.

Here, You will need to set properly path for DIR_CACHE DIR_DOWNLOAD DIR_LOGS DIR_MODIFICATION DIR_UPLOAD in config.php(front & admin both config.php) file.

Wrong path for OpenCart 2.1.0.2. (this following path is for 2.0.x version)

```<code>define('DIR_CACHE', 'YOURSITE/system/cache/');
define('DIR_DOWNLOAD', 'YOURSITE/system/download/');
define('DIR_LOGS', 'YOURSITE/system/logs/');
define('DIR_MODIFICATION', 'YOURSITE/system/modification/');
define('DIR_UPLOAD', 'YOURSITE/system/upload/');
</code>```

Correct Path for OpenCart 2.1.0.2. Here, You will need to add /storage/ in following path. (front & admin both config.php file)

```<code>define('DIR_CACHE', 'YOURSITE/system/storage/cache/');
define('DIR_DOWNLOAD', 'YOURSITE/system/storage/download/');
define('DIR_LOGS', 'YOURSITE/system/storage/logs/');
define('DIR_MODIFICATION', 'YOURSITE/system/storage/modification/');
define('DIR_UPLOAD', 'YOURSITE/system/storage/upload/');
</code>```

Hope this will helpful for you.

Body:
I have realized. this issue happen with wrong path in config.php file. has been modification folder location change(inside storage folder) than older version in OpenCart 2.1.0.2 by OpenCart.

and, Some user install OpenCart with quick setup feature from Hosting provider services. So, there, The proper path is not set in the config.php file with Hosting quick install feature in OpenCart 2.1.x. Version.

Here, You will need to set properly path for DIR_CACHE DIR_DOWNLOAD DIR_LOGS DIR_MODIFICATION DIR_UPLOAD in config.php(front & admin both config.php) file.

Wrong path for OpenCart 2.1.0.2. (this following path is for 2.0.x version)

define('DIR_CACHE', 'YOURSITE/system/cache/');
define('DIR_DOWNLOAD', 'YOURSITE/system/download/');
define('DIR_LOGS', 'YOURSITE/system/logs/');
define('DIR_MODIFICATION', 'YOURSITE/system/modification/');
define('DIR_UPLOAD', 'YOURSITE/system/upload/');

Correct Path for OpenCart 2.1.0.2. Here, You will need to add /storage/ in following path. (front & admin both config.php file)

define('DIR_CACHE', 'YOURSITE/system/storage/cache/');
define('DIR_DOWNLOAD', 'YOURSITE/system/storage/download/');
define('DIR_LOGS', 'YOURSITE/system/storage/logs/');
define('DIR_MODIFICATION', 'YOURSITE/system/storage/modification/');
define('DIR_UPLOAD', 'YOURSITE/system/storage/upload/');

Hope this will helpful for you.


问:
ng-disable is not rendering properly

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
 $scope.firstName =false;
    $scope.toggle = function(){
        $scope.firstName =!$scope.firstName ;
    };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <body>
    <div ng-app="myApp" ng-controller="myCtrl">
      <button ng-click=toggle()>ToGgLe</button>
      <input type="text" ng-disabled="{{firstName}}">
   </div>
  </body>
</html></code>```

Here i'm trying to toggle the input field with the function as shown in code.I can see the value changing in the DOM but it is not rendered by angular properly...input is not toggling...Help me out...Thanks in advance

答:
You don't need to do string interpolation, as ngDisabled accepts a expression pass direct firstName .

```<code><input type="text" ng-disabled="firstName">
</code>```

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
 $scope.firstName =false;
    $scope.toggle = function(){
        $scope.firstName =!$scope.firstName ;
    };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <body>
    <div ng-app="myApp" ng-controller="myCtrl">
      <button ng-click=toggle()>ToGgLe</button>
      <input type="text" ng-disabled="firstName">
   </div>
  </body>
</html></code>```

Title: ng-disable is not rendering properly

Body:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
 $scope.firstName =false;
    $scope.toggle = function(){
        $scope.firstName =!$scope.firstName ;
    };
});

<!DOCTYPE html>

      <button ng-click=toggle()>ToGgLe</button>
      <input type="text" ng-disabled="{{firstName}}">

Here i'm trying to toggle the input field with the function as shown in code.I can see the value changing in the DOM but it is not rendered by angular properly...input is not toggling...Help me out...Thanks in advance

Body:
You don't need to do string interpolation, as ngDisabled accepts a expression pass direct firstName .

<input type="text" ng-disabled="firstName">

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
 $scope.firstName =false;
    $scope.toggle = function(){
        $scope.firstName =!$scope.firstName ;
    };
});

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <body>
    <div ng-app="myApp" ng-controller="myCtrl">
      <button ng-click=toggle()>ToGgLe</button>
      <input type="text" ng-disabled="firstName">
   </div>
  </body>
</html>


答:
You don't have to use interpolation operator {{}}

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
 $scope.firstName =false;
    $scope.toggle = function(){
        $scope.firstName =!$scope.firstName ;
    };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <body>
    <div ng-app="myApp" ng-controller="myCtrl">
      <button ng-click=toggle()>ToGgLe</button>
      <input type="text" ng-disabled="firstName">
   </div>
  </body>
</html></code>```

Title: ng-disable is not rendering properly

Body:
You don't have to use interpolation operator {{}}

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
 $scope.firstName =false;
    $scope.toggle = function(){
        $scope.firstName =!$scope.firstName ;
    };
});

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <body>
    <div ng-app="myApp" ng-controller="myCtrl">
      <button ng-click=toggle()>ToGgLe</button>
      <input type="text" ng-disabled="firstName">
   </div>
  </body>
</html>


问:
Leaflet marker on-click display data in div
I have a jacascript code which loads the geojson data from a file and displays circleMarkers (Cannot display normal markers as the popups don't work).

```<code>{
  $.ajax({
    dataType: "json",
    type: 'POST',
    url: "geojsonfile.php",
    beforeSend: function() {},
    success: function(data) {
      display = L.geoJson(data, {
        style: function(feature) {
          return {
            color: '#0515B5'
          };
        },
        pointToLayer: function(feature, latlng) {
          return new L.CircleMarker(latlng, {
            radius: 6,
            fillOpacity: 0.85
          });
        },
        onEachFeature: function(feature, layer) {
          layer.bindPopup("Name: " + feature.properties.name);
          document.getElementById("sname").innerHTML = feature.properties.name;
          layer.on({
            click: showData
          });

        }
      }).addTo(map);

    }
  }).error(function(xhr, status, error) {
    console.log(error);
  });

}

function showData(e) {
  $("#sdata").show();
}
</code>```

The html table where the data is to be displayed is

```<code><table  id="sdata">
  <tbody>
    <tr>
      <td> Name:</td>
      <td id="sname"></td>
    </tr>
  </tbody>
</table>
</code>```

But the problem is only the last value of the geojson is displayed in the table, Is it possible that onclicking the marker the value in the sname is displayed accordingly like the marker popup.

答:
May be this code

map.on('popupopen', function(e){
    var marker = e.popup._source;
});

will help you?
see: How to identify Leaflet's Marker during a `popupopen` event?

Body:
I have a jacascript code which loads the geojson data from a file and displays circleMarkers (Cannot display normal markers as the popups don't work).

{
  $.ajax({
    dataType: "json",
    type: 'POST',
    url: "geojsonfile.php",
    beforeSend: function() {},
    success: function(data) {
      display = L.geoJson(data, {
        style: function(feature) {
          return {
            color: '#0515B5'
          };
        },
        pointToLayer: function(feature, latlng) {
          return new L.CircleMarker(latlng, {
            radius: 6,
            fillOpacity: 0.85
          });
        },
        onEachFeature: function(feature, layer) {
          layer.bindPopup("Name: " + feature.properties.name);
          document.getElementById("sname").innerHTML = feature.properties.name;
          layer.on({
            click: showData
          });

        }
      }).addTo(map);

    }
  }).error(function(xhr, status, error) {
    console.log(error);
  });

}

function showData(e) {
  $("#sdata").show();
}

The html table where the data is to be displayed is

       Name:

But the problem is only the last value of the geojson is displayed in the table, Is it possible that onclicking the marker the value in the sname is displayed accordingly like the marker popup.


问:
NTFS Alternate Data Streams - Good or bad Idea?
I would like to store some Application-Related Metadata for Files, and NTFS Alternate Data Streams (AltDS) would allow me to store this metadata directly on the files rather than in a separate database.

I just don't feel like this is a good idea. I know that this only works on NTFS, but at least if the user copies/moves the files to a Non-NTFS drive they get a Warning from Windows (yeah, yeah, no one reads warnings, I know)-

But also, storing additional data on a file can become very wasteful, as the AltDS stay even if my Application is uninstalled. It's like a decade ago when people used "Registry Cleaners" to remove useless entries from the registry after uninstalling a program to make their system run faster (and less stable when the cleaner cleaned too much...).

I just wonder what they can be reasonably used for? Should they be completely left for Microsoft Apps to use? Or is there some sort of common policy what types of apps may use them (apart from malware)?

Edit: Just to clarify what my idea was. I'm in the early stages of writing a small document management system for myself. Because I want to have the freedom to move files around, I want to store metadata on the file so that if I move/rename/modify them, my app still recognizes them. It could either be the entire Metadata or just a GUID that works with a separate database.

To summarize the points given:

Pros:

Metadata moves with the file, so no need to recognize it through hashing or filename

Works with all FileTypes, even .txt files where it's impossible to store any data in the file itself

Cons:

Only works on NTFS which may not be the default file system in future Windows Versions

Although it would surprise me if MS doesn't automatically convert them if they ever get WinFS together

AltDS remain even if my App is uninstalled

Privacy concerns

Fragile

Most USB Sticks are FAT32. Many private file servers are Linux. Downloading a file from the internet should only transfer the file but not the streams. In short: It's rather easy to lose them.

答:
One thing I did NOT hear so far is using AltDS in applications where certain kind of information MUST be hidden (i.e. Medical applications), while it is desired to NOT hide other kind of information.

The reason I LOVE AltDS is exactly that: I can design a Medical Imaging system, where I keep medical images in the open (as BMP, i.e.) w/o any patient information details, because those I can keep in an AltDS. Bingo.
Advantage: If somebody copies the files to a thumb-drive - well, all that person gets is the BMP w/o the patient info.

Backup/Restore is always nasty - my solution was to move to a proprietary file-format on the backup, where the patient info is encoded/encrypted in the same file as the (raw) BMP.

Lastly, if you store the hidden information in XML format, your application may be gone but the information is still there. The information should be linked to the file itself, not the application. That should probably be stored somewhere else.

Overall I L-O-V-E AltDS. The lack of OS support (can't see the AltDS data), lack of general/public knowledge (who? what? Ads? What kinda advertisements) and the fact that I don't have to worry about that additional information to keep in sync with the main file (ahem Stream) allows me to design and implement really robust systems.
The Backup is a bummer - especially Joliet should have been designed to handle those AltDS - but I can live with it.

Just my 2c (well, maybe 3c...).