text:
Q: Error while injecting Firebase as a Service in Component. What can be the issue? I am having problem in fetching data from the firebase service. I have a method called getListing. This is my service class:
import { Injectable } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';

@Injectable()
export class FirebaseService {

  listings: FirebaseListObservable<any[]>;

  constructor(private af: AngularFireDatabase) {}

  getListings(){
    console.log('In getListings');
    this.listings = this.af.list('/listings') as FirebaseListObservable<Listing[]>;
    return this.listings;
  }

}

interface Listing{
  $key?:string;
  title?:string;
  type?:string;
  image?:string;
  city?:string;
  owner?:string;
  bedrooms?:string;
}

This is the component where I am Injecting the service:
import { Component, OnInit } from '@angular/core';
import { FirebaseService } from '../../services/firebase.service';

@Component({
  selector: 'app-listings',
  templateUrl: './listings.component.html',
  styleUrls: ['./listings.component.css']
})
export class ListingsComponent implements OnInit {
  listings:any;

  constructor(private firebaseService:FirebaseService) { }

  ngOnInit() {
    this.firebaseService.getListings().subscribe(listings => {
      console.log(listings);
      this.listings = listings;
    });
  }

}

I am able to login using Google authentication and then when I try to call the getListing method in Service, I don't get a list of data. I am logging the list in the Console. The console log doesn't have any data. What could be the issue? I am injecting the service in the constructor of the Component and I have imported the Service from the services folder.
Any advice would be helpful.


text:
Q: Tensor Product Notation third order I'm trying to figure out how to carry a tensorial operation. I am not sure if I implemented correctly, as the results I get are not what I was expecting. I found these two representations in different documents:
A:
$\mathbf{H}=(\mathbf{\epsilon}\cdot \mathbf{ z})\mathbf{ z} $
$\mathbf{h}=\mathbf{H}: \mathbf{\dot\gamma}  $
B:
$\mathbf{h}=\mathbf{\epsilon}_{ijl} \mathbf{ z}_l\mathbf{ z}_k \mathbf{\dot\gamma}_{jk}  $
Where $\epsilon$ is the third order permutation tensor, $\mathbf z$ and $\mathbf h$ are vectors and $\dot \gamma $ and $\mathbf H $ second order tensors. I implemented B as:
$ \mathbf{h}_{i} = \sum_j \sum _l \sum _k \mathbf{\epsilon}_{ijl} \mathbf{ z}_l\mathbf{ z}_k \mathbf{\dot\gamma}_{jk}  $
A does not make much sense to me, because the dot product within the brackets would yield a second order tensor, and I dont know how you can get a second order tensor from a second order tensor and a vector. Furthermore, the double inner product between two order tensors should yield an scalar and not a vector. Am I correct?
If you are wondering, the context is fluid mechanics, particularly to find the hydrodynamic torque on an elongated particle, it is the contribution to the torque from the rate of strain ($\dot \gamma$) which tries to align the particle along its principal direction. $\mathbf{z}$ is the normalized particle orientation. I see it as the projection of the dyadic product of the orientation vector to the rate of strain tensor.
Thanks!

A: Regarding the notation:

.... am I correct?

No.
$(\epsilon\cdot \mathbf{z})$ is as you said, a second order tensor. But then
$(\epsilon\cdot\mathbf{z})\mathbf{z}$ is a third order tensor: you are taking the tensor product between a second order one with a first order one (a vector) and so end up with a third order one (2+1 = 3). In particular, the assertion that $\mathbf{H}$ is a second order tensor is wrong.
Then you can take $\mathbf{H}:\dot{\gamma}$, where the $:$ operation means inner product on two indices, and finally get a vector as desired.

redpajama_set_name: RedPajamaStackExchange


text:
Q: XSL for XML to Excel: Using a Curly Bracket in Formula How do I use curly brackets in an XSL which generates an Excel file from an XML?
I can accomplish what I want with an Excel formula, but it needs to use curly brackets list like:
    =LOOKUP(XXXX, {"NA","NF","NR","O"},{"NA","Completed","NR","Ongoing"}

Which I can not get the XSL to accept even when using the HTML indicators for the brackets and commas, I still get an error on the first comma after the first curly bracket.
    =LOOKUP(XXXX,{"NA","NF","NR","O"},{"NA","Completed","NR","OngoingNA"})

&123; = {
&#$$; = , (comma)

But I get an XML Error on the first command saying: "Expected token '{' found ','.
    =LOOKUP(XXXX,{"NA"-->,<--"NF,"NR","O"},{"NA","Completed","NR","Ongoing","NA"})

A: I am guessing (!) you are trying to create a literal result element with an attribute containing curly braces. This is problematic, because the curly braces are interpreted as an attribute value template - i.e. the XSLT processor tries to evaluate the expression contained within.
To avoid this, you must either escape the curly braces by doubling them, or use the xsl:attribute instruction to specify the value as text. For example, both:
<elem attr="=SUM({{1,2}}*{{4,5}})"/>

and:
<elem>
    <xsl:attribute name="attr">=SUM({1,2}*{4,5})</xsl:attribute>
</elem>

will return the same result:
<elem attr="=SUM({1,2}*{4,5})"/>


text:
Q: Скачать файл с сервера Отправляю запрос на сервер и получаю в ответ объект:

И я пытаюсь сохранить этот файл таким способом
let FileSaver = require('file-saver');
let file = new File([res.body.uri], "hello world.js");
 FileSaver.saveAs(file);

И собственно файл сохраняется, но при открытии файла, его содержимое выглядет точно так же как res.body.uri - то есть
uri:"data:application/javascript;base64,alF1ZXJ5KGRvY3VtZW50KS5yZWFkeShmdW5jdGlvbigkKSB7CiAgICAkKCcucG

Что мне нужно сделать что бы файл сохранялся корректно? (я не знаю в каком расширении лижит файл на сервере)

A: *

*Получим из строки данные для конвертации.
[res.body.uri].split(",")[1];

*Используем функцию для конвертации в UTF-8
function b64DecodeUnicode(str) {
    return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
    }).join(''));
}

*Сохраняем полученные данные
let FileSaver = require('file-saver');
let file = new File(decode_data, "hello world.js");
FileSaver.saveAs(file);


text:
Q: How do I generate a random number within a non-contiguous range using Ruby? For example suppose I have the following ranges
5031..5032  6248..6249
How do I generate a random number within these two ranges?

A: The simple way:
(r1.to_a + r2.to_a).choice

A faster and much more memory-efficient general solution would involve computing the total range size, generating a random number, and then normalizing the number to the range that it falls in.
Update: Ok, got it. This solution works with an arbitrary number of Ranges and does not generate giant arrays or iterate through the Ranges themselves. (It iterates twice over an array of Ranges, not arrays of Range elements.)
def rangerand *r
  r.inject(rand(
      r.inject(0) do |accum, rng|
        accum + rng.last - rng.first + 1
      end
    )) do |accum, rng|
      rngsize = rng.last - rng.first + 1
      return rng.first + accum if accum < rngsize
      accum - rngsize
    end
  # raise 'this "cannot happen"'
end

puts rangerand 1..3, 999..1001, 10_200..10_205

Heh, I've never used two #injects in the same expression before.

A: For arbitrary number of ranges

*

*Count number of possible values as total.

*Generate random number rnd between 0 and total - 1.

*Iterate through list of ranges, subtracting range size from rnd until possible (until rnd is non-negative).

*When can't subtract more, just get rnd-th number in the current range.

A: I wrote this code and looking now at Nikita's answer I think it's more or less his idea (I use r.end/r.begin because Ruby ranges have no pre-calculated length attribute)
ranges = [1..10, 21..40, 81..120]

counts = ranges.map { |r| r.end - r.begin + (r.exclude_end? ? 0 : 1) }
random = rand(counts.inject(&:+))
idx, remainder = counts.inject([0, random]) do |(idx, remainder), count|
  if remainder < count
    [idx, remainder] # break here if you care more for efficiency than for functional purity
  else
    [idx+1, remainder - count]
  end
end
p ranges[idx].begin + remainder

Of course if I had ranges of reasonable length, I'd simply use the other solutions already discussed.

A: Add the ranges to an array and flatten it to get a series of numbers, then call rand to find a particular element of this array.
range_1 = 1..10
range_2 = 2..30

range_array = [range_1.to_a, range_2.to_a].flatten
range_array[rand(range_array.length)]

A: This is what I came up with:
require 'benchmark'

class RangeRandom
  def initialize(ranges=[])

    # sanity checks need to go here for things like:
    #   backward/inverted ranges: (0..-1)
    #   range overlaps: (0..2 & 1..3)
    #     could combine ranges, or raise an exception
    #
    # Restrict to ranges that pass ".inclusive?"?

    # the end value is informative only
    @prepped_ranges = ranges.map{ |r| [ r.begin, r.end - r.begin, r.end ] }
  end

  def rand
    range = @prepped_ranges[ Kernel::rand( @prepped_ranges.size ) ]
    range[0] + Kernel::rand( range[1] )
  end
end

Some tests:
range_random = RangeRandom.new([0..10, 90..100])
5.times do
  puts range_random.rand
end
puts

# >> 94
# >> 97
# >> 92
# >> 92
# >> 8

n = 500_000
Benchmark.bm(7) do |x|
  x.report('rand1:') { n.times do ; r = RangeRandom.new([ 0..1             ]); r.rand; end }
  x.report('rand2:') { n.times do ; r = RangeRandom.new([ 0..1_000_000     ]); r.rand; end }
  x.report('rand3:') { n.times do ; r = RangeRandom.new([ 0..1_000_000_000 ]); r.rand; end }

  x.report('rand4:') { n.times do ; r = RangeRandom.new([ 0..1 ]); r.rand; end }
  x.report('rand5:') { n.times do ; r = RangeRandom.new([ 0..1, 2..3, 4..5, 6..7 ]); r.rand; end }

  x.report('rand6:') { r = RangeRandom.new([ 0..1             ]) ; n.times do ; r.rand; end }
  x.report('rand7:') { r = RangeRandom.new([ 0..1_000_000_000 ]) ; n.times do ; r.rand; end }
end

Overall run times for 500,000 iterations:
# >>              user     system      total        real
# >> rand1:   2.220000   0.000000   2.220000 (  2.224894)
# >> rand2:   2.250000   0.010000   2.260000 (  2.254730)
# >> rand3:   2.250000   0.000000   2.250000 (  2.247406)

Times for initializing multiple ranges for 500,000 iterations:
# >> rand4:   2.220000   0.000000   2.220000 (  2.222983)
# >> rand5:   4.340000   0.000000   4.340000 (  4.337312)

Times for a single initialization, then a small range vs. big range for 500,000 iterations:
# >> rand6:   0.560000   0.000000   0.560000 (  0.559673)
# >> rand7:   0.580000   0.000000   0.580000 (  0.584331)

Times increase a little when using big ranges but that might be variations due to system activity. Initializing multiple ranges in the array has a greater effect which is what I expected.

A: For wide ranges range.to_a is not a very good solution. You can create unnecessarily many big arrays. Fastest solution can look like this:
ruby-1.9.2-head > from, to = 1, 50000000
 => [1, 50000000]
ruby-1.9.2-head > from + rand(to-from+1)
 => 20698596
ruby-1.9.2-head > from + rand(to-from+1)
 => 15143263
ruby-1.9.2-head > from + rand(to-from+1)
 => 18469491

Similar solution for Ranges is however almost as slow as range.to_a:
ruby-1.9.2-head > range1 = 1..5000000
 => 50..50000
ruby-1.9.2-head > range1.begin + rand(range1.count)   # TAKES ABOUT 1 SECOND!
 => 1788170


text:
Q: Integer solutions of $n^k+(n+1)^k+\cdots+(n+m)^k=(n+m+1)^k$ So we all know already that next identities follow:
$3^2+4^2=5^2$
$3^3+4^3+5^3=6^3$
So it raises my question:
For $(*)n^k+(n+1)^k+...+(n+m)^k=(n+m+1)^k$ are there infinite triples (n,m,k) s.t (*) is satisifed?
Any literature on this question or more general question from this follows?
Thanks.

A: I do not have a definite answer, but in view of the discusion, and since it connects, as requested, the question to problems investigated in the literature, some remarks.
I claim that:

If an answer to this question is known, then it is of the form that there are infinitely many solutions.

This might seem like a strange claim, and I do not claim that the number of solutions is infinite, but here is the reason:
Erdős and Moser (in the 50s) conjectured that the equation
$$ 1^k + \dots  + m^k = (m+1)^k $$
has only the solution $1+2=3$.
Over the decades it was investigated quite a bit, still it is unknown whether the number of solutions to this equation (the special case $ n= 1 $ of the questioner's equation) is even finite.
So, even fixing $ n = 1 $ in the equation of the questioner one does not know how to prove that the number of solutions is finite.
Thus, the only way an answer to this question can be known, is the one I mentioned,
otherwise (and likely) this is an open problem.
I already mentioned the names Erdős and Moser; searching for 'Erdős--Moser type equation' will yield various investigations on this and related problems.
More specifically, the book 'Unsolved Problems in Number Theory' by Guy, already mentioned by Gerry Meyerson, contains a section on it (namely D7), you might be able to see it on Google books, with various references, in particular to computational work excluding solutions for $ m $ up to $ 10^{10^6} $ and even beyond that.
For more recent work on variants of this problem, see for example, a preprint by MacMillan and Sondow or a paper by Lengyel (scroll to A41).

A: I'm quite unhappy with the answers I gave until now ; let me try to do better.
The first case you mention ($k=2$ and $m=1$) falls inside the theory of pythagorean triples ; that is the integer solutions to $x^2+y^2=z^2$. Some trivial calculations show that the only pythagorean triple which has the more specific form you ask for is the one you gave, with the relation $3^2+4^2=5^2$.
Then, the more general case you mention falls inside the search of integer solutions to an equation of the form $x_1^k+\dots+x_m^k=y^k$, where $k$ is fixed, so the equation is polynomial. It is for this general type of problem that I was mentioning that Faltings' theorem applies : if the geometric curve is too complex, then there will be only a finite number of solutions. And hence, only a finite number of solutions of the prescribed form.
I tried a few more calculations : for $m\geq2$ and $k=2$, I first saw that $n$ could only be $0$ or $1$ ; then using $\sum_{l=0}^Nl^2=\frac{N(N+1)(2N+1)}6$, I ruled out all possibilities.
For the other cases, I didn't find anything useful.

A: Can you find any other solutions aside from $1^1+2^1=3^1$ and $n^0=(n+1)^0$?  There certainly aren't any others with $k<100.$
You want $f(x,k,m)=x^k+(x+1)^k+...+(x+m)^k-(x+m+1)^k=0$ with $x$ a positive integer.  Let $x_{m,k}$ be the positive real root (if any). Convince yourself that, for $k \gt 2$, $2k-1 \lt x_{2,k} \lt 2k$. Next convince yourself that for fixed $m$, $x_{m,k}$ is a decreasing function of $k$ and that $x_{m,k} \lt 1$ if $m \gt \frac{3k}{2}$. This allows a quick search and the claim above.

A: "Introduction to elliptic curves and modular forms" by Neal Koblitz discusses at length the pythagorean triples (your first example)
More generally, your question falls in the arithmetic geometry realm, and there is a wealth of references. Let me just mention "Arithmetic of elliptic curves" by Joseph Silverman.

A: The question seems much harder than the pythagorean triples problem...
Now observe that:
$$n^k+(n+1)^k+...+(n+m)^k=1^k+2^k+...+(n+m)^k-(1^k+2^k+...+(n-1)^k)$$
So you can actually get an expression of this (using Bernoulli numbers). When $k$ and $n$ are fixed, it is polynomial in $m$ of degree $k+1$ so it equal to $(n+m+1)^k$ only for a finite number of $m$...
You could swap $m$ and $n$...

A: For the more general question, I think : Falting's theorem is what you want to know.


text:
Q: Clion / Cmake can't find boost on linux I recently changed to Linux Mint Debian Edition and cannot include boost to Clion using cmake. Yesterday I tried every option I could find, including on stackoverflow, but nothing has worked yet.
Boost has been installed using: sudo apt -y install libboost-filesystem-dev
This is a version I found in this thread: How to include external library (boost) into CLion C++ project with CMake?
which supposedly worked, but it didn't.
cmake_minimum_required(VERSION 3.22)
project(boost_project)

set(CMAKE_CXX_STANDARD 14)

find_package(Boost COMPONENTS system filesystem REQUIRED)

if(Boost_FOUND)

    message(STATUS "Boost_INCLUDE_DIRS: ${Boost_INCLUDE_DIRS}")
    message(STATUS "Boost_LIBRARIES: ${Boost_LIBRARIES}")
    message(STATUS "Boost_VERSION: ${Boost_VERSION}")

    include_directories(${Boost_INCLUDE_DIRS})

endif()

add_executable(boost_project main.cpp)

if(Boost_FOUND)

    target_link_libraries(boost_project ${Boost_LIBRARIES})

endif()

The Cmake output message is:
CMake Error at /app/extra/clion/bin/cmake/linux/share/cmake-3.22/Modules/FindPackageHandleStandardArgs.cmake:230 (message):
Could NOT find Boost (missing: Boost_INCLUDE_DIR system filesystem)
I've gone through dozens of threads but so far nothing has worked. Has anyone suggestions of what's wrong?

EDIT:
So I've de-installed Clion and re-installed it with snap, since I read in another thread that it was an issue with installing Clion through the software center. Now I can include boost with no problem, but building it reveals the compiler still doesn't like using it.
#include <iostream>
#include "boost/asio.hpp"
boost::asio::io_service io_s;
int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

: && /usr/bin/c++ -g  CMakeFiles/BoostTest.dir/main.cpp.o -o BoostTest   && :
/usr/bin/ld: CMakeFiles/BoostTest.dir/main.cpp.o: in function boost::asio::detail::posix_event::posix_event()': /usr/include/boost/asio/detail/impl/posix_event.ipp:42: undefined reference to pthread_condattr_setclock'
/usr/bin/ld: CMakeFiles/BoostTest.dir/main.cpp.o: in function boost::asio::detail::posix_thread::~posix_thread()': /usr/include/boost/asio/detail/impl/posix_thread.ipp:35: undefined reference to pthread_detach'
/usr/bin/ld: CMakeFiles/BoostTest.dir/main.cpp.o: in function boost::asio::detail::posix_thread::join()': /usr/include/boost/asio/detail/impl/posix_thread.ipp:42: undefined reference to pthread_join'
/usr/bin/ld: CMakeFiles/BoostTest.dir/main.cpp.o: in function boost::asio::detail::posix_thread::start_thread(boost::asio::detail::posix_thread::func_base*)': /usr/include/boost/asio/detail/impl/posix_thread.ipp:59: undefined reference to pthread_create'
/usr/bin/ld: CMakeFiles/BoostTest.dir/main.cpp.o: in function boost::asio::detail::posix_signal_blocker::posix_signal_blocker()': /usr/include/boost/asio/detail/posix_signal_blocker.hpp:43: undefined reference to pthread_sigmask'
/usr/bin/ld: CMakeFiles/BoostTest.dir/main.cpp.o: in function boost::asio::detail::posix_signal_blocker::~posix_signal_blocker()': /usr/include/boost/asio/detail/posix_signal_blocker.hpp:50: undefined reference to pthread_sigmask'
collect2: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.

A: The solution to the first problem, cmake not finding boost, had nothing to do with cmake but Clion. Installing Clion with flatpak can apparently cause this error. To fix it I just needed to de-install Clion and re-install it with snap.
The second issue was cmake not finding several thread related includes. For that cmake needed
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread")

to be added. I found this solution in these threads:
linking errors for boost for visual studio linux project
Undefined reference to pthread_create in Linux
The complete and working cmake looks like this now:
cmake_minimum_required(VERSION 3.22)
project(boost_project)

message(STATUS "start running cmake...")

find_package(Boost COMPONENTS system)

if(Boost_FOUND)

    message(STATUS "Boost_INCLUDE_DIRS: ${Boost_INCLUDE_DIRS}")
    message(STATUS "Boost_LIBRARIES: ${Boost_LIBRARIES}")
    message(STATUS "Boost_VERSION: ${Boost_VERSION}")

    set(CMAKE_CXX_STANDARD 14)
    add_executable(boost_project main.cpp)

    include_directories(${Boost_INCLUDE_DIR})
    link_directories(${Boost_LIBRARY_DIR})

    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread")

endif()

target_link_libraries(boost_project ${Boost_LIBRARIES})


text:
Q: Как сделать галерею карточек в виде карусели Пользователь создает карточки. Как можно реализовать идею, чтобы сформировывалась галерея карточек в виде карусели, чтобы пользователь мог листать их. На данном этапе карточки располагаются по горизонтали по 3 штуки, а дальше смещаются вниз.

html код
{% block contant %}
    {% if tasks %}

        {% for el in tasks %}

{{ el.title }}

{{ el.task }}

        {% endfor %}

    {% else %}

У Вас нет карточек

    {% endif %}
{% endblock %}

css
*{
    margin: 0;
    padding: 0;
    text-decoration: none;
    font-family: "montserrat";
  }

body{
  background-image: url(https://sun9-2.userapi.com/impg/q-Eqf80s58QRuG_JYJB_pwySsSIvLInCD1SkRg/aj1e0-Vo6b0.jpg?size=1600x890&quality=95&sign=cfd9c0cdeb175a5666f8035229cac400&type=album);
  background-size: cover;
  /* background-position: center center;
  background-attachment: fixed; */
}

.middle{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
.card{
  display: inline-block;
  margin-right: 40px;
  /* float: left; */
  cursor: pointer;
  width: 340px;
  height: 480px;
  margin-top: 15%;
}
.front,.back{
  width: 100%;
  height: 100%;
  overflow: hidden;
  backface-visibility: hidden;
  position: absolute;
  transition: transform .6s linear;
  padding: 5rem 2.5rem;

}
.front{
  border-radius: 5%;
  background: #f1f1f1;
  transform: perspective(600px) rotateY(0deg);
}
.back{
  border-radius: 5%;
  background: #f1f1f1;
  transform: perspective(600px) rotateY(180deg);
}

.front-content{
  color: #2c3e50;
  text-align: center;
  width: 100%;
}

.back-content{
  color: #2c3e50;
  text-align: center;
  width: 100%;
}

.card{
  background-color: rgba(189, 189, 189, 0);
  background-clip: border-box;
  border: none;
  border-radius: 5%;
}

.card:hover > .front{
  transform: perspective(600px) rotateY(-180deg);
}
.card:hover > .back{
  transform: perspective(600px) rotateY(0deg);
}


text:
Q: Nlog Posting to a CosmosDB Target I'm using Nlog and trying to make it post to a CosmosDB(DocumentDB) target
using https://www.nuget.org/packages/Nlog.DocumentDBTarget/
my configuration code looks like this
  var documentDBTarget = new DocumentDBTarget()
        {
            Name = "logDocument",
            EndPoint = "https://[my endpoint].documents.azure.com:443/",
            AuthorizationKey = "[my auth key]",
            Collection = "[my collection]",
            Database = "[my database]",
            Layout=jsonLayout
        };
        config.AddTarget(documentDBTarget);
        config.AddRuleForAllLevels(documentDBTarget);

I have declared jsonLayout and then I configure the logger and use it to start logging. this was working fine when I was logging to a local file target or a console target but it's not working with cosmosDB
LogManager.Configuration =config;
Logger logger = LogManager.GetLogger("Example");
logger.Info("{object}");

what am I missing? the documentation for https://github.com/goto10hq/NLog.DocumentDB?files=1
I didn't find any information about posting using Nlog I only found info about configuring it which I believe I did correctly
Thank you

A: Works on my computer. Is the object that you are trying to log consistent with the JSON layout?
var jsonLayout = new JsonLayout()
        {
            Attributes =
                {
                    new JsonAttribute("name", "${name}"),
                    new JsonAttribute("level", "${level}"),
                    new JsonAttribute("message", "${message}"),
                }
        };
…

logger.Info(new
        {
            Name = "SomeName",
            Level = "SomeLevel",
            Message = "HelloWorld"
        });


text:
Q: Using PCA for detecting similar regions in an image I'm trying to understand an algorithm that detects similar regions of an image using PCA. The algorithm essentially divides the image into overlapping square blocks and then does PCA with each block as a dimension. Next it does a lexicographical sort of the principal components to arrange similar blocks close to one another. Finally similar regions are selected based on distance in the list and a few other measurements.
The PCA part of the algorithm is described as follows:

An image is tiled with overlapping blocks of $b$ pixles ($\sqrt{b} \times \sqrt{b}$ pixels in size), each of which is assumed to be considerably smaller than the size of the duplicated regions to be detected. Let $ \vec x_i,i=1,...,N_b,$ denote these blocks in vectorized form, where $N_b=\left(\sqrt{N}-\sqrt{b}+1 \right)^2$. We now consider an alternate representation of these blocks based on a principal component analysis (PCA)[15]. Assume that the blocks $\vec x_i$ are zero-mean, and the compute the covarience matrix as:
  \begin{equation*}
\tag{1.1}
C = \sum_{i=1}^{N_b} \vec x_i \vec x_i^T
\end{equation*}
  The orthonormal eigenvectors,$\vec e_j$,of the matrix $C$, with corresponding eigenvalues,$\lambda_j$, satisfying:
  \begin{equation*}
\tag{1.2}
C \vec e_j = \lambda_j \vec e_j,
\end{equation*}
  define the principal components, where $j=1,\dots,b$ and $ \lambda_1 \geq \lambda_2 \geq \cdots \geq \lambda_b$. The eigenvectors, $\vec e_j$, form a new linear basis for each image block,$\vec x_i$:
  \begin{equation*}
\tag{1.3}
\vec x_i = \sum_{j=1}^b a_j \vec e_j,
\end{equation*}
  where $a_j = \vec x_i^T \vec e_j$, and $\vec a_i = \left(a_i \dots a_b \right)$ is the new representation for each image block.
The dimensionality of this representation can be reduced by simply truncating the sum in Equation (1.3) to the first $N_t$ terms. Note that the projection onto the first $N_t$ eigenvectors of the PCA basis gives the best $N_t$-dimensional approximation in the least squares sense, if the distribution of the vectors, $\vec x_i$, is a multi-dimensional Gaussian [15]. This reduced dimension representation, therefore, provides a convenient space in which to identify similar blocks in the presence of corrupting noise, as truncation of the basis will remove minor intensity variations.

I've completed translating the algorithm into MATLAB/Octave but it does not appear to be working correctly.  Below is my test image with a screen shot of the data in vectorized form and the PCA results. Here $N_b = 225$ and $ b=4$. In the PCA table all the remaining rows are either 0 or -1.
 (Please download test image at left. Only two blocks are identical.)

What I don't understand is how a lexicographical sort on the PCA data will show similarity. My expectation was that row 1 and 4 in the PCA output would be identical and that PCA would allow me to remove higher columns to increase matches. Similar to the way discrete cosine transform moves 'important' information to a smaller number of values of the data set. I've verified that my PCA algorithm mostly matches (signs are different) vs MATLAB's princomp() command so I must not understand what PCA is telling me. My question is, how would a sort on PCA results show self-similarity?
%This does principal component analysis
clear all;

bSide = 2; % Size of side of one block

%Read B&W image
chanData = imread('./randS.gif');

%Setup the input values
[imageWidth,imageHeight] = size(chanData);
tic();

%Calculate the derived constants
N = imageHeight * imageWidth;
b = bSide^2;
Nb = (sqrt(N) - sqrt(b) + 1)^2;
printf("ET:%d - ",toc());
printf("Finished deriving constants: N:%d b:%d Nb:%d\n",N,b,Nb);

%A set of observations of M variables
X = zeros(b,Nb); %Block representation of input image
u = zeros(b,Nb);%Temp for zero-mean calculation
coords = zeros(Nb,2); %Coordinate of the block at this location

%Create our matrix holding the dimension data
%X = zeros([Nb,b]); %b columns by Nb rows

%Populate the dimension matrix
iWidth = imageWidth - bSide + 1;
row = 1;
column = 1;
for i = 1:Nb
  %Setup local variables
  Xtemp = zeros(1,b);

  %Each block becomes a column of bSide rows
  for j = 1:bSide
    lowerX = (j - 1)*bSide + 1;
    Xtemp(lowerX:lowerX+(bSide-1)) = chanData(row+(j-1),column:column+(bSide-1));
  end

  %Add this vector as a column to the array
  X(:,i) = Xtemp;

  %Now create a mean vector
  u(i) = mean(X(:,i));

  %Save the coordinates of this block in a two column matrix
  coords(i,1) = row;
  coords(i,2) = column;

  %Update our source matrix indicies
  if column == iWidth
    row = row + 1;
    column = 1;
  else
    column = column + 1;
  end
end
clear Xtemp row column j iWidth lowerX;
printf("ET:%d - ",toc());
printf("Finished matrix construction\n");

%Get the mean for this vector and subtract it from the data
B = zeros(b,Nb);
for i = 1:Nb
  B(:,i) = X(:,i) - u(i);
end
printf("ET:%d - ",toc());
printf("Allocated mean-zero matrix\n");
%clear u X;

%Find the covarience matrix
C = cov(B);
printf("ET:%d - ",toc());
printf("Found covarience matrix\n");
%clear B;

%Find the eigenvalues and eigenvectors
%Evec: Nb x Nb matrix of eigenvectors, each column is a vector
%Eval: Nb x Nb matrix where only the main diagonal contains eiganvalues
[Evec,Eval] =  eig(C);
Eval = diag(Eval); %Convert eigenvalue matrix to vector
%clear C;
printf("ET:%d - ",toc());
printf("Found eigenvalues\n");

%Sort by eigenvalue. We do this by appending the eigenvalue vector as the
%first row. MATLAB won't sort by column for some reason, so we must
%transpose.
sortedEvec = [transpose(Eval); Evec];
sortedEvec = transpose(sortedEvec);
sortedEvec = sortrows(sortedEvec,-1);
sortedEvec = transpose(sortedEvec);
printf("ET:%d - ",toc());
printf("Sorted eigenvectors\n");

%Remove the eigenvalues row
sortedEvec(1,:) = [];

%Now do the final multiplication of the two transposed matrices
PCA = transpose(sortedEvec) * transpose(B);
printf("ET:%d - ",toc());
printf("Finished PCA\n");
%PCAt = PCA'; %PCAt matches princomp(B) except signs are reversed for first column

%Now integer quantize the array
PCA = floor(PCA);
printf("ET:%d - ",toc());
printf("Quantized PCA\n");

This is code I used to get the PCA matrix. princomp isn't defined for Octave but I was able to access MATLAB and run it there. My results match except the signs are inverted and the matrix from princomp is the transpose of my results.

A: It's to be expected that "copied" blocks are almost equal (and more so after the PCA manipulation), so in the lexicographical sort (warning: it's understood that this lexicographic order orders first the most principal component, and so on) "copied" blocks should appear adjacent or near (the reverse is not true: adjacent lexicographicly sorted elements are not necessarily copied, nor even similar)
Here I made up a very simple example myself, in Octave, with a unidimensional signal (y)
of size N=200, which has a portion of it copied (here, from 20-50 to 150-180) and a little noise added. I take a small block size (b=3).
I convert to PC, sort the rows in lexicographical order (I append first the original block position in an extra column), and compute the distance between adjacent rows (notice that I'm simplifiying a lot here: I'm not discarding components, nor quantizing them; and I'm considering only adjacent rows, not a neighborhood band). I then look at the histogram of those distance, and the original offset is cleary visible.
N=200;
b=3;
delay=130;
y = filter([1],[1,-0.8,0.1],rand(1,N)-0.5); % my signal, rather arbitrary
y(20+delay:50+delay) = y(20:50);  % a portion is copied
y += (rand(1,N)-0.5)*0.1; % noise added
yy=[y(1:N-2);y(2:N-1);y(3:N)];  % octave does not have  corrmtx (this is not general in b!)
[PC, Z, W, TSQ] = princomp (yy'); % PCA
Z(:,b+1)=[1:N-2]'; % append original block position, in extra row
Z1=sortrows(Z);  % sort rows lexicographycally
Z2=abs(Z1(1:N-3,b+1)-Z1(2:N-2,b+1));  % compute temporal distances between adjacent rows
histo(Z2); % histogram: should show a peak at delay


text:
Q: How to print html string as html If just for example I do:
var = "Asd";

{{ var }}

The string is printed like text and not as html, so how do I print the html ?

A: You can also try something like that:

    app.filter('to_trusted', ['$sce', function($sce) {
      return function(text) {
        return $sce.trustAsHtml(text);
      };
    }]);

and then, in view:

    ng-bind-html=" myHTML | to_trusted"

A: You should be using ng-bind-html directive.

Creates a binding that will innerHTML the result of evaluating the
  expression into the current element in a secure way.

<ANY ng-bind-html="{expression}">
   ...
</ANY>

A: Before using the ng-bind-html directive you must include the $sanitize service or it will throw an error.
Error: $sce:unsafe
Require a safe/trusted value
Attempting to use an unsafe value in a safe context.
Error: [$sce:unsafe] http://errors.angularjs.org/1.4.5/$sce/unsafe
    at Error (native)

The right way:

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

myApp.controller('MyController', ['$scope', function($scope) {
  $scope.myHTML = 'Hello, World!';
}]);

https://docs.angularjs.org/api/ngSanitize
https://docs.angularjs.org/api/ng/directive/ngBindHtml


text:
Q: How to overlay CSS onto the main resource theme in Codenameone My goal is simply to have a UID which allows me to put a shadow around different components, but still have the main theme.res used in my project. I'm finding i can only have one or the other running in the simulator at once - this is my problem.

After a lot of messing in the theme and then research it seems that i can't achieve this shadow affect in the theme, but it has to be done in CSS. I followed the CN1 research pages to produce the CSS below which then gave me the ability to have shadow UIDs in my project
BottomShadow {
box-shadow: 2pt 22pt 22pt 0px rgba(61,59,61,0.48);
padding-bottom: 2mm;
padding-top: 1mm;

}
But i am finding that when I use the CN1 Settings > Enable CSS, this stops the project from using my main theme.res (most likely because the settings creates a theme.css.res which overides it). But i have lots of 'regular' UIDs in my main theme that i need to run, as well as locales. I have read about people being able to overlay the CSS on the main theme, but this doesn't work for me.
        theme = UIManager.initNamedTheme("/theme", "Theme");
    if (Display.getInstance().isTablet()) {
        UIManager.getInstance().addThemeProps(theme.getTheme("Theme_Tablet"));
    }
    try {
        Resources css = Resources.openLayered("/theme.css");
        UIManager.getInstance().addThemeProps(css.getTheme(css.getThemeResourceNames()[0]));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

I either get CSS or the main theme running, not both. FYI here is my Console info, when i start the app in the simulator, if it helps. Thanks
Found theme.css file.  Watching for changes...
 CSS> Retina Scale: 1.0
 CSS> Input: C:\...\css\theme.css
 CSS> Output: C:\...\src\theme.res
 CSS> Acquiring lock on CSS checksums file C:\...\.cn1_css_checksums...
 CSS> Lock obtained
 CSS> C:\...\src\theme.res has been modified since it was last compiled.       Making copy at C:\...\css\.backups\theme.res.1570314993006.bak
 CSS> Waiting for web browser
 CSS> Opening JavaFX Webview to render some CSS styles
 CSS> Waiting for web browser
 CSS> Web browser is available
 CSS> Releasing lock
 CSS> CSS file successfully compiled.  C:\...\src\theme.res
 CSS> Watching file C:\...\css\theme.css for changes...

A: What the CSS does for this particular case is create a screenshot of the effect as an image to create that shadow. So if you generated a CSS theme res you can just open it in the designer and export it. You can then reimplement it in your non-CSS theme with the exported resource and (image screenshots).
You also have the option of a theme overlay which requires some manual work. Load the CSS theme then load your theme as an overlay add theme instead of as a set theme. This is covered in the developer guide under theme overlays.
BTW I'm guessing you've seen this and don't like the effect or need to interact with it: https://www.codenameone.com/blog/in-the-shadow.html


text:
Q: JPA: Mapping ManyToMany relationship with additional property I have many-to-many relationship between Employee and SkillSet table, with additional column numberOfYears for each relation
employeeId  skillSetId  numberOfYears
10          101         2

I am new to JPA and unable to define the entities with relationship. Should I define a new entity class for Employee_SkillSet table? Or can I have many to many relationship defined in both Employee and SkillSet class? Where do I specify numberOfYears column?
Edit: Seems duplicate, but I had explicit requirement of using @IdClass, and one of the entities was @MappedSuperclass, so have to define both ID instance, and referred entity object.

A: Since you need an additional field for the tuple (Employee, SkillSet), you have to make another entity.
@Entity
public class Employee implements Serializable {
    private @Id Long id;

    @OneToMany(mappedBy="employee")
    private List<EmployeeSkillSet> skillSets;
}

@Entity
public class SkillSet implements Serializable {
    private @Id Long id;
}

@Entity
public class EmployeeSkillSet implements Serializable {
    private @Id Long id;
    private @ManyToOne Employee employee;
    private @ManyToOne SkillSet skillSet;
    private @Basic int numberOfYears;
}

Of course you can choose to use a @IdClass to make ("employee", "skillSet") the primary key of EmployeeSkillSet like so:
@Entity @IdClass(EmployeeSkillSet.Key.class)
public class EmployeeSkillSet implements Serializable {

    private @Id @ManyToOne Employee employee;
    private @Id @ManyToOne SkillSet skillSet;
    private @Basic int numberOfYears;

    public static class Key implements Serializable {
        private Long employee; // plus getter+setter
        private Long skillSet; // plus getter+setter
        // plus hashCode, equals
    }
}

A: Although you can use @ManyToMany annotation is better for performance reasons define two many to one relations in order to model the Many To Many relationship.
You will need 4 artifacts, there are

*

*Employee Entity

*SkillSet Entity

*EmployeeSkillSet Relation entity (here you can specify numberOfYears Column)

*EmployeeSkillSetPK (Primary Key for EmployeeSkillSet Relation entity)

The code would be something like this
Employee
package <your_package>;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 *
 */
@Entity
@Table(name="EMPLOYEE")
public class Employee implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="EMPLOYEEID")
    private int id;

    // Rest of columns and getter and setters for all
}

SkillSet
package <your_package>;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 *
 */
@Entity
@Table(name="SKILLSET")
public class SkillSet implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="SKILLSETID")
    private int id;

    // Rest of columns and getter and setters for all
}

EmployeeSkillSetPK
/**
 *
 */
package <your_package>;

import java.io.Serializable;

import javax.persistence.Embeddable;

/**
 *
 */
@Embeddable
public class EmployeeSkillSetPK implements Serializable {

    @ManyToOne
    private Employee emp;

    @ManyToOne
    private SkillSet sk;
    /**
     * @return the employee
     */
    public Employee getEmployee() {
        return emp;
    }
    /**
     * @param employee the employee to set
     */
    public void setEmployee(Employee employee) {
        this.employee = employee;
    }
    /**
     * @return the sk
     */
    public SkillSet getSkillSet() {
        return sk;
    }
    /**
     * @param sk the sk to set
     */
    public void setSkillSet(SkillSet sk) {
        this.sk = sk;
    }

    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }

        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        EmployeeSkillSetPK that = (EmployeeSkillSetPK) o;

        if (employee != null ? !employee.equals(that.employee) : that.employee != null) {
            return false;
        }
        if (sk != null ? !sk.equals(that.sk) : that.sk != null) {
            return false;
        }

        return true;
    }

    public int hashCode() {
        int result;
        result = (employee != null ? employee.hashCode() : 0);
        result = 31 * result + (sk != null ? sk.hashCode() : 0);
        return result;
    }
}

EmployeeSkillSet
/**
 *
 */
package <your_package>;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 *
 */
@Entity
@Table(name="EMPLOYEESKILLSET")
    @AssociationOverrides({ @AssociationOverride(name = "pk.employee", joinColumns = @JoinColumn(name = "EMPLOYEEID")),
    @AssociationOverride(name = "pk.sk", joinColumns = @JoinColumn(name = "SKILLSETID")) })
public class EmployeeSkillSet implements Serializable {

    @EmbeddedId
    private EmployeeSkillSetPK pk = new EmployeeSkillSetPK();

    @Column
    private Integer numberOfYears;

    @Transient
    public Employee getEmployee() {
        return pk.getEmployee();
    }

    public void setEmployee(Employee employee) {
        pk.setEmployee(employee);
    }

    @Transient
    public SkillSet getSkillSet() {
        return pk.getSkillSet();
    }

    public void setSkillSet(SkillSet sk) {
        pk.setSkillSet(sk);
    }

    public Integer getNumbersOfYears() {
        return numberOfYears;
    }

    public void setNumbersOfYears(Integer numberOfYears) {
        this.numberOfYears = numberOfYears;
    }
}

This is for JPA 1.0, I cannot test the code right now, but it should work.
Note that I wrote the table and columns names on my own. Adapt it as you wish.


text:
Q: Deleting a dynamically allocated jagged array I have an array of pointers that point to arrays of ints.
I have made a hard coded array of ints (check 'array' below) and I want to insert it into the array of pointers (check 'bar' below), as far as I can tell, it is still an array of pointers that point to arrays of ints.
It compiles fine; no warnings.
It runs fine; and closes fine;
Until at least, I introduce the currently commented out delete statement in the destructor.
I imagine my compiler would make a better destructor at this point, but I'm interested as to what I'm doing wrong. The terminal window just throws out a gigantic memory map; and googling and searching SO didn't help much.
class foo {
    public:
    int **bar;
    int aSize;

    //CONSTRUCTOR
    foo(int aSize) {
        this->aSize = aSize;
        bar = new int*[aSize];
        for (int i=0;i<aSize;i++) {
            bar[i] = new int[aSize + i];
            for (int j=0;j<(aSize + i);j++) {
                bar[i][j] = 0;
            }
        }
        }
    void myfunc(int *pointer) {
        bar[0] = pointer;
    }
    ~foo() {
        for (int i=0;i<aSize;i++) {
            //delete[] bar[i];
        }
        delete[] bar;
    }
};
int main() {
    foo *obj = new foo(5);

    int array[] = {1,2,3,4};

    obj->myfunc(array);

    delete obj;
    return 0;
};

I know I've probably done something tragic; I just don't know what it is yet.
There is a reason why I am not using STL or other templates, it is simply because I'm interested in learning this.
Maximum criticism appreciated.

A: The myfunc function takes in a pointer, and then sets bar[0] to that memory address.  In your example code, you pass it the address of array, which is an automatic (stack) variable.  The destructor then attempts to delete[] bar[0], which points to a stack variable.  This is completely undefined behavior, and the reason your program is crashing.  You can't delete[] a stack array.  You can only delete[] an array which was allocated using new[].
Also, the myfunc function is always going to leak memory, because bar[0] points to a heap-allocated array.  When you set bar to a different memory address without first delete[]ing the previous address, you are leaking memory.

A: The problem is calling myfunc. In that function, you are replacing a pointer (bar[0]) that your class thinks it owns. Your obj destructor will then consequently try to run delete[] on your array[] in main, which probably causes your crash and leaves your original bar[0] dangling.


text:
Q: Is WADL a standard for REST applications? Is WADL a real standard like WSDL?
Must WADL URI end with ".wadl" extension?
I've created an HelloWorld example in Jersey and I've got the WADL from URL.
Then I've created a client using "wadl-client-plugin" and it works.
My question is this:
if I use another framework (i.e. CXF) that generate WADL, can I use it in my "wadl-client-plugin" to create the client?

A: The REST approach is simpler than SOAP, but unfortunately there is no standard at the moment.
More specifically, concerning WADL, the W3 team answered:

W3C is pleased to receive the Web Application Description Language from SUN Microsystems Inc.
  As of today, W3C has no plans to take up work based on this Submission. We encourage people interested by this work to discuss on the public-web-http-desc@w3.org Mailing List

However, there are ways to create clients from WADL


text:
Q: Can't install Openjdk 1.6 in ubuntu Accidentally I removed Openjdk from Ubuntu. Now it is not possible to install it again.It gives error that:
Err http://in.archive.ubuntu.com/ubuntu/ precise-updates/main tzdata all 2014c-0ubuntu0.12.04
  404  Not Found [IP: 91.189.92.200 80]

I used to try sudo apt-get update also.
Finally it gives:
WARNING: The following packages cannot be authenticated!
  openjdk-6-jre-lib ca-certificates-java tzdata tzdata-java openjdk-6-jre-headless libgif4 openjdk-6-jre libatk-wrapper-java libatk-wrapper-java-jni
  libxt-dev ttf-dejavu-extra icedtea-6-jre-cacao icedtea-6-jre-jamvm icedtea-netx-common icedtea-netx openjdk-6-jdk
Install these packages without verification [y/N]? y
Err http://in.archive.ubuntu.com/ubuntu/ precise-updates/main tzdata all 2014c-0ubuntu0.12.04
  404  Not Found [IP: 91.189.91.14 80]
Err http://in.archive.ubuntu.com/ubuntu/ precise-updates/main tzdata-java all 2014c-0ubuntu0.12.04
  404  Not Found [IP: 91.189.91.14 80]
Get:1 http://in.archive.ubuntu.com/ubuntu/ precise-updates/main libxt-dev amd64 1:1.1.1-2ubuntu0.1 [490 kB]
Get:2 http://in.archive.ubuntu.com/ubuntu/ precise-updates/main openjdk-6-jdk amd64 6b31-1.13.3-1ubuntu1~0.12.04.2 [16.0 MB]
Fetched 16.5 MB in 59s (278 kB/s)
Failed to fetch http://in.archive.ubuntu.com/ubuntu/pool/main/t/tzdata/tzdata_2014c-0ubuntu0.12.04_all.deb  404  Not Found [IP: 91.189.91.14 80]
Failed to fetch http://in.archive.ubuntu.com/ubuntu/pool/main/t/tzdata/tzdata-java_2014c-0ubuntu0.12.04_all.deb  404  Not Found [IP: 91.189.91.14 80]
E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?

A: Use Ubuntu Software Center: OpenJDK Java 6 Runtime

A: Why do you need openjdk? it's slow and not fully implemented. Use java instead.
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer

A: Since June of 2017, the traditional way to install the Java 6,  does not work. Note that Java 1.6 is not supported anymore by Oracle neither.

The traditional way to install Java
The typical method to install Java is adding the webup8 repository and using apt-get to install the software.
$ sudo add-apt-repository ppa:webupd8team/java
$ sudo apt-get update
$ sudo apt-get install oracle-java6-installer     # this does not work

Currently, I think you can install Java 8 or Java 9.

An alternative method
You may try to download the installer from the Java download archive using a Browser. There is a .bin file that is a self-extracting installer.
For instance, if you download the jdk-6u45-linux-x64.bin, you must run that file
$ jdk-6u45-linux-x64.bin


text:
Q: Laravel Key Value Pair in Get Request I'm using Laravel 5.4 and Axios to make async requests to my backend and retrieve data based on the get request parameters of my api endpoint.
I can see in inspector I'm making the following request to the server:
https://website.com/api/users?page=1&sort=%7B%22fieldName%22:%22lname%22,%22order%22:%22asc%22%7D&filter=

Which decodes to:
https://website.com/api/users?page=1&sort={"fieldName":"lname","order":"asc"}&filter=

Looks like I can successfully get pieces of the query via:
return $request->query('sort');

which returns:
data:
    fieldName: "lname"
    order: "asc"

But when I use:
return $request->query('sort.fieldName');

I don't get anything. Should I not be using the dot notation? How do I get each key / value pair of the sort input? Thanks for any help!

A: I thought you could use dot notation, but at any rate you could try just converting it from json to an associative array.
$sort = json_decode($request->query('sort'), true);

This should then allow you to do something like, $sort['fieldName']. The true parameter tells the decode to turn it into an associative array versus being returned an object.


text:
Q: Handle asynchronous events from model to view model Suppose a Model that asynchronously fires events (i.e. not from the UI thread). Because this Model has access to a DAQ card and performs time critical tasks it is important that the event handlers do not block/take to long to process the event.
To summarize:

*

*event handlers shouldn't block while processing the event

*since events are not fired from the UI thread they need to be delegated to the UI thread

By now I created a View Model that uses the Dispatcher of the View and BeginInvoke. In the code below I try to change a property IsEmergencyButtonActive onto which the UI may create a data binding:
void board_EmergencyButtonEvent(object sender, EventArgs e, bool state)
{
    uiDispatcher.BeginInvoke((Action)(() => {
        IsEmergencyButtonActive = state;
        // Perform other time consuming tasks ...
    }));
}

Is this "the way to go"? Are there better approaches to solve this task?

A:
Are there better approaches to solve this task?

Two immediately come to mind.
First is a minor modification to the code you already have: instead of a specific dispatcher, you can use the more generic SynchronizationContext:
// elsewhere, from the UI thread...
context = SynchronizationContext.Current;

void board_EmergencyButtonEvent(object sender, EventArgs e, bool state)
{
  context.Post(_ =>
  {
    IsEmergencyButtonActive = state;
    // Perform other time consuming tasks ...
  }, null);
}

In this simplified code, it wouldn't make any difference. But if this code was in, say, a ViewModel, then taking a dependency on the SynchronizationContext is a better choice than taking a dependency on a UI-specific dispatcher type. (Easier to work with in unit tests, more portable if you change to a different UI framework).
The other option - which I prefer - is to treat your stream of events as an Rx stream. So, instead of EmergencyButtonEvent, you'd have an IObservable<bool>. Then the consuming code would look like:
// IObservable<bool> EmergencyButtonStates { get; }
IDisposable subscription = board.EmergencyButtonStates
    .ObserveOn(context) // Same "context" as above. Rx can also use dispatchers, too.
    .Subscribe(state =>
    {
      IsEmergencyButtonActive = state;
      // Perform other time consuming tasks ...
    });
// Dispose "subscription" when you don't want any more events.

Rx has a bit more of a learning curve, but it's incredibly powerful. It's especially useful when it comes to any kind of time-related logic. E.g., "throttle this event stream to no more than once every 200ms" or "take the most recent value from this event stream when this other event stream hasn't updated in over a second", which is probably useful given your hardware-based scenario.

A: Generally, I would recommend using async/await. Event Handlers are one of the few scenarios where it is appropriate to use async void instead of async Task.
async void board_EmergencyButtonEvent(object sender, EventArgs e)
{
    IsEmergencyButtonActive = taskBegunState;
    await Task.Run(() => { ...Long Running Code... });
    IsEmergencyButtonActive = taskCompleteState;
}


text:
Q: I need to display data stored in cloud firestore android studio I am trying to display data stored in cloud firestore in a recycler view but it is not working. It is not displaying anything. I just have a blank activity. what could be wrong in my code? Thank you in advance
Here is my code:
Users.java:
package com.example.how;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;

public class Users extends AppCompatActivity {

private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference UsersRef = db.collection("Users");
private UsersAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_users);

    setUpRecyclerView();
}
private void setUpRecyclerView() {
    Query query = UsersRef;
    FirestoreRecyclerOptions<UsersModel> options = new FirestoreRecyclerOptions.Builder<UsersModel>()
            .setQuery(query, UsersModel.class)
            .build();
    adapter = new UsersAdapter(options);
    RecyclerView recyclerView = findViewById(R.id.FireStoreList);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(adapter);
}
@Override
protected void onStart() {
    super.onStart();
    adapter.startListening();
}
@Override
protected void onStop() {
    super.onStop();
    adapter.stopListening();
}

}

activity_users.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Users">

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/FireStoreList"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" >

</androidx.recyclerview.widget.RecyclerView>

</androidx.constraintlayout.widget.ConstraintLayout>

UsersModel.java:
package com.example.how;

public class UsersModel {

private String FName,LName,DOB,email,PhoneNumber,UserID;

private UsersModel(){}

private UsersModel(String FName,String LName, String DOB, String email, String PhoneNumber,
String UserID){

    this.FName = FName;
    this.LName = LName;
    this.DOB = DOB;
    this.email = email;
    this.PhoneNumber = PhoneNumber;
    this.UserID = UserID;

}

public String getFName() {
    return FName;
}

public void setFName(String FName) {
    this.FName = FName;
}

public String getLName() {
    return LName;
}

public void setLName(String LName) {
    this.LName = LName;
}

public String getDOB() {
    return DOB;
}

public void setDOB(String DOB) {
    this.DOB = DOB;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPhoneNumber() {
    return PhoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
    PhoneNumber = phoneNumber;
}

public String getUserID() {
    return UserID;
}

public void setUserID(String userID) {
    UserID = userID;
}

}

UsersAdapter.java:
package com.example.how;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;

public class UsersAdapter extends FirestoreRecyclerAdapter<UsersModel, UsersAdapter.UsersHolder>
{

public UsersAdapter(@NonNull FirestoreRecyclerOptions<UsersModel> options) {
    super(options);
}

@Override
protected void onBindViewHolder(@NonNull UsersHolder holder, int position, @NonNull UsersModel
model) {

    holder.FName.setText(model.getFName());
    holder.LName.setText(model.getLName());
    holder.email.setText(model.getEmail());
    holder.PhoneNumber.setText(model.getPhoneNumber());
    holder.DOB.setText(model.getDOB());
    holder.UserID.setText(model.getUserID());

}

@NonNull
@Override
public UsersHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View v =
LayoutInflater.from(parent.getContext()).inflate(R.layout.userdetails,parent,false);

    return new UsersHolder(v);
}

class UsersHolder extends RecyclerView.ViewHolder{

    TextView FName,LName,DOB,email,PhoneNumber,UserID;
    public UsersHolder(View itemView) {
        super(itemView);

        FName= itemView.findViewById(R.id.txtFName);
        LName= itemView.findViewById(R.id.txtLName);
        DOB= itemView.findViewById(R.id.txtDOB);
        email= itemView.findViewById(R.id.txtemail);
        PhoneNumber= itemView.findViewById(R.id.txtPhoneNumber);
        UserID= itemView.findViewById(R.id.txtUserID);
    }
}

}

userdetails.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TextView
    android:id="@+id/txtFName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="51dp"
    android:text="hrllo"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/txtLName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="13dp"
    android:text="hrllo"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/txtFName" />

<TextView
    android:id="@+id/txtDOB"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="13dp"
    android:text="hrllo"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/txtLName" />

<TextView
    android:id="@+id/txtemail"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="11dp"
    android:text="hrllo"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/txtDOB" />

<TextView
    android:id="@+id/txtPhoneNumber"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="11dp"
    android:text="hrllo"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/txtemail" />

<TextView
    android:id="@+id/txtUserID"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="11dp"
    android:text="hrllo"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/txtPhoneNumber" />
</androidx.constraintlayout.widget.ConstraintLayout>

A: The first error was solved by @MayurGajra which was that I was inflating activity_users instead of userdetails. And the second error was that fields' names should be the same in the Model.java, and the firebase. If they were different, data would not be retrieved


text:
Q: Changing iptables chain from port based to ip based Im working to limit access to a new XenServer 6.2 installation. The default iptables rules on the boxes have a RH-Firewall-1-INPUT chain that exposes quite a bit to the outside world.
Without going through and adding -s <ip range> to each rule (there are many) is there a way to add the ip ranges to all the rules by default?
Historically I build iptables with INPUT DROP and FORWARD DROP then open everything to the internal networks followed by a -j REJECT to ignore the rest. The XenServer rules seem a bit more complex and having an inadvertant iptables lock-out would be a bad thing.

A: You could have a rule that will -j JUMP to another chain, if the IP matches your range, else just drop everything.

A: FWIW, these are the default XenServer 6.2 rules - basically the stock RedHat rules since XenServer is based on RedHat:
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 ACCEPT     47   --  *      *       0.0.0.0/0            0.0.0.0/0
 499M 1226G RH-Firewall-1-INPUT  all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 RH-Firewall-1-INPUT  all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain OUTPUT (policy ACCEPT 187M packets, 1105G bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain RH-Firewall-1-INPUT (2 references)
 pkts bytes target     prot opt in     out     source               destination
 312K  429M ACCEPT     all  --  lo     *       0.0.0.0/0            0.0.0.0/0
15842 1331K ACCEPT     icmp --  *      *       0.0.0.0/0            0.0.0.0/0           icmp type 255
    0     0 ACCEPT     esp  --  *      *       0.0.0.0/0            0.0.0.0/0
    0     0 ACCEPT     ah   --  *      *       0.0.0.0/0            0.0.0.0/0
    0     0 ACCEPT     udp  --  *      *       0.0.0.0/0            224.0.0.251         udp dpt:5353
    0     0 ACCEPT     udp  --  *      *       0.0.0.0/0            0.0.0.0/0           udp dpt:631
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp dpt:631
    0     0 ACCEPT     udp  --  xenapi *       0.0.0.0/0            0.0.0.0/0           udp dpt:67
 497M 1223G ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
    0     0 ACCEPT     udp  --  *      *       0.0.0.0/0            0.0.0.0/0           state NEW udp dpt:694
    1    60 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:22
    3   180 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:80
10474  543K ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:443
1883K 2404M REJECT     all  --  *      *       0.0.0.0/0            0.0.0.0/0           reject-with icmp-host-prohibited

So if you want to limit the access to a known range (eg 192.168.0.0/24) you could do something like this:
iptables -I INPUT -s ! 192.168.0.0/24 -j REJECT

This will reject anything NOT from that source address, so the remaining rules will only apply to that source range.
If you have multiple trusted sources, you'll need to use a new chain like @Matt said (although you should use -j RETURN instead of -j INPUT)

A: Something like this should work.  Off the top of my head, it's been a while since I used iptables but.
# Create a whitelist chain
iptables -N whitelist

# Add some ip's to it
iptables -A whitelist -s 1.2.3.4/32 -j RETURN
iptables -A whitelist -s 2.3.4.5/32 -j RETURN
iptables -A whitelist -s 3.4.5.6/32 -j RETURN
# etc

# default drop on whitelist, no match - drop
iptables -P whitelist DROP

# Jump to the whitelist chain by default which will jump back if we get a match
iptables -A INPUT -j whitelist

# now back at your input chain
# All the normal rules follow


text:
Q: Logfile not generated using Cordova file plugin in Android Nougat & Marshmallow I am using the Cordova File Plugin to create a logfile in my internal storage of my device which is running Nougat. I do not have an external SD card.
Here is my code
function myLogger(logString) {
    alert("Inside mylogger");
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
        alert("Inside Local File System");
        var absPath = cordova.file.externalRootDirectory;
        var fileDir = cordova.file.externalDataDirectory.replace(cordova.file.externalRootDirectory, '');
        var fileName = "logfile.txt";
        var filePath = fileDir + fileName;
        alert(filePath);
        fs.root.getFile(filePath, {create: true, exclusive: false}, function (fileEntry) {
            alert("Inside getFile method");
            fileEntry.createWriter(function (fileWriter) {
                alert("Inside createwriter method");
                fileWriter.seek(fileWriter.length); // Start write position at EOF.
                var logStringWithTimeStamp = Date.parse(new Date()) + " : " + logString + "\n";
                var blob = new Blob([logStringWithTimeStamp], {type: 'text/plain', endings: 'native'});
                fileWriter.write(blob);
            }, function (err) {
                console.log("Err logString" + err);
            });
        }, function (err) {
            console.log("Err" + err);
        });
    }, function (err) {
        console.log("Err1" + err);
    });
}

myLogger("Hello Logger");

In this code I am getting Error Code 9 - INVALID_MODIFICATION_ERR
I have checked repeated times - the code is not entering fs.root.getFile block. So I changed the code a bit.
ALTERNATIVE CODE which gives no error but still logfile is not generated
function myLogger(logString) {
    alert("Inside mylogger");
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
        alert("Inside Local File System");
        var absPath = cordova.file.externalRootDirectory;
        var fileDir = cordova.file.externalDataDirectory.replace(cordova.file.externalRootDirectory, '');
        var fileName = "logfile.txt";
        var filePath = fileDir + fileName;
        alert(filePath);
        fs.root.getFile(fileName, {create: true, exclusive: false}, function (fileEntry) {
            alert("Inside getFile method");
            fileEntry.createWriter(function (fileWriter) {
                alert("Inside createwriter method");
                fileWriter.seek(fileWriter.length); // Start write position at EOF.
                var logStringWithTimeStamp = Date.parse(new Date()) + " : " + logString + "\n";
                var blob = new Blob([logStringWithTimeStamp], {type: 'text/plain', endings: 'native'});
                fileWriter.write(blob);
            }, function (err) {
                console.log("Err logString" + err);
            });
        }, function (err) {
            console.log("Err" + err);
        });
    }, function (err) {
        console.log("Err1" + err);
    });
}

myLogger("Hello Logger");

In the 2nd Code I am giving fileName as parameter instead of filePath in the getFile method. Here I am not getting any error but still logfile is not generated. I have all permissions in Android Manifest. I have also given storage access to my Ionic Cordova app. Why am I unable to generate logfile in my device internal storage?
Edit 1 : I have also tested in Marshmallow. In the 2nd code it is going to all blocks, there are no error but still logfile is not created

A: The main problem I can see with your implementation is this line:
var fileDir = cordova.file.externalDataDirectory.replace(cordova.file.externalRootDirectory, '');

This is replacing the absolute path and making it relative. You are then using this to construct your filePath and passing this to fs.root.getFile which expects an absolute path, not a relative one.
I would do it slightly differently from your approach and resolve the directory in which you want to create the file then use that directory entry to create the local file entry, something like this:
function onDeviceReady(){
    myLogger("Hello Logger");
}

function myLogger(logString) {
    var fileDir = cordova.file.externalDataDirectory;
    var fileName = "logfile.txt";
    var filePath = fileDir + fileName;
    window.resolveLocalFileSystemURL(fileDir, function (dirEntry) {
        log("Inside Local File System");

        log("Write to: " + filePath);
        dirEntry.getFile(fileName, {create: true, exclusive: false}, function (fileEntry) {
            log("Inside getFile method");
            fileEntry.createWriter(function (fileWriter) {
                log("Inside createwriter method");

                fileWriter.onwriteend = function () {
                    log("Successfully wrote file");
                };
                fileWriter.onerror = function (e) {
                    error("Failed file write: " + e.toString());
                };

                fileWriter.seek(fileWriter.length); // Start write position at EOF.
                var logStringWithTimeStamp = Date.parse(new Date()) + " : " + logString + "\n";
                var blob = new Blob([logStringWithTimeStamp], {type: 'text/plain', endings: 'native'});
                fileWriter.write(blob);
            }, function (err) {
                error("creating file writer " + JSON.stringify(err));
            });
        }, function (err) {
            error("getting file for writing " + JSON.stringify(err));
        });
    }, function (err) {
        error("requesting filesystem " + JSON.stringify(err));
    });
}

function error(msg){
    log("ERROR: "+msg);
}

function log(msg){
    document.body.innerHTML += '<p>'+msg+'</p>';
}

document.addEventListener('deviceready', onDeviceReady, false);


text:
Q: How to offset image contents by X,Y pixels using ImageMagick? I need to offset the pixels in a PNG image by -1 in X and -4 in Y axis.
The images were converted from a PDF created by Corel Draw, which adds an offset, breaking the image processing system I'm working on.
align_image_stack from hugin-tools package crashes when processing these files, that's why I resort to trying a fixed offest correction.
I tried this these commands:
$ convert a.png: -geometry 100%-100-100 b.png

$ convert -region '100%+500px+100px' a.png b.png

$ convert -page '100%+500px+100px' a.png b.png

$ convert -repage '100%+500px+100px' a.png b.png

$ convert -crop '100%+500px+100px' a.png b.png

$ convert a.png -geometry 100%-100px-100px b.png

They have all finished without an error, but the gave me the same image I fed them as input.
a.png = b.png
What am I doing wrong? Why the Covert command does not shift the image contents?
EDIT:
Here's a pair of images to illustrate my problem. The first image is what  I want, the second is what comes out of Corel Draw, I want to apply an arbitrary X/Y offset to compensate for this difference. The images are faked only to illustrate the problem, this is not authentic data.

New point is that I was able to produce the offset once, but I can't reproduce this. It looks to me like a bug in ImageMagick, because I'm trying the same command that I used before and it doesn't work now.
I also tried using GraphicsMagick to doublechek this.
I was able to get an offset written to PNG header, but that doesn't make Blender use that offset, so I need to "burn" that offset into the bitmap data, not just specify it in the metadata.
This command did a change, but only GIMP seems understands that and I need to make Blender apply the offset:
convert a.png -repage '100%x100%+100+1000' b.png

I tried using -sample to apply the transformation, but it's not alpplied and stays in the metadata - I can check this with GIMP.
convert a.png -repage '100%x100%+100+1000' -sample 100% b.png

I can't believe I am unable to do such a simple thing.

A: Updated Answer
It is hard to understand what you want without proper images, but here is another attempt at guessing a solution for you. Let's start with this image - ignore the colours as I only added them so you can see the extent of the images and you can remove/change them anyway:

The new plan is to trim your image so there is no border around the letters at all and then to add in whatever border you want afterwards. So, trimming the existing border and adding a 10px border left and right and a 50px border top and bottom:
convert start.png -trim -bordercolor red -border 10x50 result.png

Or, trimming the original border and adding a 10px border to the right side  only:
convert start.png -trim -gravity east -background blue -splice 10x0 result.png

Hopefully that will give you an approach to achieve what you seek.
Original Answer
If you want to reset the page offsets back to zero, the easiest way is:
mogrify +repage image.png

Or, slightly harder:
convert image.png +repage result.png


text:
Q: How to print a single item of a list at specific key from dict list Creating a list with 2 arrays, list contains one item from array zz and 1 one item from array xtime.
l = np.empty(len(yy), dtype=np.object)
for i in range(len(zz)):
    l[i] = zz[i], xtime[i]

print(l[:10])

output:
[(2, 2008) (1, 2008) (4, 395) (3, 395) (6, 1935) (5, 1935) (8, 3828)
 (7, 3828) (10, 4182) (9, 4182)]

Here I am creating a dict of lists (each key is a node containing to which node it is connected and time to get to that node).
for i in range(0,5):
    g.addEdge(yy[i], l[i])

Following is the dict list (is this a correct form of dict list?) and I want to get values like to which node 2 is connected (as it is connected to node 1). So to get that value if this dict list is in correct format.
defaultdict(<class 'list'>, {1: [(2, 2008)], 2: [(1, 2008)], 3: [(4, 395)], 4: [(3, 395)], 5: [(6, 1935)]})


text:
Q: Set up two divs as a dragable areas with HTML5 Hi there HTML5 developers, I am trying to set up two different divs to be the dragable area for the incoming file. However, it seems that only one of those can be active at a time, how can I make them both ready to accept the dnd of the file. This is the code I have:
var node = dojo.byId("welcomeDialog1_Id");
var node2 = dojo.byId("firstDialogBackground");
    // Reference
    // http://www.html5rocks.com/features/file
    // http://www.html5rocks.com/tutorials/dnd/basics/
    // https://developer.mozilla.org/En/DragDrop/Drag_Operations
    dojo.connect(node, "dragenter", function(evt){
        // If we don't prevent default behavior here, browsers will
        // perform the default action for the file being dropped i.e,
        // point the page to the file.
        evt.preventDefault();
    });

    dojo.connect(node, "dragover", function(evt){
        evt.preventDefault();
    });
    dojo.connect(node, "drop", handleDrop);

  dojo.connect(node2, "dragenter", function(evt){
        evt.preventDefault();
    });

    dojo.connect(node2, "dragover", function(evt){
        evt.preventDefault();
    });
    dojo.connect(node2, "drop", handleDrop);

A: Make sure that your drop zones are not nested inside each other or overlapping...
I can testify that, at least with FF and Chrome, you can have multiple drop zones on your page to accept incoming files. I did not test with IE.
When I worked with file DnD I found the following article very useful:

http://www.sitepoint.com/html5-file-drag-and-drop/


text:
Q: SQL deletion of a row returning- "ORA-02292: integrity constraint (..) violated - child record found" I've got a database consisting of four tables. Relation schema as follows in the picture:

And here are the rows:

Now I'm trying to delete the owner with owner id OW1 . Because the id is a primary key in owner table and foreign key in other table its not allowing me to delete the row. Here is the SQL I tried:
 delete from owners
 where ownerid = 'OW1' and petid = 'PT1'

And it returns :
ORA-02292: integrity constraint (TEST_1.ADDRESSES_OWNERS_FK) violated - child record found
And I'm not allowed to set the delete rule to 'CASCADE' in relation diagram.
Please help :(

A: Well, if an anonymous block counts as one statement, just wrap your deletes in a block:
begin
  delete from addresses where ownerid = 'OW1';
  delete from contacts where ownerid = 'OW1';
  delete from pets where ownerid = 'OW1';
  delete from owners where ownerid = 'OW1';
end;
/

SQL Fiddle. Seems like a bit of a cheat, but if those are the conditions you've been given...

A: Sometimes, it is tedious to find out which child reference tables are resisting from deleting the data from the parent table. In such cases, we can find the references to the main table using this query.
   select * from
       all_constraints where
            r_constraint_name in
                 (select  constraint_name from all_constraints
                  where table_name= '<PARENT_TABLE_NAME>');

By going through the result list, one can easily find out the references. From there, you can temporarily disable constraints if you need to by:
ALTER TABLE table_name DISABLE CONSTRAINT constraint_name;

And re-enable it when necessary. Hope this helps.


text:
Q: Can Xtext "factorize" features when it generates an Ecore model with multiple inheritance? If I have the following grammar:
grammar org.xtext.example.mydsl.MyDsl with org.eclipse.xtext.common.Terminals

generate myDsl "http://www.xtext.org/example/mydsl/MyDsl"

WithX:
    A | B | C;

A:
    "a" x=INT y=INT;

B:
    "b" x=INT y=INT;

C:
    "c" x=INT;

Then Xtext will generate the following Ecore model with a nice super class to factorize x:

However, if I add a rule to the grammar to also factorize y:
grammar org.xtext.example.mydsl.MyDsl with org.eclipse.xtext.common.Terminals

generate myDsl "http://www.xtext.org/example/mydsl/MyDsl"

WithX:
    A | B | C;

WithY:
    A | B ;

A:
    "a" x=INT y=INT;

B:
    "b" x=INT y=INT;

C:
    "c" x=INT;

Then the generated Ecore Model does not factorize any feature anymore:

Is there any wait to obtain x in WithX and y in WithY?

A: I just answered my own question. I simply had to add a relationship between WithX and WithY:
grammar org.xtext.example.mydsl.MyDsl with org.eclipse.xtext.common.Terminals

generate myDsl "http://www.xtext.org/example/mydsl/MyDsl"

WithX:
    WithY | C;

WithY:
    A | B ;

A:
    "a" x=INT y=INT;

B:
    "b" x=INT y=INT;

C:
    "c" x=INT;

And it now generates:

Hurray :)


text:
Q: Python .sum adding random numbers I have the below python code:
import pandas as pd
import numpy as np
import openpyxl

wb = openpyxl.load_workbook('MOA_Assignment.xlsx')
PD = pd.DataFrame(wb['Purchase Exit Survey Data'].values)
#drop unneeded rows and columns
PD=PD.iloc[6:,1:]
#sum columns into the 58th row
PD[58]=PD.sum()

Why would DataFrame.sum() add strange numbers?
I have used DataFrame.astype('int') to make sure the data frame is not an object but it still gives me weird results. The correct results should be 6, 1, 2, 1 ,15 in that order. CNBC alone should have at least more than a result of 3.0 as the five numbers showing add up to more than 3. Please help, thank you.
PD.head().to_dict()
{1: {6: 'aapka_colors',
  7: 'baby_first',
  8: 'bloomberg',
  9: 'cbs_sports',
  10: 'cnbc'},
 2: {6: None, 7: None, 8: None, 9: None, 10: None},
 3: {6: None, 7: None, 8: None, 9: 1, 10: 1},
 4: {6: None, 7: None, 8: None, 9: None, 10: 1},
 5: {6: None, 7: None, 8: None, 9: None, 10: None},
 6: {6: None, 7: None, 8: None, 9: None, 10: None},
 7: {6: None, 7: None, 8: None, 9: None, 10: None},
 8: {6: None, 7: None, 8: None, 9: None, 10: 2},
 9: {6: None, 7: None, 8: None, 9: None, 10: None},
 10: {6: 1, 7: None, 8: 1, 9: None, 10: None},
 11: {6: None, 7: None, 8: None, 9: None, 10: None},
 12: {6: None, 7: None, 8: None, 9: None, 10: None},
 13: {6: None, 7: None, 8: None, 9: None, 10: None},
 14: {6: None, 7: None, 8: None, 9: None, 10: None},
 15: {6: None, 7: None, 8: None, 9: None, 10: None},
 16: {6: None, 7: None, 8: None, 9: None, 10: None},
 17: {6: None, 7: None, 8: None, 9: None, 10: None},
 18: {6: None, 7: None, 8: None, 9: None, 10: None},
 19: {6: None, 7: None, 8: None, 9: None, 10: None},
 20: {6: None, 7: None, 8: None, 9: None, 10: None},
 21: {6: None, 7: None, 8: None, 9: None, 10: None},
 22: {6: None, 7: None, 8: None, 9: None, 10: None},
 23: {6: None, 7: 1, 8: None, 9: None, 10: None},
 24: {6: None, 7: None, 8: None, 9: None, 10: None},
 25: {6: None, 7: None, 8: None, 9: None, 10: 1},
 26: {6: None, 7: None, 8: None, 9: None, 10: None},
 27: {6: None, 7: None, 8: None, 9: None, 10: None},
 28: {6: None, 7: None, 8: None, 9: None, 10: None},
 29: {6: 1, 7: None, 8: None, 9: None, 10: 1},
 30: {6: 1, 7: None, 8: None, 9: None, 10: None},
 31: {6: None, 7: None, 8: None, 9: None, 10: 1},
 32: {6: None, 7: None, 8: None, 9: None, 10: None},
 33: {6: None, 7: None, 8: None, 9: None, 10: None},
 34: {6: None, 7: None, 8: None, 9: None, 10: None},
 35: {6: None, 7: None, 8: None, 9: None, 10: None},
 36: {6: None, 7: None, 8: None, 9: None, 10: 1},
 37: {6: None, 7: None, 8: None, 9: None, 10: None},
 38: {6: None, 7: None, 8: 1, 9: None, 10: 1},
 39: {6: None, 7: None, 8: None, 9: None, 10: None},
 40: {6: None, 7: None, 8: None, 9: None, 10: None},
 41: {6: None, 7: None, 8: None, 9: None, 10: None},
 42: {6: None, 7: None, 8: None, 9: None, 10: None},
 43: {6: 1, 7: None, 8: None, 9: None, 10: 1},
 44: {6: None, 7: None, 8: None, 9: None, 10: None},
 45: {6: None, 7: None, 8: None, 9: None, 10: None},
 46: {6: None, 7: None, 8: None, 9: None, 10: None},
 47: {6: None, 7: None, 8: None, 9: None, 10: None},
 48: {6: None, 7: None, 8: None, 9: None, 10: None},
 49: {6: None, 7: None, 8: None, 9: None, 10: 1},
 50: {6: 2, 7: None, 8: None, 9: None, 10: None},
 51: {6: None, 7: None, 8: None, 9: None, 10: None},
 52: {6: None, 7: None, 8: None, 9: None, 10: None},
 53: {6: None, 7: None, 8: None, 9: None, 10: None},
 54: {6: None, 7: None, 8: None, 9: None, 10: None},
 55: {6: None, 7: None, 8: None, 9: None, 10: None},
 56: {6: None, 7: None, 8: None, 9: None, 10: 1},
 57: {6: None, 7: None, 8: None, 9: None, 10: 3},
 58: {6: 7, 7: 7, 8: 7, 9: 1, 10: 3}}

A: I cannot replicate your issue.
From the dictionary you have pasted, I see results as expected:
res = df.sum(axis=1).to_dict()

# {6: 13.0, 7: 8.0, 8: 9.0, 9: 2.0, 10: 18.0}

df = df.fillna(0.0).loc[:, df.sum(axis=0) != 0]

#               1    3    4    8    10   23   25   29   30   31   36   38   43  \
# 6   aapka_colors  0.0  0.0  0.0  1.0  0.0  0.0  1.0  1.0  0.0  0.0  0.0  1.0
# 7     baby_first  0.0  0.0  0.0  0.0  1.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
# 8      bloomberg  0.0  0.0  0.0  1.0  0.0  0.0  0.0  0.0  0.0  0.0  1.0  0.0
# 9     cbs_sports  1.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
# 10          cnbc  1.0  1.0  2.0  0.0  0.0  1.0  1.0  0.0  1.0  1.0  1.0  1.0

#      49   50   56   57  58
# 6   0.0  2.0  0.0  0.0   7
# 7   0.0  0.0  0.0  0.0   7
# 8   0.0  0.0  0.0  0.0   7
# 9   0.0  0.0  0.0  0.0   1
# 10  1.0  0.0  1.0  3.0   3

A: Change
PD[58]=PD.sum()

to
PD[58]=PD.sum(1)
# P[58] = PD.sum(axis=1) Or this either option does the same

you are currently summing columns, you want to sum rows


text:
Q: Trying to add conditional constraint into LP excel I have an LP equation with a condition of at least 3/4 of the constraints has to be satisfied
$z = 60X_1 + 50X_2 + 120X_3$
s.t:
$60X_1 + 40X_2 + 30X_3 >= 45$
$40X_1 + 15X_2 + 40X_3 >= 20$
$20X_1 + 40X_2 + 60X_3 >= 40$
$5X_2 + 10X_3 >= 5$
$X_1,X_2,X_3 >= 0$
How am I able to add this into Solver in Excel?

A: Not sure if Solver can handle mixed-integer problems but if it can, one way is to define binary variables $c_{1},c_{2},c_{3},c_{4}$, and reformulate the constraints as
$60X_{1} + 40X_{2} + 30X_{3} >= 45c_{1} \\
40X_{1} + 15X_{2} + 40X_{3} >= 20c_{2} \\
20X_{1} + 40X_{2} + 60X_{3} >= 40c_{3} \\
5X_{2} + 10X_{3} >= 5c_{4} \\
X_{1},X_{2},X_{3} >= 0\\
c_{1}+c_{2}+c_{3}+c_{4}>= 3 \\
c_{1},c_{2},c_{3},c_{4} \in \{0,1\}$


text:
Q: How do you create a RichTextBox in either C++ or Java Can someone give me a simple example of how to write text in a RichTextBox? I've looked online for some sample code without finding much help.
The only thing that I found was that I would have to declare a RichTextBox variable:
//Using C++
RichTextBox richbox = gcnew RichTextBox;

However, this doesn't work at all.

A: Rich edit box controls are provided by many different frameworks. How they are implemented in either language will depend on the one you choose.
For C++ there is the ever popular windows specific Win32 API or MFC, or if you are diving into the .NET framework there is WinForms. There are also cross platform libraries like wxWidgets or Qt.
For Java, the JDK has AWT and Swing. There is also the Standard Widget Toolkit and others.
Once you choose a language and a framework, try to create your application with the rich edit control. If you have trouble come back with your code and we can help you with more specific questions.


text:
Q: Word for excessive use of adjectives or a long stream of adjectives I was tasked with analyzing an article, and I encountered within the text a long sentence with a stream of adjectives, e.g.

Gove and all the other know-nothing know-it-alls happily continue to peddle their sneering, condescending, dismissive, misanthropic, elitist, made-up twaddle.

Is there an appellation for such an occurrence? In addition, is there a specific word for excessive use of adjectives? I know circumlocution may be appropriate for the second question, but I was hoping there was a word specific to adjectives or adverbs.

A: Synathroesmus: A rhetorical term for the piling up of words (usually adjectives), often in the spirit of invective.


text:
Q: What redirect rule should I use to replace this 301 redirect, in Apache? I am using this directive to redirect to HTTPS:
<VirtualHost *:80>
        ServerName              foo.bananas.net
        Redirect                301 / https://foo.bananas.net
</VirtualHost>

The problem is that when a path is used in the address bar, like http://bananas.net/webpage, it takes a pauses for a while before failing with https://bananas.netwebpage (no slash).
Should a rewrite rule be used instead?  What should it be, and are there any differences in behaviour that I should be aware of?

A: You could use mod_rewrite, or you could use a RedirectMatch.
e.g. something like this:
RedirectMatch  301  ^(.*)  https://foo.bananas.net$1

on second thoughts, just add a "/" to the end of the Redirect rule you already have:
    Redirect  301  /  https://foo.bananas.net/

either should work.


text:
Q: Adding source code to all jars of Tomcat9 Targeted Runtime in Eclipse so that F3 opens source code In a Dynamic Web Project in Eclipse I have a Tomcat9 attached as a Targeted Runtime (I downloaded binary distribution from official site
But if I press F3 on any class (say, SimpleTagSupport class) no source code appears because it is not attached.
How to add source code?
I understand I can download source code distribution

And I understand how to add source code:

In my case ( SimpleTagSupport ) it is

But can I somehow attach source code to all jars in Tomcat Targeted Runtime? It is a tiresom work to manually find source and attach it to each jar!
Besides I cannot find needed source-folders for all respective jars, b/c source distributions looks like this:

Also it turns out ot be that java/javax/servlet/jsp/tagext folder does not contain any valid source files, but what shall add as source to servlet-api.jar or for javax.servlet.jsp.tagext package (for SimpleTagSupport class)...

A: The idea is that for every .jar (for example for servlet-api.jar) you specify entire src.zip file (Eclipse will figure out the needed part itself)
Solution is found here

Use: https://javaee.github.io/javaee-spec/javadocs/
If we add source files then besides opening source by F3 it also enables tooltip (javadoc) help (taken from javadocs inside source files) on hover (or F2), but Shift+F2 would not work.
To enable Shift+F2 we need to explicitly attach Javadoc (attach source is not enough for Shift+F2).
Download Tomcat's Full Documentation (not source!!!), unarchive it and then use file:/// notation:

file:/K:/SERVERS/apache-tomcat-9.0.16-fulldocs/tomcat-9.0-doc/servletapi

Now Shift+F2 is enabled!


text:
Q: "Argument is of length 0" when comparing xts objects This must be very simple, but I can't seem to find the solution. I need to compare the Close value for 2 xts objects
I have 2 xts objects:
>low2
low2           daco.Close
2013-07-24     6.63

>low3
low3           daco.Close
2013-07-24     2.63

But when I try something like this
if(low2$daco.Close < low3$daco.Close) {...}

I keep getting the error
Error in if (low2$daco.Close < low3$daco.Close) { :
  argument is of length zero

Even though when I try print(low2) or print(low3) I get the correct values.
Any tip on how to solve this will be much appreciated.
Thanks!
Edit:
Following are the outputs of low2 and low3
> dput(low2)
structure(6.63, .indexCLASS = "Date", tclass = "Date", .indexTZ = "UTC", tzone = "UTC", src = "xxx", updated = structure(1374782893.98805, class = c("POSIXct",
"POSIXt")), class = c("xts", "zoo"), index = structure(1374451200, tzone = "UTC", tclass = "Date"), .Dim = c(1L,
1L), .Dimnames = list(NULL, "daco.Close"))
> dput(low3)
structure(2.63, .indexCLASS = "Date", tclass = "Date", .indexTZ = "UTC", tzone = "UTC", src = "xxx", updated = structure(1374782893.98805, class = c("POSIXct",
"POSIXt")), class = c("xts", "zoo"), index = structure(1374624000, tzone = "UTC", tclass = "Date"), .Dim = c(1L,
1L), .Dimnames = list(NULL, "daco.Close"))

A: xts objects are aligned by index before operations are done.  Note that low2$daco.Close + low3$daco.Close probably doesn't return what you thought it would either.
This is what you are passing to your if statement:
> low2$daco.Close < low3$daco.Close
     [,1]
> str(low2$daco.Close < low3$daco.Close)
An 'xts' object of zero-width

You can use coredata on one or both of the xts objects.
low2$daco.Close < coredata(low3$daco.Close)
#           daco.Close
#2013-07-22      FALSE

or you could coerce one or both of them to numeric first
as.numeric(low2$daco.Close) < as.numeric(low3$daco.Close)
#[1] FALSE

If they did in fact have the same index it should have just worked.
index(low3) <- index(low2)
low2$daco.Close < low3$daco.Close
#           daco.Close
#2013-07-22      FALSE


text:
Q: Remove jQuery delegated event handler on specific object I've attached delegated event handlers to a number of elements on the page using a single selector. As the events are triggered for individual elements, I'd like to turn off only that element's event handler based on some conditional logic. That means I won't necessarily want to disable the event on the very first click. But I can't figure out how to do it without turning off all of them.
HTML:
<button>One</button>
<button>Two</button>
<button>Three</button>

JS:
$(document).on('click', 'button', function(ev) {
    // doesn't work because argument needs to be a string
    $(document).off('click', $(ev.target));

    // doesn't do what I want b/c turns off events on all buttons, not just this one
    $(document).off('click', 'button');

    // doesn't work because event is on document, not button
    $(ev.target).off('click');
});

jQuery's off documentation says I need to provide a string as the second argument, not a jQuery object ($(ev.target)), but if I provide a string, there's no value that refers only to the item clicked.
From jQuery's off documentation:

To remove specific delegated event handlers, provide a selector
  argument. The selector string must exactly match the one passed to
  .on() when the event handler was attached. To remove all delegated
  events from an element without removing non-delegated events, use the
  special value "**".

So how do I turn off a delegated event handler for a specific element?
Here's a JSFiddle of the code above
UPDATE: Added a few examples of options that don't work, based on initial answers provided.

A: After having read thru on the web, the answer is you can't! You can either remove all or none. A workaround could be something like the following.
$(document).on('click', '.btn', function (ev) {
    alert('pressed');
    $(this).removeClass("btn");
});

Demo@Fiddle
Sample HTML:
<button class="btn">One</button>
<button class="btn">Two</button>
<button class="btn">Three</button>

A: In addition to what lshettyl said (the current top post) - an additional work around is to bind a new event listener directly to the element that you're trying to remove the listener and call stopPropagation() therein.
What this will do is prevent the event from traveling up the DOM and reaching the event handler that is initially bound to the document. Also this will allow you to keep some functionality on the button click, such as an alert to the user that this button has already been clicked - or something to that effect.
$(document).on('click', 'button', function(ev) {
    // Your logic to occur on button click

    // Prevent further click on just this button
    $(this).click(function(event) {
        event.stopPropagation();
    }):
});

A: Question: Do you have to use the delegated events? LIke LShetty said, it is not possible to remove a delegated event for a single element. You either remove the entire event delegation, or leave it. You could try using a different selector instead like in this example

$('button').on('click', function(ev) {
    $('#output').append('Clicked! ');
    $(this).off('click');
});

<button>One</button>
<button>Two</button>
<button>Three</button>


text:
Q: Lifetime in chained Dependency Injection In .NET Core, there are three different lifetimes one can use: Transient, Scoped and Singleton.
Let's assume I have the following chain of depencency-injected services:
Service A > Service B > Service C,
meaning that Service A has Service B injected (e.g. Service A depends on Service B) and Service B has Service C injected.
Now consider Service B having a Singleton lifetime, and Service C having a Transient lifetime. Because Service B is a Singleton, it is only created once. Service C is Transient, but because Service B is a Singleton, Service C is still just created once as well.
Is this argumentation correct, and thus does the Transient lifetime I set for Service C not make sense? Or am I thinking wrongly here?

A: What you are describing here is a common problem known as Captive Dependency. Service C becomes captive because its consumer has a longer lifetime.
This issue is widespread and is a common source of bugs in applications that use Dependency Injection and DI containers. When an application grows, these issues can easily slip in undetected. From experience I can tell that tracing back a bug to such misconfiguration can take a lot of time.
Unfortunately, the built-in container of .NET Core does not detect and prevent these kinds of mistakes. Some of the other, more mature, DI libraries for .NET actually have these kinds of features where they detect and prevent these kinds of misconfigurations.