问:
How to specify a test with method name, class name and parameters in testng.xml?
I wish to have test level parameters in my testng.xml and below is the code present in my testng.xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="My Test Suite" verbose="1">
   <parameter name="param1" value="value1" />
   <parameter name="param2" value="value2" />
   <listeners>
      <listener class-name="TestListener" />
   </listeners>
   <test name="Test1">
      <parameter name="param" value="value" />
      <classes>
         <class name="ClassContainingTest1" />
         <methods>
            <include name="test1" />
         </methods>
      </classes>
   </test>
   <test name="Test2">
      <parameter name="param" value="value" />
      <classes>
         <class name="ClassContainingTest2" />
         <methods>
            <include name="test2" />
         </methods>
      </classes>
   </test>
</suite>
</code>```

But the XML editor highlights the classes tag in red. It seems something is wrong with my XML structure, but I'm unable to figure out the same.

Please help.

答:
The issue was with the methods tag not being inside the class tag.

Revising the XML code to below fixed the issue:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="My Test Suite" verbose="1">
   <parameter name="param1" value="value1" />
   <parameter name="param2" value="value2" />
   <listeners>
      <listener class-name="TestListener" />
   </listeners>
   <test name="Test1">
      <parameter name="param" value="value" />
      <classes>
         <class name="ClassContainingTest1">
            <methods>
               <include name="test1" />
            </methods>
         </class>
      </classes>
   </test>
   <test name="Test2">
      <parameter name="param" value="value" />
      <classes>
         <class name="ClassContainingTest2">
            <methods>
               <include name="test2" />
            </methods>
         </class>
      </classes>
   </test>
</suite>
</code>```

Body:
I wish to have test level parameters in my testng.xml and below is the code present in my testng.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="My Test Suite" verbose="1">
   <parameter name="param1" value="value1" />
   <parameter name="param2" value="value2" />
   <listeners>
      <listener class-name="TestListener" />
   </listeners>
   <test name="Test1">
      <parameter name="param" value="value" />
      <classes>
         <class name="ClassContainingTest1" />
         <methods>
            <include name="test1" />
         </methods>
      </classes>
   </test>
   <test name="Test2">
      <parameter name="param" value="value" />
      <classes>
         <class name="ClassContainingTest2" />
         <methods>
            <include name="test2" />
         </methods>
      </classes>
   </test>
</suite>

But the XML editor highlights the classes tag in red. It seems something is wrong with my XML structure, but I'm unable to figure out the same.

Please help.

Body:
The issue was with the methods tag not being inside the class tag.

Revising the XML code to below fixed the issue:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="My Test Suite" verbose="1">
   <parameter name="param1" value="value1" />
   <parameter name="param2" value="value2" />
   <listeners>
      <listener class-name="TestListener" />
   </listeners>
   <test name="Test1">
      <parameter name="param" value="value" />
      <classes>
         <class name="ClassContainingTest1">
            <methods>
               <include name="test1" />
            </methods>
         </class>
      </classes>
   </test>
   <test name="Test2">
      <parameter name="param" value="value" />
      <classes>
         <class name="ClassContainingTest2">
            <methods>
               <include name="test2" />
            </methods>
         </class>
      </classes>
   </test>
</suite>


来源: stackexchange

问:
May I get ng-model's key instead of value in ng-value?
I am trying to set up a radio selector based on an array and return the key instead of the value to the server.

Here is the array:

```<code>$scope.customer_types = ['a', 'b', 'c', 'd', 'other'];
</code>```

Here is the radio selector:

```<code><label style="margin-right:15px"><input type="radio" ng-model="ctype" ng-value="customer_type" name="customer_type">{{customer_type}}</label>
</code>```

Now $scope.ctype will store the selected customer type and return a number, for example if I select other it should send out 4 to the server. I can do a reverse filter for this but it seems to me if I can use something like ng-value="customer_type[key]" it would be a lot easier...

答:
ng-repeat="(customer_key,customer_type) in customer_types"

You will need to separate key and value in ng-repeat.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to set up a radio selector based on an array and return the key instead of the value to the server.

Here is the array:

$scope.customer_types = ['a', 'b', 'c', 'd', 'other'];

Here is the radio selector:

<input type="radio" ng-model="ctype" ng-value="customer_type" name="customer_type">{{customer_type}}

Now $scope.ctype will store the selected customer type and return a number, for example if I select other it should send out 4 to the server. I can do a reverse filter for this but it seems to me if I can use something like ng-value="customer_type[key]" it would be a lot easier...


问:
Unable to create Manhattan plot with d3
I have to make a Manhattan plot with d3.js using the dataset given below (a part):

```<code>[
    {
      'chromosome': 1,
      'values': [
        {
          'position': 78178310,
          'p_value': 7.17731162216
        },
        {
          'position': 78178493,
          'p_value': 3.03890339149
        },
        ..
      ]
    },
    {
      'chromosome': 2,
      'values': [
        {
          'position': 257683,
          'p_value': 6.08904891824
        },
        {
          'position': 257742,
          'p_value': 3.50110329843
        },
        ..
      ]
    },
  ]
</code>```

The x-axis has a domain with sub-domains. The domain is the chromosome, and the subdomain the positions for each chromosome. The y-axis shows the p-values. I'll explain my problem with the chart below:

My points are not being able to differentiate the positions. I need them to spread across the subdomain allocated to each position. My code:

```<code>const margin = { top: 20, right: 20, bottom: 30, left: 40 };
const width = 1260 - margin.left - margin.right;
const height = 500 - margin.top - margin.bottom;

const x0 = d3.scale.ordinal()
             .rangeRoundBands([0, width], .1);

const x1 = d3.scale.ordinal();
const y = d3.scale.linear()
            .range([height, 0]);

const color = d3.scale.category20c();

const xAxis = d3.svg.axis().scale(x0).orient('bottom');

const yAxis = d3.svg.axis().scale(y).orient('left').tickFormat(d3.format('.2s'));

let svg = d3.select('body').append('svg')
            .attr('width', width + margin.left + margin.right)
            .attr('height', height + margin.top + margin.bottom)
            .append('g')
            .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

d3.csv('test.csv', (error, data) => {

  if (error) {
    throw error;
  }

  const x0Max = d3.max(data, (d) => {
    return d.chromosome;
  });

  const x1Max = d3.max(data, (d) => {
    return parseInt(d.position);
  });

  const yMax = d3.max(data, (d) => {
    return parseFloat(d.p_value);
  });

  x0.domain(data.map((d) => { return d.chromosome }));
  console.log(x0.rangeBand());
  const x1 = d3.scale.ordinal()
              .domain(data.map((d) => { return d.position }))
              .rangeRoundBands([0, x0.rangeBand()]);
  y.domain([0, yMax]);

  svg.append('g')
    .attr('transform', 'translate(0, ' + height + ')')
    .call(xAxis)

  svg.append('g')
    .call(yAxis)
    .append('text')
    .attr('transform', 'rotate(-90)')
    .attr('y', 6)
    .attr('dy', '.71em')
    .style('text-anchor', 'end')
    .text('p-value');

  // formatData returns data in the format shown above in this post
  const input = formatData(data);

  const chromosome = svg.selectAll('.chr')
    .data(input)
    .enter().append('g')
    .attr('class', 'chr')
    .attr('x', (d) => {
      return x0(d.chromosome);
    })
    .attr('transform', (d) => {
      return 'translate(' + x0(d.chromosome) + ',0)';
    })
    .style('fill', (d) => {
      return color(d.chromosome);
    });

  chromosome.selectAll('circle')
    .data((d) => {
      return d.values;
    })
    .enter().append('circle')
    .attr('r', 3)
    .attr('cx', (d, i) => {
      return x1(d.position);
    })
    .attr('cy', (d) => {
      return y(d.p_value);
    });
});
</code>```

There is a SO post with almost the same problem. It was really helpful, but I can't get it to work with the accepted answer. Other than that, I am using this post as reference.

I want to make x1 my subdomain and x0 my primary domain, as shown in the grouped bar chart post. My problem is I cannot associate the subdomain with the domain properly. Also, this is my first attempt with d3.js and I haven't understood everything in the code I have written, as I have relied heavily on the example. Please help.

答:
I have created Manhattan chart for Cricket data.This will help you to create you manhattan plot in d3. It is based on D3 V4.

PLease refer this link

https://gist.github.com/ChandrakantThakkarDigiCorp/0620e41591f278431b8b98bfdf361b40

also you can see output here

http://bl.ocks.org/ChandrakantThakkarDigiCorp/0620e41591f278431b8b98bfdf361b40

Title: Unable to create Manhattan plot with d3

Body:
I have to make a Manhattan plot with d3.js using the dataset given below (a part):

[
    {
      'chromosome': 1,
      'values': [
        {
          'position': 78178310,
          'p_value': 7.17731162216
        },
        {
          'position': 78178493,
          'p_value': 3.03890339149
        },
        ..
      ]
    },
    {
      'chromosome': 2,
      'values': [
        {
          'position': 257683,
          'p_value': 6.08904891824
        },
        {
          'position': 257742,
          'p_value': 3.50110329843
        },
        ..
      ]
    },
  ]

The x-axis has a domain with sub-domains. The domain is the chromosome, and the subdomain the positions for each chromosome. The y-axis shows the p-values. I'll explain my problem with the chart below:

My points are not being able to differentiate the positions. I need them to spread across the subdomain allocated to each position. My code:

const margin = { top: 20, right: 20, bottom: 30, left: 40 };
const width = 1260 - margin.left - margin.right;
const height = 500 - margin.top - margin.bottom;

const x0 = d3.scale.ordinal()
             .rangeRoundBands([0, width], .1);

const x1 = d3.scale.ordinal();
const y = d3.scale.linear()
            .range([height, 0]);

const color = d3.scale.category20c();

const xAxis = d3.svg.axis().scale(x0).orient('bottom');

const yAxis = d3.svg.axis().scale(y).orient('left').tickFormat(d3.format('.2s'));

let svg = d3.select('body').append('svg')
            .attr('width', width + margin.left + margin.right)
            .attr('height', height + margin.top + margin.bottom)
            .append('g')
            .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

d3.csv('test.csv', (error, data) => {

  if (error) {
    throw error;
  }

  const x0Max = d3.max(data, (d) => {
    return d.chromosome;
  });

  const x1Max = d3.max(data, (d) => {
    return parseInt(d.position);
  });

  const yMax = d3.max(data, (d) => {
    return parseFloat(d.p_value);
  });

  x0.domain(data.map((d) => { return d.chromosome }));
  console.log(x0.rangeBand());
  const x1 = d3.scale.ordinal()
              .domain(data.map((d) => { return d.position }))
              .rangeRoundBands([0, x0.rangeBand()]);
  y.domain([0, yMax]);

  svg.append('g')
    .attr('transform', 'translate(0, ' + height + ')')
    .call(xAxis)

  svg.append('g')
    .call(yAxis)
    .append('text')
    .attr('transform', 'rotate(-90)')
    .attr('y', 6)
    .attr('dy', '.71em')
    .style('text-anchor', 'end')
    .text('p-value');

  // formatData returns data in the format shown above in this post
  const input = formatData(data);

  const chromosome = svg.selectAll('.chr')
    .data(input)
    .enter().append('g')
    .attr('class', 'chr')
    .attr('x', (d) => {
      return x0(d.chromosome);
    })
    .attr('transform', (d) => {
      return 'translate(' + x0(d.chromosome) + ',0)';
    })
    .style('fill', (d) => {
      return color(d.chromosome);
    });

  chromosome.selectAll('circle')
    .data((d) => {
      return d.values;
    })
    .enter().append('circle')
    .attr('r', 3)
    .attr('cx', (d, i) => {
      return x1(d.position);
    })
    .attr('cy', (d) => {
      return y(d.p_value);
    });
});

There is a SO post with almost the same problem. It was really helpful, but I can't get it to work with the accepted answer. Other than that, I am using this post as reference.

I want to make x1 my subdomain and x0 my primary domain, as shown in the grouped bar chart post. My problem is I cannot associate the subdomain with the domain properly. Also, this is my first attempt with d3.js and I haven't understood everything in the code I have written, as I have relied heavily on the example. Please help.


问:
Excel Macro Help - Stacking Macros
I am using the following subroutine to combine multiple Excel files from a single folder into a single workbook with multiple worksheets.

```<code>Sub Merge2MultiSheets()

Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim MyPath As String
Dim strFilename As String

Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
MyPath = "C:\MyPath" ' <-- Insert Absolute Folder Location
Set wbDst = Workbooks.Add(xlWBATWorksheet)
strFilename = Dir(MyPath & "\*.xls", vbNormal)

If Len(strFilename) = 0 Then Exit Sub

Do Until strFilename = ""
    Set wbSrc = Workbooks.Open(Filename:=MyPath & "\" & strFilename)
    Set wsSrc = wbSrc.Worksheets(1)
    wsSrc.Copy After:=wbDst.Worksheets(wbDst.Worksheets.Count)
    wbSrc.Close False
    strFilename = Dir()
Loop
wbDst.Worksheets(1).Delete

Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True

End Sub
</code>```

The end product is an excel file with multiple worksheets (as well as one blank Sheet 1). I was wondering how I can then apply another macro to this newly created Workbook. As an example, I wish for all the worksheets within this new workbook to have their Headers bold and coloured a certain way, and to have the empty Worksheet deleted.

eg:

```<code>Sub Headers()

Rows("1:1").Select
Selection.Font.Bold = True
With Selection.Interior
    .ColorIndex = 37
    .Pattern = xlSolid
End With
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeTop)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeRight)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideVertical)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With

End Sub
</code>```

答:
This code will do the following:

1) First, delete Sheet1 as you asked for in your post

2) Format the top row in the remaining sheets

```<code>Sub Headers()
Dim wkSheet As Worksheet

//Delete Sheet1. Note that alerts are turned off otherwise you are prompted with a dialog box to check you want to delete sheet1
Application.DisplayAlerts = False
Worksheets("Sheet1").Delete
Application.DisplayAlerts = False

//Loop through each worksheet in workbook sheet collection
For Each wkSheet In ActiveWorkbook.Worksheets
    With wkSheet.Rows("1:1")
        .Interior.ColorIndex = 37
        //Add additional formatting requirements here
    End With
Next

End Sub
</code>```

ContentLicense: CC BY-SA 2.5

Title: Excel Macro Help - Stacking Macros

Body:
I am using the following subroutine to combine multiple Excel files from a single folder into a single workbook with multiple worksheets.

Sub Merge2MultiSheets()

Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim MyPath As String
Dim strFilename As String

Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
MyPath = "C:\MyPath" ' <-- Insert Absolute Folder Location
Set wbDst = Workbooks.Add(xlWBATWorksheet)
strFilename = Dir(MyPath & "\*.xls", vbNormal)

If Len(strFilename) = 0 Then Exit Sub

Do Until strFilename = ""
    Set wbSrc = Workbooks.Open(Filename:=MyPath & "\" & strFilename)
    Set wsSrc = wbSrc.Worksheets(1)
    wsSrc.Copy After:=wbDst.Worksheets(wbDst.Worksheets.Count)
    wbSrc.Close False
    strFilename = Dir()
Loop
wbDst.Worksheets(1).Delete

Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True

End Sub

The end product is an excel file with multiple worksheets (as well as one blank Sheet 1). I was wondering how I can then apply another macro to this newly created Workbook. As an example, I wish for all the worksheets within this new workbook to have their Headers bold and coloured a certain way, and to have the empty Worksheet deleted.

eg:

Sub Headers()

Rows("1:1").Select
Selection.Font.Bold = True
With Selection.Interior
    .ColorIndex = 37
    .Pattern = xlSolid
End With
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeTop)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeRight)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideVertical)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With

End Sub

Body:
This code will do the following:

1) First, delete Sheet1 as you asked for in your post

2) Format the top row in the remaining sheets

Sub Headers()
Dim wkSheet As Worksheet

//Delete Sheet1. Note that alerts are turned off otherwise you are prompted with a dialog box to check you want to delete sheet1
Application.DisplayAlerts = False
Worksheets("Sheet1").Delete
Application.DisplayAlerts = False

//Loop through each worksheet in workbook sheet collection
For Each wkSheet In ActiveWorkbook.Worksheets
    With wkSheet.Rows("1:1")
        .Interior.ColorIndex = 37
        //Add additional formatting requirements here
    End With
Next

End Sub


问:
Crashing with 'unexpectedly found nil while unwrapping an optional' on UISegmentedControl setTitle method
I have a sourceViewController which is accessing a UISegmentedControl in destinationViewController. EventType is an enum defined as:

```<code>enum EventType: Int {
    case Rashifal, RashiGyan
}
</code>```

The title of segmentedControl on destinationViewController should change according to the change of the value of segmentedControl on sourceViewController.

Whenever the segmentedControl is tapped in sourceViewController, value changed is seen, as I have printed in the console. Now, I want to change the content of segmentedControl in destinationViewController according to the previously selected segmentedControl value in my sourceViewController.

The value of segmentedControl in destinationViewController works fine on the first run and as expected, but when I navigate to my sourceViewController and change the segmentedControl and navigate to destinationViewController, there's a crash with message Fatal error: unexpectedly found nil while unwrapping an Optional value in a console.

Here's how I have tried to change the value of my segmentedControl in destinationViewController from sourceViewController.

```<code> @IBAction func segmentedControlValueChanaged(_ sender: UISegmentedControl) {
    let eventType = EventType(rawValue: sender.selectedSegmentIndex)!

    let anotherVC = UIStoryboard(name: "Rashifal", bundle: nil).instantiateViewController(withIdentifier: "RashiDetailVC") as? RashiDetailVC
    switch eventType {
    case .Rashifal:
        print("at Rashifal")
        anotherVC?.segmentedControl.setTitle("दैनिक", forSegmentAt: 0)
        anotherVC?.segmentedControl.setTitle("साप्ताहिक", forSegmentAt: 1)
        anotherVC?.segmentedControl.setTitle("मासिक", forSegmentAt: 2)
        anotherVC?.segmentedControl.setTitle("वार्षिक", forSegmentAt: 3)
    case .RashiGyan:
        print("At RashiGyan")
        anotherVC?.segmentedControl.setTitle("विशेषता", forSegmentAt: 0)
        anotherVC?.segmentedControl.setTitle("शुभ/अशुभ", forSegmentAt: 1)
        anotherVC?.segmentedControl.setTitle("प्रेम", forSegmentAt: 2)
        anotherVC?.segmentedControl.setTitle("जीवन", forSegmentAt: 3)
    }

}
</code>```

What might have possibly gone wrong?

答:
To pass data to a VC that you are going to show, do not use the instantiateViewController method. That will give you a new VC, instead of the one that is going to be presented.

First, make a variable called eventType in the destination controller:

```<code>var eventType: EventType!
</code>```

Override prepareForSegue in source VC:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // make segmentedControl as an IBOutlet if you haven't done already
    let eventType = EventType(rawValue: segmentedControl.selectedSegmentIndex)!
    if let vc = segue.destination as? RashiDetailVC {
        vc.eventType = eventType
    }
}
</code>```

In the destination VC's viewDidLoad, do the switch statement:

```<code>        switch eventType {
        case .Rashifal:
            print("at Rashifal")
            segmentedControl.setTitle("दैनिक", forSegmentAt: 0)
            segmentedControl.setTitle("साप्ताहिक", forSegmentAt: 1)
            segmentedControl.setTitle("मासिक", forSegmentAt: 2)
            segmentedControl.setTitle("वार्षिक", forSegmentAt: 3)
        case .RashiGyan:
            print("At RashiGyan")
            segmentedControl.setTitle("विशेषता", forSegmentAt: 0)
            segmentedControl.setTitle("शुभ/अशुभ", forSegmentAt: 1)
            segmentedControl.setTitle("प्रेम", forSegmentAt: 2)
            segmentedControl.setTitle("जीवन", forSegmentAt: 3)
        }
</code>```

This ensures that the segmented control has been initialised before you set its title.

Body:
I have a sourceViewController which is accessing a UISegmentedControl in destinationViewController. EventType is an enum defined as:

enum EventType: Int {
    case Rashifal, RashiGyan
}

The title of segmentedControl on destinationViewController should change according to the change of the value of segmentedControl on sourceViewController.

Whenever the segmentedControl is tapped in sourceViewController, value changed is seen, as I have printed in the console. Now, I want to change the content of segmentedControl in destinationViewController according to the previously selected segmentedControl value in my sourceViewController.

The value of segmentedControl in destinationViewController works fine on the first run and as expected, but when I navigate to my sourceViewController and change the segmentedControl and navigate to destinationViewController, there's a crash with message Fatal error: unexpectedly found nil while unwrapping an Optional value in a console.

Here's how I have tried to change the value of my segmentedControl in destinationViewController from sourceViewController.

 @IBAction func segmentedControlValueChanaged(_ sender: UISegmentedControl) {
    let eventType = EventType(rawValue: sender.selectedSegmentIndex)!

    let anotherVC = UIStoryboard(name: "Rashifal", bundle: nil).instantiateViewController(withIdentifier: "RashiDetailVC") as? RashiDetailVC
    switch eventType {
    case .Rashifal:
        print("at Rashifal")
        anotherVC?.segmentedControl.setTitle("दैनिक", forSegmentAt: 0)
        anotherVC?.segmentedControl.setTitle("साप्ताहिक", forSegmentAt: 1)
        anotherVC?.segmentedControl.setTitle("मासिक", forSegmentAt: 2)
        anotherVC?.segmentedControl.setTitle("वार्षिक", forSegmentAt: 3)
    case .RashiGyan:
        print("At RashiGyan")
        anotherVC?.segmentedControl.setTitle("विशेषता", forSegmentAt: 0)
        anotherVC?.segmentedControl.setTitle("शुभ/अशुभ", forSegmentAt: 1)
        anotherVC?.segmentedControl.setTitle("प्रेम", forSegmentAt: 2)
        anotherVC?.segmentedControl.setTitle("जीवन", forSegmentAt: 3)
    }

}

What might have possibly gone wrong?

Body:
To pass data to a VC that you are going to show, do not use the instantiateViewController method. That will give you a new VC, instead of the one that is going to be presented.

First, make a variable called eventType in the destination controller:

var eventType: EventType!

Override prepareForSegue in source VC:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // make segmentedControl as an IBOutlet if you haven't done already
    let eventType = EventType(rawValue: segmentedControl.selectedSegmentIndex)!
    if let vc = segue.destination as? RashiDetailVC {
        vc.eventType = eventType
    }
}

In the destination VC's viewDidLoad, do the switch statement:

        switch eventType {
        case .Rashifal:
            print("at Rashifal")
            segmentedControl.setTitle("दैनिक", forSegmentAt: 0)
            segmentedControl.setTitle("साप्ताहिक", forSegmentAt: 1)
            segmentedControl.setTitle("मासिक", forSegmentAt: 2)
            segmentedControl.setTitle("वार्षिक", forSegmentAt: 3)
        case .RashiGyan:
            print("At RashiGyan")
            segmentedControl.setTitle("विशेषता", forSegmentAt: 0)
            segmentedControl.setTitle("शुभ/अशुभ", forSegmentAt: 1)
            segmentedControl.setTitle("प्रेम", forSegmentAt: 2)
            segmentedControl.setTitle("जीवन", forSegmentAt: 3)
        }

This ensures that the segmented control has been initialised before you set its title.


问:
Real Ajax Uploader Error: Cannot write on file
I'm building a site that requires the ability to upload large .wav files. I figured the best way to upload these files was via a jQuery plugin that could chunk the data to the server. I chose Real Ajax Uploader to do this.

I put the following together and it works great for smaller files:

```<code>$('.demo').ajaxupload({
    url : '/upload.php',
    remotePath: '/remote/path/',
    maxFiles: 1,
    maxFileSize: '250M',
 });
</code>```

The problem occurs when I have a larger file that involves "chunking". For some reason the script keeps giving me this error:

```<code>Cannot write on file.
</code>```

I've traced it down to this location in the upload.php file:

```<code>...
//start of the file upload, first chunk
if ($currByte == 0) {
    $tempFile           = tempnam($this->tempPath, 'axupload');
    $this->tempFileName = basename($tempFile);
}

// some rare times (on very very fast connection), file_put_contents will be unable to write on the file,
// so we try until it writes for a max of 5 times
$try = 5;
while (file_put_contents($tempFile, $fileChunk, FILE_APPEND) === false && $try > 0) {
   usleep(50);
   $try--;
}

//if the above fails then user cannot write file due to permission or other problems
if (!$try) {
   $this->message(-1, 'Cannot write on file.');
}
...
</code>```

I assumed this meant that $tempFile was not writable, so I added this bit:

```<code>...
//start of the file upload, first chunk
if ($currByte == 0) {
    $tempFile           = tempnam($this->tempPath, 'axupload');
    $this->tempFileName = basename($tempFile);
 }

 chmod($tempFile, 0755);
 ...
</code>```

I tried it again and I still had a problem, so I changed the permissions of /tmp to 755, thinking maybe that was the case. Again, nothing.

I could try to just change the location of my /tmp directory and have a more writable environment, but if there's an easier solution I'd rather go with that.

Thank you.

答:
First of all upload a small file in a directory and check whether it uploads successfully or not. If successful, than search for the php.ini setting file and check the following:

```<code>php_value upload_max_filesize 10M
php_value post_max_size 10M
php_value max_input_time 300
php_value max_execution_time 300
</code>```

update all the above settings to meet your requirement and after that restart the server and then try again.

Body:
I'm building a site that requires the ability to upload large .wav files. I figured the best way to upload these files was via a jQuery plugin that could chunk the data to the server. I chose Real Ajax Uploader to do this.

I put the following together and it works great for smaller files:

$('.demo').ajaxupload({
    url : '/upload.php',
    remotePath: '/remote/path/',
    maxFiles: 1,
    maxFileSize: '250M',
 });

The problem occurs when I have a larger file that involves "chunking". For some reason the script keeps giving me this error:

Cannot write on file.

I've traced it down to this location in the upload.php file:

...
//start of the file upload, first chunk
if ($currByte == 0) {
    $tempFile           = tempnam($this->tempPath, 'axupload');
    $this->tempFileName = basename($tempFile);
}

// some rare times (on very very fast connection), file_put_contents will be unable to write on the file,
// so we try until it writes for a max of 5 times
$try = 5;
while (file_put_contents($tempFile, $fileChunk, FILE_APPEND) === false && $try > 0) {
   usleep(50);
   $try--;
}

//if the above fails then user cannot write file due to permission or other problems
if (!$try) {
   $this->message(-1, 'Cannot write on file.');
}
...

I assumed this meant that $tempFile was not writable, so I added this bit:

...
//start of the file upload, first chunk
if ($currByte == 0) {
    $tempFile           = tempnam($this->tempPath, 'axupload');
    $this->tempFileName = basename($tempFile);
 }

 chmod($tempFile, 0755);
 ...

I tried it again and I still had a problem, so I changed the permissions of /tmp to 755, thinking maybe that was the case. Again, nothing.

I could try to just change the location of my /tmp directory and have a more writable environment, but if there's an easier solution I'd rather go with that.

Thank you.

Body:
First of all upload a small file in a directory and check whether it uploads successfully or not. If successful, than search for the php.ini setting file and check the following:

php_value upload_max_filesize 10M
php_value post_max_size 10M
php_value max_input_time 300
php_value max_execution_time 300

update all the above settings to meet your requirement and after that restart the server and then try again.


问:
Text Adventure, enemy stats not storing/updating from one method to another?
I have a system here that randomly generates an enemy character with random traits involving their race, gender, etc. When the string array enemyRace chooses one of the options I have a block of if-statements made to modify the health, defense, and money of whatever race is chosen.

Once that is finished it should display that information at the bottom in the EnemyStats() method but it doesn't, all stats show up as 0. I initialize the two methods in my Start class in the Main method.

Can you guys help to properly display its stats? Is it due to the fact that the methods are void? I'm still new to C# so any guidance will be appreciated.

class Start (Contains Main method)

```<code>        // Loading in objects
        Enemy enemy = new Enemy();

        // Loading in the game

        Console.WriteLine("Press enter to create a new character . . . ");
        string input = Console.ReadLine();
        Console.Clear();

        // Game Loop
        enemy.EnemySpawn();
        enemy.EnemyStats();
        Console.ReadLine();
</code>```

class Enemy

```<code>    Random random = new Random();

    // Enemy Base Stats
    public static int enemyHP;
    public static int enemyEP;
    public static int enemyCoins;

    // Enemy Attack
    public static int enemyMelee = 0;
    public static int enemyMagic = 0;
    public static int enemyRange = 0;

    // Enemy Defense
    public static int enemyMeleeDefense = 0;
    public static int enemyMagicDefense = 0;
    public static int enemyRangeDefense = 0;

    public void EnemySpawn()
    {

        string[] enemyGender = { "Male ", "Female " };
        string[] enemyRace = { "Human ", "Elf ", "Dwarf ", "Gnome ", "Halfling ", "Half-Elf ", "Half-Orc " };
        string[] enemyClass = { "Ranger", "Paladin", "Thief", "Mage", "Shaman", "Warlock", "Cleric", "Druid", "Monk", "Bard", "Mercenary", "Merchant" };

        // Determines if class is Melee, Magic, Healer, or Clerk
        int enemyClassChance = random.Next(1, 4);

        if (enemyRace.ToString() == "Human ")
        {
            enemyHP += 100;
            enemyEP += 80;
            enemyCoins += 10;

            enemyMelee += 5;
            enemyMagic += 5;
            enemyRange += 5;

            enemyMeleeDefense += 6;
            enemyMagicDefense += 5;
            enemyRangeDefense += 6;
        }
        else if (enemyRace.ToString() == "Elf ")
        {
            enemyHP += 90;
            enemyEP += 90;
            enemyCoins += 10;

            enemyMelee += 5;
            enemyMagic += 9;
            enemyRange += 8;

            enemyMeleeDefense += 4;
            enemyMagicDefense += 8;
            enemyRangeDefense += 4;
        }
        else if (enemyRace.ToString() == "Dwarf ")
        {
            enemyHP += 125;
            enemyEP += 100;
            enemyCoins += 10;

            enemyMelee += 8;
            enemyMagic += 5;
            enemyRange += 5;

            enemyMeleeDefense += 8;
            enemyMagicDefense += 3;
            enemyRangeDefense += 4;
        }
        else if (enemyRace.ToString() == "Gnome ")
        {
            enemyHP += 95;
            enemyEP += 80;
            enemyCoins += 10;

            enemyMelee += 4;
            enemyMagic += 8;
            enemyRange += 4;

            enemyMeleeDefense += 2;
            enemyMagicDefense += 6;
            enemyRangeDefense += 5;
        }
        else if (enemyRace.ToString() == "Halfling ")
        {
            enemyHP += 80;
            enemyEP += 75;
            enemyCoins += 10;

            enemyMelee += 3;
            enemyMagic += 10;
            enemyRange += 7;

            enemyMeleeDefense += 1;
            enemyMagicDefense += 9;
            enemyRangeDefense += 4;
        }
        else if (enemyRace.ToString() == "Half-Elf ")
        {
            enemyHP += 95;
            enemyEP += 80;
            enemyCoins += 10;

            enemyMelee += 2;
            enemyMagic += 8;
            enemyRange += 8;

            enemyMeleeDefense += 5;
            enemyMagicDefense += 8;
            enemyRangeDefense += 2;
        }
        else if (enemyRace.ToString() == "Half-Orc ")
        {
            enemyHP += 150;
            enemyEP += 125;
            enemyCoins += 10;

            enemyMelee += 10;
            enemyMagic += 1;
            enemyRange += 4;

            enemyMeleeDefense += 10;
            enemyMagicDefense += 1;
            enemyRangeDefense += 5;
        }

        switch (enemyClassChance)
        {
            case 1:
                Console.WriteLine(enemySpawnText[random.Next(0, enemySpawnText.Length)] + enemyGender[random.Next(0, enemyGender.Length)] +
                                  enemyRace[random.Next(0, enemyRace.Length)] + enemyClassMelee[random.Next(0, enemyClassMelee.Length)] + ".");
                break;
            case 2:
                Console.WriteLine(enemySpawnText[random.Next(0, enemySpawnText.Length)] + enemyGender[random.Next(0, enemyGender.Length)] +
                                  enemyRace[random.Next(0, enemyRace.Length)] + enemyClassMagic[random.Next(0, enemyClassMagic.Length)] + ".");
                break;
            case 3:
                Console.WriteLine(enemySpawnText[random.Next(0, enemySpawnText.Length)] + enemyGender[random.Next(0, enemyGender.Length)] +
                                  enemyRace[random.Next(0, enemyRace.Length)] + enemyClassHealer[random.Next(0, enemyClassHealer.Length)] + ".");
                break;
            case 4:
                Console.WriteLine(enemySpawnText[random.Next(0, enemySpawnText.Length)] + enemyGender[random.Next(0, enemyGender.Length)] +
                                  enemyRace[random.Next(0, enemyRace.Length)] + enemyClassClerk[random.Next(0, enemyClassClerk.Length)] + ".");
                break;
        }

    }

    public void EnemyStats()
    {
        Console.WriteLine("##################### ");
        Console.WriteLine("Enemy Statistics: ");
        Console.WriteLine(" ");
        Console.WriteLine("Melee:       {0}", enemyMelee);
        Console.WriteLine("Magic:       {0}", enemyMagic);
        Console.WriteLine("Range:       {0}", enemyRange);
        Console.WriteLine(" ");
        Console.WriteLine("Melee Defense:       {0}", enemyMeleeDefense);
        Console.WriteLine("Magic Defense:       {0}", enemyMagicDefense);
        Console.WriteLine("Range Defense:       {0}", enemyRangeDefense);
        Console.WriteLine("##################### ");
        Console.ReadLine();

    }
}
</code>```

}

答:
In your EnemySpawn() method instead of :

```<code> if (enemyRace.ToString() == "Human ")
</code>```

replace in every condition (i.e. in if block use enemyClassChance as index like below)

```<code>if (enemyRace[enemyClassChance].ToString() == "Human ")
</code>```

Also , I believe instead of

```<code> int enemyClassChance = random.Next(1, 4);
</code>```

it should be :

```<code>int enemyClassChance = random.Next(1, enemyRace.Length);
</code>```

Body:
I have a system here that randomly generates an enemy character with random traits involving their race, gender, etc. When the string array enemyRace chooses one of the options I have a block of if-statements made to modify the health, defense, and money of whatever race is chosen.

Once that is finished it should display that information at the bottom in the EnemyStats() method but it doesn't, all stats show up as 0. I initialize the two methods in my Start class in the Main method.

Can you guys help to properly display its stats? Is it due to the fact that the methods are void? I'm still new to C# so any guidance will be appreciated.

class Start (Contains Main method)

        // Loading in objects
        Enemy enemy = new Enemy();

        // Loading in the game

        Console.WriteLine("Press enter to create a new character . . . ");
        string input = Console.ReadLine();
        Console.Clear();

        // Game Loop
        enemy.EnemySpawn();
        enemy.EnemyStats();
        Console.ReadLine();

class Enemy

    Random random = new Random();

    // Enemy Base Stats
    public static int enemyHP;
    public static int enemyEP;
    public static int enemyCoins;

    // Enemy Attack
    public static int enemyMelee = 0;
    public static int enemyMagic = 0;
    public static int enemyRange = 0;

    // Enemy Defense
    public static int enemyMeleeDefense = 0;
    public static int enemyMagicDefense = 0;
    public static int enemyRangeDefense = 0;

    public void EnemySpawn()
    {

        string[] enemyGender = { "Male ", "Female " };
        string[] enemyRace = { "Human ", "Elf ", "Dwarf ", "Gnome ", "Halfling ", "Half-Elf ", "Half-Orc " };
        string[] enemyClass = { "Ranger", "Paladin", "Thief", "Mage", "Shaman", "Warlock", "Cleric", "Druid", "Monk", "Bard", "Mercenary", "Merchant" };

        // Determines if class is Melee, Magic, Healer, or Clerk
        int enemyClassChance = random.Next(1, 4);

        if (enemyRace.ToString() == "Human ")
        {
            enemyHP += 100;
            enemyEP += 80;
            enemyCoins += 10;

            enemyMelee += 5;
            enemyMagic += 5;
            enemyRange += 5;

            enemyMeleeDefense += 6;
            enemyMagicDefense += 5;
            enemyRangeDefense += 6;
        }
        else if (enemyRace.ToString() == "Elf ")
        {
            enemyHP += 90;
            enemyEP += 90;
            enemyCoins += 10;

            enemyMelee += 5;
            enemyMagic += 9;
            enemyRange += 8;

            enemyMeleeDefense += 4;
            enemyMagicDefense += 8;
            enemyRangeDefense += 4;
        }
        else if (enemyRace.ToString() == "Dwarf ")
        {
            enemyHP += 125;
            enemyEP += 100;
            enemyCoins += 10;

            enemyMelee += 8;
            enemyMagic += 5;
            enemyRange += 5;

            enemyMeleeDefense += 8;
            enemyMagicDefense += 3;
            enemyRangeDefense += 4;
        }
        else if (enemyRace.ToString() == "Gnome ")
        {
            enemyHP += 95;
            enemyEP += 80;
            enemyCoins += 10;

            enemyMelee += 4;
            enemyMagic += 8;
            enemyRange += 4;

            enemyMeleeDefense += 2;
            enemyMagicDefense += 6;
            enemyRangeDefense += 5;
        }
        else if (enemyRace.ToString() == "Halfling ")
        {
            enemyHP += 80;
            enemyEP += 75;
            enemyCoins += 10;

            enemyMelee += 3;
            enemyMagic += 10;
            enemyRange += 7;

            enemyMeleeDefense += 1;
            enemyMagicDefense += 9;
            enemyRangeDefense += 4;
        }
        else if (enemyRace.ToString() == "Half-Elf ")
        {
            enemyHP += 95;
            enemyEP += 80;
            enemyCoins += 10;

            enemyMelee += 2;
            enemyMagic += 8;
            enemyRange += 8;

            enemyMeleeDefense += 5;
            enemyMagicDefense += 8;
            enemyRangeDefense += 2;
        }
        else if (enemyRace.ToString() == "Half-Orc ")
        {
            enemyHP += 150;
            enemyEP += 125;
            enemyCoins += 10;

            enemyMelee += 10;
            enemyMagic += 1;
            enemyRange += 4;

            enemyMeleeDefense += 10;
            enemyMagicDefense += 1;
            enemyRangeDefense += 5;
        }

        switch (enemyClassChance)
        {
            case 1:
                Console.WriteLine(enemySpawnText[random.Next(0, enemySpawnText.Length)] + enemyGender[random.Next(0, enemyGender.Length)] +
                                  enemyRace[random.Next(0, enemyRace.Length)] + enemyClassMelee[random.Next(0, enemyClassMelee.Length)] + ".");
                break;
            case 2:
                Console.WriteLine(enemySpawnText[random.Next(0, enemySpawnText.Length)] + enemyGender[random.Next(0, enemyGender.Length)] +
                                  enemyRace[random.Next(0, enemyRace.Length)] + enemyClassMagic[random.Next(0, enemyClassMagic.Length)] + ".");
                break;
            case 3:
                Console.WriteLine(enemySpawnText[random.Next(0, enemySpawnText.Length)] + enemyGender[random.Next(0, enemyGender.Length)] +
                                  enemyRace[random.Next(0, enemyRace.Length)] + enemyClassHealer[random.Next(0, enemyClassHealer.Length)] + ".");
                break;
            case 4:
                Console.WriteLine(enemySpawnText[random.Next(0, enemySpawnText.Length)] + enemyGender[random.Next(0, enemyGender.Length)] +
                                  enemyRace[random.Next(0, enemyRace.Length)] + enemyClassClerk[random.Next(0, enemyClassClerk.Length)] + ".");
                break;
        }

    }

    public void EnemyStats()
    {
        Console.WriteLine("##################### ");
        Console.WriteLine("Enemy Statistics: ");
        Console.WriteLine(" ");
        Console.WriteLine("Melee:       {0}", enemyMelee);
        Console.WriteLine("Magic:       {0}", enemyMagic);
        Console.WriteLine("Range:       {0}", enemyRange);
        Console.WriteLine(" ");
        Console.WriteLine("Melee Defense:       {0}", enemyMeleeDefense);
        Console.WriteLine("Magic Defense:       {0}", enemyMagicDefense);
        Console.WriteLine("Range Defense:       {0}", enemyRangeDefense);
        Console.WriteLine("##################### ");
        Console.ReadLine();

    }
}

}

Body:
In your EnemySpawn() method instead of :

 if (enemyRace.ToString() == "Human ")

replace in every condition (i.e. in if block use enemyClassChance as index like below)

if (enemyRace[enemyClassChance].ToString() == "Human ")

Also , I believe instead of

 int enemyClassChance = random.Next(1, 4);

it should be :

int enemyClassChance = random.Next(1, enemyRace.Length);


问:
The final field cannot be assigned, for an interface
I have a class Product and an interface LargeProduct. Product implements LargeProduct.

LargeProduct has a variable height which has getter and setter methods which have to be implemented in the Product class.

The height variable in LargeProduct is defined like so:

```<code>public int height = null;
</code>```

The getter method works fine:

```<code>public int getHeight() {
    return height;
}
</code>```

But the setter method does not:

```<code>public void setHeight(int height) {
    this.height = height;
}
</code>```

Errors:

```<code>The final field LargeProduct.height cannot be assigned
The static field LargeProduct.height should be accessed in a static way
</code>```

I'm not sure which error it's actually giving.. I'm using Eclipse and when I hover it gives the first error, and at the bottom of the window it gives the second error.

答:
By default fields (member variable) in interface are public static final

and you don't have setter for final

Body:
I have a class Product and an interface LargeProduct. Product implements LargeProduct.

LargeProduct has a variable height which has getter and setter methods which have to be implemented in the Product class.

The height variable in LargeProduct is defined like so:

public int height = null;

The getter method works fine:

public int getHeight() {
    return height;
}

But the setter method does not:

public void setHeight(int height) {
    this.height = height;
}

Errors:

The final field LargeProduct.height cannot be assigned
The static field LargeProduct.height should be accessed in a static way

I'm not sure which error it's actually giving.. I'm using Eclipse and when I hover it gives the first error, and at the bottom of the window it gives the second error.


问:
Find the longest arithmetic progression from an array
I have an array of numbers ex.[5,1,2,4,6,8,12], and I want to find the length of longest arithmetic progression within the sequence and to print it. Longest arithmetic progression means an increasing sequence with common difference, in this case [2,4,6,8].</p>

```<code>#include <stdio.h>

void main()
{
    int array[100], i, num,diff;
    printf("Enter the size of an array \n");

    scanf("%d", &num);

    printf("Enter the elements of the array \n");

    for (i = 0; i < num; i++) {
        scanf("%d", &array[i]);
    }

    printf("\n Numbers in a.p: ");

    for (i = 0; i < num; i++) {
        diff = array[i+1]-array[i];
        if (array[i]-diff == array[i+1]-diff);
        {
            printf("%d, ", array[i]);
        }
    }
    printf("\n Common difference:%d", diff);
}
</code>```

答:
Since this seems to be a homework or challenge I will only help by solving your immediate problems, caused by very strange code.

Here is code which at leat detects the progressions correctly.
You can yourself count the length, store the longest length and its index, then print that sequence after parsing all the array.
There are two assumptions here, which you might want to avoid for challenge/homework:

no identical numbers entered

no overlapping progressions,

i.e. no number is the last of one and the first of next progression

The representation of more than one sequence in the output is a little jittery (missing ")"), but that is not relevant for finding and exclusively printing the longest one.
I did not bother about your ratio output, no idea what that is supposed to be.

Code:

```<code>#include <stdio.h>

// avoid a warning
int main() {
    int array[100], i, num, diff=0, lastdiff=0, first=1;

    printf("Enter the size of an array \n");

    // for good code, this should check the result
    scanf("%d", &num);
    // in case of scaf-failure, cleanup here for good code

    // asking for the number of elements
    // and then relying on that number to be entered
    // is less elegant than checking for and end condition
    // like EOF or negative input

    printf("Enter the elements of the array \n");
    for (i = 0; i < num; i++) {
        // for good code, this should check the result
        scanf("%d", &array[i]);
        // in case of scaf-failure, cleanup here for good code
    }
    printf("\n Numbers in a.p: ");
    for (i = 1; i < num; i++) {

        lastdiff=diff;
        diff = array[i]-array[i-1];
        if (diff==lastdiff)
        {   if(first==1)
            { first=0;
                printf("(%d, %d",array[i-2], array[i-1]);
            }
            printf(", %d", array[i]);
        } else
        {   first=1;
        }
    }
    printf(")\n Ratio:%d", diff);

    // avoid a warning
    return 0;
}
</code>```

Body:
I have an array of numbers ex.[5,1,2,4,6,8,12], and I want to find the length of longest arithmetic progression within the sequence and to print it. Longest arithmetic progression means an increasing sequence with common difference, in this case [2,4,6,8].

#include <stdio.h>

void main()
{
    int array[100], i, num,diff;
    printf("Enter the size of an array \n");

    scanf("%d", &num);

    printf("Enter the elements of the array \n");

    for (i = 0; i < num; i++) {
        scanf("%d", &array[i]);
    }

    printf("\n Numbers in a.p: ");

    for (i = 0; i < num; i++) {
        diff = array[i+1]-array[i];
        if (array[i]-diff == array[i+1]-diff);
        {
            printf("%d, ", array[i]);
        }
    }
    printf("\n Common difference:%d", diff);
}

Body:
Since this seems to be a homework or challenge I will only help by solving your immediate problems, caused by very strange code.

Here is code which at leat detects the progressions correctly.
You can yourself count the length, store the longest length and its index, then print that sequence after parsing all the array.
There are two assumptions here, which you might want to avoid for challenge/homework:

no identical numbers entered

no overlapping progressions,

i.e. no number is the last of one and the first of next progression

The representation of more than one sequence in the output is a little jittery (missing ")"), but that is not relevant for finding and exclusively printing the longest one.
I did not bother about your ratio output, no idea what that is supposed to be.

Code:

#include <stdio.h>

// avoid a warning
int main() {
    int array[100], i, num, diff=0, lastdiff=0, first=1;

    printf("Enter the size of an array \n");

    // for good code, this should check the result
    scanf("%d", &num);
    // in case of scaf-failure, cleanup here for good code

    // asking for the number of elements
    // and then relying on that number to be entered
    // is less elegant than checking for and end condition
    // like EOF or negative input

    printf("Enter the elements of the array \n");
    for (i = 0; i < num; i++) {
        // for good code, this should check the result
        scanf("%d", &array[i]);
        // in case of scaf-failure, cleanup here for good code
    }
    printf("\n Numbers in a.p: ");
    for (i = 1; i < num; i++) {

        lastdiff=diff;
        diff = array[i]-array[i-1];
        if (diff==lastdiff)
        {   if(first==1)
            { first=0;
                printf("(%d, %d",array[i-2], array[i-1]);
            }
            printf(", %d", array[i]);
        } else
        {   first=1;
        }
    }
    printf(")\n Ratio:%d", diff);

    // avoid a warning
    return 0;
}


问:
Props value not showing on top of render to a function ReactJS
However the this.props.NotesAll retrieving object from another component and it's showing object's to under render() method but when I'm trying to use that this.props.NotesAll on top of render on a function to working with those object, and i'm trying to check the value with console on functions it's just always say's undefined shit. So please help me ReactNinja's what actually is the wrong is going on here.

Here codes you can have a look on them

```<code>export default class EditNotes extends Component {
    constructor(props) {
        super(props);
        this.state ={};
    }

    handleEdit() {
        console.log(this + ' Clicked on That ');
    }

//Here it's throwing error when I'm trying to click and console. the problem is here. i want this.props.NotesAll value here also to finding elements from objects
    handleDelete(id) {
        let Notes = this.props.NotesAll;
        console.log(Notes)
    }

    render() {
        let noteItems;
</code>```

//this.props.NotesAll working fine here.

```<code>        if (this.props.NotesAll) {
            noteItems = this.props.NotesAll.map( Note => {
                return(
                    <li key={Note.id}>{Note.body}
                    <button onClick={this.handleEdit.bind(Note.id)} className="btn btn-primary btn-sm">Edit</button>
                    <button onClick={this.handleDelete.bind(Note.id)} className="btn btn-danger btn-sm">Delete</button></li>
                    );
            });
        }
        return(
            <div className="col-md-4">
                <h3 className="header-ttile">Current Notes:</h3>
                <ul className="note-item-wrapper">
                {noteItems}
                </ul>
            </div>
            );
    }
}
</code>```

答:
```<code>constructor(props) {
    super(props);
    this.state ={};
    this.notes = props.notesAll;
    this.handleDelete = this.handleDelete.bind(this);
}
</code>```

And then try to access your this.notes inside your handeDelete function. I'm not sure because I'm not a react ninja neither, but I think it should work this way

Body:
However the this.props.NotesAll retrieving object from another component and it's showing object's to under render() method but when I'm trying to use that this.props.NotesAll on top of render on a function to working with those object, and i'm trying to check the value with console on functions it's just always say's undefined shit. So please help me ReactNinja's what actually is the wrong is going on here.

Here codes you can have a look on them

export default class EditNotes extends Component {
    constructor(props) {
        super(props);
        this.state ={};
    }

    handleEdit() {
        console.log(this + ' Clicked on That ');
    }

//Here it's throwing error when I'm trying to click and console. the problem is here. i want this.props.NotesAll value here also to finding elements from objects
    handleDelete(id) {
        let Notes = this.props.NotesAll;
        console.log(Notes)
    }

    render() {
        let noteItems;

//this.props.NotesAll working fine here.

        if (this.props.NotesAll) {
            noteItems = this.props.NotesAll.map( Note => {
                return(

{Note.body}
                    <button onClick={this.handleEdit.bind(Note.id)} className="btn btn-primary btn-sm">Edit</button>
                    <button onClick={this.handleDelete.bind(Note.id)} className="btn btn-danger btn-sm">Delete</button>

                    );
            });
        }
        return(

Current Notes:

                {noteItems}

            );
    }
}

Body:
constructor(props) {
    super(props);
    this.state ={};
    this.notes = props.notesAll;
    this.handleDelete = this.handleDelete.bind(this);
}

And then try to access your this.notes inside your handeDelete function. I'm not sure because I'm not a react ninja neither, but I think it should work this way


问:
PhpStorm, Laravel and autocompletition
I have a method run() in TreeGen class:

```<code>class TreeGen implements TreeGenerable{

 public function run()
 {
     ...
     $this->pushEmptyGroupsToTree($numFighters);
     ...
 }
}
</code>```

Thing is $this could be one of the 4 Subclasses of tree gen, and all those method implement different versions of pushEmptyGroupsToTree.

But PhpStorm is only looking for pushEmptyGroupsToTree in TreeGen class and off course, I don't have it defined in the super class, so it doesn't detect it.

Is there a way to make him recognize subclass methods?

答:
For this case you must use PHPDoc and type hinting

And don`t forget about:

```<code>  ide-helper:generate  Generate a new IDE Helper file.
  ide-helper:meta      Generate metadata for PhpStorm
  ide-helper:models    Generate autocompletion for models
</code>```

Title: PhpStorm, Laravel and autocompletition

Body:
I have a method run() in TreeGen class:

class TreeGen implements TreeGenerable{

 public function run()
 {
     ...
     $this->pushEmptyGroupsToTree($numFighters);
     ...
 }
}

Thing is $this could be one of the 4 Subclasses of tree gen, and all those method implement different versions of pushEmptyGroupsToTree.

But PhpStorm is only looking for pushEmptyGroupsToTree in TreeGen class and off course, I don't have it defined in the super class, so it doesn't detect it.

Is there a way to make him recognize subclass methods?

Body:
For this case you must use PHPDoc and type hinting

And don`t forget about:

  ide-helper:generate  Generate a new IDE Helper file.
  ide-helper:meta      Generate metadata for PhpStorm
  ide-helper:models    Generate autocompletion for models


问:
Use Django's ORM in Celery
I have a few django micro-services.
Their main workload is constant background processes, not request handling.

The background processes constantly use Django's ORM, and since I needed to hack a few things for it to work properly (it did for quite a while), now I have problems with the DB connection, since Django is not really built for using DB connections a lot in the background I guess...

Celery is always suggested in these cases, but before switching the entire design, I want to know if it really is a good solution.

Can celery tasks (a lot of tasks, time-consuming tasks) use Django's ORM in the background without problems?

答:
You can import django env with the following steps</p>

```<code>import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cmdb.settings")

import django
django.setup()
</code>```

Title: Use Django's ORM in Celery

Body:
You can import django env with the following steps

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cmdb.settings")

import django
django.setup()


问:
groupByRowLabel doesn't work on Google Timeline
Currently, My timeline Chart looks like this

but I want to put all bars which is the same country on one row

and I already set

timeline:{groupByRowLabel:true}

in  options but it doesn't work

My data from google sheet looks like this

My full code below

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

```

答:
What you have done is absolutely correct. there is nothing to be added in your code.

```<code>timeline:{groupByRowLabel:true}
</code>```

this will give your labels in same row.

But the problem here is the dataset that ur giving.
All the labels for country(in ur case) will come in same row if and only if date of labels are not overlapping.

say for example, in ur case.

```<code>Albania WEEE 7/20/2000   6/6/2017
Albania Batteries 7/20/2015 6/5/2017
</code>```

See the above dates (end time of WEEE and start time of Batteries) are overlapiing.

if the dates are like

```<code>Albania WEEE 7/20/2000  6/6/2016
Albania Batteries 6/6/2016 6/5/2017
</code>```

check this dates. with this data set ur labels will come in the same row.

Body:
What you have done is absolutely correct. there is nothing to be added in your code.

timeline:{groupByRowLabel:true}

this will give your labels in same row.

But the problem here is the dataset that ur giving.
All the labels for country(in ur case) will come in same row if and only if date of labels are not overlapping.

say for example, in ur case.

Albania WEEE 7/20/2000   6/6/2017
Albania Batteries 7/20/2015 6/5/2017

See the above dates (end time of WEEE and start time of Batteries) are overlapiing.

if the dates are like

Albania WEEE 7/20/2000  6/6/2016
Albania Batteries 6/6/2016 6/5/2017

check this dates. with this data set ur labels will come in the same row.


答:
use ng-repeat="(key,customer_type) in customer_types" and change radio button as : </p>

```<code><label style="margin-right:15px"><input type="radio" ng-model="ctype" ng-value="key" name="customer_type">{{customer_type}}</label>
</code>```

Title: May I get ng-model's key instead of value in ng-value?

Body:
I am trying to set up a radio selector based on an array and return the key instead of the value to the server.

Here is the array:

$scope.customer_types = ['a', 'b', 'c', 'd', 'other'];

Here is the radio selector:

<input type="radio" ng-model="ctype" ng-value="customer_type" name="customer_type">{{customer_type}}

Now $scope.ctype will store the selected customer type and return a number, for example if I select other it should send out 4 to the server. I can do a reverse filter for this but it seems to me if I can use something like ng-value="customer_type[key]" it would be a lot easier...

Body:
use ng-repeat="(key,customer_type) in customer_types" and change radio button as :

<label style="margin-right:15px"><input type="radio" ng-model="ctype" ng-value="key" name="customer_type">{{customer_type}}</label>


问:
ManualResetEvent to IObservable<bool> (or WaitHandle to IObservable<Unit> )?
I'd like to create an IObservable-stream based on Sets/Resets of a ManualResetEvent, e.g. in principle something like

```<code>IObservable<bool> ToObservable(ManualResetEvent ev)
{
  var s = new Subject<bool>();
  ev.OnSet += s.OnNext(true);
  ev.OnReset += s.OnNext(false);
  return s;
}
</code>```

Only that ManualResetEvent doesn't expose such events of course. So is there any way to observe when this gets stopped/reset?

For the record, if the differentiation between set/unset into true/false isn't possible, a more simple IObservable<Unit> pushing a value whenever the state of ManualResetEvent changes would be okay as well.

Is there any way of doing this?

I've found a post explaining how to convert a ManualResetEvent (or rather, a WaitHandle in general) into a task ( Wrapping ManualResetEvent as awaitable task ), which seems to complete whenever the next time is that the ManualResetEvent changes (from set to unset, or other way around).
But I haven't really found any way how I could chain this up into a sequence (e.g. after the task completes, I'd need to create another one for the next event, etc., and somehow create an observable out of this "recursive" sequence)

Thanks!

答:
There are many different ways to do this, but something likes this:</p>

```<code>public static class ManualResetEventObservable
{
    public static IObservable<bool> Create(ManualResetEvent e, TimeSpan timeout)
    {
        return Observable.Create<bool>(observer =>
        {
            var cancelEvent = new ManualResetEvent(false);
            var waitHandles = new[] { cancelEvent, e };
            var thread = new Thread(new ThreadStart(() =>
            {
                var index = WaitHandle.WaitAny(waitHandles, timeout);
                if (index == 1)
                    observer.OnNext(true);

                observer.OnCompleted();
            }));
            thread.Start();
            return Disposable.Create(() => cancelEvent.Set());
        });
    }
</code>```

Body:
I'd like to create an IObservable-stream based on Sets/Resets of a ManualResetEvent, e.g. in principle something like

IObservable<bool> ToObservable(ManualResetEvent ev)
{
  var s = new Subject<bool>();
  ev.OnSet += s.OnNext(true);
  ev.OnReset += s.OnNext(false);
  return s;
}

Only that ManualResetEvent doesn't expose such events of course. So is there any way to observe when this gets stopped/reset?

For the record, if the differentiation between set/unset into true/false isn't possible, a more simple IObservable<Unit> pushing a value whenever the state of ManualResetEvent changes would be okay as well.

Is there any way of doing this?

I've found a post explaining how to convert a ManualResetEvent (or rather, a WaitHandle in general) into a task ( Wrapping ManualResetEvent as awaitable task ), which seems to complete whenever the next time is that the ManualResetEvent changes (from set to unset, or other way around).
But I haven't really found any way how I could chain this up into a sequence (e.g. after the task completes, I'd need to create another one for the next event, etc., and somehow create an observable out of this "recursive" sequence)

Thanks!

Body:
There are many different ways to do this, but something likes this:

public static class ManualResetEventObservable
{
    public static IObservable<bool> Create(ManualResetEvent e, TimeSpan timeout)
    {
        return Observable.Create<bool>(observer =>
        {
            var cancelEvent = new ManualResetEvent(false);
            var waitHandles = new[] { cancelEvent, e };
            var thread = new Thread(new ThreadStart(() =>
            {
                var index = WaitHandle.WaitAny(waitHandles, timeout);
                if (index == 1)
                    observer.OnNext(true);

                observer.OnCompleted();
            }));
            thread.Start();
            return Disposable.Create(() => cancelEvent.Set());
        });
    }


问:
Python range function step size list assignment out of range error, simulating a brainteaser
A classic math brainteaser, problem statement taken from leetcode
"There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds."

I realize there is a concise solution to the problem itself but I want to simulate the bulb switching on/off problem. But as the step size increases I am running into list index out of range errors, how do I handle this error? I want the values to be toggled only if the index is still valid.

 def bulbSwitch(self, n):
        """
        :type n: int
        :rtype: int
        """
        bulbs= [0]*n
        step=0
        for i in range(n):
            step += 1
            for s in range(0, n, step):
                bulbs[s+i]=0 if bulbs[s]==1 else 1 #this line produces error
        print bulbs
```

答:
As others have pointed out, the issue is the s+i index. The maximum value for s in the loop is n-1, so if you add anything to it, you're going to run past the end of the list.

You said you want to start with bulbs[1] when step is 2, bulbs[2] when step is 3, etc. So just start your range there instead:

```<code>for step in range(1, n+1):  # this avoids separate `i` vs. `step` variables
    for s in range(step-1, n, step):  # start in the right place
        bulbs[s] = 0 if bulbs[s] == 1 else 1
</code>```

EDIT

Perhaps this is easier? (Here I used a +1 instead of a -1.)

```<code>for step in range(n):  # this avoids separate `i` vs. `step` variables
    for s in range(step, n, step+1):  # start in the right place
        bulbs[s] = 0 if bulbs[s] == 1 else 1
</code>```

EDIT 2

Just making sure it works... I added a test (which passes):

```<code>import math

def bulb_switch(n):
    bulbs = [0] * n

    for step in range(n):  # this avoids separate `i` vs. `step` variables
        for s in range(step, n, step+1):  # start in the right place
            bulbs[s] = 0 if bulbs[s] == 1 else 1

    return sum(bulbs)

for i in range(1000):
    assert math.floor(math.sqrt(i)) == bulb_switch(i)
</code>```

Body:
As others have pointed out, the issue is the s+i index. The maximum value for s in the loop is n-1, so if you add anything to it, you're going to run past the end of the list.

You said you want to start with bulbs[1] when step is 2, bulbs[2] when step is 3, etc. So just start your range there instead:

for step in range(1, n+1):  # this avoids separate `i` vs. `step` variables
    for s in range(step-1, n, step):  # start in the right place
        bulbs[s] = 0 if bulbs[s] == 1 else 1

EDIT

Perhaps this is easier? (Here I used a +1 instead of a -1.)

for step in range(n):  # this avoids separate `i` vs. `step` variables
    for s in range(step, n, step+1):  # start in the right place
        bulbs[s] = 0 if bulbs[s] == 1 else 1

EDIT 2

Just making sure it works... I added a test (which passes):

import math

def bulb_switch(n):
    bulbs = [0] * n

    for step in range(n):  # this avoids separate `i` vs. `step` variables
        for s in range(step, n, step+1):  # start in the right place
            bulbs[s] = 0 if bulbs[s] == 1 else 1

    return sum(bulbs)

for i in range(1000):
    assert math.floor(math.sqrt(i)) == bulb_switch(i)


问:
Set markers under POI's (google maps v2)
How can I set markers under POI's? I need to show POI's always.
On this screen my current situation: IMG_LINK

Sorry for my russian english (mistakes).

答:
Try using this</p>

```<code>yourmap.addMarker(new MarkerOptions().position(LatLng).title(String).zIndex(float));
</code>```

Body:
Try using this

yourmap.addMarker(new MarkerOptions().position(LatLng).title(String).zIndex(float));


问:
Separating js from angular controllers (do I create a directive for this?)
I'm using a lot of built in angular directives such as ng-repeat with the html. I already separated the UI component to a different HTML file using ng-include. How do I separate out the js from the controller?

html (ui/hotkeys.ui.html)

```<code><div ng-controller="AddManagerController as vm">

<button class="btn hotkey" ng-change="vm.changed($index)" ng-class="{'btn-danger': $index === 1, 'btn-info': $index === 2, 'btn-primary': $index === 3, 'btn-success': $index === 4, 'btn-warning': $index === 5, 'btn-inverse': $index === 6 }" ng-if="hotkeys !== null" ng-model="vm.credentials.groups[$index]" ng-repeat="hotkeys in vm.showGroups track by $index" tabindex="-1" type="button" style="margin-right: 4px" uib-btn-checkbox>
  <svg width="42" height="42" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <circle cx="20" cy="20" r="4" stroke="black" fill="white" ng-if="$index === 1 || $index === 3 || $index === 5" stroke-width="1"/>
    <circle cx="10" cy="10" r="4" stroke="black" fill="white" ng-if="$index ===4 || $index === 5 || $index === 6" stroke-width="1"/>
    <circle cx="10" cy="20" r="4" stroke="black" fill="white" ng-if="$index === 6" stroke-width="1"/>
    <circle cx="10" cy="30" r="4" stroke="black" fill="white" ng-if="$index === 2 || $index === 3 || $index === 4 || $index === 5 || $index === 6" stroke-width="1"/>
    <circle cx="30" cy="10" r="4" stroke="black" fill="white" ng-if="$index === 2 || $index === 3 || $index === 4 || $index === 5 || $index === 6" stroke-width="1"/>
    <circle cx="30" cy="20" r="4" stroke="black" fill="white" ng-if="$index === 6" stroke-width="1"/>
    <circle cx="30" cy="30" r="4" stroke="black" fill="white" ng-if="$index === 4 || $index === 5 || $index === 6" stroke-width="1"/>
  </svg>
</button>

</div>
</code>```

This is the code I want to load from another js file instead of keeping all this in the controller.

```<code>/* ============ HOTBAR ============ */
var enableHotbar = true;
$document.bind('keypress', function (e) {
    //console.log(e.key);
    var key = String.fromCharCode(e.which);
    if (key == 1 || key == 2 || key == 3 || key == 4 || key == 5 || key == 6) {
        //alert(key);
        $scope.$broadcast('keypress', e, e.which);
    }
});
$scope.keyList = []; //["1","2", "3"];
$scope.$on('keypress', function (event, key) {
  var easyToReadKeyFromKeycode = String.fromCharCode(key.charCode);
  if (enableHotbar && (document.activeElement.id !== 'manager-phone') && (document.activeElement.id !== 'manager-name')) {
    vm.credentials.groups.forEach(function(group, index){
      if (easyToReadKeyFromKeycode === (index).toString()) {
        vm.credentials.groups[index] = !vm.credentials.groups[index];
      }
    })
  }
  $scope.keyList.push(String.fromCharCode(key.charCode));
  //console.log($scope.keyList);
  $scope.$apply();
});

  // add ng-focused and ng-blurred to any input element requiring numbers
    $scope.focused = function (e) {
      enableHotbar = false;
    }
    $scope.blurred = function (e) {
      enableHotbar = true;
    }

    // Manager Name disables keys 1 through 6
    $scope.keyPressed = function(e) {
      console.log(e);
      if ((e.keyCode >= 49 && e.keyCode <= 54)) {
        event.preventDefault();
      }
    }

/* ================================= */
</code>```

答: You have more options to separate JS from controller (to another controller honestly). If you want some singleton usage, you should create service for it. If you want some special functionality without separate view create a filter or directive. And if your special functionality has some view (HTML) create component. This is angularJS basic</p>

Body:
I'm using a lot of built in angular directives such as ng-repeat with the html. I already separated the UI component to a different HTML file using ng-include. How do I separate out the js from the controller?

html (ui/hotkeys.ui.html)

<button class="btn hotkey" ng-change="vm.changed($index)" ng-class="{'btn-danger': $index === 1, 'btn-info': $index === 2, 'btn-primary': $index === 3, 'btn-success': $index === 4, 'btn-warning': $index === 5, 'btn-inverse': $index === 6 }" ng-if="hotkeys !== null" ng-model="vm.credentials.groups[$index]" ng-repeat="hotkeys in vm.showGroups track by $index" tabindex="-1" type="button" style="margin-right: 4px" uib-btn-checkbox>
  <svg width="42" height="42" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <circle cx="20" cy="20" r="4" stroke="black" fill="white" ng-if="$index === 1 || $index === 3 || $index === 5" stroke-width="1"/>
    <circle cx="10" cy="10" r="4" stroke="black" fill="white" ng-if="$index ===4 || $index === 5 || $index === 6" stroke-width="1"/>
    <circle cx="10" cy="20" r="4" stroke="black" fill="white" ng-if="$index === 6" stroke-width="1"/>
    <circle cx="10" cy="30" r="4" stroke="black" fill="white" ng-if="$index === 2 || $index === 3 || $index === 4 || $index === 5 || $index === 6" stroke-width="1"/>
    <circle cx="30" cy="10" r="4" stroke="black" fill="white" ng-if="$index === 2 || $index === 3 || $index === 4 || $index === 5 || $index === 6" stroke-width="1"/>
    <circle cx="30" cy="20" r="4" stroke="black" fill="white" ng-if="$index === 6" stroke-width="1"/>
    <circle cx="30" cy="30" r="4" stroke="black" fill="white" ng-if="$index === 4 || $index === 5 || $index === 6" stroke-width="1"/>
  </svg>
</button>

This is the code I want to load from another js file instead of keeping all this in the controller.

/* ============ HOTBAR ============ */
var enableHotbar = true;
$document.bind('keypress', function (e) {
    //console.log(e.key);
    var key = String.fromCharCode(e.which);
    if (key == 1 || key == 2 || key == 3 || key == 4 || key == 5 || key == 6) {
        //alert(key);
        $scope.$broadcast('keypress', e, e.which);
    }
});
$scope.keyList = []; //["1","2", "3"];
$scope.$on('keypress', function (event, key) {
  var easyToReadKeyFromKeycode = String.fromCharCode(key.charCode);
  if (enableHotbar && (document.activeElement.id !== 'manager-phone') && (document.activeElement.id !== 'manager-name')) {
    vm.credentials.groups.forEach(function(group, index){
      if (easyToReadKeyFromKeycode === (index).toString()) {
        vm.credentials.groups[index] = !vm.credentials.groups[index];
      }
    })
  }
  $scope.keyList.push(String.fromCharCode(key.charCode));
  //console.log($scope.keyList);
  $scope.$apply();
});

  // add ng-focused and ng-blurred to any input element requiring numbers
    $scope.focused = function (e) {
      enableHotbar = false;
    }
    $scope.blurred = function (e) {
      enableHotbar = true;
    }

    // Manager Name disables keys 1 through 6
    $scope.keyPressed = function(e) {
      console.log(e);
      if ((e.keyCode >= 49 && e.keyCode <= 54)) {
        event.preventDefault();
      }
    }

/* ================================= */


问:
Does Visual Inheritance work with User controls in VS2008
I have a base User Control. I place Ok and Cancel buttons on the bottom right of the control and anchor them Bottom and Right.

I then create another user control that inherits from the base user control. I resize the inherited control (e.g. increase height or width). Throw the inherited control onto the form.  Run.  The inherited control does not honor the anchor properties of the Ok and Cancel buttons.

Here are the exact steps to repro.

1 - Create a new winforms project

2 - Create a base control (BaseControl1) with a Ok and Cancel buttons located at bottom/right. Anchor them there at Bottom,Right.  Compile the app.

3 - Create a new User Control (UserControl1) that inherits from the base control (BaseControl1), created in step 1.

4 - Increase (in the designer) UserControl1's height or width.

5 - Throw UserControl1 onto Form1.  Run.  You'll see that Ok and Cancel buttons are not where they are supposed to be.

Am I doing something wrong, or does VS2008 simply not honor the anchor properties of the controls on the base user control?

答:
I think your problem is that the default values for the Anchor property is not to be anchored. When you change the property and compile, that doesn't mean that's the default setting for classes that inherit your control.

If you are using the property selector, Visual Studio automatically puts some code in your application to change those values (i.e the designer code). Find the InitializeComponent() method and I bet you'll see something to the effect of:

```<code>this.myOKButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
this.myCancelButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
</code>```

You'll need to set this property somewhere in your class, like the constructor, or override that property and specify the way you want it anchored.

OwnerDisplayName: AngryHacker

LastEditorDisplayName: Joel Coehoorn

Body:
I think your problem is that the default values for the Anchor property is not to be anchored. When you change the property and compile, that doesn't mean that's the default setting for classes that inherit your control.

If you are using the property selector, Visual Studio automatically puts some code in your application to change those values (i.e the designer code). Find the InitializeComponent() method and I bet you'll see something to the effect of:

this.myOKButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
this.myCancelButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;

You'll need to set this property somewhere in your class, like the constructor, or override that property and specify the way you want it anchored.


问:
Unity Start nog called on real build
I've made a dice app as a project to learn to work with unity (it was so good in my eyes that I put it on the google play store) but when I downloaded it from there, the Start function of at least 2 scripts isn't called and I have no idea whether the other Start functions are being called.

Here you can see 2 of the Start functions that aren't called

```<code>void Start()
{
    light = light.GetComponent<Light>();
    GetComponent<Button>().onClick.AddListener(TaskOnClick);
    rawImage = GetComponent<RawImage>();
    isLockMode = false;
    rawImage.texture = getIconLock(isLockMode);
}

void Start()
{
    Screen.fullScreen = false;
    Dice.AddDie();
    Input.gyro.enabled = true;
    GlobalConfig.onShowShadowsChanged += onShadowsEnabledChange;
}
</code>```

They work when I use Unity Remote on my smartphone and they also work when I just use unity without the remote...

the first script is attached to a UI element and the second script is attached to an empty GameObject called 'App'

It's also even more weird because they used to work but then I switched pc's (but used the same code).
I think something is wrong with the building itself

答: Found out the problem, the build was generating two files, an .apk and an other .odb or somethingl ike that (might be another extension). I had to untick 'split application binary' in the player settings</p>

Title: Unity Start nog called on real build

Body:
I've made a dice app as a project to learn to work with unity (it was so good in my eyes that I put it on the google play store) but when I downloaded it from there, the Start function of at least 2 scripts isn't called and I have no idea whether the other Start functions are being called.

Here you can see 2 of the Start functions that aren't called

void Start()
{
    light = light.GetComponent<Light>();
    GetComponent<Button>().onClick.AddListener(TaskOnClick);
    rawImage = GetComponent<RawImage>();
    isLockMode = false;
    rawImage.texture = getIconLock(isLockMode);
}

void Start()
{
    Screen.fullScreen = false;
    Dice.AddDie();
    Input.gyro.enabled = true;
    GlobalConfig.onShowShadowsChanged += onShadowsEnabledChange;
}

They work when I use Unity Remote on my smartphone and they also work when I just use unity without the remote...

the first script is attached to a UI element and the second script is attached to an empty GameObject called 'App'

It's also even more weird because they used to work but then I switched pc's (but used the same code).
I think something is wrong with the building itself


问:
Retrieve data from three table using join in CodeIgniter
I am trying to get result from three table using CodeIgnitor active record. But I am just getting record who match with second join condition only. But I need all record..

```<code>$uid   = $this->session->userdata('uid');
$codn  = ['stud.uid'=>$uid,'stud.status'=>"ACTIVE"];

$liststudent = $this->db->select('stud.id,stud.studname,stud.mobile1,stud.photo,stud.totalfees,bs.title,SUM(sp.pay_in_digit) AS paidfees')
                        ->from('students as stud')
                        ->join('batchsetting as bs', 'bs.id  = stud.bid')
                        ->join('stud_payment as sp', 'sp.sid = stud.id')
                        ->where($codn)
                        ->get();
return $liststudent->result();
</code>```

Here is the my query.

Concept is: I need batch title from batchsetting who's 'id = stud.bid'. and sum of paidfees from stud_payment who's 'sid=stud.id'.

But in result I am getting only those record of student who's record avail in stud_payment table.

答:
Basically ci bydefault consider inner Join query.so you need to specify left join</p>

```<code>->join('stud_payment as sp', 'sp.sid = stud.id', 'left');
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to get result from three table using CodeIgnitor active record. But I am just getting record who match with second join condition only. But I need all record..

$uid   = $this->session->userdata('uid');
$codn  = ['stud.uid'=>$uid,'stud.status'=>"ACTIVE"];

$liststudent = $this->db->select('stud.id,stud.studname,stud.mobile1,stud.photo,stud.totalfees,bs.title,SUM(sp.pay_in_digit) AS paidfees')
                        ->from('students as stud')
                        ->join('batchsetting as bs', 'bs.id  = stud.bid')
                        ->join('stud_payment as sp', 'sp.sid = stud.id')
                        ->where($codn)
                        ->get();
return $liststudent->result();

Here is the my query.

Concept is: I need batch title from batchsetting who's 'id = stud.bid'. and sum of paidfees from stud_payment who's 'sid=stud.id'.

But in result I am getting only those record of student who's record avail in stud_payment table.

Body:
Basically ci bydefault consider inner Join query.so you need to specify left join

->join('stud_payment as sp', 'sp.sid = stud.id', 'left');


问:
Display header and footer in every page is breaks by long table
I want to set all header and footer in all page in a pdf with mpdf,

So, my code looked like this :

```<code><!DOCTYPE html>
<html>
<head>
    <title>Data Category</title>
    <style type="text/css">
        .page{
            padding-top:2.5cm;
            padding-right:1.5cm;
            padding-left:1cm;
            padding-bottom:5cm;
        }
        table{
            border-spacing:0;
            border-collapse: collapse;
            width:100%;
            page-break-inside:auto;
        }

        table td, table th{
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <div class="page">

        <table border="0">
            <thead>
                <tr>
                    <th>No</th>
                    <th>Tanggal</th>
                    <th>Jam</th>
                    <th>No struk</th>
                    <th>Nama</th>
                    <th>Quantity</th>
                    <th>Nama Item</th>
                    <th>Harga Jual</th>
                    <th>Sub total</th>
                </tr>
            </thead>

            <tbody>
                <?php
                $no = 1;
                foreach ($data as $key => $value) {
                    ?>
                    <tr>
                        <td><?= $no++ ?></td>
                        <td><?= $value['date_format'] ?></td>
                        <td><?= $value['jam'] ?></td>
                        <td><?= $value['struk_no'] ?></td>
                        <td><?= $value['nama_karyawan'] ?></td>
                        <td><?= $value['jumlah_jual'] ?></td>
                        <td><?= $value['nama_item'] ?></td>
                        <td><?= $value['harga_jual'] ?></td>
                        <td><?= $value['subtotal'] ?></td>
                    </tr>
                    <?php
                }
                ?>
            </tbody>
        </table>
    </div>
</body>
</code>```

I have alread read their docs from here : mpdf docs.

But, when my table is loaded more than one page, the table breaks the header:

```<code>$detail = Yii::$app->db->createCommand($this->getSqlReportDetail($parseStart, $parseEnd))->queryAll();
    $html = $this->renderPartial('_report_detail', ['data' => $detail]);
    $mpdf = new \mPDF('c', 'A4', '', '', 0, 0, 0, 0, 0, 0);
    $mpdf->SetDisplayMode('fullpage');
    $mpdf->list_indent_first_level = 0;  // 1 or 0 - whether to indent the first level of a list
    $mpdf->SetHTMLHeader(''
            . '<div style="text-align: center; font-weight: bold;">'
            . '<h1>Hair Deeper Salon</h1><br>'
            . '<hr>'
            . '</div>'
    );

    $mpdf->SetHTMLFooter('
            <table width="100%" style="vertical-align: bottom; font-family: serif; font-size: 8pt; color: #000000; font-weight: bold; font-style: italic;">
                <tr>
                    <td width="33%"><span style="font-weight: bold; font-style: italic;">{DATE j-m-Y}</span></td>
                    <td width="33%" align="center" style="font-weight: bold; font-style: italic;">{PAGENO}/{nbpg}</td>
                    <td width="33%" style="text-align: right; ">My document</td>
                </tr>
            </table>
    ');
    $mpdf->WriteHTML($html);
    $mpdf->Output();
    exit;
</code>```

This is the document right now :

答:
Try using this before setting header and footer</p>

```<code>$mpdf->setAutoTopMargin = 'stretch';
$mpdf->setAutoBottomMargin = 'stretch';
</code>```

Body:
I want to set all header and footer in all page in a pdf with mpdf,

So, my code looked like this :

<!DOCTYPE html>

    <title>Data Category</title>

                    No
                    Tanggal
                    Jam
                    No struk
                    Nama
                    Quantity
                    Nama Item
                    Harga Jual
                    Sub total

                <?php
                $no = 1;
                foreach ($data as $key => $value) {
                    ?>

                        <?= $no++ ?>
                        <?= $value['date_format'] ?>
                        <?= $value['jam'] ?>
                        <?= $value['struk_no'] ?>
                        <?= $value['nama_karyawan'] ?>
                        <?= $value['jumlah_jual'] ?>
                        <?= $value['nama_item'] ?>
                        <?= $value['harga_jual'] ?>
                        <?= $value['subtotal'] ?>

                    <?php
                }
                ?>

I have alread read their docs from here : mpdf docs.

But, when my table is loaded more than one page, the table breaks the header:

$detail = Yii::$app->db->createCommand($this->getSqlReportDetail($parseStart, $parseEnd))->queryAll();
    $html = $this->renderPartial('_report_detail', ['data' => $detail]);
    $mpdf = new \mPDF('c', 'A4', '', '', 0, 0, 0, 0, 0, 0);
    $mpdf->SetDisplayMode('fullpage');
    $mpdf->list_indent_first_level = 0;  // 1 or 0 - whether to indent the first level of a list
    $mpdf->SetHTMLHeader(''
            . '
'
            . '
Hair Deeper Salon

'
            . '
'
            . '
'
    );

    $mpdf->SetHTMLFooter('

                    {DATE j-m-Y}
                    {PAGENO}/{nbpg}
                    My document

    ');
    $mpdf->WriteHTML($html);
    $mpdf->Output();
    exit;

This is the document right now :

Body:
Try using this before setting header and footer

$mpdf->setAutoTopMargin = 'stretch';
$mpdf->setAutoBottomMargin = 'stretch';


问:
why it didn't go through the thread?
I was checking if the sign Up button is clicked it do something in another thread but it didn't go to the end of thread ?

```<code>    if(!(email.isEmpty() ||username.isEmpty() || password.isEmpty())){
     Main.users.add(new User(username, password, email));
                        new Thread(new SocketSender(Main.socket, Main.users)).start();
   Thread.sleep(1000);
   System.out.println("here");
   new Thread(new ServerReciver(Main.socket)).start();
   Thread.sleep(2000);
   System.out.println("here");
   Main.pstage.setScene(new Scene(FXMLLoader.load(getClass().getResource("/sample/logIn.fxml")),700,700))}
</code>```

Socket Sender

```<code>public class SocketSender  implements  Runnable{
    Socket socket;
    Object object;

    public SocketSender(Socket socket, Object object) {
        this.socket = socket;
        this.object = object;
    }

@Override
public void run() {
    try {
        ObjectOutputStream write = new ObjectOutputStream(socket.getOutputStream());
        write.writeObject(object);
        write.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}}
</code>```

Server Reciver

```<code>public class ServerReciver implements  Runnable {
    Socket socket;

    public ServerReciver(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        System.out.println("log1");
        try {
            System.out.println("log2");
            ObjectInputStream read = new ObjectInputStream(socket.getInputStream());
            System.out.println("log3");
            Object o = read.readObject();
            System.out.println("ma");
            if(o instanceof User){
                System.out.println(log4);
                Server.getUsers().add((User) o);
            }
            else if(o instanceof Artist){
                Server.getArtists().add((Artist) o);
            }
            else if(o instanceof PlayList){
                Server.getPlayLists().add((PlayList) o);
            }
            else if(o instanceof Song){
                Server.getSongs().add((Song) o);
            }
            else if(o instanceof Album){
                Server.getAlbums().add((Album) o);
            }
            System.out.println(log6);
            Server.write();
            System.out.println(log7);
            Thread.sleep(100);
            System.out.println(Server.getUsers().get(0));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
</code>```

in the Server receiver it prints the 2 first log but it didn't print all the logs!?

答:
To create server's client use java.net.Socket:

```<code>Socket s = new Socket(serverAddress, 9090);
        BufferedReader input =
            new BufferedReader(new InputStreamReader(s.getInputStream()));
        String answer = input.readLine();
</code>```

To create server use java.net.ServerSocket :

```<code>ServerSocket listener = new ServerSocket(9090);

        try {
            while (true) {
                Socket socket = listener.accept();

                try {
                    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                    out.println(new Date().toString());
                } finally {
                    socket.close();
                }
            }
        } finally {
            listener.close();
        }
</code>```

Title: why it didn't go through the thread?

Body:
I was checking if the sign Up button is clicked it do something in another thread but it didn't go to the end of thread ?

    if(!(email.isEmpty() ||username.isEmpty() || password.isEmpty())){
     Main.users.add(new User(username, password, email));
                        new Thread(new SocketSender(Main.socket, Main.users)).start();
   Thread.sleep(1000);
   System.out.println("here");
   new Thread(new ServerReciver(Main.socket)).start();
   Thread.sleep(2000);
   System.out.println("here");
   Main.pstage.setScene(new Scene(FXMLLoader.load(getClass().getResource("/sample/logIn.fxml")),700,700))}

Socket Sender

public class SocketSender  implements  Runnable{
    Socket socket;
    Object object;

    public SocketSender(Socket socket, Object object) {
        this.socket = socket;
        this.object = object;
    }

@Override
public void run() {
    try {
        ObjectOutputStream write = new ObjectOutputStream(socket.getOutputStream());
        write.writeObject(object);
        write.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}}

Server Reciver

public class ServerReciver implements  Runnable {
    Socket socket;

    public ServerReciver(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        System.out.println("log1");
        try {
            System.out.println("log2");
            ObjectInputStream read = new ObjectInputStream(socket.getInputStream());
            System.out.println("log3");
            Object o = read.readObject();
            System.out.println("ma");
            if(o instanceof User){
                System.out.println(log4);
                Server.getUsers().add((User) o);
            }
            else if(o instanceof Artist){
                Server.getArtists().add((Artist) o);
            }
            else if(o instanceof PlayList){
                Server.getPlayLists().add((PlayList) o);
            }
            else if(o instanceof Song){
                Server.getSongs().add((Song) o);
            }
            else if(o instanceof Album){
                Server.getAlbums().add((Album) o);
            }
            System.out.println(log6);
            Server.write();
            System.out.println(log7);
            Thread.sleep(100);
            System.out.println(Server.getUsers().get(0));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

in the Server receiver it prints the 2 first log but it didn't print all the logs!?

Body:
To create server's client use java.net.Socket:

Socket s = new Socket(serverAddress, 9090);
        BufferedReader input =
            new BufferedReader(new InputStreamReader(s.getInputStream()));
        String answer = input.readLine();

To create server use java.net.ServerSocket :

ServerSocket listener = new ServerSocket(9090);

        try {
            while (true) {
                Socket socket = listener.accept();

                try {
                    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                    out.println(new Date().toString());
                } finally {
                    socket.close();
                }
            }
        } finally {
            listener.close();
        }