text:
Q: Text flows out of input after next event is fired if input is focued While building a basic application, when I click a button, the text inside my currently focused input overflows only in Chrome. However, that text can be accessed using (right) arrow key(s). Is there any way to avoid this? I tried clipboard copy-paste but that did not work.

const peopleElem = document.querySelector("#people");
const billElem = document.querySelector("#bill");
const submit = document.querySelector("[type=\"submit\"]");
const form = document.querySelector("form");
const tipPerPersonElem = document.querySelector("[data-tip-person]");
const totalPerPersonElem = document.querySelector("[data-total-person]");
let billError = peopleError = false;

class TipCalc {
  constructor() {
    this.tipPerPerson = 0;
    this.totalPerPerson = 0;
    this.tip = 0
    this.tipPercent = 0;
    this.bill = parseFloat(billElem.value);
    this.people = parseFloat(peopleElem.value);
  }

  getTip() {
    const element = document.querySelector(".active");
    if (!element) return 0;
    if (element.tagName === "BUTTON") return this.tipPercent = element.innerText.replace("%", "");
    return this.tipPercent = element.value.replace("%", "");
  }

  getTipPerPerson() {
    this.getTip();
    this.tip = ((this.tipPercent / 100) * this.bill);
    this.tipPerPerson = this.tip / this.people;
    return this.tipPerPerson;
  }

  getTotalPerPerson() {
    this.getTipPerPerson();
    this.totalPerPerson = (this.bill + this.tip) / this.people
    return this.totalPerPerson;
  }
}

const tipOptions = [...document.querySelectorAll("button"), document.querySelector("#custom")];
tipOptions.forEach(option => {
  if (option.tagName === "INPUT" && option.value.length) option.addEventListener("keyup", () => {
    tipOptions.forEach(option => option.classList.remove("active"));
    option.classList.toggle("active");
  })
  if (!(option.type == "submit")) option.addEventListener("click", () => {
    tipOptions.forEach(option => option.classList.remove("active"));
    option.classList.toggle("active");
  })
})

form.addEventListener("submit", event => {
  event.preventDefault();
  checkInputForError(peopleElem, peopleError, true);
  checkInputForError(billElem, billError, false);
  if (billError || peopleError) return;
  const tipCalculator = new TipCalc();
  const tip = isNaN(tipCalculator.getTipPerPerson()) ? 0 : tipCalculator.getTipPerPerson();
  const total = isNaN(tipCalculator.getTotalPerPerson()) ? 0 : tipCalculator.getTotalPerPerson();
  const formatter = new Intl.NumberFormat(undefined, {
    style: "currency",
    currency: "USD",
    signDisplay: "never"
  });
  tipPerPersonElem.innerText = formatter.format(tip);
  totalPerPersonElem.innerText = formatter.format(total);
  submit.style.display = "none";
  const resetBtn = document.querySelector("[type=\"reset\"]");
  resetBtn.style.display = "block";
  resetBtn.addEventListener("click", () => {
    reset()
    resetBtn.style.display = "none";
    submit.style.display = "block";
  })
})

document.addEventListener("DOMContentLoaded", () => {
  reset()
})

peopleElem.addEventListener("keyup", () => checkInputForError(peopleElem, peopleError, true));
billElem.addEventListener("keyup", () => checkInputForError(billElem, billError, false));

function checkInputForError(input, error, showError) {
  const value = input.value.trim() || 0;
  if (!value || isNaN(parseFloat(value)) || parseFloat(value) == 0) {
    if (showError) document.querySelector(".warning").style.display = "inline";
    input.classList.add("error");
    error = true;
  } else {
    if (showError) document.querySelector(".warning").style.display = "none";
    input.classList.remove("error");
    input.classList.add("correct");
    error = false;
  }
}

function reset(submit = false) {
  const tipPerPersonElem = document.querySelector("[data-tip-person]");
  const totalPerPersonElem = document.querySelector("[data-total-person]");
  tipPerPersonElem.innerText = "";
  totalPerPersonElem.innerText = "";
  console.log(tipPerPersonElem.innerText, totalPerPersonElem.innerText, "reset", submit);
  tipOptions.forEach(option => option.classList.remove("active"));
  document.querySelectorAll("input").forEach(input => {
    input.classList.remove("correct");
    input.classList.remove("error");
    input.value = "";
  })
}
:root {
  --primary-color: hsl(172, 67%, 45%);
  --very-dark-cyan: hsl(183, 100%, 15%);
  --dark-grayish-cyan: hsl(186, 14%, 43%);
  --grayish-cyan: hsl(184, 14%, 56%);
  --light-grayish-cyan: hsl(185, 41%, 84%);
  --very-light-grayish-cyan: hsl(189, 41%, 97%);
  --white: hsl(0, 0%, 100%);
  --primary-font-size: 24px;
  --primary-font-family: 'Space Mono', monospace;
}

/* GLOABAL TAGS */

body {
  width: 100%;
  margin: 0;
  overflow: hidden;
  font-family: var(--primary-font-family);
  background-color: var(--light-grayish-cyan);
}

header {
  text-align: center;
}

h1 {
  color: var(--very-dark-cyan);
  margin-top: 0;
  text-transform: uppercase;
}

h1 span {
  display: block;
  margin: 0;
}

label {
  display: block;
  text-transform: capitalize;
}

button {
  outline: none;
  border: none;
  text-align: center;
  background-color: var(--very-dark-cyan);
  font-size: var(--primary-font-size);
  color: var(--white);
  text-transform: capitalize;
  margin: 8px;
  padding-top: 8px;
  padding-bottom: 8px;
  border-radius: 4px;
  cursor: pointer;
}

legend {
  margin-bottom: 8px;
}

/* Chrome,
Safari,
Edge, */

/* Opera  */

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

/* Firefox */

input[type=number] {
  -moz-appearance: textfield;
}

input {
  display: block;
  border: none;
  background-color: var(--very-light-grayish-cyan);
  font-size: var(--primary-font-size);
  height: 30px;
  color: var(--very-dark-cyan);
  background-repeat: no-repeat;
  background-position: left center;
}

input:not(#custom) {
  text-indent: 99.8%;
}

aside {
  font-size: 11px;
  text-align: center;
}

aside a {
  color: hsl(228, 45%, 44%);
}

/* END OF GLOBAL TAGS GENERIC IDs  */

#bill {
  background-image: url('https://kaustubhmaladkar.github.io/Tip-Calculator/images/icon-dollar.svg');
}

#people {
  background-image: url('https://kaustubhmaladkar.github.io/Tip-Calculator/images/icon-person.svg');
}

/* END OF GENERIC IDs GENERIC CLASSES*/

button,
#custom {
  width: calc(50% - 20px);
  font-weight: bold;
}

/* END OF GENERIC CLASSES  */

/* INPUT  */

.input {
  background-color: var(--white);
  color: var(--dark-grayish-cyan);
  border-top-right-radius: 20px;
  border-top-left-radius: 20px;
  margin-top: 20px;
  padding-bottom: 30px;
}

.input legend {
  margin-top: 20px;
  margin-left: 20px;
}

legend:nth-of-type(2) label {
  width: 100%;
}

legend:nth-of-type(2) {
  display: flex;
  flex-wrap: wrap;
}

[for="people"] {
  display: inline;
}

.warning {
  display: none;
  /* margin-left: 92px; */
  color: red;
  font-size: 12px;
  background-color: transparent;
}

input#custom {
  background-color: var(--white);
  color: var(--dark-grayish-cyan);
  margin-top: 12px;
  margin-left: 2px;
  padding-bottom: 8px;
  opacity: 1;
}

input#custom::placeholder {
  text-transform: capitalize;
  color: var(--dark-grayish-cyan);
  opacity: 1;
}

/* END OF INPUT */

/*OUTPUT*/

.output {
  background-color: var(--very-dark-cyan);
  display: flex;
  margin-top: -8px;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  border-radius: 10px;
}

.output div,
.output span {
  width: 100%;
}

.output>div>div {
  display: flex;
  gap: 15px;
}

.output>div>div:first-of-type {
  margin-top: 30px;
  margin-bottom: 15px;
}

.output>div>div:last-of-type {
  margin-top: 15px;
  margin-bottom: 30px;
}

[type="submit"],
[type="reset"] {
  font-family: var(--primary-font-family);
  background-color: var(--primary-color);
  width: 90%;
  text-align: center;
  color: var(--very-dark-cyan);
}

.tip-person,
.total-person {
  font-size: 35px;
  color: var(--primary-color);
}

.output>div>div>div>span:first-of-type {
  text-transform: capitalize;
  color: var(--white);
  display: block;
}

.output>div>div>div>span:last-of-type {
  color: var(--grayish-cyan);
}

/*END OF OUTPUT */

.active:not(input) {
  background-color: var(--primary-color);
  color: var(--very-dark-cyan);
  transition: background 0.7s ease-in-out;
}

.correct {
  border: lightgreen 2px solid;
}

.error {
  border: red 2px solid;
}

.correct:focus,
.error:focus {
  outline: none;
}

/* JAVASCRIPT CLASSES */

/* END OF JAVASCRIPT CLASSES */

/* FOR DESKTOP   */

@media (min-width: 1200px) {
  /* RESET */
  html,
  body,
  main {
    margin: 0;
  }
  /* END OF RESET */
  /* GENERIC TAGS */
  form {
    width: 100%;
    max-width: 900px;
    border-radius: 15px;
    overflow: hidden;
    margin: auto;
    padding-right: 15px;
    display: flex;
    width: fit-content;
    background-color: var(--white);
  }
  input {
    width: 90%;
  }
  aside {
    display: none;
  }
  /* END OF GENERIC TAGS */
  /* GENERIC CLASSES */
  .output,
  .input {
    height: 400px;
  }
  .warning {
    margin-left: 92px;
  }
  /* END OF GENERIC CLASSES */
  /* INPUT */
  .input button,
  .input input#custom {
    width: calc(100% / 3 - 20px);
  }
  .input {
    width: 50%;
    padding-bottom: 0;
  }
  .input legend {
    margin-left: 25px;
  }
  /* END OF INPUT */
  /* OUTPUT */
  .output {
    width: 50%;
    margin: 22px;
    padding: 0;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
  }
  .output div {
    margin-left: 20px;
  }
  .output>div>div:first-of-type {
    margin-top: -20px;
    margin-bottom: 40px;
  }
  [type="reset"] {
    display: none;
  }
  /* END OF OUTPUT */
}

  spli
  tter

<form action="post">

    <legend>
      bill
      <input type="number" name="bill" id="bill" class="correct">
    </legend>

    <legend>
      select tip %
      <button type="button">5%</button>
      <button type="button" class="">10%</button>
      <button type="button">15%</button>
      <button type="button">25%</button>
      <button type="button">50%</button>
      <input placeholder="custom" name="custom" id="custom" class="">
    </legend>

    <legend>
      Number of People

Can't be zero

      <input type="number" name="people" id="people" class="">
    </legend>

          tip amount
          / person

          Total
          / person

    <button type="submit" style="display: block;">Calculate</button>
    <button type="reset" class="" style="display: none;">Reset</button>

</form>

Live site: https://kaustubhmaladkar.github.io/Tip-Calculator/
Code on Github: https://github.com/KaustubhMaladkar/Tip-Calculator/

A: The problem comes from this line:
input:not(#custom) {
  text-indent: 99.8%;
}

If you only want a alignment to the right, change it to:
input:not(#custom) {
  text-align: right;
}

Working example:

const peopleElem = document.querySelector("#people");
const billElem = document.querySelector("#bill");
const submit = document.querySelector("[type=\"submit\"]");
const form = document.querySelector("form");
const tipPerPersonElem = document.querySelector("[data-tip-person]");
const totalPerPersonElem = document.querySelector("[data-total-person]");
let billError = peopleError = false;

class TipCalc {
  constructor() {
    this.tipPerPerson = 0;
    this.totalPerPerson = 0;
    this.tip = 0
    this.tipPercent = 0;
    this.bill = parseFloat(billElem.value);
    this.people = parseFloat(peopleElem.value);
  }

  getTip() {
    const element = document.querySelector(".active");
    if (!element) return 0;
    if (element.tagName === "BUTTON") return this.tipPercent = element.innerText.replace("%", "");
    return this.tipPercent = element.value.replace("%", "");
  }

  getTipPerPerson() {
    this.getTip();
    this.tip = ((this.tipPercent / 100) * this.bill);
    this.tipPerPerson = this.tip / this.people;
    return this.tipPerPerson;
  }

  getTotalPerPerson() {
    this.getTipPerPerson();
    this.totalPerPerson = (this.bill + this.tip) / this.people
    return this.totalPerPerson;
  }
}

const tipOptions = [...document.querySelectorAll("button"), document.querySelector("#custom")];
tipOptions.forEach(option => {
  if (option.tagName === "INPUT" && option.value.length) option.addEventListener("keyup", () => {
    tipOptions.forEach(option => option.classList.remove("active"));
    option.classList.toggle("active");
  })
  if (!(option.type == "submit")) option.addEventListener("click", () => {
    tipOptions.forEach(option => option.classList.remove("active"));
    option.classList.toggle("active");
  })
})

form.addEventListener("submit", event => {
  event.preventDefault();
  checkInputForError(peopleElem, peopleError, true);
  checkInputForError(billElem, billError, false);
  if (billError || peopleError) return;
  const tipCalculator = new TipCalc();
  const tip = isNaN(tipCalculator.getTipPerPerson()) ? 0 : tipCalculator.getTipPerPerson();
  const total = isNaN(tipCalculator.getTotalPerPerson()) ? 0 : tipCalculator.getTotalPerPerson();
  const formatter = new Intl.NumberFormat(undefined, {
    style: "currency",
    currency: "USD",
    signDisplay: "never"
  });
  tipPerPersonElem.innerText = formatter.format(tip);
  totalPerPersonElem.innerText = formatter.format(total);
  submit.style.display = "none";
  const resetBtn = document.querySelector("[type=\"reset\"]");
  resetBtn.style.display = "block";
  resetBtn.addEventListener("click", () => {
    reset()
    resetBtn.style.display = "none";
    submit.style.display = "block";
  })
})

document.addEventListener("DOMContentLoaded", () => {
  reset()
})

peopleElem.addEventListener("keyup", () => checkInputForError(peopleElem, peopleError, true));
billElem.addEventListener("keyup", () => checkInputForError(billElem, billError, false));

function checkInputForError(input, error, showError) {
  const value = input.value.trim() || 0;
  if (!value || isNaN(parseFloat(value)) || parseFloat(value) == 0) {
    if (showError) document.querySelector(".warning").style.display = "inline";
    input.classList.add("error");
    error = true;
  } else {
    if (showError) document.querySelector(".warning").style.display = "none";
    input.classList.remove("error");
    input.classList.add("correct");
    error = false;
  }
}

function reset(submit = false) {
  const tipPerPersonElem = document.querySelector("[data-tip-person]");
  const totalPerPersonElem = document.querySelector("[data-total-person]");
  tipPerPersonElem.innerText = "";
  totalPerPersonElem.innerText = "";
  console.log(tipPerPersonElem.innerText, totalPerPersonElem.innerText, "reset", submit);
  tipOptions.forEach(option => option.classList.remove("active"));
  document.querySelectorAll("input").forEach(input => {
    input.classList.remove("correct");
    input.classList.remove("error");
    input.value = "";
  })
}
:root {
  --primary-color: hsl(172, 67%, 45%);
  --very-dark-cyan: hsl(183, 100%, 15%);
  --dark-grayish-cyan: hsl(186, 14%, 43%);
  --grayish-cyan: hsl(184, 14%, 56%);
  --light-grayish-cyan: hsl(185, 41%, 84%);
  --very-light-grayish-cyan: hsl(189, 41%, 97%);
  --white: hsl(0, 0%, 100%);
  --primary-font-size: 24px;
  --primary-font-family: 'Space Mono', monospace;
}

/* GLOABAL TAGS */

body {
  width: 100%;
  margin: 0;
  overflow: hidden;
  font-family: var(--primary-font-family);
  background-color: var(--light-grayish-cyan);
}

header {
  text-align: center;
}

h1 {
  color: var(--very-dark-cyan);
  margin-top: 0;
  text-transform: uppercase;
}

h1 span {
  display: block;
  margin: 0;
}

label {
  display: block;
  text-transform: capitalize;
}

button {
  outline: none;
  border: none;
  text-align: center;
  background-color: var(--very-dark-cyan);
  font-size: var(--primary-font-size);
  color: var(--white);
  text-transform: capitalize;
  margin: 8px;
  padding-top: 8px;
  padding-bottom: 8px;
  border-radius: 4px;
  cursor: pointer;
}

legend {
  margin-bottom: 8px;
}

/* Chrome,
Safari,
Edge, */

/* Opera  */

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

/* Firefox */

input[type=number] {
  -moz-appearance: textfield;
}

input {
  display: block;
  border: none;
  background-color: var(--very-light-grayish-cyan);
  font-size: var(--primary-font-size);
  height: 30px;
  color: var(--very-dark-cyan);
  background-repeat: no-repeat;
  background-position: left center;
}

input:not(#custom) {
  text-align: right;
}

aside {
  font-size: 11px;
  text-align: center;
}

aside a {
  color: hsl(228, 45%, 44%);
}

/* END OF GLOBAL TAGS GENERIC IDs  */

#bill {
  background-image: url('https://kaustubhmaladkar.github.io/Tip-Calculator/images/icon-dollar.svg');
}

#people {
  background-image: url('https://kaustubhmaladkar.github.io/Tip-Calculator/images/icon-person.svg');
}

/* END OF GENERIC IDs GENERIC CLASSES*/

button,
#custom {
  width: calc(50% - 20px);
  font-weight: bold;
}

/* END OF GENERIC CLASSES  */

/* INPUT  */

.input {
  background-color: var(--white);
  color: var(--dark-grayish-cyan);
  border-top-right-radius: 20px;
  border-top-left-radius: 20px;
  margin-top: 20px;
  padding-bottom: 30px;
}

.input legend {
  margin-top: 20px;
  margin-left: 20px;
}

legend:nth-of-type(2) label {
  width: 100%;
}

legend:nth-of-type(2) {
  display: flex;
  flex-wrap: wrap;
}

[for="people"] {
  display: inline;
}

.warning {
  display: none;
  /* margin-left: 92px; */
  color: red;
  font-size: 12px;
  background-color: transparent;
}

input#custom {
  background-color: var(--white);
  color: var(--dark-grayish-cyan);
  margin-top: 12px;
  margin-left: 2px;
  padding-bottom: 8px;
  opacity: 1;
}

input#custom::placeholder {
  text-transform: capitalize;
  color: var(--dark-grayish-cyan);
  opacity: 1;
}

/* END OF INPUT */

/*OUTPUT*/

.output {
  background-color: var(--very-dark-cyan);
  display: flex;
  margin-top: -8px;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  border-radius: 10px;
}

.output div,
.output span {
  width: 100%;
}

.output>div>div {
  display: flex;
  gap: 15px;
}

.output>div>div:first-of-type {
  margin-top: 30px;
  margin-bottom: 15px;
}

.output>div>div:last-of-type {
  margin-top: 15px;
  margin-bottom: 30px;
}

[type="submit"],
[type="reset"] {
  font-family: var(--primary-font-family);
  background-color: var(--primary-color);
  width: 90%;
  text-align: center;
  color: var(--very-dark-cyan);
}

.tip-person,
.total-person {
  font-size: 35px;
  color: var(--primary-color);
}

.output>div>div>div>span:first-of-type {
  text-transform: capitalize;
  color: var(--white);
  display: block;
}

.output>div>div>div>span:last-of-type {
  color: var(--grayish-cyan);
}

/*END OF OUTPUT */

.active:not(input) {
  background-color: var(--primary-color);
  color: var(--very-dark-cyan);
  transition: background 0.7s ease-in-out;
}

.correct {
  border: lightgreen 2px solid;
}

.error {
  border: red 2px solid;
}

.correct:focus,
.error:focus {
  outline: none;
}

/* JAVASCRIPT CLASSES */

/* END OF JAVASCRIPT CLASSES */

/* FOR DESKTOP   */

@media (min-width: 1200px) {
  /* RESET */
  html,
  body,
  main {
    margin: 0;
  }
  /* END OF RESET */
  /* GENERIC TAGS */
  form {
    width: 100%;
    max-width: 900px;
    border-radius: 15px;
    overflow: hidden;
    margin: auto;
    padding-right: 15px;
    display: flex;
    width: fit-content;
    background-color: var(--white);
  }
  input {
    width: 90%;
  }
  aside {
    display: none;
  }
  /* END OF GENERIC TAGS */
  /* GENERIC CLASSES */
  .output,
  .input {
    height: 400px;
  }
  .warning {
    margin-left: 92px;
  }
  /* END OF GENERIC CLASSES */
  /* INPUT */
  .input button,
  .input input#custom {
    width: calc(100% / 3 - 20px);
  }
  .input {
    width: 50%;
    padding-bottom: 0;
  }
  .input legend {
    margin-left: 25px;
  }
  /* END OF INPUT */
  /* OUTPUT */
  .output {
    width: 50%;
    margin: 22px;
    padding: 0;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
  }
  .output div {
    margin-left: 20px;
  }
  .output>div>div:first-of-type {
    margin-top: -20px;
    margin-bottom: 40px;
  }
  [type="reset"] {
    display: none;
  }
  /* END OF OUTPUT */
}

  spli
  tter

<form action="post">

    <legend>
      bill
      <input type="number" name="bill" id="bill" class="correct">
    </legend>

    <legend>
      select tip %
      <button type="button">5%</button>
      <button type="button" class="">10%</button>
      <button type="button">15%</button>
      <button type="button">25%</button>
      <button type="button">50%</button>
      <input placeholder="custom" name="custom" id="custom" class="">
    </legend>

    <legend>
      Number of People

Can't be zero

      <input type="number" name="people" id="people" class="">
    </legend>

          tip amount
          / person

          Total
          / person

    <button type="submit" style="display: block;">Calculate</button>
    <button type="reset" class="" style="display: none;">Reset</button>

</form>


text:
Q: transferring audio files via WebSocket I have to send and receive an audio file via WebSocket using mobile devices. The clients are Android, IOS and WP. Do you guys have any idea how to accomplish this? I thought about encode file with base64 and send it as string, but maybe there is a better way to do this? Which WebSocket I should use?
Thanks

A: Send your audio file as a sequence of binary frames. Most WebSocket libraries provide means to send and receive binary data. See 5. Data Framing in RFC 6455 for details about binary frames.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Configure S3 with custom error redirect logic? I currently have my CI pipeline to deploy previews to s3/:commit_hash/ (eg. //preview.domain.com/a1a2a3/
The previews are single-page-apps that use react-router for navigation. As a result, anything except index.html will 404.
There are s3 hacks to have 404 serve index.html thread
Is it possible to create a redirect rule that will take a 404 and serve it with the first part of the path intact? eg:
//preview.domain.com/a1a2a3/does/not/exist => serves //preview.domain.com/a1a2a3/index.html
//preview.domain.com/deadbeef/random => //preview.domain.com/deadbeef/index.html


text:
Q: Stop Concatenating String to Dynamic Array when '#' is Entered by User in C I am required to write a code where I constantly read a string input from the user and store it in the same variable. Each time an input is received the string will be concatenated onto a dynamic array (so the dynamic array grows bigger and bigger). It will stop reading the input from the user when the input contains '#'.
Expected inputs and outputs should be:
inputs              output
here I am #abc      hereIam
there you are #12   thereyouare

Here's the code I've done:
#include<stdio.h>
#include<stdlib.h> // for malloc
#include<string.h> // for string funs

int main(void){
    char input1[256];
    char *combined = malloc(sizeof(char));
    int i = 0;

    while (input1[i]!= '#'){
    // read in the arrays
    printf("Enter a string (max 256 char) ");
    scanf("%256s",input1);

    // find out string lengths
    int len1;
    len1=strlen(input1);

     // allocate an array big enough for both
     combined=realloc(combined, sizeof(char)*(len1));

     //concatenate
     strcat(combined,input1);
    }

    // print
    printf("%s\n",combined);

    return 0;
}

This code I have here have several problems:

*

*I have no idea how to check if elements other than the first element of the user's input is '#' or not.

*Even if the input contains '#', the output will still contain that input where '#' is in it.

Can anyone give me hints on how to solve this? Thank you!

A: You may be making this harder on yourself that need be. While your heading a 2-column output adds a bit of formatting challenge, the easiest way to handle the input and classification (store-it/ignore-it) is with a character-oriented approach using getchar() or fgetc().
That way you simply continually read from the input and check if the character is a '#' or '\n', if so, stop storing characters in your buffer and just read and output the rest. After your loop completes, you simply need to nul-terminate your final buffer, compute the whitespace needed between the end of the original and the output of your buffer content, write the spaces and the final buffer and you are done. A short example would be:
#include <stdio.h>
#include <ctype.h>

#define MAXC 1024   /* if you need a constant, #define one (or more) */

int main (int argc, char **argv) {

    char buf[MAXC];
    int c, idx = 0, nc = 0, ws = 0;
    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    puts ("inputs              output");    /* output headings */
    while ((c = fgetc(fp)) != EOF) {        /* read each char until EOF */
        if (c == '#' || c == '\n') {        /* if # or \n, end of storage */
            buf[idx] = 0;                   /* nul-terminate buffer at idx */
            putchar (c);                    /* output delim in orig string */
            nc++;                           /* increment no. of char  */
            while ((c = fgetc(fp)) != '\n' && c != EOF) {   /* print rest */
                putchar (c);
                nc++;
            }
            ws = 20 - nc;           /* compute amount of whitespace to col */
            while (ws--)            /* output that many spaces */
                putchar (' ');
            printf ("%s\n", buf);   /* print the stored buffer */
            idx = 0, nc = 0;        /* reset index and counter */
            continue;               /* go get next char */
        }
        else if (isalnum (c))       /* if alnum char add to buffer */
            buf[idx++] = c;
        putchar (c);        /* output all chars until # */
        nc++;               /* increment no. of chars */
    }
    buf[idx] = 0;           /* nul-terminate final line after loop */
    ws = 20 - nc;           /* set number of whitespace needed to 2nd col */
    while (ws--)            /* write that number of spaces */
        putchar (' ');
    printf ("%s\n", buf);   /* output string without whitespace in buf */

    if (fp != stdin)        /* close file if not reading stdin */
        fclose (fp);

    return 0;
}

Example Input File
$ cat dat/pounddelim.txt
here I am #abc
there you are #12

Example Use/Output
Running the program on your input produces the "Expected inputs and outputs":
$ ./bin/pounddelim <dat/pounddelim.txt
inputs              output
here I am #abc      hereIam
there you are #12   thereyouare

Look things over and let me know if you have further questions.


text:
Q: Ubuntu 20.04 stuck at [ok] reached target local encrypted volumes I got my Ubuntu 20.04 triple booted with Windows and Kali and it was working all fine until today, when it gave an Ubuntu Software update pop up.
I clicked to update the software, and after that it said it needed a restart. After I restarted, the GRUB screen was shown as usual, but when I selected Ubuntu 20.04, it got stuck at this:

I have tried using nomodeset, but it gets stuck at Started GNOME Display Manager.
Can anyone help me solve this without a fresh install?

A: I just had this and the only workaround I could find was to add this to /etc/default/grub:
GRUB_TERMINAL=console

Then run:
sudo update-grub

and reboot.


text:
Q: CS1502 error when inserting media url in img source attribute (Umbraco) I want to display a header logo on my master template.
So far I have this code:

    <img width="320px"
       src='@(Model.Content.GetPropertyValue<IEnumerable<IPublishedContent>>
       ("headerLogo").Url)'>

When i run the page i receive this error message:
http://i.imgur.com/4RaL947.png
I'm not sure what causes this error, as the formatting looks fine to me. The mediapicker property editor for the header logo is defined in a language document type, which has the master as its template.

A: You are telling GetPropertyValue to try to return an IEnumerable of IPublishedContent, yet you immediately try to use a single .Url. Have you tried Model.Content.GetPropertyValue ("headerLogo").Url instead?

A: If using a MediaPicker, I've been successful in using it in an img tag with the following:
@var image = Umbraco.Media(Convert.ToString(Umbraco.Field("mediaPickerName"))).umbracoFile;


text:
Q: What can I do in VIM that I can't already do in Visual Studio? I heard it takes 30 days minimum to get comfortable with vi. I'm on day 2 hehe. Right now, I seem to be merely memorizing different shortcuts for things I already did in Visual Studio (incremental search, prev/next word, etc.).
So far the most powerful aspect seems to be the numeric keys combined with commands (5 * next line), and the idea of normal/insert modes.
There are a few things I miss from Visual Studio. Ctrl-Click'ing the mouse for quick copy and pasting is probably the biggest.
So that I don't get discouraged, can you guys walk me through some things in vi that you do regularly that can't be done in Visual Studio? It'll help me focus on what to learn and help me develop better habits.

A: Note that I don't use Visual Studio, and know little about the available features in it. The following are examples of what I find useful in Vim, not a list of missing features in Visual Studio.
Macros
It's easy to create macros for complex (but repetitive) operations. To illustrate with a simple example, let's say we start with:

Line1
Line2
Line3
Line4
Line5

Now we want to envelop each line in a print(""); statement.
Place the cursor on the first line, and enter:

*

*qx to start recording a macro to the register x

*Shift+I print(" Esc    to insert text at the beginning of the line

*Shift+A "); Esc            to append text at the end of the line

*j to go down one line

*q to stop recording the macro

*4@x to execute the macro in register x 4 times

See :help complex-repeat for more info on Vim macros.
Text objects
Note that this is one of the improvements Vim has over the traditional Vi. If it doesn't work, you're probably running in Vi compatibility mode; use :set nocompatible to enable the full functionality of Vim.
Text objects allow you to easily select regions of text. Let's say we start with the following text, and place the cursor on some text:

some text

Now we want to delete everything between  and . This can be done by simply typing  the command dit (d'elete i'nner t'ag)! Or if we want to include the tags themselves in our selection, use dat (d'elete a t'ag). To delete everything inside the  tags, use d2it (d'elete two i'nner t'ags).
You can similarly use daw (delete a word), dap (delete a paragraph), di" (delete inside double-quotes), etc; see :help text-objects for the complete list.
Another useful example of text objects:

v2ap"+y

*

*v toggles visual mode. This makes it easier to see what you're selecting, and lets you adjust your selection with a series of multiple motions before you execute a command.

*2ap selects this paragraph and the next one

*"+ selects the system clipboard as register for the next operation

*y yanks the selection to the given register

In other words, that command would copy two paragraphs from your text to the system clipboard (e.g. for pasting them here at StackOverflow).
Global editing
The global command is used to apply an Ex command to all lines matching a given regular expression. Examples:

*

*:global/test/print or :g/test/p would print all lines containing the phrase test

*:global/test/delete or :g/test/d would delete said lines

*:global/test/substitute/^/#/ or :g/test/s/^/#/ would search for lines containing the phrase test, and comment them out by substituting the regexp anchor ^ (beginning-of-line) with the symbol #.

You can also do some cool stuff by passing the search motions /pattern or ?pattern as ranges:

*

*:?test?move . searches backwards for a line containing test, and moves it to your current position in the file

*:/test/copy . searches forwards for a line containing test, and copies it to the current position in the file

Good luck and have fun learning Vim!

A: Edit a file on a Solaris machine that only allows SSH access.

A: This article is what got me started on Vim, and I never looked back:
http://www.viemu.com/a-why-vi-vim.html
It has some great examples on Vim's power.

A: Use screen to keep a session running on a remote machine accessed over ssh

A: Visual Studio's regular expressions are a little bit Mickey Mouse. Vim has the full POSIX regular expression language at your fingertips.

A: As far as I can tell (in Visual C# express 2010) ctrl-click just selects whatever word you click on.  To do the same in VIM, you can combine the yank command with a movement command.
So you press "y" for yank (copy) then "e" or "w" to copy to the end of the word.

A: There is many differences.

*

*Block (and column) wise copy, paste, edit

*the dot command! (after duck tape the second most powerful tool on the planet, seriously)

I suggest you watch some screencasts at http://vimcasts.org/ to get a feeling of the power of vim.
e.g.:

*

*http://vimcasts.org/episodes/creating-the-vimcasts-logo-as-ascii-art/

*http://vimcasts.org/episodes/selecting-columns-with-visual-block-mode/

A: You could always use the Vim emulator/add-on for Visual Studio and get some of the power of vim mixed with the features of VS. If you're already using Visual Studio, I assume you're using a .NET language, which without VS, would be much more painful to use.

A: I'll just leave a link to this SO answer here.

A: VI means never ever having to take you fingers off the keyboard.

A: Vim Essentials is a nice set of slides.
Personally, I got used to vi a long time ago, when we didn't have the luxury of a mouse in student's Unix terminals. Since then, I used vi/vim for everything safe for writing emails.
To this day, I probably use only 1/20 of the commands, but never felt the need to write code with another text editor, and reaching for a mouse in an IDE feels very clumsy to me.
Using high level and expressive languages, that do not require an IDE (mainly python, sql, javascript) really helps. I suppose it wouldn't be as easy with Java or C++.
Not having to move and point with the mouse when coding (safe for using the browser) also helps preventing Carpal tunnel syndrome.
BTW, I suppose Vim integrates better with Unix than with Windows... and who said 30 minutes was a little optimistic :)

A: Edit documents over SSH. Vim's really nice for that.
Edit: looks like a lot of people have already said that :)

A: teco is your answer. You only need a PDP-10 and an ASR-33 and you're on your way!


text:
Q: How to group data to minimize the variance while preserving the order of the data in R I have a data frame (760 rows)  with two columns, named Price and Size. I would like to put the data into 4/5 groups based on price that would minimize the variance in each group while preserving the order Size (which is in ascending order). The Jenks natural breaks optimization would be an ideal function however it does not take the order of Size into consideration.
Basically, I have data simlar to the following (with more data)
Price=c(90,100,125,100,130,182,125,250,300,95)

Size=c(10,10,10.5,11,11,11,12,12,12,12.5)

mydata=data.frame(Size,Price)

I would like to group data, to minimize the variance of price in each group respecting 1) The Size value: For example, the first two prices 90 and 100 cannot be in a different groups since they are the same size & 2) The order of the Size: For example, If Group One includes observations (Obs) 1-2 and Group Two includes observations  3-9, observation 10 can only enter into group two or three.
Can someone please give me some advice? Maybe there is already some such function that I can't find?

A: Is this what you are looking for? With the dplyr package, grouping is quite easy. The %>%can be read as "then do" so you can combine multiple actions if you like.
See http://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html for further information.
library("dplyr")
Price <– c(90,100,125,100,130,182,125,250,300,95)
Size <- c(10,10,10.5,11,11,11,12,12,12,12.5)

mydata <- data.frame(Size,Price) %>% # "then"
  group_by(Size) # group data by Size column

mydata_mean_sd <- mydata %>%  # "then"
  summarise(mean = mean(Price), sd = sd(Price)) # calculate grouped
                                         #mean and sd for illustration

A: I had a similar problem with optimally splitting a day into 4 "load blocks". Adjacent time periods must stick together, of course.
Not an elegant solution, but I wrote my own function that first split up a sorted series at specified break points, then calculates the sum(SDCM) using those break points (using the algorithm underlying the jenks approach from Wiki).
Then just iterated through all valid combinations of break points, and selected the set of points that produced the minimum sum(SDCM).
Would quickly become unmanageable as number of possible breakpoints combinations increases, but it worked for my data set.


text:
Q: space leaves in website after the last div http://www.cjofficial.in
Please Check the Website Via Inspect Element After Clicking a Tab(animation),
There Is Some Space Left Freeley After The last Div..
its showing after the animation of div which is moving from bottom of page to upside..
Please Help Me To Remove That..
Javascript File example.js is Linked to the Site Please Check That Too

A: Don't give height:100% to #content_hold .

A: That extra space is because #content has height:100%;
Looking at your design I recommend you to wrap your page in a div and give following css to it :
.page-wrapper{
    display: flex;
    flex-direction: column;
}

The layout you are trying to achieve can be built easily with flexbox. The support of flexbox is good.

A: Please try adding the following code to your CSS:
html,body {
    padding:0;
    margin:0;
    height:100%;
    width:100%;
}


text:
Q: getIntent().getExtras() sometimes crashing in Activity I start an Intent with some extras and read the passed extras in the Activity's onCreate
class MyActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val extras: Bundle? = intent.extras // <-- crash
        val someInt = extras?.getInt(EXTRA_SOME_INT, -1) ?: -1

        // ...
    }

    companion object {

        const val EXTRA_SOME_INT = "someInt"

        fun createIntent(context: Context, someInt: Int) =
            Intent(context, MyActivity::class.java).apply {
                putExtra(EXTRA_SOME_INT, someInt)
            }
    }
}

// Activity started like this:
fun startMyActivity(context: Context) {
    context.startActivity(MyActivity.createIntent(context, 1234))
}

This works fine, however, in production, the marked line sometimes causes the app to crash when getExtras() is called. According to documentation it can be nullable, but it shouldn't throw an exception.
The crashlog is not always the same, but either this happens in BaseBundle:
java.lang.NullPointerException
Attempt to invoke virtual method 'int android.os.Parcel.dataSize()' on a null object reference

BaseBundle.java line 164 in android.os.BaseBundle.<init>()
Bundle.java line 106 in android.os.Bundle.<init>()
Intent.java line 6580 in android.content.Intent.getExtras()

... or this happens:
java.lang.IllegalArgumentException
Duplicate key in ArrayMap:

BaseBundle.java line 126 in android.os.BaseBundle.<init>()
Bundle.java line 102 in android.os.Bundle.<init>()
Intent.java line 5756 in android.content.Intent.getExtras()

The crash happens only on Android 5, 6 or 7. I haven't found a way to reproduce it on my own device.
Is there something I do wrong, or what would be the best way to avoid this crash? Without the extra bundle, I cannot display my Activity.

A: This was a bug in AOSP which was fixed after Android 7. Here is the reason in the commit message:

Fix for race in writeToParcel and unparcel
Don't access the parcelled data while it might be recycled by another
thread.
Also make a local reference of mMap, which could be modified by
another thread.

A:     Bundle receiveData = getIntent().getExtras();

    if (receiveData != null){
        .....
    }


text:
Q: CSS – 'overflow-x: scroll' hides content that overflows in the y-axis I have some HTML structured roughly as such (I have included the relevant CSS):

Example

Example

Example

I am designing a horizontal bar that contains several items, which – when hovered over – display tooltips. These tooltips are positioned absolutely, whilst the parent div (container) is positioned relatively. The container uses flexbox and has 'overflow-x: scroll' on it in order to allow horizontal scrolling when the width is smaller than the contents. However, this current setup hides the tooltips, which are meant to be visible below the items (they overflow the container div in the y-axis). When 'overflow-x: scroll' is removed, the tooltips are visible. Hence, it seems that the attribute is also hiding the y-overflow. Has anyone experienced this issue before and/or has a solution?
Edit: If 'position: relative' is instead placed on the wrapper, the tooltips become visible, but do not scroll with the items if there is x-overflow.


text:
Q: node.js express как подключить https? Пытаюсь так:
var express = require('express');
var path = require('path');
var fs = require('fs');
var app = express();

var server = require('https').createServer({
    key: fs.readFileSync(path.resolve(__dirname, 'sslcert/server.key')),
    cert: fs.readFileSync(path.resolve(__dirname, 'sslcert/server.crt'))
},app);
server.listen(80);

Но ничего не выходит =(
Есть идеи как запустить сертификат на ноде?

A: Решил вопрос, поменял порт с 80 на 443


text:
Q: How to attatch a bufferedInputStream to a string? Basically, I'm trying to automate keystrokes by switching an existing BufferedInputStream(System.in) to my own buffered input stream.  I would like to make a BufferedInputStream() object that attaches to something like a string which can be controlled asynchronously.
Here's what I'd like to do..
StringBuilder stringBuilder=new StringBuilder;
BufferedInputStream output=new something(new something(stringBuilder));

Currently the only option I can see is to check if a file exists, then open a buffered input stream to it.
I'm not really sure how to do this, but I need to write to something which can take the place of the System.in inpustream.

A: I put a good solid  10 hours into this... here's what I came up with..   Piped Streams are what i need
    int BUFFER = 4096;
    PipedOutputStream toAppPipedOutputStream;
    PipedInputStream toAppPipedInputStream;

    static BufferedReader fromAppBufferedReaderfinal;
    BufferedOutputStream fromAppOutputStream;
    PipedOutputStream fromAppPipedOutputStream;
    PipedInputStream fromAppPipedInputStream;

    /* constructor sets up logging and parameters */

           try {
                fromAppPipedInputStream = new PipedInputStream(BUFFER);
                fromAppOutputStream=new BufferedOutputStream(new PipedOutputStream(fromAppPipedInputStream));
                fromAppBufferedReaderfinal=new BufferedReader(new InputStreamReader(fromAppPipedInputStream));
                CASUAL.Log.out = new PrintStream(fromAppOutputStream);

                toAppPipedInputStream = new PipedInputStream(BUFFER);
                toAppPipedOutputStream=new PipedOutputStream(toAppPipedInputStream);
                CASUAL.CASUALInteraction.in= new BufferedReader(new InputStreamReader(toAppPipedInputStream));

In my log and output classes I am, by default, writing into a buffered reader/writer that is pointing at System.in.  I can hyjack it because it's a public static and this is possible.  Now I can just read and write to my app as though it were running on the command line inside my own app


text:
Q: How do I rotate a picturebox around a point?
Solved

I am trying to simulate a planet rotating a star. I am currently aware of the syntax to move the picture box
(I have this in a timer so it is repeated)
private void rotate_timer(object sender, EventArgs e) {
picturebox1.location = new point (picturebox1.location.x + 1,
picturebox1.location.y + 1);
}

But I don't know where to start so that it rotates around a specific point.
How would I go about rotating it around (0,0)?

A: This may help:
float angle = 0;
float rotSpeed = 1;
Point origin = new Point(222, 222);  // your origin
int distance = 100;                  // your distance

private void timer1_Tick(object sender, EventArgs e)
{
    angle += rotSpeed;
    int x = (int)(origin.X + distance * Math.Sin(angle *Math.PI / 180f));
    int y = (int)(origin.Y + distance * Math.Cos(angle *Math.PI / 180f));
    yourControl.Location = new Point(x, y);
}

Pick your timer Interval and don't be disappointed that it will look a little uneven. Winforms is really bad at animation..
If you want the image to rotate as well you can find an example here.


text:
Q: Selecting an element in the same row as specific text I'm using Selenium IDE 1.7.1 to select the checkbox that corresponds with invoice # 405357.  Css seems to allow me to move forward in selecting an element, but not backward.
So this would select the $420:
css=td:contains('405357') + td

Any ideas for a workaround in order to select a the checkbox? Ideally the workaround wouldn't involve going backward or forward but would just say select checkbox
css=input#paymentsForm_invoiceToPayIds if td:contains('405357')

I'd prefer it to be in CSS, but XPath would be ok too.
Thank you!

<input id="paymentsForm_invoiceToPayIds" type="checkbox" onclick="calculateInvoices(this)" value="405357" name="invoiceToPayIds">
<input id="__checkbox_paymentsForm_invoiceToPayIds" type="hidden" value="405357" name="__checkbox_invoiceToPayIds">

405357

A: I believe :contains() works for the parent tr too. Try this:
css=tr:contains('405357') input[type="checkbox"]

A: You can't do this in real CSS, because real CSS doesn't have :contains.  But in XPath, it's simple: //tr[//input[@value="405357"]]//input[@type="checkbox"], which means "The checkbox contained in the table row that contains an input field with the value '405357'".

A: //input[@type='checkbox' and @value="405357"]

try out this one


text:
Q: How to keep changes made to a class when the page refreshes with Javascript I have a table of data for the user to look through and make changes. They have the option to delete a row if they want. When they delete a row it sends back to the db what row is to be deleted. For the user the row won't delete right away but it will get a new class 'deleted' that has some styles to let the user know it's being deleted. I also have the page refreshing every 10 minutes and when it refreshes the new added 'deleted' class goes away.
How can I get it that the class will stay on the row when the page refreshes?
Here is the timer function for the timer to know when to refresh the page. I'm using ajax to refresh the page.
        function startClock() {
          // Get the time to stop the effect
          var stopTime = new Date();
          stopTime.setMinutes(stopTime.getMinutes() + 10);
          // Get a reference to the timer so it can be cancelled later
          timer = setInterval(function () {
              // Check to see if the timer should stop
              var currentTime = new Date();
              if (currentTime < stopTime) {
                  triggerDataTable(); //refresh dataTable
                  var randomnumber = Math.floor(Math.random() * 100);
              } else {
                  // Stop the timer
                  clearInterval(timer);
              }
          }, 600000);
      }

Would I use localStorage? If so how would I actually do it? I'm not familiar with storing local values or anything like that.

A: I'm not 100% sure about this but what about doing something like this:
var deletedRow = $(".deleted");
localStorage.setItem( deletedRow, $(".deleted").val() );

A: try using sessionstorage over localstorage
Session Storage property maintains a separate storage area for each given origin and for a session .
Local Storage does the same thing, but persists even when the browser is closed and reopened.
sessionStorage.setItem('item', value);
sessionStorage.getItem('item');


text:
Q: How quickly does a MFR Auto-Spawner spawn mobs? The MFR Auto-Spawner can be used to spawn mobs, much like a vanilla mob spawner. The mod Soul Shards does this as well. I've been told that a tier 5 soul shard spawns mobs faster than the Auto-Spawner, but I want to know how much faster. How fast does an Auto-Spawner spawn things?

A: The MFR spawners act much like vanilla spawners so you could take a look at the algorithm. They also require power and mob essence to function. The Tier 5 Soul Shard spawner requires nothing to run, and spawns more mobs faster.


text:
Q: Aggregate document multilevel Now consider the case , i have one document containing below collection like structure.
Below is the order collection
{

        "_id" : ObjectId("5788fcd1d8159c2366dd5d93"),
        "color" : "Blue",
        "code" : "1",
        "category_id" : ObjectId("5693d170a2191f9020b8c815"),
        "description" : "julia tried",
        "name" : "Order1",
        "brand_id" : ObjectId("5b0e52f058b8287a446f9f05")

}

There is also a collection for Brand and Category. This is the
Category collection
{
"_id" : ObjectId("5693d170a2191f9020b8c815"),
"name" : "Category1",
"created_at" : ISODate("2016-01-11T20:32:17.832+0000"),
"updated_at" : ISODate("2016-01-11T20:32:17.832+0000"),
}

Brand Collection
{
   "_id" : ObjectId("5b0e52f058b8287a446f9f05"),
   "name" : "brand1",
   "description" : "brand1",
   "updated_at" : ISODate("2017-07-05T09:18:13.951+0000"),
   "created_at" : ISODate("2017-07-05T09:18:13.951+0000"),
}

Now after aggregation applied, it should result in below format:
{
    'brands': [
             {
                _id: '*******'
                name: 'brand1',

                categories: [
                   {
                      _id: '*****',
                      name: 'category_name1',
                      orders: [
                          {
                              _id: '*****',
                              title: 'order1'
                          }

                      ]

                   }
                ]
             }
     ]
}

A: You can try below aggregation:
db.brand.aggregate([
    {
        $lookup: {
            from: "order",
            localField: "_id",
            foreignField: "brand_id",
            as: "orders"
        }
    },
    {
        $unwind: "$orders"
    },
    {
        $lookup: {
            from: "category",
            localField: "orders.category_id",
            foreignField: "_id",
            as: "categories"
        }
    },
    {
        $unwind: "$categories"
    },
    {
        $group: {
            _id: "$_id",
            name: { $first: "$name" },
            description: { $first: "$description" },
            updated_at: { $first: "$updated_at" },
            created_at: { $first: "$created_at" },
            categories: { $addToSet: "$categories" },
            orders: { $addToSet: "$orders" }
        }
    },
    {
        $addFields: {
            categories: {
                $map: {
                    input: "$categories",
                    as: "category",
                    in: {
                        $mergeObjects: [
                            "$$category", {
                                orders: [ {
                                    $filter: {
                                        input: "$orders",
                                        as: "order",
                                        cond: { $eq: [ "$$category._id", "$$order.category_id" ] }
                                    }
                                } ]
                         } ]
                    }
                }
            }
        }
    },
    {
        $project: {
            orders: 0
        }
    }
])

Basically you have to use $lookup twice to "merge" data from all these collections based on brand_id and category_id fields. Since you expect orders in categories in brands you can use $unwind for both arrays and then use $group to get following shape:
{
    "_id" : ObjectId("5b0e52f058b8287a446f9f05"),
    "name" : "brand1",
    "description" : "brand1",
    "updated_at" : ISODate("2017-07-05T09:18:13.951Z"),
    "created_at" : ISODate("2017-07-05T09:18:13.951Z"),
    "categories" : [
            {
                    "_id" : ObjectId("5693d170a2191f9020b8c814"),
                    "name" : "Category1",
                    "created_at" : ISODate("2016-01-11T20:32:17.832Z"),
                    "updated_at" : ISODate("2016-01-11T20:32:17.832Z")
            }
    ],
    "orders" : [
            {
                    "_id" : ObjectId("5788fcd1d8159c2366dd5d93"),
                    "color" : "Blue",
                    "code" : "1",
                    "category_id" : ObjectId("5693d170a2191f9020b8c814"),
                    "description" : "julia tried",
                    "name" : "Order1",
                    "brand_id" : ObjectId("5b0e52f058b8287a446f9f05")
            }
    ]
}

Now you have brand1 with all its subcategories and all orders that should be placed in one of those categories. The only thing is how to "nest" orders in categories. One way to do that might be $map where you can merge each category with all orders that match that category (using $mergeObjects you don't have to specify all properties from categories object).
To match category with orders you can perform $filter on orders array.
Then you can drop orders since those are nested into categories so you don't need them anymore.
EDIT: 3.4 version
In MongoDB 3.4 you can't use $mergeObjects so you should specify all properties for `categories:
db.brand.aggregate([
    {
        $lookup: {
            from: "order",
            localField: "_id",
            foreignField: "brand_id",
            as: "orders"
        }
    },
    {
        $unwind: "$orders"
    },
    {
        $lookup: {
            from: "category",
            localField: "orders.category_id",
            foreignField: "_id",
            as: "categories"
        }
    },
    {
        $unwind: "$categories"
    },
    {
        $group: {
            _id: "$_id",
            name: { $first: "$name" },
            description: { $first: "$description" },
            updated_at: { $first: "$updated_at" },
            created_at: { $first: "$created_at" },
            categories: { $addToSet: "$categories" },
            orders: { $addToSet: "$orders" }
        }
    },
    {
        $addFields: {
            categories: {
                $map: {
                    input: "$categories",
                    as: "category",
                    in: {
                        _id: "$$category._id",
                        name: "$$category.name",
                        created_at: "$$category.created_at",
                        updated_at: "$$category.updated_at",
                        orders: [
                            {
                                $filter: {
                                    input: "$orders",
                                    as: "order",
                                    cond: { $eq: [ "$$category._id", "$$order.category_id" ] }
                                }
                            }
                        ]
                    }
                }
            }
        }
    },
    {
        $project: {
            orders: 0
        }
    }
])


text:
Q: AngularJs - Argument 'AppController' is not a function, got undefined I have a problem that has frustrated me, I get the error Error: [ng: areq] Argument 'AppController' is not a function, got undefined, I have not been able to solve it, I have tried many ways but in all of them I get this same error, does anybody know how I can fix it?
my html:

            <button class="btn btn-primary" ng-click="openDlg()">Open Modal</button>

        <ng-include src=""></ng-include>

my app.js:
var app = angular.module("sampleAngularApp", []);
app.controller("AppController", ["$scope", function ($scope) {
    $scope.openDlg = function () {
        console.log("clicked here...");

        var dlgElem = angular.element("#modalDlg");
        if (dlgElem) {
            dlgElem.modal("show");
        }
    };
}]);

A: Try passing the controller as an argument in the array of your angular module.
var app = angular.module("sampleAngularApp", ['AppController']);
  app.controller("AppController", ["$scope", function ($scope) {
   $scope.openDlg = function () {
    console.log("clicked here...");

    var dlgElem = angular.element("#modalDlg");
    if (dlgElem) {
        dlgElem.modal("show");
    }
 };
}]);

A: Your code works fine for me:
index.html
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

            <button class="btn btn-primary" ng-click="openDlg()">Open Modal</button>

        <ng-include src=""></ng-include>

app.js
var app = angular.module("sampleAngularApp", []);
app.controller("AppController", ["$scope", function ($scope) {
    $scope.openDlg = function () {
        console.log("clicked here...");
    };
}]);

Perhaps check the order in which you're loading the scripts.


text:
Q: When my Word VBA form opens, why won't my the Open or Load events run I must be missing something basic (no pun intended), but I can't figure this out.
I have a MS Word VBA form called frmChooseMacros. I want to execute a subroutine on an Open or Load event for that form before the user interacts with the form.
From this topic https://learn.microsoft.com/en-us/office/vba/api/access.form.open, I came up with this code as a test and added it to the code window for frmChooseMacros:
Private Sub Form_Open(Cancel As Integer)
    MsgBox "Running open event"
End Sub

But it never executes when the form loads.
From this topic, https://learn.microsoft.com/en-us/office/vba/api/access.form.load, I also tried the Load event, like this, but still no joy:
Private Sub Form_Load()
    MsgBox "Running open event"
End Sub

I'm running the form through this sub-routine...
Sub DocFix_00_RunMultipleMacros()
    frmChooseMacros.Show
End Sub

...which executes when a button tied is clicked on the menu.
This image may help provide additional context:

Any help is appreciated. Thank you!

A: (Credit goes to @braX for helping me find the answer here.)
For Word, you have to use the UserForm_Initialize or UserForm_Activate events. There is no Form_Load or Form_Open events for Word.
I was able to solve this by first defining a UserForm object and setting it to my frmChooseMacros user form:
Sub DocFix_00_RunMultipleMacros()
    Dim oForm As UserForm
    Set oForm = New frmChooseMacros
    frmChooseMacros.Show
End Sub

Then I use the UserForm_Activate event here:
Private Sub UserForm_Activate()
  MsgBox "Form has activated."
End Sub


text:
Q: Spring boot embedded tomcat custom realm I am aware of this question:  embedded tomcat spring boot
however this leaves much to be desired as far as a solution is concerned,  Currently I have the following code which works to enable SSL:
TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container;
tomcat.addConnectorCustomizers( (connector) -> {
     connector.setPort(8443);
     connector.setSecure(true);
     connector.setScheme("https");

     Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
     protocol.setSSLEnabled(true);
     protocol.setKeystoreFile(keystore);
     protocol.setKeystorePass(password);
     protocol.setKeystoreType("jks");
     protocol.setKeyAlias(alias);
}
)

My question is this, if I have a Realm that looks like this in XML:
<Realm classname="foo.bar.baz | bing.bang.bong"
        var1 = "xyz"
        var2 = "123"
/>

How do I recreate that with embedded tomcat?

A: Try using the ContextCustomizer instead of the ConnectorCustomizer
tomcat.addContextCustomizers( (context) -> {
    context.setRealm(...);
}
)


text:
Q: Why am I receiving this Template error in my django tutorial? I am currently working through the django polls tutorial and I keep receiving this error. I just can't seem to figure out how to fix it.
I have tried watching multiple youtube tutorials, searched on stack for users having the same problem, and I can't seem to get anything to work.
Any and all help would be much appreciated. Thanks guys
my_code
stacktrace
settings
urls

A: You are making a type mistake while sending the template name in detail view.
return render(request, 'polls/detail.html', {'question':question})

You have set the template name as 'polls/detail.html' but your template is details.html in your file.
Rename the template file to detail.html and it will work fine.


text:
Q: How solr+node.js+mongoDB works? HI I am using a nodeJS application. I trying to use solr-client to serch.
I wanted know does I have to add data to solr those are available in mongoDB or solr can search from there.
And I am running the application in port number 4000, do I have to run another server on port number 8983 to solr-client or solr itself can take care of it.

A: First, populate your mongoDB collection. Then, create a json file with the content of your collection (mongoexport command). Finally, update your Solr collection with your json file.


text:
Q: sns.scatter plot python, specify size I have the sns.scatterplot below, where I have set the size to Gap. The Gap values that have come up are 0, 0.8, 0.16 and 0.24, however the values in my dataframe are 0, 0.5, 1 and 2. How can I set them to equal the values in my dataframe?
ax = sns.scatterplot(x='Number tapes', y='Ic', hue="Angle of twist (degree)", size="Gap", data=Ic_layers)

A: The values that are shown in the legend seem inconsistent with what you are saying the range of data is in your dataframe, but anyway...
You can use legend='full' in the call to scatterplot() to force seaborn to show a legend item for each of the levels of your hues/sizes variable.
N=50
df = pd.DataFrame({'x': np.random.random(size=(N,)), 'y': np.random.random(size=(N,)),
                   'size': np.random.choice([0, 0.5, 1, 2], size=(N,))})
fig, (ax1, ax2) = plt.subplots(1,2)
sns.scatterplot(x="x", y="y", size="size", data=df, ax=ax1)
ax1.set_title('legend="brief" (default)')
sns.scatterplot(x="x", y="y", size="size", data=df, legend='full', ax=ax2)
ax2.set_title('legend="full"')


text:
Q: Copy Text from tmux when another pane is updating In tmux, when I try to copy text, I select it using the mouse and want to hit Ctrl + SHIFT + C. H,owever between selecting and hitting that shortcut another pane is updating (tail -f or top something like that) and the selection is lost.
How can I circumvent that behavior?

A: I guess you're not talking about selecting in tmux like this (selection disappears when user releases the button) but rather about this mode or similar.
Zooming the pane (by default Ctrl+b, z, the same to unzoom later) will hide other panes, so they won't interfere. This method resizes the desired pane, so you may not want this.
Alternatively you can enter copy mode in other panes (Ctrl+b, [ in each interfering pane, quit with q later) to make them stop updating. This method doesn't resize the desired pane.


text:
Q: Building a table with the data from scratch Python I need to build a table with the data like this:
     ┌────────┬───────────┬────────┐
     │ ID     │ Name      │ Age    │
     ├────────┼───────────┼────────┤
     │ 1      │ Jonh      │ 35     │
     ├────────┼───────────┼────────┤
     │ 2      │ Joseph    │ 40     │
     └────────┴───────────┴────────┘

I am not allowed use any Python libraries for that. It has to be done from scratch.
I found that there are some box drawing unicode characters that I could use to draw the table(https://en.wikipedia.org/wiki/Box-drawing_character). Ex:
print(u'\u250C') -> will print ─

I am lost on how I should approach this problem. Should I print the data and then draw the table around or should I print the complete boxed row by row.
Any help is appreciated.
My work so far:
length_list = [len(element) for row in data for element in row]
column_width = max(length_list)
for row in data:
   print(u'\u250C' + (u'\u2500'*column_width*len(data[0])) + u'\u2510')
   row = "".join(element.ljust(column_width + 2) for element in row)
   print(row)
   print(u'\u2514' + (u'\u2500'*column_width*len(data[0])) + u'\u2518')

Gives me this:
┌──────────────────┐
ID      Name    Age
└──────────────────┘
┌──────────────────┐
1       John    35
└──────────────────┘
┌──────────────────┐
2       Joseph  40
└──────────────────┘

A: You're nearly there. You could divide the task into smaller portions and use join() to make your life easier.
Let's first define some constant characters to improve code readability
char_line = u'\u2500'
char_lcorner_top = u'\u250C'
char_rcorner_top = u'\u2510'
char_lside = u'\u251C'
char_rside = u'\u2524'
char_top = u'\u252C'
char_bot = u'\u2534'
char_cross = u'\u253C'
char_lcorner_bot = u'\u2514'
char_rcorner_bot = u'\u2518'

Now let's write functions to create the lines between rows:
def top_rule(width, ncols):
    return char_lcorner_top + char_top.join([char_line * width for i in range(ncols)]) + char_rcorner_top

Explanation:

*

*char_line * width multiplies the - character width times. Let's say width = 4. This would give four dashes like so: ----

*[char_line * width for i in range(ncols)] creates a list with ncols items, each of which is ----.

*char_top.join(...) joins the elements of the list with the ┬ character

*Before returning, we add ┌ before and ┐ after the string we just created.

So top_rule(4, 3) gives "┌────┬────┬────┐"
Similarly, we can define more functions:
def bot_rule(width, ncols):
    return char_lcorner_bot + char_bot.join([char_line * width for i in range(ncols)]) + char_rcorner_bot

def mid_rule(width, ncols):
    return char_lside + char_cross.join([char_line * width for i in range(ncols)]) + char_rside

In each row, we have multiple cells to format. Let's write a function to format each row individually.
def fmt_row(row, width, loffset):
    return "|" + "|".join([cell.ljust(width - loffset).rjust(width) for cell in row]) + "|"

For each cell in the row, we left-justify the cell text to a length of (width - loffset) and right-justify it to width. Then, join with a pipe (|) and add pipes before and after
Now all we need to do is call the functions we made. Remember we only need to print a single mid_rule after all rows except the last. After the last row, we need to print a bot_rule.
num_cols = len(data[0])
length_list = [len(element) for row in data for element in row]
column_width = max(length_list) + 2

print(top_rule(column_width, num_cols))
for row in data[:-1]:
    print(fmt_row(row, column_width, 1))
    print(mid_rule(column_width, num_cols))

print(fmt_row(data[-1], column_width, 1))
print(bot_rule(column_width, num_cols))

With your data, you should get this:
┌────────┬────────┬────────┐
| ID     | Name   | Age    |
├────────┼────────┼────────┤
| 1      | John   | 35     |
├────────┼────────┼────────┤
| 2      | Joseph | 40     |
└────────┴────────┴────────┘

A: It seems like you've basically got it. The only two minor changes you need to make are

*

*Print the rows formatted correctly in terms of spacing (See here) and put pipes between the the entries.

*Print the divider rows once per loop rather than twice. You only need to use the corner characters for the first and last iteration (Move one of the prints to above outside of the loop, keep track of how many rows you printed (perhaps using enumerate) and only print the corner characters instead of pipes if it's the last iteration)

A: Instead of printing out boxes, you only want to print a single line of table characters between rows. Make sure you check if you're iterating over the first row, and if you're not then use the ├ character.
And then you need to add a | to the beginning and end of each row you print out.
Also since the width of the table rows are always the same you can calculate it before your for loop, and it'll make the print statements look a little bit cleaner.
The following works as long as each row has the same number of items in it.
data = [list('abcde'), ['ab', 'cd', 'ef', 'gh', 'aa'], list('abcde')]

length_list = [len(element) for row in data for element in row]
min_gutter_space = 2 # minimum space between columns
column_width = max(length_list) + min_gutter_space
row_width = (len(data[0])+1) * column_width - 1
for i, row in enumerate(data):
    row = ['|', *row, '|']
    if i == 0:
        print('┌' + '─'*row_width + '┐')
    else:
        print('├' + '─'*row_width + '┤')
    print( "".join(element.ljust(column_width) for element in row) )
print('└' + '─'*row_width + '┘')

A:
Should I print the data and then draw the table around or should I print the complete boxed row by row.

Printing to the terminal is done row by row. With the basic print() function in Python, there is no way to go back to a previous row. This means that you have to print the data and the borders as you go.

A: This might just be a small challenge or something, but you really should try to clean up your code to make it more understandable to other people, but also help you understand what's going on, and importantly what's going wrong.
For example, we could write some functions for creating table_row, the table_top,
and table_bottom. Then we simply print the table_top, print table_row (looping through each row), then print the table_bottom.
To keep things clean (like you already did) we would also need to factor in the size of each column.
def table_row(column_sizes: list, row: list):
    output = "│"
    for idx, value in enumerate(row): # assuming length of row is same as column_sizes
        val = " " + str(value)
        while len(val) < column_sizes[idx]:
            val += " "
        output += val + "│"
    return output

def table_top(column_sizes: list):
    output = "┌"
    for idx, column_size in enumerate(column_sizes):
        output += "─" * column_size
        if idx != len(column_sizes) - 1:
            output += "┬"
    output += "┐"
    return output

def table_bottom(column_sizes: list):

    output = "└"
    for idx, column_size in enumerate(column_sizes):
        output += "─" * column_size
        if idx != len(column_sizes) - 1:
            output += "┴"
    output += "┘"
    return output

# Find the size for each column. This could be implemented
# different ways depending on your data format.

data = [
    ["ID", "Name", "Age"],
    [1, "John", 35],
    [2, "Joseph", 40]
]
column_sizes = [0 for i in range(len(data[0]))] # eg [0, 0, 0]
print(column_sizes)
for row in data:
    for idx,col in enumerate(row):
        if len(str(col)) > column_sizes[idx]:
            column_sizes[idx] = len(str(col)) + 4 # spaces on either side
print(column_sizes) # [6, 8, 7]

print(table_top(column_sizes)) # ┌──────┬────────┬───────┐
for row in data:
    print(table_row(column_sizes, row))
    # │ ID   │ Name   │ Age   │
    # │ 1    │ John   │ 35    │
    # │ 2    │ Joseph │ 40    │

print(table_bottom(column_sizes)) # └──────┴────────┴───────┘


text:
Q: Xamarin IOS Notification HTTP Post failing I have a Xamarin IOS app that uses remote notifications with actions. When an action button is pressed, I want to post a message back to the server to record the response. This is mostly working. If the app is active it always works. If the app is in the background then I am sometimes getting the following exception:

System.Net.Http.HttpRequestException: The network connection was lost. ---> Foundation.NSErrorException: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=-4, NSUnderlyingError=0x2815e27c0 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey={length = 16, capacity = 16, bytes = 0x100201bb0d42d4cd0000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <8A9B9110-D44C-46F5-B67E-B11231D82319>.<18>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
      "LocalDataTask <8A9B9110-D44C-46F5-B67E-B11231D82319>.<18>"
  ), NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=https://callservice-v2.azurewebsites.net/api/callaction, NSErrorFailingURLKey=https://callservice-v2.azurewebsites.net/api/callaction, _kCFStreamErrorDomainKey=4}
     --- End of inner exception stack trace ---
    at System.Net.Http.NSUrlSessionHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) <0x105b568a0 + 0x009a3> in :0
    at System.Net.Http.HttpClient.FinishSendAsyncBuffered (System.Threading.Tasks.Task`1[TResult] sendTask, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationTokenSource cts, System.Boolean disposeCts) <0x105a960c0 + 0x005f4> in <692b89da4aac4c12a3ac3af90678ac25#21125a282fd7860e37414196dba0c548>:0
    at Dialer.Models.HttpDataServerClient.PostAsync (System.String api, System.Object message) <0x105f01a70 + 0x0047b> in <8e7629d69d3341bfa512d35c83fa84e0#21125a282fd7860e37414196dba0c548>:0

I have a UNUserNotificationCenterDelegate that has the following method:
    public override void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
    {
        try
        {
            _logger.TraceInfo($"DidReceiveNotificationReponse entered");
            var userInfo = response.Notification.Request.Content.UserInfo;
            var token = GetUserInfoItem(userInfo, "CallToken");
            var subscriberPhoneNumber = GetUserInfoItem(userInfo, "SubscriberPhoneNumber");
            var clientCallingNumber = GetUserInfoItem(userInfo, "ClientCallingNumber");
            var clientDialedNumber = GetUserInfoItem(userInfo, "ClientDialedNumber");
            _logger.TraceInfo($"Notification received, action: {response.ActionIdentifier}, token: {token}, phone #: {subscriberPhoneNumber}");

            // Take action based on Action ID
            switch (response.ActionIdentifier)
            {
                case "accept-call":
                    _callActionsHandler.SendAction(token, subscriberPhoneNumber, CallActions.Accept);
                    break;
                case "send-to-voice-mail":
                    _callActionsHandler.SendAction(token, subscriberPhoneNumber, CallActions.VoiceMail);
                    break;
            }

            // Save the incoming call in the call history
            _callHistoryAccess.AddCallToHistory(
                new CallHistoryInstance()
                {
                    CallerIdNumber = clientDialedNumber,
                    CallTime = DateTime.UtcNow,
                    CustomerPhoneNumber = clientCallingNumber,
                    Type = CallHistoryInstance.CallType.Inbound
                });
        }
        catch (Exception ex)
        {
            _logger.TraceException($"An exception occurred while processing the notification", ex);
        }

        // Inform caller it has been handled
        completionHandler();
    }

The important thing here is the _callActionsHandler.SendAction call. That code is here:
    public void SendAction(string callToken, string subscriberPhoneNumber, CallActions action)
    {
        Task.Run(async () =>
        {
            await SendActionAsync(new CallActionMessage(subscriberPhoneNumber, action, callToken));
        });
    }

    private async Task SendActionAsync(CallActionMessage msg)
    {
        _logger.TraceInfo($"Registering call action for {msg.CallToken} to {msg.CallAction}");
        var result = await _client.PostAsync(Constants.CallActionsApi, msg);

        if (result != 200)
        {
            throw new CallActionsException($"HTTP status {result}");
        }
    }

This code has a wrapper around HttpClient. The PostAsync method is here:
    public async Task<int> PostAsync(string api, object message)
    {
        var apiUrl = Constants.DefaultAppApi + api;
        var contentText = JsonConvert.SerializeObject(message);
        var content = new StringContent(contentText, Encoding.UTF8, "application/json");
        var backOff = 10;
        var retryCount = 5;
        HttpResponseMessage response = null;

        for (var attempt = 1; attempt <= retryCount; attempt++)
        {
            _logger.TraceInfo($"DataServerClient Post message: {message.GetType().Name}, attempt = {attempt}");
            try
            {
               response = await _client.PostAsync(apiUrl, content);
            }
            catch (Exception ex)
            {
                if (attempt == retryCount)
                    _logger.TraceException($"DataServerClient Post failed", ex);
            }

            if (response != null && response.IsSuccessStatusCode)
            {
                _logger.TraceInfo($"DataServerClient post was successful at retry count: {attempt}");
                break;
            }

            backOff *= 2;
            await Task.Delay(backOff);
        }

        return (int)response.StatusCode;
    }

I suspected an issue with the await and possibly needing a ConfigureAwait(). I have experimented with both ConfigureAwait(true) and ConfigureAwait(false) with no success. The results are very similar.
I am at a loss right now for why this is failing. Can anyone provide some information here why this is failing? Or, does anyone have code that does an HTTP post in response to a notification action?


text:
Q: Flash file select dialog limitation in Chrome I'm trying to integrate a JavaScript multiple file uploader into a website. I've worked with Uploadify before and wanted to go with that. The difference in this case was that I needed to allow a large number of files in the upload queue (up to 500).
Everything works fine in Firefox, IE6-9 and Safari. Except for Chrome, where when selecting more than 232 files at once (using the Flash file select dialog) it doesn't do anything (the file select event is not triggered for the JS script to capture).
At first I thought it was an Uploadify bug, and decided to try Plupload as an alternative. Problem is that I hit the same dead end with the Flash version of Plupload, it just won't do anything when selecting more than 232 files at once.
Is this a known Flash Player limitation/bug in Chrome?
Thanks

A: There is a bug related to this:
http://bugs.adobe.com/jira/browse/ASL-299


text:
Q: When Im trying to install easyocr i get an error As a result I get this error:
pip install easyocr

ERROR: Cannot install easyocr==1.0, easyocr==1.1, easyocr==1.1.1, easyocr==1.1.10, easyocr==1.1.2, easyocr==1.1.3, easyocr==1.1.4, easyocr==1
.1.5, easyocr==1.1.6, easyocr==1.1.7, easyocr==1.1.8, easyocr==1.1.9, easyocr==1.2, easyocr==1.2.1, easyocr==1.2.2, easyocr==1.2.3, easyocr==
1.2.4, easyocr==1.2.5, easyocr==1.2.5.1, easyocr==1.3, easyocr==1.3.0.1, easyocr==1.3.1, easyocr==1.3.2, easyocr==1.4, easyocr==1.4.1, easyoc
r==1.4.2, easyocr==1.5.0, easyocr==1.6.0, easyocr==1.6.1 and easyocr==1.6.2 because these package versions have conflicting dependencies.
The conflict is caused by:
easyocr 1.6.2 depends on torch
easyocr 1.6.1 depends on torch
easyocr 1.6.0 depends on torch
easyocr 1.5.0 depends on torch
easyocr 1.4.2 depends on torch
easyocr 1.4.1 depends on torch
easyocr 1.4 depends on torch
easyocr 1.3.2 depends on torch
easyocr 1.3.1 depends on torch
easyocr 1.3.0.1 depends on torch
easyocr 1.3 depends on torch
easyocr 1.2.5.1 depends on torch
easyocr 1.2.5 depends on torch
easyocr 1.2.4 depends on torch
easyocr 1.2.3 depends on torch
easyocr 1.2.2 depends on torch
easyocr 1.2.1 depends on torch
easyocr 1.2 depends on torch
easyocr 1.1.10 depends on torch
easyocr 1.1.9 depends on torch
easyocr 1.1.8 depends on torch
easyocr 1.1.7 depends on torch
easyocr 1.1.6 depends on torch
easyocr 1.1.5 depends on torch
easyocr 1.1.4 depends on torch
easyocr 1.1.3 depends on torch
easyocr 1.1.2 depends on torch
easyocr 1.1.1 depends on torch
easyocr 1.1 depends on torch
easyocr 1.0 depends on torch
To fix this you could try to:

*

*loosen the range of package versions you've specified

*remove package versions to allow pip attempt to solve the dependency conflict

ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/topics/dependency-resolution/#dealing-with-dependency-conflicts
I tried to follow the example as indicated in the instructions, but this caused additional errors
python -m pip install "pytest < 4.6" pytest-cov==2.12.1

ERROR: Cannot install pytest-cov==2.12.1 and pytest<4.6 because these package versions have conflicting dependencies.
The conflict is caused by:
The user requested pytest<4.6
pytest-cov 2.12.1 depends on pytest>=4.6
To fix this you could try to:

*

*loosen the range of package versions you've specified

*remove package versions to allow pip attempt to solve the dependency conflict

ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/topics/dependency-resolution/#dealing-with-dependency-conflicts
Maybe there is some solution to this error? Thanks


text:
Q: How to check why file is not opened? std::ifstream fin;
fin.open("file.txt", std::ios::in);
std::cout << fin.is_open();

This code prints false so the file is not opened. How to check why is it. Maybe get error message from fin object? I am guessing the reason is that the file is opened already for writing. But I want to open it for reading. Is it possible to open a file both for reading and writing.?
I am using linux. With strerror(errno) I get the error No such file or directory but I the file exists. Maybe the error is because it is opened already using other object?
It is already opened using C API, therefore fin cant open it. How can I open file which already is opened?

A: The standard specifies that there is a preprocessor symbol
errno, which expands to something which references a (thread
local) int, in which system functions are expected to put an
extended error code.  It also defines a function strerror,
which allow recovering a char const* with a text message,
given this number (but unlike errno, that function is not
guaranteed to be thread safe).
The standard does not place any requirements on filebuf to
use errno, at least not in the case of open, but in
practice, filebuf will invoke lower level functions which will
(hopefully) use errno.  (This is required by Posix, where all
of the system calls set errno in case of error.  I'm less sure
about Windows.)
As for bi-directional access: it's probably a bad idea, but...
filebuf is always potentially bidirectional, but ifstream
won't define any << operators, and ofstream won't define any
>> operators, so you might want to use std::fstream.  If you
want to be able to seek, you'll also want to open the file in
binary mode; otherwise, you can only seek to places you've been
to before, and memorized the position.  If you want to read what
you've just written, a better solution would be to close the
output, then open it for reading.

A: Answer Q#1: errno and also GetLastError() hold the last error information. For getting the string message for the error use: strerrno(errno).
Answer Q#2: To open it for both read/write you need to use a fstream (not ostream or istream) class and set the open mode to std::ios::in | std::ios::out.

A: Yes. you should use fstream instead of ifstream or ofstream. please refer to link below:
http://www.cplusplus.com/doc/tutorial/files/


text:
Q: Need help with Android TableLayout alignment I'm trying to build a calculator layout using TableLayout, but the last two rows aren't aligning with the rest of the layout. Is there something wrong with my layout XML?
What I'm trying to do would be easier to accomplish in HTML (<td> with colspan or rowspan), so should I try converting this into a WebView?
Code is as follows: (Screenshot)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <EditText
        android:id="@+id/EditText01"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent" />
    <TableLayout
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:stretchColumns="*">
        <TableRow
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1">
            <Button
                android:id="@+id/Button08"
                android:textSize="16pt"
                android:text="^"
                android:layout_weight="1"
                android:layout_height="fill_parent"
                android:layout_width="wrap_content" />
            <Button
                android:id="@+id/Button09"
                android:text="÷"
                android:textSize="16pt"
                android:layout_height="fill_parent"
                android:layout_weight="1"
                android:layout_width="wrap_content" />
            <Button
                android:id="@+id/Button10"
                android:text="×"
                android:textSize="16pt"
                android:layout_height="fill_parent"
                android:layout_weight="1"
                android:layout_width="wrap_content" />
            <Button
                android:id="@+id/Button11"
                android:textSize="16pt"
                android:text="-"
                android:layout_weight="1"
                android:layout_height="fill_parent"
                android:layout_width="wrap_content" />
        </TableRow>
        <TableRow
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="2">
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:orientation="vertical"
                android:layout_weight="1">
                <Button
                    android:id="@+id/Button01"
                    android:text="7"
                    android:textSize="16pt"
                    android:layout_weight="1"
                    android:layout_height="wrap_content"
                    android:layout_width="fill_parent" />
                <Button
                    android:layout_height="wrap_content"
                    android:textSize="16pt"
                    android:text="4"
                    android:id="@+id/Button05"
                    android:layout_weight="1"
                    android:layout_width="fill_parent" />
            </LinearLayout>
            <LinearLayout
                android:layout_height="fill_parent"
                android:orientation="vertical"
                android:layout_weight="1"
                android:layout_width="fill_parent">
                <Button
                    android:id="@+id/Button02"
                    android:layout_height="wrap_content"
                    android:text="8"
                    android:textSize="16pt"
                    android:layout_weight="1"
                    android:layout_width="fill_parent" />
                <Button
                    android:layout_height="wrap_content"
                    android:textSize="16pt"
                    android:text="5"
                    android:id="@+id/Button06"
                    android:layout_weight="1"
                    android:layout_width="fill_parent" />
            </LinearLayout>
            <LinearLayout
                android:layout_height="fill_parent"
                android:orientation="vertical"
                android:layout_weight="1"
                android:layout_width="fill_parent">
                <Button
                    android:id="@+id/Button03"
                    android:text="9"
                    android:textSize="16pt"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1" />
                <Button
                    android:textSize="16pt"
                    android:text="6"
                    android:id="@+id/Button07"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1" />
            </LinearLayout>
            <Button
                android:id="@+id/Button04"
                android:text="+"
                android:textSize="16pt"
                android:layout_height="fill_parent"
                android:layout_width="fill_parent"
                android:layout_weight="1" />
        </TableRow>
        <TableRow
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="2">
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:orientation="vertical"
                android:layout_weight="2">
                <LinearLayout
                    android:layout_weight="1"
                    android:orientation="horizontal"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content">
                    <Button
                        android:id="@+id/Button02"
                        android:textSize="16pt"
                        android:layout_weight="1"
                        android:layout_width="fill_parent"
                        android:layout_height="fill_parent"
                        android:text="1" />
                    <Button
                        android:textSize="16pt"
                        android:id="@+id/Button06"
                        android:layout_weight="1"
                        android:layout_width="fill_parent"
                        android:layout_height="fill_parent"
                        android:text="2" />
                </LinearLayout>
                <Button
                    android:id="@+id/Button01"
                    android:layout_height="wrap_content"
                    android:textSize="16pt"
                    android:layout_weight="1"
                    android:layout_width="fill_parent"
                    android:text="0" />
            </LinearLayout>
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:orientation="vertical"
                android:layout_weight="1">
                <Button
                    android:id="@+id/Button03"
                    android:textSize="16pt"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="3" />
                <Button
                    android:textSize="16pt"
                    android:id="@+id/Button07"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="." />
            </LinearLayout>
            <Button
                android:id="@+id/Button04"
                android:textSize="16pt"
                android:layout_height="fill_parent"
                android:layout_width="fill_parent"
                android:layout_weight="1"
                android:text="=" />
        </TableRow>
    </TableLayout>
</LinearLayout>

A: Your final TableRow has three cells (i.e., immediate children). The rest have four. Hence, they're not going to align unless you put an android:layout_span attribute in there somewhere to indicate which cell is absorbing the fourth.


text:
Q: Setting class for BODY in index.html programmatically in React app I have a pretty standard React app.
Up until now, I had set a class for my  tag in the index.html that rendered a nice background that looked like this:
.
Now, I'd like to set the class for the  tag programmatically based on URL.
Specifically, if the current URL is http OR https://{host}/public, I want to set the class to
.
This should work in production as well as locally while I'm developing the app. So the URL could be:
http://localhost:3000/public
or the actual production URL https://myapp.com/public.
I'd appreciate some pointers on this. Thanks!

A: So, to answer your question, you can access the body using document.body and access its classes using document.body.classList, so you could use that to do something like document.body.classList.toggle("some-class"). And you can access the current url using window.location.href or in this case it might work better to use location.pathname.
But a better answer would be that this kind of scripting is pretty anti-pattern for React. The more React-y solution would be something like having a class on your main component that you change based on a state. Something like:
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { backgroundClass: "bg-123" }
  }
  render() {
    return (

...

    );
  }
  // This would be whatever event happens in your app that should cause the background to change
  handleSomeEvent() {
    this.setState({
      backgroundClass: "bg-456",
    });
  }
}


text:
Q: split and arrange string column data New to R, so I'm a bit lost.
I have a data set with various variables including the following column "drink_daily":
drink_daily <- c("(ID 3) Cola & (ID 1) Sprite",
  "(ID 1) Sprite & (ID 3) Cola",
  "(ID 2) water & (ID 3) Cola & (ID 4) Other",
  "(ID 3) Cola & (ID 1) Sprite & (ID 2) water")

etc.
I need to end up with something like this in the dataframe:
[1] "1" & "3"
[2] "1" & "3"
[3] "2" & "3" & "4"
[4] "1" & "2" & "3"

*

*a) I would like to arrange for all the string to be in alphabetical (1-4) order

*b) split the strings within the column to 4 variables

*c) re code to text to numbers (1->4)

*d) merger the 4 columns back into one

A: You can get some help from the stringr and purrr libraries. For example
library(purrr)
stringr::str_match_all(drink_daily, "\\(ID (\\d+)\\)") %>%
  map(function(x) x[,2]) %>%
  map(as.numeric) %>%
  map(sort) %>%
  map_chr(paste, collapse=" & ")
# [1] "1 & 3"     "1 & 3"     "2 & 3 & 4" "1 & 2 & 3"

We use str_match_all to extract the number inside the string "(ID #)" and then sort those and paste them back together.

A: Justo to introduce stringi package which makes dealing with strings a bit easier (although same structure as @Mr.Flick's answer),
library(stringi)

sapply(stri_extract_all_regex(drink_daily, '\\d+'), function(i)
                                              paste(sort(as.numeric(i)), collapse = ' & '))

#[1] "1 & 3"     "1 & 3"     "2 & 3 & 4" "1 & 2 & 3"

A: I came up with something which is not very pretty - partly because R may not be the best tool to do this with - but it does the trick.
Here, strsplit is used to break up the blocks separated by '&'.
gsub strips the brackets and 'ID'.
as.numeric turns it into numbers (alternative: as.integer).
sort does not need further explanation
The result is a list of vectors with all IDs sorted. Names of list items are the original items
df <- c("(ID 3) Cola & (ID 1) Sprite",
        "(ID 1) Sprite & (ID 3) Cola",
        "(ID 2) water & (ID 3) Cola & (ID 4) Other",
        "(ID 3) Cola & (ID 1) Sprite & (ID 2) water")

df2 <- sapply(df,function(x) strsplit(x,split='& *'))

result <- lapply(df2, function(x) {
    sort(as.numeric(gsub(').*','',gsub('\\(ID ','',x))))
})

## Show result:
result
 $`(ID 3) Cola & (ID 1) Sprite`
[1] 1 3

 $`(ID 1) Sprite & (ID 3) Cola`
[1] 1 3

 $`(ID 2) water & (ID 3) Cola & (ID 4) Other`
[1] 2 3 4

 $`(ID 3) Cola & (ID 1) Sprite & (ID 2) water`
[1] 1 2 3


text:
Q: Spell Checker using Ternary Search tree I made a spell checker using Ternary search tree (TST).
Can anybody tell me how to find the next possible word in the TST?
eg: If i want to search the word "Manly" in spell checker and if the word is not present in the TST, so that it outputs near words like this:
DO YOU MEAN: "Man" "Mango" .
Here is the code for implementing ternary search tree.
Can any body please modify to find nearest possible word.
http://www.geeksforgeeks.org/ternary-search-tree/

A: A spell-checker would probably want to find the nearest matches to a target word, rather than words which happen to have the same prefix. TSTs are good at finding prefixes, but they're not going to help you much if you want to find similar words.
In your example (assuming that "manly" is not in your dictionary, although it is a word), the suggestion "mainly" is much more likely than "mango", but it won't be found by a scan starting with the longest matching prefix.
However, if you want the scan starting at the longest match prefix:
1) Modify searchTST so that it returns a struct Node*, and replace the last else clause with:
else if (*(word+1) == '\0')
  return root;
else {
  struct Node* child = searchTST(root->eq, word+1);
  return child ? child : root;
}

2) searchTST will now return the root for the longest-matching prefix to the target. The caller will have to check whether the returned Node's isEndOfString flag is set.
3) You can use something like traverseTST on the node returned by searchTST in order to produce all the words starting with that prefix.

A: You can try a wildcard. For example replace somewhere in your search word a letter with a wildcard then split the word into two substrings and insert them into the TST. Then search for all patterns and not only the exact match. It works by createing every prefices of the dictionary word. But I recommend to try the aho-corasick algorithm with a TST.


text:
Q: Nonlinear solvers cant deal with NaN values I've a Problem that runs perfectly fine with linear and nonlinear solvers (with a fixed size of the input parameter). I then modified it so that the size of the input parameter can be a variable too. I did this by defining the largest size the vector can take and setting all non used entries to float('nan'). This still runs well with the Linear Solvers and yields the same results as the case with fixed input size. However, all nonlinear solvers reset the value of this input parameter to ones. The solver then converges to a trivial case set by these inital values.
I think this could amount to a bug since the linear solvers work fine with my new problem.
Any ideas? Thanks.

A: Did you try using zeros instead of NaN? I am not sure how safely you can propagate NaN through a general nonlinear solver.