问:
jQuery Append: Generic way to move options to bottom of select lists
I have a form with several dozen pages. Across all pages, I need to use jQuery to move specific options in select lists to the bottom of the list.

When I have a single select on the page, this works just fine:

```<code>$('select').find('option[value="optionZ"]').appendTo('select');
</code>```

The issue is when I have more than one select, the optionZ value appends to each list multiple times.

```<code>        <select name="select1">
            <option value="optionA">option A</option>
            <option value="optionZ">option Z</option>
            <option value="optionB">option B</option>
            <option value="optionC">option C</option>
        </select>

        <select name="select2">
            <option value="optionA">option D</option>
            <option value="optionZ">option Z</option>
            <option value="optionB">option E</option>
            <option value="optionC">option F</option>
        </select>
</code>```

The only way I have been able to solve this is by targeting by name:

```<code>$('select[name=select1]').find('option[value="optionZ"]').appendTo('select[name=select1]');

$('select[name=select2]').find('option[value="optionZ"]').appendTo('select[name=select2]');
</code>```

I am looking for a generic way of doing this without referencing the name of the element everytime for maintainability purposes. Essentially "If option Z exists in this select list, append it to this select list". Any ideas?

答:
I'm not exactly sure if this is what you want, but you can move just the selected option to the bottom of the list by putting a button and the <select> element in a containing div.

You can then use .siblings() and .children() functions to find the selected option and append it to the end.

```<code><div id="select1">
  <select name="select1">
    <option value="optionA">option A</option>
    <option value="optionZ">option Z</option>
    <option value="optionB">option B</option>
    <option value="optionC">option C</option>
  </select>
  <button>
  Move to Bottom
  </button>
</div>

$( "button" ).click(function() {
    var thisSelect = $( this ).siblings("select");
  var selected = thisSelect.children(":selected");
  thisSelect.append(selected);
});
</code>```

Fiddle link: https://jsfiddle.net/pjpwea/8fhtu5sa/1/

Body:
I have a form with several dozen pages. Across all pages, I need to use jQuery to move specific options in select lists to the bottom of the list.

When I have a single select on the page, this works just fine:

$('select').find('option[value="optionZ"]').appendTo('select');

The issue is when I have more than one select, the optionZ value appends to each list multiple times.

        <select name="select1">
            <option value="optionA">option A</option>
            <option value="optionZ">option Z</option>
            <option value="optionB">option B</option>
            <option value="optionC">option C</option>
        </select>

        <select name="select2">
            <option value="optionA">option D</option>
            <option value="optionZ">option Z</option>
            <option value="optionB">option E</option>
            <option value="optionC">option F</option>
        </select>

The only way I have been able to solve this is by targeting by name:

$('select[name=select1]').find('option[value="optionZ"]').appendTo('select[name=select1]');

$('select[name=select2]').find('option[value="optionZ"]').appendTo('select[name=select2]');

I am looking for a generic way of doing this without referencing the name of the element everytime for maintainability purposes. Essentially "If option Z exists in this select list, append it to this select list". Any ideas?

Body:
I'm not exactly sure if this is what you want, but you can move just the selected option to the bottom of the list by putting a button and the <select> element in a containing div.

You can then use .siblings() and .children() functions to find the selected option and append it to the end.

<div id="select1">
  <select name="select1">
    <option value="optionA">option A</option>
    <option value="optionZ">option Z</option>
    <option value="optionB">option B</option>
    <option value="optionC">option C</option>
  </select>
  <button>
  Move to Bottom
  </button>
</div>

$( "button" ).click(function() {
    var thisSelect = $( this ).siblings("select");
  var selected = thisSelect.children(":selected");
  thisSelect.append(selected);
});

Fiddle link: https://jsfiddle.net/pjpwea/8fhtu5sa/1/


来源: stackexchange

问:
Service to get/set current entity
I have a Project entity, which has a controller defining many routes:

projects/1
projects/1/foo
projects/1/bar

I need a service to provide the current project. The use case is that I have dependencies in my base twig templates which need to know the current project. i.e. a dropdown project selector that is outside the context of the template the current controller is serving.

I've tried creating a service getting route info with $container->get('router.request_context');, however, that only provides a path. I don't want to have to parse the path string if I don't have to.

What is the most proper approach?

答:
In your controller, you can use type hinting to load the "current" entity via the route.

For example:

```<code>#myrouter.yml
current_project:
  path: /projects/{project}
</code>```

Separately, your controller...

```<code>//mycontroller.php
public function myControllerAction(Request $request, Project $project)
{
    //$project is entity (assuming valid) loaded via the route above
    return $this->render('mytemplate.twig', ['project' => $project]);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Service to get/set current entity

Body:
In your controller, you can use type hinting to load the "current" entity via the route.

For example:

#myrouter.yml
current_project:
  path: /projects/{project}

Separately, your controller...

//mycontroller.php
public function myControllerAction(Request $request, Project $project)
{
    //$project is entity (assuming valid) loaded via the route above
    return $this->render('mytemplate.twig', ['project' => $project]);
}


答:
You could try to use this keyword to reference to currently used select. Assuming that you'd use a change event handler, it would look something like this:

```<code>$('select').on('change',function(){
    $(this).find("option:selected").appendTo( this );
});
</code>```

fiddle: https://jsfiddle.net/3tphmqvv/

Title: jQuery Append: Generic way to move options to bottom of select lists

Body:
You could try to use this keyword to reference to currently used select. Assuming that you'd use a change event handler, it would look something like this:

$('select').on('change',function(){
    $(this).find("option:selected").appendTo( this );
});

fiddle: https://jsfiddle.net/3tphmqvv/


问:
How to solve the error convert String date from xml file to an int format?
I also find myself facing the date problem today, I extracted the date from an xml file in string format but when I try to convert it  into an int format  I have an error.

This is a part of my code :

```<code>DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("top");
for (int j=0; j<= inputFile.length();j++)
    for (int temp =0; temp < nList.getLength(); temp++) {
         j++;
         System.out.println("---------------------------------------");
         Node nNode = nList.item(temp);
         System.out.println("\n La requete numero " +j+ " " + nNode.getNodeName());
         if (nNode.getNodeType() == Node.ELEMENT_NODE) {
             Element eElement = (Element) nNode;
             dateq=eElement.getElementsByTagName("querytime").item(0).getTextContent();
             System.out.println("date de la requete est " +dateq);
             DateFormat dfq = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.FRENCH);
             Date date1 = dfq.parse(dateq);
             System.out.println("new date: " +date1);
</code>```

and the output is :

```<code>date de la requete est  Tue Feb 08 12:30:27 +0000 2011
java.text.ParseException: Unparseable date: " Tue Feb 08 12:30:27 +0000 2011 "
</code>```

答:
As in your previous question I recommend you throw out the outdated classes SimpleDateFormat and friends. The modern classes are generally so much more programmer friendly.

Let’s try an experiment:

```<code>    String dateq = " Tue Feb 08 12:30:27 +0000 2011 ";
    DateTimeFormatter dtfFr = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss xx uuuu",
                                                          Locale.FRENCH);
    OffsetDateTime date1 = OffsetDateTime.parse(dateq, dtfFr);
</code>```

Your exception message clearly shows there are spaces (or other invisible chars) in the beginning and end of your string, so I put them in my string too. Other than that your message just said that the date was unparseable, not why. In contrast, the above code gives java.time.format.DateTimeParseException: Text ' Tue Feb 08 12:30:27 +0000 2011 ' could not be parsed at index 0. Index 0, that is where the first space is, so it’s already a bit more helpful.

My suggestion for removing the spaces:

```<code>    dateq = dateq.trim();
</code>```

This will work with all whitespace, not only space characters, and it will work if there are 0, 1, 2 or many of them. With this line inserted at the right place we get java.time.format.DateTimeParseException: Text 'Tue Feb 08 12:30:27 +0000 2011' could not be parsed at index 0. It’s almost the same message! This time we see no space in the beginning of the string, but it still says the problem is at index 0. This is now where it says “Tue”. The message again is to the point because the problem with “Tue” is it’s English, and you gave a locale of Locale.FRENCH. Having seen that, it’s not difficult:

```<code>    System.out.println("date de la requete est " + dateq);
    dateq = dateq.trim();
    DateTimeFormatter dtfEng = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss xx uuuu",
                                                           Locale.ENGLISH);
    OffsetDateTime date1 = OffsetDateTime.parse(dateq, dtfEng);
    System.out.println("new date: " + date1);
</code>```

This prints:

```<code>date de la requete est  Tue Feb 08 12:30:27 +0000 2011
new date: 2011-02-08T12:30:27Z
</code>```

If you don’t know in advance whether you will have a date in English or French, just try both:

```<code>    dateq = dateq.trim();
    DateTimeFormatter dtfEng = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss xx uuuu",
                                                           Locale.ENGLISH);
    DateTimeFormatter dtfFr = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss xx uuuu",
                                                          Locale.FRENCH);
    OffsetDateTime date1;
    try {
        date1 = OffsetDateTime.parse(dateq, dtfEng);
    } catch (DateTimeParseException dtpe) {
        // didn’t work in English, try French
        date1 = OffsetDateTime.parse(dateq, dtfFr);
    }
</code>```

This handles both dim. janv. 23 24:00:00 +0000 2011 and Tue Feb 08 12:30:27 +0000 2011.

Body:
I also find myself facing the date problem today, I extracted the date from an xml file in string format but when I try to convert it  into an int format  I have an error.

This is a part of my code :

DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("top");
for (int j=0; j<= inputFile.length();j++)
    for (int temp =0; temp < nList.getLength(); temp++) {
         j++;
         System.out.println("---------------------------------------");
         Node nNode = nList.item(temp);
         System.out.println("\n La requete numero " +j+ " " + nNode.getNodeName());
         if (nNode.getNodeType() == Node.ELEMENT_NODE) {
             Element eElement = (Element) nNode;
             dateq=eElement.getElementsByTagName("querytime").item(0).getTextContent();
             System.out.println("date de la requete est " +dateq);
             DateFormat dfq = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.FRENCH);
             Date date1 = dfq.parse(dateq);
             System.out.println("new date: " +date1);

and the output is :

date de la requete est  Tue Feb 08 12:30:27 +0000 2011
java.text.ParseException: Unparseable date: " Tue Feb 08 12:30:27 +0000 2011 "

Body:
As in your previous question I recommend you throw out the outdated classes SimpleDateFormat and friends. The modern classes are generally so much more programmer friendly.

Let’s try an experiment:

    String dateq = " Tue Feb 08 12:30:27 +0000 2011 ";
    DateTimeFormatter dtfFr = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss xx uuuu",
                                                          Locale.FRENCH);
    OffsetDateTime date1 = OffsetDateTime.parse(dateq, dtfFr);

Your exception message clearly shows there are spaces (or other invisible chars) in the beginning and end of your string, so I put them in my string too. Other than that your message just said that the date was unparseable, not why. In contrast, the above code gives java.time.format.DateTimeParseException: Text ' Tue Feb 08 12:30:27 +0000 2011 ' could not be parsed at index 0. Index 0, that is where the first space is, so it’s already a bit more helpful.

My suggestion for removing the spaces:

    dateq = dateq.trim();

This will work with all whitespace, not only space characters, and it will work if there are 0, 1, 2 or many of them. With this line inserted at the right place we get java.time.format.DateTimeParseException: Text 'Tue Feb 08 12:30:27 +0000 2011' could not be parsed at index 0. It’s almost the same message! This time we see no space in the beginning of the string, but it still says the problem is at index 0. This is now where it says “Tue”. The message again is to the point because the problem with “Tue” is it’s English, and you gave a locale of Locale.FRENCH. Having seen that, it’s not difficult:

    System.out.println("date de la requete est " + dateq);
    dateq = dateq.trim();
    DateTimeFormatter dtfEng = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss xx uuuu",
                                                           Locale.ENGLISH);
    OffsetDateTime date1 = OffsetDateTime.parse(dateq, dtfEng);
    System.out.println("new date: " + date1);

This prints:

date de la requete est  Tue Feb 08 12:30:27 +0000 2011
new date: 2011-02-08T12:30:27Z

If you don’t know in advance whether you will have a date in English or French, just try both:

    dateq = dateq.trim();
    DateTimeFormatter dtfEng = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss xx uuuu",
                                                           Locale.ENGLISH);
    DateTimeFormatter dtfFr = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss xx uuuu",
                                                          Locale.FRENCH);
    OffsetDateTime date1;
    try {
        date1 = OffsetDateTime.parse(dateq, dtfEng);
    } catch (DateTimeParseException dtpe) {
        // didn’t work in English, try French
        date1 = OffsetDateTime.parse(dateq, dtfFr);
    }

This handles both dim. janv. 23 24:00:00 +0000 2011 and Tue Feb 08 12:30:27 +0000 2011.


问:
Not able to append the return of a function when I read csv files using a for loop.
The issue i am facing is I am getting individual lists for each .csv i read and it is not appending the result to a single dataframe or list. I am very new to R. Please help me out.
I am getting output as
amazon.csv 10.07
facebook.csv 54.67

Whereas i am expecting all the values in a data frame with column company and CAGR values.

```<code>enter code here

preprocess <- function(x){

  ##flipping data to suit time series analysis
  my.data <- x[nrow(x):1,]

  #sort(x,)

  ## setting up date as date format
  my.data$date <- as.Date(my.data$date)

  ##creating a new data frame to sort the data.
  sorted.data <- my.data[order(my.data$date),]

  #removing the last row as it contains stocks price at moment when i downloaded data
  #sorted.data <- sorted.data[-nrow(sorted.data),]
  #calculating lenght of the data frame
  data.length <- length(sorted.data$date)

  ## extracting the first date
  time.min <- sorted.data$date[1]
  ##extracting the last date
  time.max <- sorted.data$date[data.length]

  # creating a new data frame with all the dates in sequence
  all.dates <- seq(time.min, time.max, by="day")
  all.dates.frame <- data.frame(list(date=all.dates))

  #Merging all dates data frame and sorted data frame; all the empty cells are assigned NA vales
  merged.data <- merge(all.dates.frame, sorted.data, all=T)

  ##Replacing all NA values with the values of the rows of previous day
  final.data <- transform(merged.data, close = na.locf(close), open = na.locf(open), volume = na.locf(volume), high = na.locf(high), low =na.locf(low))
 # write.csv(final.data, file = "C:/Users/rites/Downloads/stock prices", row.names = FALSE)

#
 #return(final.data) #--> ##{remove comment for Code Check}

  ################################################################
  ######calculation of  CAGR(Compound Annual Growth Rate ) #######
  #### {((latest price/Oldest price)^1/#ofyears) - 1}*100 ########
  ################################################################

  ##Extracting closing price of the oldest date

 old_closing_price <- final.data$close[1]

  ##extracting the closing price of the latest date
 new_closing_price <- final.data$close[length(final.data$close)]

  ##extracting the starting year
 start_date <- final.data$date[1]
  start_year <- as.numeric(format(start_date, "%Y"))

  ##extracting the latest date
  end_date <- final.data$date[length(final.data$date)]
 end_year <- as.numeric(format(end_date, "%Y"))

  CAGR_1 <- new_closing_price/old_closing_price
  root <- 1/(end_year-start_year)

 CAGR <- (((CAGR_1)^(root))-1)*100
  return (CAGR)

}

temp = list.files(pattern="*.csv")
for (i in 1:length(temp))
  assign(temp[i], preprocess (read.csv(temp[i])))
</code>```

答:
you need to create an empty data frame and append to this in the loop. You're using assign at the moment which creates variables, not in a data frame. try something like: </p>

```<code>df<-data.frame()
for(i in 1:length(temp)){

   preproc <- preprocess(read.csv(temp[i])))

   df<-rbind(df,data.frame(company = paste0(temp[i]),
                           value = preproc))

}
</code>```

Body:
The issue i am facing is I am getting individual lists for each .csv i read and it is not appending the result to a single dataframe or list. I am very new to R. Please help me out.
I am getting output as
amazon.csv 10.07
facebook.csv 54.67

Whereas i am expecting all the values in a data frame with column company and CAGR values.

enter code here

preprocess <- function(x){

  ##flipping data to suit time series analysis
  my.data <- x[nrow(x):1,]

  #sort(x,)

  ## setting up date as date format
  my.data$date <- as.Date(my.data$date)

  ##creating a new data frame to sort the data.
  sorted.data <- my.data[order(my.data$date),]

  #removing the last row as it contains stocks price at moment when i downloaded data
  #sorted.data <- sorted.data[-nrow(sorted.data),]
  #calculating lenght of the data frame
  data.length <- length(sorted.data$date)

  ## extracting the first date
  time.min <- sorted.data$date[1]
  ##extracting the last date
  time.max <- sorted.data$date[data.length]

  # creating a new data frame with all the dates in sequence
  all.dates <- seq(time.min, time.max, by="day")
  all.dates.frame <- data.frame(list(date=all.dates))

  #Merging all dates data frame and sorted data frame; all the empty cells are assigned NA vales
  merged.data <- merge(all.dates.frame, sorted.data, all=T)

  ##Replacing all NA values with the values of the rows of previous day
  final.data <- transform(merged.data, close = na.locf(close), open = na.locf(open), volume = na.locf(volume), high = na.locf(high), low =na.locf(low))
 # write.csv(final.data, file = "C:/Users/rites/Downloads/stock prices", row.names = FALSE)

#
 #return(final.data) #--> ##{remove comment for Code Check}

  ################################################################
  ######calculation of  CAGR(Compound Annual Growth Rate ) #######
  #### {((latest price/Oldest price)^1/#ofyears) - 1}*100 ########
  ################################################################

  ##Extracting closing price of the oldest date

 old_closing_price <- final.data$close[1]

  ##extracting the closing price of the latest date
 new_closing_price <- final.data$close[length(final.data$close)]

  ##extracting the starting year
 start_date <- final.data$date[1]
  start_year <- as.numeric(format(start_date, "%Y"))

  ##extracting the latest date
  end_date <- final.data$date[length(final.data$date)]
 end_year <- as.numeric(format(end_date, "%Y"))

  CAGR_1 <- new_closing_price/old_closing_price
  root <- 1/(end_year-start_year)

 CAGR <- (((CAGR_1)^(root))-1)*100
  return (CAGR)

}

temp = list.files(pattern="*.csv")
for (i in 1:length(temp))
  assign(temp[i], preprocess (read.csv(temp[i])))

Body:
you need to create an empty data frame and append to this in the loop. You're using assign at the moment which creates variables, not in a data frame. try something like:

df<-data.frame()
for(i in 1:length(temp)){

   preproc <- preprocess(read.csv(temp[i])))

   df<-rbind(df,data.frame(company = paste0(temp[i]),
                           value = preproc))

}


问:
Android, textviews alignment within listitem
I want to arrange the text views in each of my list items so that textview (id:lnumber) is on the left end,  textview (id:lname) next to it and the textview (id:lname1) under textview (id:lname)

I was able to align the first two textviews but am unable to arrange the third, right below the second

list_item.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/lnumber"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:paddingBottom="20dip"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:textColor="@android:color/black"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/lname"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentRight="true"
        android:paddingBottom="20dip"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textSize="17sp"
        android:textColor="@android:color/black" />

    <TextView
        android:id="@+id/lname1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_below="@+id/lname"
        android:paddingBottom="20dip"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textSize="17sp"
        android:textColor="@android:color/black" />

    </LinearLayout>
</code>```

答:
You can use this

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
    android:id="@+id/lname"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="Number" />

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:orientation="vertical">

    <TextView
        android:id="@+id/lnumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name" />

    <TextView
        android:id="@+id/lnumber1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Some Text" />

</LinearLayout>
</code>```

add some padding to suit your needs.

Body:
I want to arrange the text views in each of my list items so that textview (id:lnumber) is on the left end,  textview (id:lname) next to it and the textview (id:lname1) under textview (id:lname)

I was able to align the first two textviews but am unable to arrange the third, right below the second

list_item.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/lnumber"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:paddingBottom="20dip"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:textColor="@android:color/black"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/lname"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentRight="true"
        android:paddingBottom="20dip"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textSize="17sp"
        android:textColor="@android:color/black" />

    <TextView
        android:id="@+id/lname1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_below="@+id/lname"
        android:paddingBottom="20dip"
        android:paddingTop="20dip"
        android:paddingLeft="10dip"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textSize="17sp"
        android:textColor="@android:color/black" />

    </LinearLayout>

Body:
You can use this

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
    android:id="@+id/lname"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="Number" />

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:orientation="vertical">

    <TextView
        android:id="@+id/lnumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name" />

    <TextView
        android:id="@+id/lnumber1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Some Text" />

</LinearLayout>

add some padding to suit your needs.


问:
HealthKit unable to write HKSample with multiple entries if some of the entry types are disallowed by user
Let's say an app requests authorization to write fat and carbohydrates to HealthKit:

```<code>func dataTypesToWrite() -> NSSet {
    return NSSet(objects:
        HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryCarbohydrates)!,
        HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryFatTotal)!
    )
}

healthStore.requestAuthorization(toShare: dataTypesToWrite() as? Set<HKSampleType>, read: nil, completion: { (success, error) -> Void in
    if success {
        print("completed")
    }
})
</code>```

This will prompt the user to allow the app to write to HealthKit. If the user allows both fat and carbs to be written, all is well. But if they only choose to allow one, and an HKSample with fat and carbs is written to HealthKit, that entry won't show up:

```<code>func foodCorrelationForFoodItem(foodNutrients: Dictionary<String, Double>, foodTitle: String) -> HKCorrelation {
    let nowDate: Date = Date()

    let consumedSamples: Set<HKSample> = [
        HKQuantitySample(
            type: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryCarbohydrates)!,
            quantity: HKQuantity(unit: HKUnit.gram(), doubleValue: 5.0),
            start: nowDate,
            end: nowDate),
        HKQuantitySample(
            type: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryFatTotal)!,
            quantity: HKQuantity(unit: HKUnit.gram(), doubleValue: 10.0),
            start: nowDate,
            end: nowDate)
    ]

    let foodType: HKCorrelationType = HKCorrelationType.correlationType(forIdentifier: HKCorrelationTypeIdentifier.food)!
    let foodCorrelationMetadata: [String: AnyObject] = [HKMetadataKeyFoodType: foodTitle as AnyObject]

    let foodCorrelation: HKCorrelation = HKCorrelation(type: foodType, start: nowDate, end: nowDate, objects: consumedSamples, metadata: foodCorrelationMetadata)

    return foodCorrelation
}

self.healthStore.save(foodCorrelationForFoodItem) { (success, error) in
    if let error = error {
        print(error)
    }
}
</code>```

Since Apple doesn't allow applications to see which HealthKit items are writeable, it's impossible to detect if e.g. only fat should be written. Is there a solution to this? Thanks.

答: It's not true that Apple does not allow apps to query which HealthKit types it can write to. You might be thinking of read authorization, which is not queryable. You can use authorizationStatus(for:) on HKHealthStore to determine whether your app has write authorization. If it returns notDetermined or sharingDenied then your app does not have authorization.

Body:
Let's say an app requests authorization to write fat and carbohydrates to HealthKit:

func dataTypesToWrite() -> NSSet {
    return NSSet(objects:
        HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryCarbohydrates)!,
        HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryFatTotal)!
    )
}

healthStore.requestAuthorization(toShare: dataTypesToWrite() as? Set<HKSampleType>, read: nil, completion: { (success, error) -> Void in
    if success {
        print("completed")
    }
})

This will prompt the user to allow the app to write to HealthKit. If the user allows both fat and carbs to be written, all is well. But if they only choose to allow one, and an HKSample with fat and carbs is written to HealthKit, that entry won't show up:

func foodCorrelationForFoodItem(foodNutrients: Dictionary<String, Double>, foodTitle: String) -> HKCorrelation {
    let nowDate: Date = Date()

    let consumedSamples: Set<HKSample> = [
        HKQuantitySample(
            type: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryCarbohydrates)!,
            quantity: HKQuantity(unit: HKUnit.gram(), doubleValue: 5.0),
            start: nowDate,
            end: nowDate),
        HKQuantitySample(
            type: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryFatTotal)!,
            quantity: HKQuantity(unit: HKUnit.gram(), doubleValue: 10.0),
            start: nowDate,
            end: nowDate)
    ]

    let foodType: HKCorrelationType = HKCorrelationType.correlationType(forIdentifier: HKCorrelationTypeIdentifier.food)!
    let foodCorrelationMetadata: [String: AnyObject] = [HKMetadataKeyFoodType: foodTitle as AnyObject]

    let foodCorrelation: HKCorrelation = HKCorrelation(type: foodType, start: nowDate, end: nowDate, objects: consumedSamples, metadata: foodCorrelationMetadata)

    return foodCorrelation
}

self.healthStore.save(foodCorrelationForFoodItem) { (success, error) in
    if let error = error {
        print(error)
    }
}

Since Apple doesn't allow applications to see which HealthKit items are writeable, it's impossible to detect if e.g. only fat should be written. Is there a solution to this? Thanks.


问:
Can Clocks from std::chrono be different on different cores
I like to compare time_points from std::chrono::high_resolution_clock that were measured in threads running on different cores in a processor. Can there be significant differences, such as lags or from faster/slower clocks? What does the standard specify?

答:
I am going to answer this specifically based on your comment that you are running this on a 'Modern' Intel CPU.

I am also going to highlight that this can be a highly contentious discussion since this is very much dependent on the CPU and motherboard. 'Modern' can be a very fluid concept :)

Generally Speaking

The 'Modern' Intel CPU's have incorporated a few mechanisms to ensure uniform ticks across cores. However, it also matters what OS you are running on. For example, some Linux kernels will use the Time Stamp Counter as its source due to less overhead and fall back on the (modern) High Precision Event Timer that attempts to keep the clock tick uniform across cores.

Also, bear in mind that Intel CPUs have numerous power consumption utilities that can affect the CPU Clock frequency.

Best Case Assumption

I would check for the constant_tsc flag as part of the /proc/cpuinfo on Linux as it can then be assumed that the TSC runs in fixed frequency across cores. But...remember the variations above.

There are machine state events like power saving and machine hibernate that can cause the CPU clock frequency to change. In this event, a recalibration of the TSC is required and some documentation suggests this is only at reboot.

Recommendation:

Target a specific chipset and OS and study the specific documentation. Most OS families will have detailed information on the specifics of its clock source.

Depending on your time precision requirements you might want to switch to use

```<code>clock_gettime(CLOCK_MONOTONIC, ...);
</code>```

Body:
I am going to answer this specifically based on your comment that you are running this on a 'Modern' Intel CPU.

I am also going to highlight that this can be a highly contentious discussion since this is very much dependent on the CPU and motherboard. 'Modern' can be a very fluid concept :)

Generally Speaking

The 'Modern' Intel CPU's have incorporated a few mechanisms to ensure uniform ticks across cores. However, it also matters what OS you are running on. For example, some Linux kernels will use the Time Stamp Counter as its source due to less overhead and fall back on the (modern) High Precision Event Timer that attempts to keep the clock tick uniform across cores.

Also, bear in mind that Intel CPUs have numerous power consumption utilities that can affect the CPU Clock frequency.

Best Case Assumption

I would check for the constant_tsc flag as part of the /proc/cpuinfo on Linux as it can then be assumed that the TSC runs in fixed frequency across cores. But...remember the variations above.

There are machine state events like power saving and machine hibernate that can cause the CPU clock frequency to change. In this event, a recalibration of the TSC is required and some documentation suggests this is only at reboot.

Recommendation:

Target a specific chipset and OS and study the specific documentation. Most OS families will have detailed information on the specifics of its clock source.

Depending on your time precision requirements you might want to switch to use

clock_gettime(CLOCK_MONOTONIC, ...);


问:
Why time is stored with minus an hour in oracle database?
I am using angular-moment-picker to pick time ( hours and minutes ). I got the time in this format HH:mm as it is shown in my source code below:

```<code><div class="form-group">
     <p class="icon-group input-group ">
      <input readonly ng-model="workTime.startTime" class="form-control">
      <span class="input-group-btn ">
       <button moment-picker="startTime" format="HH:mm" type="button" class="btn btn-default" id="startTime">
        <i aria-hidden="true" class="glyphicon glyphicon-calendar"></i>
       </button>
      </span>
      <span class="show-date-picker"></span>
     </p>
   </div>
</code>```

After that i formatted it in date format like that:

```<code>var startDate=new Date();
var start=$scope.startTime.toString().trim().split(':');
startDate.setHours(start[0]);
startDate.setMinutes(start[1]);
startDate.setSeconds(0);
</code>```

I got the date in this format:

Mon, 05 Jun 2017 12:00:00 GMT

whenever I store this date in oracle database I got Mon, 05 Jun 2017 11:00:00 GMT

Can someone explain to me why the time is reduced by one hour.

Thank you

答:
You can display your date on UTC like this:</p>

```<code>const date = new Date();
console.log(date.toUTCString());
</code>```

Body:
I am using angular-moment-picker to pick time ( hours and minutes ). I got the time in this format HH:mm as it is shown in my source code below:

      <input readonly ng-model="workTime.startTime" class="form-control">

       <button moment-picker="startTime" format="HH:mm" type="button" class="btn btn-default" id="startTime">

       </button>

After that i formatted it in date format like that:

var startDate=new Date();
var start=$scope.startTime.toString().trim().split(':');
startDate.setHours(start[0]);
startDate.setMinutes(start[1]);
startDate.setSeconds(0);

I got the date in this format:

Mon, 05 Jun 2017 12:00:00 GMT

whenever I store this date in oracle database I got Mon, 05 Jun 2017 11:00:00 GMT

Can someone explain to me why the time is reduced by one hour.

Thank you

Body:
You can display your date on UTC like this:

const date = new Date();
console.log(date.toUTCString());


问:
Multiple observables one subscriber
I need to consume events from multiple sources. Amount of sources varies, a source may be dinamically added or removed.

As I want a possibility to change set of sources 'on the fly', without need to resubscribe, merge is not a case.

Have tried something like

```<code>PublishSubject<Integer> sourcesSubject = PublishSubject.create();

sourcesSubject.subscribe(...);

Observable<Integer> source1 = ...;
source1.subscribe(sourcesSubject); // add first source

Observable<Integer> source2 = ...;
source2.subscribe(sourcesSubject); // add second source

..... // How to remove a source?
</code>```

but have no idea how to remove a source.

Is there a simple solution?

答:
Have found the simplest way to remove source:</p>

```<code>Observable<Integer> source = ...;
Subscription subscription = source.subscribe(sourcesSubject); // add source
subscription.unsubscribe(); // remove source
</code>```

Title: Multiple observables one subscriber

Body:
I need to consume events from multiple sources. Amount of sources varies, a source may be dinamically added or removed.

As I want a possibility to change set of sources 'on the fly', without need to resubscribe, merge is not a case.

Have tried something like

PublishSubject<Integer> sourcesSubject = PublishSubject.create();

sourcesSubject.subscribe(...);

Observable<Integer> source1 = ...;
source1.subscribe(sourcesSubject); // add first source

Observable<Integer> source2 = ...;
source2.subscribe(sourcesSubject); // add second source

..... // How to remove a source?

but have no idea how to remove a source.

Is there a simple solution?

Body:
Have found the simplest way to remove source:

Observable<Integer> source = ...;
Subscription subscription = source.subscribe(sourcesSubject); // add source
subscription.unsubscribe(); // remove source


问:
TypeLoadException when trying to mock IObjectSet with Moq
I have the following setup code:

```<code>MockOf<IObjectSet<Dummy>>().Setup(c => c.AddObject(dummy)).Verifiable();
MockOf<IObjectContextWrapper>().Setup(c => c.GetObjectSet<Dummy>()).Returns(MockOf<IObjectSet<Dummy>>().Object);
</code>```

where Dummy is an empty class definition, and dummy is a Dummy. MockOf<T>() is a mock managing feature on a base class, which basically makes sure that each time it's called on a type, it returns the same mock instance.

The test containing this setup code fails with a TypeLoadException and the following message:

System.TypeLoadException : Type 'IObjectSet`1Proxy389e220f10aa4d9281d0b9e136edc1d4' from assembly 'DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=a621a9e7e5c32e69' is attempting to implement an inaccessible interface.

at System.Reflection.Emit.TypeBuilder.TermCreateClass(RuntimeModule module, Int32 tk, ObjectHandleOnStack type)

  at System.Reflection.Emit.TypeBuilder.CreateTypeNoLock()

  at System.Reflection.Emit.TypeBuilder.CreateType()

  at Castle.DynamicProxy.Generators.Emitters.AbstractTypeEmitter.BuildType()

  at Castle.DynamicProxy.Generators.InterfaceProxyWithTargetGenerator.GenerateCode(Type proxyTargetType, Type[] interfaces, ProxyGenerationOptions options)

  at Castle.DynamicProxy.ProxyGenerator.CreateInterfaceProxyWithoutTarget(Type interfaceToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, IInterceptor[] interceptors)

  at Moq.Mock1.<InitializeInstance>b__0()

  at Moq.Mock1.InitializeInstance()

  at Moq.Mock`1.get_Object()

  at OddEnds.Tests.Data.EntityFramework.RepositoryTest.Delete_DeletesObjectFromObjectSet() in RepositoryTest.cs: line 43

I have imported System.Data.Objects and referenced both System.Data.Entity.dll and Microsoft.Data.Entity.CTP.dll in both the test project and the project where the class being tested resides. The build succeeds with no errors, warnings or messages (except a few related to Code Contracts...)

How do I fix this?

答:
I tripped across another case which I couldn't figure out at first.  I was working on a proxy for an interface created inside of my unit test...

```<code>public IDoWork
{
    void DoWork();
}
</code>```

It took me forever to figure out that the problem was not with that interface, but was, rather, that the unit test itself was not public:

```<code>class TestSomething // missing public keyword
{

// .. some test which tries to create a mock of the interface

    public IDoWork
    {
        void DoWork();
    }

}
</code>```

So, while IDoWork is says it's public, it really is not since it's enclosed in a private class.

Hope this helps someone.

ContentLicense: CC BY-SA 2.5

Body:
I have the following setup code:

MockOf<IObjectSet<Dummy>>().Setup(c => c.AddObject(dummy)).Verifiable();
MockOf<IObjectContextWrapper>().Setup(c => c.GetObjectSet<Dummy>()).Returns(MockOf<IObjectSet<Dummy>>().Object);

where Dummy is an empty class definition, and dummy is a Dummy. MockOf<T>() is a mock managing feature on a base class, which basically makes sure that each time it's called on a type, it returns the same mock instance.

The test containing this setup code fails with a TypeLoadException and the following message:

System.TypeLoadException : Type 'IObjectSet`1Proxy389e220f10aa4d9281d0b9e136edc1d4' from assembly 'DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=a621a9e7e5c32e69' is attempting to implement an inaccessible interface.

at System.Reflection.Emit.TypeBuilder.TermCreateClass(RuntimeModule module, Int32 tk, ObjectHandleOnStack type)

  at System.Reflection.Emit.TypeBuilder.CreateTypeNoLock()

  at System.Reflection.Emit.TypeBuilder.CreateType()

  at Castle.DynamicProxy.Generators.Emitters.AbstractTypeEmitter.BuildType()

  at Castle.DynamicProxy.Generators.InterfaceProxyWithTargetGenerator.GenerateCode(Type proxyTargetType, Type[] interfaces, ProxyGenerationOptions options)

  at Castle.DynamicProxy.ProxyGenerator.CreateInterfaceProxyWithoutTarget(Type interfaceToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, IInterceptor[] interceptors)

  at Moq.Mock1.<InitializeInstance>b__0()

  at Moq.Mock1.InitializeInstance()

  at Moq.Mock`1.get_Object()

  at OddEnds.Tests.Data.EntityFramework.RepositoryTest.Delete_DeletesObjectFromObjectSet() in RepositoryTest.cs: line 43

I have imported System.Data.Objects and referenced both System.Data.Entity.dll and Microsoft.Data.Entity.CTP.dll in both the test project and the project where the class being tested resides. The build succeeds with no errors, warnings or messages (except a few related to Code Contracts...)

How do I fix this?

Body:
I tripped across another case which I couldn't figure out at first.  I was working on a proxy for an interface created inside of my unit test...

public IDoWork
{
    void DoWork();
}

It took me forever to figure out that the problem was not with that interface, but was, rather, that the unit test itself was not public:

class TestSomething // missing public keyword
{

// .. some test which tries to create a mock of the interface

    public IDoWork
    {
        void DoWork();
    }

}

So, while IDoWork is says it's public, it really is not since it's enclosed in a private class.

Hope this helps someone.


问:
Proper collation in format file for BULK INSERT
I'm trying to import a .CSV file into a SQL Server table using a BULK INSERT with a format file. I can get it to import, but any Latin characters are imported as strange characters. I take a lot of pride in completing this personal project on my own, but I've hit a point where I just need help. I can change the characters by doing some messy UPDATE and REPLACE statements after importing the data, but I really want to be able to import the Latin characters as they appear in the .CSV file in one step.
Here's the database and table that I created:

```<code>CREATE DATABASE Test;

CREATE TABLE dbo.rawData
    ([Position] nvarchar(500) NULL,
    [Const] nvarchar(500) NULL,
    [Created] nvarchar(500) NULL,
    [Modified] nvarchar(500) NULL,
    [Description] nvarchar(500) NULL,
    [Title] nvarchar(500) NOT NULL,
    [TitleType] nvarchar(500) NULL,
    [Directors] nvarchar(500) NULL,
    [YouRated] nvarchar(500) NULL,
    [IMDbRating] nvarchar(500) NULL,
    [Runtime] nvarchar(500) NULL,
    [Year] nvarchar(500) NULL,
    [Genres] nvarchar(500) NULL,
    [NumVotes] nvarchar(500) NULL,
    [ReleaseDate] nvarchar(500) NULL,
    [URL] nvarchar(500) NULL,
    )
GO
</code>```

And here is some of the data that I'm working with taken from a .CSV file (saved as ratings.csv). I use Notepad++ and it is encoded in UTF-8. Notice how the last row for "Dallas Buyers Club" has a director with a Latin character in his name:

```<code>"position","const","created","modified","description","Title","Title type","Directors","You rated","IMDb Rating","Runtime (mins)","Year","Genres","Num. Votes","Release Date (month/day/year)","URL"
"1","tt0437863","Tue Feb 16 00:00:00 2016","","","The Benchwarmers","Feature Film","Dennis Dugan","5","5.6","80","2006","comedy, romance, sport","39413","2006-04-07","http://www.imdb.com/title/tt0437863/"
"2","tt0085334","Tue Feb 16 00:00:00 2016","","","A Christmas Story","Feature Film","Bob Clark","6","8.1","94","1983","comedy, family","103770","1983-11-18","http://www.imdb.com/title/tt0085334/"
"3","tt2403029","Tue Feb 16 00:00:00 2016","","","The Starving Games","Feature Film","Jason Friedberg, Aaron Seltzer","2","3.3","83","2013","comedy","13719","2013-10-31","http://www.imdb.com/title/tt2403029/"
"4","tt0316465","Tue Feb 16 00:00:00 2016","","","Radio","Feature Film","Michael Tollin","6","6.9","109","2003","biography, drama, sport","31692","2003-10-24","http://www.imdb.com/title/tt0316465/"
"5","tt0141369","Tue Feb 16 00:00:00 2016","","","Inspector Gadget","Feature Film","David Kellogg","4","4.1","78","1999","action, adventure, comedy, family, sci_fi","35340","1999-07-18","http://www.imdb.com/title/tt0141369/"
"6","tt0033563","Tue Feb 16 00:00:00 2016","","","Dumbo","Feature Film","Sam Armstrong, Norman Ferguson","6","7.3","64","1941","animation, family, musical","80737","1941-10-23","http://www.imdb.com/title/tt0033563/"
"7","tt0384642","Tue Feb 16 00:00:00 2016","","","Kicking & Screaming","Feature Film","Jesse Dylan","5","5.5","95","2005","comedy, family, romance, sport","29539","2005-05-01","http://www.imdb.com/title/tt0384642/"
"8","tt0116705","Tue Feb 16 00:00:00 2016","","","Jingle All the Way","Feature Film","Brian Levant","7","5.4","89","1996","comedy, family","66879","1996-11-16","http://www.imdb.com/title/tt0116705/"
"9","tt1981677","Tue Feb 16 00:00:00 2016","","","Pitch Perfect","Feature Film","Jason Moore","7","7.2","112","2012","comedy, music, romance","203205","2012-09-28","http://www.imdb.com/title/tt1981677/"
"10","tt0409459","Tue Feb 16 00:00:00 2016","","","Watchmen","Feature Film","Zack Snyder","7","7.6","162","2009","action, mystery, sci_fi","368137","2009-02-23","http://www.imdb.com/title/tt0409459/"
"11","tt1343092","Tue Feb 16 00:00:00 2016","","","The Great Gatsby","Feature Film","Baz Luhrmann","5","7.3","143","2013","drama, romance","345664","2013-05-01","http://www.imdb.com/title/tt1343092/"
"12","tt0332379","Tue Feb 16 00:00:00 2016","","","School of Rock","Feature Film","Richard Linklater","5","7.1","108","2003","comedy, music","202083","2003-09-09","http://www.imdb.com/title/tt0332379/"
"13","tt0120783","Tue Feb 16 00:00:00 2016","","","The Parent Trap","Feature Film","Nancy Meyers","6","6.4","128","1998","adventure, comedy, drama, family, romance","82087","1998-07-20","http://www.imdb.com/title/tt0120783/"
"14","tt0790636","Tue Feb 16 00:00:00 2016","","","Dallas Buyers Club","Feature Film","Jean-Marc Vallée","7","8.0","117","2013","biography, drama","308118","2013-09-07","http://www.imdb.com/title/tt0790636/"
</code>```

I have a format file (saved as format.fmt), that when opened in Notepad++ looks like this:

```<code>11.0
16
1       SQLCHAR             0       1000    "\",\""    1     Position                   SQL_Latin1_General_CP1_CI_AS
2       SQLCHAR             0       1000    "\",\""    2     Const                      SQL_Latin1_General_CP1_CI_AS
3       SQLCHAR             0       1000    "\",\""    3     Created                    SQL_Latin1_General_CP1_CI_AS
4       SQLCHAR             0       1000    "\",\""    4     Modified                   SQL_Latin1_General_CP1_CI_AS
5       SQLCHAR             0       1000    "\",\""    5     Description                SQL_Latin1_General_CP1_CI_AS
6       SQLCHAR             0       1000    "\",\""    6     Title                      SQL_Latin1_General_CP1_CI_AS
7       SQLCHAR             0       1000    "\",\""    7     TitleType                  SQL_Latin1_General_CP1_CI_AS
8       SQLCHAR             0       1000    "\",\""    8     Directors                  SQL_Latin1_General_CP1_CI_AS
9       SQLCHAR             0       1000    "\",\""    9     YouRated                   SQL_Latin1_General_CP1_CI_AS
10      SQLCHAR             0       1000    "\",\""    10    IMDbRating                 SQL_Latin1_General_CP1_CI_AS
11      SQLCHAR             0       1000    "\",\""    11    Runtime                    SQL_Latin1_General_CP1_CI_AS
12      SQLCHAR             0       1000    "\",\""    12    Year                       SQL_Latin1_General_CP1_CI_AS
13      SQLCHAR             0       1000    "\",\""    13    Genres                     SQL_Latin1_General_CP1_CI_AS
14      SQLCHAR             0       1000    "\",\""    14    NumVotes                   SQL_Latin1_General_CP1_CI_AS
15      SQLCHAR             0       1000    "\",\""    15    ReleaseDate                SQL_Latin1_General_CP1_CI_AS
16      SQLCHAR             0       1000    "\""     16    URL                        SQL_Latin1_General_CP1_CI_AS
</code>```

When I run the following code, everything imports, however the Latin characters are replaced with a series of strange characters. Here is the code that I'm running:

```<code>BULK INSERT [Test].[dbo].[rawData]
FROM 'C:\IMDbRatings\Files\ratings.csv' WITH (FIRSTROW = 2, FORMATFILE= 'C:\IMDbRatings\format.fmt');
</code>```

A few things I tried were changing the .CSV file to UCS-2 BE, adding different conditions in the WITH clause of the BULK INSERT, and changing the variable type in the format file to SQLNCHAR instead of SQLCHAR, but nothing worked. Often what happens in these cases is "0 rows are affected", rather than an error. Any help would be so appreciated.

答:
I'm answering this old question in the hopes that it will save someone the headaches I recently went through.

Simply put: you should use the "" collation in your format file when inserting from a UTF-8 encoded file using code page 65001. You must have SQL Server 2016 for code page 65001 to be available.

Do the following:

Specify that your bulk insert table is encoded in UTF-8 with CODEPAGE = 65001 in the bulk insert statement

In your format file, specify character column types as SQLCHAR

In your format file, use the "" collation for all columns

Bulk insert statement:

```<code>BULK INSERT [Test].[dbo].[rawData]
FROM 'C:\IMDbRatings\Files\ratings.csv'
WITH (CODEPAGE = 65001, FIRSTROW = 2, FORMATFILE= 'C:\IMDbRatings\format.fmt');
</code>```

Format file:

```<code>13.0
16
1       SQLCHAR             0       1000    "\",\""    1     Position                   ""
2       SQLCHAR             0       1000    "\",\""    2     Const                      ""
3       SQLCHAR             0       1000    "\",\""    3     Created                    ""
4       SQLCHAR             0       1000    "\",\""    4     Modified                   ""
5       SQLCHAR             0       1000    "\",\""    5     Description                ""
6       SQLCHAR             0       1000    "\",\""    6     Title                      ""
7       SQLCHAR             0       1000    "\",\""    7     TitleType                  ""
8       SQLCHAR             0       1000    "\",\""    8     Directors                  ""
9       SQLCHAR             0       1000    "\",\""    9     YouRated                   ""
10      SQLCHAR             0       1000    "\",\""    10    IMDbRating                 ""
11      SQLCHAR             0       1000    "\",\""    11    Runtime                    ""
12      SQLCHAR             0       1000    "\",\""    12    Year                       ""
13      SQLCHAR             0       1000    "\",\""    13    Genres                     ""
14      SQLCHAR             0       1000    "\",\""    14    NumVotes                   ""
15      SQLCHAR             0       1000    "\",\""    15    ReleaseDate                ""
16      SQLCHAR             0       1000    "\""     16    URL                        ""
</code>```

On "" or RAW collation from https://technet.microsoft.com/en-us/library/ms190657(v=sql.105).aspx:

Specifies that the data is stored in the code page that is specified
  in a code-page option in the command or the bcp_control BCPFILECP
  hint. If none of these is specified, the collation of the data file is
  that of the OEM code page of the client computer.

Body:
I'm trying to import a .CSV file into a SQL Server table using a BULK INSERT with a format file. I can get it to import, but any Latin characters are imported as strange characters. I take a lot of pride in completing this personal project on my own, but I've hit a point where I just need help. I can change the characters by doing some messy UPDATE and REPLACE statements after importing the data, but I really want to be able to import the Latin characters as they appear in the .CSV file in one step.
Here's the database and table that I created:

CREATE DATABASE Test;

CREATE TABLE dbo.rawData
    ([Position] nvarchar(500) NULL,
    [Const] nvarchar(500) NULL,
    [Created] nvarchar(500) NULL,
    [Modified] nvarchar(500) NULL,
    [Description] nvarchar(500) NULL,
    [Title] nvarchar(500) NOT NULL,
    [TitleType] nvarchar(500) NULL,
    [Directors] nvarchar(500) NULL,
    [YouRated] nvarchar(500) NULL,
    [IMDbRating] nvarchar(500) NULL,
    [Runtime] nvarchar(500) NULL,
    [Year] nvarchar(500) NULL,
    [Genres] nvarchar(500) NULL,
    [NumVotes] nvarchar(500) NULL,
    [ReleaseDate] nvarchar(500) NULL,
    [URL] nvarchar(500) NULL,
    )
GO

And here is some of the data that I'm working with taken from a .CSV file (saved as ratings.csv). I use Notepad++ and it is encoded in UTF-8. Notice how the last row for "Dallas Buyers Club" has a director with a Latin character in his name:

"position","const","created","modified","description","Title","Title type","Directors","You rated","IMDb Rating","Runtime (mins)","Year","Genres","Num. Votes","Release Date (month/day/year)","URL"
"1","tt0437863","Tue Feb 16 00:00:00 2016","","","The Benchwarmers","Feature Film","Dennis Dugan","5","5.6","80","2006","comedy, romance, sport","39413","2006-04-07","http://www.imdb.com/title/tt0437863/"
"2","tt0085334","Tue Feb 16 00:00:00 2016","","","A Christmas Story","Feature Film","Bob Clark","6","8.1","94","1983","comedy, family","103770","1983-11-18","http://www.imdb.com/title/tt0085334/"
"3","tt2403029","Tue Feb 16 00:00:00 2016","","","The Starving Games","Feature Film","Jason Friedberg, Aaron Seltzer","2","3.3","83","2013","comedy","13719","2013-10-31","http://www.imdb.com/title/tt2403029/"
"4","tt0316465","Tue Feb 16 00:00:00 2016","","","Radio","Feature Film","Michael Tollin","6","6.9","109","2003","biography, drama, sport","31692","2003-10-24","http://www.imdb.com/title/tt0316465/"
"5","tt0141369","Tue Feb 16 00:00:00 2016","","","Inspector Gadget","Feature Film","David Kellogg","4","4.1","78","1999","action, adventure, comedy, family, sci_fi","35340","1999-07-18","http://www.imdb.com/title/tt0141369/"
"6","tt0033563","Tue Feb 16 00:00:00 2016","","","Dumbo","Feature Film","Sam Armstrong, Norman Ferguson","6","7.3","64","1941","animation, family, musical","80737","1941-10-23","http://www.imdb.com/title/tt0033563/"
"7","tt0384642","Tue Feb 16 00:00:00 2016","","","Kicking & Screaming","Feature Film","Jesse Dylan","5","5.5","95","2005","comedy, family, romance, sport","29539","2005-05-01","http://www.imdb.com/title/tt0384642/"
"8","tt0116705","Tue Feb 16 00:00:00 2016","","","Jingle All the Way","Feature Film","Brian Levant","7","5.4","89","1996","comedy, family","66879","1996-11-16","http://www.imdb.com/title/tt0116705/"
"9","tt1981677","Tue Feb 16 00:00:00 2016","","","Pitch Perfect","Feature Film","Jason Moore","7","7.2","112","2012","comedy, music, romance","203205","2012-09-28","http://www.imdb.com/title/tt1981677/"
"10","tt0409459","Tue Feb 16 00:00:00 2016","","","Watchmen","Feature Film","Zack Snyder","7","7.6","162","2009","action, mystery, sci_fi","368137","2009-02-23","http://www.imdb.com/title/tt0409459/"
"11","tt1343092","Tue Feb 16 00:00:00 2016","","","The Great Gatsby","Feature Film","Baz Luhrmann","5","7.3","143","2013","drama, romance","345664","2013-05-01","http://www.imdb.com/title/tt1343092/"
"12","tt0332379","Tue Feb 16 00:00:00 2016","","","School of Rock","Feature Film","Richard Linklater","5","7.1","108","2003","comedy, music","202083","2003-09-09","http://www.imdb.com/title/tt0332379/"
"13","tt0120783","Tue Feb 16 00:00:00 2016","","","The Parent Trap","Feature Film","Nancy Meyers","6","6.4","128","1998","adventure, comedy, drama, family, romance","82087","1998-07-20","http://www.imdb.com/title/tt0120783/"
"14","tt0790636","Tue Feb 16 00:00:00 2016","","","Dallas Buyers Club","Feature Film","Jean-Marc Vallée","7","8.0","117","2013","biography, drama","308118","2013-09-07","http://www.imdb.com/title/tt0790636/"

I have a format file (saved as format.fmt), that when opened in Notepad++ looks like this:

11.0
16
1       SQLCHAR             0       1000    "\",\""    1     Position                   SQL_Latin1_General_CP1_CI_AS
2       SQLCHAR             0       1000    "\",\""    2     Const                      SQL_Latin1_General_CP1_CI_AS
3       SQLCHAR             0       1000    "\",\""    3     Created                    SQL_Latin1_General_CP1_CI_AS
4       SQLCHAR             0       1000    "\",\""    4     Modified                   SQL_Latin1_General_CP1_CI_AS
5       SQLCHAR             0       1000    "\",\""    5     Description                SQL_Latin1_General_CP1_CI_AS
6       SQLCHAR             0       1000    "\",\""    6     Title                      SQL_Latin1_General_CP1_CI_AS
7       SQLCHAR             0       1000    "\",\""    7     TitleType                  SQL_Latin1_General_CP1_CI_AS
8       SQLCHAR             0       1000    "\",\""    8     Directors                  SQL_Latin1_General_CP1_CI_AS
9       SQLCHAR             0       1000    "\",\""    9     YouRated                   SQL_Latin1_General_CP1_CI_AS
10      SQLCHAR             0       1000    "\",\""    10    IMDbRating                 SQL_Latin1_General_CP1_CI_AS
11      SQLCHAR             0       1000    "\",\""    11    Runtime                    SQL_Latin1_General_CP1_CI_AS
12      SQLCHAR             0       1000    "\",\""    12    Year                       SQL_Latin1_General_CP1_CI_AS
13      SQLCHAR             0       1000    "\",\""    13    Genres                     SQL_Latin1_General_CP1_CI_AS
14      SQLCHAR             0       1000    "\",\""    14    NumVotes                   SQL_Latin1_General_CP1_CI_AS
15      SQLCHAR             0       1000    "\",\""    15    ReleaseDate                SQL_Latin1_General_CP1_CI_AS
16      SQLCHAR             0       1000    "\""     16    URL                        SQL_Latin1_General_CP1_CI_AS

When I run the following code, everything imports, however the Latin characters are replaced with a series of strange characters. Here is the code that I'm running:

BULK INSERT [Test].[dbo].[rawData]
FROM 'C:\IMDbRatings\Files\ratings.csv' WITH (FIRSTROW = 2, FORMATFILE= 'C:\IMDbRatings\format.fmt');

A few things I tried were changing the .CSV file to UCS-2 BE, adding different conditions in the WITH clause of the BULK INSERT, and changing the variable type in the format file to SQLNCHAR instead of SQLCHAR, but nothing worked. Often what happens in these cases is "0 rows are affected", rather than an error. Any help would be so appreciated.

Body:
I'm answering this old question in the hopes that it will save someone the headaches I recently went through.

Simply put: you should use the "" collation in your format file when inserting from a UTF-8 encoded file using code page 65001. You must have SQL Server 2016 for code page 65001 to be available.

Do the following:

Specify that your bulk insert table is encoded in UTF-8 with CODEPAGE = 65001 in the bulk insert statement

In your format file, specify character column types as SQLCHAR

In your format file, use the "" collation for all columns

Bulk insert statement:

BULK INSERT [Test].[dbo].[rawData]
FROM 'C:\IMDbRatings\Files\ratings.csv'
WITH (CODEPAGE = 65001, FIRSTROW = 2, FORMATFILE= 'C:\IMDbRatings\format.fmt');

Format file:

13.0
16
1       SQLCHAR             0       1000    "\",\""    1     Position                   ""
2       SQLCHAR             0       1000    "\",\""    2     Const                      ""
3       SQLCHAR             0       1000    "\",\""    3     Created                    ""
4       SQLCHAR             0       1000    "\",\""    4     Modified                   ""
5       SQLCHAR             0       1000    "\",\""    5     Description                ""
6       SQLCHAR             0       1000    "\",\""    6     Title                      ""
7       SQLCHAR             0       1000    "\",\""    7     TitleType                  ""
8       SQLCHAR             0       1000    "\",\""    8     Directors                  ""
9       SQLCHAR             0       1000    "\",\""    9     YouRated                   ""
10      SQLCHAR             0       1000    "\",\""    10    IMDbRating                 ""
11      SQLCHAR             0       1000    "\",\""    11    Runtime                    ""
12      SQLCHAR             0       1000    "\",\""    12    Year                       ""
13      SQLCHAR             0       1000    "\",\""    13    Genres                     ""
14      SQLCHAR             0       1000    "\",\""    14    NumVotes                   ""
15      SQLCHAR             0       1000    "\",\""    15    ReleaseDate                ""
16      SQLCHAR             0       1000    "\""     16    URL                        ""

On "" or RAW collation from https://technet.microsoft.com/en-us/library/ms190657(v=sql.105).aspx:

Specifies that the data is stored in the code page that is specified
  in a code-page option in the command or the bcp_control BCPFILECP
  hint. If none of these is specified, the collation of the data file is
  that of the OEM code page of the client computer.


问:
Unable to Activate appService, Program is blocked by group policy
I have a UWP appService (e.g. <uap:Extension Category="windows.appService") that was working fine that no longer deploys to Windows after upgrading to 15063.

When I start without debugging from Visual Studio I get "Unable to activate Windows Store app ... The activation request failed with error 'This program is blocked by group policy ..."

I've tried manually uninstalling the app, rebooting, and clearing out my bin and obj directories.  I'm not connected to AD, and I've tried and setting everything to Enabled (from Undefined) in

```<code>Local Computer Policy -> Computer Configuration -> Administrative Templates -> Windows Components -> App Package Deployment"
</code>```

What am I doing wrong?  Has something changed in 15063 for appServices?

答:
You can't debug app services out of the box.  The error message is a red herring.
 Instead right click and select "Deploy".

Or if you want breakpoints to hit Project Properties -> Debug -> Start action = Do not launch, but debug your code when it starts.

Body:
I have a UWP appService (e.g. <uap:Extension Category="windows.appService") that was working fine that no longer deploys to Windows after upgrading to 15063.

When I start without debugging from Visual Studio I get "Unable to activate Windows Store app ... The activation request failed with error 'This program is blocked by group policy ..."

I've tried manually uninstalling the app, rebooting, and clearing out my bin and obj directories.  I'm not connected to AD, and I've tried and setting everything to Enabled (from Undefined) in

Local Computer Policy -> Computer Configuration -> Administrative Templates -> Windows Components -> App Package Deployment"

What am I doing wrong?  Has something changed in 15063 for appServices?


问:
CLIPS code no result
I am new to CLIPS and I can't figure out why my code doesn't run. Actually I get no errros, but when I press run the facts don't change and the goal is never found. The project is that we have 2 bottles. Bottle A with capacity 3 and B with capacity 2. The goal is A has 0 and B has 1. We can do it with these rules: fillA,fillB,emptyA,emptyB,moveAB,moveBA.
Below is my code. Can someone help?thanks!</p>

```<code>(deffacts problem
   (name A cap 3 water 0)
   (name B cap 2 water 0)
)

(defrule goal
 (declare (salience 100))
 (name A water 0)
 (name B water 1)
=>
 (printout t "FOUND" crlf)
 (halt)
)

(defrule start
 (initial-fact)
=>
 (set-strategy random)
)

(defrule emptyA
 ?x<-(name A water ?w)
=>
 (retract ?x)
 (assert (name A water 0))
)

(defrule emptyB
 ?x<-(name B water ?w)
=>
 (retract ?x)
 (assert (name B water 0))
)

(defrule fillA
 ?x<-(name A water ?w)
=>
 (retract ?x)
 (assert (name A water 3))
)

(defrule fillB
 ?x<-(name B water ?w)
=>
 (retract ?x)
 (assert (name B water 2))
)

(defrule moveAB
 ?x<-(name A water ?w)
 ?y<-(name B water ?water)
 (test (not (< ?w 0)))
 (test (not (> ?water 2)))
=>
 (retract ?x ?y)
 (assert (name B water ?w))
 (assert (name A water ?water))
)

(defrule moveBA
 ?x<-(name A water ?w)
 ?y<-(name B water ?water)
 (test (not (> ?w 3)))
 (test (not (< ?water 0)))
=>
 (retract ?x ?y)
 (assert (name A water ?water))
 (assert (name B water ?w))
)
</code>```

答:
All of your fact patterns match name facts with three fields. Your name facts have five fields. There needs to be an exact match. For example, instead of the following pattern:

```<code>(name B water ?w)
</code>```

You should use:

```<code>(name B cap ? water ?w)
</code>```

or:

```<code>(name B cap ?c water ?w)
</code>```

Alternately, use deftemplate facts so that you can specify only the slots of interest in your patterns:

```<code>(deftemplate bottle
   (slot name)
   (slot cap)
   (slot water (default 0)))

(deffacts problem
   (bottle (name A) (cap 3))
   (bottle (name B) (cap 2)))

(defrule fillA
   ?x <- (bottle (name A ) (water ?w))
   =>
   (modify ?x (water 3)))
</code>```

Title: CLIPS code no result

Body:
I am new to CLIPS and I can't figure out why my code doesn't run. Actually I get no errros, but when I press run the facts don't change and the goal is never found. The project is that we have 2 bottles. Bottle A with capacity 3 and B with capacity 2. The goal is A has 0 and B has 1. We can do it with these rules: fillA,fillB,emptyA,emptyB,moveAB,moveBA.
Below is my code. Can someone help?thanks!

(deffacts problem
   (name A cap 3 water 0)
   (name B cap 2 water 0)
)

(defrule goal
 (declare (salience 100))
 (name A water 0)
 (name B water 1)
=>
 (printout t "FOUND" crlf)
 (halt)
)

(defrule start
 (initial-fact)
=>
 (set-strategy random)
)

(defrule emptyA
 ?x<-(name A water ?w)
=>
 (retract ?x)
 (assert (name A water 0))
)

(defrule emptyB
 ?x<-(name B water ?w)
=>
 (retract ?x)
 (assert (name B water 0))
)

(defrule fillA
 ?x<-(name A water ?w)
=>
 (retract ?x)
 (assert (name A water 3))
)

(defrule fillB
 ?x<-(name B water ?w)
=>
 (retract ?x)
 (assert (name B water 2))
)

(defrule moveAB
 ?x<-(name A water ?w)
 ?y<-(name B water ?water)
 (test (not (< ?w 0)))
 (test (not (> ?water 2)))
=>
 (retract ?x ?y)
 (assert (name B water ?w))
 (assert (name A water ?water))
)

(defrule moveBA
 ?x<-(name A water ?w)
 ?y<-(name B water ?water)
 (test (not (> ?w 3)))
 (test (not (< ?water 0)))
=>
 (retract ?x ?y)
 (assert (name A water ?water))
 (assert (name B water ?w))
)

Body:
All of your fact patterns match name facts with three fields. Your name facts have five fields. There needs to be an exact match. For example, instead of the following pattern:

(name B water ?w)

You should use:

(name B cap ? water ?w)

or:

(name B cap ?c water ?w)

Alternately, use deftemplate facts so that you can specify only the slots of interest in your patterns:

(deftemplate bottle
   (slot name)
   (slot cap)
   (slot water (default 0)))

(deffacts problem
   (bottle (name A) (cap 3))
   (bottle (name B) (cap 2)))

(defrule fillA
   ?x <- (bottle (name A ) (water ?w))
   =>
   (modify ?x (water 3)))


问:
Goal Seek in multiple rows (with empty rows in the middle)
I want to perform a goal seek for several rows (I don't know exactly how many - in the code I have below it stops in row 100). The thing is, for example, if I have 10 rows, row number 5 can be empty. So I want it to skip from row 4 to row 6, then continue, then "jump" another empty row if they exist.

I want to set cell M2 to 0 by changing the value of cell K2. The same for row 3, row 4, etc. and I want it to skip empty rows.

Right now I just have this... a simple case

```<code>Sub GSeek()

Dim i As Long
For i = 2 To 100

    range("M" & i).GoalSeek Goal:=0, ChangingCell:=range("K" & i)

Next

End Sub
</code>```

答:
Try this

```<code>Dim i As Long

For i = 2 To 100
    If range("M" & i).Value <> "" Then
        range("M" & i).GoalSeek Goal:=0, ChangingCell:=range("K" & i)
    End If
Next i
</code>```

Each time it just makes sure that the cell isn't empty. If it is, it'll just move to next i

Body:
I want to perform a goal seek for several rows (I don't know exactly how many - in the code I have below it stops in row 100). The thing is, for example, if I have 10 rows, row number 5 can be empty. So I want it to skip from row 4 to row 6, then continue, then "jump" another empty row if they exist.

I want to set cell M2 to 0 by changing the value of cell K2. The same for row 3, row 4, etc. and I want it to skip empty rows.

Right now I just have this... a simple case

Sub GSeek()

Dim i As Long
For i = 2 To 100

    range("M" & i).GoalSeek Goal:=0, ChangingCell:=range("K" & i)

Next

End Sub

Body:
Try this

Dim i As Long

For i = 2 To 100
    If range("M" & i).Value <> "" Then
        range("M" & i).GoalSeek Goal:=0, ChangingCell:=range("K" & i)
    End If
Next i

Each time it just makes sure that the cell isn't empty. If it is, it'll just move to next i


问:
Generate list of numbers fron N to 1 in prolog
I am trying to generate a list of numbers from N to 1 without using any build-in predicated such as findall or numlist. What am I doing wrong ?

```<code>    pred(N,[H|T]):-  H is N, N1 is N-1, pred(N1,T).
    pred(1,[]).
</code>```

I keep getting ERROR: Out of global stack

答:
The most complete solution would be:

```<code>pred(1, [1]).
pred(N, [N|T]) :-
    N > 1,
    N1 is N-1,
    pred(N1, T).
</code>```

Without the N > 1 condition you can still get a stack overflow:

```<code>| ?- pred(3, L).

L = [3,2,1] ? ;

Fatal Error: global stack overflow (size: 32768 Kb, reached: 32765 Kb, environment variable used: GLOBALSZ)
</code>```

But with the N > 1 condition:

```<code>| ?- pred(3, L).

L = [3,2,1] ? ;

(1 ms) no
| ?-
</code>```

Also, with the correct conditions, the order of your predicates no longer matters. This is because your clauses properly then only operate under the conditions they are supposed to. Without it, your pred(N, [N|T]) :- ... clause, which is only intended to operate when N > 1 will also attempt to run when N =< 1. Swapping the clause order only hides this issue and only somewhat. Order can, however, be important for efficiency.

Body:
I am trying to generate a list of numbers from N to 1 without using any build-in predicated such as findall or numlist. What am I doing wrong ?

    pred(N,[H|T]):-  H is N, N1 is N-1, pred(N1,T).
    pred(1,[]).

I keep getting ERROR: Out of global stack

Body:
The most complete solution would be:

pred(1, [1]).
pred(N, [N|T]) :-
    N > 1,
    N1 is N-1,
    pred(N1, T).

Without the N > 1 condition you can still get a stack overflow:

| ?- pred(3, L).

L = [3,2,1] ? ;

Fatal Error: global stack overflow (size: 32768 Kb, reached: 32765 Kb, environment variable used: GLOBALSZ)

But with the N > 1 condition:

| ?- pred(3, L).

L = [3,2,1] ? ;

(1 ms) no
| ?-

Also, with the correct conditions, the order of your predicates no longer matters. This is because your clauses properly then only operate under the conditions they are supposed to. Without it, your pred(N, [N|T]) :- ... clause, which is only intended to operate when N > 1 will also attempt to run when N =< 1. Swapping the clause order only hides this issue and only somewhat. Order can, however, be important for efficiency.


问:
Determine device public ip
Does anyone know how I could get the public ip address of an android device?

I am trying to run a server socket (just experimenting with simple p2p).

This requires informing the local and remote users of each others public ip. I did find this thread How to get IP address of the device from code? which contains a link to an article (http://www.droidnova.com/get-the-ip-address-of-your-device,304.html) that shows how to get the IP. However this returns the local ip when connected through a router and I would like to get the actual public IP instead.

TIA

答:
```<code>public class Test extends AsyncTask {

    @Override
    protected Object doInBackground(Object[] objects) {

        URL whatismyip = null;
        try {
            whatismyip = new URL("http://icanhazip.com/");

            try {
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        whatismyip.openStream()));

                String ip = in.readLine(); //you get the IP as a String
                Log.i(TAG, "EXT IP: " + ip);
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return null;
    }

}
</code>```

Title: Determine device public ip


问:
How do i put bitmaps or any image format in an assembly program
this is a question i really need help on, i am currently writing an OS in FASM assembly and have a decent output with icons being from the ASCII table. I want to know if you can have images show up on your assembly program. I couldn't find a website so a link to a website that can help would be perfect, or no if its not possible.</p>

答:
First of all, You need to know the file structure You are implementing.

You can check it for example on wikipedia, for bmp here:
https://en.wikipedia.org/wiki/BMP_file_format

or here: http://www.dragonwins.com/domains/getteched/bmp/bmpfileformat.htm - I prefer using this one

As you see, we have to implement a bit of a header and then we can just create the file.

Lets write some sample code:

```<code>File_begin:
file_header:
        .bfType: db "BM"
        .bfSize: dd File_end - File_begin
        .bfReserved1: dw 0
        .bfReserved2: dw 0
        .bfOffBits: dd PIXEL_DATA_START
image_header:
        .biSize: dd image_header_end-image_header
        .biWidth: dd 3
        .biHeight: dd 3
        .biPlanes: dw 1
        .biBitCount: dw 32
        .biCompression: dd 0
        .biSizeImage: dd 0
        .biXPelsPerMeter: dd 0
        .biYPelsPerMeter: dd 0
        .biClrUsed: dd 0
        .biClrImportant: dd 16
image_header_end:

PIXEL_DATA_START:
dd 0x00000000, 0x00000000, 0x00000000
dd 0x00ffffff, 0x00ffffff, 0x00000000
dd 0x00ffffff, 0x00000000, 0x00ffffff

File_end:
</code>```

This is a really simple BMP file that displays a 3x3 glider symbol.

As you see the BMP file format is really simple to implement- just refer to the documentation I linked to if you need explanation of any of the fields.

One thing to keep in mind is that you should define bytes in the reversed order as things are little endian in PC architecture.

My code compiles with FASM and runs on every platform as it is just an image- no processor jobs at all.

So, to answer your question- look up the file header format and then just implement it. The same technique works with everything you do in assembly, so the file would look exactly the same way in a normal OS source.

After you create or parse such file, you should write every single pixel to the framebuffer using the following formula:

Pixel address = framebuffer address + pixelX * colordepth + pixelY * screenWidth*ColorDepth

for example:

```<code>mov eax, [framebuffer_addr]
add eax, pixelX * cDepth ; simplified code, in normal circumstances you will have to muliply it first
add eax, pixelY * cDepth * scrWidth
mov [eax], 0x00ff0000 ;; this will paint your desired pixel red
</code>```

Process every pixel of the image and write it to the framebuffer and you are done.

Body:
First of all, You need to know the file structure You are implementing.

You can check it for example on wikipedia, for bmp here:
https://en.wikipedia.org/wiki/BMP_file_format

or here: http://www.dragonwins.com/domains/getteched/bmp/bmpfileformat.htm - I prefer using this one

As you see, we have to implement a bit of a header and then we can just create the file.

Lets write some sample code:

File_begin:
file_header:
        .bfType: db "BM"
        .bfSize: dd File_end - File_begin
        .bfReserved1: dw 0
        .bfReserved2: dw 0
        .bfOffBits: dd PIXEL_DATA_START
image_header:
        .biSize: dd image_header_end-image_header
        .biWidth: dd 3
        .biHeight: dd 3
        .biPlanes: dw 1
        .biBitCount: dw 32
        .biCompression: dd 0
        .biSizeImage: dd 0
        .biXPelsPerMeter: dd 0
        .biYPelsPerMeter: dd 0
        .biClrUsed: dd 0
        .biClrImportant: dd 16
image_header_end:

PIXEL_DATA_START:
dd 0x00000000, 0x00000000, 0x00000000
dd 0x00ffffff, 0x00ffffff, 0x00000000
dd 0x00ffffff, 0x00000000, 0x00ffffff

File_end:

This is a really simple BMP file that displays a 3x3 glider symbol.

As you see the BMP file format is really simple to implement- just refer to the documentation I linked to if you need explanation of any of the fields.

One thing to keep in mind is that you should define bytes in the reversed order as things are little endian in PC architecture.

My code compiles with FASM and runs on every platform as it is just an image- no processor jobs at all.

So, to answer your question- look up the file header format and then just implement it. The same technique works with everything you do in assembly, so the file would look exactly the same way in a normal OS source.

After you create or parse such file, you should write every single pixel to the framebuffer using the following formula:

Pixel address = framebuffer address + pixelX * colordepth + pixelY * screenWidth*ColorDepth

for example:

mov eax, [framebuffer_addr]
add eax, pixelX * cDepth ; simplified code, in normal circumstances you will have to muliply it first
add eax, pixelY * cDepth * scrWidth
mov [eax], 0x00ff0000 ;; this will paint your desired pixel red

Process every pixel of the image and write it to the framebuffer and you are done.


问:
How do I remove or rename a Bluemix organization after a name change?
I try to remove my organization executing this command:

1) Change the original organization name from miguel@thingtrack.com to Miguel correctly from the Dashboard.

1) Login in my bluemix account correctly from CLI like this:

bluemix login

2) Try to remove my unique organization called Miguel:

```<code>bluemix iam org-delete Miguel
</code>```

The error result is:

```<code>Suprimiendo la organización Miguel como miguel@thingtrack.com...
FAILED
Error response from server. StatusCode: 500; description: multiple documents found containing guid 7f1f9939-b0bc-4e61-85b9-d7e3744b6c77: [{"_id":"org.Miguel","_rev":"3-9b1bba6c8f8c618ba424c728e55ee247","customer":"ibm","deployment":"yp","name":"Miguel","type":"org","value":{"ibm:yp:eu-gb":{"guid":"6b7219e6-5992-4d43-ac52-083bf0ce8d50","owner":true},"ibm:yp:us-south":{"guid":"7f1f9939-b0bc-4e61-85b9-d7e3744b6c77"}},"created_at":"2016-05-23T13:49:36.660Z","updated_at":"2016-09-09T17:50:02.846Z","migrated":true},{"_id":"org.miguel@thingtrack.com","_rev":"2-cf26e55555fe9730b4a9a9a4525f4bf3","customer":"ibm","deployment":"yp","name":"miguel@thingtrack.com","type":"org","value":{"ibm:yp:us-south":{"guid":"7f1f9939-b0bc-4e61-85b9-d7e3744b6c77","owner":true}},"created_at":"2015-08-28T09:49:49.221Z","updated_at":"2016-08-13T18:06:03.994Z","migrated":true}]
</code>```

Also I noticed that if I try to rename again the organization to other name I obtain the same error.

So in my opinion if you change the organization name one time, you will never remove it or change the name never more.

Is it a bug of bluemix??

Regards

答:
I know I am late to the party, but I hope this helps the future users.
You can rename org using the bluemix cli as @marcel Ribas stated above.

bluemix iam org-rename old_org_name new_org_name

bluemix iam org-delete org_name

Alternatively you can go into your bluemix account and you have and option to change org name under the manange organizations tab. Just click on edit button next to org name and make the changes

Note- You need to have manager level access to the org you are trying to rename. You can check this on your bluemix account under the manage organizations tab

Body:
I try to remove my organization executing this command:

1) Change the original organization name from miguel@thingtrack.com to Miguel correctly from the Dashboard.

1) Login in my bluemix account correctly from CLI like this:

bluemix login

2) Try to remove my unique organization called Miguel:

bluemix iam org-delete Miguel

The error result is:

Suprimiendo la organización Miguel como miguel@thingtrack.com...
FAILED
Error response from server. StatusCode: 500; description: multiple documents found containing guid 7f1f9939-b0bc-4e61-85b9-d7e3744b6c77: [{"_id":"org.Miguel","_rev":"3-9b1bba6c8f8c618ba424c728e55ee247","customer":"ibm","deployment":"yp","name":"Miguel","type":"org","value":{"ibm:yp:eu-gb":{"guid":"6b7219e6-5992-4d43-ac52-083bf0ce8d50","owner":true},"ibm:yp:us-south":{"guid":"7f1f9939-b0bc-4e61-85b9-d7e3744b6c77"}},"created_at":"2016-05-23T13:49:36.660Z","updated_at":"2016-09-09T17:50:02.846Z","migrated":true},{"_id":"org.miguel@thingtrack.com","_rev":"2-cf26e55555fe9730b4a9a9a4525f4bf3","customer":"ibm","deployment":"yp","name":"miguel@thingtrack.com","type":"org","value":{"ibm:yp:us-south":{"guid":"7f1f9939-b0bc-4e61-85b9-d7e3744b6c77","owner":true}},"created_at":"2015-08-28T09:49:49.221Z","updated_at":"2016-08-13T18:06:03.994Z","migrated":true}]

Also I noticed that if I try to rename again the organization to other name I obtain the same error.

So in my opinion if you change the organization name one time, you will never remove it or change the name never more.

Is it a bug of bluemix??

Regards


问:
How can I tell which project I'm using in Sublime Text?
I often have multiple copies of the same Git repository on my machine. I usually have multiple Sublime Text windows open, each with the opened project for one of the Git repo copies.

Is there any setting that will show the project file's path on the status or title bar, or some other way of easily distinguishing otherwise similar projects from each other? As it is, I have no easy way of distinguishing which Sublime Text window is using which project file.

答:
The title bar of Sublime will show you the file name portion of the project currently associated with a window by default; it's the text to the right of the name of the currently selected file inside round brackets. For example, here I have the OverrideAudit project currently open:

There's no way (currently) to display other information in the caption bar, but using some plugin code you can display text in the status bar instead.

[Edit] There is an open feature request on the issue tracker to add the ability to configure the title bar which you may want to weigh in on. [/Edit]

Here is an example of a plugin that replicates putting the project name from the window caption into the status bar. If desired you could modify the code in show_project that isolates only the project name to e.g. include the path if desired.

To use this, you can select Tools > Developer > New Plugin... from the menu and replace the default stub with this code, modifying as needed.

This code is also available on GitHub.

import sublime
import sublime_plugin
import os

# Related Reading:
#     https://forum.sublimetext.com/t/displaying-project-name-on-the-rite-side-of-the-status-bar/24721

# This just displays the filename portion of the current project file in the
# status bar, which is the same text that appears by default in the window
# caption.

def plugin_loaded ():
    """
    Ensure that all views in all windows show the associated project at startup.
    """
    # Show project in all views of all windows
    for window in sublime.windows ():
        for view in window.views ():
            show_project (view)

def show_project(view):
    """
    If a project file is in use, add the name of it to the start of the status
    bar.
    """
    if view.window() is None:
        return

    project_file = view.window ().project_file_name ()
    if project_file is not None:
        project_name = os.path.splitext (os.path.basename (project_file))[0]
        view.set_status ("00ProjectName", "[" + project_name + "]")

class ProjectInStatusbar(sublime_plugin.EventListener):
    """
    Display the name of the current project in the status bar.
    """
    def on_new(self, view):
        show_project (view)

    def on_load(self, view):
        show_project (view)

    def on_clone(self, view):
        show_project (view)
```


问:
Not getting Hidden field value on submitting form in Angular2
I am initializing a hidden field inside a form </p>

```<code><input type="text" name="test" value="{{interest.id}}"  formControlName="test" />
</code>```

<p>On submitting the form I receive empty value of the field value which should be a integer value .  </p>

答:
try this one :

<input type="text" name="test" [value]="interest.id"  formControlName="test" />

hope it helps :)

Body:
I am initializing a hidden field inside a form

<input type="text" name="test" value="{{interest.id}}"  formControlName="test" />

On submitting the form I receive empty value of the field value which should be a integer value .


问:
Relatively positioned content not stacking vertically?
I am trying to stack these elements so that they lie on top of one another, but they end up squishing horizontally instead. What am I doing wrong?

HTML:

    .content-wrapper {
      position: absolute;
      top: 0;
      left: 0;
      height:100%;
      width:100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .content-box {
      background-color: #f2f2f2;
      padding: 5vh 5vw;
      font-family: "Roboto";
      color: #676767;
      text-align: center;
      max-width: 60vw;
      position: relative;
      z-index:10;
      margin: 1vh
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content-wrapper">
        <div class="content-box">
            <span class="title"> Stats </span>
            <br>
            <div class="sep"></div>
            <p> Lorem ipsum 1 </p>
        </div>

        <div class="content-box">
            <span class="title"> Stats </span>
            <br>
            <div class="sep"></div>
            <p> Lorem ipsum 2 </p>
        </div>
    </div></code>```

答:
Use flex boxes instead. flex direction

.box-list {
  padding: 10px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.box {
  flex: 0 0 auto;
  width: 50px;
  height: 50px;
  background-color: #ccc;

  margin-bottom: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="box-list">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</section></code>```

Body:
I am trying to stack these elements so that they lie on top of one another, but they end up squishing horizontally instead. What am I doing wrong?

HTML:

    .content-wrapper {
      position: absolute;
      top: 0;
      left: 0;
      height:100%;
      width:100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .content-box {
      background-color: #f2f2f2;
      padding: 5vh 5vw;
      font-family: "Roboto";
      color: #676767;
      text-align: center;
      max-width: 60vw;
      position: relative;
      z-index:10;
      margin: 1vh
    }

             Stats

 Lorem ipsum 1

             Stats

 Lorem ipsum 2

Body:
Use flex boxes instead. flex direction

.box-list {
  padding: 10px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.box {
  flex: 0 0 auto;
  width: 50px;
  height: 50px;
  background-color: #ccc;

  margin-bottom: 10px;
}

<section class="box-list">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</section>


问:
HighCharts error 16
I am loading high charts through an ajax call which include parameters for creating the chart. So when I select values from a dropdown filter, the chart has to be different. Now I am using a load chart function, which will work on the onchange event of dropdown and it is like this :

```<code>function load_chart(stat, type, matrix){
    chart_url = '<?=site_url('/admin/charts/index');?>';
    $("#chart_wrap").load(chart_url);
}
</code>```

I need to load charts to the same #chart_wrap div. But then it is giving me this error :

```<code>uncaught exception: Highcharts error #16: www.highcharts.com/errors/16
</code>```

and this is due to the fact that I have multiple charts in same page. So how can I fix this

答: I was also receiving this error.  After scouring the internet, I decided to try changing the call contained in my controller from View("SomeView", query) to PartialView("_someView", query).  I renamed the actual view cshtml file from SomeView.cshtml to _someView.cshtml to follow recommended naming conventions, and my error went away.  That helped me, so I thought I would jot it down in case it helps somebody else out there.</p>

Title: HighCharts error 16

Body:
I am loading high charts through an ajax call which include parameters for creating the chart. So when I select values from a dropdown filter, the chart has to be different. Now I am using a load chart function, which will work on the onchange event of dropdown and it is like this :

function load_chart(stat, type, matrix){
    chart_url = '<?=site_url('/admin/charts/index');?>';
    $("#chart_wrap").load(chart_url);
}

I need to load charts to the same #chart_wrap div. But then it is giving me this error :

uncaught exception: Highcharts error #16: www.highcharts.com/errors/16

and this is due to the fact that I have multiple charts in same page. So how can I fix this


问:
Why can't I inherit static classes?
I have several classes that do not really need any state. From the organizational point of view, I would like to put them into hierarchy.

But it seems I can't declare inheritance for static classes.

Something like that:

```<code>public static class Base
{
}

public static class Inherited : Base
{
}
</code>```

will not work.

Why have the designers of the language closed that possibility?

答:
A workaround you can do is not use static classes but hide the constructor so the classes static members are the only thing accessible outside the class. The result is an inheritable "static" class essentially:

```<code>public class TestClass<T>
{
    protected TestClass()
    { }

    public static T Add(T x, T y)
    {
        return (dynamic)x + (dynamic)y;
    }
}

public class TestClass : TestClass<double>
{
    // Inherited classes will also need to have protected constructors to prevent people from creating instances of them.
    protected TestClass()
    { }
}

TestClass.Add(3.0, 4.0)
TestClass<int>.Add(3, 4)

// Creating a class instance is not allowed because the constructors are inaccessible.
// new TestClass();
// new TestClass<int>();
</code>```

Unfortunately because of the "by-design" language limitation we can't do:

```<code>public static class TestClass<T>
{
    public static T Add(T x, T y)
    {
        return (dynamic)x + (dynamic)y;
    }
}

public static class TestClass : TestClass<double>
{
}
</code>```

Title: Why can't I inherit static classes?

Body:
I have several classes that do not really need any state. From the organizational point of view, I would like to put them into hierarchy.

But it seems I can't declare inheritance for static classes.

Something like that:

public static class Base
{
}

public static class Inherited : Base
{
}

will not work.

Why have the designers of the language closed that possibility?

Body:
A workaround you can do is not use static classes but hide the constructor so the classes static members are the only thing accessible outside the class. The result is an inheritable "static" class essentially:

public class TestClass<T>
{
    protected TestClass()
    { }

    public static T Add(T x, T y)
    {
        return (dynamic)x + (dynamic)y;
    }
}

public class TestClass : TestClass<double>
{
    // Inherited classes will also need to have protected constructors to prevent people from creating instances of them.
    protected TestClass()
    { }
}

TestClass.Add(3.0, 4.0)
TestClass<int>.Add(3, 4)

// Creating a class instance is not allowed because the constructors are inaccessible.
// new TestClass();
// new TestClass<int>();

Unfortunately because of the "by-design" language limitation we can't do:

public static class TestClass<T>
{
    public static T Add(T x, T y)
    {
        return (dynamic)x + (dynamic)y;
    }
}

public static class TestClass : TestClass<double>
{
}


答:
Add flex-direction: column; to the wrapper:

.content-wrapper {
      position: absolute;
      top: 0;
      left: 0;
      height:100%;
      width:100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }
    .content-box {
      background-color: #f2f2f2;
      padding: 5vh 5vw;
      font-family: "Roboto";
      color: #676767;
      text-align: center;
      max-width: 60vw;
      position: relative;
      z-index:10;
      margin: 1vh
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content-wrapper">
        <div class="content-box">
            <span class="title"> Stats </span>
            <br>
            <div class="sep"></div>
            <p> Lorem ipsum 1 </p>
        </div>

        <div class="content-box">
            <span class="title"> Stats </span>
            <br>
            <div class="sep"></div>
            <p> Lorem ipsum 2 </p>
        </div>
    </div></code>```

Title: Relatively positioned content not stacking vertically?

Body:
Add flex-direction: column; to the wrapper:

.content-wrapper {
      position: absolute;
      top: 0;
      left: 0;
      height:100%;
      width:100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }
    .content-box {
      background-color: #f2f2f2;
      padding: 5vh 5vw;
      font-family: "Roboto";
      color: #676767;
      text-align: center;
      max-width: 60vw;
      position: relative;
      z-index:10;
      margin: 1vh
    }

<div class="content-wrapper">
        <div class="content-box">
            <span class="title"> Stats </span>
            <br>
            <div class="sep"></div>
            <p> Lorem ipsum 1 </p>
        </div>

        <div class="content-box">
            <span class="title"> Stats </span>
            <br>
            <div class="sep"></div>
            <p> Lorem ipsum 2 </p>
        </div>
    </div>