问:
Implementing a directive in Angular 4 to continuously cycle through background colors on host
I'm learning angular 4 and would like to implement a directive that causes the host element's background colors to cycle through the 7 listed in an array. Ideally I would want it to be continuous. I don't know which life-cycle hooks I need to hook into.
Here's what I have at the moment. Presently, it's not even visibly cycling through the 7 one time, with one-second intervals, as expected through the use of the SetTimeOut. I've commented out the While block as that just hangs the browser.

```<code>import {
  Directive,
  OnInit,
  HostBinding,
  Input
} from '@angular/core';

@Directive({
  selector: '[rainbowize]'
})
export class RainbowizeDirective {
  colors: Array<string>;

 @HostBinding('style.backgroundColor') bgColor: string;

  constructor() {
    this.colors = ['violet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red'];
 }

 ngOnInit(){
   let that = this;
   //while (true) {
      for (let i = 0; i < 7; i++) {
        console.log(that.colors[i]);
        setTimeout(function () {
          that.bgColor = that.colors[i];
        }, 1000)
      }
    //}
  }
}
</code>```

html:

```<code><h2 rainbowize >This is a raibowized paragraph</h2>
</code>```

答:
Here is how you can do it:

```<code>ngOnInit() {
    let that = this;
    let counter = 0;
    let length = this.colors.length;

    upd();

    function upd() {
        that.bgColor = that.colors[counter % length];
        counter++;

        // some stopping condition here
        if (counter < 20) {
            setTimeout(upd, 1000);
        }
    }
}
</code>```

The most important thing here is this line:

```<code>that.colors[counter % length];
</code>```

I use modulo operator %, which returns remainder after the integer division. So it will return:

```<code>0%7 = 0
1%7 = 1
2%7 = 2
...
6%7 = 6
7%7 = 0  <---- here the sequence starts from the beginning
8%7 = 1
</code>```

This will run until the counter variable reaches Number.MAX_SAFE_INTEGER, which is 9007199254740991.

Another simpler approach could be to just do the following:

```<code>    that.bgColor = that.colors[counter % length];
    counter++;

    if (counter === length) {
        counter = 0;
    }
</code>```

Or use a circular linked list.

But I'm still not clear as to where my error lies? Is it because I
  have my code in the ngOnInit's main body as opposed to having it a
  function there?

The problem with your code has nothing to do with Angular. It is that you're adding all callbacks to be executed within a second. And since they are all executed very fast, you only see the latest change to red. You could fix it like this:

```<code>  for (let i = 0; i < 7; i++) {
    console.log(that.colors[i]);
    setTimeout(function () {
      that.bgColor = that.colors[i];
    }, 1000*i+1)
       ^^^^^^ --------------
  }
</code>```

But the problem now remains that your loop executes only once, so each callback is scheduled only once.

Body:
I'm learning angular 4 and would like to implement a directive that causes the host element's background colors to cycle through the 7 listed in an array. Ideally I would want it to be continuous. I don't know which life-cycle hooks I need to hook into.
Here's what I have at the moment. Presently, it's not even visibly cycling through the 7 one time, with one-second intervals, as expected through the use of the SetTimeOut. I've commented out the While block as that just hangs the browser.

import {
  Directive,
  OnInit,
  HostBinding,
  Input
} from '@angular/core';

@Directive({
  selector: '[rainbowize]'
})
export class RainbowizeDirective {
  colors: Array<string>;

 @HostBinding('style.backgroundColor') bgColor: string;

  constructor() {
    this.colors = ['violet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red'];
 }

 ngOnInit(){
   let that = this;
   //while (true) {
      for (let i = 0; i < 7; i++) {
        console.log(that.colors[i]);
        setTimeout(function () {
          that.bgColor = that.colors[i];
        }, 1000)
      }
    //}
  }
}

html:

This is a raibowized paragraph

Body:
Here is how you can do it:

ngOnInit() {
    let that = this;
    let counter = 0;
    let length = this.colors.length;

    upd();

    function upd() {
        that.bgColor = that.colors[counter % length];
        counter++;

        // some stopping condition here
        if (counter < 20) {
            setTimeout(upd, 1000);
        }
    }
}

The most important thing here is this line:

that.colors[counter % length];

I use modulo operator %, which returns remainder after the integer division. So it will return:

0%7 = 0
1%7 = 1
2%7 = 2
...
6%7 = 6
7%7 = 0  <---- here the sequence starts from the beginning
8%7 = 1

This will run until the counter variable reaches Number.MAX_SAFE_INTEGER, which is 9007199254740991.

Another simpler approach could be to just do the following:

    that.bgColor = that.colors[counter % length];
    counter++;

    if (counter === length) {
        counter = 0;
    }

Or use a circular linked list.

But I'm still not clear as to where my error lies? Is it because I
  have my code in the ngOnInit's main body as opposed to having it a
  function there?

The problem with your code has nothing to do with Angular. It is that you're adding all callbacks to be executed within a second. And since they are all executed very fast, you only see the latest change to red. You could fix it like this:

  for (let i = 0; i < 7; i++) {
    console.log(that.colors[i]);
    setTimeout(function () {
      that.bgColor = that.colors[i];
    }, 1000*i+1)
       ^^^^^^ --------------
  }

But the problem now remains that your loop executes only once, so each callback is scheduled only once.


来源: stackexchange

问:
How to select a path tag using jQuery
I have made a Box Plot chart (Highcharts) , Here's my example:

https://jsfiddle.net/hew8nq5u/

My code is:

```<code> Highcharts.chart('container', {

        chart: {
            type: 'boxplot'
        },

        title: {
            text: 'All Patients'
        },

        legend: {
            enabled: true
        },

        xAxis: {
            categories: ['Asia Pacific', 'Europe', 'Latin America', 'North America', 'SWAC'],
            title: {
                text: '      '
            }
        },

        yAxis: {
            title: {
                text: 'Annual Center Volume 2016'
            },
            tickInterval: 5,
            min: 0,
            max: 75
            //plotLines: [{
            //    value: 932,
            //    color: 'red',
            //    width: 1,
            //    label: {
            //        text: 'Theoretical mean: 932',
            //        align: 'center',
            //        style: {
            //            color: 'gray'
            //        }
            //    }
            //}]
        },
        //colors: ['#91e8e1', '#7cb5ec', '#434348', '#90ed7d', '#f7a35c',
        //         '#8085e9', '#f15c80', '#e4d354', '#2b908f', '#f45b5b', ], //updates default colors
        plotOptions: {
            boxplot: {
                fillColor: '#F0F0E0',
                lineWidth: 2,
                upperQuartileColor: 'green',
                lowerQuartileColor: 'green',
                medianColor: '#0C5DA5',
                medianWidth: 3,
                stemColor: '#A63400',
                stemDashStyle: 'solid',
                stemWidth: 1,
                whiskerColor: '#3D9200',
                whiskerLength: '20%',
                whiskerWidth: 3
            }
        },
        series: [{
            name: 'Region Runs',
            showInLegend: false,
            //colorByPoint: true,
            color: 'red',
            data: [
                [2, 4, 18, 43, 53],
                [5, 9, 16.5, 32, 52],
                [1, 3, 6, 11.5, 21],
                [3, 9, 20, 38, 73],
                [1, 2, 8, 16, 20]
            ],
            tooltip: {
                headerFormat: '<em>Experiment No {point.key}</em><br/>'
            }
        },
        {
            name: '75th Percentile',
            type: 'line',
            color: 'red',
            marker: {
                symbol: 'square'
            },

        },
        {
            name: 'Median',
            type: 'line',
            color:'#0C5DA5',
            marker: {
                symbol: 'square'
            },

        },
        {
            name: '25th Percentile',
            type: 'line',
            color: 'red',
            marker: {
                symbol: 'square'
            },

        },
        {
            name: '90th percentile',
            type: 'line',
            color: '#3D9200',
            marker: {
                symbol: 'square'
            },

        },{
            name: '10th percentile',
            type: 'line',
            color: '#3D9200',
            marker: {
                symbol: 'square'
            },

        }//,
        //{
        //    name: 'IQR',
        //    type: 'line',
        //    color: 'brown',
        //    marker: {
        //        symbol: 'square'
        //    },

        //},
        //{
        //    name: 'Outlier',
        //    color: Highcharts.getOptions().colors[0],
        //    type: 'scatter',
        //    data: [ // x, y positions where 0 is the first category
        //        [0, 128],
        //        [1, 161],
        //        [2, 58],
        //        [3, 204],
        //        [4,42]
        //    ],
        //    marker: {
        //        fillColor: 'white',
        //        lineWidth: 1,
        //        lineColor: Highcharts.getOptions().colors[0]
        //    },

        //    tooltip: {
        //        pointFormat: 'Observation: {point.y}'
        //    }

        //}
        ]

    });
</code>```

I would like to have top of the box and bottom of the box in different colors, and also top of the whisker and bottom of the whisker in different colosr for each box (region). But all of the lines in the box are in the same color (red) and top and bottom of the whisker are in the same color (green).

I've found currently it's not possible in highcharts to have box bottom and top in different colors. Same with top and bottom whiskers. Because of that, I want to resolve the issue, by selecting the element "path" (its class) using jQuery and appending html in it to change the color in yellow. Something like this:

```<code>$(".highcharts-boxplot-whisker").append("<path fill='none' class='highcharts-boxplot-whisker' stroke='yellow' stroke-width='3' d='M 59.1 80.5 L 71.9 80.5'></path>");
</code>```

But something is wrong with my selector, nothing happened. How can I do this? Thank you in advance for any help. The tag that I want to select

答:
You can change borders using jQuery css() ! :)

div {
  height: 100px;
  width: 100px;
  margin: 40px auto;
  background-color: pink;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

<script>
  $("div").css("border-top", "5px solid blue");
  $("div").css("border-bottom", "5px solid red");
</script></code>```

ContentLicense: CC BY-SA 3.0

Title: How to select a path tag using jQuery

Body:
I have made a Box Plot chart (Highcharts) , Here's my example:

https://jsfiddle.net/hew8nq5u/

My code is:

 Highcharts.chart('container', {

        chart: {
            type: 'boxplot'
        },

        title: {
            text: 'All Patients'
        },

        legend: {
            enabled: true
        },

        xAxis: {
            categories: ['Asia Pacific', 'Europe', 'Latin America', 'North America', 'SWAC'],
            title: {
                text: '      '
            }
        },

        yAxis: {
            title: {
                text: 'Annual Center Volume 2016'
            },
            tickInterval: 5,
            min: 0,
            max: 75
            //plotLines: [{
            //    value: 932,
            //    color: 'red',
            //    width: 1,
            //    label: {
            //        text: 'Theoretical mean: 932',
            //        align: 'center',
            //        style: {
            //            color: 'gray'
            //        }
            //    }
            //}]
        },
        //colors: ['#91e8e1', '#7cb5ec', '#434348', '#90ed7d', '#f7a35c',
        //         '#8085e9', '#f15c80', '#e4d354', '#2b908f', '#f45b5b', ], //updates default colors
        plotOptions: {
            boxplot: {
                fillColor: '#F0F0E0',
                lineWidth: 2,
                upperQuartileColor: 'green',
                lowerQuartileColor: 'green',
                medianColor: '#0C5DA5',
                medianWidth: 3,
                stemColor: '#A63400',
                stemDashStyle: 'solid',
                stemWidth: 1,
                whiskerColor: '#3D9200',
                whiskerLength: '20%',
                whiskerWidth: 3
            }
        },
        series: [{
            name: 'Region Runs',
            showInLegend: false,
            //colorByPoint: true,
            color: 'red',
            data: [
                [2, 4, 18, 43, 53],
                [5, 9, 16.5, 32, 52],
                [1, 3, 6, 11.5, 21],
                [3, 9, 20, 38, 73],
                [1, 2, 8, 16, 20]
            ],
            tooltip: {
                headerFormat: 'Experiment No {point.key}
'
            }
        },
        {
            name: '75th Percentile',
            type: 'line',
            color: 'red',
            marker: {
                symbol: 'square'
            },

        },
        {
            name: 'Median',
            type: 'line',
            color:'#0C5DA5',
            marker: {
                symbol: 'square'
            },

        },
        {
            name: '25th Percentile',
            type: 'line',
            color: 'red',
            marker: {
                symbol: 'square'
            },

        },
        {
            name: '90th percentile',
            type: 'line',
            color: '#3D9200',
            marker: {
                symbol: 'square'
            },

        },{
            name: '10th percentile',
            type: 'line',
            color: '#3D9200',
            marker: {
                symbol: 'square'
            },

        }//,
        //{
        //    name: 'IQR',
        //    type: 'line',
        //    color: 'brown',
        //    marker: {
        //        symbol: 'square'
        //    },

        //},
        //{
        //    name: 'Outlier',
        //    color: Highcharts.getOptions().colors[0],
        //    type: 'scatter',
        //    data: [ // x, y positions where 0 is the first category
        //        [0, 128],
        //        [1, 161],
        //        [2, 58],
        //        [3, 204],
        //        [4,42]
        //    ],
        //    marker: {
        //        fillColor: 'white',
        //        lineWidth: 1,
        //        lineColor: Highcharts.getOptions().colors[0]
        //    },

        //    tooltip: {
        //        pointFormat: 'Observation: {point.y}'
        //    }

        //}
        ]

    });

I would like to have top of the box and bottom of the box in different colors, and also top of the whisker and bottom of the whisker in different colosr for each box (region). But all of the lines in the box are in the same color (red) and top and bottom of the whisker are in the same color (green).

I've found currently it's not possible in highcharts to have box bottom and top in different colors. Same with top and bottom whiskers. Because of that, I want to resolve the issue, by selecting the element "path" (its class) using jQuery and appending html in it to change the color in yellow. Something like this:

$(".highcharts-boxplot-whisker").append("<path fill='none' class='highcharts-boxplot-whisker' stroke='yellow' stroke-width='3' d='M 59.1 80.5 L 71.9 80.5'></path>");

But something is wrong with my selector, nothing happened. How can I do this? Thank you in advance for any help. The tag that I want to select

Body:
You can change borders using jQuery css() ! :)

div {
  height: 100px;
  width: 100px;
  margin: 40px auto;
  background-color: pink;
}

<div></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

<script>
  $("div").css("border-top", "5px solid blue");
  $("div").css("border-bottom", "5px solid red");
</script>


问:
Determine if MySQL has been started with skip-grant-tables
Is there a way to tell if MySQL has been started with skip-grant-tables within mysql? I can't find anything in show variables

I'd like to add a guard to a startup sql script to prevent UDF functions from trying to be created when they can't be (e.g. the docker startup is running setup, etc)

Thanks

答:
There doesn't seem to exist a variable to determine that.

The following stored procedure can give you some ideas:

DELIMITER //

DROP PROCEDURE IF EXISTS `_`.`skip_grant_tables`//

CREATE PROCEDURE `_`.`skip_grant_tables`(OUT `skip_grant` BOOL)
BEGIN
  DECLARE `skip_grant_text` TEXT;
  DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
  BEGIN
    GET DIAGNOSTICS CONDITION 1 `skip_grant_text` = MESSAGE_TEXT;
  END;
  SET `skip_grant` := 0;
  GRANT SELECT ON *.* TO ''@'';
  IF (`skip_grant_text` REGEXP '--skip-grant-tables option') THEN
    SET `skip_grant` := 1;
  END IF;
END//

DELIMITER ;

mysql> CALL `_`.`skip_grant_tables`(@`skip_grant_tables?`);
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT @`skip_grant_tables?`;
+-----------------------+
| @`skip_grant_tables?` |
+-----------------------+
|                     1 |
+-----------------------+
1 row in set (0.00 sec)
```


问:
Understanding nagios check_ping plugin output
Trying to understand the output of Nagios Plugin check_ping:

```<code>root@debian:/usr/local/nagios/libexec# ./check_ping -H 192.168.234.135 -w 10,1% -c 20,10%
PING CRITICAL - Packet loss = 60%, RTA = 1.26 ms|rta=1.256000ms;10.000000;20.000000;0.000000 pl=60%;1;10;0
root@debian:/usr/local/nagios/libexec#
</code>```

As per the documentation, the performance data is displayed after the pipe '|' symbol. I am trying to understand the fourth parameter for each category / section. In the above example, what does 0.000000 and 0 stands for?

答:
First, here is the official documentation: Nagios Plugin Development Guidelines

Second, the numbers returned from each metric (in order) is:

value [with unit of measurement], warning threshold, critical threshold, minimum value, maximum value

In your case, only the warning,critical and minimum are reported after the perfdata itself. So to answer your question, those numbers are the minimum value (possible).

Body:
Trying to understand the output of Nagios Plugin check_ping:

root@debian:/usr/local/nagios/libexec# ./check_ping -H 192.168.234.135 -w 10,1% -c 20,10%
PING CRITICAL - Packet loss = 60%, RTA = 1.26 ms|rta=1.256000ms;10.000000;20.000000;0.000000 pl=60%;1;10;0
root@debian:/usr/local/nagios/libexec#

As per the documentation, the performance data is displayed after the pipe '|' symbol. I am trying to understand the fourth parameter for each category / section. In the above example, what does 0.000000 and 0 stands for?


问:
De-duplicating redux action logic with high order reducers
I'm refactoring a React/Redux app that has been built to a point where there is a need to de-duplicate a lot of reducer logic. I've looked into High Order Reducers but I'm having a hard time wrapping my head around how I can get them to work for me.

Here's an example:

reducers.js

```<code>import components from './entities/components';
import events from './entities/events';
import items from './entities/items';

const entities = combineReducers({
  components,
  items,
  events,
});
</code>```

I'm using normalizr. Here's an idea of what my state looks like. For this example, just know that events can belong to components or items, but the two are otherwise distinguishable.

```<code>{
  entities: {
    components: {
      component_1: {
        events: ['event_1'],
      },
    },
    items: {
      item_1: {
        events: ['event_2'],
      },
    },
    events: {
      event_1: {
        comment:  "foo"
      },
      event_2: {
        comment:  "bar"
      }
    }
  }
}
</code>```

I'm using the EVENT_ADD action type in all 3 reducers. The logic is identical for component.js and item.js (below), but the two also have independent actions that are specific to their type.

Here, I got around unnecessarily adding the event to the wrong place by using Immutable.js's .has() function to check if the target ID exists in that part of the state.

```<code>export default (state = getInitState('component'), action) => {
  switch (action.type) {
    case EVENT_ADD:
      return state.has(action.targetId) ?
        state.updateIn(
          [action.targetId, 'events'],
          arr => arr.push(action.event.id)
        ) :
        state;

    [...]
  }
}
</code>```

In event.js, I use EVENT_ADD here as well to add the contents of an event to that portion of the state.

```<code>export default (state = getInitState('events'), action) => {
  switch (action.type) {
    case EVENT_ADD:
      return state.set(action.event.id, fromJS(action.event));

    [...]
  }
}
</code>```

My understanding of high order reducers is that I need to do one or both of the following:

Use separate action types ADD_EVENT_${entity} (thus making me use both EVENT_ADD_COMPONENT and EVENT_ADD_ITEM in event.js to create an event regardless of its parent.)

Filter by name in my main reducer, as shown at the bottom of the docs, in which case, I'm not sure how to to differentiate my initialState and actions that are specific to a component and item if I'm just sharing a reducer for both.

It seems like I want some sharedReducer.js where I can share logic between components and items for actions like ADD_EVENT, DELETE_EVET, etc. And then also have two independent reducers for each entity. I'm unsure how I can accomplish this or what design pattern is best.

Any guidance would be appreciated. Thank you!

答:
The phrase "higher-order $THING" generally means "a function that takes a $THING as an argument, and/or returns a new $THING" (where "$THING" is usually "function", "component", "reducer", etc).  So, a "higher-order reducer" is a function that takes some arguments, and returns a reducer.

Per the Structuring Reducers - Reusing Reducer Logic section you linked, the most common higher-order reducer example is a function that takes some kind of distinguishing value like an ID or action type or substring, and returns a new reducer function that uses that distinguishing value to know when it's actually supposed to respond.  That way, you can create multiple instances of the same function, and only the "right" one will respond to a given action even though the rest of the logic is the same.

It seems like you're generally on the right track already, and there's a few ways you could possibly organize the shared logic.

One approach might be to explicitly look for the "common" actions first and run that reducer, and then look for the specific cases:

```<code>export default (state = getInitState('events'), action) => {
    // First check for common cases
    switch(action.type) {
        case EVENT_ADD:
        case OTHER_COMMON_ACTION: {
            state = sharedReducer(state, action);
            break;
        }
    }

    switch(action.type) {
        case EVENT_ADD:
        case EVENTS_SPECIFIC_ACTION: {
            return eventsSpecificReducer(state, action);
        }
    }

    return state;
}
</code>```

Another approach might be to use something like the reduce-reducers utility, as shown in the Structuring Reducers - Beyond combineReducers section:

```<code>const entities = combineReducers({
    components : reduceReducers(componentsReducer, sharedReducer),
    items : reduceReducers(itemsReducer, sharedReducer)
    events,
});
</code>```

Hopefully that gives you some pointers in the right direction.  If you've got more questions, feel free to ask here, or in the Reactiflux chat channels on Discord - invite link is at https://www.reactiflux.com.  (Note: I'm a Redux maintainer, author of that "Structuring Reducers" docs section, and an admin on Reactiflux.)

ContentLicense: CC BY-SA 4.0

Body:
I'm refactoring a React/Redux app that has been built to a point where there is a need to de-duplicate a lot of reducer logic. I've looked into High Order Reducers but I'm having a hard time wrapping my head around how I can get them to work for me.

Here's an example:

reducers.js

import components from './entities/components';
import events from './entities/events';
import items from './entities/items';

const entities = combineReducers({
  components,
  items,
  events,
});

I'm using normalizr. Here's an idea of what my state looks like. For this example, just know that events can belong to components or items, but the two are otherwise distinguishable.

{
  entities: {
    components: {
      component_1: {
        events: ['event_1'],
      },
    },
    items: {
      item_1: {
        events: ['event_2'],
      },
    },
    events: {
      event_1: {
        comment:  "foo"
      },
      event_2: {
        comment:  "bar"
      }
    }
  }
}

I'm using the EVENT_ADD action type in all 3 reducers. The logic is identical for component.js and item.js (below), but the two also have independent actions that are specific to their type.

Here, I got around unnecessarily adding the event to the wrong place by using Immutable.js's .has() function to check if the target ID exists in that part of the state.

export default (state = getInitState('component'), action) => {
  switch (action.type) {
    case EVENT_ADD:
      return state.has(action.targetId) ?
        state.updateIn(
          [action.targetId, 'events'],
          arr => arr.push(action.event.id)
        ) :
        state;

    [...]
  }
}

In event.js, I use EVENT_ADD here as well to add the contents of an event to that portion of the state.

export default (state = getInitState('events'), action) => {
  switch (action.type) {
    case EVENT_ADD:
      return state.set(action.event.id, fromJS(action.event));

    [...]
  }
}

My understanding of high order reducers is that I need to do one or both of the following:

Use separate action types ADD_EVENT_${entity} (thus making me use both EVENT_ADD_COMPONENT and EVENT_ADD_ITEM in event.js to create an event regardless of its parent.)

Filter by name in my main reducer, as shown at the bottom of the docs, in which case, I'm not sure how to to differentiate my initialState and actions that are specific to a component and item if I'm just sharing a reducer for both.

It seems like I want some sharedReducer.js where I can share logic between components and items for actions like ADD_EVENT, DELETE_EVET, etc. And then also have two independent reducers for each entity. I'm unsure how I can accomplish this or what design pattern is best.

Any guidance would be appreciated. Thank you!

Body:
The phrase "higher-order $THING" generally means "a function that takes a $THING as an argument, and/or returns a new $THING" (where "$THING" is usually "function", "component", "reducer", etc).  So, a "higher-order reducer" is a function that takes some arguments, and returns a reducer.

Per the Structuring Reducers - Reusing Reducer Logic section you linked, the most common higher-order reducer example is a function that takes some kind of distinguishing value like an ID or action type or substring, and returns a new reducer function that uses that distinguishing value to know when it's actually supposed to respond.  That way, you can create multiple instances of the same function, and only the "right" one will respond to a given action even though the rest of the logic is the same.

It seems like you're generally on the right track already, and there's a few ways you could possibly organize the shared logic.

One approach might be to explicitly look for the "common" actions first and run that reducer, and then look for the specific cases:

export default (state = getInitState('events'), action) => {
    // First check for common cases
    switch(action.type) {
        case EVENT_ADD:
        case OTHER_COMMON_ACTION: {
            state = sharedReducer(state, action);
            break;
        }
    }

    switch(action.type) {
        case EVENT_ADD:
        case EVENTS_SPECIFIC_ACTION: {
            return eventsSpecificReducer(state, action);
        }
    }

    return state;
}

Another approach might be to use something like the reduce-reducers utility, as shown in the Structuring Reducers - Beyond combineReducers section:

const entities = combineReducers({
    components : reduceReducers(componentsReducer, sharedReducer),
    items : reduceReducers(itemsReducer, sharedReducer)
    events,
});

Hopefully that gives you some pointers in the right direction.  If you've got more questions, feel free to ask here, or in the Reactiflux chat channels on Discord - invite link is at https://www.reactiflux.com.  (Note: I'm a Redux maintainer, author of that "Structuring Reducers" docs section, and an admin on Reactiflux.)


问:
Execution failed for task ':app:compileDebugAidl': aidl is missing
I installed Android Studio on my computer. I created a new project but that got me the error below. What can I do?

```<code>Error:Execution failed for task ':app:compileDebugAidl'.
> aidl is missing
</code>```

My Android Studio version is 1.1.0.

This is my build.gradle file:

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.1.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
allprojects {
    repositories {
        jcenter()
    }
}
</code>```

And :

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "24.1.2"

    defaultConfig {
        applicationId "com.example.jo.cloning_a_login_screen"
        minSdkVersion 13
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.0.0'
}
</code>```

答: Use your file browser and copy-paste the IInAppBillingService.aidl into /app/src/main/aidl/com/android/vending/billing/</p>

Body:
I installed Android Studio on my computer. I created a new project but that got me the error below. What can I do?

Error:Execution failed for task ':app:compileDebugAidl'.
> aidl is missing

My Android Studio version is 1.1.0.

This is my build.gradle file:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.1.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
allprojects {
    repositories {
        jcenter()
    }
}

And :

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "24.1.2"

    defaultConfig {
        applicationId "com.example.jo.cloning_a_login_screen"
        minSdkVersion 13
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.0.0'
}


问:
Disable download button until file download is finished (AngularJS 1.4)
in AngularJS 1.4 app we need to disable download button until file download is finished and enable it afterwards. Ideally it should work eve in IE 7 :)

Page

<button ng-click="downloadFile()"
                            ng-class="inProgressDownloadFile ? 'btn-disabled' : 'btn-enabled'">

                        Download
                    </button>```
</div>
</div>
</p>

<h2>Controller</h2>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>$scope.downloadFile = function() {
if ($scope.inProgressDownloadFile) {
                return;
            }
$scope.inProgressDownloadFile = true;
FileService.downloadFileById($scope.fileId).then(function(response) {
var blob = new Blob([response.data], {type: "application/vnd.ms-excel.sheet.macroEnabled.12"});
var url = window.URL || window.webkitURL;

                    var downloadLink = angular.element('<a></a>');
                    downloadLink.attr('href',url.createObjectURL(blob));
                    downloadLink.attr('target','_self');
                    downloadLink.attr('download', 'invoice.xlsm');
                    downloadLink[0].click();
}
$scope.inProgressDownloadExcel = false;
               }, function(response) {
                    $scope.inProgressDownloadExcel = false;
               });
console.log('End of method downloadFile().');
        };</code>```

Service

factory.downloadFileById = function(fileId) {
            var httpConfig = {
                 responseType: 'arraybuffer',
                 headers: {
                        'Content-type': 'application/json',
                         'Accept': 'application/vnd.ms-excel.sheet.macroEnabled.12'
                     }
            };

            return $http.get(restAppBaseContext + 'restFile/?id=' + fileId, null, httpConfig);
        };```

Problem

File is downloaded but corrupted! When I open downloaded excel file I get popup message: "We found a problem with some content in invoice.xlsm. Do you want us to try to recover as much as we can? ...". If I click "Yes" I get another popup message: "Excel cannot open the file invoice.xlsm because the file format or file extension is not valid. ...".

答:
you can use

ng-disabled

```<code><button ng-click="downloadFile()"
                        ng-disabled="downloaded">
                    <img ng-show="inProgressDownloadFile" src="imgs/ajax-loader.gif"/>
                    <span>Download</span>
                </button>
</code>```

Use $scope.downloaded as default true until download complete.

for more reference go to HERE

Body:
in AngularJS 1.4 app we need to disable download button until file download is finished and enable it afterwards. Ideally it should work eve in IE 7 :)

Page

<button ng-click="downloadFile()"
                            ng-class="inProgressDownloadFile ? 'btn-disabled' : 'btn-enabled'">

                        Download
                    </button>

Controller

$scope.downloadFile = function() {
if ($scope.inProgressDownloadFile) {
                return;
            }
$scope.inProgressDownloadFile = true;
FileService.downloadFileById($scope.fileId).then(function(response) {
var blob = new Blob([response.data], {type: "application/vnd.ms-excel.sheet.macroEnabled.12"});
var url = window.URL || window.webkitURL;

                    var downloadLink = angular.element('');
                    downloadLink.attr('href',url.createObjectURL(blob));
                    downloadLink.attr('target','_self');
                    downloadLink.attr('download', 'invoice.xlsm');
                    downloadLink[0].click();
}
$scope.inProgressDownloadExcel = false;
               }, function(response) {
                    $scope.inProgressDownloadExcel = false;
               });
console.log('End of method downloadFile().');
        };

Service

factory.downloadFileById = function(fileId) {
            var httpConfig = {
                 responseType: 'arraybuffer',
                 headers: {
                        'Content-type': 'application/json',
                         'Accept': 'application/vnd.ms-excel.sheet.macroEnabled.12'
                     }
            };

            return $http.get(restAppBaseContext + 'restFile/?id=' + fileId, null, httpConfig);
        };

Problem

File is downloaded but corrupted! When I open downloaded excel file I get popup message: "We found a problem with some content in invoice.xlsm. Do you want us to try to recover as much as we can? ...". If I click "Yes" I get another popup message: "Excel cannot open the file invoice.xlsm because the file format or file extension is not valid. ...".

Body:
you can use

ng-disabled

<button ng-click="downloadFile()"
                        ng-disabled="downloaded">
                    <img ng-show="inProgressDownloadFile" src="imgs/ajax-loader.gif"/>
                    <span>Download</span>
                </button>

Use $scope.downloaded as default true until download complete.

for more reference go to HERE


问:
Remove this border line from Calendar WPF styled
Can be remove this border line from WPF calendar?

I try a simple example xaml and same effect:

```<code><Grid >
    <StackPanel Orientation="horizontal" >
        <Calendar BorderThickness="0px" Background="Beige" Foreground="Beige" BorderBrush="Beige"
              SelectedDate="6/4/2017"
              DisplayDate="6/4/2017" DisplayDateStart="5/1/1900" DisplayDateEnd="7/1/3000"
              DisplayMode="Month"
            />
    </StackPanel>
</Grid>
</code>```

答:
I think for this you might have to modify the template. It is part of the CalendarItem style on an inner border.</p>

```<code><Style x:Key="CalendarItemStyle1" TargetType="{x:Type CalendarItem}">
        <Setter Property="Margin" Value="0"/>
        <Setter Property="Padding" Value="0"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type CalendarItem}">
                    <ControlTemplate.Resources>
                        <DataTemplate x:Key="{x:Static CalendarItem.DayTitleTemplateResourceKey}">
                            <TextBlock Foreground="#FF333333" FontWeight="Bold" FontSize="9.5" FontFamily="Verdana" HorizontalAlignment="Center" Margin="0,6,0,6" Text="{Binding}" VerticalAlignment="Center"/>
                        </DataTemplate>
                    </ControlTemplate.Resources>
                    <Grid x:Name="PART_Root">
                        <Grid.Resources>
                            <SolidColorBrush x:Key="DisabledColor" Color="#A5FFFFFF"/>
                        </Grid.Resources>
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal"/>
                                <VisualState x:Name="Disabled">
                                    <Storyboard>
                                        <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="PART_DisabledVisual"/>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="1">

// get rid of the border thickness here and it's gone
                            <Border BorderBrush="Purple" BorderThickness="2" CornerRadius="1">
                                <Grid>
                                    <Grid.Resources>
                                        <ControlTemplate x:Key="PreviousButtonTemplate" TargetType="{x:Type Button}">
</code>```

Body:
Can be remove this border line from WPF calendar?

I try a simple example xaml and same effect:

<Grid >
    <StackPanel Orientation="horizontal" >
        <Calendar BorderThickness="0px" Background="Beige" Foreground="Beige" BorderBrush="Beige"
              SelectedDate="6/4/2017"
              DisplayDate="6/4/2017" DisplayDateStart="5/1/1900" DisplayDateEnd="7/1/3000"
              DisplayMode="Month"
            />
    </StackPanel>
</Grid>

Body:
I think for this you might have to modify the template. It is part of the CalendarItem style on an inner border.

<Style x:Key="CalendarItemStyle1" TargetType="{x:Type CalendarItem}">
        <Setter Property="Margin" Value="0"/>
        <Setter Property="Padding" Value="0"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type CalendarItem}">
                    <ControlTemplate.Resources>
                        <DataTemplate x:Key="{x:Static CalendarItem.DayTitleTemplateResourceKey}">
                            <TextBlock Foreground="#FF333333" FontWeight="Bold" FontSize="9.5" FontFamily="Verdana" HorizontalAlignment="Center" Margin="0,6,0,6" Text="{Binding}" VerticalAlignment="Center"/>
                        </DataTemplate>
                    </ControlTemplate.Resources>
                    <Grid x:Name="PART_Root">
                        <Grid.Resources>
                            <SolidColorBrush x:Key="DisabledColor" Color="#A5FFFFFF"/>
                        </Grid.Resources>
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal"/>
                                <VisualState x:Name="Disabled">
                                    <Storyboard>
                                        <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="PART_DisabledVisual"/>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="1">

// get rid of the border thickness here and it's gone
                            <Border BorderBrush="Purple" BorderThickness="2" CornerRadius="1">
                                <Grid>
                                    <Grid.Resources>
                                        <ControlTemplate x:Key="PreviousButtonTemplate" TargetType="{x:Type Button}">


问:
Stop CSS3 opacity animation before 1
I'm trying to animate a certain div opacity from 0 to 0.6, but it seems that at the end of the animation it jumps to 1.

What am I missing?

#test {
  width: 200px;
  height: 200px;
  background-color: #900;
  animation: fadein 2s;
  -moz-animation: fadein 2s;
  -webkit-animation: fadein 2s;
  -o-animation: fadein 2s;
}

@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}

@-moz-keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}

@-webkit-keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}

@-o-keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.5;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="test"></div></code>```

答:
Have you tried setting the opacity on the element you are animating to the final value?

I believe the rules in a CSS animation stop applying when the animation finishes. I would guess it is animating from 0 to 0.5 and then reverting to 1, 1 being the default opacity since you don't have an opacity specified on the element itself.

I hope this helps!

Title: Stop CSS3 opacity animation before 1


问:
Error HRESULT E_FAIL has been returned from a call to a COM component VS2012 when debugging
I have a problem debugging a project migrated from Visual Studio 2010 to 2012.  Every time I go to debug it I get the error message:

"Error HRESULT E_FAIL has been returned from a call to a COM component".

Compiling and running the application in a local IIS server works fine - just cannot debug.

The other change other than moving to VS2012 is I am now using Team Foundation Server for source control and issue tracking - but I cannot see how that would affect it.

I can narrow it down to the following

The project file - it has been migrated from VS 2003 as a website project and has been chopped and changed up the different versions

Crystal Report runtime library/ some other library

Anyone with any ideas?

答:
I fixed the same issue by deleting ComponentModelCache folder

Close Visual Studio (if you haven’t done so already out of despair)

Open a file explorer window and navigate toyour AppData folder. You can get there by:

In the search bar, type %APPDATA%/.. and press enter

Alternatively, navigate to C:\Users\\AppData

Go into Local\Microsoft\VisualStudio\<version> where  is 12.0 for Visual Studio 2013.

Delete the ComponentModelCache folder.

From here: http://withmartin.net/how-visual-studios-component-model-cache-can-be-a-pain/


问:
javascript regex help
i am trying to validate if a certain company was already picked for an application. the companyList format is:

60,261,420  ( a list of companyID)

I used

```<code>cID = $('#coName').val().split('::')[1];
</code>```

to get the id only.

I am calling this function by passing say 60:

```<code>    findCompany = function(value) {
    var v = /^.+60,261,420$/.test(value);
    alert(v);
}
</code>```

when I pass the exact same string, i get false. any help?

答:
Why not split the string into an array, like you did for your testing, iterate over the list and check if it's in?

A regexp just for that is balls, overhead and slower. A lot.

Anyway, for your specific question:

You’re checking the string "60" for /^.+60,261,420$/.

.+60 will obviously not match because you require at least one character before the 60. The commas also evaluate and are not in your String.

I don’t quite get where your regexp comes from.

Were you looking for a regexp to OR them a hard-coded list of IDs?

Code for splitting it and checking the array of IDs:

```<code>findCompany = function(value) {
  $('#coName').val().split('::').each(function(val){
    if(val == value) return true;
  });
  return false;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: javascript regex help

Body:
i am trying to validate if a certain company was already picked for an application. the companyList format is:

60,261,420  ( a list of companyID)

I used

cID = $('#coName').val().split('::')[1];

to get the id only.

I am calling this function by passing say 60:

    findCompany = function(value) {
    var v = /^.+60,261,420$/.test(value);
    alert(v);
}

when I pass the exact same string, i get false. any help?

Body:
Why not split the string into an array, like you did for your testing, iterate over the list and check if it's in?

A regexp just for that is balls, overhead and slower. A lot.

Anyway, for your specific question:

You’re checking the string "60" for /^.+60,261,420$/.

.+60 will obviously not match because you require at least one character before the 60. The commas also evaluate and are not in your String.

I don’t quite get where your regexp comes from.

Were you looking for a regexp to OR them a hard-coded list of IDs?

Code for splitting it and checking the array of IDs:

findCompany = function(value) {
  $('#coName').val().split('::').each(function(val){
    if(val == value) return true;
  });
  return false;
}


问:
FPDF align text LEFT, Center and Right
I've have three cells and i'am trying to align the text to Left, Center and Right.

```<code>function Footer()
{
    $this->SetY( -15 );

    $this->SetFont( 'Arial', '', 10 );

    $this->Cell(0,10,'Left text',0,0,'L');

    $this->Cell(0,10,'Center text:',0,0,'C');

    $this->Cell( 0, 10, 'Right text', 0, 0, 'R' );
}
</code>```

When I ouput my PDF file, center text get automatically aligned right.
This is how it looks:

Can somebody tell me what I'm doing wrong here and how I can fix this issue?

答:
Though Jan Slabon's answer was really good I still had issues with the center not being exactly centered on my page, maybe we have different versions of the library and that's what accounts for the slight differences, for instance he uses lMargin and on some versions that's not available. Anyway, the way it worked for me is this:</p>

```<code>        $pdf = new tFPDF\PDF();
        //it helps out to add margin to the document first
        $pdf->setMargins(23, 44, 11.7);
        $pdf->AddPage();
        //this was a special font I used
        $pdf->AddFont('FuturaMed','','AIGFutura-Medium.ttf',true);
        $pdf->SetFont('FuturaMed','',16);

        $nombre = "NAME OF PERSON";
        $apellido = "LASTNAME OF PERSON";

        $pos = 10;
        //adding XY as well helped me, for some reaons without it again it wasn't entirely centered
        $pdf->SetXY(0, 10);

        //with SetX I use numbers instead of lMargin, and I also use half of the size I added as margin for the page when I did SetMargins
        $pdf->SetX(11.5);
        $pdf->Cell(0,$pos,$nombre,0,0,'C');

        $pdf->SetX(11.5);
        //$pdf->SetFont('FuturaMed','',12);
        $pos = $pos + 10;
        $pdf->Cell(0,$pos,$apellido,0,0,'C');
        $pdf->Output('example.pdf', 'F');
</code>```

Title: FPDF align text LEFT, Center and Right

Body:
I've have three cells and i'am trying to align the text to Left, Center and Right.

function Footer()
{
    $this->SetY( -15 );

    $this->SetFont( 'Arial', '', 10 );

    $this->Cell(0,10,'Left text',0,0,'L');

    $this->Cell(0,10,'Center text:',0,0,'C');

    $this->Cell( 0, 10, 'Right text', 0, 0, 'R' );
}

When I ouput my PDF file, center text get automatically aligned right.
This is how it looks:

Can somebody tell me what I'm doing wrong here and how I can fix this issue?

Body:
Though Jan Slabon's answer was really good I still had issues with the center not being exactly centered on my page, maybe we have different versions of the library and that's what accounts for the slight differences, for instance he uses lMargin and on some versions that's not available. Anyway, the way it worked for me is this:

        $pdf = new tFPDF\PDF();
        //it helps out to add margin to the document first
        $pdf->setMargins(23, 44, 11.7);
        $pdf->AddPage();
        //this was a special font I used
        $pdf->AddFont('FuturaMed','','AIGFutura-Medium.ttf',true);
        $pdf->SetFont('FuturaMed','',16);

        $nombre = "NAME OF PERSON";
        $apellido = "LASTNAME OF PERSON";

        $pos = 10;
        //adding XY as well helped me, for some reaons without it again it wasn't entirely centered
        $pdf->SetXY(0, 10);

        //with SetX I use numbers instead of lMargin, and I also use half of the size I added as margin for the page when I did SetMargins
        $pdf->SetX(11.5);
        $pdf->Cell(0,$pos,$nombre,0,0,'C');

        $pdf->SetX(11.5);
        //$pdf->SetFont('FuturaMed','',12);
        $pos = $pos + 10;
        $pdf->Cell(0,$pos,$apellido,0,0,'C');
        $pdf->Output('example.pdf', 'F');


问:
Comparator<File> for "directories-first" order
I'm stumped... Let's say I have this directory tree:

```<code>{someRoot}/
{someRoot}/bar/
{someRoot}/bar/file1.txt
{someRoot}/foo/
{someRoot}/foo/baz/
{someRoot}/foo/baz/file3.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/file2.txt
{someRoot}/aardvark.txt
{someRoot}/food.txt
{someRoot}/zebra.txt
</code>```

You'll note the ordering. Call this order1. At each stage, the directories come first before the files. (NOTE:  bar/file1.txt comes before foo, so on a global basis, the directories do not all come before all the files.)

If I enumerate this directory tree, and then recursively enumerate the subdirectories, I'll get the following List<File>, with ordering order2.

```<code>{someRoot}/
{someRoot}/aardvark.txt
{someRoot}/bar/
{someRoot}/foo/
{someRoot}/food.txt
{someRoot}/zebra.txt
{someRoot}/bar/file1.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/baz/
{someRoot}/foo/file2.txt
{someRoot}/foo/baz/file3.txt
</code>```

If I create the straightforward Comparator<File>:

```<code>Comparator<File> fc = new Comparator<File>(){
    @Override public int compare(File o1, File o2) {
        return o1.compareTo(o2);
    }
};
</code>```

and I sort, I get this ordering (order3) from lexicographic ordering:

```<code>{someRoot}
{someRoot}/aardvark.txt
{someRoot}/bar
{someRoot}/bar/file1.txt
{someRoot}/foo
{someRoot}/food.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/baz
{someRoot}/foo/baz/file3.txt
{someRoot}/foo/file2.txt
{someRoot}/zebra.txt
</code>```

But I don't want this ordering (which has problems: note that food.txt comes between directory foo and its sub-items), I want order1. How can I write a Comparator to get me that?

答:
This works in my tests.</p>

```<code>new Comparator<File>() {
    @Override
    public int compare(File first, File second) {
        if (first.isDirectory() && second.isDirectory())
            return first.compareTo(second);

        if (first.isDirectory())
            return this.compareToFile(first, second);

        if (second.isDirectory())
            return -(this.compareToFile(second, first));

        return this.compareFiles(first, second);
    }

    private int compareFiles(File first, File second) {
        File firstParentFile = first.getParentFile();
        File secondParentFile = second.getParentFile();

        if (isSubDir(firstParentFile, secondParentFile))
            return -1;

        if (isSubDir(secondParentFile, firstParentFile))
            return 1;

        return first.compareTo(second);
    }

    private int compareToFile(File directory, File file) {
        File fileParent = file.getParentFile();
        if (directory.equals(fileParent))
            return -1;

        if (isSubDir(directory, fileParent))
            return -1;

        return directory.compareTo(file);
    }

    private boolean isSubDir(File directory, File subDir) {
        for (File parentDir = directory.getParentFile(); parentDir != null; parentDir = parentDir.getParentFile()) {
            if (subDir.equals(parentDir)) {
                return true;
            }
        }

        return false;
    }
</code>```

Body:
I'm stumped... Let's say I have this directory tree:

{someRoot}/
{someRoot}/bar/
{someRoot}/bar/file1.txt
{someRoot}/foo/
{someRoot}/foo/baz/
{someRoot}/foo/baz/file3.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/file2.txt
{someRoot}/aardvark.txt
{someRoot}/food.txt
{someRoot}/zebra.txt

You'll note the ordering. Call this order1. At each stage, the directories come first before the files. (NOTE:  bar/file1.txt comes before foo, so on a global basis, the directories do not all come before all the files.)

If I enumerate this directory tree, and then recursively enumerate the subdirectories, I'll get the following List<File>, with ordering order2.

{someRoot}/
{someRoot}/aardvark.txt
{someRoot}/bar/
{someRoot}/foo/
{someRoot}/food.txt
{someRoot}/zebra.txt
{someRoot}/bar/file1.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/baz/
{someRoot}/foo/file2.txt
{someRoot}/foo/baz/file3.txt

If I create the straightforward Comparator<File>:

Comparator<File> fc = new Comparator<File>(){
    @Override public int compare(File o1, File o2) {
        return o1.compareTo(o2);
    }
};

and I sort, I get this ordering (order3) from lexicographic ordering:

{someRoot}
{someRoot}/aardvark.txt
{someRoot}/bar
{someRoot}/bar/file1.txt
{someRoot}/foo
{someRoot}/food.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/baz
{someRoot}/foo/baz/file3.txt
{someRoot}/foo/file2.txt
{someRoot}/zebra.txt

But I don't want this ordering (which has problems: note that food.txt comes between directory foo and its sub-items), I want order1. How can I write a Comparator to get me that?

Body:
This works in my tests.

new Comparator<File>() {
    @Override
    public int compare(File first, File second) {
        if (first.isDirectory() && second.isDirectory())
            return first.compareTo(second);

        if (first.isDirectory())
            return this.compareToFile(first, second);

        if (second.isDirectory())
            return -(this.compareToFile(second, first));

        return this.compareFiles(first, second);
    }

    private int compareFiles(File first, File second) {
        File firstParentFile = first.getParentFile();
        File secondParentFile = second.getParentFile();

        if (isSubDir(firstParentFile, secondParentFile))
            return -1;

        if (isSubDir(secondParentFile, firstParentFile))
            return 1;

        return first.compareTo(second);
    }

    private int compareToFile(File directory, File file) {
        File fileParent = file.getParentFile();
        if (directory.equals(fileParent))
            return -1;

        if (isSubDir(directory, fileParent))
            return -1;

        return directory.compareTo(file);
    }

    private boolean isSubDir(File directory, File subDir) {
        for (File parentDir = directory.getParentFile(); parentDir != null; parentDir = parentDir.getParentFile()) {
            if (subDir.equals(parentDir)) {
                return true;
            }
        }

        return false;
    }


问:
Angular2-Leafletjs: Defining style for L.geoJSON().addTo(myMap)
In am using Leafletjs in Angular2, http.get to invoke JSON from a URL, but I can't define style for the features that are added to the map because of predefining the geoJSON layer:

```<code>  // Add an empty layer to the map
  var geoJsonLayer1 = L.geoJSON().addTo(myMap);

  // Retrieve the geojson file
  http.get(myJsonURL)
  .map((response: Response) => {
      geoJsonLayer1.addData(response.json());
  }).subscribe();
</code>```

The geoJSON layer doesn't have any style and it looks as below:

The reason that I am predefining the layer is, I am lazy-loading the JSON file. In the regular way, we can define the style as below:

```<code>L.geoJSON(myLines, {
    style: myStyle
}).addTo(map);
</code>```

Now my question is, how to define the style for a predefined layer?

答:
Just predefine the layer without data…

```<code>var geoJsonLayer1 = L.geoJSON(null, {
  style: myStyle
}).addTo(map);

// Later on…
geoJsonLayer1.addData(response.json());
</code>```

BTW your screenshot looks to show markers (for "Point" type features) with missing icon image. In that case, instead of style option for vector shapes (like polygons, line strings, etc.), you should use the pointToLayer option.

Body:
In am using Leafletjs in Angular2, http.get to invoke JSON from a URL, but I can't define style for the features that are added to the map because of predefining the geoJSON layer:

  // Add an empty layer to the map
  var geoJsonLayer1 = L.geoJSON().addTo(myMap);

  // Retrieve the geojson file
  http.get(myJsonURL)
  .map((response: Response) => {
      geoJsonLayer1.addData(response.json());
  }).subscribe();

The geoJSON layer doesn't have any style and it looks as below:

The reason that I am predefining the layer is, I am lazy-loading the JSON file. In the regular way, we can define the style as below:

L.geoJSON(myLines, {
    style: myStyle
}).addTo(map);

Now my question is, how to define the style for a predefined layer?

Body:
Just predefine the layer without data…

var geoJsonLayer1 = L.geoJSON(null, {
  style: myStyle
}).addTo(map);

// Later on…
geoJsonLayer1.addData(response.json());

BTW your screenshot looks to show markers (for "Point" type features) with missing icon image. In that case, instead of style option for vector shapes (like polygons, line strings, etc.), you should use the pointToLayer option.


问:
Foreach loop in CodeIgniter
I'm using the CI framework and I'm trying to make a foreach loop so that all products of my site are displayed.

This is my controller file:

```<code>class AlleCadeausController extends CI_Controller {

public function index()
{
    $this->load->model('allecadeaus_model');
    $data['cadeaus'] = $this->allecadeaus_model->get_cadeaus();
    $this->load->view('allecadeaus');
}
</code>```

This is my model file:

```<code><?php
class Allecadeaus_model extends CI_Model {
   public function __construct()
   {
       parent::__construct();
   }
    public function get_cadeaus()
    {
        $query = $this->db->query('SELECT * FROM products');
        $result = $query->result_array();
        return $result;
    }
}
</code>```

this is my view:

```<code><?php
foreach ($cadeaus as $cadeau)
{
    echo $cadeau->product_naam;
}
?>
</code>```

The error is:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: cadeaus

Filename: views/allecadeaus.php

Line Number: 3

Backtrace:

File: /home/ubuntu/workspace/application/views/allecadeaus.php Line: 3
  Function: _error_handler

File:
  /home/ubuntu/workspace/application/controllers/AlleCadeausController.php
  Line: 11 Function: view

File: /home/ubuntu/workspace/index.php Line: 315 Function:
  require_once

My table name is products

答:
You need pass array of data in second argument.
Please use this :

```<code>$this->load->view('allecadeaus',$data);
</code>```

If you load child view in allecadeaus, then you don't need to pass array of data. You can directly access all variables from array of data.

Title: Foreach loop in CodeIgniter

Body:
I'm using the CI framework and I'm trying to make a foreach loop so that all products of my site are displayed.

This is my controller file:

class AlleCadeausController extends CI_Controller {

public function index()
{
    $this->load->model('allecadeaus_model');
    $data['cadeaus'] = $this->allecadeaus_model->get_cadeaus();
    $this->load->view('allecadeaus');
}

This is my model file:

<?php
class Allecadeaus_model extends CI_Model {
   public function __construct()
   {
       parent::__construct();
   }
    public function get_cadeaus()
    {
        $query = $this->db->query('SELECT * FROM products');
        $result = $query->result_array();
        return $result;
    }
}

this is my view:

<?php
foreach ($cadeaus as $cadeau)
{
    echo $cadeau->product_naam;
}
?>

The error is:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: cadeaus

Filename: views/allecadeaus.php

Line Number: 3

Backtrace:

File: /home/ubuntu/workspace/application/views/allecadeaus.php Line: 3
  Function: _error_handler

File:
  /home/ubuntu/workspace/application/controllers/AlleCadeausController.php
  Line: 11 Function: view

File: /home/ubuntu/workspace/index.php Line: 315 Function:
  require_once

My table name is products

Body:
You need pass array of data in second argument.
Please use this :

$this->load->view('allecadeaus',$data);

If you load child view in allecadeaus, then you don't need to pass array of data. You can directly access all variables from array of data.


问:
select top n record from each group sqlite
I am trying to select top 2 records from a database table result that looks like this

```<code>SubjectId |  StudentId | Levelid | total
------------------------------------------
 1        |  1         |   1     | 89
 1        |  2         |   1     | 77
 1        |  3         |   1     | 61
 2        |  4         |   1     | 60
 2        |  5         |   1     | 55
 2        |  6         |   1     | 45
</code>```

i tried this query

```<code>SELECT rv.subjectid,
       rv.total,
       rv.Studentid,
       rv.levelid
  FROM ResultView rv
       LEFT JOIN ResultView rv2
              ON ( rv.subjectid = rv2.subjectid
    AND
rv.total <= rv2.total )
 GROUP BY rv.subjectid,
          rv.total,
          rv.Studentid
HAVING COUNT( * ) <= 2
order by rv.subjectid desc
</code>```

but some subjects like where missing, i even tried the suggestiong frm the following link

How to select the first N rows of each group?

but i get more that two for each subjectid

what am i doing wrong?

答:
I hope I'm understanding your question correctly.  Let me know if this is correct:

I recreated your table:

```<code>CREATE TABLE stack (
       SubjectId INTEGER(10),
       StudentId INTEGER(10),
       Levelid INTEGER(10),
       total INTEGER(10)
       )
;
</code>```

Inserted values

```<code>INSERT INTO stack VALUES
       (1,1,1,89),
       (1,2,1,77),
       (1,3,1,61),
       (2,4,1,60),
       (2,5,1,55),
       (2,6,1,45)
;
</code>```

If you're trying to get the top group by Levelid (orderd by total field, assuming StudentID as primary key):

```<code>SELECT *
FROM stack AS a
WHERE a.StudentID IN (
      SELECT b.StudentID
      FROM stack AS b
      WHERE a.levelid = b.levelid
      ORDER BY b.total DESC
      LIMIT 2
      )
;
</code>```

Yields this result:

```<code>SubjectId | StudentId | Levelid | total
1         | 1         | 1       | 89
1         | 2         | 1       | 77
</code>```

Example of top 2 by SubjectId, ordered by total:

```<code>SELECT *
FROM stack AS a
WHERE a.StudentID IN (
      SELECT b.StudentID
      FROM stack AS b
      WHERE a.subjectID = b.subjectID
      ORDER BY b.total DESC
      LIMIT 2
      )
;
</code>```

Result:

```<code>SubjectId | StudentId | Levelid | total
1         | 1         | 1       | 89
1         | 2         | 1       | 77
2         | 4         | 1       | 60
2         | 5         | 1       | 55
</code>```

I hope that was the answer you were looking for.

Body:
I am trying to select top 2 records from a database table result that looks like this

SubjectId |  StudentId | Levelid | total
------------------------------------------
 1        |  1         |   1     | 89
 1        |  2         |   1     | 77
 1        |  3         |   1     | 61
 2        |  4         |   1     | 60
 2        |  5         |   1     | 55
 2        |  6         |   1     | 45

i tried this query

SELECT rv.subjectid,
       rv.total,
       rv.Studentid,
       rv.levelid
  FROM ResultView rv
       LEFT JOIN ResultView rv2
              ON ( rv.subjectid = rv2.subjectid
    AND
rv.total <= rv2.total )
 GROUP BY rv.subjectid,
          rv.total,
          rv.Studentid
HAVING COUNT( * ) <= 2
order by rv.subjectid desc

but some subjects like where missing, i even tried the suggestiong frm the following link

How to select the first N rows of each group?

but i get more that two for each subjectid

what am i doing wrong?

Body:
I hope I'm understanding your question correctly.  Let me know if this is correct:

I recreated your table:

CREATE TABLE stack (
       SubjectId INTEGER(10),
       StudentId INTEGER(10),
       Levelid INTEGER(10),
       total INTEGER(10)
       )
;

Inserted values

INSERT INTO stack VALUES
       (1,1,1,89),
       (1,2,1,77),
       (1,3,1,61),
       (2,4,1,60),
       (2,5,1,55),
       (2,6,1,45)
;

If you're trying to get the top group by Levelid (orderd by total field, assuming StudentID as primary key):

SELECT *
FROM stack AS a
WHERE a.StudentID IN (
      SELECT b.StudentID
      FROM stack AS b
      WHERE a.levelid = b.levelid
      ORDER BY b.total DESC
      LIMIT 2
      )
;

Yields this result:

SubjectId | StudentId | Levelid | total
1         | 1         | 1       | 89
1         | 2         | 1       | 77

Example of top 2 by SubjectId, ordered by total:

SELECT *
FROM stack AS a
WHERE a.StudentID IN (
      SELECT b.StudentID
      FROM stack AS b
      WHERE a.subjectID = b.subjectID
      ORDER BY b.total DESC
      LIMIT 2
      )
;

Result:

SubjectId | StudentId | Levelid | total
1         | 1         | 1       | 89
1         | 2         | 1       | 77
2         | 4         | 1       | 60
2         | 5         | 1       | 55

I hope that was the answer you were looking for.


问:
Print characters with an acute in ZPL
If I send the ZPL commands below to a Zebra printer, it prints AmitiÙ:

```<code>^XA
^FO50,20
^CI7
^A0N,25,15
^FD
Amitié
^FS
^XZ
</code>```

Note that the file encoding is ANSI.

Note the use of the ZPL command ^CI7 (7 => Single Byte Encoding - France 1 Character Set).

On the other hand, if I send the ZPL commands below to a Zebra printer, it prints Amitié (which is what I actually need to get):

```<code>^XA
^FO50,20
^CI28
^A0N,25,15
^FD
Amitié
^FS
^XZ
</code>```

Note that the file encoding is UTF-8.

Note the use of the ZPL command ^CI28 (28 => Unicode (UTF-8 encoding) - Unicode Character Set).

Do you know what's wrong in the first case?

Thank you for helping.

答:
Use UTF-8 by placing a ^CI28 command at the top of your ZPL template, eg

```<code>^XA
^CI28
^CF0,80
^FO70,40^FDavión^FS
^XZ
</code>```

Title: Print characters with an acute in ZPL

Body:
If I send the ZPL commands below to a Zebra printer, it prints AmitiÙ:

^XA
^FO50,20
^CI7
^A0N,25,15
^FD
Amitié
^FS
^XZ

Note that the file encoding is ANSI.

Note the use of the ZPL command ^CI7 (7 => Single Byte Encoding - France 1 Character Set).

On the other hand, if I send the ZPL commands below to a Zebra printer, it prints Amitié (which is what I actually need to get):

^XA
^FO50,20
^CI28
^A0N,25,15
^FD
Amitié
^FS
^XZ

Note that the file encoding is UTF-8.

Note the use of the ZPL command ^CI28 (28 => Unicode (UTF-8 encoding) - Unicode Character Set).

Do you know what's wrong in the first case?

Thank you for helping.

Body:
Use UTF-8 by placing a ^CI28 command at the top of your ZPL template, eg

^XA
^CI28
^CF0,80
^FO70,40^FDavión^FS
^XZ


问:
SQL Create variables from 2 different tables
I have 2 different tables called observations and intervals.

observations:

id,

type,

date

1 recess 03.05.2011 17:00

2 recess 03.06.2011 12:00

intervals:

id,

observation id,

value

1 1 5

2 1 8

3 2 4

4 2 4

I want a view that will display:

observation_id

percent_positive ((count where value = 5)/(total number of observations))

1 .5

2 0

I know

```<code>Select observation_id, Count(*) from intervals where value = 5 Group by
observation_id
</code>```

will give me:

1 1

1 0

and

```<code>Select observation_id, Count(*) from intervals Group by
observation_id
</code>```

will give me:

1 2

2 2

So how do I combine these to create a view with the percent_positive variable I'm looking for?

答:
You can use joins to fetch data from two tables having a common column field .

For more ,please read it in detail  Multiple values from multiple Tables

Body:
I have 2 different tables called observations and intervals.

observations:

id,

type,

date

1 recess 03.05.2011 17:00

2 recess 03.06.2011 12:00

intervals:

id,

observation id,

value

1 1 5

2 1 8

3 2 4

4 2 4

I want a view that will display:

observation_id

percent_positive ((count where value = 5)/(total number of observations))

1 .5

2 0

I know

Select observation_id, Count(*) from intervals where value = 5 Group by
observation_id

will give me:

1 1

1 0

and

Select observation_id, Count(*) from intervals Group by
observation_id

will give me:

1 2

2 2

So how do I combine these to create a view with the percent_positive variable I'm looking for?


问:
Using module variables for workbooks selected by user
Haven't really had the chance to use module variables before and unfortunately even after reading about them I can't seem to make it work.

My issues is that I'm trying to use a variable assigned as a workbook which the user browses for and use it in different subs.

As an example code of what I mean:

```<code>Sub GetFile()

Dim fNameAndPath As Variant

fNameAndPath = Application.GetOpenFilename(FileFilter:="Excel Files (*.XLS), *.XLS", Title:="Select File To Be Opened")
If fNameAndPath = False Then Exit Sub

    Call one
    Call two

End Sub

Sub one()

    With fNameAndPath

        'do stuff

    End With

End Sub

Sub two()

    With fNameAndPath

        'do stuff

    End With

End Sub
</code>```

答:
Its best practice to restrict the scope of a variable (where its visible) to the smallest area as possible - in this case send the variable as an argument, that way the variable lives only within the subs that declare or use it.

```<code>If fNameAndPath = False Then Exit Sub

one fNameAndPath
two fNameAndPath

End Sub
</code>```

And receive them as:

```<code>Sub one(fNameAndPath as Variant)
///

Sub two(fNameAndPath as Variant)
///
</code>```

(With fNameAndPath is not valid as fNameAndPath is a string not an object)

Body:
Haven't really had the chance to use module variables before and unfortunately even after reading about them I can't seem to make it work.

My issues is that I'm trying to use a variable assigned as a workbook which the user browses for and use it in different subs.

As an example code of what I mean:

Sub GetFile()

Dim fNameAndPath As Variant

fNameAndPath = Application.GetOpenFilename(FileFilter:="Excel Files (*.XLS), *.XLS", Title:="Select File To Be Opened")
If fNameAndPath = False Then Exit Sub

    Call one
    Call two

End Sub

Sub one()

    With fNameAndPath

        'do stuff

    End With

End Sub

Sub two()

    With fNameAndPath

        'do stuff

    End With

End Sub

Body:
Its best practice to restrict the scope of a variable (where its visible) to the smallest area as possible - in this case send the variable as an argument, that way the variable lives only within the subs that declare or use it.

If fNameAndPath = False Then Exit Sub

one fNameAndPath
two fNameAndPath

End Sub

And receive them as:

Sub one(fNameAndPath as Variant)
///

Sub two(fNameAndPath as Variant)
///

(With fNameAndPath is not valid as fNameAndPath is a string not an object)


问:
How to get immediate parent node with scrapy in python?
I am new to scrapy. I want to crawl some data from the web. I got the html document like below.

```<code>dom style1:
<div class="user-info">
    <p class="user-name">
        something in p tag
    </p>
    text data I want
</div>

dom style2:
<div class="user-info">
    <div>
        <p class="user-img">
            something in p tag
        </p>
        something in div tag
    </div>
    <div>
        <p class="user-name">
            something in p tag
        </p>
        text data I want
    </div>
</div>
</code>```

I want to get the data text data I want, now I can use css or xpath selector to get it by check it exists. But I want to know some better ways.
For example, I can get css p.user-name first, and then I get it's parent, and then I get it's div/text(), and always the data I want is the text() of the p.user-name's immediate parent div, but the question is, how can I get the immediate parent p.user-name?

答:
What about using following-sibling axis?

```<code>>>> s = scrapy.Selector(text='''<div class="user-info">
...     <p class="user-name">
...         something in p tag
...     </p>
...     text data I want
... </div>''')
>>> username = s.css('p.user-name')[0]
>>> username.xpath('following-sibling::text()[1]').get()
'\n    text data I want\n'
>>>

>>> s2 = scrapy.Selector(text='''<div class="user-info">
...     <div>
...         <p class="user-img">
...             something in p tag
...         </p>
...         something in div tag
...     </div>
...     <div>
...         <p class="user-name">
...             something in p tag
...         </p>
...         text data I want
...     </div>
... </div>''')
>>> username = s2.css('p.user-name')[0]
>>> username.xpath('following-sibling::text()[1]').get()
'\n        text data I want\n    '
>>>
</code>```

Body:
I am new to scrapy. I want to crawl some data from the web. I got the html document like below.

dom style1:

        something in p tag

    text data I want

dom style2:

            something in p tag

        something in div tag

            something in p tag

        text data I want

I want to get the data text data I want, now I can use css or xpath selector to get it by check it exists. But I want to know some better ways.
For example, I can get css p.user-name first, and then I get it's parent, and then I get it's div/text(), and always the data I want is the text() of the p.user-name's immediate parent div, but the question is, how can I get the immediate parent p.user-name?

Body:
What about using following-sibling axis?

>>> s = scrapy.Selector(text='''<div class="user-info">
...     <p class="user-name">
...         something in p tag
...     </p>
...     text data I want
... </div>''')
>>> username = s.css('p.user-name')[0]
>>> username.xpath('following-sibling::text()[1]').get()
'\n    text data I want\n'
>>>

>>> s2 = scrapy.Selector(text='''<div class="user-info">
...     <div>
...         <p class="user-img">
...             something in p tag
...         </p>
...         something in div tag
...     </div>
...     <div>
...         <p class="user-name">
...             something in p tag
...         </p>
...         text data I want
...     </div>
... </div>''')
>>> username = s2.css('p.user-name')[0]
>>> username.xpath('following-sibling::text()[1]').get()
'\n        text data I want\n    '
>>>


问:
How to convert lists of lines in strings to lists of lists, with each item in the lines stripped
I want to convert lists of lines in strings to lists of lists, with each item in the lines stripped.

The following works, but I suspect there is a sleeker way to do this.

```<code>def str_to_lst_of_lsts(s):
    lst = s.splitlines()[1:]
    lst2 = [i.split(';') for i in lst]
    lst3 = []
    for i in lst2:
        i2 = [j.strip() for j in i]
        lst3.append(i2)
    return lst3

s = '''
c; German for dog; Hund
c; capital of France; Paris
c; company; IBM
c; nation; Sweden
c; nickname for James; Jim
'''

print(str_to_lst_of_lsts(s))

# [['c', 'German for dog', 'Hund'], ['c', 'capital of France', 'Paris'], ['c', 'company', 'IBM'], ['c', 'nation', 'Sweden'], ['c', 'nickname for James', 'Jim']]
</code>```

答:
The main step is to use a list comprehension in place of the loop:

```<code>lst3 = [[j.strip() for j in i] for i in lst2]
</code>```

Yes, you can nest list comprehensions.  Now if you insist on a one-line solution, you can substitute the previous two comprehensions into this one.

Coding style: don't do it.  :-)

Body:
I want to convert lists of lines in strings to lists of lists, with each item in the lines stripped.

The following works, but I suspect there is a sleeker way to do this.

def str_to_lst_of_lsts(s):
    lst = s.splitlines()[1:]
    lst2 = [i.split(';') for i in lst]
    lst3 = []
    for i in lst2:
        i2 = [j.strip() for j in i]
        lst3.append(i2)
    return lst3

s = '''
c; German for dog; Hund
c; capital of France; Paris
c; company; IBM
c; nation; Sweden
c; nickname for James; Jim
'''

print(str_to_lst_of_lsts(s))

# [['c', 'German for dog', 'Hund'], ['c', 'capital of France', 'Paris'], ['c', 'company', 'IBM'], ['c', 'nation', 'Sweden'], ['c', 'nickname for James', 'Jim']]

Body:
The main step is to use a list comprehension in place of the loop:

lst3 = [[j.strip() for j in i] for i in lst2]

Yes, you can nest list comprehensions.  Now if you insist on a one-line solution, you can substitute the previous two comprehensions into this one.

Coding style: don't do it.  :-)


问:
Dynamic connection in Package Part Control Flow
I use SSIS 2016. I have created a Package Part Control Flow as you can see in this image :

The perpose of this Package Part Control Flow is to have a loop on the all files in one folder and transfer all files to another folder.

I have a Foreach Loop Container and a File System Task.

I have created these variable

Then I have created two Flat File Connection Manager:

Now I need to configure expressions for Connection String of each Flat File Connection Manager.

But as you can see I don't have access to my variables.

I need to be able to configure my connection managers inside the Package Parts Control Flow and then in package where I use this Package Parts Control Flow I will pass the values of variables.

The way I would like send the value for variables of Package Parts Control Flow.

Can I have an expression on ConnectionString of Flat File Connection Manager inside the Package Parts Control Flow by using the variable?

答:
After reading multiple articles and users feedbacks.

Unfortunately, you cannot use dynamic connections with package parts.

Control flow Package parts has some limitations, which make it useless in many cases.

References

Reuse control flow across packages...

Package parts in ssis 2016

control flow package parts in ssis 2016

My thoughts on ssis 2016 - ssis package parts 1

My thoughts on ssis 2016 - ssis package parts 2


问:
Extract JSON XPath in JavaScript
I have the below JSON data. I would like to extract the HOME phone number. I do not want the work phone number. Would you write for me a JavaScript XPath expression for that?</p>

```<code>{
   "Response":{
      "Details":{
         "MemberDetails":[
            {
               "DateOfBirth":"1969-04-03T00:00:00",
               "FirstName":"MIRIDA",
               "Gender":"M",
               "LastName":"MEARES",
               "MasterId":"rrrrr",
               "PhoneList":[
                  {
                     "number":"7088739304",
                     "type":"Home"
                  },
                  {
                     "number":"7088739304",
                     "type":"Work"
                  }
               ],
               "PlatformPointerList":[
                  {
                     "application":"",
                     "keyType":"AKAName",
                     "keyValue":"xxxxxx",
                     "source":"WPP"
                  },
                  {
                     "application":"",
                     "keyType":"xxxx",
                     "keyValue":"xxx",
                     "source":"xxxx"
                  },
                  {
                     "application":"",
                     "keyType":"xxxxx",
                     "keyValue":"xxxxxx",
                     "source":"ODS"
                  },
                  {
                     "application":"",
                     "keyType":"PERSONID",
                     "keyValue":"xxxxx",
                     "source":"EM"
                  },
                  {
                     "application":"",
                     "keyType":"PERSONID",
                     "keyValue":"xxxxxx",
                     "source":"WPP"
                  }
               ],
               "MemberId":"xxxxx",
               "MemberDependentCode":"xxx",
               "MemberSource":"xx"
            }
         ]
      },
      "MetaData":{
         "CorrelationId":"undefined"
      },
      "Status":{
         "type":"OK",
         "code":"200",

      }
   }
}
</code>```

答:
There is no native method for parsing JSON structures using XPath in Javascript, so you'll need to use a library of some kind.

As you've included the JQuery tag in your question, jQuery-JSONPath would be a good choice: https://github.com/wilhelm-murdoch/jQuery-JSONPath

Using that, your query would simply be:

```<code>var path = $.JSONPath({data: JSONOut});
homePhoneDetails = path.query("$.Response.Details.MemberDetails[0].PhoneList[?(@.type == 'Home')].number");
</code>```

See JS Fiddle here for a working example: https://jsfiddle.net/qy4end8k/

Title: Extract JSON XPath in JavaScript

Body:
I have the below JSON data. I would like to extract the HOME phone number. I do not want the work phone number. Would you write for me a JavaScript XPath expression for that?

{
   "Response":{
      "Details":{
         "MemberDetails":[
            {
               "DateOfBirth":"1969-04-03T00:00:00",
               "FirstName":"MIRIDA",
               "Gender":"M",
               "LastName":"MEARES",
               "MasterId":"rrrrr",
               "PhoneList":[
                  {
                     "number":"7088739304",
                     "type":"Home"
                  },
                  {
                     "number":"7088739304",
                     "type":"Work"
                  }
               ],
               "PlatformPointerList":[
                  {
                     "application":"",
                     "keyType":"AKAName",
                     "keyValue":"xxxxxx",
                     "source":"WPP"
                  },
                  {
                     "application":"",
                     "keyType":"xxxx",
                     "keyValue":"xxx",
                     "source":"xxxx"
                  },
                  {
                     "application":"",
                     "keyType":"xxxxx",
                     "keyValue":"xxxxxx",
                     "source":"ODS"
                  },
                  {
                     "application":"",
                     "keyType":"PERSONID",
                     "keyValue":"xxxxx",
                     "source":"EM"
                  },
                  {
                     "application":"",
                     "keyType":"PERSONID",
                     "keyValue":"xxxxxx",
                     "source":"WPP"
                  }
               ],
               "MemberId":"xxxxx",
               "MemberDependentCode":"xxx",
               "MemberSource":"xx"
            }
         ]
      },
      "MetaData":{
         "CorrelationId":"undefined"
      },
      "Status":{
         "type":"OK",
         "code":"200",

      }
   }
}

Body:
There is no native method for parsing JSON structures using XPath in Javascript, so you'll need to use a library of some kind.

As you've included the JQuery tag in your question, jQuery-JSONPath would be a good choice: https://github.com/wilhelm-murdoch/jQuery-JSONPath

Using that, your query would simply be:

var path = $.JSONPath({data: JSONOut});
homePhoneDetails = path.query("$.Response.Details.MemberDetails[0].PhoneList[?(@.type == 'Home')].number");

See JS Fiddle here for a working example: https://jsfiddle.net/qy4end8k/


问:
select max between two columns in linq
i have dateSend Column and dateEdit Column in product table, i can select max dateSend with this code:

```<code>(from pro in Products.ToList()
select new { pro.DateSend }).Max();
</code>```

but i have max between dateSend and dateEdit, please help me.

答:
Same code but with One LinQ

```<code>   (From pro in Products.ToList
    Let max = {pro.DateSend, pro.DateEdit}.Max
    select max).Max
</code>```

If pro items not a valid DateTime, It will crash or return unexpected result.

Other solution(Parsing the Products list items):

```<code> (From pro in Products.ToList
    Let DSend as DateTime = Convert.ToDateTime(Iif(ValidDateTime(pro.DateSend), pro.DateSend, DateTime.MinValue))
    Let DEdit as DateTime = Convert.ToDateTime(Iif(ValidDateTime(pro.DateEdit), pro.DateEdit, DateTime.MinValue))
    Let MaxDate as DateTime= {DSend, DEdit}.Max
    select MaxDate).Max

private function ValidDateTime(ByVal Dat as Object) as Boolean
   if Dat Is Nothing OrElse IsDbNull(Dat) OrElse String.IsNullOrEmpty(Dat)  then
      return false
   end if

   return true
end function
</code>```

You can replace the ValidDateTime with an "Iif".

Other example returning max value of Double items, but in the personalized object(MyObject), items are String type.

```<code>  (From Item as MyObject in MyListOfObject
    Let Frec as Double = Convert.ToDouble(Iif(String.IsNullOrEmpty(Item.Frecuency),0,Item.Frecuency))
    Let Pot as Double = Convert.ToDouble(Iif(String.IsNullOrEmpty(Item.Power),0,Item.Power))
    Let max as Double= {Frec, Pot}.Max
    select max).Max
</code>```

Recap

Declare Column Items separately. Parse It(If you need)

Create an Item for store the max value of the row(all columns)

Create an Array, put in all declared Items and asign array to the before declared item(Item created in step 2)

Append in the end of the array the Max property like this: {Item1, Item2,...}.Max

Create Select fr return the Max item

Append in the end the linq Max property. (MyLinQ).Max

I hope this code helps to someone.
Sorry for my English.

Title: select max between two columns in linq

Body:
i have dateSend Column and dateEdit Column in product table, i can select max dateSend with this code:

(from pro in Products.ToList()
select new { pro.DateSend }).Max();

but i have max between dateSend and dateEdit, please help me.

Body:
Same code but with One LinQ

   (From pro in Products.ToList
    Let max = {pro.DateSend, pro.DateEdit}.Max
    select max).Max

If pro items not a valid DateTime, It will crash or return unexpected result.

Other solution(Parsing the Products list items):

 (From pro in Products.ToList
    Let DSend as DateTime = Convert.ToDateTime(Iif(ValidDateTime(pro.DateSend), pro.DateSend, DateTime.MinValue))
    Let DEdit as DateTime = Convert.ToDateTime(Iif(ValidDateTime(pro.DateEdit), pro.DateEdit, DateTime.MinValue))
    Let MaxDate as DateTime= {DSend, DEdit}.Max
    select MaxDate).Max

private function ValidDateTime(ByVal Dat as Object) as Boolean
   if Dat Is Nothing OrElse IsDbNull(Dat) OrElse String.IsNullOrEmpty(Dat)  then
      return false
   end if

   return true
end function

You can replace the ValidDateTime with an "Iif".

Other example returning max value of Double items, but in the personalized object(MyObject), items are String type.

  (From Item as MyObject in MyListOfObject
    Let Frec as Double = Convert.ToDouble(Iif(String.IsNullOrEmpty(Item.Frecuency),0,Item.Frecuency))
    Let Pot as Double = Convert.ToDouble(Iif(String.IsNullOrEmpty(Item.Power),0,Item.Power))
    Let max as Double= {Frec, Pot}.Max
    select max).Max

Recap

Declare Column Items separately. Parse It(If you need)

Create an Item for store the max value of the row(all columns)

Create an Array, put in all declared Items and asign array to the before declared item(Item created in step 2)

Append in the end of the array the Max property like this: {Item1, Item2,...}.Max

Create Select fr return the Max item

Append in the end the linq Max property. (MyLinQ).Max

I hope this code helps to someone.
Sorry for my English.