问:
Importing a local HTML file/code into a WebBrowser
I'm trying to get a local HTML file to display within a WebBrowser in a VB.NET program. I'm using the code below, however it doesn't seem to work, and I can't figure out why:

    'first method
    WebBrowser1.Navigate(@".\index.html");

    'second method
    HTML = "normal"
    WebBrowser1.Document.Body.InnerHtml = HTML
```

<p>The first method produces the error "" in the Debug console when I go to run it. If I try it with out the <code>@</code>, I get an empty white page. If I change the address, however ,so I know its a broken URL, I get a 404 message, which makes it seem like it's finding the file but not rendering it?</p>

<p>The second method does the same as the first except no error is produced, its like its finding the text but doing nothing.</p>

<p>In both examples I have tried the following HTML and plain text variations:</p>

```boldnormal
```

<p>and</p>

```normal
```

Why isn't this simple code working?

答:
Another option I found that works, don't have to create a file.

WebBrowser1.DocumentText = strHTML
        WebBrowser1.Update()

Body:
I'm trying to get a local HTML file to display within a WebBrowser in a VB.NET program. I'm using the code below, however it doesn't seem to work, and I can't figure out why:

    'first method
    WebBrowser1.Navigate(@".\index.html");

    'second method
    HTML = "normal"
    WebBrowser1.Document.Body.InnerHtml = HTML

The first method produces the error "" in the Debug console when I go to run it. If I try it with out the @, I get an empty white page. If I change the address, however ,so I know its a broken URL, I get a 404 message, which makes it seem like it's finding the file but not rendering it?

The second method does the same as the first except no error is produced, its like its finding the text but doing nothing.

In both examples I have tried the following HTML and plain text variations:

boldnormal

and

normal

Why isn't this simple code working?


来源: stackexchange

问:
html & css - using different image between each nav menu item as separator
I've yet to see a known-good way of using a different image between different nav menu elements, though I know there is a way to use one image as the consistent separator.

I have seven nav elements:

```<code>#menu-item-26{
}
//blue square here
#menu-item-25{
}
//yellow square here
#menu-item-24{
}
//red square here
#menu-item-23{
}
//pink square here
#menu-item-22{
}
//green square here
#menu-item-21{
}
//purple square here
#menu-item-20{
}
</code>```

And I've created 6 images in photoshop, essentially just 10px by 10px squares, each a different color. I want to use a different one between each set but I don't know if it would need to be used as a background image with each item and padding or if maybe there's another responsive-friendly way.

答:
Maybe something like this, using :before selector and the content:""; style.

.fancy-separator li {
  list-style:none;
  float:left;
  margin-left:10px;
  padding-left:10px;
}
.fancy-separator > li:first-child {
  content:none;
  margin-left: 0;
}
.fancy-separator > li:before {
  content:"";
  width:10px;
  height:10px;
  display: inline-block;
  vertical-align: middle;
  position: relative;
  left: -10px;

}
.fancy-separator > li:nth-child(2)::before {
  background: blue;
}
.fancy-separator > li:nth-child(3)::before {
  background: yellow;
}
.fancy-separator > li:nth-child(4)::before {
  background: red;
}
.fancy-separator a {
 text-decoration:none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="fancy-separator">
  <li>home</li>
  <li>about</li>
  <li>news</li>
  <li>contact</li>
<ul></code>```

ContentLicense: CC BY-SA 3.0

Body:
I've yet to see a known-good way of using a different image between different nav menu elements, though I know there is a way to use one image as the consistent separator.

I have seven nav elements:

#menu-item-26{
}
//blue square here
#menu-item-25{
}
//yellow square here
#menu-item-24{
}
//red square here
#menu-item-23{
}
//pink square here
#menu-item-22{
}
//green square here
#menu-item-21{
}
//purple square here
#menu-item-20{
}

And I've created 6 images in photoshop, essentially just 10px by 10px squares, each a different color. I want to use a different one between each set but I don't know if it would need to be used as a background image with each item and padding or if maybe there's another responsive-friendly way.

Body:
Maybe something like this, using :before selector and the content:""; style.

.fancy-separator li {
  list-style:none;
  float:left;
  margin-left:10px;
  padding-left:10px;
}
.fancy-separator > li:first-child {
  content:none;
  margin-left: 0;
}
.fancy-separator > li:before {
  content:"";
  width:10px;
  height:10px;
  display: inline-block;
  vertical-align: middle;
  position: relative;
  left: -10px;

}
.fancy-separator > li:nth-child(2)::before {
  background: blue;
}
.fancy-separator > li:nth-child(3)::before {
  background: yellow;
}
.fancy-separator > li:nth-child(4)::before {
  background: red;
}
.fancy-separator a {
 text-decoration:none;
}

<ul class="fancy-separator">
  <li><a href="#">home</a></li>
  <li><a href="#">about</a></li>
  <li><a href="#">news</a></li>
  <li><a href="#">contact</a></li>
<ul>


问:
Error while restoring from a checkpoint in tensorflow
```<code>def test_neural_network():
    prediction = neural_network_model(x)
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        for epoch in range(hm_epochs):
            saver.restore(sess, './model.ckpt')
        # more code here
</code>```

This is a sample of the code that I am working on. I have saved the model.ckpt in the same directory as my file.

However when I run the code, I get an error saying:

```<code>InvalidArgumentError (see above for traceback): Expected to restore a tensor of type float, got a tensor of type int32 instead: tensor_name = Variable
 [[Node: save/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_save/Const_0, save/RestoreV2/tensor_names, save/RestoreV2/shape_and_slices)]]
</code>```

答: It looks like the model your defined is somehow different to the one you saved. Try using saver = tf.train.import_meta_graph('your_model_name.meta') instead of build the graph mannually in neural_network_model().

Body:
def test_neural_network():
    prediction = neural_network_model(x)
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        for epoch in range(hm_epochs):
            saver.restore(sess, './model.ckpt')
        # more code here

This is a sample of the code that I am working on. I have saved the model.ckpt in the same directory as my file.

However when I run the code, I get an error saying:

InvalidArgumentError (see above for traceback): Expected to restore a tensor of type float, got a tensor of type int32 instead: tensor_name = Variable
 [[Node: save/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_save/Const_0, save/RestoreV2/tensor_names, save/RestoreV2/shape_and_slices)]]


问:
Creating an Array to store Table Cell Button Values at Cell Index
I am currently working on a program where I have a TableView with a Segmented Control in each row. I have attached a tag to each segmented control that corresponds to the row the segmented control is in (i.e. segmented control 1 corresponds to row 1, etc). Additionally, the segmented control has its own index (option 0 corresponds to an index of 0 and option 1 corresponds to an index of 1)

I would like to have an array that stores the value of the segmented control index in a location that corresponds to segmented control's tag. i.e. if the first row's segmented control index is 1, the second row's segmented control index is 0, and the third row's segmented control index is 1, the array should output:
[1,0,1]

The best idea I have is to create an array, specify the array's index as the segmented control's tag, and then specify the value at that index to be the value of the segmented control's index (sorry I know its confusing).

I'm sure this is a programming problem someone has had before, however I can't find any information on it. I am programming in swift, but since this is more of a logical problem than a programming one I am willing to accept a solution in any other language.

Thanks,
Nick

P.S.
Here is a picture of the app so far and the code I am using for your reference.

https://i.stack.imgur.com/ezMUJ.png

import UIKit

class MyTableViewController: UITableViewController {

```<code>override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 150
}

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

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)

    let nameLabel: UILabel = {
        let label = UILabel()
        label.text = "Sample Item"
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    let actionButton = YSSegmentedControl(
        frame: CGRect.zero,
        titles: [
            "Yes",
            "No"
        ])

actionButton.delegate = self
cell.addSubview(nameLabel)
cell.addSubview(actionButton)
actionButton.translatesAutoresizingMaskIntoConstraints = false

cell.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-16-[v0]-160-[v1]-16-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel, "v1": actionButton]));
cell.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))
cell.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-60-[v0]-60-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": actionButton]))

actionButton.tag = indexPath.row

    cell.backgroundColor = .green
    return cell

}

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellId")

    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

extension MyTableViewController: YSSegmentedControlDelegate {
func segmentedControl(_ segmentedControl: YSSegmentedControl, willPressItemAt    index: Int) {
    print("\(segmentedControl.tag)" + "\(index)")

}

func segmentedControl(_ segmentedControl: YSSegmentedControl, didPressItemAt index: Int) {

}
</code>```

}

答:
Why don't you use a dictionary instead of an array? This way ou can store and easily look up the segment control's index from it's tag or vice versa:

```<code>// Storing index and corresponding tag
var indexToTag = [Int:Int]()
indexToTag[index] = tag

// Looking up tag
let tag = indexToTag[index]
</code>```

You can also do the opposite:

```<code>// Storing tag and corresponding index
var tagToIndex = [Int:Int]()
tagToIndex[tag] = index

// Looking up tag
let index = tagToIndex[tag]
</code>```

I'm not sure exactly what you are trying to achieve but you could even store an array of you UISegmentedControls so you could reference them by indexRow.path and get whatever info you want:

```<code>var mySegments = [UISegmentedControls]()
</code>```

You can even use them in a dictionary

```<code>var tagToSegment = [Int:UISegmentedControls]()
</code>```

Body:
I am currently working on a program where I have a TableView with a Segmented Control in each row. I have attached a tag to each segmented control that corresponds to the row the segmented control is in (i.e. segmented control 1 corresponds to row 1, etc). Additionally, the segmented control has its own index (option 0 corresponds to an index of 0 and option 1 corresponds to an index of 1)

I would like to have an array that stores the value of the segmented control index in a location that corresponds to segmented control's tag. i.e. if the first row's segmented control index is 1, the second row's segmented control index is 0, and the third row's segmented control index is 1, the array should output:
[1,0,1]

The best idea I have is to create an array, specify the array's index as the segmented control's tag, and then specify the value at that index to be the value of the segmented control's index (sorry I know its confusing).

I'm sure this is a programming problem someone has had before, however I can't find any information on it. I am programming in swift, but since this is more of a logical problem than a programming one I am willing to accept a solution in any other language.

Thanks,
Nick

P.S.
Here is a picture of the app so far and the code I am using for your reference.

https://i.stack.imgur.com/ezMUJ.png

import UIKit

class MyTableViewController: UITableViewController {

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

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

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)

    let nameLabel: UILabel = {
        let label = UILabel()
        label.text = "Sample Item"
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    let actionButton = YSSegmentedControl(
        frame: CGRect.zero,
        titles: [
            "Yes",
            "No"
        ])

actionButton.delegate = self
cell.addSubview(nameLabel)
cell.addSubview(actionButton)
actionButton.translatesAutoresizingMaskIntoConstraints = false

cell.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-16-[v0]-160-[v1]-16-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel, "v1": actionButton]));
cell.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))
cell.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-60-[v0]-60-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": actionButton]))

actionButton.tag = indexPath.row

    cell.backgroundColor = .green
    return cell

}

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellId")

    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

extension MyTableViewController: YSSegmentedControlDelegate {
func segmentedControl(_ segmentedControl: YSSegmentedControl, willPressItemAt    index: Int) {
    print("\(segmentedControl.tag)" + "\(index)")

}

func segmentedControl(_ segmentedControl: YSSegmentedControl, didPressItemAt index: Int) {

}

}

Body:
Why don't you use a dictionary instead of an array? This way ou can store and easily look up the segment control's index from it's tag or vice versa:

// Storing index and corresponding tag
var indexToTag = [Int:Int]()
indexToTag[index] = tag

// Looking up tag
let tag = indexToTag[index]

You can also do the opposite:

// Storing tag and corresponding index
var tagToIndex = [Int:Int]()
tagToIndex[tag] = index

// Looking up tag
let index = tagToIndex[tag]

I'm not sure exactly what you are trying to achieve but you could even store an array of you UISegmentedControls so you could reference them by indexRow.path and get whatever info you want:

var mySegments = [UISegmentedControls]()

You can even use them in a dictionary

var tagToSegment = [Int:UISegmentedControls]()


问:
Unable to save ManyToMany relationship in Hibernate
This is really puzzling me.

I have the following classes:

Ingredient.java

```<code>@Entity
@Table(name = "INGREDIENTS", uniqueConstraints =
{@UniqueConstraint(columnNames = "NAME")})
public class Ingredient implements Serializable{

@Id
@GeneratedValue
@Column(name = "ingredient_id")
private Long id;

@Column(nullable = false, name = "name")
private String name;

@Column(nullable = false, name = "name")
private Long calories;

public Ingredient() {
}

public Ingredient(String name, Long calories) {
    this.name = name;
    this.calories = calories;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Long getCalories() {
    return calories;
}

public void setCalories(Long calories) {
    this.calories = calories;
}

public Long getId(){
    return this.id;
}

public void setId(Long id) {
    this.id = id;
}
</code>```

}

Meal.java

```<code>@Entity
@Table(name = "MEALS")
public class Meal implements Serializable {

@ManyToOne
private User user;

@Id
@GeneratedValue
@Column(name = "meal_id")
private Long id;

@ElementCollection(targetClass = Ingredient.class)
private Set<Ingredient> ingredients = new HashSet<>(0);

//More fields and constructors

@ManyToMany(targetEntity = Ingredient.class, cascade = CascadeType.ALL)
@JoinTable(name = "ingredient_meal", joinColumns = {@JoinColumn(name = "meal_id")}, inverseJoinColumns = {@JoinColumn(name = "ingredient_id")})
public List<Ingredient> getIngredients() {
    return ingredients;
}

public void setIngredients(List<Ingredient> ingredients) {
    this.ingredients = ingredients;
}

public Long getId(){
    return this.id;
}

public void setId(Long id) {
    this.id = id;
}
</code>```

This is the code where I persist the entities:

```<code>SessionFactory sessionFactory =
entityManagerFactory.unwrap(SessionFactory.class);

Session session = sessionFactory.openSession();
session.beginTransaction();

 /***/
Meal coolMeal = new Meal(user, new Date(115, 0, 8), new Time(19, 0, 0), "8 -
Moules Frites", 1000L);
coolMeal.getIngredients().add(new Ingredient("Fish2", 100L));
        session.persist(coolMeal);
    try{
        session.getTransaction().commit();
    }catch(Throwable e){
        e.printStackTrace();
        throw e;
    }
    session.close();
</code>```

But I keep getting this exception:

```<code>org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: calories.tracker.app.model.Ingredient
at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:294)
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:537)
at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:165)
at org.hibernate.persister.collection.AbstractCollectionPersister.writeElement(AbstractCollectionPersister.java:899)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1308)
at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:67)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at
</code>```

However if I persist the objects in this way:

```<code>    Ingredient i1 = new Ingredient("Potatoes2", 100L);
    session.persist(i1);
    Meal coolMeal = new Meal(user, new Date(115, 0, 8), new Time(19, 0, 0),
    "8 -  Moules Frites", 1000L);
    coolMeal.getIngredients().add(i1);
</code>```

It works fine, why? Everything is exactly the same as here.

答: you have to use @OneToMany(mappedBy = "Ord", cascade = CascadeType.ALL, fetch = FetchType.LAZY), replace Ord by your entity name.

Body:
This is really puzzling me.

I have the following classes:

Ingredient.java

@Entity
@Table(name = "INGREDIENTS", uniqueConstraints =
{@UniqueConstraint(columnNames = "NAME")})
public class Ingredient implements Serializable{

@Id
@GeneratedValue
@Column(name = "ingredient_id")
private Long id;

@Column(nullable = false, name = "name")
private String name;

@Column(nullable = false, name = "name")
private Long calories;

public Ingredient() {
}

public Ingredient(String name, Long calories) {
    this.name = name;
    this.calories = calories;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Long getCalories() {
    return calories;
}

public void setCalories(Long calories) {
    this.calories = calories;
}

public Long getId(){
    return this.id;
}

public void setId(Long id) {
    this.id = id;
}

}

Meal.java

@Entity
@Table(name = "MEALS")
public class Meal implements Serializable {

@ManyToOne
private User user;

@Id
@GeneratedValue
@Column(name = "meal_id")
private Long id;

@ElementCollection(targetClass = Ingredient.class)
private Set<Ingredient> ingredients = new HashSet<>(0);

//More fields and constructors

@ManyToMany(targetEntity = Ingredient.class, cascade = CascadeType.ALL)
@JoinTable(name = "ingredient_meal", joinColumns = {@JoinColumn(name = "meal_id")}, inverseJoinColumns = {@JoinColumn(name = "ingredient_id")})
public List<Ingredient> getIngredients() {
    return ingredients;
}

public void setIngredients(List<Ingredient> ingredients) {
    this.ingredients = ingredients;
}

public Long getId(){
    return this.id;
}

public void setId(Long id) {
    this.id = id;
}

This is the code where I persist the entities:

SessionFactory sessionFactory =
entityManagerFactory.unwrap(SessionFactory.class);

Session session = sessionFactory.openSession();
session.beginTransaction();

 /***/
Meal coolMeal = new Meal(user, new Date(115, 0, 8), new Time(19, 0, 0), "8 -
Moules Frites", 1000L);
coolMeal.getIngredients().add(new Ingredient("Fish2", 100L));
        session.persist(coolMeal);
    try{
        session.getTransaction().commit();
    }catch(Throwable e){
        e.printStackTrace();
        throw e;
    }
    session.close();

But I keep getting this exception:

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: calories.tracker.app.model.Ingredient
at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:294)
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:537)
at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:165)
at org.hibernate.persister.collection.AbstractCollectionPersister.writeElement(AbstractCollectionPersister.java:899)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1308)
at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:67)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at

However if I persist the objects in this way:

    Ingredient i1 = new Ingredient("Potatoes2", 100L);
    session.persist(i1);
    Meal coolMeal = new Meal(user, new Date(115, 0, 8), new Time(19, 0, 0),
    "8 -  Moules Frites", 1000L);
    coolMeal.getIngredients().add(i1);

It works fine, why? Everything is exactly the same as here.


问:
multiple query in one query where
I wrote this query for finding the highest score from 2 tables (Selected Item: StudentId and Score), and now I want to select some other data: (StudentName, StudentImage, ...) from other tables that must filter items using StudentId

my query returns:

```<code>StudentId       HighScoreUser
-1              250
-2              100
-3               90
-4               80
-5               40
</code>```

For showing data in a grid, I need the Student Name, ... so I must use StudentId to find the info for the specific user:

```<code>CREATE PROCEDURE SelectTopYear
AS
    SELECT TOP 5 StudentId, ISNULL(SUM(Score),0) As HighScoreUser
FROM (SELECT StudentId, Score FROM tbl_ActPoint
      UNION ALL
      SELECT StudentId, Score FROM tbl_EvaPoint
     ) as T
GROUP BY  StudentId ORDER BY HighScoreUser DESC
RETURN 0
</code>```

答:
You can use a CTE (or subquery) and JOIN:

```<code>WITH s as (
      SELECT TOP 5 StudentId, ISNULL(SUM(Score),0) As HighScoreUser
      FROM (SELECT StudentId, Score FROM tbl_ActPoint
            UNION ALL
            SELECT StudentId, Score FROM tbl_EvaPoint
           ) s
      GROUP BY  StudentId
      ORDER BY HighScoreUser DESC
     )
SELECT . . .
FROM s JOIN
     othertable ot
     ON s.StudentId = ot.StudentId;
</code>```

Fill in the appropriate column names and table names.

Title: multiple query in one query where

Body:
I wrote this query for finding the highest score from 2 tables (Selected Item: StudentId and Score), and now I want to select some other data: (StudentName, StudentImage, ...) from other tables that must filter items using StudentId

my query returns:

StudentId       HighScoreUser
-1              250
-2              100
-3               90
-4               80
-5               40

For showing data in a grid, I need the Student Name, ... so I must use StudentId to find the info for the specific user:

CREATE PROCEDURE SelectTopYear
AS
    SELECT TOP 5 StudentId, ISNULL(SUM(Score),0) As HighScoreUser
FROM (SELECT StudentId, Score FROM tbl_ActPoint
      UNION ALL
      SELECT StudentId, Score FROM tbl_EvaPoint
     ) as T
GROUP BY  StudentId ORDER BY HighScoreUser DESC
RETURN 0

Body:
You can use a CTE (or subquery) and JOIN:

WITH s as (
      SELECT TOP 5 StudentId, ISNULL(SUM(Score),0) As HighScoreUser
      FROM (SELECT StudentId, Score FROM tbl_ActPoint
            UNION ALL
            SELECT StudentId, Score FROM tbl_EvaPoint
           ) s
      GROUP BY  StudentId
      ORDER BY HighScoreUser DESC
     )
SELECT . . .
FROM s JOIN
     othertable ot
     ON s.StudentId = ot.StudentId;

Fill in the appropriate column names and table names.


问:
cython - how to iterate over c++ list
I want to initiate a cpp list in cython, assign values to it and then iterate over the list to obtain its values. A generic code could look like this:

```<code>from libcpp.list cimport list as cpplist
from cpython cimport array
import array

cdef int[:] c_volumecheck(int n, int comb):

    cdef:
        array.array match = array.array('i', [0]*(n*comb))
        int[:] match_c = match
        cpplist[int] arr

    asign(match_c, comb, n, arr)

    return match_c

cdef void asign(int[:] match, int row, int col, cpplist[int] arr):

    cdef int j, i

    for j in range(row):
        for i in range(col):
            arr.push_back(1)

    for j in range(row):
        for i in range(col):
            match[j*col + i] = arr[j*col +i]
</code>```

However, when I compile this I get the error:

Indexing list[int] not supported for index type int

Given the way they iterate over cpp vectors here I thought that would be the way to go.

答: The int in python is not bounded to the system-bus-size, lists in C++ are using another int as indexing, an int with maximum of 32/64 bits capacity. ctypes.c_int should work.

ContentLicense: CC BY-SA 4.0

Title: cython - how to iterate over c++ list

Body:
I want to initiate a cpp list in cython, assign values to it and then iterate over the list to obtain its values. A generic code could look like this:

from libcpp.list cimport list as cpplist
from cpython cimport array
import array

cdef int[:] c_volumecheck(int n, int comb):

    cdef:
        array.array match = array.array('i', [0]*(n*comb))
        int[:] match_c = match
        cpplist[int] arr

    asign(match_c, comb, n, arr)

    return match_c

cdef void asign(int[:] match, int row, int col, cpplist[int] arr):

    cdef int j, i

    for j in range(row):
        for i in range(col):
            arr.push_back(1)

    for j in range(row):
        for i in range(col):
            match[j*col + i] = arr[j*col +i]

However, when I compile this I get the error:

Indexing list[int] not supported for index type int

Given the way they iterate over cpp vectors here I thought that would be the way to go.


问:
How to clean up left over $watches
We interop our angularJS web components with a jqxGrid. When the user edits in a cell, we create a custom typeahead editor (written in angular). When the editor is destroyed, I noticed that my $watches array doesn't return back to the previous value.

I am creating a new isolateScope for my directive, which I then compile and then append to the DOM element that JQX passes to me when the editor is needed:

var scope = $rootScope.$new(true);
 var customEditor = $compile(directive)(scope);

What do I have to do in order to clean up these $watches?

答:
Here is the way to clean up watchers effectively.
Should angular $watch be removed when scope destroyed?
Hope this helps.</p>

Title: How to clean up left over $watches


问:
Sequence contains no elements even though I add OrDefault
I am getting an error for the life of me I can not resolve.
The error I get is as follows:

[InvalidOperationException]: Sequence contains no elements    at
  NHibernate.Linq.DefaultQueryProvider.ExecuteQuery(NhLinqExpression
  nhLinqExpression, IQuery query, NhLinqExpression nhQuery)    at
  NHibernate.Linq.DefaultQueryProvider.Execute(Expression expression)

  at NHibernate.Linq.DefaultQueryProvider.Execute[TResult](Expression
  expression)    at System.Linq.Queryable.First[TSource](IQueryable1
  source)    at Nichols.Web.Controllers.LoadController.RttInUse(String
  rttNumber) in
  c:\projects\NicholsFarms_demo_newCropYear\Nichols\src\Nichols.Web\Controllers\LoadController.cs:line
  71    at lambda_method(Closure , ControllerBase , Object[] )    at
  System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext
  controllerContext, IDictionary2 parameters)    at
  System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext
  controllerContext, ActionDescriptor actionDescriptor, IDictionary2
  parameters)    at
  System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult
  asyncResult, ActionInvocation innerInvokeState)    at
  System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult
  asyncResult)    at
  System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3d()
  at
  System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.b__3f()
  at
  System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass33.b__32(IAsyncResult asyncResult)    at
  System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<>c__DisplayClass2b.b__1c()
  at
  System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.b__1e(IAsyncResult
  asyncResult)    at
  System.Web.Mvc.Controller.b__1d(IAsyncResult
  asyncResult, ExecuteCoreState innerState)    at
  System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult
  asyncResult)    at
  System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)

  at
  System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult
  asyncResult)    at
  System.Web.Mvc.MvcHandler.b__5(IAsyncResult
  asyncResult, ProcessRequestState innerState)    at
  System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult
  asyncResult)    at
  System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
  at System.Web.HttpApplication.ExecuteStep(IExecutionStep step,
  Boolean& completedSynchronously)

and the code I am TRYING to use is:

```<code>public ActionResult RttInUse(string rttNumber)
{
    int validNumber;
    int recommendRttNumber = 0;
    var cropYear = _session.Query<CropYear>().SingleOrDefault(x => x.IsCurrent);

    if (cropYear.RttRangeHaveBeenConfiguredForNewCropYear)
    {
        recommendRttNumber = _session.Query<Load>()
            .Where(x =>
                x.CropYear == cropYear &&
                !x.RttNumber.Contains("VOID") &&
                x.RttNumber.Length < 9)
            .OrderByDescending(x => x.Id)
            .Select(x => x.RttNumber)
            .FirstOrDefault(x => int.Parse(x) >= cropYear.RttNumberRangeStart &&
                                 int.Parse(x) <= cropYear.RttNumberRangeEnd).AsInt() + 1;
    }

    if (rttNumber == null || !int.TryParse(rttNumber, out validNumber))
    {
        return AsJson(
            "Rtt number invalid, numeric values only. Next Rtt Number should be " +
            recommendRttNumber);
    }

    var loadExists = _session.Query<Load>()
        .Any(x =>
            x.RttNumber.ToLower() == rttNumber.ToLower() &&
            x.CropYear == cropYear);

    if (loadExists)
    {
        return AsJson("Rtt Number already in use. Next Rtt Number should be " +
                      recommendRttNumber);
    }

    return AsJson(true);
}
</code>```

Basically while operators enter a string such as 150001 on the form, the value they enter is compared against an acceptable range in the database.

Crop year has entries such that the year 2015 has an acceptable range of 150001 to 159999 to choose from which is RttNumberRangeStart to RttNumberRangeEnd; if it is in use, they should get recommended the current used rttnumber + 1.

答:
Probably the sequence below contains no elements:

```<code>.FirstOrDefault(x => int.Parse(x) >= cropYear.RttNumberRangeStart &&
                     int.Parse(x) <= cropYear.RttNumberRangeEnd)
</code>```

so it cannot do the following on a null (default) element

```<code>.AsInt() + 1;
</code>```

Assuming RttNumber is a string and AsInt() an extension method to convert an string to int, change it to return 0 on a null string.

Body:
I am getting an error for the life of me I can not resolve.
The error I get is as follows:

[InvalidOperationException]: Sequence contains no elements    at
  NHibernate.Linq.DefaultQueryProvider.ExecuteQuery(NhLinqExpression
  nhLinqExpression, IQuery query, NhLinqExpression nhQuery)    at
  NHibernate.Linq.DefaultQueryProvider.Execute(Expression expression)

  at NHibernate.Linq.DefaultQueryProvider.Execute[TResult](Expression
  expression)    at System.Linq.Queryable.First[TSource](IQueryable1
  source)    at Nichols.Web.Controllers.LoadController.RttInUse(String
  rttNumber) in
  c:\projects\NicholsFarms_demo_newCropYear\Nichols\src\Nichols.Web\Controllers\LoadController.cs:line
  71    at lambda_method(Closure , ControllerBase , Object[] )    at
  System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext
  controllerContext, IDictionary2 parameters)    at
  System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext
  controllerContext, ActionDescriptor actionDescriptor, IDictionary2
  parameters)    at
  System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult
  asyncResult, ActionInvocation innerInvokeState)    at
  System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult
  asyncResult)    at
  System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3d()
  at
  System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.b__3f()
  at
  System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass33.b__32(IAsyncResult asyncResult)    at
  System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<>c__DisplayClass2b.b__1c()
  at
  System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.b__1e(IAsyncResult
  asyncResult)    at
  System.Web.Mvc.Controller.b__1d(IAsyncResult
  asyncResult, ExecuteCoreState innerState)    at
  System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult
  asyncResult)    at
  System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)

  at
  System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult
  asyncResult)    at
  System.Web.Mvc.MvcHandler.b__5(IAsyncResult
  asyncResult, ProcessRequestState innerState)    at
  System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult
  asyncResult)    at
  System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
  at System.Web.HttpApplication.ExecuteStep(IExecutionStep step,
  Boolean& completedSynchronously)

and the code I am TRYING to use is:

public ActionResult RttInUse(string rttNumber)
{
    int validNumber;
    int recommendRttNumber = 0;
    var cropYear = _session.Query<CropYear>().SingleOrDefault(x => x.IsCurrent);

    if (cropYear.RttRangeHaveBeenConfiguredForNewCropYear)
    {
        recommendRttNumber = _session.Query<Load>()
            .Where(x =>
                x.CropYear == cropYear &&
                !x.RttNumber.Contains("VOID") &&
                x.RttNumber.Length < 9)
            .OrderByDescending(x => x.Id)
            .Select(x => x.RttNumber)
            .FirstOrDefault(x => int.Parse(x) >= cropYear.RttNumberRangeStart &&
                                 int.Parse(x) <= cropYear.RttNumberRangeEnd).AsInt() + 1;
    }

    if (rttNumber == null || !int.TryParse(rttNumber, out validNumber))
    {
        return AsJson(
            "Rtt number invalid, numeric values only. Next Rtt Number should be " +
            recommendRttNumber);
    }

    var loadExists = _session.Query<Load>()
        .Any(x =>
            x.RttNumber.ToLower() == rttNumber.ToLower() &&
            x.CropYear == cropYear);

    if (loadExists)
    {
        return AsJson("Rtt Number already in use. Next Rtt Number should be " +
                      recommendRttNumber);
    }

    return AsJson(true);
}

Basically while operators enter a string such as 150001 on the form, the value they enter is compared against an acceptable range in the database.

Crop year has entries such that the year 2015 has an acceptable range of 150001 to 159999 to choose from which is RttNumberRangeStart to RttNumberRangeEnd; if it is in use, they should get recommended the current used rttnumber + 1.

Body:
Probably the sequence below contains no elements:

.FirstOrDefault(x => int.Parse(x) >= cropYear.RttNumberRangeStart &&
                     int.Parse(x) <= cropYear.RttNumberRangeEnd)

so it cannot do the following on a null (default) element

.AsInt() + 1;

Assuming RttNumber is a string and AsInt() an extension method to convert an string to int, change it to return 0 on a null string.


问:
Using Adobe PhoneGap - Beginners Questions
I'm starting out with Adobe PhoneGap as a way to develop native mobile apps. I have a solid understanding of jQuery/HTML5/CSS but upon using PhoneGap, there are a few basic areas which leave me baffled.

All of these questions relate to using the PhoneGap Desktop App to test apps on my iOS devices.

No matter what I do, I can't get Splash screens to show on test apps via PhoneGap Desktop App. Even the example "Hello World" project that PhoneGap can create has links/files for a splashscreen but it doesn't show - is this normal?

Related to the above, why are there multiple config.xml files? I have been editing the root config.xml file but there is also a config.xml in "platforms/browser" - having read some other answers, it seems as though there should be a config.xml in the "www" folder too? Any clarification would be much appreciated.

Finally, using the sample code generated by PhoneGap Desktop, I have been able to edit a blank project and trigger notifications, access the camera etc successfully from my jQuery code. However, the "Plugin"s folder is empty and I'm not referencing any of the plugins in my config.xml - Does the PhoneGap Desktop App always include all plugins by default? Do I need to explicitly state which Plug-Ins I use once I get to the point where I want to deploy a native app?

Thank you for any pointers on the above.

答:
I can't give you a complete answer, as I mainly use the CLI and PhoneGap Build service to build my app. But here's some more info that might help:

Missing splash screens can be due to a few things:

If you are using legacy launch images for the splash screen (i.e., you have an image for each screen size), it could be a missing <splash> element for a particular platform, or a relative path that isn't pointing to the right place

If you're using the splashscreen plugin with storyboard screens, you might be missing some of the screen images. More info can be found on the Cordova website: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-splashscreen/index.html

Either way, if it's throwing some sort of file not found exception, you should be able to catch it by either adding the browser platform (to test) or clicking refresh in the browser. Not sure how the PG desktop app works, or if it has a refresh option somewhere.

[EDIT] I should also mention, it's possible that there is also some security policy nonsense going on as well. See https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-whitelist/ for more info. I think errors related to security also show up in the console.

A lot of the configuration path stuff is tied into the config.xml file. This has gone through a few iterations over the development of Cordova / PhoneGap, so it's understandable that there would be some confusion. The file should be in the app's top-level directory; it gets copied down to each platform as part of the build script process. Older versions of Cordova / PhoneGap had this file down in the \www directory. There's some more info on that file here: https://cordova.apache.org/docs/en/latest/config_ref/

No idea what's going on here. Access to the camera, etc. should be controlled by plugins, which would be specified in your config.xml file (insert meme here: PHONEGAP DESKTOP APP Y U NO BLOCK?). You will definitely need to specify which plugins will be used in the config.xml file when you deploy to an actual device.


问:
Does ColdFusion support REST API URIs with a dynamic token in the middle of the URI?
I've been playing with ColdFusion 11's REST API support and am wondering if it's possible to have it support a URI with a dynamic token in the middle of the URI instead of only at the end.  That is, it very easily supports URIs like:

```<code>/rest/users/12345
</code>```

where the 12345 is dynamic (in this case, the user's userID).  But I haven't been able to find a way (without a tremendous amount of URI hacking) to support URIs like:

```<code>/rest/users/12345/emailAddresses
</code>```

So, is it possible to do this in ColdFusion (11 or 2016)?  If not, is it supported in Taffy (I didn't see where it is but I could be wrong)?

TIA

答:
It's been a while and I wanted to provide the answer in case anyone else has this same question...

ColdFusion, when defining a CFC for a REST endpoint, allows you to specify wildcards/variable names in the restpath attribute to both the <cfcomponent> and <cffunction> tags.  You would then define <cfargument> tags for each one of these variables so that you can access them within your function.  For example:

```<code><cfcomponent rest="true" restpath="/users/{userId}/pets" ... >
    <cffunction name="getPets" access="remote" httpMethod="GET">
        <cfargument name="userId" type="numeric" required="true" restargsource="Path" />

        <!--- Called with a path like /users/123/pets/ --->
        <!--- do stuff using the arguments.userId (123) variables --->
    </cffunction>

    <cffunction name="getPet" access="remote" httpMethod="GET" restpath="{petId}">
        <cfargument name="userId" type="numeric" required="true" restargsource="Path" />
        <cfargument name="petId" type="numeric" required="true" restargsource="Path" />

        <!--- Called with a path like /users/123/pets/456/ --->
        <!--- do stuff using the arguments.userId (123) and/or arguments.petId (456) variables --->
    </cffunction>
</cfcomponent>
</code>```

The keys here are using the restpath attribute with the variable defined as a variable name in curly braces and then defining those variables as arguments to the function with a restargsource attribute set to "Path".

I hope this helps.

Body:
I've been playing with ColdFusion 11's REST API support and am wondering if it's possible to have it support a URI with a dynamic token in the middle of the URI instead of only at the end.  That is, it very easily supports URIs like:

/rest/users/12345

where the 12345 is dynamic (in this case, the user's userID).  But I haven't been able to find a way (without a tremendous amount of URI hacking) to support URIs like:

/rest/users/12345/emailAddresses

So, is it possible to do this in ColdFusion (11 or 2016)?  If not, is it supported in Taffy (I didn't see where it is but I could be wrong)?

TIA

Body:
It's been a while and I wanted to provide the answer in case anyone else has this same question...

ColdFusion, when defining a CFC for a REST endpoint, allows you to specify wildcards/variable names in the restpath attribute to both the <cfcomponent> and <cffunction> tags.  You would then define <cfargument> tags for each one of these variables so that you can access them within your function.  For example:

<cfcomponent rest="true" restpath="/users/{userId}/pets" ... >
    <cffunction name="getPets" access="remote" httpMethod="GET">
        <cfargument name="userId" type="numeric" required="true" restargsource="Path" />

        <!--- Called with a path like /users/123/pets/ --->
        <!--- do stuff using the arguments.userId (123) variables --->
    </cffunction>

    <cffunction name="getPet" access="remote" httpMethod="GET" restpath="{petId}">
        <cfargument name="userId" type="numeric" required="true" restargsource="Path" />
        <cfargument name="petId" type="numeric" required="true" restargsource="Path" />

        <!--- Called with a path like /users/123/pets/456/ --->
        <!--- do stuff using the arguments.userId (123) and/or arguments.petId (456) variables --->
    </cffunction>
</cfcomponent>

The keys here are using the restpath attribute with the variable defined as a variable name in curly braces and then defining those variables as arguments to the function with a restargsource attribute set to "Path".

I hope this helps.


问:
Sorting data by multiple fields and conditions
I want to sort the data according to following conditions:

Sort by type with precedence as [state,city,district].

-Data with type state should be at first place, then data with city and so on.

Duplicate data should be sort by score.

-eg : if 3 rows are with type, then sort it by score.

My data object is:

```<code>$scope.data = [{
 id: 1,
 name: 'ABC',
 type: 'city',
 score: 0.1
}, {
 id: 2,
 name: 'PQR',
 type: 'city',
 score: 0.7
}, {
 id: 3,
 name: 'ABC',
 type: 'state',
 score: 0.3
});
</code>```

And template is:

```<code><div ng-repeat="d in data">
 <span>{{d.name}}</span>
 <span>{{d.type}}</span>
 <span>{{d.score}}</span>
</div>
</code>```

Result should be like this:

```<code>ABC state 0.3
PQR city 0.7
ABC city 0.1
</code>```

Here is the link of plunker.

I want to sort it by multiple fields as well as with a specific precedence.

Any help will be appreciated. Thanks in advance.

答:
//here is my code. I think this code solve your problem</p>

```<code>  var tempFlag = {'state':1, 'city':2, 'district':3}
  $scope.data=[
    {
     id: 1,
     name: 'ABC',
     type: 'city',
     score: 0.1
    }, {
     id: 2,
     name: 'PQR',
     type: 'city',
     score: 0.7
    }, {
     id: 3,
     name: 'ABC',
     type: 'state',
     score: 0.3
    }
    ].sort(function(a, b) {
        if(a.type == b.type)
           return a.score < b.score;
       return tempFlag[a.type] > tempFlag[b.type];
    });
</code>```

Body:
I want to sort the data according to following conditions:

Sort by type with precedence as [state,city,district].

-Data with type state should be at first place, then data with city and so on.

Duplicate data should be sort by score.

-eg : if 3 rows are with type, then sort it by score.

My data object is:

$scope.data = [{
 id: 1,
 name: 'ABC',
 type: 'city',
 score: 0.1
}, {
 id: 2,
 name: 'PQR',
 type: 'city',
 score: 0.7
}, {
 id: 3,
 name: 'ABC',
 type: 'state',
 score: 0.3
});

And template is:

 {{d.name}}
 {{d.type}}
 {{d.score}}

Result should be like this:

ABC state 0.3
PQR city 0.7
ABC city 0.1

Here is the link of plunker.

I want to sort it by multiple fields as well as with a specific precedence.

Any help will be appreciated. Thanks in advance.

Body:
//here is my code. I think this code solve your problem

  var tempFlag = {'state':1, 'city':2, 'district':3}
  $scope.data=[
    {
     id: 1,
     name: 'ABC',
     type: 'city',
     score: 0.1
    }, {
     id: 2,
     name: 'PQR',
     type: 'city',
     score: 0.7
    }, {
     id: 3,
     name: 'ABC',
     type: 'state',
     score: 0.3
    }
    ].sort(function(a, b) {
        if(a.type == b.type)
           return a.score < b.score;
       return tempFlag[a.type] > tempFlag[b.type];
    });


Title: How to select rows with timestamp close to adjacent rows?

Body:
I have a SQL table with timestamps as one field. How can I select "adjacent" rows, i.e., rows that have timestamps within a certain delta (e.g. 5 seconds)?

Edit:

Sample Table:

CurrTime                Weight Length
----------------------- ------ -------------
2017-05-05 12:59:52.000 392    18.18
2017-05-05 12:59:29.000 396    18.18
2017-05-05 12:59:22.000 511    18.5
2017-05-05 12:58:53.000 512    18.5
2017-05-05 12:58:49.000 537    18.5

So the query should return:

CurrTime                Weight Length
----------------------- ------ -------------
2017-05-05 12:58:53.000 512    18.5
2017-05-05 12:58:49.000 537    18.5

Body:
using exists():

select *
from t
where exists (
  select 1
  from t i
  where i.currtime<>t.currtime
    and abs(datediff(second,i.currtime,t.currtime))<=5
    )

rextester demo: http://rextester.com/LYDBV65396

returns:

+-------------------------+--------+--------+
|        CurrTime         | Weight | Length |
+-------------------------+--------+--------+
| 2017-05-05 12:58:53.000 |    512 | 18.50  |
| 2017-05-05 12:58:49.000 |    537 | 18.50  |
+-------------------------+--------+--------+


问:
how to implement a dynamic combo box selection system
I'm implementing a system these days, i want to implement a combo box selection process but i don't know how to implement it, so asking you guys favor?

my scenario is this, let's say we have two combo box selection lists, left one and right one, left one is the main one and the right one is the child of the left one.

when i select a item from the left combo box the right combo box's content should be changed according to the selection of the left one,

Ex: let's think about mobile phones, if i select the brand

Nokia

from the left combo box right combo box's content should be changed to

```<code>C6-01
E7-00
5232
X3-02
C1-01
C7-00
5228
C5-03
5250
6120ci
E5-00
E73
</code>```

like wise. please help me to implement a this kind of scenario!
any tutorial links, sample codes to understand the scenario is better!

regards,
Rangana

答:
The trick is do subscribe to the change event and reset the contents of the second box accordingly.

HTML:

```<code><select id="brand">
    <option value="">- select -</option>
    <option value="nokia">Nokia</option>
    <option value="apple">Apple</option>
</select>

<select id="type"></select>
</code>```

JavaScript (on ready):

```<code>var selectBrand = $("#brand");
var selectType = $("#type");

var optionsList = {
    nokia: [
        "C6-01",
        "E7-00"
    ],
    apple: [
        "iPhone 3",
        "iPhone 3G",
        "iPhone 4"
    ]
};

selectBrand.change(function() {
    var brand = selectBrand.val();
    var options = optionsList[brand];
    var html;

    if (options) {
        html = '<option value="">- select -</option>';
        $.each(options, function(index, value) {
            html += '<option value="' + value + '">' + value + '</option>';
        });
    } else {
        html = '<option value="">Select a brand</option>';
    }
    selectType.html(html);
}).change();
</code>```

Full example at See http://www.jsfiddle.net/TJJ8f/

ContentLicense: CC BY-SA 2.5

Body:
I'm implementing a system these days, i want to implement a combo box selection process but i don't know how to implement it, so asking you guys favor?

my scenario is this, let's say we have two combo box selection lists, left one and right one, left one is the main one and the right one is the child of the left one.

when i select a item from the left combo box the right combo box's content should be changed according to the selection of the left one,

Ex: let's think about mobile phones, if i select the brand

Nokia

from the left combo box right combo box's content should be changed to

C6-01
E7-00
5232
X3-02
C1-01
C7-00
5228
C5-03
5250
6120ci
E5-00
E73

like wise. please help me to implement a this kind of scenario!
any tutorial links, sample codes to understand the scenario is better!

regards,
Rangana

Body:
The trick is do subscribe to the change event and reset the contents of the second box accordingly.

HTML:

<select id="brand">
    <option value="">- select -</option>
    <option value="nokia">Nokia</option>
    <option value="apple">Apple</option>
</select>

<select id="type"></select>

JavaScript (on ready):

var selectBrand = $("#brand");
var selectType = $("#type");

var optionsList = {
    nokia: [
        "C6-01",
        "E7-00"
    ],
    apple: [
        "iPhone 3",
        "iPhone 3G",
        "iPhone 4"
    ]
};

selectBrand.change(function() {
    var brand = selectBrand.val();
    var options = optionsList[brand];
    var html;

    if (options) {
        html = '<option value="">- select -</option>';
        $.each(options, function(index, value) {
            html += '<option value="' + value + '">' + value + '</option>';
        });
    } else {
        html = '<option value="">Select a brand</option>';
    }
    selectType.html(html);
}).change();

Full example at See http://www.jsfiddle.net/TJJ8f/


问:
Very basic N1QL grouping data operation
So I am learning N1QL in order to write some queries to see usage data, and I am trying to look at data that looks like the following:

```<code>   "data": {
      "datapoints": [
        {
          "point1": "data 1",
          "point2": "data 2",
          "point3": "data 3"
        },
        {
          "point1": "more data 1",
          "point2": "more data 2",
          "point3": "more data 3"
        }
     ]
    }
</code>```

If I select like this:

SELECT data.datapoints[].point1, data.datapoints[].point2 FROM datatable

I get the data back grouped by the name of the column, like this:

```<code>[
  {
    "point1": [
        "data 1",
        "more data 1"
    ]
  },
  {
    "point2": [
        "data 2",
        "more data 2"
    ]
  },
]
</code>```

Is it possible to set up the query so that it returns data grouped by object, as opposed to grouped by the data point(s), but just with the fields I want?  I would like to look at by document, instead of by data point across documents, just with a subset of the data points in the documents.  Thanks in advance!

EDIT: I notice if I set up my query like this:

```<code>SELECT data.datapoints[0].point1, data.datapoints[0].point2 FROM datatable
</code>```

My data is formatted properly, like so:

```<code>  "datapoints": [
    {
      "point1": "data 1",
      "point2": "data 2",
    }
   ]
</code>```

but of course only the first datapoints record is returned.

答:
SELECT ud AS datapoints FROM datatable d UNNEST d.datapoints AS ud;

UNNEST works same as JOIN. UNNEST works on arrays.

datatable d UNNEST d.datapoints AS ud makes Cartesian JOIN of d and each element of  d.datapoints. Finally we project ud.

Checkout UNNEST Clause for details.

https://developer.couchbase.com/documentation/server/current/n1ql/n1ql-language-reference/from.html

Title: Very basic N1QL grouping data operation

Body:
So I am learning N1QL in order to write some queries to see usage data, and I am trying to look at data that looks like the following:

   "data": {
      "datapoints": [
        {
          "point1": "data 1",
          "point2": "data 2",
          "point3": "data 3"
        },
        {
          "point1": "more data 1",
          "point2": "more data 2",
          "point3": "more data 3"
        }
     ]
    }

If I select like this:

SELECT data.datapoints[].point1, data.datapoints[].point2 FROM datatable

I get the data back grouped by the name of the column, like this:

[
  {
    "point1": [
        "data 1",
        "more data 1"
    ]
  },
  {
    "point2": [
        "data 2",
        "more data 2"
    ]
  },
]

Is it possible to set up the query so that it returns data grouped by object, as opposed to grouped by the data point(s), but just with the fields I want?  I would like to look at by document, instead of by data point across documents, just with a subset of the data points in the documents.  Thanks in advance!

EDIT: I notice if I set up my query like this:

SELECT data.datapoints[0].point1, data.datapoints[0].point2 FROM datatable

My data is formatted properly, like so:

  "datapoints": [
    {
      "point1": "data 1",
      "point2": "data 2",
    }
   ]

but of course only the first datapoints record is returned.


问:
Error deploying Angular4 to ghpages using angular-cli-ghpages
I am trying to deploy a simple Angular 4 app to gh-pages. I have tried several methods and it seems that angular-cli-ghpages is the most up to date way to do it.

I've followed the instructions on the npm angular-cli-ghpages page.

First I installed successfully angular-cli-ghpages,

```<code>$ sudo npm i -g angular-cli-ghpages
</code>```

This command wouldn't work without sudo.

Next I created the dist folder and set the base-href,

```<code>$ ng build --prod --base-href "https://shanegibney.github.io/mathapp/"
</code>```

Then I deployed with,

```<code>$ ngh
</code>```

but this gives errors,

The output can be seen in this image below,

Running angular-cli-ghpages instead of ngh produces the same error,

I am using the following versions,

npm 3.10.10

angular-cli-ghpages ^0.5.1

node 6.9.4 (not really an issue here)

Thanks

答:
I solved this by added the following to the end of the scripts object in package.json,

```<code>"scripts": {

   "deploy": "ng build --prod --base-href
   https://shanegibney.github.io/mathapp/ && angular-cli-ghpages --branch
   gh-pages"
}
</code>```

and then ran,

$sudo npm run deploy

So it seems that what was needed was the '--branch gh-pages' as an option, but there is nothing to suggest this on the npm page for angular-cli-ghpages.

Note if running these command separately without going through package.json I found it doesn't work,

$ sudo ng build --prod --base-href https://shanegibney.github.io/mathapp/

$ sudo angular-cli-ghpages --branch gh-pages

Got help from a blog post on shermandigital.com

Body:
I am trying to deploy a simple Angular 4 app to gh-pages. I have tried several methods and it seems that angular-cli-ghpages is the most up to date way to do it.

I've followed the instructions on the npm angular-cli-ghpages page.

First I installed successfully angular-cli-ghpages,

$ sudo npm i -g angular-cli-ghpages

This command wouldn't work without sudo.

Next I created the dist folder and set the base-href,

$ ng build --prod --base-href "https://shanegibney.github.io/mathapp/"

Then I deployed with,

$ ngh

but this gives errors,

The output can be seen in this image below,

Running angular-cli-ghpages instead of ngh produces the same error,

I am using the following versions,

npm 3.10.10

angular-cli-ghpages ^0.5.1

node 6.9.4 (not really an issue here)

Thanks

Body:
I solved this by added the following to the end of the scripts object in package.json,

"scripts": {

   "deploy": "ng build --prod --base-href
   https://shanegibney.github.io/mathapp/ && angular-cli-ghpages --branch
   gh-pages"
}

and then ran,

$sudo npm run deploy

So it seems that what was needed was the '--branch gh-pages' as an option, but there is nothing to suggest this on the npm page for angular-cli-ghpages.

Note if running these command separately without going through package.json I found it doesn't work,

$ sudo ng build --prod --base-href https://shanegibney.github.io/mathapp/

$ sudo angular-cli-ghpages --branch gh-pages

Got help from a blog post on shermandigital.com


问:
Hazelcast partition lost behavior with initial-mode="LAZY/EAGER"
I am wondering that how initial-mode="LAZY/EAGER" behave at a partition lost.

According to the online documentations
EAGER - Synchronously loads the entries. Calls to getMap() are blocked while this happens

I need to know how the lost partition are loading in following scenarios...

1 ) Node crash and lost partition  when there is a backup in another node

will that lost partition data loaded from DB or backup ?

if this is loaded from DB ,How the initial-mode="LAZY/EAGER" affect for map
loading ?

Will that lost partition migrated to the node where the
backup is available or can it be possible to migrate to completely
new node ?

2 )  Node crash and lost partition when there is no any backup in another node

In this scenario lost partition data will be loaded from DB

How the initial-mode="LAZY/EAGER" affect for map loading when there is no any backup ?

When initial-mode="LAZY" ,
Instantly after partition lost, i can see it relocated in another node , I think that is only the partition creation not with data

In this image you can see the partition ID 87 lost and instantly partition summery shows it is relocated in another node

62- ( LOM:FE44 ) =  partionID - ( partition key )

答:
First lets begin by understanding the fundamental differences between the backup options:
Synchronous - default 1 [backup-count]
Asynchronous - default 0 [async-backup-count]

By default we have strong consistency because:
Client map.put(foo) -> Primary two threads: T1 operational thread stores in partition on Primary while T2 stores on Backup. T1 and T2 Join prior to returning to Client. So once the return from map.put occurs the data is safely stored in two locations.

In the event you set [backup-count] to 0 and [async-backup-count] >0 then you will have eventual consistency since T1 and T2 will not be joined prior to returning to the client; instead once T1 finishes the server returns to the Client.

So now lets look at your questions:
1 ) Node crash and lost partition when there is a backup in another node
will that lost partition data loaded from DB or backup ?
We have not discussed a MapStore (which is one of several ways to store the data into a database) but if you have implemented a Map Store then it would be restored from there in the event of a cache miss.

if this is loaded from DB ,How the initial-mode="LAZY/EAGER" affect for map loading ?
Lazy will only load the partition data (think 1/271th of the data by default) versus Eager which will load the full map (271/271th of the data)

Will that lost partition migrated to the node where the backup is available or can it be possible to migrate to completely new node ?
The backup will immediately restore the partition from the lost server. The backup which is now primary will solicit a new backup.

2 ) Node crash and lost partition when there is no any backup in another node
If you fail to set [backup-count] and [async-backup-count] and MapStore and you are not using HotRestart then you just lost data. But you had to change our defaults in order to create this situation.

In this scenario lost partition data will be loaded from DB
How the initial-mode="LAZY/EAGER" affect for map loading when there is no any backup ?
Again it determines how much of the map data will be loaded and if you have a map store it means how many load(key) will be invoked on your DB.

Hope this helps,


答: A number of previous SO posts cover this topic, have a look at this for example: Using javascript and jquery, to populate related select boxes with array structure</p>

Title: how to implement a dynamic combo box selection system


问:
awk pipeline to extract and validate xml files
How do I extract and validate xml files using awk and xmllint in a pipeline.

Awk program that only extracts files:

extractxml

```<code>#!/usr/bin/awk -f
/<?xml version/{ getline doctype; getline datadoc;
     if (match(datadoc,/file="([^-]+)-[^"]+.XML"/,a)) {
         fn=a[1]".xml"; print $0 ORS doctype ORS datadoc > fn; print a[1]".xml" ; next;
     }}{ print > fn }
</code>```

The input concatenated xml file:

refcase.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE data-document SYSTEM "refcase.dtd" [ ]>
<data-document lang="EN" dtd-version="v1 2017-01-01" file="aa1234aa-20170101.XML">
<document-metatdata lang="EN" country="INTL">
<document-reference/>
</document-metatdata>
</data-document>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE data-document SYSTEM "refcase.dtd" [ ]>
<data-document lang="EN" dtd-version="v1 2017-01-01" file="aa2345bb-20170202.XML">
<document-metatdata lang="EN" country="LOCAL">
<document-reference/>
</document-metatdata>
</data-document>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE data-document SYSTEM "refcase.dtd" [ ]>
<data-document lang="EN" dtd-version="v1 2017-01-01" file="aa3456cc-20170303.XML">
<document-metatdata lang="EN" country="NA">
<document-reference/>
</document-metatdata>
</data-document>
</code>```

Validation command:

```<code>xmllint --debug --dtdvalid refcase.dtd aa1234bb.xml
</code>```

XML dtd file used by xmllint for validation of the xml file:

refcase.dtd

```<code><?xml encoding="UTF-8"?>

<!ELEMENT data-document (document-metatdata)>
<!ATTLIST data-document
  xmlns CDATA #FIXED ''
  date-published CDATA #REQUIRED
  dtd-version CDATA #REQUIRED
  file NMTOKEN #REQUIRED

<!ELEMENT document-metatdata (document-reference)>
<!ATTLIST document-metatdata
  xmlns CDATA #FIXED ''
  country NMTOKEN #REQUIRED
  lang NMTOKEN #REQUIRED>

<!ELEMENT document-reference EMPTY>
<!ATTLIST document-reference
xmlns CDATA #FIXED ''>
</code>```

When I add this code to the awk program:

```<code>{ print > fn } system("xmllint --debug --dtdvalid refcase.dtd " fn " > " a[1]".xml.rpt")
</code>```

The awk extract still works fine and the .xml files are created as before.

The awk output is now passed to the xmllint command for xml validation and it looks like there is problem with the input into the xmllint command.

Awk program that extracts the files and sends the output to the xmllint command:

```<code>#!/usr/bin/awk -f
/<?xml version/{ getline doctype; getline datadoc;
     if (match(datadoc,/file="([^-]+)-[^"]+.XML"/,a)) {
         fn=a[1]".xml"; print $0 ORS doctype ORS datadoc > fn; print a[1]".xml" ; next;
     }}{ print > fn } system("xmllint --debug --dtdvalid refcase.dtd " fn " > " a[1]".xml.rpt")
</code>```

Problem output from the xmllint command when invoked in awk:

```<code>aa1234aa.xml
aa1234aa.xml:5: parser error : Premature end of data in tag document-metatdata line 4
aa1234aa.xml:5: parser error : Premature end of data in tag data-document line 3
<document-metatdata lang="EN" country="INTL">
aa1234aa.xml:6: parser error : Premature end of data in tag document-metatdata line 4
aa1234aa.xml:6: parser error : Premature end of data in tag data-document line 3
<document-reference/>
aa1234aa.xml:7: parser error : Premature end of data in tag data-document line 3
</code>```

The parser errors do not occur when the command is executed in the shell, the errors only occur when executed in the awk program. Which suggests to me the extracted xml files are okay.

It is an extraction process for thousands of concatenated txt files that each contain thousands of xml files. I need to trace and audit all the steps and validate the outputs.

Expected output of extracted xml files:

```<code>aa1234aa.XML

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE data-document SYSTEM "refcase.dtd" [ ]>
<data-document lang="EN" dtd-version="v1 2017-01-01" file="aa1234aa-20170101.XML">
<document-metatdata lang="EN" country="INTL">
<document-reference/>
</document-metatdata>
</data-document>

aa2345bb.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE data-document SYSTEM "refcase.dtd" [ ]>
<data-document lang="EN" dtd-version="v1 2017-01-01" file="aa2345bb-20170202.XML">
<document-metatdata lang="EN" country="LOCAL">
<document-reference/>
</document-metatdata>
</data-document>

aa3456cc.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE data-document SYSTEM "refcase.dtd" [ ]>
<data-document lang="EN" dtd-version="v1 2017-01-01" file="aa3456cc-20170303.XML">
<document-metatdata lang="EN" country="NA">
<document-reference/>
</document-metatdata>
</data-document>
</code>```

Questions:

I would like awk to write the output to a file and redirect the output to a command for further processing.

Not sure if awk is the best tool for extractions, it has worked well so far across the test data. I need to log the process and validate the output.

Appreciate any other approaches that would be reliable and scalable?

答:
Your posted command is:

```<code>/<?xml version/{ getline doctype; getline datadoc;
     if (match(datadoc,/file="([^-]+)-[^"]+.XML"/,a)) {
         fn=a[1]".xml"; print $0 ORS doctype ORS datadoc > fn; print a[1]".xml" ; next;
     }}{ print > fn } system("xmllint --debug --dtdvalid refcase.dtd " fn " > " a[1]".xml.rpt")
</code>```

Step 1 is to fix it to use sensible formatting so we can see the control flow:

```<code>/<?xml version/{
     getline doctype
     getline datadoc;
     if (match(datadoc,/file="([^-]+)-[^"]+.XML"/,a)) {
         fn=a[1]".xml"
         print $0 ORS doctype ORS datadoc > fn
         print a[1]".xml"
         next
     }
}
{ print > fn }
system("xmllint --debug --dtdvalid refcase.dtd " fn " > " a[1]".xml.rpt")
</code>```

OK, so now at a glance we can see that the system() call is in a condition block instead of an action, it's not closing output files as it goes, it's not quoting the xmllint file names, and it's hard-coding a[1]".xml" in multiple places so lets fix those:

```<code>/<?xml version/{
     getline doctype
     getline datadoc
     if (match(datadoc,/file="([^-]+)-[^"]+.XML"/,a)) {
         close(fn)
         fn=a[1]".xml"
         print $0 ORS doctype ORS datadoc > fn
         print fn
         next
     }
}
{
    print > fn
    system("xmllint --debug --dtdvalid refcase.dtd \047" fn "\047 > \047" fn ".rpt\047")
}
</code>```

Now let's get rid of the fragile and unnecessary calls to getline:

```<code>/<?xml version/{
    xmlversion = $0
    cnt = 3
}
cnt==2 {
    doctype = $0
}
cnt==1 {
    datadoc = $0
    if (match(datadoc,/file="([^-]+)-[^"]+.XML"/,a)) {
        close(fn)
        fn=a[1]".xml"
        print xmlversion ORS doctype ORS datadoc > fn
        print fn
        next
    }
}
cnt { cnt--; next }
{
    print > fn
    system("xmllint --debug --dtdvalid refcase.dtd \047" fn "\047 > \047" fn ".rpt\047")
}
</code>```

Now we can see that you're calling "xmllint" for every line that's output instead of on every output file that's completed. Change your command to this:

```<code>/<?xml version/{
    xmlversion = $0
    cnt = 3
}
cnt==2 {
    doctype = $0
}
cnt==1 {
    if (match($0,/file="([^-]+)-[^"]+.XML"/,a)) {
        lint(fn)
        fn=a[1]".xml"
        print xmlversion ORS doctype ORS $0 > fn
        print fn
        next
    }
}
cnt { cnt--; next}
{ print > fn }
END { lint(fn) }

function lint(fn) {
    if (fn != "") {
        close(fn)
        system("xmllint --debug --dtdvalid refcase.dtd \047" fn "\047 > \047" fn ".rpt\047")
        fn = ""
    }
}
</code>```

Finally, given what I now know about your expected output, this is how I'd really write your script (also fixed the unescaped regexp metacharacters ? in <?xml and . in .XML that I hadn't spotted previously):

```<code>/<\?xml version/ {
    lint(fn)
    fn = ""
}
match($0,/file="([^-]+)-[^"]+\.XML"/,a) {
    fn = a[1]".xml"
    $0 = prev2 ORS prev1 ORS $0
    print fn
}
{
    if ( fn != "" ) {
        print > fn
    }
    prev2 = prev1
    prev1 = $0
}
END { lint(fn) }

function lint(fn) {
    if (fn != "") {
        close(fn)
        system("xmllint --debug --dtdvalid refcase.dtd \047" fn "\047 > \047" fn ".rpt\047")
    }
}
</code>```

Body:
How do I extract and validate xml files using awk and xmllint in a pipeline.

Awk program that only extracts files:

extractxml

#!/usr/bin/awk -f
/<?xml version/{ getline doctype; getline datadoc;
     if (match(datadoc,/file="([^-]+)-[^"]+.XML"/,a)) {
         fn=a[1]".xml"; print $0 ORS doctype ORS datadoc > fn; print a[1]".xml" ; next;
     }}{ print > fn }

The input concatenated xml file:

refcase.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE data-document SYSTEM "refcase.dtd" [ ]>
<data-document lang="EN" dtd-version="v1 2017-01-01" file="aa1234aa-20170101.XML">
<document-metatdata lang="EN" country="INTL">
<document-reference/>
</document-metatdata>
</data-document>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE data-document SYSTEM "refcase.dtd" [ ]>
<data-document lang="EN" dtd-version="v1 2017-01-01" file="aa2345bb-20170202.XML">
<document-metatdata lang="EN" country="LOCAL">
<document-reference/>
</document-metatdata>
</data-document>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE data-document SYSTEM "refcase.dtd" [ ]>
<data-document lang="EN" dtd-version="v1 2017-01-01" file="aa3456cc-20170303.XML">
<document-metatdata lang="EN" country="NA">
<document-reference/>
</document-metatdata>
</data-document>

Validation command:

xmllint --debug --dtdvalid refcase.dtd aa1234bb.xml

XML dtd file used by xmllint for validation of the xml file:

refcase.dtd

<?xml encoding="UTF-8"?>

<!ELEMENT data-document (document-metatdata)>
<!ATTLIST data-document
  xmlns CDATA #FIXED ''
  date-published CDATA #REQUIRED
  dtd-version CDATA #REQUIRED
  file NMTOKEN #REQUIRED

<!ELEMENT document-metatdata (document-reference)>
<!ATTLIST document-metatdata
  xmlns CDATA #FIXED ''
  country NMTOKEN #REQUIRED
  lang NMTOKEN #REQUIRED>

<!ELEMENT document-reference EMPTY>
<!ATTLIST document-reference
xmlns CDATA #FIXED ''>

When I add this code to the awk program:

{ print > fn } system("xmllint --debug --dtdvalid refcase.dtd " fn " > " a[1]".xml.rpt")

The awk extract still works fine and the .xml files are created as before.

The awk output is now passed to the xmllint command for xml validation and it looks like there is problem with the input into the xmllint command.

Awk program that extracts the files and sends the output to the xmllint command:

#!/usr/bin/awk -f
/<?xml version/{ getline doctype; getline datadoc;
     if (match(datadoc,/file="([^-]+)-[^"]+.XML"/,a)) {
         fn=a[1]".xml"; print $0 ORS doctype ORS datadoc > fn; print a[1]".xml" ; next;
     }}{ print > fn } system("xmllint --debug --dtdvalid refcase.dtd " fn " > " a[1]".xml.rpt")

Problem output from the xmllint command when invoked in awk:

aa1234aa.xml
aa1234aa.xml:5: parser error : Premature end of data in tag document-metatdata line 4
aa1234aa.xml:5: parser error : Premature end of data in tag data-document line 3
<document-metatdata lang="EN" country="INTL">
aa1234aa.xml:6: parser error : Premature end of data in tag document-metatdata line 4
aa1234aa.xml:6: parser error : Premature end of data in tag data-document line 3
<document-reference/>
aa1234aa.xml:7: parser error : Premature end of data in tag data-document line 3

The parser errors do not occur when the command is executed in the shell, the errors only occur when executed in the awk program. Which suggests to me the extracted xml files are okay.

It is an extraction process for thousands of concatenated txt files that each contain thousands of xml files. I need to trace and audit all the steps and validate the outputs.

Expected output of extracted xml files:

aa1234aa.XML

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE data-document SYSTEM "refcase.dtd" [ ]>
<data-document lang="EN" dtd-version="v1 2017-01-01" file="aa1234aa-20170101.XML">
<document-metatdata lang="EN" country="INTL">
<document-reference/>
</document-metatdata>
</data-document>

aa2345bb.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE data-document SYSTEM "refcase.dtd" [ ]>
<data-document lang="EN" dtd-version="v1 2017-01-01" file="aa2345bb-20170202.XML">
<document-metatdata lang="EN" country="LOCAL">
<document-reference/>
</document-metatdata>
</data-document>

aa3456cc.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE data-document SYSTEM "refcase.dtd" [ ]>
<data-document lang="EN" dtd-version="v1 2017-01-01" file="aa3456cc-20170303.XML">
<document-metatdata lang="EN" country="NA">
<document-reference/>
</document-metatdata>
</data-document>

Questions:

I would like awk to write the output to a file and redirect the output to a command for further processing.

Not sure if awk is the best tool for extractions, it has worked well so far across the test data. I need to log the process and validate the output.

Appreciate any other approaches that would be reliable and scalable?

Body:
Your posted command is:

/<?xml version/{ getline doctype; getline datadoc;
     if (match(datadoc,/file="([^-]+)-[^"]+.XML"/,a)) {
         fn=a[1]".xml"; print $0 ORS doctype ORS datadoc > fn; print a[1]".xml" ; next;
     }}{ print > fn } system("xmllint --debug --dtdvalid refcase.dtd " fn " > " a[1]".xml.rpt")

Step 1 is to fix it to use sensible formatting so we can see the control flow:

/<?xml version/{
     getline doctype
     getline datadoc;
     if (match(datadoc,/file="([^-]+)-[^"]+.XML"/,a)) {
         fn=a[1]".xml"
         print $0 ORS doctype ORS datadoc > fn
         print a[1]".xml"
         next
     }
}
{ print > fn }
system("xmllint --debug --dtdvalid refcase.dtd " fn " > " a[1]".xml.rpt")

OK, so now at a glance we can see that the system() call is in a condition block instead of an action, it's not closing output files as it goes, it's not quoting the xmllint file names, and it's hard-coding a[1]".xml" in multiple places so lets fix those:

/<?xml version/{
     getline doctype
     getline datadoc
     if (match(datadoc,/file="([^-]+)-[^"]+.XML"/,a)) {
         close(fn)
         fn=a[1]".xml"
         print $0 ORS doctype ORS datadoc > fn
         print fn
         next
     }
}
{
    print > fn
    system("xmllint --debug --dtdvalid refcase.dtd \047" fn "\047 > \047" fn ".rpt\047")
}

Now let's get rid of the fragile and unnecessary calls to getline:

/<?xml version/{
    xmlversion = $0
    cnt = 3
}
cnt==2 {
    doctype = $0
}
cnt==1 {
    datadoc = $0
    if (match(datadoc,/file="([^-]+)-[^"]+.XML"/,a)) {
        close(fn)
        fn=a[1]".xml"
        print xmlversion ORS doctype ORS datadoc > fn
        print fn
        next
    }
}
cnt { cnt--; next }
{
    print > fn
    system("xmllint --debug --dtdvalid refcase.dtd \047" fn "\047 > \047" fn ".rpt\047")
}

Now we can see that you're calling "xmllint" for every line that's output instead of on every output file that's completed. Change your command to this:

/<?xml version/{
    xmlversion = $0
    cnt = 3
}
cnt==2 {
    doctype = $0
}
cnt==1 {
    if (match($0,/file="([^-]+)-[^"]+.XML"/,a)) {
        lint(fn)
        fn=a[1]".xml"
        print xmlversion ORS doctype ORS $0 > fn
        print fn
        next
    }
}
cnt { cnt--; next}
{ print > fn }
END { lint(fn) }

function lint(fn) {
    if (fn != "") {
        close(fn)
        system("xmllint --debug --dtdvalid refcase.dtd \047" fn "\047 > \047" fn ".rpt\047")
        fn = ""
    }
}

Finally, given what I now know about your expected output, this is how I'd really write your script (also fixed the unescaped regexp metacharacters ? in <?xml and . in .XML that I hadn't spotted previously):

/<\?xml version/ {
    lint(fn)
    fn = ""
}
match($0,/file="([^-]+)-[^"]+\.XML"/,a) {
    fn = a[1]".xml"
    $0 = prev2 ORS prev1 ORS $0
    print fn
}
{
    if ( fn != "" ) {
        print > fn
    }
    prev2 = prev1
    prev1 = $0
}
END { lint(fn) }

function lint(fn) {
    if (fn != "") {
        close(fn)
        system("xmllint --debug --dtdvalid refcase.dtd \047" fn "\047 > \047" fn ".rpt\047")
    }
}


问:
VBA | How can I make a Macro Sheet Specific
I am creating a workbook with several introductory sheets followed by ten data sheets labeled "'1'", "'2'" etc. The macro is meant to do the same thing for each page, but the variable [A0] could change for each data sheet (a value ranging from 5 to 7). I would like to make the macro page specific so that I could create a button (on a seperate tab called "Inputs") that would process the macro without the user needing to visit tab "'2'".

(The purpose of the multiple buttons is to allow the user to only use 3 of the tabs if needed, because the excel program that I have created for the rest of the workbook can take about 5 minutes to execute.)

```<code>Sub InsertCells()

    Dim lastColCell As Range
    Set lastColCell = Cells(1, Columns.Count).End(xlToLeft)
    Dim ws as Worksheet
    Dim i As Long, k As Long, A0 As Long
    k = 0
    'A0 = Flowback Constant
    A0 = Sheets("Wells").Cells(2, 20)
    For i = 6 To lastColCell.Column
        Range(Cells(3, i), Cells(7 + k, i + 2)).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
        k = k + A0
        'Each A0 should correspond to a different cell if user has different flowback delays
        i = i + 2
    Next i

End Sub
</code>```

This code was created by user @BryceWayne and works very well - but unfortunately I have had trouble adding this final feature.

答:
Fully qualify all of your Cells, Columns, Rows, Range references. Easiest way to do this on a small procedure would be to wrap it in a With block:

```<code>Sub InsertCells
    Dim lastColCell As Range
    Dim ws as Worksheet
    Dim i As Long, k As Long, A0 As Long

    A0 = Sheets("Wells").Cells(2, 20)   ' Flowback Constant

    With ActiveWorkbook.Worksheets(1) 'Modify as needed
        Set lastColCell = .Cells(1, .Columns.Count).End(xlToLeft)
        k = 0
        For i = 6 To lastColCell.Column
            .Range(.Cells(3, i), .Cells(7 + k, i + 2)).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
            k = k + A0
            'Each A0 should correspond to a different cell if user has different flowback delays
            i = i + 2
        Next i
    End With
End Sub
</code>```

It's a little unclear why you're doing For i = 6 to lastColCell.Column and then incrementing i=i+2 within  that loop. That appears to be effectively incrementing i by 3 at each iteration (2 because of the =+ and then one more because of Next.  You would be better to do:

```<code>        For i = 6 To lastColCell.Column Step 3
            .Range(.Cells(3, i), .Cells(7 + k, i + 2)).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
            k = k + A0
            'Each A0 should correspond to a different cell if user has different flowback delays
        Next i
</code>```

Body:
I am creating a workbook with several introductory sheets followed by ten data sheets labeled "'1'", "'2'" etc. The macro is meant to do the same thing for each page, but the variable [A0] could change for each data sheet (a value ranging from 5 to 7). I would like to make the macro page specific so that I could create a button (on a seperate tab called "Inputs") that would process the macro without the user needing to visit tab "'2'".

(The purpose of the multiple buttons is to allow the user to only use 3 of the tabs if needed, because the excel program that I have created for the rest of the workbook can take about 5 minutes to execute.)

Sub InsertCells()

    Dim lastColCell As Range
    Set lastColCell = Cells(1, Columns.Count).End(xlToLeft)
    Dim ws as Worksheet
    Dim i As Long, k As Long, A0 As Long
    k = 0
    'A0 = Flowback Constant
    A0 = Sheets("Wells").Cells(2, 20)
    For i = 6 To lastColCell.Column
        Range(Cells(3, i), Cells(7 + k, i + 2)).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
        k = k + A0
        'Each A0 should correspond to a different cell if user has different flowback delays
        i = i + 2
    Next i

End Sub

This code was created by user @BryceWayne and works very well - but unfortunately I have had trouble adding this final feature.

Body:
Fully qualify all of your Cells, Columns, Rows, Range references. Easiest way to do this on a small procedure would be to wrap it in a With block:

Sub InsertCells
    Dim lastColCell As Range
    Dim ws as Worksheet
    Dim i As Long, k As Long, A0 As Long

    A0 = Sheets("Wells").Cells(2, 20)   ' Flowback Constant

    With ActiveWorkbook.Worksheets(1) 'Modify as needed
        Set lastColCell = .Cells(1, .Columns.Count).End(xlToLeft)
        k = 0
        For i = 6 To lastColCell.Column
            .Range(.Cells(3, i), .Cells(7 + k, i + 2)).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
            k = k + A0
            'Each A0 should correspond to a different cell if user has different flowback delays
            i = i + 2
        Next i
    End With
End Sub

It's a little unclear why you're doing For i = 6 to lastColCell.Column and then incrementing i=i+2 within  that loop. That appears to be effectively incrementing i by 3 at each iteration (2 because of the =+ and then one more because of Next.  You would be better to do:

        For i = 6 To lastColCell.Column Step 3
            .Range(.Cells(3, i), .Cells(7 + k, i + 2)).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
            k = k + A0
            'Each A0 should correspond to a different cell if user has different flowback delays
        Next i


问:
What's $interval mean in Grafana?
After installed Heapster in my kubernetes cluster, I can access Grafana but the graph are empty.
I can build a new graph with special value, e.g. "cpu/limits"; but if the pre-defined graph used $interval, the graph can not display; for example,</p>

```<code>SELECT mean(value) FROM "cpu/limit_gauge" WHERE "container_name" = 'machine' AND $timeFilter GROUP BY time($interval), "hostname"
</code>```

答:
For future readers -

I want to add that sometimes the "group-by" "fill" option, which is NULL by default, can cause no values to be displayed depending on the resolution.

If you have a query you think should work, but still see no data, try changing the fill value to another setting that you think works (ie: none) and see if data shows up.

Grafana tries to use that configuration to fill in for missing data, and occasionally, depending on your interval and data collection rate, you might end up with oddness.

Title: What's $interval mean in Grafana?

Body:
After installed Heapster in my kubernetes cluster, I can access Grafana but the graph are empty.
I can build a new graph with special value, e.g. "cpu/limits"; but if the pre-defined graph used $interval, the graph can not display; for example,

SELECT mean(value) FROM "cpu/limit_gauge" WHERE "container_name" = 'machine' AND $timeFilter GROUP BY time($interval), "hostname"


问:
VBA doesn't include every sheet in pdf output
I'm attempting to output 4 sheets into one pdf file, but for some reason the output only includes the first sheet, "Report 1a". Here's my code:

```<code>Dim Ref As Worksheet

Set Ref = Worksheets("Charts for Report")

Sheets(Array("Report 1a", "Report 1b", "Report 2", "Comments")).Select
Sheets("Report 1a").Activate
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    "T:\QA\Sample Reports\Reports for CCC\" & Ref.[B1] _
    & " - " & Ref.[B2] & " - " & Worksheets("Provider Data").[I2] & ".pdf" _
    , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
    :=False, OpenAfterPublish:=False

Worksheets("Report 1a").Select
</code>```

I've even tried recording a macro to see what I'm doing wrong. It'll work (i.e., include all 4 pages) when I record it, but if I try to rerun it it'll only put include the first page ("Report 1a").

答:
I still don't know what was going wrong, but I at least found a solution.

Prior to exporting anything I hid all the worksheets that I didn't want included. (All the more reason to avoid select like the plague!)

```<code>Sub Hide_non_Packet_Sheets()
    Dim index As Integer
    Dim SheetExists As Worksheet

    For index = 1 To 50
        Set SheetExists = Sheets(index)
        On Error Resume Next
        If Sheets(index).Name = "Page1" Or Sheets(index).Name = "Page2" Then
            Sheets(index).Visible = True
            Else
            Sheets(index).Visible = False
            End If
        Next index
End Sub
</code>```

Then I just export the entire workbook:

```<code>ThisWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:= "C:\Place\Name.pdf", _
    Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas :=False, _
    OpenAfterPublish:=False
</code>```

And then you can set a macro to unhide sheets when you're done exporting if you want.

Body:
I'm attempting to output 4 sheets into one pdf file, but for some reason the output only includes the first sheet, "Report 1a". Here's my code:

Dim Ref As Worksheet

Set Ref = Worksheets("Charts for Report")

Sheets(Array("Report 1a", "Report 1b", "Report 2", "Comments")).Select
Sheets("Report 1a").Activate
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    "T:\QA\Sample Reports\Reports for CCC\" & Ref.[B1] _
    & " - " & Ref.[B2] & " - " & Worksheets("Provider Data").[I2] & ".pdf" _
    , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
    :=False, OpenAfterPublish:=False

Worksheets("Report 1a").Select

I've even tried recording a macro to see what I'm doing wrong. It'll work (i.e., include all 4 pages) when I record it, but if I try to rerun it it'll only put include the first page ("Report 1a").

Body:
I still don't know what was going wrong, but I at least found a solution.

Prior to exporting anything I hid all the worksheets that I didn't want included. (All the more reason to avoid select like the plague!)

Sub Hide_non_Packet_Sheets()
    Dim index As Integer
    Dim SheetExists As Worksheet

    For index = 1 To 50
        Set SheetExists = Sheets(index)
        On Error Resume Next
        If Sheets(index).Name = "Page1" Or Sheets(index).Name = "Page2" Then
            Sheets(index).Visible = True
            Else
            Sheets(index).Visible = False
            End If
        Next index
End Sub

Then I just export the entire workbook:

ThisWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:= "C:\Place\Name.pdf", _
    Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas :=False, _
    OpenAfterPublish:=False

And then you can set a macro to unhide sheets when you're done exporting if you want.