text:
Q: Strongswan several left subnets with IKEv1 We are in process of replacing a Microsoft TMG server with a CentOS server. For VPN we decided to use strongswan due to instabilities with libreswan. But, strongswan has some weird issues with several subnets on either side. The current (libreswan) working config has leftsubnets={10.x.x.0/24,172.y.y.0/24} and rightsubnets={10.y.y.0/24,172.z.z.0/24}. How to port this libreswan configuration to strongswan? I have tried making several conns with a single leftsubnet and rightsubnet in each, configuration file seems to be parsed properly, but no SAs get established (connecting 0, up 0). Do I miss a something?
Current config is like this:
conn hmmm
  left=86.x.x.x
  right=y.y.y.84
  keyexchange=ikev1
  authby=secret
  type=tunnel
  auto=start
  ike=aes256-sha1-modp1024
  rekey=yes
  leftsubnet=10.x.x.0/24
  rightsubnet=10.y.y.0/24

conn hmmm-2
  also=hmmm
  leftsubnet=172.y.y.0/24
  rightsubnet=172.z.z.0/24

Logs say "no proposal", however this IKEv1 setting is what worked with libreswan. The other end is Cisco ASA under our control, but since we need an in-place swap of firewalls, we cannot perform connection upgrade to IKEv2.

A: This configuration misses esp parameter to specify IKEv1 quick mode parameters to be used with IPsec connection in question. Just that. Extra parameters were leftauth=psk and rightauth=psk to conform with non-deprecated syntax (authby is deprecated), mobike=no just in case, and ikelifetime=8h and lifebytes=4608000000 to match the other side's SA lifetime settings. This is the missing line:
esp = aes256-sha1-modp1024,aes192-sha1-modp1024,aes128-sha1-modp1024

I was expecting ESP to use IKE parameters to set up quick mode SAs, but probably misread the manual.


text:
Q: How to apply rigor to proof sketches When doing analysis, I have difficulties to recite the proofs given in the lectures in oral examinations. I am able to do calculations with the theorems that I encountered. (Note that in central europe, there is no separation of calculus and analysis.)
My way of learning focuses on finding out the ideas, to be able to state which other theorems are involved and how they interact at which state of the proof. I am mostly unable to formalize the ideas behind the proof when it becomes technical, even though the outline of the proof itself is understood. I can convince myself why the corollaries are meaningful and how they relate to the preceding theorem.
Example: When proving the inverse function theorem (we did this by using the implicit function theorem), I know how to define the function that transfers the problem to the requirements of the implicit function theorem, and I know how I arrive at all given objects that are used for instance in the picture drawn to visualise the problem (the open sets involved in the assertion of the inverse function theorem).
The question is the following, as I find it particularly hard to get rid of my aversion to study technical details:
What are possible ways to master making the step from talking about the connections to really show the connections? When studying a proposition and its proof, I am always working with a sheet of paper, writing down the things and the core aspects, though I am having a particularly hard time to write down more than the vital aspects. Also, I am looking for good reasons (might be philosophical ones) why it is important to not exclude technical details in the studies and overcome studying for the big picture.
When checking out related questions, many answers suggest to learn the ideas and getting a big picture. Here, I am having troubles converting proof sketches/skeletons to formalised mathematics and becoming rigorous in reasoning.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Вывод escape-последовательности из переменной Есть строка которая берется из файла, и в ней содержатся escape-последовательности, например: char *ptr="bla \n bla"!
Если printf("%s", ptr) то будет с новой строки все, а я хочу чтобы вывелось все точно так же как строка. Есть идея бежать по строке и если по ascii '10' то печатать то что надо, if и прочее. Есть другие способы вывести нв стандартный вывод в точности как строка на Си и C++
Например на python выглядело бы так print(repr(ptr))

A: Если я правильно понимаю, вам надо что-то вроде этого?
void out(const char * s)
{
    for(;*s;++s)
    {
        char esc = ' ';
        switch(*s)
        {
        case 0x07: esc = 'a'; break;
        case 0x08: esc = 'b'; break;
        case 0x09: esc = 't'; break;
        case 0x0A: esc = 'n'; break;
        case 0x0B: esc = 'v'; break;
        case 0x0C: esc = 'f'; break;
        case 0x0D: esc = 'r'; break;
        case 0x5C: esc = '\\'; break;
        case 0x27: esc = '\''; break;
        case 0x22: esc = '\"'; break;
        }
        if (esc == ' ') putchar(*s);
        else { putchar('\\'); putchar(esc); }
    }
}

A: Как написал Harry, можно и так:
void recode(const char* s) {
    for (; *s; ++s) {
        char code[] = "\x07\x08\x09\x0A\x0B\x0C\x0D\x22\x27\x5C";
        char* c = strchr(code, *s);

        if (c) {
            putchar('\\');
            putchar("abtnvfr\"\'\\"[c - code]);
            }
        else putchar(*s);
        }
    }


text:
Q: React state passed as prop does not update in child component Hi I wonder if someone could explain why when the returned zones of each function, are passed down to a child as props, the first function updates the props and renders the child, but a small change in the second function targets the exact values required does not? I think I may be losing the original reference somehow, but do not know how to fix it. Thanks in advance
getAudioControls1(controls,rooms){
    let zones = []

    for (const key in controls) {
        if (controls.hasOwnProperty(key)) {
            const element = controls[key];
            if (element.type === "InfoOnlyText" && element.name === "Synched") {
                let room = this.getReqRoom(element.room, rooms)
                element.roomName = room.name
                zones.push(element)
            }
        }
    }
    return zones
}

getAudioControls2(controls,rooms){
    let zones = []
    for (const key in controls) {
        if (controls.hasOwnProperty(key)) {
            const element = controls[key];
            if (element.type === "InfoOnlyText" && element.name === "Synched") {
                let room = this.getReqRoom(element.room, rooms)
                let rawZones = []
                element.roomName = room.name
                rawZones.push(element.roomName,element.statesValue.text)
                zones.push(rawZones)
            }
        }
    }
    return zones
}

A: In the first example you push element (I guess it's an object) to zones. As a result you have array of objects.
In the second you push array rawZones to your zones. As a result you have array of arrays.


text:
Q: VkApi, загрузка файла на сервер вк Здравствуйте. Пытаюсь решить эту проблему уже третий день, но ничего не выходит.
Суть в том, что мне по url картинке надо сначала сохранить её к себе в файле(только cURL), а потом как-то передать её на сервер вк, который мне возвращает один метод. Всё это только cURL.
Вот таким кодом я пыталась загружать изображение на свой сервер:
$url = $query["response"]["upload_url"];

$file2 = "https://pp.userapi.com/c834204/v834204071/2e431/hRxE5SHqV2s.jpg";

$ch = curl_init($file2);

curl_setopt($ch, CURLINFO_HEADER_OUT, true);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

$rawdata = curl_exec($ch);

 curl_close($ch);
 $fp = fopen('../vk_post/allow_url_fopen/image.jpg', 'wb');
 fclose($fp);

Но ничего в результате. Так и не додумалась как можно загрузить файл с фото на сервер вк.
Буду чрезвычайно благодарна, если вы покажете как исполнить хоть один шаг - загрузку на мой сервер или на сервер вк.

A: Вот так, например. Сначала создаем  у себя копию картинки, затем грузим, затем unlink
copy($file,'./tempimg.jpg');
$lala = "./tempimg.jpg";
$cfile = curl_file_create($lala,'image/jpeg','test_name.jpg');
$postparam = array("file1"=>$cfile);

$ch = curl_init($server);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$postparam);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data; charset=UTF-8'));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,10);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$json = json_decode(curl_exec($ch));
curl_close($ch);
unlink('./tempimg.jpg');


text:
Q: How can I plot an indicator with a condition that RSI must be greater than x but less than y in pine script? I want to plot an indicator with an rsi value from 52 to 80 only but whenever I put a range format below:
rsiup = 50 < rsi < 80
rsidown = 30 < rsi < 50

then I get this error:
Cannot call 'operator <' with argument 'expr0'='call 'operator <' (series bool)'. An argument of 'series bool' type was used but a 'const float' is expected

Please help

A: You need to break it down into two and conditions.
rsiup = (50 < rsi) and (rsi < 80)
rsidown = (30 < rsi) and (rsi < 50)


text:
Q: Can I set a member variable before constructor call? I started to implement an ID based memory pool, where every element has an id, which is basically an index in a vector. In this special case I know the index before I construct the object itself so I thought I set the ID before I call the constructor.
Some details
Allocating an object from an ID based pool is the following:

*

*allocate a free id from the pool

*get a memory address based on the id value

*construct the object on the memory address

*set the ID member of the object

and the deallocation is based on that id
here is the code (thanks jrok):
#include <new>
#include <iostream>

struct X
{
  X()
  {
    // id come from "nothing"
    std::cout << "X constructed with id: " << id << std::endl;
  }
  int id;
};

int main()
{
    void* buf = operator new(sizeof(X));

    // can I set the ID before the constructor call
    ((X*)buf)->id = 42;
    new (buf) X;
    std::cout << ((X*)buf)->id;
}

EDIT
I found a stock solution for this in boost sandbox:
sandbox Boost.Tokenmap

A:
Can I set a member variable before constructor call?

No, but you can make a base class with ID that sets ID within its constructor (and throws exception if ID can't be allocated, for example). Derive from that class, and at the moment derived class enter constructor, ID will be already set. You could also manage id generation within another class - either within some kind of global singleton, or you could pass id manager as a first parameter to constructor.
typedef int Id;
class IdObject{
public:
    Id getId() const{
        return id;
    }
protected:
    IdManager* getIdManager() ...
    IdObject()
    :id(0){
        IdManager* manager = getIdManager();
        id = manager->generateId();
        if (!id)
            throw IdException;
        manager->registerId(id, this);
    }
    ~IdObject(){
        if (id)
            getIdManager()->unregisterId(id, this);
    }
private:
    Id id;
    IdObject& operator=(IdObject &other){
    }
    IdObject(IdObject &other)
    :id(0){
    }
};

class DerivedObject: public IdObject{
public:
    DerivedObject(){
        //at this point, id is set.
    }
};

This kind of thing.

A: No, you cannot set anything in an object before its constructor is called.  However, you have a couple of choices:

*

*Pass the ID to the constructor itself, so it can store the ID in the object.

*Allocate extra memory in front of the object being constructed, store the ID in that extra memory, then have the object access that memory when needed.

A: If you know the object's to-be address, which is the case for your scenario, then yes you can do that kind of thing. However, it is not well-defined behaviour, so it's most probably not a good idea (and in every case not good design). Although it will probably "work fine".
Using a std::map as suggested in a comment above is cleaner and has no "ifs" and "whens" of UB attached.
Despite writing to a known memory address will probably be "working fine", an object doesn't exist before the constructor is run, so using any of its members is bad mojo.
Anything is possible. No compiler will likely do any such thing, but the compiler might for example memset the object's storage with zero before running the constructor, so even if you don't set your ID field, it's still overwritten. You have no way of knowing, since what you're doing is undefined.

A: Yes, you can do what you're doing, but it's really not a good idea. According to the standard, your code invokes Undefined Behaviour:

3.8 Object lifetime [basic.life]
The lifetime of an object is a runtime property of the object. An object is said to have non-trivial initialization
  if it is of a class or aggregate type and it or one of its members is initialized by a constructor other than a trivial
  default constructor. [ Note: initialization by a trivial copy/move constructor is non-trivial initialization. —
  end note ] The lifetime of an object of type T begins when:
— storage with the proper alignment and size for type T is obtained, and
— if the object has non-trivial initialization, its initialization is complete.
The lifetime of an object of type T ends when:
— if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or
— the storage which the object occupies is reused or released.
Before the lifetime of an object has started but after the storage which the object will occupy has been
  allocated or, after the lifetime of an object has ended and before the storage which the object occupied is
  reused or released, any pointer that refers to the storage location where the object will be or was located
  may be used but only in limited ways. For an object under construction or destruction, see 12.7. Otherwise,
  such a pointer refers to allocated storage (3.7.4.2), and using the pointer as if the pointer were of type void*,
  is well-defined. Such a pointer may be dereferenced but the resulting lvalue may only be used in limited
  ways, as described below. The program has undefined behavior if:
— the pointer is used to access a non-static data member or call a non-static member function of the
  object

When your code invokes Undefined Behaviour, the implementation is allowed to do anything it wants to. In most cases nothing will happen - and if you're lucky your compiler will warn you - but occasionally the result will be unexpectedly catastrophic.
You describe a pool of N objects of the same type, using a contiguous array as the underlying storage. Note that in this scenario you do not need to store an integer ID for each allocated object - if you have a pointer to the allocated object, you can derive the ID from the offset of the object within the array like so:
struct Object
{
};

const int COUNT = 5; // allow enough storage for COUNT objects

char storage[sizeof(Object) * COUNT];

// interpret the storage as an array of Object
Object* pool = static_cast<Object*>(static_cast<void*>(storage));

Object* p = pool + 3; // get a pointer to the third slot in the pool
int id = p - pool; // find the ID '3' for the third slot

A: Is there a reason you want to do this before the constructor call?

Allocating an object from an ID based pool is the following:
1) allocate a free id from the pool
2) get a memory address based on the id value
3) construct the object on the memory address
4) set the ID member of the object and the deallocation is based on that id

According to your steps, you are setting the ID after the constructor.

so I thought I set the ID before I call the constructor.

I hate to be blunt, but you need to have a better reason than that to wade into the undefined behaviour territory. Remember, as programmers, there is a lot we're learning all the time and unless there is absolutely no way around it, we need to stay away from minefields, undefined behavior being one of them.
As other people have pointed out, yes you can do it, but that's like saying you can do rm -rf / as root. Doesn't mean you should :)

C makes it easy to shoot yourself in the foot. C++ makes it harder, but when you do, you blow away your whole leg! — Bjarne Stroustrup


text:
Q: unable to use c++amp in vs 2017 I tried to use C++ amp in Visual Studio 2017, but compiler said, "error C3564" and I tried the old code(which worked in Visual Studio 2015), and it said same thing.
Does Visual Studio 2017 support C++ amp?
#include "stdafx.h"
using namespace concurrency;
int main(void){
    int size;
    scanf_s("%d", &size);
    array_view<int, 1> a(1);
    parallel_for_each(extent<1>(1),
    [=](index<1> &idx) restrict(amp)
    {
        a(idx) = size;
    });
}

the code above will generate problem.

A: just added the amp.h file and the code above compiles.
i am also working on other project with C++AMP in vs 2017 and it working fine.
#include "stdafx.h"
#include <amp.h>

using namespace concurrency;

int main(void) {
    int size;
    scanf_s("%d", &size);
    array_view<int, 1> a(1);
    parallel_for_each(extent<1>(1),
        [=](index<1> &idx) restrict(amp)
    {
        a(idx) = size;
    });
}


text:
Q: Share file in slack from one user to another user using api I want to share slack file from one user to another user within the same workspace using api.
What I tried in code is, downloaded the file want to share and uploaded the file to the user using files.upload method.
But both the files are assigned with the different file ids.
Is there any way to share the file from one user to another without changing its file id using api

A: In Slack you can usually share files with others. (as described here)
However, this is currently not possible with the Slack API, since it does not have a method for sharing a file, other then through files.upload.
Alternatively you can use the files.share method from the undocumented Slack API. This comes with a couple caveats though, one being that the method requires a legacy token and will therefore not work well with distributed Slack apps. But if you are just building something for your own Slack workspace it will work fine.
To share a file with another user provide the user ID as channel property for files.share.
Note: If you need this functionality I would suggest to let the Slack team know about it. The more feedback they get the more likely this method will become part of the official API.


text:
Q: View Scoped Bean preRenderView method being called multiple times I have a problem with my Mojarra 2.1.6 web-application, I'm developing it using @ViewScoped managed beans and each bean is attached to an xhtml page. This page is receiving some view params and after initializing the bean in that way:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui"
template="/templates/general_template.xhtml">

<ui:define name="metadata">
    <f:metadata>
        <f:viewParam id="user" name="user"
            value="#{navegableUserData._ParamUser}" />

        <f:viewParam id="NavIndex" name="NavIndex"
            value="#{navegableUserData._QueueIndex}" />
        <f:event type="preRenderView"
            listener="#{navegableUserData.initialize}" />
    </f:metadata>
    <h:message for="user" />
</ui:define>

<ui:define name="general_content">
    <p:outputPanel autoUpdate="false" id="Datos_Loged" name="Datos_Loged"
        layout="block">
        <h:form id="SystemUserForm">
            <ui:include
                src="/system/manage_user/content/edit_user/system_user_data/system_user.xhtml">
                <ui:param name="manager" value="#{navegableUserData}" />
            </ui:include>
        </h:form>
    </p:outputPanel>
</ui:define>

As you can see, I have my pages nested into a general template which looks like that:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui" xmlns:o="http://omnifaces.org/ui">

<h:head>
    <meta http-equiv="Pragma" CONTENT="no-cache"></meta>
    <meta http-equiv="cache-control" content="no-cache"></meta>
    <meta http-equiv="Expires" CONTENT="-1"></meta>
    <meta http-equiv="Content-Type"
        content="text/html; charset=ISO-8859-15" />
    <h:outputStylesheet library="css" name="prime_styles.css" />
    <h:outputScript library="js" name="prime_translations.js" />
</h:head>

<h:body>
    <ui:insert name="metadata" />
    <o:importConstants
        type="com.company.system.view.beans.NavigationResults" />

<!-- More stuff -->

Problem comes when I make an ajax request such as a Primefaces table filtering. Although my backing bean is not being created again, <f:event type="preRenderView" listener="#{navegableUserData.initialize}" /> is being called again.
I'm doing a data loading based into view params and need that method to execute only when the page is rendered first time. I have been very careful using <c:xxx> tags and think that's not the problem because I used them only in general template and my view beans properties are not attached to them. Also I have this problem with all my pages, so I think it is not an issue of an specific backing bean.

A: If this occur only during ajax request, try the following:
public void initialize() {
    if (!FacesContext.getCurrentInstance().isPostback()) {
        // -----------
        // -----------
    }
}

Related as BalusC suggested:

*

*What can f:metadata and f:viewParam be used for?

A: Just for completeness, apart from the method @jonhy mentions, there's a cleaner choice if using JSF 2.2: Using f:viewAction instead of f:event.
<f:viewAction action="#{navegableUserData.initialize}" />

With that, it's not necessary to wrap your server code with if (!FacesContext.getCurrentInstance().isPostback()), since basically the method itself doesn't get called, because by default this actions are not executed on postbacks.
You alternatively can set them to be, which would be the same behavior as using the original f:event:
<f:viewAction action="#{navegableUserData.initialize}" onPostback="true" />

See also:

*

*New JavaServer Faces 2.2 Feature: The viewAction Component


text:
Q: Foreman conditional running processes I have a foreman app with a Procfile like this
web: bundle exec rails s
custom_process: bundle exec rake custom:process
faking_custom_process: bundle exec rake custom:faking_process

And I want to run custom_process or faking custom_process depends on my needs:
foreman start # run web & custom_process
FAKING_PROCESS # run web & faking_custom_process

Yes, I know about ability of running like that foreman start -c faking_custom_process=0, but this is more difficult than I expect, right?

A: There's no option in foreman to just skip a process. I think you'd need to extend your start invocation to do something different too if you want to run the other processes. Otherwise you're just telling it to run zero copies of faking_custom_process and nothing else:
foreman start -m web=1,custom_process=1,faking_custom_process=0

or for the faking version:
foreman start -m web=1,custom_process=0,faking_custom_process=1

You could of course script that so you've got two scripts running those different versions.

An alternative would be to switch faking on or off using a variable in the environment (I'm not convinced it's any easier but it's an alternative):
web: bundle exec rails d
custom_process: PROCESS=$FAKING"process" && bundle exec rake custom:$PROCESS

A normal foreman start will just run bundle exec rake custom:process.
For the faking equivalent you can do:
export FAKING="faking_"

which will mean that from then on foreman start it will call bundle exec rake custom:faking_process instead.
You can return to the normal process by clearing the FAKING variable with:
export FAKING=

You could of course encapsulate that into a shell script too.

A: You can use .profile to store default options for foreman start:
concurrency: web=1,custom_process=1,faking_custom_process=0

or using shortcut:
concurrency: all=1,faking_custom_process=0

And then you override this default option to switch to fake process:
foreman start -c all=1,custom_process=0

See: http://ddollar.github.io/foreman/#DEFAULT-OPTIONS


text:
Q: Exporting a d3.js overlay on top of a Bing Map using html2canvas Has anyone attempted to use html2canvas with Bing Maps. I have been able to get html2canvas to work with google maps but I now need to get it to work for Bing Maps. When I attempt to export my svg with is a d3.js overlay ontop of a Bing Map it looks like this?

My html2canvas export code is as follows:
 html2canvas($svg, {
 proxy: "",
 useCORS: true,
 background: "#E8F0F6",
 onrendered: function (canvas) {

            var a = document.createElement('a');
            a.download = name;
            a.href = canvas.toDataURL('image/png');
            document.body.appendChild(a);
            a.click();

        },
        width: 450,
        height: 700,

    });


text:
Q: Are these queries the same? If not how to make more simple query Beginners question here, are these two queries the same? For some reason they give different count of rows.
=> count of row ~2154
SELECT *
FROM kliendi_aadress
WHERE maakond ~'\s\s'
   OR linn ~'\s\s'
   OR asula ~'\s\s'
   OR tanav ~'\s\s'
   OR maja ~'\s\s'
   OR korter ~'\s\s'
   OR postikood ~'\s\s'

=> count of rows ~1923
SELECT *
FROM kliendi_aadress
WHERE maakond || linn || asula || tanav || maja || korter || postikood ~'\s\s'

If not how to make first query more simple and faster?

A: The queries may return different results, because a simple columns concatenation may add extra two-spaces substrings. You can try the concatenation with separator:
SELECT *
FROM kliendi_aadress
WHERE concat_ws(',', maakond, linn, asula, tanav, maja, korter, postikood) ~ '\s\s'

A: It returns something different because you have "Tanav" in the next query written twice?


text:
Q: supervisor [ERROR] Error on initialization of server mk-supervisor I set up storm on a production server and it worked well until I had an abrupt power failure now I get the supervisor error  supervisor [ERROR] Error on initialization of server mk-supervisor anytime I try to push a topology. Storm ui nolonger shows my number of workers (which used to be 4); is now 0.
I get that supervisor is no longer working well but re-installing supervisor does not resolve the issue. I had this problem with a previous setup that caused me to redo the whole setup again to get it working. But I cannot keep doing a setup anytime supervisor fails.
2014-04-06 23:59:48 supervisor [INFO] Starting Supervisor with conf {"dev.zookeeper.path" "/tmp/dev-storm-zookeeper", "topology.tick.tuple.freq.secs" nil, "topology.fall.back.on.java.serialization" true, "topology.max.error.report.per.interval" 5, "zmq.linger.millis" 5000, "topology.skip.missing.kryo.registrations" false, "ui.childopts" "-Xmx768m -Djava.net.preferIPv4Stack=true", "storm.zookeeper.session.timeout" 20000, "nimbus.reassign" true, "topology.trident.batch.emit.interval.millis" 500, "nimbus.monitor.freq.secs" 10, "java.library.path" "/usr/local/lib:/opt/local/lib:/usr/lib", "topology.executor.send.buffer.size" 1024, "storm.local.dir" "/var/storm", "supervisor.worker.start.timeout.secs" 120, "topology.enable.message.timeouts" true, "nimbus.cleanup.inbox.freq.secs" 600, "nimbus.inbox.jar.expiration.secs" 3600, "drpc.worker.threads" 64, "topology.worker.shared.thread.pool.size" 4, "nimbus.host" "192.168.254.145", "storm.zookeeper.port" 2181, "transactional.zookeeper.port" nil, "topology.executor.receive.buffer.size" 1024, "transactional.zookeeper.servers" nil, "storm.zookeeper.root" "/storm", "supervisor.enable" true, "storm.zookeeper.servers" ["192.168.254.145"], "transactional.zookeeper.root" "/transactional", "topology.acker.executors" 1, "topology.transfer.buffer.size" 1024, "topology.worker.childopts" nil, "drpc.queue.size" 128, "worker.childopts" "-Xmx768m -Djava.net.preferIPv4Stack=true", "supervisor.heartbeat.frequency.secs" 5, "topology.error.throttle.interval.secs" 10, "zmq.hwm" 0, "drpc.port" 3772, "supervisor.monitor.frequency.secs" 3, "topology.receiver.buffer.size" 8, "task.heartbeat.frequency.secs" 3, "topology.tasks" nil, "topology.spout.wait.strategy" "backtype.storm.spout.SleepSpoutWaitStrategy", "topology.max.spout.pending" nil, "storm.zookeeper.retry.interval" 1000, "topology.sleep.spout.wait.strategy.time.ms" 1, "nimbus.topology.validator" "backtype.storm.nimbus.DefaultTopologyValidator", "supervisor.slots.ports" [6700 6701 6702 6703], "topology.debug" false, "nimbus.task.launch.secs" 120, "nimbus.supervisor.timeout.secs" 60, "topology.message.timeout.secs" 30, "task.refresh.poll.secs" 10, "topology.workers" 1, "supervisor.childopts" "-Djava.net.preferIPv4Stack=true", "nimbus.thrift.port" 6627, "topology.stats.sample.rate" 0.05, "worker.heartbeat.frequency.secs" 1, "topology.acker.tasks" nil, "topology.disruptor.wait.strategy" "com.lmax.disruptor.BlockingWaitStrategy", "nimbus.task.timeout.secs" 30, "storm.zookeeper.connection.timeout" 15000, "topology.kryo.factory" "backtype.storm.serialization.DefaultKryoFactory", "drpc.invocations.port" 3773, "zmq.threads" 1, "storm.zookeeper.retry.times" 5, "topology.state.synchronization.timeout.secs" 60, "supervisor.worker.timeout.secs" 30, "nimbus.file.copy.expiration.secs" 600, "drpc.request.timeout.secs" 600, "storm.local.mode.zmq" false, "ui.port" 8080, "nimbus.childopts" "-Xmx1024m -Djava.net.preferIPv4Stack=true", "storm.cluster.mode" "distributed", "topology.optimize" true, "topology.max.task.parallelism" nil}

  2014-04-06 23:59:48 supervisor [ERROR] Error on initialization of server mk-supervisor
java.lang.RuntimeException: java.io.EOFException
    at backtype.storm.utils.Utils.deserialize(Utils.java:68)
    at backtype.storm.utils.LocalState.snapshot(LocalState.java:24)
    at backtype.storm.utils.LocalState.get(LocalState.java:28)
    at backtype.storm.daemon.supervisor$standalone_supervisor$reify__4810.prepare(supervisor.clj:486)
    at backtype.storm.daemon.supervisor$fn__4757$exec_fn__1228__auto____4758.invoke(supervisor.clj:329)
    at clojure.lang.AFn.applyToHelper(AFn.java:167)
    at clojure.lang.AFn.applyTo(AFn.java:151)
    at clojure.core$apply.invoke(core.clj:601)
    at backtype.storm.daemon.supervisor$fn__4757$mk_supervisor__4782.doInvoke(supervisor.clj:327)
    at clojure.lang.RestFn.invoke(RestFn.java:436)
    at backtype.storm.daemon.supervisor$_launch.invoke(supervisor.clj:477)
    at backtype.storm.daemon.supervisor$_main.invoke(supervisor.clj:506)
    at clojure.lang.AFn.applyToHelper(AFn.java:159)
    at clojure.lang.AFn.applyTo(AFn.java:151)
    at backtype.storm.daemon.supervisor.main(Unknown Source)
Caused by: java.io.EOFException
    at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2323)
    at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2792)
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:800)
    at java.io.ObjectInputStream.<init>(ObjectInputStream.java:298)
    at backtype.storm.utils.Utils.deserialize(Utils.java:63)

I cannot tell what actually went on during the power failure. I am lost here...Help pls

A: I think what you need to do is to clear all of the local directories that are used by Storm (at least, moving them to a different place to have some kind of backup -if needed-).
Local directories is what you configure in conf/storm.yaml.
This is due Storm wasn't shutdown properly.


text:
Q: Matching Features with ORB python opencv hi im working in Matching Features with ORB python opencv but when i run this code i get this error
Traceback (most recent call last):
  File "ffl.py", line 27, in
    for m,n in matches:
TypeError: 'cv2.DMatch' object is not iterable
i don't know how to fix it
import numpy as np
import cv2
import time

ESC=27
camera = cv2.VideoCapture(0)
orb = cv2.ORB_create()
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

imgTrainColor = cv2.imread('/home/shar/home.jpg')
imgTrainGray = cv2.cvtColor(imgTrainColor, cv2.COLOR_BGR2GRAY)

kpTrain = orb.detect(imgTrainGray,None)
kpTrain, desTrain = orb.compute(imgTrainGray, kpTrain)

firsttime = True

while True:

    ret, imgCamColor = camera.read()
    imgCamGray = cv2.cvtColor(imgCamColor, cv2.COLOR_BGR2GRAY)
    kpCam = orb.detect(imgCamGray,None)
    kpCam, desCam = orb.compute(imgCamGray, kpCam)
    bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
    matches = bf.match(desCam,desTrain)
    good = []
    for m,n in matches:
        if m.distance < 0.7*n.distance:
            good.append(m)

    if firsttime==True:
        h1, w1 = imgCamColor.shape[:2]
        h2, w2 = imgTrainColor.shape[:2]
        nWidth = w1+w2
        nHeight = max(h1, h2)
        hdif = (h1-h2)/2
        firsttime=False

    result = np.zeros((nHeight, nWidth, 3), np.uint8)
    result[hdif:hdif+h2, :w2] = imgTrainColor
    result[:h1, w2:w1+w2] = imgCamColor

    for i in range(len(matches)):
        pt_a=(int(kpTrain[matches[i].trainIdx].pt[0]), int(kpTrain[matches[i].trainIdx].pt[1]+hdif))
        pt_b=(int(kpCam[matches[i].queryIdx].pt[0]+w2), int(kpCam[matches[i].queryIdx].pt[1]))
        cv2.line(result, pt_a, pt_b, (255, 0, 0))

    cv2.imshow('Camara', result)

    key = cv2.waitKey(20)
    if key == ESC:
        break

cv2.destroyAllWindows()
camera.release()

A: for m in matches:
    if m.distance < 0.7:
        good.append(m)

This block of code is good, but does not really have the same meaning as the original. I think that using ORB and something involving n and n+1 elements in the matches refers to the original intent of SIFT algorithm, which performs a ratio match.
So, a correct code would be (I guess) :
for i, m in enumerate(matches):
    if i < len(matches) - 1 and m.distance < 0.7 * matches[i+1].distance:
        good.append(m)

Less efficient, and there may be a workaround or better code. But my main point is to underline that the answered code is not doing the same as OP's code.
Original SIFT paper saying :

This test rejects poor matches by computing the ratio between the best
  and second-best match. If the ratio is below some threshold, the match
  is discarded as being low-quality.

Please also note that "0.7" is named "ratio" and is fixed to 0.75 (from memory) in the original paper.

A: bf.match return only a list of single objects, you cannot iterate over it with m,n. Maybe you are confused with bf.knnMatch?
You can just change your code to:
for m in matches:
    if m.distance < 0.7:
        good.append(m)

From the Python tutorials of OpenCV (link):

The result of matches = bf.match(des1,des2) line is a list of DMatch
  objects. This DMatch object has following attributes:

*

*DMatch.distance - Distance between descriptors. The lower, the better
  it is.

*DMatch.trainIdx - Index of the descriptor in train descriptors

*DMatch.queryIdx - Index of the descriptor in query descriptors

*DMatch.imgIdx - Index of the train image.

A: The code attempts to use Lowe's ratio test (see original SIFT paper).
this requires, for every descriptor, the two closest matches.
the code should read:
    matches = bf.knnMatch(desCam, desTrain, k=2) # knnMatch is crucial
    good = []
    for (m1, m2) in matches: # for every descriptor, take closest two matches
        if m1.distance < 0.7 * m2.distance: # best match has to be this much closer than second best
            good.append(m1)

further, I would highly recommend the flann matcher. it's faster than the brute force matcher.
look at the OpenCV tutorials or the samples directory in OpenCV's source (samples/python/find_obj.py) for code that works.


text:
Q: code igniter can't remove index.php from URL I have my codeigniter library under a folder called 'codeigniter' (very original) so I visit it at this address which loads fine, http://mysite.co.uk/codeigniter/index.php/pages/view/about
However I can't get to my 'about' page using the following address http://mysite.co.uk/codeigniter/pages/view/about URL without the 'index.php' in the address, it keeps hitting my default controller instead of my pages controller.
I've updated the following:
config.php
$config['base_url'] = 'http://mysite';
$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI';

.htaccess
RewriteEngine on
RewriteBase /codeigniter/
RewriteCond $1 !^(index.php|resources|robots.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

Any help would be great!

A: Make sure that the "AllowOverride All" was in placed in your Apache configuration file for the .htaccess to be worked.

A: You can Use This in your .htaccess
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]

A: You can use this in your .htaccess file
Options -Indexes
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond $1 !^(index\.php|resources|robots\.txt)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L,QSA]
        #RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC]
        #RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC]
        #RewriteRule \.(jpe?g|gif|bmp|png)$ - [F]
</IfModule>
#Gzip
<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript text/javascript
</ifmodule>
<IfModule mod_headers.c>
Header add Cache-Control:  "no-store, no-cache, must-revalidate"
Header unset Pragma
FileETag None
Header unset ETag
</IfModule>
#End Gzip
# BEGIN Expire headers
<ifModule mod_expires.c>
    ExpiresActive On
    ExpiresDefault "access plus 5 seconds"
    ExpiresByType image/x-icon "access plus 2592000 seconds"
    ExpiresByType image/jpg "access plus 2592000 seconds"
    ExpiresByType image/jpeg "access plus 2592000 seconds"
    ExpiresByType image/png "access plus 2592000 seconds"
    ExpiresByType image/gif "access plus 2592000 seconds"
    ExpiresByType text/x-javascript "access 1 month"
    ExpiresByType text/html "access plus 600 seconds"
    ExpiresByType text/css "access plus 604800 seconds"
    ExpiresByType text/javascript "access plus 216000 seconds"
    ExpiresByType application/x-shockwave-flash "access plus 2592000 seconds"
    ExpiresByType application/pdf "access 1 month"
    ExpiresByType application/javascript "access plus 216000 seconds"
    ExpiresByType application/x-javascript "access plus 216000 seconds"
    ExpiresByType application/xhtml+xml "access plus 600 seconds"
</ifModule>


text:
Q: Do I need to care about big endian and little endian when I read data through AudioInputStream? I am reading a wav file through AudioInputStream into a byte array,
    AudioInputStream audiofile = AudioSystem.getAudioInputStream(f);
    byte[] audio=new byte[numberofframes*framesize];
    int bytes=audiofile.read(audio);

do I need to arrange the bytes of a sample considering that the data is arranged in little endian or does the AudioInputStream do it for me?

A: Big- versus little-endian matters if the data is encoded in more than a single byte, e.g., bit depths of 16 or more, regardless of the number of channels. Java does not automatically arrange the PCM bytes in a default order, it just accepts them.
The following is the clearest, best written single section of the java audio tutorials, imho, and covers issues pertaining to formats and their conversions:
http://docs.oracle.com/javase/tutorial/sound/converters.html


text:
Q: Correct use of Akka http client connection pools I need to consume a REST service using Akka's HTTP client (v2.0.2). The logical approach is to do this via a host connection pool because we expect large numbers of simultaneous connections. The Flow for this consumes a (HttpRequest, T) and returns a (Try[HttpResponse, T). The documentation indicates that some arbitrary type T is needed to manage potential out of order responses to requests but does not point out what the caller is supposed to do with the returned T.
My first attempt is the function below using an Int as T. It is called from many places to ensure that the connections use a single pool.
val pool = Http().cachedHostConnectionPool[Int]("127.0.0.1", 8888, ConnectionPoolSettings(system))

def pooledRequest(req: HttpRequest): Future[HttpResponse] = {
  val unique = Random.nextInt
  Source.single(req → unique).via(pool).runWith(Sink.head).flatMap {
    case (Success(r: HttpResponse), `unique`) ⇒ Future.successful(r)
    case (Failure(f), `unique`) ⇒ Future.failed(f)
    case (_, i) ⇒ Future.failed(new Exception("Return does not match the request"))
  }
}

The question is how should the client use this T? Is there a cleaner more efficient solution? And finally, Is my paranoia that something may arrive out of order not actually paranoia?

A: Akka HTTP Connection pools are powerful allies when consuming HTTP based resources. If you are going to execute single requests at a time then a solution is:
def exec(req: HttpRequest): Future[HttpResponse] = {
  Source.single(req → 1)
    .via(pool)
    .runWith(Sink.head).flatMap {
      case (Success(r: HttpResponse), _) ⇒ Future.successful(r)
      case (Failure(f), _) ⇒ Future.failed(f)
    }
}

Because you are executing a single request, there is no need to disambiguate the response. However, Akka streams are clever. You can submit multiple requests to the pool at the same time. In this instance we pass in an Iterable[HttpRequest]. The returned Iterable[HttpResponse] is reordered using a SortedMap to the same order as the original requests. You can just do a request zip response to line things up:
def exec(requests: Iterable[HttpRequest]): Future[Iterable[Future[HttpResponse]]] = {
  Source(requests.zipWithIndex.toMap)
    .via(pool)
    .runFold(SortedMap[Int, Future[HttpResponse]]()) {
      case (m, (Success(r), idx)) ⇒ m + (idx → Future.successful(r))
      case (m, (Failure(e), idx)) ⇒ m + (idx → Future.failed(e))
    }.map(r ⇒ r.values)
}

Futures of iterable futures are great if you need to unpack things your way. A simpler response can be obtained by just flattening things.
def execFlatten(requests: Iterable[HttpRequest]): Future[Iterable[HttpResponse]] = {
  Source(requests.zipWithIndex.toMap)
    .via(pool)
    .runFold(SortedMap[Int, Future[HttpResponse]]()) {
      case (m, (Success(r), idx)) ⇒ m + (idx → Future.successful(r))
      case (m, (Failure(e), idx)) ⇒ m + (idx → Future.failed(e))
    }.flatMap(r ⇒ Future.sequence(r.values))
}

I have made this gist with all the imports and wrappers to make a client for consuming HTTP services.
A special thanks to @cmbaxter for his neat example.

A: I was a little confused by this myself initially until I read through the docs a few times.  If you are going to use single requests into the pool, no matter how many different places are sharing that same pool, the T that you are supplying (an Int in your case) doesn't matter.  So if you are using Source.single all the time, that key can always be 1 if you really want.
Where it does come into play though, is if a piece of code is going to use the pool and submit multiple requests at once into the pool and wants the responses from all of those requests.  The reason why is that the responses come back in the order they were received from the service that was called, and not the order in which they were supplied to the pool.  Each request could take different amounts of time, so they flow downstream to the Sink in the order they were received back from the pool.
Say we had a service out there that accepted GET requests with a url in the form:
/product/123

Where the 123 part is the id of the product that you wanted to look up.  If I wanted to look up products 1-10 all at once, with separate request for each, this is where the identifier becomes important so that I can correlate each HttpResponse with the product id that it is for.  A simplified code example for this scenario would be as follows:
val requests = for(id <- 1 until 10) yield (HttpRequest(HttpMethods.GET, s"/product/$id"), id)
val responsesMapFut:Future[Map[Int,HttpResponse]] =
  Source(requests).
    via(pool).
    runFold(Map.empty[Int,HttpResponse]){
      case (m, (util.Success(resp), id)) =>
        m ++ Map(id -> resp)

      case (m, (util.Failure(ex), i)) =>
        //Log a failure here probably
          m
    }

When I get my responses in the fold, I also conveniently have the id that each is associated with so I can add them to my Map that is keyed by id.  Without this functionality, I would probably have to do something like parse the body (if it was json) to try and figure out which response was which and that is not ideal, and that doesn't cover the fail case.  In this solution, I know which requests failed because I still get the identifier back.
I hope that clarifies things a bit for you.

A: There is an open ticket for improving akka-http documentation about this. Please
check this example
val pool = Http().cachedHostConnectionPool[Promise[HttpResponse]](host = "google.com", port = 80)
val queue = Source.queue[(HttpRequest, Promise[HttpResponse])](10, OverflowStrategy.dropNew)
  .via(pool)
  .toMat(Sink.foreach({
     case ((Success(resp), p)) => p.success(resp)
    case ((Failure(e), p)) => p.failure(e)
  }))(Keep.left)
  .run

val promise = Promise[HttpResponse]
val request = HttpRequest(uri = "/") -> promise

val response = queue.offer(request).flatMap(buffered => {
  if (buffered) promise.future
  else Future.failed(new RuntimeException())
})


text:
Q: Simplest jQuery, PHP, AJAX, and sqlite example? I'm having a really difficult time understanding how this all works together. I've fiddled for a few days with this and have been unable to come up with any results. I'm trying to fill in a text field in a form, and when the form is submitted, I want to add the text to my sqlite db using ajax.
I understand that you need a $.get call in jquery which is triggered on the form's submit. That seems to work fine as I can trigger js alert boxes from there. However, when I pass the address of the php script which has lines to add to the sqlite db using PDO, nothing is added to the db. However, when I run this php script from using php cli, something will get added to the db.
I seem to be missing an essential step here. I would really appreciate it if someone could bridge this gap for me!
Edit:
As requested by Martin here's some code:
My php generates some list like this with a form in the middle:

hello

        <form action="" method="post">
            <input type=text name="content"/>
        </form>

world

Then my jquery code looks to add whatever is in the textbox right above it on the list does an ajax call. This is inside a $(document).ready(function(){.
 $("form").submit(function() {
    var inputText = $("input").val();
    $.ajax({
        type: "POST",
        url: "add.php",
        data: inputText,
        success: function() {
            $('#formItem').prev().after(
                "
" + inputText + "
"
            )}
    });
});

My add.php file looks like this and it will insert something into my db if I execute the php script on the cli:
<?php
$base = new PDO('sqlite:todo.db');
$sql = $base->prepare("INSERT INTO ThisTable (content, priority) VALUES ('lolololol', 1);");
$sql->execute();
$base = null;
?>

A: Do not forget that HTTP is a stateless protocol. Each HTTP request you make to your webserver is treated the same. This stands for whether the HTTP request was made using AJAX or not.
What I'm trying to say is that AJAX is a client side implementation. All AJAX means is that you can interact with your webserver without having to reload your page. Implementing an AJAX request for the first time in JavaScript is often a brain bender, because the requirement of callbacks and the general asynchronous nature of the interaction makes it difficult to grasp.
On the server however, there should be nothing to worry about. An AJAX request is still an HTTP request, so whether you navigate to http://www.yourwebsite.com/ajax/interact.php?a=1&b=2 in your browser, or make a HTTP GET request using AJAX, your PHP script will still behave exactly the same. If you var_dump($_GET); in either situation, you will get an array whose a and b members equal 1 and 2 respectively.
If you can emulate the AJAX request in your browser successfully by navigating to the URL manually, that's the server work done.
Having established that, your JavaScript should look something like this:
$('#yourForm').bind('submit', function (event) {
    jQuery.get('/ajax/interact.php', 'a=1&b=2', function (response) {
        alert("AJAX request succeeded, response from the server was: " + response);
    });

    event.preventDefault();
});

Once you're confident using jQuery's AJAX methods, you might want to look at methods such as serialize() to help you out, and you can develop your jQuery code to something as follows:
$('form.ajax').live('submit', function (event) {
    var self = $(this);

    jQuery[(self.attr('method') || 'get').toLowerCase()](self.attr('action'), self.serialize(), function (response) {
        alert("AJAX request succeeded, response from the server was: " + response);
    });

    event.preventDefault();
});

Hope this helps :)

A: Your submit function should return false;


text:
Q: using amazon ec2 and binding the IP with instance, but not working I am new to the amazon service, I have installed the node.js and mongodb on the amazon EC2, it all worked on the server side, however, when I wanted to test it, I binded the server instance with IP address, but visiting the server was not successful, I wanted to know what was wrong with it

A: You need to make sure your security group has the right ports open.
To do this, do the following:

*

*Select "Security Groups" in the "NETWORK & SECURITY" section on the left side of the screen.

*Select the security group you have assigned to your EC2 instance.

*Select the "Inbound" tab in the bottom panel.

*Add the port you want to open and the range of addresses that can access it.

For example add this:
Port range: 80
Source:     0.0.0.0/0

In order to open the standard port for HTTP from any IP address.
If you are using a load balancer you will also need to open the port there too:

*

*Select "Load Balancers" in the "NETWORK & SECURITY" section on the left side of the screen.

*Select the Load balancer pointing to your EC2 instance.

*Select the "Listeners" tab in the bottom panel.

*Add the protocol/port you want to open and the protocol/port it will be applied to on the server.

For example add this:
Load Balancer Protocol: HTTP
Load Balancer Port:     80
Instance Protocol:      HTTP
Instance Port:          8080

If you want to redirect incoming port 80 requests to port 8080 on your instance.
If you do this there will need to be a rule on the EC2 instance's security group to allow incoming connections to 8080 from elastic load balancers like this:
Port range: 8080
Source:     amazon-elb/amazon-elb-sg


text:
Q: Why does it print "NO" even after so many conditions attached to it? I found this question on Hyperskill and have been struggling with it. The solution was there too but it has made no sense to me.
In some design style, a 4x4 matrix pattern is considered looking pretty if it doesn't consist of a 2x2 matrix of the same colour. Your task is to write the program that outputs "YES" if the 4x4 matrix is looking pretty, otherwise output "NO".
The input contains 4 lines, each line contains 4 symbols, different symbols represent different colours: W stands for white colour, B - black, R - red, G - green, Y - yellow.
Sample Input 1:
WWWW
BBBB
WWWW
YYYY
Sample Output 1:
YES
Sample Input 2:
BBBB
BWWB
BWWB
BBBB
Sample Output 2:
NO
    String[] arr = new String[4];
    for (int i = 0; i < 4; i++) {
        arr[i] = scanner.next();
    }

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            if (arr[i].charAt(j) == arr[i + 1].charAt(j) && arr[i].charAt(j) == arr[i].charAt(j + 1)
                    && arr[i].charAt(j) == arr[i + 1].charAt(j + 1)) {
                System.out.println("NO");
                return;
            }
        }
    }

    System.out.println("YES");

A: I'll give my solution and explain why it works, I hope this helps.
String x="";
while(scanner.hasNextLine()){
    x+=scanner.nextLine();
}
//The above just combines the entire thing into one string length 16 to make it faster to code

boolean yes= true;
//preseted to true, if a uniformly colored 2by2 is found this becomes false

int[] topLefts = {0,1,2,4,5,6,8,9,10,12,13,14}
//top Left corner of each possible 2 by 2 matrix

for(int i: top Lefts){//iterating over an array
    if(x.charAt(i)==x.charAt(i+1)&&x.charAt(i+4)==x.charAt(i+1)
         &&x.charAt(i+4)==x.charAt(i+5)) yes = false;
}
//This checks if the chars representing each box in the 2by2 are the same
//If even one 2by2 is colored the same, yes becomes true.

if(yes) System.out.println("YES");
else System.out.println("NO");

A: It prints "NO" when all the "many conditions attached to it" are matched.
The program creates an array of 4 strings containing 4 letters. Then it sequentially checks the whole matrix like this:
if (1.1 == 2.1 && 1.1 == 1.2 && 1.1 == 2.2)
    print "NO"

*

*_ .  1. 2 3 4

*1 . X X B B

*2 . X X D B

*3 . B C D B

*4 . B B B B
Then it shifts to the right by 1 and checks again until it reaches the end of the string. After this happens it shifts down by 1 and checks strings 2 and 3 from the beginning. Same for strings 3 and 4.
If the program finds 2x2 matrix of the same characters it considers the whole matrix "unpretty" and prints "NO".

A: Here is my solution. I hope this helps:
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        char[][] c = new char[4][4];
        for (int i = 0; i < 4; i++) {
            c[i] = s.next().toCharArray();
        }
        boolean pretty = true;
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (c[i][j] == c[i][j + 1] &&
                        c[i][j] == c[i + 1][j] &&
                        c[i][j] == c[i + 1][j + 1]) {
                    pretty = false;
                }
            }
        }
        System.out.println(pretty ? "YES" : "NO");
    }
}


text:
Q: Lebesgue Monotone and Dominated Convergence Theorems I have to prove that a function is either Lebesgue integrable or to give counterexample. In particular, the problem is related to almost direct application of Dominated Convergence theorem.
Prove or disprove $$\lim _{n\rightarrow \infty} \int_{[0,1]}\exp\left(\frac{x^2}{n}\right)dx = \int_{[0,1]} \lim _{n\rightarrow \infty} \exp\left(\frac{x^2}{n}\right)dx.$$
I managed to formulate the following proof:
Looking at the function $f(x) = \exp(\frac{x^2}{n}), x \in [0,1], n \geq 1$. It is obvious that it is dominated by the function $g(x) = \exp(x^2)$, since $\exp(\frac{x^2}{n}) \leq \exp(x^2)$. Moreover, $\int _{[0,1]} e^{x^2} dx< +\infty$. From the above-stated theorem it follows that $f(x)$ is Lebesgue Integrable and $\lim _{n\rightarrow \infty} \int_{[0,1]}\exp(\frac{x^2}{n})dx = \int_{[0,1]} \lim _{n\rightarrow \infty} \exp(\frac{x^2}{n})dx$.
My question here are two. First, I am not sure about the dominance of $e^{x^2}$ on that interval. Second, since the function is dominated, it follows that it is Lebesgue integrable ($g(x)$ is integrable). Does it follow that we can interchange the limits as done in the statement?


text:
Q: Is it a good approach to send image separately from database to the client and then fetch it by src tag? I am working on project which needs to display images and text on the browser.I have stored the image in the database in the blob field. I am extracting the blob image from the database and storing it in a byte field. And then using the fileoutputStream to store image in the webcontent folder. To fetch the image i am providing the url of the image to the src tag.
code for DAO class is
          while (rs.next())
            {
                Profile = new UserProfilePojo();
                Profile.setImage1(rs.getBlob(14));
                list.add(Profile);
             }
           rs.close();

code written in pojo class is
       public byte[] getImage()
        {
            return barr;
        }

        public void setImage(Blob image1)
        {
             try
             {
                this.barr =image1.getBytes(1,(int)image1.length());
                byte[] thumbbarr=resizeImageAsJPG(barr,200);
                FileOutputStream fout=new FileOutputStream("E:\\my work\\redirecttest\\WebContent\\"+idm+fname+".jpeg");
                fout.write(thumbbarr);
                fout.close();

             }
             catch(NullPointerException | SQLException | IOException n)
             {
                n.printStackTrace();
             }

on the jsp page it is written as
          <img src="${Profile[0].id}${Profile[0].fname}imp.jpeg">

Although i am able to fetch the image but i have to refresh the webcontent folder after page load and then refresh the page to display the image.
I just wanted to ask that am i able to run this when the project will be uploaded to the remote server. If so then what should be the location of the fileoutputstream. And if it won't work then please give me some suggestion to display image and data simultaneously on the browser from database.
Thanks

A: *

*You can write two separate call for fetch data and image

*Make these two calls as asynchronize

*It solves your problem and data and image will load simultaneously.


text:
Q: If an Image placed into a Grid, the part of image below Grid.Bottom goes lost I'll try to be short. So, in XAML:
<Grid Height="100" Width="100" ClipToBounds="True">
  <Image  Width="100" Height="200" Name="image" Stretch="None" Source="/Test;component image.png" SnapsToDevicePixels="True">
    <Image.RenderTransform>
      <TranslateTransform x:Name="transform" X="0" Y="0"/>
    </Image.RenderTransform>
  </Image>
</Grid>

if now we change image position using transform in code:
transform.Y -= 50;

, the image moves 50 pixels up, but is cut to 100 pixels.
Why we do not see the whole part of the image (y from 50 to 150)?


text:
Q: How is the motion of electron in p orbital? Does an electron in p orbital move around nucleus or move randomly in any individual lobe of p orbital.
if it were to move around nucleus then does p orbital move along with it?

A: As usual, you can re-express the wave-function in momentum space (it's just a Fourier transform away from the spacial wave-function for bound state which is really nice). But that does not tell you how the electron moves anymore than the spacial wave function tells you where it is. Instead, it tells you the probability distribution function for results of measuring the electron's momentum just as the position wave-function gives you the PDF for position measurements.
I'm not an expert in those measurements, but I've found a reference in which the momentum-state of electrons in xenon atoms was measured so sufficient precision to show clear relativistic effects (PDF link) (J.P.D.Cook, J.Mitroy, and E.Weigold, PRL. vol 52. no 13. p1116 1984).
The equivalent measurement for protons in a nucleus is done reasonably often---indeed my dissertation work included extracting the momentum-space PDF's for protons in a few nuclei.

A: In addition to these two excellent answers I'd like to point out that the deceptively smooth surfaces of orbital graphical representations found in text books and web pages, like this excellent rendition of a 2p orbital, below are surfaces where the electron probability density is the same. In no way do they represent paths or 'orbits'.

A: The lobes are regions where you have a non-zero probability of finding an electron. These regions have varying shapes for different types of orbitals. It wouldn't make sense to think that orbitals are actually paths of some sort, where electrons whizz around. You'll know this is wrong if you try to understand the uncertainty principle.
The uncertainty principle prevents us from simultaneously measuring the momentum and position of an electron, up to sufficient accuracy.
Also, read:
What is the uncertainty principle?


text:
Q: SQL Insert over VPN has strange results I am not sure if I'm doing something wrong? Whenever I connect to the office wifi and test my apps registration features, the email section shows a different result from my input. Example if I enter test@test.com and the go into phpmyadmin to check, it will be test@nefiewx.legsq.nl3.gsr.awhoer.net. Is something wrong with my code or do I have to avoid using the wifi?
I had to use a vpn to access my phpmyadmin but I see that some of the address in the URL is similar to what has been entered into the database.
This is my insert code. Thank you
<?php

    include '../configuration/credentials.php';
    if($_SERVER['REQUEST_METHOD']=='POST'){
        $conn = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE);
        if($conn->connect_error){
            die("Connection failed: " . $conn->connect_error);
        }

        $firstname = $_POST["firstname"];
        $lastname = $_POST["lastname"];
        $dateofbirth = $_POST["dateofbirth"];
        $email = $_POST["email"];
        $phone = $_POST["phone"];
        $password = $_POST["password"];

        $firstname = mysqli_real_escape_string($conn,trim($firstname));
        $lastname = mysqli_real_escape_string($conn,trim($lastname));
        $dateofbirth = mysqli_real_escape_string($conn,trim($dateofbirth));
        $email = mysqli_real_escape_string($conn,trim($email));
        $phone = mysqli_real_escape_string($conn,trim($phone));
        $password = mysqli_real_escape_string($conn,trim($password));

        $checkuserexistsquery = "SELECT email, phone FROM users WHERE email='$email' AND phone='$phone'";
        $insertuserquery = "INSERT INTO users (firstname,lastname,dateofbirth,phone,email,password) VALUES ('$firstname','$lastname','$dateofbirth','$phone','$email','$password')";
        $checkuserexistsresults = mysqli_query($conn,$checkuserexistsquery);
        if($checkuserexistsresults===FALSE){
            echo "Check user query failed";
        }else{
            $countcheckuserexistsresults = mysqli_num_rows($checkuserexistsresults);
            if($countcheckuserexistsresults>0){
                //user already exists
                echo "User already exists";
                while($row = $checkuserexistsresults->fetch_assoc()){
                    echo $row['email'];
                    echo $row['phone'];
                }

            }else{
                //user doesn't exist
                $insertuserresults = mysqli_query($conn,$insertuserquery);
                if($insertuserresults===FALSE){
                    echo "Insert user query failed";
                }else{
                    echo "Insert successful";
                }
            }
        }
        mysqli_close($conn);
    }

?>

Hope I can get help with this


text:
Q: I would like to create an multidimensional array of arrays of String from an array of String I have an array of Strings, and I would like to group the content by three to create arrays within the array.
For instance:
var arrayOfStrings = ["a0", "a1", a2", "b0", "b1", "b2"]

And I am looking to achieve:
var multiDimensionalArray = [["a0", "a1", a2"], ["b0", "b1", "b2"]]

Therefore, I am looking for a function that could group the elements within arrayOfStrings in arrays containing 3 elements, in the right order.
Thank you,

A: Try this function:
func makeMultidimensional(a: [String]) -> [[String]] {
    var result: [[String]] = []
    for var i = 0; i < a.count; i += 3 {
        result.append([a[i], a[i + 1], a[i + 2]])
    }
    return result
}

print(makeMultidimensional(arrayOfStrings)) // prints [["a0", "a1", "a2"], ["b0", "b1", "b2"]]

It iterates over array of strings and adds new array of 3 items to the result every time.

A: very simple
NSArray *multiDimensionalArray = @[@[@"a0", @"a1", @"a2"], @[@"b0", @"b1", @"b2"]];

for swift
var multiDimensionalArray = [["a0", "a1", "a2"], ["b0", "b1", "b2"]];

runnig on my system well

A: func makeMultidimensional<T>(input:[T], dimensions:Int) -> [[T]]?
{
    if dimensions <= 0 || count(input) % dimensions > 0 {
        return nil
    }

    return
        input.reduce(([[T]](), [T]())) {
            if 0..<dimensions-1 ~= count($0.1) {
                return ($0.0, $0.1 + [$1])
            }
            else {
                return ($0.0 + [$0.1 + [$1]], [])
            }
        }.0
}


text:
Q: Zapier to create multiple rows in Google Sheet from Tsheets data In a Zapier Zap I am using an an API GET call to Tsheets to grab a list of Timesheets. I would like to split out each time sheet into line items like line items in a Xero invoice because I would like to save item data from each timesheet to its own row in a Google sheet. (Ideally I would like to save the line data directly to a MySQL database but I see that Zapier currently only support Google sheets saving multiple lines at a time.) However I am having no joy.
I suspect one of two issues:

*

*Zapier expects the word lineitems in the response or

*The format of the response is not correct - I seem to have two "results" categories

In my step to Set up Google Sheets Spreadsheet Row I don't get a selection of comma separated items as shown in the example shown on the picture here:
Add an action app that supports line items, and each item will be saved individually
The image is from this page: https://zapier.com/blog/formatter-line-item-automation/ with the caption "Add an action app that supports line items, and each item will be saved individually" For what I get see photo https://cdn.zapier.com/storage/photos/f055dcf11a4b11b86f912f9032780429.png
In the step that returns the data from the API the text response is shown in https://cdn.zapier.com/storage/photos/33129fb7425cfae44be4a81533d6e892.png
and if I return json data it is like this: https://cdn.zapier.com/storage/photos/34da1b98f8941324c35befef8efe350d.png
Can anyone confirm that my suspicions are correct and whether 1 or 2 is the likely culprit.
Is it possible this link Zapier - Catch Hook - JSON Array - Loop over each item in array will lead me to the solution? It looks like it may but I don't see exactly how the writer incorporated it in to his Zap.
Edit: My data returned from the API looks like this:
{
 "results": {
  "timesheets": {
   "11515534": {
    "id": 11515534,
    "user_id": 1260679,
    "jobcode_id": 11974818,
    "start": "2018-07-13T14:58:00+10:00",
    "end": "2018-07-13T14:58:00+10:00",
    "duration": 0,
    "date": "2018-07-13",
    "tz": 10,
    "tz_str": "Australia\/Brisbane",
    "type": "regular",
    "location": "(Brisbane, Queensland, AU?)",
    "on_the_clock": false,
    "locked": 0,
    "notes": "",
    "customfields": {
     "118516": "",
     "121680": "",
     "118530": "",
     "118518": "Field supplies, materials"
    },
    "last_modified": "2018-07-13T04:59:27+00:00",
    "attached_files": [

    ]
   },
   "11515652": {
    "id": 11515652,
    "user_id": 1260679,
    "jobcode_id": 11974830,
    "start": "2018-07-13T14:59:00+10:00",
    "end": "2018-07-13T14:59:00+10:00",
    "duration": 0,
    "date": "2018-07-13",
    "tz": 10,
    "tz_str": "Australia\/Brisbane",
    "type": "regular",
    "location": "(Brisbane, Queensland, AU?)",
    "on_the_clock": false,
    "locked": 0,
    "notes": "",
    "customfields": {
     "118516": "",
     "121680": "",
     "118530": ""
    },
    "last_modified": "2018-07-13T05:00:30+00:00",
    "attached_files": [

    ]
   },
   "39799840": {
    "id": 39799840,
    "user_id": 1260679,
    "jobcode_id": 19280104,
    "start": "2018-10-24T11:45:00+11:00",
    "end": "2018-10-24T12:00:00+11:00",
    "duration": 900,
    "date": "2018-10-24",
    "tz": 11,
    "tz_str": "Australia\/Brisbane",
    "type": "regular",
    "location": "(Sydney, New South Wales, AU?)",
    "on_the_clock": false,
    "locked": 0,
    "notes": "",
    "customfields": {
     "118516": "",
     "121680": "FP - Field plant Installation",
     "118530": "Site cleanup"
    },
    "last_modified": "2018-10-24T05:56:27+00:00",
    "attached_files": [

    ]
   },
   "39801850": {
    "id": 39801850,
    "user_id": 1260679,
    "jobcode_id": 19280204,
    "start": "2018-10-24T12:00:00+11:00",
    "end": "2018-10-24T13:45:00+11:00",
    "duration": 6300,
    "date": "2018-10-24",
    "tz": 11,
    "tz_str": "Australia\/Brisbane",
    "type": "regular",
    "location": "(Sydney, New South Wales, AU?)",
    "on_the_clock": false,
    "locked": 0,
    "notes": "",
    "customfields": {
     "118516": "",
     "121680": "OP - Plant, Vehicles",
     "118530": "Load\/Unload"
    },
    "last_modified": "2018-10-24T05:57:04+00:00",
    "attached_files": [

    ]
   },
   "40192757": {
    "id": 40192757,
    "user_id": 1260679,
    "jobcode_id": 19280110,
    "start": "2018-10-25T08:00:00+11:00",
    "end": "2018-10-25T10:00:00+11:00",
    "duration": 7200,
    "date": "2018-10-25",
    "tz": 11,
    "tz_str": "Australia\/Brisbane",
    "type": "regular",
    "location": "TSheets Android App",
    "on_the_clock": false,
    "locked": 0,
    "notes": "From my mobile",
    "customfields": {
     "118516": "",
     "121680": "FW - Plant Assembly",
     "118530": "Panels"
    },
    "last_modified": "2018-10-24T23:02:56+00:00",
    "attached_files": [

    ]
   },
   "40193033": {
    "id": 40193033,
    "user_id": 1260679,
    "jobcode_id": 19280108,
    "start": "2018-10-25T10:00:00+11:00",
    "end": "2018-10-25T10:00:00+11:00",
    "duration": 0,
    "date": "2018-10-25",
    "tz": 11,
    "tz_str": "Australia\/Brisbane",
    "type": "regular",
    "location": "TSheets Android App",
    "on_the_clock": false,
    "locked": 0,
    "notes": "",
    "customfields": {
     "118516": "",
     "121680": "FW - Plant Assembly",
     "118530": "Panels"
    },
    "last_modified": "2018-10-24T23:06:05+00:00",
    "attached_files": [

    ]
   }
  }
 },
 "more": false
}

And this is my Python code: https://imgur.com/a/8W1X1em

A: Alright so I think I've worked something out for you. The example you provided Zapier - Catch Hook - JSON Array - Loop over each item in array is definitely on the right track, but, because it relies on webhooks, it probably won't work for you unless you can POST the data from your invoicing application.
Note: I code in Python so my examples will be in Python, that said these examples are pretty much code agnostic and can be replicated in Javascript as well.
I setup a dummy Zap to replicate what is happening with your zap currently
# results = requests.get(url, headers=header)
# results = results.json()
# Dummy result data converted to JSON object after API GET request:
results =  {
    "results" : {
        "timesheets" : {
            "timesheet_id_1" : {
                "data_1" : "data",
                "data_2" : "data",
                "data_3" : "data"
                },
            "timesheet_id_2" : {
                "data_1" : "data",
                "data_2" : "data",
                "data_3" : "data"
                },
            "timesheet_id_3" : {
                "data_1" : "data",
                "data_2" : "data",
                "data_3" : "data"
                }
            }
        }
    }

return results

Reading a bit further here in order for Zapier to map line items it needs to receive the data in an array. The above output is a dictionary object, Zapier does map the values in this dictionary to data that can be accessed later, however it maps the entire dictionary which is why you are seeing the output as multiple fields and as is replicated in my output. What you are looking to do is map a subset of the dictionary AND provide each subset as separate outputs.
What you will want to do is loop through the inner fields of the results dictionary object and execute zaps on the nested "timesheet_id_n". To do so we will have to return a list of line items, as stated above line items must be placed into an array. And so my code to achieve this looks like:
# results = requests.get(url, headers=header)
# results = results.json()
# Dummy result data converted to JSON object after API GET request:
results =  {
    "results" : {
        "timesheets" : {
            "timesheet_id_1" : {
                "data_1" : "data",
                "data_2" : "data",
                "data_3" : "data"
                },
            "timesheet_id_2" : {
                "data_1" : "data",
                "data_2" : "data",
                "data_3" : "data"
                },
            "timesheet_id_3" : {
                "data_1" : "data",
                "data_2" : "data",
                "data_3" : "data"
                }
            }
        }
    }

# Container for my line items. Each element in this list will be executed on separately
return_results = []

results = results.get("results")
results = results.get("timesheets")
for item in results:
    return_results.append({"sheet_id" : item, "sheet_data" : results.get(item)})

return return_results

The output of return_results will be an array of dictionary objects. As these dictionary objects are in array Zapier will treat them as line items, additionally because each line item is a dictionary object Zapier will automatically map each value so that they can be independently be used in later action steps. You can see this demonstrated in the output of my trigger zap in the following screenshots:
output 1
output 2
output 3
Hope this helped!


text:
Q: Delete trace flags How can I delete trace flags in Salesforce? My question is in reference to Console Log is not showing anything.

A: From developer console, run this query-
"select id from TraceFlag"
Select the rows and your trace flags wil be deleted.
Make Sure you check "Use Tooling API" before executing the query.

A: Go To Setup -> Monitoring -> Debug Logs.
This will show you all the user trace flags.
You can also do this via the REST Explorer on workbench.
/services/data/v35.0/tooling/sobjects/TraceFlag

A: If you have Spring '16 version Try to following step:

*

*Edit Trace Log and set Time Frame just only change "Start Date" and "End Date".

*Edit "Filter" and Go to "Apex Code" and set "DEBUG" value.

*Use System.debug(Logginglevel.Debug,'Hello'); instead of System.debug('Hello');


text: Q: How do I get a ShockwaveFlashObject to display on a TabControl? I decided to switch a finished project to a tabbed layout, and I got everything working, except that my shockwaveflashobject plays the music from the videos it's executing but no longer the video, it just stays black. Before being put on the tab, the video displayed perfectly. Is there a setting I need to adjust on either the tabcontrol, tabpage, or shockwaveflashobject to allow the video to show?


text:
Q: S parameters measurement inside VNA How does a Vector Network Analyzer (VNA) measure S parameters actually?
Namely we have equations:
\$b_1=S_{11}a_1+S_{12}a_2\$
\$b_2=S_{12}a_1+S_{22}a_2 \$
In theory, if i wanted to calculate scattering parameters I would have to be able to make perfect matching on the source (\$a_1=0\$) and on the load side (\$a_2=0\$).
Unfortunately I do not understand how is this done inside the VNA. If I want to measure scattering parameters of a random network with input and output impedance different than 50ohm, how is in this case achieved \$a_1=0\$ and \$a_2=0\$?

A: Here's a good basic explanation about how a VNA works.
An excerpt follows:

To measure S11 or S21, the switch would route the signal toward Port
  1. The signal first enters a directional device, shown as Directional Device R1 in Figure. This directional device could be a directional
  coupler or bridge. A power divider could also be used here. The
  purpose of this device is to direct a portion of the input signal to a
  reference receiver, shown as Reference Receiver 1. Once the signal
  enters this reference receiver, it's downconverted and ultimately
  processed.
The signal that passes through Directional Device R1 then passes
  through another directional device, shown as Directional Device M1 in
  Figure, before arriving at the DUT. When the signal does arrive at the
  DUT, a portion is reflected back to Port 1 of the VNA and reenters
  Directional Device M1. This device now directs a portion of the
  reflected signal to a measurement receiver, shown as Measurement
  Receiver 1. Next, this signal is downconverted and processed. The VNA
  can then compare the data obtained from Measurement Receiver 1 with
  the data obtained from Reference Receiver 1. This process summarizes
  how S11 is measured.
The signal applied to the DUT also results in a transmitted signal,
  which exits the DUT and enters Port 2 of the VNA. This transmitted
  signal enters another directional device, shown as Directional Device
  M2 in Figure. This device directs a portion of the signal to another
  measurement receiver, shown as Measurement Receiver 2. This signal is
  subsequently downconverted and processed. Now, the VNA can compare the
  data obtained from Measurement Receiver 2 with the data obtained from
  Reference Receiver 1. This process summarizes how S21 is measured.
To measure S22 or S12, the switch would route the signal to Port 2.
  The same process occurs in the opposite direction: The signal first
  enters Directional Device R2 in Figure, which directs a portion of the
  signal to Reference Receiver 2. After entering this reference
  receiver, the signal is downconverted and processed.
The signal that passes through Directional Device R2 then passes
  through Directional Device M2 on its way toward the DUT. After
  arriving at the DUT, a portion of the signal is reflected back to Port
  2 of the VNA and reenters Directional Device M2. Now, a portion of
  this reflected signal is directed to Measurement Receiver 2.
  Afterward, this signal is downconverted and processed. The data
  obtained from Measurement Receiver 2 can then be compared with the
  data obtained from Reference Receiver 2, thus summarizing the S22
  measurement process.
The signal that's transmitted through the DUT enters Port 1 of the
  VNA. This transmitted signal enters Directional Device M1 in Figure,
  which directs a portion of the signal to Measurement Receiver 1. This
  signal is likewise downconverted and processed. The data obtained from
  Measurement Receiver 1 can now be compared with the data obtained from
  Reference Receiver 2, thus summarizing the S12 measurement process.

If you want to obtain S-parameters of a network with input/output impedance other than 50-ohm, these must be recalculated afterwards from the already measured, 50-ohm referenced S-parameters.

A: The HP8505 used directional couplers inside a special module located below the display/sweep/storage/compute unit.


text:
Q: UI Thread and Image processing I have a thread with a priority set to Thread.MIN_PRIORITY + 1 that does some image processing for me (resizing, reading and writing).
I've noticed that whenever that thread is working on an image, animations in my UI thread start to stutter and freeze up.
The priority is low enough such that animations should take a higher priority over that thread, and my CPU certainly isn't starved for resources.
Is there any particular reason this might be happening?

Edit - my thread:
public class WorkerQueue extends Thread {
  public Handler handler;
  int priority = Thread.MIN_PRIORITY + 1;
  private static WorkerQueue self = null;

  public static WorkerQueue getInstance() {
    if (self == null) {
      self = new WorkerQueue();
      self.start();
      self.setPriority(priority);
    }

    return self;
  }

  @Override
  public void run() {
      Looper.prepare();
      handler = new Handler();
      handler.getLooper().getThread().setPriority(priority);
      Looper.loop();
  }

  public synchronized void enqueueTask(final Worker task) {
    handler.post(new Runnable() {
      @Override
      public void run() {
          task.run();
      }
    });
  }
}

A: It may be GC.
Image processing can require a lot of memory allocations and consequent garbage collection. GCs in Android use the mark-and-sweep algorithm which requires the VM to stop execution of your program - you can see how this can cause UI stuttering. See for example this answer and this on-the-money quote:

The main disadvantage of the mark-and-sweep approach is the fact that that normal program
    execution is suspended while the garbage collection algorithm runs. In particular, this
    can be a problem in a program that interacts with a human user or that must satisfy real
    time execution constraints. For example, an interactive application that uses mark-and
    sweep garbage collection becomes unresponsive periodically.

You can confirm whether this is correct by looking at logcat - this prints out a message for every GC, and for that time, the UI thread will be blocked.
If it is GC, then one approach to resolve it would be to look at your memory allocation patterns and see if you can reduce memory churn, maybe by reusing buffers and working memory.

A: LazyList can help you.
This is open source that loading image in other thread and display on UI when it finish

A: You should be using AsyncTask to process and display bitmaps:
https://developer.android.com/training/displaying-bitmaps/process-bitmap.html#async-task
This class specifically designed for this usage, as to why this is happening on your Thread it is probably related to how Android handles GC differently to regular Java applications. This is especially true when dealing with Bitmap objects displayed in a ListView or GridView.


text:
Q: Subclassing PFObject in Swift The Parse documentation for adding properties and methods on PFObject subclasses conveniently skips the Swift syntax in their sample code listing just the Objective-C syntax:
https://parse.com/docs/ios_guide#subclasses-properties/iOS
// Armor.h
@interface Armor : PFObject<PFSubclassing>
+ (NSString *)parseClassName;
@property (retain) NSString *displayName;
@end

// Armor.m
@dynamic displayName;

Has anyone figured out a work around for Swift's lack of dynamic synthesizers in order to implement properties and methods with PFSubclassing? I want to be able to do something like:
class Armor : PFObject, PFSubclassing {
    class func parseClassName() -> String! {
        return "Armor"
    }
}

var armor = Armor()
armor.displayName = "Iron Clad"

A: Swift 1.2
First: Create a swift file and define the subclass. Don't forget to import Parse! (for example Armor)
import Foundation
import Parse

class Armor: PFObject, PFSubclassing {

    // MARK: - PFSubclassing

    override class func initialize() {
        struct Static {
            static var onceToken: dispatch_once_t = 0;
        }
        dispatch_once(&Static.onceToken) {
            self.registerSubclass()
        }
    }

    class func parseClassName() -> String {
        return "Armor"
    }

    // MARK: - Parse Core Properties

    @NSManaged var displayName: String?

}

Note: You can define your properties as optionals. Every "undefined" value inside the Parse Core Manager will be translated to "nil".
Second: Register all subclasses, inside your AppDelegate.swift.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    // MARK: - Parse Setup
    Parse.setApplicationId("YOUR_ID", clientKey: "YOUR_KEY")

    // MARK: - Parse Register Subclasses
    Armor.registerSubclass()

    return true
}

A: Prototypic is correct.  As of right now it won't work with the dynamic attribute, but the code sample doesn't include the registerSubclass Parse recommends, so the code should include it like this:
class Armor : PFObject, PFSubclassing {
    @NSManaged var displayName: String

    override class func load() {
        self.registerSubclass()
    }
    class func parseClassName() -> String! {
        return "Armor"
    }
}

var armor = Armor.object()
armor.displayName = "Iron Clad"

(Note that "override" is required but missing from the Parse documentation.)

A: I had this same problem. Had to add @NSManaged to the properties I wanted saved:
class Armor : PFObject, PFSubclassing {
    @NSManaged var displayName: String

    class func parseClassName() -> String! {
        return "Armor"
    }
}

var armor = Armor.object()
armor.displayName = "Iron Clad"

Hopefully this is resolved in the next update.

A: The solution is to use computed properties instead of stored properties:
class Armor : PFObject, PFSubclassing {

    var displayName: String? {
        get {
            return self["displayName"] as? String
        }
        set {
            self["displayName"] = newValue
        }
    }

    class func parseClassName() -> String {
        return "Armor"
    }
}

A: I ran into the same issue, though I should note that your class definition should look more like this:
class Armor : PFObject, PFSubclassing {
    var displayName: String

    class func parseClassName() -> String! {
        return "Armor"
    }
}

var armor = Armor()
armor.displayName = "Iron Clad"

I tried a few different things without success. It doesn't look like the Parse SDK supports this yet, keep in mind that the current release of the Parse iOS SDK predates the swift announcement. Sounds like they're working on better swift support for an upcoming release though.
Instead, you can still create PFObject subclasses (as you did) and access data with .getObjectForKey("displayName"), or write your own class methods to access this data. The biggest missing piece is really just some convenience methods that the SDK usually creates for you.


text:
Q: 2 domains, each with own SSL certificates pointing to one set of files I have been asked to point a new domain name to my already SSL secured website.  The tricky part is that the new domain is also to have an SSL certificate so that the website can be accessed from both domain names without redirecting.
Is it possible to do this given that each SSL certificate must (I think) have its own IP address.  To further complicate things, the server uses WHM/cPanel to manage accounts and from what I have seen, there doesn't appear to be a way of having one account use 2 IP addresses.
So my question is this:  Is it possible to install an SSL certificate for a new account in cPanel, assign its own IP address etc, and then change the document root so that the new account points to the same document root of another account that is also secured via SSL?  If so, would this work without generating any errors etc in the browser and would cPanel still be able to be used to manage the account without it resetting the document root change?
Server info:
Dedicated CENTOS based server running WHM 11.32.5 (build 13)

A: This is Bryan from Symantec SSL Support. From the certificate perspective, if you would like to secure 2 domains with one SSL certificte, you can enroll for a multi-domain certificate which supports SAN (Subject Alternative Name). All certificate are issued to a FQDN (Fully Qualified Domain Name) and not an IP address as the CAB forum standardization was implented.
Once the certificate is issued, you must install it to the same server the CSR was generated from. If you are using CPanel/WHM, the interface creates a private key when you generate the CSR. The private key is needed during the SSL installation to match with the public key which is issued by the CA (Certificate Authority). The CA only issues the public key, not the private key, so it's important you have the private key on the server.
So, if you have a multi-domain or SAN certificate installed on one domain on one server and you want the second domain on the second server to work, you will need the same private key and public key from the first server installed on that second server. Otherwise, you will get a mismatch error. Any type of IP, domain or document root configuration needs to referenced by the server's documentation.

A: I believe you should be able to set up 2 different websites each with it's own ip address but pointing to the same document root. If you are using using cpanel, there is a good chance it's on top of apache, and I know apache will allow this.

A: For more information visit Symantec SSL


text:
Q: Machine learning clustering algorithms: k-means and Gaussian mixtures Suppose we clustered a set of N data points using two different clustering algorithms: k-means and Gaussian mixtures. In both cases we obtained 5 clusters and in both cases the centers of the clusters are exactly the same. Can 3 points that are assigned to different clusters in the kmeans solution be assigned to the same cluster in the Gaussian mixture solution? If no, explain. If so, sketch an example or explain in 1-2 sentences.

A: From my understanding of Machine Learning theory, Gaussian Mixture Model(GMM) and K-Means differ in the fundamental setting that K-Means is a Hard Clustering Algorithm, while GMM is a Soft Clustering Algorithm. K-Means will assign every point to a cluster whereas GMM will give you a probability distribution as to what is the probability of the point to belong in each of the 5 clusters. Furthermore, this also depends on the kind of parameters are you using for GMM. It could be possible for GMM to produce clusters somewhat similar to K-Means if you use a constant variance.
Now, I am not sure about this because you need to provide more information on how you are picking Hard Clusters from GMM and how are you calculating the cluster centers. If you are just making a hard assignment from GMM based on the cluster which has the maximum probability, then it could be possible that they get assigned to the same clusters. In my opinion this will be possible only if the data points are easily separable and your GMM is assuming constant variance.
As far as the cluster centers go, it depends on the way you are calculating them. If you are using the mean vectors obtained from GMM, then it is very very unlikely that K-Means and GMM will give you same cluster centers. On the other hand if you are first generating Hard clusters like mentioned above and then calculating the centers yourself, then it could be possible that they have the same centers when the hard clustering for all your points is the same in both K-Means and GMM.
I think you should provide more information about the way you are doing this, so that the community members can better help you. Also you should also identify your use case well and decide whether you need Hard or Soft Clustering. Choose GMM only if you desire soft clustering and/or you have a prior belief that your data points have been generated from Gaussian Distributions for each cluster.


text:
Q: Ошибка сборки пустого кода При сборке кода пример.сс
int main() {
    return 0;
}

командой
$ gcc -o пример пример.cc && ./пример

выводится ошибка
undefined reference to '__gxx_personality_v0'
В чем может быть проблема?
A: Или переименовать файл в пример.c. Напоминаю:

*

*C-файлы по умолчанию имеют расширение .c.

*C++-файлы по умолчанию имеют расширение .cc, .cp, .cxx, .cpp, .c++, .C.

Варианты таких извращений, как компиляция GCC, а затем линковка G++, опустим.
Еще способ - использование ключа -x компилятора, который задает используемый язык.

A: Нужно так:
$ g++ -o пример пример.cc && ./пример


text:
Q: Problem organizing code in asp.net MVC 2 I'm new to MVC and I borrow a book from library yesterday on asp.net MVC 2.
I'm a bit confused about what kind of code should be included in Model, view and controller.  I was working on user input validation from the book and if I understand correctly, it seems they declare variables in "Model", validating user input in "Controller" and display the web page in "View".
Model:
-Declaring variables
e.g:
class Contact:
public string Name { get; set; }
public string EmailAddress { get; set; }

Views:
-Contain HTML, HTML Helper code, displaying contents and use variables from "Model"
e.g:
<%: Html.TextBoxFor(model => model.Name) %>
<%: Html.ValidationMessageFor(model => model.Name) %>

Controller:
-"Playing"/"Manipulating" variables from Model + Call "View" to display web page at the end (return View()). (Validating user input for this example)
e.g:
if (String.IsNullOrEmpty(contact.Name))
   ModelState.AddModelError("Name", "Please enter your name.");

I'm not sure but it seems to me that "Controller" is the "heavy coding" part to me.  On the other hand, "View" is the good old HTML, markup that display the web site and "Model" is a place that store data (declaring variables for example.)
Please let me know whether I'm on the right direction.
Thanks :)

A:
I'm not sure but it seems to me that "Controller" is the "heavy coding" part to me

You should avoid having fat controllers. In fact the controller might depend on a service layer which contains the business logic of you application. This service layer could itself depend on repositories performing the data access (simple CRUD operations) on the models. So the controller would simply invoke a business operation call on the service layer to fetch/update the model and then pass a view model to the view in order to display it.

A: I am also new to MVC and first thing i did when i started was to view most of the talks given by Scott Hanselman and Phill Haack. So you might try this one: [http://channel9.msdn.com/blogs/matthijs/aspnet-mvc-2-basics-introduction-by-scott-hanselman][1]
[1]: http://channel9.msdn.com/blogs/matthijs/aspnet-mvc-2-basics-introduction-by-scott-hanselman to get started. From what i got so for, Darin is right. Try to avoid fat controllers and work with a repository for your model. Also, I noticed that for simple validation (required, maximum string length and such) it is preferred to use DataAnnotion on the model... So your Contact model might look like this:
class Contact:
[Required]
public string Name { get; set; }
public string EmailAddress { get; set; }

This will make the Name property required on Edit/Create Views.