问:
PHP Header Location is not working in localhost xampp?
i am trying to redirect the page using header location in xampp but it is not working and redirecting to localhost/dashboard

i used the following code for simple redirecting in localhost , i placed my site in htdocs/test/   and files in that are index.html and index.php,  the index.php code is as follows

```<code><?php
      header("Location:/index.html");
 ?>
</code>```

when i am trying to access http://localhost/test/index.php it is not going to localhost/test/index.html
but it is redirecting to http://localhost/dashboard/

答:
try:</p>

```<code><?php
echo "<script type=\"text/javascript\" language=\"javascript\">
        window.location.replace(\"index.html\");
      </script>";

?>
</code>```

Body:
i am trying to redirect the page using header location in xampp but it is not working and redirecting to localhost/dashboard

i used the following code for simple redirecting in localhost , i placed my site in htdocs/test/   and files in that are index.html and index.php,  the index.php code is as follows

<?php
      header("Location:/index.html");
 ?>

when i am trying to access http://localhost/test/index.php it is not going to localhost/test/index.html
but it is redirecting to http://localhost/dashboard/

Body:
try:

<?php
echo "<script type=\"text/javascript\" language=\"javascript\">
        window.location.replace(\"index.html\");
      </script>";

?>


来源: stackexchange

问:
Is it possible to extend/insert a CSS property value
My question may be a little confusing, my css skills are moderate at best but none the less I'll do my best to try and explain. So my question is as follows;

Is it possible to insert/extend a CSS property value?

An example of what im trying to achieve can be found within the snippet below;

* {
  margin: 0;
  padding: 0;
}

.wrap {
  width: 100%;
}

.box {
  display: inline-block;
  float:left;
  width: 50%;
  padding-top: 80%;
  background-position: center center;
  background-repeat: no-repeat;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

/* --- original element... --- */

.original {
  background-image: url(http://imageshack.com/a/img631/8360/WuQwuf.jpg);
}

/* --- What I'm After --- */

.sourced {
  background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.4) 0%, rgba(0, 0, 0, 0.4) 100%), url(http://imageshack.com/a/img631/8360/WuQwuf.jpg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">
  <div class="box original"></div>
  <div class="box sourced"></div>
</div></code>```

Some background of my intended application, I have a WP installation running Avada wp theme. Within the theme a div element is built with a css image background, but the nature of this theme minizes the need for heavy coding. This is where I hit a wall as the element can only be overidden with css. But, I want to refrain from doing so as the image is dynamically inserted from the wp image library to keep the images responsive; I.e. desktop size, tablet, mobile, etc.

From what I understand overiding the css would mean hardcoding the URL into the stylesheet breaking the responsitivity.

My Research

I spent some time digging around the web but the solutions I came across seemed more difficult, or a little to hacky for practical use. After further digging I was able to stumble accross this CSS Extend Rule.

However, my understanding of this article is that using @extend would simply chain on a new rule to an exisiting class, providing the rule is computed.

The answer may be super simple, but I have never encountered a need for this before. Any help is much appreciated.

EDIT - THU 8 JUN 2017 09:52

Due to the nature of this project being a little time sensitive I have hardcoded the Property and it's Value, breaking the responsitivity. This will not be a long term fix and I will be sourcing a better solution. To all that arrive late I will be monitoring this question for the forseeable future, so feel free to try to answer.

```<code>/* -- Overide Currently in Use -- */
.post-content #main-hero {
    background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.3) 0%, rgba(0, 0, 0, 0.3) 100%), url("https://www.url.com/image") !important;
}
</code>```

答:
You don´t need any js to do this. I can do it with css. I´ll use these technique every days!! :) Pass inline css (only background-image property) to the element you need to change dynamically background image.

```<code><div class="wrap">
     <div class="box" style="background-image: url(your/image/url.jpg)"></div>
     <div class="box" style="background-image: url(your/image1/url.jpg)"></div>
</div>
</code>```

And in your css you´ll only need this code lines:

```<code>.box {
    display: inline-block;
    float:left;
    width: 50%;
    padding-top: 80%;

    // Important to keep
    background-position: center center;
    background-repeat: no-repeat;
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: cover;
</code>```

}

If you keep the above code you´ll have the responsiveness on your images.

ContentLicense: CC BY-SA 3.0

Body:
My question may be a little confusing, my css skills are moderate at best but none the less I'll do my best to try and explain. So my question is as follows;

Is it possible to insert/extend a CSS property value?

An example of what im trying to achieve can be found within the snippet below;

* {
  margin: 0;
  padding: 0;
}

.wrap {
  width: 100%;
}

.box {
  display: inline-block;
  float:left;
  width: 50%;
  padding-top: 80%;
  background-position: center center;
  background-repeat: no-repeat;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

/* --- original element... --- */

.original {
  background-image: url(http://imageshack.com/a/img631/8360/WuQwuf.jpg);
}

/* --- What I'm After --- */

.sourced {
  background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.4) 0%, rgba(0, 0, 0, 0.4) 100%), url(http://imageshack.com/a/img631/8360/WuQwuf.jpg);
}

Some background of my intended application, I have a WP installation running Avada wp theme. Within the theme a div element is built with a css image background, but the nature of this theme minizes the need for heavy coding. This is where I hit a wall as the element can only be overidden with css. But, I want to refrain from doing so as the image is dynamically inserted from the wp image library to keep the images responsive; I.e. desktop size, tablet, mobile, etc.

From what I understand overiding the css would mean hardcoding the URL into the stylesheet breaking the responsitivity.

My Research

I spent some time digging around the web but the solutions I came across seemed more difficult, or a little to hacky for practical use. After further digging I was able to stumble accross this CSS Extend Rule.

However, my understanding of this article is that using @extend would simply chain on a new rule to an exisiting class, providing the rule is computed.

The answer may be super simple, but I have never encountered a need for this before. Any help is much appreciated.

EDIT - THU 8 JUN 2017 09:52

Due to the nature of this project being a little time sensitive I have hardcoded the Property and it's Value, breaking the responsitivity. This will not be a long term fix and I will be sourcing a better solution. To all that arrive late I will be monitoring this question for the forseeable future, so feel free to try to answer.

/* -- Overide Currently in Use -- */
.post-content #main-hero {
    background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.3) 0%, rgba(0, 0, 0, 0.3) 100%), url("https://www.url.com/image") !important;
}

Body:
You don´t need any js to do this. I can do it with css. I´ll use these technique every days!! :) Pass inline css (only background-image property) to the element you need to change dynamically background image.

<div class="wrap">
     <div class="box" style="background-image: url(your/image/url.jpg)"></div>
     <div class="box" style="background-image: url(your/image1/url.jpg)"></div>
</div>

And in your css you´ll only need this code lines:

.box {
    display: inline-block;
    float:left;
    width: 50%;
    padding-top: 80%;

    // Important to keep
    background-position: center center;
    background-repeat: no-repeat;
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: cover;

}

If you keep the above code you´ll have the responsiveness on your images.


问:
Need to change date variable with drop down menu selection dynamically in PHP
I have a php file (index.php) which has a titlebar, the titlebar holds date as (MM YYYY). The dates are pulled from another php file titled latest_update.php. The dates are listed in the latest_update file using the following syntax

```<code>$latest_run="April 2017";
$latest_run2="May 2017";
</code>```

The $latest_run date is stripped from the file and passed to a variable using the following.

```<code>include_once "scripts/latest_update.php";
$mainTitle = "Content Title";
$secondaryTitle = $latest_run;
$thirdTitle = $latest_run2;
</code>```

The title and date are held in a div using span

```<code>   <div class="titleBar">
   <span class="mainTitle"><?php echo $mainTitle ?></span></br>
   <span Class="secondaryTitle"><?php echo $secondaryTitle ?></span>
   </div>
</code>```

I have a selection menu and when I change the selection menu I want the option of the secondaryTitle to change. So if I select Run2 as the option I want the title to change to reflect May 2017 which corresponds to $thirdTitle. If I select Run1 I want it to change to the Secondarytitle referring to April 2017. The select menu is held within a form.

```<code> <form id="myForm">
 <select style="visibility:visible;position:relative;left:0px;top:1px;font-size:12px" name="selmenu" id="selmenu">
 <option value="Run1">Run1</option>
 <option value="Run2">Run2</option>
 <option value="Run3">Run3</option>
 </select>
 </form>
</code>```

I am new to php and have not been able to find a solution to complete this action. Any help would be appreciated.

答:
Try something to this effect: (requires JQuery and Ajax)

```<code>JS -gets data from your form selection, sends it to your php file, then appends the response to the title

    $(document).ready(function()
    var runChoice = $("#selectRun").val();
    $.ajax({
              url: 'latest_update.php',
              type: 'POST',
              data: {run:runChoice},
              success: function(response){
                  $(".secondaryTitle").append(response);
                }
    )};
)};
</code>```

PHP Side - gets data from ajax

```<code>$choice = $_POST['runChoice'];
if($choice == "Run1"){
    echo $latest_run;
}else if($choice == "Run2"){
    echo $latest_run2;
}else{
    echo $latest_run3;
}
</code>```

This could be completed entirely without a PHP file though if you don't need database related things, you could store the values for run dates into an array, then just change the title based on the selected option without using ajax and just using appends.

Body:
I have a php file (index.php) which has a titlebar, the titlebar holds date as (MM YYYY). The dates are pulled from another php file titled latest_update.php. The dates are listed in the latest_update file using the following syntax

$latest_run="April 2017";
$latest_run2="May 2017";

The $latest_run date is stripped from the file and passed to a variable using the following.

include_once "scripts/latest_update.php";
$mainTitle = "Content Title";
$secondaryTitle = $latest_run;
$thirdTitle = $latest_run2;

The title and date are held in a div using span

   <?php echo $mainTitle ?>

   <?php echo $secondaryTitle ?>

I have a selection menu and when I change the selection menu I want the option of the secondaryTitle to change. So if I select Run2 as the option I want the title to change to reflect May 2017 which corresponds to $thirdTitle. If I select Run1 I want it to change to the Secondarytitle referring to April 2017. The select menu is held within a form.

 <form id="myForm">
 <select style="visibility:visible;position:relative;left:0px;top:1px;font-size:12px" name="selmenu" id="selmenu">
 <option value="Run1">Run1</option>
 <option value="Run2">Run2</option>
 <option value="Run3">Run3</option>
 </select>
 </form>

I am new to php and have not been able to find a solution to complete this action. Any help would be appreciated.

Body:
Try something to this effect: (requires JQuery and Ajax)

JS -gets data from your form selection, sends it to your php file, then appends the response to the title

    $(document).ready(function()
    var runChoice = $("#selectRun").val();
    $.ajax({
              url: 'latest_update.php',
              type: 'POST',
              data: {run:runChoice},
              success: function(response){
                  $(".secondaryTitle").append(response);
                }
    )};
)};

PHP Side - gets data from ajax

$choice = $_POST['runChoice'];
if($choice == "Run1"){
    echo $latest_run;
}else if($choice == "Run2"){
    echo $latest_run2;
}else{
    echo $latest_run3;
}

This could be completed entirely without a PHP file though if you don't need database related things, you could store the values for run dates into an array, then just change the title based on the selected option without using ajax and just using appends.


问:
Enum trick in C++/CLI
In native C++ we could use enum trick in class definition:

```<code>namespace EFoo
{
  enum { a = 10; };
}

class Foo
{
   // Declare an array of 10 integers.
   int m_Arr[EFoo::a];
};
</code>```

However, with managed enum in C++/CLI,

```<code>public enum class EFoo
{
  a = 10,
};
</code>```

EFoo::a couldn't be converted implicitly to int,
so the enum trick wouldn't be allowed.

Is there any workaround?

Thanks.

答:
Try:</p>

```<code>arr[(int)EFoo.a];
</code>```

ContentLicense: CC BY-SA 2.5

Title: Enum trick in C++/CLI

Body:
In native C++ we could use enum trick in class definition:

namespace EFoo
{
  enum { a = 10; };
}

class Foo
{
   // Declare an array of 10 integers.
   int m_Arr[EFoo::a];
};

However, with managed enum in C++/CLI,

public enum class EFoo
{
  a = 10,
};

EFoo::a couldn't be converted implicitly to int,
so the enum trick wouldn't be allowed.

Is there any workaround?

Thanks.

Body:
Try:

arr[(int)EFoo.a];


问:
How to change GMT to PST format in Java?
I have a code that displays time in GMT and I need to show it in PST. How can I modify the below code to get the time in PST?

Code

```<code>public static final String FORMAT = "MM/dd/yyyy";
public static final String OUTPUT_FORMAT_STD_DATE6 = "MM/dd/yy hh:mm a";
public static final String INPUT_FORMAT_STD_TIMESTAMP = "yyyy-MM-dd HH:mm:ss";

public static String formatDate(String strDate, String inputFormat, String outputFormat) {
    Date date = convertStringToDate(strDate,inputFormat);
    String displayDateString = formatDate(date, outputFormat);
    return displayDateString;
}
</code>```

formatDate is being called here

```<code>public void endElement(String uri, String localName, String qName) throws SAXException {
    if( EVENT.equalsIgnoreCase( qName ) ) {
        auditEntries.add(entry);
    } else if( LOG_TIME.equalsIgnoreCase( qName ) ) {
        String time = content.toString();
        entry.setLogTime( DateUtils.formatDate(time, "yyyy-MM-dd'T'HH:mm:ss", DateUtils.OUTPUT_FORMAT_STD_DATE6));
}
</code>```

Please help, I am new b in writing Java code.

This is how I am doing it.

```<code>public static String formatDate(String strDate, String inputFormat, String outputFormat) {
    Date date = convertStringToDate(strDate,inputFormat);

    DateFormat pstFormat = new SimpleDateFormat( outputFormat );
    pstFormat.setTimeZone( TimeZone.getDefault() );
    String displayDateString = formatDate(date, outputFormat);
    return displayDateString;
}
</code>```

Thanks

答:
This is how I did it.     </p>

```<code>public static String convertUTC( String strDate, String inputFormat, String outputFormat ) {
    String displayDateString = null;

    try {
        DateFormat inFormat = new SimpleDateFormat( inputFormat );
        inFormat.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
        Date date = inFormat.parse( strDate );

        DateFormat outFormat = new SimpleDateFormat( outputFormat );
        outFormat.setTimeZone( TimeZone.getDefault() );

        displayDateString = formatDate(date, outputFormat);
    } catch ( ParseException pe ) {
        pe.printStackTrace();
    }

    return displayDateString;
}
</code>```

Body:
I have a code that displays time in GMT and I need to show it in PST. How can I modify the below code to get the time in PST?

Code

public static final String FORMAT = "MM/dd/yyyy";
public static final String OUTPUT_FORMAT_STD_DATE6 = "MM/dd/yy hh:mm a";
public static final String INPUT_FORMAT_STD_TIMESTAMP = "yyyy-MM-dd HH:mm:ss";

public static String formatDate(String strDate, String inputFormat, String outputFormat) {
    Date date = convertStringToDate(strDate,inputFormat);
    String displayDateString = formatDate(date, outputFormat);
    return displayDateString;
}

formatDate is being called here

public void endElement(String uri, String localName, String qName) throws SAXException {
    if( EVENT.equalsIgnoreCase( qName ) ) {
        auditEntries.add(entry);
    } else if( LOG_TIME.equalsIgnoreCase( qName ) ) {
        String time = content.toString();
        entry.setLogTime( DateUtils.formatDate(time, "yyyy-MM-dd'T'HH:mm:ss", DateUtils.OUTPUT_FORMAT_STD_DATE6));
}

Please help, I am new b in writing Java code.

This is how I am doing it.

public static String formatDate(String strDate, String inputFormat, String outputFormat) {
    Date date = convertStringToDate(strDate,inputFormat);

    DateFormat pstFormat = new SimpleDateFormat( outputFormat );
    pstFormat.setTimeZone( TimeZone.getDefault() );
    String displayDateString = formatDate(date, outputFormat);
    return displayDateString;
}

Thanks

Body:
This is how I did it.

public static String convertUTC( String strDate, String inputFormat, String outputFormat ) {
    String displayDateString = null;

    try {
        DateFormat inFormat = new SimpleDateFormat( inputFormat );
        inFormat.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
        Date date = inFormat.parse( strDate );

        DateFormat outFormat = new SimpleDateFormat( outputFormat );
        outFormat.setTimeZone( TimeZone.getDefault() );

        displayDateString = formatDate(date, outputFormat);
    } catch ( ParseException pe ) {
        pe.printStackTrace();
    }

    return displayDateString;
}


问:
Java - Most efficient way to read in a CSV file with various data types
I'm attempting to read in a CSV file with various data types.

A row of the sheet would be like below:

Single, Monthly, Accelerated, John, Smith, 08/15/1951, Yes

I then need to assign each field to a variable name, preform some calculations, print an output and then move onto the next line in the excel sheet

Up until now, I've been using the below

```<code>ArrayList<String> lines = new ArrayList<>();
try {
    BufferedReader reader = new BufferedReader(new FileReader(fileName));
    String line = null;
    while ((line = reader.readLine()) != null) {
        lines.add(line);
        }
</code>```

But this creates an array with each slot containing a long string with the text (including comma) of the corresponding excel row.
This seems inefficient and impractical as i then have to traverse each slot/string to extract the values.

Once I have the methodology, I wont have any issue writing the code but i don't know the best way to go about it

Is it better to read each cell separately and assign to a variable ?
Or is it better to read in a file once and traverse it afterwards?
Perhaps there is a more efficient way to do this task

Edit : I also though of attempting to read in the entire CSV file as a 2D array, but the different data types could be an issue..?

答:
You don't need to store the lines. Instead create a class that represents each row and add them to a list.

Something like :

```<code>class MyData
{
   String status;
   String salary;
   String accelerated;
   String firstName;
   String lastName;
   String date;
   String trueOrFalse;

}
</code>```

You could keep them without any access qualifier or make them private and add getter/setters.

In your file reader, split the line using the separator used in csv which is by default a comma ( , )

```<code>ArrayList<MyData> datas = new ArrayList<MyData>();
while ((line = reader.readLine()) != null) {
        String[] columns = line.split( "," );
        MyData data = new MyData();
        data.status = columns[0];
        data.salary = columns[1];
        .
        .
        data.trueOrFalse = columns[6];
        datas.add( data );
        }
</code>```

OR

If you want to just perform some calculations and print, you don't need a separate class or even ArrayList<String> lines.

Just do :

```<code>while ((line = reader.readLine()) != null) {
        String[] columns = line.split( "," );
        // Perform calculations with columns
        // Print.
}
</code>```

No need to store information if that is the case.

Body:
I'm attempting to read in a CSV file with various data types.

A row of the sheet would be like below:

Single, Monthly, Accelerated, John, Smith, 08/15/1951, Yes

I then need to assign each field to a variable name, preform some calculations, print an output and then move onto the next line in the excel sheet

Up until now, I've been using the below

ArrayList<String> lines = new ArrayList<>();
try {
    BufferedReader reader = new BufferedReader(new FileReader(fileName));
    String line = null;
    while ((line = reader.readLine()) != null) {
        lines.add(line);
        }

But this creates an array with each slot containing a long string with the text (including comma) of the corresponding excel row.
This seems inefficient and impractical as i then have to traverse each slot/string to extract the values.

Once I have the methodology, I wont have any issue writing the code but i don't know the best way to go about it

Is it better to read each cell separately and assign to a variable ?
Or is it better to read in a file once and traverse it afterwards?
Perhaps there is a more efficient way to do this task

Edit : I also though of attempting to read in the entire CSV file as a 2D array, but the different data types could be an issue..?

Body:
You don't need to store the lines. Instead create a class that represents each row and add them to a list.

Something like :

class MyData
{
   String status;
   String salary;
   String accelerated;
   String firstName;
   String lastName;
   String date;
   String trueOrFalse;

}

You could keep them without any access qualifier or make them private and add getter/setters.

In your file reader, split the line using the separator used in csv which is by default a comma ( , )

ArrayList<MyData> datas = new ArrayList<MyData>();
while ((line = reader.readLine()) != null) {
        String[] columns = line.split( "," );
        MyData data = new MyData();
        data.status = columns[0];
        data.salary = columns[1];
        .
        .
        data.trueOrFalse = columns[6];
        datas.add( data );
        }

OR

If you want to just perform some calculations and print, you don't need a separate class or even ArrayList<String> lines.

Just do :

while ((line = reader.readLine()) != null) {
        String[] columns = line.split( "," );
        // Perform calculations with columns
        // Print.
}

No need to store information if that is the case.


问:
Scalastyle "Public method must have explicit type" in Play Framework
We've started experimenting with Scala and the Play framework at my work. Setup our auto-linting and testing framework as the first thing, and have deployed Scalastyle to handle the former.

That has been very useful, except that we are getting this specific lint error that we are finding it difficult to resolve in a good way. A simple example is this:

```<code>  def helloWorld = Action {
    req =>
      Ok("Hello World!")
  }
</code>```

Though often it can be much more complex, of course (to the point where it can difficult to figure out what the type actually is).

In either case, this gives us the "Public method must have explicit type" error from Scalastyle.

Unfortunately, setting the expected explicit type here seems typically to cause a syntax error.

Any suggestions on a good solution for this? Or do we just have to turn of this check for Play projects?

答:
<img src="https://i.stack.imgur.com/TtRPO.png" alt="enter image description here">
I hope this helps. To to Settings -> Editor -> Scala -> Type Annotations. Change the value to 'Add' instead of 'Add & Check' for Public value and method. Then it IDE will not show that warning anymore. </p>

Body:
We've started experimenting with Scala and the Play framework at my work. Setup our auto-linting and testing framework as the first thing, and have deployed Scalastyle to handle the former.

That has been very useful, except that we are getting this specific lint error that we are finding it difficult to resolve in a good way. A simple example is this:

  def helloWorld = Action {
    req =>
      Ok("Hello World!")
  }

Though often it can be much more complex, of course (to the point where it can difficult to figure out what the type actually is).

In either case, this gives us the "Public method must have explicit type" error from Scalastyle.

Unfortunately, setting the expected explicit type here seems typically to cause a syntax error.

Any suggestions on a good solution for this? Or do we just have to turn of this check for Play projects?


问:
C# : Wait for n miliseconds, and test a boolean every n/m milliseconds
I have to test a boolean every 250ms, max 2 seconds, and stop when it's true.

Tried this, but Thread.Sleep isn't a good solution for me because it's freezing my software, and waiting for even more won't change anything because the boolean won't change while it's frozen.

```<code>bool onLine = false;
Stopwatch chrono = new Stopwatch();
chrono.Start();
while (chrono.ElapsedMilliseconds < 2000)
{
    if (!State().Equals(Online))
    {
        System.Threading.Thread.Sleep(250);
    }
    else
    {
        onLine = true;
        operationCompleted();
        break;
    }
}
if (!onLine)
{
    MessageBox.Show("Error");
}
</code>```

I don't know how to make the tests in an event raised by a timer if someone has a correct implementation?

答:
Here's one way this could be accomplished with a timer. The idea is to set the interval to how often you want to check, and set a timeout variable to the time you want to stop checking. Then, in the Tick event (which triggers every interval), do your online check, followed by a check of the timeout.

[Updated for WPF to use a DispatcherTimer]

```<code>System.Windows.Threading.DispatcherTimer timer = new DispatcherTimer();
private DateTime timeout;

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    timeout = DateTime.Now.AddSeconds(2);
    timer.Tick += Timer_Tick;
    timer.Interval = TimeSpan.FromMilliseconds(250);
    timer.Start();
}

private void Timer_Tick(object sender, EventArgs e)
{
    if (State().Equals(Online))
    {
        onLine = true;
        operationCompleted();
        timer.Stop();
    }

    if (DateTime.Now > timeout)
    {
        timer.Stop();
        MessageBox.Show("Error");
    }
}

// rest of code omitted
</code>```

Body:
I have to test a boolean every 250ms, max 2 seconds, and stop when it's true.

Tried this, but Thread.Sleep isn't a good solution for me because it's freezing my software, and waiting for even more won't change anything because the boolean won't change while it's frozen.

bool onLine = false;
Stopwatch chrono = new Stopwatch();
chrono.Start();
while (chrono.ElapsedMilliseconds < 2000)
{
    if (!State().Equals(Online))
    {
        System.Threading.Thread.Sleep(250);
    }
    else
    {
        onLine = true;
        operationCompleted();
        break;
    }
}
if (!onLine)
{
    MessageBox.Show("Error");
}

I don't know how to make the tests in an event raised by a timer if someone has a correct implementation?

Body:
Here's one way this could be accomplished with a timer. The idea is to set the interval to how often you want to check, and set a timeout variable to the time you want to stop checking. Then, in the Tick event (which triggers every interval), do your online check, followed by a check of the timeout.

[Updated for WPF to use a DispatcherTimer]

System.Windows.Threading.DispatcherTimer timer = new DispatcherTimer();
private DateTime timeout;

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    timeout = DateTime.Now.AddSeconds(2);
    timer.Tick += Timer_Tick;
    timer.Interval = TimeSpan.FromMilliseconds(250);
    timer.Start();
}

private void Timer_Tick(object sender, EventArgs e)
{
    if (State().Equals(Online))
    {
        onLine = true;
        operationCompleted();
        timer.Stop();
    }

    if (DateTime.Now > timeout)
    {
        timer.Stop();
        MessageBox.Show("Error");
    }
}

// rest of code omitted


问:
How to get the changed value of UIPicker to be used for a Label? - Swift-3
I have declared table cells and each cell I have added a label and a UIPicker. Once the UIPicker Value is changed, I would like to show the value in the label of the corresponding label.</p>

```<code>class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var myTable: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return 2
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

        let picker = UIPickerView()
        let y = 200 * indexPath.row
        picker.frame = CGRect(x: 200, y: y, width: 100, height: 150)
        picker.delegate = self
        picker.dataSource = self
        picker.tag = indexPath.row
        view.addSubview(picker)

        let myLbl = UILabel()
        myLbl.frame = CGRect(x: 100, y: y, width: 80, height: 100)
        myLbl.backgroundColor = UIColor.gray
        myLbl.textColor = UIColor.white
        myLbl.textAlignment = .center
        myLbl.tag = indexPath.row
        myLbl.text = "hi" // I would like to show the value of the UI picker
        view.addSubview(myLbl)

        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 200
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(indexPath.row)
        NotificationCenter.default.addObserver(self, selector: #selector(pickerChangeAction), name: NSNotification.Name("pickerChange"), object: self)
    }

    public func numberOfComponents(in pickerView: UIPickerView) -> Int{
        return 1
    }

    public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
        return myData.count
    }

     public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{

        return myData[row]

}

     public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){

       NotificationCenter.default.post(name: NSNotification.Name("pickerChange"), object: self)
        print("Hello2")
    }

    func pickerChangeAction(){
        print("Hello1")
    }
}
</code>```

答:
Create a custom UITableViewCell.

Add a UILabel and UIPickerView to it.

Set the custom cell as the delegate for the picker view and move the pickers methods to the custom cell.

In the didSelectRow function update the cells corresponding UILabel

Have a look at the following link if you need help creating a custom UITableViewCell: https://www.ralfebert.de/tutorials/ios-swift-uitableviewcontroller/custom-cells/

Body:
I have declared table cells and each cell I have added a label and a UIPicker. Once the UIPicker Value is changed, I would like to show the value in the label of the corresponding label.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var myTable: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return 2
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

        let picker = UIPickerView()
        let y = 200 * indexPath.row
        picker.frame = CGRect(x: 200, y: y, width: 100, height: 150)
        picker.delegate = self
        picker.dataSource = self
        picker.tag = indexPath.row
        view.addSubview(picker)

        let myLbl = UILabel()
        myLbl.frame = CGRect(x: 100, y: y, width: 80, height: 100)
        myLbl.backgroundColor = UIColor.gray
        myLbl.textColor = UIColor.white
        myLbl.textAlignment = .center
        myLbl.tag = indexPath.row
        myLbl.text = "hi" // I would like to show the value of the UI picker
        view.addSubview(myLbl)

        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 200
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(indexPath.row)
        NotificationCenter.default.addObserver(self, selector: #selector(pickerChangeAction), name: NSNotification.Name("pickerChange"), object: self)
    }

    public func numberOfComponents(in pickerView: UIPickerView) -> Int{
        return 1
    }

    public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
        return myData.count
    }

     public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{

        return myData[row]

}

     public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){

       NotificationCenter.default.post(name: NSNotification.Name("pickerChange"), object: self)
        print("Hello2")
    }

    func pickerChangeAction(){
        print("Hello1")
    }
}


问:
How to increase Simple T-SQL query Performance - taking long hours to complete. Please....!
I have the following simple query with 2 table joins and a WHERE clause.

I already indexed the key joining fields as well as the WHERE clause field.

These 2 tables have about 123 million rows which is pretty huge. It takes about 7/8 hours to complete the full query below. I indexed and not sure what else to do since it's such a simple query with a JOIN & WHERE clauses:

```<code>insert into dbo.IMS_CLAIMS(CLAIM_ID
                          ,DX_CLAIM_ID
                          ,SVC_SEQ_NBR
                          ,SVC_DT
                          ,ALLWD_AMT
                          ,BILL_AMT
                          )
select h.CLAIM_ID
      ,h.DX_CLAIM_ID
      ,s.SVC_SEQ_NBR
      ,h.SVC_DT
      ,s.ALLWD_AMT
      ,s.BILL_AMT
from [2016Q4_VITALS_EXPORT_HEADERS] as h
    inner join [2016Q4_VITALS_EXPORT_SERVICE] as s
        on h.claim_id = s.claim_id
where cast(SVC_DT as date) >= '2015-10-01'
      and cast(SVC_DT as date) <= '2016-11-30';
</code>```

Estimated Execution Plan:

答:
```<code> WHERE cast(SVC_DT as date) >= '2015-10-01' And cast(SVC_DT as date) <= '2016-11-30'
</code>```

When you cast SVC_DT to a date, you are forcing SQL Server to read every row, perform the cast, then do the comparison to '2015-10-01'.  This precludes the usage of indexes on SVC_DT.

```<code> WHERE SVC_DT >= '2015=10-01'  AND SVC_DT < '2016-12-01'
</code>```

Note that we have to bump the ending date from 11/30 to 12/01, and that the <= changed to <

The logic is the same as above, but now SQL Server can use an index.

Body:
I have the following simple query with 2 table joins and a WHERE clause.

I already indexed the key joining fields as well as the WHERE clause field.

These 2 tables have about 123 million rows which is pretty huge. It takes about 7/8 hours to complete the full query below. I indexed and not sure what else to do since it's such a simple query with a JOIN & WHERE clauses:

insert into dbo.IMS_CLAIMS(CLAIM_ID
                          ,DX_CLAIM_ID
                          ,SVC_SEQ_NBR
                          ,SVC_DT
                          ,ALLWD_AMT
                          ,BILL_AMT
                          )
select h.CLAIM_ID
      ,h.DX_CLAIM_ID
      ,s.SVC_SEQ_NBR
      ,h.SVC_DT
      ,s.ALLWD_AMT
      ,s.BILL_AMT
from [2016Q4_VITALS_EXPORT_HEADERS] as h
    inner join [2016Q4_VITALS_EXPORT_SERVICE] as s
        on h.claim_id = s.claim_id
where cast(SVC_DT as date) >= '2015-10-01'
      and cast(SVC_DT as date) <= '2016-11-30';

Estimated Execution Plan:

Body:
 WHERE cast(SVC_DT as date) >= '2015-10-01' And cast(SVC_DT as date) <= '2016-11-30'

When you cast SVC_DT to a date, you are forcing SQL Server to read every row, perform the cast, then do the comparison to '2015-10-01'.  This precludes the usage of indexes on SVC_DT.

 WHERE SVC_DT >= '2015=10-01'  AND SVC_DT < '2016-12-01'

Note that we have to bump the ending date from 11/30 to 12/01, and that the <= changed to <

The logic is the same as above, but now SQL Server can use an index.


问:
How Do I Combine Multiple SQL Queries?
I'm having some trouble figuring out any way to combine two SQL queries into a single one that expresses some greater idea.

For example, let's say that I have query A, and query B. Query A returns the total number of hours worked. Query B returns the total number of hours that were available for workers to work. Each one of these queries returns a single column with a single row.

What I really want, though, is essentially query A over query B. I want to know the percentage of capacity that was worked.

I know how to write query A and B independently, but my problem comes when I try to figure out how to use those prewritten queries to come up with a new SQL query that uses them together. I know that, on a higher level, like say in a report, I could just call both queries and then divide them, but I'd rather encompass it all into a single SQL query.

What I'm looking for is a general idea on how to combine these queries using SQL.

Thanks!

答:
The answer depends on where the data is coming from.

If it's coming from a single table, it could be something as easy as:

```<code>select totalHours, availableHours, (totalHours - availableHours) as difference
from hoursTable
</code>```

But if the data is coming from separate tables, you need to add some identifying column so that the rows can be joined together to provide some useful view of the data.

You may want to post examples of your queries so we know better how to answer your question.

Title: How Do I Combine Multiple SQL Queries?

Body:
The answer depends on where the data is coming from.

If it's coming from a single table, it could be something as easy as:

select totalHours, availableHours, (totalHours - availableHours) as difference
from hoursTable

But if the data is coming from separate tables, you need to add some identifying column so that the rows can be joined together to provide some useful view of the data.

You may want to post examples of your queries so we know better how to answer your question.


问:
What is the difference between iterator and iterable and how to use them?
I am new in Java and I'm really confused with iterator and iterable. Can anyone explain to me and give some examples?</p>

答:
Basically speaking, both of them are very closely related to each other.

Consider Iterator to be an interface which helps us in traversing through a collection with the help of some undefined methods like hasNext(), next() and remove()

On the flip side, Iterable is another interface, which, if implemented by a class forces the class to be Iterable and is a target for For-Each construct.
It has only one method named iterator() which comes from Iterator interface itself.

When a collection is iterable, then it can be iterated using an iterator.

For understanding visit these:

ITERABLE:  http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Iterable.java

ITERATOR http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Iterator.java


答:
Simple solution using a custom cell and a callback closure:

Create a custom cell in Interface Builder, add an UILabel and an UIPickerView.

Create a custom class PickerViewCell, which contains the outlets, the picker data source and a callback closure.

```<code>class PickerViewCell: UITableViewCell {

  var pickerDataSource = ["Alpha", "Beta", "Gamma", "Delta"]

  var callback : ((String) -> ())?

  @IBOutlet var picker : UIPickerView!
  @IBOutlet var selectedText : UILabel!
}

extension PickerViewCell : UIPickerViewDataSource, UIPickerViewDelegate
{
  func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 }
  func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickerDataSource.count }
  func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return pickerDataSource[row] }
  func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { callback?(pickerDataSource[row]) }
}
</code>```

In Interface Builder

Set the class of the custom cell to PickerViewCell and the identifier to PickerCell.

Connect the UI elements to the outlets.

Connect delegate and datasource of the picker to the custom cell.

Implement cellForRow this way, the callback is used to update the label text and to be able to update the data model and do other things after the user picks a value.

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "PickerCell", for: indexPath) as! PickerViewCell
    cell.callback = { (value) in
      cell.selectedText.text = value
      // update the data model
    }
    return cell
}
</code>```

If the picker instances are supposed to have different data source arrays, declare the arrays in the view controller and set the data source in cellForRow respectively.

Title: How to get the changed value of UIPicker to be used for a Label? - Swift-3

Body:
Simple solution using a custom cell and a callback closure:

Create a custom cell in Interface Builder, add an UILabel and an UIPickerView.

Create a custom class PickerViewCell, which contains the outlets, the picker data source and a callback closure.

class PickerViewCell: UITableViewCell {

  var pickerDataSource = ["Alpha", "Beta", "Gamma", "Delta"]

  var callback : ((String) -> ())?

  @IBOutlet var picker : UIPickerView!
  @IBOutlet var selectedText : UILabel!
}

extension PickerViewCell : UIPickerViewDataSource, UIPickerViewDelegate
{
  func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 }
  func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickerDataSource.count }
  func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return pickerDataSource[row] }
  func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { callback?(pickerDataSource[row]) }
}

In Interface Builder

Set the class of the custom cell to PickerViewCell and the identifier to PickerCell.

Connect the UI elements to the outlets.

Connect delegate and datasource of the picker to the custom cell.

Implement cellForRow this way, the callback is used to update the label text and to be able to update the data model and do other things after the user picks a value.

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "PickerCell", for: indexPath) as! PickerViewCell
    cell.callback = { (value) in
      cell.selectedText.text = value
      // update the data model
    }
    return cell
}

If the picker instances are supposed to have different data source arrays, declare the arrays in the view controller and set the data source in cellForRow respectively.


问:
I want to run a t-test, how should I organise my data to do so?
In R, I want to run a statistical test to compare the averages between two categories, but I do not know how to organise my data to do so.

Mock example

My data is organised like:

```<code>structure(list(age = c(39, 45, 83, 68, 48, 52, 66, 50, 61, 67), gender =
structure(c(2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L), .Label = c("female",
"male"), class = "factor")), .Names = c("age", "gender"), row.names = c(NA,
10L), class = "data.frame")
</code>```

What I want to do is compare the average of each gender with a Welch t-test, answering the question "do women's ages are significantly different from men's ages?".

Theoretically, to run the test, I think my data should be in the form:

```<code>male  female
39    45
83    61
...
</code>```

I'm sure there is either a way to run the test directly on the original table or an easy way to transform my data into this form...

So, how should I proceed?

答:
I would go with the pretty data.table:
assuming dt is a data.table (dt<-data.table(dataBase), that is):

```<code>library(stats)
library(data.table)

dt[,t.test(age),by=gender]
</code>```

resulting in:

```<code>   gender statistic parameter      p.value  conf.int estimate null.value alternative            method data.name
1:   male  11.73781         7 7.373447e-06  47.21406   59.125          0   two.sided One Sample t-test       age
2:   male  11.73781         7 7.373447e-06  71.03594   59.125          0   two.sided One Sample t-test       age
3: female   6.62500         1 9.537357e-02 -48.64964   53.000          0   two.sided One Sample t-test       age
4: female   6.62500         1 9.537357e-02 154.64964   53.000          0   two.sided One Sample t-test       age
</code>```

Body:
In R, I want to run a statistical test to compare the averages between two categories, but I do not know how to organise my data to do so.

Mock example

My data is organised like:

structure(list(age = c(39, 45, 83, 68, 48, 52, 66, 50, 61, 67), gender =
structure(c(2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L), .Label = c("female",
"male"), class = "factor")), .Names = c("age", "gender"), row.names = c(NA,
10L), class = "data.frame")

What I want to do is compare the average of each gender with a Welch t-test, answering the question "do women's ages are significantly different from men's ages?".

Theoretically, to run the test, I think my data should be in the form:

male  female
39    45
83    61
...

I'm sure there is either a way to run the test directly on the original table or an easy way to transform my data into this form...

So, how should I proceed?

Body:
I would go with the pretty data.table:
assuming dt is a data.table (dt<-data.table(dataBase), that is):

library(stats)
library(data.table)

dt[,t.test(age),by=gender]

resulting in:

   gender statistic parameter      p.value  conf.int estimate null.value alternative            method data.name
1:   male  11.73781         7 7.373447e-06  47.21406   59.125          0   two.sided One Sample t-test       age
2:   male  11.73781         7 7.373447e-06  71.03594   59.125          0   two.sided One Sample t-test       age
3: female   6.62500         1 9.537357e-02 -48.64964   53.000          0   two.sided One Sample t-test       age
4: female   6.62500         1 9.537357e-02 154.64964   53.000          0   two.sided One Sample t-test       age


问:
Scanning COM dll registry without admin privileges
I'm trying to create a program that scans a COM dll and creates a reg file of the necessary registry keys, without having to call regsvr32 and without having to have administrative permissions.

To do that, I'm using RegOverridePredefKey to remap the windows registry hives inside a subkey of HKEY_CURRENT_USER.

https://msdn.microsoft.com/pt-br/library/windows/desktop/ms724901(v=vs.85).aspx

The remapping is working. I know because I can, for instance, call a windows api function to create a bogus registry key under HKEY_LOCAL_MACHINE and it actually appears under my HKEY_CURRENT_USER subkey. No admin privileges required.

Here is the remaping code:

```<code>if (reg::remapRegistry(HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, basekey + "hkcr"))
    {
        if (reg::remapRegistry(HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER, basekey + "hklm"))
        {
            if (reg::remapRegistry(HKEY_USERS, HKEY_CURRENT_USER, basekey + "hku"))
            {
                if (reg::remapRegistry(HKEY_CURRENT_USER, HKEY_CURRENT_USER, basekey + "hkcu"))
                {
                    reg::createKey(HKEY_LOCAL_MACHINE, "Software\\Classes");
                    reg::createKey(HKEY_CURRENT_USER, "Software\\Classes");
                    ret = scan(args);
                    reg::cancelRemapedRegistry(HKEY_CURRENT_USER);
                }
                reg::cancelRemapedRegistry(HKEY_USERS);
            }
            reg::cancelRemapedRegistry(HKEY_LOCAL_MACHINE);
        }
        reg::cancelRemapedRegistry(HKEY_CLASSES_ROOT);
    }
</code>```

The args parameter to my scan function is just a structure with the path to my dll. The reg:: functions are just wrappers around windows api.

Here is my scan function:

```<code>int scan(const Args &args)
{
typedef HRESULT (__stdcall *pDllRegisterServer) (void);
try
{
    HMODULE hDLL = LoadLibrary(args.dll.c_str());
    if (hDLL == NULL)
    {
        LOGERROR("Cannot load dll");
        return 1;
    }

    pDllRegisterServer DllRegisterServer = (pDllRegisterServer) GetProcAddress(hDLL, "DllRegisterServer");
    if (DllRegisterServer == NULL)
    {
        LOGERROR("Cannot find function DllRegisterServer in dll");
        FreeLibrary(hDLL);
        return 2;
    }

    HRESULT res = DllRegisterServer();
    DWORD err = GetLastError();

    switch (res)
    {
    case S_OK:
        LOGINFO("successfully called DllRegisterServer");
        return 0;
    case SELFREG_E_TYPELIB:
        LOGERROR("DllRegisterServer error SELFREG_E_TYPELIB");
        return 3;
    case SELFREG_E_CLASS:
        LOGERROR("DllRegisterServer error SELFREG_E_CLASS");
        return 4;
    case E_OUTOFMEMORY:
        LOGERROR("DllRegisterServer error E_OUTOFMEMORY");
        return 5;
    case E_UNEXPECTED:
        LOGERROR("DllRegisterServer error E_UNEXPECTED");
        return 6;
    default:
        LOGERROR("DllRegisterServer really unexpected error");
    }

    return 7;
}
catch (...)
{
    LOGERROR("unknown error loading dll or function");
    return -1;
}
}
</code>```

DllRegisterServer is returning S_OK but only half the registry keys are being created. My remapped HKEY_CLASSES_ROOT under HKEY_CURRENT_USER\tempkey\hkcr contains all the expected keys. But HKEY_CURRENT_USER\tempkey\hklm (remapped HKEY_LOCAL_MACHINE) contains only the empty keys "Software\Classes" that I have created myself. It is missing the "TypeLib" and "Interface" keys that DllRegisterServer was supposed to create.

It is not a remapping or permission problem because I can create the empty "Software\Classes" under HKEY_LOCAL_MACHINE without admin rights.

Strangely, testing on another machine DllRegisterServer failed with SELFREG_E_TYPELIB.

I also tried calling LoadTypeLib() and RegisterTypeLib() for which I get the error code "0x8002801c Error accessing the OLE registry."

If I then restart visual studio as administrator and run the program again, I get all expected registry key, including the ones under HKLM.

Any ideas on why is it failing and how to get this thing working?

I know it is possible to get all registry keys without being an administrator, because wix's harvest tool heat.exe does that successfully. I already inspected their source code and I believe I'm already doing all that they are doing. And I don't want to have the wix toolset as a requirement to my build environment just to do that, also because I would need to parse their file format into a *.reg file.

答:
I found out the solution: we must call the function OaEnablePerUserTLibRegistration() before doing the remap.

https://msdn.microsoft.com/en-us/library/windows/desktop/cc713570(v=vs.85).aspx

After calling that function, the callback DllRegisterServer() from the COM dll will try to create the typelib keys under HKCR instead of HKLM.

Body:
I'm trying to create a program that scans a COM dll and creates a reg file of the necessary registry keys, without having to call regsvr32 and without having to have administrative permissions.

To do that, I'm using RegOverridePredefKey to remap the windows registry hives inside a subkey of HKEY_CURRENT_USER.

https://msdn.microsoft.com/pt-br/library/windows/desktop/ms724901(v=vs.85).aspx

The remapping is working. I know because I can, for instance, call a windows api function to create a bogus registry key under HKEY_LOCAL_MACHINE and it actually appears under my HKEY_CURRENT_USER subkey. No admin privileges required.

Here is the remaping code:

if (reg::remapRegistry(HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, basekey + "hkcr"))
    {
        if (reg::remapRegistry(HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER, basekey + "hklm"))
        {
            if (reg::remapRegistry(HKEY_USERS, HKEY_CURRENT_USER, basekey + "hku"))
            {
                if (reg::remapRegistry(HKEY_CURRENT_USER, HKEY_CURRENT_USER, basekey + "hkcu"))
                {
                    reg::createKey(HKEY_LOCAL_MACHINE, "Software\\Classes");
                    reg::createKey(HKEY_CURRENT_USER, "Software\\Classes");
                    ret = scan(args);
                    reg::cancelRemapedRegistry(HKEY_CURRENT_USER);
                }
                reg::cancelRemapedRegistry(HKEY_USERS);
            }
            reg::cancelRemapedRegistry(HKEY_LOCAL_MACHINE);
        }
        reg::cancelRemapedRegistry(HKEY_CLASSES_ROOT);
    }

The args parameter to my scan function is just a structure with the path to my dll. The reg:: functions are just wrappers around windows api.

Here is my scan function:

int scan(const Args &args)
{
typedef HRESULT (__stdcall *pDllRegisterServer) (void);
try
{
    HMODULE hDLL = LoadLibrary(args.dll.c_str());
    if (hDLL == NULL)
    {
        LOGERROR("Cannot load dll");
        return 1;
    }

    pDllRegisterServer DllRegisterServer = (pDllRegisterServer) GetProcAddress(hDLL, "DllRegisterServer");
    if (DllRegisterServer == NULL)
    {
        LOGERROR("Cannot find function DllRegisterServer in dll");
        FreeLibrary(hDLL);
        return 2;
    }

    HRESULT res = DllRegisterServer();
    DWORD err = GetLastError();

    switch (res)
    {
    case S_OK:
        LOGINFO("successfully called DllRegisterServer");
        return 0;
    case SELFREG_E_TYPELIB:
        LOGERROR("DllRegisterServer error SELFREG_E_TYPELIB");
        return 3;
    case SELFREG_E_CLASS:
        LOGERROR("DllRegisterServer error SELFREG_E_CLASS");
        return 4;
    case E_OUTOFMEMORY:
        LOGERROR("DllRegisterServer error E_OUTOFMEMORY");
        return 5;
    case E_UNEXPECTED:
        LOGERROR("DllRegisterServer error E_UNEXPECTED");
        return 6;
    default:
        LOGERROR("DllRegisterServer really unexpected error");
    }

    return 7;
}
catch (...)
{
    LOGERROR("unknown error loading dll or function");
    return -1;
}
}

DllRegisterServer is returning S_OK but only half the registry keys are being created. My remapped HKEY_CLASSES_ROOT under HKEY_CURRENT_USER\tempkey\hkcr contains all the expected keys. But HKEY_CURRENT_USER\tempkey\hklm (remapped HKEY_LOCAL_MACHINE) contains only the empty keys "Software\Classes" that I have created myself. It is missing the "TypeLib" and "Interface" keys that DllRegisterServer was supposed to create.

It is not a remapping or permission problem because I can create the empty "Software\Classes" under HKEY_LOCAL_MACHINE without admin rights.

Strangely, testing on another machine DllRegisterServer failed with SELFREG_E_TYPELIB.

I also tried calling LoadTypeLib() and RegisterTypeLib() for which I get the error code "0x8002801c Error accessing the OLE registry."

If I then restart visual studio as administrator and run the program again, I get all expected registry key, including the ones under HKLM.

Any ideas on why is it failing and how to get this thing working?

I know it is possible to get all registry keys without being an administrator, because wix's harvest tool heat.exe does that successfully. I already inspected their source code and I believe I'm already doing all that they are doing. And I don't want to have the wix toolset as a requirement to my build environment just to do that, also because I would need to parse their file format into a *.reg file.


答:
You can try something similar to this. Use StringTokenizer to split the line by comma and add those elements to another List as strings in each iteration.

```<code>ArrayList<ArrayList<String>> lines = new ArrayList<>();
try {
    BufferedReader reader = new BufferedReader(new FileReader(fileName));
    String line = null;
    while ((line = reader.readLine()) != null) {
        ArrayList<String> tokens = new ArrayList<>();
        StringTokenizer st = new StringTokenizer(line, ",");
        while (st2.hasMoreElements()) {
            tokens.add(st2.nextElement());
        }
        lines.add(tokens);
    }
}
</code>```

Now you can use proper casts to convert them to types you want. For example, to get the date,

```<code>DateFormat format = new SimpleDateFormat("mm/dd/yyyy", Locale.ENGLISH);
String dateString = lines.get(0).get(5);
Date date = format.parse(dateString);
</code>```

Title: Java - Most efficient way to read in a CSV file with various data types

Body:
You can try something similar to this. Use StringTokenizer to split the line by comma and add those elements to another List as strings in each iteration.

ArrayList<ArrayList<String>> lines = new ArrayList<>();
try {
    BufferedReader reader = new BufferedReader(new FileReader(fileName));
    String line = null;
    while ((line = reader.readLine()) != null) {
        ArrayList<String> tokens = new ArrayList<>();
        StringTokenizer st = new StringTokenizer(line, ",");
        while (st2.hasMoreElements()) {
            tokens.add(st2.nextElement());
        }
        lines.add(tokens);
    }
}

Now you can use proper casts to convert them to types you want. For example, to get the date,

DateFormat format = new SimpleDateFormat("mm/dd/yyyy", Locale.ENGLISH);
String dateString = lines.get(0).get(5);
Date date = format.parse(dateString);


问:
NullReferenceException changing the logic within the statement
I have the following piece of code.

```<code>(!string.IsNullOrEmpty(billInfo.BillingMethod) || (!billInfo.BillingMethod.Equals(bill) && bill != null)
</code>```

I understand that I'm getting a null reference exception because more than likely its comparing a null value within the equals method. However I'm confused on how to change the logic so I still end up with the same result without using a method.

答:
NullReferenceException can occur if billInfo or BillingMethod is null. So first checking for billInfo not equal to null, then check for other conditions. Also, the condition after the || is the other way around. As there is no point of checking not null if the first statement is failed.

Try this instead:

```<code> if(billInfo != null && (!string.IsNullOrEmpty(billInfo.BillingMethod) ||
                        (bill != null && !billInfo.BillingMethod.Equals(bill)))
 {
      // Your code here
 }
</code>```

Body:
I have the following piece of code.

(!string.IsNullOrEmpty(billInfo.BillingMethod) || (!billInfo.BillingMethod.Equals(bill) && bill != null)

I understand that I'm getting a null reference exception because more than likely its comparing a null value within the equals method. However I'm confused on how to change the logic so I still end up with the same result without using a method.

Body:
NullReferenceException can occur if billInfo or BillingMethod is null. So first checking for billInfo not equal to null, then check for other conditions. Also, the condition after the || is the other way around. As there is no point of checking not null if the first statement is failed.

Try this instead:

 if(billInfo != null && (!string.IsNullOrEmpty(billInfo.BillingMethod) ||
                        (bill != null && !billInfo.BillingMethod.Equals(bill)))
 {
      // Your code here
 }


问:
Mysql query parent_id order problem
```<code>SELECT * FROM `websiteadmin_pm_categories` WHERE `username`='demo' LIMIT 0, 30 ;
</code>```

Output now:

```<code>id parent_id active_en name_en description_en link_en username
47 0 1 DVD     demo
48 0 1 Spill     demo
49 0 1 Utstyr     demo
50 49 1 PC     demo
51 47 1 Barnefilmer   demo
</code>```

Should be:

```
    id parent_id active_en name_en description_en link_en username
    47 0 1 DVD     demo
    51 47 1 Barnefilmer   demo
    48 0 1 Spill     demo
    49 0 1 Utstyr     demo
    50 49 1 PC     demo```

The problem here is ID and PARENT_ID ,the PARENT_ID should come out under the ID they belong to.

答:
I am not sure if such a solution is possible. I would be quite surprised to see if this is implemented by default in any database.

THis kind of solution should be present in the Display logic rather than queries, as the data is independent of the relation between ID and PARENT_ID

Title: Mysql query parent_id order problem

Body:
SELECT * FROM `websiteadmin_pm_categories` WHERE `username`='demo' LIMIT 0, 30 ;

Output now:

id parent_id active_en name_en description_en link_en username
47 0 1 DVD     demo
48 0 1 Spill     demo
49 0 1 Utstyr     demo
50 49 1 PC     demo
51 47 1 Barnefilmer   demo

Should be:

    id parent_id active_en name_en description_en link_en username
    47 0 1 DVD     demo
    51 47 1 Barnefilmer   demo
    48 0 1 Spill     demo
    49 0 1 Utstyr     demo
    50 49 1 PC     demo

The problem here is ID and PARENT_ID ,the PARENT_ID should come out under the ID they belong to.


问:
Using Xpath Count() for the current node index
I have an xpath that is attempting to select all td tags that have th tag containing text "tracking code"
The issue I am now facing is using the position and count function to select only the relevant td.

Here is what i have thus far

//td[parent::tr/preceding-sibling::tr[1]/th[.='tracking_code']][position()=(count(//th[.="tracking_code"][1]/preceding-sibling::th)-8)]

Ive decided to use the count function in-order to calculate the index but it is returning a count of everything in the document instead of the current node.

As there are multiple table within the html and "tracking_code" position is dynamic what is best approach in using the count() to only count the current node

Here is the html code

````

segment

segment_type	survey

exclusions

aa

aa

inclusions

aa

aa

aa

aa

segment

ID	Section A

question

type	aa

tracking_code	010

exclusions	aa

inclusions	aa

text	aa

ID	1

routing

destination	value

2	aa

37	No

type	aa

tracking_code	023

exclusions	aa

inclusions

aa

aa

text	aa?

ID	2

context	aa

segment

text	bb

ID	4

question

text	bb

tracking_code	165

context	bb

type	bb

text	bb

tracking_code	316

type	bb

ID	Section B

question

type	bb

tracking_code	154

exclusions	bb

inclusions	bb

text	bb

ID	3

context	bb.

text	bb

tracking_code	155

ID	5

routing

destination	value

6	bb

7	No

type	bb

text	bb

tracking_code	156

ID	6

type	bb

segment

segment

text	cc

ID	10

question

validation	text	tracking_code	type

IF YES THEN 278, 279, 280, 281 = NO	cc	277	boolean

IF YES THEN 277, 279, 280, 281 = NO	2Mbps or more, but less than 10Mbps	278	boolean

IF YES THEN 277, 278, 280, 281 = NO	10Mbps or more, but less than 30Mbps	279	boolean

IF YES THEN 277, 278, 279, 281 = NO	30Mbps or more, but less than 100Mbps	280	boolean

IF YES THEN 277, 278, 279, 280 = NO	100Mbps or more	281	boolean

text	cc

question

text	cc

tracking_code	356

ID	9

routing

destination	value

10	Yes

12	No

type	boolean

text	cc

tracking_code	452

ID	11

type	boolean

text	cc

context	cc

question

text	cc

tracking_code	413

ID	12

type	boolean

inclusions	cc

type	boolean

tracking_code	453

inclusions	pcc

text	cc

ID	13

routing

destination	value

14	Yes

15	No

text	cc

tracking_code	320

ID	14

context	cc

type	cc

segment

text	cc

ID	16

question

text	tracking_code	type

cc	203	boolean

cc	147	cc

cc	332	boolean

Tcc	202	boolean

cc	205	boolean

Lcc	414	boolean

text	cc:

ID	17

questions

text	cc

tracking_code	454

type	boolean

text	cc?

tracking_code	455

type	cc

inclusions	cc

exclusions	Oc.

text	cc:

ID	18

questions

text	cc

tracking_code	456

type	boolean

text	cc

tracking_code	457

type	boolean

inclusions	cc

exclusions	cc.

text	cc

question

type	tracking_code	exclusions	text	ID	routing

boolean	080	cc	cc	15

destination	16

value	Yes

destination	17

value	No

segment

text	ID	question

cc	19

text	cc

tracking_code	386

routing

destination	value

20	Yes

21	No

type	boolean

text	cc

tracking_code	387

routing

destination	value

20	Yes

21	No

type	boolean

text	cc

tracking_code	338

routing

destination	value

20	Yes

21	No

type	boolean

text	cc

tracking_code	389

routing

destination	value

20	Yes

21	No

type	boolean

cc	20

text	cc

tracking_code	341

type	boolean

text	cc

tracking_code	342

type	boolean

text	cc

tracking_code	343

type	boolean

text	cc

tracking_code	344

type	boolean

text	c?

tracking_code	345

type	boolean

text	cc?

tracking_code	346

type	boolean

text	cc

context	cc

ID	Section C

question

text	cc

tracking_code	038

ID	7

routing

destination	value

8	Yes

21	No

type	cc

type	cc

tracking_code	022

exclusions

cc

cc

cc

inclusions

cc

cc

cc

text	cc

ID	8

context	cc

segment

text	ID	question

dd:	22

text	dd?

tracking_code	191

type	boolean

text	dd

tracking_code	197

type	boolean

ID	Section D

context

dd

dd

question

text	dd

tracking_code	190

ID	21

type	dd

segment

text	ee

ID	24

question

text	tracking_code	type

ee	259	boolean

Vee	260	boolean

ID	Section E

context	ee.

question

type	boolean

tracking_code	375

exclusions	ee

inclusions	ee

text	ee

ID	23

routing

destination	value

24	Yes

25	No

segment

text	ff:

ID	25

question

text	tracking_code	type

ff	251	boolean

ff	246	boolean

ff	245	boolean

ID	Section F

context

ff.

ff

segment

segment

validation	348 + 349 = '100'

text	gg:

ID	28

question

text	tracking_code	type

gg	348	gg

gg?	349	gg

text	gg?

ID	29

routing

destination	value

30	Yes

31	No

question

text	gg

tracking_code	458

type	boolean

inclusions	gg

text	gg

tracking_code	459

type	boolean

validation	460 + 461 = '100'

text	gg:

ID	30

question

text	tracking_code	type

gg?	460	gg

gg	461	percentage_dec

text	gg?

ID	31

question

text	gg

tracking_code	310

context	Tgg

type	gg

text	gg

tracking_code	311

routing

destination	value

32	Yes

33	No

context	gg

type	boolean

text	Rest of the world

tracking_code	312

type	boolean

text	gg

ID	32

question

text	tracking_code	type

gg	462	boolean

gg	463	boolean

gg	464	boolean

gg	465	boolean

gg	465	boolean

text	gg

question

type	boolean

tracking_code	234

exclusions

gg

gg

inclusions	gg'

text	gg

ID	26

routing

destination	value

27	Yes

33	No

type	gg

tracking_code	235

inclusions	gg

text	gg

ID	27

context	gg

segment

text	gg

ID	35

question

text	UK

tracking_code	313

context	gg

type	boolean

text	gg

tracking_code	314

context	gg

type	boolean

text	gg

tracking_code	315

type	boolean

text	gg

question

type	boolean

tracking_code	257

exclusions

gg

gg

inclusions	gg

text	gg

ID	33

routing

destination	value

34	Yes

36	No

type	gg

tracking_code	258

inclusions	gg

text	gg

ID	34

context	gg

text	gg

question

type	boolean

tracking_code	254

exclusions

cgg

gg

gg

inclusions	gg

text	gg

ID	36

ID	Section G

context	gg

exclusions	gg

segment

text	hh

ID	37

question

text	Ahh

tracking_code	442

type	boolean

text	hh

tracking_code	443

type	boolean

text	hh

tracking_code	444

type	boolean

text	hh

tracking_code	445

type	boolean

text	hh

tracking_code	446

type	boolean

text	hh

tracking_code	447

type	boolean

type	open_text

tracking_code	448

context	hh

text	hh

ID	38

question

type	tracking_code

hours	441

minutes	440

text	hh

ID	39

question

text	hh

tracking_code	449

type	hh

text	hh

tracking_code	450

type	hh

type	open_text

tracking_code	451

context	hh

inclusions	hh

ID	Section H

context

hh

hh

ID	Section I

question

text	Ii

ID	40

tracking-code	500

type	ii

text	ii.

ID	41

tracking-code	C_1

type	ii

type	ii

text	2016

form_type	0031

reporting_period

start	01/01/2016

finish	31/12/2016

notes	aa

survey_number	187

survey_scrape_info

file_name	ex_

folder_name	187

scrape_date	24/05/2017

download_date	22/03/2017

`
```

答: //th gives you all the th elements in the document, so it's doing exactly what you asked for. If you only want th elements that are descendants of the context node, use descendant::th or .//th. But since the context item is itself a th element, I doubt that this is quite what you want. I can't correct the code for you as I have very little idea what it is trying to achieve.

Body:
I have an xpath that is attempting to select all td tags that have th tag containing text "tracking code"
The issue I am now facing is using the position and count function to select only the relevant td.

Here is what i have thus far

//td[parent::tr/preceding-sibling::tr[1]/th[.='tracking_code']][position()=(count(//th[.="tracking_code"][1]/preceding-sibling::th)-8)]

Ive decided to use the count function in-order to calculate the index but it is returning a count of everything in the document instead of the current node.

As there are multiple table within the html and "tracking_code" position is dynamic what is best approach in using the count() to only count the current node

Here is the html code

`

segment

segment_type	survey

exclusions

aa

aa

inclusions

aa

aa

aa

aa

segment

ID	Section A

question

type	aa

tracking_code	010

exclusions	aa

inclusions	aa

text	aa

ID	1

routing

destination	value

2	aa

37	No

type	aa

tracking_code	023

exclusions	aa

inclusions

aa

aa

text	aa?

ID	2

context	aa

segment

text	bb

ID	4

question

text	bb

tracking_code	165

context	bb

type	bb

text	bb

tracking_code	316

type	bb

ID	Section B

question

type	bb

tracking_code	154

exclusions	bb

inclusions	bb

text	bb

ID	3

context	bb.

text	bb

tracking_code	155

ID	5

routing

destination	value

6	bb

7	No

type	bb

text	bb

tracking_code	156

ID	6

type	bb

segment

segment

text	cc

ID	10

question

validation	text	tracking_code	type

IF YES THEN 278, 279, 280, 281 = NO	cc	277	boolean

IF YES THEN 277, 279, 280, 281 = NO	2Mbps or more, but less than 10Mbps	278	boolean

IF YES THEN 277, 278, 280, 281 = NO	10Mbps or more, but less than 30Mbps	279	boolean

IF YES THEN 277, 278, 279, 281 = NO	30Mbps or more, but less than 100Mbps	280	boolean

IF YES THEN 277, 278, 279, 280 = NO	100Mbps or more	281	boolean

text	cc

question

text	cc

tracking_code	356

ID	9

routing

destination	value

10	Yes

12	No

type	boolean

text	cc

tracking_code	452

ID	11

type	boolean

text	cc

context	cc

question

text	cc

tracking_code	413

ID	12

type	boolean

inclusions	cc

type	boolean

tracking_code	453

inclusions	pcc

text	cc

ID	13

routing

destination	value

14	Yes

15	No

text	cc

tracking_code	320

ID	14

context	cc

type	cc

segment

text	cc

ID	16

question

text	tracking_code	type

cc	203	boolean

cc	147	cc

cc	332	boolean

Tcc	202	boolean

cc	205	boolean

Lcc	414	boolean

text	cc:

ID	17

questions

text	cc

tracking_code	454

type	boolean

text	cc?

tracking_code	455

type	cc

inclusions	cc

exclusions	Oc.

text	cc:

ID	18

questions

text	cc

tracking_code	456

type	boolean

text	cc

tracking_code	457

type	boolean

inclusions	cc

exclusions	cc.

text	cc

question

type	tracking_code	exclusions	text	ID	routing

boolean	080	cc	cc	15

destination	16

value	Yes

destination	17

value	No

segment

text	ID	question

cc	19

text	cc

tracking_code	386

routing

destination	value

20	Yes

21	No

type	boolean

text	cc

tracking_code	387

routing

destination	value

20	Yes

21	No

type	boolean

text	cc

tracking_code	338

routing

destination	value

20	Yes

21	No

type	boolean

text	cc

tracking_code	389

routing

destination	value

20	Yes

21	No

type	boolean

cc	20

text	cc

tracking_code	341

type	boolean

text	cc

tracking_code	342

type	boolean

text	cc

tracking_code	343

type	boolean

text	cc

tracking_code	344

type	boolean

text	c?

tracking_code	345

type	boolean

text	cc?

tracking_code	346

type	boolean

text	cc

context	cc

ID	Section C

question

text	cc

tracking_code	038

ID	7

routing

destination	value

8	Yes

21	No

type	cc

type	cc

tracking_code	022

exclusions

cc

cc

cc

inclusions

cc

cc

cc

text	cc

ID	8

context	cc

segment

text	ID	question

dd:	22

text	dd?

tracking_code	191

type	boolean

text	dd

tracking_code	197

type	boolean

ID	Section D

context

dd

dd

question

text	dd

tracking_code	190

ID	21

type	dd

segment

text	ee

ID	24

question

text	tracking_code	type

ee	259	boolean

Vee	260	boolean

ID	Section E

context	ee.

question

type	boolean

tracking_code	375

exclusions	ee

inclusions	ee

text	ee

ID	23

routing

destination	value

24	Yes

25	No

segment

text	ff:

ID	25

question

text	tracking_code	type

ff	251	boolean

ff	246	boolean

ff	245	boolean

ID	Section F

context

ff.

ff

segment

segment

validation	348 + 349 = '100'

text	gg:

ID	28

question

text	tracking_code	type

gg	348	gg

gg?	349	gg

text	gg?

ID	29

routing

destination	value

30	Yes

31	No

question

text	gg

tracking_code	458

type	boolean

inclusions	gg

text	gg

tracking_code	459

type	boolean

validation	460 + 461 = '100'

text	gg:

ID	30

question

text	tracking_code	type

gg?	460	gg

gg	461	percentage_dec

text	gg?

ID	31

question

text	gg

tracking_code	310

context	Tgg

type	gg

text	gg

tracking_code	311

routing

destination	value

32	Yes

33	No

context	gg

type	boolean

text	Rest of the world

tracking_code	312

type	boolean

text	gg

ID	32

question

text	tracking_code	type

gg	462	boolean

gg	463	boolean

gg	464	boolean

gg	465	boolean

gg	465	boolean

text	gg

question

type	boolean

tracking_code	234

exclusions

gg

gg

inclusions	gg'

text	gg

ID	26

routing

destination	value

27	Yes

33	No

type	gg

tracking_code	235

inclusions	gg

text	gg

ID	27

context	gg

segment

text	gg

ID	35

question

text	UK

tracking_code	313

context	gg

type	boolean

text	gg

tracking_code	314

context	gg

type	boolean

text	gg

tracking_code	315

type	boolean

text	gg

question

type	boolean

tracking_code	257

exclusions

gg

gg

inclusions	gg

text	gg

ID	33

routing

destination	value

34	Yes

36	No

type	gg

tracking_code	258

inclusions	gg

text	gg

ID	34

context	gg

text	gg

question

type	boolean

tracking_code	254

exclusions

cgg

gg

gg

inclusions	gg

text	gg

ID	36

ID	Section G

context	gg

exclusions	gg

segment

text	hh

ID	37

question

text	Ahh

tracking_code	442

type	boolean

text	hh

tracking_code	443

type	boolean

text	hh

tracking_code	444

type	boolean

text	hh

tracking_code	445

type	boolean

text	hh

tracking_code	446

type	boolean

text	hh

tracking_code	447

type	boolean

type	open_text

tracking_code	448

context	hh

text	hh

ID	38

question

type	tracking_code

hours	441

minutes	440

text	hh

ID	39

question

text	hh

tracking_code	449

type	hh

text	hh

tracking_code	450

type	hh

type	open_text

tracking_code	451

context	hh

inclusions	hh

ID	Section H

context

hh

hh

ID	Section I

question

text	Ii

ID	40

tracking-code	500

type	ii

text	ii.

ID	41

tracking-code	C_1

type	ii

type	ii

text	2016

form_type	0031

reporting_period

start	01/01/2016

finish	31/12/2016

notes	aa

survey_number	187

survey_scrape_info

file_name	ex_

folder_name	187

scrape_date	24/05/2017

download_date	22/03/2017

`


问:
PHP find max between variables
I'm trying to find out wich variable is bigger (those are all integers):

```<code><?php
$ectoA=3;
$ectoB=5;
$mesoA=0;
$mesoB=4;
$endoA=11;
$endoB=11;

echo max($ectoA,$ectoB,$mesoA,$mesoB,$endoA,$endoB);
</code>```

I tried with max but it gives the value and not the $varName.

I want to get the name of the variable and if there are two that are equal I need both.

Thanks for the help.

As suggested i tried this and worked but still got to know if I have two MAX values I need to do something else...

```<code>  $confronto = [
    'ectoA' => $ectoA,
    'ectoB' => $ectoB,
    'endoA' => $endoA,
    'endoB' => $endoB,
    'mesoA' => $mesoA,
    'mesoB' => $mesoB,
];

$result= array_keys($confronto,max($confronto));

$neurotipo = $result[0];
echo $neurotipo;
</code>```

I want endoA and endoB to be identified...

答:
use the array like this
```</p>

<code><?php
    $value= array (
    "ectoA" =>3,
    "ectoB"=>5,
    "mesoA"=>0,
    "mesoB"=>4,
    "endoA"=>11,
    "endoB"=>11);

    $result= array_keys($value,max($values))
    print_r($result);

?>
</code>```

Title: PHP find max between variables

Body:
I'm trying to find out wich variable is bigger (those are all integers):

<?php
$ectoA=3;
$ectoB=5;
$mesoA=0;
$mesoB=4;
$endoA=11;
$endoB=11;

echo max($ectoA,$ectoB,$mesoA,$mesoB,$endoA,$endoB);

I tried with max but it gives the value and not the $varName.

I want to get the name of the variable and if there are two that are equal I need both.

Thanks for the help.

As suggested i tried this and worked but still got to know if I have two MAX values I need to do something else...

  $confronto = [
    'ectoA' => $ectoA,
    'ectoB' => $ectoB,
    'endoA' => $endoA,
    'endoB' => $endoB,
    'mesoA' => $mesoA,
    'mesoB' => $mesoB,
];

$result= array_keys($confronto,max($confronto));

$neurotipo = $result[0];
echo $neurotipo;

I want endoA and endoB to be identified...

Body:
use the array like this

<?php
    $value= array (
    "ectoA" =>3,
    "ectoB"=>5,
    "mesoA"=>0,
    "mesoB"=>4,
    "endoA"=>11,
    "endoB"=>11);

    $result= array_keys($value,max($values))
    print_r($result);

?>


问:
grunt karma getting error .... Loading "grunt-karma.js" tasks...ERROR
Loading "grunt-karma.js" tasks...ERROR

TypeError: Cannot read property 'prototype' of undefined
    Warning: Task "karma" not found. Use --force to continue.

Aborted due to warnings.

I'm experiencing this issue too.
I'm using node 7.5.0 and npm 4.1.2.

答: Doing npm install on karma helped me fix this problem.</p>


问:
MySQL Daemon Failed to Start - centos 6
EDIT: Look at the checkmarked answer comments to get your issue solved.

Whenever I try to start the SQLD service I get MySQL Daemon Failed to Start. I infact tried to "start" the service by doing the following:

```<code>service mysqld start
</code>```

Also

When I type: mysql

I get:

```<code>ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
</code>```

I know that there should be a mysql.sock file in that directory, so I create one. But the file just auto removes its self and I continue to get the error 2002.

I am also unable to log into PHPMyAdmin due to the error. I can access phpmyadmin page but when logging in I get: #2002 Cannot log in to the MySQL server

EDIT:

Here is my mysql.log file:

```<code>131201 13:05:07 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
131201 13:18:18 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
131201 13:18:18 [Note] Plugin 'FEDERATED' is disabled.
/usr/libexec/mysqld: Can't find file: './mysql/plugin.frm' (errno: 13)
131201 13:18:18 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
131201 13:18:18 InnoDB: The InnoDB memory heap is disabled
131201 13:18:18 InnoDB: Mutexes and rw_locks use GCC atomic builtins
131201 13:18:18 InnoDB: Compressed tables use zlib 1.2.3
131201 13:18:18 InnoDB: Using Linux native AIO
131201 13:18:18 InnoDB: Initializing buffer pool, size = 128.0M
131201 13:18:18 InnoDB: Completed initialization of buffer pool
131201 13:18:18  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
InnoDB: File name ./ibdata1
InnoDB: File operation call: 'open'.
InnoDB: Cannot continue operation.
131201 13:18:18 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
</code>```

I ran mysql_upgrade and got

```<code>Looking for 'mysql' as: mysql
Looking for 'mysqlcheck' as: mysqlcheck
FATAL ERROR: Upgrade failed
</code>```

答:
RE: MySQL Daemon Failed to Start - centos 6 / RHEL 6

Yum Install MySQL

/etc/init.d/mysqld start
MySQL Daemon failed to start.
Starting mysqld:                                           [FAILED]

Review The log: /var/log/mysqld.log

You might get this error:  [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.

Solution that works for me is running this:

$ mysql_install_db

Please let me know if this won't solve your issue.

Title: MySQL Daemon Failed to Start - centos 6

Body:
EDIT: Look at the checkmarked answer comments to get your issue solved.

Whenever I try to start the SQLD service I get MySQL Daemon Failed to Start. I infact tried to "start" the service by doing the following:

service mysqld start

Also

When I type: mysql

I get:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

I know that there should be a mysql.sock file in that directory, so I create one. But the file just auto removes its self and I continue to get the error 2002.

I am also unable to log into PHPMyAdmin due to the error. I can access phpmyadmin page but when logging in I get: #2002 Cannot log in to the MySQL server

EDIT:

Here is my mysql.log file:

131201 13:05:07 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
131201 13:18:18 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
131201 13:18:18 [Note] Plugin 'FEDERATED' is disabled.
/usr/libexec/mysqld: Can't find file: './mysql/plugin.frm' (errno: 13)
131201 13:18:18 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
131201 13:18:18 InnoDB: The InnoDB memory heap is disabled
131201 13:18:18 InnoDB: Mutexes and rw_locks use GCC atomic builtins
131201 13:18:18 InnoDB: Compressed tables use zlib 1.2.3
131201 13:18:18 InnoDB: Using Linux native AIO
131201 13:18:18 InnoDB: Initializing buffer pool, size = 128.0M
131201 13:18:18 InnoDB: Completed initialization of buffer pool
131201 13:18:18  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
InnoDB: File name ./ibdata1
InnoDB: File operation call: 'open'.
InnoDB: Cannot continue operation.
131201 13:18:18 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended

I ran mysql_upgrade and got

Looking for 'mysql' as: mysql
Looking for 'mysqlcheck' as: mysqlcheck
FATAL ERROR: Upgrade failed


问:
Get height of UIView based on specific width before showing view
I have a UIView which I have designed in Interface Builder. It basically consists out of a header image and some text (UILabel) below. The view is being shown modally with a custom Transition and doesn't fill the whole screen.

There is like a 20 pixels margin on the left and right and 40 px on the top. The UILabel gets filled with some text that's coming from the web. What I want do do, is to find (or should I say predict) the height of the whole view for a specific width. How can I do that?

答:
I had similar problem, but instead of calculating font size and image height you can use this UIView extension that will autosize your view with max width:

```<code>extension UIView {

    func autosize(maxWidth: CGFloat) {

        translatesAutoresizingMaskIntoConstraints = false

        let dummyContainerView = UIView(frame: CGRect(x: 0, y: 0, width: maxWidth, height: 10000000))
        dummyContainerView.addSubview(self)
        dummyContainerView.topAnchor.constraint(equalTo: topAnchor, constant: 0).isActive = true
        dummyContainerView.leftAnchor.constraint(equalTo: leftAnchor, constant: 0).isActive = true
        dummyContainerView.rightAnchor.constraint(equalTo: rightAnchor, constant: 0).isActive = true

        setNeedsLayout()
        layoutIfNeeded()

        removeFromSuperview()

        frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)

        translatesAutoresizingMaskIntoConstraints = true
    }
}
</code>```

Using this approuch you don't have to worry about your content inside the view.

To use it:

```<code>let customView: CustomView = ... //create your view
... // configure all data on your view, e.g. labels with correct text
customView.autosize(maxWidth: 150) // resize your view
view.addSubview(customView) // add your view to any view
</code>```

Body:
I had similar problem, but instead of calculating font size and image height you can use this UIView extension that will autosize your view with max width:

extension UIView {

    func autosize(maxWidth: CGFloat) {

        translatesAutoresizingMaskIntoConstraints = false

        let dummyContainerView = UIView(frame: CGRect(x: 0, y: 0, width: maxWidth, height: 10000000))
        dummyContainerView.addSubview(self)
        dummyContainerView.topAnchor.constraint(equalTo: topAnchor, constant: 0).isActive = true
        dummyContainerView.leftAnchor.constraint(equalTo: leftAnchor, constant: 0).isActive = true
        dummyContainerView.rightAnchor.constraint(equalTo: rightAnchor, constant: 0).isActive = true

        setNeedsLayout()
        layoutIfNeeded()

        removeFromSuperview()

        frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)

        translatesAutoresizingMaskIntoConstraints = true
    }
}

Using this approuch you don't have to worry about your content inside the view.

To use it:

let customView: CustomView = ... //create your view
... // configure all data on your view, e.g. labels with correct text
customView.autosize(maxWidth: 150) // resize your view
view.addSubview(customView) // add your view to any view


问:
Fetch cursor from multiple tables view PostgreSQL
I try until couple of hours to fetch all the row from a view, created from multiple tables.

I have two tables (Position, and Vector) to which correspond respectively two custom composite types , type_position and type_vector

Position (id, sys_time, lat, lon)

Vector   (id, sys_time, speed)

I want to create a temporary VIEW in plpgsql procedure to bring together all Position and Vector and order them by sys_time so i wrote :

```<code>CREATE TEMP VIEW posAndVectView AS
                    SELECT * from position
                    UNION ALL
                    SELECT * from vector;
</code>```

I need to iterate over this view and made some work depends on Position and Vector attributes.

So i think i should use a cursor :

```<code>DECLARE
 manyRows refcursor;
BEGIN

OPEN manyRows FOR
SELECT * FROM posAndVectView ORDER BY sys_time ASC;
LOOP
FETCH manyRows INTO posOrVect;
EXIT WHEN NOT FOUND;
...
END LOOP;
CLOSE manyRows;
</code>```

So my question is what should the type of the posOrVect variable be in the DECLARE section ?

It seems to be sometimes a type_vector, sometimes a type_position...

答:
Simple. The type should be posAndVectView.

Like for any other table, there is also a composite type with the same name as a temporary table.

But do you need a view? You could just open the cursor for the query with the UNION. In that case, you'd use type position because it is the first table.

Body:
I try until couple of hours to fetch all the row from a view, created from multiple tables.

I have two tables (Position, and Vector) to which correspond respectively two custom composite types , type_position and type_vector

Position (id, sys_time, lat, lon)

Vector   (id, sys_time, speed)

I want to create a temporary VIEW in plpgsql procedure to bring together all Position and Vector and order them by sys_time so i wrote :

CREATE TEMP VIEW posAndVectView AS
                    SELECT * from position
                    UNION ALL
                    SELECT * from vector;

I need to iterate over this view and made some work depends on Position and Vector attributes.

So i think i should use a cursor :

DECLARE
 manyRows refcursor;
BEGIN

OPEN manyRows FOR
SELECT * FROM posAndVectView ORDER BY sys_time ASC;
LOOP
FETCH manyRows INTO posOrVect;
EXIT WHEN NOT FOUND;
...
END LOOP;
CLOSE manyRows;

So my question is what should the type of the posOrVect variable be in the DECLARE section ?

It seems to be sometimes a type_vector, sometimes a type_position...


问:
Saving custom Swift class with NSCoding to UserDefaults
I am currently trying to save a custom Swift class to NSUserDefaults. Here is the code from my Playground:

```<code>import Foundation

class Blog : NSObject, NSCoding {

    var blogName: String?

    override init() {}

    required init(coder aDecoder: NSCoder) {
        if let blogName = aDecoder.decodeObjectForKey("blogName") as? String {
            self.blogName = blogName
        }
    }

    func encodeWithCoder(aCoder: NSCoder) {
        if let blogName = self.blogName {
            aCoder.encodeObject(blogName, forKey: "blogName")
        }
    }

}

var blog = Blog()
blog.blogName = "My Blog"

let ud = NSUserDefaults.standardUserDefaults()
ud.setObject(blog, forKey: "blog")
</code>```

When I run the code, I get the following error

Execution was interrupted, reason: signal SIGABRT.

in the last line (ud.setObject...)

The same code also crashes when in an app with the message

"Property list invalid for format: 200 (property lists cannot contain
  objects of type 'CFType')"

Can anybody help? I am using Xcode 6.0.1 on Maverick. Thanks.

答:
In Swift 4 you have a new protocol that replaces the NSCoding protocol. It's called Codable and it supports classes and Swift types! (Enum, structs):

```<code>struct CustomStruct: Codable {
    let name: String
    let isActive: Bool
}
</code>```

Body:
I am currently trying to save a custom Swift class to NSUserDefaults. Here is the code from my Playground:

import Foundation

class Blog : NSObject, NSCoding {

    var blogName: String?

    override init() {}

    required init(coder aDecoder: NSCoder) {
        if let blogName = aDecoder.decodeObjectForKey("blogName") as? String {
            self.blogName = blogName
        }
    }

    func encodeWithCoder(aCoder: NSCoder) {
        if let blogName = self.blogName {
            aCoder.encodeObject(blogName, forKey: "blogName")
        }
    }

}

var blog = Blog()
blog.blogName = "My Blog"

let ud = NSUserDefaults.standardUserDefaults()
ud.setObject(blog, forKey: "blog")

When I run the code, I get the following error

Execution was interrupted, reason: signal SIGABRT.

in the last line (ud.setObject...)

The same code also crashes when in an app with the message

"Property list invalid for format: 200 (property lists cannot contain
  objects of type 'CFType')"

Can anybody help? I am using Xcode 6.0.1 on Maverick. Thanks.

Body:
In Swift 4 you have a new protocol that replaces the NSCoding protocol. It's called Codable and it supports classes and Swift types! (Enum, structs):

struct CustomStruct: Codable {
    let name: String
    let isActive: Bool
}


问:
Recursively reading any java Object and pulling out complex types into a hash map
I need to write a utility program which would accept a blank HashMap and any object as arguments and return the HashMap

```<code>public HashMap returnMap(HashMap map,Object parseThisObject){

//logic to strip all children, children of children...... and place it in HashMap
//return map

}
</code>```

This object contains a lot of objects within it and those objects within has a lot of children and the lineage goes on.

My utility must be generic enough to recursively read through all children until it hits primitives in each object, place each of those objects in the hasp map and return it back.
This is something like the parent would be there in the map. but the individual children also would be there as sub sequent entries in the map.

I am new to java reflection and I went through some tutorials and examples on the net. Not very confident about how to proceed. I believe this is one of the frequent requirements experts and professionals over here might have faced.

Plese help me with a starting point on this. If there is any bean utilities open source available to do this? if so please let me know.

答: Have a look at Apache Commons BeanUtils. It already does a large chunk of what you need, and may even do the whole lot in one go.</p>

Body:
I need to write a utility program which would accept a blank HashMap and any object as arguments and return the HashMap

public HashMap returnMap(HashMap map,Object parseThisObject){

//logic to strip all children, children of children...... and place it in HashMap
//return map

}

This object contains a lot of objects within it and those objects within has a lot of children and the lineage goes on.

My utility must be generic enough to recursively read through all children until it hits primitives in each object, place each of those objects in the hasp map and return it back.
This is something like the parent would be there in the map. but the individual children also would be there as sub sequent entries in the map.

I am new to java reflection and I went through some tutorials and examples on the net. Not very confident about how to proceed. I believe this is one of the frequent requirements experts and professionals over here might have faced.

Plese help me with a starting point on this. If there is any bean utilities open source available to do this? if so please let me know.


问:
Dependent type automatic deduction
is it possible to do something like:

```<code>template<class T, T type>
constexpr auto f(/* type used in some way... */) // -> decltype (etc. in case of C++11)
  {
  return std::integral_constant<T,t>{};
  }

constexpr auto z = f(3); // z is deduced as an integral_constant<int,3>;
</code>```

It's for sure not possible using a runtime value, but 3 in this case is a compile time value. Maybe someone knows some trick I'm not aware of...

[edit]
  constexpr auto z2 = f<3>(); // This would be ok too

I just would like to avoid to repeat the type..

答:
Since c++11 you can declare your own literals (I used here std::index_sequence and it's c++14 but you can easily find c++11 implementation of aforesaid):

```<code>#include <utility> // for std::index_sequence and std::size_t

constexpr std::size_t ipow(std::size_t base, int exp, std::size_t result = 1) {
  return exp < 1 ? result : ipow(base*base, exp/2, (exp % 2) ? result*base : result);
}

constexpr std::size_t vdot(std::index_sequence<>, std::index_sequence<>) {
    return 0;
}

template <std::size_t C, std::size_t... Cs, std::size_t I, std::size_t... Is>
constexpr std::size_t vdot(std::index_sequence<C, Cs...>, std::index_sequence<I, Is...>) {
    return C*ipow(10, I) + vdot(std::index_sequence<Cs...>{}, std::index_sequence<Is...>{});
}

template <char... Cs>
std::integral_constant<std::size_t, vdot(std::index_sequence<static_cast<std::size_t>(Cs - '0')...>{}, std::make_index_sequence<sizeof...(Cs)>{})> operator ""_ic() {
    return {};
}

int main() {
   auto ic = 3_ic;
   static_cast<void>(ic);
}
</code>```

[live demo]

Title: Dependent type automatic deduction

Body:
is it possible to do something like:

template<class T, T type>
constexpr auto f(/* type used in some way... */) // -> decltype (etc. in case of C++11)
  {
  return std::integral_constant<T,t>{};
  }

constexpr auto z = f(3); // z is deduced as an integral_constant<int,3>;

It's for sure not possible using a runtime value, but 3 in this case is a compile time value. Maybe someone knows some trick I'm not aware of...

[edit]
  constexpr auto z2 = f<3>(); // This would be ok too

I just would like to avoid to repeat the type..

Body:
Since c++11 you can declare your own literals (I used here std::index_sequence and it's c++14 but you can easily find c++11 implementation of aforesaid):

#include <utility> // for std::index_sequence and std::size_t

constexpr std::size_t ipow(std::size_t base, int exp, std::size_t result = 1) {
  return exp < 1 ? result : ipow(base*base, exp/2, (exp % 2) ? result*base : result);
}

constexpr std::size_t vdot(std::index_sequence<>, std::index_sequence<>) {
    return 0;
}

template <std::size_t C, std::size_t... Cs, std::size_t I, std::size_t... Is>
constexpr std::size_t vdot(std::index_sequence<C, Cs...>, std::index_sequence<I, Is...>) {
    return C*ipow(10, I) + vdot(std::index_sequence<Cs...>{}, std::index_sequence<Is...>{});
}

template <char... Cs>
std::integral_constant<std::size_t, vdot(std::index_sequence<static_cast<std::size_t>(Cs - '0')...>{}, std::make_index_sequence<sizeof...(Cs)>{})> operator ""_ic() {
    return {};
}

int main() {
   auto ic = 3_ic;
   static_cast<void>(ic);
}

[live demo]