text:
Q: Sql left join and show result Welcome,
I have 2 tables int_client AND int_client_bank.
In first important columns: client_id, firstname, lastname, country, email, status.
In the second: client_id, status.
I need to display all records: firstname, lastname, country, e-mail WHERE status='25' of the first column (except those records where client_id occurs in the second table).
If client_id occurs in the second table is skipping statuses of the first column, and displays only status='25' in secound table.
Sb can help me?
edit:
SELECT firstname, lastname, country, email, COALESCE(b.status, a.status) status
 FROM int_client a
 LEFT JOIN int_client_back b USING (client_id)
 WHERE
  (b.status IS NULL and a.status='25')
  OR b.status IS NOT NULL;

This is good code, but i need show only records there have status='25' in column B, and if a.client_id != b.client_id, i need show records there have status='25' in column A
Sb, help?

A: LEFT JOIN with COALESCE() should do:
SELECT firstname, lastname, country, email, COALESCE(b.status, a.status) status
 FROM int_client a
 LEFT JOIN int_client_back b USING (client_id)
 WHERE
  (b.status IS NULL and a.status='25')
  OR b.status IS NOT NULL;

A: This select query should work:
SELECT t1.first_name,t1.last_name,t1.country,t1.email FROM int_client AS t1, int_client_bank AS t2
WHERE t1.client_id = t2.client_id AND t1.status = 25;

A: Below is the query which will do the trick for you.
SELECT client_id, firstname, lastname, country, email, status FROM int_client as ic LEFT JOIN int_client_back icb ON ic.client_id=icb.client_id WHERE ic.status=25

A: If I understand correctly, you want all records from int_client where status is "25".  However, if another status exists in int_client_bank, then you want to show that status.
select c.first_name, c.last_name, c.email, c.country,
       coalesce(cb.status, c.status)
from int_client c left join
     int_client_bank cb
     on cb.client_id = c.client_id
where c.status = 25;

A: SELECT DISTINCT firstname, lastname, country, email,
a.status as status_a, b.status as status_b, if(b.status is NULL, a.status, b.status) as final_status
 FROM int_client a
 LEFT JOIN int_client_bank b USING (client_id)
 WHERE
  if(b.status is NULL, a.status, b.status) = '25'


text:
Q: Read lines from a file with variable line endings in Go How can I read lines from a file where the line endings are carriage return (CR), newline (NL), or both?
The PDF specification allows lines to end with CR, LF, or CRLF.

*

*bufio.Reader.ReadString() and bufio.Reader.ReadBytes() allow a single delimiter byte.

*bufio.Scanner.Scan() handles \n optionally preceded by \r, but not a lone \r.

The end-of-line marker is one optional carriage return followed by one mandatory newline.

Do I need to write my own function that uses bufio.Reader.ReadByte()?

A: You can write custom bufio.SplitFunc for bufio.Scanner. E.g:
// Mostly bufio.ScanLines code:
func ScanPDFLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
    if atEOF && len(data) == 0 {
        return 0, nil, nil
    }
    if i := bytes.IndexAny(data, "\r\n"); i >= 0 {
        if data[i] == '\n' {
            // We have a line terminated by single newline.
            return i + 1, data[0:i], nil
        }
        advance = i + 1
        if len(data) > i+1 && data[i+1] == '\n' {
            advance += 1
        }
        return advance, data[0:i], nil
    }
    // If we're at EOF, we have a final, non-terminated line. Return it.
    if atEOF {
        return len(data), data, nil
    }
    // Request more data.
    return 0, nil, nil
}

And use it like:
scan := bufio.NewScanner(r)
scan.Split(ScanPDFLines)

A: While reading an older Mac generated file with only CR line endings, I ran into regression for the edge case where if CRLF is split across the buffer boundary, the accepted answer will treat them as separate line terminators. You basically need to exit early and request more data if the buffer ends with CR. This seems to solve it.
func scanLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
    if atEOF && len(data) == 0 {
        return 0, nil, nil
    }
    if i := bytes.IndexAny(data, "\r\n"); i >= 0 {
        if data[i] == '\n' {
            // We have a line terminated by single newline.
            return i + 1, data[0:i], nil
        }
        // We have a line terminated by carriage return at the end of the buffer.
        if !atEOF && len(data) == i+1 {
            return 0, nil, nil
        }
        advance = i + 1
        if len(data) > i+1 && data[i+1] == '\n' {
            advance += 1
        }
        return advance, data[0:i], nil
    }
    // If we're at EOF, we have a final, non-terminated line. Return it.
    if atEOF {
        return len(data), data, nil
    }
    // Request more data.
    return 0, nil, nil
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I test in Production Facebook page with test data showing for tester of the app only I have developed a chatbot which is only used to send a private message to user who leave specific key word on our particular facebook post on my Facebook page.
I want to have a pre-production test in my Production page. Please let me know how can I test with data not displaying to public but only display to the tester of the app and the page admin.


text:
Q: assign index dependant value to each index in numpy array I want to center multi-dimensional data in a n x m matrix (<class 'numpy.matrixlib.defmatrix.matrix'>), let's say X . I defined a new array ones(645), lets say centVector to produce the mean for every row in matrix X. And now I want to iterate every row in X, compute the mean and assign this value to the corresponding index in centVector. Isn't this possible in a single row in scipy/numpy? I am not used to this language and think about something like:
centVector = ones(645)
for key, val in X:
    centVector[key] = centVector[key] * (val.sum/val.size)

Afterwards I just need to subtract the mean in every Row:
X = X - centVector

How can I simplify this?
EDIT: And besides, the above code is not actually working - for a key-value loop I need something like enumerate(X). And I am not sure if X - centVector is returning the proper solution.

A: First, some example data:
>>> import numpy as np
>>> X = np.matrix(np.arange(25).reshape((5,5)))
>>> print X
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]]

numpy conveniently has a mean function. By default however, it'll give you the mean over all the values in the array. Since you want the mean of each row, you need to specify  the axis of the operation:
>>> np.mean(X, axis=1)
matrix([[  2.],
        [  7.],
        [ 12.],
        [ 17.],
        [ 22.]])

Note that axis=1 says: find the mean along the columns (for each row), where 0 = rows and 1 = columns (and so on). Now, you can subtract this mean from your X, as you did originally.
Unsolicited advice
Usually, it's best to avoid the matrix class (see docs). If you remove the np.matrix call from the example data, then you get a normal numpy array.
Unfortunately, in this particular case, using an array slightly complicates things because np.mean will return a 1D array:
>>> X = np.arange(25).reshape((5,5))
>>> r_means = np.mean(X, axis=1)
>>> print r_means
[  2.   7.  12.  17.  22.]

If you try to subtract this from X, r_means gets broadcast to a row vector, instead of a column vector:
>>> X - r_means
array([[ -2.,  -6., -10., -14., -18.],
       [  3.,  -1.,  -5.,  -9., -13.],
       [  8.,   4.,   0.,  -4.,  -8.],
       [ 13.,   9.,   5.,   1.,  -3.],
       [ 18.,  14.,  10.,   6.,   2.]])

So, you'll have to reshape the 1D array into an N x 1 column vector:
>>> X - r_means.reshape((-1, 1))
array([[-2., -1.,  0.,  1.,  2.],
       [-2., -1.,  0.,  1.,  2.],
       [-2., -1.,  0.,  1.,  2.],
       [-2., -1.,  0.,  1.,  2.],
       [-2., -1.,  0.,  1.,  2.]])

The -1 passed to reshape tells numpy to figure out this dimension based on the original array shape and the rest of the dimensions of the new array. Alternatively, you could have reshaped the array using r_means[:, np.newaxis].


text:
Q: How to control the distortion level of the google reCaptcha image gem for rails 3 I am using the rails recaptach gem https://github.com/ambethia/recaptcha
The default image that comes is very highly distorted and I would like to make it a little simpler to read. Is there a way that we could control the distortion level of the image that is shown up? any configuration options available in the gem. I have asked the same question as well, however, have not got any reply yet.
Also, if we can control the number of text items that appear. By default its 2, can we control it to make it one instead via this gem.
Any help is greatly appreciated.

A: The recaptcha gem is a wrapper around the the reCAPTCHA library itself, so you're very much limited by what that library offers in the way of customisation. The gem can't expose elements for customisation that aren't supported by the underlying library.
As you'll see from the documentation at https://developers.google.com/recaptcha/docs/customization, customisation is pretty much confined to the visual appearance around the CAPTCHA codes – you can't customise the code appearance themselves.
If the reCAPTCHA style isn't to your taste, it's possible that there are other forms of reverse Turing test that will be more to your liking.


text:
Q: Is Spring's QueryByExampleExecutor usable with Projections Is there a way to return Iterable< IUser > where IUser is a projection of User entity.
Example<User> userExample = Example.of(user, userMatcher);
Iterable<User> foundUsers = userRepository.findAll(userExample, Sort.by("createdAt").descending());

A: Instead of sticking with spring data auto generated query and response type.
You can create your own HQL query by using @Query annotation so that you can except your custom return type.
Example :
@Query(" select user from User as user where user.userName like %:username% order by createdAt desc")
public List<User> findAllByUserName(String username);


text:
Q: Javascript DOM manipulation, Each click creates a new li element I have an app with a few buttons, and every button has an element, button one has a "banana" and button 2 has an "apple", when the user clicks on those buttons, a new li element should be added to a list. Here is a JSFiddle with an example of the problem I'm running into:
https://jsfiddle.net/ejha3q94/
Only 1 li is created with every click and the elements are just added on that same li.
 var newElement = document.createElement("li");
 var newElText = document.createTextNode ("");

 document.getElementById("itemOne").addEventListener("click", function() {
  newElText = document.createTextNode("Banana");
   document.getElementById("list").appendChild(newElement).appendChild(newElText);

 });

 document.getElementById("itemTwo").addEventListener("click", function() {
  newElText = document.createTextNode("Apple");
    document.getElementById("list").appendChild(newElement).appendChild(newElText);

  });

How can I make it so every click is a new li element using only Javascript?

A: You can't reuse elements by reassigning them. You have to create a new element each time you wish to insert a new element into the DOM.
This solution creates a generic function addItem for your procedure. You can see all the element creation and DOM manipulation in one place.

// element references
var list = document.getElementById('list');
var appleBtn = document.getElementById('apple');
var bananaBtn = document.getElementById('banana');

// DOM manipulating function
function addItem(listElem, text) {
  var li = document.createElement('li');
  var textNode = document.createTextNode(text);
  listElem.appendChild(li).appendChild(textNode);
}

// event listeners
appleBtn.addEventListener('click', function(event) {
  addItem(list, 'apple');
});
bananaBtn.addEventListener('click', function(event) {
  addItem(list, 'banana');
});

<button id="apple">Apple</button>
<button id="banana">Banana</button>

But even repeating addItem(list, *) can get repetitious too. Plus, we don't necessarily need one event listener per button. Wouldn't it be nice if we could just use a single event listener to handle all of the cases?
The solution below uses a data-* attribute to store each button's contribution to the list. Then, using event delegation we handle all buttons with a single event listener (function).

// element references
var list = document.getElementById('list');
var buttons = document.getElementById('buttons');

// single #buttons event delegate
buttons.addEventListener('click', function(event) {
  // event.target contains the element that was clicked
  var item = event.target.dataset.item;
  if (item === undefined) return false;
  var li = document.createElement('li');
  var textNode = document.createTextNode(item);
  list.appendChild(li).appendChild(textNode);
});

  <button data-item="apple">Apple</button>
  <button data-item="banana">Banana</button>
  <button data-item="orange">Orange</button>
  <button data-item="grape">Grape</button>
  <button data-item="plum">Plum</button>

A: Make sure that var newElement and newElText is created or cloned on every click instead of referenced: https://jsfiddle.net/ejha3q94/2/
Otherwise it won't create a new list element but modifies the existing list element every time.
document.getElementById("itemOne").addEventListener("click", function() {
    var newElement = document.createElement("li");
    var newElText = document.createTextNode("Banana");
    document.getElementById("list").appendChild(newElement).appendChild(newElText);
});

document.getElementById("itemTwo").addEventListener("click", function() {
    var newElement = document.createElement("li");
    var newElText = document.createTextNode("Apple");
    document.getElementById("list").appendChild(newElement).appendChild(newElText);
});

A: You can use document.querySelectorAll() with selector "[id^=item]"; iterate elements using for..of loop; create the elements within click event handler; append #text node to li element using HTMLElement.dataset before appending li element to ul element

jsfiddle https://jsfiddle.net/ejha3q94/4/

A: There can only be a single newElText node. If you append it multiple times, it will just be moved. You should clone it manually:

var newElement = document.createElement("li");
var list = document.getElementById("list");
document.getElementById("itemOne").addEventListener("click", function() {
  var newElText = document.createTextNode("Banana");
  list.appendChild(newElement.cloneNode(false)).appendChild(newElText);
});
document.getElementById("itemTwo").addEventListener("click", function() {
  var newElText = document.createTextNode("Apple");
  list.appendChild(newElement.cloneNode(false)).appendChild(newElText);
});


text:
Q: Can we give Gradle plugin in code base as JAR file Can we give Gradle plugin in code base as JAR file, rather than downloading from Internet ?
Below plugin I am using in my application.
plugins {

    id 'red.sukun1899.wanko' version '1.0.7'
    id 'net.saliman.properties' version '1.5.1'
    id 'io.errorlab.gradle.vault' version '0.1.0'
}

Please guide me how can i use as JAR file rather than download all the time from internet.


text:
Q: Are fundamental groups and skeletal categories related? For any two topological spaces $X, Y$ that are homotopy-equivalent with $f: X\to Y$, we have that their fundamental groups $\pi_1(X, x_0) \cong \pi_1(Y, f(x_0))$ are isomorphic. Similarly, we have that for any equivalent categories $\mathbb{C} \simeq \mathbb{D}$ that their skeletal categories are isomorphic $\text{sk}\ \mathbb{C} \cong \text{sk}\ \mathbb{D}$. The construction of both skeletal categories and the fundamental group relates objects to their equivalence classes, so is there some "deeper" relation between these two?
Now, I know that one of these statements relates homotopies and group isomorphisms, while the other relates category equivalences and category isomorphisms, so the analogy may break down at some point. It's just that since Category Theory grew off of Algebraic Topology, and that most of the notation and concepts are very similar in both subjects that I wondered whether there is a connection between these two.

A: There is a simple relation between the two.
If $X$ is path-connected, then the fundamental group of $X$, expressed as a 1-element category, is a skeleton of its fundamental groupoid.
The more relevant analogy here is the preorder associated with a category, which is an example of $(-1)$-truncation. Given a category $C$, we can give the objects a pre-order by writing $a \leq b$ iff there is some morphism $a \to b$. We can then quotient the objects by equivalence to get a partial order.
Analogously, the fundamental groupoid is a higher-order truncation of the fundamental 2-groupoid. In the fundamental 2-groupoid, we also have paths between paths. But when we pass to the fundamental groupoid, we suppress the paths between between paths (or, equivalently, pretend that there is at most one path between paths). We can then quotient the paths by equivalence to get a set of paths between any two points up to homotopy equivalence.


text:
Q: Prolog If statement fact I want to state a unique fact in my Prolog data base to change the outcome of my if statement.
My code is as follows:
suspect(Killer, mrBoddy) :-
    affair(mrBoddy, Y),
    married(X,Y),
    write('Killer= '),
    write(X), nl;
    greedy(X),
    write('Killer= '),
    write(X), nl.

The output is
?- suspect(Killer, mrBoddy).
Killer= profPlum

true ? ;
Killer= colMustard

yes

My Facts
affair(mrBoddy, msGreen).
affair(mrBoddy,missScarlet).
married(profPlum, msGreen).

rich(mrBoddy).
greedy(colMustard).
motive_to_kill_affair(profPlum).
motive_to_kill_greed(colMustard).

I want to add a fact that will change the output to only one "Killer". Doesn't matter who it is. How could I achieve this?


text:
Q: How to add class in angular using ng-repeat for adding a review purposes?
This is what i have so far, my data(retrieved via get: method expecting json)  and the html part will do the ng-repeat for review in reviews; adding class filled. But it just add's filled to all. Open to any suggestion's, like this directives as well.
$scope.data = [{
    "_id": "56aa6f601c5e0d520e4a54ca",
    "index": 0,
    "picture": " http://fillmurray.com/75/75",
    "rating": 5,
    "name": "Kelli Alexander",
    "comment": "Eu mollit officia enim cupidatat consequat. Elit ex reprehenderit sint veniam Lorem in ad non exercitation fugiat dolore esse ex. Exercitation occaecat ut dolore voluptate labore minim eiusmod ea quis. Consectetur deserunt id minim exercitation eu sit Lorem laboris. Nulla minim ea fugiat ex sit pariatur adipisicing incididunt officia nisi. Incididunt dolore consectetur sunt quis irure in. Labore ipsum deserunt dolor quis incididunt occaecat minim mollit mollit incididunt officia reprehenderit ut ipsum.\r\n",
    "registered": "2014-06-09T04:11:13 +05:00",
}, {
    "_id": "56aa6f602b63c7bef8e4ad4b",
    "index": 1,
    "picture": " http://fillmurray.com/75/75",
    "rating": 3,
    "name": "Hopper Buck",
    "comment": "Eiusmod aliquip pariatur consequat et eu laboris. Mollit mollit reprehenderit enim sint incididunt dolor aliqua Lorem commodo aute aliqua aliquip. Et pariatur exercitation culpa irure occaecat. Elit id laboris quis culpa quis aute dolor consequat excepteur officia enim ullamco enim elit. Sunt pariatur reprehenderit quis commodo velit enim exercitation mollit.\r\n",
    "registered": "2014-04-11T03:22:35 +05:00",
}, {
    "_id": "56aa6f60fe9bae6d177b7137",
    "index": 2,
    "picture": " http://fillmurray.com/75/75",
    "rating": 2,
    "name": "Vera Mcfadden",
    "comment": "Ipsum consectetur ipsum velit do nostrud officia excepteur. Laboris qui consectetur officia culpa est mollit ex. Ea qui proident ut aute consequat ea proident quis duis.\r\n",
    "registered": "2015-10-05T12:46:04 +05:00",
}, {
    "_id": "56aa6f60d60a0c80b87fa3ed",
    "index": 3,
    "picture": " http://fillmurray.com/75/75",
    "rating": 3,
    "name": "Howard Christensen",
    "comment": "Pariatur commodo dolore ipsum aute cupidatat ipsum adipisicing voluptate sit voluptate commodo. Sint cupidatat eu sunt Lorem ad. Enim ex irure sit tempor culpa. Culpa cillum commodo duis laborum pariatur do aliqua culpa commodo consectetur eiusmod. Sit esse aute ad cupidatat do et Lorem ut tempor cillum. Proident consequat reprehenderit nulla excepteur elit ea exercitation adipisicing. Excepteur ullamco tempor ipsum ipsum Lorem tempor fugiat amet Lorem.\r\n",
    "registered": "2015-09-04T10:09:25 +05:00",
}, {
    "_id": "56aa6f60ba2f88f333bba049",
    "index": 4,
    "picture": " http://fillmurray.com/75/75",
    "rating": 3,
    "name": "Burke Reilly",
    "comment": "Do ex culpa adipisicing commodo ut aute consectetur cillum est eiusmod ut minim excepteur. Reprehenderit ex incididunt occaecat commodo magna est commodo reprehenderit non ullamco. Lorem proident velit incididunt nostrud labore mollit laboris nostrud ut commodo fugiat. Sint aliqua laborum laboris mollit magna proident. Veniam anim ad in aute sunt reprehenderit ullamco nisi sunt velit consequat amet. Nisi ea amet in labore.\r\n",
    "registered": "2014-11-18T09:16:38 +06:00",
}, {
    "_id": "56aa6f6061f6d711988c5521",
    "index": 5,
    "picture": " http://fillmurray.com/75/75",
    "rating": 3,
    "name": "Robyn Douglas",
    "comment": "Proident cupidatat incididunt ut anim sit excepteur esse ad veniam reprehenderit. Nisi dolor labore occaecat irure reprehenderit deserunt aute amet. Magna veniam sint velit esse laboris officia est in ipsum tempor voluptate quis sunt. Proident eu duis elit aliqua non anim consectetur consequat ut do.\r\n",
    "registered": "2015-12-18T01:58:11 +06:00",
}, {
    "_id": "56aa6f6018d679470f9c656c",
    "index": 6,
    "picture": " http://fillmurray.com/75/75",
    "rating": 4,
    "name": "Avery Merritt",
    "comment": "Adipisicing proident consequat do aliquip. Anim magna deserunt ut culpa. In exercitation tempor quis in nisi nisi et velit nulla ea. Anim consequat mollit incididunt velit labore culpa qui consectetur in. Aliqua reprehenderit nostrud officia aliquip officia id amet ut proident aliquip adipisicing. Sunt incididunt minim et minim.\r\n",
    "registered": "2015-12-18T01:58:11 +06:00",
}];

add max 5 circles :

Edit: tried this and is correct but its in reverse order.
 <i class="ion-ios-circle-filled" ng-class="{filled: $index < 5 - review.rating}" ng-repeat="n in range(5) track by $index">

A: you could probably do a comparison in the ng-class here to achieve what you're looking for:
<i class="ion-ios-circle-filled" ng-class="{filled: $index < review.rating}" ng-repeat="n in range(5) track by $index">


text:
Q: Редактирование текста как в google docs Как можно сделать ввод текста с возможностью форматирования (жирный/курсив/цветной итд...) как это реализовано в google docs.
Чтоб пользователю не приходилось расставлять теги html
P.S. Так-как обычный input такое не поддерживает, у меня в голове только решение - обрабатывать ввод c помощью js, и внедрять в html.  Если это единственное решение, как тогда сделать курсор, чтоб он еще попадал в нужное место при клике.. А выделение надеюсь как-то осилю.

A: Чтоб написать самому:
Вот то что нужно:
https://learn.javascript.ru/range-textrange-selection
Там есть все, в том числе и определить куда в тексте кликнул пользователь, чтоб поставить туда курсор ввода. Там конечно моей задачи не рассматривается.. но я другого решения, извините не вижу
Чтоб НЕ написать самому:
А так Vladimir Gamalian (оставил комментарий в теме) прав: "Гуглится как Javascript WYSIWYG" - это если нужно готовое решение!
Вот список готовых работ под самыми разными лицензиями
https://github.com/cheeaun/mooeditable/wiki/Javascript-WYSIWYG-editors
Вообще полно инфы в интернете, оказывается, и под лицензией Mit тоже есть


text:
Q: What's deprecated in KitWare's guide to Finding libraries in CMake? I need to write a CMake FindXYZ-type module. Googling, I've found this guide:
https://cmake.org/Wiki/CMake:How_To_Find_Libraries
from Kitware, but there's a disclaimer about it being deprecated. Which significant changes, if any, have been made to how these modules are written over the past, say, 6-7 years?

A: Yes, the CMake Wiki's content now officially moved inside CMake's documentation, so the "deprecated" warning is more a general one that the Wiki is no longer looked after.
In your case the main part of CMake Wiki: How To Find Libraries moved to CMake's documentation cmake-packages chapter.
What has changed?
I think the major change over the last years is what Stephen Kelly in his "Embracing Modern CMake" talk called:

Modern CMake packages define IMPORTED targets
find_package(Foo REQUIRED)

add_executable(hello main.cpp)
target_link_libraries(hello
    Foo::Core
)

The same basic tint is found in CMake's documentation  cmake-developer - Find Modules chapter:

The traditional approach is to use variables for everything, including libraries and executables. This is what most of the existing find modules provided by CMake do.
The more modern approach is to behave as much like config file packages files as possible, by providing imported target. This has the advantage of propagating Transitive Usage Requirements to consumers.

Details
You can see this "modern approach" as an extension of the previous methods (like in "FindZLIB: Add imported target and documentation" commit).
What should definitely be there (the core of all "Find Modules" for years now) is the find_package_handle_standard_args() macro.
 This macro is build around the ..._FOUND cached variable handling.
My recommendation would be to concentrate on the imported targets and the ..._INCLUDE_DIRS and ..._LIBRARIES variables are just a side effect of having to cache your find results somewhere.

A: No, I don't think there's any significant changes. I still use it.
I think they are just trying to get you to look at their other documentation, like find_package.
In writing new Find modules, I normally just look at the other
FindXXX.cmake
 as examples/templates and go from there.


text:
Q: How to auto close user account dropdown menu after few seconds How I can close user account dropdown menu after few seconds after click on icon?
When I use these code setTimeout works only 1 times, when I refresh the browser.
Someone can help?

User email

line 1

line 2

line 3

A: You can try it using this code.

const toggleMenu = document.querySelector('.menu');
function menuToggle() {
    toggleMenu.classList.toggle('active')
    setTimeout(removeToggle, 4000);
}
function removeToggle() {
    toggleMenu.classList.remove('active')
}

A: Put your setTimeout inside the function menuToggle
function menuToggle() {
  setTimeout(function(){
      const toggleMenu = document.querySelector('.menu');
      toggleMenu.classList.toggle('active')
    }, 4000);
}


text:
Q: Use case diagram extend or include for admin relation to customer order So basically i'm wondering if I'm thinking correctly. In an e-commerce environment does the order of a product have a relationship to the admin use case of managing orders? Once an order has gone through  is the admin then going to be able to see the order through a relationship between the 2 use cases. I've provided an image for reference in my case.Here is the image

A: TL;DR
No, there is no extension here. Those will be two separate UCs.
Explanation
First let me focus on the goal of the Use Case diagram. This diagram is intended to show functions of the system and users (or more broadly actors) engaged in those functions. It is not used to show how data flow through the system or what are steps of the processing. There are other diagrams to do that.
As a rule of thumb, something is a good use case if you can log into the system, perform only the action of this single use case and then log out.
Extends (Includes works pretty much the same, it's just stronger) means that when you run the extended UC you can include the other use case as well. In other words in your specific example when Customer logs to E-Commerce to place an order he can while placing an order also choose to additionally receive and manage order (BTW I would reconsider this UC, you probably have few separate UCs here like Complete order, Dispatch order or Reject order) in which case additionally an Admin is need. Even if you invert Extends, it's still not what you want. Those two UC happen totally separately even though the order processed by Admin is the very same one placed by Customer.

A: I did not search for too long but I did not find a case where a given use case, associated to one actor, is extended or included by another use case, associated to another actors.
A use case describe the usage of your system by a given actor so you do not have any other actor involved.


text:
Q: Is there a way to redefine malloc at link time on Windows? I would like to replace the default malloc at link time to use a custom malloc. But when I try to redefine malloc in my program, I get this error:
MSVCRT.lib(MSVCR80.dll) : error LNK2005: _malloc already defined in test.lib(test.obj)

This works perfectly on any Unix, and it works on Windows with most functions, but not with malloc. How can I do this? And what is different with malloc that disallow overriding it?
I know I could replace every call to malloc with my custom malloc, or use a macro to do this, but I would rather not modify every third party library.

A: I think it depends in which order you link the files. I think you need to link your custom function first, then the import library.

A: There is really good discussion of how hard this is here:
http://benjamin.smedbergs.us/blog/2008-01-10/patching-the-windows-crt/
Apparently, you need to patch the CRT
Edit: actually, a MS employee gave the technique in the discussion.  You need to move your malloc to a lib, and then link it before the CRT
"he also mentions that if you link your malloc as a lib before the CRT (i.e. make sure to turn on 'ignore default libs' and explictly include the CRT), you'll get what you want, and can redistribute this lib without problems."

A: From version 3.0 Firefox uses a custom allocator (AFAIR jmalloc) -- you could check how they did it. I read that they had some problems with it. You may check this blog post.

A: What about defining malloc=_custom_malloc in the project makefile.
Than adding a file such as:
my_memory.c
#undef malloc
#undef calloc
...
void *_custom_malloc(int size) { return jmalloc(size); }
void *_custom_calloc(int size) { return jcalloc(size); }
...


text:
Q: Ordering output by custom order with GridDB I am trying to run a ORDER BY query but I want the output to be ordered according to a custom scheme.
In SQL this is often done with a case system, but depending on the DB there are also other implementations.
How would I achieve the sorting explained below with GridDB?
Lets assume my GridDB lists all the animals that are in a zoo and how many of each live there,
I would like all the animals of which there are 4 or more, by size, smallest first (mouse), largest last (elephant).
Things I tried:
$query = $col->query("SELECT * WHERE count >= 4 ORDER BY CASE
                        WHEN 'mouse' THEN 1
                        WHEN 'cat' THEN 2
                        WHEN  'dog' THEN 3
                        WHEN  'elephant' THEN 4
                        ELSE 5
                        END");

$query = $col->query("SELECT * WHERE count >= 4 ORDER BY FIND_IN_SET(animal, 'mouse, cat, dog, elephant')";

In either case one receives an error that the input is not valid syntax.

A: GridDB's TQL doesn't support ORDER BY CASE but with multi-query you can perform this operation quickly/efficiently.
Please excuse my Python:
   queries=[]
   queries.append(col.query("select * where count >=4 and animal = 'mouse'"))
   queries.append(col.query("select * where count >=4 and animal = 'cat'"))
   queries.append(col.query("select * where count >=4 and animal = 'dog'"))
   queries.append(col.query("select * where count >=4 and animal = 'elephant'"))

   store.fetch_all(queries)

   for q in queries:
       rs = q.get_row_set()
       while rs.has_next():
           print(rs.next())

A: You can use now use ORDER BY CASE with the V4.5CE SQL interface:
CREATE TABLE myTable (
  key INTEGER PRIMARY KEY,
  animal STRING,
  count INTEGER
);

INSERT INTO myTable VALUES(1, 'cat', 4); INSERT INTO myTable VALUES(2, 'dog', 1); INSERT INTO myTable VALUES(3, 'mouse', 6);

SELECT * FROM myTable WHERE count >= 4 ORDER BY CASE animal
                        WHEN 'mouse' THEN 1
                        WHEN 'cat' THEN 2
                        WHEN  'dog' THEN 3
                        WHEN  'elephant' THEN 4
                        ELSE 5
                        END;
-->
key | animal | count
----+--------+------
  3 | mouse  |     6
  1 | cat    |     4


text:
Q: Camel cluster on kubernetes using Hazelcast error when rolling updates I have an embedded Hazelcast instance that I configure to use k8s API (service discovery) and I use Route Policy to have an Active/Passive clustered FTP reader.
I have min of 3 instances in the cluster. My rolling updates are first adding a new instance before replacing old ones.
I am getting this error when I do rolling updates.
[com.hazelcast.core.HazelcastInstanceNotActiveException - Hazelcast instance is not active!]com.hazelcast.core.HazelcastInstanceNotActiveException: Hazelcast instance is not active!
at com.hazelcast.spi.impl.AbstractDistributedObject.throwNotActiveException(AbstractDistributedObject.java:115)
at com.hazelcast.spi.impl.AbstractDistributedObject.lifecycleCheck(AbstractDistributedObject.java:110)
at com.hazelcast.spi.impl.AbstractDistributedObject.getNodeEngine(AbstractDistributedObject.java:104)
at com.hazelcast.map.impl.proxy.MapProxyImpl.tryLock(MapProxyImpl.java:500)
at org.apache.camel.component.hazelcast.policy.HazelcastRoutePolicy.acquireLeadership(HazelcastRoutePolicy.java:296)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)

It looks like the Hazelcast instance is stopping before the camel has a chance to elect a new leader for this cluster.
Questions:

*

*Do I need to add the instance to the camel component when I create a Hazelcast instance in code?

*How do I control the shutdown order to make sure the lock is migrated to a different node?

*Any code examples for how this should be done?

I am using the Hazelcast kubernetes plugin
    Config config = new Config();

    config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);

    config
        .getNetworkConfig()
        .getJoin()
        .getKubernetesConfig()
        .setEnabled(true)
        .setProperty("namespace", "aaaa")
        .setProperty("service-name", "bbbb");

    HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(config);

I then create a route policy
    HazelcastRoutePolicy routePolicy = new HazelcastRoutePolicy(hz);
    routePolicy.setLockMapName("etl");
    routePolicy.setLockKey("etl-key");
    routePolicy.setLockValue("etl-value");
    routePolicy.setTryLockTimeout(5, TimeUnit.SECONDS);
    context.getRegistry().bind("cluster", routePolicy);

and use this policy in my route:
        .routePolicyRef("cluster")

Thanks in advance :)
EDIT
I think this is related, I always have double the number of Hazelcast nodes as Pods.
I start a 3 containers cluster and see 6 in logs.
Members {size:6, ver:6} [
      Member [172.30.0.3]:5701 - ae3861bb-3f77-427e-ada1-5b669c89776f
      Member [172.30.0.4]:5701 - cd7741f0-a3b1-4883-a8bb-c3fecaad6b14 this
      Member [172.30.0.2]:5701 - 3403bbee-8141-4572-bbd2-4379bf452e79
      Member [172.30.0.3]:5702 - 0d48a691-b166-4d29-9b34-77b93be4370b
      Member [172.30.0.4]:5702 - d36f0342-730e-40e6-a18e-cf72d9d4b574
      Member [172.30.0.2]:5702 - f3644c6c-afe7-4f48-9832-b604830b6955

A: If you use Hazelcast with Rolling Upgrade (or scaling down), you should configure graceful shutdown as described here:

*

*Kubernetes Rolling Upgrade and Scaling

*Hazelcast Docker Graceful Shutdown


text:
Q: Compare Two strings in O(logn) with some pre-processing and assumption I am thinking if it possible to compare two string in O(log n) with some pre-processing and assumption.
My pre-processing is to store the string as the AVL tree where the value of the node is the Ascii value of the character. Since I am using the same algorithm to build the AVL tree, two idental string will have the same AVL tree.
As a result, we may not need to check all nodes. Is it possible to only check O(log n) nodes to know if two trees are the same? If not, will it be possible to build another tree structure that achieve my goal?

A: If you're building an AVL tree where the value of the node is the ASCII value of the character, then wouldn't "STOP" and "SPOT" result in the same AVL tree? What if the strings were "aaaaaaaa" and "aaaaaaab"? Those strings are 8 characters long. Which three characters will you compare? Would that work for "aaaabaaa", as well?
The answer is no. Your idea won't work.


text:
Q: how to save and retrive data from the last run of an android application? I have to create a small android application for my college course work which presents 10 maths problems and take answers from users to calculate the score.
The program is supposed to have a main screen with "new game" button and a "continue" button.
How do I program to save data during the application run and retrieve them from the stored place to continue from that point if the user presses continue button? (what sort of a method I should be looking at for such a task? )
Thanks in advance.

A: Just use preference to store and retrieve value in the code.Here is the snippet
//Set Preference
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor;
prefsEditor = myPrefs.edit();
prefsEditor.putString("REFKEY", valuetobestored);
prefsEditor.commit();

//Get Preferenece
SharedPreferences myPrefs;
myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String output=myPrefs.getString("REFKEY", "");

A: It depends on the kind of data you want to store. If it is really basic, you would want to store them as name value pairs in the onSaveInstanceState method or as Preferences in the onPause method, if it is a bit more complex, you might want to store in a SQLiteDB.
The guide says

the method onSaveInstanceState(Bundle) is called before placing the
  activity in such a background state, allowing you to save away any
  dynamic instance state in your activity into the given Bundle, to be
  later received in onCreate(Bundle) if the activity needs to be
  re-created. See the Process Lifecycle section for more information on
  how the lifecycle of a process is tied to the activities it is
  hosting. Note that it is important to save persistent data in
  onPause() instead of onSaveInstanceState(Bundle) because the latter is
  not part of the lifecycle callbacks, so will not be called in every
  situation as described in its documentation.

This is how you save data in onSaveInstanceState: Saving Android Activity state using Save Instance State
This is how you can save data in Preferences: Making data persistent in android

A: Just use SharedPreferences. Check this link out for more details. 2 early in the morning to give you an example of my own :P
How do I get the SharedPreferences from a PreferenceActivity in Android?
The preferences lasts as long as the application is installed on the device. One you delete if , it removes them as well.
Another cool thing you might want to know, if you want to check if your app is at it's  first run, EVER, then just check a boolean value stored (or not stored on the first run) on the device. :) If there isn't one (it will return the default value), then just change it's value to true or something and as you'll check it every time the app runs, you'll know it's not the first run :)
Hope this helps, cheers.

A: May be this is not the best solution.. but this is a way to get required functionality..
in on click of continue button put this code
finish();
                 Intent k=new Intent(youractivitytivity.this,youractivity.class);
k.putExtra("qno",x+1)<---- next question number to appear on screen(x is the present question number)
k.putExtra("score",bool)<--- if the answer is right or wrong)
                 startActivity(k);

then in the on create of your activity.. get extras and check which question you have to display...
i think you have an array of 10 questions..


text:
Q: Local maximality implies global maximality?
Let $S$ be the unit sphere in $\mathbb R^n.$ For a given $A\in\operatorname{M}_n(\mathbb R),$ define $f:\mathbb R^n\mapsto\mathbb R$ as $f(x)=\langle x,Ax\rangle.$
  Suppose $a\in S$ is an element such that $\exists \delta\gt0,$ with $f(a)\ge f(x), \forall x\in\mathbb R^n$ such that $\|x-a\|\lt\delta.$ Then is it true that $f(a)\ge f(x), \forall x\in S?$

Intuitively, I think this must fail, as we are only given a local maximiser. However, I failed to find a counter-example, nor a proof.
If I can calculate the derivative of $f,$ maybe I can conclude that $f$ has no more than one local maximiser, which thus must be a global maximiser. But I do not know about $f'$, either.
Thanks very much in advance for any hint or reference.

A: I am assuming that $S = \{x | \|x\|=1\}$ and that $a$ is such that $f(a) \ge f(x)$ for all $x \in B(a,\delta) \cap S$, where $\delta >0$. Then $f$ is a global maximizer on $S$.
Since $\langle x, Ax \rangle = \langle Ax , x\rangle = \langle x, A^Tx \rangle = \langle x, {1 \over 2} (A+A^T)x \rangle$, we may assume that $A$ is symmetric, hence orthogonally diagonalizable. In particular, we may assume $f(x) = \sum_k \lambda_k x_k^2$, where the $ \lambda_k$ are real.
Suppose $x$ is such that $x_i \neq 0$ and there is some $\lambda_j > \lambda_i$. Write $(x_i,x_j) = r (\cos \theta, \sin \theta)$, where $r = \sqrt{x_i^2 + x_j^2}$. Note that $\cos \theta \neq 0$ and hence $|\sin \theta| \neq 1$.
We have
\begin{eqnarray}
f(x) &=&\sum_{k \notin \{i,j\}} \lambda_k x_k^2 + \lambda_i x_i^2+ \lambda_j x_j^2 \\
&=&  \sum_{k \notin \{i,j\}} \lambda_k x_k^2 + r(\lambda_i \cos^2 \theta + \lambda_i \sin^2 \theta) \\
&=&  \sum_{k \notin \{i,j\}} \lambda_k x_k^2 + r(\lambda_i + (\lambda_j- \lambda_i) \sin^2 \theta)
\end{eqnarray}
Consequently we can find some $\theta'$ arbitrarily close to $\theta$ such that
$f(x') > f(x)$, where $x'$ is the same as $x$ except with $x_i,y_i$ replaced by $r (\cos \theta', \sin \theta')$, and $\|x'\|=\|x\| = 1$.
Consequently, if $a$ is a local maximizer of $f$, $a$ must be a unit eigenvector corresponding to the maximum eigenvalue $\lambda_\max$. Then it follows that $f(a) = \lambda_\max $, and since $f(x) \le \lambda_\max$ whenever $x \in S$, it follows that $f(x) \le f(a)$ for all $x \in S$.


text:
Q: Flutter Annoying Black Stripe at the bottom of screen I have made a Login Screen, the problem is I am getting a black stripe at the end of my screen, while in my code I have'nt added any color at the end, moreover I thought that this might because of sizebox, but even if I remove it, nothing really happens. Moreover at first when I was creating and debugging this code, there was no such line and once everything is done, it started appearing at the bottom..
Here's the output picture:

Here's my UI code:
 Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
    body: SingleChildScrollView(
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 40),
        width: double.infinity,
        decoration: BoxDecoration(
            gradient: LinearGradient(begin: Alignment.topCenter, colors: [
          Colors.black,
          Colors.black87,
          Color(0xff0a0b0d),
        ])),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            SizedBox(
              height: 70,
            ),
            Padding(
              padding: EdgeInsets.all(20),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    "Login",
                    style: TextStyle(color: Colors.white, fontSize: 30,fontFamily: 'Signatra'),
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Text(
                    "Welcome to T Post",
                    style: TextStyle(color: Colors.white, fontSize: 30, fontFamily: 'Signatra'),
                  ),
                ],
              ),
            ),
            Container(
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(50),
                    topRight: Radius.circular(50),
                  )),
              child: Padding(
                padding: EdgeInsets.all(20),
                child: Column(
                  children: <Widget>[
                    Container(
                      padding: EdgeInsets.all(20),
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(10),
                          boxShadow: [
                            BoxShadow(
                              color: Color.fromARGB(220, 90, 30, 10),
                              blurRadius: 20,
                              offset: Offset(0, 10),
                            )
                          ]),
                      child: Column(
                        children: <Widget>[
                          Container(
                            decoration: BoxDecoration(
                                border: Border(
                                    bottom: BorderSide(
                                        color: Colors.grey.shade200))),
                            child: TextField(
                              decoration: InputDecoration(
                                hintText: "Phone Number",
                                hintStyle: TextStyle(color: Colors.grey),
                                border: InputBorder.none,
                              ),
                            ),
                          ),
                          Container(
                            decoration: BoxDecoration(
                                border: Border(
                                    bottom: BorderSide(
                                        color: Colors.grey.shade200))),
                            child: TextField(
                              decoration: InputDecoration(
                                hintText: "Password",
                                hintStyle: TextStyle(color: Colors.grey),
                                border: InputBorder.none,
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 40,
                    ),
                    Text(
                      "Forget Password",
                      style: TextStyle(color: Colors.grey),
                    ),
                    SizedBox(
                      height: 40,
                    ),
                    Container(
                      height: 50,
                      margin: EdgeInsets.symmetric(horizontal: 50),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(50),
                        color: Color(0xff0a0b0d),
                      ),
                      child: Center(
                        child: Text(
                          "Login",
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 18,
                              fontWeight: FontWeight.bold),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: 60,
                    ),
                    Text(
                      "Continue with social media",
                      style: TextStyle(
                        color: Colors.grey,
                      ),
                    ),
                    SizedBox(
                      height: 20,
                    ),
                    Row(
                      children: <Widget>[
                        Expanded(
                          child: Container(
                            height: 50,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(50),
                              color: Colors.blueAccent,
                            ),
                            child: Center(
                              child: Text(
                                "Twitter",
                                style: TextStyle(color: Colors.white),
                              ),
                            ),
                          ),
                        ),
                        SizedBox(
                          width: 30,
                        ),
                        Expanded(
                          child: Container(
                            height: 50,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(50),
                              color: Colors.deepPurpleAccent,
                            ),
                            child: Center(
                              child: Text(
                                "Skype",
                                style: TextStyle(color: Colors.white),
                              ),
                            ),
                          ),
                        ),
                        SizedBox(
                          width: 30,
                        ),
                      ],
                    )
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    ),
  ),

    );
  }

A: It looks like you have containers wrapping their content, so it appears like a stripe.  Try having one of the containers filling the screen instead of wrapping the content.  What happens when you make the following change to the SingleChildScrollView?
Container(
    padding: EdgeInsets.symmetric(vertical: 40),
    width: double.infinity,
    height: MediaQuery.of(context).size.height,  // <<<<<< Add this line.
    decoration: BoxDecoration(
        gradient: LinearGradient(begin: Alignment.topCenter, colors: [
      Colors.black,
      Colors.black87,
      Color(0xff0a0b0d),
    ]))


text:
Q: Samsung J5 and TAB4 refuse native debugging Using Android Studio 1.5.1 in a win7 ultimate sp1 and in a Mac mini 10.11.3 fully updated.
I have a number of Samsung units for testing my app development incl JNI and this week my private Samsung Galaxy S4mini (Kitkat) died physically so I got a new Samsung Galaxy J5.
However the J5 (lollipop) refuses to be debugged in native mode. Does not matter the app, fails also with Hello-JNI.
The J5 also have some odd java bugs like in a AlertDialog (with stacked linear layouts) linearLayout.addView(anotherLinearLayout); just crashes?? Also I have an odd JNI-bug, I like to debug. And both "bugs" works without crashing in my other devices my old S4mini and a TAB4 Kitkat and a TAB3 and S3mini.
However I found the TAB4 also refuses native debugging. Both the TAB4 and the J5 works fine in (non-native) app-debugging. All other units debugs native no problem, just switching unit on the cable and run, works fine?
Is there something missing in the J5 and TAB4 for making native debugging available?

The debug error message is (I tried everything I could find):
Target device: samsung-sm_j500fn-0af60463
Installing APK: C:\Users\JB\AndroidStudioProjects\HelloJNI\app\build\outputs\apk\app-all-debug.apk
Uploading file to: /data/local/tmp/com.example.hellojni
Installing com.example.hellojni
DEVICE SHELL COMMAND: pm install -r "/data/local/tmp/com.example.hellojni"
    pkg: /data/local/tmp/com.example.hellojni
Success

Launching application: com.example.hellojni/com.example.hellojni.HelloJni.
DEVICE SHELL COMMAND: am start -D -n "com.example.hellojni/com.example.hellojni.HelloJni" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.hellojni/.HelloJni }

Warning: debug info can be unavailable. Please close other application using ADB: Monitor, DDMS, Eclipse
Restart ADB integration and try again
Waiting for process: com.example.hellojni
DEVICE SHELL COMMAND: run-as com.example.hellojni mkdir /data/data/com.example.hellojni/lldb
Error while launching debug server on device: com.android.tools.ndk.run.DebuggerContext$StartServerException: java.lang.IllegalStateException: run-as is broken (please see http://b.android.com/187955 for details)


text:
Q: Converting a String to a List of Dictionaries I have one column of a pandas dataframe whose elements are of the form '[{"foo": 42, "bar": "conversion"}]'.  That is, they are all lists of dictionaries (of varying length) but saved in the dataframe as strings.
Is there a way to make this column contain actual lists of dictionaries?

A: import json
json.loads('[{"foo": 42, "bar": "conversion"}]')
# [{u'bar': u'conversion', u'foo': 42}]

This will only work if your strings are in json format, but the example is so it's very likely that it will work.


text:
Q: What is the most appropriate way to convert nibbles to a u64? I am trying to learn Rust and decided to write a program that converts a hex string into a u64.
Currently, I have parsed the string into a vector of u8 values, each representing four bits (or "nibble"). I wrote the following code to take a Vec<u8> and return a corresponding u64. It works (as far as my testing shows), but I am not sure if it is the "appropriate" way in Rust to go about doing this.
fn convert_nibbles_to_u64(values: &Vec<u8>) -> u64 {
    // We need to turn this buffer into a u64 now
    let mut temp:u64 = 0;
    for i in values {
        temp = temp << 4;

        unsafe {
            // We need to unsafely convert a u8 to a u64. Note that
            // the host endian-ness will matter here.
            use std::mem;
            let i_64_buffer = [0u8,0u8,0u8,0u8,0u8,0u8,0u8,i.clone()];
            let i_64 = mem::transmute::<[u8; 8], u64>(i_64_buffer);
            let i_64_be = u64::from_be(i_64);
            temp = temp | i_64_be;
        }
    }
    return temp;
}

I suppose the main issue I don't know how else to cast a u8 to a u64 value. Could you comment on ways to improve or write the code in a more idiomatic, Rust-like style?
EDIT:
I have tried the following (unsuccessful) alternatives to the unsafe block:
Or'ing with i as a u64:
temp = temp | i as u64;
------
Compiler error:
main.rs:115:23: 115:31 error: non-scalar cast: `&u8` as `u64`
main.rs:115         temp = temp | i as u64;

Or'ing with i directly:
temp = temp | i;
------
Compiler error:
main.rs:115:16: 115:24 error: the trait `core::ops::BitOr<&u8>` is not implemented for the type `u64` [E0277]
main.rs:115         temp = temp | i;

A: Your issue is a simple one: for i in values, where values is of type &Vec<u8>, iterates over references to each value; that is, i is of type &u8. Oring and adding and such with references doesn't make sense; you need to dereference it, getting the underlying u8. The easiest way of doing this is writing it into the for loop's pattern (for the for grammar is for PATTERN in EXPRESSION, refer to the documentation on patterns for more explanation if you need it; for this simple case, for &x in y { … } basically means for x in y { let x = *x; … }):
fn convert_nibbles_to_u64(values: &[u8]) -> u64 {
    let mut out = 0;
    for &i in values {
        out = out << 4 | i as u64;
    }
    out
}

The whole form of a loop can be collapsed using Iterator.fold, too, like this:
fn convert_nibbles_to_u64(values: &[u8]) -> u64 {
    values.iter().fold(0, |x, &i| x << 4 | i as u64)
}


text:
Q: CakePHP tmp folder access for mod_php and mod_fcgid CakePHP needs to change owner of temp folders like this:
http://book.cakephp.org/2.0/en/getting-started.html#tmp-directory-permissions
# chown -R username app/tmp

When I use Apache with mod_php, username must be apache.
When I use Apache with mod_fcgid, username must be myswebsiteuser.
I need to make some tryouts to check the performance of the fcgid vs. mod_php. So When I switch the php type, I get tons of errors in minutes. I run script that changes owner of the folder from apache to mywebsiteuser, remove old temporary files and wait cakephp to create new ones with new user. I need to combine old and new log files also.
It seems like chown permits to set user groups. Is there a way to set "tmp" folders so they can be used in mod_php and mod_fcgid, without switching owners ?
(I own the server, it has CentOS and it has only one website. Also Plesk 11.5)
Similar: What are the right ownership & permissions to the CakePHP app/tmp folder for production?

A: This is not a cakephp issue, neither apache. You just need a basic linux file/folder permissions understanding.
Quick and dirty solution: Set tmp to 777 (chmod 777 <path>/tmp) it will solve your problem for your tests.
Then do some reading on the above subject and reset permissions/ownership accordingly.

A: First create a group:
# groupadd mygroup

Open the groups file:
# vi /etc/group

In the last line there exists a line like this:
mygroup:x:510:

Look for the username of the mod_fcgid, if you website is mywebsite.com, then possibly it is "mywebsite".
You need to add 2 users to your new group "apache" and "mywebsite".
mygroup:x:510:apache,mywebsite

Now change owner and mod of the folders like this:
# chown -R mywebsite:mygrup /var/www/vhosts/mywebsite.com/httpdocs/app/tmp/
# chmod -R 664 /var/www/vhosts/mywebsite.com/httpdocs/app/tmp/

Now temp folder is both writeable by mod_php (apache) mod_fcgid (mywebsite).


text:
Q: Use of $ in postfix expression
*

*The value of the postfix expression 8 3 4 + - 3 8 2 / + * 2 $ 3 + is:
a) 17
b) 131
c) 64
d) 52

*Prefix of A-B/C*D$E is:
a)-/*$ACBDE
b)-ABCD*$DE
c)-A/B*C*$DE
d)-A/BC*$DE
Can anybody explain to me how to solve these expressions when a $ sign is present? What does this dollar sign indicate?

A: In this case, I am certain the operator is exponentiation.
  8 3 4 + - 3 8 2 / + * 2 $ 3 + is:

  8 3 4 + - = 1

  3 8 2 / + = 7

  1 7 * = 7

  7 2 $ = 49

  49 3 + = 52.

Or maybe
  7 2 $ = 128

  128 3 + = 131.

Depends on how your instructor defined the operator.

A: Actually, dollar operator is called exponentiation operator. Means if i say A$B so it means B in the power of A. Ex. 3$2=3*3=9.
             Also this exponentiation operator has highest precedence among all operators.

:Precedence.
    EXPONENTIATION($)
    MULTIPLICATION/DIVISION
    ADDITION/SUBTRACTION.
So in above given two questions correct answer is
1. 131
2. -/*$ABCDE
Best of Luck.  :)


text:
Q: Django on Heroku, url template tag causes 'ParseResult' object not callable Does anyone know what Heroku changes on deploy?  I've got a local dev machine setup with Ubuntu 11.10, and my project installed into a venv, all packages managed via pip.  The corresponding requirements.txt is in my repo, and is sent to Heroku on push.  Both my local machine and Heroku are accessing the same RDS instance on AWS.
Running the Django dev server locally (manage.py runserver) results in a working page.  Attempting to run (via my Procfile) the dev server on Heroku causes an error in the template at {% url foobar %} as follows:
Caught TypeError while rendering: 'ParseResult' object is not callable

My requirements.txt contains the following:
Django==1.3.1
MySQL-python==1.2.3
PIL==1.1.7
amqplib==1.0.2
anyjson==0.3.1
boto==2.2.2
celery==2.5.1
distribute==0.6.24
django-celery==2.5.1
django-kombu==0.9.4
django-picklefield==0.2.0
django-piston==0.2.3
gevent==0.13.6
greenlet==0.3.4
gunicorn==0.14.2
httplib2==0.7.4
kombu==2.1.1
python-dateutil==1.5
wsgiref==0.1.2
zencoder==0.4

Anyone have an idea?

A: While I'm afraid I can't offer much insight into your issue, with regard to the question "Does anyone know what Heroku changes on deploy?", then for Django apps, it's just the following:
Heroku DB config appended to your settings.py
This just overrides your existing DATABASES setting by pulling in the DATABASE_URL in the environment and parsing it accordingly.
Basic Procfile autogenerated if you don't already have one
Don't rely on this, as the generated Procfile just uses the Django development server (replace it with e.g. one running gunicorn), but it's all you need to get a basic project started.
5MB (free) shared database added
This just ensures your app will have a database to access.

Now, I don't see how any of those would cause the problem you experience, but you seem to have that sorted which is good.

A: I had a similar problem (actually in the urls.py, not in the template rendering) while using django-piston.  I managed to fix it by changing
from django.conf.urls.defaults import url

to
from django.conf.urls.defaults import url as django_url

and then changing all the url() directives in urlpatterns to django_url().
This also fixed up the template thing I was seeing in admin pages.  I'm not sure if this is the same thing, but might be a fruitful inquiry.


text:
Q: Existence of root of nondegenerate operator Let $A: C^n \to C^n$ has zero kernel. How one can prove that there is operator $B$ such that $A = B^k$? (I don't know if k is limited somehow or not)

A: Consider the case where you have an operator $T \colon \mathbb{C}^k \rightarrow \mathbb{C}^k$ of the form $T = \lambda I + N$ where $\lambda \neq 0$ and $N$ is nilpotent. Motivated by the Taylor series for $(1+x)^{\alpha}$, you can define
$$ B = \lambda^{\frac{1}{k}} \sum_{n=0}^{\infty} { \frac{1}{k} \choose n} \left( \frac{N}{\lambda} \right)^{n} $$
where $\lambda^{\frac{1}{k}}$ is any complex $k$-root of $\lambda$. The operator $B$ is well-defined as $N$ is nilpotent and you can verify that $B^k = T$.
The general case follows by Jordan decomposition as every invertible operator $A \colon \mathbb{C}^n \rightarrow \mathbb{C}^n$ is conjugate to a direct sum of operators of the form above.


text:
Q: Como gerenciar o funcionamento e falha na execução das Spiders? Estou desenvolvendo um módulo para obter informações sobre as spiders que rodam no sistema da empresa. Segue abaixo o modelo onde guardamos o início das operações e o job. Gostaria de validar se os jobs foram realizados da maneira correta e preencher o resto dos campos.
models.py
# -*- coding: utf-8 -*-

from django.db import models

class CrawlerJob(models.Model):

    job_id = models.CharField(verbose_name=u'ID da Tarefa', editable=False,
                              max_length=255, blank=True, null=True,)

    job_started_dt = models.DateTimeField(
        verbose_name=u'data de início da tarefa', blank=True, null=True,
        editable=False)

    job_has_errors = models.BooleanField(
        verbose_name=u'erros?', blank=True, default=False)

    job_finished_dt = models.DateTimeField(
        verbose_name=u'data de fim da tarefa', blank=True, null=True,
        editable=False)

tasks.py
# -*- coding: utf-8 -*-

from app.models import CrawlerJob
from celery.decorators import periodic_task
from celery.task.schedules import crontab
from django.utils import timezone
from scrapyd_api import ScrapydAPI
import celery
import datetime

scrapy_url = 'http://localhost:6800'
scrapyd = ScrapydAPI(scrapy_url)

@periodic_task(run_every=(crontab(hour="6-19")))
def funcao_assincrona():

    crj = CrawlerJob()
    job_id = scrapyd.schedule('projeto_X', 'rodar_spider')
    crj.job_id = job_id
    crj.job_started_dt = timezone.now()
    crj.save()

Uma ideia para isso era ter acesso aos logs do sistema e checar pelo json gerado como o que segue abaixo.
2015-01-09 12:40:18-0300 [spider] INFO: Closing spider (finished)
2015-01-09 12:40:18-0300 [spider] INFO: Stored jsonlines feed (11 items) in: scrapyd_build/items/projeto_X/spider/5a3bc7ca980e11e4b396600308991ea6.jl
2015-01-09 12:40:18-0300 [spider] INFO: Dumping Scrapy stats:
    {'downloader/request_bytes': 2448,
     'downloader/request_count': 5,
     'downloader/request_method_count/GET': 3,
     'downloader/request_method_count/POST': 2,
     'downloader/response_bytes': 28218,
     'downloader/response_count': 5,
     'downloader/response_status_count/200': 5,
     'finish_reason': 'finished',
     'finish_time': datetime.datetime(2015, 1, 9, 15, 40, 18, 93445),
     'item_scraped_count': 11,
     'log_count/DEBUG': 19,
     'log_count/INFO': 8,
     'request_depth_max': 4,
     'response_received_count': 5,
     'scheduler/dequeued': 5,
     'scheduler/dequeued/memory': 5,
     'scheduler/enqueued': 5,
     'scheduler/enqueued/memory': 5,
     'start_time': datetime.datetime(2015, 1, 9, 15, 40, 13, 90020)}
2015-01-09 12:40:18-0300 [spider] INFO: Spider closed (finished)

Existe alguma maneira mais prática de obter essas informações? E no caso de ocorrer erros obter as mensagens geradas por possíveis erros ou exceções?

A: Bem, como quem tem acesso aos stats de verdade é o Scrapy (o scrapyd só roda os jobs), acho que o caminho pra resolver esse problema é usar um spider middleware que envie as estatísticas do crawler para a sua aplicação quando o spider terminar.
Você também precisará duma maneira de atualizar a aplicação num spider do Scrapy, e acionar isso no spider middleware.
Eis um rascunho:
from scrapy import signals
import os

class UpdateStatsMiddleware(object):
    def __init__(self, crawler):
        self.crawler = crawler
        # registra método close_spider como callback para o sinal spider_closed
        crawler.signals.connect(self.close_spider, signals.spider_closed)

    @classmethod
    def from_crawler(cls, crawler):
        return cls(crawler)

    def close_spider(self, spider, reason):
        spider.log('Finishing spider with reason: %s' % reason)
        stats = self.crawler.stats.get_stats()
        jobid = self.get_jobid()
        self.update_job_stats(jobid, stats)

    def get_jobid(self):
        """Gets jobid through scrapyd's SCRAPY_JOB env variable"""
        return os.environ['SCRAPY_JOB']

    def update_job_stats(self, jobid, stats):
        # TODO: atualizar as stats na aplicação Django
        pass

Ler mais:

*

*Spider middleware

*Scrapy Signals


text:
Q: Create Dataframes columns with values from another DF and update matched in R My data looks like this.
df1:

df2:

expected output:

Can anyone help with the functions in R if available.

A: Does this answer:
> df1 %>% inner_join(df2 %>% count(name, language) %>%
+                      pivot_wider(names_from = language, values_from = n, values_fill = 0) %>%
+                                                               relocate(c(c, java, r, q, k, t, s)))
Joining, by = "name"
# A tibble: 3 x 9
  name   var1     c  java     r     q     k     t     s
  <chr> <dbl> <int> <int> <int> <int> <int> <int> <int>
1 a         7     1     0     0     1     0     0     1
2 b         8     0     1     0     0     1     0     0
3 c         8     1     0     1     0     0     1     0
>

A: library(reshape2)
  name var1
1    a    7
2    b    8
3    c    8

df2
  name language
1    a        c
2    a        q
3    a        s
4    b     java
5    b        k
6    c        r
7    c        t
8    c        c

df3 <- df1 %>% inner_join(df2 %>% count(name, language)
df3 <- dcast(df3, name + var1 ~ language, value.var = "n", fun.aggregate = sum)

df3
  name var1 c java k q r s t
1    a    7 1    0 0 1 0 1 0
2    b    8 0    1 1 0 0 0 0
3    c    8 1    0 0 0 1 0 1


text:
Q: Time Series Chart not working with TimePeriod="Month" I have created a time series chart in Jaspersoft studio. It works fine when I set TimePeriod="Day", but chart is empty when TimePeriod="Month". Data is created in java backend app, and passed with JRBeanCollectionDataSource :
Map<String, Object> statsModel = new HashMap<>();
statsModel.put("interval", date);
statsModel.put("accepted", accepted);
statsModel.put("rejected", rejected);
statsModel.put("unresolved", unresolved);

Collection statsList = new LinkedList();
statsList.add(statsModel);
JRBeanCollectionDataSource reportData = new JRBeanCollectionDataSource(statsList);

date: java.util.Date in format "yyyy-MM-dd", theres exactly one value per each day in interval.
accepted, rejected, resolved: long
Shouldn't TimePeriod="Month" make jasper to add all the values of the month and show it on the chart?


text:
Q: How to download android gradle project dependencies to custom folder? How to download android gradle project dependencies to custom folder?
I cannot save or read *.exe files in my home folder in my work enviroment under Windows (due security reason and corporate policy)
How to resolve exception thrown by gradle when I try to build or import in IDE Android project?
I tried to change Gradle user home, but it didn't help.
Caused by: java.io.FileNotFoundException: \\{my-company-url-for-user-home}\android-sdk-windows\SDK Manager.exe (Access is denied)
    at org.rauschig.jarchivelib.IOUtils.copy(IOUtils.java:50)
    at org.rauschig.jarchivelib.CommonsArchiver.extract(CommonsArchiver.java:83)
    at org.rauschig.jarchivelib.Archiver$extract.call(Unknown Source)
    at com.jakewharton.sdkmanager.internal.SdkDownload.download(SdkDownload.groovy:57)
    at com.jakewharton.sdkmanager.internal.SdkDownload$download$0.call(Unknown Source)
    at com.jakewharton.sdkmanager.internal.Downloader$Real.download(Downloader.groovy:8)
    at com.jakewharton.sdkmanager.internal.Downloader$download.call(Unknown Source)
    at com.jakewharton.sdkmanager.internal.SdkResolver.downloadSdk(SdkResolver.groovy:95)
    at com.jakewharton.sdkmanager.internal.SdkResolver$downloadSdk$1.callCurrent(Unknown Source)
    at com.jakewharton.sdkmanager.internal.SdkResolver.resolve(SdkResolver.groovy:87)
    at com.jakewharton.sdkmanager.internal.SdkResolver$resolve$0.call(Unknown Source)
    at com.jakewharton.sdkmanager.internal.SdkResolver.resolve(SdkResolver.groovy:17)
    at com.jakewharton.sdkmanager.internal.SdkResolver$resolve.call(Unknown Source)
    at com.jakewharton.sdkmanager.SdkManagerPlugin$_apply_closure1.doCall(SdkManagerPlugin.groovy:27)
    at com.jakewharton.sdkmanager.SdkManagerPlugin$_apply_closure1.doCall(SdkManagerPlugin.groovy)
    at com.jakewharton.sdkmanager.SdkManagerPlugin.time(SdkManagerPlugin.groovy:45)
    at com.jakewharton.sdkmanager.SdkManagerPlugin$time$0.callCurrent(Unknown Source)
    at com.jakewharton.sdkmanager.SdkManagerPlugin.apply(SdkManagerPlugin.groovy:26)
    at com.jakewharton.sdkmanager.SdkManagerPlugin.apply(SdkManagerPlugin.groovy)
    at org.gradle.api.internal.plugins.DefaultPluginContainer.providePlugin(DefaultPluginContainer.java:110)
    at org.gradle.api.internal.plugins.DefaultPluginContainer.addPluginInternal(DefaultPluginContainer.java:69)
    at org.gradle.api.internal.plugins.DefaultPluginContainer.apply(DefaultPluginContainer.java:35)
    at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.applyPlugin(DefaultObjectConfigurationAction.java:117)
    at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.access$200(DefaultObjectConfigurationAction.java:36)
    at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction$3.run(DefaultObjectConfigurationAction.java:85)
    at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.execute(DefaultObjectConfigurationAction.java:130)
    at org.gradle.api.internal.project.AbstractPluginAware.apply(AbstractPluginAware.java:41)
    at org.gradle.api.Project$apply$2.call(Unknown Source)
    at org.gradle.api.internal.project.ProjectScript.apply(ProjectScript.groovy:34)
    at org.gradle.api.Script$apply$0.callCurrent(Unknown Source)
    at build_1nbccshuhk647b9aqa26vge5lo.run(C:\Projects\Android\core\build.gradle:1)
    at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:52)
    ... 54 more

A: To gather all the dependencies, you can just "copy" the configuration that represents the dependencies you want.
For example, to copy all the compile time and runtime dependencies you could do something like:
task copyToLib(type: Copy) {
    into "$buildDir/output/lib"
    from configurations.runtime
}

you can also use gradle.user.home system property property  or --gradle-user-home command line property

A: I found solution while reading debug logs:
Set up ANDROID_HOME enviroment variable
13:18:32.382 [DEBUG] [com.jakewharton.sdkmanager.internal.SdkResolver] Missing l
ocal.properties.
13:18:32.395 [DEBUG] [com.jakewharton.sdkmanager.internal.SdkResolver] Missing A
NDROID_HOME.
13:18:32.406 [LIFECYCLE] [com.jakewharton.sdkmanager.internal.SdkResolver] Andro
id SDK not found. Downloading...
13:18:32.425 [DEBUG] [com.jakewharton.sdkmanager.internal.SdkDownload] Downloadi
ng SDK from http://dl.google.com/android/android-sdk_r23-windows.zip.


text:
Q: ipsec vpn with racoon drops traffic on phase 1 renegotiation We are running racoon on Linux connecting to a Checkpoint firewall. The connection comes up fine, but we see an interruption to traffic every 24 hours, corresponding to Phase 1 regenogiation.
Our setup is as follows:
Local side
racoon from ipsec-tools 0.8.0 installed from RPM on Amazon Linux.
Local IP: 10.130.0.253
Local subnet: 10.130.0.252/30
This is running inside an AWS VPC, i.e. it's on a private subnet. So we have NAT traversal enabled. We are binding the VPN to a sub-interface and using iptables to translate the vpn connection to the primary address and NAT traffic destined for the remote LAN to the subinterface. This allows the host to act as a VPN gateway for other hosts, which works well. Iptables rules:
Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination
SNAT       all  --  10.130.0.253         2.2.2.2       to:10.100.200.112
SNAT       all  --  0.0.0.0/0            10.128.80.0/24       to:10.130.0.253

Remote side:
VPN Gateway IP: 2.2.2.2 (anonymised)
Remote subnet:  10.128.80.0/24
Our local configuration is as follows:
/etc/racoon/racoon.conf:
# Racoon IKE daemon configuration file.
# See 'man racoon.conf' for a description of the format and entries.

log debug2;

path include "/etc/racoon";
path pre_shared_key "/etc/racoon/psk.txt";
path certificate "/etc/racoon/certs";
path script "/etc/racoon/scripts";

# Listen on sub-interface - initial connection to establish tunnel is translated to primary IP by iptables
listen {
  isakmp 10.130.0.253 [500];
  isakmp_natt 10.130.0.253 [4500];
}

timer {
 natt_keepalive 1 minute ;
}

# CP VPN-1
remote 2.2.2.2
{
  exchange_mode main;
  lifetime time 24 hour;

  nat_traversal on;

  dpd_delay 20;

  proposal {
    encryption_algorithm 3des;
    hash_algorithm sha1;
    authentication_method pre_shared_key;
    dh_group 2;
  }
}

# net-to-net
sainfo address 10.130.0.252/30 any address 10.128.80.0/24 any
{
  pfs_group 2;
        lifetime time 1 hour;
        encryption_algorithm 3des;
        authentication_algorithm hmac_sha1 ;
        compression_algorithm deflate ;
}

# gateway to gateway
sainfo address 10.130.0.253/32 any address 2.2.2.2/32 any
{
        lifetime time 1 hour;
        encryption_algorithm 3des;
        authentication_algorithm hmac_sha1 ;
        compression_algorithm deflate ;
}

/etc/racoon/setkey.sh
#!/sbin/setkey -f

# First of all flush the SPD database
flush;
spdflush;

# Gateway to Gateway
spdadd 10.130.0.253 2.2.2.2 any -P out ipsec esp/tunnel/10.130.0.253-2.2.2.2/unique;
spdadd 2.2.2.2 10.130.0.253 any -P in  ipsec esp/tunnel/2.2.2.2-10.130.0.253/unique;

# Linux-racoon -> CP VPN-1
spdadd 10.130.0.252/30 10.128.80.0/24 any -P out ipsec esp/tunnel/10.130.0.253-2.2.2.2/unique;

# CP VPN-1 > Linux-racoon
spdadd 10.128.80.0/24 10.130.0.252/30 any -P in  ipsec esp/tunnel/2.2.2.2-10.130.0.253/unique;

We've been getting some alerts on our monitoring of the VPN recently so I set up a more detailed monitoring script which connects to the remote server every minute. It seems that we get significant downtime every 24 hours. My script shows when the connection goes down and when it comes back:
Fri Jan 18 20:24:33 UTC 2013 Connection went down
Fri Jan 18 20:48:36 UTC 2013 Connection came up

Sat Jan 19 20:48:36 UTC 2013 Connection went down
Sat Jan 19 21:00:40 UTC 2013 Connection came up

Sun Jan 20 21:00:38 UTC 2013 Connection went down
Sun Jan 20 21:12:43 UTC 2013 Connection came up

As you can see, the connection goes down exactly 24 hours after it last came up.
These interruptions seem to correspond to Phase 1 renegotiations in the VPN log, which makes sense as the Phase 1 lifetime is 24 hours:
Friday:
Jan 18 20:24:32 ip-10-100-200-112 racoon: INFO: ISAKMP-SA expired 10.130.0.253[500]-2.2.2.2[500] spi:13b2510d0bc467f9:ff649237b81a65b7
Jan 18 20:24:32 ip-10-100-200-112 racoon: INFO: ISAKMP-SA deleted 10.130.0.253[500]-2.2.2.2[500] spi:13b2510d0bc467f9:ff649237b81a65b7
Jan 18 20:36:34 ip-10-100-200-112 racoon: INFO: IPsec-SA expired: ESP/Tunnel 2.2.2.2[500]->10.130.0.253[500] spi=213727991(0xcbd3af7)
Jan 18 20:36:34 ip-10-100-200-112 racoon: INFO: IPsec-SA expired: ESP/Tunnel 10.130.0.253[500]->2.2.2.2[500] spi=3400029604(0xcaa855a4)
Jan 18 20:48:34 ip-10-100-200-112 racoon: INFO: IPsec-SA expired: ESP/Tunnel 2.2.2.2[500]->10.130.0.253[500] spi=213727991(0xcbd3af7)
Jan 18 20:48:34 ip-10-100-200-112 racoon: INFO: IPsec-SA expired: ESP/Tunnel 10.130.0.253[500]->2.2.2.2[500] spi=3400029604(0xcaa855a4)
Jan 18 20:48:34 ip-10-100-200-112 racoon: INFO: IPsec-SA request for 2.2.2.2 queued due to no phase1 found.
Jan 18 20:48:34 ip-10-100-200-112 racoon: INFO: initiate new phase 1 negotiation: 10.130.0.253[500]<=>2.2.2.2[500]
Jan 18 20:48:34 ip-10-100-200-112 racoon: INFO: begin Identity Protection mode.
Jan 18 20:48:34 ip-10-100-200-112 racoon: INFO: ISAKMP-SA established 10.130.0.253[500]-2.2.2.2[500] spi:c4978718cd291fde:01245a461d26cc34
Jan 18 20:48:35 ip-10-100-200-112 racoon: INFO: initiate new phase 2 negotiation: 10.130.0.253[500]<=>2.2.2.2[500]
Jan 18 20:48:35 ip-10-100-200-112 racoon: INFO: IPsec-SA established: ESP/Tunnel 10.130.0.253[500]->2.2.2.2[500] spi=264213233(0xfbf92f1)
Jan 18 20:48:35 ip-10-100-200-112 racoon: INFO: IPsec-SA established: ESP/Tunnel 10.130.0.253[500]->2.2.2.2[500] spi=919162535(0x36c94ea7)

Saturday:
Jan 19 20:48:34 ip-10-100-200-112 racoon: INFO: ISAKMP-SA expired 10.130.0.253[500]-2.2.2.2[500] spi:c4978718cd291fde:01245a461d26cc34
Jan 19 20:48:34 ip-10-100-200-112 racoon: INFO: ISAKMP-SA deleted 10.130.0.253[500]-2.2.2.2[500] spi:c4978718cd291fde:01245a461d26cc34
Jan 19 20:48:36 ip-10-100-200-112 racoon: INFO: IPsec-SA expired: ESP/Tunnel 2.2.2.2[500]->10.130.0.253[500] spi=229822093(0xdb2ce8d)
Jan 19 20:48:36 ip-10-100-200-112 racoon: INFO: IPsec-SA expired: ESP/Tunnel 10.130.0.253[500]->2.2.2.2[500] spi=2536548534(0x9730a8b6)
Jan 19 21:00:36 ip-10-100-200-112 racoon: INFO: IPsec-SA expired: ESP/Tunnel 2.2.2.2[500]->10.130.0.253[500] spi=229822093(0xdb2ce8d)
Jan 19 21:00:36 ip-10-100-200-112 racoon: INFO: IPsec-SA expired: ESP/Tunnel 10.130.0.253[500]->2.2.2.2[500] spi=2536548534(0x9730a8b6)
Jan 19 21:00:37 ip-10-100-200-112 racoon: INFO: IPsec-SA request for 2.2.2.2 queued due to no phase1 found.
Jan 19 21:00:37 ip-10-100-200-112 racoon: INFO: initiate new phase 1 negotiation: 10.130.0.253[500]<=>2.2.2.2[500]
Jan 19 21:00:37 ip-10-100-200-112 racoon: INFO: begin Identity Protection mode.
Jan 19 21:00:38 ip-10-100-200-112 racoon: INFO: ISAKMP-SA established 10.130.0.253[500]-2.2.2.2[500] spi:8b7e98a2cc9d55cb:0b4e8a4cbca2ada9
Jan 19 21:00:38 ip-10-100-200-112 racoon: INFO: initiate new phase 2 negotiation: 10.130.0.253[500]<=>2.2.2.2[500]
Jan 19 21:00:39 ip-10-100-200-112 racoon: INFO: IPsec-SA established: ESP/Tunnel 10.130.0.253[500]->2.2.2.2[500] spi=111999639(0x6acfa97)
Jan 19 21:00:39 ip-10-100-200-112 racoon: INFO: IPsec-SA established: ESP/Tunnel 10.130.0.253[500]->2.2.2.2[500] spi=577442054(0x226b1106)

Sunday:
Jan 20 21:00:38 ip-10-100-200-112 racoon: INFO: ISAKMP-SA expired 10.130.0.253[500]-2.2.2.2[500] spi:8b7e98a2cc9d55cb:0b4e8a4cbca2ada9
Jan 20 21:00:38 ip-10-100-200-112 racoon: INFO: ISAKMP-SA deleted 10.130.0.253[500]-2.2.2.2[500] spi:8b7e98a2cc9d55cb:0b4e8a4cbca2ada9
Jan 20 21:00:39 ip-10-100-200-112 racoon: INFO: IPsec-SA expired: ESP/Tunnel 2.2.2.2[500]->10.130.0.253[500] spi=131435403(0x7d58b8b)
Jan 20 21:00:39 ip-10-100-200-112 racoon: INFO: IPsec-SA expired: ESP/Tunnel 10.130.0.253[500]->2.2.2.2[500] spi=272995718(0x10459586)
Jan 20 21:12:39 ip-10-100-200-112 racoon: INFO: IPsec-SA expired: ESP/Tunnel 2.2.2.2[500]->10.130.0.253[500] spi=131435403(0x7d58b8b)
Jan 20 21:12:39 ip-10-100-200-112 racoon: INFO: IPsec-SA expired: ESP/Tunnel 10.130.0.253[500]->2.2.2.2[500] spi=272995718(0x10459586)
Jan 20 21:12:40 ip-10-100-200-112 racoon: INFO: IPsec-SA request for 2.2.2.2 queued due to no phase1 found.
Jan 20 21:12:40 ip-10-100-200-112 racoon: INFO: initiate new phase 1 negotiation: 10.130.0.253[500]<=>2.2.2.2[500]
Jan 20 21:12:40 ip-10-100-200-112 racoon: INFO: begin Identity Protection mode.
Jan 20 21:12:40 ip-10-100-200-112 racoon: INFO: ISAKMP-SA established 10.130.0.253[500]-2.2.2.2[500] spi:e6d2b9ccb25f4992:31807020144b9a1e
Jan 20 21:12:41 ip-10-100-200-112 racoon: INFO: initiate new phase 2 negotiation: 10.130.0.253[500]<=>2.2.2.2[500]
Jan 20 21:12:41 ip-10-100-200-112 racoon: INFO: IPsec-SA established: ESP/Tunnel 10.130.0.253[500]->2.2.2.2[500] spi=179370287(0xab0f92f)
Jan 20 21:12:41 ip-10-100-200-112 racoon: INFO: IPsec-SA established: ESP/Tunnel 10.130.0.253[500]->2.2.2.2[500] spi=1696204357(0x651a0645)

So it seems that the phase 1 renegotiation takes at least 12 minutes. Does anyone know why this might be and what we can do to fix it so we can have uninterrupted traffic over the VPN?

A: If you enable dead peer detection, Racoon should detect phase 1 expiration, and renegotiate automatically, assuming I've diagnosed the problem correctly.
By default, dpd is disabled;

dpd_delay 0;
  is the default.

Setting a reasonable number, in seconds, between dpd checks, will enable it;

dpd_delay 30;

Now to try this in anger on the my ipsec vpn which was doing the same thing.

A: Sorry to answer my own question - I moved from ipsec-tools to Openswan and the VPN is now completely stable. It seems that ipsec-tools is a dead project while Openswan is maintained and is now the default VPN solution in RHEL.


text:
Q: Using existing VNET with Azure Function APP I have one VNET and 2 subnets under that. One subnet is used to connect to an external Kafka server.
VNET: xx.xx.xx.0/26
Subnets: xx.xx.xxx.0/27 and xx.xx.xxx.32/27 (27 Available IPs each)
I wanted to test the Kafka topics using the bootstrap server. Is it possible to create a Function App and target that to the same existing subnet (that was used to connect to an external Kafka server.) So that, I can get a console in Azure to run the commands and test the Kafka topics.

A: •   Since your Kafka Server is an external server and you have deployed a bootstrap-config server to connect and forward the Azure resources metadata to the Kafka server while also configuring the function app in the same subnet as the bootstrap server, you will need two subnets. As you can relate with P2S(Point-to-Site) connectivity where we connect two virtual machines, one is external and the other one is internal. For this type of connection, you require a VPN gateway and application gateway itself which will create another subnet.
•   Hence, from the above conclusion, you will require two subnets to create a connection between external Kafka server and function application hosted on Azure. You can also refer to the link below for more details on configuring and deploying a Kafka cluster and a function app on Azure within a closed virtual network. In this document, the architecture of the deployed resources implies that the Kafka server and the function app to be deployed will be hosted on different subnets within the same virtual network.
https://techcommunity.microsoft.com/t5/apps-on-azure-blog/collaborate-kafka-and-azure-functions-securely-within-closed/ba-p/2429394
Also, for more details on setting up the Kafka bootstrap server with other platforms, and similar resources in Azure, please refer to the below documented sample link: -
https://learn.microsoft.com/en-us/samples/azure/azure-functions-kafka-extension-sample-confluent/azure-functions-kafka-extension-sample-using-confluent-cloud/
https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-vnet


text:
Q: Sum of elements in a forward looking rolling window by month I have the following data.frame with columns: Id, Month, have
library(dplyr)

dt <- read.table(header = TRUE, text = '
Id  Month    have   want
1   01-Jan-2018  1.000000000000000   1.234567901220000
1   01-Feb-2018  0.200000000000000   0.234567901233000
1   01-Mar-2018  0.030000000000000   0.034567901234400
1   01-Apr-2018  0.004000000000000   0.004567901234550
1   01-May-2018  0.000500000000000   0.000567901234566
1   01-Jun-2018  0.000060000000000   0.000067901234566
1   01-Jul-2018  0.000007000000000   0.000007901234566
1   01-Aug-2018  0.000000800000000   0.000000901234566
1   01-Sep-2018  0.000000090000000   0.000000101234566
1   01-Oct-2018  0.000000010000000   0.000000011234566
1   01-Nov-2018  0.000000001100000   0.000000001234566
1   01-Dec-2018  0.000000000120000   0.000000000134566
1   01-Jan-2019  0.000000000013000   0.000000000014566
1   01-Feb-2019  0.000000000001400   0.000000000001566
1   01-Mar-2019  0.000000000000150   0.000000000000166
1   01-Apr-2019  0.000000000000016   0.000000000000016
2   01-Jan-2018 1337.00 1338.00
2   01-Feb-2018 1.00    1.00
3   01-Jan-2018  5.000000000000000000    5.000000000000000
') %>% mutate(Month=as.Date(Month, format='%d-%b-%Y')

I would like to programmatically calculate sum of elements in a 12 month forward looking rolling window by Month and grouped by Id as demonstrated in column want. If the rolling observation window is less than 12 months, the missing elements should be ignored.
For bonus points would the solution would also allow for missing months, such as in:
dt <- read.table(header = TRUE, text = '
Id  Month    have   want
1   01-Jan-18    1.000000000000000   1.200000000000000
1   01-Dec-18    0.200000000000000   0.230000000000000
1   01-Jan-19    0.030000000000000   0.030000000000000
') %>% mutate(Month=as.Date(Month, format='%d-%b-%Y')

I have tried different solutions, e.g. rollapplyr() of the zoo package and some functions in the runner package, but it doesn't seem to give me what I need.

A: You can use zoo's rollaply with partial = TRUE
library(dplyr)

dt %>%
  group_by(Id) %>%
  tidyr::complete(Month = seq(min(Month), max(Month), "month")) %>%
  mutate(result = zoo::rollapply(have, 12, sum, na.rm = TRUE,
                                 align = 'left', partial = TRUE)) -> result
result

If you have data for every month for each Id like in the example shared you can remove the complete step.

A: I suggest to use runner package in this case. runner function let you to calculate rolling window having a full control in time. k is a window length, lag is a lag of the window and in idx you specify index column which window depends on.
library(runner)

dt %>%
  group_by(Id) %>%
  mutate(want2 = runner(
    .,
    f = function(x) sum(x$have),
    k = 12,    # or "12 months"
    lag = -11, # or "-11 months"
    idx = Month)
  )

# # A tibble: 19 x 5
# # Groups:   Id [3]
#    Id Month          have     want    want2
# <int> <date>        <dbl>    <dbl>    <dbl>
#   1     1 2018-01-01 1.00e+ 0 1.23e+ 0 1.00e+ 0
#   2     1 2018-02-01 2.00e- 1 2.35e- 1 2.00e- 1
#   3     1 2018-03-01 3.00e- 2 3.46e- 2 3.00e- 2
#   4     1 2018-04-01 4.00e- 3 4.57e- 3 4.00e- 3
#   5     1 2018-05-01 5.00e- 4 5.68e- 4 5.00e- 4
#   6     1 2018-06-01 6.00e- 5 6.79e- 5 6.00e- 5


text:
Q: Setting exposure compensation with cwac-camera I'm using a SeekBar, and I'd like to set the exposure compensation when the user changes the SeekBar, for the preview surface.
I'm using cwac-camera (CameraView), and I'd like to use Camera.Parameters.setExposureCompensation, however CameraView does not give access to the Camera object.

A: setExposureCompensation() is a method on Camera.Parameters. You are provided a Camera.Parameters at various points in time, such as via adjustPreviewParameters().


text:
Q: CsvHelper and immutable types I have an immutable class that I want to write to and read from a CSV file. The issue is I am getting an exception when reading the CSV despite having mapped the object and set up a configuration that should allow this to work.
To do this I am using CsvHelper. The immutable class looks like the following.
public class ImmutableTest
{
    public Guid Id { get; }

    public string Name { get; }

    public ImmutableTest(string name) : this(Guid.NewGuid(), name)
    {
    }

    public ImmutableTest(Guid id, string name)
    {
        Id = id;
        Name = name;
    }
}

I have no issue writing this to a CSV file, but when I try to read it from a file, I get the following exception.

No members are mapped for type 'CsvTest.Program+ImmutableTest'

However, I have mapped the members for this class in the map class below.
public sealed class ImmutableTestMap : ClassMap<ImmutableTest>
{
    public ImmutableTestMap()
    {
        Map(immutableTest => immutableTest.Id)
            .Index(0)
            .Name(nameof(ImmutableTest.Id).ToUpper());

        Map(immutableTest => immutableTest.Name)
            .Index(1)
            .Name(nameof(ImmutableTest.Name));
    }
}

I have also tried to configure the reader to use the constructor to build the object by using the following configuration.
Configuration config = new Configuration
{
    IgnoreBlankLines = true
};

config.RegisterClassMap<ImmutableTestMap>();
config.ShouldUseConstructorParameters = type => true;
config.GetConstructor = type => type.GetConstructors()
    .MaxBy(constructor => constructor.GetParameters().Length)
    .FirstOrDefault();

No of this seems to be working. Where am I going wrong?

Complete MCVE .NET Framework Console Example
Install the packages
Install-Package CsvHelper
Install-Package morelinq

Sample console program
using System;
using System.IO;
using CsvHelper;
using CsvHelper.Configuration;
using MoreLinq;

namespace CsvTest
{
    class Program
    {
        static void Main()
        {
            Configuration config = new Configuration
            {
                IgnoreBlankLines = true
            };

            config.RegisterClassMap<ImmutableTestMap>();
            config.ShouldUseConstructorParameters = type => true;
            config.GetConstructor = type => type.GetConstructors()
                .MaxBy(constructor => constructor.GetParameters().Length)
                .FirstOrDefault();

            const string filePath = "Test.csv";
            using (FileStream file = new FileStream(filePath, FileMode.Create))
            using (StreamWriter fileWriter = new StreamWriter(file))
            using (CsvSerializer csvSerializer = new CsvSerializer(fileWriter, config))
            using (CsvWriter csvWriter = new CsvWriter(csvSerializer))
            {
                csvWriter.WriteHeader<ImmutableTest>();
                csvWriter.NextRecord();
                csvWriter.WriteRecord(new ImmutableTest("Test 1"));
                csvWriter.NextRecord();
                csvWriter.WriteRecord(new ImmutableTest("Test 2"));
                csvWriter.NextRecord();
            }

            using (FileStream file = new FileStream(filePath, FileMode.Open))
            using (StreamReader fileReader = new StreamReader(file))
            using (CsvReader csvReader = new CsvReader(fileReader, config))
            {
                foreach (ImmutableTest record in csvReader.GetRecords<ImmutableTest>())
                {
                    Console.WriteLine(record.Id);
                    Console.WriteLine(record.Name);
                    Console.WriteLine();
                }
            }
        }

        public sealed class ImmutableTestMap : ClassMap<ImmutableTest>
        {
            public ImmutableTestMap()
            {
                Map(immutableTest => immutableTest.Id)
                    .Index(0)
                    .Name(nameof(ImmutableTest.Id).ToUpper());

                Map(immutableTest => immutableTest.Name)
                    .Index(1)
                    .Name(nameof(ImmutableTest.Name));
            }
        }

        public class ImmutableTest
        {
            public Guid Id { get; }

            public string Name { get; }

            public ImmutableTest(string name) : this(Guid.NewGuid(), name)
            {
            }

            public ImmutableTest(Guid id, string name)
            {
                Id = id;
                Name = name;
            }
        }
    }
}

A: If the type is immutable, it will use constructor mapping instead. Your constructor variable names need to match the header names. You can do this using Configuration.PrepareHeaderForMatch.
void Main()
{
    var s = new StringBuilder();
    s.AppendLine("Id,Name");
    s.AppendLine($"{Guid.NewGuid()},one");
    using (var reader = new StringReader(s.ToString()))
    using (var csv = new CsvReader(reader))
    {
        csv.Configuration.PrepareHeaderForMatch = (header, indexer) => header.ToLower();
        csv.GetRecords<ImmutableTest>().ToList().Dump();
    }
}

public class ImmutableTest
{
    public Guid Id { get; }

    public string Name { get; }

    public ImmutableTest(string name) : this(Guid.NewGuid(), name)
    {
    }

    public ImmutableTest(Guid id, string name)
    {
        Id = id;
        Name = name;
    }
}

A: So the issue here is that there are no ParameterMaps in the class map.
The easy way to fix this, with the example above, is to write something like
public ImmutableTestMap()
{
    AutoMap();

    Map(immutableTest => immutableTest.Id)
        .Index(0)
        .Name(nameof(ImmutableTest.Id).ToUpper());
}

But this causes an issue that the column headers in the CSV file are ID, Name and the parameter maps generated are id, name. These are not equal to each other and so the reader throws an error saying it can't find a column with the name ID. It also says you can set header validated to null. After playing around with this, I ended up at a point where the configuration
Configuration config = new Configuration
{
    IgnoreBlankLines = true,
    ShouldUseConstructorParameters = type => true,
    GetConstructor = type => type.GetConstructors()
        .MaxBy(constructor => constructor.GetParameters().Length)
        .FirstOrDefault(),
    HeaderValidated = null,
    MissingFieldFound = null
};

config.RegisterClassMap<ImmutableTestMap>();

Is trying to parse empty fields and failing to convert it to a GUID. So it looked like that road was dead.
To get around this, I looked at checking each parameter map generated by auto map for the "id" value and then to replace it with "ID". However, this also did not work as the auto generated maps are generated with a null name. The name is only assigned when SetMapDefaults are called during the registration of a map in a config.
So I went for a blind loop of setting the names of the parameters maps to the explicitly defined member maps.
public ImmutableTestMap()
{
    AutoMap();
    Map(immutableTest => immutableTest.Id)
        .Index(0)
        .Name(nameof(ImmutableTest.Id).ToUpper());

    Map(immutableTest => immutableTest.Name)
        .Index(0)
        .Name(nameof(ImmutableTest.Id));

    if (MemberMaps.Count != ParameterMaps.Count)
    {
        return;
    }

    for (int i = 0; i < MemberMaps.Count; i++)
    {
        ParameterMaps[i].Data.Name = MemberMaps[i].Data.Names[0];
    }
}

However, I would say this is more of a bodge than a fix and would definitely be open to other answers.


text:
Q: Should each SolrCloud node have its own ssl certificate? I'm attempting to enable SSL for SolrCloud to be used with Sitecore. I currently have an external assembly of three Zookeeper nodes on three Azure vms and two Solr 6.6.6 nodes on two Azure vms.
I'm following the steps outlined in Apache's documentation: https://lucene.apache.org/solr/guide/6_6/enabling-ssl.html
Should I generate a separate certificate for each of the nodes or should I only create it on one and share it in some way? I was thinking that maybe in the later steps that Zookeeper distributes it someway but the directions are unclear to me.
I did check for similar questions and found this: inter-Solr-node communication with SSL but it doesn't really address whether I should be generating separate certificates to begin with or not.

A: Taking into account setup what you described, you can even make it more simple by off-loading SSL on Application Gateway (I can assume you are using Azure App Gateway to balance traffic to Solr nodes) and then forwarding request from App Gateway to Solr Nodes over HTTP (no SSL)
If you configure your ZK and Solr nodes to communicate by internal IP address and vnet/nsg to let only requests from App Gateway, this setup won't have any security impact.
If you insist keeping SolrCloud using SSL, I believe that should be one single certificate.
Note: don't forget to let Zookeeper to know that whole SolrCloud should use SSL by setting a parameter (see step #7 as an example here https://github.com/ivanbuzyka/Sitecore.SolrCloudConfiguration/wiki/3.-Install-Zookeeper-as-a-service)


text:
Q: tensorflow protobuf conflict when compiling with third party framework I built my own tensorflow c++ library(with protobuf 3.4).
When compiling with the network framework, there is a big problem. The network framework depends on protobuf 2.5. And I can't change the protobuf of the network framework, no one is maintenance this project.
Can I build tensorflow library with a stand-alone namespace? And how to configure this?

A: I also get this issue in using opencv and tensorflow together on iOS. Anyone with a solution?