问:
d3v4 Lollipop chart - refactored conversion - static
-- end goal

-- current attempt

I am interested in adapting the d3v3 lollipop chart into v4.

ref - https://bl.ocks.org/laysent/5739f087ec78e4386a6a

//version 3
https://jsfiddle.net/urmtj3v4/1/

//version 4 -- more simple variant - with placeholder circles as a POC
https://jsfiddle.net/ynmcfk3a/1/

^ but the circles are not sitting on the stalks correctly - they seem offset - what the issue is with the current calculation

```<code>                var lolliradian = 20;

                lollipop.selectAll("circle")
                  .data(data)
                  .enter()
                  .append("circle")
                  //.transition()
                  //.duration(1000)
                    .attr("cx", function(d) { return x(d.label) - x.bandwidth()/2 + lolliradian/2 ; })
                    .attr("cy", function(d) { return y(d.value); })
                    .attr("r", lolliradian)
                    .attr("fill", "#69b3a2");
</code>```

答:
I've managed to finish conversion of the chart.

//d3v4 lollipop chart I
https://jsfiddle.net/ynmcfk3a/1/

A hybrid bar chart with circle tips.

        LolliPop I

```<code>    <!--libs-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://d3js.org/d3.v4.min.js"></script>

    <!--js-->
    <script>

        $(document).ready(function() {

            var $this = $('.lollipopchart');

            var data = [
                {
                    label: 'Toblerone',
                    value: 10,
                },
                {
                    label: 'Snickers',
                    value: 25,
                },
                {
                    label: 'Jawbreakers',
                    value: 60,
                },
                {
                    label: 'Gummi Worms',
                    value: 20,
                },
            ];

            var width = $this.data('width'),
                height = $this.data('height');

            var color = d3.scaleOrdinal()
                .range(["#eb6383", "#fa9191", "#ffe9c5", "#b4f2e1"]);

            data.forEach(function(d) {
                d.total = +d.value;
            });

            var margin = {top: 20, right: 20, bottom: 85, left: 20},
                width = width - margin.left - margin.right,
                height = height - margin.top - margin.bottom;

            var x = d3.scaleBand()
                      .range([0, width])
                      .padding(0.9);
            var y = d3.scaleLinear()
                      .range([height, 0]);

            x.domain(data.map(function(d) { return d.label; }));
            y.domain([0, d3.max(data, function(d) { return d.total; })]);

            var svg = d3.select($this[0])
                .append("svg")
                .attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.top + margin.bottom)
                .append("g")
                .attr('class', 'lollipopchart')
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

            var lollipop = svg.append('g').attr('class', 'lollipop');

            var bars = lollipop
                .append("g")
                .attr('class', 'bars')

            bars.selectAll(".bar")
                    .data(data)
                    .enter().append("rect")
                    .attr("class", "bar")
                    .attr('fill', function(d, i) {
                        return color(i);
                    })
                    .attr("x", function(d) { return x(d.label); })
                    .attr("width", x.bandwidth())
                    .attr("y", function(d) { return y(d.value); })
                    .attr("height", function(d) { return height - y(d.total); });

                var lolliradian = 10;

            var circles = lollipop
                .append("g")
                .attr('class', 'circles');

                circles.selectAll("circle")
                  .data(data)
                  .enter()
                  .append("circle")
                  //.transition()
                  //.duration(1000)
                    .attr("cx", function(d) { return (x(d.label) + x.bandwidth()/2); })
                    .attr("cy", function(d) { return y(d.value); })
                    .attr("r", lolliradian)
                .attr('fill', function(d, i) {
                    return color(i);
                })

            var innercircles = lollipop
                .append("g")
                .attr('class', 'innercircles');

                innercircles.selectAll("circle")
                  .data(data)
                  .enter()
                  .append("circle")
                  //.transition()
                  //.duration(1000)
                    .attr("cx", function(d) { return (x(d.label) + x.bandwidth()/2); })
                    .attr("cy", function(d) { return y(d.value); })
                    .attr("r", lolliradian-5)
                .attr('fill', '#ffffff')

            lollipop.append("g")
                .attr("transform", "translate(0," + height + ")")
                .call(d3.axisBottom(x))
                .selectAll("text")
                .style("text-anchor", "end")
                .attr("dx", "-.8em")
                .attr("dy", ".15em")
                .attr("transform", "rotate(-65)");

            lollipop.append("g")
                .call(d3.axisLeft(y));

        });

    </script>
    <!--js-->

    <!--css-->
    <style>
        body {
            background: #ffd;
        }
    </style>
    <!--css-->
</head>
<body>

    <h1>LolliPop I</h1>
    <!--html-->
    <div
        class="lollipopchart"
        data-width="300"
        data-height="300"
    />
    <!--html-->

</body>
</code>```

Body:
-- end goal

-- current attempt

I am interested in adapting the d3v3 lollipop chart into v4.

ref - https://bl.ocks.org/laysent/5739f087ec78e4386a6a

//version 3
https://jsfiddle.net/urmtj3v4/1/

//version 4 -- more simple variant - with placeholder circles as a POC
https://jsfiddle.net/ynmcfk3a/1/

^ but the circles are not sitting on the stalks correctly - they seem offset - what the issue is with the current calculation

                var lolliradian = 20;

                lollipop.selectAll("circle")
                  .data(data)
                  .enter()
                  .append("circle")
                  //.transition()
                  //.duration(1000)
                    .attr("cx", function(d) { return x(d.label) - x.bandwidth()/2 + lolliradian/2 ; })
                    .attr("cy", function(d) { return y(d.value); })
                    .attr("r", lolliradian)
                    .attr("fill", "#69b3a2");

Body:
I've managed to finish conversion of the chart.

//d3v4 lollipop chart I
https://jsfiddle.net/ynmcfk3a/1/

A hybrid bar chart with circle tips.

        LolliPop I

    <!--libs-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://d3js.org/d3.v4.min.js"></script>

    <!--js-->
    <script>

        $(document).ready(function() {

            var $this = $('.lollipopchart');

            var data = [
                {
                    label: 'Toblerone',
                    value: 10,
                },
                {
                    label: 'Snickers',
                    value: 25,
                },
                {
                    label: 'Jawbreakers',
                    value: 60,
                },
                {
                    label: 'Gummi Worms',
                    value: 20,
                },
            ];

            var width = $this.data('width'),
                height = $this.data('height');

            var color = d3.scaleOrdinal()
                .range(["#eb6383", "#fa9191", "#ffe9c5", "#b4f2e1"]);

            data.forEach(function(d) {
                d.total = +d.value;
            });

            var margin = {top: 20, right: 20, bottom: 85, left: 20},
                width = width - margin.left - margin.right,
                height = height - margin.top - margin.bottom;

            var x = d3.scaleBand()
                      .range([0, width])
                      .padding(0.9);
            var y = d3.scaleLinear()
                      .range([height, 0]);

            x.domain(data.map(function(d) { return d.label; }));
            y.domain([0, d3.max(data, function(d) { return d.total; })]);

            var svg = d3.select($this[0])
                .append("svg")
                .attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.top + margin.bottom)
                .append("g")
                .attr('class', 'lollipopchart')
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

            var lollipop = svg.append('g').attr('class', 'lollipop');

            var bars = lollipop
                .append("g")
                .attr('class', 'bars')

            bars.selectAll(".bar")
                    .data(data)
                    .enter().append("rect")
                    .attr("class", "bar")
                    .attr('fill', function(d, i) {
                        return color(i);
                    })
                    .attr("x", function(d) { return x(d.label); })
                    .attr("width", x.bandwidth())
                    .attr("y", function(d) { return y(d.value); })
                    .attr("height", function(d) { return height - y(d.total); });

                var lolliradian = 10;

            var circles = lollipop
                .append("g")
                .attr('class', 'circles');

                circles.selectAll("circle")
                  .data(data)
                  .enter()
                  .append("circle")
                  //.transition()
                  //.duration(1000)
                    .attr("cx", function(d) { return (x(d.label) + x.bandwidth()/2); })
                    .attr("cy", function(d) { return y(d.value); })
                    .attr("r", lolliradian)
                .attr('fill', function(d, i) {
                    return color(i);
                })

            var innercircles = lollipop
                .append("g")
                .attr('class', 'innercircles');

                innercircles.selectAll("circle")
                  .data(data)
                  .enter()
                  .append("circle")
                  //.transition()
                  //.duration(1000)
                    .attr("cx", function(d) { return (x(d.label) + x.bandwidth()/2); })
                    .attr("cy", function(d) { return y(d.value); })
                    .attr("r", lolliradian-5)
                .attr('fill', '#ffffff')

            lollipop.append("g")
                .attr("transform", "translate(0," + height + ")")
                .call(d3.axisBottom(x))
                .selectAll("text")
                .style("text-anchor", "end")
                .attr("dx", "-.8em")
                .attr("dy", ".15em")
                .attr("transform", "rotate(-65)");

            lollipop.append("g")
                .call(d3.axisLeft(y));

        });

    </script>
    <!--js-->

    <!--css-->
    <style>
        body {
            background: #ffd;
        }
    </style>
    <!--css-->
</head>
<body>

    <h1>LolliPop I</h1>
    <!--html-->
    <div
        class="lollipopchart"
        data-width="300"
        data-height="300"
    />
    <!--html-->

</body>


来源: stackexchange

问:
Custom Javascript Variable to return dollar amount
On a product page, after product options are selected a dollar amount is shown, and I am trying to create a custom javascript variable in google tag manager to return the dollar amount when the "add to cart" button is clicked.

this is the element from my page:

```<code><span data-hook="formatted-primary-price">$42.00</span>
</code>```

I'm trying to return the "$42.00" text as the "order value"

Thanks for any help!

答:
After getting the element using something like priceElement = document.querySelector("span[data-hook='formatted-primary-price']")

you could get its value using rawValue = priceElement.innertext.

You should also trim the dollar sign off the amount, and convert it into an integer number of cents so that you can't get stuck with floating point errors. Something like orderValue = parseInt(rawValue.replace(/$\./, "")). This way your final order value for your example would be 4200.

ContentLicense: CC BY-SA 4.0

Body:
On a product page, after product options are selected a dollar amount is shown, and I am trying to create a custom javascript variable in google tag manager to return the dollar amount when the "add to cart" button is clicked.

this is the element from my page:

$42.00

I'm trying to return the "$42.00" text as the "order value"

Thanks for any help!


问:
caesar cipher does not work, can't figure why
I wrote my code and it seems fine, but there is something about it that just doesn't work and I can't figure out why. It is one caesar cipher but it just doesn't give me the expected output</p>

```<code>int main(int key, char* argv[])
{

key = atoi(argv[1]);
string ptext = get_string("plaintext: ");
int len = strlen(ptext);
printf("%s %i\n", ptext, key);`

    for (int i = 0; i < len; i++)
    {
        if (isalpha(ptext[i])){
            if (ptext[i] >= 'a' && ptext[i] <= 'z')
            {
                if (ptext[i] + key > 'z')
                {
                    printf("%c", 'a' + (key % 26)); //'a' is used to reset the ascii table so it use letters only
                }
                else{
                    printf("%c", ptext[i] + key);
                }
            if (ptext[i] >= 'A' && ptext[i] <= 'Z')
            {
                if (ptext[i] + key >= 'Z'){
                    printf("%c", (ptext[i] + (key % 26)) - 'z'); //'A' is used to reset the ascii table so it use letters only

                }
                else{
                    printf("%c", ptext[i] + key);
                }
                    }
            }
        else{
            printf("%c", ptext[i]);
        }
        }
    }
}
</code>```

答:
Incorrect handling when ptext[i] + key > 'z'.

'a' + (key % 26) does not depend on ptext[i]

```<code>if (ptext[i] + key > 'z') {
  printf("%c", 'a' + (key % 26)); // Incorrect.
} else {
  ....
}
</code>```

Instead

```<code>int sum = (ptext[i] - 'a' + key)%26 + 'a';
printf("%c", sum);
</code>```

Likewise for if (ptext[i] + key >= 'Z'){.

Body:
I wrote my code and it seems fine, but there is something about it that just doesn't work and I can't figure out why. It is one caesar cipher but it just doesn't give me the expected output

int main(int key, char* argv[])
{

key = atoi(argv[1]);
string ptext = get_string("plaintext: ");
int len = strlen(ptext);
printf("%s %i\n", ptext, key);`

    for (int i = 0; i < len; i++)
    {
        if (isalpha(ptext[i])){
            if (ptext[i] >= 'a' && ptext[i] <= 'z')
            {
                if (ptext[i] + key > 'z')
                {
                    printf("%c", 'a' + (key % 26)); //'a' is used to reset the ascii table so it use letters only
                }
                else{
                    printf("%c", ptext[i] + key);
                }
            if (ptext[i] >= 'A' && ptext[i] <= 'Z')
            {
                if (ptext[i] + key >= 'Z'){
                    printf("%c", (ptext[i] + (key % 26)) - 'z'); //'A' is used to reset the ascii table so it use letters only

                }
                else{
                    printf("%c", ptext[i] + key);
                }
                    }
            }
        else{
            printf("%c", ptext[i]);
        }
        }
    }
}

Body:
Incorrect handling when ptext[i] + key > 'z'.

'a' + (key % 26) does not depend on ptext[i]

if (ptext[i] + key > 'z') {
  printf("%c", 'a' + (key % 26)); // Incorrect.
} else {
  ....
}

Instead

int sum = (ptext[i] - 'a' + key)%26 + 'a';
printf("%c", sum);

Likewise for if (ptext[i] + key >= 'Z'){.


问:
Create own colormap using matplotlib and plot color scale
I have the following problem, I want to create my own colormap (red-mix-violet-mix-blue) that maps to values between -2 and +2 and want to use it to color points in my plot.
The plot should then have the colorscale to the right.

That is how I create the map so far. But I am not really sure if it mixes the colors.

```<code>cmap = matplotlib.colors.ListedColormap(["red","violet","blue"], name='from_list', N=None)
m = cm.ScalarMappable(norm=norm, cmap=cmap)
</code>```

That way I map the colors to the values.

```<code>colors = itertools.cycle([m.to_rgba(1.22), ..])
</code>```

Then I plot it:

```<code>for i in range(0, len(array_dg)):
  plt.plot(array_dg[i], markers.next(),alpha=alpha[i], c=colors.next())
</code>```

My problems are:

1. I can't plot the color scale.

2. I am not completely sure if my scale is creating a continues (smooth) colorscale.

答:
This seems to work for me.

```<code>def make_Ramp( ramp_colors ):
    from colour import Color
    from matplotlib.colors import LinearSegmentedColormap

    color_ramp = LinearSegmentedColormap.from_list( 'my_list', [ Color( c1 ).rgb for c1 in ramp_colors ] )
    plt.figure( figsize = (15,3))
    plt.imshow( [list(np.arange(0, len( ramp_colors ) , 0.1)) ] , interpolation='nearest', origin='lower', cmap= color_ramp )
    plt.xticks([])
    plt.yticks([])
    return color_ramp

custom_ramp = make_Ramp( ['#754a28','#893584','#68ad45','#0080a5' ] )
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following problem, I want to create my own colormap (red-mix-violet-mix-blue) that maps to values between -2 and +2 and want to use it to color points in my plot.
The plot should then have the colorscale to the right.

That is how I create the map so far. But I am not really sure if it mixes the colors.

cmap = matplotlib.colors.ListedColormap(["red","violet","blue"], name='from_list', N=None)
m = cm.ScalarMappable(norm=norm, cmap=cmap)

That way I map the colors to the values.

colors = itertools.cycle([m.to_rgba(1.22), ..])

Then I plot it:

for i in range(0, len(array_dg)):
  plt.plot(array_dg[i], markers.next(),alpha=alpha[i], c=colors.next())

My problems are:

1. I can't plot the color scale.

2. I am not completely sure if my scale is creating a continues (smooth) colorscale.

Body:
This seems to work for me.

def make_Ramp( ramp_colors ):
    from colour import Color
    from matplotlib.colors import LinearSegmentedColormap

    color_ramp = LinearSegmentedColormap.from_list( 'my_list', [ Color( c1 ).rgb for c1 in ramp_colors ] )
    plt.figure( figsize = (15,3))
    plt.imshow( [list(np.arange(0, len( ramp_colors ) , 0.1)) ] , interpolation='nearest', origin='lower', cmap= color_ramp )
    plt.xticks([])
    plt.yticks([])
    return color_ramp

custom_ramp = make_Ramp( ['#754a28','#893584','#68ad45','#0080a5' ] )


问:
List<MyObject> does not contain a definition for GetAwaiter
I have a method that returns a List<> of an object.  This method takes a while to run.

```<code>private List<MyObject> GetBigList()
{
    ... slow stuff
}
</code>```

This method is called from 4 or 5 sources.  So, I thought I would try and use async and await to keep things moving while this list builds.  I added this method:

```<code>public async Task<List<MyObject>> GetBigListAsync()
{
    var resultsTask = GetBigList();
    var resuls = await resultsTask;
    return resuls;
}
</code>```

But, on this line:

```<code>var resuls = await resultsTask;
</code>```

I get this error:

List<MyObject> does not contain a definition for GetAwaiter,
  and no extension method 'GetAwaiter' accepting a first argument of type List<MyObject> could be found.

What am I missing?

答:
A couple of years later but I feel it is worth to add for the collection, once people search for the resolution since .NET has changed quite a bit:

return await Task.FromResult(GetBigList())

Body:
I have a method that returns a List<> of an object.  This method takes a while to run.

private List<MyObject> GetBigList()
{
    ... slow stuff
}

This method is called from 4 or 5 sources.  So, I thought I would try and use async and await to keep things moving while this list builds.  I added this method:

public async Task<List<MyObject>> GetBigListAsync()
{
    var resultsTask = GetBigList();
    var resuls = await resultsTask;
    return resuls;
}

But, on this line:

var resuls = await resultsTask;

I get this error:

List<MyObject> does not contain a definition for GetAwaiter,
  and no extension method 'GetAwaiter' accepting a first argument of type List<MyObject> could be found.

What am I missing?


问:
Slot contents are merged between Tabs in VueJS
I have this TabPanel where I am rendering multiple tabs. Each Panel inside TabPanel uses/extends Panel where I am using slots. However, during tab switch content of Tabs are getting merged.

```<code><template>
  <div class>
    <div class>
      <ul class>
        <li
          style="display: inline-block; padding:10px; margin: 10px; border: 1px solid #ccc"
          v-for="(panel, index) in panels"
          :key="index"
          @click="selectTab(index)"
          :ref="'panel' + index"
        >{{ panel.title }}</li>
      </ul>
    </div>
    <div class>
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: "TabPanel",
  data() {
    return {
      panels: [],
      selectedIndex: 0
    };
  },
  methods: {
    selectTab(panelIndex) {
      this.selectedIndex = panelIndex;
      this.panels.forEach((panel, index) => {
        panel.isActive = index === panelIndex;
      });
    }
  },
  created() {
    this.panels = this.$children;
  },
  mounted() {
    this.selectTab(0);
  }
};
</script>
</code>```

Panel code

```<code><template>
  <div v-show="isActive">
    <slot></slot>
  </div>
</template>

<script>
export default {
  name: "Panel",
  props: {
    title: {
      type: String,
      required: true
    },
    panelId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      isActive: true
    };
  }
};
</script>
</code>```

Is there anyway to fix this issue. This is the CodeSandbox link to demonstrate this issue since its easier to visualize problem that way I think.

答:
Dashboard.vue and RosePanel.vue changes isActive data but they are not doing nothing whit this.

One option is to set a v-show/v-if to each own <Panel>:

<Panel v-show="isActive" :title="title" :panelId="panelId">Content from Dashboard</Panel>
```

CodeSandbox: https://codesandbox.io/s/charming-hamilton-jz1og

Body:
I have this TabPanel where I am rendering multiple tabs. Each Panel inside TabPanel uses/extends Panel where I am using slots. However, during tab switch content of Tabs are getting merged.

<template>

{{ panel.title }}

      <slot></slot>

</template>

Panel code

<template>

    <slot></slot>

</template>

Is there anyway to fix this issue. This is the CodeSandbox link to demonstrate this issue since its easier to visualize problem that way I think.

Body:
Dashboard.vue and RosePanel.vue changes isActive data but they are not doing nothing whit this.

One option is to set a v-show/v-if to each own <Panel>:

<Panel v-show="isActive" :title="title" :panelId="panelId">Content from Dashboard</Panel>

CodeSandbox: https://codesandbox.io/s/charming-hamilton-jz1og


问:
Overlay text for OfficeUI fabric PivotItem
is it possible to add an overlay when individual buttons in a Pivot are moused over?

For example, when I hover my mouse over the Search icon I want to display overlay text saying "search". I have tried to use the OverlayTrigger from react-bootstrap, but if the PivotItem tag is surrounded, it will not display in the Pivot. I also tried the onMouseEnter function in the PivotItem tag, but this is called when the component shown by this pivot is moused over, not the icon in the Pivot.

```<code><Pivot>
      <OverlayTrigger
        placement={'bottom'}
        overlay={
          <Tooltip>
            My overlay text
            </Tooltip>
        }>
          <PivotItem itemIcon="Search">  // this pivot will not show up
            <Search />
          </PivotItem>
      </OverlayTrigger>
</Pivot>
</code>```

any ideas?

```<code>      // onMouseEnter will be called with <Search /> is moused over, not the search icon
      <PivotItem itemIcon="Search" onMouseEnter={() => console.log("moused over")} >
        <Search />
      </PivotItem>
</code>```

答:
If possible, strongly consider not using tooltips and instead make the pivot headers themselves descriptive. Tooltips are not discoverable and don't work well for touchscreen users.

That said, this is possible by defining onRenderItemLink in each PivotItem like the following example:

```<code>    <Pivot aria-label="Basic Pivot Example">
      <PivotItem onRenderItemLink={() => <TooltipHost content="This is the tooltip content">some text</TooltipHost>}>
        lorem ipsum
      </PivotItem>
      <PivotItem headerText="Recent">
        lorem ipsum
      </PivotItem>
    </Pivot>
</code>```

Body:
is it possible to add an overlay when individual buttons in a Pivot are moused over?

For example, when I hover my mouse over the Search icon I want to display overlay text saying "search". I have tried to use the OverlayTrigger from react-bootstrap, but if the PivotItem tag is surrounded, it will not display in the Pivot. I also tried the onMouseEnter function in the PivotItem tag, but this is called when the component shown by this pivot is moused over, not the icon in the Pivot.

<Pivot>
      <OverlayTrigger
        placement={'bottom'}
        overlay={
          <Tooltip>
            My overlay text
            </Tooltip>
        }>
          <PivotItem itemIcon="Search">  // this pivot will not show up
            <Search />
          </PivotItem>
      </OverlayTrigger>
</Pivot>

any ideas?

      // onMouseEnter will be called with <Search /> is moused over, not the search icon
      <PivotItem itemIcon="Search" onMouseEnter={() => console.log("moused over")} >
        <Search />
      </PivotItem>

Body:
If possible, strongly consider not using tooltips and instead make the pivot headers themselves descriptive. Tooltips are not discoverable and don't work well for touchscreen users.

That said, this is possible by defining onRenderItemLink in each PivotItem like the following example:

    <Pivot aria-label="Basic Pivot Example">
      <PivotItem onRenderItemLink={() => <TooltipHost content="This is the tooltip content">some text</TooltipHost>}>
        lorem ipsum
      </PivotItem>
      <PivotItem headerText="Recent">
        lorem ipsum
      </PivotItem>
    </Pivot>


问:
Why code removing elements from HashSet Takes much longer than adding to HashMap?
I am solving this question on Leetcode. https://leetcode.com/problems/word-ladder

Given two words (beginWord and endWord), and a dictionary's word list,
  find the length of shortest transformation sequence from beginWord to
  endWord, such that:

Only one letter can be changed at a time.

Each transformed word must exist in the word list.

The approach I took takes 1100 ms of time and the editorial approach takes 43 ms time. Although the difference is merely that editorial uses a hashmap instead of hashset used by me and an extra hashset.remove() method in my approach. Since the time difference is little high, someone please help me understand the reason. Thanks.

Below are the two code snaps, the editorial and my solution. They are almost identical, and difference is marked explicitly in code.

My solution : takes 1100 ms

```<code>class Solution {
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {

        Map<String, ArrayList<String>> m = new HashMap<>();
        int len = beginWord.length();
        for(String word : wordList) {
            for(int i = 0; i < len; i++) {
                String newWord = word.substring(0, i) + "*" + word.substring(i+1, len);
                m.computeIfAbsent(newWord, k -> new ArrayList<String>()).add(word);
            }
        }
        HashSet<String> set = new HashSet<>(wordList);
        if(!set.contains(endWord))
            return 0;
        Queue<String> q = new LinkedList<>();
        q.offer(beginWord);
        int level = 1;
        int res = Integer.MAX_VALUE;;
        while(!q.isEmpty()) {

            int size = q.size();

            while(size-- > 0) {
                String s = q.poll();

                for(int i = 0; i < len; i++) {
                    String newWord = s.substring(0, i) + "*" + s.substring(i+1, len);
                    for(String str : m.getOrDefault(newWord, new ArrayList<>())) {
                        if(str.equals(endWord)) {
                            return level + 1;
                        }
                        *** The condition and content are different ***
                        if(set.contains(str))
                        q.offer(str);
                    }
                }
                set.remove(s);
            }
            level++;
        }

        return 0;
    }
}
</code>```

Editorial Solution : takes 40 ms

```<code>class Solution {
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {

        Map<String, ArrayList<String>> m = new HashMap<>();
        int len = beginWord.length();
        for(String word : wordList) {
            for(int i = 0; i < len; i++) {
                String newWord = word.substring(0, i) + "*" + word.substring(i+1, len);
                m.computeIfAbsent(newWord, k -> new ArrayList<String>()).add(word);
            }
        }

        // Visited to make sure we don't repeat processing same word.
        ***Next line is not in my code***
        Map<String, Boolean> visited = new HashMap<>();
        visited.put(beginWord, true);
        HashSet<String> set = new HashSet<>(wordList);
        if(!set.contains(endWord))
            return 0;
        Queue<String> q = new LinkedList<>();
        q.offer(beginWord);
        int level = 1;
        int res = Integer.MAX_VALUE;;
        while(!q.isEmpty()) {

            int size = q.size();

            while(size-- > 0) {
                String s = q.poll();

                for(int i = 0; i < len; i++) {
                    String newWord = s.substring(0, i) + "*" + s.substring(i+1, len);
                    for(String str : m.getOrDefault(newWord, new ArrayList<>())) {
                        if(str.equals(endWord)) {
                            return level + 1;
                        }
                        *** The condition and content are different ***
                        if (!visited.containsKey(str)) {
                            visited.put(str, true);
                            q.add(str);
                        }
                    }
                }
            }
            level++;
        }

        return 0;
    }
}
</code>```

答:
This problem is basically finding a shortest path in an unweighted graph, and both solutions use BFS.

I did not dive into too much details into the editorial solution, but your solution does not run in O(|V| + |E|), and as such can be suboptimal.

Note that you remove a word from the set when you are done processing it, but you use the set to determine processing when you add a word to the queue.

Think of this example:

```<code>dictionary = { aaa, aba, aab, abb, bbb }
start = aaa
end = bbb

first iteration:
set = { aaa, aba, aab, abb, bbb }
q = { aaa }
In this iteration: remove aaa from set and q, insert aba and aab.

second iteration:
set = { aba, aab, abb, bbb }
q = { aba, aab }
process aba:
add to queue abb
remove from set and q aba
process aab:
add to queue abb
remove from set and queue aab

third iteration:
set = { abb, bbb }
q = { abb, abb }
in this iteraiotn you will process abb twice, and add bbb twice.
</code>```

This behavior grows exponentially, each of the nodes inserted twice could add again the same node multiple times, causing growth of 2*2*2*...

The solution is quite simple, you need to be consistent, and choose one of two options:

Keep removing the item from set in the same place, but add an early continue polling an element not in the set from the queue.

Keep checking if an element is in set before inserting it - but also remove the element from the set once you add it to the queue.

Body:
I am solving this question on Leetcode. https://leetcode.com/problems/word-ladder

Given two words (beginWord and endWord), and a dictionary's word list,
  find the length of shortest transformation sequence from beginWord to
  endWord, such that:

Only one letter can be changed at a time.

Each transformed word must exist in the word list.

The approach I took takes 1100 ms of time and the editorial approach takes 43 ms time. Although the difference is merely that editorial uses a hashmap instead of hashset used by me and an extra hashset.remove() method in my approach. Since the time difference is little high, someone please help me understand the reason. Thanks.

Below are the two code snaps, the editorial and my solution. They are almost identical, and difference is marked explicitly in code.

My solution : takes 1100 ms

class Solution {
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {

        Map<String, ArrayList<String>> m = new HashMap<>();
        int len = beginWord.length();
        for(String word : wordList) {
            for(int i = 0; i < len; i++) {
                String newWord = word.substring(0, i) + "*" + word.substring(i+1, len);
                m.computeIfAbsent(newWord, k -> new ArrayList<String>()).add(word);
            }
        }
        HashSet<String> set = new HashSet<>(wordList);
        if(!set.contains(endWord))
            return 0;
        Queue<String> q = new LinkedList<>();
        q.offer(beginWord);
        int level = 1;
        int res = Integer.MAX_VALUE;;
        while(!q.isEmpty()) {

            int size = q.size();

            while(size-- > 0) {
                String s = q.poll();

                for(int i = 0; i < len; i++) {
                    String newWord = s.substring(0, i) + "*" + s.substring(i+1, len);
                    for(String str : m.getOrDefault(newWord, new ArrayList<>())) {
                        if(str.equals(endWord)) {
                            return level + 1;
                        }
                        *** The condition and content are different ***
                        if(set.contains(str))
                        q.offer(str);
                    }
                }
                set.remove(s);
            }
            level++;
        }

        return 0;
    }
}

Editorial Solution : takes 40 ms

class Solution {
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {

        Map<String, ArrayList<String>> m = new HashMap<>();
        int len = beginWord.length();
        for(String word : wordList) {
            for(int i = 0; i < len; i++) {
                String newWord = word.substring(0, i) + "*" + word.substring(i+1, len);
                m.computeIfAbsent(newWord, k -> new ArrayList<String>()).add(word);
            }
        }

        // Visited to make sure we don't repeat processing same word.
        ***Next line is not in my code***
        Map<String, Boolean> visited = new HashMap<>();
        visited.put(beginWord, true);
        HashSet<String> set = new HashSet<>(wordList);
        if(!set.contains(endWord))
            return 0;
        Queue<String> q = new LinkedList<>();
        q.offer(beginWord);
        int level = 1;
        int res = Integer.MAX_VALUE;;
        while(!q.isEmpty()) {

            int size = q.size();

            while(size-- > 0) {
                String s = q.poll();

                for(int i = 0; i < len; i++) {
                    String newWord = s.substring(0, i) + "*" + s.substring(i+1, len);
                    for(String str : m.getOrDefault(newWord, new ArrayList<>())) {
                        if(str.equals(endWord)) {
                            return level + 1;
                        }
                        *** The condition and content are different ***
                        if (!visited.containsKey(str)) {
                            visited.put(str, true);
                            q.add(str);
                        }
                    }
                }
            }
            level++;
        }

        return 0;
    }
}

Body:
This problem is basically finding a shortest path in an unweighted graph, and both solutions use BFS.

I did not dive into too much details into the editorial solution, but your solution does not run in O(|V| + |E|), and as such can be suboptimal.

Note that you remove a word from the set when you are done processing it, but you use the set to determine processing when you add a word to the queue.

Think of this example:

dictionary = { aaa, aba, aab, abb, bbb }
start = aaa
end = bbb

first iteration:
set = { aaa, aba, aab, abb, bbb }
q = { aaa }
In this iteration: remove aaa from set and q, insert aba and aab.

second iteration:
set = { aba, aab, abb, bbb }
q = { aba, aab }
process aba:
add to queue abb
remove from set and q aba
process aab:
add to queue abb
remove from set and queue aab

third iteration:
set = { abb, bbb }
q = { abb, abb }
in this iteraiotn you will process abb twice, and add bbb twice.

This behavior grows exponentially, each of the nodes inserted twice could add again the same node multiple times, causing growth of 2*2*2*...

The solution is quite simple, you need to be consistent, and choose one of two options:

Keep removing the item from set in the same place, but add an early continue polling an element not in the set from the queue.

Keep checking if an element is in set before inserting it - but also remove the element from the set once you add it to the queue.


问:
Unable to simultaneously satisfy constraints when adding any non-zero constraint programmatically
```<code>import UIKit

@IBDesignable
class LargeButtonWithIcon: UIView {

    var iconBackgroundView: UIView?
    var iconIv: UIImageView?

    @IBInspectable var iconImage: UIImage? {
        didSet {
            self.iconIv?.image = iconImage
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        initializeView()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)

        initializeView()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()

        initializeView()
    }

    private func initializeView() {
        initializeIconView()
    }

    private func initializeIconView() {
        iconBackgroundView = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.height, height: self.frame.height))
        addSubview(iconBackgroundView!)

        iconBackgroundView?.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
        iconBackgroundView?.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        iconBackgroundView?.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true

        iconIv = UIImageView()
        iconIv?.image = iconImage
        iconIv?.clipsToBounds = true
        iconIv?.contentMode = .scaleAspectFit
        iconIv?.translatesAutoresizingMaskIntoConstraints = false

        iconBackgroundView!.addSubview(iconIv!)

        iconBackgroundView?.leadingAnchor.constraint(equalTo: iconBackgroundView!.leadingAnchor, constant: 20).isActive = true
//        iconBackgroundView?.topAnchor.constraint(equalTo: iconBackgroundView!.topAnchor, constant: 0).isActive = true
//        iconBackgroundView?.rightAnchor.constraint(equalTo: iconBackgroundView!.rightAnchor, constant: 20).isActive = true
//        iconBackgroundView?.bottomAnchor.constraint(equalTo: iconBackgroundView!.bottomAnchor, constant: 20).isActive = true
//        iconBackgroundView?.centerXAnchor.constraint(equalTo: iconBackgroundView!.centerXAnchor).isActive = true
//        iconBackgroundView?.centerYAnchor.constraint(equalTo: iconBackgroundView!.centerYAnchor).isActive = true
    }

}

</code>```

I'm trying to achieve the following:

iconBackgroundView is the square at the left of the button, iconIv is the icon in that square.

When I activate any non-zero constraint for the iconIv (or all of them), it prints the warning:

```<code>2020-06-03 01:26:37.163392+0300 FindDifferences[5310:34823037] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x6000012bc6e0 UIView:0x7f880c0075a0.leading == UIView:0x7f880c0075a0.leading + 20   (active)>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x6000012bc6e0 UIView:0x7f880c0075a0.leading == UIView:0x7f880c0075a0.leading + 20   (active)>
</code>```

But if I change the its constant to 0, it does not. Why, and how should I center the iconIv in this view with given padding?

答:
This line doesn't make sense because you're trying to set a view's leading anchor equal to its own leading anchor.

```<code>iconBackgroundView?.leadingAnchor.constraint(equalTo: iconBackgroundView!.leadingAnchor, constant: 20).isActive = true

</code>```

I think what you actually want is this:

```<code>iconIv?.leadingAnchor.constraint(equalTo: iconBackgroundView!.leadingAnchor, constant: 20).isActive = true
</code>```

Body:
import UIKit

@IBDesignable
class LargeButtonWithIcon: UIView {

    var iconBackgroundView: UIView?
    var iconIv: UIImageView?

    @IBInspectable var iconImage: UIImage? {
        didSet {
            self.iconIv?.image = iconImage
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        initializeView()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)

        initializeView()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()

        initializeView()
    }

    private func initializeView() {
        initializeIconView()
    }

    private func initializeIconView() {
        iconBackgroundView = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.height, height: self.frame.height))
        addSubview(iconBackgroundView!)

        iconBackgroundView?.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
        iconBackgroundView?.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        iconBackgroundView?.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true

        iconIv = UIImageView()
        iconIv?.image = iconImage
        iconIv?.clipsToBounds = true
        iconIv?.contentMode = .scaleAspectFit
        iconIv?.translatesAutoresizingMaskIntoConstraints = false

        iconBackgroundView!.addSubview(iconIv!)

        iconBackgroundView?.leadingAnchor.constraint(equalTo: iconBackgroundView!.leadingAnchor, constant: 20).isActive = true
//        iconBackgroundView?.topAnchor.constraint(equalTo: iconBackgroundView!.topAnchor, constant: 0).isActive = true
//        iconBackgroundView?.rightAnchor.constraint(equalTo: iconBackgroundView!.rightAnchor, constant: 20).isActive = true
//        iconBackgroundView?.bottomAnchor.constraint(equalTo: iconBackgroundView!.bottomAnchor, constant: 20).isActive = true
//        iconBackgroundView?.centerXAnchor.constraint(equalTo: iconBackgroundView!.centerXAnchor).isActive = true
//        iconBackgroundView?.centerYAnchor.constraint(equalTo: iconBackgroundView!.centerYAnchor).isActive = true
    }

}

I'm trying to achieve the following:

iconBackgroundView is the square at the left of the button, iconIv is the icon in that square.

When I activate any non-zero constraint for the iconIv (or all of them), it prints the warning:

2020-06-03 01:26:37.163392+0300 FindDifferences[5310:34823037] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x6000012bc6e0 UIView:0x7f880c0075a0.leading == UIView:0x7f880c0075a0.leading + 20   (active)>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x6000012bc6e0 UIView:0x7f880c0075a0.leading == UIView:0x7f880c0075a0.leading + 20   (active)>

But if I change the its constant to 0, it does not. Why, and how should I center the iconIv in this view with given padding?

Body:
This line doesn't make sense because you're trying to set a view's leading anchor equal to its own leading anchor.

iconBackgroundView?.leadingAnchor.constraint(equalTo: iconBackgroundView!.leadingAnchor, constant: 20).isActive = true

I think what you actually want is this:

iconIv?.leadingAnchor.constraint(equalTo: iconBackgroundView!.leadingAnchor, constant: 20).isActive = true


问:
Snowflake Python Connector: Copy Command Status and Error Handling
According to the Snowflake docs, when a user executes a copy command it will return 1 of 3 status values:

loaded

load failed

partially loaded

My question is if I use the Python Snowflake Connector (see example code below) to execute a copy command is an exception raised if the status returned is load failed or partially loaded?

Thank you!

```<code>copy_dml = 'copy into database.schema.table ' \
'from @fully_qualified_stage pattern = \'.*'+ table_name +'.*[.]json\' ' \
'file_format = (format_name = fully_qualified_json_format) ' \
'force = true;'

 try:
        import snowflake.connector
#-------------------------------------------------------------------------------------------------------------------------------
        #snowflake variables
        snowflake_warehouse = credentials.iloc[0]['snowflake_warehouse']
        snowflake_account = credentials.iloc[0]['snowflake_account']
        snowflake_role = credentials.iloc[0]['snowflake_role']
        snowflake_username = credentials.iloc[0]['Username']
        snowflake_password = credentials.iloc[0]['Password']
        snowflake_connection = ''
        cs = ''#snowflake connection cursor
        exec_copy_dml = ''
        copy_result_field_metadata = ''
        copy_result = ''
        snowflake_copy_result_df = ''
#-------------------------------------------------------------------------------------------------------------------------------
        # load JSON file(s) into Snowflake
        snowflake_connection = snowflake.connector.connect(
        user = snowflake_username,
        password = snowflake_password,
        account = snowflake_account,
        warehouse = snowflake_warehouse,
        role = snowflake_role)
        cs = snowflake_connection.cursor()
        exec_copy_dml = cs.execute(copy_dml)
        copy_result =  exec_copy_dml.fetchall()
        copy_result_field_metadata = cs.description
        snowflake_copy_result_df = snowflake_results_df(copy_result_field_metadata,copy_result)
    except snowflake.connector.errors.ProgrammingError as copy_error:
        copy_exception_message = "There was a problem loading JSON files to Snowflake," + \
        "a snowflake.connector.errors.ProgrammingError exception was raised."
        print(copy_exception_message)
        raise
    except Exception as error_message:
        raise
    finally:
        snowflake_connection.close()
</code>```

答:
After you issue your COPY INTO dml, you can run the following query -

```<code>SELECT * FROM TABLE(VALIDATE(TABLE_NAME, job_id => '_last'))
</code>```

This will give you details on the files that you were trying to load. It will normally return empty, unless you encountered issues upload.

You can save this save results in an object and make necessary control adjustments.

Body:
According to the Snowflake docs, when a user executes a copy command it will return 1 of 3 status values:

loaded

load failed

partially loaded

My question is if I use the Python Snowflake Connector (see example code below) to execute a copy command is an exception raised if the status returned is load failed or partially loaded?

Thank you!

copy_dml = 'copy into database.schema.table ' \
'from @fully_qualified_stage pattern = \'.*'+ table_name +'.*[.]json\' ' \
'file_format = (format_name = fully_qualified_json_format) ' \
'force = true;'

 try:
        import snowflake.connector
#-------------------------------------------------------------------------------------------------------------------------------
        #snowflake variables
        snowflake_warehouse = credentials.iloc[0]['snowflake_warehouse']
        snowflake_account = credentials.iloc[0]['snowflake_account']
        snowflake_role = credentials.iloc[0]['snowflake_role']
        snowflake_username = credentials.iloc[0]['Username']
        snowflake_password = credentials.iloc[0]['Password']
        snowflake_connection = ''
        cs = ''#snowflake connection cursor
        exec_copy_dml = ''
        copy_result_field_metadata = ''
        copy_result = ''
        snowflake_copy_result_df = ''
#-------------------------------------------------------------------------------------------------------------------------------
        # load JSON file(s) into Snowflake
        snowflake_connection = snowflake.connector.connect(
        user = snowflake_username,
        password = snowflake_password,
        account = snowflake_account,
        warehouse = snowflake_warehouse,
        role = snowflake_role)
        cs = snowflake_connection.cursor()
        exec_copy_dml = cs.execute(copy_dml)
        copy_result =  exec_copy_dml.fetchall()
        copy_result_field_metadata = cs.description
        snowflake_copy_result_df = snowflake_results_df(copy_result_field_metadata,copy_result)
    except snowflake.connector.errors.ProgrammingError as copy_error:
        copy_exception_message = "There was a problem loading JSON files to Snowflake," + \
        "a snowflake.connector.errors.ProgrammingError exception was raised."
        print(copy_exception_message)
        raise
    except Exception as error_message:
        raise
    finally:
        snowflake_connection.close()

Body:
After you issue your COPY INTO dml, you can run the following query -

SELECT * FROM TABLE(VALIDATE(TABLE_NAME, job_id => '_last'))

This will give you details on the files that you were trying to load. It will normally return empty, unless you encountered issues upload.

You can save this save results in an object and make necessary control adjustments.


问:
Django order by related field
I want to sort a QuerySet of contacts by a related field. But I do not know how.
I tried it like this, but it does not work.

```<code>foundContacts.order_by("classification.kam")
</code>```

Actually in a template I can access the kam value of a contact through contact.classification.kam since it is a OneToOne relationship.

The (simplified) models look like this:

```<code>class Classification(models.Model):
    kam = models.ForeignKey(User)
    contact = models.OneToOneField(Contact)

class Contact(models.Model):
    title = models.ForeignKey(Title, blank=True, null=True)
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
</code>```

答:
as the documentation indicates, it should be used as in queries about related models

https://docs.djangoproject.com/en/3.0/ref/models/querysets/#order-by

```<code>foundContacts.order_by("classification__kam")
</code>```

Title: Django order by related field

Body:
I want to sort a QuerySet of contacts by a related field. But I do not know how.
I tried it like this, but it does not work.

foundContacts.order_by("classification.kam")

Actually in a template I can access the kam value of a contact through contact.classification.kam since it is a OneToOne relationship.

The (simplified) models look like this:

class Classification(models.Model):
    kam = models.ForeignKey(User)
    contact = models.OneToOneField(Contact)

class Contact(models.Model):
    title = models.ForeignKey(Title, blank=True, null=True)
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)

Body:
as the documentation indicates, it should be used as in queries about related models

https://docs.djangoproject.com/en/3.0/ref/models/querysets/#order-by

foundContacts.order_by("classification__kam")


问:
Docker Compose Django + PostgreSQL access postgres host without using service name
So, basically i have this docker-compose.yml config:

```<code>services:
  postgres:
    container_name: youtube_manager_postgres
    restart: always
    image: postgres:alpine
    environment:
      - POSTGRES_HOST_AUTH_METHOD=trust
      - POSTGRES_USER=admin
      - POSTGRES_PASSWORD=qwerty123
      - POSTGRES_DB=ytmanager
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    ports:
      - "5432:5432"

  django:
    container_name: youtube_manager_django
    restart: always
    build:
      context: ../
      dockerfile: deploy/django/Dockerfile
    command: sh -c "poetry run python3 manage.py migrate &&
                    poetry run python3 manage.py collectstatic --no-input --clear &&
                    poetry run uwsgi --ini /etc/uwsgi.ini"
    ports:
      - "8000:8000"
    volumes:
      - staticfiles:/code/static
      - mediafiles:/code/media
    depends_on:
      - postgres
</code>```

My Django's database preferences are:

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'ytmanager',
        'USER': 'admin',
        'HOST': '0.0.0.0',
        'PASSWORD': 'qwerty123',
        'PORT': '5432',
    }
}
</code>```

I wan't to use it in two ways:
1. Running docker-compose up -d postgres and then python3 manage.py runserver (actually, poetry run python3 manage.py runserver but for now it doesn't matter) during development.
2. Running docker-compose up during deployment.

For now, it works fine with the 1 option, but when I'm execution docker-compose up I'm getting an error:

```<code>youtube_manager_django | django.db.utils.OperationalError: could not connect to server: Connection refused
youtube_manager_django |        Is the server running on host "0.0.0.0" and accepting
youtube_manager_django |        TCP/IP connections on port 5432?
</code>```

If I'm changing Django database settings this way:

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'ytmanager',
        'USER': 'admin',
        'HOST': '0.0.0.0',
        'PASSWORD': 'qwerty123',
        'PORT': '5432',
    }
}
</code>```

Executing docker-compose up -d postgres and then python manage.py runserver causes an error:

```<code>django.db.utils.OperationalError: could not translate host name "postgres" to address: Temporary failure in name resolution
</code>```

How could I properly config docker-compose.yml to use the same HOST in Django settings? (for example, 'HOST': '0.0.0.0' or 'HOST': 'postgres' for both options).

I've tried to use network_mode: host on my django and postgres services. It works fine, but is there any other way to solve a problem (for example, using networking settings? I've read docker-compose documentation on their website, but can't get what's going on there).

答:
I think you are mixing develop a production environments (by the way, second time you pasted your Django database settings probably you meant 'HOST': 'postgres')

So, if I'm not wrong:

On development you want in your Django setting .py file: 'HOST': '0.0.0.0', since i think your are
executing python manage.py runserver outside docker,
keeping postgres in docker.

On production you want the same in your Django setting .py file: 'HOST': '0.0.0.0', but to make it work you need 'HOST': 'postgres' (matching the name of the service in the compose file) and run everything on docker (executing the whole compose file as it is: docker-compose up). In this case, Django can't get access to '0.0.0.0' database host since it is running 'containerized' and that ip don't bind to any service, so it needs the ip or name of the service 'postgres'.

Posible solution:

In my opinion the solution is having two yml files to be called by Docker ( e.g. docker-compose -f docker-compose-development.yml up):

docker-compose-development.yml

docker-compose-production.yml

In each .yml file you can use different env variables or settings to cover differences between development and production in a clean way.

You can have a look at:
https://github.com/pydanny/cookiecutter-django. It is a template Django project using Docker.

It follows "The Twelve Factors" app methodology:
https://12factor.net/

In short:

Environment variables are set in files under the .envs folder.

in the compose .yml files you point to them in order to load the environment variables:

```<code>env_file:
     ./.envs/.production/.postgres
</code>```

Django settings .py files get access to the env variables using the django-environ package.

Body:
So, basically i have this docker-compose.yml config:

services:
  postgres:
    container_name: youtube_manager_postgres
    restart: always
    image: postgres:alpine
    environment:
      - POSTGRES_HOST_AUTH_METHOD=trust
      - POSTGRES_USER=admin
      - POSTGRES_PASSWORD=qwerty123
      - POSTGRES_DB=ytmanager
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    ports:
      - "5432:5432"

  django:
    container_name: youtube_manager_django
    restart: always
    build:
      context: ../
      dockerfile: deploy/django/Dockerfile
    command: sh -c "poetry run python3 manage.py migrate &&
                    poetry run python3 manage.py collectstatic --no-input --clear &&
                    poetry run uwsgi --ini /etc/uwsgi.ini"
    ports:
      - "8000:8000"
    volumes:
      - staticfiles:/code/static
      - mediafiles:/code/media
    depends_on:
      - postgres

My Django's database preferences are:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'ytmanager',
        'USER': 'admin',
        'HOST': '0.0.0.0',
        'PASSWORD': 'qwerty123',
        'PORT': '5432',
    }
}

I wan't to use it in two ways:
1. Running docker-compose up -d postgres and then python3 manage.py runserver (actually, poetry run python3 manage.py runserver but for now it doesn't matter) during development.
2. Running docker-compose up during deployment.

For now, it works fine with the 1 option, but when I'm execution docker-compose up I'm getting an error:

youtube_manager_django | django.db.utils.OperationalError: could not connect to server: Connection refused
youtube_manager_django |        Is the server running on host "0.0.0.0" and accepting
youtube_manager_django |        TCP/IP connections on port 5432?

If I'm changing Django database settings this way:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'ytmanager',
        'USER': 'admin',
        'HOST': '0.0.0.0',
        'PASSWORD': 'qwerty123',
        'PORT': '5432',
    }
}

Executing docker-compose up -d postgres and then python manage.py runserver causes an error:

django.db.utils.OperationalError: could not translate host name "postgres" to address: Temporary failure in name resolution

How could I properly config docker-compose.yml to use the same HOST in Django settings? (for example, 'HOST': '0.0.0.0' or 'HOST': 'postgres' for both options).

I've tried to use network_mode: host on my django and postgres services. It works fine, but is there any other way to solve a problem (for example, using networking settings? I've read docker-compose documentation on their website, but can't get what's going on there).

Body:
I think you are mixing develop a production environments (by the way, second time you pasted your Django database settings probably you meant 'HOST': 'postgres')

So, if I'm not wrong:

On development you want in your Django setting .py file: 'HOST': '0.0.0.0', since i think your are
executing python manage.py runserver outside docker,
keeping postgres in docker.

On production you want the same in your Django setting .py file: 'HOST': '0.0.0.0', but to make it work you need 'HOST': 'postgres' (matching the name of the service in the compose file) and run everything on docker (executing the whole compose file as it is: docker-compose up). In this case, Django can't get access to '0.0.0.0' database host since it is running 'containerized' and that ip don't bind to any service, so it needs the ip or name of the service 'postgres'.

Posible solution:

In my opinion the solution is having two yml files to be called by Docker ( e.g. docker-compose -f docker-compose-development.yml up):

docker-compose-development.yml

docker-compose-production.yml

In each .yml file you can use different env variables or settings to cover differences between development and production in a clean way.

You can have a look at:
https://github.com/pydanny/cookiecutter-django. It is a template Django project using Docker.

It follows "The Twelve Factors" app methodology:
https://12factor.net/

In short:

Environment variables are set in files under the .envs folder.

in the compose .yml files you point to them in order to load the environment variables:

env_file:
     ./.envs/.production/.postgres

Django settings .py files get access to the env variables using the django-environ package.


问:
Accumulated count for each element in a range
I have a table x, where start and end are hour of the day.

x = data.table(start=c(5,7,9,12), end=c(12,14,15,20), val = 7:10)

I want the output table to be:

for each hour from  hour 4 (not 5) to the 21 (not 20), has the accumulated value such as:

```<code>hour total
4    0
5    7
6    7
7    15(7+8)
</code>```

Body:
I have a table x, where start and end are hour of the day.

x = data.table(start=c(5,7,9,12), end=c(12,14,15,20), val = 7:10)

I want the output table to be:

for each hour from  hour 4 (not 5) to the 21 (not 20), has the accumulated value such as:

hour total
4    0
5    7
6    7
7    15(7+8)

Body:
Here is another data.table option using by=.EACHI for each hour:

x[.(hr=max(0L, min(x)-1L):min(23L, max(end)+1L)),
    on=.(start<=hr, end>=hr), by=.EACHI, fcoalesce(sum(val), 0L)]

output:

    start end V1
 1:     4   4  0
 2:     5   5  7
 3:     6   6  7
 4:     7   7 15
 5:     8   8 15
 6:     9   9 24
 7:    10  10 24
 8:    11  11 24
 9:    12  12 34
10:    13  13 27
11:    14  14 27
12:    15  15 19
13:    16  16 10
14:    17  17 10
15:    18  18 10
16:    19  19 10
17:    20  20 10
18:    21  21  0


问:
material design bootstrap right to left Direction
I am using Material Design Bootstrap for React and iIwant to use it for Persian mood.

Is there any solution for right to left direction.

答:
only add this CSS class to your classes  i had a problem with Label on
  the MDBInput in Material Design Bootstrap so i finally add this class
  to Label Class.

```<code>.md-form label {
left: unset !important;
display: block;
</code>```

};

Body:
only add this CSS class to your classes  i had a problem with Label on
  the MDBInput in Material Design Bootstrap so i finally add this class
  to Label Class.

.md-form label {
left: unset !important;
display: block;

};


答:
The simplest way to fix the issue is to wrap all components in <Panel>-s:

```<code><TabPanel>
  <Panel title="Dashboard" panel-id="dashboard">
    <Dashboard></Dashboard>
  </Panel>
  <Panel title="Test" panel-id="test">Content from Panel</Panel>
  <Panel title="Rose Panel" panel-id="rose-panel">
    <RosePanel></RosePanel>
  </Panel>
</TabPanel>
</code>```

https://codesandbox.io/s/eager-brown-6ethk?file=/src/App.vue

But this is probably not what you had in mind.

From what I see, you simply forgot to propagate the "is-active" property to the embedded panel:

```<code>  <Panel :title="title" :panelId="panelId" :is-isActive="isActive">Content from Dashboard</Panel>
</code>```

(e.x in the Dashboard Component)

Title: Slot contents are merged between Tabs in VueJS

Body:
I have this TabPanel where I am rendering multiple tabs. Each Panel inside TabPanel uses/extends Panel where I am using slots. However, during tab switch content of Tabs are getting merged.

<template>

{{ panel.title }}

      <slot></slot>

</template>

Panel code

<template>

    <slot></slot>

</template>

Is there anyway to fix this issue. This is the CodeSandbox link to demonstrate this issue since its easier to visualize problem that way I think.

Body:
The simplest way to fix the issue is to wrap all components in <Panel>-s:

<TabPanel>
  <Panel title="Dashboard" panel-id="dashboard">
    <Dashboard></Dashboard>
  </Panel>
  <Panel title="Test" panel-id="test">Content from Panel</Panel>
  <Panel title="Rose Panel" panel-id="rose-panel">
    <RosePanel></RosePanel>
  </Panel>
</TabPanel>

https://codesandbox.io/s/eager-brown-6ethk?file=/src/App.vue

But this is probably not what you had in mind.

From what I see, you simply forgot to propagate the "is-active" property to the embedded panel:

  <Panel :title="title" :panelId="panelId" :is-isActive="isActive">Content from Dashboard</Panel>

(e.x in the Dashboard Component)


问:
Digital filter algorithm
I just found a fir algorithm on wikipedia

http://en.wikipedia.org/wiki/Digital_filter

```<code>// if the size of NB_COEF = 2^n use a bit mask instead of the modulo (%)
// %=NB_COEF => &=(NB_COEF-1)
// pipe is a circular buffer

#define NB_COEF 16  // numbers of coefficients of the filter
double x_buffer[NB_COEF]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
double coef[NB_COEF]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int ptr_x_buffer=0;

double FiltreFIR(double x)
// x: Signal d'entrée
// y: Signal de sortie
{
  int n, y=0;
  x_buffer[ptr_x_buffer++] = x;
  ptr_x_buffer %= NB_COEF;

  for( n = (NB_COEF-1) ; n >= 0 ; n-- )
  {
    y += coef[n] * x_buffer[ptr_x_buffer++];
    ptr_x_buffer %= NB_COEF;
  }
  return(y);
}
</code>```

-Can anybody tell me why do we need constantly to do this expression

```<code>ptr_x_buffer%= NB_COEFF.
</code>```

Because for me it would mean the variable ptr_x_buffer always take the value 0 ?!
And it seems to me far from logic?!

And also can somebody explain to me the first comment about bit masking and modulo.

thank you in advance
:)

答:
Quite simply, x_buffer is a circular buffer; ptr_x_buffer points to the current location in the buffer:

ptr_x_buffer++ increments ptr_x_buffer;

ptr_x_buffer %= NB_COEF resets ptr_x_buffer to zero as soon as it reaches NB_COEF.

The comment suggests a modification of the code for certain values of NB_COEF. Whoever wrote that comments appears to have considered the suggested modification to be a performance improvement. However, it is highly doubtful that the change would lead to better performance and, therefore, the remark can be ignored.

Title: Digital filter algorithm

Body:
I just found a fir algorithm on wikipedia

http://en.wikipedia.org/wiki/Digital_filter

// if the size of NB_COEF = 2^n use a bit mask instead of the modulo (%)
// %=NB_COEF => &=(NB_COEF-1)
// pipe is a circular buffer

#define NB_COEF 16  // numbers of coefficients of the filter
double x_buffer[NB_COEF]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
double coef[NB_COEF]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int ptr_x_buffer=0;

double FiltreFIR(double x)
// x: Signal d'entrée
// y: Signal de sortie
{
  int n, y=0;
  x_buffer[ptr_x_buffer++] = x;
  ptr_x_buffer %= NB_COEF;

  for( n = (NB_COEF-1) ; n >= 0 ; n-- )
  {
    y += coef[n] * x_buffer[ptr_x_buffer++];
    ptr_x_buffer %= NB_COEF;
  }
  return(y);
}

-Can anybody tell me why do we need constantly to do this expression

ptr_x_buffer%= NB_COEFF.

Because for me it would mean the variable ptr_x_buffer always take the value 0 ?!
And it seems to me far from logic?!

And also can somebody explain to me the first comment about bit masking and modulo.

thank you in advance
:)


问:
Nav bar - last element float right but not wrap
Just when I think I start to understand css...

The last item in my nav-bar is the current user. I want this to float right but then be hidden and NOT wrap if the user sizes the screen narrow. I have been able to either get it to float right or not wrap but never both at once. I want to eat the cake.

Here is a simple example that demonstrates the problem. Much thanks in advance! - Jon

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 50px;
}

ul {
  position: relative;
  list-style-type: none;
  white-space: nowrap;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  display: inline-block;
}

li a {
  display: block;
  font-family: Arial, Helvetica, sans-serif;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover {
  color: wheat;
}

.current-user {
  color: lightblue;
  margin-top: 10px;
  margin-right: 10px;
  float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><navbar class="nav-bar">
  <ul>
    <li>link1</li>
    <li>link2</li>
    <li>link3</li>
    <li>link4</li>
    <li>link5</li>
    <li>link6</li>
    <li>link7</li>
    <li>link8</li>

    <!-- Joe float right but be hidden if overflow -->
    <li class="current-user">Joe Doe</li>
  </ul>
</navbar></code>```

答:
Method #1:

I would suggest using a media query and hiding it that way. For example:

```<code>  @media screen and (max-width: 620px) {
    .current-user {
      display: none;
    }
  }
</code>```

The above CSS will only be applied when the screen width is below 620 pixels. You can, of course, adjust this as needed.

Here your entire code:

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 50px;
}

ul {
  position: relative;
  list-style-type: none;
  white-space: nowrap;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  display: inline-block;
}

li a {
  display: block;
  font-family: Arial, Helvetica, sans-serif;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover {
  color: wheat;
}

.current-user {
  color: lightblue;
  margin-top: 10px;
  margin-right: 10px;
  float: right;
}

@media screen and (max-width: 620px) {
  .current-user {
    display: none;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><navbar class="nav-bar">
  <ul>
    <li>link1</li>
    <li>link2</li>
    <li>link3</li>
    <li>link4</li>
    <li>link5</li>
    <li>link6</li>
    <li>link7</li>
    <li>link8</li>

    <!-- Joe float right but be hidden if overflow -->
    <li class="current-user">Joe Doe</li>
  </ul>
</navbar></code>```

For more on media queries see: these docs

Method #2:

You could also position the element absolutely instead of floating it. For example:

```<code>.current-user {
  position: absolute;
  right: 0;
}
</code>```

Here a snippet:

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 50px;
}

ul {
  position: relative;
  list-style-type: none;
  white-space: nowrap;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  display: inline-block;
}

li a {
  display: block;
  font-family: Arial, Helvetica, sans-serif;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover {
  color: wheat;
}

.current-user {
  color: lightblue;
  margin-top: 10px;
  margin-right: 10px;
  position: absolute;
  right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><navbar class="nav-bar">
  <ul>
    <li>link1</li>
    <li>link2</li>
    <li>link3</li>
    <li>link4</li>
    <li>link5</li>
    <li>link6</li>
    <li>link7</li>
    <li>link8</li>

    <!-- Joe float right but be hidden if overflow -->
    <li class="current-user">Joe Doe</li>
  </ul>
</navbar></code>```

This way the element will not wrap. You would, however, have to fix the overlapping. You could do this by assigning a background color to your nav items and ensuring that they slide over the user element by adjusting z-index.

I believe method #1 would be a cleaner solution.

Body:
Just when I think I start to understand css...

The last item in my nav-bar is the current user. I want this to float right but then be hidden and NOT wrap if the user sizes the screen narrow. I have been able to either get it to float right or not wrap but never both at once. I want to eat the cake.

Here is a simple example that demonstrates the problem. Much thanks in advance! - Jon

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 50px;
}

ul {
  position: relative;
  list-style-type: none;
  white-space: nowrap;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  display: inline-block;
}

li a {
  display: block;
  font-family: Arial, Helvetica, sans-serif;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover {
  color: wheat;
}

.current-user {
  color: lightblue;
  margin-top: 10px;
  margin-right: 10px;
  float: right;
}

<navbar class="nav-bar">

link1

link2

link3

link4

link5

link6

link7

link8

Joe Doe

</navbar>

Body:
Method #1:

I would suggest using a media query and hiding it that way. For example:

  @media screen and (max-width: 620px) {
    .current-user {
      display: none;
    }
  }

The above CSS will only be applied when the screen width is below 620 pixels. You can, of course, adjust this as needed.

Here your entire code:

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 50px;
}

ul {
  position: relative;
  list-style-type: none;
  white-space: nowrap;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  display: inline-block;
}

li a {
  display: block;
  font-family: Arial, Helvetica, sans-serif;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover {
  color: wheat;
}

.current-user {
  color: lightblue;
  margin-top: 10px;
  margin-right: 10px;
  float: right;
}

@media screen and (max-width: 620px) {
  .current-user {
    display: none;
  }
}

<navbar class="nav-bar">
  <ul>
    <li><a href="#">link1</a></li>
    <li><a href="#">link2</a></li>
    <li><a href="#">link3</a></li>
    <li><a href="#">link4</a></li>
    <li><a href="#">link5</a></li>
    <li><a href="#">link6</a></li>
    <li><a href="#">link7</a></li>
    <li><a href="#">link8</a></li>

    <!-- Joe float right but be hidden if overflow -->
    <li class="current-user">Joe Doe</li>
  </ul>
</navbar>

For more on media queries see: these docs

Method #2:

You could also position the element absolutely instead of floating it. For example:

.current-user {
  position: absolute;
  right: 0;
}

Here a snippet:

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 50px;
}

ul {
  position: relative;
  list-style-type: none;
  white-space: nowrap;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  display: inline-block;
}

li a {
  display: block;
  font-family: Arial, Helvetica, sans-serif;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover {
  color: wheat;
}

.current-user {
  color: lightblue;
  margin-top: 10px;
  margin-right: 10px;
  position: absolute;
  right: 0;
}

<navbar class="nav-bar">
  <ul>
    <li><a href="#">link1</a></li>
    <li><a href="#">link2</a></li>
    <li><a href="#">link3</a></li>
    <li><a href="#">link4</a></li>
    <li><a href="#">link5</a></li>
    <li><a href="#">link6</a></li>
    <li><a href="#">link7</a></li>
    <li><a href="#">link8</a></li>

    <!-- Joe float right but be hidden if overflow -->
    <li class="current-user">Joe Doe</li>
  </ul>
</navbar>

This way the element will not wrap. You would, however, have to fix the overlapping. You could do this by assigning a background color to your nav items and ensuring that they slide over the user element by adjusting z-index.

I believe method #1 would be a cleaner solution.


问:
What is difference between Keys and Secrets in Azure Key Vault?
It would be great to know

what are they,

what are they used for

why would one prefer one versus the other.

答:
The Azure Key Vault (KV) can store 3 types of items: (1) secrets, (2) keys, & (3) certificates (certs).

Secrets - provides secure storage of secrets, such as DB connection strings, account keys, or passwords for PFX (private key files). An auth app can retrieve a secret for use in its operation. More on AZ KV Secrets

(Cryptographic) Keys - keys represented as JWK (JSON Web Key). Supports multiple key types and algorithms, and enables the use of Hardware Security Modules (HSM) for high value keys. More on AZ KV Keys

Cert - is a managed X.509 certificate, which are built on top of keys and secrets and add an automated renewal feature/auto-rollover. More on AZ KV Certificate


问:
How to increment count id for each insert and every loop iteration?
I have for loop that should increment count_id for every query and each loop iteration. Here is example of my code:

```<code>qryCode = queryExecute("SELECT max(display_order) AS maxdisplay FROM type_ref",{},{datasource: application.datasource}); // Result set of the query is: 58
qryItems = queryExecute("SELECT DISTINCT type_id, label, type_shortcode FROM types gtr WHERE item_id = :item_id",{item_id: {cfsqltype: "cf_sql_numeric",value: arguments.item_id}},{datasource: application.datasource});

// Result set of qryItems:
TYPE_ID  LABEL    TYPE_SHORTCODE
1        2012-1   HOA
2        2012-1   HOC
5        2012-1   HOR

local.display_count = qryCode.maxdisplay;

for ( row in qryItems ) {
    local.sqlInsert &= " INSERT INTO type_ref (display_order) VALUES (?) ";
    qryParams.append({cfsqltype="CF_SQL_NUMERIC", value: display_count+1});
    local.sqlInsert &= " INSERT INTO type_ref (display_order) VALUES (?) ";
    qryParams.append({cfsqltype="CF_SQL_NUMERIC", value: display_count+2});
    display_count++;
}
</code>```

The code above will increment first two values correct (59 & 60) but for the second iteration it will start from 60 instead of 61. The code should produce count_id's int his order: 59,60,61,62,63,64. There are three records in qryItems. The qryCode has max value of 58. The first query in first iteration should start from 58 + 1 = 59. The next one should be 58 + 2 = 60. In the second iteration the first count_id should be 61 and so on. I'm not sure why the code I have above starts second iteration from 60 instead of 61. I do have this line that should increase the count_id at the end of each iteration: display_count++;.

答:
How about

```<code>for ( row in qryItems ) {
    local.sqlInsert &= " INSERT INTO type_ref (display_order) VALUES (?),(?) ";

    qryParams.append({cfsqltype="CF_SQL_NUMERIC", value: ++display_count});
    qryParams.append({cfsqltype="CF_SQL_NUMERIC", value: ++display_count});

}
</code>```

Also see: Inserting multiple rows in a single SQL query?

Body:
I have for loop that should increment count_id for every query and each loop iteration. Here is example of my code:

qryCode = queryExecute("SELECT max(display_order) AS maxdisplay FROM type_ref",{},{datasource: application.datasource}); // Result set of the query is: 58
qryItems = queryExecute("SELECT DISTINCT type_id, label, type_shortcode FROM types gtr WHERE item_id = :item_id",{item_id: {cfsqltype: "cf_sql_numeric",value: arguments.item_id}},{datasource: application.datasource});

// Result set of qryItems:
TYPE_ID  LABEL    TYPE_SHORTCODE
1        2012-1   HOA
2        2012-1   HOC
5        2012-1   HOR

local.display_count = qryCode.maxdisplay;

for ( row in qryItems ) {
    local.sqlInsert &= " INSERT INTO type_ref (display_order) VALUES (?) ";
    qryParams.append({cfsqltype="CF_SQL_NUMERIC", value: display_count+1});
    local.sqlInsert &= " INSERT INTO type_ref (display_order) VALUES (?) ";
    qryParams.append({cfsqltype="CF_SQL_NUMERIC", value: display_count+2});
    display_count++;
}

The code above will increment first two values correct (59 & 60) but for the second iteration it will start from 60 instead of 61. The code should produce count_id's int his order: 59,60,61,62,63,64. There are three records in qryItems. The qryCode has max value of 58. The first query in first iteration should start from 58 + 1 = 59. The next one should be 58 + 2 = 60. In the second iteration the first count_id should be 61 and so on. I'm not sure why the code I have above starts second iteration from 60 instead of 61. I do have this line that should increase the count_id at the end of each iteration: display_count++;.

Body:
How about

for ( row in qryItems ) {
    local.sqlInsert &= " INSERT INTO type_ref (display_order) VALUES (?),(?) ";

    qryParams.append({cfsqltype="CF_SQL_NUMERIC", value: ++display_count});
    qryParams.append({cfsqltype="CF_SQL_NUMERIC", value: ++display_count});

}

Also see: Inserting multiple rows in a single SQL query?


问:
User-accessible folder for Click-Once applications
In a WinForms application written in C# and being deployed via Click-Once, if certain errors happen, I write information to a log file. I'm setting the path for that log file as such:

```<code>private static string strAppPath = Path.GetDirectoryName(Application.ExecutablePath);
private static readonly string strLogFile = "Log File.txt";
private static readonly string strPathToLogFile = strAppPath + "\\" + strLogFile;
</code>```

When an error happens, I am also showing a messagebox instructing the user to locate the file (I'm providing the strPathToLogFile variable in the message).

However, in testing it I found that the path is quite user-unfriendly, to say the least. It looks something like this:

Is there a better/recommended place to save the file to? I can't save it to a user folder, as multiple users will be running the application.

答:
There are several solutions

put the log in a simple path like c:\logs\log.txt

add button in the message box that opens the folder of the file

add button in the message box that sand the logs to the developer automatically

Body:
In a WinForms application written in C# and being deployed via Click-Once, if certain errors happen, I write information to a log file. I'm setting the path for that log file as such:

private static string strAppPath = Path.GetDirectoryName(Application.ExecutablePath);
private static readonly string strLogFile = "Log File.txt";
private static readonly string strPathToLogFile = strAppPath + "\\" + strLogFile;

When an error happens, I am also showing a messagebox instructing the user to locate the file (I'm providing the strPathToLogFile variable in the message).

However, in testing it I found that the path is quite user-unfriendly, to say the least. It looks something like this:

Is there a better/recommended place to save the file to? I can't save it to a user folder, as multiple users will be running the application.


问:
Comprehensive JavaDoc-like documentation for Mozilla/Firefox extension developers?
Is there any thing like JavaDoc for Mozilla/Firefox that helps extension developers?

For example where can I find what delayedOpenTab() does and how to use it?

答: May be Mozilla Cross-Reference and delayedOpenTab() is here.


问:
Hide scrollable content behind transparent fixed position divs when scrolling the page?
I have a div called header that is set up with a fixed position. The problem is when I scroll the page the content of the page shows up behind the header (the header is transparent).

I know a lot about css, but cannot seem to figure this one out. I have tried setting overflow to hidden, but I knew it wouldn't work (and it didn't).

This is very hard to explain, so I did the best I could.

html:

```<code><div id="header">
    <div id="topmenu">Home | Find Feeds | Subscriptions</div>
</div>
<div id="container">
    <div id="content">
        testing
    </div>
</div>
</code>```

css:

```<code>#header {
    margin:0 auto;
    position: fixed;
    width:100%;
    z-index:1000;
}
#topmenu {
    background-color:#0000FF;
    height:24px;
    filter: alpha(opacity=50);
    opacity: 0.5;
}

#leftlinks {
    padding: 4px;
    padding-left: 10px;
    float: left;
}

#rightlinks {
    padding: 4px;
    padding-right: 10px;
    float: right;
}

#containerfixedtop {
    width: 100%;
    height: 20px;
}

#contentfixedtop {
    margin: 0 auto;
    background-color: #DAA520;
    width: 960px;
    height:20px;
}

#container {
    position: relative;
    top: 68px;
    width: 100%;
    height: 2000px;
    overflow: auto;
}

#content {
    margin: 0 auto;
    background-color: #DAA520;
    width: 960px;
    height: 2000px;
}
</code>```

Here's a screenshot of the problem:

答:
Just came up with a new solution to this type of problem that I'm quite happy with.

Use clip-path on the content that needs to hide behind the transparent element. Then update the clip-path dynamically with js on window scroll.

HTML

```<code><div id="sticky">Sticky content</div>
<div id="content">
  <!-- any html inside here will hide behind #sticky -->
</div>
</code>```

JS

```<code>window.addEventListener("scroll",function(){
  const windowScrollTop = window.scrollTop;
  const elementToHide = document.getElementById("content");

  elementToHide.style.clipPath = `inset(${windowScrollTop}px 0 0 0)`;
});
</code>```

Dynamic sticky content

In my case I had an element that I switched to position: sticky after scrolling past it.   The #sticky content needs to be relative to the dom elements that came before it until we have scrolled far enough. Here's how I accounted for that:

HTML

```<code><div id="otherStuff">Here's some other stuff</div>
<div id="sticky">Sticky content</div>
<div id="content">
  <!-- any html inside here will hide behind #sticky -->
</div>
</code>```

JS

```<code>window.addEventListener("scroll",function(){
  const windowScrollTop = window.scrollTop;
  const stickyElement = document.getElementById("sticky");
  const elementToHide = document.getElementById("content");
  const stickyElementTop = stickyElement.getBoundingClientRect().top

  if(windowScrollTop >= stickyElementTop){
    stickyElement.style.position = "sticky";
    elementToHide.style.clipPath = `inset(${windowScrollTop - stickyElementTop}px 0 0 0)`;
  }
  else {
    stickyElement.style.position = "relative";
    elementToHide.style.clipPath = "none";
  }
});
</code>```

Body:
I have a div called header that is set up with a fixed position. The problem is when I scroll the page the content of the page shows up behind the header (the header is transparent).

I know a lot about css, but cannot seem to figure this one out. I have tried setting overflow to hidden, but I knew it wouldn't work (and it didn't).

This is very hard to explain, so I did the best I could.

html:

Home | Find Feeds | Subscriptions

        testing

css:

#header {
    margin:0 auto;
    position: fixed;
    width:100%;
    z-index:1000;
}
#topmenu {
    background-color:#0000FF;
    height:24px;
    filter: alpha(opacity=50);
    opacity: 0.5;
}

#leftlinks {
    padding: 4px;
    padding-left: 10px;
    float: left;
}

#rightlinks {
    padding: 4px;
    padding-right: 10px;
    float: right;
}

#containerfixedtop {
    width: 100%;
    height: 20px;
}

#contentfixedtop {
    margin: 0 auto;
    background-color: #DAA520;
    width: 960px;
    height:20px;
}

#container {
    position: relative;
    top: 68px;
    width: 100%;
    height: 2000px;
    overflow: auto;
}

#content {
    margin: 0 auto;
    background-color: #DAA520;
    width: 960px;
    height: 2000px;
}

Here's a screenshot of the problem:

Body:
Just came up with a new solution to this type of problem that I'm quite happy with.

Use clip-path on the content that needs to hide behind the transparent element. Then update the clip-path dynamically with js on window scroll.

HTML

<div id="sticky">Sticky content</div>
<div id="content">
  <!-- any html inside here will hide behind #sticky -->
</div>

JS

window.addEventListener("scroll",function(){
  const windowScrollTop = window.scrollTop;
  const elementToHide = document.getElementById("content");

  elementToHide.style.clipPath = `inset(${windowScrollTop}px 0 0 0)`;
});

Dynamic sticky content

In my case I had an element that I switched to position: sticky after scrolling past it.   The #sticky content needs to be relative to the dom elements that came before it until we have scrolled far enough. Here's how I accounted for that:

HTML

<div id="otherStuff">Here's some other stuff</div>
<div id="sticky">Sticky content</div>
<div id="content">
  <!-- any html inside here will hide behind #sticky -->
</div>

JS

window.addEventListener("scroll",function(){
  const windowScrollTop = window.scrollTop;
  const stickyElement = document.getElementById("sticky");
  const elementToHide = document.getElementById("content");
  const stickyElementTop = stickyElement.getBoundingClientRect().top

  if(windowScrollTop >= stickyElementTop){
    stickyElement.style.position = "sticky";
    elementToHide.style.clipPath = `inset(${windowScrollTop - stickyElementTop}px 0 0 0)`;
  }
  else {
    stickyElement.style.position = "relative";
    elementToHide.style.clipPath = "none";
  }
});


问:
how can i apply convolution to a stereo audio signal?

here's my code, but i don't know how to apply convolution to a stereo audio signal, i could only apply it to one channel instead of both, so i want to know if is possible to apply convolution between an array 1d to an aray 2d (stereo audio signal)

```<code>import  numpy as np
import soundfile as sf
import  sounddevice as sd

delay=22050

x, FS = sf.read('acdc-stereo.wav', dtype='float')
print(x)
zeros = np.zeros(delay-1,dtype='float')
h = np.concatenate(([1],zeros,[0.3]))

print('Processing..')
y = np.convolve(x[:,0],h, mode="full")
newaudio=(y,FS)
print(y)
print('Playing original signal')
sd.play(x,FS)
sd.wait()
print("playing output signal")
sd.play(newaudio)
sd.wait()
</code>```

答:
The numpy array is a frames x channel array. And in this line:

```<code>y = np.convolve(x[:,0],h, mode="full")
</code>```

You did convolution only to channel 0. You should apply it to other channels as well if you mean to. I think for most realistic cases, convolution should be applied separately to different channels:

```<code>y = np.array([np.convolve(x[:,0], h, mode="full"),
              np.convolve(x[:,1], h, mode="full")]).T
</code>```

Body:
here's my code, but i don't know how to apply convolution to a stereo audio signal, i could only apply it to one channel instead of both, so i want to know if is possible to apply convolution between an array 1d to an aray 2d (stereo audio signal)

import  numpy as np
import soundfile as sf
import  sounddevice as sd

delay=22050

x, FS = sf.read('acdc-stereo.wav', dtype='float')
print(x)
zeros = np.zeros(delay-1,dtype='float')
h = np.concatenate(([1],zeros,[0.3]))

print('Processing..')
y = np.convolve(x[:,0],h, mode="full")
newaudio=(y,FS)
print(y)
print('Playing original signal')
sd.play(x,FS)
sd.wait()
print("playing output signal")
sd.play(newaudio)
sd.wait()

Body:
The numpy array is a frames x channel array. And in this line:

y = np.convolve(x[:,0],h, mode="full")

You did convolution only to channel 0. You should apply it to other channels as well if you mean to. I think for most realistic cases, convolution should be applied separately to different channels:

y = np.array([np.convolve(x[:,0], h, mode="full"),
              np.convolve(x[:,1], h, mode="full")]).T


问:
How to sort tuple with python by using specific rules
I have this tuple:

```<code>[('site-nfv01-swsto01',), ('site-nfv01-swsto01V',),('site-nfv01-swsto02',),('site-nfv02-swsto02',), ('site-nfv02-swsto01',) , ('site-nfv02-swsto01V',)]
</code>```

I would like to classify it in this order:

```<code>site-nfv01-swsto01V
site-nfv01-swsto01
site-nfv01-swsto02
site-nfv02-swsto01V
site-nfv02-swsto01
site-nfv02-swsto02
</code>```

To have: [('site-nfv01-swsto01V',), ('site-nfv01-swsto01',),('site-nfv01-swsto02',),('site-nfv02-swsto01V',), ('site-nfv02-swsto01',) , ('site-nfv02-swsto02',)]

574 idea is to first classify the NFV part in ascending order ,after that, we classify the SWSTO in increasing order too but by putting the SWSTO which ends with 'V' first

How can I do that?

答:
The best way would be to use key argument for sorted function.

from docs:

The value of the key parameter should be a function that takes a
  single argument and returns a key to use for sorting purposes. This
  technique is fast because the key function is called exactly once for
  each input record.

to sort your list of codes I would do something like this:

```<code>your_list = [('site-nfv01-swsto01',), ('site-nfv01-swsto01V',),('site-nfv01-swsto02',),('site-nfv02-swsto02',), ('site-nfv02-swsto01',) , ('site-nfv02-swsto01V',)]
#sort using key parameter
#key must be a function that returns a new value to be sorted
#this particular key function checks if 'V' is at the last position,
#leaves the code unchanged if true,
#else adds arbitrary string at the end of the code that will cause the code to be sorted after codes with the same content at the beginning but lacking the 'V'
#in this case I chose 'z' which comes after 'v' in the alphabet
sorted_list = sorted(your_list, key=lambda code: code[0] if code[0][-1] == 'V'  else code[0]+'z')
</code>```

If you don't know how lambda expressions work check out the docs.

Body:
I have this tuple:

[('site-nfv01-swsto01',), ('site-nfv01-swsto01V',),('site-nfv01-swsto02',),('site-nfv02-swsto02',), ('site-nfv02-swsto01',) , ('site-nfv02-swsto01V',)]

I would like to classify it in this order:

site-nfv01-swsto01V
site-nfv01-swsto01
site-nfv01-swsto02
site-nfv02-swsto01V
site-nfv02-swsto01
site-nfv02-swsto02

To have: [('site-nfv01-swsto01V',), ('site-nfv01-swsto01',),('site-nfv01-swsto02',),('site-nfv02-swsto01V',), ('site-nfv02-swsto01',) , ('site-nfv02-swsto02',)]

574 idea is to first classify the NFV part in ascending order ,after that, we classify the SWSTO in increasing order too but by putting the SWSTO which ends with 'V' first

How can I do that?

Body:
The best way would be to use key argument for sorted function.

from docs:

The value of the key parameter should be a function that takes a
  single argument and returns a key to use for sorting purposes. This
  technique is fast because the key function is called exactly once for
  each input record.

to sort your list of codes I would do something like this:

your_list = [('site-nfv01-swsto01',), ('site-nfv01-swsto01V',),('site-nfv01-swsto02',),('site-nfv02-swsto02',), ('site-nfv02-swsto01',) , ('site-nfv02-swsto01V',)]
#sort using key parameter
#key must be a function that returns a new value to be sorted
#this particular key function checks if 'V' is at the last position,
#leaves the code unchanged if true,
#else adds arbitrary string at the end of the code that will cause the code to be sorted after codes with the same content at the beginning but lacking the 'V'
#in this case I chose 'z' which comes after 'v' in the alphabet
sorted_list = sorted(your_list, key=lambda code: code[0] if code[0][-1] == 'V'  else code[0]+'z')

If you don't know how lambda expressions work check out the docs.


问:
How to sort array of structs by char field so that empty fields go to last place?
I have a struct:

```<code>struct StructA{
  char name[TEXT_LEN];
  int year;
};
typedef struct StructA Data_t;
</code>```

And lets say that it can be something like:

```<code>Name: A
Year: 2002

Name:
Year: 2003

Name: C
Year: 2003

Name: B
Year: 2004

Name:
Year: 2005
</code>```

Now I would like to sort it in a way that it sorts first existing values and put empty values in last place. For this I use qsort():

```<code>int compareDataT(const void *v1, const void *v2)
{
    const Data_t *u1 = v1;
    const Data_t *u2 = v2;
    return strcmp(u1->name, u2->name);
}

qsort(items, length, sizeof(Data_t), compareDataT);
</code>```

This gives me:

```<code>Name:
Year: 2003

Name:
Year: 2005

Name: A
Year: 2002

Name: B
Year: 2004

Name: C
Year: 2003
</code>```

If I reverse it in function then it gives me C, B, A, blank, blank...

I want to have it as A, B, C, blank, blank... So, sorted and then put blank values in the end.

I am struggling with this issue for hours... So any help is appreciated.

答:
If you want the empty fields to go last, you can modify the comparison function so they compare larger than non empty ones:</p>

```<code>int compareDataT(const void *v1, const void *v2) {
    const Data_t *u1 = v1;
    const Data_t *u2 = v2;
    if (*u1->name == '\0')
        return (*u2->name == '\0') ? 0 : 1;
    if (*u2->name == '\0')
        return -1;
    return strcmp(u1->name, u2->name);
}
</code>```

Body:
I have a struct:

struct StructA{
  char name[TEXT_LEN];
  int year;
};
typedef struct StructA Data_t;

And lets say that it can be something like:

Name: A
Year: 2002

Name:
Year: 2003

Name: C
Year: 2003

Name: B
Year: 2004

Name:
Year: 2005

Now I would like to sort it in a way that it sorts first existing values and put empty values in last place. For this I use qsort():

int compareDataT(const void *v1, const void *v2)
{
    const Data_t *u1 = v1;
    const Data_t *u2 = v2;
    return strcmp(u1->name, u2->name);
}

qsort(items, length, sizeof(Data_t), compareDataT);

This gives me:

Name:
Year: 2003

Name:
Year: 2005

Name: A
Year: 2002

Name: B
Year: 2004

Name: C
Year: 2003

If I reverse it in function then it gives me C, B, A, blank, blank...

I want to have it as A, B, C, blank, blank... So, sorted and then put blank values in the end.

I am struggling with this issue for hours... So any help is appreciated.

Body:
If you want the empty fields to go last, you can modify the comparison function so they compare larger than non empty ones:

int compareDataT(const void *v1, const void *v2) {
    const Data_t *u1 = v1;
    const Data_t *u2 = v2;
    if (*u1->name == '\0')
        return (*u2->name == '\0') ? 0 : 1;
    if (*u2->name == '\0')
        return -1;
    return strcmp(u1->name, u2->name);
}