text:
Q: Characterization of maps with $\mathbb{Z}/2\mathbb{Z}$-equivariant lifts. I'm interested in characterizing maps $f:\mathbb{R}P^k\to\mathbb{R}P^\infty$ that lift to a $\mathbb{Z}/2\mathbb{Z}$-equivariant map $\tilde{f}:S^k\to S^\infty$.
For $k\geq 2$ I have been able to prove:
$$
(1)\;f\text{ lifts to a }\mathbb{Z}/2\mathbb{Z}\text{- equivariant map} \iff f_\#:\pi_1(\mathbb{R}P^k)\to \pi_1(\mathbb{R}P^\infty) \text{ is an isomorphism} \; (2)
$$
where $f_\#$ is the induced map on the fundamental group.
But I'm much more interested in a statement about the induced maps on (co)homology with $\mathbb{Z}/2\mathbb{Z}$-coefficients.
In particular: Is the following equivalence true? If so, how does one prove this?

$$(1)\iff f_*:H_k(\mathbb{R}P^k;\mathbb{Z}/2\mathbb{Z})\to H_k(\mathbb{R}P^\infty;\mathbb{Z}/2\mathbb{Z})\text{ is an isomorphism}\quad (3)$$
  Or even better:
  $$(1)\iff f_*:H_i(\mathbb{R}P^k;\mathbb{Z}/2\mathbb{Z})\to H_i(\mathbb{R}P^\infty;\mathbb{Z}/2\mathbb{Z})\text{ is an isomorphism for }i\leq k \quad (4)$$

Edit: I have been able to prove the above statements.
In fact $(1)$ is equivalent to the following statements (coefficients are in $\mathbb{Z}/2\mathbb{Z}$):

*

*$\exists i\in\{1,\ldots, k\}$ such that $ f_*:H_i(\mathbb{R}P^k)\to H_i(\mathbb{R}P^\infty)$ is an isomorphism

*$\forall i\in\{1,\ldots, k\}:$ $ f_*:H_i(\mathbb{R}P^k)\to H_i(\mathbb{R}P^\infty)$ is an isomorphism

*$\exists i\in\{1,\ldots, k\}$ such that $ f^*:H^i(\mathbb{R}P^\infty)\to H^i(\mathbb{R}P^k)$ is an isomorphism

*$\forall i\in\{1,\ldots, k\}:$ $ f^*:H^i(\mathbb{R}P^\infty)\to H^i(\mathbb{R}P^k)$ is an isomorphism

Since I now know the answer to my own question I will probably delete it soon. At least if there is no activity here during the next few days.


text:
Q: Trigger a click on a specific tab loaded inside iframe I'm just trying to trigger a click on a particular tab using JS/jQuery. I'm having a web page which contains a iframe & which has number of tabs, loading page using ajax.
I'm able to find the specific tab:
$('#decider').find('iframe').contents().find('[data-tab="lay_customblock"] a').length;

And, also can able to give css color for that tab:
$('#decider').find('iframe').contents().find('[data-tab="lay_customblock"] a').css('color','#900')

But my issue is that, I was not able to trigger a click on that tab, i have tried:
$('#decider').find('iframe').contents().find('[data-tab="lay_customblock"] a').trigger('click');

I have check all this in code & also using browser console.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Groupby to Count Frequency of Unique Values in Set I have a DF like this
   User      Dept
    1        Cook
    1        Cook
    1        Home
    2        Sports
    2        Travel
    2        Cook

I want to count the unique users within each department:
   Dept      User
   Cook      2
   Home      1
   Sports    1
   Travel    1

Notice how the department Cook only has a count of two because even though three users were found in 'Cook', there were only two unique users
I have tried the following:
 df.groupby(['Dept']).count()  -- counts 'Cook' three times
 df.drop_duplicates(['Dept']).groupby('Dept')['User'].sum() -- over counts all departments

I know the answer is a groupby, I just can't seem to figure it out!

A: You could use nunique:
>>> df.groupby("Dept")["User"].nunique()
Dept
Cook      2
Home      1
Sports    1
Travel    1
Name: User, dtype: int64
>>> df.groupby("Dept")["User"].nunique().reset_index()
     Dept  User
0    Cook     2
1    Home     1
2  Sports     1
3  Travel     1

(Note that I used your example data, which only has one unique user in Sports.)


text:
Q: ActiveRecord belongs_to with an 'or' statement I've got a bit of a strange system here where the app I'm developing has a local db, but also connects to an external db for some data.
One of the requirements was that if a manufacturer is not found in the external db, it have a temporary entry created in the local db until the external db can be updated (not under my control, but usually happens within 48 hours).
So, what I created was a temp_manufacturer table which would hold the details until the manufacturer is added to the external db.
That works fine, with the exception that products belong_to manufacturers, and I can't add a product it seems until the manufacturer is in the external db. In my products model I have

class Product < ActiveRecord::Base
        validates_uniqueness_of :sku
        validates_presence_of :manufacturer

    has_many :categories
    belongs_to :manufacturer
end

Of course, the problem here is that though I'm passing a manufacturer_id, the manufacturer_id is not in the manufacturer table in the external database.
What I was hoping to do was something like

validates_presence_of :manufacturer || :temp_manufacturer

belongs_to :manufacturer || :temp_manufacturer

but it doesn't seem like this is possible.
Is there another way to 'fake' a parent > child relationship like this?
Unfortunately it isn't possible for me to update the manufacturer table from my app, though I am able to get the id which will be used for the new manufacturer.


text:
Q: Array jQuery - Remover indices e concatenar html Estou realizando uma chamada ajax que me retona o Html de filtros a serem postos em uma determinada div.
Contudo gostaria de remover alguns elementos do html previamente. Para isso passei o html para o jQuery, assim transformando-o em um array.
Apos remover os elementos gostaria de retomar o html concatenado.
Atualmente estou fazendo assim:
msg = jQuery(msg);
var index = 0;
var html = '';
msg.each(function(i, _this){
    if(jQuery(_this).find('input[type="submit"]').size() == 1){
        index = i;
        return;
    }
});
msg.splice(index,2);
msg.each(function(){
    html += this.outerHTML
});

Exemplo
Mas não estou muito contente com o desenvolvimento, alguém saberia como deixar essa função melhor?

A: Vou te dá dois conselhos:

*

*jQuery não é uma ferramenta obrigatoria para manipular o DOM.

*Você não precisa recriar todos os elementos para poder remover um nó.

var submits = document.querySelectorAll("p input[type='submit']")
[].forEach.call(submits, function (elemento, indice) {
  elemento.parentNode.removeChild(elemento);
});

 <input name="teste1" type="text" />

 <input name="teste2" type="text" />

 <input name="teste3" type="text" />

 <input name="teste4" type="text" />

 <input name="teste5" type="text" />

 <input type="submit" />

A: Utilizando da resposta fornecida pelo @TobyMosque e pesquisando mais um pouco.
Cheguei a esta solução, que se adequá mais ao caso, pois como comentei o HTML vem via Ajax. Ou Seja é uma string, então basicamente eu gostaria de tratar a string.
var doc = new DOMParser().parseFromString(msg, 'text/html');
var submits = doc.querySelectorAll("P input[type='submit']");
[].forEach.call(submits, function (elemento, indice){
    elemento.parentNode.removeChild(elemento);
});
var htmlFinal = doc.body.innerHTML


text:
Q: GAE remote api: RemoteApiInstaller install always fail GAE remote API for java :Configuring Remote API on an App Engine Client
RemoteApiInsideAppEngineExample(String username, String password)
        throws IOException {
        // Authenticating with username and password is slow, so we'll do it
        // once during construction and then store the credentials for reuse.
        this.options = new RemoteApiOptions()
            .server("your_target_app_id.appspot.com", 443)
            .credentials(username, password);
        RemoteApiInstaller installer = new RemoteApiInstaller();
        installer.install(options);
        try {
            // Update the options with reusable credentials so we can skip
            // authentication on subsequent calls.
            options.reuseCredentials(username, installer.serializeCredentials());
        } finally {
            installer.uninstall();
        }
    }

In my test it always throw exception:
java.lang.IllegalArgumentException: charset may not be null or empty
    at com.google.appengine.repackaged.org.apache.commons.httpclient.util.EncodingUtil.getString(Unknown Source)
    at com.google.appengine.repackaged.org.apache.commons.httpclient.util.EncodingUtil.getString(Unknown Source)
    at com.google.appengine.tools.remoteapi.AppEngineClient$Response.getBodyAsString(AppEngineClient.java:138)
    at com.google.appengine.tools.remoteapi.RemoteApiInstaller.getAppIdFromServer(RemoteApiInstaller.java:318)
    at com.google.appengine.tools.remoteapi.RemoteApiInstaller.loginImpl(RemoteApiInstaller.java:278)
    at com.google.appengine.tools.remoteapi.RemoteApiInstaller.login(RemoteApiInstaller.java:239)
    at com.google.appengine.tools.remoteapi.RemoteApiInstaller.install(RemoteApiInstaller.java:106)

.....
I'm sure the username and password is admin one, I use GAE 1.7, Federated Login, High Replication Datastore.
Any ideas?
Thanks.

A: The code was working on me. You Just need to be sure that your replace the "your_target_app_id" by the applicationID

A: I think i found the answer, i use federated login, and currently GAE remote API does not support federated login---so bad that i spent much time on debugging.


text:
Q: difference between C++ template partial specialization for function and functor I have been using C++ template class partial specialization for function argument for a while. I was surprised to find that the same syntax could be used to partial specialize functors.
In the case 1 below, it is easy to see F(T) is a function type. Since it is a type, it could be used to substitute the template parameter, however in case 2, the semantics of F(T) is changed, it is not a type but still can pass the compiler and work.
I googled a few hours, but not found too much valuable info in this regard. Could anyone explain why case 2 worked?
template<class> struct func;

template<class F, class T>
struct func<F(T)>              //1. this is a partial specialization for function
{                              //with signature F(T)
   using type = F(T);
};

template<class> struct ftor;
template<class F, class T>
struct ftor<F(T)>              //2. Is F(T) a type?
{
   using type = F;
};

struct foo {
  void operator()(int) {}
};

int main() {
    //1 void(int) is a function signature
    cout<<typeid(typename func<void(int)>::type).name()<<endl;
    //2 what is foo(int)?
    cout<<typeid(typename ftor<foo(int)>::type).name()<<endl;
    return 0;
}

A: In the 2 cases, F(T) is a signature of function taking T and returning F.
You may rename your class func by identity and ftor by result_of and F by ReturnType to better match naming/implementation.


text:
Q: How to disable a component from enlarging JPanel in GridBagLayout? So in my code I create a window which presents you with two options, each option is a JLabel on top of a JButton.  However, when the text in one of the JLabels is too long, it pushes the other "side" out of the frame, so you have to stretch the width of the frame to even be able to see the other button.
Here's how it looks:
How it's supposed to look:

How it looks when the text is too long

How do I make it so that the JLabel doesn't push the other side out of the frame  I tried to use setMaximumSize() but that doesn't seem to do anything.
Here's the snippet of code that governs this:
    GridBagConstraints c = new GridBagConstraints();
    JPanel options = new JPanel(new GridBagLayout());

    JLabel artistOne = new JLabel(one.getArtist());
    JLabel artistTwo = new JLabel(two.getArtist());
    JButton albumOne = new JButton(one.getName());
    JButton albumTwo = new JButton(two.getName());

    albumOne.addActionListener(this);
    albumTwo.addActionListener(this);

    artistOne.setMaximumSize(new Dimension(100, 100));
    artistTwo.setMaximumSize(new Dimension(100, 100));
    albumOne.setMaximumSize(new Dimension(100, 100));
    albumTwo.setMaximumSize(new Dimension(100, 100));

    c.insets = new Insets(0, 25, 0, 25);

    c.gridx = 0;
    c.gridy = 0;
    options.add(artistOne, c);

    c.gridx = 0;
    c.gridy = 1;
    options.add(albumOne, c);

    c.gridheight = 1;
    c.gridx = 2;
    c.gridy = 0;
    options.add(artistTwo, c);

    c.gridx = 2;
    c.gridy = 1;
    options.add(albumTwo, c);

    pane.add(options);


text:
Q: How can I create a div/button with stacked text inside? I've been trying to figure out how to produce this in CSS:

However, when I've tried this thus far, it's only partially been on track:

How can I fix the below CSS and HTML so that it works as a stacked text meter properly? I do have Bootstrap, and I'm using SCSS/SASS.
A Pen with the same code, including the full menu, shows the same issue:
https://codepen.io/anon/pen/zLYWZR

.buFontSize {
    font-size: 11px;
    padding: 0px;
}

.pointButton {
    display: block;
    border: rgba(255, 255, 255, 0.534) 1px solid !important;
    justify-content: center;
    padding: 0px !important;
}

.buttonBlock {
    display: block;
}

    Link One

        Link Two

        Link Three

                Games

                100000

A: You can use a button group with a br:

body {
  background-color: black !important; /* test only */
}

.btn-group .btn {
  background: transparent;
  color: #ffffff;
  border: 1px solid #ffffff;
  line-height:1;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />

    Games

    10000

    Points

    000000

Example bootply

A:

.buFontSize {
    font-size: 11px;
    color: #fff;
    padding: 0px;
}

.pointButton {
    display: block;
    border: rgba(255, 255, 255, 0.534) 1px solid;
    background: #000;
    justify-content: center;
    padding: 0px;
}

.buttonBlock {
    display: block;
    padding: 0px;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>

           Games

           100000

A: try this

body{
  background-color: black;
}
.buttonBlock{
 float: left;
 margin: 0;
 padding: 0;
 border: 1px solid white;
 width: 120px;
 text-align: center;
 display: inline-block;
  color: white;
}

.buttonBlock > span{
 display: block;
}

.buttonBlock:first-child{
 border-radius: 5px 0 0 5px;
 -webkit-border-radius: 5px 0 0 5px;
 -moz-border-radius: 5px 0 0 5px;
 -ms-border-radius: 5px 0 0 5px;
 -o-border-radius: 5px 0 0 5px;
}

.buttonBlock:last-child{
 border-radius: 0 5px 5px 0;
 -webkit-border-radius: 0 5px 5px 0;
 -moz-border-radius: 0 5px 5px 0;
 -ms-border-radius: 0 5px 5px 0;
 -o-border-radius: 0 5px 5px 0;
}

.buttonBlock:not(:first-child){
 border-left: 0;
}

   First
   100000

   Second
   100000

   Third
   100000

   Fourth
   100000

   Fifth
   100000

A: Maybe Use
.somewrapperclass{
    display: flex;
    flex-flow: wrap row;
    align-items: flex-start;
}

Don't use display block as there is a better alternative, check this complete guide to flexbox


text:
Q: Rails 4 - sending devise params to a User model method i have my own RegistrationsController, which inherits from Devise. In update I want to send params to my User method like above:
def update
   params = resource.delete_invoice(params) if resource.check_invoice(params[:user])
   if params[:user][:name].blank?
      flash[:alert] = t 'devise.registrations.wrong_user_name'
      redirect_to action: 'edit' and return
  end
  super
end

Unfortunatelly i get error:
NoMethodError in Users::RegistrationsController#update, undefined method `[]' for nil:NilClass

It's strange because I can normally write puts params and it's not empty. How can I resolve this?

A: Try this:
unless params[:user].blank?
  if params[:user][:name].blank?
    #do your stuff
  end
end

A: The error here is that it is trying to call [] on a nil object, as it is very unlikely that params or flash is nil, the only other place you call [] is on params[:user] which suggests that this is nil.
Couple of options, check if params[:user] is nil or use try:
if params[:user].nil? or params[:user][:name].blank?
      flash[:alert] = t 'devise.registrations.wrong_user_name'
      redirect_to action: 'edit' and return
end

Alternatively:
if params[:user].try(:fetch, :name).try(:blank?)
      flash[:alert] = t 'devise.registrations.wrong_user_name'
      redirect_to action: 'edit' and return
end

Which I think is neater. NB try is a rails method, not ruby.

A: Are you sure the resource is built when you run update? In Rails 4 the build_resource is being built inside that method devise/registrations_controller. Probably you want to use resource_class?


text:
Q: Ice in contact with a heat reservoir at $0^\circ \textrm{C}$? Let us say I put ice starting at a temperature $T \lt 0^\circ \textrm{C}$, and held at constant pressure of $1atm$ in contact with an infinite heat reservoir at temperature exactly  $0^\circ \textrm{C}$. When we have reached an equilibrium state will we have just ice, water and ice, or just water?
I doubt the answer is going to be just water, but between the other two I do not know.

A: TL;DR: If the ice has surfaces then it will completely melt to form water. If the ice has no surfaces (it's infinitely large) then it will remain completely ice.
Here's the reasoning:
If we imagine an idealised system that is infinitely large in extent (i.e. no surfaces and therefore no heterogeneous nucleation) then the ice will remain in an ice state, with small water nuclei that spontaneously form and then disappear again. To see why, consider how the free energy changes when a water nucleus of radius $r$ forms:
$$ \Delta G=-\Delta G_V (4\pi r^3/3) + \gamma(4\pi r^2) $$
where $\Delta G_V$ is the difference in free energy between the bulk phases, and $\gamma$ is the surface free energy. At the coexistence point, $\Delta G_V=0$ by definition, and so the the growth of a water phase will only ever cost energy (i.e. there's no critical size). The size distribution of these random water droplets will be given by the Boltzmann distribution:
$$ P\propto \exp(-4\pi r^2 \gamma/k_BT) $$
In the real world, the ice will have surfaces. And the surface energy of ice is greater than that of water, so the outer layers will melt, resulting in a block of ice surrounded by a layer of water. As before, since neither bulk phase is preferred, then the system will move towards the state that minimises the interfacial free energy, and so the ice in the core will shrink in size until it disappears.
The result is pure water with tiny ice nuclei spontaneously forming and melting with the same size distribution as before ($P\propto \exp(-4\pi r^2 \gamma/k_BT)$).

A: The ice would rise to the same temperature as the reservoir (0 C).  Once it got to that temperature, there would be no more driving force for heat transfer, and the system would be in equilibrium.  So it would be the same as if you took any solid block of any material at T < 0 C and put it in contact with an ideal infinite reservoir at 0 C.  There would be transient conduction within the block until the system equilibrated at 0 C.

A: The answer of Lemon is Practically correct (-> Water), but I want to give another approach; QED.
First we need just to think what is HEAT? It's just kinetic "jiggling" of atoms. The carousel is rotating faster/with bigger radius when there is more heat.
What is melting of ice? (Or what is Solid-liquid change on state in matter?) It's the process where the atoms starts to flow freely compared to each other.
The basic question here is; Does a single molecule "know" if it's solid or if it's liquid. The Answer is of course; it doesn't, there is no difference to single atom if it's part of solid / liquid / gas / plasma. It's merely an issue of enough electromagnetic forces able to hold the molecule in it's position compared to others.
This thinking can be brought even below the molecule-level. Water molecule $H_2O$ is 2x Hydrogen + 1 x Oxygen. And with normal flowing water, the hydrogen atom doesn't even know which oxygen atom it's supposed to form the molecule with. And thus in fluid the hydrogen bonds are continually breaking and reforming at timescales faster than 200 femtoseconds.
This is the major difference of Solid ice and liquid water; on solid-ice the atoms are locked on the lattice structure.
Answer; The whole ice will turn in to water over time, because at melting temperature, the Heat of hydrogen is too great; there is nothing which would maintain the lattice structure; not even in idealized infinitely large system. The Melting will happen spontaneously throughout the whole matter, according to QED probabilities if there just is the needed Heat provided to keep up this process.

A: Since the heat reservoir has exactly 0 deg. the ice would heat to reach the same temperature, but ideally it would not change since it's directly the freezing/melting point. Melting ice would require additional energy.
In case of being submerged in water at freezing point:
It depends on the initial temperature of ice. Since the thermal equilibrium is 0 deg. C. the ice would heat up to 0 deg.
The energy lost by ice would be consumed by water for phase transition, thus creating additional ice layer.
Simple response: the amount of ice would increase depending on initial ice temperature.


text:
Q: HttpUrlConnection setConnectTimeout doesn't work? I'm trying to get use of setConnectTimeout function like this:
protected HttpURLConnection getConnection() throws SocketTimeoutException, IOException{
    Log.d("HTTPRequest", address);
    URL page = new URL(address);
    HttpURLConnection connection = (HttpURLConnection) page.openConnection();

    connection.setUseCaches(cacheResult);
    connection.setConnectTimeout(3000);
    connection.connect();
    return connection;
}

and then:
public String getTextData() throws InternetConnectionUnavailableException {
    try{
        HttpURLConnection conn = getConnection();
        StringBuffer text = new StringBuffer();
        InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
        BufferedReader buff = new BufferedReader(in);
        String line;

        while (true) {
            if((line = buff.readLine()) != null){
                text.append(line);
            }else{
                break;
            }
        }
        return (text.toString());
    } catch (SocketTimeoutException socketTimeoutException) {
            throw new InternetConnectionUnavailableException();
    } catch (IOException ioException) {
            throw new InternetConnectionUnavailableException();
    }
}

However, it never gets in the "catch (SocketTimeoutException socketTimeoutException)" block. What's wrong here.
P.S. For the testing I've made a page that puts my server into sleep for 10 seconds.

A: try this:
try {

   HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
   con.setRequestMethod("HEAD");

   con.setConnectTimeout(5000); //set timeout to 5 seconds
   con.setReadTimeout(socketTimeout);
   return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (java.net.SocketTimeoutException e) {
   e.printStackTrace();
} catch (java.io.IOException e) {
    e.printStackTrace();
}


text:
Q: Работа с скролом у блока Возникло несколько моментов с прокруткой блока. Прошу заметить, тут меня не интересует прокрутка страницы, как оказалось... оно работает иначе.
1. Как запустить функцию js когда до  начала блока(конца в моём случае) осталось 200px.
2. Как перемещать человека в самый конец (начало в  моём случае) блока при загрузке страницы
Приведу примеры, что у меня не работает
Прокрутка  в конец

 window.onload = function() {
  var objDiv = document.getElementById("#logick");
  objDiv.scrollTop = objDiv.scrollHeight;
 };
#logick{
  height: 5000px;
  width: 600px;
}

А вот не рабочий вариант запуска функции

$(window).scroll(function () {
  if ($("#logick").scrollTop() <= 200) {
    alert();
  }
});
#logick{
  height: 5000px;
  width: 600px;
}

A: Если касаемо конкретно прокрутки в блоке то будет вот так.

var anchor = true;

function fuckingFunction(){
  if(anchor){
    alert('Hello World, I am fucking function, меня запустили один раз за 200px до конца искомого блока и счас вас прокрутят обратно вверх, потому что мне кажется что вы прочли не все лоремы');
    var topBlock = $('.on_this').offset().top;
   $('html, body').animate({scrollTop: topBlock}, 2000);
    anchor = false;
  }
}

$(window).on('scroll', function(e){
   if( ($('.on_this').offset().top + $('.on_this').height() -200) < ($(window).scrollTop()+ $(window).height())){
   fuckingFunction();
   }
}); //запуск функции за 200px до конца блока.

$(document).ready(function(){
 var topBlock = $('.on_this').offset().top;
  $('html, body').animate({scrollTop: topBlock}, 2000);
}); //прокрутка до верха нужного блока искомого блока
.on_this{
  color: coral;
  border: 1px dashed coral;
  border-radius: 8px;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam iusto vel dolore quod sit perspiciatis repellat voluptatem magnam impedit! Illo in nobis eos. Voluptate sapiente repellendus, aspernatur, non ipsum optio. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id sed nam eveniet architecto repellat similique officiis facilis molestias sit doloremque, nisi illum et officia maiores, vero magni itaque expedita rerum. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam iusto vel dolore quod sit perspiciatis repellat voluptatem magnam impedit! Illo in nobis eos. Voluptate sapiente repellendus, aspernatur, non ipsum optio. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id sed nam eveniet architecto repellat similique officiis facilis molestias sit doloremque, nisi illum et officia maiores, vero magni itaque expedita rerum.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam iusto vel dolore quod sit perspiciatis repellat voluptatem magnam impedit! Illo in nobis eos. Voluptate
ore quod sit perspiciatis repellat voluptatem magnam impedit! Illo in nobis eos. Voluptate sapiente repellendus, aspernatur, non ipsum optio. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id sed nam eveniet architecto repellat similique officiis facilis molestias sit doloremque, nisi illum et officia maiores, vero magni itaque expedita rerum. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam iusto vel dolore quod sit perspiciatis repellat voluptatem magnam impedit! Illo in nobis eos. Voluptate sapiente repellendus, aspernatur, non ipsum optio. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id sed nam eveniet architecto repellat similique officiis facilis molestias sit doloremque, nisi illum et officia maiores, vero magni itaque expedita rerum.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam iusto vel dolore quod sit perspiciatis repellat voluptatem magnam impedit! Illo in nobis eos. Voluptatsapiente repellendus, aspernatur, non ipsum optio. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id sed nam eveniet architecto repellat similique officiis facilis molestias sit doloremque, nisi illum et officia maiores, vero magni itaque expedita rerum.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam iusto vel dolore quod sit perspiciatis repellat voluptatem magnam impedit! Illo in nobis eos. Voluptate sapiente repellendus, aspernatur, non ipsum optio. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id sed nam eveniet architecto repellat similique officiis facilis molestias sit doloremque, nisi illum et officia maiores, vero magni itaque expedita rerum.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam iusto vel dolore quod sit perspiciatis repellat voluptatem magnam impedit! Illo in nobis eos. Voluptate sapiente repellendus, aspernatur, non ipsum optio. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id sed nam eveniet architecto repellat similique officiis facilis molestias sit doloremque, nisi illum et officia maiores, vero magni itaque expedita rerum.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam iusto vel dolore quod sit perspiciatis repellat voluptatem magnam impedit! Illo in nobis eos. Voluptate sapiente repellendus, aspernatur, non ipsum optio. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id sed nam eveniet architecto repellat similique officiis facilis molestias sit doloremque, nisi illum et officia maiores, vero magni itaque expedita rerum.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam iusto vel dolore quod sit perspiciatis repellat voluptatem magnam impedit! Illo in nobis eos. Voluptate sapiente repellendus, aspernatur, non ipsum optio. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id sed nam eveniet architecto repellat similique officiis facilis molestias sit doloremque, nisi illum et officia maiores, vero magni itaque expedita rerum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

A:

var anchor = true;

function fuckingFunction(){
  if(anchor){
    alert('Hello World, I am fucking function, меня запустили один раз за 200px до искомого блока');
    anchor = false;
  }
}

$(window).on('scroll', function(e){
    if ($('html, body').scrollTop()+$(window).height() > $('.on_this').offset().top -200) {
       fuckingFunction();
    }
}); //запуск функции за 200px до блока.

$(document).ready(function(){
 var bottomBlock = $('.on_this').offset().top - $(window).height() + $('.on_this').height();
  $('html, body').animate({scrollTop: bottomBlock}, 2000);
}); //прокрутка до низа искомого блока
.on_this{
  color: coral;
  border: 1px dashed coral;
  border-radius: 8px;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae voluptates, nihil in repellat, totam rerum libero et iste expedita impedit culpa architecto quos, eos ipsam officia nemo ipsum perferendis ab.


text:
Q: What is this inductor symbol? Straight line with 90° and 45° intersection lines In the picture below, what does the symbol labeled with "L11" stand for?
The letter L and the 10uH suggest it is some kind of inductor, but the symbol seems rather non-standard to me.

A: It looks like the symbol of an iron core with winding, resulting in an inductance of \$10 \mu H\$.
Source:

A: Back when, those used to be used widely to create memory arrays.

A 32 x 32 core memory plane storing a whopping 1024 bits of data.

Up close
In fact, a company where I worked was still knitting them for the military back in the early 90s. They are probably still using some.


text:
Q: Handling signals across several QMLs I just began learning about Qt programming and found myself struggling with the signals and slot mechanism while making a simple test application.
I have two QML files: main.qml and grocery.qml.
I have a header file that manages the signals and slots of the application:
applicationamanger.h
#ifndef APPLICATIONMANAGER_H
#define APPLICATIONMANAGER_H
#include <QObject>
#include <QDebug>
class ApplicationManager : public QObject
{
    Q_OBJECT
public:
    explicit ApplicationManager(QObject *parent = 0);

signals:
    void newGroceryItem();

public slots:
    void addGroceryItem();
};
#endif // APPLICATIONMANAGER_H

The user starts the application on main.qml and when pressing a button loads grocery.qml
On grocery.qml I have an image that can be clicked by the user and emits the signal newGroceryItem()
MouseArea {
    id: okBtnClkd
    anchors.fill: parent
    Connections {
        onClicked: {
            newGroceryItem()
        }
    }
}

And the main application main.cpp connects the signals but says it can't find the signal newGroceryItem() as it doesn't belong to main.qml. So my question is, how can I establish the connection to the slot addGroceryItem() from the secondary qml file grocery.qml?
EDIT:
As requested here're the contents of main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickWindow>
#include <QQmlContext>
#include "applicationmanager.h"
int main(int argc, char *argv[]){
  QGuiApplication app(argc, argv);
  QQmlApplicationEngine engine;
  engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

  QObject *topLevel = engine.rootObjects().value(0);
  QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
  ApplicationManager applicationManager;
  QObject::connect(window, SIGNAL(newGroceryItem()), &applicationManager, SLOT(addGroceryItem()));

  return app.exec();
}

And the contents of grocery.qml
import QtQuick 2.5
import QtQuick.Controls 1.4

ApplicationWindow {
    //Declaration of signals.
    signal newGroceryItem()

    width: 300
    height: 400
    visible: true
    TextField {
        id: product
        x: 14
        y: 111
        width: 270
        height: 22
    }
    Text {
        id: text1
        x: 14
        y: 81
        width: 124
        height: 24
        text: qsTr("Product")
        font.pixelSize: 20
    }
    Image {
        id: okBtn
        x: 99
        y: 290
        width: 100
        height: 100
        source: "img/main/okBtn.png"

        MouseArea {
            id: okBtnClkd
            anchors.fill: parent
            Connections {
                onClicked: {
                    newGroceryItem()
                }
            }
        }
    }
}

A: Any method of a QObject-derived type is accessible from QML code if it is:

*

*a public method flagged with the Q_INVOKABLE macro

*a method that is a public Qt SLOT

So there are two ways to access addGroceryItem(). The first one is to use Q_INVOKABLE macro as follows:
class ApplicationManager : public QObject
{
    Q_OBJECT
public:
    explicit ApplicationManager(QObject *parent = 0);
    Q_INVOKABLE void addGroceryItem();
};

The second way is to use public slots as follows:
class ApplicationManager : public QObject
{
    Q_OBJECT
public:
    explicit ApplicationManager(QObject *parent = 0);
public slots:
    void addGroceryItem();
};

If you are creating your class object in C++ then you should set the object as the context data for main.qml as follows:
 int main(int argc, char *argv[]) {
     QCoreApplication app(argc, argv);

     QQmlEngine engine;
     ApplicationManager app;
     engine.rootContext()->setContextProperty("applicationManager", &app);
     QQmlComponent component(&engine, QUrl::fromLocalFile("main.qml"));
     component.create();

     return app.exec();
 }

Now you can access the ApplicationManager object created in main.cpp from main.qml as follows:
MouseArea {
    id: okBtnClkd
    anchors.fill: parent
    onClicked: {
        applicationManager.addGroceryItem();
    }
}

For more information see here.


text:
Q: MongoDB ReDOS test I was reading about ReDOS.
https://en.wikipedia.org/wiki/ReDoS
It seems if you run this code in Node.js:
console.time('aaa');
/^(a+)+$/.test('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!')
console.timeEnd('aaa');

it takes around 7821ms to run.
But if I add the same value to MongoDB:
db.users.insert({name: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!"});
db.users.findOne({name: { '$regex': '^(a+)+$'}});

This gets evaluated immediately and it returns null.
Any idea how MongoDB is able to evaluate it so fast?

A: According to MongoDB Docs

MongoDB uses Perl compatible regular expressions (i.e. "PCRE" ) version 8.41 with UTF-8 support.

Also it's stated here for Handling Regexes Provided by The User

The PCRE engine allows you to set recursion limits. The lower your limits the better the protection against ReDoS, but higher the risk of aborting legitimate regexes that would find a valid match given slightly more time. Low recursion limits may prevent long regex matches. Low timeouts may abort searches through large files too early.

PCRE uses hard limit on number of iterations according to Wikipedia

PCRE has a hard limit on recursion depth, Perl does not
With default build options "bbbbXcXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" =~ /.X(.+)+X/ will fail to match due to stack overflow, but Perl will match this correctly. Perl uses the heap for recursion and has no hard limit for recursion depth, whereas PCRE has a compile time hard limit.

Unfortunately I couldn't get what actual hard limit does Mongo apply on PCRE recursion depth.
for more details on PCRE recursion depth check this answer


text:
Q: how get jquery current val() + string? I want the textarea current val() + something string value.
I tried this code:

  $("textarea").val($("textarea").val() + str);

The results have only have showed str.
For example,
now textarea's typing value is "abcd", and var str value is "zxcv",
and if I click a button, I want textarea's value to be "abcdzxcv".
I don't know how to get this value, how is this possible?

A: It may be the case that you have multiple textareas on your page. Try to give proper identifier as in the below snippet. Hope that helps:
https://jsfiddle.net/rxp7kzkn/5/
<textarea id="textData">data</textarea>

$(document).ready(function(){
$("#textData").val("aman");
$("#textData").val($("#textData").val()+"xy");
});

So, in above example, initially textarea was having value data which was first updated to another value aman and then concatenate with another string xy. You can simply update the value of textarea by simply using
$("#textData").val()


text:
Q: Qt cannot load MySql driver on XAMPP I have written a very simple test to see how database connection works. This is my first attempt :
 QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
 db.setHostName("localhost");
 db.setPort(3306);
 db.setDatabaseName("testqt");
 db.setUserName("aaaaaa");
 db.setPassword(".bbbbbb!,");

 if (db.open())
 {
     qDebug() << "Connected!";
 }else
 {
     qDebug() << "Failed to connect!";
 }

Why I always get this error?

Note that I have this :

I have also seen online that someone puts the libmysql.dll and I've done that but still nothing. I have installed the C and C++ mysql connector from internet. Any idea?
My SQL database is on a XAMPP server and this is the username :

Also note this:

There is mariadb but it asks for libmysql!

A: If you have using of MinGW compiler, download c connector from bellow link :
https://dev.mysql.com/downloads/connector/c/
Then copy  "libmysql.dll" dll file to your qt path where installed :
C:\Qt\5.5\mingw492_32\bin


text:
Q: Can't use public static class, or don't know how to I have a public static class Cashier:
namespace MPP_TCP_Client
{
    public static class Cashier
    {
        public static IPAddress localAddr = IPAddress.Parse("127.0.0.1");

        public static TcpClient Connect()
        {
            try
            {
                return new TcpClient(Util.localAddrStr, Util.port);
            }
            catch (ArgumentNullException ane)
            {
                Console.WriteLine("ArgumentNullException: {0}", ane);
            }
            catch (SocketException se)
            {
                Console.WriteLine("SocketException: {0}", se);
            }
            catch (NullReferenceException nre)
            {
                Console.WriteLine("Null Reference Exception: {0}", nre);
            }
            return null;
        }

        // etc.
    }
}

Now I want to use the Connect method:
namespace Mpp_TCP_Client
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Press enter to start client");
            Console.ReadKey();
            TcpClient whatever = Cashier.Connect(); // Cashier is not being seen by Visual Studio
        }
    }
}

A: As Dennis_E mentioned above (I noticed his comment after I posted this answer):
Your namespaces have different casing.
The Cashier class uses: MPP_TCP_Client and the Program class uses: Mpp_TCP_Client.
Try this which matches the namespaces:
namespace MPP_TCP_Client // This should now be the same as the Cashier class
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Press enter to start client");
            Console.ReadKey();
            TcpClient whatever = Cashier.Connect(); // Cashier is not being seen by Visual     Studio
        }
    }
}

Or if this was intentional, add the following using statement:
using MPP_TCP_Client;


text:
Q: TimeDistributed Layer: Incompatible shapes: [32,3,3] vs. [32,3] I have a model that was working before, but now it does not work. It gives an error about:

InvalidArgumentError: Incompatible shapes: [32,3,3] vs. [32,3]
       [[{{node Nadam/gradients/loss/time_distributed_loss/SquaredDifference_grad/BroadcastGradientArgs}}]]

The old model:
class Model:
def set_the_model(self, look_back):
    self.model = Sequential()
    self.model.add(LSTM(16, activation="relu", input_shape=(look_back, 3),return_sequences=True)) #, stateful=True
    self.model.add(Dropout(0.2))
    self.model.add(LSTM(32, activation="relu", return_sequences=True))
    self.model.add(Dropout(0.2))
    self.model.add(TimeDistributed(Dense(look_back)))
    #self.model.add(Dense(3))
    self.model.compile(loss="mse", optimizer="nadam", metrics=['acc']) #mse
    self.model.summary()

def start_train(self, trainD1, trainD2):
    es = EarlyStopping(monitor='loss', patience = 2, mode='min')
    #for i, j in trainD1, trainD2:
    self.model.fit(trainD1, trainD2, epochs=200, batch_size = 32, verbose=1,  callbacks=[es])
    #  self.model.reset_states()

def predict_result(self, test_case):
    value = self.model.predict(test_case, verbose=0)
    return value

The error starts when I uncomment two lines of code in start_train method, and I turned the code into this (current model):
class Model:
def set_the_model(self, look_back):
    self.model = Sequential()
    self.model.add(LSTM(16, activation="relu", batch_input_shape=(1,look_back, 3),return_sequences=True, stateful=True))
    self.model.add(Dropout(0.2))
    self.model.add(LSTM(32, activation="relu", return_sequences=True))
    self.model.add(Dropout(0.2))
    self.model.add(TimeDistributed(Dense(look_back)))
    #self.model.add(Dense(3))
    self.model.compile(loss="mse", optimizer="nadam", metrics=['acc']) #mse
    self.model.summary()

def start_train(self, trainD1, trainD2):
    es = EarlyStopping(monitor='loss', patience = 2, mode='min')
    for i, j in zip(trainD1, trainD2):
        self.model.fit(i, j, epochs=200, batch_size = 1, verbose=1,  callbacks=[es])
        self.model.reset_states()

def predict_result(self, test_case):
    value = self.model.predict(test_case, verbose=0)
    return value

Then, I wanted to turn back to old model. When I started to train the model, It gives the error above.
This is how the model looks like:
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
lstm (LSTM)                  (None, 3, 16)             1280
_________________________________________________________________
dropout (Dropout)            (None, 3, 16)             0
_________________________________________________________________
lstm_1 (LSTM)                (None, 3, 32)             6272
_________________________________________________________________
dropout_1 (Dropout)          (None, 3, 32)             0
_________________________________________________________________
time_distributed (TimeDistri (None, 3, 3)              99
=================================================================
Total params: 7,651
Trainable params: 7,651
Non-trainable params: 0

Edit: I changed batch_size into 1 on the old model, and now it works, but now, It will be extremely slow.


text:
Q: Keep single storyboard for iPhone and iPad I am creating a demo project for keeping single storyboard for both iPad and iPhone devices. I am going to use Xcode 8 first time.
I created a button and put this button in center of the View with using constraints. I successfully managed the width and height of the button according to the device. On iPhone width is 100 and height is 50. And on iPad width is 200 and height is 100. To achieve this I used "Vary for Traits".
So I just want to know, am I on correct flow, I mean, to achieve size classes "Vary for Traits" is the correct ways OR is there any other way to achieve this?


text:
Q: How do I get xml tag values? From the data below how do I get the country name as shown in the example output I require (this part in my attempted query ????????????????)
declare @xml xml =
'<animals>
    <dog>
        <country>
            <australia>Perth</australia>
        </country>
    </dog>
    <cat>
        <country>
            <USA>Miami</USA>
        </country>
    </cat>
    <horse>
        <country>
            <Spain>Madrid</Spain>
        </country>
    </horse>
</animals>'

select
    col.value('local-name(.)','char(20)') as animal
    ,col.value('local-name(country/*/.)', 'varchar(25)') as country /* ?????????? */
    ,col.value('(*)[1]', 'varchar(25)') as city
from @xml.nodes('/animals/*') tab(col)

Expected output :
animal  country       city
------------------------------
dog     australia   Perth
cat     USA         Miami
horse   Spain       Madrid

A: You can shred the XML twice, on child of animals level and then on child of country level. This way you can select local-name() on both elements :
.....
select
    animals.value('local-name(.)','char(20)') as animal
    ,country.value('local-name(.)', 'varchar(25)') as country
    ,country.value('.', 'varchar(25)') as city
from @xml.nodes('/animals/*') T1(animals)
 cross apply T1.animals.nodes('country/*') T2(country)

rextester demo


text:
Q: SWT treeview - width of the image in the cell I want to add an image (size: 36px x 16px) in one cell of a tree viewer.
It works but the image get shrinked to a smaller size as you can see in the following image:

The other icons look fine. They are 16px x 16px.
I'm setting the image like this in my custom label provider:
@Override
public void update(ViewerCell cell){
   //some code...
   cell.setimage(MyPlugin.getDefault().getImageDescriptor("PATH_TO_ICON").createImage());
}

Where can I set the width of the image? Is it possible?


text:
Q: Telerik Chart UI is slow with 1000 values So, I have simple xaml (UWP) page with telerik chart:
<Grid>
        <telerikChart:RadCartesianChart Background="Beige" >
            <telerikChart:RadCartesianChart.Behaviors>
                <telerikChart:ChartPanAndZoomBehavior   ZoomMode="Both" PanMode="Both"/>
                <telerikChart:ChartTooltipBehavior  />
            </telerikChart:RadCartesianChart.Behaviors>
            <telerikChart:RadCartesianChart.VerticalAxis>
                <telerikChart:LinearAxis Padding="0" Title=" (m/s/s)"  Foreground="Black"/>
            </telerikChart:RadCartesianChart.VerticalAxis>
            <telerikChart:RadCartesianChart.HorizontalAxis>
                <telerikChart:LinearAxis Title="Time (s)" Foreground="Black"/>
            </telerikChart:RadCartesianChart.HorizontalAxis>
            <telerikChart:RadCartesianChart.Grid>
                <telerikChart:CartesianChartGrid MajorLinesVisibility="XY"/>
            </telerikChart:RadCartesianChart.Grid>

            <telerikChart:ScatterLineSeries   ItemsSource="{x:Bind Values, Mode=OneWay}">
                <telerikChart:ScatterLineSeries.XValueBinding>
                    <telerikChart:PropertyNameDataPointBinding PropertyName="XValue" />
                </telerikChart:ScatterLineSeries.XValueBinding>
                <telerikChart:ScatterLineSeries.YValueBinding>
                    <telerikChart:PropertyNameDataPointBinding PropertyName="YValue" />
                </telerikChart:ScatterLineSeries.YValueBinding>
            </telerikChart:ScatterLineSeries>

        </telerikChart:RadCartesianChart>

    </Grid>

Code behind creates 1000 values for chart control:
        public MainPage()
        {
            this.InitializeComponent();
            for (int i = 0; i < 1000; i++)
            {
                var val = new ValueForChart() { XValue = i, YValue = Math.Sin( i / 2d )};
                Values.Add(val);
            }
        }

        public List<ValueForChart> Values { get; set; } = new List<ValueForChart>();
//...
  public class ValueForChart
    {
        public double XValue { get; set; }
        public double YValue { get; set; }
    }

UI is rendered fast, but is unusable for panning, zooming or freezes when window is resized. 1000 values is not that much... I think RadChart should handle much more..
Am I doing something wrong?


text:
Q: Converting values to fit in an Image I have to read out some values from a database and create a line diagram with it.
The values i get from the database are the time in ms(going up to 72000) for the x-axis, and a value between 0 and 10 for the y-axis.
How do I get the values ranging from 0 to 72000 into the picture which has to have a width of 800px and how do use the complete 600px of the y-axis with the 0-10 values?


text:
Q: How to get Notice / Warning as object in PHP? I'm using PHP 7.3. I'm curious if it is possible to get PHP's Notice or Warning as an object (raised by PHP itself and not by user)? I would appreciate any examples including PHP manual references or code snippets from PHP's internals.
Note: I'm not asking about set_error_handler function which can catch warnings and notices but sadly not as a full objects (https://www.php.net/manual/en/function.set-error-handler.php). I don't want to generate my own Notice / Warning objects with trigger_error as it mentioned here: Is there any way to show, or throw, a PHP warning?.


text:
Q: Autodesk Inventor C# API UserParameter.set_Units 'object does not contain a definition for "set_Units"' I am using Autodesk.Inventor.Interop.DLL to work with Autodesk Inventor API. 'Embed Interop Types' option is set to false.
The goal is to loop through all user model parameters and update values from a provided JSON file and it does work but I am unable to update units due to this error: object does not contain a definition for "set_Units".
obj.unit is string

Any ideas how to set the units of user parameter?

A: The solution was to convert dynamic value to string:
string unit = Convert.ToString(obj.unit);
user_param.set_Units(unit);


text:
Q: Model incomplete when loading with Forge AR/VR Toolkit I have an IFC model, and I use the sample script 'test-2legged' in Scene Preparation (http://forgetoolkit.com/#/scenePrepration) to upload it to Forge. Then I loaded it with AR/VR toolkit (ForgeARKit-update-6-2018.1). However the downloaded model is incomplete (see below pictures). There is no external links in the model.
Please also note that I did some minor modification in 'test-2legged', as the original sample does not work directly with the new beta server 'https://developer-api-beta.autodesk.io' (please refer to another post: Forge ARKit: Cannot load model in Unity).
It seems for some components in the model it is visible but for some others it 's not, one thing I noticed is that some components has non-Unicode(Finnish) value in properties such as Type/Type name, not sure if that is the root-cause.
Can anyone help to check what can be wrong? I can upload the sample model.

Thank you in advance!

A: For anyone running into a similar issue, there was a problem with how affine transforms from https://developer-api-beta.autodesk.io were being parsed in Unity. If you're seeing similar issues (meshes in the scene having positions/rotations/scales all set to zeros), go to Assets/Forge/CodeBase/InstanceTreeRequest.cs and replace the "AffineMatrix" switch case with the following code:
case "AffineMatrix":
    Matrix4x4 mat = new Matrix4x4 ();

    var elements = node["mt"]["elements"].AsArray;
    mat.m00 = elements[0].AsFloat;
    mat.m10 = elements[1].AsFloat;
    mat.m20 = elements[2].AsFloat;
    mat.m01 = elements[3].AsFloat;
    mat.m11 = elements[4].AsFloat;
    mat.m21 = elements[5].AsFloat;
    mat.m02 = elements[6].AsFloat;
    mat.m12 = elements[7].AsFloat;
    mat.m22 = elements[8].AsFloat;

    mat.m03 = node["tr"]["x"].AsFloat;
    mat.m13 = node["tr"]["y"].AsFloat;
    mat.m23 = node["tr"]["z"].AsFloat;
    mat.m33 = 1.0f;

    obj.transform.localScale = ScaleFromMatrix (mat);
    obj.transform.rotation = RotationFromMatrix (mat);
    obj.transform.position = TranslationFromMatrix (mat);
    break;


text:
Q: Finding $E[X]$, $\operatorname{Var}(X)$ and distribution of $X$ in Bernoulli trials Let $X$ be the number of Bernoulli ($p$) trials required to produce at least one success and at least one failure. What is the distribution of $X$? Also, what is $E[X]$ and $\operatorname{Var}(X)$?
To find $\operatorname{Var} (X)$ I know that I'll need to use the formula $E\left[X^2\right]-\left(E\left[X\right]\right)^2$ after I find $E[X]$ and also $E\left[X^2\right]$. How would I do that? I think that $X$ has a geometric distribution, but how do I show that?

A: Let's try some values, letting $H$ = heads = success and $T$ = tails = failure:
\begin{align*}
P(X = 1) & = 0, \\
P(X = 2) & = P(HT \text{ or } TH) = p(1-p) + (1-p)p, \\
P(X = 3) & = P(HHT \text{ or } TTH) = p^2(1-p) + (1-p)^2p, \\
P(X = 4) & = P(HHHT \text{ or } TTTH) = p^3(1-p) + (1-p)^3p, \\
& \vdots
\end{align*}
So we can see that
$$
P(X = n) =
\begin{cases}
0, \qquad &  n = 1, \\
p^{n-1}(1-p) +(1-p)^{n-1}p, \qquad & n \geq 2
\end{cases}
$$
and we have the pmf.  You can calculate expected value based on the observation that
$$
P(X = n) = P(Y_1 = n) + P(Y_2 = n)
$$
where $Y_1 \sim geom(p)$ and $Y_2 \sim geom(1-p)$ for $n \geq 2$.  Recall that $E(Y_1) = \frac{1}{p}$ and $E(Y_2) = \frac{1}{1-p}$.  Then
\begin{align*}
E(X) & = \sum_{n=2}^\infty n \left[p^{n-1}(1-p) +(1-p)^{n-1}p\right] \\
& = \sum_{n=2}^\infty n p^{n-1}(1-p) + \sum_{n=2}^\infty n(1-p)^{n-1}p \\
& = \underbrace{\sum_{n=1}^\infty n p^{n-1}(1-p)}_{E(Y_2)} - (1-p) + \underbrace{\sum_{n=1}^\infty n(1-p)^{n-1}p}_{E(Y_1)} - p \\
& = \frac{1}{1-p} - (1-p) + \frac{1}{p} - p
\end{align*}
Similarly for variances.


text:
Q: awk -f does not work with piped content $ cat > test.txt <<EOL
Beam goes blah
John goes hey
Beam goes what?
John goes forget it
Beam goes okay
Beam goes bye
EOL
$

# works
tail -f test.txt | awk                      '/Beam/ {print $3}'

# does not work
tail -f test.txt | awk -f CERTAINLIB.AWK -e '/Beam/ {print $3}'

# does not work either
awk -f CERTAINLIB.AWK -e '/Beam/ {print $3}' < <(tail -f test.txt)

Could you help to comment why awk -f does not work with piped content, and the possible workaround ? Many thanks !
It turns out the problem comes from CERTAINLIB.AWK, which filters incoming text...

A: The issue was resolved in comments.
Rather than being an issue related to reading piped input, the CERTAINLIB.AWK code removed the data that the -e expression would have outputted.


text:
Q: What is this C# generic constraint does: public class ValueObject where T : ValueObject I don't understand this generic constraint where the constraint is the same type as the class.
public class ValueObject<T> where T : ValueObject<T>

What does this constraints? When it is used?

A: Generic T must inherit of gived type.
where T : BaseClass.


text:
Q: What's the difference between var and let? The MDN tutorial for JavaScript says

Back when JavaScript was first
  created, there was only var. This works basically fine in most cases,
  but it has some issues in the way it works — its design can sometimes
  be confusing or downright annoying. So, let was created in modern
  versions of JavaScript, a new keyword for creating variables that
  works somewhat differently to var, fixing its issues in the process.

It continues to say

For these reasons and more, we recommend that you use let as much as
  possible in your code, rather than var. There is no reason to use var,
  unless you need to support old versions of Internet Explorer with your
  code (it doesn't support let until version 11; the modern Windows Edge
  browser supports let just fine).

I'm looking at JavaScript code in templates and tutorials and, almost universally, I see var for initializing variables.
Are the differences over-stated between var and let?

A: Var has a larger scope then let let is only valid in the block where it was declared .
Try adding 10 clickhandlers that output a numbers in a loop and you will quickly see the difference


text:
Q: Trying to understand Single Responsiblity Principle I'm having a difficult time understanding the Single Responsibility Principle.
What should I look for to evaluate the various sources of information on the matter?
What should I look for in examples explaining the principle?

A: SRP is a fairly straight-forward principle.

the single responsibility principle
  states that every object should have a
  single responsibility, and that
  responsibility should be entirely
  encapsulated by the class. All its
  services should be narrowly aligned
  with that responsibility.

-- http://en.wikipedia.org/wiki/Single_responsibility_principle

A class should have one, and only one,
  reason to change.

-- http://www.butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod
Often, I find the second quote more applicable.  I try to envision what my class does.  What logic does it contain, or what external (to the class) services might it depend on.
I try to think about what might change, and how might this cause my class to change.  Are there multiple things that could change and affect my class?  That is a code smell (but not always reason enough to split a class).
Also, while I'm thinking along these lines, I look for cases where several classes will need to change if one other thing changes (logic, and external service, etc.).  This too is a code smell.
Often, though, I have small groups of tightly coupled classes that coordinate or interact to perform a single function or service.  If the changes occur across this set of tightly coupled classes, I find that ok.  But if a change in, say, an external service requires changes in multiple classes in different areas of my application, that is a stinkier code smell.

A: Pluralsight has a course Principles of Object Oriented Design that covers SRP as the first topic in about 12 minutes. I believe you get a couple of hours of video for free, after that you need a subscription.


text:
Q: How to dynamically add bucket_key value in airflow's S3KeySensor I'm trying to set S3KeySensor's bucket_key up based on dagrun input variable.
I have one dag "dag_trigger" that uses TriggerDagRunOperator to trigger dagrun for dag "dag_triggered". I'm trying to extend example https://github.com/apache/incubator-airflow/blob/master/airflow/example_dags/example_trigger_target_dag.py.
So I want to send a variable to triggered dag, and according to the variable's value I want to set backet_key value in S3KeySensor task. I know how to use sent variable in PythonOperator callable function, but I do not know how to use it on the sensor object.
dag_trigger dag:
import datetime

from airflow import DAG
from airflow.operators.dagrun_operator import TriggerDagRunOperator

default_args = {
    'owner': 'airflow',
    'start_date': datetime.datetime.now()}

dag = DAG('dag_trigger', default_args=default_args, schedule_interval="@hourly")

def task_1_run(context, dag_run_object):
    sent_variable = '2018_02_19' # not important
    dag_run_object.payload = {'message': sent_variable}
    print "DAG dag_trigger triggered with payload: %s" % dag_run_object.payload)
    return dag_run_object

task_1 = TriggerDagRunOperator(task_id="task_1",
                               trigger_dag_id="dag_triggered",
                               provide_context=True,
                               python_callable=task_1_run,
                               dag=dag)

And dag_triggered dag:
import datetime

from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from airflow.operators.sensors import S3KeySensor

default_args = {
    'owner': 'airflow',
    'start_date': datetime.datetime.now()
}

dag = DAG('dag_triggered', default_args=default_args, schedule_interval=None)

wait_files_to_arrive_task = S3KeySensor(
    task_id='wait_file_to_arrive',
    bucket_key='file_%s' % '', # Here I want to place conf['sent_variable']
    wildcard_match=True,
    bucket_name='test-bucket',
    s3_conn_id='test_s3_conn',
    timeout=18*60*60,
    poke_interval=120,
    dag=dag)

I tried to get the value from dag object using dag.get_dagrun().conf['sent_variable'] but I have a doubt how to set dagrun create_date variable (dag_trigger will triggered dag_triggered every hour and dag_triggered could wait longer for file).
I also tried to create PythonOperator that would be upstream for wait_files_to_arrive_task. The callable python function could get information about sent_variable. After that I tried to set value for bucket_key like bucket_key = callable_function() - but I have problem with arguments.
And I also think the global variables is not good solution.
Maybe someone has idea that works.

A: It's not possible to fetch a value in your DAG run conf directly in your DAG file. That's something that cannot be determined without context of which DAG run it's part of. One way to think about it is when you run python my_dag.py to test if your DAG file compiles, it has to initialize all these operators without needing to specify an execution date. So anything that could differ by DAG run can't be referenced directly.
So instead, you can pass it as a template value which will later get rendered with context when the task is actually being run.
wait_files_to_arrive_task = S3KeySensor(
    task_id='wait_file_to_arrive',
    bucket_key='file_{{ dag_run.conf["message"] }}',
    ...)

Note that only parameters listed in the template_fields of an operator will be rendered. Luckily someone anticipated this so bucket_key is indeed a template field.


text:
Q: 403 Forbidden in root I'm setting up a webserver with virtual hosts, and I'm having a hard time getting around this 403 Forbidden error. The error claims something is pointing to root /, but the directives are set for any requests for the domain to be routed to it's directory:
<VirtualHost *:80>
DocumentRoot /var/www/twistedpleasures
ServerName twistedpleasures.net
</VirtualHost>

Here's the apache2.conf
# This is the main Apache server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See http://httpd.apache.org/docs/2.2/ for detailed information about
# the directives and /usr/share/doc/apache2-common/README.Debian.gz about
# Debian specific hints.
#
#
# Summary of how the Apache 2 configuration works in Debian:
# The Apache 2 web server configuration in Debian is quite different to
# upstream's suggested way to configure the web server. This is because Debian's
# default Apache2 installation attempts to make adding and removing modules,
# virtual hosts, and extra configuration directives as flexible as possible, in
# order to make automating the changes and administering the server as easy as
# possible.

# It is split into several files forming the configuration hierarchy outlined
# below, all located in the /etc/apache2/ directory:
#
#   /etc/apache2/
#   |-- apache2.conf
#   |   `--  ports.conf
#   |-- mods-enabled
#   |   |-- *.load
#   |   `-- *.conf
#   |-- conf.d
#   |   `-- *
#   `-- sites-enabled
#       `-- *
#
#
# * apache2.conf is the main configuration file (this file). It puts the pieces
#   together by including all remaining configuration files when starting up the
#   web server.
#
#   In order to avoid conflicts with backup files, the Include directive is
#   adapted to ignore files that:
#   - do not begin with a letter or number
#   - contain a character that is neither letter nor number nor _-:.
#   - contain .dpkg
#
#   Yet we strongly suggest that all configuration files either end with a
#   .conf or .load suffix in the file name. The next Debian release will
#   ignore files not ending with .conf (or .load for mods-enabled).
#
# * ports.conf is always included from the main configuration file. It is
#   supposed to determine listening ports for incoming connections, and which
#   of these ports are used for name based virtual hosts.
#
# * Configuration files in the mods-enabled/ and sites-enabled/ directories
#   contain particular configuration snippets which manage modules or virtual
#   host configurations, respectively.
#
#   They are activated by symlinking available configuration files from their
#   respective *-available/ counterparts. These should be managed by using our
#   helpers a2enmod/a2dismod, a2ensite/a2dissite. See
#   their respective man pages for detailed information.
#
# * Configuration files in the conf.d directory are either provided by other
#   packages or may be added by the local administrator. Local additions
#   should start with local- or end with .local.conf to avoid name clashes. All
#   files in conf.d are considered (excluding the exceptions noted above) by
#   the Apache 2 web server.
#
# * The binary is called apache2. Due to the use of environment variables, in
#   the default configuration, apache2 needs to be started/stopped with
#   /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not
#   work with the default configuration.

# Global configuration
#

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# NOTE!  If you intend to place this on an NFS (or otherwise network)
# mounted filesystem then please read the LockFile documentation (available
# at <URL:http://httpd.apache.org/docs/2.2/mod/mpm_common.html#lockfile>);
# you will save yourself a lot of trouble.
#
# Do NOT add a slash at the end of the directory path.
#
#ServerRoot "/etc/apache2"

#
# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
#
LockFile ${APACHE_LOCK_DIR}/accept.lock

#
# PidFile: The file in which the server should record its process
# identification number when it starts.
# This needs to be set in /etc/apache2/envvars
#
PidFile ${APACHE_PID_FILE}

#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 300

#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On

#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100

#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 5

##
## Server-Pool Size Regulation (MPM specific)
##

# prefork MPM
# StartServers: number of server processes to start
# MinSpareServers: minimum number of server processes which are kept spare
# MaxSpareServers: maximum number of server processes which are kept spare
# MaxClients: maximum number of server processes allowed to start
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_prefork_module>
    StartServers          5
    MinSpareServers       5
    MaxSpareServers      10
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>

# worker MPM
# StartServers: initial number of server processes to start
# MinSpareThreads: minimum number of worker threads which are kept spare
# MaxSpareThreads: maximum number of worker threads which are kept spare
# ThreadLimit: ThreadsPerChild can be changed to this maximum value during a
#              graceful restart. ThreadLimit can only be changed by stopping
#              and starting Apache.
# ThreadsPerChild: constant number of worker threads in each server process
# MaxClients: maximum number of simultaneous client connections
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_worker_module>
    StartServers          2
    MinSpareThreads      25
    MaxSpareThreads      75
    ThreadLimit          64
    ThreadsPerChild      25
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>

# event MPM
# StartServers: initial number of server processes to start
# MinSpareThreads: minimum number of worker threads which are kept spare
# MaxSpareThreads: maximum number of worker threads which are kept spare
# ThreadsPerChild: constant number of worker threads in each server process
# MaxClients: maximum number of simultaneous client connections
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_event_module>
    StartServers          2
    MinSpareThreads      25
    MaxSpareThreads      75
    ThreadLimit          64
    ThreadsPerChild      25
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>

# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}

#
# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives.  See also the AllowOverride
# directive.
#

AccessFileName .htaccess

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>

#
# DefaultType is the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value.  If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
# It is also possible to omit any default MIME type and let the
# client's browser guess an appropriate action instead. Typically the
# browser will decide based on the file's extension then. In cases
# where no good assumption can be made, letting the default MIME type
# unset is suggested  instead of forcing the browser to accept
# incorrect  metadata.
#
DefaultType None

#
# HostnameLookups: Log the names of clients or just their IP addresses
# e.g., www.apache.org (on) or 204.62.129.132 (off).
# The default is off because it'd be overall better for the net if people
# had to knowingly turn this feature on, since enabling it means that
# each client request will result in AT LEAST one lookup request to the
# nameserver.
#
HostnameLookups Off

# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog ${APACHE_LOG_DIR}/error.log

#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn

# Include module configuration:
Include mods-enabled/*.load
Include mods-enabled/*.conf

# Include list of ports to listen on and which to use for name based vhosts
Include ports.conf

#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
# If you are behind a reverse proxy, you might want to change %h into %{X-Forwarded-For}i
#
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

# Include of directories ignores editors' and dpkg's backup files,
# see the comments above for details.

# Include generic snippets of statements
Include conf.d/

# Include the virtual host configurations:
Include sites-enabled/*.conf

Here's the ownerships:
ls -alF /var/www/
total 44
drwxr-xr-x  9 jason root     4096 May 23 21:53 ./
drwxr-xr-x 13 root  root     4096 Oct 15  2013 ../
drwxr-xr-x  2 jason root     4096 Oct 15  2013 cgi-bin/
drwxr-xr-x  2 jason root     4096 Oct 15  2013 css/
drwx------  2 jason jason    4096 May 23 21:53 fluidvector/
drwxr-xr-x  2 jason root     4096 Oct 15  2013 images/
-rw-r--r--  1 jason root     2709 Oct 15  2013 index.php
drwxr-xr-x  2 jason root     4096 Oct 15  2013 js/
-rw-r--r--  1 jason root       20 Oct 15  2013 phpinfo.php
drwx------  2 jason jason    4096 May 23 21:52 therealmsbeyond/
drwxrwxr-x  9 root  www-data 4096 May 23 22:22 twistedpleasures/

And I've verified that the VirtualHost is being init'd correctly with sh -c ". /etc/apache2/envvars; apache2 -S"
I'm running on Debian 7 (wheezy) with Apache 2.2.22
I've seen other posts about a Require all denied directive option, but cannot find this in my conf files at all. Any suggestions?

A: Not sure why this was down-voted, but the issue stemmed from incorrect permissions on one of the site's .htaccess files.


text:
Q: Creating view with additional column based on multiple condition I've been trying to sort out some data from my current job. I need to create additional column with shift number that depends on the product creation hour. The table looks like this:
product_id    creation_time         warehouse_name
  varchar       timestamp                varchar
    1      2016-03-29 08:30:45            11
    2      2016-03-15 14:15:10            9
    3      2016-03-14 05:40:45            11

Now I need to add a column with a shift number that's based on the hours - 06:00:00 - 14:00:00 shift 1, 14:00:00-22:00:00 shift 2 and 22:00:00-06:00:00 shift 3. I'm quite new when it comes to sql, I know how to add a column via AS, but I don't know how to fill the column with correct data based on the condition that's based on the timestamps. We're using postgres database via pgadmin.I tried something like:
 SELECT creation_time, product_id, warehouse_name
 FROM products WHERE creation_time BETWEEN LIKE '%06:00:00' AND '%14:00:00';

but I'm lost at how to insert the condition data into a new column named shifts.

A: You shouldn't compare timestamp values using LIKE. To select the rows with a time between 06:00 and 14:00 cast the timestamp to a time and compare that:
SELECT creation_time, product_id, warehouse_name
FROM products
WHERE creation_time::time BETWEEN time '06:00:00' AND time '14:00:00';

The same "trick" can be used to create the shift column:
SELECT creation_time, product_id, warehouse_name,
       case
         when creation_time::time between time '06:00:00' AND time '14:00:00' then 1
         when creation_time::time BETWEEN time '14:00:01' AND time '22:00:00' then 2
         else 3
       end as shift_number
FROM products;

The between operator includes both values that's why the second check starts 1 second after 14:00
time '06:00:00' specifies a time literal (constant). For more details on how to specify time (or timestamp) values, please see the manual:
http://www.postgresql.org/docs/current/static/datatype-datetime.html#DATATYPE-DATETIME-INPUT


text:
Q: Why is #import Foundation.h widespread in Objective-C but individual imports are typical in Java From what I've seen, Android development requires the traditional Java style importing of each individual class/interface while the suggested templates in XCode import files like Foundation and UIKit. What is the difference in the compiler between Obj-C and Java that makes this sort of big import OK in one, but not OK in the other?
To be clear, I am not whining that this is not available in Java, I am just curious why it would be bad to do something like importing java.util.* or creating some sort of super header file that imports a lot of stuff.

A: One important thing to note is that the only source code you need to compile any given Java class is the source code of that class.
Everything else needs to be available in compiled form only (i.e. as .class files). This means that a single .java file is always a syntacitcally closed unit that needs no other source code to make interpretable to a compiler.
This is quite different to how C-style languages treat external dependencies: they need type and function definitions (as well as macros and some things I probably forgot about right now) in order to be able to correctly parse and compile a  .c file (of course some .c files might be syntactically closed, but that's not the usual case).
The closest you can get to including a huge .h file in Java is using a .* import to import all classes of a given package: import foo.bar.*, but that's still miles away from the C/C++/Objective-C way.
And on a separate note: import foo.* is probably a bit less common in Java than individual imports for a simple reason: Individual imports are much more explicit and make it very clear which classes are used and they are usually written by your IDE of choice anyway, so this choice doesn't even make Java code harder to write.


text:
Q: pass  id value javascript function I want to pass
 id value instead for this.id , How to get tr id value. please help me thanks

        <input type="checkbox" onclick="toggle(this.id)" value="private" name="private" id="private_1">

        <input type="checkbox" onclick="toggle(this.id)" checked="" value="public" name="public" id="public_1">

        <input type="checkbox" onclick="toggle(this.id)" checked=""  value="private" name="private" id="private_2">

        <input type="checkbox" onclick="toggle(this.id)" value="public" name="public" id="public_2">

Demo

A: If the structure is exactly like this, you can use
this.parentNode.parentNode.id

Of course this will brake as soon as the structure changes.
Instead of binding to the click event, you should bind to the change event. Then you also cover changes made by the keyboard.

As every handler is doing the same, you should consider to leverage event bubbling. Instead of attaching the event handler to every input element in your HTML, attach only one event handler to the table:
var table = document.getElementById('tableId');

table.onchange = function(event) {
   event = event || window.srcElement;  // IE specials
   var target = event.target || event.srcElement;  // IE specials

   // was the element a checkbox?
   if(target.nodeName === "INPUT" && target.type === "checkbox") {
       // find parent row
       var parent = target.parentNode;
       while(parent.nodeName !== "TR" && parent !== null) {
           parent = parent.parentNode;
       }

       if(parent) { // we found the row
           toggle(parent.id);
       }
   }
};

This looks more complicated but has the advantage that you don't have to write onclick="toggle(this.id)" on every input element.
DEMO


text:
Q: show full view controller from popover in iOS Swift I am trying to show a full screen view from a button in a popover view. I tried various codes including the following. Any help would be appreciated. Thanks :)
self.view.presentviewcontroller
self.parentview.presentviewcontroller.

A: try
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let view2 = storyboard.instantiateViewControllerWithIdentifier("login") as logInViewController
    self.presentViewController(view2, animated:true, completion: nil)