问:
How to create custom icons for QFileSystemModel in a background thread
I am making a file browser in qt for some custom design-files. I want to load their preview as their thumbnail and for that reason I am using QIconProvider to return the Icon to my QFileSystemModel.

The problem is that the algorithm that creates the QIcon needs some resources and as a result my application is not responsive until it finishes loading all the thumbnails.

I am wondering if there is any way to put my QIconProvider in a background thread, so that I have my application responsive.

答:
The accepted answer is fantastic - introduced me to some of the more advanced Qt concepts.

For anyone trying this in the future, here's some changes I had to make to get this working smoothly:

Limit threads: Pass a QThreadPool to QConcurrent::run, with max threads set to 1 or 2.  Using the default killed the app, as all threads get burned building image previews.  Bottleneck will be disk, so doesn't make
sense to have more than 1 or 2 threads on this task.

Avoid re-entry: Need to handle the case where the icon for the same path is queried multiple times before icon generation is complete. Current code would spawn multiple threads generating the same icon.  Simple solution is to add a placeholder entry to the m_icons map before the QConcurrent::run call.  I just called to the default QIdentityProxyModel::data(index, QFileSystemModel::FileIconRole), so the icon gets a decent default before loading is complete

Task cancellation: If you destroy your model (or want to switch view folders, etc.), you'll want a way to cancel the active tasks.  Unfortunately, there's no built-in way to cancel a pending QConcurrent::run task.  I used a std::atomic_bool to signal cancellation, which the tasks check before executing. And a std::condition_variable to wait on until all tasks are cancelled/complete.

Tip: My use case for this was to load thumbnail previews from images on disk (likely the common use case). After some experimentation, I found that the fastest way to generate previews is to use QImageReader, passing your thumbnail size to setScaledSize. Note that if you have non-square images, you'll want to pass a size with the appropriate aspect ratio like this:

```<code>    const QSize originalSize = reader.size(); // Note: Doesn't load the file contents
    QSize scaledSize = originalSize;
    scaledSize.scale(MaximumIconSize, Qt::KeepAspectRatio);
    reader.setScaledSize(scaledSize);
</code>```

Body:
The accepted answer is fantastic - introduced me to some of the more advanced Qt concepts.

For anyone trying this in the future, here's some changes I had to make to get this working smoothly:

Limit threads: Pass a QThreadPool to QConcurrent::run, with max threads set to 1 or 2.  Using the default killed the app, as all threads get burned building image previews.  Bottleneck will be disk, so doesn't make
sense to have more than 1 or 2 threads on this task.

Avoid re-entry: Need to handle the case where the icon for the same path is queried multiple times before icon generation is complete. Current code would spawn multiple threads generating the same icon.  Simple solution is to add a placeholder entry to the m_icons map before the QConcurrent::run call.  I just called to the default QIdentityProxyModel::data(index, QFileSystemModel::FileIconRole), so the icon gets a decent default before loading is complete

Task cancellation: If you destroy your model (or want to switch view folders, etc.), you'll want a way to cancel the active tasks.  Unfortunately, there's no built-in way to cancel a pending QConcurrent::run task.  I used a std::atomic_bool to signal cancellation, which the tasks check before executing. And a std::condition_variable to wait on until all tasks are cancelled/complete.

Tip: My use case for this was to load thumbnail previews from images on disk (likely the common use case). After some experimentation, I found that the fastest way to generate previews is to use QImageReader, passing your thumbnail size to setScaledSize. Note that if you have non-square images, you'll want to pass a size with the appropriate aspect ratio like this:

    const QSize originalSize = reader.size(); // Note: Doesn't load the file contents
    QSize scaledSize = originalSize;
    scaledSize.scale(MaximumIconSize, Qt::KeepAspectRatio);
    reader.setScaledSize(scaledSize);


来源: stackexchange

问:
I am not sure what the following is expecting for
I am really appreciate for those who helps!!

Here is the question:
Consider a class MotorBoat that represents motorboats.  A motorboat has private attributes for:

The capacity of the fuel tank

The amount of fuel in the tank

The amount of fuel in the tank

The maximum speed of the boat

The current speed of the boat

The efficiency of the boat’s motor

The distance traveled

The class has methods to:

Change the speed of the boat

Operate the boat for an amount of time at the current speed

Refuel the boat with some amount of fuel

Return the amount of fuel in the tank

Return the distance traveled so far If the boat has efficiency e, the
amount of fuel used when traveling at a speed s for time t is e x s2
x t.  The distance traveled in that time is s x t.

And here is what I got by so far:

```<code>public class MotorBoat {

    //the capacity of the fuel tank
    private double capaity;
    //the amount of fuel in the tank
    private double amount;
    //the maximum speed of the boat
    private double maxSpeed;
    //the current speed of the boat
    private double curSpeed;
    //the efficiency of the boat's motor
    private double efficiency;
    //the distance traveled
    private double distance;

    //Change the speed of the boat
    public void changeSpeed(double newSpeed)
    {
        this.curSpeed = newSpeed;
    }
    //Operate the boat for an amount of time at the current speed
    public void operateAmount(double newAmount)
    {
        this.amount = newAmount;
    }

    //Refuel the boat with some amount of fuel
    //I don't get this one

    //Return the amount of fuel in the tank
    public double getAmount()
    {
        return amount;
    }
    //Return the distance traveled so far
    public double getDistance()
    {
        return distance;
    }

    //If the boat has efficiency e, the amount of fuel used when traveling at a speed s for time t is e x s2 x t.  The distance traveled in that time is s x t.

    public double amountUsed()
    {
        double amountUsed = this.efficiency*(this.curSpeed*this.curSpeed)*(this.getDistance()/this.curSpeed);
        return amountUsed();
    }

    public static void main(String[] args) {

        MotorBoat boat = new MotorBoat();
        System.out.println("Current Speed: " + boat.curSpeed);

        boat.changeSpeed(200);
        System.out.println("Current Speed: " + boat.curSpeed);

        System.out.println("Fuel Amount: " + boat.getAmount());
        boat.operateAmount(2000);
        System.out.println("Fuel Amount: " + boat.getAmount());

        System.out.println("Distance Traveled: " + boat.getDistance());

        boat.amountUsed();
        System.out.println("Fuel Amount: " + boat.amountUsed());

    }

}
</code>```

答:
You need a contructor, or setting all values before trying to get them or there will be null pointers

```<code>public MotorBoat(double a, double b, double c /* etc*/){
    this.a = a;
    this.b = b;
    this.c = c;
}
</code>```

also returning amunt used needs to have the () removed in the return else you are refering to the function, not the temporary variable you created in the function

Finally you need to have getters and setters for all values that are private you wish to acces from outside the class, say on an instance of the class, and then use these functions when operating on the class in a non-class scope, say your static manin in this case

Next time you ask a question, please specify the error, and what you are looking for help with, there is nothing wrong with asking for help with homework per say, but there is unless you show you tried and provide a describtion of what you need help with

ContentLicense: CC BY-SA 3.0

Body:
I am really appreciate for those who helps!!

Here is the question:
Consider a class MotorBoat that represents motorboats.  A motorboat has private attributes for:

The capacity of the fuel tank

The amount of fuel in the tank

The amount of fuel in the tank

The maximum speed of the boat

The current speed of the boat

The efficiency of the boat’s motor

The distance traveled

The class has methods to:

Change the speed of the boat

Operate the boat for an amount of time at the current speed

Refuel the boat with some amount of fuel

Return the amount of fuel in the tank

Return the distance traveled so far If the boat has efficiency e, the
amount of fuel used when traveling at a speed s for time t is e x s2
x t.  The distance traveled in that time is s x t.

And here is what I got by so far:

public class MotorBoat {

    //the capacity of the fuel tank
    private double capaity;
    //the amount of fuel in the tank
    private double amount;
    //the maximum speed of the boat
    private double maxSpeed;
    //the current speed of the boat
    private double curSpeed;
    //the efficiency of the boat's motor
    private double efficiency;
    //the distance traveled
    private double distance;

    //Change the speed of the boat
    public void changeSpeed(double newSpeed)
    {
        this.curSpeed = newSpeed;
    }
    //Operate the boat for an amount of time at the current speed
    public void operateAmount(double newAmount)
    {
        this.amount = newAmount;
    }

    //Refuel the boat with some amount of fuel
    //I don't get this one

    //Return the amount of fuel in the tank
    public double getAmount()
    {
        return amount;
    }
    //Return the distance traveled so far
    public double getDistance()
    {
        return distance;
    }

    //If the boat has efficiency e, the amount of fuel used when traveling at a speed s for time t is e x s2 x t.  The distance traveled in that time is s x t.

    public double amountUsed()
    {
        double amountUsed = this.efficiency*(this.curSpeed*this.curSpeed)*(this.getDistance()/this.curSpeed);
        return amountUsed();
    }

    public static void main(String[] args) {

        MotorBoat boat = new MotorBoat();
        System.out.println("Current Speed: " + boat.curSpeed);

        boat.changeSpeed(200);
        System.out.println("Current Speed: " + boat.curSpeed);

        System.out.println("Fuel Amount: " + boat.getAmount());
        boat.operateAmount(2000);
        System.out.println("Fuel Amount: " + boat.getAmount());

        System.out.println("Distance Traveled: " + boat.getDistance());

        boat.amountUsed();
        System.out.println("Fuel Amount: " + boat.amountUsed());

    }

}

Body:
You need a contructor, or setting all values before trying to get them or there will be null pointers

public MotorBoat(double a, double b, double c /* etc*/){
    this.a = a;
    this.b = b;
    this.c = c;
}

also returning amunt used needs to have the () removed in the return else you are refering to the function, not the temporary variable you created in the function

Finally you need to have getters and setters for all values that are private you wish to acces from outside the class, say on an instance of the class, and then use these functions when operating on the class in a non-class scope, say your static manin in this case

Next time you ask a question, please specify the error, and what you are looking for help with, there is nothing wrong with asking for help with homework per say, but there is unless you show you tried and provide a describtion of what you need help with


问:
Overriding a component method
I'm using VueCharts which is a Google Charts plugin for vue.

I'm trying to give the newer Material Design looks to the charts. I've tried passing "google.charts.Bar" to chart-type prop and it did work. However, many of the options are ignored because, as stated in the Google Charts docs, the options object needs to be converted by using google.charts.Bar.convertOptions(options), something the plugin doesn't do.

Looking at the source, the plugin installs a 'vue-chart' component. This component uses ChartWrapper to handle loading the chart libraries, like so:

```<code>methods: {
    buildWrapper (chartType, dataTable, options, containerId) {
      let wrapper = new google.visualization.ChartWrapper({
        chartType: chartType,
        dataTable: dataTable,
        options: options,
        containerId: containerId
      })

      return wrapper
    },
</code>```

So all I need is to override this method to convert the options before passing them to the ChartWrapper.

But how? I haven't found a way to simply override a component method in vue docs. I could create a new component and pass the converted options down, but I need access to the google object, which is only loaded internally by the plugin.

I have also read I could use mixins, but it's not clear how. This doesn't work:

```<code>Vue.component('MyCustomChart', {
    mixins: ['vue-chart'],
    methods: {
        buildWrapper (chartType, dataTable, options, containerId) {
            let wrapper = new google.visualization.ChartWrapper({
                chartType: chartType,
                dataTable: dataTable,
                options: google.charts.Bar.convertOptions(options), // that's all I need
                containerId: containerId
            })

            return wrapper
        },
    }
})
</code>```

[Vue warn]: Failed to mount component: template or render function not defined.
  (found in MyCustomChart)

答:
I played around with this a bit and I misled @thanksd above with my recommendation on what to extend. One way that works is this:

```<code>import VueChart from "vue-charts";

Vue.use(VueChart);

const BaseChart = Vue.options.components["vue-chart"];
const CustomChart = BaseChart.extend({
  methods:{
    buildWrapper (chartType, dataTable, options, containerId) {
      let wrapper = new google.visualization.ChartWrapper({
        chartType: chartType,
        dataTable: dataTable,
        options: google.charts.Bar.convertOptions(options),
        containerId: containerId
      })

      return wrapper
    }
  }
});

Vue.component("custom-chart", CustomChart);
</code>```

Further Explanation

As I thought, extending VueChart either through Vue's native extend, or through lodash, will not achieve the expected results. The result of importing VueChart is a plugin definition. Both lodash and Vue will happily accept that as an object to extend, but neither will result in a Vue component. Trying to use the result of either will result in the error mentioned in the question, "template or render function not defined". That error is absolutely true; extending VueChart extends an install function with a single method.

So how do you get the object to extend? vue-charts doesn't expose it. The install just calls Vue.component('vue-chart', Chart).

Fortunately, Vue makes the globally installed components through Vue.options.components. By extending Vue.options.components["vue-chart"] we get a proper Vue component definition.

Finally, I was surprised google was not available to @RegularEverydayNormalGuy. It has to be available; vue-chart uses it. But he's right, it's not available immediately. vue-chart loads the script asynchronously. Again, the plugin unfortunately doesn't make it available to you in any way, it just initializes itself after it's asynchronously loaded. There are ways to work around that, but at that point you should just probably submit a pull request.

Original Answer

options is a property on vue-chart. Why not just pass in the converted options?

```<code>new Vue({
    data:{
        convertedOptions: google.charts.Bar.convertOptions({<my options>})
    }
})
</code>```

And in the template

```<code><vue-chart :options="convertedOptions"></vue-chart>
</code>```

Title: Overriding a component method

Body:
I'm using VueCharts which is a Google Charts plugin for vue.

I'm trying to give the newer Material Design looks to the charts. I've tried passing "google.charts.Bar" to chart-type prop and it did work. However, many of the options are ignored because, as stated in the Google Charts docs, the options object needs to be converted by using google.charts.Bar.convertOptions(options), something the plugin doesn't do.

Looking at the source, the plugin installs a 'vue-chart' component. This component uses ChartWrapper to handle loading the chart libraries, like so:

methods: {
    buildWrapper (chartType, dataTable, options, containerId) {
      let wrapper = new google.visualization.ChartWrapper({
        chartType: chartType,
        dataTable: dataTable,
        options: options,
        containerId: containerId
      })

      return wrapper
    },

So all I need is to override this method to convert the options before passing them to the ChartWrapper.

But how? I haven't found a way to simply override a component method in vue docs. I could create a new component and pass the converted options down, but I need access to the google object, which is only loaded internally by the plugin.

I have also read I could use mixins, but it's not clear how. This doesn't work:

Vue.component('MyCustomChart', {
    mixins: ['vue-chart'],
    methods: {
        buildWrapper (chartType, dataTable, options, containerId) {
            let wrapper = new google.visualization.ChartWrapper({
                chartType: chartType,
                dataTable: dataTable,
                options: google.charts.Bar.convertOptions(options), // that's all I need
                containerId: containerId
            })

            return wrapper
        },
    }
})

[Vue warn]: Failed to mount component: template or render function not defined.
  (found in MyCustomChart)

Body:
I played around with this a bit and I misled @thanksd above with my recommendation on what to extend. One way that works is this:

import VueChart from "vue-charts";

Vue.use(VueChart);

const BaseChart = Vue.options.components["vue-chart"];
const CustomChart = BaseChart.extend({
  methods:{
    buildWrapper (chartType, dataTable, options, containerId) {
      let wrapper = new google.visualization.ChartWrapper({
        chartType: chartType,
        dataTable: dataTable,
        options: google.charts.Bar.convertOptions(options),
        containerId: containerId
      })

      return wrapper
    }
  }
});

Vue.component("custom-chart", CustomChart);

Further Explanation

As I thought, extending VueChart either through Vue's native extend, or through lodash, will not achieve the expected results. The result of importing VueChart is a plugin definition. Both lodash and Vue will happily accept that as an object to extend, but neither will result in a Vue component. Trying to use the result of either will result in the error mentioned in the question, "template or render function not defined". That error is absolutely true; extending VueChart extends an install function with a single method.

So how do you get the object to extend? vue-charts doesn't expose it. The install just calls Vue.component('vue-chart', Chart).

Fortunately, Vue makes the globally installed components through Vue.options.components. By extending Vue.options.components["vue-chart"] we get a proper Vue component definition.

Finally, I was surprised google was not available to @RegularEverydayNormalGuy. It has to be available; vue-chart uses it. But he's right, it's not available immediately. vue-chart loads the script asynchronously. Again, the plugin unfortunately doesn't make it available to you in any way, it just initializes itself after it's asynchronously loaded. There are ways to work around that, but at that point you should just probably submit a pull request.

Original Answer

options is a property on vue-chart. Why not just pass in the converted options?

new Vue({
    data:{
        convertedOptions: google.charts.Bar.convertOptions({<my options>})
    }
})

And in the template

<vue-chart :options="convertedOptions"></vue-chart>


问:
How to take a "num/den" type input in Java?
I want to take in input like this:

Enter a fraction(num/den):

I thought this would work,

```<code>Scanner input = new Scanner(System.in);
System.out.print("Enter a fraction(num/den):");
numerator = input.nextInt();
input.next();
denominator = input.nextInt();
</code>```

and divide symbol will be disregarded.

答:
Try splitting it into two parts using String#split.

```<code>String s = input.readLine();
String array[] = s.split("/");
double num = Double.parseDouble(array[0]);
double den = Double.parseDouble(array[1]);
</code>```

Now, just divide the two variables.

Body:
I want to take in input like this:

Enter a fraction(num/den):

I thought this would work,

Scanner input = new Scanner(System.in);
System.out.print("Enter a fraction(num/den):");
numerator = input.nextInt();
input.next();
denominator = input.nextInt();

and divide symbol will be disregarded.

Body:
Try splitting it into two parts using String#split.

String s = input.readLine();
String array[] = s.split("/");
double num = Double.parseDouble(array[0]);
double den = Double.parseDouble(array[1]);

Now, just divide the two variables.


问:
SQL LEFT JOIN/INNER JOIN different result
I don't know what I'm doing wrong but can't found solution for my statement. Current statement is:

```<code>SELECT tb1.RestaurantID, Title, City
FROM Restaurant AS tb1
LEFT JOIN RestaurantLunch AS tb2 ON tb1.RestaurantID = tb2.RestaurantID
WHERE (MATCH (tb1.Title, tb1.City) AGAINST ('+string1* +string2*' IN BOOLEAN MODE)) LIMIT 5;
</code>```

Offcourse i would also like to search for string in other table(tb2) and i change my statement to:

```<code>SELECT tb1.RestaurantID, Title, City
FROM Restaurant AS tb1
LEFT JOIN RestaurantLunch AS tb2 ON tb1.RestaurantID = tb2.RestaurantID
WHERE (MATCH (tb1.Title, tb1.City, tb2.Text) AGAINST ('+string1* +string2*' IN BOOLEAN MODE)) LIMIT 5;
</code>```

After submit i get different result, which is not logic at all. Why is that?

答:
When you do a left join and create a condition in where section to the table on right (tb2 in your case) this left join became a plain join with that condition. That is why you are getting different results.

Try this way:

```<code>SELECT tb1.RestaurantID, Title, City
  FROM Restaurant AS tb1
        LEFT JOIN RestaurantLunch AS tb2
                  ON tb1.RestaurantID = tb2.RestaurantID
                     AND (MATCH (tb2.Text)
                              AGAINST ('+string1* +string2*' IN BOOLEAN MODE))
 WHERE (MATCH (tb1.Title, tb1.City)
            AGAINST ('+string1* +string2*' IN BOOLEAN MODE)) LIMIT 5;
</code>```

Body:
I don't know what I'm doing wrong but can't found solution for my statement. Current statement is:

SELECT tb1.RestaurantID, Title, City
FROM Restaurant AS tb1
LEFT JOIN RestaurantLunch AS tb2 ON tb1.RestaurantID = tb2.RestaurantID
WHERE (MATCH (tb1.Title, tb1.City) AGAINST ('+string1* +string2*' IN BOOLEAN MODE)) LIMIT 5;

Offcourse i would also like to search for string in other table(tb2) and i change my statement to:

SELECT tb1.RestaurantID, Title, City
FROM Restaurant AS tb1
LEFT JOIN RestaurantLunch AS tb2 ON tb1.RestaurantID = tb2.RestaurantID
WHERE (MATCH (tb1.Title, tb1.City, tb2.Text) AGAINST ('+string1* +string2*' IN BOOLEAN MODE)) LIMIT 5;

After submit i get different result, which is not logic at all. Why is that?

Body:
When you do a left join and create a condition in where section to the table on right (tb2 in your case) this left join became a plain join with that condition. That is why you are getting different results.

Try this way:

SELECT tb1.RestaurantID, Title, City
  FROM Restaurant AS tb1
        LEFT JOIN RestaurantLunch AS tb2
                  ON tb1.RestaurantID = tb2.RestaurantID
                     AND (MATCH (tb2.Text)
                              AGAINST ('+string1* +string2*' IN BOOLEAN MODE))
 WHERE (MATCH (tb1.Title, tb1.City)
            AGAINST ('+string1* +string2*' IN BOOLEAN MODE)) LIMIT 5;


问:
Guard not unwrapping optional
I'm trying to process a JSON object, using a guard statement to unwrap it and cast to the type I want, but the value is still being saved as an optional.

```<code>guard let json = try? JSONSerialization.jsonObject(with: data) as? [String:Any] else {
    break
}

let result = json["Result"]
// Error: Value of optional type '[String:Any]?' not unwrapped
</code>```

Am I missing something here?

答:
```<code>try? JSONSerialization.jsonObject(with: data) as? [String:Any]
</code>```

is interpreted as

```<code>try? (JSONSerialization.jsonObject(with: data) as? [String:Any])
</code>```

which makes it a "double optional" of type [String:Any]??.
The optional binding removes only one level, so that json has
the type [String:Any]?

The problem is solved by setting parentheses:

```<code>guard let json = (try? JSONSerialization.jsonObject(with: data)) as? [String:Any] else {
    break
}
</code>```

And just for fun: Another (less obvious?, obfuscating?) solution is to
use pattern matching with a double optional pattern:

```<code>guard case let json?? = try? JSONSerialization.jsonObject(with: data) as? [String:Any] else {
    break
}
</code>```

Title: Guard not unwrapping optional

Body:
I'm trying to process a JSON object, using a guard statement to unwrap it and cast to the type I want, but the value is still being saved as an optional.

guard let json = try? JSONSerialization.jsonObject(with: data) as? [String:Any] else {
    break
}

let result = json["Result"]
// Error: Value of optional type '[String:Any]?' not unwrapped

Am I missing something here?

Body:
try? JSONSerialization.jsonObject(with: data) as? [String:Any]

is interpreted as

try? (JSONSerialization.jsonObject(with: data) as? [String:Any])

which makes it a "double optional" of type [String:Any]??.
The optional binding removes only one level, so that json has
the type [String:Any]?

The problem is solved by setting parentheses:

guard let json = (try? JSONSerialization.jsonObject(with: data)) as? [String:Any] else {
    break
}

And just for fun: Another (less obvious?, obfuscating?) solution is to
use pattern matching with a double optional pattern:

guard case let json?? = try? JSONSerialization.jsonObject(with: data) as? [String:Any] else {
    break
}


问:
sorting objects with multiple conditions
I'm currently trying to sort an array of objects that is being returned in my reducer. I want to sort the apps based off of their name that is being returned, and where there are still currently some names that are null I want to list the null names at the end. Currently when I try to add an additional condition I am getting an error Cannot read property 'toLowerCase' of null which i'm expecting null items just need to move them to the end.

```<code>// Actions
export const FETCH_MYAPPS_PENDING = 'widgets/apps/FETCH_PENDING';
export const FETCH_MYAPPS_FULFILLED = 'widgets/apps/FETCH_FULFILLED';

// Reducer
const appsSort = (a, b) => {
  if (a.name != null && b.name != null) {
   if (a.name.toLowerCase() > b.name.toLowerCase()) return 1;
   if (a.name.toLowerCase() < b.name.toLowerCase()) return -1;
  }
  return 0;
};

export default function reducer(state = { data: [], pending: false }, action) {
switch (action.type) {
case FETCH_MYAPPS_FULFILLED:
  return {
    data: action.apps.sort(appsSort),
    pending: false,
    retrievedAt: Date.now(),
  };
case FETCH_MYAPPS_PENDING:
  return {
    ...state,
    pending: true,
  };
default:
  return state;
 }
}
</code>```

答:
My attempt. It's slightly redundant towards the top, but it makes sense to have null checks before you check the names.

    const appsSort = (a, b) => {
      //null checks
      if (a.name === null && b.name === null) return 0;
      if (a.name === null && b.name !== null) return 1;
      if (b.name === null && a.name !== null) return -1;
      //check for lowercase
      if (a.name.toLowerCase() > b.name.toLowerCase()) return 1;
      if (a.name.toLowerCase() < b.name.toLowerCase()) return -1;
      return 0;
    };

    var obj = [
      {name: 'apples', id: 1},
      {name: null, id: 3},
      {name: 'Banana', id: 2},
      {name: null, id: 4}
    ]

    obj.sort(appsSort);

    console.log(obj)```

Body:
I'm currently trying to sort an array of objects that is being returned in my reducer. I want to sort the apps based off of their name that is being returned, and where there are still currently some names that are null I want to list the null names at the end. Currently when I try to add an additional condition I am getting an error Cannot read property 'toLowerCase' of null which i'm expecting null items just need to move them to the end.

// Actions
export const FETCH_MYAPPS_PENDING = 'widgets/apps/FETCH_PENDING';
export const FETCH_MYAPPS_FULFILLED = 'widgets/apps/FETCH_FULFILLED';

// Reducer
const appsSort = (a, b) => {
  if (a.name != null && b.name != null) {
   if (a.name.toLowerCase() > b.name.toLowerCase()) return 1;
   if (a.name.toLowerCase() < b.name.toLowerCase()) return -1;
  }
  return 0;
};

export default function reducer(state = { data: [], pending: false }, action) {
switch (action.type) {
case FETCH_MYAPPS_FULFILLED:
  return {
    data: action.apps.sort(appsSort),
    pending: false,
    retrievedAt: Date.now(),
  };
case FETCH_MYAPPS_PENDING:
  return {
    ...state,
    pending: true,
  };
default:
  return state;
 }
}


问:
How to learn CouchDB API without documentation?
Since CouchDB has very few API documentation (at least I can not find it), I would like to inspect some JavaScript objecs myself. What is the best way to do this?

For example, show functions recive the request object req as argument. How to find out, which properties (cookies, requested url,...) this request object precisely has?

答: Have a look at the CouchOne Docs and the open CouchDB Book.</p>

ContentLicense: CC BY-SA 2.5


问:
ApplicationScoped Managed bean atribute not being refreshedin datatable
Well, I have a OLD jsp system using JavaEE5

One of the screens shows the user a BIG datatable that is called from the database each view, because the tables is HUGE and they need all the data it takes 15 miutus to render

In order to solve the problem I choose to use an AplicationScoped ManagedBean that stores the list in a List myList and it is acceded for the backing bean of the user interface

So far, so good, it work.

When the application adds another ecord I aded a line in the procedure to add the new object to the list myList.add(Object)

When I debug the application the object is correctly put in the list (the list grows by one record)

But when I logoff and log in, or refresh the grid the list is not renewed.

Maybe is not the best solution (using an application scoped bean)

I am using JSF 2.2, Primefaces 6.0 and javaEE5

My aPPScoped bean (getters and setters not shown to save space)

```<code>@ManagedBean(eager=true)
@ApplicationScoped
public class AplicationBean {

   public static List<Object> myList = new ArrayList();

   @PostConstruct
   public void iniciar() {
        myList=  est.getALLDATA();
   }
}
</code>```

The backing bean

```<code>@ManagedBean
@SessionScoped
public class jsfbean {

    private List<Object> myList= new ArrayList();

    @PostConstruct
    public void init(){
        this.myList =  AplicationBean.getALLDATA();
    }
}
</code>```

the grid

```<code>                     paginatorTemplate="{CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {Exporters}"
                     paginator="true"
                     rows="40"
                     >
</code>```

After the Insert an object P y created and then I add that in the list as this:

```<code>System.out.println("size"+AplicationBean.getMylist().size()); //(size is 1000)
AplicationBean.getMyList().add(P);

System.out.println("NEW SIZE"+AplicationBean.getMyList().size());
</code>```

答:
EJB and static attributes is a bad idea. I propose the following structure.

```<code>@Startup
@Singleton
public class ApplicationBean {

    public List<Object> myList = new ArrayList();

    @PostConstruct
    public void iniciar()
    {
        myList=  est.getALLDATA();
    }

    public void add(Object o){
        this.myList.add(o);
    }

}

@ManagedBean
@SessionScoped
public class SessionBean {

    @EJB
    ApplicationBean applicationBean;

    List<Object> list;

    // Cached for the session
    public List<Object> getObjectList(){
        if(list==null){
            list = applicationBean.getObjectList();
        }
        return list;
    }

    // Always fresh data
    public List<Object> getObjectListNotCached(){
        return applicationBean.getObjectList();
    }
    ...
}
</code>```

The list attributes live as long as the session.
But this design have also problems, by example, what is after you update the base list? And the solutions isn't thread safe.

Body:
Well, I have a OLD jsp system using JavaEE5

One of the screens shows the user a BIG datatable that is called from the database each view, because the tables is HUGE and they need all the data it takes 15 miutus to render

In order to solve the problem I choose to use an AplicationScoped ManagedBean that stores the list in a List myList and it is acceded for the backing bean of the user interface

So far, so good, it work.

When the application adds another ecord I aded a line in the procedure to add the new object to the list myList.add(Object)

When I debug the application the object is correctly put in the list (the list grows by one record)

But when I logoff and log in, or refresh the grid the list is not renewed.

Maybe is not the best solution (using an application scoped bean)

I am using JSF 2.2, Primefaces 6.0 and javaEE5

My aPPScoped bean (getters and setters not shown to save space)

@ManagedBean(eager=true)
@ApplicationScoped
public class AplicationBean {

   public static List<Object> myList = new ArrayList();

   @PostConstruct
   public void iniciar() {
        myList=  est.getALLDATA();
   }
}

The backing bean

@ManagedBean
@SessionScoped
public class jsfbean {

    private List<Object> myList= new ArrayList();

    @PostConstruct
    public void init(){
        this.myList =  AplicationBean.getALLDATA();
    }
}

the grid

                     paginatorTemplate="{CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {Exporters}"
                     paginator="true"
                     rows="40"
                     >

After the Insert an object P y created and then I add that in the list as this:

System.out.println("size"+AplicationBean.getMylist().size()); //(size is 1000)
AplicationBean.getMyList().add(P);

System.out.println("NEW SIZE"+AplicationBean.getMyList().size());

Body:
EJB and static attributes is a bad idea. I propose the following structure.

@Startup
@Singleton
public class ApplicationBean {

    public List<Object> myList = new ArrayList();

    @PostConstruct
    public void iniciar()
    {
        myList=  est.getALLDATA();
    }

    public void add(Object o){
        this.myList.add(o);
    }

}

@ManagedBean
@SessionScoped
public class SessionBean {

    @EJB
    ApplicationBean applicationBean;

    List<Object> list;

    // Cached for the session
    public List<Object> getObjectList(){
        if(list==null){
            list = applicationBean.getObjectList();
        }
        return list;
    }

    // Always fresh data
    public List<Object> getObjectListNotCached(){
        return applicationBean.getObjectList();
    }
    ...
}

The list attributes live as long as the session.
But this design have also problems, by example, what is after you update the base list? And the solutions isn't thread safe.


问:
How to mockup in Java POJO calling JAX-RS Web service with @OPTIONS annotation
I would like the use in RESTful WS @OPTION annotation to use it as a Help. I found one snippet on http://www.programcreek.com/java-api-examples/index.php?source_dir=AIDR-master/aidr-output/src/main/java/qa/qcri/aidr/output/getdata/GetBufferedAIDRData.java. There is snippet of code:

```<code> @OPTIONS
 @Produces(MediaType.APPLICATION_JSON)
 @Path("/channel/filter/{crisisCode}")
 public Response getBufferedAIDRDataPostFilter(@PathParam("crisisCode") String channelCode,
   @QueryParam("callback") String callbackName,
   @DefaultValue("1000") @QueryParam("count") int count) {
  return Response.ok()
    .allow("POST", "GET", "PUT", "UPDATE", "OPTIONS", "HEAD")
    .header("Access-Control-Allow-Origin", "*")
    .header("Access-Control-Allow-Credentials", "true")
    .header("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, OPTIONS, HEAD")
    .header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With")
    .build();
 }
</code>```

But I didnt't found, how to call and obtain content of header etc. from definition above on the client side.

答:
Since the snippet that you posted in a JaxRS REST API implementation, my solution provided below is also a JaxRS Client implementation.
This can be implemented in any language using any framework though depending on your requirements.

Following is a code snippet to invoke the OPTIONS request on a REST API endpoint and process its response.

```<code>import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import java.util.List;
import java.util.Map;

public class RestClient {

    public static void main(String[] args) {

        Client client = ClientBuilder.newBuilder().build();
        WebTarget target = client.target("https://<api-base-url>/<resource-path>");

        Response response = target.request().options();
        Map<String, List<String>> headerMap = response.getStringHeaders();

        for (String key : headerMap.keySet()) {
            List<String> values = headerMap.get(key);
            for (String value : values) {
                // The header and its corresponding value can be processed as per the case.
            }
        }

        // This will return a list of all supported HTTP Methods (GET, POST, PUT, ..., etc)
        List<String> httpMethods = headerMap.get("Allow");

        for (String method : httpMethods) {
            if ("GET".equals(method)) {
                // Do something
            }

            if ("POST".equals(method)) {
                // Do something
            }
            ...
            ...
        }

        response.close();
    }
}
</code>```

There are may more methods exposed by the Response class which can be explored as needed for your implementation.

Body:
I would like the use in RESTful WS @OPTION annotation to use it as a Help. I found one snippet on http://www.programcreek.com/java-api-examples/index.php?source_dir=AIDR-master/aidr-output/src/main/java/qa/qcri/aidr/output/getdata/GetBufferedAIDRData.java. There is snippet of code:

 @OPTIONS
 @Produces(MediaType.APPLICATION_JSON)
 @Path("/channel/filter/{crisisCode}")
 public Response getBufferedAIDRDataPostFilter(@PathParam("crisisCode") String channelCode,
   @QueryParam("callback") String callbackName,
   @DefaultValue("1000") @QueryParam("count") int count) {
  return Response.ok()
    .allow("POST", "GET", "PUT", "UPDATE", "OPTIONS", "HEAD")
    .header("Access-Control-Allow-Origin", "*")
    .header("Access-Control-Allow-Credentials", "true")
    .header("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, OPTIONS, HEAD")
    .header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With")
    .build();
 }

But I didnt't found, how to call and obtain content of header etc. from definition above on the client side.

Body:
Since the snippet that you posted in a JaxRS REST API implementation, my solution provided below is also a JaxRS Client implementation.
This can be implemented in any language using any framework though depending on your requirements.

Following is a code snippet to invoke the OPTIONS request on a REST API endpoint and process its response.

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import java.util.List;
import java.util.Map;

public class RestClient {

    public static void main(String[] args) {

        Client client = ClientBuilder.newBuilder().build();
        WebTarget target = client.target("https://<api-base-url>/<resource-path>");

        Response response = target.request().options();
        Map<String, List<String>> headerMap = response.getStringHeaders();

        for (String key : headerMap.keySet()) {
            List<String> values = headerMap.get(key);
            for (String value : values) {
                // The header and its corresponding value can be processed as per the case.
            }
        }

        // This will return a list of all supported HTTP Methods (GET, POST, PUT, ..., etc)
        List<String> httpMethods = headerMap.get("Allow");

        for (String method : httpMethods) {
            if ("GET".equals(method)) {
                // Do something
            }

            if ("POST".equals(method)) {
                // Do something
            }
            ...
            ...
        }

        response.close();
    }
}

There are may more methods exposed by the Response class which can be explored as needed for your implementation.


问:
Github Emoji tag to Emojies
I've collected description of some github repos. Some of the have github emoji tags. I would like to convert them to emoji images.

I have the following,

```<code>var innerContent = "<li><span class='link'><a href='" + JSON.parse(response)[i].html_url + "' target='_blank'>" + JSON.parse(response)[i].name + "<span> - " + String(JSON.parse(response)[i].description).replace(/(:.+:)/g, 'Do Something here') + "</span>" + "<br/></a></span></li>"
</code>```

How can I convert them images? I know that I can get their images from Github API. But I am not able to remove : from the description.

答:
There are many emojify libraries on GitHub, which converts emoji tag to emoji character. Like this the official GitHub one https://github.com/github/gemoji and this one https://github.com/mrowa44/emojify.

You need to find one suiting your case.

Technically, regex can do this, but it will be a huge regex to cover all the emojis.

Title: Github Emoji tag to Emojies

Body:
I've collected description of some github repos. Some of the have github emoji tags. I would like to convert them to emoji images.

I have the following,

var innerContent = "
" + JSON.parse(response)[i].name + " - " + String(JSON.parse(response)[i].description).replace(/(:.+:)/g, 'Do Something here') + "" + "

"

How can I convert them images? I know that I can get their images from Github API. But I am not able to remove : from the description.


问:
Calculated fields in Laravel using Query Builder
I've been working in a Laravel Project and I want to know how can I show a calculated field in a blade view? I want to retrieve some information from an invoice and a Total calculated field.

I would like to get this result, but using Eloquent ORM. The query is this:

```<code>SELECT
    invoiceheader.id,
    invoiceheader.customerlastname,
    invoiceheader.customerfirstname,
    invoiceheader.customernit,
    invoicedetail.productid,
    invoicedetail.quantity,
    invoicedetail.saleprice,
    (quantity * saleprice) as Total
FROM invoiceheader
INNER JOIN invoicedetail
    ON invoiceheader.id = invoicedetail.invoiceid
</code>```

Thank you so much in advance.

答:
You can use laravels DB::raw(), which injects the string to the query, like so:

Laravel raw expressions

```<code>InvoiceHeader::select('invoiceheader.id', 'invoiceheader.customerlastname',
   'invoiceheader.customerfirstname', 'invoiceheader.customernit',
   'invoicedetail.productid', 'invoicedetail.quantity',
   'invoicedetail.saleprice', DB::raw('(quantity * saleprice) as Total'))
->join('invoicedetail', 'invoiceheader.id', '=', 'invoicedetail.invoiceid')
->get();
</code>```

Note: make sure to import use DB; on the top of the page

Body:
I've been working in a Laravel Project and I want to know how can I show a calculated field in a blade view? I want to retrieve some information from an invoice and a Total calculated field.

I would like to get this result, but using Eloquent ORM. The query is this:

SELECT
    invoiceheader.id,
    invoiceheader.customerlastname,
    invoiceheader.customerfirstname,
    invoiceheader.customernit,
    invoicedetail.productid,
    invoicedetail.quantity,
    invoicedetail.saleprice,
    (quantity * saleprice) as Total
FROM invoiceheader
INNER JOIN invoicedetail
    ON invoiceheader.id = invoicedetail.invoiceid

Thank you so much in advance.

Body:
You can use laravels DB::raw(), which injects the string to the query, like so:

Laravel raw expressions

InvoiceHeader::select('invoiceheader.id', 'invoiceheader.customerlastname',
   'invoiceheader.customerfirstname', 'invoiceheader.customernit',
   'invoicedetail.productid', 'invoicedetail.quantity',
   'invoicedetail.saleprice', DB::raw('(quantity * saleprice) as Total'))
->join('invoicedetail', 'invoiceheader.id', '=', 'invoicedetail.invoiceid')
->get();

Note: make sure to import use DB; on the top of the page


问:
Grabbing list of paths contained in a file and passing them to Perl as an argument
Hi everyone i need a single line  command and scenario is like as below.

a file named path.txt has a path  "C:/Windows/system32/main.txt"
and that main.txt has some unicode characters.

i need to remove the unicode characters from main.txt and used below command and it worked.

```<code>perl -i.bak -pe 's/[^[:ascii:]]//g' main.txt
</code>```

so above command removed all unicode (non ascii) characters from the file.

But i need a command where the data in path.txt keeps changing it points to different file for different intervals.

i tried the below command in order to achieve it but it failed.

```<code>cat path.txt | perl -i.bak -pe 's/[^[:ascii:]]//g' &1
</code>```

could some one help me in completing the test by modifying the above script or providing with new command.

i want to achieve this only by command and not using scripts.

答:
I guess path.txt has the list of files that you want to modify.  You can use a read loop like this:

```<code>#!/bin/bash
while read -r file; do
  perl -i.bak -pe 's/[^[:ascii:]]//g' "$file"
done < path.txt
</code>```

If you using Bash, you can run the above loop from command line, without the need to store the code in a script.

You can also achieve the same results with a Bash array as well (needs Bash 4 and above):

```<code>readarray -t files < paths.txt  # store all the paths from paths.txt in files array
perl -i.bak -pe 's/[^[:ascii:]]//g' "${files[@]}" # pass the array content to perl
</code>```

You can do this in one line with

```<code>perl -i.bak -pe 's/[^[:ascii:]]//g' "$(< paths.txt)"
</code>```

but that is strongly discouraged because of the word splitting and globbing issues.

Body:
Hi everyone i need a single line  command and scenario is like as below.

a file named path.txt has a path  "C:/Windows/system32/main.txt"
and that main.txt has some unicode characters.

i need to remove the unicode characters from main.txt and used below command and it worked.

perl -i.bak -pe 's/[^[:ascii:]]//g' main.txt

so above command removed all unicode (non ascii) characters from the file.

But i need a command where the data in path.txt keeps changing it points to different file for different intervals.

i tried the below command in order to achieve it but it failed.

cat path.txt | perl -i.bak -pe 's/[^[:ascii:]]//g' &1

could some one help me in completing the test by modifying the above script or providing with new command.

i want to achieve this only by command and not using scripts.

Body:
I guess path.txt has the list of files that you want to modify.  You can use a read loop like this:

#!/bin/bash
while read -r file; do
  perl -i.bak -pe 's/[^[:ascii:]]//g' "$file"
done < path.txt

If you using Bash, you can run the above loop from command line, without the need to store the code in a script.

You can also achieve the same results with a Bash array as well (needs Bash 4 and above):

readarray -t files < paths.txt  # store all the paths from paths.txt in files array
perl -i.bak -pe 's/[^[:ascii:]]//g' "${files[@]}" # pass the array content to perl

You can do this in one line with

perl -i.bak -pe 's/[^[:ascii:]]//g' "$(< paths.txt)"

but that is strongly discouraged because of the word splitting and globbing issues.


问:
SVN checking out new files from repo that others have added
If I have checked out a SVN repo and work on it locally all is fine.  If my colleague also checks out the repo and they can also work on it fine.

When my colleague creates a new file, adds it to the repo and commits it.  Running update does not automatically download the additional file.

Deleting the local repo and checking it out a second gets the additional file.

What command do I need to execute to ensure that when running update it does get any additional files?

I am using the Tortoise shell and subversion SVN.   The end application is an electronics cad package, Altium, so we normally only use checkout, commit and update commands.

答:
Update tortoise to latest version.  To fix your existing working copy, instead of choosing "Update", choose "Update to revision"  and change the depth to "Fully recursive".  You'll have to do this once on the latest version, or you could stay on the version you have now and do it every time...

Source


问:
How Do I Keep the Last Hovered Item Active?
So, I got this code the works like Tabs opening the content when each tab is hovered. So when the user removed the mouse, they close automatically. How would I go to make the content of the last hovered Tab to remain open?

body {
  position: relative;
  width: 50%;
  margin: 10% auto;
}

.tab {
  width: 20%;
  height: 50px;
  background: gray;
  cursor: pointer;
}

.content {
  background: #ccc;
  display: none;
}

.clear {
  clear: both;
  height: 10px;
}

#tab1:hover+#content1,
#tab2:hover+#content2,
#tab3:hover+#content3 {
  display: block;
}

#tab1 {
  position: absolute;
  top: 0;
  left: 0;
}

#tab2 {
  position: absolute;
  top: 60px;
  left: 0;
}

#tab3 {
  position: absolute;
  top: 120px;
  left: 0;
}

#content1 {
  position: absolute;
  top: 0;
  left: 20%;
}

#content2 {
  position: absolute;
  top: 0;
  left: 20%;
}

#content3 {
  position: absolute;
  top: 0;
  left: 20%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div id="tab1" class="tab">
    Tab 1
  </div>
  <div id="content1" class="content">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer in ullamcorper nisi. Cras sit amet ligula aliquet justo pellentesque dignissim. Integer ullamcorper felis magna, a porttitor urna molestie vitae. Fusce vitae pharetra tortor. Integer non
    ex quis ex tristique laoreet. Nulla interdum porta sem, eu eleifend felis elementum eu. Integer vehicula nibh metus, id eleifend diam vestibulum ac. Curabitur malesuada mauris nec libero vulputate, id interdum tortor tempor. Cras tincidunt arcu at
    orci ullamcorper faucibus id et metus. Vestibulum semper condimentum volutpat. Nullam a ex ante. Cras laoreet felis dictum lectus elementum, non tempor ex feugiat.
  </div>
  <div id="tab2" class="tab">
    Tab 2
  </div>
  <div id="content2" class="content">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer in ullamcorper nisi. Cras sit amet ligula aliquet justo pellentesque dignissim. Integer ullamcorper felis magna, a porttitor urna molestie vitae. Fusce vitae pharetra tortor. Integer non
    ex quis ex tristique laoreet. Nulla interdum porta sem, eu eleifend felis elementum eu. Integer vehicula nibh metus, id eleifend diam vestibulum ac. Curabitur malesuada mauris nec libero vulputate, id interdum tortor tempor. Cras tincidunt arcu at
    orci ullamcorper faucibus id et metus. Vestibulum semper condimentum volutpat. Nullam a ex ante. Cras laoreet felis dictum lectus elementum, non tempor ex feugiat.
  </div>
  <div id="tab3" class="tab">
    Tab 3
  </div>
  <div id="content3" class="content">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer in ullamcorper nisi. Cras sit amet ligula aliquet justo pellentesque dignissim. Integer ullamcorper felis magna, a porttitor urna molestie vitae. Fusce vitae pharetra tortor. Integer non
    ex quis ex tristique laoreet. Nulla interdum porta sem, eu eleifend felis elementum eu. Integer vehicula nibh metus, id eleifend diam vestibulum ac. Curabitur malesuada mauris nec libero vulputate, id interdum tortor tempor. Cras tincidunt arcu at
    orci ullamcorper faucibus id et metus. Vestibulum semper condimentum volutpat. Nullam a ex ante. Cras laoreet felis dictum lectus elementum, non tempor ex feugiat.
  </div>
</body></code>```

答:
Add a .last class when you hover a tab, and only remove it when another tab is hovered.

var $tabs = $('.tab');
$tabs.hover(function() {
  $tabs.not($(this)).removeClass('last');
  $(this).addClass('last');
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  position: relative;
  width: 50%;
  margin: 10% auto;
}

.tab {
  width: 20%;
  height: 50px;
  background: gray;
  cursor: pointer;
}

.content {
  background: #ccc;
  display: none;
}

.clear {
  clear: both;
  height: 10px;
}

#tab1:hover+#content1,
#tab2:hover+#content2,
#tab3:hover+#content3,
.last + .content {
  display: block;
}

#tab1 {
  position: absolute;
  top: 0;
  left: 0;
}

#tab2 {
  position: absolute;
  top: 60px;
  left: 0;
}

#tab3 {
  position: absolute;
  top: 120px;
  left: 0;
}

#content1 {
  position: absolute;
  top: 0;
  left: 20%;
}

#content2 {
  position: absolute;
  top: 0;
  left: 20%;
}

#content3 {
  position: absolute;
  top: 0;
  left: 20%;
}</code>```

  Tab 1

  1

  Tab 2

  2

  Tab 3

  3

```

Body:
So, I got this code the works like Tabs opening the content when each tab is hovered. So when the user removed the mouse, they close automatically. How would I go to make the content of the last hovered Tab to remain open?

body {
  position: relative;
  width: 50%;
  margin: 10% auto;
}

.tab {
  width: 20%;
  height: 50px;
  background: gray;
  cursor: pointer;
}

.content {
  background: #ccc;
  display: none;
}

.clear {
  clear: both;
  height: 10px;
}

#tab1:hover+#content1,
#tab2:hover+#content2,
#tab3:hover+#content3 {
  display: block;
}

#tab1 {
  position: absolute;
  top: 0;
  left: 0;
}

#tab2 {
  position: absolute;
  top: 60px;
  left: 0;
}

#tab3 {
  position: absolute;
  top: 120px;
  left: 0;
}

#content1 {
  position: absolute;
  top: 0;
  left: 20%;
}

#content2 {
  position: absolute;
  top: 0;
  left: 20%;
}

#content3 {
  position: absolute;
  top: 0;
  left: 20%;
}

    Tab 1

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer in ullamcorper nisi. Cras sit amet ligula aliquet justo pellentesque dignissim. Integer ullamcorper felis magna, a porttitor urna molestie vitae. Fusce vitae pharetra tortor. Integer non
    ex quis ex tristique laoreet. Nulla interdum porta sem, eu eleifend felis elementum eu. Integer vehicula nibh metus, id eleifend diam vestibulum ac. Curabitur malesuada mauris nec libero vulputate, id interdum tortor tempor. Cras tincidunt arcu at
    orci ullamcorper faucibus id et metus. Vestibulum semper condimentum volutpat. Nullam a ex ante. Cras laoreet felis dictum lectus elementum, non tempor ex feugiat.

    Tab 2

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer in ullamcorper nisi. Cras sit amet ligula aliquet justo pellentesque dignissim. Integer ullamcorper felis magna, a porttitor urna molestie vitae. Fusce vitae pharetra tortor. Integer non
    ex quis ex tristique laoreet. Nulla interdum porta sem, eu eleifend felis elementum eu. Integer vehicula nibh metus, id eleifend diam vestibulum ac. Curabitur malesuada mauris nec libero vulputate, id interdum tortor tempor. Cras tincidunt arcu at
    orci ullamcorper faucibus id et metus. Vestibulum semper condimentum volutpat. Nullam a ex ante. Cras laoreet felis dictum lectus elementum, non tempor ex feugiat.

    Tab 3

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer in ullamcorper nisi. Cras sit amet ligula aliquet justo pellentesque dignissim. Integer ullamcorper felis magna, a porttitor urna molestie vitae. Fusce vitae pharetra tortor. Integer non
    ex quis ex tristique laoreet. Nulla interdum porta sem, eu eleifend felis elementum eu. Integer vehicula nibh metus, id eleifend diam vestibulum ac. Curabitur malesuada mauris nec libero vulputate, id interdum tortor tempor. Cras tincidunt arcu at
    orci ullamcorper faucibus id et metus. Vestibulum semper condimentum volutpat. Nullam a ex ante. Cras laoreet felis dictum lectus elementum, non tempor ex feugiat.

Body:
Add a .last class when you hover a tab, and only remove it when another tab is hovered.

var $tabs = $('.tab');
$tabs.hover(function() {
  $tabs.not($(this)).removeClass('last');
  $(this).addClass('last');
})

body {
  position: relative;
  width: 50%;
  margin: 10% auto;
}

.tab {
  width: 20%;
  height: 50px;
  background: gray;
  cursor: pointer;
}

.content {
  background: #ccc;
  display: none;
}

.clear {
  clear: both;
  height: 10px;
}

#tab1:hover+#content1,
#tab2:hover+#content2,
#tab3:hover+#content3,
.last + .content {
  display: block;
}

#tab1 {
  position: absolute;
  top: 0;
  left: 0;
}

#tab2 {
  position: absolute;
  top: 60px;
  left: 0;
}

#tab3 {
  position: absolute;
  top: 120px;
  left: 0;
}

#content1 {
  position: absolute;
  top: 0;
  left: 20%;
}

#content2 {
  position: absolute;
  top: 0;
  left: 20%;
}

#content3 {
  position: absolute;
  top: 0;
  left: 20%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tab1" class="tab">
  Tab 1
</div>
<div id="content1" class="content">
  1
</div>
<div id="tab2" class="tab">
  Tab 2
</div>
<div id="content2" class="content">
  2
</div>
<div id="tab3" class="tab">
  Tab 3
</div>
<div id="content3" class="content">
  3
</div>


问:
If and else condition inside success in ajax
As the title says I want to run the if and else inside the success condition in Ajax, For example after running the Ajax and sees that there is a record it will go to success then inside the success it must look for the "if statement"  and display the alert inside the "if statement" if the statement is true but instead it always display the "else statement" with the alert('no') inside of it, even if there is a record, Thank you

```<code><script>
function renderAttendees(id)
        {
            ///$("#attendeesContent").empty();
            var dataString = { "id": id };
            $.ajax({
                type: 'POST',
                url: server+'webservice/crm/viewAttendeesDetails',
                data: dataString,
                dataType: 'json',
                contentType: "application/x-www-form-urlencoded",
                cache: true,
                success: function(data)
                {
                 if($.trim(data) === 'error')
                 {
                  alert('yes');
                 }
                 else
                 {
                  alert('no');
                 }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown)                    {
                    console.log("Error connecting to server. " + XMLHttpRequest + ", " + textStatus +", "+ errorThrown);

                }
</script>
</code>```

//My Controller Code

```<code> public function viewAttendeesDetails()
{
  header('Access-Control-Allow-Origin: *');
  header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');

  $data = array();
  $id = $_POST['id'];

  $AttendeesDetails = $this->model->GetAttendeesDetail($id);
  if($row = $AttendeesDetails->fetch(PDO::FETCH_ASSOC))
  {
    $this->tp->DBToHTMLAll($row, $data);
  }

    echo json_encode($data);
    exit;
}

?>
</code>```

//My Model Code

db->prepare("SELECT * FROM crm_contact_list WHERE id = :AttendId");

           $stmt->bindParam(":AttendId", $id);
           $stmt->execute();
           return $stmt;
        }
        catch (Exception $e)
        {
            return $e->getMessage();

            return $stmt;
        }
        return;
    }
?>

//Here is the result of console.log(data);

Object
email:"kyle@localhost.com"
full_name:"Test kim"
id:"1"
interest:"Test"
number:"123456"
position:"Prog"
venueID:"1"

答:
I would return from your controller something like

{status: 'success', data: myArrayWithFoundData}

so when you receive the ajax response you could do a json_decode, and check the status.

So in you controller you would have

```<code>if($row = $AttendeesDetails->fetch(PDO::FETCH_ASSOC))
      {
          $this->tp->DBToHTMLAll($row, $data);
          $rsp_data = {status: 'success', data: $data};
      }else{
          $rsp_data = {status: 'error', data: null};
      }
echo json_encode($resp_data);
</code>```

Something like that, so in the ajax response you would do a

```<code>var a = JSON.parse(data);
</code>```

and check the a.status for error

Body:
As the title says I want to run the if and else inside the success condition in Ajax, For example after running the Ajax and sees that there is a record it will go to success then inside the success it must look for the "if statement"  and display the alert inside the "if statement" if the statement is true but instead it always display the "else statement" with the alert('no') inside of it, even if there is a record, Thank you

//My Controller Code

 public function viewAttendeesDetails()
{
  header('Access-Control-Allow-Origin: *');
  header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');

  $data = array();
  $id = $_POST['id'];

  $AttendeesDetails = $this->model->GetAttendeesDetail($id);
  if($row = $AttendeesDetails->fetch(PDO::FETCH_ASSOC))
  {
    $this->tp->DBToHTMLAll($row, $data);
  }

    echo json_encode($data);
    exit;
}

?>

//My Model Code

db->prepare("SELECT * FROM crm_contact_list WHERE id = :AttendId");

           $stmt->bindParam(":AttendId", $id);
           $stmt->execute();
           return $stmt;
        }
        catch (Exception $e)
        {
            return $e->getMessage();

            return $stmt;
        }
        return;
    }
?>

//Here is the result of console.log(data);

Object
email:"kyle@localhost.com"
full_name:"Test kim"
id:"1"
interest:"Test"
number:"123456"
position:"Prog"
venueID:"1"

Body:
I would return from your controller something like

{status: 'success', data: myArrayWithFoundData}

so when you receive the ajax response you could do a json_decode, and check the status.

So in you controller you would have

if($row = $AttendeesDetails->fetch(PDO::FETCH_ASSOC))
      {
          $this->tp->DBToHTMLAll($row, $data);
          $rsp_data = {status: 'success', data: $data};
      }else{
          $rsp_data = {status: 'error', data: null};
      }
echo json_encode($resp_data);

Something like that, so in the ajax response you would do a

var a = JSON.parse(data);

and check the a.status for error


问:
What is the best way to care about assertion fail in Eigen C++?
I have a question what the best way is to care about assertion fail in Eigen C++.
I know if there were wrong matrix calculation, Eigen stops program by assertion fail.
For example,

```<code>MatrixXf a(2, 2);
MatrixXf b(1, 1);
MatrixXf c = a + b;
</code>```

In this case, the size of matrix a and b is difference, so assertion fails occurs.
Then what is the best way to avoid it ?

I can avoid, if I checked matrix size at every time before calculating.

```<code>MatrixXf a(2, 2);
MatrixXf b(1, 1);
MatrixXf c;
if (a.cols() == b.cols() && a.rows() == b.rows()) {
    c = a + b;
}
</code>```

But I think it's not smart way, checking each calculation.

Is there any better way to check it ?
Could I catch exception by using try-catch ? Or does Eigen have any check function ?

答:
You can predefine the eigen_assert macro to throw an exception instead of asserting. E.g.:

```<code>#define eigen_assert(X) do { if(!(X)) throw std::runtime_error(#X); } while(false);
// make sure Eigen is not included before your define:
#include <Eigen/Core>
</code>```

But as @n.m. pointed out, you should rather fix your logic error, i.e., you should not try to add matrices if you are not sure that their sizes match.

Body:
I have a question what the best way is to care about assertion fail in Eigen C++.
I know if there were wrong matrix calculation, Eigen stops program by assertion fail.
For example,

MatrixXf a(2, 2);
MatrixXf b(1, 1);
MatrixXf c = a + b;

In this case, the size of matrix a and b is difference, so assertion fails occurs.
Then what is the best way to avoid it ?

I can avoid, if I checked matrix size at every time before calculating.

MatrixXf a(2, 2);
MatrixXf b(1, 1);
MatrixXf c;
if (a.cols() == b.cols() && a.rows() == b.rows()) {
    c = a + b;
}

But I think it's not smart way, checking each calculation.

Is there any better way to check it ?
Could I catch exception by using try-catch ? Or does Eigen have any check function ?

Body:
You can predefine the eigen_assert macro to throw an exception instead of asserting. E.g.:

#define eigen_assert(X) do { if(!(X)) throw std::runtime_error(#X); } while(false);
// make sure Eigen is not included before your define:
#include <Eigen/Core>

But as @n.m. pointed out, you should rather fix your logic error, i.e., you should not try to add matrices if you are not sure that their sizes match.


问:
How to display just the group name of groups user is member of in powershell
So I have the following script but it lists the full name of the AD group. (e.g. CN=GroupName,OU=OUName,DC=DomainName,DC=com) How do I specify only the group's name, so that it lists only the name itself. The part after CN=. I tried $group.Name but no such luck.

```<code>Import-Module ActiveDirectory
$userlist = Get-Content "C:\Scripts\US_User_List.txt"

foreach ($username in $userlist) {
    $grplist = (Get-ADUser $username –Properties MemberOf | Select-Object MemberOf).MemberOf
    foreach ($group in $grplist) {
        write-host $group
    }
}
</code>```

Also as a second question is there some way to filter based on what the group name starts with?

答:
You can look it up with Get-ADGroup

```<code>Import-Module ActiveDirectory
$userlist = Get-Content "C:\Scripts\US_User_List.txt"

foreach ($username in $userlist) {
    $grplist = (Get-ADUser $username –Properties MemberOf).MemberOf
    foreach ($group in $grplist) {
        (Get-ADGroup $group).name
    }
}
</code>```

For the second part, you can use a Where-Object/? filter.

```<code>$grplist = (Get-ADUser $username –Properties MemberOf).MemberOf | ? {$_ -like "CN=StartsWithExample*"}
</code>```

Body:
So I have the following script but it lists the full name of the AD group. (e.g. CN=GroupName,OU=OUName,DC=DomainName,DC=com) How do I specify only the group's name, so that it lists only the name itself. The part after CN=. I tried $group.Name but no such luck.

Import-Module ActiveDirectory
$userlist = Get-Content "C:\Scripts\US_User_List.txt"

foreach ($username in $userlist) {
    $grplist = (Get-ADUser $username –Properties MemberOf | Select-Object MemberOf).MemberOf
    foreach ($group in $grplist) {
        write-host $group
    }
}

Also as a second question is there some way to filter based on what the group name starts with?

Body:
You can look it up with Get-ADGroup

Import-Module ActiveDirectory
$userlist = Get-Content "C:\Scripts\US_User_List.txt"

foreach ($username in $userlist) {
    $grplist = (Get-ADUser $username –Properties MemberOf).MemberOf
    foreach ($group in $grplist) {
        (Get-ADGroup $group).name
    }
}

For the second part, you can use a Where-Object/? filter.

$grplist = (Get-ADUser $username –Properties MemberOf).MemberOf | ? {$_ -like "CN=StartsWithExample*"}


问:
regex match file with multiple extension
I have several strings like this

XYZ_TEST_2017.txt

ASD_TEST_2017.txt.tmp

I need to extract only those strings ending with .txt

So I'm using this regex:

```<code>[A-Z]{3}_TEST_[0-9]{4}.txt
</code>```

However I still get the strings with multiple extensions like the second one (.txt.tmp)

See my regex demo.

How can I handle it?

答:
To have your regex match everything up to the end, append an "end-of-text marker" ($) to your pattern like this:

```<code>[A-Z]{3}_TEST_[0-9]{4}\.txt$
</code>```

As you may have noticed, I also escaped the dot, otherwise this filename would match as well:

```<code>SOM_TEST_1234Etxt
</code>```

The dot (.) would match any character (depending on your flags, even newline and carriage return), in this case, the E before txt.

Body:
I have several strings like this

XYZ_TEST_2017.txt

ASD_TEST_2017.txt.tmp

I need to extract only those strings ending with .txt

So I'm using this regex:

[A-Z]{3}_TEST_[0-9]{4}.txt

However I still get the strings with multiple extensions like the second one (.txt.tmp)

See my regex demo.

How can I handle it?

Body:
To have your regex match everything up to the end, append an "end-of-text marker" ($) to your pattern like this:

[A-Z]{3}_TEST_[0-9]{4}\.txt$

As you may have noticed, I also escaped the dot, otherwise this filename would match as well:

SOM_TEST_1234Etxt

The dot (.) would match any character (depending on your flags, even newline and carriage return), in this case, the E before txt.


问:
Perforce (p4v) - Simple create/push/merge branch for git developer

Background

I come from a git background, and have been using it for years. Prior to that, I used subversion for several years, and had to occasionally use CVS.

Question

I'm starting on a large perforce project and want to create a feature branch so that:

I don't impact trunk/mainline/master.

I can backup my work at end-of-day to the remote server.

With a tool like git, this was pretty easy:

```<code>git checkout -b my_branch
# make some edits
git add -u
git commit
git push
</code>```

How do I accomplish the same (more or less) in perforce, using the command-line interface? Apparently I have to first use p4 branch to "create a branch spec", and then use p4 integrate to "open files for merging or branching", but couldn't find any concrete examples that make sense.

Thank you.

答:
If you are unable to use DVCS and your site uses streams, have a look at Task Streams:
  https://www.perforce.com/perforce/doc.current/manuals/p4guide/chapter.streams.html#streams.types.task

You can use these to work on bug-fixes or features and they are semi-private.

Once you are happy with the work it can be merged back to the main stream/branch.

They even work with non-streams depots.b

Body:
Background

I come from a git background, and have been using it for years. Prior to that, I used subversion for several years, and had to occasionally use CVS.

Question

I'm starting on a large perforce project and want to create a feature branch so that:

I don't impact trunk/mainline/master.

I can backup my work at end-of-day to the remote server.

With a tool like git, this was pretty easy:

git checkout -b my_branch
# make some edits
git add -u
git commit
git push

How do I accomplish the same (more or less) in perforce, using the command-line interface? Apparently I have to first use p4 branch to "create a branch spec", and then use p4 integrate to "open files for merging or branching", but couldn't find any concrete examples that make sense.

Thank you.


问:
AtomicIncrement using CompareAndSwap
Not homework, studying for an exam.

My best attempt at a problem statement:

Assume a thread calls AtomicIncrement, passing a pointer to a shared integer variable. It is not specified whether or not another thread will modify this variable, but it is possible. This implementation of Compare and swap returns 1 on successful swap and 0 on failure (old != value)

```<code>void AtomicIncrement(int *value, int amount) {
    do { int old = *value; } // save old value
    while (CompareAndSwap(value, old, old + amount) == 0);
}
</code>```

Question:

I am not really understanding what's going on here.

Is the reason why the code does " int old = *value; " because another thread could change (*value) between the do {} and while condition check?

My textbook (page 10) says "repeatedly tries to update value to the new amount" but I don't see how *value could be anything other than the original value passed into AtomicIncrement() by a calling thread, I must be missing something. The confusion comes from the fact that CompareAndSwap should be an atomic instruction to begin with, so there is no chance for *value to be changed during the "call" to CompareAndSwap.

答:
Without the temporary variable or loop, you'd be running CompareAndSwap(value, *value, *value + amount). This is not atomic. There's a sequence point between evaluating a function's arguments (with no determine sequencing between evaluating each argument) and the function call itself.

This function must load *value to pass as an argument to CompareAndSwap. It must also load *value for use in the expression *value + account, also to pass as an argument.

Problem 1. Between the time when this thread loads *value and when it calls CompareAndSwap, *value could have been changed by another thread. That's why the loop is necessary.

Problem 2. There is no guarantee that the compiler emits only a single load of *value. It would be legal for it to load *value once, and add amount to a copy of it locally, but it would also be legal for it to load *value twice, once for use in the second argument and one for use in the third. If that happens, it's possible that another thread could have changed *value in between those loads. That's why the temporary variable is used, although that still doesn't actually guarantee a single load without a memory barrier.

Title: AtomicIncrement using CompareAndSwap

Body:
Not homework, studying for an exam.

My best attempt at a problem statement:

Assume a thread calls AtomicIncrement, passing a pointer to a shared integer variable. It is not specified whether or not another thread will modify this variable, but it is possible. This implementation of Compare and swap returns 1 on successful swap and 0 on failure (old != value)

void AtomicIncrement(int *value, int amount) {
    do { int old = *value; } // save old value
    while (CompareAndSwap(value, old, old + amount) == 0);
}

Question:

I am not really understanding what's going on here.

Is the reason why the code does " int old = *value; " because another thread could change (*value) between the do {} and while condition check?

My textbook (page 10) says "repeatedly tries to update value to the new amount" but I don't see how *value could be anything other than the original value passed into AtomicIncrement() by a calling thread, I must be missing something. The confusion comes from the fact that CompareAndSwap should be an atomic instruction to begin with, so there is no chance for *value to be changed during the "call" to CompareAndSwap.


问:
resizing multidimensional vector
How to resize multidimensional vector such as:

```<code>  vector <vector <vector <custom_type> > > array;
</code>```

For example, I need array[3][5][10]?

答:
see also Boost.MultiArray

Boost.MultiArray provides a generic N-dimensional array concept definition and common implementations of that interface.

Title: resizing multidimensional vector

Body:
How to resize multidimensional vector such as:

  vector <vector <vector <custom_type> > > array;

For example, I need array[3][5][10]?


问:
how parse console on travis-ci and find the number of occured word
I use github + travis-ci for continuous integration. I have a maven project with lot of tests. I want parse all console and find a special word by xpath. If this word is present x times my job is OK else my job is KO.

how parse console on travis-ci and find the number of occured word by xpath or other method?

答:
Given log.txt as input, and desired input lines like these:

```<code>Tests run: 10, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 7.957 sec - in TestSuite
Tests run: 10, Failures: 0, Errors: 0, Skipped: 0
</code>```

Assuming we just want to test the "10", this might do:

```<code>n=5
awk -F '[ ,]*' '/^Tests run:/ \
               { if ($3>'$n') { print "OK found " $3 ; x=$3 ; exit} } \
               END {if (x<'$n') print "Fail."} ' log.txt
</code>```

Output:

```<code>OK found 10
</code>```

Body:
Given log.txt as input, and desired input lines like these:

Tests run: 10, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 7.957 sec - in TestSuite
Tests run: 10, Failures: 0, Errors: 0, Skipped: 0

Assuming we just want to test the "10", this might do:

n=5
awk -F '[ ,]*' '/^Tests run:/ \
               { if ($3>'$n') { print "OK found " $3 ; x=$3 ; exit} } \
               END {if (x<'$n') print "Fail."} ' log.txt

Output:

OK found 10


问:
reCaptcha shared between forms
I have a page where I generate a list of forms based on a database with PHP. I want to implement reCaptcha to prevent bots in the forms. I have two options.

To generate a reCaptcha element for each form. The problem is that I would have to generate programatically a function for each one of the forms submission, so I can use it on reCaptcha data-callback, something like

 where formid would be inserted through the PHP iteration.

What I though is if I have the option to create a single reCaptcha element that I could share between all forms. But although I tried a lot, I couldn't get to do this. The question is: is there a form to share a submition function between forms?

答:
Give every submit button a common classname and do the following. This is just a pseudo code sort of thing.</p>

```<code><button class="btn1 handleClick someOtherClasses">Submit 1</button>
<button class="btn2 handleClick someOtherClasses">Submit 2</button>
<button class="btn3 handleClick someOtherClasses">Submit 3</button>

<script>
var elems = document.getElementsByClassName('handleClick');
for(i=0;i<elems;i++) {
  elems[i].addEventListener('click', handle, false);
}

function handle(e) {
   var buttonClicked = e.target;
   // verify captcha
   if(!captchaGood) {
      return false;
   }
}
</script>
</code>```

Title: reCaptcha shared between forms

Body:
Give every submit button a common classname and do the following. This is just a pseudo code sort of thing.

<button class="btn1 handleClick someOtherClasses">Submit 1</button>
<button class="btn2 handleClick someOtherClasses">Submit 2</button>
<button class="btn3 handleClick someOtherClasses">Submit 3</button>

<script>
var elems = document.getElementsByClassName('handleClick');
for(i=0;i<elems;i++) {
  elems[i].addEventListener('click', handle, false);
}

function handle(e) {
   var buttonClicked = e.target;
   // verify captcha
   if(!captchaGood) {
      return false;
   }
}
</script>


问:
makefile with debug option
I am kinda rookie in makefile field but trying to write makefile that would go in two modes: normal mode make outputing executable file called say bingo depending on some files and a mode make debug outputing   executable file called bingo.debug that shall be compiled with debug option. I'm trying to use target variable with the following result:

```<code>PROGRAM = bingo
SUFIX = .debug
CC = gcc
CFLAGS = -Wall -O2
DEBUG = -g -D DEBUG

all: $(PROGRAM)
debug: CFLAGS += $(DEBUG)
debug: PROGRAM += $(SUFIX)
debug: all

file1.o: file1.c file1.h
    $(CC) -c $(CFLAGS) -o $@ $<

file2.o: file2.c file2.h
    $(CC) -c $(CFLAGS) -o $@ $<

$(PROGRAM).o: $(PROGRAM).c
    $(CC) -c $(CFLAGS) -o $@ $<

$(PROGRAM): file1.o file2.o ($PROGRAM).o
    $(CC) -o $@ $^

.PHONY: all clean

clean:
    rm -rf $(PROGRAM) *.o
</code>```

It looks like make debug correctly compiles the file with debug flags but it does not change the file name (i.e. both modes outputs the same bingo file). Any help much appriciated!

答:
You cannot use target-specific variables in targets.  The documentation is very clear that they are available only in recipes.

In general it's problematic to do things this way, because make has no idea which objects were built with debug and which weren't.  If you forget to do a complete clean and/or run make the wrong way then you'll get a mix of different object files: some compiled with debug and some not.

Instead, you should put your debug object files in a different directory from your non-debug object files so you don't have to worry about that.

Title: makefile with debug option

Body:
I am kinda rookie in makefile field but trying to write makefile that would go in two modes: normal mode make outputing executable file called say bingo depending on some files and a mode make debug outputing   executable file called bingo.debug that shall be compiled with debug option. I'm trying to use target variable with the following result:

PROGRAM = bingo
SUFIX = .debug
CC = gcc
CFLAGS = -Wall -O2
DEBUG = -g -D DEBUG

all: $(PROGRAM)
debug: CFLAGS += $(DEBUG)
debug: PROGRAM += $(SUFIX)
debug: all

file1.o: file1.c file1.h
    $(CC) -c $(CFLAGS) -o $@ $<

file2.o: file2.c file2.h
    $(CC) -c $(CFLAGS) -o $@ $<

$(PROGRAM).o: $(PROGRAM).c
    $(CC) -c $(CFLAGS) -o $@ $<

$(PROGRAM): file1.o file2.o ($PROGRAM).o
    $(CC) -o $@ $^

.PHONY: all clean

clean:
    rm -rf $(PROGRAM) *.o

It looks like make debug correctly compiles the file with debug flags but it does not change the file name (i.e. both modes outputs the same bingo file). Any help much appriciated!


问:
Call JavaScript function in another file using JavaScript object
I want to call one JavaScript function from another JavaScript file

below is my code:

```<code> var exJS = function () {
     function coolMethod() {
       alert("hello suraj");
     }
  }
</code>```

when I call the function

```<code>var myClass = new exJS();
myClass.coolMethod();
</code>```

Why do I get the error that coolmethod is not defined?

答:
For it to be accessible externally, you need to define the child function using the this reference of the parent function, like this:

var exJS = function() {
  this.coolMethod = function() {
    alert("hello suraj");
  }
}

var myClass = new exJS();
myClass.coolMethod();```

Body:
I want to call one JavaScript function from another JavaScript file

below is my code:

 var exJS = function () {
     function coolMethod() {
       alert("hello suraj");
     }
  }

when I call the function

var myClass = new exJS();
myClass.coolMethod();

Why do I get the error that coolmethod is not defined?


问:
Cakephp uploading an image, the tmp_name file is getting deleted before the script is done?
I have an html form that allows the user to browse for a file to upload.

In the cakephp script, I use move_uploaded_file() to upload the file from the temp location to a location on the server.

```<code>move_uploaded_file($file['tmp_name'], $url);
</code>```

However, the file seems to be disappearing before the upload is complete:

move_uploaded_file(/img/recipes/5.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory [APP\app_controller.php, line 97]

move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\Windows\Temp\phpF25A.tmp' to '/img/recipes/5.jpg' [APP\app_controller.php, line 97]

答:
I think it's telling you that the target does not exist. /img/recipes/5.jpg is hardly a valid directory to upload to on UNIX system, it's probably completely invalid on Windows.

You'll need to build an absolute path to save the file in (like C:\webroot\project\images\foo.jpg) instead of a URL.

Body:
I have an html form that allows the user to browse for a file to upload.

In the cakephp script, I use move_uploaded_file() to upload the file from the temp location to a location on the server.

move_uploaded_file($file['tmp_name'], $url);

However, the file seems to be disappearing before the upload is complete:

move_uploaded_file(/img/recipes/5.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory [APP\app_controller.php, line 97]

move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\Windows\Temp\phpF25A.tmp' to '/img/recipes/5.jpg' [APP\app_controller.php, line 97]


问:
Form controls are undefined
My form is made in the following way:

<form #form="ngForm" novalidate (ngSubmit)="register(form);">

        First Name
        <input #firstname="ngModel" type="text" name="firstname" maxlength="30" pattern="[a-zA-Z ]*" required ngModel>

            Please enter your name

             Max length is 30 characters

             Only letters are allowed

        <button type="submit" class="btn-register">Register</button>

</form>
```

<p>I'm getting the following error:</p>

```EXCEPTION: Uncaught (in promise): Error: Error in http://localhost:3000/app/register/register.component.html:7:17 caused by: Cannot read property 'touched' of undefined
Error: Error in http://localhost:3000/app/register/register.component.html:7:17 caused by: Cannot read property 'touched' of undefined
```

It seems like it cannot find my controls. However, when I try to print out form.controls, I get the following result:

So in this case, it finds them just fine. What is the problem here? I've made something similar in the past that worked.

UPDATE: I found out that instead of for example form.controls.firstname.touched, I have to access them using just firstname.touched. I just don't understand why, because I have another file in the same project where I'm using forms which has been made in the exact same way, but in that one I was using form.controls.*. I guess you can use firstname.touched if you have declared a template reference variable, but I don't know under which circumstances you can use form.controls.*.

答:
Another way of doing validation is :

```<code><form #form="ngForm" novalidate (ngSubmit)="register(form);">
    <div class="registerinput">
        <label for="firstname">First Name</label>
        <input #firstname="ngModel" type="text" name="firstname" maxlength="30" pattern="[a-zA-Z ]*" required ngModel>
        <div [hidden]="!firstname.touched && !firstname.errors?.required" class="alert-danger">
            Please enter your name
        </div>
        <div [hidden]="!firstname.touched && !firstname.errors?.maxlength" class="alert-danger">
             Max length is 30 characters
        </div>
        <div [hidden]="!firstname.touched && !firstname.errors?.pattern" class="alert-danger">
             Only letters are allowed
        </div>
    </div>
    <div class="registerinput">
        <button type="submit" class="btn-register" [disabled]='!form.valid'>Register</button>
    </div>
</form>
</code>```

This one is pretty simple and easy way of doing.

Title: Form controls are undefined

Body:
My form is made in the following way:

<form #form="ngForm" novalidate (ngSubmit)="register(form);">

        First Name
        <input #firstname="ngModel" type="text" name="firstname" maxlength="30" pattern="[a-zA-Z ]*" required ngModel>

            Please enter your name

             Max length is 30 characters

             Only letters are allowed

        <button type="submit" class="btn-register">Register</button>

</form>

I'm getting the following error:

EXCEPTION: Uncaught (in promise): Error: Error in http://localhost:3000/app/register/register.component.html:7:17 caused by: Cannot read property 'touched' of undefined
Error: Error in http://localhost:3000/app/register/register.component.html:7:17 caused by: Cannot read property 'touched' of undefined

It seems like it cannot find my controls. However, when I try to print out form.controls, I get the following result:

So in this case, it finds them just fine. What is the problem here? I've made something similar in the past that worked.

UPDATE: I found out that instead of for example form.controls.firstname.touched, I have to access them using just firstname.touched. I just don't understand why, because I have another file in the same project where I'm using forms which has been made in the exact same way, but in that one I was using form.controls.*. I guess you can use firstname.touched if you have declared a template reference variable, but I don't know under which circumstances you can use form.controls.*.

Body:
Another way of doing validation is :

<form #form="ngForm" novalidate (ngSubmit)="register(form);">
    <div class="registerinput">
        <label for="firstname">First Name</label>
        <input #firstname="ngModel" type="text" name="firstname" maxlength="30" pattern="[a-zA-Z ]*" required ngModel>
        <div [hidden]="!firstname.touched && !firstname.errors?.required" class="alert-danger">
            Please enter your name
        </div>
        <div [hidden]="!firstname.touched && !firstname.errors?.maxlength" class="alert-danger">
             Max length is 30 characters
        </div>
        <div [hidden]="!firstname.touched && !firstname.errors?.pattern" class="alert-danger">
             Only letters are allowed
        </div>
    </div>
    <div class="registerinput">
        <button type="submit" class="btn-register" [disabled]='!form.valid'>Register</button>
    </div>
</form>

This one is pretty simple and easy way of doing.


问:
How to _directly_ COPY files to "Program Files (x86)" folder in a Windows container?
My question is specific to the Docker for Windows. The version I'm using is 17.03.1-ce-rc1-win3 (10625) on Windows 10 Pro x64.

I'm trying to create an image where I need to copy a folder into the "Program Files (x86)" folder in my container based on microsoft/dotnet-framework:3.5 image.

My Dockerfile is super simple ...

```<code># escape=`

FROM microsoft/dotnet-framework:3.5

COPY ["TestFolder", "C:\Program Files (x86)\TestFolder"]
</code>```

Running docker build, I ended up

```<code>Step 2/2 : COPY ["TestFolder", "C:\Program Files (x86)\TestFolder"]
GetFileAttributesEx C:\Program: The system cannot find the file specified.
</code>```

It looks like docker mistakenly stopped parsing the dest name at the first whitespace. However this COPY ["<src>", ..."<dest>"] is exactly the syntax for dealing the paths containing whitespace (ref). And if I use any other folder name like "Foo Bar" instead, the COPY instruction just works as expected.

So my current workaround is using WORKDIR first to change the working dir to the "Prog...(x86)" folder and then doing COPY without explicitly giving the full dest path.

But I really would like to know if I did anything wrong with the COPY instruction.

Thanks.

答:
You have to use double backslashes inside the braces

```<code>FROM microsoft/windowsservercore

COPY ["test.txt", "c:\\program files\\WindowsPowerShell\\Modules\\test.txt"]
</code>```

It is interpreted as JSON.

Body:
My question is specific to the Docker for Windows. The version I'm using is 17.03.1-ce-rc1-win3 (10625) on Windows 10 Pro x64.

I'm trying to create an image where I need to copy a folder into the "Program Files (x86)" folder in my container based on microsoft/dotnet-framework:3.5 image.

My Dockerfile is super simple ...

# escape=`

FROM microsoft/dotnet-framework:3.5

COPY ["TestFolder", "C:\Program Files (x86)\TestFolder"]

Running docker build, I ended up

Step 2/2 : COPY ["TestFolder", "C:\Program Files (x86)\TestFolder"]
GetFileAttributesEx C:\Program: The system cannot find the file specified.

It looks like docker mistakenly stopped parsing the dest name at the first whitespace. However this COPY ["<src>", ..."<dest>"] is exactly the syntax for dealing the paths containing whitespace (ref). And if I use any other folder name like "Foo Bar" instead, the COPY instruction just works as expected.

So my current workaround is using WORKDIR first to change the working dir to the "Prog...(x86)" folder and then doing COPY without explicitly giving the full dest path.

But I really would like to know if I did anything wrong with the COPY instruction.

Thanks.

Body:
You have to use double backslashes inside the braces

FROM microsoft/windowsservercore

COPY ["test.txt", "c:\\program files\\WindowsPowerShell\\Modules\\test.txt"]

It is interpreted as JSON.


答:
You can use mouseover, mouseleave events, .filter(), .next(), .not(), .show(), .hide()

$("[id^=tab]").on({"mouseover": function() {
  $("[id^=content]").hide().filter($(this).next()).show()
}, "mouseleave": function() {
  $("[id^=content]").not($(this).next()).hide()
}})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  position: relative;
  width: 50%;
  margin: 10% auto;
}

.tab {
  width: 20%;
  height: 50px;
  background: gray;
  cursor: pointer;
}

.content {
  background: #ccc;
  display: none;
}

.clear {
  clear: both;
  height: 10px;
}
/*
#tab1:hover+#content1,
#tab2:hover+#content2,
#tab3:hover+#content3 {
  display: block;
}
*/
#tab1 {
  position: absolute;
  top: 0;
  left: 0;
}

#tab2 {
  position: absolute;
  top: 60px;
  left: 0;
}

#tab3 {
  position: absolute;
  top: 120px;
  left: 0;
}

#content1 {
  position: absolute;
  top: 0;
  left: 20%;
}

#content2 {
  position: absolute;
  top: 0;
  left: 20%;
}

#content3 {
  position: absolute;
  top: 0;
  left: 20%;
}</code>```

    Tab 1

    1

    Tab 2

    2

    Tab 3

    3

```

Title: How Do I Keep the Last Hovered Item Active?

Body:
So, I got this code the works like Tabs opening the content when each tab is hovered. So when the user removed the mouse, they close automatically. How would I go to make the content of the last hovered Tab to remain open?

body {
  position: relative;
  width: 50%;
  margin: 10% auto;
}

.tab {
  width: 20%;
  height: 50px;
  background: gray;
  cursor: pointer;
}

.content {
  background: #ccc;
  display: none;
}

.clear {
  clear: both;
  height: 10px;
}

#tab1:hover+#content1,
#tab2:hover+#content2,
#tab3:hover+#content3 {
  display: block;
}

#tab1 {
  position: absolute;
  top: 0;
  left: 0;
}

#tab2 {
  position: absolute;
  top: 60px;
  left: 0;
}

#tab3 {
  position: absolute;
  top: 120px;
  left: 0;
}

#content1 {
  position: absolute;
  top: 0;
  left: 20%;
}

#content2 {
  position: absolute;
  top: 0;
  left: 20%;
}

#content3 {
  position: absolute;
  top: 0;
  left: 20%;
}

    Tab 1

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer in ullamcorper nisi. Cras sit amet ligula aliquet justo pellentesque dignissim. Integer ullamcorper felis magna, a porttitor urna molestie vitae. Fusce vitae pharetra tortor. Integer non
    ex quis ex tristique laoreet. Nulla interdum porta sem, eu eleifend felis elementum eu. Integer vehicula nibh metus, id eleifend diam vestibulum ac. Curabitur malesuada mauris nec libero vulputate, id interdum tortor tempor. Cras tincidunt arcu at
    orci ullamcorper faucibus id et metus. Vestibulum semper condimentum volutpat. Nullam a ex ante. Cras laoreet felis dictum lectus elementum, non tempor ex feugiat.

    Tab 2

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer in ullamcorper nisi. Cras sit amet ligula aliquet justo pellentesque dignissim. Integer ullamcorper felis magna, a porttitor urna molestie vitae. Fusce vitae pharetra tortor. Integer non
    ex quis ex tristique laoreet. Nulla interdum porta sem, eu eleifend felis elementum eu. Integer vehicula nibh metus, id eleifend diam vestibulum ac. Curabitur malesuada mauris nec libero vulputate, id interdum tortor tempor. Cras tincidunt arcu at
    orci ullamcorper faucibus id et metus. Vestibulum semper condimentum volutpat. Nullam a ex ante. Cras laoreet felis dictum lectus elementum, non tempor ex feugiat.

    Tab 3

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer in ullamcorper nisi. Cras sit amet ligula aliquet justo pellentesque dignissim. Integer ullamcorper felis magna, a porttitor urna molestie vitae. Fusce vitae pharetra tortor. Integer non
    ex quis ex tristique laoreet. Nulla interdum porta sem, eu eleifend felis elementum eu. Integer vehicula nibh metus, id eleifend diam vestibulum ac. Curabitur malesuada mauris nec libero vulputate, id interdum tortor tempor. Cras tincidunt arcu at
    orci ullamcorper faucibus id et metus. Vestibulum semper condimentum volutpat. Nullam a ex ante. Cras laoreet felis dictum lectus elementum, non tempor ex feugiat.

Body:
You can use mouseover, mouseleave events, .filter(), .next(), .not(), .show(), .hide()

$("[id^=tab]").on({"mouseover": function() {
  $("[id^=content]").hide().filter($(this).next()).show()
}, "mouseleave": function() {
  $("[id^=content]").not($(this).next()).hide()
}})

body {
  position: relative;
  width: 50%;
  margin: 10% auto;
}

.tab {
  width: 20%;
  height: 50px;
  background: gray;
  cursor: pointer;
}

.content {
  background: #ccc;
  display: none;
}

.clear {
  clear: both;
  height: 10px;
}
/*
#tab1:hover+#content1,
#tab2:hover+#content2,
#tab3:hover+#content3 {
  display: block;
}
*/
#tab1 {
  position: absolute;
  top: 0;
  left: 0;
}

#tab2 {
  position: absolute;
  top: 60px;
  left: 0;
}

#tab3 {
  position: absolute;
  top: 120px;
  left: 0;
}

#content1 {
  position: absolute;
  top: 0;
  left: 20%;
}

#content2 {
  position: absolute;
  top: 0;
  left: 20%;
}

#content3 {
  position: absolute;
  top: 0;
  left: 20%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <div id="tab1" class="tab">
    Tab 1
  </div>
  <div id="content1" class="content">
    1
  </div>
  <div id="tab2" class="tab">
    Tab 2
  </div>
  <div id="content2" class="content">
    2
  </div>
  <div id="tab3" class="tab">
    Tab 3
  </div>
  <div id="content3" class="content">
    3
  </div>
</body>