text:
Q: Need help pausing tilt.js glare while the card flips over I'm making a collectible card game this is my first HTML, CSS and JS project. So far I've managed to get the cards to flip over and added tilt.js into my project however the built in glare doesn't "pause" whilst card is flipping so as it flips you are left with faint white box until the card flips fully which doesn't look nice at all.
I thought to myself that I could make an if statement saying something along the lines of "if card not 'flat' glare=false" but I have no idea how to put that into JS, if anyone can help or if anyone has another solution would be appreciated :)

function flip(event) {
  var element = event.currentTarget;
  if (element.className === "card") {
    if (element.style.transform == "rotateY(180deg)") {
      element.style.transform = "rotateY(0deg)";
    } else {
      element.style.transform = "rotateY(180deg)";
    }
  }
};

var VanillaTilt = (function() {
  'use strict';

  /**
   * Created by Sergiu Șandor (micku7zu) on 1/27/2017.
   * Original idea: https://github.com/gijsroge/tilt.js
   * MIT License.
   * Version 1.7.0
   */

  class VanillaTilt {
    constructor(element, settings = {}) {
      if (!(element instanceof Node)) {
        throw ("Can't initialize VanillaTilt because " + element + " is not a Node.");
      }

      this.width = null;
      this.height = null;
      this.clientWidth = null;
      this.clientHeight = null;
      this.left = null;
      this.top = null;

      // for Gyroscope sampling
      this.gammazero = null;
      this.betazero = null;
      this.lastgammazero = null;
      this.lastbetazero = null;

      this.transitionTimeout = null;
      this.updateCall = null;
      this.event = null;

      this.updateBind = this.update.bind(this);
      this.resetBind = this.reset.bind(this);

      this.element = element;
      this.settings = this.extendSettings(settings);

      this.reverse = this.settings.reverse ? -1 : 1;
      this.glare = VanillaTilt.isSettingTrue(this.settings.glare);
      this.glarePrerender = VanillaTilt.isSettingTrue(this.settings["glare-prerender"]);
      this.fullPageListening = VanillaTilt.isSettingTrue(this.settings["full-page-listening"]);
      this.gyroscope = VanillaTilt.isSettingTrue(this.settings.gyroscope);
      this.gyroscopeSamples = this.settings.gyroscopeSamples;

      this.elementListener = this.getElementListener();

      if (this.glare) {
        this.prepareGlare();
      }

      if (this.fullPageListening) {
        this.updateClientSize();
      }

      this.addEventListeners();
      this.updateInitialPosition();
    }

    static isSettingTrue(setting) {
      return setting === "" || setting === true || setting === 1;
    }

    /**
     * Method returns element what will be listen mouse events
     * @return {Node}
     */
    getElementListener() {
      if (this.fullPageListening) {
        return window.document;
      }

      if (typeof this.settings["mouse-event-element"] === "string") {
        const mouseEventElement = document.querySelector(this.settings["mouse-event-element"]);

        if (mouseEventElement) {
          return mouseEventElement;
        }
      }

      if (this.settings["mouse-event-element"] instanceof Node) {
        return this.settings["mouse-event-element"];
      }

      return this.element;
    }

    /**
     * Method set listen methods for this.elementListener
     * @return {Node}
     */
    addEventListeners() {
      this.onMouseEnterBind = this.onMouseEnter.bind(this);
      this.onMouseMoveBind = this.onMouseMove.bind(this);
      this.onMouseLeaveBind = this.onMouseLeave.bind(this);
      this.onWindowResizeBind = this.onWindowResize.bind(this);
      this.onDeviceOrientationBind = this.onDeviceOrientation.bind(this);

      this.elementListener.addEventListener("mouseenter", this.onMouseEnterBind);
      this.elementListener.addEventListener("mouseleave", this.onMouseLeaveBind);
      this.elementListener.addEventListener("mousemove", this.onMouseMoveBind);

      if (this.glare || this.fullPageListening) {
        window.addEventListener("resize", this.onWindowResizeBind);
      }

      if (this.gyroscope) {
        window.addEventListener("deviceorientation", this.onDeviceOrientationBind);
      }
    }

    /**
     * Method remove event listeners from current this.elementListener
     */
    removeEventListeners() {
      this.elementListener.removeEventListener("mouseenter", this.onMouseEnterBind);
      this.elementListener.removeEventListener("mouseleave", this.onMouseLeaveBind);
      this.elementListener.removeEventListener("mousemove", this.onMouseMoveBind);

      if (this.gyroscope) {
        window.removeEventListener("deviceorientation", this.onDeviceOrientationBind);
      }

      if (this.glare || this.fullPageListening) {
        window.removeEventListener("resize", this.onWindowResizeBind);
      }
    }

    destroy() {
      clearTimeout(this.transitionTimeout);
      if (this.updateCall !== null) {
        cancelAnimationFrame(this.updateCall);
      }

      this.reset();

      this.removeEventListeners();
      this.element.vanillaTilt = null;
      delete this.element.vanillaTilt;

      this.element = null;
    }

    onDeviceOrientation(event) {
      if (event.gamma === null || event.beta === null) {
        return;
      }

      this.updateElementPosition();

      if (this.gyroscopeSamples > 0) {
        this.lastgammazero = this.gammazero;
        this.lastbetazero = this.betazero;

        if (this.gammazero === null) {
          this.gammazero = event.gamma;
          this.betazero = event.beta;
        } else {
          this.gammazero = (event.gamma + this.lastgammazero) / 2;
          this.betazero = (event.beta + this.lastbetazero) / 2;
        }

        this.gyroscopeSamples -= 1;
      }

      const totalAngleX = this.settings.gyroscopeMaxAngleX - this.settings.gyroscopeMinAngleX;
      const totalAngleY = this.settings.gyroscopeMaxAngleY - this.settings.gyroscopeMinAngleY;

      const degreesPerPixelX = totalAngleX / this.width;
      const degreesPerPixelY = totalAngleY / this.height;

      const angleX = event.gamma - (this.settings.gyroscopeMinAngleX + this.gammazero);
      const angleY = event.beta - (this.settings.gyroscopeMinAngleY + this.betazero);

      const posX = angleX / degreesPerPixelX;
      const posY = angleY / degreesPerPixelY;

      if (this.updateCall !== null) {
        cancelAnimationFrame(this.updateCall);
      }

      this.event = {
        clientX: posX + this.left,
        clientY: posY + this.top,
      };

      this.updateCall = requestAnimationFrame(this.updateBind);
    }

    onMouseEnter() {
      this.updateElementPosition();
      this.element.style.willChange = "transform";
      this.setTransition();
    }

    onMouseMove(event) {
      if (this.updateCall !== null) {
        cancelAnimationFrame(this.updateCall);
      }

      this.event = event;
      this.updateCall = requestAnimationFrame(this.updateBind);
    }

    onMouseLeave() {
      this.setTransition();

      if (this.settings.reset) {
        requestAnimationFrame(this.resetBind);
      }
    }

    reset() {
      this.event = {
        clientX: this.left + this.width / 2,
        clientY: this.top + this.height / 2
      };

      if (this.element && this.element.style) {
        this.element.style.transform = `perspective(${this.settings.perspective}px) ` +
          `rotateX(0deg) ` +
          `rotateY(0deg) ` +
          `scale3d(1, 1, 1)`;
      }

      this.resetGlare();
    }

    resetGlare() {
      if (this.glare) {
        this.glareElement.style.transform = "rotate(180deg) translate(-50%, -50%)";
        this.glareElement.style.opacity = "0";
      }
    }

    updateInitialPosition() {
      if (this.settings.startX === 0 && this.settings.startY === 0) {
        return;
      }

      this.onMouseEnter();

      if (this.fullPageListening) {
        this.event = {
          clientX: (this.settings.startX + this.settings.max) / (2 * this.settings.max) * this.clientWidth,
          clientY: (this.settings.startY + this.settings.max) / (2 * this.settings.max) * this.clientHeight
        };
      } else {
        this.event = {
          clientX: this.left + ((this.settings.startX + this.settings.max) / (2 * this.settings.max) * this.width),
          clientY: this.top + ((this.settings.startY + this.settings.max) / (2 * this.settings.max) * this.height)
        };
      }

      let backupScale = this.settings.scale;
      this.settings.scale = 1;
      this.update();
      this.settings.scale = backupScale;
      this.resetGlare();
    }

    getValues() {
      let x, y;

      if (this.fullPageListening) {
        x = this.event.clientX / this.clientWidth;
        y = this.event.clientY / this.clientHeight;
      } else {
        x = (this.event.clientX - this.left) / this.width;
        y = (this.event.clientY - this.top) / this.height;
      }

      x = Math.min(Math.max(x, 0), 1);
      y = Math.min(Math.max(y, 0), 1);

      let tiltX = (this.reverse * (this.settings.max - x * this.settings.max * 2)).toFixed(2);
      let tiltY = (this.reverse * (y * this.settings.max * 2 - this.settings.max)).toFixed(2);
      let angle = Math.atan2(this.event.clientX - (this.left + this.width / 2), -(this.event.clientY - (this.top + this.height / 2))) * (180 / Math.PI);

      return {
        tiltX: tiltX,
        tiltY: tiltY,
        percentageX: x * 100,
        percentageY: y * 100,
        angle: angle
      };
    }

    updateElementPosition() {
      let rect = this.element.getBoundingClientRect();

      this.width = this.element.offsetWidth;
      this.height = this.element.offsetHeight;
      this.left = rect.left;
      this.top = rect.top;
    }

    update() {
      let values = this.getValues();

      this.element.style.transform = "perspective(" + this.settings.perspective + "px) " +
        "rotateX(" + (this.settings.axis === "x" ? 0 : values.tiltY) + "deg) " +
        "rotateY(" + (this.settings.axis === "y" ? 0 : values.tiltX) + "deg) " +
        "scale3d(" + this.settings.scale + ", " + this.settings.scale + ", " + this.settings.scale + ")";

      if (this.glare) {
        this.glareElement.style.transform = `rotate(${values.angle}deg) translate(-50%, -50%)`;
        this.glareElement.style.opacity = `${values.percentageY * this.settings["max-glare"] / 100}`;
      }

      this.element.dispatchEvent(new CustomEvent("tiltChange", {
        "detail": values
      }));

      this.updateCall = null;
    }

    /**
     * Appends the glare element (if glarePrerender equals false)
     * and sets the default style
     */
    prepareGlare() {
      // If option pre-render is enabled we assume all html/css is present for an optimal glare effect.
      if (!this.glarePrerender) {
        // Create glare element
        const jsTiltGlare = document.createElement("div");
        jsTiltGlare.classList.add("js-tilt-glare");

        const jsTiltGlareInner = document.createElement("div");
        jsTiltGlareInner.classList.add("js-tilt-glare-inner");

        jsTiltGlare.appendChild(jsTiltGlareInner);
        this.element.appendChild(jsTiltGlare);
      }

      this.glareElementWrapper = this.element.querySelector(".js-tilt-glare");
      this.glareElement = this.element.querySelector(".js-tilt-glare-inner");

      if (this.glarePrerender) {
        return;
      }

      Object.assign(this.glareElementWrapper.style, {
        "position": "absolute",
        "top": "0",
        "left": "0",
        "width": "100%",
        "height": "100%",
        "overflow": "hidden",
        "pointer-events": "none"
      });

      Object.assign(this.glareElement.style, {
        "position": "absolute",
        "top": "50%",
        "left": "50%",
        "pointer-events": "none",
        "background-image": `linear-gradient(0deg, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%)`,
        "width": `${this.element.offsetWidth * 2}px`,
        "height": `${this.element.offsetWidth * 2}px`,
        "transform": "rotate(180deg) translate(-50%, -50%)",
        "transform-origin": "0% 0%",
        "opacity": "0",
      });
    }

    updateGlareSize() {
      if (this.glare) {
        Object.assign(this.glareElement.style, {
          "width": `${this.element.offsetWidth * 2}`,
          "height": `${this.element.offsetWidth * 2}`,
        });
      }
    }

    updateClientSize() {
      this.clientWidth = window.innerWidth ||
        document.documentElement.clientWidth ||
        document.body.clientWidth;

      this.clientHeight = window.innerHeight ||
        document.documentElement.clientHeight ||
        document.body.clientHeight;
    }

    onWindowResize() {
      this.updateGlareSize();
      this.updateClientSize();
    }

    setTransition() {
      clearTimeout(this.transitionTimeout);
      this.element.style.transition = this.settings.speed + "ms " + this.settings.easing;
      if (this.glare) this.glareElement.style.transition = `opacity ${this.settings.speed}ms ${this.settings.easing}`;

      this.transitionTimeout = setTimeout(() => {
        this.element.style.transition = "";
        if (this.glare) {
          this.glareElement.style.transition = "";
        }
      }, this.settings.speed);

    }

    /**
     * Method return patched settings of instance
     * @param {boolean} settings.reverse - reverse the tilt direction
     * @param {number} settings.max - max tilt rotation (degrees)
     * @param {startX} settings.startX - the starting tilt on the X axis, in degrees. Default: 0
     * @param {startY} settings.startY - the starting tilt on the Y axis, in degrees. Default: 0
     * @param {number} settings.perspective - Transform perspective, the lower the more extreme the tilt gets
     * @param {string} settings.easing - Easing on enter/exit
     * @param {number} settings.scale - 2 = 200%, 1.5 = 150%, etc..
     * @param {number} settings.speed - Speed of the enter/exit transition
     * @param {boolean} settings.transition - Set a transition on enter/exit
     * @param {string|null} settings.axis - What axis should be disabled. Can be X or Y
     * @param {boolean} settings.glare - What axis should be disabled. Can be X or Y
     * @param {number} settings.max-glare - the maximum "glare" opacity (1 = 100%, 0.5 = 50%)
     * @param {boolean} settings.glare-prerender - false = VanillaTilt creates the glare elements for you, otherwise
     * @param {boolean} settings.full-page-listening - If true, parallax effect will listen to mouse move events on the whole document, not only the selected element
     * @param {string|object} settings.mouse-event-element - String selector or link to HTML-element what will be listen mouse events
     * @param {boolean} settings.reset - false = If the tilt effect has to be reset on exit
     * @param {gyroscope} settings.gyroscope - Enable tilting by deviceorientation events
     * @param {gyroscopeSensitivity} settings.gyroscopeSensitivity - Between 0 and 1 - The angle at which max tilt position is reached. 1 = 90deg, 0.5 = 45deg, etc..
     * @param {gyroscopeSamples} settings.gyroscopeSamples - How many gyroscope moves to decide the starting position.
     */
    extendSettings(settings) {
      let defaultSettings = {
        reverse: false,
        max: 15,
        startX: 0,
        startY: 0,
        perspective: 1000,
        easing: "cubic-bezier(.03,.98,.52,.99)",
        scale: 1,
        speed: 300,
        transition: true,
        axis: null,
        glare: false,
        "max-glare": 1,
        "glare-prerender": false,
        "full-page-listening": false,
        "mouse-event-element": null,
        reset: true,
        gyroscope: true,
        gyroscopeMinAngleX: -45,
        gyroscopeMaxAngleX: 45,
        gyroscopeMinAngleY: -45,
        gyroscopeMaxAngleY: 45,
        gyroscopeSamples: 10
      };

      let newSettings = {};
      for (var property in defaultSettings) {
        if (property in settings) {
          newSettings[property] = settings[property];
        } else if (this.element.hasAttribute("data-tilt-" + property)) {
          let attribute = this.element.getAttribute("data-tilt-" + property);
          try {
            newSettings[property] = JSON.parse(attribute);
          } catch (e) {
            newSettings[property] = attribute;
          }

        } else {
          newSettings[property] = defaultSettings[property];
        }
      }

      return newSettings;
    }

    static init(elements, settings) {
      if (elements instanceof Node) {
        elements = [elements];
      }

      if (elements instanceof NodeList) {
        elements = [].slice.call(elements);
      }

      if (!(elements instanceof Array)) {
        return;
      }

      elements.forEach((element) => {
        if (!("vanillaTilt" in element)) {
          element.vanillaTilt = new VanillaTilt(element, settings);
        }
      });
    }
  }

  if (typeof document !== "undefined") {
    /* expose the class to window */
    window.VanillaTilt = VanillaTilt;

    /**
     * Auto load
     */
    VanillaTilt.init(document.querySelectorAll("[data-tilt]"));
  }

  return VanillaTilt;

}());
.container {
  width: 305px;
  height: 445px;
  perspective: 1000px;
  padding: 20px;
  float: left;
  margin: 5px;
}

.card {
  transition: transform .5s;
  transform-style: preserve-3d;
  cursor: pointer;
  position: absolute;
}

.front,
.back {
  position: absolute;
  backface-visibility: hidden;
  overflow: hidden;
}

.front {
  background: transparent;
}

.back {
  background: transparent;
  transform: rotateY(180deg);
}

A: You can use toggleAttribute to toggle the data-tilt-glare attribute in the flip function.

document.getElementById("tiltDiv").toggleAttribute("data-tilt-glare")

Note: I have added an ID to the .container div and used that to select the element with document.getelementbyid

So, your flip function should be like this:
function flip(event) {
  document.getElementById("tiltDiv").toggleAttribute("data-tilt-glare");

  var element = event.currentTarget;
  if (element.className === "card") {
    if (element.style.transform == "rotateY(180deg)") {
      element.style.transform = "rotateY(0deg)";
    } else {
      element.style.transform = "rotateY(180deg)";
    }
  }
};


text:
Q: Getting characters in textarea on keyup I want to get the number of characters in a textarea. This needs to update at every keystroke. So i used this simple function:
$(document).on('keyup', 'textarea', function () {
    var count = $(this).val().length;
    console.log(count);
});

Now the problem is, If i try to type very fast, the count repeats. We can see the repetition in console. What is the reason behind this repetition ? Also how can i avoid it ?
Here's a fiddle: https://jsfiddle.net/w6mzzfd8/
Thanks !

A: As per Docs:

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except in the case of key repeats. If the user presses and holds a key, a keydown event is triggered once, but separate keypress events are triggered for each inserted character. In addition, modifier keys (such as Shift) trigger keydown events but not keypress events.

Solution:
Use keydown instead of keyup
Code:
$(document).on('keydown', 'textarea', function () {
 var count = $(this).val().length;
 console.log(count);
});

Working Demo

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fixed norm problem for analytic functions Hi there,
I have the following problems on my hand:
Given arbitrary positive sub-harmonic function $l(x,y)$ on plane, for all analytic functions: $f=a(x,y)+ib(x,y)$ on complex plane, consider the equation:
$|f|^2=l$, i.e. $a^2+b^2=l$
1) for what kind of $l(x,y)$, the equation has $C^2$ solution?
2) for what kind of $l(x,y)$, the number of solutions is finite, after quotient of $S^1$ action: $e^{i\theta}\cdot f$ ?
Thanks!

A: For this equation to have solutions, it is not enough that $l$ is subharmonic. It must be
logarithmically subharmonic which means that $\log l$ is subharmonic. Now if $l$ is logarithmically
subharmonic, the nesessary and sufficient condition that $f$ exists in a simply connected domain
is that the measure $(2\pi)^{-1}\Delta\log l$ is discrete and integer-valued.
If the solution exists it is always unique up to a constant factor $e^{i\theta}$.
EDIT. To prove sufficiency, one uses the Weierstrass representation. Suppose that $l$ is logarithmically subharmonic and $(2\pi)^{-1}\Delta\log l$ is a discrete integer-valued measure with
atoms $m_k$ at the points $a_k$. Consider the Weierstrass product $f$ with zeros $a_k$ of
multiplicity $m_k$. This $f$ is an entire function. Now $u:=\log l-\log|f|$ is harmonic,
by construction. Let $v$ be such harmonic function that $g:=u+iv$ is entire.
Then $l=|f\exp g|.$


text:
Q: Unitary Bose gas A unitary Bose gas (more about it [here]) is defined to occur when the scattering length diverges.
What I don't understand, however, is which quantity/matrix is actually unitary?
I mean, they could have called it "divergent", "critical" etc. but they named it "unitary", which suggests it has a connection with the physical meaning of unitarity.

A: The term unitary gas refers to the regime where the scattering cross-section is the largest possible, under the unitarity constraint: the scattering matrix (i.e. the time-evolution operator) must be unitary. The terminology derives from unitarity-limited. One also refers to the regime of maximal cross-section simply as unitarity; for example, "the scattering length diverges at unitarity". For $s$-wave scattering, which is the most relevant at low temperatures, the total cross-section at unitarity is
$$ \sigma(k) = \frac{4\pi}{k^2},$$
where $\hbar k$ is the momentum of the scattered particles.


text:
Q: How To Retrieve All Properties of An Arbitrary List of Wikidata Items I have a list of Wikidata items. This list is arbitrary ie the items are not connected in any known way. eg. a random list:
Q5
Q10
Q11
Q123

I'd like to retrieve all properties of these entities, with one query. Such that I can see entities, properties and values of those properties all in one table like:
itemName.  propertyName.  valueName.
Q5.        P2.            Q1002.
...

How do I do this?

A: There were already good answers in the comments, but I'll add one more. When you want to run the same query for a list of items/inputs, then a VALUES clause outside of the SELECT is a good option:
SELECT * {
  ?itemName ?propertyName ?valueName
}
VALUES ?itemName {
  wd:Q5
  wd:Q10
  wd:Q11
  wd:Q123
}


text:
Q: Get the name of a columns default constraint on SQL Server 2000? How do I get the name of a columns default contraint on a SQL Server 2000 installation? As far as I know sys.default_constraints is not available. Its different on every DB, the structure is like DF_table_column__3DE8FB0E for example.
Thanks :)

A: Try using INFORMATION_SCHEMA, SQL Server's implementation of the SQL 92 self-describing features.
SELECT * FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE


text:
Q: Как запустить функцию в python на постоянное выполнение при обновление информации У меня есть код, который сначала вытягивает у пользователя телеграм бота изображение, потом прогоняет его через pytesseract и на выходе (на данный момент) печатает результат в консоли, но при попытке скинуть второе изображение, файл меняется, но функция не выводит результат со второй картинки, подскажите, как правильно сделать этот цикл
bot = telebot.TeleBot("id")

@bot.message_handler(content_types=['photo'])
def photo(message):
     fileID = message.photo[-1].file_id
     file_info = bot.get_file(fileID)
     downloaded_file = bot.download_file(file_info.file_path)
     with open("image.jpg", 'wb') as new_file:
         new_file.write(downloaded_file)

img = Image.open("image.jpg")
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
a = pytesseract.image_to_string(img)
string = a
operations = ['+', '-', '/' ,'*']
operation = ''
counter = 0
one_number = list()
two_number = list()

l = [i for i in string]

for elem in l:
    if elem in operations:
        operation = elem
        counter += 1
    elif elem.isdigit() and operation == '':
        one_number.append(elem)
    elif elem.isdigit() and operation != '':
        two_number.append(elem)

if counter == 1 and one_number != [] and two_number != []:     # Проверка, что бы был один мат оператор, и по обе стороны от него были цифры
    if operation == '+':
        result = int(''.join(one_number)) + int(''.join(two_number))
    if operation == '-':
        result = int(''.join(one_number)) - int(''.join(two_number))
    if operation == '/':
        result = int(''.join(one_number)) / int(''.join(two_number))
    if operation == '*':
        result = int(''.join(one_number)) * int(''.join(two_number))
    print(result)
else:
        print('Не расспознано')
bot.polling(none_stop=True, interval=0)

A: Предположу, что проблема в том, что код по преобразовании картинки находится вне функции, поэтому программа до нее не доходит.

A: сдвинуть на 4 пробела перобразование image,
    a = pytesseract.image_to_string(img)
    string = a

заменить на
    string = pytesseract.image_to_string(img)

и подсказывали что преобразование без списков лучше. работать со строкой


text:
Q: TextView does not display text I use TextView to display a photo, everything works fine, but why, on iPhone, plus the version does not display text with photos, who knows what could be the reason?
override func viewDidLoad() {
        super.viewDidLoad()

         textView.attributedText = detail?.text?.html2AttributedString
         textView.attributedText.correctimage(textView: text, SV: view)
    }

downloads photos and processes html text
extension String {
var html2AttributedString: NSAttributedString? {
    do {
        return try NSAttributedString(data: Data(utf8), options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
    } catch {
        print("error:", error)
        return nil
    }

}
var html2String: String {
    return html2AttributedString?.string ?? ""
}

}

Find photos in the text and set them the size
extension NSAttributedString {
func correctimage(textView:UITextView, SV:Any){

    textView.font = UIFont(name: "roboto-light", size: 19)

    textView.attributedText.enumerateAttribute(NSAttributedStringKey.attachment, in: NSRange(location: 0, length: textView.attributedText.length), options: [], using: {(value,range,stop) -> Void in
        if (value is NSTextAttachment) {
            let attachment: NSTextAttachment? = (value as? NSTextAttachment)

            if ((attachment?.image) != nil) {

                attachment?.bounds.origin = CGPoint(x:  (SV as AnyObject).frame.size.width - 20, y: 20)
                attachment?.bounds.size = CGSize(width: (SV as AnyObject).frame.size.width - 25, height: 250)

            }
        }
    })

}

EDIT:
my code works on all iphone models but not on the emulator with plus models

A: Check this out, My side working for me
func convertToInlineImageFormat(htmlStrr:String) -> NSMutableAttributedString {

        let htmlStringgg = htmlStrr as String
        let content = try! NSMutableAttributedString(
            data: htmlStringgg.data(using: String.Encoding.unicode, allowLossyConversion: true)!,
            options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil)
        //        content.addAttribute(NSForegroundColorAttributeName, value: UIColor.white, range: NSRange(location: 0, length: htmlStrr.length))

        // Resizing Inline images
        content.enumerateAttribute(NSAttachmentAttributeName, in: NSMakeRange(0, content.length), options: NSAttributedString.EnumerationOptions.init(rawValue: 0), using: { (value, range, stop) -> Void in
            if let attachement = value as? NSTextAttachment {
                let image = attachement.image(forBounds: attachement.bounds, textContainer: NSTextContainer(), characterIndex: range.location)
                let screenSize: CGRect = UIScreen.main.bounds
                if (image?.size.width)! > screenSize.width - 2 {
                    let newImage = image?.resizeImage(scale: (screenSize.width - 2)/(image?.size.width)!)
                    let newAttribut = NSTextAttachment()

                    newAttribut.image = newImage
                    content.addAttribute(NSAttachmentAttributeName, value: newAttribut, range: range)

                }
            }
            // ARTICLE DESCRIPTION FONT
            //            let replacementFont = Contants.descFont

            let fontSizeDescribtion = UserDefaults.standard.float(forKey: "FontSize")
            var fontSize :Float = 0.0
            if fontSizeDescribtion == 0{
                fontSize = 21
            }else{
                fontSize = Float(fontSizeDescribtion)
            }
            let fontDesc =  UIFont(name: Contants.abiramiFont, size: CGFloat(Float(fontSize)))

            content.addAttribute(NSFontAttributeName, value: fontDesc!, range: NSRange(location: 0, length: content.length))
            content.addAttribute(NSForegroundColorAttributeName, value: UIColor.black, range: NSRange(location: 0, length: content.length))

        }) // Content block

        return content
    }

Use like below:
 DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            self.descriptionTextView.attributedText = self.convertToInlineImageFormat(htmlStrr: currentData["ArticleXML"] as! String)
        }


text:
Q: Which background color to use for Android Market's no-alpha "Hi Resolution Application Icon" Now the Android Market requires developers to upload a:

Hi Resolution Application Icon, 512w x 512h, 24 bit PNG or JPEG (no alpha)

Problem: my application's icon is not a square, and because alpha is forbidden I will have to fill with some color like black. Or maybe white.
Which color should I choose?

A: According to the mail sent to Android developers, "the Android icon design guidelines located at http://developer.android.com/guide/practices/ui_guidelines/icon_design.html apply."
So you can use a transparent background.
Later edit: Roman Nurik (Android developer advocate @ Google) said on Twitter that it's ok to use 32-bit PNG: http://twitter.com/romannurik/status/8375870980886528.


text:
Q: How to add a JWT to header after successful login I am building a web app using Symfony 4 and I am trying to implement the back end as a REST API.
As part of the login process, I have created an endpoint that returns a JWT upon receiving a valid username and password. I then save the JWT to local storage in the browser as so:
$(document).ready(function() {

$('.js-login-form').submit(function (e) {
    e.preventDefault();

    let username = $('#_username').val();
    let password = $('#_password').val();
    let data = JSON.stringify({_username: username, _password: password});

    $.ajax({
        method: 'POST',
        url: '/api/tokens',
        contentType: "application/json",
        dataType: 'json',
        data: data,
        success: function(data) {
            localStorage.setItem('token', data.token);
            // Add Header to the request Authorization: "Bearer " . data.token
            window.location='/app';
        },
        error: function(jqXHR) {
            var errorData = JSON.parse(jqXHR.responseText);
            console.log(errorData);
        }
    });
});
});

My question is how I can add the JWT to the header so I can redirect the user to the password protected area. My guard authenticator will then validate the token accordingly.
Many thanks

A: Do you mean add JWT to the header in backend?
If yes, you can create middleware to check user is auth or not.
This is example :
// add jwt module
const jwt = require('jsonwebtoken');

async function isAuthValid(req,res,next) {
  try {
    // check header
    let token = req.headers['authorization'];
    if (token.startsWith('Bearer ')) {
      // check token type
      token = token.slice(7, token.length).trimLeft();
    } else {
      return res.send('wrong token type');
    }

    if (token) {
      // ? check token
      let verifiedUser = await jwt.verify(token, 'somesecret', (err, decoded) => {
        if (err) {
          return res.send(err.message);
        } else {
          return decoded
        }
      });
      req.authUser = verifiedUser
      next();
    }
  } catch (err) {
    return res.send('no token provided');
  }
}

module.exports = isAuthValid

Registering as middleware on your route
const express = require('express');
const isAuthValid = require('./checkAuthUser.js');

const app = express();

app.get('/myRoute', isAuthValid, (req,res) => {
  return res.send('protected endpoint')
});


text:
Q: Explanation why Height=100% breaks design I have a problem with the Height Tag in CSS. I want the page to be displayed without any scrollbars and just can't figure out why when i change "height" in the body tag from 99% to 100% suddenly scrollingbars appear and break the design.
I want to know why this happens and what's the reason for it.
thanks!
<!DOCTYPE html>

<title>XYZ</title>

XYZ

LOREM

            XYZ is a project by XZY.  |
            Website Information — info@info.com

    Open by Appointment     sponsored by XYZ

A: There is also bottom margin on the body.
body {
    height: 100%;
    margin: 0 0 0 20px;
}

Though you should consider using a css reset such as eric meyers reset or normalize

A: Replacing your body style with this should solve the issue :
body {
height: 100%;
margin-left: 20px;
margin:0px;

}

A: It breaks the page because you use 99% of the page, then you move everything to the right of 20px. it moves the 99% outside and use more. here is the solution, i think both of them work :
body {
    height: 100%;
    margin-left: 20px;
    margin-right: -20px;
    margin-top:0px;
}

or
body {
    height: 100%;
    padding-left: 20px;
    padding-right: -20px;
    margin-top:0px;
}


text:
Q: Problems using edit text with numbers in java I am studying java on my own and I am creating an app that calculates areas, but when I enter a 1-digit number the app says I didn't put anything. But it works with decimals and 2-digit numbers. Can anyone help me to figure out why this is happening? That is the code:
public void calcRetangulo (View view){
    EditText compRet = (EditText) findViewById(R.id.compRetangulo);
    EditText ladoRet = (EditText) findViewById(R.id.ladoRetangulo);

    if (compRet.getText().toString().matches("") || compRet.getText().toString().matches(".") && ladoRet.getText().toString().matches("") || ladoRet.getText().toString().matches(".")){

        LayoutInflater er = getLayoutInflater();

        View erro = er.inflate(R.layout.erro, null);

        erro.findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                alertaErro.dismiss();
            }
        });

        AlertDialog.Builder builderErro = new AlertDialog.Builder(this);
        builderErro.setView(erro);
        alertaErro = builderErro.create();
        alertaErro.show();

        compRet.setText("");
        ladoRet.setText("");

    } else{

        float comp = Float.parseFloat(compRet.getText().toString());
        float lado = Float.parseFloat(ladoRet.getText().toString());

        float area = comp * lado;

        LayoutInflater li = getLayoutInflater();

        View result = li.inflate(R.layout.layout, null);
        final TextView resultado = (TextView) result.findViewById(R.id.resultado);

        resultado.setText(String.format("A = c x l\nA = "+ comp +" x " + lado +"\nA = "+ area));

        result.findViewById(R.id.fechar).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                alertaResult.dismiss();
                resultado.setText("");

            }
        });

        AlertDialog.Builder builderResult = new AlertDialog.Builder(this);
        builderResult.setView(result);
        alertaResult = builderResult.create();
        alertaResult.show();

        compRet.setText("");
        ladoRet.setText("");
    }
}

A: String.matches in java is a regex.  So matches(".") will match any 1 digit string (. is a wildcard in regex).  If you want to match the literal string ".",  use matches("\.")

A: Use the length of the EditText Text.
matches() is for regex expression.

A: You should use editText.getText().toString().contains("What ever you want")


text:
Q: how to denormalize ranges and store them in a data warehouse? My custom web servers report session information in the form of a wall clock timestamp (start of session) and the number of wall click seconds the session lasted.
I want to store this information in a data warehouse (MySQL + start schema) in a way that will allow me to for example query the number of sessions for a particular entity at a specific time.  A requirement is that we must be able to extract time series data that will be feed to a graph.
Is there any other way to store the data than to insert a row for every absolute second of the session?

A: I would say that the simplest way is to store one row per session with StartTime, EndTime in the fact table.
Let's say we have factSession with:
  (
   ...
  ,SessionID int
  ,StartTime datetime
  ,EndTime datetime
  ,EntityID int
   ...
  ) ;

and
TimeSeries TABLE ( TimePoint datetime ) ;

You can:
SELECT  t.TimePoint
       ,f.EntityID
       ,COUNT(f.SessionID) AS cnt
FROM    TimeSeries AS t
        LEFT JOIN factSessions AS f ON ( f.StartTime <= t.TimePoint
                                          AND t.TimePoint <= f.EndTime
                                        )
GROUP BY t.TimePoint ,f.EntityID
ORDER BY t.TimePoint


text:
Q: Difference between NULL, 0 ,False and ''? What is the exact difference between null, 0, false, and an empty string in PHP? Is null similar to None in python?

A: Well, after massive comments and then poof deletion of them... may as well try to help you out.
null is the absence of value.
0 can be a numeric value, or a representation of a boolean FALSE, or a string.  PHP doesn't really have variable typing, so depending on what you are checking for using ==0 or ===0 or ==false or ===false may be appropriate.
You may want to read over this - https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/  as well as the PHP manual for isset() and empty()


text:
Q: AppleScript SL to ML Issue (compatibility error?) I've written the following script in Applescript in Snow Leopard, and I tried to use it in Mountain Lion, but to no avail (doesn't work). The script watches a folder for added files, and if the filetype matches, it will scp it to a server.
It runs great, no errors on Snow Leopard. When it's run in ML it spits back the error (in console):
AppleScript Runner: CPSGetFrontProcess(): This call is deprecated and should not be called anymore.
I'm almost positive this has something to do with the way the script is written. I have tried copying & pasting into a new script in mountain lion, and then saving that. Doesn't work either.
Here is the code itself, any insight as to what call is working wrong?
on adding folder items to this_folder after receiving the_files

--set login vars
set fileExt to "zip"
set scpIP to "blah"
set scpUser to "blah"
set scpDest to "/home/blah"
set scpPort to "1234"

--repeat on each file that is added to the folder
repeat with each_file in the_files
    set filename to name of (info for each_file)
    tell application "Finder"
        --check extension, if match, scp. else, error.
        if name extension of each_file is fileExt then
            try
                do shell script "scp -p" & scpPort & " " & scpUser & "@" & scpIP & ":" & scpDes
                move each_file to trash
            end try
        end if
    end tell
end repeat

end adding folder items to

A: this might fix it, failing that can you post the contents of the plist files from ~/Library/LaunchAgents
on adding folder items to this_folder after receiving the_files

--set login vars
set fileExt to "zip"
set scpIP to "blah"
set scpUser to "blah"
set scpDest to "/home/blah"
set scpPort to "1234"

--repeat on each file that is added to the folder
repeat with each_file in the_files
    set filename to name of (info for each_file)
    --check extension, if match, scp. else, error.
    if name extension of each_file is fileExt then
        try
            do shell script "scp -p" & scpPort & " " & scpUser & "@" & scpIP & ":" & scpDes
            tell application "System Events" to move each_file to trash
        end try
    end if
end repeat
end adding folder items to


text:
Q: Different results in Sklearn linear regression with same dataset (UCI student performance dataset) I am getting different outputs during predicting the values. The output in the train_linear_regression_model() is correct but when i run fetch_prediction_data() for single user it is giving very wrong values.
Code
def get_dataset_for_linear():
    efficacy_data = models.StudentEfficacy.objects.all()

    features = efficacy_data.values_list('father_education', 'internet_facility', 'study_time',
                                                 'paid_tuition', 'past_failures', 'free_time',
                                                 'extra_curricular_activities',
                                                 'absences', 'past_marks', 'past_marks1', 'class_engagement', 'health')
    labels = efficacy_data.values_list('predictions')

    np_features_avg = np.array(features)
    np_labels_avg = np.array(labels)

    return np_features_avg, np_labels_avg

def train_linear_regression_model():
    test_features = list()
    test_labels = list()

    feature_dataset, label_dataset = get_dataset_for_linear()

    best_accuracy = 0
    for i in range(10000):
        train_features, test_features, train_labels, test_labels = \
            sklearn.model_selection.train_test_split(feature_dataset, label_dataset, test_size=0.9)

        mdl_linear_regression = linear_model.LinearRegression()

        mdl_linear_regression.fit(train_features, train_labels)
        accuracy = mdl_linear_regression.score(test_features, test_labels)

        if best_accuracy < accuracy:
            with open("StudentPerformancePrediction/MachineLearningModels/mdl_linear_regression.pickle", "wb") as regression_file:
                pickle.dump(mdl_linear_regression, regression_file)

            best_accuracy = accuracy

    print(best_accuracy)

    is_debugger_attached = bool(__debug__)
    if is_debugger_attached:
        pickled_model = open("StudentPerformancePrediction/MachineLearningModels/mdl_linear_regression.pickle", "rb")
        mdl_linear_regression = pickle.load(pickled_model)

        predicted_labels = mdl_linear_regression.predict(test_features)

        count = 0
        b = 0
        for x in predicted_labels:
            up = ceil(x) + 1
            down = floor(x) - 1
            print(f'\t\t\t test:{down} : {test_labels[b]} : {up}')
            b += 1
        print(f'{count}/{len(predicted_labels)}')

        print(f'Coefficients: {mdl_linear_regression.coef_}')
        print(f'Mean squared error: {mean_squared_error(test_labels, predicted_labels)}')
        print(f'Coefficient of determination: {r2_score(test_labels, predicted_labels)}')

def fetch_prediction_data(user):
    efficacy_data = models.StudentEfficacy.objects.get(student_efficacy_id=user)

    features = list(model_to_dict(efficacy_data, fields=['father_education', 'internet_facility', 'study_time',
                                                 'paid_tuition', 'past_failures', 'free_time',
                                                 'extra_curricular_activities',
                                                 'absences', 'past_marks', 'past_marks1', 'class_engagement', 'health'])
                    .values())
    labels = list(model_to_dict(efficacy_data, fields=["predictions"]).values())

    feature_dataset = np.array(features)
    label_dataset = np.array(labels)
    feature_dataset = feature_dataset.reshape(1, -1)
    label_dataset = label_dataset.reshape(1, -1)

    pickled_model = open("StudentPerformancePrediction/MachineLearningModels/mdl_linear_regression.pickle", "rb")
    mdl_linear_regression = pickle.load(pickled_model)

    predicted = mdl_linear_regression.predict(feature_dataset)

    return predicted, label_dataset, efficacy_data.student

calling function for displaying values
def test(request):
    LinearRegression.train_linear_regression_model()
    c = ""
    for i in spp.StudentEfficacy.objects.all().order_by('pk'):
        # a, b = LinearRegression.fetch_prediction_data(msh.MySchoolUser.objects.get(auth_user=i.student.auth_user))
        a, b, d = LinearRegression.fetch_prediction_data(i.pk)
        c += f'
predicted: {a} : {b} : {d}

'
    return HttpResponse(f'
{c}
')

accuracy and terminl Output form function : "train_linear_regression_model"
acc: 0.8281699530791696
output : format = test:[predicted - 2 : actual value : predicted + 1]
                         test:102 : [95] : 105
                         test:34 : [50] : 37
                         test:9 : [30] : 12
                         test:50 : [60] : 53
                         test:39 : [55] : 42
                         test:36 : [50] : 39
                         test:41 : [50] : 44
                         test:60 : [70] : 63
                         test:32 : [45] : 35
                         test:-7 : [0] : -4
                         test:65 : [70] : 68
                         test:74 : [75] : 77
                         test:54 : [60] : 57
                         test:33 : [40] : 36
                         test:54 : [60] : 57
                         test:39 : [50] : 42
                         test:30 : [40] : 33
                         test:62 : [65] : 65
                         test:53 : [55] : 56
                         test:21 : [0] : 24
                         test:-13 : [0] : -10
                         test:99 : [90] : 102
                         test:15 : [30] : 18
                         test:44 : [40] : 47
                         test:99 : [90] : 102
                         test:78 : [80] : 81
                         test:73 : [75] : 76

output from : "fetch_prediction_data(user)"
format : ["predicted" value] : actualValue : userID
predicted: [[1.19540496]] : [[30]] : Frederick342

predicted: [[-3.81400747]] : [[30]] : Tyler763

predicted: [[9.16808199]] : [[50]] : Kimberly521

predicted: [[26.72044263]] : [[75]] : Jared721

predicted: [[18.3986461]] : [[50]] : Kate8105

predicted: [[34.63203366]] : [[75]] : Rebecca900

predicted: [[18.76076664]] : [[55]] : Julia9895

predicted: [[-3.61118462]] : [[30]] : Anna1079

predicted: [[32.96699407]] : [[95]] : Alfred11685

predicted: [[33.57675547]] : [[75]] : Sienna1258

predicted: [[7.41266665]] : [[45]] : Adison13475

predicted: [[15.34683413]] : [[60]] : Derek1437

predicted: [[30.93347564]] : [[70]] : Alexia15265

predicted: [[15.0282954]] : [[55]] : Miranda1616

predicted: [[29.62933642]] : [[80]] : Arthur17055


text:
Q: Seeking help to excel in Excel This pictures shows my table and formula's yield
I have used following formula to extract result from a table.
Its working perfectly fine but I am hoping to level up my understanding of Excel formulas.
The trouble is that I use IF in Excel way to often.
what I wanted to know is if its possible to use a different approach, something that can work similar to if but is perhaps more sophisticated.
=IF(OR(J2="08L",J2="08R"),IF(ISNUMBER(MATCH(LEFT(I2,3),'SID separations'!$D$34,0)),"LAM",IF(ISNUMBER(MATCH(LEFT(I2,3),'SID separations'!$D$35:$E$35,0)),"West",IF(ISNUMBER(MATCH(LEFT(I2,3),'SID separations'!$D$36:$G$36,0)),"East",IF(ISNUMBER(MATCH(LEFT(I2,3),'SID separations'!$D$37,0)),"SFD",NA())))),0)

I very much appreciate any help.

A: Now that there is an example, I think this is a good question. You've recognised that your formula is fairly messy and also can't be easily expanded if there are more routes.
The problem is that Excel is very good for searching for a value in a single row or column, but not as good for searching for a value in a block of data.
You can simplify this problem by creating an additional column that has each entire route in a single cell. You can do this just by concatenating values. In your example, use column H:
=B2&" "&C2&" "&D2&" "&E2&" "&F2&" "&G2

This will create a string with the entire route in a single cell. Spaces are added in between each part of the route to make sure you don't accidentally create a sequences of letters that matches part of another route. It doesn't matter if there are blank cells, there will just be some extra spaces at the end which doesn't matter. Fill this down the column to get the entire path for each route in a single cell.
Then, you can create a formula that tries to find the 3 letters anywhere in any of the full routes.
=INDEX($A$2:$A$5,MATCH("*"&left(I2,3)&"*",$H$2:$H$5,0))

This formula is basically a deconstructed vlookup. It determines where the 3 characters can be found in column H, then gives back the corresponding value from column A.
The MATCH function tries to find the left 3 characters of I2 in column H. The MATCH function normally tries to find a complete exact match (with the last parameter being equal to 0), but we can just add wildcards to the search value. The MATCH function then returns the index of the range where it was found. I.e., if it was found in the 2nd cell of the range H2:H5, it returns the number 2.
The INDEX function then just gets a value from a range based on an index. In this case, it will get the 2nd value from range A2:A5.


text:
Q: how to show different colors in gauge dashboard in sales force? My requirement is in that gauge chart we have to show different colors up to 5.
for that i have created custom vf page, but in that i have to show only 2 different colors.
Here i'm pasted my vf page and class..
vf page:
<apex:page controller="TestPageController">
  <html>

<apex:chart height="250" width="450" animate="true" legend="true" data="{!data}" >
    <apex:axis type="Gauge" position="left" margin="-10"
       minimum="0" maximum="10000" steps="2000" />
    <apex:gaugeSeries dataField="score" highlight="true" tips="true" donut="60"
        colorSet="#FF0000,#FACC2E,#31B404,#8A084B">

    </apex:gaugeSeries>
</apex:chart>
</html>
</apex:page>

Controller is:
public class TestPageController {

    public TestPageController(){

    }

    public List<gaugeData> getData() {
        double NPS_score = 0;
        Account score = [Select Id, Name, Amount_1__c, Amount_2__c,AnnualRevenue  From Account Where id='001i000000cxxM4' LIMIT 1];
         Account score1 = [Select Id, Name,  Amount_1__c From Account LIMIT 1];
        List<gaugeData> data = new List<gaugeData>();
        data.add(new gaugeData('AMT1', score.Amount_1__c));
        data.add(new gaugeData('AMT1', score.Amount_2__c));
        data.add(new gaugeData('AMT1', score.AnnualRevenue));

        return data;
    }
    public class gaugeData {
        public String name { get; set; }

        public decimal score { get; set; }

        public gaugeData(String name, decimal npsScore) {
            this.name = name;

            this.score = npsScore;

        }
    }
}

i have attached the screenshot also..


text:
Q: Trigger  event from  nested in composite Is there any way to trigger an event in my composite component with clientBehavior and jQuery?
If not possible, what is the proper way to create custom events in composites?
Example:
ajaxTest.xhtml:
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:cc="http://xmlns.jcp.org/jsf/composite"
      xmlns:p="http://primefaces.org/ui">

    <cc:interface>
        <cc:clientBehavior name="myEvent" targets="myLabel" event="myEvent"/>
    </cc:interface>

    <cc:implementation>
        <div id="#{cc.clientId}">
            <p:outputLabel id="myLabel" value="Test label" />
            <p:commandLink value="trigger event"
                           onstart="$(PrimeFaces.escapeClientId('#{cc.clientId}:myLabel')).trigger('myEvent');"/>
        </div>
    </cc:implementation>
</html>

testPage.xhtml:
<html xmlns="http://www.w3.org/1999/xhtml"
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:p="http://primefaces.org/ui"
        xmlns:demo="http://xmlns.jcp.org/jsf/composite/component">

<h:body>
        <h:form id="form-1">
            <demo:ajaxTest>
                <p:ajax event="myEvent" oncomplete="alert('Ajax called');" />
            </demo:ajaxTest>
        </h:form>
</h:body>
</html>

A: The <cc:clientBehavior event> must declare a valid event name as supported by the target component in question. In this context, it must thus be exactly the same event name as you would use when nesting <p:ajax> directly inside <p:commandLink>. You perhaps want action or click.
<cc:clientBehavior ... event="action" />

See also:

*

*What values can I pass to the event attribute of the f:ajax tag?


text:
Q: What happened to Wesley's nanites? In ST:TNG episode "Evolution", we see that Wesley's nanites are dropped off on Kavis Alpha IV. Do we ever hear of these particular species of nanites ever again (perhaps in sources other than the TV series)?
Memory Alpha doesn't give us much on this, basically what's below:

In 2366, nanites threatened the USS Enterprise-D with destruction of its main computer core during an experiment in the Kavis Alpha sector. After conflict with the crew of the Enterprise, and particularly the experiment's lead scientist Paul Stubbs, the nanites were relocated to Kavis Alpha IV, which Stubbs' influence had helped designate their new homeworld. The nanites left the Enterprise and began creating their own civilization on the planet. (TNG: "Evolution")

A: Within the TV and Film Series, there's no further mention of Wesley's Nanites. The last we see of them, they've been abandoned on Kavis Alpha IV.
In the wider trek canon (books, etc), we meet them again briefly in Immortal Coil where they're referenced as being part of a wider pan-civilisational grouping of robot and machine intelligences living in and around the Planet Odin.

Data felt pressure against his back. They were being borne upward by
  another swelling of the silver clouds, pushed back up toward the
  Enterprise. He looked at Rhea, who appeared calm, even relaxed, and
  then felt her tapping against his forearm. She spelled out a word in
  Morse code, but it wasn't necessary. Data understood now. It must have
  been another one of Vaslovik's liberation projects, just like the
  exocomps: Wesley Crusher's nanites, the microscopic robots that had
  inexplicably developed into a sentient colonial artificial
  intelligence. Shepherded here to Odin by Vaslovik, they thrived,
  reproducing and evolving freely in the gas giant's immense
  hydrogen-rich atmosphere.


text:
Q: Explanation for the static degree sort algorithm of Deo et al. I would like to apply the static degree sort method of Deo et al (see section 3.1 in https://www.researchgate.net/profile/Mukkai_Krishnamoorthy/publication/220492840_Algorithms_for_Generating_Fundamental_Cycles_in_a_Graph/links/09e4150d0619a2b4bc000000.pdf). Could you please explain using the attached graph or give a pseudocode for the problem?

A: I'm not sure what part of the algorithm is confusing, so I will just break it down in steps. We are trying to construct a special kind of spanning tree.

*

*First take one of the vertices with highest degree (if there are more than one to choose from, just pick one); so take vertex 1.

*For the next vertex, choose the highest degree neighbor of the oldest vertex. So we look at our oldest vertex (vertex 1) and choose one of it's highest degree neighbors, so vertex 2 works. So now we have vertex 1 and 2 connected.

*We are just repeating the previous step until we have added in all the vertices: we put in 4 (attached to 1), 5 (attached to 1), then 0 (attached to 1).

*Then we have chosen all of 1s neighbors so we move on to the second oldest which is 2: so we put in 6 (attached to 2) and 3 (attached to 2).

*The next oldest is 4, but we have already used all of its neighbors. Then 5, but we have also used all of 5s neighbors. Next is 0, but we have used all of 0s neighbors. The next is 6, which has exactly one neighbor we haven't used yet so we add 7 connected to 6.

This gives us a spanning tree, the edges are (in the order given by the algorithm)
$$\{1,2\}, \{1,4\}, \{1,5\}, \{1,0\}, \{2,6\}, \{2,3\}, \{6,7\}. $$


text:
Q: AJAX call in array loop, call next only after previous complete I have an array to upload data and I want them to send to server one by one.
I want the previous one to complete before I send next one.
Actually, after each response I want to decide whether to send next one or not.
while (packetCount < bulkUploadPackets.length) {
  d = d.then(save(bulkUploadPackets[packetCount]))
    .then(function(uploadResponse) {
      //I want to come here after first call complete
      //before second call is fired and so on
      packetCount++;
    });
}

save: function(modelToSave) {
  var defer = $.Deferred();
  var self = this;
  this.model = modelToSave;
  Backbone.sync('create', this, {
    success: function(data, textStatus, jqXHR) {
      console.log("success" + data);
      defer.resolve(data);
    },
    error: function(response) {
      defer.reject(errorObj);
    }
  });

  return defer.promise();
}

A: You can use recursive function and put recursive call inside then:
(function loop() {
     if (packetCount<bulkUploadPackets.length) {
           d = d.then(save(bulkUploadPackets[packetCount]))
                .then(function(uploadResponse){
                      //I want to come here after first call complete before second call is fired and so on
                      packetCount++;
                      loop();
                 });
     }
})();


text:
Q: How to get lists of string entries of a list? I wonder how I can make lists of every string entry of a list? Let's say I have a list:
list_1 = ['a', 'b', 'c']

and I want to get automatically a list of every entry of the list above:
a = []
b = []
c = []

Is there a way to do that?

A: You can use a dictionary to achieve something similar. Just use the names of your strings as dictionary keys and value as a list. `
list_1 = ['a', 'b', 'c']
dict1 = {}
for i in range(len(list_1)):
    dict1[list_1[i]] = [10,20]

print(dict1)

which gives you
{'a': [10, 20], 'c': [10, 20], 'b': [10, 20]}

A: You may do that using a dictionary.
vars = {}
list_1 = ['a', 'b', 'c']

for i in list_1:
    if i not in vars:
        vars[i] = []

So your vars dict will be
vars = {
    'a': [],
    'b': [],
    'c': []
}

And then you can access to data like a normal variable:
>>> vars['a'].append(10)
>>> vars
{'a': [10], 'b': [], 'c': []}
>>> vars['a']
[10]


text:
Q: Embedding of Cantor space proof issue

I think there is an issue in this proof, where $i(n)$ and $k(n)$ need to be redefined slightly as follows for the intersection of the nested open balls to be a singleton: $i(n) = \inf \{m > n : \overline{B(x_m,2^{-m})} \subset B(x_n,2^{-n}) \setminus B(x_n,2^{-m}) \}$ and $k(n)$ redefined similarly.
By making these changes reading up to the third image, the proof makes sense to me, but I am totally at a loss as to why in the third image (last paragraph) of this proof we have that $r_n \leq \rho(y_{\sigma},y_{\tilde{\sigma}})$.
Any help illuminating why this is the case would be much appreciated. This lower bound is used to prove the continuity of the inverse map and so I am assuming it must be true (or a very close lower bound is true).
Edit : Now that I think about this a little more, the cantor space is compact, and since $f: C \rightarrow f(C)$ is a continuous bijection from a compact space to $f(C)$ which is hausdorff, isn't $f$ automatically a homeomorphism? In which case the final paragraph proving the continuity of the inverse map seems unnecessary, but my question still stands as to how the lower bound mentioned in the final paragraph was achieved.
The proof quoted as an image can be found here https://www.math.ucla.edu/~biskup/245b.1.20w/ (lecture 15 - second to last page)

A: I think that you're right about the definitions of $i(n)$ and $k(n)$; I don't see anything in the construction that could substitute for that change. Fortunately, the extra requirement causes no difficulty. I think that there's also a small error in $(15.38)$: if I'm not mistaken, it should read
$$r_{\color{red}{n+1}}\le\rho(y_\sigma,y_{\tilde{\sigma}})\le 2^{-n+1}\,:$$
if $\rho(y_\sigma,y_{\tilde{\sigma}})$ were less than $r_{n+1}$, $\sigma$ and $\tilde{\sigma}$ would agree in the first $n+1$ places, but $\sigma_{n+1}\ne\tilde{\sigma}_{n+1}$.
Finally, the last paragraph is indeed superfluous; it may be that the author has chosen not to assume that much topological knowledge on the part of the reader.


text:
Q: Prevent snap between Android tween animations I have a series of animations that I call in series like so:
final Animation anim1 = AnimationUtils.loadAnimation(thisObject, R.anim.animation1);
final Animation anim2 = AnimationUtils.loadAnimation(thisObject, R.anim.animation2);
final Animation anim3 = AnimationUtils.loadAnimation(thisObject, R.anim.animation3);
final Animation anim4 = AnimationUtils.loadAnimation(thisObject, R.anim.animation4);

anim1.setAnimationListener(new AnimationListener()
{
    public void onAnimationStart(Animation animation) { }
    public void onAnimationRepeat(Animation animation) { }

    public void onAnimationEnd(Animation animation)
    {
        image.startAnimation(anim2);
    }
});

anim2.setAnimationListener(new AnimationListener()
{
    public void onAnimationStart(Animation animation) { }
    public void onAnimationRepeat(Animation animation) { }

    public void onAnimationEnd(Animation animation)
    {
        image.startAnimation(anim3);
    }
});

// etc...

view.startAnimation(anim1);

While this works, the image snaps back to its original position for a split second between each animation.  I've defined android:fillAfter as true in all my animation XML files, but this doesn't seem to change anything.  Is there a way to prevent this snap between animations?  Or is there a better way to achieve the same effect?


text:
Q: What is the difference between Lucene and Elasticsearch I know ElasticSearch is built upon Apache Lucene but I want to know the significant differences between the two.

A: I'll answer from a usage perspective.
Lucene is a search engine library. You'd want to use it to build your own search engine: either a new Elasticsearch or Solr competitor or something narrow for your use-case (e.g. text analysis).
Elasticsearch is a search engine. Most people use it for log aggregation, product search, or a variant of these two (e.g. social media analysis or finding relevant people for some search criteria). It's built on top of Lucene, so it exposes most (though not all) of its features. It also adds a lot on top, most significantly:

*

*REST API

*query DSL

*distributed system (sharding, replication, cluster management)

*facets/aggregations

*additional features for common usage (e.g. ingest processing) and management (APIs for monitoring its relevant metrics, backup and restore, etc)

A: I'll add another angle to the discussion.
Elasticsearch index Vs Lucene index.
The Elasticsearch index is a chunk of documents just like databases consist of tables in relational world.  In order to achieve scaling we spread the Elasticsearch Indices into multiple physical nodes / servers.
For that, we break the Elasticsearch Indices into smaller units which are called shards.
Question: How it is related to Lucene index?
If we want to search for a specific term (for example: "Cake" or "Cookie") we'll have to go over each shard and look for it (lets put aside how shards are being located and replicated on each node).
This operation will take a lot of time - so we need to use an efficient data structure for this search - this is where Lucene's index comes into play.
Each Elasticsearch shard is based on the Lucene index structure and stores statistics about terms in order to make term-based search more efficient.
(!) This is quite confusing because of the word "index" and the fact that an Elasticsearch shard is a portion of Elasticsearch index BUT is based on a data structure of Lucene index .

Bonus - Lucene's index as a inverted index
As can be seen in the example below , Lucene's index stores the original document's content plus additional information, such as term dictionary and term frequencies, which
increase searching efficiency:
Term           Document                 Frequency
Cake           doc_id_1, doc_id_8       4 (2 in doc_id_1, 2 in doc_id_8)
Cookie         doc_id_1, doc_id_6       3 (2 in doc_id_1, 1 in doc_id_6)
Spaghetti      doc_id_12                1 (1 in doc_id_12)

Lucene's index falls into the family of indexes known as an inverted index. This is because it can list, for a term, the documents that contain it.
This is the inverse of the natural relationship, in which documents list terms.

(Reminder) How did we reach from a Shard to a term?
(1) Shard is a directory of files which contains documents.
(2) A document is a sequence of fields.
(3) A field is a named sequence of terms.

A: In addition to @Vineeth Mohan words:
High Availability: Elasticsearch is distributed, so that it can manage data replication, which means having multiple copies of data in your cluster. This enables high availability.
Powerful Query DSL:Elasticsearch offers us, JSON interface for reading and writing queries on top of Lucene. Thanks to Elasticsearch, you can write complex queries without knowing Lucene syntax.
Schemaless (Schema-Free): Fields(name,value pairs) for schema do not have to be defined before. When you index data, elasticsearch can create schema automatically at runtime, like magic.

A: Lucene is a Java library.
You can include it in your project and refer to its functions using function calls.
Elasticsearch is a JSON Based, Distributed, web server built over Lucene.
Though it's Lucene who is doing the actual work beneath, Elasticsearch provides us a convenient layer over Lucene. Each shard that gets created in Elasticsearch is a separate Lucene instance.
So to summarize

*

*Elasticsearch is built over Lucene and provides a JSON based REST API to refer to Lucene features.

*Elasticsearch provides a distributed system on top of Lucene. A distributed system is not something Lucene is aware of or built for. Elasticsearch provides this abstraction of distributed structure.

*Elasticsearch provides other supporting features like thread-pool, queues, node/cluster monitoring API, data monitoring API, Cluster management, etc.


text:
Q: Azure Web Job won't find Connection String I have a fairly straightforward Azure Web Job connected to a queue.  I have validated that it works locally.  When I deploy to Azure, however it fails on the issue: Unhandled Exception: System.InvalidOperationException: Failed to validate Microsoft Azure WebJobs SDK Dashboard connection string
In my job, I set the connection string via hardcode (because I can't get the bloody configuration thing to work anyways)
[<EntryPoint>]
let main argv =
    let _dashboardConn = @"DefaultEndpointsProtocol=https;AccountName=STUFF;AccountKey=STUFF"
    let _storageConn = @"DefaultEndpointsProtocol=https;AccountName=STUFF;AccountKey=STUFF"
    let config = new JobHostConfiguration()
    config.DashboardConnectionString <- _dashboardConn
    config.StorageConnectionString <- _storageConn
    let host = new JobHost(config)
    host.RunAndBlock()
    0

So that didn't work, and I decided to set the value in the configuration section of the websites...which also did not work.  It is as though the App.Config does not exist.  Oh, and I made sure that it is set to always copy (just to be sure, I deleted the whole output folder and made it rebuild and ensured it was there and correct).

A: You can set the following 2 appsettings in Azure Websites "AzureWebJobsDashboard" and "AzureWebJobsStorage". When you run the app in AzureWebsites, our recommendation is to the storage ConnectionString in the AppSetting section.


text:
Q: Best way to protect chart data In my website i need to put a chart with data, like: http://www.swapmeetdave.com/Bible/StockGraph.gif
I need the chart to be sexy. To archive this I have to use CSS+JS. But I don't weant anyone to be able to scrap the chart data.
If I use an image chart, I protect the data but the filesize is too big.
1) Is there a way to create a non image chart and make sure no one will be able to extract the information?
2) Is there a way to create an ultra low size image with only a signle color (green line in the chart above)? png is 4-6kb. Can I do this with < 1kb? SVG maybe?


text:
Q: Is "very" an acceptable answer? If you ask a question starting with "are you...", for example:

Are you hungry?

Is it acceptable to answer with:

Very.

I'm not sure if it's acceptable though I've heard it used.

A: To build on @marcellothearcane's answer:
The formal and grammatically correct answer would be:

Yes, thank you, I am very hungry.

However, in colloquial English (especially spoken English), that's a very cumbersome answer.  It's longer than the question, afer all!  Therefore, following common practices concerning conversational-deletion, the vast majority of that sentence is dropped and "very" becomes an acceptable answer.
Note, though, the @marcellothearcane is very correct in that the circumstances may not prefer the use of "very" as an answer.  The more formal the engagement, the less likely it will be appreciated.


text:
Q: How to create JSON webservice in ASP.NET with database connectivity? How to create a JSON webservice in ASP.NET that connect to MS SQL Database and update/delete values from the database?
This webservice will eventually be used to communicate with iPhone SDK.
Any help would be appreciated.
Thanks!

A: You could do this:
1) Make a data access layer of some sort.
Example: Linq to SQL, Entity Framework, SubSonic, nHibernate, ADO.Net

2) Create a web service (.asmx file) which calls your data access.
3) Make methods in the web service which return json seralized objects or what not.
 [WebMethod]
 public Item GetSingleItem()
 {
     return DataStore.FetchItem(); // return a single object
 }

4) Have a client which can send parameters to the web service and then consume the returned json. I'm thinking that your client on the iPhone will either be a native iPhone application or a web application run through the phones browser. Either way, this sounds like a neat idea.
Good luck, and hope this short list helps you out some.


text:
Q: Redirect URL with query string on same domain but different directory using htaccess I am trying to redirect a page to another page along with query string.
Example:
The URL below
http://example.com/firstdir/?abc=xyz

needs to redirect to the below URL with same query string on same domain.
http://example.com/seconddir/?abc=xyz

When there are no query string added in the URL, it should stay on the same page and will not redirect.
I have tried to explain what I am looking for, please HELP !!!
tHANK YOU.

A: Just put your .htaccess in your root folder and it will handle recursive folders.

A: You can use this code in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On

RewriteCond %{QUERY_STRING} .+
RewriteRule ^firstdir/?$ /seconddir [NC,L,R=302]

Query string is automatically carried over to target URL


text:
Q: Virtual Function simply a function overloading? So I came across something called Virtual Function in C++, which in a nutshell from what I understood is used to enable function overloading in derived/child classes.
So given that we have the following class:
class MyBase{
public:
    virtual void saySomething() { /* some code */ }
};

then when we make a new class that inherits MyBase like this:
class MySubClass : public MyBase{
public:
    void saySomething() { /* different code than in MyBase function */ }
};

the function in MySubClass will execute its own saySomething() function.
To understand it, isn't it same as in Java where you achieve the same by simply writing the same name of the function in the derived class, which will automatically overwrite it / overload it?
Where's in C++ to achieve that you need that extra step, which is declaring the function in base class as virtual?
Thank you in advance! :)

A: Yes you are correct. In Java, all functions are implicitly virtual. In C++ you have a choice: in order to make a function virtual, you need to mark it as such in the base class. (Some folk also repeat the virtual keyword in derived classes, but that is superfluous).

A: Well in c++ a virtual function comes with a cost. To be able to provide polymorphism, overloading etc you need to declare a method as virtual.
As C++ is concerned with the layout of a program the virtual keywords comes with an overhead which may not be desired. Java is compiled into bytecode and execute in a virtual machine. C++ and native assembly code is directly executed on the CPU. This gives you, the developer, a possibility to fully understand and control how the code looks and execute at assembler level (beside optimization, etc).
Declaring anything virtual in a C++ class creates a vtable entry per class on which the entire overloading thing is done.
There is also compile time polymorphism with templates that mitigates the vtable and resolution overhead which has it's own set of issues and possibilities.

A: Let's put it this way.
MyBase *ptr; // Pointer to MyBase
ptr = new MySubClass;
ptr->saySomething();

If saySomething is not virtual in MyBase, the base class version will always be called. If it's virtual, then any derived version will be used, if available.

A:
Virtual Function simply a function overloading?

No. "Overloading" means providing multiple functions with the same name but different parameter types, with the appropriate function chosen at compile time. "Overriding" means providing multiple functions within a class heirarchy, with the appropriate function chosen at run time. In C++, only virtual functions can be overridden.

To understand it, isn't it same as in Java where you achieve the same by simply writing the same name of the function in the derived class, which will automatically overwrite it / overload it?

Yes, assuming you mean "override". In Java, methods are overridable by default. This matches Java's (original) philosophy that we should use a 90s-style object-oriented paradigm for everything.

Where's in C++ to achieve that you need that extra step, which is declaring the function in base class as virtual?

Making functions overridable has a run-time cost, so C++ only does that if you specifically request it. This matches C++'s philosophy that you should choose the most appropriate paradigm for your application, and not pay for language facilities you don't need.


text:
Q: mousemove is fired automatically IE 9 I'm having a problem in IE 9 (haven't tested 8), What the code is supposed to do is detect whether or not the mouse was dragged after clicking on a certain element.  The problem is that IE 9 automatically enters the $(window).mousemove event handler even though I don't move the mouse.  Works Fine in Chrome and FF.
   $(Element).mousedown(function() {
            $(window).mousemove(function() {
                isDragging = true;
                $(window).unbind("mousemove");
            });
        }).mouseup(function() {
            $(window).unbind("mousemove");
        });

A: You should be only starting a drag after the mouse has moved a certain minimum distance.  To do that, record the mouse position in the mousedown handler and then in mousemove, only start your drag when the mouse has moved a minimum distance.
    $(Element).mousedown(function(e) {
        var x = e.clientX;
        var y = e.clientY;
        var minMovement = 3;
        $(window).mousemove(function(e) {
            if (Math.abs(e.clientX - x) > minMovement || Math.abs(e.clientY - y) > minMovement) {
                isDragging = true;
                $(window).unbind("mousemove");
            }
        });
    }).mouseup(function() {
        $(window).unbind("mousemove");
    });

FYI, some mice can record very, very tiny movements (less than one pixel on the screen) so it's likely that the mouse does actually move after you press the mouse down and IE is probably just reporting that movement.  Other browsers may wait until the mouse moves a whole pixel.  In any case, if you require a minimum number of pixels of movement then you won't have this issue.

A: Because the movement of the mouse is so minute with a laser mouse I changed your method a bit to better suit my need of monitoring just the fact of weather or not the mouse is moving:
$(window).mousemove(function (e) {
    var smallNo = 0;
    var x = e.clientX;
    var y = e.clientY;
    var minMovement = 1;
    if ((x - smallNo) > minMovement || (y - smallNo) > minMovement) {
        countDownTime = logoutTime;
    }
});

Even though the mousemove event is firing constantly the coordinates do not change unless you physically move your mouse. I used that to figure out weather or not the mouse had moved or not.


text:
Q: Identical subquery optimisation in an update update activitybooking set `submitted`='1' where id='958'
    and (select SUM(pool1_count) from (select pool1_count from `activitybooking` where `abt`='12' and
                            (id='958' or `submitted`='1' or `submitted`='3' or `submitted`='8')) as temp_pool1_count) &lt 10
    and (select SUM(pool2_count) from (select pool2_count from `activitybooking` where `abt`='12' and
                            (id='958' or `submitted`='1' or `submitted`='3' or `submitted`='8')) as temp_pool2_count) &lt 5
    and (select SUM(pool3_count) from (select pool3_count from `activitybooking` where `abt`='12' and
                            (id='958' or `submitted`='1' or `submitted`='3' or `submitted`='8')) as temp_pool3_count) &lt 20

The statement above has three identical subqueries and seems to execute them independently. How can I best rewrite the update to perform the subquery only once?
(The idea of this query is to only perform the update if doing so would not cause the sum of pool1_count to exceed the maximum allowed pool1_count and the same for pool2, pool3 ....)

A: MySQL lacks common table expressions but you can achieve the same goal here with the multiple-table update syntax:
update activitybooking
       cross join ( select sum(pool1_count) p1, sum(pool2_count) p2, sum(pool3_count) p3
                    from `activitybooking`
                    where `abt`='12' and (id='958' or `submitted`='1' or `submitted`='3' or `submitted`='8') ) z
set `submitted`='1'
where id='958' and p1
(SQLFiddle here)


text:
Q: Cookies from .net are not remembered by the browser I try send cookie from .net to my react app. I get response with cookie but my browser dont remember cookie. In swagger is ok, browser get cookie. I changed settings of cookies, i tried samesite options, added "Access-Control-Allow-Origin" etc. Someone know what going on? What else can we check?
I read this but not working for me.
My .NET address: http://localhost:5255/
My .NET swagger address: http://localhost:5255/swagger/index.html
My react address: http://localhost:3000/login
My Login method:
[HttpPost]
public ActionResult<User> Login(User user)
{
    ...

    var jwt = _jwtService.Generate(existUser.Id);
    Response.Cookies.Append("jwt", jwt, new CookieOptions
    {
        HttpOnly = true,
        SameSite = SameSiteMode.Strict,
    });

    return Ok(jwt);
}

React metohod to call login:
  const BASE_URL = 'http://localhost:5255/';
  login: (name: string, password: string) =>
      axios.post(
        BASE_URL + 'api/auth/login',
        { name, password },
        { headers: { 'Content-Type': 'application/json' } },
      ),

Netowrk response


text:
Q: update problem 11.10
Possible Duplicate:
How do I fix a "Failed to download package files" error?

Whenever I try to install any software through Terminal or Software on my Ubuntu 11.10, I'm getting this response:
Failed to download repository information
Check your Internet connection.
please help me
,

A: Check your software sources> download from> other> select best server> change the mirror to best server, let it update and retry.


text:
Q: Open Cart, Want to create multiple parent categories Currently I have multiple categories in my open cart shop. like A1, A2, A3 ... and their respective subcategories.
Now I want to create two new parents like A and B, where parent A will have child like A1, A2, A3... and their respective subcategories. Similarly parent B will have child like B1, B2, B3 ... and their respective subcategories...
Any clue.

A: Just create a new category A and B, then go to category A1, A2, A3 and change their parent category from nothing to Category A. Do the same for the Bx categories. However this question does not belong to StackOverflow and should be asked at OpenCart forums instead...


text:
Q: Using 'defer' attribute with scripts before the body tag I ran my web page on the Google web page test tool and it suggested I use 'defer' or 'async' attribute to get rid of render blocking JS . My HTML is this:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>My Page</title>
    <link href="https://mycdn.com/style.css" rel="stylesheet">

Since , my scripts are getting including before the closing of the 'body' tag , and not in the 'head', are they  really blocking ? Would a paint not happen until the closing 'html' is parsed ?

A: Using async or defer or moving your scripts to the bottom of the file does not always work across different browser, one recommended way of loading the external scripts is to load it in the following way is by placing this piece of code before the end of the body tag.

See here for more.


text:
Q: SQL: Updating a table updates only 7 rows at a time While executing a SQL update,
update request set state_id = 2 where id in (
           select id from request where state_id = 0 and entity_id in
           (<list of numbers>)
)

This updates only 7 rows at a time.
The inner select query,
 select id from request where state_id = 0 and entity_id in (<list of numbers>)

returns 2000+ records.
I am using Squirrel SQL client to run the query and checked if the limit rows is set to 3000.
What makes it more interesting is, if I wait for more time in between successive executing of the update query, more rows gets updated.
I mean, When I waited for 10 secs, and executed the update, 45 rows got updated.
but when ran rapidly, just 7 rows gets updated.
Can someone please help me point out what I might be doing wrong?
Executing the inner select -

Executing the update -

A: I suggest writing a proper update, since I see no reason to introduce a more complex query involving a subquery. Also just to be sure you didn't previously alter @@ROWCOUNT:
SET @@ROWCOUNT 0;

UPDATE dbo.request
  SET state_id = 2
  WHERE state_id = 0
  AND entity_id IN (<list of numbers>);

Also check that you haven't artificially limited the row count in Management Studio. In Tools > Options:

(Well, that would have been relevant if you had tagged correctly. Check whatever client tool you use against Sybase and see if it has some similar option.)


text:
Q: How can I display a local html file in Shiny UI dynamically? An example.html gets created in a local directory by another script. Until then, Shiny UI should show an empty screen, and when the example.html gets generated, it should be reflected in Shiny UI.
The example.html is loaded into the Shiny UI, but it is not getting reflected.
This is the code I've tried, at least for displaying the file
Code:
ui = shinyUI(fluidPage(titlePanel("Generated Report"),
                       mainPanel(htmlOutput("showfile"))
                       )
             )

server = function(input, output, session){
  output$showfile <- renderUI({
    includeHTML("C://Users//DELL//Desktop//abc_files//www//report.html")
    # HTML(readLines(file_to_show))
  })

}

shinyApp(ui, server)

A: If you want to display the ...report.html file in your shiny app, the // in your path-to-file are not correct.
This script (with a single /) will display the HTML file.
ui = shinyUI(fluidPage(titlePanel("Generated Report"),
                   mainPanel(htmlOutput("showfile"))
                   )
         )

server = function(input, output, session){
  output$showfile <- renderUI({
    includeHTML("C:/Users/DELL/Desktop/abc_files/www/report.html")
    # HTML(readLines(file_to_show))
  })

}

shinyApp(ui, server)


text:
Q: How to round off the result of \pscalculate? \documentclass[12pt,pstricks,border=5pt]{standalone}

\usepackage{pst-func,pst-calculate}
\begin{document}
\begin{pspicture}(-1,-1)(1,1)
\def\q{\pscalculate{1/sqrt(5)}}
\def\a{\pscalculate{(1+sqrt(5))/2}}
\foreach \i in {0,1,...,10}{\pscalculate{\q*((\a)^(\i)-(1-\a)^(\i))},}
\end{pspicture}

\end{document}

I want to generate a list of Fibonacci sequence but without trailing zeros.

How to remove the trailing zeros?

A: \psCalculate (with an uppercase C) can accept some settings.
\documentclass[12pt,border=5pt]{standalone}
\usepackage{pst-calculate,pgffor}
\def\q{\pscalculate{1/sqrt(5)}}
\def\a{\pscalculate{(1+sqrt(5))/2}}

\begin{document}
$0\foreach \i in {1,...,10}{,\psCalculate[round-mode=places,round-precision=0]{\q*((\a)^(\i)-(1-\a)^(\i))}}$
\end{document}

A: Fibonacci with simple LaTeX commands:
\documentclass{article}
\usepackage{ifthen}
\newcounter{fiba}\newcounter{fibb}\newcounter{fibc}\newcounter{fibrun}
\newcommand\fib[1]{%
  \init\whiledo{\thefibrun<#1}{\step\stepcounter{fibrun}}\thefiba}
\newcommand\init{%
  \setcounter{fiba}{1}\setcounter{fibb}{1}\setcounter{fibrun}{0}}
\newcommand\step{\add \rotate}
\newcommand\add{\setcounter{fibc}{\thefiba}\addtocounter{fibc}{\thefibb}}
\newcommand\rotate{\setcounter{fiba}{\thefibb}\setcounter{fibb}{\thefibc}}

\begin{document}
  \newcounter{i} \newcounter{en} \setcounter{en}{20}
  the first \theen\ Fibonacci numbers:\\
  \whiledo{\thei < \theen}{$\fib{\thei}$ \stepcounter{i}}
\end{document}

and the same with running lualatex:
\documentclass[12pt,a4paper]{article}
\usepackage{luacode}
\begin{luacode*}
function printFib(n)
  for i=1,n do tex.print(Fibonacci(i).." ") end
end
function Fibonacci(n)
  local function inner(m)
    if m < 2 then return m end
    return inner(m-1) + inner(m-2)
  end
  return inner(n)
end
\end{luacode*}

\begin{document}
\noindent\directlua{printFib(35)}
\end{document}

A:

Someone should create a rlatex compiler at once, but meanwhile, I will settle with the knitr preprocess. Here the .Rnw file:
\documentclass[12pt,border=1cm]{standalone}
\begin{document}
<<Fib,echo=F>>=
Fibonacci <- function(n) {
    x <- c(0,1)
    while (length(x) < n) {nth <- length(x)
        new <- x[nth] + x[nth-1]
        x <- c(x,new)}
    return(x)}
@
\Sexpr{combine_words(Fibonacci(11))}.
\end{document}

A: Just for fun. Without rounding and without pscalculate. The example is literally copied from p. 640 of the pgfmanual. I confirm the first ten numbers of this answer (but there are rumors some mathematician called Fibonacci had them even a bit earlier  just kidding! ;-).
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{math}
\begin{document}
\tikzmath{
% Adapted from http://www.cs.northwestern.edu/academics/courses/110/html/fib_rec.html
function fibonacci(\n) {
    if \n == 0 then {
      return 0;
    } else {
       return fibonacci2(\n, 0, 1);
}; };
  function fibonacci2(\n, \p, \q) {
    if \n == 1 then {
      return \q;
    } else {
      return fibonacci2(\n-1, \q, \p+\q);
    };
  };
  int \f, \i;
  for \i in {0,1,...,20}{
    \f = fibonacci(\i);
    print {\f, };
  };
}
\end{document}


text:
Q: Toolbar is missing in Crystal Report Viewer (version 13) I am using the latest version of Crystal Report in my ASP.Net web application project. My IDE is Visual Studio Ultimate 2012 Version 11.0.6.
My problem is that when I run the aspx file that contains the Crystal Report Viewer, the toolbar is missing. Please see the attached image:

I already tried copying the toolbar folder to my root folder. I also tried hard-coding ToolbarImagesFolderUrl. I also tried copying crystalreportviewers from inetpub/wwwroot to my root folder. But nothing solved my problem.
Any suggestion?

A: It has to do with the default table css in Visual Studio 2012 projects.  Remove the table, th, td, and tr stuff under tables and it will fix it.  I just spent almost a whole day trying to figure out why it was doing this.

A: I found the answer for this issue on
SAP Community Netwrk: Crystal Report for VS 2012. It is not appear as a option in Reporting. http://scn.sap.com/message/13828750
Redist packages are for deploying your project only. Uninstall them and then use the complete package install:
http://downloads.businessobjects.com/akdlm/cr4vs2010/CRforVS_13_0_5.exe
Now you should not have to do anything except possibly adding the Viewer to the tool box.
Click on your form and then the Tool bar and then select Choose New Item and browse to this:
toolbar items http://scn.sap.com/servlet/JiveServlet/showImage/2-13834457-182961/pastedImage_0.png
Now you should see:
Reportviewer] http://scn.sap.com/servlet/JiveServlet/showImage/2-13834457-182962/pastedImage_1.png
Not sure if the warnings are because you have not installed it correctly. If the above doesn't work then add the PATH to CR runtime to the project:
I don't believe you need to go this far down but this is where they exist on a DEV PC:
C:\Program Files (x86)\SAP BusinessObjects\Crystal Reports for .NET Framework 4.0\Common\SAP BusinessObjects Enterprise XI 4.0\win32_x86\dotnet
Runtime only they are only in the GAC.

A: copy the aspnet_client folder from the default web site to your app website

A: If the above issue is not resolved with web.config entry then press F12 in chrome. Click on console, find the files missing having .axd extensions. Create a blank notepad file and save with same name and extension. Place in the location where it is not found. Your problem will be resolved.


text:
Q: WSO2 IS: How to use email AND username as login I have a WSO2 IS server running with a ReadOnly LDAP user store. Some of the users in that store have an email as username, by default these users cannot login in applications using the IS's oauth2 endpoint. If I follow the instructions here [1] I can make them login without problems, but the rest of users, those without email as username, are no longer allowed to login.
So, my question, is it possible to allow users with AND without email as username to log in an app connected to WSO2 IS through oauth2?
Thanks a lot, cheers
[1] https://docs.wso2.org/display/IS460/Email+Authentication

A: Try using <Property name="UsernameJavaRegEx">[a-zA-Z0-9._-|//]{3,30}$</Property> instead of one given in the doc.
In the doc, its restricting usernames other than emails. Changing the property as above will remove that restriction.
And add following property under  tag in /repository/conf/user-mgt.xml file.
<Property name="UsernameWithEmailJavaScriptRegEx">[a-zA-Z0-9._-|//]{3,30}$</Property>

This will allows you to escape expecting email as a username from UI.
HTH,
DarRay


text:
Q: Export data from multiple databases with one single select statement I have 100+ websites all sitting on a single host and accessable via phpMyAdmin. Each one of these websites uses the same database structure.
I want to pull out all the profile specific information to do a mass mail to all my registered users. I'd then need to combine, sort, remove duplicates and upload to my mail client, I have the following query:
SELECT `NickName`,`FirstName`,`LastName`,`Email` FROM `Profiles`;

What I want to know is can I build a query where I can execute a similar statement yet pull the data from every database and just do one export? Then I can clean the data and upload and send everyone an email? Is this possible?


text:
Q: Custom Loss function in Keras Value Error I am trying to predict 4 variables, but what I really care about is the sum of the variables over what any particular variable is. With that in mind, I've defined my model like:
import keras.backend as K
from keras import losses

def baseline_model():
    def loss_function(y_actual, y_predict):
        return losses.mean_squared_error(
            K.sum(y_actual),
            K.sum(y_predict)
        )

    model = Sequential()
    model.add(Dense(60, input_dim=40, kernel_initializer='normal', activation='relu'))
    model.add(Dense(30, kernel_initializer='normal', activation='relu'))
    model.add(Dense(5, kernel_initializer='normal'))
    model.compile(loss=loss_function, optimizer='adam')

    return model

Where I'm trying to return the mean squared error of the sum. I'm getting an error saying:
ValueError: Invalid reduction dimension -1 for input with 0 dimensions. for 'loss_10/dense_33_loss/loss_function/Mean' (op: 'Mean') with input shapes: [], [] and with computed input tensors: input[1] = <-1>.
Any idea how I can properly accomplish this or where I'm going wrong?

A: K.sum reduces the rank of the input tensor by default and computes the sum over all axes by default. The combination of these two defaults is causing your issue. All you need to do is set keepdims=True for each use of K.sum, or alternatively set axis=1 (or whichever axis you want to sum over).
def loss_function(y_actual, y_predict):
        return losses.mean_squared_error(
            K.sum(y_actual,keepdims=True),
            K.sum(y_predict,keepdims=True)
        )

def loss_function(y_actual, y_predict):
        return losses.mean_squared_error(
            K.sum(y_actual,axis=1),
            K.sum(y_predict,axis=1)
        )

Both should compile just fine. You probably want the keepdims version, though.


text:
Q: how to translate list from a file? fo=open("sample.txt","r")
item=fo.readlines()
fo.close()

replacements = (('4','A'),('8','b'),('3','e'),('5','s'),('7','t'),('@','a'),('3','e'),('0','o'))
new_string = item
for new, old in replacements:
new_string = new_string.replace(new, old)

print ( new_string)

I have written the following code but does not read my list. My goal is translate the list.

A: Use str.translate() to use a translation table for faster translation.  Here is an example:
with open("sample.txt","r") as fo:
    lines = fo.readlines()

replacements = {'4':'A', '8':'b', '3':'e', '5':'s', '7':'t', '@':'a', '3':'e', '0':'o'}
trans_table = str.maketrans(replacements)
for line in lines:
    print(line, end="")
    new_line = line.translate(trans_table)
    print(new_line)

OUTPUT:
h3llo 70 y0u
hello to you

4 8377er w0rld 70d@y
A better world today