text:
Q: Анимация поворота ячеек таблицы на JavaScript Вот задание по JavaScript, которое я пытаюсь решить.
Задача:

*

*Сделать сетку 4x4 из блоков.

*Ниже расположить кнопку [start], при нажатии на которую текст в ней изменится на [in progress], а ячейки в сетке начнут переворачиваться на 180 градусов по очереди (важно заметить, что анимация следующей ячейки должна начинаться перед тем, как закончится анимация предыдущей).

*После окончания эффектов вывести сообщение об успехе и кнопку снова изменить на [start].

*Всю служебную информацию записывать в консоль (старт прогресса / старт анимации ячейки / окончание анимации ячейки / окончание прогресса).

*

*P.S. эффект для ячеек сетки нужно реализовать на CSS.

*P.S.S. если сделать сетку 4x5, ваш код должен работать.

*P.S.S.S. кроссбраузерность будет плюсом.

Видео с примером реализации: смотреть.
===
Мой старый код(можно не смотреть, тогда я еще почти не знал JavaScript):
*Ответ пользователя wNow шел для этого кода(точнее он все полностью за меня написал, за что ему благодарность).

$(document).ready(function() {
  $('button.action').click(function() {
    console.log('---PROGRESS START---');
    console.log('Cell 1 Animation START');
    $("tr.one td:nth-child(1)").addClass("takeover");
    window.setTimeout(function() {
      console.log('Cell 1 Animation END');
    }, 1200);
    window.setTimeout(function() {
      console.log('Cell 2 Animation START');
      $("tr.one td:nth-child(2)").addClass("takeover")
    }, 300);
    window.setTimeout(function() {
      console.log('Cell 2 Animation END');
    }, 1500);
    window.setTimeout(function() {
      console.log('Cell 3 Animation START');
      $("tr.one td:nth-child(3)").addClass("takeover")
    }, 600);;
    window.setTimeout(function() {
      console.log('Cell 3 Animation END');
    }, 1800);
    window.setTimeout(function() {
      console.log('Cell 4 Animation START');
      $("tr.one td:nth-child(4)").addClass("takeover")
    }, 900);
    window.setTimeout(function() {
      console.log('Cell 4 Animation END');
    }, 2100);

    window.setTimeout(function() {
      console.log('Cell 5 Animation START');
      $("tr.two td:nth-child(1)").addClass("takeover")
    }, 1200);
    window.setTimeout(function() {
      console.log('Cell 5 Animation END');
    }, 2400);
    window.setTimeout(function() {
      console.log('Cell 6 Animation START');
      $("tr.two td:nth-child(2)").addClass("takeover")
    }, 1500);;
    window.setTimeout(function() {
      console.log('Cell 6 Animation END');
    }, 2700);
    window.setTimeout(function() {
      console.log('Cell 7 Animation START');
      $("tr.two td:nth-child(3)").addClass("takeover")
    }, 1800);
    window.setTimeout(function() {
      console.log('Cell 7 Animation END');
    }, 3000);
    window.setTimeout(function() {
      console.log('Cell 8 Animation START');
      $("tr.two td:nth-child(4)").addClass("takeover")
    }, 2100);
    window.setTimeout(function() {
      console.log('Cell 8 Animation END');
    }, 3300);

    window.setTimeout(function() {
      console.log('Cell 9 Animation START');
      $("tr.three td:nth-child(1)").addClass("takeover")
    }, 2400);
    window.setTimeout(function() {
      console.log('Cell 9 Animation END');
    }, 3600);
    window.setTimeout(function() {
      console.log('Cell 10 Animation START');
      $("tr.three td:nth-child(2)").addClass("takeover")
    }, 2700);;
    window.setTimeout(function() {
      console.log('Cell 10 Animation END');
    }, 3900);
    window.setTimeout(function() {
      console.log('Cell 11 Animation START');
      $("tr.three td:nth-child(3)").addClass("takeover")
    }, 3000);
    window.setTimeout(function() {
      console.log('Cell 11 Animation END');
    }, 4200);
    window.setTimeout(function() {
      console.log('Cell 12 Animation START');
      $("tr.three td:nth-child(4)").addClass("takeover")
    }, 3300);
    window.setTimeout(function() {
      console.log('Cell 12 Animation END');
    }, 4500);

    window.setTimeout(function() {
      console.log('Cell 13 Animation START');
      $("tr.four td:nth-child(1)").addClass("takeover")
    }, 3600);
    window.setTimeout(function() {
      console.log('Cell 13 Animation END');
    }, 4800);
    window.setTimeout(function() {
      console.log('Cell 14 Animation START');
      $("tr.four td:nth-child(2)").addClass("takeover")
    }, 3900);;
    window.setTimeout(function() {
      console.log('Cell 14 Animation END');
    }, 5100);
    window.setTimeout(function() {
      console.log('Cell 15 Animation START');
      $("tr.four td:nth-child(3)").addClass("takeover")
    }, 4200);
    window.setTimeout(function() {
      console.log('Cell 15 Animation END');
    }, 5400);
    window.setTimeout(function() {
      console.log('Cell 16 Animation START');
      $("tr.four td:nth-child(4)").addClass("takeover")
    }, 4500);
    window.setTimeout(function() {
      console.log('Cell 16 Animation END');
      console.log('---PROGRESS END---');
    }, 5700);
  });
  /*#############################################*/
});
body {
  background-color: #212120;
}

/* begin Content */

.content {
  margin-top: 200px;
  text-align: center;
}

.content table {
  margin: auto;
}

.content table tbody tr td {
  padding: 20px 40px;
  background-color: #4989C7;
  color: #fff;
  font-size: 30px;
  border: 5px solid #212120;
  vertical-align: middle;
  text-align: center;
}

.content table tbody tr td.takeover {
  transform: rotateX(180deg);
  transition: 1.2s;
}

.content button {
  background-color: #4989C7;
  color: #fff;
  border: none;
  font-size: 20px;
  padding: 10px 20px;
  margin-top: 20px;
}

.content button:hover {
  cursor: pointer;
  opacity: 0.9;
}

/* end Content */

        1
        2
        3
        4

        5
        6
        7
        8

        9
        10
        11
        12

        13
        14
        15
        16

  <button class="action" type="button">start</button>

======= Обновлено 30.03.17 =======
Получив знания по JavaScript, написал данный код(по нему и будет вопрос):

'use strict';

function startFliping() {
  var score = 0;
  screen.innerHTML += '-- PROGRESS START --
';
  button.innerHTML = 'in progress';

  (function flip() {
    var thisScore = score;
    var td = tdList[thisScore];

    if (thisScore != tdList.length) {
      screen.innerHTML += 'Cell ' + (thisScore + 1) + ' Animation START
';
      screen.scrollTop += screen.offsetHeight; // Добавил скролл, в задании нет, но на видео есть.
      td.style.transition = '1s';
      td.style.transform = 'rotateX(180deg)';

      td.addEventListener('transitionend', function() { // Отслеживаю окончание анимации.
        screen.innerHTML += 'Cell ' + (thisScore + 1) + 'Animation END
';
        screen.scrollTop += screen.offsetHeight;

        if (thisScore + 1 == tdList.length) { // Здесь проверка, если подходит, завершаем.
          screen.innerHTML += '-- PROGRESS END --
';
          alert('sucess');
          button.innerHTML = 'start';
          screen.scrollTop += screen.offsetHeight;

          for (var i = 0, length1 = tdList.length; i < length1; i++) {
            tdList[i].style.transition = '0s';
            tdList[i].style.transform = 'rotateX(0)';
          }
        };

      });

      score++;
      setTimeout(flip, 200);
    };
    return;
  })();

};

var flipFlops = document.querySelector('.flipFlops');
var button = flipFlops.querySelector('.button');
var screen = flipFlops.querySelector('.screen');
var tdList = flipFlops.querySelectorAll('td');

button.addEventListener('click', startFliping);
body {
  background-color: #f1f1f1;
}

td {
  padding: 40px;
  color: white;
  background: #4289CE;
}

p {
  margin: 0;
}

.flipFlops {
  text-align: center;
}

table {
  margin: auto;
}

.screen {
  padding: 10px;
  text-align: left;
  background: #4289CE;
  color: #fff;
  width: 380px;
  height: 200px;
  overflow-y: scroll;
  margin: 20px auto;
}

.button {
  padding: 10px 50px;
  background: #4289CE;
  color: #fff;
  font-size: 20px;
  text-transform: uppercase;
}

.button:hover {
    cursor: pointer;
    opacity: 0.9;
  }

      1
      2
      3
      4

      5
      6
      7
      8

      9
      10
      11
      12

      13
      14
      15
      16

  start

*

*Использовал рекурсию.

*Добавил комментарии в код.

*Я новичок в js.

Мой вопрос: Первый раз запускаем, все как надо, но если еще запустить(без перезагрузки страницы), то появляется баг, а именно двойные надписи Animation END и двойной alert, третий раз запускаем уже три раза и т.д.(хочется чтобы было как при первом запуске). Я долго с этим возился, предполагаю, что проблема с addEventListener('transitionend' Как поправить не знаю, буду рад получить помощь(хочу узнать из-за чего ошибка и можно ли поправить не меняя сильно код).

A:

function get(elem) {
  return document.getElementById(elem)
};
get('button').onclick = function() {
  get('console').innerHTML += '-- PROGRESS START --
';
  get('button').innerHTML = 'in progress';
  setTimeout(function() {
    alert('success');
    get('console').innerHTML += '-- PROGRESS END --
';
    for (var i = 0; i < 16; i++) {
      get(i).style.transform = 'rotateX(0)';
      get(i).style.transition = '0s';
      get('button').innerHTML = 'start';
    }
  }, 2100);
  for (var i = 0; i < 16; i++) {
    get(i).style.transition = '0.5s';
    var t = i * 100;
    setTimeout(function(i) {
      get(i).style.transform = 'rotateX(180deg)';
      get('console').innerHTML += 'cell ' + (i + 1) + ' animation START
';
      setTimeout(function(i) {
        get('console').innerHTML += 'cell ' + (i + 1) + ' animation END
';
      }, 500, i)
    }, t, i);
  }
}
td {
  perspective: 400px;
}
td div {
  text-align: center;
  padding: 40px;
  color: white;
  background: #00accc;
  transition: 0.5s;
}
#console {
  background: #ddd;
  width: 400px;
  overflow: scroll;
  height: 200px;
}
#button {
  padding: 10px;
  background: #00accc;
  margin-left: 150px;
}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

start


text:
Q: Using microsoft sync framework 2.1 for SQL Server 2000 We need to synchronize database and image files between two servers. The source server has sql server 2000 and the destination server has sql server 2008. We need to synchronize data in some tables in sql server 2000 so that the updated data comes to sql server 2008 every once in a while. Similarly for the folder where images are stored.
I tried to implement Microsoft sync framework (http://msdn.microsoft.com/sync) with WCF to achieve the goal. I ran the following project successfully for two databases in SQL Server 2008:
http://code.msdn.microsoft.com/Database-SyncSQL-Server-e97d1208/sourcecode?fileId=19017&pathId=519811259
However, when I tried to synchronize data between database, one in sql server 2000 and sql server 2008, then I could not synchronize data.
Questions:

*

*Is there anyway to synchronize data between sql server 2000 and sql server 2008?

*If not, are there any other possible architectures i can implement to achieve the objective?

A: the minimum Sql Server version for the sync provider in the sample you used above is Sql Server 2005 SP2 (where min_active_version() was introduced.)
try using the steps in this link so you can overrride the commands and make them work against Sql 2000: Synchronizing Other ADO.NET Compatible Databases

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using Try out of Exception contexts Is it in Scala acceptable to use Try (Success/Failure) outside of an actual Exception context as a return type of a function that can succeed or fail?

A: It is certainly possible to use a Try outside an exception context; I use it that way all the time. That does not necessarily mean that it is "acceptable" :)
I would say that the whole point of using Try is to take the Throwable instance out of the exception context and put it in an object that can be used anywhere in a program. It is hard to see why Try would have such a rich set of methods (e.g. flatMap) if it is only intended to be used inside an exception context.

A: Instances of Try, are either Success or Failure, where Failure is
case class Failure[+T](exception: Throwable)

Note how Failure must be constructed with Throwable, so I think Try is meant to be used within context of Throwables. So we cannot do something like
def foo: Try[Int] = {
  Failure(42) // Error: type mismatch; found : Int(42) required: Throwable
}

Consider using Either instead of Try outside exceptions context.

Addressing the comment consider

*

*Valid/Invalid from cats: https://typelevel.org/cats/datatypes/validated.html

*define your own ADT with your own meaning of success and failure cases, and then wrap function results in those cases

In neither of these are you forced to use exceptions.
Here is an example
sealed trait MyValidationADT[T]
case class Good[T](result: T) extends MyValidationADT[T]
case class Bad[T](result: T) extends MyValidationADT[T]

def foo(i: Int): MyValidationADT[Int] = Bad(42)

foo(11) match {
  case Good(result) => "woohoo"
  case Bad(result) => "boom"
}

which outputs
res0: String = boom


text:
Q: Removing a user folder with RDP access and "We can't sign into your account" error I work in a lab where we have a desktop that we allow researchers to remote into and use for working with their data.  There hasn't really been any policy to keep the machine clean except telling people to clean up after themselves, and after years of use we now have completely full hard drives. The machine is on a university domain, but we are a somewhat separate non-profit entity so we aren't supposed to be using the university tech support / IT help...
There are approx 30 user folders on the machine, and about 10 people who currently have remote access.  My plan was to delete any user folders with a LastAccessTime before 1 year ago.  User folders correspond to university IDs, and so I was able to email users and notify them (although many emails were no longer valid).
So I ran a test with a new user to see what would happen and I'm a little confused by the results.  Here is what I did:

*

*Gave RDP access to a new testuser account.  Confirmed that there was no user folder for testuser under C:\Users.

*Logged in with that test user, and a C:\Users\testuser folder was created

*Logged in with an admin account and deleted the C:\Users\testuser folder

*Logged in with the testuser account and received an error ""We can't sign into your account.  This problem can often be fixed by signing out of your account and then signing back in.
If you don't sign out now, any files you create or changes you make will be lost."

I logged out an in again with testuser and received the same error.  I'm wondering why initially when there was no user folder, one was created when I logged in.  I assumed after I deleted the user folder, a new one would be created the next time I signed in, but apparently that's not the case?
I didn't really want to dig through all of the user folders to find data and delete it, and I don't think we need to keep all users, but I would like users to be able to remote into the machine again and have a "clean" user folder created if their old one was deleted and they still have RDP access.
Any guidance on the best way to clean up our machine is appreciated!


text:
Q: how we can paginate data on Laravel when we have a complex query I have the following query on the Oracle database

SELECT * FROM ( SELECT to_char(to_date(t2.REGISTRATION_DATE,'yyyy/mm/dd'),'yyyy/mm/dd','nls_calendar=persian') as REGISTRATION_DATE , t2.MOBILE as mobile , t1.VOUCHER_NO as voucher_number
                             FROM Table1 t1
                             INNER JOIN table2 t2
                             ON T1.a= T2.b
                             Where to_number(to_char(to_date(t2.REGISTRATION_DATE,'yyyy/mm/dd'),'yyyymmdd','nls_calendar=persian')) between {$start} and {$end}
                             order by 1) WHERE rownum BETWEEN 1 AND 10

I want to paginate outputs and show them on a blade file. How I can do that?


text:
Q: SSH hangs when executing command remotely
*

*Client : OpenSSH_5.1p1 Debian-5ubuntu1 (Ubuntu 9.04)

*Server : OpenSSH_5.1p1 Debian-5 (Proxmox 2.6.24-7-pve)

I use SSH to execute commands remotely on the server (module check_by_ssh of Nagios). But SSH hangs from time to time when trying to execute commands. I can log to the server via SSH but not executing a simple 'ls'. And it seems to block from all clients from the same IP address.
Authentication is not the problem, may it be made by SSH keys or password.
ssh -l root -p 2222 server.domain.tld 'ls'

Here the client debug info
debug1: Entering interactive session.
debug2: callback start
debug2: client_session2_setup: id 0
debug1: Sending environment.
debug3: Ignored env ORBIT_SOCKETDIR
*** skipping approx 40 env var ignored
debug1: Sending command: ls
debug2: channel 0: request exec confirm 1

It hangs there. Then after a random time, it works again (without doing anything). Killing all sshd process on the server seems to work too. It works from a Putty. I saw that some people had trouble like this due to ISP reverse DNS problem, but it does not seem to be the case here.
It can work for hours and then not work for half an hour or so.
What could explain this behaviour ?
EDIT :
Seems that with -t or -T option, ssh does not hang, but I can't pass one of these options in the check_by_ssh of nagios

A: I got idea to resolve my problem from this blog. I also have very interesting problem
I got a L2vpn link (vendor provided MPLS L2) to connect my HO and branch office. all ping connectivity testings were working fine.
When i ssh using debian server from HO to a debian server at client side i can log in to that server but after remotely ssh login to branch server i was unable to run ifconfig, htop or ps -ef commands. When i apply thoses commands the session freezes. Evn that i check it from windows pc using putty the result was same.
Interesting thing is that when i use putty manager and ssh via that application from win 7 pc it was working fine.
After reading this blog i got mpls mtu information from service provider and try the same scenario with different mtu size on source debian server interface at HO.
Finally mtu sizes from 1440 to 1470 was working fine where as defaults mtu size 1500 was not working.
Conclusion:
the both end debian server's mtu size was default ie 1500 but in the mid way where service providers MPLS L2vpn mtu size was miss matching.
thanks

A: You may be hitting an SSH rate limiter on the server-side network. This is a firewall technique to block IP addresses that have too many new connection requests within a short period of time. Then the source IP is blocked for a defined period of time.

A: Possibly an ICMP Path MTU Discovery issue.
In our cause, all ICMP Paramters were blocked by the firewall on the server side. Decreasing client side MTU (adviced by this text) solved the issue temporary. But after allowing all (but redirect) ICMP parameters at the server side, the problem gone.

A: I had the same problem, and today finally discovered what was causing the issue (for me at least).  This might help you too.
When ssh is setting up a session, the DSCP flags field in the IP header is set to 0x0.  If you establish an interactive session, it is set to 0x10 (16),  and if you establish a non-interactive session, it is set to 0x8 (8).  The ssh client sets the DSCP field with the setsockopt() system call (which I verified in the source)
A faulty configuration on a VPN at my employer was dropping the packets with the DSCP of 0x8,  causing all non-interactive ssh traffic to also get dropped.  To verify it was the DSCP field that was causing the drop, I used iptables on the ssh server to force the DSCP field to be set to 0x16 and tested my non-interactive traffic (ssh  ls, same thing you were trying) and it worked after that.  You might also try the same thing and see if thats why your session is hanging.
To set DSCP to 0x10 on all outgoing ssh traffic from your ssh server, run:
$ sudo iptables -t mangle -A OUTPUT -p tcp --sport 22 -j DSCP --set-dscp 0x19
This was on a rhel 6.5 box.

A: I've experienced the same when having MTU problems. Using ciscos ipsec client-to-site, and then openvpn on top of that. Basically any packet with the size of 1500 bytes would freeze the session.

A: On my linux machine the VMWare network adapter vmnet2 MTU was set to 1500.
The network is used for a virtual machine acting as internet gateway.
Since changing the source from Wifi Internet to PPPoE Internet (fiber optics), remote ssh was not working anymore.
After lowering vmnet2'S mtu to 1400 ssh remote commands to other ssh servers worked again.
ifconfig vmnet2 mtu 1400 up

A: Check the ssh on the server side. You may "strace" the created process / mail sshd process and see what syscalls is it calling. This should give you more info on what is it doing.
Also try "touch /tmp/randomfile" and see if the hangs happens after it get created or afterwards.

A: Have you checked to make sure there arent any PAM errors?  just because it works from putty doesnt mean authentication isnt the problem.

A: I had similar problem. Both client's and server's MTU were 9000. After I lowered client's MTU to 1500 problem was gone.

A: A hang on "sending command" can be caused by SSH actually waiting for the keyphrase/password on the key. One can find out if this is the case by just taking off the command and SSH'ing into the server without a command at the end. It would then ask for a passphrase.

A: Could there be anything in the user shell environment deadlocking or delaying on open? The -t/-T workaround and closing other ssh sessions clearing it up sounds like something acquiring a lock with the assumption it's the only process.


text:
Q: Selecting 4 consecutive rows after conditioın I have this data
ratings <- data.frame(Rating = c(0,99,99,99,99,99,99,99,0,99,99,99,99,99,99,99,99,99,99,99),
Trial = c(1,NA,NA,NA,NA,NA,NA,NA,2,NA,NA,NA,NA,NA,3,NA,NA,NA,NA,NA))

Rating Trial
0        1
99      NA
99      NA
99      NA
99      NA
99      NA
99      NA
99      NA
0       2
99      NA
99      NA
99      NA
99      NA
99      NA
1       3
99      NA
99      NA
99      NA
99      NA
99      NA

I want to select the four consecutive rows after the second trial.
What I've tried
ratings |>
 mutate(var = ifelse(lag(Trial, n = 4L) == 2, 1, 0))

But, reasonably so, I am selecting only the 4th row.
What I want to get to:
Rating Trial var
0        1    0
99      NA    0
99      NA    0
99      NA    0
99      NA    0
99      NA    0
99      NA    0
99      NA    0
0       2     0
99      NA    1
99      NA    1
99      NA    1
99      NA    1
99      NA    0
1       3     0
99      NA    0
99      NA    0
99      NA    0
99      NA    0
99      NA    0

Any ideas? Thanks.

A: ratings <- data.frame(Rating = c(0,99,99,99,99,99,99,99,0,99,99,99,99,99,99,99,99,99,99,99),
Trial = c(1,NA,NA,NA,NA,NA,NA,NA,2,NA,NA,NA,NA,NA,3,NA,NA,NA,NA,NA))

library(dplyr, warn.conflicts = FALSE)

ratings %>%
  mutate(var = replace(rep(0, n()), which(Trial == 2) + 1:4, 1))
#>    Rating Trial var
#> 1       0     1   0
#> 2      99    NA   0
#> 3      99    NA   0
#> 4      99    NA   0
#> 5      99    NA   0
#> 6      99    NA   0
#> 7      99    NA   0
#> 8      99    NA   0
#> 9       0     2   0
#> 10     99    NA   1
#> 11     99    NA   1
#> 12     99    NA   1
#> 13     99    NA   1
#> 14     99    NA   0
#> 15     99     3   0
#> 16     99    NA   0
#> 17     99    NA   0
#> 18     99    NA   0
#> 19     99    NA   0
#> 20     99    NA   0

Created on 2022-08-07 by the reprex package (v2.0.1.9000)


text:
Q: elementFromPoint() full document alternative I am trying to recover a value from a cookie, which is somewhere on the Y-axis where the user clicked. I then want to find the parent
 from that click (if it helps, all the
s are the first child of a
). Here is what I have so far:
var bookmarkLocation;
function getBookmarkPos() {
    if ($.cookie("bookmark-position") !== null) {
        $(".bdnable").each(function(i) {
            var scrollTopTop = $(this).offset.top;
            var scrollTopBottom = $(this).offset.top + $(this).height();
            // var screenWidth = parseInt(screen.width/2);
            // alert(screenWidth);
            // var bookmarkPosition = parseInt($.cookie("bookmark-position"));
            // alert(bookmarkPosition);
            // var query = document.elementFromPoint(screenWidth, 50).nodeName;
            // alert(query);
            if ($.cookie("bookmark-position")>=scrollTopTop && $.cookie("bookmark-position")<=scrollTopBottom) {
                bookmarkLocation = $(this).closest("div").children(":nth-child(1)").text();
            }
        });

        if (bookmarkLocation == null) {
            bookmarkLocation = "Unknown";
        }
    } else {
        bookmarkLocation = "No bookmark set";
    }

    $("#bookmarklocationspan").html(bookmarkLocation);
}

In the commented out section is where I tried to use getElementFromPoint and then realized that it only checks the visible area. Not good, because the scrollable Y-axis on the page is 1000s of pixels tall.
Any ideas are greatly appreciated!!!

A: If you already have the y-coordinate of the click from the cookie, why not simply compare all H2's y-position and pick the one which is the next "higher" one? Your approach looks like it's compares whether the user has clicked directly on the H2 instead of the article/button below it?
Just an idea - don't rate it's style, think its prettey messy:
var $myH2 = $('h2');
var clickY = <COOKIE_VALUE>;
var currentY = 0;
var foundH2ID = '';
for (var i = 0; i < $myH2.length; i++) {
 var h2Y = $($myH2[i]).position().top;
 if (h2Y <= clickY && h2Y > currentY) {
  currentY = h2Y;
  foundH2ID = $myH2[i].id;
 }
}

Or maybe I got you wrong?


text:
Q: Problems on sending POST requests with Ruby RestClient I want to submit a form with Ruby RestClient to get the BibTex files for some papers. This is the request caught by the browser:
Request URL:
http://ieeexplore.ieee.org/xpl/downloadCitations
Request Method:
POST

Status Code:200 OK (from cache)
Request Payload
recordIds=6665065&citations-format=citation-only&download-format=download-bibtex&x=74&y=7

So here is my Ruby script:
response = RestClient.post("http://ieeexplore.ieee.org/xpl/downloadCitations", "recordIds"=> 6665065, "citations-format" => "citation-only", "download-format" => "download-bibtex", "x" => "74", "y" => "7"){|response, request, result, &block|
                    if [301, 302, 307].include?(response.code)
                            puts response
                    else
                            response.return!(request, result, &block)
                    end
            }
puts response

Though I could get the correct results directly in my browser, the script kept returning this:
<title>302 Moved Temporarily</title>

This document you requested has moved temporarily.

It's now at http://ieeexplore.ieee.org:80/xpl/downloadCitations?reload=true.

Does anybody know why this happens?
Thanks!


text:
Q: How to calculate gravitational force? I am getting the wrong output for the code below.  G = 6.674 x 10^-11.  I am supposed to get 3.559466666666664e+22 but I am getting 8.0088E44.  Can someone please explain what I have wrong on my code?  I will appreciate it. The inputs are 2e30 6e24 1.5e11
import stdlib.StdOut;
public class GraviForce {
    public static void main(String[] args) {
    double m1 = Double.parseDouble(args [0]);
    double m2 = Double.parseDouble(args [1]);
    double r  = Double.parseDouble(args [2]);
    double G = 6.674e-11;
    double f = G * (m1 * m2) / r * r;
    StdOut.println(f);

A: A simple operator associativity mistake - missing parens:
double f = G * (m1 * m2) / (r * r);


text:
Q: regex for extracting data in the middle of a string that has preceding comma + space and ends with space + (capital X) I have a string that I am trying to use regex to extract from. Here is the example of my string:
splitm = 'SM Analyst, AMT Tax Company X Hi.'

I want to parse out the name as "SM Analyst", The company as "AMT Tax Company" and the data after X as "Hi."
My regex for parsing the name is as below:
x = re.match('^.*?\,', splitm)

For the company I am trying: (everything after the comma but it isn't working)
y = re.match('^\,(.*?)', splitm).
Any pointers on what I am doing wrong here?

A: Caret (^) matches the position before the first character in the string.
This is not necessary if you don't use re.MULTILINE, because you use re.match:

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding match object.

Solution
We can use named groups to catch the relevant parts in a single regular expression, then to use groupdict to get the results as a dictionary:
import re

REGEX = r'(?P<role>.+?),\s+(?P<company>.+?)\s+X\s+(?P<message>.+)'
re.match(REGEX, "SM Analyst, AMT Tax Company X Hi.").groupdict()

{'role': 'SM Analyst', 'company': 'AMT Tax Company', 'message': 'Hi.'}

A: Try this:
import re

splitm = 'SM Analyst, AMT Tax Company X Hi.'

print(re.findall('(?<=, ).*(?= [A-Z] )',splitm)) # Find string that is between a ', ' and a uppercase letter that has a space on both sides
print(re.findall('(?<= )\w+\.',splitm)) # Find word character string that is between a ' ' and a '.'

Output:
['AMT Tax Company']
['Hi.']


text:
Q: Is it possibile to use a CAN transceiver to send RS485 data? Looking at the signal ranges I'm not sure if I can use a CAN transceiver (not controller!) to send data to a single RS485 device.

A: In the CAN recessive state, the differential voltage can be zero. This is not a valid RS-485 signal level.
However, many RS-485 receivers have built-in fail-safe logic that interprets an undriven bus as logic one, and a bus without such logic is supposed to have fail-safe biasing resistors with the same effect. So if you wire the bus so that the CAN dominant state (CANH > CANL) corresponds to RS-485 logical zero (A < B), then it might actually work.


text:
Q: how do i SQL specific items from a column (php) <?php
    mysql_connect('localhost', 'admin', '') or die (mysql_error());
    mysql_select_db("elia_internal") or die (mysql_error());

    $query = "SELECT * FROM information GROUP BY Karori ";
    $result = mysql_query($query) or die(mysql_error());

    while($row = mysql_fetch_array($result)){
    print"
".$row['Agent']."	".$row['Address']."	".$row['Suburb']."	".$row['Bedrooms']."	".$row['Bathrooms']."	".$row['Price']."	";
    }

?>
I am trying to SQL specific items from columns from my database for example im trying to pull up all houses listed in the suburb Karori. the column is Suburb and there are 5 different suburbs in the column. how do i get the php to show JUST the houses listed in Karori and not the others.

A: Try this
$query = "SELECT * FROM information where suburb="karori" GROUP BY Karori ";


text:
Q: Select div having similar class name but no div id Parent Class inddetails-wrapper clearfix has two divs which as further classes having same name.
I want to select first class col-md-6 nopadding. How should I do that ?
Below is the code:

...

...

A: You can use :first-child:

.inddetails-wrapper div:first-child .col-md-6 {
  background: #f00;
}

...

...

A: as this question was tagged under jquery You can select the first element inside
 using Jquery like this:
var firstChild = $( ".inddetails-wrapper.clearfix div" ).first();

and you can play with firstChild using more jquery properties depending upon what do you need.


text:
Q: Ubuntu 20.04 boot time is slow I am using ubuntu 20..4 LTS.
system configuration is:-
RAM= 6GB
PROCESSOR= i3 4th gen.
HDD = 500GB.
Its boot time takes 2-3 times. 1-2 minutes After Booting, if i want to open the application then it does'not open. it look like hang.
It takes more and more in boot time as well as after boot time.
so how i resolve it?


text:
Q: Application becomes terribly slow on full screen - AIR I have many movieclips with a sequence of bitmaps inside them, one in each frame. When I set the program to fullscreen or make it bigger on the screen, it gets REALLY slow.
Is this a known problem? Is there some way to fix it?

A: Discovered the problem already. It isn't related to being in full-screen or not. It happened because I forgot to tell the app to remove some instances after some time, they was still on screen when I added another big object upon the smaller ones, making them invisible but still processor costly.


text:
Q: Core Audio: How to store buffers in RAM before writing to disk or deleting? My app uses Core Audio to analyse audio buffers, recording over long time periods but only presenting a few samples of that audio to the user. To date, I have been writing everything to disk before selectively deleting files. However, it seems that the write operation is quite demanding of the hardware, and can occasionally trigger crashes if used too much.
I'd love to have a way to avoid the write operation unless necessary, which could be done by storing audio buffers (say 1 minutes worth) in RAM before either writing to disk or releasing them from memory if not needed.
Can anyone please advise of the most efficient way that this can be done?
renderErr = AudioUnitRender(rioUnit, ioActionFlags,
                                    inTimeStamp, bus1, inNumberFrames, THIS->bufferList);

Analysis of buffer....

OSStatus s;

s = ExtAudioFileWriteAsync(THIS->mAudioFileRef, inNumberFrames, THIS->bufferList);

What would be the best container for storing the buffer before selectively running a loop to write the buffer to disk...? What would  be the best way to release the memory?

A: A lock-free circular queue or fifo using an array of samples of size 2646000+1 or larger could store 1 minute of mono audio at 44.1 ksps in RAM.  Most iOS devices won't have a problem allocating 6MB or more of memory for a queue or fifo.  Displaying, analyzing or writing this data to disk can be done in another thread via a periodic polling or displaylink timer (emptying from the tail of the circular queue or fifo).  The memory used for this array can be released after the audio unit is stopped.


text:
Q: Checking success of http status In Classic ASP, I'm setting a page's status to 410 Gone, as the contents were previously removed by our administrators. Is there any way to check if this was successfully applied or not?

A: As @dash pointed out Fiddler is a good tool for debugging and verifying HTML / server responses.

A: Yes, you can check this by many debugging tools or websites. Here's a couple of websites:

*

*http://web-sniffer.net/

*http://www.axandra.com/free-online-seo-tool/status-code.php


text:
Q: Pairwise displacement vectors among set of points

I have an array of N points in d dimensions (N, d) and I'd like to make a new array of all the displacement vectors for each pair (N choose 2, d).  If I just want the magnitude of these vectors, I can use pdist from scipy.spatial.distance.
It would be great if I could just do
pdist(points, lambda u, v: u - v)

but the metric function must return a scalar (ValueError: setting an array element with a sequence.)

My solution is to use np.triu_indices:
i, j = np.triu_indices(len(points), 1)
displacements = points[i] - points[j]

This is about 20-30 times slower than using pdist (I compare by taking the the magnitude of displacements, though this is not the time-consuming part, which I presume is actually making the upper triangle and running fancy indexing).

A: Straight forward would be
dis_vectors = [l - r for l, r in itertools.combinations(points, 2)]

but I doubt that it is fast. Actually %timeit says:
For 3 points:
list : 13 us
pdist: 24 us

But already for 27 points:
list : 798 us
pdist: 35.2 us

About how many points are we talking here?
Another possibility something like
import numpy
from operator import mul
from fractions import Fraction

def binomial_coefficient(n,k):
    # credit to http://stackoverflow.com/users/226086/nas-banov
    return int( reduce(mul, (Fraction(n-i, i+1) for i in range(k)), 1) )

def pairwise_displacements(a):
    n = a.shape[0]
    d = a.shape[1]
    c = binomial_coefficient(n, 2)

    out = numpy.zeros( (c, d) )

    l = 0
    r = l + n - 1
    for sl in range(1, n): # no point1 - point1!
        out[l:r] = a[:n-sl] - a[sl:]
        l = r
        r += n - (sl + 1)
    return out

This simply "slides" the array against itself over all dimensions and performs a (broadcastable) subtraction in each step. Note that no repetition is considered and no equal pairs (e.g. point1 - point1).
This function still performs well in the 1000 points range with 31.3ms, whereas pdist is still faster with 20.7 ms and the list comprehension takes the third place with 1.23 s.

A: If you compute the full cartesian product of differences, flatten the resulting 2D array, and create your own indices to extract the upper triangle, you can get it to be "only" 6x slower than pdist:
In [39]: points = np.random.rand(1000, 2)

In [40]: %timeit pdist(points)
100 loops, best of 3: 5.81 ms per loop

In [41]: %%timeit
    ...: n = len(points)
    ...: rng = np.arange(1, n)
    ...: idx = np.arange(n *(n-1) // 2) + np.repeat(np.cumsum(rng), rng[::-1])
    ...: np.take((points[:, None] - points).reshape(-1, 2), idx, axis=0)
    ...:
10 loops, best of 3: 33.9 ms per loop

You can also speed up your solution, creating the indices yourself, and using take instead of fancy indexing:
In [75]: %%timeit
    ...: n = len(points)
    ...: rng = np.arange(1, n)
    ...: idx1 = np.repeat(rng - 1, rng[::-1])
    ...: idx2 = np.arange(n*(n-1)//2) + np.repeat(n - np.cumsum(rng[::-1]), rng[::-1])
    ...: np.take(points, idx1, axis=0) - np.take(points, idx2, axis=0)
    ...:
10 loops, best of 3: 38.8 ms per loop


text:
Q: How to test docker image with external script Assume that I have a code repo. That code repo has the following files in it:

*

*Dockerfile

*test.sh

lets say I now build a docker image from the Dockerfile
docker build -t my-image .

Now I want to execute the test.sh in the context of my-image in a container, yet I don't have added test.sh to the docker image during build.
How do I run the docker image and execute the test.sh in it? Do I have to mount the repo as volume first or is there a quicker way?

A: If test.sh is not part of image then you will have to mount the local repository as a volume.
docker run -v /path/to/local/repo:/tmp my-image /tmp/test.sh

A: Couple of options:

*

*Copy it in (docker cp test.sh <container_id>:<path_file_should_go_inside>) - but then you gotta run the file as a separate step

*Mount it in (docker run -v $(pwd)/test.sh:<path_file_should_go_inside> my-image <path_file_should_go_inside>)


text:
Q: &nbsp Acting Oddly I'm seeing this odd issue where &nbsp is being turned into some odd "?" symbol. Like it's some unknown character I've typed. (I'm using   in the xsl).
Once pass through the XSL just leaves this as &nbsp. Another "pass" through the XSL makes this odd character show up, the "?". The "?" even shows up when doing inspect element. So odd!
What could do the XSL transformer be doing to cause such a thing?
I've thought it was the different CSS templates being applied on the problem "pass" but the css I see through inspect element is identical for both cases.

A: You forgot a semicolon:


text:
Q: NullPointerException in DialogFragment on setAdapter() of a list I create a custom DialogFragment. It contains a listView, but when the list calls setAdapter there is a NullPointerException. I can't understand why.
This is the code:
public class LineUpConfirm extends DialogFragment {

    private ListView list;
    private List<ItemLineUpConfirm> pList = new ArrayList<ItemLineUpConfirm>();
    private AdapterListConfirmLineUp adapter;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        LayoutInflater inflater = getActivity().getLayoutInflater();
        builder.setView(inflater.inflate(R.layout.confirm_lineup_layout, null));

        pList.add(new ItemLineUpConfirm("P", "C. Abbiati","MIL","INT"));
    pList.add(new ItemLineUpConfirm("D", "C. Papastapopulos","SAS","VER"));
    pList.add(new ItemLineUpConfirm("C", "Cacca","SAM","GEN"));

    adapter = new AdapterListConfirmLineUp(CurrentContext.getContext(),
            R.layout.item_confirm_lineup, pList);

    list =  (ListView) getActivity().findViewById(R.id.list_confirm_lineup);

        list.setAdapter(adapter);   // HERE NullPointerException

        return builder.create();
    }
}

This is the layout of my Dialogfragment:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/title_progressdialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Formazione creata"
        android:layout_margin="5dp" />

    <ListView
        android:id="@+id/list_confirm_lineup"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:background="#fff"
        android:divider="#575555"
        android:dividerHeight="1dp" />

    <Button
        android:id="@+id/button_confirm_lineup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Conferma"
        android:layout_gravity="center" />

</LinearLayout>

A: Your list is null because you're trying to get the View from the Activity layout instead of the one of the Dialog.
Try to keep a reference of the Dialog view and get it from there:
View dialogView = inflater.inflate(R.layout.confirm_lineup_layout, null);
// some code
list =  (ListView) dialogView.findViewById(R.id.list_confirm_lineup);

A: I update your method
@Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        LayoutInflater inflater = getActivity().getLayoutInflater();
        View v = inflater.inflate(R.layout.confirm_lineup_layout, null);
        builder.setView(v);

        pList.add(new ItemLineUpConfirm("P", "C. Abbiati", "MIL", "INT"));
        pList.add(new ItemLineUpConfirm("D", "C. Papastapopulos", "SAS", "VER"));
        pList.add(new ItemLineUpConfirm("C", "Cacca", "SAM", "GEN"));

        adapter = new AdapterListConfirmLineUp(CurrentContext.getContext(), R.layout.item_confirm_lineup, pList);

        list = (ListView) v.findViewById(R.id.list_confirm_lineup);

        list.setAdapter(adapter); // HERE NullPointerException

        return builder.create();
    }

The problem was you are trying to find the listview from activity but it is actually in alertbuilder view. So I just change that.


text:
Q: angularjs window.alert() while using mouseEvents causes error Here is the link to the code:
http://plnkr.co/edit/usrmiNkj5YJY5SlV8ETw?p=preview
Open up your javascript console and click on "say hi". It will trigger an error that $apply is already in progress.
But when you remove this piece of code:
ng-controller="mouseEvents" ng-mousedown="onMouseDown()" ng-mouseup="onMouseUp()" ng-mousemove="onMouseMove()"

and after saving when you click on "say hi" the error is gone.
How can I solve this?
I need the mouseEvents to set flags if the mouse is down or if it is up for multiple different controllers. I can not simply remove it in my code.
Edit:
Newer angular version solved my issue without $timeout v1.3.10 or higher

A: Use $timeout to let angular finish dirty checking then show the alert.
app.controller("demoController",function($scope,$window, $timeout){
  $scope.save = function(){
    $timeout(function(){
       window.alert("hi!");
    });

  };
});

Plunkr: http://plnkr.co/edit/Kxbey5Rc43xsB9v5ugZ5?p=preview


text:
Q: Defining variables with grunt-contrib-less Unless I'm misunderstanding this documentation it's possible to define a global less variable within your Gruntfile and reference it in your .less file (pretend there's a reason).
less: {
  modVar: {
    options: {
      plugins: [
        new (require('less-plugin-autoprefix'))
      ],
      modifyVars: {
        root: "<%= grunt.option('distRoot') %><%= grunt.option('distTarget') %>"
      },
      root: "<%= grunt.option('distRoot') %><%= grunt.option('distTarget') %>",
    },
    files: {
      '<%= yeoman.dist %>/styles/main.less' : '<%= yeoman.app %>/styles/{,*}*.less'
    }
  },

That (above) is my entry for the Gruntfile, and I'm trying to reference the variable root in one of my my .less files (main.less), but every time it's throwing an error in my console, "@root is undefined" in main.less. Am I misunderstanding what's possible with grunt-contrib-less? Or am I simply doing something wrong?

A: Alright, I figured it out. Had to tweak my less task in my gruntfile like so (based on the documentation/scouring the issues section):
less: {
  options: {
    compress: true,
    yuicompress: true,
    optimization: 2,
    modifyVars: {
      root: '"<%= grunt.option(\'distRoot\') %><%= grunt.option(\'distTarget\') %>"'
    }
  },
  /* blah, blah, blah...other less stuff.... */
}

So, rather than create a completely separate task for this variable modification I needed to simply throw the modifyVars option in the options section of my less task. More importantly (because I had tried that previously), was to wrap my variable's new value in single quotes despite having them already doubly-quoted. This was a huuuuuge headache to figure out.
Your variables should look like this:
 '"myWorkingValue"'

and not like this:
 "myNonWorkingValue"

And, for completeness, reference the variables in your .less file like so:
@{myModifiedVariable}

You should be set at this point.


text:
Q: Python: Output while waiting for input So I currently have a thread that is outputting, and I need a way to handle input while still allowing output from the thread in the meantime.
Currently I have something like this
def thread_func():
    while True:
        print("Information")

threading.Thread(target=thread_func).start()

while True:
    command = raw_input("Enter a command:")
    #dostuff with command

My issue now is that my thread isn't printing anything.  Or if it is it isn't showing up
Edit:
Found a solution here
Exiting while loop by pressing enter without blocking. How can I improve this method?

A: You want to use a Queue. New input will go into the back of the queue, and work will be started from the front.


text:
Q: Динамические строки, их ввод Пытаюсь придумать, как заполнить строку (динамически выделенную) неизвестной длины с консоли.
Вот к чему я пришел:
str = (char*)calloc(1, 1);
    c2 = 0;

    while (1==1)
    {
        sim = getchar();

        if (sim != '\n')
            str[c2] = sim;
        else
            break;

        c2++;
        str = (char*)realloc(str, c2+1);
    }

str - строка для ввода
т.е я читаю посимвольно и выделяю память для каждого символа, который перед помещением в строку храниться в sim.
В итоге getchar() остановился на \n, что печально, ведь я хотел еще считать неопределенное количество строк и записывать в массив строк. Можно использовать string, но меня интересует чистый Си.
И второй момент: когда я выделяю память под строку в ней находиться какой-то мусор!! Хотя я делал так - str = new char[0 или 1];
Хрень какая-то. Можете помочь с решением двух проблем. Заранее спасибо
И еще, как ввести символ нулевой строки(признак конца строки) в Windows?

A: *

*Все же realloc для каждого символа (а работа с памятью довольно дорогостояща в плане эффективности) вариант тяжелый. Может, задуматься о, например, удвоении памяти, если ее не хватает?

*Что значит getchar() остановился? Вы ввели строку, она пошла в буфер ввода, пошло считывание, последний введенный символ \n, работает break. Все, как вы попросили. Приступайте к новому чтению очередной строки.

*Мусор будет находиться и при вызове malloc, например. Выделенная память не очищается, если только вы не сделали это самостоятельно или не вызвали специальную функцию выделения с очисткой, как это сделано у вас.

*Нулевой символ в Windows вводится в строку точно так же, как и в любой другой операционной системе — присваиванием типа str[i] = '\0' или просто str[i] = 0.


text:
Q: regular expressions cut from the second pipe Using java regular expressions basically to reduce a list of semicolon separated properties
2013-07-15 21:46:26|Dinner with James|Lucerne|MEDIATYPE;image|CATEGORY;25|365|423|IMGTOKEN;8adbfb5840349cac014052ded00f26da|TAGS;dinner|james|lucerne;

What I am trying to achieve is to:

*

*strip all characters after the next semicolon;

*cut the word before the semicolon (in this example MEDIATYPE);

*cut the pipe

Expected end result:
2013-07-15 21:46:26|Dinner with James|Lucerne

How could I do that with regular expressions?
Solved! Thanks! (.*?)(?=\|[^|;]+;) worked out for me

A: So you want to split on the the pipe (|) before the semi-colon?
This pattern will work:
\\|(?=[^|]*;)

Explanation

*

*\\| a literal pipe character. The double escape is Java syntax

*(?=[^|]*;) this is a lookahead assertion that finds a semi-colon that follows the pipe. There are any number of non-pipe characters before the semi-colon.

Example:
public static void main(final String[] args) throws IOException {
    final String input = "2013-07-15 21:46:26|Dinner with James|Lucerne|MEDIATYPE;image|CATEGORY;25|365|423|IMGTOKEN;8adbfb5840349cac014052ded00f26da|TAGS;dinner|james|lucerne;";
    final String[] split = input.split("\\|(?=[^|]*;)");
    System.out.println(split[0]);
}

Output:
2013-07-15 21:46:26|Dinner with James|Lucerne

A: You could perhaps use a replace, matching on the first pipe that is immediately followed by a semicolon. The raw regex string I suggest is:
\|(?=[^|;]*;).*

Which is this in Java string:
\\|(?=[^|;]*;).*

An example:
String text = "2013-07-15 21:46:26|Dinner with James|Lucerne|MEDIATYPE;image|CATEGORY;25|365|423|IMGTOKEN;8adbfb5840349cac014052ded00f26da|TAGS;dinner|james|lucerne;";
String result = text.replaceAll("\\|(?=[^|;]*;).*", "");
System.out.println("Result: " + result);

which should give you:
2013-07-15 21:46:26|Dinner with James|Lucerne

Breakdown:
\\|      Match a literal pipe
(?=      Begin positive lookahead
  [^|;]* Any character except pipe or semicolon
  ;      A semicolon
)        End positive lookahead
.*       Anything else on this line

The positive lookahead is ensuring that there is a semicolon right after the pipe where the 'cut' begins without any more pipe or semicolons in between.

A: Use this pattern:
(.*?)(?=\|[^|;]+;)

Example


text:
Q: validation in jquery If an address polo Rd is given, it identifies "po" in  polo and alerts error message.
So, we should frame a new validation which should not accept address lines 1 and 2 with the values:

*

*"PO BOX",  "PO BIN",  "BIN", "P.O BOX", "P.O BIN", "P.O", "PO"

*the above values can be in any case

*spaces before, in between  and after the above words should also be found and validated. For example:  "    P  O    1234    "  should be validated and alert error message.

*But "Polo Rd", "Robin Rd", "testbintest" should be accepted as valid address in both the address lines

the code which is writen for this is
jQuery.validator.addMethod("nopobox", function(value, element) {
     return this.optional(element) || ! /(P(OST)?\.?\s*O(FF(ICE)?)?\.?\s*((BOX)|(BIN)))|(^[^0-9]*((P(OST)?\.?\s*O(FF(ICE)?)?\.?)|((BOX)|(BIN))))/i.test(value);
}, "");

Please let me know how I can change it

A: edit
I played around with this a bit... don't know if this will match 100% of your cases but try this:
<html>
   <head>
      <title>testing...</title>
      <script type="text/javascript" src="scripts/jquery/1.3.1/jquery.min.js"></script>
      <script type="text/javascript" src="scripts/jquery.validate.min.js"></script>
      <script type="text/javascript">
jQuery.validator.addMethod("nopobox", function(value, element) {
     return ! /(?:p(?:ost)?\.?\s?[o|0](?:\.|ffice)?)\b|(?:b(?:[o|0]x)|(?:in))\b/i.test(value);
}, "PO Boxes are not allowed.");

$(document).ready(function() {$('#test').validate({rules: {address: {nopobox: false, required: true}}})});
      </script>
   </head>
   </body>
      <form id="test" action="#">
         <input type="textbox" id="address" class="required nopobox" />
         <input type="submit" />
      </form>
   </body>
</html>

When I run this I get the "PO Boxes are not allowed" error on: PO, po, p.o, p.o., po box, box, bin, etc, etc.  But polo road, testboxtest, etc: no warning.  One bug: po road throws and error... I'm not sure you can test 100% of the cases in a single Regex.
end edit
Ok... the Regex master don't seem to be online... I'll give it a shot:
Try this regex (?:(?:p(?:[o|0]st)?\.?(?:[o|0](?:ffice)?\.?))|(?:b[o|0]x|bin))(?=\s\d)
It give me the following in the powertoy: (entered as: s/(?:(?:p(?:[o|0]st)?\.?(?:[o|0](?:ffice)?\.?))|(?:b[o|0]x|bin))(?=\s\d)/**NO PO BOXES**/i for testing.
Matches:

*

*PO BOX 123

*PO BIN 1

*BIN 1

*P.O BOX 134

*P.O BIN 12

*P.O 12

*P.o. 12

*PO 123

Does not match:

*

*123 boxing road

*123 box road

*123 polo road


text:
Q: Why no refactoring tools in PHP Eclipse? Do I need to install something? I'm looking for the "Highlight code -> right-click -> Extract Method" type of functionality I see in Eclipse Java. Does this exist for PHP?

A: I'm using Zend Studio 7, which is also an Eclipse product, and I can see that option through the "refactor" submenu

Highlight code -> right-click ->
  Refactor -> Extract Method

Not sure if PHP Eclipse has the same thing.

A: No, most of the refactoring functionality does not work for PHP in Eclipse with PDT. I assume it's because PHP is so much more dynamically typed than Java.
Zend Studio, which is Eclipse with some other extensions has more PHP features, but it will cost you a few hundred bucks.

A: hum, having been one of the phpeclipse developers, the only thing I can say is that: it has never been implemented...  refactoring in Java's JDT is a large piece of non-trivial code! doing the same in PHp is even less trivial


text:
Q: (Bash) Regex variable inside another regex I am writing on a script which greps with a regular expression and includes another regular expression with a variable. But there it seems to lay the problem.
Script ($hostname is an argument from command line and can be i.e. google.com):
tldlist="$(curl -s http://data.iana.org/TLD/tlds-alpha-by-domain.txt | grep -v '#' | tr '\n' '|' | sed 's/|$//g')"

curl="$(curl -vfIk https://$hostname 2>&1 | sed 's/^\* \t //g' | grep -i -o --color=never -E \"CN=\(.*\)\.\($tldlist\)\")"
expiration="`curl -vfIk https://$hostname 2>&1 | sed 's/^\* \t //g' | grep -i -E --color=never '(start|expire)'`"

echo "$curl"
echo "$expiration"

It just does not match the part with the common name in the output of curl.
If I write the regex manually, it works and matches successfully.
So the question is: How to solve this regex problem inside bash?
Update
Now I tried to write it in another way, it works (basically):
curl=$(curl -vfIk https://$hostname 2>&1 | sed 's/^\* \t //g' | grep -i -o --color=never -E "CN=(.*)\.($tldlist)")

The problem lays at escaping the quotes and brackets. But I have to put the output of the command into double quotes due to multiline variables (not with the line above, this just gives you one line).
But still:
There is the question how to solve the escape/regex/variable problem.

A: The immediate problem is not a regex issue.  You have your $tldlist variable inside single quotes, and single quotes prevent variable expansion.  Change your second line to, e.g.:
curl="$(curl -vfIk https://$hostname 2>&1 | sed 's/^\* \t //g' | tr '[A-Z]' '[a-z]' | grep -i --color=never -E "CN=\(.*\)\.$tldlist")"

so as to allow $tldlist to expand.


text:
Q: I am not able to Razorpay payment getway intigretion in Flutter web, could you help me in this import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: Scaffold(
          body: Container(
            child: Column(
              children: [
                SizedBox(
                  height: 50,
                ),
                Image.network(
                  'https://images.unsplash.com/photo-1611186871348-b1ce696e52c9?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8YXBwbGUlMjBsYXB0b3B8ZW58MHx8MHx8&w=1000&q=80',
                  height: 250,
                  width: 350,
                ),
                SizedBox(
                  height: 20,
                ),
                Text('macbook pro'),
                SizedBox(
                  height: 20,
                ),
                Text('description'),
                SizedBox(
                  height: 20,
                ),
                Text('rs200000'),
                SizedBox(
                  height: 20,
                ),
                ElevatedButton(onPressed: () {}, child: Text('buy now'))
              ],
            ),
          ),
        ));
  }
}

Let's suppose this is the project then when we click on buynow button then razorpay popup should be open in website
**Could you guys help me in this because I think razorpay doesn't provide any plugin for Flutter web **

A: Add this package razorpay_web: ^1.1.0 in pubspec.yaml file
Then copy the full code and paste in main.dart and run it works then enjoy..
import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:razorpay_web/razorpay_web.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: Scaffold(
          body: Container(
            child: Column(
              children: [
                SizedBox(
                  height: 50,
                ),
                Image.network(
                  'https://images.unsplash.com/photo-1611186871348-b1ce696e52c9?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8YXBwbGUlMjBsYXB0b3B8ZW58MHx8MHx8&w=1000&q=80',
                  height: 250,
                  width: 350,
                ),
                SizedBox(
                  height: 20,
                ),
                Text('macbook pro'),
                SizedBox(
                  height: 20,
                ),
                Text('description'),
                SizedBox(
                  height: 20,
                ),
                Text('rs200000'),
                SizedBox(
                  height: 20,
                ),
                Builder(
                  builder: (context) => Center(
                    child: RaisedButton(
                      color: Colors.blue,
                      child: Text("Buy Now"),
                      onPressed: () => Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => Payments()),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ));
  }
}

class Payments extends StatefulWidget {
  const Payments({Key? key}) : super(key: key);

  @override
  _PaymentsState createState() => _PaymentsState();
}

class _PaymentsState extends State<Payments> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: RazorpayWeb(
          rzpKey: "rzp_test_DNaSxot4oJHykG", // Enter Your Razorpay Key Here
          options: RzpOptions(
            amount: 1000,
            name: "Razorpay",
            description: "Test Payment",
            image: "https://i.imgur.com/3g7nmJC.png",
            prefill: const PrefillData(
              name: "Razorpay",
              email: "rzp@gmail.com",
              contact: "9876543210",
            ),
            colorhex: "#FF0000",
          ),
          onPaymentSuccess: (String paymentId) {
            print("Payment Success");
            log(paymentId);
          },
          onPaymentError: (String error) {
            print("Payment Error");
          },
        ),
      ),
    );
  }
}

If payment is successful onPaymentSuccess Function will contain the payment_id from razorpay.


text:
Q: elastic search - exclude documents matching criteria Is there a way to search and exclude certain documents?
my use case is that I serve 5 documents to the client at a time, and I want to allow the client to query for more.
the idea is to store IDs of documents client already has and pass this back to the API endpoint.
I want to apply a search terms and also exclude documents that match the sent IDs.


text:
Q: How can I perform a full-text CONTAINS call across a list of phrases? I have a list of words/phrases in a table phrases. I have another table with a full-text catalog indexing the description column.
I want to populate a table results with a record for each phrase, and the number of times that phrases was found in the description:
INSERT INTO results(phrase, foundcount)
SELECT  phrase,
    (SELECT COUNT(*) FROM table WHERE CONTAINS(table.description, phrase))
FROM    phrases;

No matter how I try, this results in the error:
Incorrect syntax near `phrase`. Expecting STRING, TEX_LEX, or VARIABLE

I would really rather not use a cursor just so I can assign each phrase to a variable. Is that really the only option?

A: Try this:
go
create function dbo.fn_GetCountForPhrase (@phrase varchar(500))
    returns  int
as
begin
    declare @count int
    declare @localphrase varchar(8000)
    set @localphrase='"' + @phrase + '"'
    SELECT @count=COUNT(*) FROM table  a WHERE CONTAINS(table.description,   @localphrase)
    return @count
end
go
SELECT
    phrase,
    dbo.fn_GetCountForPhrase(phrase)
FROM phrases

A: I think you can get what you need from the DMVs, including sys.dm_fts_index_keywords_by_document and sys.dm_fts_parser, something like this:
SELECT p.phrase, kbd.display_term
FROM sys.dm_fts_index_keywords_by_document( DB_ID(), OBJECT_ID('dbo.documentText') ) kbd
    CROSS APPLY dbo.phrases p
        CROSS APPLY sys.dm_fts_parser  ( N'FORMSOF(FREETEXT, "' + phrase + N'")', 1033, 0, 1 ) x
WHERE x.display_term = kbd.display_term

Caution: if you wrap your searches in quotes you get an exact match, so you're not really getting the benefit of full-text indexing.  You could also just do that with Like and wildcards(%).  Also scalar functions do not tend to scale well over large resultsets.


text:
Q: Adding a border to circle object fabricjs I'm trying to add a border to a circle. The only round about way I can think of is by adding another circle underneath it. Is there a better way?
fiddle: http://jsfiddle.net/9mqqh3of/4/
PS: having trouble centering it too.
HTML:
<canvas id="c" width="300" height="300"></canvas>

Javascript:
var canvas  = new fabric.Canvas('c');

let radius = 20;
let radius1 = 10;

let circle = new fabric.Circle({
  fill: "green",
  hoverCursor: "pointer",
  left: 20 - radius,
  opacity: 1,
  radius,
  selectable: false,
  strokeWidth: 5,
  strokeColor: "white",
  top: 20 - radius
});

let circle1 = new fabric.Circle({
  fill: "red",
  hoverCursor: "pointer",
  left: 20 - radius1,
  opacity: 1,
  radius: radius1,
  top: 20 - radius1
});

canvas.add(circle);
canvas.add(circle1);

A: Use stroke for stroke color and strokeWidth for width of stroke.
DEMO

let canvas = new fabric.Canvas('canvas');
let circle = new fabric.Circle({
  fill: "green",
  hoverCursor: "pointer",
  left: 20,
  opacity: 1,
  radius:100,
  selectable: false,
  strokeWidth: 15,
  stroke: "red",
  top: 20
});
canvas.add(circle)
canvas {
  border:1px solid #000;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="canvas" height="400" width="400"></canvas>


text:
Q: Generate a custom tzdb.dat for Java time zones With Java 1.6 I generated a jre/lib/zi/America/Sao_Paulo time zone file from a .zic file, which has a content like following:
Rule Brazil 2012 only - Feb 26 06:00 0 S
Rule Brazil 2012 only - Oct 21 00:00 1 D
Rule Brazil 2013 only - Feb 17 06:00 0 S
Rule Brazil 2013 only - Oct 20 00:00 1 D
Rule Brazil 2014 only - Feb 16 06:00 0 S
Rule Brazil 2014 only - Oct 19 00:00 1 D
Rule Brazil 2015 only - Feb 22 06:00 0 S
Rule Brazil 2015 only - Oct 18 00:00 1 D
Rule Brazil 2016 only - Feb 21 06:00 0 S
Rule Brazil 2016 only - Oct 16 00:00 1 D
Rule Brazil 2017 only - Feb 19 06:00 0 S
Rule Brazil 2017 only - Oct 15 00:00 1 D
Zone Brazil/East -3:00 Brazil BR%sT

Now, with Java 8, the jre/lib/zi folder no longer exists. It was replaced by the jre/lib/tzdb.dat file.
How can I generate this tzdb.dat file with my custom Time Zones?

A: I've found the solution.

*

*Download a Time Zone Database from the Internet Assigned Numbers Authority (iana - http://www.iana.org/time-zones). In my case, Time Zone Data v. 2015f (http://www.iana.org/time-zones/repository/releases/tzdata2015f.tar.gz)

*Unpack the compressed file.

*Edit the file which references the location. In my case, southamerica.

*Replace the lines with custom values.
Rule Brazil 2012 only - Feb 26 06:00 0 S
Rule Brazil 2012 only - Oct 21 00:00 1 D

*Repack the files into a tar.gz file.

*Calculate the sha512 hash for the file (https://defuse.ca/checksums.htm#checksums)

*Create a file containing the sha512 hash.

*Name this file with the same name of the tar.gz adding .sha512 at the end of the name.

*Put both files in the same directory

*Use the Timezone Updater Tool (tzupdater.jar) - http://www.oracle.com/us/technologies/java/tzupdater-readme-136440.html - for create a new tzdb.dat file
java -jar tzupdater.jar -f -l file:///path/to/file/tzdata2015f.tar.gz
Voila!

A: You might be able to try this backport-class:
TzdbZoneRulesCompiler
But note: It is not public (you could circumvent it by copy-and-paste or similar) hence not really intended for public usage. And furthermore, it is not the original tz compiler used by oracle but probably creates the same output (assuming that this detail was kept identical in backport of java.time).
And I agree with the comments of Matt Johnson to avoid using custom time zones if possible and to adjust the application code instead. You could also consider creating custom time zones by defining specialized zone rules (via the official Java-8-API).


text:
Q: Webpack Sequential Multiple Configs? I have a single file webpack.dev.js and within it I have 2 standard build configs.
const buildA = {};
const buildB = {};

module.exports = [buildA, buildB];

This is sweet, everything works.  The problem is however that buildB expects buildA to complete and the builds appear to occur in parallel.  So I get an error.
Is there a way to achieve sequential builds when using this format?  Otherwise, how could I achieve something similar by another means?
I am using webpack-dev-server which appears to only take a single configuration and that is why I am down this path of multiple configurations exported

A: there's a discussion at Github (ref https://github.com/webpack/webpack/issues/3838, https://www.viget.com/articles/run-multiple-webpack-configs-sequentially/) will try it in a bit.
the plugin was trying to poll and wait for a certain file to be available before resuming the next config in line.


text:
Q: I am trying to view the definition of the stored procedure using sp_helptext but I am not able to. Can you please suggest? enter image description here
I am trying to view the definition of the stored procedure using sp_helptext but I am not able to. Can you please suggest?

A: use the following:-
USE MSDev
EXEC sp_helptext 'yourProcedureName'
Hope it helps.
Regards,


text:
Q: Apply google.maps.LatLngBounds() but not working - Ionic I'm trying to add google maps in my ionic project. Other than that, I want all the markers in google maps fits all in screen. I don't know where it wrong. My reference here https://developers.google.com/maps/documentation/javascript/reference?csw=1#LatLngBounds
Here is the code
HTML: index.html

   <map on-create="mapCreated(map)"></map>
</ion-content>

JS: directives.js
angular.module('starter.directives', [])

    .directive('map', function() {
      return {
        restrict: 'E',
        scope: {
      onCreate: '&'
    },
    link: function ($scope, $element, $attr) {
      function initialize() {
        var mapOptions = {
          center: new google.maps.LatLng(43.07493, -89.381388),
          zoom: 16,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map($element[0], mapOptions);

        $scope.onCreate({map: map});

        // Stop the side bar from dragging when mousedown/tapdown on the map
        google.maps.event.addDomListener($element[0], 'mousedown', function (e) {
          e.preventDefault();
          return false;
        });
      }

      if (document.readyState === "complete") {
        initialize();
      } else {
        google.maps.event.addDomListener(window, 'load', initialize);
      }
    }
  }
});

JS: app.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.directives'])

JS: controllers.js
$scope.mapCreated = function (map) {
        $scope.map = map;

        var pos = new Array (new google.maps.LatLng(3.050511,101.687833), new google.maps.LatLng(3.122847,101.676846), new google.maps.LatLng(3.078409,101.608025), new google.maps.LatLng(2.932928,101.642603));

        //Create marker
        var createMarker = function (pos, icon) {
            console.log("create marker");
            var marker = new google.maps.Marker({
                position: pos,
                map: map,
                icon: icon,
            });
        }

        var getAllMarkers = function(){
            var bounds = new google.maps.LatLngBounds();
            for(var i=0; i<pos.length; i++){
                bounds.extend(pos[i]);
                createMarker(pos[i], 'https://maps.google.com/mapfiles/ms/icons/red-dot.png');
            }

            $scope.map.fitBounds (bounds);
        }

        getAllMarkers();
        $scope.map.setCenter(pos[0]);
    };

Output from the code: Picture 1

This is the output that I want: Picture 2

A: I suggest to use ngMap or other Angular-module (for example angular-google-map).
Here is an example:

var app = angular.module('myApp', ['ionic', 'ngMap']);

app.controller('MapCtrl', ['$scope', '$http', '$state', 'NgMap', '$timeout',
function($scope, $http, $state, NgMap, $timeout) {

  $scope.zoom = 10;

  $scope.cx = {
    "latitude": 3.050511, "longitude": 101.687833
  };

  $scope.pos = [{"lat": 3.050511,"lng": 101.687833},
  {"lat": 3.122847,"lng": 101.676846},
  {"lat": 3.078409,"lng": 101.608025},
  {"lat": 2.932928,"lng": 101.642603}
  ];

  NgMap.getMap().then(function(map) {
    $scope.map = map;
  });

}])
<!DOCTYPE html>

  <title>Simle Map</title>
  <meta name="description" content="Simple Map" />
  <meta name="keywords" content="ng-map,AngularJS,center" />
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

  <link href="http://code.ionicframework.com/nightly/css/ionic.min.css" rel="stylesheet">

  <ion-header-bar class="bar-dark">

Simple Map in Ionic

  </ion-header-bar>
  <ion-content>

        NgMap

      <ng-map center="{{cx.latitude}}, {{cx.longitude}}" zoom="{{zoom}}" style="width:100%; height: 100%;">
        <marker ng-repeat="p in pos track by $index" position="{{p.lat}}, {{p.lng}}"></marker>
      </ng-map>

cx = {{cx|json}}

pos = {{pos|json}}

  </ion-content>
  <ion-footer-bar class="bar-dark">
    Footer
  </ion-footer-bar>

A: Here is the list of changes that demonstrates how to notify a controller once the map is created.
For directive:
$scope.$emit('onCreate',map);

For controller:
$scope.$on('onCreate', function (event, map) {
     $scope.map = map;
     //the remaining code goes here...
});

Demo on CodePen


text:
Q: find Number of connected components of $Y$? Let $Q,Q^c$ denotes  be the set of all rational and irrational numbers in $\mathbb {R}$. $Y=\mathbb {R^2}\setminus(Q×Q^C )$ with the usual subspace topology of $\mathbb {R^2}$.find  Number of connected components of $Y$?
My answer   :  i thinks  $Y = \mathbb{R} \times \mathbb{R} \cup  \mathbb{R} \times \mathbb{R}$. Since $Y$ is covered by lines in both coordinate directions,  it is path connected. so  $Y$ has one connected component.
is  its correct/incorrect ??
Pliz tell me

A: Notice that
$Y =\mathbb{R}^2\backslash(\mathbb{Q}\times\mathbb{Q}^c) = (\mathbb{R}\times (\mathbb{R}\backslash \mathbb{Q}^c))\cup((\mathbb{R}\backslash \mathbb{Q})\times \mathbb{Q}^c) = (\mathbb{R}\times\mathbb{Q})\cup(\mathbb{Q}^c\times\mathbb{Q}^c).$
So, if $y=(a,b)\in Y$ and $b\in \mathbb{Q}^c$, then $a\in\mathbb{Q}^c$ and $\{y\}$ is the connected component of $y$.
If, $y'= (a,b)\in Y$ and $b\in\mathbb{Q}$, then $a$ can be any real number, so $\{(t,b),\ t\in \mathbb{R}\}$ is the connected componet of $y'$.


text:
Q: Can I get codecs for mpeg-4 , 3gpp and pcm extensions for Chrome Browser ? Now , I currently used  HTML video and audio control. What is codecs for mpeg-4 and 3gpp extension in Chrome Browser ? I tested Firefox , it's work both. But I try in Chrome Browser , it's not work although same codecs. Has some others codecs or content type?
Here is my function:
function DisplayAudio(source, fileName) {

        var audioElm = document.getElementById("audioControl");
        var audioSource = document.getElementById("source");
        audioElm.setAttribute('src', source);

        var n = fileName.indexOf(".");
        var extension = fileName.substring(fileName.length, n + 1);

        if (extension == "3gp") {
            audioSource.type = 'audio/3gpp';
        }
        else if (extension == "3gpp") {
             // testing
            //audioSource.type = 'audio/ogg; codecs="theora, vorbis"';
        }
        else if (extension == "mpeg4") {
             // testing
            //audioSource.type = 'audio/ogg; codecs="theora, vorbis"';
        }
        else if (extension == "pcm") {

        }
}


text:
Q: Using loop to generate String Jmeter I have start of loop and end of loop like int i=0 when initialized and loop should continue until i=99.
With each iteration I need to generate String with value of i like Sk+i.
With each iteration it should generate values like
sk001
sk002
...
sk099

and not only this string this loop should generate it in an specific form like
<register><name>sk001</name>
  <name>sk002</name>
  ...
  <name>sk099</name>
</register>

How can I achieve it in Jmeter?

A: I've done it using BeanShell Sampler
String authString ="<name>" + "${name}" + "</name>";

String temp=vars.get("acc");

vars.put("acc",temp+authString);

where ${name} is the value i get from iterating array of names.
It will concatenate old and new values.


text:
Q: How to authorize the file upload api using ckeditor 4 I am using CKEditor 4 for upload image upload and file upload option in my angular web app, while I am trying to upload a file and getting an Unauthorized error (status 401). How to authorize, please let me know the solution. Thanks in advance
Regards
Santosh M


text:
Q: i have an issue with an "autosuggestbox" on release deployment I am developing a very basic uwp application with Visual Studio 2019 community. I use an autosuggestbox to allow the user to find entries that come up often.
When I deploy the application in debug mode the autosuggestbox works perfectly. If I start to type the beginning of one of the terms of the list then this one appears well in suggestion. On the other hand as soon as I deploy the application in release mode, typing in the autosuggestbox causes the application of the second letter to crash.
There is an exception that appears in release and no errors of any kind in debug.
Suddenly I wonder if there is not a problem / bug with this particular version of Visual Studio.
The exception is (in french sorry about that):

Exception non gérée à 0x00007FFB43F02EC0 (Windows.UI.Xaml.dll) dans
  mesCoursUWP.exe*: 0xC000027B: Une exception interne de l'application
  s'est produite (paramètres*: 0x000002677AA56290, 0x0000000000000003).
  a eu lieu*

In the debug window I have this:

Exception levée*: 'System.IO.FileNotFoundException' dans
  System.Private.CoreLib.dll Exception levée*:
  'System.IO.FileNotFoundException' dans System.Private.CoreLib.dll
  Exception levée*: 'System.IO.FileNotFoundException' dans
  System.Private.CoreLib.dll
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB404801F5) ReturnHr(1) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB4048017A) ReturnHr(2) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB404801F5) ReturnHr(3) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB404801F5) ReturnHr(4) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB404801F5) ReturnHr(5) tid(530) 80070490 Élément
  introuvable. Exception levée*: 'System.IO.FileNotFoundException' dans
  System.Private.CoreLib.dll Exception levée*:
  'System.IO.FileNotFoundException' dans System.Private.CoreLib.dll
  Exception levée*: 'System.IO.FileNotFoundException' dans
  System.Private.CoreLib.dll Exception levée*:
  'System.IO.FileNotFoundException' dans System.Private.CoreLib.dll
  Exception levée*: 'System.IO.FileNotFoundException' dans
  System.Private.CoreLib.dll
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB404801F5) ReturnHr(6) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB4048017A) ReturnHr(7) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB404801F5) ReturnHr(8) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB404801F5) ReturnHr(9) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB4048017A) ReturnHr(10) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB404801F5) ReturnHr(11) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB4048017A) ReturnHr(12) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB404801F5) ReturnHr(13) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB404801F5) ReturnHr(14) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB4048017A) ReturnHr(15) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB404801F5) ReturnHr(16) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB4048017A) ReturnHr(17) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB404801F5) ReturnHr(18) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB4048017A) ReturnHr(19) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB404801F5) ReturnHr(20) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB404801F5) ReturnHr(21) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB4048017A) ReturnHr(22) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB404801F5) ReturnHr(23) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB4048017A) ReturnHr(24) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB404801F5) ReturnHr(25) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB404801F5) ReturnHr(26) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB4048017A) ReturnHr(27) tid(530) 80070490 Élément
  introuvable. Exception levée*: 'System.IO.FileNotFoundException' dans
  System.Private.CoreLib.dll
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB404801F5) ReturnHr(28) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB4048017A) ReturnHr(29) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB404801F5) ReturnHr(30) tid(530) 80070490 Élément
  introuvable.
  onecoreuap\windows\wgi\winrt\display\displaycommon.cpp(411)\Windows.Graphics.dll!00007FFB404804B0:
  (caller: 00007FFB404801F5) ReturnHr(31) tid(530) 80070490 Élément
  introuvable. Exception levée*: 'System.MissingMemberException' dans
  Microsoft.VisualBasic.dll


text:
Q: __vdso_time missing from core utils? I built the latest glibc and now i'm having some trouble with functions in coreutils like ls or cat or anything else like vim.
My error is
-bash-4.0$ cat
cat: error while loading shared libraries: __vdso_time: invalid mode for dlopen(): Invalid argument

and I built, glibc without errors with the following configure
../glibc/configure --prefix=/home/ex/uid377/glibbuilt

On older versions, like 2.14, running the utilities results in a segmentation fault.
-bash-4.0$ ./pwd
./pwd: /lib64/libc.so.6: version `GLIBC_2.14' not found (required by ./pwd)
-bash-4.0$ LD_LIBRARY_PATH=/home/ex/uid377/glibc/lib/:${LD_LIBRARY_PATH}
-bash-4.0$ ./pwd
Segmentation fault (core dumped)

Edit
Kernel Version
-bash-4.0$ uname -r
2.6.32.26-175.fc12.x86_64

A: Having multiple versions of glibc on a single system is possible, but slightly tricky, as explained in this answer. In particular, this:

LD_LIBRARY_PATH=/home/ex/uid377/glibc/lib/:${LD_LIBRARY_PATH}

is expected to crash, because your ld-linux-x86-64.so.2 will not match your libc.so.6

cat: error while loading shared libraries: __vdso_time: invalid mode for dlopen(): ...

It's not clear how you built this cat, but it's most likely the exact same problem: you are picking some libraries from /lib64, and some from /home/ex/uid377/glibc/lib. Don't do that. You must link all the programs that will use /home/ex/uid377/glibc/lib/libc.so.6 with -Wl,--dynamic-linker=/home/ex/uid377/glibc/lib/ld-linux-x86-64.so.2.
You can trace which libraries are currently being loaded by running:
env LD_DEBUG=files,libs ./cat


text:
Q: Apple doesn't guarantee delivery of pushes? Sometimes my script, that sends push notifications crashes with error:

Warning: stream_socket_client() [function.stream-socket-client]: SSL
  operation failed with code 1. OpenSSL Error messages:
  error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake
  failure

And sometimes everything is ok. I think this is not connected with certs or code. Cause I'm sending the same messages to the same devices and use the same algorithm. Any ideas ?

A: Regarding your question in the title - no, there's no guarantee that notifications will arrive.


text:
Q: Django template tag IF not returning what is expected I have the following in my template
{% for excursion in excursions %}
    {{ excursion.pk }}-{{ formset.excursion.value }},
        <input type="radio" id="id_excursion_{{ excursion.pk }}" name="excursion" value="{{ excursion.pk }}"{% if formset.excursion.value ==  excursion.pk %} checked="checked"{% endif %} />
        <label for="id_excursion">{{ excursion.name }}</label>
        {{ excursion.short|safe|linebreaksbr }}
    </div>
{% endfor %}

template print: 1-1,1-3,

formset.excursion.value is 1
excursion.pk = 1 and 3 (2 objects)

My view:
def edit(request, uuid):
    confirm = None
    instance = get_object_or_404(Foo, uuid=uuid)
    formset = FooForm(instance=instance)
    excursions = Excursion.objects.filter(is_activity=False)

    context = {
        'excursions':excursions,
        'formset':formset,
    }

    if request.method == "POST":
        formset = FooForm(request.POST, request.FILES, instance=instance)
        if formset.is_valid():
            form = formset.save()
            confirm = 'true'

            context =  {
                'excursions':excursions,
                'formset':formset,
                'confirm_create':confirm
            }

    return render(request, "edit.html", context)

This works as its supposed to when I navigate to this page, BUT when I submit the form, and render the page again after the submit, it does not return TRUE again, even though the values are still there, the same as before?
I thought perhaps is is because the one value is a string and the other an int? But this does not seem to make a difference when putting the values in quotes
I even tried the ifequal tag but it does the same


text:
Q: Where is the filesystem that "Root Storage Daemons" run on? What does it look like? https://www.freedesktop.org/wiki/Software/systemd/RootStorageDaemons/

...these storage daemons are started from the initramfs, stay running all the time during normal operation and are terminated only after we returned control back to the initramfs and by the initramfs. As such, storage daemons involved with maintaining the root file system storage conceptually are more like kernel threads than like normal system services: from the perspective of the init system (i.e. systemd) these services have been started before systemd got initialized and stay around until after systemd is already gone.

But, isn't the initramfs unmounted once systemd starts?  I can't see the initramfs mounted anywhere on my Fedora 28 system.[*]
Where is the filesystem that "Root Storage Daemons" run from?
And what does it look like from their point of view?  For example, can they access a fully-featured /dev during runtime?

[*]  There is a directory /run/initramfs, but it is not a separate ram filesystem (tmpfs mount).  It is empty except for a couple of directories with no files, and one file rwtab which lists the directory names.
$ findmnt -T /run/initramfs
TARGET SOURCE FSTYPE OPTIONS
/run   tmpfs  tmpfs  rw,nosuid,nodev,seclabel,mode=755
$ find /run/initramfs -type d
/run/initramfs
/run/initramfs/state
/run/initramfs/state/var
/run/initramfs/state/var/lib
/run/initramfs/state/var/lib/dhclient
/run/initramfs/state/etc
/run/initramfs/state/etc/sysconfig
/run/initramfs/state/etc/sysconfig/network-scripts
/run/initramfs/log
$ find /run/initramfs -not -type d
/run/initramfs/rwtab
/run/initramfs/.need_shutdown
$ cat /run/initramfs/rwtab
files /etc/sysconfig/network-scripts
files /var/lib/dhclient
$ cat /run/initramfs/.need_shutdown
$

A:
But, isn't the initramfs unmounted once systemd starts?

No.  The initramfs filesystem actually can't be unmounted.

At least if the initramfs is implemented using systemd, it does calls umount(), but it passes the flag MNT_DETACH.  See also umount -l.
(This mode of umount() is not prevented when there are open files.  It only "detaches" the initramfs filesystem from its mount point, removing it from the mount table (/proc/mounts etc).  Any open files can continue to be used.  Once all open files are closed, then the kernel will finish unmounting the filesystem).

Where is the filesystem that "Root Storage Daemons" run from? And what does it look like from their point of view?

The spirit of "RootStorageDaemons" says that they continue running inside the detached initramfs.
In addition to detaching the mount, MNT_DETACH detaches any child mounts.  So Root Storage Daemons would not see critical API filesystems including /dev and /proc mounts.  This is pretty brutal:
# unshare -m
\# umount -l /
\# findmnt
findmnt: can't read /proc/mounts: No such file or directory
\# ls /dev
\#

After using MNT_DETACH, systemd in the initramfs continues to match the more traditional switch_root command, by deleting unlink()ing every file from the initramfs.  (The systemd function is called rm_rf_children() - it effectively does rm -rf *.  As usual, any open files - including the executable and library files of running daemons - will keep working.  When the last reference to the file is closed, their storage will be freed by the kernel).
If true this would be quite interesting; it would be a nice protection against a bug in a RootStorageDaemon which opened a file on the root filesystem.  It could also be a partial protection against making RPC calls through sockets in /run, and becoming dependent on daemons running from the root filesystem.  Doing either of these things would be liable to cause a deadlock (circular dependency).

However in fact, if you look at /proc/$PID/root of a Root Storage Daemon, it will most likely point to the main root filesystem, not the initramfs.  So why would this happen, and how does the system work in face of this?
It happens because the initramfs uses pivot_root() to switch to the root filesystem.  As well as modifying the mount table, pivot_root() currently scans the root and current working directory (/proc/$PID/root and /proc/$PID/cwd) of all processes.  If either of these match the root directory of the old root filesystem (initramfs), they are replaced with the new one.  This is documented as an implementation detail of pivot_root(), which programs are not supposed to rely on.
<del>The system works because pivot_root() is also how systemd is able to switch back to an initramfs.  So the references to the root filesystem are replaced again, with references to the shiny new initramfs. </del>

(It is also likely that the /run tmpfs in the shiny new initramfs, is passed down from /run on the root filesystem.  Which in turn was passed down from the initramfs.  In this case, I think it would allow the shutdown initramfs to communicate with the RootStorageDaemon, if the daemon opened a socket in /run as part of its startup sequence.)


text:
Q: How to add setTimeout function for the Foreach loop Hi want to set the timeout funtion for the Freach loop for the callback i am setting the timeout funtion. but its displaying Undifined error. can anybody Explain me here is My code.

function async(array,cb){

    array.forEach(function () {
        setTimeout(cb,0);

    })

}

async([1,2,3,4],function(i){
    console.log(i);
});

A: Try:

function async(array,cb){
    array.forEach(function(e) {
        setTimeout(function() { cb(e); },0);

    });
}

async([1,2,3,4,5], function(i) {
  console.log(i);
});


text:
Q: Custom Event Not Firing in Google Tag Manager I am trying to fire a custom event in Google Tag Manager for a Virtual Page View. I want to be able to track a conversion in a dynamic shopping cart page where the actual URL does not change.
I added the following code for a dataLayer and set it up to fire when the event= VirtualPageView but it's not working.
Any ideas?
dataLayer.push({
  'event':'VirtualPageView',
  'virtualPageURL':'/thankyou',
  'virtualPageTitle':'Thank You'
  'conversionValue':'value'
  'currencyCode':'currency'
});

Google Tag Setup
Custom Event Setup

A: Looking at your code I see a lot of missing commas after everything but the second line. This will cause the JS to fail which means no event is pushed into the dataLayer which means GTM won't see anything happening and therefore not fire any tags.
I.e. add a comma after 'virtualPageTitle':'Thank You and after 'conversionValue':'value'. Keep in mind that if you actually pass 'value' as a string and an AdWords Conversion Tag looks for a float, it will fail that tag.
GTM is fairly finicky and will just stop execution when JS code related to it fails.


text:
Q: Characteristic Equation of A Closed Loop System in Terms of PI Controller Just wondering if you could guide me on how to find the characteristic equation of a trasfer function G(s) (see below for G(s)) in terms of the coefficients in the PI controller?
G(s) = 45/(5s + 2)
No sure what to do here, as I'm used to just multiplying the error by the proportional gain - but there's no error value provided.
Any advice would be much appreciated. Thanks in advance ;)

A: Given:
G(s) = 45/(5s + 2) (plant transfer function)
C(s) = Kp + Ki/s (PI Controller transfer function)

and assuming your system looks like:
https://www.dropbox.com/s/wtt4tvujn6tpepv/block_diag.JPG
The equation of the closed loop transfer function is:
Gcl(s) =  C(s)G(s)/(1+C(s)G(s)) = CG/(1+CG)

In general, If you had another transfer function on the feedback path, H(s),
the the closed loop transfer function becomes:
CG / (1 + CGH)

If you plug in G(s) and C(s) as shown above you will get the following closed loop transfer function after some algebraic simplification:
45*[Kp*s + Ki] / [5*s*s + (2 + 45*Kp)*s + 45*Ki]

and so the characteristic equation is
5*s*s + (2 + 45*Kp)*s + 45*Ki = 0

Notice how the integral term adds a pole to the system but has a side effect of also adding a zero which could produce unwanted transient behaviour if Kp is not chosen correctly. The presence of Kp in the s term in the denominator shows that the value of Kp will determine the damping ratio of the system and therefore determine the transient response.
More information on poles, zeros, and system dynamics:
http://web.mit.edu/2.14/www/Handouts/PoleZero.pdf


text:
Q: breakpoint in ISR is it legal/possible to set a breakpoint inside an ISR? Or this is rather hardware specific?

A: Yes, it is perfectly legal, but there may be some hiccups due to other ISR's not being fired in time, eg USB.


text:
Q: Windows Socket Programming: MFC CSocket vs Win32 socket I am trying to understand how these 2 types of socket implementations vary? Is the CSocket class from MFC library is a mere wrapper around the WinSock/WinSock2 Win32 APIs or there is something more than that meets the eyes.
Also which is recommended to be used in case of MFC applications and in case of non-MFC applications?


text:
Q: C# Entity Framework XUnit Tests Always Failing I'm currently trying to setup some tests to check that my code is working. I've managed to set it up with the .NET 6 minimal API and use a test db context instead, however, when I have multiple tests all the tests are failing.
I believe the reason for this is because they are running parallel which is obviously causing a conflict with the database context.
To counteract this, I've tried an in memory database and create a new database based on a guid which is resolved before the test, however, I've read that in memory databases aren't the best for testing as it's not a true reflection. So I've opted to use a test SQL Server. Which I plan on tearing down after each test - I know this may take a lot longer than usual but I'm happy to take that given it's an accurate reflection of the code interacting with the database.
However, for that I think I need to run the tests individually rather than in parallel.
My test is really simple, it just tests a 200 and a count. Running them individually works perfectly.
public class GetUserEndpointTest()
{
  [Fact]
  public async Task OnSuccess_ReturnStatusCodeOk()
  {
    await using var application = new Application();
    var client = application.CreateClient();

    var response = await client.GetAsync("/v1/users");
    response.EnsureSuccessStatusCode();
  }

  [Fact]
  public async Task OnSuccess_ReturnsTheCorrectUserCount()
  {
    await using var application = new Application();
    var client = application.CreateClient();

    var users = await client.GetFromJsonAsync<List<User>>("/v1/users");
    users.Count.Shound().Be(1);
  }
}

My application factory is just simple:
class Application : WebApplicationFactory<Program>
{
  protected override IHost CreateHost(IHostBuilder builder)
  {
    builder.ConfigureServices(services =>
    {
      services.RemoveAll(typeof(DbContextOptions<ApplicationContext>));
      services.AddDbContext<ApplicationContext>(options =>
        {
          options.UseSqlServer(
            "Server=localhost;Database=testing_database;Trusted_Connection=True;"
          );
        });
     });

     return base.CreateHost(builder);
  }
}

A: When testing with XUnit, you can prevent parallel execution of the tests by putting them in a "collection". You declare which tests belong to the collection by "decorating" the class declaration with a Collection attribute.
This is explained at https://xunit.net/docs/running-tests-in-parallel
For example:
    [Collection("NonParallelTestCollection")]
    public class MyUnitTests1
    {
    // your tests here ...
    }

    [Collection("NonParallelTestCollection")]
    public class MyUnitTests2
    {
    // your tests here ...
    }

In this example, none of the tests in either of the classes will run in parallel.