问:
Scale an SVG responsively in CSS
I'm wondering how to scale an SVG to look nice on every screen size. Here's what I have

A linear gradient as background

2 masks that I need to apply on top of it, with white space on top of the top one and at the bottom of the bottom one

I managed to reproduce the design that I want at a size of 320x770 pixels, but I'm pulling my hair out to find how I coud make it scale well for different screen sizes or orientations.

I've created  a code sandbox to showcase my problem (open it to a new window of 320x770 to see the desired result). https://codesandbox.io/s/blissful-frost-ste6y?file=/pages/index.vue

main section {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.wave-wrapper {
  background: linear-gradient(#0e548c, #197d89, #0e548c);
  position: relative;
  overflow: hidden;
}

.above-waves {
  position: relative;
  z-index: 2;
}

.white {
  margin-top: 160px;
  color: #fff;
}

.mask-1,
.mask-2 {
  position: absolute;
  z-index: 1;
  width: 100%;
}

.mask-1__image {
  width: 100%;
  transform: translateY(-53%);
}

.mask-2__image {
  width: 100%;
  transform: translateY(-55%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
    <section>Section A</section>
    <div class="wave-wrapper">
      <div class="mask-1">
        <img class="mask-1__image" src="https://ste6y.sse.codesandbox.io/_nuxt/assets/waves-mask-1.svg" alt="Waves mask 1">
      </div>
      <div class="above-waves">
        <section>Section B</section>
        <section>Section C</section>
      </div>
      <div class="mask-2">
        <img class="mask-2__image" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzMjAiIGhlaWdodD0iMTI5OS43NTciIHZpZXdCb3g9IjAgMCAzMjAgMTI5OS43NTciPgogIDxnIGlkPSJHcm91cGVfMTAiIGRhdGEtbmFtZT0iR3JvdXBlIDEwIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgwLjQ3NSAtMTcxOSkiPgogICAgPHBhdGggaWQ9IlRyYWPDg8KpXzMxIiBkYXRhLW5hbWU9IlRyYWPDg8KpIDMxIiBkPSJNLTExNDUsMjE1NC43NTdWOTc5LjA2czMuOTkxLDI1LjU3MiwyNi4zNjksNTMuOTE5LDMzLjgxMiw0MS4zNTUsNjMuMTQyLDU5LjQ2OGMxNy4yMTIsMTAuNjI5LDMyLjk4NywxNy45MzUsNDcuNTc1LDI1LjMzMiw0OS42MiwyNS4xNjEsODYuOTQyLDMzLjc2LDg2Ljk0MiwzMy43NnM1Mi40NTQsNy40NDQsOTUuNSw3Mi4xNzV2OTMxLjA0MloiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDExNDUgODY0KSIgZmlsbD0iI2ZmZiIvPgogICAgPHBhdGggaWQ9IlRyYWPDg8KpXzMyIiBkYXRhLW5hbWU9IlRyYWPDg8KpIDMyIiBkPSJNLTExNDUsODU1cy05LjY4NCw5OC41ODcsNTguNDQ3LDE3My44MzhjMzkuNTE2LDQzLjY0NSwxMTguMTYsODcuMDE5LDE2MC40NDYsMTA1LjE3MiwzMC40LDEzLjA0OSwzNC44OTEsMTEuMjM1LDYyLjIsMzEuNzQ4LDI3LjMzMSwyMy45MTEsMzguNDMsNTguNDQ3LDM4LjQzLDU4LjQ0N3MtMjguNjEtMzkuNDgxLTY0LjEtNTguNDQ3Yy0xMy45ODMtNy40NzMtNDQuNTE5LTE2LjkxNC02OS4yNzctMjYuMzc2LTM3LjM3Ny0xNC4yODUtNzYuMjMyLTMwLjYtMTEwLjY0My01NS43ODEtNTYuNzg0LTQxLjU1NS03NS41MDYtOTkuNTMxLTc1LjUwNi05OS41MzFaIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxMTQ1IDg2NCkiIGZpbGw9IiM5M2I1YzUiLz4KICA8L2c+Cjwvc3ZnPgo=" alt="Waves mask 2">
      </div>
    </div>
    <div>
      <section>Section D</section>
    </div>
  </main></code>```

Here's what I've tried so far:

Scale the SVG relative to the parent by at some point it just becomes way too big

Keep the original size but I end up with the gradient showing on the sides

Title: Scale an SVG responsively in CSS

Body:
I'm wondering how to scale an SVG to look nice on every screen size. Here's what I have

A linear gradient as background

2 masks that I need to apply on top of it, with white space on top of the top one and at the bottom of the bottom one

I managed to reproduce the design that I want at a size of 320x770 pixels, but I'm pulling my hair out to find how I coud make it scale well for different screen sizes or orientations.

I've created  a code sandbox to showcase my problem (open it to a new window of 320x770 to see the desired result). https://codesandbox.io/s/blissful-frost-ste6y?file=/pages/index.vue

main section {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.wave-wrapper {
  background: linear-gradient(#0e548c, #197d89, #0e548c);
  position: relative;
  overflow: hidden;
}

.above-waves {
  position: relative;
  z-index: 2;
}

.white {
  margin-top: 160px;
  color: #fff;
}

.mask-1,
.mask-2 {
  position: absolute;
  z-index: 1;
  width: 100%;
}

.mask-1__image {
  width: 100%;
  transform: translateY(-53%);
}

.mask-2__image {
  width: 100%;
  transform: translateY(-55%);
}

Section A

Section B

Section C

        <img class="mask-2__image" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzMjAiIGhlaWdodD0iMTI5OS43NTciIHZpZXdCb3g9IjAgMCAzMjAgMTI5OS43NTciPgogIDxnIGlkPSJHcm91cGVfMTAiIGRhdGEtbmFtZT0iR3JvdXBlIDEwIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgwLjQ3NSAtMTcxOSkiPgogICAgPHBhdGggaWQ9IlRyYWPDg8KpXzMxIiBkYXRhLW5hbWU9IlRyYWPDg8KpIDMxIiBkPSJNLTExNDUsMjE1NC43NTdWOTc5LjA2czMuOTkxLDI1LjU3MiwyNi4zNjksNTMuOTE5LDMzLjgxMiw0MS4zNTUsNjMuMTQyLDU5LjQ2OGMxNy4yMTIsMTAuNjI5LDMyLjk4NywxNy45MzUsNDcuNTc1LDI1LjMzMiw0OS42MiwyNS4xNjEsODYuOTQyLDMzLjc2LDg2Ljk0MiwzMy43NnM1Mi40NTQsNy40NDQsOTUuNSw3Mi4xNzV2OTMxLjA0MloiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDExNDUgODY0KSIgZmlsbD0iI2ZmZiIvPgogICAgPHBhdGggaWQ9IlRyYWPDg8KpXzMyIiBkYXRhLW5hbWU9IlRyYWPDg8KpIDMyIiBkPSJNLTExNDUsODU1cy05LjY4NCw5OC41ODcsNTguNDQ3LDE3My44MzhjMzkuNTE2LDQzLjY0NSwxMTguMTYsODcuMDE5LDE2MC40NDYsMTA1LjE3MiwzMC40LDEzLjA0OSwzNC44OTEsMTEuMjM1LDYyLjIsMzEuNzQ4LDI3LjMzMSwyMy45MTEsMzguNDMsNTguNDQ3LDM4LjQzLDU4LjQ0N3MtMjguNjEtMzkuNDgxLTY0LjEtNTguNDQ3Yy0xMy45ODMtNy40NzMtNDQuNTE5LTE2LjkxNC02OS4yNzctMjYuMzc2LTM3LjM3Ny0xNC4yODUtNzYuMjMyLTMwLjYtMTEwLjY0My01NS43ODEtNTYuNzg0LTQxLjU1NS03NS41MDYtOTkuNTMxLTc1LjUwNi05OS41MzFaIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxMTQ1IDg2NCkiIGZpbGw9IiM5M2I1YzUiLz4KICA8L2c+Cjwvc3ZnPgo=" alt="Waves mask 2">

Section D

Here's what I've tried so far:

Scale the SVG relative to the parent by at some point it just becomes way too big

Keep the original size but I end up with the gradient showing on the sides

Body:
I would first simplify your code to consider multiple background then I edited your SVG a little and added preserveAspectRatio="none" to allow them to scale:

main section {
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.wave-wrapper {
  background:
   url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none"  viewBox="0 0 320 320"><g transform="translate(0.234 -830)"><path  d="M-1145,64.915V329.746s22.005-19.129,79.3-16.761,56.2-27.834,73.869-65.12a638.771,638.771,0,0,0,27.089-65.789s-7.336-47.7,40-38.816,99.508-78.345,99.508-78.345V-742.778H-1145Z" transform="translate(1145 762)" fill="%23fff"/><path  d="M-1145,1093.2s-4.7-4.83,28.093-16.427c17.284-6.111,50.688,2.344,71.642-5.336,2.49-.912,20.226-6.871,29.843-19.3,5.073-6.558,14.5-24.414,26.67-49.892a460.544,460.544,0,0,0,19.872-49.015s1.287-31.084,11.2-41.9,29.93-7.273,29.93-7.273,14.885.669,27.688-3.488,25.246-15.641,43.839-33.959a210.939,210.939,0,0,0,30.76-39.311s-17.815,35.666-39.747,59.618-37.356,33.452-48.208,36.191-22.293-.251-30.053,5.818-13.259,15.752-14.209,32.117c-.669,11.521-21.459,52.772-39.6,84-11.908,17.052-29.306,34.514-35.62,36.561-21.333,6.915-44.562,5.125-44.562,5.125s-30.163-1.633-47.047,15.7-20.49,53.617-20.49,53.617Z" transform="translate(1145)" fill="%2393b5c5"/></g></svg>')
   top / 101% 40%,
   url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none"  viewBox="0 0 320 330"><g  transform="translate(0.475 -1760)"><path  d="M-1145,2154.757V979.06s3.991,25.572,26.369,53.919,33.812,41.355,63.142,59.468c17.212,10.629,32.987,17.935,47.575,25.332,49.62,25.161,86.942,33.76,86.942,33.76s52.454,7.444,95.5,72.175v931.042Z" transform="translate(1145 864)" fill="%23fff"/><path  d="M-1145,855s-9.684,98.587,58.447,173.838c39.516,43.645,118.16,87.019,160.446,105.172,30.4,13.049,34.891,11.235,62.2,31.748,27.331,23.911,38.43,58.447,38.43,58.447s-28.61-39.481-64.1-58.447c-13.983-7.473-44.519-16.914-69.277-26.376-37.377-14.285-76.232-30.6-110.643-55.781-56.784-41.555-75.506-99.531-75.506-99.531Z" transform="translate(1145 864)" fill="%2393b5c5"/></g></svg>')
   bottom / 101% 40%,
   linear-gradient(#0e548c, #197d89, #0e548c);
 background-repeat:no-repeat;
}

<main>
  <section>Section A</section>
  <div class="wave-wrapper">
    <section>Section B</section>
    <section>Section C</section>
  </div>
  <section>Section D</section>
</main>

You can easily switch the position:

main section {
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.wave-wrapper {
  background:
   url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none"  viewBox="0 0 320 320"><g transform="translate(0.234 -830)"><path  d="M-1145,64.915V329.746s22.005-19.129,79.3-16.761,56.2-27.834,73.869-65.12a638.771,638.771,0,0,0,27.089-65.789s-7.336-47.7,40-38.816,99.508-78.345,99.508-78.345V-742.778H-1145Z" transform="translate(1145 762)" fill="%23fff"/><path  d="M-1145,1093.2s-4.7-4.83,28.093-16.427c17.284-6.111,50.688,2.344,71.642-5.336,2.49-.912,20.226-6.871,29.843-19.3,5.073-6.558,14.5-24.414,26.67-49.892a460.544,460.544,0,0,0,19.872-49.015s1.287-31.084,11.2-41.9,29.93-7.273,29.93-7.273,14.885.669,27.688-3.488,25.246-15.641,43.839-33.959a210.939,210.939,0,0,0,30.76-39.311s-17.815,35.666-39.747,59.618-37.356,33.452-48.208,36.191-22.293-.251-30.053,5.818-13.259,15.752-14.209,32.117c-.669,11.521-21.459,52.772-39.6,84-11.908,17.052-29.306,34.514-35.62,36.561-21.333,6.915-44.562,5.125-44.562,5.125s-30.163-1.633-47.047,15.7-20.49,53.617-20.49,53.617Z" transform="translate(1145)" fill="%2393b5c5"/></g></svg>')
   bottom / 101% 50%,
   url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none"  viewBox="0 0 320 330"><g  transform="translate(0.475 -1760)"><path  d="M-1145,2154.757V979.06s3.991,25.572,26.369,53.919,33.812,41.355,63.142,59.468c17.212,10.629,32.987,17.935,47.575,25.332,49.62,25.161,86.942,33.76,86.942,33.76s52.454,7.444,95.5,72.175v931.042Z" transform="translate(1145 864)" fill="%23fff"/><path  d="M-1145,855s-9.684,98.587,58.447,173.838c39.516,43.645,118.16,87.019,160.446,105.172,30.4,13.049,34.891,11.235,62.2,31.748,27.331,23.911,38.43,58.447,38.43,58.447s-28.61-39.481-64.1-58.447c-13.983-7.473-44.519-16.914-69.277-26.376-37.377-14.285-76.232-30.6-110.643-55.781-56.784-41.555-75.506-99.531-75.506-99.531Z" transform="translate(1145 864)" fill="%2393b5c5"/></g></svg>')
   top / 101% 50%,
   linear-gradient(#0e548c, #197d89, #0e548c);
 background-repeat:no-repeat;
}

<main>
  <section>Section A</section>
  <div class="wave-wrapper">
    <section>Section B</section>
    <section>Section C</section>
  </div>
  <section>Section D</section>
</main>

Like below for each section:

main section {
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

section:nth-child(2) {
  background:
   url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none"  viewBox="0 0 320 320"><g transform="translate(0.234 -830)"><path  d="M-1145,64.915V329.746s22.005-19.129,79.3-16.761,56.2-27.834,73.869-65.12a638.771,638.771,0,0,0,27.089-65.789s-7.336-47.7,40-38.816,99.508-78.345,99.508-78.345V-742.778H-1145Z" transform="translate(1145 762)" fill="%23fff"/><path  d="M-1145,1093.2s-4.7-4.83,28.093-16.427c17.284-6.111,50.688,2.344,71.642-5.336,2.49-.912,20.226-6.871,29.843-19.3,5.073-6.558,14.5-24.414,26.67-49.892a460.544,460.544,0,0,0,19.872-49.015s1.287-31.084,11.2-41.9,29.93-7.273,29.93-7.273,14.885.669,27.688-3.488,25.246-15.641,43.839-33.959a210.939,210.939,0,0,0,30.76-39.311s-17.815,35.666-39.747,59.618-37.356,33.452-48.208,36.191-22.293-.251-30.053,5.818-13.259,15.752-14.209,32.117c-.669,11.521-21.459,52.772-39.6,84-11.908,17.052-29.306,34.514-35.62,36.561-21.333,6.915-44.562,5.125-44.562,5.125s-30.163-1.633-47.047,15.7-20.49,53.617-20.49,53.617Z" transform="translate(1145)" fill="%2393b5c5"/></g></svg>')
   top right/101% 80% no-repeat,
   linear-gradient(#0e548c, #197d89);
}

section:nth-child(3) {
  background:
   url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none"  viewBox="0 0 320 330"><g  transform="translate(0.475 -1760)"><path  d="M-1145,2154.757V979.06s3.991,25.572,26.369,53.919,33.812,41.355,63.142,59.468c17.212,10.629,32.987,17.935,47.575,25.332,49.62,25.161,86.942,33.76,86.942,33.76s52.454,7.444,95.5,72.175v931.042Z" transform="translate(1145 864)" fill="%23fff"/><path  d="M-1145,855s-9.684,98.587,58.447,173.838c39.516,43.645,118.16,87.019,160.446,105.172,30.4,13.049,34.891,11.235,62.2,31.748,27.331,23.911,38.43,58.447,38.43,58.447s-28.61-39.481-64.1-58.447c-13.983-7.473-44.519-16.914-69.277-26.376-37.377-14.285-76.232-30.6-110.643-55.781-56.784-41.555-75.506-99.531-75.506-99.531Z" transform="translate(1145 864)" fill="%2393b5c5"/></g></svg>')
   bottom right/101% 80% no-repeat,
   linear-gradient(#197d89, #0e548c);
}

<main>
  <section>Section A</section>
  <section>Section B</section>
  <section>Section C</section>
  <section>Section D</section>
</main>

As a bonus you can also consider mask to have transparency instead of white color:

:root {
  --svg1:url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none"  viewBox="0 0 320 320"><g transform="translate(0.234 -830)"><path  d="M-1145,64.915V329.746s22.005-19.129,79.3-16.761,56.2-27.834,73.869-65.12a638.771,638.771,0,0,0,27.089-65.789s-7.336-47.7,40-38.816,99.508-78.345,99.508-78.345V-742.778H-1145Z" transform="translate(1145 762)" fill="%23fff"/><path  d="M-1145,1093.2s-4.7-4.83,28.093-16.427c17.284-6.111,50.688,2.344,71.642-5.336,2.49-.912,20.226-6.871,29.843-19.3,5.073-6.558,14.5-24.414,26.67-49.892a460.544,460.544,0,0,0,19.872-49.015s1.287-31.084,11.2-41.9,29.93-7.273,29.93-7.273,14.885.669,27.688-3.488,25.246-15.641,43.839-33.959a210.939,210.939,0,0,0,30.76-39.311s-17.815,35.666-39.747,59.618-37.356,33.452-48.208,36.191-22.293-.251-30.053,5.818-13.259,15.752-14.209,32.117c-.669,11.521-21.459,52.772-39.6,84-11.908,17.052-29.306,34.514-35.62,36.561-21.333,6.915-44.562,5.125-44.562,5.125s-30.163-1.633-47.047,15.7-20.49,53.617-20.49,53.617Z" transform="translate(1145)" fill="%2393b5c5"/></g></svg>');
  --svg1-mask:url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none"  viewBox="0 0 320 320"><g transform="translate(0.234 -830)"><path  d="M-1145,64.915V329.746s22.005-19.129,79.3-16.761,56.2-27.834,73.869-65.12a638.771,638.771,0,0,0,27.089-65.789s-7.336-47.7,40-38.816,99.508-78.345,99.508-78.345V-742.778H-1145Z" transform="translate(1145 762)" fill="%23fff"/></g></svg>');
  --svg2:url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none"  viewBox="0 0 320 330"><g  transform="translate(0.475 -1760)"><path  d="M-1145,2154.757V979.06s3.991,25.572,26.369,53.919,33.812,41.355,63.142,59.468c17.212,10.629,32.987,17.935,47.575,25.332,49.62,25.161,86.942,33.76,86.942,33.76s52.454,7.444,95.5,72.175v931.042Z" transform="translate(1145 864)" fill="%23fff"/><path  d="M-1145,855s-9.684,98.587,58.447,173.838c39.516,43.645,118.16,87.019,160.446,105.172,30.4,13.049,34.891,11.235,62.2,31.748,27.331,23.911,38.43,58.447,38.43,58.447s-28.61-39.481-64.1-58.447c-13.983-7.473-44.519-16.914-69.277-26.376-37.377-14.285-76.232-30.6-110.643-55.781-56.784-41.555-75.506-99.531-75.506-99.531Z" transform="translate(1145 864)" fill="%2393b5c5"/></g></svg>');
  --svg2-mask:url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none"  viewBox="0 0 320 330"><g  transform="translate(0.475 -1760)"><path  d="M-1145,2154.757V979.06s3.991,25.572,26.369,53.919,33.812,41.355,63.142,59.468c17.212,10.629,32.987,17.935,47.575,25.332,49.62,25.161,86.942,33.76,86.942,33.76s52.454,7.444,95.5,72.175v931.042Z" transform="translate(1145 864)" fill="%23fff"/></g></svg>');
}

main section {
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position:relative;
  z-index:0;
}

section:nth-child(2):before,
section:nth-child(3):before{
  content:"";
  position:absolute;
  z-index:-1;
  top:0;
  left:0;
  right:0;
  bottom:0;

  --s:101% 80%; /* control the height(80%) to adjust the SVG */
  /* Mask */
  -webkit-mask:
     var(--m),
     linear-gradient(#fff,#fff);
          mask:
     var(--m),
     linear-gradient(#fff,#fff);
  -webkit-mask-size: var(--s),100% 100%;
          mask-size: var(--s),100% 100%;
  -webkit-mask-position:var(--p);
          mask-position:var(--p);
  -webkit-mask-composite:destination-out;
          mask-composite:exclude;
  -webkit-mask-repeat:no-repeat;
          mask-repeat:no-repeat;
  /* background */
  background:
     var(--b) var(--p)/var(--s),
     linear-gradient(var(--d),#0e548c, #197d89);
  background-repeat: no-repeat;
}

section:nth-child(2) {
  --m:var(--svg1-mask);
  --p:top right;
  --b:var(--svg1);
  --d:180deg;
}

section:nth-child(3) {
  --m:var(--svg2-mask);
  --p:bottom right;
  --b:var(--svg2);
  --d:0deg;
}

body {
  background:grey;
  margin:0;
}

<main>
  <section>Section A</section>
  <section>Section B</section>
  <section>Section C</section>
  <section>Section D</section>
</main>


来源: stackexchange

问:
Can I import svg into Gideros?
Ok I will admit to being a noob with Gideros.  I am trying to import an svg file.  I followed the same procedure as you would do for a png file, that is create a texture using:

myTexture = Texture.new("orangeSquare.svg")

orangeSquare = Bitmap.new(myTexture)

stage:addChild(orangeSquare)

Unsurprisingly it doesn't work (output gives orangeSquare.svg: Error while reading image file. and program does not run) as it is not a bitmap file.  Is there an alternative to import svg files?  It is probably a very simple solution but I have been searching for some time without an answer.  I am considering giving up on Gideros if I don't find an answer to what should be a simple problem.

答:
You can not import the svg directly, you need to pass the svg data:

```<code>--Banana shape, SVG path format
local banana = "M8.64,223.948c0,0,143.468,3.431,185.777-181.808c2.673-11.702-1.23-20.154,1.316-33.146h16.287c0,0-3.14,17.248,1.095,30.848c21.392,68.692-4.179,242.343-204.227,196.59L8.64,223.948z"
p=Path2D.new()
p:setSvgPath(banana) --Set the path from a SVG path description
p:setLineThickness(5) -- Outline width
p:setFillColor(0xFFFF80,0.7) --Fill color
p:setLineColor(0x404000) --Line color
p:setAnchorPosition(100,100)
stage:addChild(p)
</code>```

You can find more info on their wiki: https://wiki.giderosmobile.com/index.php?search=svg&title=Special%3ASearch&go=Go&fulltext=1

They also have it as a sample project when you open gideros studio.

ContentLicense: CC BY-SA 4.0

Title: Can I import svg into Gideros?

Body:
You can not import the svg directly, you need to pass the svg data:

--Banana shape, SVG path format
local banana = "M8.64,223.948c0,0,143.468,3.431,185.777-181.808c2.673-11.702-1.23-20.154,1.316-33.146h16.287c0,0-3.14,17.248,1.095,30.848c21.392,68.692-4.179,242.343-204.227,196.59L8.64,223.948z"
p=Path2D.new()
p:setSvgPath(banana) --Set the path from a SVG path description
p:setLineThickness(5) -- Outline width
p:setFillColor(0xFFFF80,0.7) --Fill color
p:setLineColor(0x404000) --Line color
p:setAnchorPosition(100,100)
stage:addChild(p)

You can find more info on their wiki: https://wiki.giderosmobile.com/index.php?search=svg&title=Special%3ASearch&go=Go&fulltext=1

They also have it as a sample project when you open gideros studio.


问:
Is putting a div inside an anchor ever correct?
I've heard that putting a block element inside a inline element is a HTML sin:

        What we have here is a problem.
        You see, an anchor element is an inline element,
        and the div element is a block level element.

```

But what about if you style the outer anchor as display:block in the stylesheet? Is it still wrong? The HTML 4.01 spec on block-level and inline elements seems to think so:

Style sheets provide the means to
specify the rendering of arbitrary
elements, including whether an element
is rendered as block or inline. In
some cases, such as an inline style
for list elements, this may be
appropriate, but generally speaking,
authors are discouraged from
overriding the conventional
interpretation of HTML elements in
this way.

Does anyone have any further tips about this issue?

答:
you can achieve this by adding "::before" Pseudo-element

Pure CSS Trick ;)

a:before{
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1;
  pointer-events: auto;
  content: "";
  background-color: rgba(0,0,0,0);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="card" style="width: 18rem;">
  <img src="https://via.placeholder.com/250" class="card-img-top" alt="...">
  <div class="card-body">
    <h5 class="card-title">Card with stretched link</h5>
    <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
    Go somewhere
  </div>
</div></code>```

Body:
I've heard that putting a block element inside a inline element is a HTML sin:

        What we have here is a problem.
        You see, an anchor element is an inline element,
        and the div element is a block level element.

But what about if you style the outer anchor as display:block in the stylesheet? Is it still wrong? The HTML 4.01 spec on block-level and inline elements seems to think so:

Style sheets provide the means to
specify the rendering of arbitrary
elements, including whether an element
is rendered as block or inline. In
some cases, such as an inline style
for list elements, this may be
appropriate, but generally speaking,
authors are discouraged from
overriding the conventional
interpretation of HTML elements in
this way.

Does anyone have any further tips about this issue?

Body:
you can achieve this by adding "::before" Pseudo-element

Pure CSS Trick ;)

a:before{
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1;
  pointer-events: auto;
  content: "";
  background-color: rgba(0,0,0,0);
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="card" style="width: 18rem;">
  <img src="https://via.placeholder.com/250" class="card-img-top" alt="...">
  <div class="card-body">
    <h5 class="card-title">Card with stretched link</h5>
    <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
    <a href="#" class="btn btn-primary stretched-link">Go somewhere</a>
  </div>
</div>


问:
How to resolve conflicts in xcode 4 when using SVN?
On trying to update my working copy, Xcode indicates that there are certain conflicts. A new screen comes up which shows my local file on the left and the server code on the right highlighting whatever conflicts are present. What I'm doing at this stage is, reviewing my code and make necessary changes using this tool:

When I'm finally done reviewing and making changes to my code as necessary, I'd like to update my project with the changes I've made. However the update button at the bottom is still disabled. What is it that I'm missing here? How do I convey to Xcode that I'm done making changes and it may update the project?

答:
After making changes to your code, you have to right click your file and select 'resolve conflicts.'

I hope this may help.

ContentLicense: CC BY-SA 3.0


问:
Asynchronous XML parsing with SAX in Kotlin
I have a SAX parser reading an XML file (specifically, a .xlsx file) and returning the content as a list of Row objects: it's roughly like this

```<code>fun readExcelContent(data: InputStream) {
    val pkg = OPCPackage.open(file)
    val reader = XSSFReader(pkg)
    val sst = reader.sharedStringsTable
    val parser = XMLHelper.newXMLReader()
    val handler = ExcelSheetHandler(sst)
    parser.contentHandler = handler
    val sheet = reader.sheetsData.next()
    val source = InputSource(sheet)
    parser.parse(source)

    return handler.content
}
</code>```

Where ExcelSheetHandler is a class that extends DefaultHandler and takes care of filling up a list:

```<code>class ExcelSheetHandler(sst: SharedStringsTable): DefaultHandler() {

    private val content = mutableListOf<Row>()

    @Throws(SAXException::class)
    override fun endElement(uri: String?, localName: String?, name: String) {
        // If it's the end of a content element, add a row to content
    }
}
</code>```

It's basically a slight modification of the event model example in the Apache POI howto.

I was wondering if there was a way to have readExcelContent return an asynchronous object, such as a flow, and emit the rows to its client as soon as they are read rather than having to wait for the whole file to be processed.

答:
I'd prefer kotlinx.coroutines.Channel over kotlinx.coroutines.Flow for this use case since this is a hot stream of data triggered by the parse() method. Here's what Kotlin Language Guide states.

Flows are cold streams similar to sequences — the code inside a flow
  builder does not run until the flow is collected

Here's a quick implementation that you can try.

```<code>class ExcelSheetHandler : DefaultHandler() {

    private val scope = CoroutineScope(Dispatchers.Default)
    private val rows = Channel<Row>()

    override fun endDocument() {
        // To avoid suspending forever!
        rows.close()
    }

    @Throws(SAXException::class)
    override fun endElement(uri: String?, localName: String?, name: String) {
        readRow(uri, localName, name)
    }

    private fun readRow(uri: String?, localName: String?, name: String) = runBlocking {
        // If it's the end of a content element, add a row to content
        rows.send(row)
    }

    // Client code - if it needs to be somewhere else
    // you can expose a reference to Channel object
    private fun processRows() = scope.launch {
        for(row in rows) {
            // Do something
            println(row)
        }
    }
}
</code>```

Body:
I have a SAX parser reading an XML file (specifically, a .xlsx file) and returning the content as a list of Row objects: it's roughly like this

fun readExcelContent(data: InputStream) {
    val pkg = OPCPackage.open(file)
    val reader = XSSFReader(pkg)
    val sst = reader.sharedStringsTable
    val parser = XMLHelper.newXMLReader()
    val handler = ExcelSheetHandler(sst)
    parser.contentHandler = handler
    val sheet = reader.sheetsData.next()
    val source = InputSource(sheet)
    parser.parse(source)

    return handler.content
}

Where ExcelSheetHandler is a class that extends DefaultHandler and takes care of filling up a list:

class ExcelSheetHandler(sst: SharedStringsTable): DefaultHandler() {

    private val content = mutableListOf<Row>()

    @Throws(SAXException::class)
    override fun endElement(uri: String?, localName: String?, name: String) {
        // If it's the end of a content element, add a row to content
    }
}

It's basically a slight modification of the event model example in the Apache POI howto.

I was wondering if there was a way to have readExcelContent return an asynchronous object, such as a flow, and emit the rows to its client as soon as they are read rather than having to wait for the whole file to be processed.

Body:
I'd prefer kotlinx.coroutines.Channel over kotlinx.coroutines.Flow for this use case since this is a hot stream of data triggered by the parse() method. Here's what Kotlin Language Guide states.

Flows are cold streams similar to sequences — the code inside a flow
  builder does not run until the flow is collected

Here's a quick implementation that you can try.

class ExcelSheetHandler : DefaultHandler() {

    private val scope = CoroutineScope(Dispatchers.Default)
    private val rows = Channel<Row>()

    override fun endDocument() {
        // To avoid suspending forever!
        rows.close()
    }

    @Throws(SAXException::class)
    override fun endElement(uri: String?, localName: String?, name: String) {
        readRow(uri, localName, name)
    }

    private fun readRow(uri: String?, localName: String?, name: String) = runBlocking {
        // If it's the end of a content element, add a row to content
        rows.send(row)
    }

    // Client code - if it needs to be somewhere else
    // you can expose a reference to Channel object
    private fun processRows() = scope.launch {
        for(row in rows) {
            // Do something
            println(row)
        }
    }
}


问:
JAVA PriorityQueue comparator not accepting float

I have the following class:

```<code>    int x;
    int y;
    float distance;

    public Point(int x, int y, float distance){
        this.x = x;
        this.y = y;
        this.distance = distance;
    }
}
</code>```

On my main program I have this line:

```<code>PriorityQueue<Point> minHeap = new PriorityQueue<Point>( (a,b) -> ((float) a.distance - (float) b.distance) );
</code>```

I keep getting this error:

```<code>        PriorityQueue<Point> minHeap = new PriorityQueue<Point>( (a,b) -> ((float) a.distance - (float) b.distance) );
                                                                                ^
    possible lossy conversion from float to int```
------------------------------------------------------------------------------------

I dont know why is not accepting my comparator method. Any ideas? thanks in advance.
```

答:
That's because the compare method you're defining returns an int, but since you're getting an int with an operation between floats the compiler tells you some data might get lost (it actually will, all the decimals, but you don't really care since it's just a comparator).

You could use Float.compare(f1, f2) in

```<code>PriorityQueue<Point> minHeap = new PriorityQueue<Point>( (a,b) -> Float.compare(a.distance, b.distance));
</code>```

Body:
I have the following class:

    int x;
    int y;
    float distance;

    public Point(int x, int y, float distance){
        this.x = x;
        this.y = y;
        this.distance = distance;
    }
}

On my main program I have this line:

PriorityQueue<Point> minHeap = new PriorityQueue<Point>( (a,b) -> ((float) a.distance - (float) b.distance) );

I keep getting this error:

        PriorityQueue<Point> minHeap = new PriorityQueue<Point>( (a,b) -> ((float) a.distance - (float) b.distance) );
                                                                                ^
    possible lossy conversion from float to int```
------------------------------------------------------------------------------------

I dont know why is not accepting my comparator method. Any ideas? thanks in advance.

Body:
That's because the compare method you're defining returns an int, but since you're getting an int with an operation between floats the compiler tells you some data might get lost (it actually will, all the decimals, but you don't really care since it's just a comparator).

You could use Float.compare(f1, f2) in

PriorityQueue<Point> minHeap = new PriorityQueue<Point>( (a,b) -> Float.compare(a.distance, b.distance));


问:
(Django) Trying to figure out how I can get the right product using query parameters on Postman (url.py and views.py)
I have been building a sandwich shop app and I succeesfully build models.py and inserted all the product data. However, when I try to call specific products using Postman and the Django server, it keeps showing 404. What I typed on postman is like so:
http://10.58.1.157:8000/product/sandwich?product_id=1

Below are my codes for urls.py and views.py

So far, I have tried:
urls.py

```<code>from django.urls import path
from .views import ProductView

urlpatterns = [
    path('sandwich/int:<product_id>/', ProductView.as_view()),
]
</code>```

and:
urls.py

```<code>path('sandwich/(?P<product_id>[\w.-]+)/', ProductView.as_view())
</code>```

views.py

```<code>import json
import bcrypt
import jwt

from django.views               import View
from django.shortcuts           import render
from django.http                import HttpResponse, JsonResponse
from django.db.models           import Q

from .models                    import Product, Category, SubCategory

class ProductView(View):
    def get(self, request):

        product_id = request.GET.get('product_id', None)

        return JsonResponse({'product_name':Product.objects.get(id=product_id).values()})
</code>```

To clarify the GET request, I will add the screenshot of Postman below:

答:
It seems like this is due to malformed URL path. That's whats typically indicative of 404-NotFound error.

You need to add question mark that essentially forms the querystring. It is processed and available as a dictionary-like object (a QueryDict) in request.GET in views.py

You can define it like so, with a ? using a REGEX pattern (You may also alter to your needs)

```<code>path('sandwich/(?P<product_id>[\w.-]+)/', ProductView.as_view()),
</code>```

In your views.py you can filter them with

```<code>product_id = request.GET.get('product_id', None)
</code>```

This should now hopefully return a response now that the URL cannot give a 404 error.

See this for an example

Body:
I have been building a sandwich shop app and I succeesfully build models.py and inserted all the product data. However, when I try to call specific products using Postman and the Django server, it keeps showing 404. What I typed on postman is like so:
http://10.58.1.157:8000/product/sandwich?product_id=1

Below are my codes for urls.py and views.py

So far, I have tried:
urls.py

from django.urls import path
from .views import ProductView

urlpatterns = [
    path('sandwich/int:<product_id>/', ProductView.as_view()),
]

and:
urls.py

path('sandwich/(?P<product_id>[\w.-]+)/', ProductView.as_view())

views.py

import json
import bcrypt
import jwt

from django.views               import View
from django.shortcuts           import render
from django.http                import HttpResponse, JsonResponse
from django.db.models           import Q

from .models                    import Product, Category, SubCategory

class ProductView(View):
    def get(self, request):

        product_id = request.GET.get('product_id', None)

        return JsonResponse({'product_name':Product.objects.get(id=product_id).values()})

To clarify the GET request, I will add the screenshot of Postman below:

Body:
It seems like this is due to malformed URL path. That's whats typically indicative of 404-NotFound error.

You need to add question mark that essentially forms the querystring. It is processed and available as a dictionary-like object (a QueryDict) in request.GET in views.py

You can define it like so, with a ? using a REGEX pattern (You may also alter to your needs)

path('sandwich/(?P<product_id>[\w.-]+)/', ProductView.as_view()),

In your views.py you can filter them with

product_id = request.GET.get('product_id', None)

This should now hopefully return a response now that the URL cannot give a 404 error.

See this for an example


问:
How to get resource path for PNG files from Bundle?
I'm trying to get a resource path of image files added to the project. The following code works fine for jpeg files. But it gives nil for PNG files. The name of the images are correct and added to the project.

Image files are added with the puppy.png and car.jpeg names.

```<code>let carPathURL = Bundle.main.path(forResource: "car", ofType: "jpeg") // Gives right path
let puppyPathURL = Bundle.main.path(forResource: "puppy", ofType: "png") // Gives nil
</code>```

Below is the screenshot of the Application bundle contents.

The screenshot for the project is below showing the added files.

Why it is giving nil for PNG files? How to get the resource path for PNG files?

答:
If extension is uppercased (ie, PNG, not png) you have to specify this explicitly</p>

```<code>Bundle.main.path(forResource: "puppy", ofType: "PNG")
</code>```

Body:
I'm trying to get a resource path of image files added to the project. The following code works fine for jpeg files. But it gives nil for PNG files. The name of the images are correct and added to the project.

Image files are added with the puppy.png and car.jpeg names.

let carPathURL = Bundle.main.path(forResource: "car", ofType: "jpeg") // Gives right path
let puppyPathURL = Bundle.main.path(forResource: "puppy", ofType: "png") // Gives nil

Below is the screenshot of the Application bundle contents.

The screenshot for the project is below showing the added files.

Why it is giving nil for PNG files? How to get the resource path for PNG files?

Body:
If extension is uppercased (ie, PNG, not png) you have to specify this explicitly

Bundle.main.path(forResource: "puppy", ofType: "PNG")


问:
How do I extend a Yii2 kartik-v grid DataColumn to a BooleanColumn?
Currently:

Model: ProductSearch

```<code><?php
    namespace frontend\models;

    use yii\base\Model;
    use yii\data\ActiveDataProvider;
    use frontend\models\Product;

    class ProductSearch extends Product
    {
      public function rules()
      {
        return [
        [['id','productcategory_id', 'productsubcategory_id'], 'integer'],
        [['name', 'surname','frequency','contactmobile', 'gc_number','specialrequest',
          'sellstartdate', 'sellenddate', 'discontinueddate', 'modifieddate'], 'safe'],
        [['listprice'], 'number'],
        [['isactive'],'boolean'],
        ];
      }

      public function scenarios()
      {
         return Model::scenarios();
      }

      public function search($params)
      {
         $query = Product::find();

         $dataProvider = new ActiveDataProvider([
          'pagination' => ['pageSize' => 10],
          'query' => $query,
          'db'=> \frontend\components\Utilities::userdb(),
         ]);

         $this->load($params);
         if (!$this->validate()) {
            return $dataProvider;
         }

         $dataProvider->sort->attributes['productcategory_id'] = [
         'asc' => ['productcategory_id' => SORT_ASC],
         'desc' => ['productcategory_id' => SORT_DESC],
         ];
         $dataProvider->sort->attributes['productsubcategory_id'] = [
         'asc' => ['productsubcategory_id' => SORT_ASC],
         'desc' => ['productsubcategory_id' => SORT_DESC],
         ];

         $query->andFilterWhere([
            'id' => $this->id,
            'listprice' => $this->listprice,
            'isactive'=>$this->isactive,
            'productcategory_id' => $this->productcategory_id,
            'productsubcategory_id' => $this->productsubcategory_id,
            'frequency'=>$this->frequency,
            'name'=>$this->name,
            'surname'=>$this->surname,
            'gc_number'=>$this->gc_number,
            'sellstartdate' => $this->sellstartdate,
            'sellenddate' => $this->sellenddate,
            'discontinueddate' => $this->discontinueddate,
            'modifieddate' => $this->modifieddate,
        ])
        ->all();
        return $dataProvider;
    }
}
</code>```

Current Grid Picture and Code

```<code>[
 'class' => 'kartik\grid\DataColumn',
 'attribute'=>'isactive',
 'value' => function ($dataProvider) {
                return $dataProvider->isactive;
        },
 'filter'=>Html::activeCheckbox($searchModel,'isactive',ArrayHelper::map(Product::find()->indexBy('isactive')->asArray()->all(),'isactive','isactive'),[ 'options' => ['style'=> 'font-size:'.Yii::$app->session['sliderfontproduct'].'px']]),
 'filterType'=>GridView::FILTER_CHECKBOX,
 'filterInputOptions' => [
              'options' => ['style'=> 'font-size:'.Yii::$app->session['sliderfontproduct'].'px'],
              'label'=>'',
 ],
 'filterWidgetOptions'=>[
              'options' => ['style'=> 'font-size:'.Yii::$app->session['sliderfontproduct'].'px'],
              'type'=>\kartik\switchinput\Switchinput::CHECKBOX
 ],
],

<?php
    echo kartik\grid\GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => $gridColumns,
    'bootstrap'=>true,
    'options' => ['style'=> 'font-size:'.Yii::$app->session['sliderfontproduct'].'px'],
    'containerOptions' => ['style'=>'overflow: auto'],
    'pjax' => true,
    'pjaxSettings' =>[
                      'neverTimeout'=>true,
                      'options'=>['id'=>'kv-unique-id-7'],
                     ],
    'responsiveWrap'=>true,
    'bordered' => true,
    'striped' => true,
    'condensed' => true,
    'responsive' => true,
    'hover' => true,
    'floatHeader' => false,
    'showPageSummary' => true,
    'panel' => [
    'type' => GridView::TYPE_PRIMARY,
    'heading'=> $comptel,
    ],
    'exportConfig' => [
                   GridView::CSV => ['label' => Yii::t('app','Export as CSV'),'config' =>
$config_array, 'filename' => 'Houses_Printed_'.date('d-M-Y')],
                   GridView::HTML => ['label' => Yii::t('app','Export as HTML'),'config' =>
$config_array, 'filename' => 'Houses_Printed_'.date('d-M-Y')],
                   GridView::PDF => [ 'label' => Yii::t('app','Export as PDF'),'config' =>
$config_array, 'filename' => 'Houses_Printed_'.date('d-M-Y')],
                   GridView::EXCEL=> ['label' => Yii::t('app','Export as EXCEL'), 'filename' =>
'Houses_Printed_'.date('d-M-Y')],
                   GridView::TEXT=> ['label' => Yii::t('app','Export as TEXT'), 'filename' =>
'Houses_Printed_'.date('d-M-Y')],
                 ],
]);
?>
</code>```

If I change the format to 'boolean' I get yes's however I would prefer to see an image of a tick or a cross. A tick for the yes's and a cross for the no's.

How can I accomplish this given the above code? My data is filtering nicely so that if I check on the checkbox column under active, it either displays zero's or one's.

答:
I have managed to sort this problem out by changing the classname to Boolean. The BooleanColumn extends from the DataColumn. I removed the:

```<code>'format' => 'boolean'
</code>```

as well. Even though the filter in kartik\grid\BooleanColumn is auto-generated it is generating the following output for all my one's which is what I want:

Here is my final code:

```<code>[
 'class' => 'kartik\grid\BooleanColumn',
 'attribute'=>'isactive',
 'value' => function ($dataProvider) {
                return $dataProvider->isactive;
        },
 'filter'=>Html::activeCheckbox($searchModel,'isactive',ArrayHelper::map(Product::find()->indexBy('isactive')->asArray()->all(),'isactive','isactive'),[ 'options' => ['style'=> 'font-size:'.Yii::$app->session['sliderfontproduct'].'px']]),
 'filterType'=>GridView::FILTER_CHECKBOX,
 'filterInputOptions' => [
              'options' => ['style'=> 'font-size:'.Yii::$app->session['sliderfontproduct'].'px'],
              'label'=>'',
 ],
 'filterWidgetOptions'=>[
              'options' => ['style'=> 'font-size:'.Yii::$app->session['sliderfontproduct'].'px'],
              'type'=>\kartik\switchinput\Switchinput::CHECKBOX
 ],
],
</code>```

Body:
Currently:

Model: ProductSearch

<?php
    namespace frontend\models;

    use yii\base\Model;
    use yii\data\ActiveDataProvider;
    use frontend\models\Product;

    class ProductSearch extends Product
    {
      public function rules()
      {
        return [
        [['id','productcategory_id', 'productsubcategory_id'], 'integer'],
        [['name', 'surname','frequency','contactmobile', 'gc_number','specialrequest',
          'sellstartdate', 'sellenddate', 'discontinueddate', 'modifieddate'], 'safe'],
        [['listprice'], 'number'],
        [['isactive'],'boolean'],
        ];
      }

      public function scenarios()
      {
         return Model::scenarios();
      }

      public function search($params)
      {
         $query = Product::find();

         $dataProvider = new ActiveDataProvider([
          'pagination' => ['pageSize' => 10],
          'query' => $query,
          'db'=> \frontend\components\Utilities::userdb(),
         ]);

         $this->load($params);
         if (!$this->validate()) {
            return $dataProvider;
         }

         $dataProvider->sort->attributes['productcategory_id'] = [
         'asc' => ['productcategory_id' => SORT_ASC],
         'desc' => ['productcategory_id' => SORT_DESC],
         ];
         $dataProvider->sort->attributes['productsubcategory_id'] = [
         'asc' => ['productsubcategory_id' => SORT_ASC],
         'desc' => ['productsubcategory_id' => SORT_DESC],
         ];

         $query->andFilterWhere([
            'id' => $this->id,
            'listprice' => $this->listprice,
            'isactive'=>$this->isactive,
            'productcategory_id' => $this->productcategory_id,
            'productsubcategory_id' => $this->productsubcategory_id,
            'frequency'=>$this->frequency,
            'name'=>$this->name,
            'surname'=>$this->surname,
            'gc_number'=>$this->gc_number,
            'sellstartdate' => $this->sellstartdate,
            'sellenddate' => $this->sellenddate,
            'discontinueddate' => $this->discontinueddate,
            'modifieddate' => $this->modifieddate,
        ])
        ->all();
        return $dataProvider;
    }
}

Current Grid Picture and Code

[
 'class' => 'kartik\grid\DataColumn',
 'attribute'=>'isactive',
 'value' => function ($dataProvider) {
                return $dataProvider->isactive;
        },
 'filter'=>Html::activeCheckbox($searchModel,'isactive',ArrayHelper::map(Product::find()->indexBy('isactive')->asArray()->all(),'isactive','isactive'),[ 'options' => ['style'=> 'font-size:'.Yii::$app->session['sliderfontproduct'].'px']]),
 'filterType'=>GridView::FILTER_CHECKBOX,
 'filterInputOptions' => [
              'options' => ['style'=> 'font-size:'.Yii::$app->session['sliderfontproduct'].'px'],
              'label'=>'',
 ],
 'filterWidgetOptions'=>[
              'options' => ['style'=> 'font-size:'.Yii::$app->session['sliderfontproduct'].'px'],
              'type'=>\kartik\switchinput\Switchinput::CHECKBOX
 ],
],

<?php
    echo kartik\grid\GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => $gridColumns,
    'bootstrap'=>true,
    'options' => ['style'=> 'font-size:'.Yii::$app->session['sliderfontproduct'].'px'],
    'containerOptions' => ['style'=>'overflow: auto'],
    'pjax' => true,
    'pjaxSettings' =>[
                      'neverTimeout'=>true,
                      'options'=>['id'=>'kv-unique-id-7'],
                     ],
    'responsiveWrap'=>true,
    'bordered' => true,
    'striped' => true,
    'condensed' => true,
    'responsive' => true,
    'hover' => true,
    'floatHeader' => false,
    'showPageSummary' => true,
    'panel' => [
    'type' => GridView::TYPE_PRIMARY,
    'heading'=> $comptel,
    ],
    'exportConfig' => [
                   GridView::CSV => ['label' => Yii::t('app','Export as CSV'),'config' =>
$config_array, 'filename' => 'Houses_Printed_'.date('d-M-Y')],
                   GridView::HTML => ['label' => Yii::t('app','Export as HTML'),'config' =>
$config_array, 'filename' => 'Houses_Printed_'.date('d-M-Y')],
                   GridView::PDF => [ 'label' => Yii::t('app','Export as PDF'),'config' =>
$config_array, 'filename' => 'Houses_Printed_'.date('d-M-Y')],
                   GridView::EXCEL=> ['label' => Yii::t('app','Export as EXCEL'), 'filename' =>
'Houses_Printed_'.date('d-M-Y')],
                   GridView::TEXT=> ['label' => Yii::t('app','Export as TEXT'), 'filename' =>
'Houses_Printed_'.date('d-M-Y')],
                 ],
]);
?>

If I change the format to 'boolean' I get yes's however I would prefer to see an image of a tick or a cross. A tick for the yes's and a cross for the no's.

How can I accomplish this given the above code? My data is filtering nicely so that if I check on the checkbox column under active, it either displays zero's or one's.

Body:
I have managed to sort this problem out by changing the classname to Boolean. The BooleanColumn extends from the DataColumn. I removed the:

'format' => 'boolean'

as well. Even though the filter in kartik\grid\BooleanColumn is auto-generated it is generating the following output for all my one's which is what I want:

Here is my final code:

[
 'class' => 'kartik\grid\BooleanColumn',
 'attribute'=>'isactive',
 'value' => function ($dataProvider) {
                return $dataProvider->isactive;
        },
 'filter'=>Html::activeCheckbox($searchModel,'isactive',ArrayHelper::map(Product::find()->indexBy('isactive')->asArray()->all(),'isactive','isactive'),[ 'options' => ['style'=> 'font-size:'.Yii::$app->session['sliderfontproduct'].'px']]),
 'filterType'=>GridView::FILTER_CHECKBOX,
 'filterInputOptions' => [
              'options' => ['style'=> 'font-size:'.Yii::$app->session['sliderfontproduct'].'px'],
              'label'=>'',
 ],
 'filterWidgetOptions'=>[
              'options' => ['style'=> 'font-size:'.Yii::$app->session['sliderfontproduct'].'px'],
              'type'=>\kartik\switchinput\Switchinput::CHECKBOX
 ],
],


问:
Checking for duplicate data in SQL Server
Please don't ask me why but there is a lot of duplicate data where every field is duplicated.

For example

```<code>alex, 1
alex, 1
liza, 32
hary, 34
</code>```

I will need to eliminate from this table one of the alex, 1 rows

I know this algorithm will be very ineffecient, but it does not matter. I will need to remove duplicate data.

What is the best way to do this? Please keep in mind I do not have 2 fields, I actually have about 10 fields to check on.

答:
I understand this does not answer the specific question (eliminating dupes in SAME table), but I'm offering the solution because it is very fast and might work best for the author.

Speedy solution, if you don't mind creating a new table, create a new table with the same schema named NewTable.

Execute this SQL

```<code> Insert into NewTable
 Select
   name,
   num
 from
   OldTable
 group by
   name,
   num
</code>```

Just include every field name in both the select and group by clauses.

Body:
Please don't ask me why but there is a lot of duplicate data where every field is duplicated.

For example

alex, 1
alex, 1
liza, 32
hary, 34

I will need to eliminate from this table one of the alex, 1 rows

I know this algorithm will be very ineffecient, but it does not matter. I will need to remove duplicate data.

What is the best way to do this? Please keep in mind I do not have 2 fields, I actually have about 10 fields to check on.

Body:
I understand this does not answer the specific question (eliminating dupes in SAME table), but I'm offering the solution because it is very fast and might work best for the author.

Speedy solution, if you don't mind creating a new table, create a new table with the same schema named NewTable.

Execute this SQL

 Insert into NewTable
 Select
   name,
   num
 from
   OldTable
 group by
   name,
   num

Just include every field name in both the select and group by clauses.


问:
To retrieve specific data from multiple similar portions in a .json file
A part of json file's content as below:

```<code>{"ID": "PK45", "People": "Kate", "Date": "2020-01-05"}, {"ID": "OI85", "People": "John", "Date": "2020-01-18" }, {"ID": "CN658", "People": "Pevo", "Date": "2020-02-01" }
</code>```

It has multiple portions containing "ID", "People" and "Date".

What I want to do is to retrieve John's ID (in this case "OI85". )

If the key is unique, I can use:

```<code>data_content = json.loads(data)
ID = data_content['ID']
</code>```

But there are multiple similar portions. So I can only locate the "John" first:

```<code>with open("C:\\the_file.json") as data_file:
    data = data_file.read()
    where = data.find('John')
    where_1 = data[where - 20 : where]
    ID = where_1[where_1.find('ID')+3:where_1.find('ID')+7]
    print (ID)
</code>```

It looked clumsy.

What will be the smart json way to retrieve the specific data from multiple similar portions in a .json file?

Thank you.

答:
Iterate on the list of dicts until you find the right one:

```<code>import json

data = '[{"ID": "PK45", "People": "Kate", "Date": "2020-01-05"}, {"ID": "OI85", "People": "John", "Date": "2020-01-18" }, {"ID": "CN658", "People": "Pevo", "Date": "2020-02-01" }]'

data_content = json.loads(data)

def find_id_by_name(name, data):
    for d in data:
        if d['People'] == name:
            return d["ID"]
    else:
        raise ValueError('Name not found')

print(find_id_by_name('John', data_content))
# OI85

print(find_id_by_name('Jane', data_content))
# ... ValueError: Name not found
</code>```

If you have to do many such searches, it may be worth creating another dict from your data to associate IDs to names:

```<code>ids_by_name = {d['People']:d['ID'] for d in data_content}
print(ids_by_name['John'])

# OI85
</code>```

Body:
A part of json file's content as below:

{"ID": "PK45", "People": "Kate", "Date": "2020-01-05"}, {"ID": "OI85", "People": "John", "Date": "2020-01-18" }, {"ID": "CN658", "People": "Pevo", "Date": "2020-02-01" }

It has multiple portions containing "ID", "People" and "Date".

What I want to do is to retrieve John's ID (in this case "OI85". )

If the key is unique, I can use:

data_content = json.loads(data)
ID = data_content['ID']

But there are multiple similar portions. So I can only locate the "John" first:

with open("C:\\the_file.json") as data_file:
    data = data_file.read()
    where = data.find('John')
    where_1 = data[where - 20 : where]
    ID = where_1[where_1.find('ID')+3:where_1.find('ID')+7]
    print (ID)

It looked clumsy.

What will be the smart json way to retrieve the specific data from multiple similar portions in a .json file?

Thank you.

Body:
Iterate on the list of dicts until you find the right one:

import json

data = '[{"ID": "PK45", "People": "Kate", "Date": "2020-01-05"}, {"ID": "OI85", "People": "John", "Date": "2020-01-18" }, {"ID": "CN658", "People": "Pevo", "Date": "2020-02-01" }]'

data_content = json.loads(data)

def find_id_by_name(name, data):
    for d in data:
        if d['People'] == name:
            return d["ID"]
    else:
        raise ValueError('Name not found')

print(find_id_by_name('John', data_content))
# OI85

print(find_id_by_name('Jane', data_content))
# ... ValueError: Name not found

If you have to do many such searches, it may be worth creating another dict from your data to associate IDs to names:

ids_by_name = {d['People']:d['ID'] for d in data_content}
print(ids_by_name['John'])

# OI85


问:
How to obtain data from sub query that has self join?
my table:

```<code>friends(uid_1 int, uid_2 int)
</code>```

This is my query :

```<code>SELECT a.uid_1
     , a.uid_2 as a2
     , b.uid_1 as b1
     , b.uid_2
  from friend a
  join friend b
    on a.uid_1 = b.uid_2;
</code>```

I want to obtain a2 and b1 from query for other purposes

So this query now:

```<code>Select a2,b1
from (SELECT a.uid_1,a.uid_2 as a2,b.uid_1 as b1,b.uid_2
      from friend a join
           friend b
           on a.uid_1=b.uid_2
     )
</code>```

does not work. How do I obtain certain data from a range of displayed data?

答:
You were just missing alias </p>

```<code>Select a2,b1
from (SELECT a.uid_1,a.uid_2 as a2,b.uid_1 as b1,b.uid_2
  from friend a join
       friend b
       on a.uid_1=b.uid_2
 ) as temp -- here it is
</code>```

Body:
my table:

friends(uid_1 int, uid_2 int)

This is my query :

SELECT a.uid_1
     , a.uid_2 as a2
     , b.uid_1 as b1
     , b.uid_2
  from friend a
  join friend b
    on a.uid_1 = b.uid_2;

I want to obtain a2 and b1 from query for other purposes

So this query now:

Select a2,b1
from (SELECT a.uid_1,a.uid_2 as a2,b.uid_1 as b1,b.uid_2
      from friend a join
           friend b
           on a.uid_1=b.uid_2
     )

does not work. How do I obtain certain data from a range of displayed data?

Body:
You were just missing alias

Select a2,b1
from (SELECT a.uid_1,a.uid_2 as a2,b.uid_1 as b1,b.uid_2
  from friend a join
       friend b
       on a.uid_1=b.uid_2
 ) as temp -- here it is


问:
How to prevent access via URL to controller's method in Rails 3?
I would like add Javascript/jQuery code to my Rails 3 application that will get data from the server and update the page accordingly.

I thought to use jQuery's $.get() method:

```<code>$.get("/get_data_about_page?page=5", function(data) {
  alert("Returned data: [" + data + "]");
});
</code>```

However, I don't want users to access get_data_about_page via URL.

How could I disable such access ?

答:
Realistically you can't stop someone from scraping it if they're determined...

You could set a variable in the session when the main page is loaded and then protect the AJAX action so that it only responds if the session variable is set - this would prevent naive use of the URL but it's not foolproof.

Body:
I would like add Javascript/jQuery code to my Rails 3 application that will get data from the server and update the page accordingly.

I thought to use jQuery's $.get() method:

$.get("/get_data_about_page?page=5", function(data) {
  alert("Returned data: [" + data + "]");
});

However, I don't want users to access get_data_about_page via URL.

How could I disable such access ?


问:
Wagtail: menu item opens in new window but appends main domain to external url?
I'm creating a menu using snipets.

The menu items have the option to have a internal page as destination, or an external page (e.g. google.com).

The internal option works great, but the external option opens in a new tag, with the hostname attached to the external link:

```<code>http://127.0.0.1:8000/google.com
</code>```

Not sure if something is wrong with my Orderable model or what's going on.

Code:

```<code>class MenuItem(Orderable):

    link_title = models.CharField(
        blank=True,
        null=True,
        max_length=50
    )
    link_url = models.CharField(
        max_length=500,
        blank=True,
    )
    link_page = models.ForeignKey(
        "wagtailcore.Page", #app y modelo de tu proyecto
        blank=True,
        null=True,
        related_name="+",
        on_delete=models.CASCADE,
    )
    open_in_new_tab = models.BooleanField(default=False, blank=True,)

    page = ParentalKey("Menu", related_name="menu_items")

    panels = [
        FieldPanel("link_title"),
        FieldPanel("link_url"),
        PageChooserPanel("link_page"),
        FieldPanel("open_in_new_tab"),
    ]

    # @tood add properties
    # link
    @property
    def link(self):
        if self.link_page:
            return self.link_page.url
        elif self.link_url:
            return self.link_url
        return "#"

    @property
    def title(self):
        if self.link_page and not self.link_title:
            return self.link_page.title
        elif self.link_title:
            return self.link_title
        return 'Missing title'

@register_snippet
class Menu(ClusterableModel):

    title = models.CharField(max_length=100)
    slug = AutoSlugField(populate_from="title", editable=True)

    panels = [
        MultiFieldPanel([
            FieldPanel("title"),
            FieldPanel("slug")
        ], heading="Menu"),
        InlinePanel("menu_items", label="Menu item")
    ]

    def __str__(self):
        return self.title
</code>```

html:

```<code><div class="collapse navbar-collapse" id="navbarCollapse">
        <ul>
            <li>
                <a href="/">Home</a>
            </li>
            {% for item in navigation.menu_items.all %}
                <li>
                    <a href="{{ item.link }}" class="nav-link" {% if item.open_in_new_tab %} target="_blank" {% endif %}>{{ item.title }}</a>
                </li>
            {% endfor %}
        </ul>
        <form class="form-inline ml-auto">
            <a href="" class="btn btn-outline-secondary">Ingresar</a>
            <a href="" class="btn btn-primary ml-2">Registro</a>
        </form>
    </div>
</code>```

Found this other question, but it differs from my approache:

Making external links open in a new window in wagtail

Screenshoot:

答:
Your code looks perfectly fine to me. It's just that you've entered your URL incorrectly. You'll need to add the http(s):// part so that the link will actually point to https://google.com instead of http://127.0.0.1:8000/google.com.

Also, I recommend to change link_url from a CharField to a URLField, for example:

```<code>class MenuItem(Orderable):

    # ...

    link_url = models.URLField(
        max_length=500,
        blank=True,
    )
</code>```

The reason is because, although the two fields are identical, URLField has built-in logic (i.e. a validator) that checks for a correct URL pattern. So when you enter an invalid URL in the admin like google.com without https://, your menu won't save. Remember to run manage.py makemigrations and manage.py migrate once you have the field replaced.

Body:
I'm creating a menu using snipets.

The menu items have the option to have a internal page as destination, or an external page (e.g. google.com).

The internal option works great, but the external option opens in a new tag, with the hostname attached to the external link:

http://127.0.0.1:8000/google.com

Not sure if something is wrong with my Orderable model or what's going on.

Code:

class MenuItem(Orderable):

    link_title = models.CharField(
        blank=True,
        null=True,
        max_length=50
    )
    link_url = models.CharField(
        max_length=500,
        blank=True,
    )
    link_page = models.ForeignKey(
        "wagtailcore.Page", #app y modelo de tu proyecto
        blank=True,
        null=True,
        related_name="+",
        on_delete=models.CASCADE,
    )
    open_in_new_tab = models.BooleanField(default=False, blank=True,)

    page = ParentalKey("Menu", related_name="menu_items")

    panels = [
        FieldPanel("link_title"),
        FieldPanel("link_url"),
        PageChooserPanel("link_page"),
        FieldPanel("open_in_new_tab"),
    ]

    # @tood add properties
    # link
    @property
    def link(self):
        if self.link_page:
            return self.link_page.url
        elif self.link_url:
            return self.link_url
        return "#"

    @property
    def title(self):
        if self.link_page and not self.link_title:
            return self.link_page.title
        elif self.link_title:
            return self.link_title
        return 'Missing title'

@register_snippet
class Menu(ClusterableModel):

    title = models.CharField(max_length=100)
    slug = AutoSlugField(populate_from="title", editable=True)

    panels = [
        MultiFieldPanel([
            FieldPanel("title"),
            FieldPanel("slug")
        ], heading="Menu"),
        InlinePanel("menu_items", label="Menu item")
    ]

    def __str__(self):
        return self.title

html:

                Home

            {% for item in navigation.menu_items.all %}

                    {{ item.title }}

            {% endfor %}

        <form class="form-inline ml-auto">
            Ingresar
            Registro
        </form>

Found this other question, but it differs from my approache:

Making external links open in a new window in wagtail

Screenshoot:

Body:
Your code looks perfectly fine to me. It's just that you've entered your URL incorrectly. You'll need to add the http(s):// part so that the link will actually point to https://google.com instead of http://127.0.0.1:8000/google.com.

Also, I recommend to change link_url from a CharField to a URLField, for example:

class MenuItem(Orderable):

    # ...

    link_url = models.URLField(
        max_length=500,
        blank=True,
    )

The reason is because, although the two fields are identical, URLField has built-in logic (i.e. a validator) that checks for a correct URL pattern. So when you enter an invalid URL in the admin like google.com without https://, your menu won't save. Remember to run manage.py makemigrations and manage.py migrate once you have the field replaced.


问:
ORACLE SQL PROCEDURE WITH FOR LOOP AND IF ELSE ERROR
I need to replace employee id in shift table for a particular day with another employee id who hasn't any shift for a particular day.
This my tables,

```<code>CREATE TABLE EMPLOYEE
        (EMPLOYEE_ID NUMBER(4) NOT NULL,
        NAME VARCHAR(50),
        GENDER VARCHAR(10),
        BIRTH_DAY DATE,
        PRIMARY KEY(EMPLOYEE_ID)
        );
CREATE TABLE SHIFT
        (SHIFT_ID NUMBER(4),
        SHIFT_DATE DATE,
        CUSTOMER_ID NUMBER(4),
        SERVICE_ID NUMBER(4),
        EMPLOYEE_ID  NUMBER(4),
        SHIFT_CHARGE FLOAT(10),
        PRIMARY KEY(SHIFT_ID),
        FOREIGN KEY (EMPLOYEE_ID) REFERENCES EMPLOYEE(EMPLOYEE_ID)
        );
</code>```

For the above purpose, I want to create a  procedure. I created the procedure is below. But there is a compilation error.

```<code>CREATE OR REPLACE PROCEDURE CHANGE_SHIFT_SHEDULED
 (
    EMPLOYEE_ID IN SHIFT.EMPLOYEE_ID%TYPE,
    SHIFT_DATE IN SHIFT.SHIFT_DATE%TYPE
 )
 AS
    CHECK_CON BOOLEAN:=TRUE;
 BEGIN
    FOR SICK_EMP_SHIFT_REC IN (SELECT * FROM SHIFT WHERE SHIFT.EMPLOYEE_ID=EMPLOYEE_ID AND SHIFT.SHIFT_DATE=SHIFT_DATE)
    LOOP
        FOR EMP_REC IN (
                SELECT e.EMPLOYEE_ID,COUNT(e.EMPLOYEE_ID)AS SHIFT_COUNT,
                CASE
                    WHEN SHIFT_COUNT>0 THEN FALSE
                    ELSE TRUE
                END AS SHIFT_COUNT
                FROM EMPLOYEE e LEFT OUTER JOIN SHIFT s ON e.EMPLOYEE_ID=s.EMPLOYEE_ID
                WHERE s.SHIFT_DATE=SHIFT_DATE
                GROUP BY e.EMPLOYEE_ID)
        LOOP
            CHECK_CON:=EMP_REC.SHIFT_COUNT;
            IF CHECK_CON THEN
                UPDATE SHIFT s SET s.EMPLOYEE_ID=EMP_REC.EMPLOYEE_ID WHERE s.SHIFT_ID=SICK_EMP_SHIFT_REC.SHIFT_ID;
                EXIT;
            END IF;
        END LOOP;
    END LOOP;
 END;
 /
</code>```

Please anyone help me to solve this issue.

答:
I'm not looking at logic you applied; I hope you did it right. I just fixed errors which prevented code you wrote to compile; for example:

don't name parameters as column names; use some prefix, e.g. par_ or p_

in cursor FOR loop, you can't have two columns with same name (shift_count); one has to be changed

also, you can't use an alias in the same statement's CASE (which is what you did with shift_count)

Boolean support is somewhat strange in Oracle. For example, there's no such datatype at SQL level. Therefore, you'll have to work with strings or numbers, and then "convert" them to Boolean (e.g. line #26)

The rest is OK, I suppose.

```<code>SQL> CREATE OR REPLACE PROCEDURE change_shift_sheduled (
  2     par_employee_id  IN shift.employee_id%TYPE,
  3     par_shift_date   IN shift.shift_date%TYPE)
  4  AS
  5     check_con  BOOLEAN := TRUE;
  6  BEGIN
  7     FOR sick_emp_shift_rec IN (SELECT *
  8                                  FROM shift
  9                                 WHERE     shift.employee_id = par_employee_id
 10                                       AND shift.shift_date = par_shift_date)
 11     LOOP
 12        FOR emp_rec
 13           IN (  SELECT e.employee_id,
 14                        COUNT (e.employee_id) AS shift_count,
 15                        CASE
 16                           WHEN COUNT (e.employee_id) > 0 THEN 'FALSE'
 17                           ELSE 'TRUE'
 18                        END
 19                           AS shift_count_case
 20                   FROM employee e
 21                        LEFT OUTER JOIN shift s ON e.employee_id = s.employee_id
 22                  WHERE s.shift_date = par_shift_date
 23               GROUP BY e.employee_id)
 24        LOOP
 25           check_con :=
 26              CASE
 27                 WHEN emp_rec.shift_count_case = 'FALSE' THEN FALSE
 28                 ELSE TRUE
 29              END;
 30
 31           IF check_con
 32           THEN
 33              UPDATE shift s
 34                 SET s.employee_id = emp_rec.employee_id
 35               WHERE s.shift_id = sick_emp_shift_rec.shift_id;
 36
 37              EXIT;
 38           END IF;
 39        END LOOP;
 40     END LOOP;
 41  END;
 42  /

Procedure created.

SQL>
</code>```

Body:
I need to replace employee id in shift table for a particular day with another employee id who hasn't any shift for a particular day.
This my tables,

CREATE TABLE EMPLOYEE
        (EMPLOYEE_ID NUMBER(4) NOT NULL,
        NAME VARCHAR(50),
        GENDER VARCHAR(10),
        BIRTH_DAY DATE,
        PRIMARY KEY(EMPLOYEE_ID)
        );
CREATE TABLE SHIFT
        (SHIFT_ID NUMBER(4),
        SHIFT_DATE DATE,
        CUSTOMER_ID NUMBER(4),
        SERVICE_ID NUMBER(4),
        EMPLOYEE_ID  NUMBER(4),
        SHIFT_CHARGE FLOAT(10),
        PRIMARY KEY(SHIFT_ID),
        FOREIGN KEY (EMPLOYEE_ID) REFERENCES EMPLOYEE(EMPLOYEE_ID)
        );

For the above purpose, I want to create a  procedure. I created the procedure is below. But there is a compilation error.

CREATE OR REPLACE PROCEDURE CHANGE_SHIFT_SHEDULED
 (
    EMPLOYEE_ID IN SHIFT.EMPLOYEE_ID%TYPE,
    SHIFT_DATE IN SHIFT.SHIFT_DATE%TYPE
 )
 AS
    CHECK_CON BOOLEAN:=TRUE;
 BEGIN
    FOR SICK_EMP_SHIFT_REC IN (SELECT * FROM SHIFT WHERE SHIFT.EMPLOYEE_ID=EMPLOYEE_ID AND SHIFT.SHIFT_DATE=SHIFT_DATE)
    LOOP
        FOR EMP_REC IN (
                SELECT e.EMPLOYEE_ID,COUNT(e.EMPLOYEE_ID)AS SHIFT_COUNT,
                CASE
                    WHEN SHIFT_COUNT>0 THEN FALSE
                    ELSE TRUE
                END AS SHIFT_COUNT
                FROM EMPLOYEE e LEFT OUTER JOIN SHIFT s ON e.EMPLOYEE_ID=s.EMPLOYEE_ID
                WHERE s.SHIFT_DATE=SHIFT_DATE
                GROUP BY e.EMPLOYEE_ID)
        LOOP
            CHECK_CON:=EMP_REC.SHIFT_COUNT;
            IF CHECK_CON THEN
                UPDATE SHIFT s SET s.EMPLOYEE_ID=EMP_REC.EMPLOYEE_ID WHERE s.SHIFT_ID=SICK_EMP_SHIFT_REC.SHIFT_ID;
                EXIT;
            END IF;
        END LOOP;
    END LOOP;
 END;
 /

Please anyone help me to solve this issue.

Body:
I'm not looking at logic you applied; I hope you did it right. I just fixed errors which prevented code you wrote to compile; for example:

don't name parameters as column names; use some prefix, e.g. par_ or p_

in cursor FOR loop, you can't have two columns with same name (shift_count); one has to be changed

also, you can't use an alias in the same statement's CASE (which is what you did with shift_count)

Boolean support is somewhat strange in Oracle. For example, there's no such datatype at SQL level. Therefore, you'll have to work with strings or numbers, and then "convert" them to Boolean (e.g. line #26)

The rest is OK, I suppose.

SQL> CREATE OR REPLACE PROCEDURE change_shift_sheduled (
  2     par_employee_id  IN shift.employee_id%TYPE,
  3     par_shift_date   IN shift.shift_date%TYPE)
  4  AS
  5     check_con  BOOLEAN := TRUE;
  6  BEGIN
  7     FOR sick_emp_shift_rec IN (SELECT *
  8                                  FROM shift
  9                                 WHERE     shift.employee_id = par_employee_id
 10                                       AND shift.shift_date = par_shift_date)
 11     LOOP
 12        FOR emp_rec
 13           IN (  SELECT e.employee_id,
 14                        COUNT (e.employee_id) AS shift_count,
 15                        CASE
 16                           WHEN COUNT (e.employee_id) > 0 THEN 'FALSE'
 17                           ELSE 'TRUE'
 18                        END
 19                           AS shift_count_case
 20                   FROM employee e
 21                        LEFT OUTER JOIN shift s ON e.employee_id = s.employee_id
 22                  WHERE s.shift_date = par_shift_date
 23               GROUP BY e.employee_id)
 24        LOOP
 25           check_con :=
 26              CASE
 27                 WHEN emp_rec.shift_count_case = 'FALSE' THEN FALSE
 28                 ELSE TRUE
 29              END;
 30
 31           IF check_con
 32           THEN
 33              UPDATE shift s
 34                 SET s.employee_id = emp_rec.employee_id
 35               WHERE s.shift_id = sick_emp_shift_rec.shift_id;
 36
 37              EXIT;
 38           END IF;
 39        END LOOP;
 40     END LOOP;
 41  END;
 42  /

Procedure created.

SQL>


问:
Download .xls file using Spring boot y Apache POI does not work
I would like to implement a method that downloads an .xls file with the records of a table from a database. I am working without any template to focus on the backend, the problem is that when I run the application and the corresponding method, the download does not start and the records "appears" on the screen

ClienteService:

```<code>@Override
    public ByteArrayInputStream exportData() throws Exception {
        String[] columnas = {"Número Cliente", "Nombre", "Apellido", "Dirección", "Activo"};

        Workbook workbook = new HSSFWorkbook();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        Sheet sheet = workbook.createSheet("Clientes");
        Row row = sheet.createRow(0);

        for(int i=0; i<columnas.length; i++){
            Cell cell = row.createCell(i);
            cell.setCellValue(columnas[i]);
        }

        List<E01_cliente> clientes = (List<E01_cliente>) clienteRepository.findAll();
        int initRow = 1;
        for(E01_cliente c : clientes){
            row = sheet.createRow(initRow);
            row.createCell(0).setCellValue(c.getNro_cliente());
            row.createCell(1).setCellValue(c.getNombre());
            row.createCell(2).setCellValue(c.getApellido());
            row.createCell(3).setCellValue(c.getDireccion());
            row.createCell(4).setCellValue(c.isActivo());
            initRow++;
        }

        workbook.write(stream);
        workbook.close();
        return new ByteArrayInputStream(stream.toByteArray());
    }
</code>```

Method of Controller:

```<code>@GetMapping("/descargar")
public ResponseEntity<InputStreamResource> exportData() throws Exception {
    ByteArrayInputStream stream = clienteService.exportData();
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Dispotion", "attachment; filename=clientes.xls");
    return ResponseEntity.ok().headers(headers).body(new InputStreamResource(stream));
}
</code>```

Entity Cliente:

```<code>@Entity
public class E01_cliente {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int nro_cliente;
    private String nombre;
    private String apellido;
    private String direccion;
    private boolean activo;

    @OneToMany(mappedBy = "cliente")
    @JsonIgnore
    private List<E01_factura> facturas;
    //Getters and Setters ignored
</code>```

答:
Use Content-Disposition instead of Content-Dispotion as Header

```<code>headers.add("Content-Disposition", "attachment; filename=clientes.xls");
</code>```

Body:
I would like to implement a method that downloads an .xls file with the records of a table from a database. I am working without any template to focus on the backend, the problem is that when I run the application and the corresponding method, the download does not start and the records "appears" on the screen

ClienteService:

@Override
    public ByteArrayInputStream exportData() throws Exception {
        String[] columnas = {"Número Cliente", "Nombre", "Apellido", "Dirección", "Activo"};

        Workbook workbook = new HSSFWorkbook();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        Sheet sheet = workbook.createSheet("Clientes");
        Row row = sheet.createRow(0);

        for(int i=0; i<columnas.length; i++){
            Cell cell = row.createCell(i);
            cell.setCellValue(columnas[i]);
        }

        List<E01_cliente> clientes = (List<E01_cliente>) clienteRepository.findAll();
        int initRow = 1;
        for(E01_cliente c : clientes){
            row = sheet.createRow(initRow);
            row.createCell(0).setCellValue(c.getNro_cliente());
            row.createCell(1).setCellValue(c.getNombre());
            row.createCell(2).setCellValue(c.getApellido());
            row.createCell(3).setCellValue(c.getDireccion());
            row.createCell(4).setCellValue(c.isActivo());
            initRow++;
        }

        workbook.write(stream);
        workbook.close();
        return new ByteArrayInputStream(stream.toByteArray());
    }

Method of Controller:

@GetMapping("/descargar")
public ResponseEntity<InputStreamResource> exportData() throws Exception {
    ByteArrayInputStream stream = clienteService.exportData();
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Dispotion", "attachment; filename=clientes.xls");
    return ResponseEntity.ok().headers(headers).body(new InputStreamResource(stream));
}

Entity Cliente:

@Entity
public class E01_cliente {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int nro_cliente;
    private String nombre;
    private String apellido;
    private String direccion;
    private boolean activo;

    @OneToMany(mappedBy = "cliente")
    @JsonIgnore
    private List<E01_factura> facturas;
    //Getters and Setters ignored

Body:
Use Content-Disposition instead of Content-Dispotion as Header

headers.add("Content-Disposition", "attachment; filename=clientes.xls");


问:
using time as a parameter in a conditional statement
I have an int(value) in a dictionary that continuously gets assigned a new value within a while loop.
I am trying to set a condition whereby if, '(value) < 0' for x amount of seconds, how would you go about creating this piece of code?

so, I was thinking something along the lines of:

```<code>from datetime import time

dict = {"special number": -0.5}

condition = 5

while true:

    if dict["special number"] < 0 'for more than' condition('%S'):

        del(dict)
</code>```

Apologises in advance, I know this if statement is far from correct, it was just for example purposes.

kindest regards

答:
Not sure if I am getting this right. May be this helps:</p>

```<code>import time

dict = {"special number": -0.5}
start_time = time.time()

while True:
    if dict["special number"] < 0:
        print("number been less that 0 for {} seconds".format(time.time() - start_time))
    else:
        start_time = time.time()
</code>```

Body:
I have an int(value) in a dictionary that continuously gets assigned a new value within a while loop.
I am trying to set a condition whereby if, '(value) < 0' for x amount of seconds, how would you go about creating this piece of code?

so, I was thinking something along the lines of:

from datetime import time

dict = {"special number": -0.5}

condition = 5

while true:

    if dict["special number"] < 0 'for more than' condition('%S'):

        del(dict)

Apologises in advance, I know this if statement is far from correct, it was just for example purposes.

kindest regards

Body:
Not sure if I am getting this right. May be this helps:

import time

dict = {"special number": -0.5}
start_time = time.time()

while True:
    if dict["special number"] < 0:
        print("number been less that 0 for {} seconds".format(time.time() - start_time))
    else:
        start_time = time.time()


问:
Use SCSS style files within AngularDart 5 and Dart 2
I’m working with Dart 2 and AngularDart 5.

⚠ I searched online about my question, but I didn’t find a satisfactory answer.

❔ Can somebody explain all the steps I need to include and to work with SCSS style files within my AngularDart application?

I started with quickstart application that you can find here.

Thank you!

答:
With newest versions:

Surprise: In styleUrls are in a different CSS filename (not with the .scss.css extension, just .css; e.g. app_component.css, but the styles are in app_component.scss).

Surprise: In app_component.scss, import without lib in the path:

```<code>@import 'package:angular_components/app_layout/mixins';
</code>```

I am using this command:

pub run build_runner serve --verbose
```

See with package info:
https://github.com/dart-lang/angular_components/issues/374#issuecomment-636344237

Body:
With newest versions:

Surprise: In styleUrls are in a different CSS filename (not with the .scss.css extension, just .css; e.g. app_component.css, but the styles are in app_component.scss).

Surprise: In app_component.scss, import without lib in the path:

@import 'package:angular_components/app_layout/mixins';

I am using this command:

pub run build_runner serve --verbose

See with package info:
https://github.com/dart-lang/angular_components/issues/374#issuecomment-636344237


问:
How to clear stack back to root activity when user leaves application?
I have an application with 2 activities, LogonAct and MainAct. LogonAct is a logon activity which I want to force the user to go through each time they return to the application. I've set android:clearTaskOnLaunch="true" on LogonAct.

When I first start the app I go through this sequence of screens,

Home -> LogonAct -> MainAct -> Home

I then follow this sequence,

LogonAct -> Back -> MainAct

Why is it bringing me back to MainAct? Shouldn't that activity haven been closed since LogonAct has android:clearTaskOnLaunch="true". I expected to be brought back to Home when I hit the Back button from LogonAct.

Relevant snippets from AndroidManifest.xml,

```<code>   <activity android:name=".LogonAct"
             android:clearTaskOnLaunch="true">
       <intent-filter>
           <action android:name="android.intent.action.MAIN"/>
           <category android:name="android.intent.category.LAUNCHER"/>
       </intent-filter>
   </activity>

   <activity android:name=".MainAct">
       <meta-data android:name="android.app.default_searchable"
                  android:value=".SearchResults" />
   </activity>
</code>```

I'm using 1.5.

Any help appreciated.

答:
You can do following:

1. set clearTaskOnLaunch = "true" in AndroidManifest, in declaration of main activity

2. in activity that must close:

```<code>@Override
public void onBackPressed(){
    moveTaskToBack(true);
}
</code>```

so if user presses back - it comes back to homescreen
if user launches aplication again - task stack clears and he comes to root main activity

ContentLicense: CC BY-SA 2.5

Body:
I have an application with 2 activities, LogonAct and MainAct. LogonAct is a logon activity which I want to force the user to go through each time they return to the application. I've set android:clearTaskOnLaunch="true" on LogonAct.

When I first start the app I go through this sequence of screens,

Home -> LogonAct -> MainAct -> Home

I then follow this sequence,

LogonAct -> Back -> MainAct

Why is it bringing me back to MainAct? Shouldn't that activity haven been closed since LogonAct has android:clearTaskOnLaunch="true". I expected to be brought back to Home when I hit the Back button from LogonAct.

Relevant snippets from AndroidManifest.xml,

   <activity android:name=".LogonAct"
             android:clearTaskOnLaunch="true">
       <intent-filter>
           <action android:name="android.intent.action.MAIN"/>
           <category android:name="android.intent.category.LAUNCHER"/>
       </intent-filter>
   </activity>

   <activity android:name=".MainAct">
       <meta-data android:name="android.app.default_searchable"
                  android:value=".SearchResults" />
   </activity>

I'm using 1.5.

Any help appreciated.

Body:
You can do following:

1. set clearTaskOnLaunch = "true" in AndroidManifest, in declaration of main activity

2. in activity that must close:

@Override
public void onBackPressed(){
    moveTaskToBack(true);
}

so if user presses back - it comes back to homescreen
if user launches aplication again - task stack clears and he comes to root main activity


问:
Generate number repeating python
Code:

```<code>import random
number1=random.randint(0,62)
print(number1)
</code>```

I tried and the numbers repeated each other.

One condition: The numbers will be different.

答:
This should do the trick. The sample method can be used to generate set of unique numbers using random module :)

```<code>import random
number1 = random.sample(range(1, 62), 61)
print(number1)
</code>```

Title: Generate number repeating python

Body:
Code:

import random
number1=random.randint(0,62)
print(number1)

I tried and the numbers repeated each other.

One condition: The numbers will be different.

Body:
This should do the trick. The sample method can be used to generate set of unique numbers using random module :)

import random
number1 = random.sample(range(1, 62), 61)
print(number1)


问:
How do i make something random in a function?
I have a function with some images in it here:

```<code>function rain() {
    ctx.drawImage (image1, x, y, 100, 50);
    ctx.drawImage (image2, x, y, 100, 50);
    ctx.drawImage (image3, x, y, 100, 50);
    ctx.drawImage (image4, x, y, 100, 50);
}
</code>```

How do I make this function randomly choose one of these images when I call it?

答:
I think it's inconvenient to do math when I want to deal with randomness, so I use Rando.js to make stuff like this simple and readable.

var images = ["one", "two", "three", "four"];

console.log( rando(images).value );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://randojs.com/1.0.0.js"></script></code>```

If you want to use this code, all you need to know is that the script tag sources in the rando function, and you're ready to use it right away. Just put the script tag in the head of your HTML document. It's easy, but if you need to know more, you can check out examples on the website or github repo.

Body:
I have a function with some images in it here:

function rain() {
    ctx.drawImage (image1, x, y, 100, 50);
    ctx.drawImage (image2, x, y, 100, 50);
    ctx.drawImage (image3, x, y, 100, 50);
    ctx.drawImage (image4, x, y, 100, 50);
}

How do I make this function randomly choose one of these images when I call it?

Body:
I think it's inconvenient to do math when I want to deal with randomness, so I use Rando.js to make stuff like this simple and readable.

var images = ["one", "two", "three", "four"];

console.log( rando(images).value );

<script src="https://randojs.com/1.0.0.js"></script>

If you want to use this code, all you need to know is that the script tag sources in the rando function, and you're ready to use it right away. Just put the script tag in the head of your HTML document. It's easy, but if you need to know more, you can check out examples on the website or github repo.


问:
Carrying out a c++ 2d array
My array is supposed to accept 3 values for 3 salespersons, store and print the array but somehow I can't get it going. I'm not too familiar with c++ 2d arrays so this is a tad bit new to me. The code is supposed to accept user input, and then output the prices of the products into table like format.</p>

答:
I went over the code and this is the final product... Turns out no input was needed I was overthinking. Thanks for the help @tadman For anyone who is interested:</p>

```<code>#include <iostream>
#include <iomanip>
#include <string>
#include <stdio.h>
#include <math.h>
#define ROW 3 //number of rows
#define COL 3 // number of columns

//Function Prototype section
    void enterItems(double salesArray[][COL]);
    void getRowTotal (double Sales[][3], double total[][3]);
    void getColTotal (double Sales[][3], double total[][3]);
    void DisplayArray (double Sales[][3], double total[][3]);

using namespace std;

int main (){ //function main begins program execution

    //storing 3 sales person and 3 different product

//Declares Arrays

 double Sales[ROW][COL] = { {250,200,300 }, {500,350,220 },{150,600,450 }};
 double total[2][3] = {0};

//Calls Functions getRowTotal, getColTotal and DisplayArray
getRowTotal (Sales, total);
getColTotal(Sales, total);
DisplayArray (Sales, total);

//Signifies that program is successfully executed
return 0;

}

//variables
int z = 0, j = 0;

//Declares And Defines getRowTotal
void getRowTotal (double Sales[][3], double total[][3]){
for(z = 0; z < 3; z++)
total[0][z] = Sales[0][z] + Sales[1][z] + Sales[2][z];
}

//Declares and Defines getColTotal
void getColTotal(double Sales[][3], double total[][3]){

for(z = 0; z < 3; z++){
total[1][z] = Sales[z][0] + Sales[z][1] + Sales[z][2];
}
}

//function DisplayArry
void DisplayArray (double Sales[][3], double total[][3]){
//Table Headings
cout << left << setw(10) << "Title" << setw(15) << "SalesPerson1    " << setw(15) << "SalesPerson2      " << setw(15) << "SalesPerson3      " << "Total";
cout << "\n_______________________________________________________________________________________________\n";

cout << fixed << setprecision(2) << showpoint;

//Displays the Sales and row headings
for(z = 0; z < 3; z++){
cout << setw(8) << "Product  " << z + 1 << setw(1) << " ";

for(j = 0; j < 3; j++)
cout << setw(17) << Sales[j][z];

cout << setw(17) << total[0][z];

cout << endl;
}

cout << setw(8) << "Total";

for( z = 0; z < 3; z++)
cout << setw(19) << total[1][z];

cout << "\n_______________________________________________________________________________________________\n";
}
</code>```

Title: Carrying out a c++ 2d array

Body:
I went over the code and this is the final product... Turns out no input was needed I was overthinking. Thanks for the help @tadman For anyone who is interested:

#include <iostream>
#include <iomanip>
#include <string>
#include <stdio.h>
#include <math.h>
#define ROW 3 //number of rows
#define COL 3 // number of columns

//Function Prototype section
    void enterItems(double salesArray[][COL]);
    void getRowTotal (double Sales[][3], double total[][3]);
    void getColTotal (double Sales[][3], double total[][3]);
    void DisplayArray (double Sales[][3], double total[][3]);

using namespace std;

int main (){ //function main begins program execution

    //storing 3 sales person and 3 different product

//Declares Arrays

 double Sales[ROW][COL] = { {250,200,300 }, {500,350,220 },{150,600,450 }};
 double total[2][3] = {0};

//Calls Functions getRowTotal, getColTotal and DisplayArray
getRowTotal (Sales, total);
getColTotal(Sales, total);
DisplayArray (Sales, total);

//Signifies that program is successfully executed
return 0;

}

//variables
int z = 0, j = 0;

//Declares And Defines getRowTotal
void getRowTotal (double Sales[][3], double total[][3]){
for(z = 0; z < 3; z++)
total[0][z] = Sales[0][z] + Sales[1][z] + Sales[2][z];
}

//Declares and Defines getColTotal
void getColTotal(double Sales[][3], double total[][3]){

for(z = 0; z < 3; z++){
total[1][z] = Sales[z][0] + Sales[z][1] + Sales[z][2];
}
}

//function DisplayArry
void DisplayArray (double Sales[][3], double total[][3]){
//Table Headings
cout << left << setw(10) << "Title" << setw(15) << "SalesPerson1    " << setw(15) << "SalesPerson2      " << setw(15) << "SalesPerson3      " << "Total";
cout << "\n_______________________________________________________________________________________________\n";

cout << fixed << setprecision(2) << showpoint;

//Displays the Sales and row headings
for(z = 0; z < 3; z++){
cout << setw(8) << "Product  " << z + 1 << setw(1) << " ";

for(j = 0; j < 3; j++)
cout << setw(17) << Sales[j][z];

cout << setw(17) << total[0][z];

cout << endl;
}

cout << setw(8) << "Total";

for( z = 0; z < 3; z++)
cout << setw(19) << total[1][z];

cout << "\n_______________________________________________________________________________________________\n";
}


问:
Pandas to create columns based on starting Character
I have below data parsed Data from the Linux Machine into a text file.

What i Want..

Any line Startswith cn: should be comes under column Group_Name by constituting it.

Below cn: there are lines starting nisNetgroupTriple:, value after this is hostname should comes under Column Host_Name.

Where there is only Group_Name just need to be None in the Host_Name column

I am able to do that in Shell way but looking it in Pandas way..

Sample Data.

Below is just sample data but the actual data is Much bigger..

```<code>cn: Infra_SAT_IMEC_TR-KPQ01
nisNetgroupTriple: kht1562.khatigusain.com.com
nisNetgroupTriple: kht1187.khatigusain.com.com

cn: Infra_RDC_IMEC_US-KDC02_SWDC02_SW

cn: Infra_RDC_APAC_CN-KHA02_SWHA02_SW

cn: Infra_SAT_EMEA_AT-GRK02_RS_SW

cn: Infra_SAT_APAC_CN-KPH04
nisNetgroupTriple: kht1402.khatigusain.com.com
nisNetgroupTriple: kht1964.khatigusain.com.com
</code>```

DataFrame:

```<code>                      cn: Infra_SAT_IMEC_TR-KPQ01
0  nisNetgroupTriple: kht1562.khatigusain.com.com
1  nisNetgroupTriple: kht1187.khatigusain.com.com
2           cn: Infra_RDC_IMEC_US-KDC02_SWDC02_SW
3           cn: Infra_RDC_APAC_CN-KHA02_SWHA02_SW
4               cn: Infra_SAT_EMEA_AT-GRK02_RS_SW
5                     cn: Infra_SAT_APAC_CN-KPH04
6  nisNetgroupTriple: kht1402.khatigusain.com.com
7  nisNetgroupTriple: kht1964.khatigusain.com.com
Index(['cn: Infra_SAT_IMEC_TR-KPQ01'], dtype='object')
</code>```

Desired Data:

```<code>Group_Name                              Host_Name
Infra_SAT_IMEC_TR-KPQ01                 kht1562.khatigusain.com.com
Infra_SAT_IMEC_TR-KPQ01                 kht1187.khatigusain.com.com
Infra_RDC_IMEC_US-KDC02_SWDC02_SW       None
Infra_RDC_APAC_CN-KHA02_SWHA02_SW       None
Infra_SAT_EMEA_AT-GRK02_RS_SW           None
Infra_SAT_APAC_CN-KPH04                 kht1402.khatigusain.com.com
Infra_SAT_APAC_CN-KPH04                 kht1964.khatigusain.com.com
</code>```

I tried to lot googling around and tried to get some clue but didn't get anything, i'm still trying.

答:
Here is an alternative solution:

Assuming original data is stored in a dataframe called 'df' and a column name 'sample'

Extract the contents following the string contents 'cn' and 'nisNetgroupTriple' into separate columns:

```<code>df['Group_Name']=df['sample'].str.extract('cn:(.*)')
df['Host_Name']=df['sample'].str.extract('nisNetgroupTriple:(.*)')
</code>```

Then forward fill the 'Group_Name' column with contents

```<code>df['Group_Name']=df['Group_Name'].ffill()
</code>```

Then delete rows where the 'Group_Name' is 'non-unique' AND the value of the 'Host_Name' in the column next to it is 'nan':

First check for uniqueness:

```<code>df['Group_Name_unique']=df.groupby('Group_Name')['Group_Name'].transform('size')
</code>```

Then set the condition:

```<code>drop_rows=(df['Group_Name_unique']>1)&(df['Host_Name']).isnull()
</code>```

Obtain results and drop unnecessary columns:

```<code>result=df.loc[~drop_rows]
result=result.drop(['sample','Group_Name_unique'],axis=1)
</code>```

Body:
I have below data parsed Data from the Linux Machine into a text file.

What i Want..

Any line Startswith cn: should be comes under column Group_Name by constituting it.

Below cn: there are lines starting nisNetgroupTriple:, value after this is hostname should comes under Column Host_Name.

Where there is only Group_Name just need to be None in the Host_Name column

I am able to do that in Shell way but looking it in Pandas way..

Sample Data.

Below is just sample data but the actual data is Much bigger..

cn: Infra_SAT_IMEC_TR-KPQ01
nisNetgroupTriple: kht1562.khatigusain.com.com
nisNetgroupTriple: kht1187.khatigusain.com.com

cn: Infra_RDC_IMEC_US-KDC02_SWDC02_SW

cn: Infra_RDC_APAC_CN-KHA02_SWHA02_SW

cn: Infra_SAT_EMEA_AT-GRK02_RS_SW

cn: Infra_SAT_APAC_CN-KPH04
nisNetgroupTriple: kht1402.khatigusain.com.com
nisNetgroupTriple: kht1964.khatigusain.com.com

DataFrame:

                      cn: Infra_SAT_IMEC_TR-KPQ01
0  nisNetgroupTriple: kht1562.khatigusain.com.com
1  nisNetgroupTriple: kht1187.khatigusain.com.com
2           cn: Infra_RDC_IMEC_US-KDC02_SWDC02_SW
3           cn: Infra_RDC_APAC_CN-KHA02_SWHA02_SW
4               cn: Infra_SAT_EMEA_AT-GRK02_RS_SW
5                     cn: Infra_SAT_APAC_CN-KPH04
6  nisNetgroupTriple: kht1402.khatigusain.com.com
7  nisNetgroupTriple: kht1964.khatigusain.com.com
Index(['cn: Infra_SAT_IMEC_TR-KPQ01'], dtype='object')

Desired Data:

Group_Name                              Host_Name
Infra_SAT_IMEC_TR-KPQ01                 kht1562.khatigusain.com.com
Infra_SAT_IMEC_TR-KPQ01                 kht1187.khatigusain.com.com
Infra_RDC_IMEC_US-KDC02_SWDC02_SW       None
Infra_RDC_APAC_CN-KHA02_SWHA02_SW       None
Infra_SAT_EMEA_AT-GRK02_RS_SW           None
Infra_SAT_APAC_CN-KPH04                 kht1402.khatigusain.com.com
Infra_SAT_APAC_CN-KPH04                 kht1964.khatigusain.com.com

I tried to lot googling around and tried to get some clue but didn't get anything, i'm still trying.

Body:
Here is an alternative solution:

Assuming original data is stored in a dataframe called 'df' and a column name 'sample'

Extract the contents following the string contents 'cn' and 'nisNetgroupTriple' into separate columns:

df['Group_Name']=df['sample'].str.extract('cn:(.*)')
df['Host_Name']=df['sample'].str.extract('nisNetgroupTriple:(.*)')

Then forward fill the 'Group_Name' column with contents

df['Group_Name']=df['Group_Name'].ffill()

Then delete rows where the 'Group_Name' is 'non-unique' AND the value of the 'Host_Name' in the column next to it is 'nan':

First check for uniqueness:

df['Group_Name_unique']=df.groupby('Group_Name')['Group_Name'].transform('size')

Then set the condition:

drop_rows=(df['Group_Name_unique']>1)&(df['Host_Name']).isnull()

Obtain results and drop unnecessary columns:

result=df.loc[~drop_rows]
result=result.drop(['sample','Group_Name_unique'],axis=1)