问:
Is there a way to use buttons whilsts a timer is active - The buttons were disabled, but are enabled when the timer starts
```<code>import PySimpleGUI as sg
from time import time

q1 = [
        [sg.Text("Question 1!"), sg.Text("Time:"), sg.Text(" ", size=(20,1), key="t")],
        [sg.Text("This is where question 1 will be?"), sg.Button("Start")],
        [sg.Button("Option 1", key="1",button_color=("#ffffff","#151515"), disabled=True, enable_events=True), sg.Button("Option 2", key="2",button_color=("#00ff00", "#151515"), disabled=True)],
        [sg.Button("Option 3", key="3",button_color=("#00ffff","#151515"), disabled=True), sg.Button("Option 4", key="4",button_color=("#ff00ff", "#151515"), disabled=True)],
        [sg.Button("Submit"), sg.Button("Next Question"), sg.Button("Skip")]
    ]

window = sg.Window("Question 1",q1)

while True:
    event, values = window.Read()
    if event is None:
        break
    if event == "Start":
        window.FindElement('1').Update(disabled=False)
        window.FindElement('2').Update(disabled=False)
        window.FindElement('3').Update(disabled=False)
        window.FindElement('4').Update(disabled=False)
        window.FindElement("Start").Update(visible=False)
        window.Refresh()

        seconds = 6

        start = time()
        current = time()
        timeleft = seconds

        while timeleft > 0:
            window.FindElement("t").Update(timeleft)
            window.refresh()
            current = time()
            timeleft = int(seconds - (current - start))
            if timeleft <= 0:
                sg.popup("no time left")
                window.FindElement('1').Update(disabled=True)
                window.FindElement('2').Update(disabled=True)
                window.FindElement('3').Update(disabled=True)
                window.FindElement('4').Update(disabled=True)
                window.FindElement("Start").Update(visible=True)
                window.Refresh()
            else:
                window.FindElement('1').Update(disabled=False)
                window.FindElement('2').Update(disabled=False)
                window.FindElement('3').Update(disabled=False)
                window.FindElement('4').Update(disabled=False)
                window.FindElement("Start").Update(visible=False)
                window.Refresh()

    if event == "1":
        sg.popup("Test 1")
    elif event == "2":
        sg.popup("Test 2")
    elif event == "3":
        sg.popup("Test 3")
    elif event == "4":
        sg.popup("Test 4")

</code>```

This is the code I have tried to do it with. When start is clicked, a timer starts so the question to be answers, however, I dont want the buttons to be able to be clicked before starting, so is there a way to enable a button to be used after being clicked?

答:
threading make possible to run different part of code concurrently. by using threading you make option clickable. try this code which allow you click the button when time run.</p>

```<code># for making screen clear
import ctypes
import platform

def make_dpi_aware():
    if int(platform.release()) >= 8:
        ctypes.windll.shcore.SetProcessDpiAwareness(True)
make_dpi_aware()

import PySimpleGUI as sg
from time import time
import threading

def timer(timeleft_time):
    global timeleft,start
    start = time()
    seconds = timeleft_time
    while True:
        current = time()
        timeleft = int(seconds - (current - start))
        #print(timeleft)
        if event == "1" or event == "2" or event == "3" or event == "4":
            timeleft = -1
            break
        elif timeleft >= 0:
            window["t"].Update(value = timeleft)
            window.Refresh()
            if timeleft <= 0:
                sg.popup("no time left")
                window['1'].Update(disabled=True)
                window['2'].Update(disabled=True)
                window['3'].Update(disabled=True)
                window['4'].Update(disabled=True)
                window["Start"].Update(visible=True)
                window.Refresh()
            else:
                window['1'].Update(disabled=False)
                window['2'].Update(disabled=False)
                window['3'].Update(disabled=False)
                window['4'].Update(disabled=False)
                window["Start"].Update(visible=False)
                window.Refresh()

q1 = [
        [sg.Text("Question 1!"), sg.Text("Time:"), sg.Text(" ", size=(20,1), key="t")],
        [sg.Text("This is where question 1 will be?"), sg.Button("Start")],
        [sg.Button("Option 1", key="1",button_color=("#ffffff","#151515"), disabled=True, enable_events=True), sg.Button("Option 2", key="2",button_color=("#00ff00", "#151515"), disabled=True)],
        [sg.Button("Option 3", key="3",button_color=("#00ffff","#151515"), disabled=True), sg.Button("Option 4", key="4",button_color=("#ff00ff", "#151515"), disabled=True)],
        [sg.Button("Submit"), sg.Button("Next Question"), sg.Button("Skip")]
    ]

window = sg.Window("Question 1",q1)

while True:
    event, values = window.Read()
    if event is None:
        break
    if event == "Start":
        window['1'].Update(disabled=False)
        window['2'].Update(disabled=False)
        window['3'].Update(disabled=False)
        window['4'].Update(disabled=False)
        window["Start"].Update(visible=False)

        window.Refresh()

        seconds = 6

        timeleft = seconds
        window["t"].Update(timeleft)
        window.refresh()
        timer_thread = threading.Thread(target=timer,args = (timeleft,),daemon=True)
        timer_thread.start()

    if event == "1":
        sg.popup("Test 1")
    elif event == "2":
        sg.popup("Test 2")
    elif event == "3":
        sg.popup("Test 3")
    elif event == "4":
        sg.popup("Test 4")
</code>```

Body:
import PySimpleGUI as sg
from time import time

q1 = [
        [sg.Text("Question 1!"), sg.Text("Time:"), sg.Text(" ", size=(20,1), key="t")],
        [sg.Text("This is where question 1 will be?"), sg.Button("Start")],
        [sg.Button("Option 1", key="1",button_color=("#ffffff","#151515"), disabled=True, enable_events=True), sg.Button("Option 2", key="2",button_color=("#00ff00", "#151515"), disabled=True)],
        [sg.Button("Option 3", key="3",button_color=("#00ffff","#151515"), disabled=True), sg.Button("Option 4", key="4",button_color=("#ff00ff", "#151515"), disabled=True)],
        [sg.Button("Submit"), sg.Button("Next Question"), sg.Button("Skip")]
    ]

window = sg.Window("Question 1",q1)

while True:
    event, values = window.Read()
    if event is None:
        break
    if event == "Start":
        window.FindElement('1').Update(disabled=False)
        window.FindElement('2').Update(disabled=False)
        window.FindElement('3').Update(disabled=False)
        window.FindElement('4').Update(disabled=False)
        window.FindElement("Start").Update(visible=False)
        window.Refresh()

        seconds = 6

        start = time()
        current = time()
        timeleft = seconds

        while timeleft > 0:
            window.FindElement("t").Update(timeleft)
            window.refresh()
            current = time()
            timeleft = int(seconds - (current - start))
            if timeleft <= 0:
                sg.popup("no time left")
                window.FindElement('1').Update(disabled=True)
                window.FindElement('2').Update(disabled=True)
                window.FindElement('3').Update(disabled=True)
                window.FindElement('4').Update(disabled=True)
                window.FindElement("Start").Update(visible=True)
                window.Refresh()
            else:
                window.FindElement('1').Update(disabled=False)
                window.FindElement('2').Update(disabled=False)
                window.FindElement('3').Update(disabled=False)
                window.FindElement('4').Update(disabled=False)
                window.FindElement("Start").Update(visible=False)
                window.Refresh()

    if event == "1":
        sg.popup("Test 1")
    elif event == "2":
        sg.popup("Test 2")
    elif event == "3":
        sg.popup("Test 3")
    elif event == "4":
        sg.popup("Test 4")

This is the code I have tried to do it with. When start is clicked, a timer starts so the question to be answers, however, I dont want the buttons to be able to be clicked before starting, so is there a way to enable a button to be used after being clicked?

Body:
threading make possible to run different part of code concurrently. by using threading you make option clickable. try this code which allow you click the button when time run.

# for making screen clear
import ctypes
import platform

def make_dpi_aware():
    if int(platform.release()) >= 8:
        ctypes.windll.shcore.SetProcessDpiAwareness(True)
make_dpi_aware()

import PySimpleGUI as sg
from time import time
import threading

def timer(timeleft_time):
    global timeleft,start
    start = time()
    seconds = timeleft_time
    while True:
        current = time()
        timeleft = int(seconds - (current - start))
        #print(timeleft)
        if event == "1" or event == "2" or event == "3" or event == "4":
            timeleft = -1
            break
        elif timeleft >= 0:
            window["t"].Update(value = timeleft)
            window.Refresh()
            if timeleft <= 0:
                sg.popup("no time left")
                window['1'].Update(disabled=True)
                window['2'].Update(disabled=True)
                window['3'].Update(disabled=True)
                window['4'].Update(disabled=True)
                window["Start"].Update(visible=True)
                window.Refresh()
            else:
                window['1'].Update(disabled=False)
                window['2'].Update(disabled=False)
                window['3'].Update(disabled=False)
                window['4'].Update(disabled=False)
                window["Start"].Update(visible=False)
                window.Refresh()

q1 = [
        [sg.Text("Question 1!"), sg.Text("Time:"), sg.Text(" ", size=(20,1), key="t")],
        [sg.Text("This is where question 1 will be?"), sg.Button("Start")],
        [sg.Button("Option 1", key="1",button_color=("#ffffff","#151515"), disabled=True, enable_events=True), sg.Button("Option 2", key="2",button_color=("#00ff00", "#151515"), disabled=True)],
        [sg.Button("Option 3", key="3",button_color=("#00ffff","#151515"), disabled=True), sg.Button("Option 4", key="4",button_color=("#ff00ff", "#151515"), disabled=True)],
        [sg.Button("Submit"), sg.Button("Next Question"), sg.Button("Skip")]
    ]

window = sg.Window("Question 1",q1)

while True:
    event, values = window.Read()
    if event is None:
        break
    if event == "Start":
        window['1'].Update(disabled=False)
        window['2'].Update(disabled=False)
        window['3'].Update(disabled=False)
        window['4'].Update(disabled=False)
        window["Start"].Update(visible=False)

        window.Refresh()

        seconds = 6

        timeleft = seconds
        window["t"].Update(timeleft)
        window.refresh()
        timer_thread = threading.Thread(target=timer,args = (timeleft,),daemon=True)
        timer_thread.start()

    if event == "1":
        sg.popup("Test 1")
    elif event == "2":
        sg.popup("Test 2")
    elif event == "3":
        sg.popup("Test 3")
    elif event == "4":
        sg.popup("Test 4")


来源: stackexchange

问:
Error: Not implemented: window.scrollTo. How do we remove this error from Jest test?

The error:

```<code>console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
      Error: Not implemented: window.scrollTo
          at module.exports (/Users/me/Projects/my-project/node_modules/jsdom/lib/jsdom/browser/not-implemented.js:9:17)
          at /Users/me/Projects/my-project/node_modules/jsdom/lib/jsdom/browser/Window.js:594:7
</code>```

Because we are using window.scrollTo(0,0).

Also getting Not implemented Navigation for:

window.location.replace(externa_link) same error happens with .assign.

I tried googling for solutions with react-router, but all examples use some component which contains window.location.

Is there a way to avoid this error? Or hide it?

I did some research  and found that the Facebook team isn't going to address it. Is there a way to suppress these errors/warnings when running jest test?

Our code doesn't break and all tests pass otherwise.

答:
In *.test.js file that calls a component that has window.scrollTo

```<code>it("renders without crashing", () => {
  window.scrollTo = jest.fn()
})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The error:

console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
      Error: Not implemented: window.scrollTo
          at module.exports (/Users/me/Projects/my-project/node_modules/jsdom/lib/jsdom/browser/not-implemented.js:9:17)
          at /Users/me/Projects/my-project/node_modules/jsdom/lib/jsdom/browser/Window.js:594:7

Because we are using window.scrollTo(0,0).

Also getting Not implemented Navigation for:

window.location.replace(externa_link) same error happens with .assign.

I tried googling for solutions with react-router, but all examples use some component which contains window.location.

Is there a way to avoid this error? Or hide it?

I did some research  and found that the Facebook team isn't going to address it. Is there a way to suppress these errors/warnings when running jest test?

Our code doesn't break and all tests pass otherwise.

Body:
In *.test.js file that calls a component that has window.scrollTo

it("renders without crashing", () => {
  window.scrollTo = jest.fn()
})


问:
Django: IE doesn't load localhost or loads very SLOWLY
I'm just starting to learn Django, building a project on my computer, running Windows 7 64-bit, Python 2.7, Django 1.3.

Basically whatever I write, it loads in Chrome and Firefox instantly. But for IE (version 9), it just stalls there, and does nothing. I can load up "http://127.0.0.1:8000" on IE and leave the computer on for hours and it doesn't load. Sometimes, when I refresh a couple of times or restart IE it'll work. If I change something in the code, again, Chrome and Firefox reflects changes instantly, whereas IE doesn't - if it loads the page at all.

What is going on? I'm losing my mind here....

答:
I'm not sure if you have the same problem as me. But I also bumped with the same white page on IE9 and apparently it was caused by html tag "fieldset" hides my form.

Try to validate your html code or check html tags compatibility with IE9. Hope it helps.

ContentLicense: CC BY-SA 3.0


问:
Regular Expression to trim number at the end of a string
I have a file which consists of string. The file also contains date.
I want to remove number at the end of the string.
For example-

```<code>Str = 'part-at-1234'
</code>```

New string should be str= 'part-at'

I have written the following regex

```<code>(-\d+)
</code>```

My regex also matches the date.
I want to write a regular expression that only matches the string not include date.
Thank you in advance

答:
If there date has a format of for example 12-12-20, you could match the hyphen and  1+ digits and assert not a digit before the hyphen.

```<code>(?<!\d)-\d+$
</code>```

Regex demo | Python demo

Example code

```<code>import re

regex = r"(?<!\d)-\d+$"
test_str = ("part-at-1234\n"
    "part-at-12-12-2020")

result = re.sub(regex, "", test_str, 0, re.MULTILINE)

if result:
    print (result)
</code>```

Output

```<code>part-at
part-at-12-12-20
</code>```

Body:
I have a file which consists of string. The file also contains date.
I want to remove number at the end of the string.
For example-

Str = 'part-at-1234'

New string should be str= 'part-at'

I have written the following regex

(-\d+)

My regex also matches the date.
I want to write a regular expression that only matches the string not include date.
Thank you in advance

Body:
If there date has a format of for example 12-12-20, you could match the hyphen and  1+ digits and assert not a digit before the hyphen.

(?<!\d)-\d+$

Regex demo | Python demo

Example code

import re

regex = r"(?<!\d)-\d+$"
test_str = ("part-at-1234\n"
    "part-at-12-12-2020")

result = re.sub(regex, "", test_str, 0, re.MULTILINE)

if result:
    print (result)

Output

part-at
part-at-12-12-20


问:
How can I initialise an .each() function only after a specific event happened?
I have the following function, that zooms out on images once they enter the viewport. All images are lazyloaded, which is why I want to start the zooming behavior only when the image is fully visible. The event to listen to is called 'lazyunveilread'. Then there is a css transition to fade in the image. Once both things are done, the zooming should be initialized.

Unfortunately, I don't know how to do that. I tried installing the event listener on the event but that only works for the first element and not for the others.

window.addEventListener('scroll', check_if_in_view, {
 capture: true,
 passive: true
});

var $animation_elements = $('.zoom-images');
var $window = $(window);
function check_if_in_view() {
 var window_height = $window.height();
 var window_top_position = $window.scrollTop();
 var window_bottom_position = (window_top_position + window_height);
 $animation_elements.each(function() {
  var $element = $(this);
  var $zoom = $(this).children('img.zoom');
  var element_height = $element.outerHeight();
  var element_top_position = $element.offset().top;
  var element_bottom_position = (element_top_position + element_height);
  if ((element_bottom_position >= window_top_position) &&
   (element_top_position <= window_bottom_position)) {
    if (!$zoom.hasClass('is-zooming')) {
     requestAnimationFrame( function() {
      $zoom.addClass('is-zooming');
     });
    }
  } else {
   if ($zoom.hasClass('is-zooming')) {
    requestAnimationFrame( function() {
     $zoom.removeClass('is-zooming');
    });
   }
  }
 });
};

/* lazyloading with lazysizes.js */

! function(a, b) {
 var c = b(a, a.document, Date);
 a.lazySizes = c, "object" == typeof module && module.exports && (module.exports = c)
}("undefined" != typeof window ? window : {}, function(a, b, c) {
 "use strict";
 var d, e;
 if (function() {
   var b, c = {
    lazyClass: "lazy",
    loadedClass: " is-loaded",
    loadingClass: " is-loading",
    preloadClass: "lazypreload",
    errorClass: "lazyerror",
    autosizesClass: "lazyautosizes",
    srcAttr: "data-src",
    srcsetAttr: "data-srcset",
    sizesAttr: "data-sizes",
    minSize: 40,
    customMedia: {},
    init: !0,
    expFactor: 1.5,
    hFac: .8,
    loadMode: 1,
    loadHidden: 0,
    ricTimeout: 0,
    throttleDelay: 125
   };
   e = a.lazySizesConfig || a.lazysizesConfig || {};
   for (b in c) b in e || (e[b] = c[b])
  }(), !b || !b.getElementsByClassName) return {
  init: function() {},
  cfg: e,
  noSupport: !0
 };
 var f = b.documentElement,
  g = a.HTMLPictureElement,
  h = "addEventListener",
  i = "getAttribute",
  j = a[h].bind(a),
  k = a.setTimeout,
  l = a.requestAnimationFrame || k,
  m = a.requestIdleCallback,
  n = /^picture$/i,
  o = ["load", "error", "lazyincluded", "_lazyloaded"],
  p = {},
  q = Array.prototype.forEach,
  r = function(a, b) {
   return p[b] || (p[b] = new RegExp("(\\s|^)" + b + "(\\s|$)")), p[b].test(a[i]("class") || "") && p[b]
  },
  s = function(a, b) {
   r(a, b) || a.setAttribute("class", (a[i]("class") || "").trim() + " " + b)
  },
  t = function(a, b) {
   var c;
   (c = r(a, b)) && a.setAttribute("class", (a[i]("class") || "").replace(c, ""))
  },
  u = function(a, b, c) {
   var d = c ? h : "removeEventListener";
   c && u(a, b), o.forEach(function(c) {
    a[d](c, b)
   })
  },
  v = function(a, c, e, f, g) {
   var h = b.createEvent("Event");
   return e || (e = {}), e.instance = d, h.initEvent(c, !f, !g), h.detail = e, a.dispatchEvent(h), h
  },
  w = function(b, c) {
   var d;
   !g && (d = a.picturefill || e.pf) ? (c && c.src && !b[i]("srcset") && b.setAttribute("srcset", c.src), d({
    reevaluate: !0,
    elements: [b]
   })) : c && c.src && (b.src = c.src)
  },
  x = function(a, b) {
   return (getComputedStyle(a, null) || {})[b]
  },
  y = function(a, b, c) {
   for (c = c || a.offsetWidth; c < e.minSize && b && !a._lazysizesWidth;) c = b.offsetWidth, b = b.parentNode;
   return c
  },
  z = function() {
   var a, c, d = [],
    e = [],
    f = d,
    g = function() {
     var b = f;
     for (f = d.length ? e : d, a = !0, c = !1; b.length;) b.shift()();
     a = !1
    },
    h = function(d, e) {
     a && !e ? d.apply(this, arguments) : (f.push(d), c || (c = !0, (b.hidden ? k : l)(g)))
    };
   return h._lsFlush = g, h
  }(),
  A = function(a, b) {
   return b ? function() {
    z(a)
   } : function() {
    var b = this,
     c = arguments;
    z(function() {
     a.apply(b, c)
    })
   }
  },
  B = function(a) {
   var b, d = 0,
    f = e.throttleDelay,
    g = e.ricTimeout,
    h = function() {
     b = !1, d = c.now(), a()
    },
    i = m && g > 49 ? function() {
     m(h, {
      timeout: g
     }), g !== e.ricTimeout && (g = e.ricTimeout)
    } : A(function() {
     k(h)
    }, !0);
   return function(a) {
    var e;
    (a = !0 === a) && (g = 33), b || (b = !0, e = f - (c.now() - d), e < 0 && (e = 0), a || e < 9 ? i() : k(i, e))
   }
  },
  C = function(a) {
   var b, d, e = 99,
    f = function() {
     b = null, a()
    },
    g = function() {
     var a = c.now() - d;
     a < e ? k(g, e - a) : (m || f)(f)
    };
   return function() {
    d = c.now(), b || (b = k(g, e))
   }
  },
  D = function() {
   var g, m, o, p, y, D, F, G, H, I, J, K, L = /^img$/i,
    M = /^iframe$/i,
    N = "onscroll" in a && !/(gle|ing)bot/.test(navigator.userAgent),
    O = 0,
    P = 0,
    Q = 0,
    R = -1,
    S = function(a) {
     Q--, (!a || Q < 0 || !a.target) && (Q = 0)
    },
    T = function(a) {
     return null == K && (K = "hidden" == x(b.body, "visibility")), K || !("hidden" == x(a.parentNode, "visibility") && "hidden" == x(a, "visibility"))
    },
    U = function(a, c) {
     var d, e = a,
      g = T(a);
     for (G -= c, J += c, H -= c, I += c; g && (e = e.offsetParent) && e != b.body && e != f;)(g = (x(e, "opacity") || 1) > 0) && "visible" != x(e, "overflow") && (d = e.getBoundingClientRect(), g = I > d.left && H < d.right && J > d.top - 1 && G < d.bottom + 1);
     return g
    },
    V = function() {
     var a, c, h, j, k, l, n, o, q, r, s, t, u = d.elements;
     if ((p = e.loadMode) && Q < 8 && (a = u.length)) {
      for (c = 0, R++; c < a; c++)
       if (u[c] && !u[c]._lazyRace)
        if (!N || d.prematureUnveil && d.prematureUnveil(u[c])) ba(u[c]);
        else if ((o = u[c][i]("data-expand")) && (l = 1 * o) || (l = P), r || (r = !e.expand || e.expand < 1 ? f.clientHeight > 500 && f.clientWidth > 500 ? 500 : 370 : e.expand, d._defEx = r, s = r * e.expFactor, t = e.hFac, K = null, P < s && Q < 1 && R > 2 && p > 2 && !b.hidden ? (P = s, R = 0) : P = p > 1 && R > 1 && Q < 6 ? r : O), q !== l && (D = innerWidth + l * t, F = innerHeight + l, n = -1 * l, q = l), h = u[c].getBoundingClientRect(), (J = h.bottom) >= n && (G = h.top) <= F && (I = h.right) >= n * t && (H = h.left) <= D && (J || I || H || G) && (e.loadHidden || T(u[c])) && (m && Q < 3 && !o && (p < 3 || R < 4) || U(u[c], l))) {
       if (ba(u[c]), k = !0, Q > 9) break
      } else !k && m && !j && Q < 4 && R < 4 && p > 2 && (g[0] || e.preloadAfterLoad) && (g[0] || !o && (J || I || H || G || "auto" != u[c][i](e.sizesAttr))) && (j = g[0] || u[c]);
      j && !k && ba(j)
     }
    },
    W = B(V),
    X = function(a) {
     var b = a.target;
     if (b._lazyCache) return void delete b._lazyCache;
     S(a), s(b, e.loadedClass), t(b, e.loadingClass), u(b, Z), v(b, "lazyloaded")
    },
    Y = A(X),
    Z = function(a) {
     Y({
      target: a.target
     })
    },
    $ = function(a, b) {
     try {
      a.contentWindow.location.replace(b)
     } catch (c) {
      a.src = b
     }
    },
    _ = function(a) {
     var b, c = a[i](e.srcsetAttr);
     (b = e.customMedia[a[i]("data-media") || a[i]("media")]) && a.setAttribute("media", b), c && a.setAttribute("srcset", c)
    },
    aa = A(function(a, b, c, d, f) {
     var g, h, j, l, m, p;
     (m = v(a, "lazybeforeunveil", b)).defaultPrevented || (d && (c ? s(a, e.autosizesClass) : a.setAttribute("sizes", d)), h = a[i](e.srcsetAttr), g = a[i](e.srcAttr), f && (j = a.parentNode, l = j && n.test(j.nodeName || "")), p = b.firesLoad || "src" in a && (h || g || l), m = {
      target: a
     }, s(a, e.loadingClass), p && (clearTimeout(o), o = k(S, 2500), u(a, Z, !0)), l && q.call(j.getElementsByTagName("source"), _), h ? a.setAttribute("srcset", h) : g && !l && (M.test(a.nodeName) ? $(a, g) : a.src = g), f && (h || l) && w(a, {
      src: g
     })), a._lazyRace && delete a._lazyRace, t(a, e.lazyClass), z(function() {
      var b = a.complete && a.naturalWidth > 1;
      p && !b || (b && s(a, " is-cached"), X(m), a._lazyCache = !0, k(function() {
       "_lazyCache" in a && delete a._lazyCache
      }, 9)), "lazy" == a.loading && Q--
     }, !0)
    }),
    ba = function(a) {
     if (!a._lazyRace) {
      var b, c = L.test(a.nodeName),
       d = c && (a[i](e.sizesAttr) || a[i]("sizes")),
       f = "auto" == d;
      (!f && m || !c || !a[i]("src") && !a.srcset || a.complete || r(a, e.errorClass) || !r(a, e.lazyClass)) && (b = v(a, "lazyunveilread").detail, f && E.updateElem(a, !0, a.offsetWidth), a._lazyRace = !0, Q++, aa(a, b, f, d, c))
     }
    },
    ca = C(function() {
     e.loadMode = 3, W()
    }),
    da = function() {
     3 == e.loadMode && (e.loadMode = 2), ca()
    },
    ea = function() {
     if (!m) {
      if (c.now() - y < 999) return void k(ea, 999);
      m = !0, e.loadMode = 3, W(), j("scroll", da, !0)
     }
    };
   return {
    _: function() {
     y = c.now(), d.elements = b.getElementsByClassName(e.lazyClass), g = b.getElementsByClassName(e.lazyClass + " " + e.preloadClass), j("scroll", W, !0), j("resize", W, !0), j("pageshow", function(a) {
      if (a.persisted) {
       var c = b.querySelectorAll("." + e.loadingClass);
       c.length && c.forEach && l(function() {
        c.forEach(function(a) {
         a.complete && ba(a)
        })
       })
      }
     }), a.MutationObserver ? new MutationObserver(W).observe(f, {
      childList: !0,
      subtree: !0,
      attributes: !0
     }) : (f[h]("DOMNodeInserted", W, !0), f[h]("DOMAttrModified", W, !0), setInterval(W, 999)), j("hashchange", W, !0), ["focus", "mouseover", "click", "load", "transitionend", "animationend"].forEach(function(a) {
      b[h](a, W, !0)
     }), /d$|^c/.test(b.readyState) ? ea() : (j("load", ea), b[h]("DOMContentLoaded", W), k(ea, 2e4)), d.elements.length ? (V(), z._lsFlush()) : W()
    },
    checkElems: W,
    unveil: ba,
    _aLSL: da
   }
  }(),
  E = function() {
   var a, c = A(function(a, b, c, d) {
     var e, f, g;
     if (a._lazysizesWidth = d, d += "px", a.setAttribute("sizes", d), n.test(b.nodeName || ""))
      for (e = b.getElementsByTagName("source"), f = 0, g = e.length; f < g; f++) e[f].setAttribute("sizes", d);
     c.detail.dataAttr || w(a, c.detail)
    }),
    d = function(a, b, d) {
     var e, f = a.parentNode;
     f && (d = y(a, f, d), e = v(a, "lazybeforesizes", {
      width: d,
      dataAttr: !!b
     }), e.defaultPrevented || (d = e.detail.width) && d !== a._lazysizesWidth && c(a, f, e, d))
    },
    f = function() {
     var b, c = a.length;
     if (c)
      for (b = 0; b < c; b++) d(a[b])
    },
    g = C(f);
   return {
    _: function() {
     a = b.getElementsByClassName(e.autosizesClass), j("resize", g)
    },
    checkElems: g,
    updateElem: d
   }
  }(),
  F = function() {
   !F.i && b.getElementsByClassName && (F.i = !0, E._(), D._())
  };
 return k(function() {
  e.init && F()
 }), d = {
  cfg: e,
  autoSizer: E,
  loader: D,
  init: F,
  uP: w,
  aC: s,
  rC: t,
  hC: r,
  fire: v,
  gW: y,
  rAF: z
 }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.zoom-images {
 display: block;
  position: relative;
 width: 300px;
 height: 300px;
 border-radius: 10px;
 overflow: hidden;
 -webkit-mask-image: -webkit-radial-gradient(white, black);
 z-index: 1;
}

.zoom-images img {
 position: absolute;
 width: 150%;
 height: 150%;
 top: -25%;
 left: -25%;
}

.zoom-images img.is-placeholder {
 -webkit-filter: blur(5px);
   filter: blur(5px);
 z-index: 1;
}

.zoom-images img.is-real {
 z-index: 2;
 will-change: transform;
}

.zoom-images img.is-real.is-zooming {
 transform: scale(0.67);
   transition: transform 2s ease;
   -o-transition: transform 2s ease;
 -webkit-transition: transform 2s ease;
    -moz-transition: transform 2s ease;
     -ms-transition: transform 2s ease;
}

img.is-real {
 opacity: 0.001;
}

img.is-loaded {
 opacity: 0.999;
 transition: opacity 1s linear;
}</code>```

```

Any help will be greatly appreciated! Thank you in advance!

答:
So I changed your markup a little bit:

```<code><div class="zoom-images">
     <img class="lazyload is-real zoom-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" data-src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait.jpg" alt="test" />
     <img class="is-placeholder fade-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" />
</div>
</code>```

lazysizes automatically replaces lazyload class with lazyloaded class once the image is loaded. So we can use that to make our adjustments.

Thanks to transition-delay, you don't need to write a lot of JavaScript to achieve what you looking for.
 We are basically setting a transition delay for high quality image, so once the image is in view-port and loaded we gonna wait for fade effect to finish and then zoom effect will be applied after that.
Also we are toggling between 2 classes:
 fade-on and fade-off for placeholder image, and also
zoom-on and zoom-off for real (high quality) image.

 So all together it looks like this: https://jsfiddle.net/sy0vqg5e/

Your markup:

```<code><body>
    <div class="images-container">
        <div class="zoom-images">
            <img class="lazyload is-real zoom-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" data-src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait.jpg" alt="test" />
            <img class="is-placeholder fade-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" />
        </div>
        <div class="zoom-images">
            <img class="lazyload is-real zoom-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" data-src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait.jpg" alt="test" />
            <img class="is-placeholder fade-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" />
        </div>
        <div class="zoom-images">
            <img class="lazyload is-real zoom-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" data-src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait.jpg" alt="test" />
            <img class="is-placeholder fade-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" />
        </div>
        <div class="zoom-images">
            <img class="lazyload is-real zoom-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" data-src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait.jpg" alt="test" />
            <img class="is-placeholder fade-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" />
        </div>
        <div class="zoom-images">
            <img class="lazyload is-real zoom-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" data-src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait.jpg" alt="test" />
            <img class="is-placeholder fade-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" />
        </div>
        <div class="zoom-images">
            <img class="lazyload is-real zoom-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" data-src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait.jpg" alt="test" />
            <img class="is-placeholder fade-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" />
        </div>
        <div class="zoom-images">
            <img class="lazyload is-real zoom-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" data-src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait.jpg" alt="test" />
            <img class="is-placeholder fade-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" />
        </div>
        <div class="zoom-images">
            <img class="lazyload is-real zoom-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" data-src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait.jpg" alt="test" />
            <img class="is-placeholder fade-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" />
        </div>
        <div class="zoom-images">
            <img class="lazyload is-real zoom-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" data-src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait.jpg" alt="test" />
            <img class="is-placeholder fade-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" />
        </div>
    </div>
</body>
</code>```

Styles:

```<code>.zoom-images {
  display: block;
  position: relative;
  width: 300px;
  height: 300px;
  border-radius: 10px;
  overflow: hidden;
  -webkit-mask-image: -webkit-radial-gradient(white, black);
          mask-image: -webkit-radial-gradient(white, black);
  z-index: 1;
}

.zoom-images img {
  position: absolute;
  width: 150%;
  height: 150%;
  top: -25%;
  left: -25%;
}

.zoom-images .is-placeholder {
  -webkit-filter: blur(5px);
          filter: blur(5px);
  -webkit-transition: 1s;
  transition: 1s;
  z-index: 1;
}

.zoom-images .fade-on {
  opacity: 1;
}

.zoom-images .is-real {
  -webkit-transition: -webkit-transform 2s ease;
  transition: -webkit-transform 2s ease;
  transition: transform 2s ease;
  transition: transform 2s ease, -webkit-transform 2s ease;
  -webkit-transition-delay: 1s;
          transition-delay: 1s;
}

.zoom-images .zoom-on {
  -webkit-transform: scale(1);
          transform: scale(1);
}

.zoom-images .fade-off {
  opacity: 0.0001;
}

.zoom-images .zoom-off {
  -webkit-transform: scale(0.67) !important;
          transform: scale(0.67) !important;
}
</code>```

Javascript:

```<code>window.addEventListener('scroll', check_if_in_view, {
    capture: true,
    passive: true,
});

var $animation_elements = $('.zoom-images');
var $window = $(window);

function check_if_in_view() {
    var window_height = $window.height();
    var window_top_position = $window.scrollTop();
    var window_bottom_position = window_top_position + window_height;

    $animation_elements.each(function () {
        var $element = $(this);
        var element_bottom_position = $element.offset().top + $element.outerHeight();

        var placeholder = $element.find('.is-placeholder');
        var real = $element.find('.is-real');

        if (element_bottom_position >= window_top_position && $element.offset().top <= window_bottom_position) {
            console.log(real);
            // When image is in viewport and has been loaded
            if (real.hasClass('lazyloaded')) {
                placeholder.addClass('fade-off');
                real.addClass('zoom-off');
            }
        } else {
            // when image is not in viewport back to starting effects
            placeholder.removeClass('fade-off');
            real.removeClass('zoom-off');
            real.addClass('zoom-on');
        }
    });
}
check_if_in_view()
</code>```

Body:
I have the following function, that zooms out on images once they enter the viewport. All images are lazyloaded, which is why I want to start the zooming behavior only when the image is fully visible. The event to listen to is called 'lazyunveilread'. Then there is a css transition to fade in the image. Once both things are done, the zooming should be initialized.

Unfortunately, I don't know how to do that. I tried installing the event listener on the event but that only works for the first element and not for the others.

window.addEventListener('scroll', check_if_in_view, {
 capture: true,
 passive: true
});

var $animation_elements = $('.zoom-images');
var $window = $(window);
function check_if_in_view() {
 var window_height = $window.height();
 var window_top_position = $window.scrollTop();
 var window_bottom_position = (window_top_position + window_height);
 $animation_elements.each(function() {
  var $element = $(this);
  var $zoom = $(this).children('img.zoom');
  var element_height = $element.outerHeight();
  var element_top_position = $element.offset().top;
  var element_bottom_position = (element_top_position + element_height);
  if ((element_bottom_position >= window_top_position) &&
   (element_top_position <= window_bottom_position)) {
    if (!$zoom.hasClass('is-zooming')) {
     requestAnimationFrame( function() {
      $zoom.addClass('is-zooming');
     });
    }
  } else {
   if ($zoom.hasClass('is-zooming')) {
    requestAnimationFrame( function() {
     $zoom.removeClass('is-zooming');
    });
   }
  }
 });
};

/* lazyloading with lazysizes.js */

! function(a, b) {
 var c = b(a, a.document, Date);
 a.lazySizes = c, "object" == typeof module && module.exports && (module.exports = c)
}("undefined" != typeof window ? window : {}, function(a, b, c) {
 "use strict";
 var d, e;
 if (function() {
   var b, c = {
    lazyClass: "lazy",
    loadedClass: " is-loaded",
    loadingClass: " is-loading",
    preloadClass: "lazypreload",
    errorClass: "lazyerror",
    autosizesClass: "lazyautosizes",
    srcAttr: "data-src",
    srcsetAttr: "data-srcset",
    sizesAttr: "data-sizes",
    minSize: 40,
    customMedia: {},
    init: !0,
    expFactor: 1.5,
    hFac: .8,
    loadMode: 1,
    loadHidden: 0,
    ricTimeout: 0,
    throttleDelay: 125
   };
   e = a.lazySizesConfig || a.lazysizesConfig || {};
   for (b in c) b in e || (e[b] = c[b])
  }(), !b || !b.getElementsByClassName) return {
  init: function() {},
  cfg: e,
  noSupport: !0
 };
 var f = b.documentElement,
  g = a.HTMLPictureElement,
  h = "addEventListener",
  i = "getAttribute",
  j = a[h].bind(a),
  k = a.setTimeout,
  l = a.requestAnimationFrame || k,
  m = a.requestIdleCallback,
  n = /^picture$/i,
  o = ["load", "error", "lazyincluded", "_lazyloaded"],
  p = {},
  q = Array.prototype.forEach,
  r = function(a, b) {
   return p[b] || (p[b] = new RegExp("(\\s|^)" + b + "(\\s|$)")), p[b].test(a[i]("class") || "") && p[b]
  },
  s = function(a, b) {
   r(a, b) || a.setAttribute("class", (a[i]("class") || "").trim() + " " + b)
  },
  t = function(a, b) {
   var c;
   (c = r(a, b)) && a.setAttribute("class", (a[i]("class") || "").replace(c, ""))
  },
  u = function(a, b, c) {
   var d = c ? h : "removeEventListener";
   c && u(a, b), o.forEach(function(c) {
    a[d](c, b)
   })
  },
  v = function(a, c, e, f, g) {
   var h = b.createEvent("Event");
   return e || (e = {}), e.instance = d, h.initEvent(c, !f, !g), h.detail = e, a.dispatchEvent(h), h
  },
  w = function(b, c) {
   var d;
   !g && (d = a.picturefill || e.pf) ? (c && c.src && !b[i]("srcset") && b.setAttribute("srcset", c.src), d({
    reevaluate: !0,
    elements: [b]
   })) : c && c.src && (b.src = c.src)
  },
  x = function(a, b) {
   return (getComputedStyle(a, null) || {})[b]
  },
  y = function(a, b, c) {
   for (c = c || a.offsetWidth; c < e.minSize && b && !a._lazysizesWidth;) c = b.offsetWidth, b = b.parentNode;
   return c
  },
  z = function() {
   var a, c, d = [],
    e = [],
    f = d,
    g = function() {
     var b = f;
     for (f = d.length ? e : d, a = !0, c = !1; b.length;) b.shift()();
     a = !1
    },
    h = function(d, e) {
     a && !e ? d.apply(this, arguments) : (f.push(d), c || (c = !0, (b.hidden ? k : l)(g)))
    };
   return h._lsFlush = g, h
  }(),
  A = function(a, b) {
   return b ? function() {
    z(a)
   } : function() {
    var b = this,
     c = arguments;
    z(function() {
     a.apply(b, c)
    })
   }
  },
  B = function(a) {
   var b, d = 0,
    f = e.throttleDelay,
    g = e.ricTimeout,
    h = function() {
     b = !1, d = c.now(), a()
    },
    i = m && g > 49 ? function() {
     m(h, {
      timeout: g
     }), g !== e.ricTimeout && (g = e.ricTimeout)
    } : A(function() {
     k(h)
    }, !0);
   return function(a) {
    var e;
    (a = !0 === a) && (g = 33), b || (b = !0, e = f - (c.now() - d), e < 0 && (e = 0), a || e < 9 ? i() : k(i, e))
   }
  },
  C = function(a) {
   var b, d, e = 99,
    f = function() {
     b = null, a()
    },
    g = function() {
     var a = c.now() - d;
     a < e ? k(g, e - a) : (m || f)(f)
    };
   return function() {
    d = c.now(), b || (b = k(g, e))
   }
  },
  D = function() {
   var g, m, o, p, y, D, F, G, H, I, J, K, L = /^img$/i,
    M = /^iframe$/i,
    N = "onscroll" in a && !/(gle|ing)bot/.test(navigator.userAgent),
    O = 0,
    P = 0,
    Q = 0,
    R = -1,
    S = function(a) {
     Q--, (!a || Q < 0 || !a.target) && (Q = 0)
    },
    T = function(a) {
     return null == K && (K = "hidden" == x(b.body, "visibility")), K || !("hidden" == x(a.parentNode, "visibility") && "hidden" == x(a, "visibility"))
    },
    U = function(a, c) {
     var d, e = a,
      g = T(a);
     for (G -= c, J += c, H -= c, I += c; g && (e = e.offsetParent) && e != b.body && e != f;)(g = (x(e, "opacity") || 1) > 0) && "visible" != x(e, "overflow") && (d = e.getBoundingClientRect(), g = I > d.left && H < d.right && J > d.top - 1 && G < d.bottom + 1);
     return g
    },
    V = function() {
     var a, c, h, j, k, l, n, o, q, r, s, t, u = d.elements;
     if ((p = e.loadMode) && Q < 8 && (a = u.length)) {
      for (c = 0, R++; c < a; c++)
       if (u[c] && !u[c]._lazyRace)
        if (!N || d.prematureUnveil && d.prematureUnveil(u[c])) ba(u[c]);
        else if ((o = u[c][i]("data-expand")) && (l = 1 * o) || (l = P), r || (r = !e.expand || e.expand < 1 ? f.clientHeight > 500 && f.clientWidth > 500 ? 500 : 370 : e.expand, d._defEx = r, s = r * e.expFactor, t = e.hFac, K = null, P < s && Q < 1 && R > 2 && p > 2 && !b.hidden ? (P = s, R = 0) : P = p > 1 && R > 1 && Q < 6 ? r : O), q !== l && (D = innerWidth + l * t, F = innerHeight + l, n = -1 * l, q = l), h = u[c].getBoundingClientRect(), (J = h.bottom) >= n && (G = h.top) <= F && (I = h.right) >= n * t && (H = h.left) <= D && (J || I || H || G) && (e.loadHidden || T(u[c])) && (m && Q < 3 && !o && (p < 3 || R < 4) || U(u[c], l))) {
       if (ba(u[c]), k = !0, Q > 9) break
      } else !k && m && !j && Q < 4 && R < 4 && p > 2 && (g[0] || e.preloadAfterLoad) && (g[0] || !o && (J || I || H || G || "auto" != u[c][i](e.sizesAttr))) && (j = g[0] || u[c]);
      j && !k && ba(j)
     }
    },
    W = B(V),
    X = function(a) {
     var b = a.target;
     if (b._lazyCache) return void delete b._lazyCache;
     S(a), s(b, e.loadedClass), t(b, e.loadingClass), u(b, Z), v(b, "lazyloaded")
    },
    Y = A(X),
    Z = function(a) {
     Y({
      target: a.target
     })
    },
    $ = function(a, b) {
     try {
      a.contentWindow.location.replace(b)
     } catch (c) {
      a.src = b
     }
    },
    _ = function(a) {
     var b, c = a[i](e.srcsetAttr);
     (b = e.customMedia[a[i]("data-media") || a[i]("media")]) && a.setAttribute("media", b), c && a.setAttribute("srcset", c)
    },
    aa = A(function(a, b, c, d, f) {
     var g, h, j, l, m, p;
     (m = v(a, "lazybeforeunveil", b)).defaultPrevented || (d && (c ? s(a, e.autosizesClass) : a.setAttribute("sizes", d)), h = a[i](e.srcsetAttr), g = a[i](e.srcAttr), f && (j = a.parentNode, l = j && n.test(j.nodeName || "")), p = b.firesLoad || "src" in a && (h || g || l), m = {
      target: a
     }, s(a, e.loadingClass), p && (clearTimeout(o), o = k(S, 2500), u(a, Z, !0)), l && q.call(j.getElementsByTagName("source"), _), h ? a.setAttribute("srcset", h) : g && !l && (M.test(a.nodeName) ? $(a, g) : a.src = g), f && (h || l) && w(a, {
      src: g
     })), a._lazyRace && delete a._lazyRace, t(a, e.lazyClass), z(function() {
      var b = a.complete && a.naturalWidth > 1;
      p && !b || (b && s(a, " is-cached"), X(m), a._lazyCache = !0, k(function() {
       "_lazyCache" in a && delete a._lazyCache
      }, 9)), "lazy" == a.loading && Q--
     }, !0)
    }),
    ba = function(a) {
     if (!a._lazyRace) {
      var b, c = L.test(a.nodeName),
       d = c && (a[i](e.sizesAttr) || a[i]("sizes")),
       f = "auto" == d;
      (!f && m || !c || !a[i]("src") && !a.srcset || a.complete || r(a, e.errorClass) || !r(a, e.lazyClass)) && (b = v(a, "lazyunveilread").detail, f && E.updateElem(a, !0, a.offsetWidth), a._lazyRace = !0, Q++, aa(a, b, f, d, c))
     }
    },
    ca = C(function() {
     e.loadMode = 3, W()
    }),
    da = function() {
     3 == e.loadMode && (e.loadMode = 2), ca()
    },
    ea = function() {
     if (!m) {
      if (c.now() - y < 999) return void k(ea, 999);
      m = !0, e.loadMode = 3, W(), j("scroll", da, !0)
     }
    };
   return {
    _: function() {
     y = c.now(), d.elements = b.getElementsByClassName(e.lazyClass), g = b.getElementsByClassName(e.lazyClass + " " + e.preloadClass), j("scroll", W, !0), j("resize", W, !0), j("pageshow", function(a) {
      if (a.persisted) {
       var c = b.querySelectorAll("." + e.loadingClass);
       c.length && c.forEach && l(function() {
        c.forEach(function(a) {
         a.complete && ba(a)
        })
       })
      }
     }), a.MutationObserver ? new MutationObserver(W).observe(f, {
      childList: !0,
      subtree: !0,
      attributes: !0
     }) : (f[h]("DOMNodeInserted", W, !0), f[h]("DOMAttrModified", W, !0), setInterval(W, 999)), j("hashchange", W, !0), ["focus", "mouseover", "click", "load", "transitionend", "animationend"].forEach(function(a) {
      b[h](a, W, !0)
     }), /d$|^c/.test(b.readyState) ? ea() : (j("load", ea), b[h]("DOMContentLoaded", W), k(ea, 2e4)), d.elements.length ? (V(), z._lsFlush()) : W()
    },
    checkElems: W,
    unveil: ba,
    _aLSL: da
   }
  }(),
  E = function() {
   var a, c = A(function(a, b, c, d) {
     var e, f, g;
     if (a._lazysizesWidth = d, d += "px", a.setAttribute("sizes", d), n.test(b.nodeName || ""))
      for (e = b.getElementsByTagName("source"), f = 0, g = e.length; f < g; f++) e[f].setAttribute("sizes", d);
     c.detail.dataAttr || w(a, c.detail)
    }),
    d = function(a, b, d) {
     var e, f = a.parentNode;
     f && (d = y(a, f, d), e = v(a, "lazybeforesizes", {
      width: d,
      dataAttr: !!b
     }), e.defaultPrevented || (d = e.detail.width) && d !== a._lazysizesWidth && c(a, f, e, d))
    },
    f = function() {
     var b, c = a.length;
     if (c)
      for (b = 0; b < c; b++) d(a[b])
    },
    g = C(f);
   return {
    _: function() {
     a = b.getElementsByClassName(e.autosizesClass), j("resize", g)
    },
    checkElems: g,
    updateElem: d
   }
  }(),
  F = function() {
   !F.i && b.getElementsByClassName && (F.i = !0, E._(), D._())
  };
 return k(function() {
  e.init && F()
 }), d = {
  cfg: e,
  autoSizer: E,
  loader: D,
  init: F,
  uP: w,
  aC: s,
  rC: t,
  hC: r,
  fire: v,
  gW: y,
  rAF: z
 }
});

.zoom-images {
 display: block;
  position: relative;
 width: 300px;
 height: 300px;
 border-radius: 10px;
 overflow: hidden;
 -webkit-mask-image: -webkit-radial-gradient(white, black);
 z-index: 1;
}

.zoom-images img {
 position: absolute;
 width: 150%;
 height: 150%;
 top: -25%;
 left: -25%;
}

.zoom-images img.is-placeholder {
 -webkit-filter: blur(5px);
   filter: blur(5px);
 z-index: 1;
}

.zoom-images img.is-real {
 z-index: 2;
 will-change: transform;
}

.zoom-images img.is-real.is-zooming {
 transform: scale(0.67);
   transition: transform 2s ease;
   -o-transition: transform 2s ease;
 -webkit-transition: transform 2s ease;
    -moz-transition: transform 2s ease;
     -ms-transition: transform 2s ease;
}

img.is-real {
 opacity: 0.001;
}

img.is-loaded {
 opacity: 0.999;
 transition: opacity 1s linear;
}

Any help will be greatly appreciated! Thank you in advance!

Body:
So I changed your markup a little bit:

<div class="zoom-images">
     <img class="lazyload is-real zoom-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" data-src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait.jpg" alt="test" />
     <img class="is-placeholder fade-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" />
</div>

lazysizes automatically replaces lazyload class with lazyloaded class once the image is loaded. So we can use that to make our adjustments.

Thanks to transition-delay, you don't need to write a lot of JavaScript to achieve what you looking for.
 We are basically setting a transition delay for high quality image, so once the image is in view-port and loaded we gonna wait for fade effect to finish and then zoom effect will be applied after that.
Also we are toggling between 2 classes:
 fade-on and fade-off for placeholder image, and also
zoom-on and zoom-off for real (high quality) image.

 So all together it looks like this: https://jsfiddle.net/sy0vqg5e/

Your markup:

<body>
    <div class="images-container">
        <div class="zoom-images">
            <img class="lazyload is-real zoom-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" data-src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait.jpg" alt="test" />
            <img class="is-placeholder fade-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" />
        </div>
        <div class="zoom-images">
            <img class="lazyload is-real zoom-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" data-src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait.jpg" alt="test" />
            <img class="is-placeholder fade-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" />
        </div>
        <div class="zoom-images">
            <img class="lazyload is-real zoom-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" data-src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait.jpg" alt="test" />
            <img class="is-placeholder fade-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" />
        </div>
        <div class="zoom-images">
            <img class="lazyload is-real zoom-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" data-src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait.jpg" alt="test" />
            <img class="is-placeholder fade-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" />
        </div>
        <div class="zoom-images">
            <img class="lazyload is-real zoom-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" data-src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait.jpg" alt="test" />
            <img class="is-placeholder fade-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" />
        </div>
        <div class="zoom-images">
            <img class="lazyload is-real zoom-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" data-src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait.jpg" alt="test" />
            <img class="is-placeholder fade-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" />
        </div>
        <div class="zoom-images">
            <img class="lazyload is-real zoom-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" data-src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait.jpg" alt="test" />
            <img class="is-placeholder fade-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" />
        </div>
        <div class="zoom-images">
            <img class="lazyload is-real zoom-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" data-src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait.jpg" alt="test" />
            <img class="is-placeholder fade-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" />
        </div>
        <div class="zoom-images">
            <img class="lazyload is-real zoom-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" data-src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait.jpg" alt="test" />
            <img class="is-placeholder fade-on" src="http://fabiankleeberger.de/porcelain-frontend/assets/img/portrait-lowres.jpg" />
        </div>
    </div>
</body>

Styles:

.zoom-images {
  display: block;
  position: relative;
  width: 300px;
  height: 300px;
  border-radius: 10px;
  overflow: hidden;
  -webkit-mask-image: -webkit-radial-gradient(white, black);
          mask-image: -webkit-radial-gradient(white, black);
  z-index: 1;
}

.zoom-images img {
  position: absolute;
  width: 150%;
  height: 150%;
  top: -25%;
  left: -25%;
}

.zoom-images .is-placeholder {
  -webkit-filter: blur(5px);
          filter: blur(5px);
  -webkit-transition: 1s;
  transition: 1s;
  z-index: 1;
}

.zoom-images .fade-on {
  opacity: 1;
}

.zoom-images .is-real {
  -webkit-transition: -webkit-transform 2s ease;
  transition: -webkit-transform 2s ease;
  transition: transform 2s ease;
  transition: transform 2s ease, -webkit-transform 2s ease;
  -webkit-transition-delay: 1s;
          transition-delay: 1s;
}

.zoom-images .zoom-on {
  -webkit-transform: scale(1);
          transform: scale(1);
}

.zoom-images .fade-off {
  opacity: 0.0001;
}

.zoom-images .zoom-off {
  -webkit-transform: scale(0.67) !important;
          transform: scale(0.67) !important;
}

Javascript:

window.addEventListener('scroll', check_if_in_view, {
    capture: true,
    passive: true,
});

var $animation_elements = $('.zoom-images');
var $window = $(window);

function check_if_in_view() {
    var window_height = $window.height();
    var window_top_position = $window.scrollTop();
    var window_bottom_position = window_top_position + window_height;

    $animation_elements.each(function () {
        var $element = $(this);
        var element_bottom_position = $element.offset().top + $element.outerHeight();

        var placeholder = $element.find('.is-placeholder');
        var real = $element.find('.is-real');

        if (element_bottom_position >= window_top_position && $element.offset().top <= window_bottom_position) {
            console.log(real);
            // When image is in viewport and has been loaded
            if (real.hasClass('lazyloaded')) {
                placeholder.addClass('fade-off');
                real.addClass('zoom-off');
            }
        } else {
            // when image is not in viewport back to starting effects
            placeholder.removeClass('fade-off');
            real.removeClass('zoom-off');
            real.addClass('zoom-on');
        }
    });
}
check_if_in_view()


问:
jquery find select options attributes
I know how to get the attributes of an element, using jquery.  But I'm not sure how to do it with the actual options in a select field.

```<code><select referenceID="55" name="test" id="test">
  <option value="1">first option</option>
  <option value="2">second option</option>
  <option value="3">third option</option>
</select>
</code>```

To get the referenceID I would just do this:

```<code>$("#test").attr("referenceID");
</code>```

And when I want to get the value:

```<code>$("#test").val();
</code>```

But I want to get a little more interesting.  I want to put some specific info into each option:

```<code><select name="test" id="test">
  <option value="1" title="something here"*>first option</option>
  <option value="2" title="something else here">second option</option>
  <option value="3" title="another thing here">third option</option>
</select>
</code>```

Is it possible to grab an attribute within the options tags?

I intend to have an onselect function that reads the title tag, and does helps me with some other things.

答:
Does this not work?</p>

```<code>$("#test").change(function() {

   var title = $(this).attr("title");

});
</code>```

Title: jquery find select options attributes

Body:
I know how to get the attributes of an element, using jquery.  But I'm not sure how to do it with the actual options in a select field.

<select referenceID="55" name="test" id="test">
  <option value="1">first option</option>
  <option value="2">second option</option>
  <option value="3">third option</option>
</select>

To get the referenceID I would just do this:

$("#test").attr("referenceID");

And when I want to get the value:

$("#test").val();

But I want to get a little more interesting.  I want to put some specific info into each option:

<select name="test" id="test">
  <option value="1" title="something here"*>first option</option>
  <option value="2" title="something else here">second option</option>
  <option value="3" title="another thing here">third option</option>
</select>

Is it possible to grab an attribute within the options tags?

I intend to have an onselect function that reads the title tag, and does helps me with some other things.

Body:
Does this not work?

$("#test").change(function() {

   var title = $(this).attr("title");

});


问:
Fuzzy match within the same column - Python
Problem: I have records in one column, eg. Bulambuli and Bulambuli district which are essentially the same.

Solution: I was trying to search a sort of fuzzy match within the same column and found -Pandas replace strings with fuzzy match in the same column:

```<code>import difflib
import pandas as pd
df = pd.DataFrame({'district' : pd.Series(['Bulambuli', 'Kampla', 'Uttah' ,'Bulambuli district'])})
names = df['district']
def fuzzy_replace(x, names):
    aliases = difflib.get_close_matches(x, names)
    closest = pd.Series(aliases).mode()
    closest = aliases[0] if closest.empty else closest[0]
    df['district'].replace(aliases, closest, True)
df["district"].apply(lambda x: fuzzy_replace(x, df['district']))
</code>```

The result:

Have you had a similar problem? How would you suggest me to approach it?

答:
Input:

```<code>df = pd.DataFrame({'district' : pd.Series(['Bulambuli', 'Kampla', 'Uttah', 'Bulambuli district'])})
df
    district
0   Bulambuli
1   Kampla
2   Uttah
3   Bulambuli district
</code>```

Just return the closest:

```<code>def fuzzy_replace(x, names):
    aliases = difflib.get_close_matches(x, names)
    closest = pd.Series(aliases).mode()
    closest = aliases[0] if closest.empty else closest[0]
    return closest

df["district"].apply(lambda x: fuzzy_replace(x, df['district']))
</code>```

Output:

```<code>0    Bulambuli
1       Kampla
2        Uttah
3    Bulambuli
</code>```

The string Bulambuli is returned by the function since it is the most similar value to Bulambuli district in the df.

Body:
Problem: I have records in one column, eg. Bulambuli and Bulambuli district which are essentially the same.

Solution: I was trying to search a sort of fuzzy match within the same column and found -Pandas replace strings with fuzzy match in the same column:

import difflib
import pandas as pd
df = pd.DataFrame({'district' : pd.Series(['Bulambuli', 'Kampla', 'Uttah' ,'Bulambuli district'])})
names = df['district']
def fuzzy_replace(x, names):
    aliases = difflib.get_close_matches(x, names)
    closest = pd.Series(aliases).mode()
    closest = aliases[0] if closest.empty else closest[0]
    df['district'].replace(aliases, closest, True)
df["district"].apply(lambda x: fuzzy_replace(x, df['district']))

The result:

Have you had a similar problem? How would you suggest me to approach it?

Body:
Input:

df = pd.DataFrame({'district' : pd.Series(['Bulambuli', 'Kampla', 'Uttah', 'Bulambuli district'])})
df
    district
0   Bulambuli
1   Kampla
2   Uttah
3   Bulambuli district

Just return the closest:

def fuzzy_replace(x, names):
    aliases = difflib.get_close_matches(x, names)
    closest = pd.Series(aliases).mode()
    closest = aliases[0] if closest.empty else closest[0]
    return closest

df["district"].apply(lambda x: fuzzy_replace(x, df['district']))

Output:

0    Bulambuli
1       Kampla
2        Uttah
3    Bulambuli

The string Bulambuli is returned by the function since it is the most similar value to Bulambuli district in the df.


问:
Convert raw data to pandas dataframe?
I have raw data in a string, which are basically multiple keywords in the form-

```<code>Law, of, three, stages
Alienation
Social, Facts
Theory, of, Social, System
</code>```

How do I import it into a dataframe such that it counts repetition and returns me a count of each word?

Edit: I've converted it into the following format

```<code> Law,of,three,stages,Alienation,Social,Facts,Theory,of,Social,System
</code>```

I want to convert it into a dataframe because i want to eventually predict which word has the highest probability of reocurring.

答:
Use a dictionary

```<code>word_count_dict = {}
with open("Yourfile.txt") as file_stream:
     lines = file_stream.readlines()
     for line in lines:
         if "," in line:
            line = line.split(",")
         else:
            line = [line]
         for item in line:
             if item in word_count_dict.keys():
                   word_count_dict[item] += 1
             else:
                   word_count_dict[item] = 1
</code>```

Since Now you will be having all the count list of words if you want the probability-based order. Its recommended dividing each value by total count of occurrences

```<code>total = sum(word_count_dict.itervalues(), 0.0)
probability_words = {k: v / total for k, v in word_count_dict.iteritems()}
</code>```

Now the probability words have all the chance of occurrence of that specific word.

Reverse Ordering based on Probabilities

```<code>sorted_probability_words = sorted(probability_words, key = lambda x : x[1], reverse = True)
</code>```

Getting the first Element with highest chance

```<code>print(sorted_probability_words[0]) # to access the word Key value
print(sorted_probability_words[0][0]) # to get the first word
print(sorted_probability_words[0][1]) # to get the first word  probability
</code>```

Title: Convert raw data to pandas dataframe?

Body:
I have raw data in a string, which are basically multiple keywords in the form-

Law, of, three, stages
Alienation
Social, Facts
Theory, of, Social, System

How do I import it into a dataframe such that it counts repetition and returns me a count of each word?

Edit: I've converted it into the following format

 Law,of,three,stages,Alienation,Social,Facts,Theory,of,Social,System

I want to convert it into a dataframe because i want to eventually predict which word has the highest probability of reocurring.

Body:
Use a dictionary

word_count_dict = {}
with open("Yourfile.txt") as file_stream:
     lines = file_stream.readlines()
     for line in lines:
         if "," in line:
            line = line.split(",")
         else:
            line = [line]
         for item in line:
             if item in word_count_dict.keys():
                   word_count_dict[item] += 1
             else:
                   word_count_dict[item] = 1

Since Now you will be having all the count list of words if you want the probability-based order. Its recommended dividing each value by total count of occurrences

total = sum(word_count_dict.itervalues(), 0.0)
probability_words = {k: v / total for k, v in word_count_dict.iteritems()}

Now the probability words have all the chance of occurrence of that specific word.

Reverse Ordering based on Probabilities

sorted_probability_words = sorted(probability_words, key = lambda x : x[1], reverse = True)

Getting the first Element with highest chance

print(sorted_probability_words[0]) # to access the word Key value
print(sorted_probability_words[0][0]) # to get the first word
print(sorted_probability_words[0][1]) # to get the first word  probability


问:
Recaptcha error code 'connection-failed' on verification
When implementing recaptcha v2, I am given the error code 'connection-failed' when trying to verify the recaptcha input.

I have followed this (https://www.freakyjolly.com/how-to-add-google-recaptcha-in-php-form/) tutorial as I had no luck with others that I found

    require('src/autoload.php');

    $siteKey = 'my key';
    $secret = 'my key';

    $recaptcha = new \ReCaptcha\ReCaptcha($secret);

    $gRecaptchaResponse = $_POST['g-recaptcha-response'];
    $remoteIp = $_SERVER['REMOTE_ADDR'];
    $recaptchaErrors = '';

    $resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp);

    if ($resp->isSuccess()) {
        $error[] = "worked";
    } else {
        $recaptchaErrors = $resp->getErrorCodes();

        foreach($recaptchaErrors as $err)
        {
            $error[] = $err;
        }

    }
```

I have not had much luck finding any details on this error anywhere, and it is not documented on the official recaptcha page. I have edited the snippet above for testing purposes, but it would be sending an email.

答:
If allow_url_fopen is off in your php.ini, the connection will fail because Recaptcha uses file_get_contents to access the API by default. I would not enable this flag as it can pose a security risk.

My suggestion, if you have the php curl module installed, is to use Recaptcha with a curl connection:

```<code>$recaptcha = new \ReCaptcha\ReCaptcha($secret, new \ReCaptcha\RequestMethod\CurlPost());
</code>```

Body:
When implementing recaptcha v2, I am given the error code 'connection-failed' when trying to verify the recaptcha input.

I have followed this (https://www.freakyjolly.com/how-to-add-google-recaptcha-in-php-form/) tutorial as I had no luck with others that I found

    require('src/autoload.php');

    $siteKey = 'my key';
    $secret = 'my key';

    $recaptcha = new \ReCaptcha\ReCaptcha($secret);

    $gRecaptchaResponse = $_POST['g-recaptcha-response'];
    $remoteIp = $_SERVER['REMOTE_ADDR'];
    $recaptchaErrors = '';

    $resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp);

    if ($resp->isSuccess()) {
        $error[] = "worked";
    } else {
        $recaptchaErrors = $resp->getErrorCodes();

        foreach($recaptchaErrors as $err)
        {
            $error[] = $err;
        }

    }

I have not had much luck finding any details on this error anywhere, and it is not documented on the official recaptcha page. I have edited the snippet above for testing purposes, but it would be sending an email.

Body:
If allow_url_fopen is off in your php.ini, the connection will fail because Recaptcha uses file_get_contents to access the API by default. I would not enable this flag as it can pose a security risk.

My suggestion, if you have the php curl module installed, is to use Recaptcha with a curl connection:

$recaptcha = new \ReCaptcha\ReCaptcha($secret, new \ReCaptcha\RequestMethod\CurlPost());


问:
Loop until the request response message equals to "true" in php
I'm trying to make a php script that would make a loop that would get the contents of my site/server and if the text response is for example "false" then it would do the same thing, basically will loop until the site's text response will echo "true".
This is what i tried:

```<code>    $getcontents = file_get_contents("http://example.com/script.php"); // it will echo false
    if (strpos($getcontents , 'false')) {
            $getcontents = file_get_contents("http://example.com/script.php");
     else if (strpos($getcontents , 'false')) {
      $getcontents = file_get_contents("http://example.com/script.php");
}
else if (strpos($getcontents , 'true')) {
      echo "finished".;
}
</code>```

I'm not sure if this is the right way or even if it is possible and i apologize in advance if i did not explain myself very well. Thank you for attention!

答:
You could use a regular while loop.

```<code>$getcontents = 'false'; //set value to allow loop to start
while(strpos($getcontents , 'false') !== false) {
    $getcontents = file_get_contents("http://example.com/script.php");
}
echo "finished";
</code>```

This will loop until $getcontents does not contain false.

You could also use a recursive function like this.

```<code>function check_for_false() {

    $getcontents = file_get_contents("http://example.com/script.php");

    if(strpos($getcontents , 'false') !== false) {
        check_for_false();
    } else if(strpos($getcontents , 'true') !== false) {
        echo "finished";
    } else {
        echo "response didn't contain \"true\" or \"false\"";
    }

}
</code>```

This function should keep calling itself until $getcontents contains the word true, and does not contain false.

Body:
I'm trying to make a php script that would make a loop that would get the contents of my site/server and if the text response is for example "false" then it would do the same thing, basically will loop until the site's text response will echo "true".
This is what i tried:

    $getcontents = file_get_contents("http://example.com/script.php"); // it will echo false
    if (strpos($getcontents , 'false')) {
            $getcontents = file_get_contents("http://example.com/script.php");
     else if (strpos($getcontents , 'false')) {
      $getcontents = file_get_contents("http://example.com/script.php");
}
else if (strpos($getcontents , 'true')) {
      echo "finished".;
}

I'm not sure if this is the right way or even if it is possible and i apologize in advance if i did not explain myself very well. Thank you for attention!

Body:
You could use a regular while loop.

$getcontents = 'false'; //set value to allow loop to start
while(strpos($getcontents , 'false') !== false) {
    $getcontents = file_get_contents("http://example.com/script.php");
}
echo "finished";

This will loop until $getcontents does not contain false.

You could also use a recursive function like this.

function check_for_false() {

    $getcontents = file_get_contents("http://example.com/script.php");

    if(strpos($getcontents , 'false') !== false) {
        check_for_false();
    } else if(strpos($getcontents , 'true') !== false) {
        echo "finished";
    } else {
        echo "response didn't contain \"true\" or \"false\"";
    }

}

This function should keep calling itself until $getcontents contains the word true, and does not contain false.


问:
How do I create an array of pointers?
I am trying to create an array of pointers. These pointers will point to a Student object that I created. How do I do it?
What I have now is:

```<code>Student * db = new Student[5];
</code>```

But each element in that array is the student object, not a pointer to the student object.
Thanks.

答:
An array of pointers is written as a pointer of pointers:

```<code>Student **db = new Student*[5];
</code>```

Now the problem is, that you only have reserved memory for the five pointers. So you have to iterate through them to create the Student objects themselves.

In C++, for most use cases life is easier with a std::vector.

```<code>std::vector<Student*> db;
</code>```

Now you can use push_back() to add new pointers to it and [] to index it. It is cleaner to use than the ** thing.

OwnerDisplayName: chustar

ContentLicense: CC BY-SA 2.5

Title: How do I create an array of pointers?

Body:
I am trying to create an array of pointers. These pointers will point to a Student object that I created. How do I do it?
What I have now is:

Student * db = new Student[5];

But each element in that array is the student object, not a pointer to the student object.
Thanks.

Body:
An array of pointers is written as a pointer of pointers:

Student **db = new Student*[5];

Now the problem is, that you only have reserved memory for the five pointers. So you have to iterate through them to create the Student objects themselves.

In C++, for most use cases life is easier with a std::vector.

std::vector<Student*> db;

Now you can use push_back() to add new pointers to it and [] to index it. It is cleaner to use than the ** thing.

OwnerDisplayName: ypnos


问:
Remove select2 no data found text
I have made a select2 multi input in order to add tags. However, when I click on the input it shows no results found. Is there a better way to remove it instead of adding css?

I use select2 version 4.0.12

https://select2.org/tagging#automatic-tokenization-into-tags

css to remove it:

.select2-results__option.select2-results__message

Initialization:

```<code>$(()=>{
    $("#sel-inp").select2({
        tags: true,
        tokenSeparators: [','],
        id: 'add_keywords',
        width: '100%'
    })
})
</code>```

答:
Here's the solution using noResults method.

```<code> $("#mail_add_keywords").select2({
    tags: true,
    tokenSeparators: [','],
    id: 'mail_add_keywords',
    width: '100%',
    "language": {
       "noResults": () => "Add Keywords"

    }
})
</code>```

Title: Remove select2 no data found text

Body:
I have made a select2 multi input in order to add tags. However, when I click on the input it shows no results found. Is there a better way to remove it instead of adding css?

I use select2 version 4.0.12

https://select2.org/tagging#automatic-tokenization-into-tags

css to remove it:

.select2-results__option.select2-results__message

Initialization:

$(()=>{
    $("#sel-inp").select2({
        tags: true,
        tokenSeparators: [','],
        id: 'add_keywords',
        width: '100%'
    })
})

Body:
Here's the solution using noResults method.

 $("#mail_add_keywords").select2({
    tags: true,
    tokenSeparators: [','],
    id: 'mail_add_keywords',
    width: '100%',
    "language": {
       "noResults": () => "Add Keywords"

    }
})


问:
How to merge multiple .NET Core assemblies into a single one (.dll / .exe)?
I know there is ILMerge for .NET Framework (Full Framework) assemblies. But what about .NET Core? I would like to create a commandline utility tool, but I don't want it to be like 20 files, but only 1 .exe.

Is there any way to do it?

答:
You can use the new feature of .NET Core 3.0:

```<code>dotnet publish -r win10-x64 -p:PublishSingleFile=true
</code>```

Read on MSDN

Body:
You can use the new feature of .NET Core 3.0:

dotnet publish -r win10-x64 -p:PublishSingleFile=true

Read on MSDN


问:
Making df columns unique to one column permanently outside of df loop function
Note: Correction - the code returns AttributeError: 'str' object has no attribute 'drop_duplicates'

I am trying to loop through a number of dfs and reduce my 'user_id' column to only unique values using the
df.drop_duplicates(subset =['user_id']
function.

I need this to be a global change and am trying to incorporate it into my function that imports .csv files and assigns them to their file name. This works perfectly but when I try and add the drop_duplicates function, it doesn't seem to do anything:

```<code>def assign_vars(files = os.listdir()):
    # Make list of variable names using file name
    variables = [make_var(file) for file in files]
    # Start list to place dfs into
    dfs = []
    for var,file in zip(variables,files):
        # Use globals to assign dfs to file names
        globals()[var] = pd.read_csv(file)
        #<<1>>
        # Add each newly made df var to a list
        dfs.append(var.drop_duplicates(subset =['user_id'])) # rmv duplicates
    return print('Your variables are: ',sorted(dfs))
</code>```

This returns an attribute error.It seems that the var is being treated as a str instead of a df

When I  len() a df, they remain the same as before. Even though when I individually df.drop_duplicates they shorten in len() by about 70%.

Alternatively, I have tried to make a mid object at <<1>> and then .drop_duplicates. This doesn't work and I believe its because the change is staying local.

答:
Fix

Adding .drop_duplicates(subset =['user_id']) to the end of the csv import, as they become globalised seemed to do the trick.

```<code>def assign_vars(files = os.listdir()):
    # Make list of variable names using file name
    variables = [make_var(file) for file in files]
    # Start list to place dfs into
    dfs = []
    for var,file in zip(variables,files):
        # Use globals to assign dfs to file names
        globals()[var] = pd.read_csv(file).drop_duplicates(subset =['user_id'])
        # Add each newly made df var to a list
        dfs.append(var) # rmv duplicates
    return print('Your variables are: ',sorted(dfs))
</code>```

Body:
Note: Correction - the code returns AttributeError: 'str' object has no attribute 'drop_duplicates'

I am trying to loop through a number of dfs and reduce my 'user_id' column to only unique values using the
df.drop_duplicates(subset =['user_id']
function.

I need this to be a global change and am trying to incorporate it into my function that imports .csv files and assigns them to their file name. This works perfectly but when I try and add the drop_duplicates function, it doesn't seem to do anything:

def assign_vars(files = os.listdir()):
    # Make list of variable names using file name
    variables = [make_var(file) for file in files]
    # Start list to place dfs into
    dfs = []
    for var,file in zip(variables,files):
        # Use globals to assign dfs to file names
        globals()[var] = pd.read_csv(file)
        #<<1>>
        # Add each newly made df var to a list
        dfs.append(var.drop_duplicates(subset =['user_id'])) # rmv duplicates
    return print('Your variables are: ',sorted(dfs))

This returns an attribute error.It seems that the var is being treated as a str instead of a df

When I  len() a df, they remain the same as before. Even though when I individually df.drop_duplicates they shorten in len() by about 70%.

Alternatively, I have tried to make a mid object at <<1>> and then .drop_duplicates. This doesn't work and I believe its because the change is staying local.

Body:
Fix

Adding .drop_duplicates(subset =['user_id']) to the end of the csv import, as they become globalised seemed to do the trick.

def assign_vars(files = os.listdir()):
    # Make list of variable names using file name
    variables = [make_var(file) for file in files]
    # Start list to place dfs into
    dfs = []
    for var,file in zip(variables,files):
        # Use globals to assign dfs to file names
        globals()[var] = pd.read_csv(file).drop_duplicates(subset =['user_id'])
        # Add each newly made df var to a list
        dfs.append(var) # rmv duplicates
    return print('Your variables are: ',sorted(dfs))


问:
Entity Framework 4.1 for large number of tables (715)
I'm developing a data access layer for a database with over 700 tables. I created the model including all the tables, which generated a huge model. I then changed the model to use DBContext from 4.1 which seemed to improve how it compiled and worked. The designer didnt seem to work at all.

I then created a test app which just added two records to the table, but the processor went 100% in the db.SaveChanges method. Being a black box it was difficult to accertain what went wrong.

So my questions are

Is the entity framework the best approach to a large database

If so, should the model be broken down into logical areas. I did note that you cant have the same sql table in multiple models

I have read that the code only approach is best in these large cases. What is that.

Any guidance would be truly appreciated

Thanks

答:
take a look this post.
http://blogs.msdn.com/b/adonet/archive/2008/11/24/working-with-large-models-in-entity-framework-part-1.aspx</p>


问:
404 on /signin-oidc multiple Client instances (data protection question)

Question

I'm working on an .NET Framework 4.7.2 MVC app, it's always behind a load balancer and works great unless I add a second instance of the MVC App.

IdentityServer4 itself is using data protection, however non core clients are having this issue.

I cannot find the data protection equivalent for .NET framework. Is there one, or am I seeing something different?

If I remove one instance from the loadbalancer, it works again.

Minimal working example

  app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
                SlidingExpiration = true
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = identityServerUrl,

                //Get this dynamically, register all possible values in IDS.
                //https://github.com/IdentityServer/IdentityServer3/issues/1458
                RedirectUri = redirectUrl,
                PostLogoutRedirectUri = postLogoutRedirectUrl,
                ResponseType = "code id_token",

                Scope = scope,
                SaveTokens = true,
                TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name",
                    RoleClaimType = "role"
                },
                RequireHttpsMetadata = false,
                SignInAsAuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
                UseTokenLifetime = false,
                AuthenticationType = "OIDC",

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async tokenValidatedNotification =>
                    {
                        try
                        {
                            logger.LogTrace("Entering AuthorizationCodeReceived {authTicketIdentity} {response}",
                                tokenValidatedNotification.AuthenticationTicket.Identity, tokenValidatedNotification.Response.StatusCode);

                            var claimsToKeep = tokenValidatedNotification.AuthenticationTicket.Identity.Claims.ToList();
                            claimsToKeep.Add(new Claim("id_token", tokenValidatedNotification.ProtocolMessage.IdToken));
                            // use the code to get the access and refresh token
#pragma warning disable CS0618 // Type or member is obsolete
                            var tokenClient = new TokenClient($"{identityServerUrl}/connect/token", clientId, clientSecret);
#pragma warning restore CS0618 // Type or member is obsolete

                            TokenResponse tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(
                                tokenValidatedNotification.ProtocolMessage.Code, redirectUrl);

                            if (tokenResponse.IsError)
                            {
                                throw new Exception($"Error authorizing user {tokenResponse.Error}, {tokenResponse.ErrorDescription}", tokenResponse.Exception);
                            }
                            // use the access token to retrieve claims from userinfo
#pragma warning disable CS0618 // Type or member is obsolete
                            var userInfoClient = new UserInfoClient($"{identityServerUrl}/connect/userinfo");
#pragma warning restore CS0618 // Type or member is obsolete
                            UserInfoResponse userInfoResponse = await userInfoClient.GetAsync(tokenResponse.AccessToken)
                                .ConfigureAwait(false);

                            if (userInfoResponse.IsError)
                            {
                                throw new Exception(userInfoResponse.Error, userInfoResponse.Exception);
                            }
                            claimsToKeep.AddRange(userInfoResponse.Claims);

                            // create new identity
                            var claimsIdentity = new ClaimsIdentity(tokenValidatedNotification.AuthenticationTicket
                                .Identity
                                .AuthenticationType, "name", "role");
                            claimsIdentity.AddClaims(userInfoResponse.Claims);

                           claimsIdentity.AddClaims(claimsToKeep);

                           var user = claimsIdentity.Claims.FirstOrDefault(x => x.Type == "sub");
                           if (user != null && user.Value.Contains('@'))
                           {
                               var username = user.Value.Split('@')[0];
                               if (!string.IsNullOrEmpty(username))
                               {
                                   //remove existing name claim
                                   var removeClaim = claimsIdentity.Claims.ToList().FirstOrDefault(x => x.Type == "name");
                                   if (removeClaim != null)
                                   {
                                       claimsIdentity.RemoveClaim(removeClaim);
                                   }
                                   //add username as name claim
                                   claimsIdentity.AddClaim(new Claim("name", username.ToLower()));
                               }
                           }

                            tokenValidatedNotification.AuthenticationTicket = new AuthenticationTicket(
                                claimsIdentity,
                                tokenValidatedNotification.AuthenticationTicket.Properties);

                            await Task.FromResult(0);
                        }
                        catch (Exception ex)
                        {
                            logger.LogError(ex, "SecurityTokenValidated error {authTicketIdentity}, {responseStatus} (failure)", tokenValidatedNotification.AuthenticationTicket.Identity, tokenValidatedNotification.Response.StatusCode);
                            throw;
                        }
                    },

                    RedirectToIdentityProvider = async redirectToIdpNotification =>
                    {
                        try
                        {
                            if (!BrowserSupportService.isBrowserSupported())
                            {
                                redirectToIdpNotification.Response.Redirect("/browserNotSupported");
                                redirectToIdpNotification.HandleResponse();
                            }
                            else
                            {
                                // if signing out, add the id_token_hint
                                if (redirectToIdpNotification.ProtocolMessage.RequestType ==
                                    OpenIdConnectRequestType.Logout)
                                {
                                    Claim idTokenHint =
                                        redirectToIdpNotification.OwinContext.Authentication.User.FindFirst("id_token");

                                    if (idTokenHint != null)
                                    {
                                        redirectToIdpNotification.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                                    }

                                    redirectToIdpNotification.ProtocolMessage.PostLogoutRedirectUri =
                                        postLogoutRedirectUrl;
                                    redirectToIdpNotification.Options.PostLogoutRedirectUri = postLogoutRedirectUrl;
                                }

                                if (redirectToIdpNotification.ProtocolMessage.RequestType ==
                                    OpenIdConnectRequestType.Authentication
                                    && IsAjaxRequest(redirectToIdpNotification.Request) &&
                                    redirectToIdpNotification.Response.StatusCode == (int) HttpStatusCode.Unauthorized)
                                {
                                    redirectToIdpNotification.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
                                    redirectToIdpNotification.HandleResponse();
                                }
                            }
                            await Task.FromResult(0);
                        }
                        catch (Exception ex)
                        {
                            logger.LogError(ex, "RedirectToIdentityProvider error");
                            throw;
                        }
                    }
                }
            });
```

<h3>Relevant parts of the log file</h3>

```IdentityServer logs are successful, no errors/warnings during this.
```

答:
I solved this some years ago at the company where I was working. The cause was that default ASP.Net authentication cookie decryption only worked on the server that created / encrypted the cookie.

To resolve the problem I'm pretty sure you just need to add a machine key to your web.config files - and make sure it the same on both servers.

As a first step, maybe try copying in the values from this article - then generate your own keys later if it works:
https://www.iambacon.co.uk/blog/getting-asp-net-authentication-to-work-on-a-web-farm

Body:
Question

I'm working on an .NET Framework 4.7.2 MVC app, it's always behind a load balancer and works great unless I add a second instance of the MVC App.

IdentityServer4 itself is using data protection, however non core clients are having this issue.

I cannot find the data protection equivalent for .NET framework. Is there one, or am I seeing something different?

If I remove one instance from the loadbalancer, it works again.

Minimal working example

  app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
                SlidingExpiration = true
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = identityServerUrl,

                //Get this dynamically, register all possible values in IDS.
                //https://github.com/IdentityServer/IdentityServer3/issues/1458
                RedirectUri = redirectUrl,
                PostLogoutRedirectUri = postLogoutRedirectUrl,
                ResponseType = "code id_token",

                Scope = scope,
                SaveTokens = true,
                TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name",
                    RoleClaimType = "role"
                },
                RequireHttpsMetadata = false,
                SignInAsAuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
                UseTokenLifetime = false,
                AuthenticationType = "OIDC",

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async tokenValidatedNotification =>
                    {
                        try
                        {
                            logger.LogTrace("Entering AuthorizationCodeReceived {authTicketIdentity} {response}",
                                tokenValidatedNotification.AuthenticationTicket.Identity, tokenValidatedNotification.Response.StatusCode);

                            var claimsToKeep = tokenValidatedNotification.AuthenticationTicket.Identity.Claims.ToList();
                            claimsToKeep.Add(new Claim("id_token", tokenValidatedNotification.ProtocolMessage.IdToken));
                            // use the code to get the access and refresh token
#pragma warning disable CS0618 // Type or member is obsolete
                            var tokenClient = new TokenClient($"{identityServerUrl}/connect/token", clientId, clientSecret);
#pragma warning restore CS0618 // Type or member is obsolete

                            TokenResponse tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(
                                tokenValidatedNotification.ProtocolMessage.Code, redirectUrl);

                            if (tokenResponse.IsError)
                            {
                                throw new Exception($"Error authorizing user {tokenResponse.Error}, {tokenResponse.ErrorDescription}", tokenResponse.Exception);
                            }
                            // use the access token to retrieve claims from userinfo
#pragma warning disable CS0618 // Type or member is obsolete
                            var userInfoClient = new UserInfoClient($"{identityServerUrl}/connect/userinfo");
#pragma warning restore CS0618 // Type or member is obsolete
                            UserInfoResponse userInfoResponse = await userInfoClient.GetAsync(tokenResponse.AccessToken)
                                .ConfigureAwait(false);

                            if (userInfoResponse.IsError)
                            {
                                throw new Exception(userInfoResponse.Error, userInfoResponse.Exception);
                            }
                            claimsToKeep.AddRange(userInfoResponse.Claims);

                            // create new identity
                            var claimsIdentity = new ClaimsIdentity(tokenValidatedNotification.AuthenticationTicket
                                .Identity
                                .AuthenticationType, "name", "role");
                            claimsIdentity.AddClaims(userInfoResponse.Claims);

                           claimsIdentity.AddClaims(claimsToKeep);

                           var user = claimsIdentity.Claims.FirstOrDefault(x => x.Type == "sub");
                           if (user != null && user.Value.Contains('@'))
                           {
                               var username = user.Value.Split('@')[0];
                               if (!string.IsNullOrEmpty(username))
                               {
                                   //remove existing name claim
                                   var removeClaim = claimsIdentity.Claims.ToList().FirstOrDefault(x => x.Type == "name");
                                   if (removeClaim != null)
                                   {
                                       claimsIdentity.RemoveClaim(removeClaim);
                                   }
                                   //add username as name claim
                                   claimsIdentity.AddClaim(new Claim("name", username.ToLower()));
                               }
                           }

                            tokenValidatedNotification.AuthenticationTicket = new AuthenticationTicket(
                                claimsIdentity,
                                tokenValidatedNotification.AuthenticationTicket.Properties);

                            await Task.FromResult(0);
                        }
                        catch (Exception ex)
                        {
                            logger.LogError(ex, "SecurityTokenValidated error {authTicketIdentity}, {responseStatus} (failure)", tokenValidatedNotification.AuthenticationTicket.Identity, tokenValidatedNotification.Response.StatusCode);
                            throw;
                        }
                    },

                    RedirectToIdentityProvider = async redirectToIdpNotification =>
                    {
                        try
                        {
                            if (!BrowserSupportService.isBrowserSupported())
                            {
                                redirectToIdpNotification.Response.Redirect("/browserNotSupported");
                                redirectToIdpNotification.HandleResponse();
                            }
                            else
                            {
                                // if signing out, add the id_token_hint
                                if (redirectToIdpNotification.ProtocolMessage.RequestType ==
                                    OpenIdConnectRequestType.Logout)
                                {
                                    Claim idTokenHint =
                                        redirectToIdpNotification.OwinContext.Authentication.User.FindFirst("id_token");

                                    if (idTokenHint != null)
                                    {
                                        redirectToIdpNotification.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                                    }

                                    redirectToIdpNotification.ProtocolMessage.PostLogoutRedirectUri =
                                        postLogoutRedirectUrl;
                                    redirectToIdpNotification.Options.PostLogoutRedirectUri = postLogoutRedirectUrl;
                                }

                                if (redirectToIdpNotification.ProtocolMessage.RequestType ==
                                    OpenIdConnectRequestType.Authentication
                                    && IsAjaxRequest(redirectToIdpNotification.Request) &&
                                    redirectToIdpNotification.Response.StatusCode == (int) HttpStatusCode.Unauthorized)
                                {
                                    redirectToIdpNotification.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
                                    redirectToIdpNotification.HandleResponse();
                                }
                            }
                            await Task.FromResult(0);
                        }
                        catch (Exception ex)
                        {
                            logger.LogError(ex, "RedirectToIdentityProvider error");
                            throw;
                        }
                    }
                }
            });

Relevant parts of the log file

IdentityServer logs are successful, no errors/warnings during this.