text:
Q: How to link nghttp2 asio project using cmake I have a project where I want to use the nghttp2 library. I am trying to link this project in CMakeLists.txt so that I can compile the following file with cmake.
My project structure
.
├── CMakeLists.txt
├── lib
│   ├── Catch2
│   └── nghttp2
├── README.md
└── src
    ├── main
    |  └── Main.cpp
    └── test

The main program that imports nghttp2
#include <iostream>
#include <nghttp2/asio_http2.h>
#include <nghttp2/asio_http2_server.h>
#include <boost/circular_buffer.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/thread/thread.hpp>
#include <boost/timer/timer.hpp>
#include <boost/call_traits.hpp>
#include <boost/bind.hpp>
#include <boost/log/trivial.hpp>
#include <string>
#include <limits>

using namespace nghttp2::asio_http2;
using namespace nghttp2::asio_http2::server;

int main(int argc, char *argv[]) {
    boost::system::error_code ec;
    http2 server;

    server.handle("/", [](const request &req, const response &res) {
        res.write_head(200);
        res.end("hello, world\n");
    });

    if (server.listen_and_serve(ec, "localhost", "3000")) {
        std::cerr << "error: " << ec.message() << std::endl;
    }
}

My CMakeLists.txt file is the following
cmake_minimum_required(VERSION 3.16.3)
project(my-project)

set(CMAKE_CXX_STANDARD 14)

set(CMAKE_CXX_STANDARD_REQUIRED True)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/build)
set(LIBRARY_NAME ${PROJECT_NAME})
set(TEST_NAME tests)

add_executable(
        ${PROJECT_NAME}

        src/main/Main.cpp
)

find_package(Threads REQUIRED)
find_package(Boost REQUIRED COMPONENTS system)
find_package(Boost REQUIRED COMPONENTS thread)
find_package(Boost REQUIRED COMPONENTS log)
find_package(OpenSSL REQUIRED)

target_link_libraries(
        ${PROJECT_NAME}

        PRIVATE Threads::Threads
        PRIVATE Boost::system
        PRIVATE Boost::thread
        PRIVATE Boost::log
        PRIVATE OpenSSL::Crypto
)

set(NGHTTP2_SRC_DIR lib/nghttp2)
add_subdirectory(${NGHTTP2_SRC_DIR})
target_link_libraries(${PROJECT_NAME} PUBLIC nghttp2)

target_include_directories(
        ${LIBRARY_NAME} PRIVATE
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/${LIBRARY_NAME}>
        $<INSTALL_INTERFACE:include/${LIBRARY_NAME}>
)
target_include_directories(
        ${LIBRARY_NAME} PUBLIC
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
        $<INSTALL_INTERFACE:include>
)

# Catch2
set(CATCH2_SRC_DIR lib/Catch2)
add_subdirectory(${CATCH2_SRC_DIR})
add_executable(${TEST_NAME} src/test/Test.cpp)
target_link_libraries(${TEST_NAME} PRIVATE Catch2::Catch2WithMain)
include(${CATCH2_SRC_DIR}/extras/Catch.cmake)
include(${CATCH2_SRC_DIR}/extras/ParseAndAddCatchTests.cmake)
list(APPEND CMAKE_MODULE_PATH ${CATCH2_SRC_DIR}/extras)
include(CTest)
catch_discover_tests(${TEST_NAME})

When I run make after cmake . I get the following error
/usr/bin/ld: CMakeFiles/my-project.dir/src/main/Main.cpp.o: in function `std::_Function_handler<void (nghttp2::asio_http2::server::request const&, nghttp2::asio_http2::server::response const&), main::{lambda(nghttp2::asio_http2::server::request const&, nghttp2::asio_http2::server::response const&)#1}>::_M_invoke(std::_Any_data const&, nghttp2::asio_http2::server::request const&, nghttp2::asio_http2::server::response const&)':
/home/username/CLionProjects/myproject/src/main/Main.cpp:23: undefined reference to `nghttp2::asio_http2::server::response::write_head(unsigned int, std::multimap<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, nghttp2::asio_http2::header_value, std::less<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, nghttp2::asio_http2::header_value> > >) const'
/usr/bin/ld: CMakeFiles/my-project.dir/src/main/Main.cpp.o: in function `operator()':
/home/username/CLionProjects/myproject/src/main/Main.cpp:24: undefined reference to `nghttp2::asio_http2::server::response::end(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) const'
/usr/bin/ld: CMakeFiles/my-project.dir/src/main/Main.cpp.o: in function `main.cold':
/home/username/CLionProjects/myproject/src/main/Main.cpp:20: undefined reference to `nghttp2::asio_http2::server::http2::~http2()'
/usr/bin/ld: CMakeFiles/my-project.dir/src/main/Main.cpp.o: in function `main':
/home/username/CLionProjects/myproject/src/main/Main.cpp:20: undefined reference to `nghttp2::asio_http2::server::http2::http2()'
/usr/bin/ld: /home/username/CLionProjects/myproject/src/main/Main.cpp:22: undefined reference to `nghttp2::asio_http2::server::http2::handle(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::function<void (nghttp2::asio_http2::server::request const&, nghttp2::asio_http2::server::response const&)>)'
/usr/bin/ld: /home/username/CLionProjects/myproject/src/main/Main.cpp:27: undefined reference to `nghttp2::asio_http2::server::http2::listen_and_serve(boost::system::error_code&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, bool)'
/usr/bin/ld: /home/username/CLionProjects/myproject/src/main/Main.cpp:20: undefined reference to `nghttp2::asio_http2::server::http2::~http2()'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/my-project.dir/build.make:95: build/my-project] Error 1
make[1]: *** [CMakeFiles/Makefile2:942: CMakeFiles/my-project.dir/all] Error 2
make: *** [Makefile:141: all] Error 2

I can manually compile the Main.cpp with
g++  Main.cpp -o Main.out -DBOOST_LOG_DYN_LINK -lboost_log -lnghttp2_asio -lboost_system -lcrypto -lpthread -lssl -lboost_thread

Edit:
I got it to compile by first having nghttp2 installing on my machine. Then adding this line in CMakeLists.txt
target_link_libraries(${PROJECT_NAME} PUBLIC /usr/local/lib/libnghttp2_asio.so)

Is there a more elegant way to do this?

A: To answer the question you added after editing your initial message, you can avoid specifying the full path to libnghttp2_asio.so manually by using CMake's find_library, like this:
find_library(nghttp2_asio_LIBRARY NAMES nghttp2_asio)
target_link_libraries(${PROJECT_NAME} PUBLIC nghttp2_asio)

However, you are mixing two different ways of adding an external library to your project. Since you are already including nghttp2's source code in your project, you should not link your program against another version of nghttp2 that you installed system-wide for at least two reasons:

*

*The nghttp2 headers your are including in your project might not match the version of the nghttp2 library you installed system-wide, which might cause linking errors

*If someone clones your code, they will have to install nghttp2 on their system as well, and they might run into the very same linking errors explained in the previous point

Instead, I suggest you build libnghttp2_asio from source, as you initially planned.
To solve your initial issue, you should link against the right library (nghttp2_asio instead of nghttp2) and set the flag --enable-asio-lib when building nghttp2. Here is what your CMake should look like:
set(NGHTTP2_SRC_DIR lib/nghttp2)
set(ENABLE_ASIO_LIB ON)
add_subdirectory(${NGHTTP2_SRC_DIR})
target_link_libraries(${PROJECT_NAME} PUBLIC nghttp2_asio)

In addition, you will have to add Boost::asio to the list of libraries in your first call to target_link_libraries, as explained in nghttp2's documentation:

libnghttp2_asio is not built by default. Use --enable-asio-lib
configure flag to build libnghttp2_asio. The required Boost libraries
are: Boost::Asio, Boost::System and Boost::Thread.


text:
Q: Sonarqube github pull request decoration url incorrect I have just about got sonarqube 9.5 developer edition working on our environment, with the pull request decoration on github, I find that the URL is wrong. What it ought to have is http:\sonarqubewebsrver.com<remainingurl> its replacing our sonarqube instance with localhost:9418 which appears to be a default value somewhere, I cant seem to find where to change it.

None of the URL's work, they will try to take you to http://localhost:9418/project/issues?id= what works is http://sonarqubeserver/project/issues?id=

A: The solution here was to update the Server base URL: Administration → General → Server base URL.
Then restart the sonarqube server.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiple charts not working chart.js I've been looking for a long time here in StackOverflow, searching for a solution to my problem. I already know that it is about window.onload that's been opened two times in my script, but I can't fix it. I'm looking it for days. Could you guys please help me?
Here's my chartBarSample.php code:
<script>
    var optionsBar = {
        responsive: true
    };

    var dataBar = {
        labels: ["Outubro", "Novembro", "Dezembro"],
        datasets: [
            {
                label: "CPF's Enviados",
                fillColor: "#00335A",
                strokeColor: "#00243F",
                highlightFill: "#00243F",
                highlightStroke: "#00192B",
                data: [6920, 7226, 7969]
            },
            {
                label: "Propostas Finalizadas",
                fillColor: "#007CDA",
                strokeColor: "#0066B4",
                highlightFill: "#0066B4",
                highlightStroke: "#005290",
                data: [6325, 6825, 7586]
            },
            {
                label: "Propostas Aprovadas",
                fillColor: "#2B8B4A",
                strokeColor: "#196431",
                highlightFill: "#196431",
                highlightStroke: "#114622",
                data: [5463, 6606, 6501]
            }
        ]
    };

    var optionsLine = {
        responsive: true
    };

    var dataLine = {
        labels: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"],
        datasets: [
            {
                label: "Dados primários",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "rgba(220,220,220,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: [randomnb(), randomnb(), randomnb(), randomnb(), randomnb(), randomnb(), randomnb(), randomnb(), randomnb(), randomnb(), randomnb(), randomnb()]
            },
            {
                label: "Dados secundários",
                fillColor: "rgba(151,187,205,0.2)",
                strokeColor: "rgba(151,187,205,1)",
                pointColor: "rgba(151,187,205,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(151,187,205,1)",
                data: [28, 48, 40, 19, 86, 27, 90, 200, 87, 20, 50, 20]
            }
        ]
    };

    function start(){
        var ctx = document.getElementById("graficoBarra").getContext("2d");
        var BarChart = new Chart(ctx).Bar(dataBar, optionsBar);

        var ctx2 = document.getElementById("graficoLinha").getContext("2d");
        var LineChart = new Chart(ctx2).Line(dataLine, optionsLine);
    }

    window.onload = start;
</script>

A: Your chart definitions are incorrect, try this:
function start(){
    var ctx = document.getElementById("graficoBarra").getContext("2d");
    var BarChart = new Chart(ctx, {
          type: 'bar',
          data: dataBar,
          options: optionsBar
    });

    var ctx2 = document.getElementById("graficoLinha").getContext("2d");
    var LineChart = new Chart(ctx2, {
          type: 'line',
          data: dataLine,
          options: optionsLine
    });
}

Full Code in Codepen: 2 Chart.js Charts
Result:


text:
Q: Motor: RuntimeError: maximum recursion depth exceeded while encoding an object to BSON I have an API, built on asynchronous Tornado and mongoDB. It works fine, except one handler:
@gen.coroutine
def get(self, *args, **kwargs):
    """
    Gets tracking lib
    """
    data = self._get_request_data()
    self._serialize_request_data(AuthValidator, data)

    tags = yield self.motor.tags.find_one({"client_id": data["client_id"]})
    raise Return(self.write(tags))

When request comes, tornado returns HTTP 500 with following stack trace:
response: Traceback (most recent call last):
  File "/Users/artemkorhov/Projects/cartreminder/env/lib/python2.7/site-packages/tornado/web.py", line 1334, in _execute
result = yield result
  File "/Users/artemkorhov/Projects/cartreminder/env/lib/python2.7/site-packages/tornado/gen.py", line 617, in run
value = future.result()
  File "/Users/artemkorhov/Projects/cartreminder/env/lib/python2.7/site-packages/tornado/concurrent.py", line 109, in result
raise_exc_info(self._exc_info)
  File "/Users/artemkorhov/Projects/cartreminder/env/lib/python2.7/site-packages/tornado/gen.py", line 620, in run
yielded = self.gen.throw(*sys.exc_info())
  File "/Users/artemkorhov/Projects/cartreminder/cartreminder_app/tracking_api/api_handlers/endpoints.py", line 35, in get
tags = yield self.motor.tags.find_one({"client_id": data["client_id"]})
  File "/Users/artemkorhov/Projects/cartreminder/env/lib/python2.7/site-packages/tornado/gen.py", line 617, in run
value = future.result()
  File "/Users/artemkorhov/Projects/cartreminder/env/lib/python2.7/site-packages/tornado/concurrent.py", line 109, in result
raise_exc_info(self._exc_info)
  File "/Users/artemkorhov/Projects/cartreminder/env/lib/python2.7/site-packages/motor/__init__.py", line 676, in call_method
result = sync_method(self.delegate, *args, **kwargs)
  File "/Users/artemkorhov/Projects/cartreminder/env/lib/python2.7/site-packages/pymongo/collection.py", line 721, in find_one
for result in cursor.limit(-1):
  File "/Users/artemkorhov/Projects/cartreminder/env/lib/python2.7/site-packages/pymongo/cursor.py", line 1038, in next
if len(self.__data) or self._refresh():
  File "/Users/artemkorhov/Projects/cartreminder/env/lib/python2.7/site-packages/pymongo/cursor.py", line 982, in _refresh
self.__uuid_subtype))
RuntimeError: maximum recursion depth exceeded while encoding an object to BSON

In mongoDB "tags" collection i have (for example):
{
"_id" : ObjectId("540eec8227c565f77d4dcd23"),
"client_id" : "1111",
"tags" : {
    "cart_add" : [
        {
            "action_element" : "#addbutton1",
            "info_element" : "#product_element1"
        }
    ],
    "cart_delete" : [
        {
            "action_element" : "#deleteButton1",
            "info_element" : "#product_element1"
        }
    ],
    "email_known" : {
        "info_element" : ".tag1"
    },
    "order_complete" : {
        "action_element" : "#order_button1",
        "info_element" : {
            "product_wrap" : ".product_wrap",
            "product_id" : ".product_id_element",
            "quantity" : ".product_quantity_element",
            "price" : ".product_price_element"
        }
    }
}
}

The interesting part is that same 'find' method works perfect in other handlers, which built almost the same

A: Your "data" dictionary has a circular reference, so when Motor passes "data" to PyMongo to be encoded as BSON and sent to the server, the BSON encoder recurses more than 1000 times. I can reproduce this error message like so:
>>> import bson
>>> d = {}
>>> d['key'] = d  # Circular reference!
>>> bson.BSON.encode(d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/emptysquare/.virtualenvs/motor/lib/python2.7/site-packages/bson/__init__.py", line 590, in encode
    return cls(_dict_to_bson(document, check_keys, uuid_subtype))
RuntimeError: maximum recursion depth exceeded while encoding an object to BSON

Try doing "pprint.pprint" on "data" to see where the self-reference occurs:
>>> import pprint
>>> pprint.pprint(d)
{'key': <Recursion on dict with id=140199700593680>}


text:
Q: Storing asian language characters in SQL Server 2016 I'm running into a problem where if I attempt to store asian language data such as mandarin, korean, japanese in my database it will display as a series of ?????????? question mark strings.
Is there anything in particular that i must do to be able to store foreign languages in SQL Server 2016?
I'm using mainly varchar datatypes.

A: For unicode characters, you must use nvarchar. Then your values should appear correctly.


text:
Q: Couldn't find foreign struct converter for 'cairo.Context' It's me again. This is a code related to a project I'm doing called Sentiment Analysis on Twitter Data. The following code is basically used to display the number of positive and negative tweets in which I'm getting the error given below.
from pyspark import SparkConf, SparkContext
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
import operator
import numpy as np
import matplotlib.pyplot as plt

def main():
        conf = SparkConf().setMaster("local[2]").setAppName("Streamer")
        sc = SparkContext(conf=conf)

        # Creating a streaming context with batch interval of 10 sec
        ssc = StreamingContext(sc, 10)
        ssc.checkpoint("checkpoint")
        pwords = load_wordlist("positive.txt")
        nwords = load_wordlist("negative.txt")
        counts = stream(ssc, pwords, nwords, 100)
        make_plot(counts)

def make_plot(counts):
        """
        This function plots the counts of positive and negative words for each timestep.
        """
        positiveCounts = []
        negativeCounts = []
        time = []

        for val in counts:
        positiveTuple = val[0]
        positiveCounts.append(positiveTuple[1])
        negativeTuple = val[1]
        negativeCounts.append(negativeTuple[1])

        for i in range(len(counts)):
        time.append(i)

        posLine = plt.plot(time, positiveCounts,'bo-', label='Positive')
        negLine = plt.plot(time, negativeCounts,'go-', label='Negative')
        plt.axis([0, len(counts), 0, max(max(positiveCounts), max(negativeCounts))+50])
        plt.xlabel('Time step')
        plt.ylabel('Word count')
        plt.legend(loc = 'upper left')
    plt.show()

def load_wordlist(filename):
    """
    This function returns a list or set of words from the given filename.
    """
    words = {}
    f = open(filename, 'rU')
    text = f.read()
    text = text.split('\n')
    for line in text:
        words[line] = 1
    f.close()
    return words

def wordSentiment(word,pwords,nwords):
    if word in pwords:
    return ('positive', 1)
    elif word in nwords:
    return ('negative', 1)

def updateFunction(newValues, runningCount):
    if runningCount is None:
       runningCount = 0
    return sum(newValues, runningCount)

def sendRecord(record):
    connection = createNewConnection()
    connection.send(record)
    connection.close()

def stream(ssc, pwords, nwords, duration):
    kstream = KafkaUtils.createDirectStream(
    ssc, topics = ['twitterstream'], kafkaParams = {"metadata.broker.list": 'localhost:9092'})
    tweets = kstream.map(lambda x: x[1].encode("ascii", "ignore"))

    # Each element of tweets will be the text of a tweet.
    # We keep track of a running total counts and print it at every time step.
    words = tweets.flatMap(lambda line:line.split(" "))
    positive = words.map(lambda word: ('Positive', 1) if word in pwords else ('Positive', 0))
    negative = words.map(lambda word: ('Negative', 1) if word in nwords else ('Negative', 0))
    allSentiments = positive.union(negative)
    sentimentCounts = allSentiments.reduceByKey(lambda x,y: x+y)
    runningSentimentCounts = sentimentCounts.updateStateByKey(updateFunction)
    runningSentimentCounts.pprint()

    # The counts variable hold the word counts for all time steps
    counts = []
    sentimentCounts.foreachRDD(lambda t, rdd: counts.append(rdd.collect()))

    # Start the computation
    ssc.start()
    ssc.awaitTerminationOrTimeout(duration)
    ssc.stop(stopGraceFully = True)

    return counts

if __name__=="__main__":
    main()

The error happens to be as follows:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_gtk3.py", line 343, in idle_draw
    self.draw()
  File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_gtk3.py", line 336, in draw
    self.get_property("window").process_updates (False)
TypeError: Couldn't find foreign struct converter for 'cairo.Context'

A: replying to above comment, 3 year forward (I'm using WSL 2 and VSCode, and X-server for GUI applications), you should use
sudo apt install python3-gi-cairo

and you are saved the hassle of changings backends.

A: In my case, python3-gi-cairo is already installed but possibly broken. So if anyone meets this case, you simply can add --reinstall in the apt install.
sudo apt install --reinstall python3-gi-cairo

Reinstall here won't break your system as when you remove (all dependants will be removed too) then installing it again.

A: See this Github discussion. For example try:
sudo apt-get install python-gi-cairo

A: The problem here is matplotlib's backend GTK3. I recommend changing it to a backend that just works for you. See https://matplotlib.org/faq/usage_faq.html
I usually do
import matplotlib
matplotlib.use('Agg')

before any import related to matplotlib.
You won't be able to see the figure but you can save it with savefig() and then open it with your image viewer.


text:
Q: how to fix IndexOutOfBoundException() within array list? In my program, I use a layered array list to remember properties about buttons (pressing certain buttons are "right" and others are "wrong") where the outer layer depends on the JPanel the buttons are found on and the inner layer is boolean variables who are either true or false. The number of buttons are random though. There is an IndexOutOfBoundsException at the line while (buttonInfo.get(buttonInfo.size() - 1).get(rightButton) == true) { so I keep getting stuck on that line but I suspect there's the same problem at buttonInfo.get(buttonInfo.size() - 1).add(rightButton, true);.
    int numberOfButtons = rnd.nextInt(5) + 2;
    buttonInfo.add(new ArrayList<Boolean>());
    JPanel newPanel = new JPanel();
    newPanel.setLayout(new GridLayout(2, 1, 5, 0));
    JLabel panelMessage = new JLabel("Choose one.");
    newPanel.add(panelMessage);
    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new GridLayout(1, 0, 0, 5));
    for (int b = 0; b < numberOfButtons; b++) {
        JButton newButton = new JButton(String.valueOf(b));
        newButton.addActionListener(this);
        buttonPanel.add(newButton);
    }
    for (int a = 0; a < (numberOfButtons/2); a++) {
        int rightButton = rnd.nextInt(numberOfButtons);
        while (buttonInfo.get(buttonInfo.size() - 1).get(rightButton) == true) {
            rightButton = rnd.nextInt(numberOfButtons);
        }
        buttonInfo.get(buttonInfo.size() - 1).add(rightButton, true);
    }

How do I fix the while statement so that it is within bounds?

A: With this line:
buttonInfo.add(new ArrayList<Boolean>());

you add only 1 item to the list buttonInfo.
This item is an initialized but empty list.
This list does not get populated (at least in the code you provided).
So this:
buttonInfo.get(buttonInfo.size() - 1).get(rightButton)

is equivalent to:
buttonInfo.get(0).get(rightButton)

whatever is the value of rightButton an error will be thrown,
because buttonInfo.get(0) is empty.


text:
Q: Текст элемента на которую нажал Подскажите пожалуйста как получить текст элемента на которую нажал
Аналог: this.Text но это работает с формой
private void ЭЛЕМЕНТ_Click(object sender, EventArgs e)
    {
        string text = ЭЛЕМЕНТ.Text;
    }

A: private void txtBox1_Click(object sender, EventArgs e)
{
    TextBox txt = sender as TextBox;

    if(txt != null)
    {
      string text  = txt.Text;
    }
}

A:     private void myHiro(object sender)
    {
        Label la = (Label) sender;
        string text  = la.Text;
    }

    private void label1_Click(object sender, EventArgs e)
    {
        myHiro(sender);
    }

    private void label2_Click(object sender, EventArgs e)
    {
        myHiro(sender);
    }

Думаю это самый лучший вариант к которому я мог прийти


text:
Q: Find median in nth range in Python I am trying to find value of every median in my dataset for every 15 days. Dataset has three columns - index, value and date.
This is for evaluation of this median according to some conditions. Each of 15 days will get new value according to conditions.
I've tried several approaches (mostly python comprehension) but I am still a beginner to solve it properly.
    value   date        index
14  13065   1983-07-15  14
15  13065   1983-07-16  15
16  13065   1983-07-17  16
17  13065   1983-07-18  17
18  13065   1983-07-19  18
19  13065   1983-07-20  19
20  13065   1983-07-21  20
21  13065   1983-07-22  21
22  13065   1983-07-23  22
23  .....    .........  ..

medians = [dataset['value'].median() for range(0, len(dataset['index']), 15) in dataset['value']]

I am expecting to return medians from the dataframe to a new variable.
syntaxError: can't assign to function call

A: Assuming you have data in the below format:
test = pd.DataFrame({'date': pd.date_range(start = '2016/02/12', periods = 1000, freq='1D'),
                                         'value': np.random.randint(1,1000,1000)})
test.head()

    date       value
0   2016-02-12  243
1   2016-02-13  313
2   2016-02-14  457
3   2016-02-15  236
4   2016-02-16  893

If you want to median for every 15 days then use pd.Grouper and groupby date:
test.groupby(pd.Grouper(freq='15D', key='date')).median().reset_index()

date        Value
2016-02-12  457.0
2016-02-27  733.0
2016-03-13  688.0
2016-03-28  504.0
2016-04-12  591.0

Note that while using pd.Grouper, your date column should be of type datetime. If it's not, convert using:
test['date'] = pd.to_datetime(test['date'])


text:
Q: Preprocessor directive for certain address space Lets say I wanted to define a directive that could take an int8_t and store it to a specified memory location say 0x0071. How would I do this?
I know I could say
#define DDRA 0xAA

And that would make DDRA = 0xAA, but how do I make it so that typing
DDRA = 0xBB;

will write 0xBB in address location 0x0071?

A: The AVR-GCC headers define I/O ports using the internal _SFR_IO8 macro, e.g. in <avr/iom328p.h>:
#define PORTB _SFR_IO8(0x05)

This macro is defined in <avr/srf_defs.h> as:
#define _SFR_IO8(io_addr) _MMIO_BYTE((io_addr) + __SFR_OFFSET)

Which, in turn, is resolved by the _MMIO_BYTE macro in the same file:
#define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

The definition of __SFR_OFFSET is… a little obscure. It has to do with the 32-byte offset between the AVR I/O space and the start of memory.
TL;DR: #define DDRA _SFR_IO8(0x71), but the standard headers for your part should be doing this already if it's actually a standard I/O port.


text:
Q: How do can I remove text from a string in Ruby when there are multiple instances of the text in the string An example of the string:
"6 red cables, 4 white cables, 9 blue cables"

I want to remove "cables" so that it reads
"6 red, 4 white, 9 blue"

I looked at the slice and sub methods, but they only remove the first instance of "cables". Can someone point me in the right direction?

A: You can use String#gsub:
2.2.0 :003 > "6 red cables, 4 white cables, 9 blue cables".gsub(" cables", "")
 => "6 red, 4 white, 9 blue"

A: Reference (compares sub vs gsub):
http://www.dotnetperls.com/sub-ruby
Answer
cleand_value = "6 red cables, 4 white cables, 9 blue cables".gsub("cables", '')
 Output "6 red , 4 white , 9 blue "

Explanation:
value = "abc abc"
# Gsub replaces all instances.
value = value.gsub("abc", "---")
puts value

Output

--- ---

You then can get rid of all the white spaces after the commas the same way.
cleaner_value = cleaned_value.gsub(", ", ",") #replaces all instances
output "6 red, 4 white, 9 blue"

Or use the other solutions and do
cleand_value = "6 red cables, 4 white cables, 9 blue cables".gsub(" cables", '') #notice the space before cables. May cause problems unless you know exactly the input


text:
Q: VBA Next Loop Not Working
This is the first time i have used VBA. I have successfully created a loop that completes what i want it too.

However when it loops to the second worksheet the "for" doesn't  appear to work. I need this to be "reset".

Please see the code below, i hope you can see why its not working:
For Each ws In wStock.Sheets
 ws.Activate
 i = 0
   For i = 1 To 4

    FullName = ActiveSheet.Cells(37, ii).Value
    Name = Split(FullName, " ")

    For intCount = LBound(Name) To UBound(Name)
      sData.Range("C" & iii).Value = Name(0)
      sData.Range("D" & iii).Value = Name(1)
    Next

    ActiveSheet.Cells(38, ii).Copy
    sData.Range("F" & iii).PasteSpecial xlPasteValues

  Address = ActiveSheet.Cells(39, ii).Value
  Address1 = Split(Address, ",")

     For intCount = LBound(Address1) To UBound(Address1)
        sData.Range("H" & iii).Value = Address1(0)
        sData.Range("J" & iii).Value = Address1(1)
     Next

    ActiveSheet.Cells(24, ii).Copy
    sData.Range("Y" & iii).PasteSpecial xlPasteValues

    ActiveSheet.Cells(18, ii).Copy
    sData.Range("Z" & iii).PasteSpecial xlPasteValues

    ActiveSheet.Cells(20, ii).Copy
    sData.Range("AA" & iii).PasteSpecial xlPasteValues

    ActiveSheet.Cells(22, ii).Copy
    sData.Range("AB" & iii).PasteSpecial xlPasteValues

    ActiveSheet.Cells(33, ii).Copy
    sData.Range("AC" & iii).PasteSpecial xlPasteValues

    ii = ii + 1
    iii = iii + 1

    Application.CutCopyMode = False
    Application.Wait (Now + TimeValue("0:00:02"))

   Next i
Next ws

I look forward to hearing from someone soon :)

A: Thanks for all your help! I managed to complete it now with the suggestion from cybernetic.nomad. I needed to reinitialise the ii and iii in the foreach loop :)

For Each ws In wStock.Sheets
  ws.Activate
  i = 0
  ii = 2
  iii = iii
  For i = 1 To 4
    FullName = ActiveSheet.Cells(37, ii).Value
    Name = Split(FullName, " ")

    For intCount = LBound(Name) To UBound(Name)
      sData.Range("C" & iii).Value = Name(0)
      sData.Range("D" & iii).Value = Name(1)
    Next

    ActiveSheet.Cells(38, ii).Copy
    sData.Range("F" & iii).PasteSpecial xlPasteValues

    Address = ActiveSheet.Cells(39, ii).Value
    Address1 = Split(Address, ",")

    For intCount = LBound(Address1) To UBound(Address1)
      sData.Range("H" & iii).Value = Address1(0)
      sData.Range("J" & iii).Value = Address1(1)
    Next

    ActiveSheet.Cells(24, ii).Copy
    sData.Range("Y" & iii).PasteSpecial xlPasteValues

    ActiveSheet.Cells(18, ii).Copy
    sData.Range("Z" & iii).PasteSpecial xlPasteValues

    ActiveSheet.Cells(20, ii).Copy
    sData.Range("AA" & iii).PasteSpecial xlPasteValues

    ActiveSheet.Cells(22, ii).Copy
    sData.Range("AB" & iii).PasteSpecial xlPasteValues

    ActiveSheet.Cells(33, ii).Copy
    sData.Range("AC" & iii).PasteSpecial xlPasteValues

    ii = ii + 1
    iii = iii + 1

    Application.CutCopyMode = False
    Application.Wait (Now + TimeValue("0:00:02"))

  Next i
Next ws


text:
Q: home network wifi packet monitoring solution My goal is to be able to capture all packets on my home network. Every packet generated by a local machine or received from the Internet. (No, I'm not trying to spy on anyone. This is my home network and I wish to capture packets for my work in developing network monitoring software. Just trying to "eat my own dog food" as they say. And yes I understand the performance limitations of forcing all my traffic into a single port.)
But I'm unable to figure out how/where I can get access to all the packets. I do have an 8-port switch with port mirroring. I've tried this:
CableModem = Switch = WifiRouter = { Machines-On-My-Network }
               ||
        MonitoringMachine

Where Machines-On-My-Network are mostly wifi-only, but a couple are wired directly to the WifiRouter. This config works fine. However, obviously my monitoring machine only sees packets that are going from a machine in my internal network to the Internet or vice versa (with NAT'd addresses); I don't get internal-only traffic.
I've also tried this config:
CableModem = WiredRouter = Switch = WifiRouterInAccessPointMode = { Machines-On-My-Network }
                             ||
                      MonitoringMachine

This has DHCP enabled in the "wired router" (actually an older wifi router with its radio disabled) and DHCP disabled in the wifi router. I say "InAccessPointMode" here but my router config has no actual access point mode -- I just disabled DHCP -- is that different? But in any case the configuration did not work well. Most of my internal machines could get addresses via DHCP but a couple of wifi-enabled machines were not receiving DHCP offers for reasons I could not determine (wireshark on the monitoring machine showed DHCP offers being sent between the routers but on the end machine no DHCP offer was showing up on its wifi port). Also, the DHCP leases on other machines were not renewing automatically as I would expect, for no apparent reason. The whole thing was flaky and my SO complained about the network not working so I reverted.
But even had this worked more reliably, I believe I would still not have seen packets between wifi-enabled machines in my local network or those between wired ports on the wifi router. So I don't know if that's really much improvement over the first configuration. I'd just see internal-external traffic plus DHCP and internal broadcast traffic.
It had occurred to me that it might be possible to do something with OpenWRT or DD-WRT to mirror everything directly to a wired port on the wifi router, but I'm still not entirely sure I'd be able to get access to all the packets (I'm not really familiar with the internal architecture of wifi routers). Also I have no experience with OpenWRT/DD-WRT and don't have either installed right now, but I would be willing to go learn that if I thought I could achieve the desired result.
For what it's worth, I currently have all TP-Link network equipment with stock firmware (TC-7610 cable modem, TL-WDR3600 for the "wired" router, TL-SG108E mirroring switch and Archer C50 wifi router).
I'd even be willing to go buy another piece of equipment if necessary. But I cannot find any wifi router that claims to support mirroring of all traffic.
Is there any way to get access to all my local traffic?


text:
Q: Integrating jQuery plugin with React I'm using jQuery nestable plugin https://dbushell.com/Nestable/ in my React App. I know that there will be problems when we use jQuery in React.
jQuery nestable solves my business needs, can't find the exact requirements in react drag/nestable components. So I have used this jQuery plugin.
The real problem is :  while dragging an element by using this jQuery plugin, it clones the DOM, apart from this everything is in react.
Initialized the jQuery nestable functionality like below:
componentDidMount() {
    this.$node = $(this.nestable); // this.nestable is a ref

    this.$node.nestable({
        group: 1,
        maxDepth: 4,
        expandBtnHTML:"",
        collapseBtnHTML:""
    });
}

the above code will let me drag the group2 among all other DOM elements like below image:

group2 is the draggable element here.
after dragged, I can see that group2 apperaed twice and I guess jQuery plugin clones the dragged element like below:

and in developer tools :

But In react developer tools, I can see that DOM is correct.

I don't know, how to rectify this problem. I'm unable to update the full code here because the code base is large.
In react developer tools, I can see that DOM is correct, and in native DOM is not !!
Is it possible to replace native DOM by virtual DOM after setState or is it possible for react to trace DOM handled by jQuery ?
I accept @ Patrick Evans comments, I'm looking for a solution here or suitable react based component like jQuery nestable.
Any help on this will be helpful.

A: React-nestable seems to have the same behavior as that jQuery plugin and could save you a lot of trouble. Mixing jQuery with React is super easy to cause trouble in my experience.

A: There is one hacky solution here:
In Nestable you have on change event. So you keep order of list as a state of component and while you drag and drop an element you can update the state and list should be re-rendered.
Please see that you can use key in list elements to optimize it a bit.
I am sure this will solve your issue.


text:
Q: How can I include a HTML-encoded "content:" character in CSS?
Possible Duplicate:
Adding HTML entities using CSS content

I have the following setup
CSS:
.header:before {
    content: "«";
}

.header:after {
    content: "»";
}

HTML:

Hello, this is some text which should be wrapped.

I'd simply like whatever is written in header to be wrapped in « («) and » (»). How can I make this work in the CSS? It's currently appearing as:

« Hello, this is some text which should be wrapped. »

rather than:

« Hello, this is some text which should be wrapped. »

A: You can't use HTML entities in CSS, but you can use Unicode hex escapes, such as
span.url:before { content: "\27e8" }
span.url:after { content: "\27e9" }

(from one of my own stylesheets -- look up the hex codepoints for the exact characters you want yourself). Notice that unlike in some other notations, hex digits follow the backslash directly, with no intervening u.


text:
Q: Incorrect values are being assigned - C This question was kind of hard to look for in the website. I tried but came back empty handed, so I'm sorry if a similar question has been asked before.
Essentially, I have a piece of code with two for loops. I believe its purpose is unnecessary for the question I'm asking. Anyway, the second time this function is called in my code (it works fine the first time) the values assigned to variables x and y are incorrect.

void draw_sprite(Sprite *sp){

 printf("outside cicle\nx: %d\ny: %d\n", (sp->x), (sp->y));

 int y;
 int x;

 int p = 0;
 for(y = sp->y; y < (sp->y + sp->height); y++){
   for(x = sp->x; x < (sp->x + sp->width); x++){
     printf("inside cicle\nx: %d\ny: %d\n", x, y);
     vg_paint_pixel(x, y, sp->map[p]);
     p++;
   }
 }

 return;
}

The program prints out:
outside cicle
x: 34
y: 30
inside cicle
x: 0
y: 136663040

As you see, before assigned, the values are 34 and 30 for x and y respectively. But after assigning them, the variables x and y become 0 and 136663040. Thanks in advance.
Definition of sp:
typedef struct {
  int x,y;
  int width, height;
  int xspeed, yspeed;
  char *map;
} Sprite;

This function's parameter (draw_sprite) is a sprite created the following way:
Sprite *sp;

sp = create_sprite(xpm, xi, yi, 0, 0);

These values are given through the terminal and I'm using an xpm map that works unless I have to move the sprite. Values xi and yi were both 30. Here is the function create_sprite:
Sprite * create_sprite(xpm_map_t xpm, int x, int y, int xspeed, int yspeed){

  Sprite *sp = (Sprite *) malloc ( sizeof(Sprite));

  if(sp == NULL){
    return NULL;
  }

  xpm_image_t img;

  sp->map = (char*)xpm_load(xpm, XPM_INDEXED, &img);

  if(sp->map == NULL){
    free(sp);
    return NULL;
  }

  sp->width = img.width;
  sp->height = img.height;
  sp->x = x;
  sp->y = y;
  sp->xspeed = xspeed;
  sp->yspeed = yspeed;

  return sp;
}

Also, as used to compile and generate said error:
int(video_test_move)(xpm_map_t xpm, uint16_t xi, uint16_t yi, uint16_t xf, uint16_t yf,
                     int16_t speed) {

  Sprite *sp;

  sp = create_sprite(xpm, xi, yi, 0, 0);

  if (sp == NULL) {
    printf("Error creating sprite.\n");
    return 1;
  }

  sp->xspeed = speed;

  draw_sprite(sp);

  if (speed > 0) {

            while(sp->x != xf || sp->y != yf)){
              destroy_sprite(sp);
              sp->x += sp->xspeed;
              sp->y += sp->yspeed;
              draw_sprite(sp);
            }

  }

return 0;
}

Finally, for the code to work, there's also destroy_sprite:
void destroy_sprite(Sprite *sp){
  if(sp == NULL){
    return;
  }

  if(sp->map){
    free(sp->map);
  }

  free(sp);
  sp = NULL;
}

A: Based on the comments the specific issue sounded like it was in
while(sp->x != xf || sp->y != yf)){
    destroy_sprite(sp);
    sp->x += sp->xspeed;
    sp->y += sp->yspeed;
    draw_sprite(sp);
}

Namely the fact that you ran into undefined behaviour as a result of using sp after freeing it. This caused (in your case) you to read garbage values resulting in an unexpected amount of iteration in your for loops.


text:
Q: Call jQuery to show a div in asp.net mvc5 I have a div tag in my HTML page which is decorated with alert class to show the alert if the login has failed. How can I show the div from asp.net mvc5 controller. I have made it hidden by writing the following script in my view(cshtml):
 $(document).ready(function () {
        $("#divAlert").hide();

    });

This is what I am trying in my controller:
public ActionResult Login(Models.userDetails UD)
        {
            LoginApplicationEntity LE = new LoginApplicationEntity();
            userDetails udd = new userDetails();
            bool g = TryUpdateModel(UD);
            if (ModelState.IsValid)
            {

                if (LE.user_details.Any(x => x.User_Name == UD.User_Name
                                        && x.User_Password == UD.User_Password))
                {
                    return RedirectToAction("LoginSuccessful", new { userName = UD.User_Name });
                }
                else
                {

                    var script = "$('#divAlert').show();";
                    return JavaScript(script);

                }
            }
            else
                return RedirectToAction("Index");

        }

This doesn't seem to be working at all. I have not done this before. Please help.

A: Use the ViewBag to store a boolean flag. On the server side when your login script fails, instead of
var script = "$('#divAlert').show();";
return JavaScript(script);

save a true value to the ViewBag like so:
ViewBag.ShowAlert = true;

Then on the client side in your view you can add some logic using Razor to interpret the flag in the ViewBag. For example:
var showAlert = @ViewBag.ShowAlert;
if (showAlert) {
    $('#divAlert').show();
}
else {
    $('#divAlert').hide();
}


text:
Q: Изменить цвет части текста в TextView Нужно сделать первые буквы красными, можно через ресурсы, можно в коде!
Как это сделать?
A: С помощью span.
TextView textView = (TextView)findViewById(R.id.textView);

final SpannableStringBuilder text = new SpannableStringBuilder("Text");
final ForegroundColorSpan style = new ForegroundColorSpan(Color.rgb(255, 0, 0));
text.setSpan(style, 0, 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
textView.setText(text);


text:
Q: After updating bashrc in cygwin the cursor starts at column 0 instead of after the prompt The issue is that, if I update PS1 in bashrc, I see that by default the cursor gets placed at column 0 instead of after the prompt, and if I type anything it starts overwriting the prompt.
I tested the same PS1 string manually by deleting the bashrc file, starting a new session and typing in the PS1 string in the terminal and it worked just fine.
I found the answer to this problem but it took me an entire day and I didn't find the exact answer after googling a lot. The basic issue was with the bashrc file format. In my case the file was in DOS format with the two character end of line.
The fix was to convert the file from DOS to UNIX format and it started working after that.
I however don't know how exactly the file format caused the issue, it wouldn't work even if "PS1='XXX'" was the only thing in the entire file, without any new lines.
The following link gives information about how to convert the file:
http://cs.nyu.edu/~yap/prog/cygwin/FAQs.html#bashrc

A: The problem is, as you said, the DOS format. More specifically: the DOS newline format.

*

*DOS newline format is a string of two characters: the carriage return character followed by the line feed character.

*Unix/Linux newline format is just one character: the line feed character.

The line feed character is often written as \n while the carriage return character is written as \r.
When you have DOS formatted .bashrc file with a PS1 declaration and bash reads the file it will read the following:
PS1='XXX'\r\n

For bash The line ends just before \n. So the variable PS1 is defined as 'XXX'\r. That is the string XXX followed by a carriage return. Carriage return means to return the carriage (the blinking cursor) to the beginning of the line. Bash does exactly that.
Read more about the newline problematic in the wikipedia article about newline.

For a quick check whether a file uses dos or unix/linux newlines you can use the file command:
$ file bashrc
bashrc: ASCII text
$ file bashrc_dosnewlines
bashrc_dosnewlines: ASCII text, with CRLF line terminators

CR is Carriage Return and LF is Line Feed.
For a detailed check use a hex dumper, for example xxd:
$ xxd bashrc
0000000: 5053 313d 2758 5858 270a                 PS1='XXX'.
$ xxd bashrc_dosnewlines
0000000: 5053 313d 2758 5858 270d 0a              PS1='XXX'..

Short explanation: the output has three columns. The first column is the offset in the file. The second and following columns are the hexadecimal representation of the file. The last column is the human readable representation of the file. Dots are used for characters which have no sensible human readable representation.
Every pair of hexadecimal digits stands for a byte, which in the case of ASCII encoding stands for a character. For example 50 is P and 53 is S. Look up the ASCII codes for the other characters.
0a is \n and 0d0a is \r\n. Whenever you see a bunch of 0d0as in your file that is a sign that your file is using dos newlines.


text:
Q: Who moved my Database property? I have the following DbContext code working in a project with EF 6.1.0, yet with 6.1.1 I get complaints that Database is not static. Any suggestions:
public class DataMonitorDbContext : DbContext
{
    private static readonly ImportConfig Config = ImportConfig.Read();
    static DataMonitorDbContext() {
        Database.SetInitializer<DataMonitorDbContext>(null);
    }

    public DataMonitorDbContext(string connString = null)
         : base(!string.IsNullOrEmpty(connString) ? connString : ConnectionString) {

    }

    public DbSet<DataRecord> DataRecords { get; set; }
    public DbSet<LogEntry> LogEntries { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder) {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Configurations.Add(new DataRecordMap());
        modelBuilder.Configurations.Add(new LogEntryMap());
    }

    private static string ConnectionString {
        get {
            return "Data Source=" + Config.DatabasePath;
        }
    }
}

A: Have you tried using the complete namespace?
System.Data.Entity.Database.SetInitializer<DataMonitorDbContext>(null);

If that works, then you have not included the correct namespaces, or you have a namespace conflict.


text:
Q: Pneumatics to mechanical Simply put it, i am trying to figure out how much momentum i can get on a crank axis based on simple pneumatic system such as this "Car pump".
What im thinking is that inertias aside, for a cylindrical object the
Effect=F x r * $\omega$ (Force x Distance * rpm)
And for a pneumatic system Effect is Q x P (Flow x Preasure)
What i am trying to do is to use a pump to put a solid cylinder in motion and i need to know the relation between the flow equation of pump and the momentum equations of the cylinder
Im guessing that these diffrent types of Effects are not equal each other (FxR =! QxP) and thus my problem.
So my question is how dose one convert effect of the pump in the picture to "F x r * $\omega$"

A: The simplest of ways i found was to use the preservation of momentum.
$F*r$ for the cylinder is equal to $P*r*A$ of the "pump" if air hiting the center of the fan blades


text:
Q: Oracle : V$TEMPFILE vs DBA_TEMP_FILES V$TEMPFILE vs DBA_TEMP_FILES? What is difference between these two views?

A: See this answer on Stack Exchange: https://dba.stackexchange.com/questions/3958/whats-the-difference-between-a-v-view-and-its-dba-equivalent
But the gist is that v$ views are sourced from control files and other instance parameters whereas dba_ views are obtained from the Data Dictionary.


text:
Q: NuGet Can't Install Packages I created a new .NET core Web App and I am trying to add packages Microsoft.EntityframeworkCore and Microsoft.AspNetCore and I am getting the error:

package restore failed rolling back packages

I have tried clearing the NuGet Caches reinstalling VS 2017 and the problem persists, note the project is brand new.

A: Please make sure your VS 2017 already upgraded to 15.3.5, you can re-run the VS 2017 installer as administrator and if there has the 'Update' button, click it to update. Then check you also installed the latest .NET Core 2.0 SDK and then create a new ASP.NET core web application, choose 'ASP.NET Core 2.0' as below to create:

Then you can successfully install those 2 packages through Manage Nuget Packages like the following:


text:
Q: Does waiting on threads defeat the purpose of a thread? Trouble with Android threading This is something that has always confused me a bit about threads.
I've got a thread that uses a LocationManager to find the Android device's current location.  I then update the UI to show that location.
In fact, I've built an entire class called LocationFinder to get the location for me.  That way I can say
String yourLocation = (new LocationFinder).getLocation();

However, the getLocation() method in LocationFinder runs on a separate thread.  So I cannot actually say
String yourLocation = (new LocationFinder).getLocation();

because the immediate value that is returned will surely not be the location, as the location takes several fractions of a second to find.  getLocation() defaults to return "notset" until an interior method sets the return value to the actual location.
Anyway, I'm baffled on how to approach this.  I don't want to block until the location is found, because it's incredibly annoying for the app to lock up for those few milliseconds.  I don't want to use AsyncTask, because that's already used when I call getLocation(), and I feel it would be a mistake to have nested AsyncTasks.
Here's the psuedocode for this hierarchy:
public class MainActivity extends Activity {

    Button locationButton = new Button(locationButtonClickListener);
    LocationFinder locationFinder = new LocationFinder();

    OnClickListener   locationButtonClickListener = new OnClickListener() {

        locationButton.setText(locationFinder.getLocation());
    }

}

public class LocationFinder {

    String city = "notYetSet";

    public String getLastLocation() {
         (new LastKnownLocationFinder).execute();
         return city;
    }

    public String getGPSLocation() {
         (new GPSLocationFinder).execute();
         return city;
    }

    private class LastKnownLocationFinder extends AsyncTask {

          protected String doInBackground {
               city = [lots of code to get last known location];
          }
    }

    private class GPSLocationFinder extends AsyncTask {

          protected String doInBackground {
               city = [lots of code to get location using GPS];
          }
    }
}

Hopefully that illustrates what I'm getting at.
Thank you.

A: You can use LocationListener. In this way your code will run as soon as the new location is available and you won't have to block a thread.
Read more: http://developer.android.com/reference/android/location/LocationListener.html

A: I would store the last city location used by the application in a preference.
I would getLastLocation() in its own background thread every time the application starts/restarts (or to be more exact, every time the application resumes its ui thread) and I would store the resulting city in the preference I spoke of above. Since that method doesn't power up the antenna and doesn't drain the battery, I wouldn't have any problem doing it that frequently.
And in answer to your original question in your title, no, "waiting on a thread doesn't defeat the purpose of using a thread". The term "waiting" in that context can be confusing. "Waiting" for a result to show up and rendering a perfectly working UI in the meantime is not the same as the UI Thread "waiting" for a result before it can draw a single pixel and freezing everything out from the UI until that result has come in. So in that sense, it doesn't matter if you're using two different async background threads as long as they're forked off from the initial UI thread (and not nested).
And then, the only code I'd place in the onclicklistener would be an async task that displays a progress spinning wheel and that does the getgpslocation in the background to insert the value into the preference, and triggers the content refresh.

A: Threads are there to divide the work up and most of the time run it parallel (asynchronous), there is pretty much no other reason for them. In some cases, one would need one thread to finish something for the second thread to deal with the result (synchronous).
Now, if you are aware that 100% of the time the work of both threads are sequential, then, theoretically, there is no need have two threads. Except sometimes people would want to encapsulate different work in different components.
As for the Android, the application starts with one thread (UI-thread / Main-thread) which is intended for controlling all the UI element changes, and should never be blocked or put to sleep or have long operations take effect on it, and that is to reduce any lag or unresponsiveness experienced by the user (which is what you seem to be doing currently).
In your case, everything seems to be done right, except for one thing, from what I can understand in your psuedocode, getLocation() will always return "notset" when called because there isn't enough time for the AsyncTask to fully execute and change the value.
You should build an interface to communicate between the LocationFinder and MainActivity to send the location signal once found, even possibly just send the location right away.
public class LocationFinder {

    private CommunicateLocationFinder mCommunicate;

    public interface CommunicateLocationFinder {
        void LocationFinderSendGpsLocation(String location);
    }

    public LocationFinder (Activity activity){
        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCommunicate = (CommunicateLocationFinder) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement CommunicateLocationFinder");
        }
    }

    private class GpsLocationFinder extends AsyncTask {
        protected String doInBackground {
            /*
             * Your work here
             */
        }

        protected void onPostExecute (String result){
            mCommunicate.LocationFinderSendGpsLocation(result);
        }
    }

    /*
     * Rest of your code
     */
}

public class MainActivity extends Activity implements
        LocationFinder.CommunicateLocationFinder {

    @Override
    public void LocationFinderSendGpsLocation(String location){
        locationButton.setText(location);
    }

    /*
     * Rest of your code
     */

}

I hope that helps, let me know, cheers.


text:
Q: CRSF Token Interfering With TDD - Is there a variable that stores csrf output? So, I kept returning a Failing test in Django when comparing expected to actual html with form input, so I printed out the result and realized the difference was the rather simple line, caused by my {% csrf_token %}, as follows:
<input type='hidden' name='csrfmiddlewaretoken' value='hrPLKVOlhAIXmxcHI4XaFjqgEAMCTfUa' />

So, I expect a simple answer, but I haven't been able to find it:
How do I render the result of a csrf_token for use in testing?
Here's the Test setup and failure:
def test_home_page_returns_correct_html_with_POST(self):
        request = HttpRequest()
        request.method = 'POST'
        request.POST['item_text'] = 'A new list item'

        response = home_page(request)

        self.assertIn('A new list item', response.content.decode())

        expected_html = render_to_string(
        'home.html',
        {'new_item_text': 'A new list item'},
******this is where I'm hoping for a simple one-line mapping******

    )
    self.assertEqual(response.content.decode(), expected_html)

Here's the rendering from views.py:
def home_page(request):
    return render(request, 'home.html', {
        'new_item_text': request.POST.get('item_text'),
    })

And here's the test failure, when I run the test with python manage.py test
FAIL: test_home_page_returns_correct_html_with_POST (lists.tests.HomePageTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\Me\PycharmProjects\superlists\lists\tests.py", line 29, in test_home_page_returns_correct_html_with_POST
    self.assertEqual(response.content.decode(), expected_html)
AssertionError: '<!DO[298 chars]     <input type=\'hidden\' name=\'csrfmiddlew[179 chars]tml>' != '<!DO[298 chars]     \n    </form>\n\n    <table
 id="id_list_t[82 chars]tml>'

----------------------------------------------------------------------

A: Judging by the code snippet you provided, it seems you are working through the examples from the book "Test Driven Development with Python", but are not using Django 1.8.
This post from the book's Google Groups discussion addresses the test failure, as you are experiencing it:
https://groups.google.com/forum/#!topic/obey-the-testing-goat-book/fwY7ifEWKMU/discussion
And this GitHub issue (from the book's official repository) describes a fix consistent with your question:
https://github.com/hjwp/book-example/issues/8

A: If I may, I would like to propose a better way of performing this test, using the built-in Django test client. This will handle all CSRF checks for you, as well as being easier to use. It would look something like this:
def test_home_page_returns_correct_html_with_POST(self):
    url = reverse('your_home_page_view_url_name')
    response = self.client.post(url, {'item_text': 'A new list item'})
    self.assertContains(response, 'A new list item')

Note that this also uses assertContains, which is an assertion provided by the Django test suite.

A: The CSRF token is part of the template context data that you have available if you are using the Django TestCase classes:
response = self.client.get(url)
print(response.context)

https://docs.djangoproject.com/en/1.9/topics/testing/tools/#django.test.Response
The key is csrf_token.
https://docs.djangoproject.com/en/1.9/_modules/django/template/context_processors/
EDIT:
As you have asked how you can compare the HTML rendered in your test to the output by your test server:
Because you are using {% csrf_token %} in your template you cannot provide the CSRF token form the response context to the render_to_string method to make it use the same value. Instead, you would have to replace it in the result of render_to_string, maybe by first looking for the input element using selenium (making that a test itself). However, how useful this test is is questionable. It will only help to assure that a CSRF token is present but that is already checked on the server in regular work mode, anyway.
Basically, you should test anything that you are influencing directly in your code and not anything offered by Django magic. E.g. if you are doing custom form validation you should test for that and not for any validation that is brought to you by Django. If you are changing querysets (custom filtering etc.) in ListViews or get_object() in DetailViews you should check that the resulting lists and 404 errors happen according to your custom code.

A: I ran in to this problem too (using latest python 3.6.12 and django 1.11.29 according to the 2nd edition of the book).
My solution doesn't answer your question 'how do I render the token' but it does answer 'how do I pass the test that compares the rendered template to the returned view response'.
I used the following code:
class HomePageTest(TestCase):
    def remove_csrf_tag(self, text):
        '''Remove csrf tag from text'''
        return re.sub(r'<[^>]*csrfmiddlewaretoken[^>]*>', '', text)

    def test_home_page_is_about_todo_lists(self):
        # Make an HTTP request
        request = HttpRequest()

        # Call home page view function
        response = home_page(request)

        # Assess if response contains the HTML we're looking for

        # First read and open the template file ..
        expected_content = render_to_string('lists/home.html', request=request)

        print(len(response.content.decode()))

        # .. then check if response is equal to template file
        # (note that response is in bytecode, hence decode() method)
        self.assertEqual(
            self.remove_csrf_tag(response.content.decode()),
            self.remove_csrf_tag(expected_content),
        )

PS: I based this on this answer.

A: I had similar problem so made a function to remove all the csrf tokens.
def test_home_page_returns_correct_html(self):
    request = HttpRequest()

    # Removes all the csrf token strings
    def rem_csrf_token(string):
        # Will contain everything before the token
        startStr = ''
        # Will contain everything after the token
        endStr = ''
        # Will carrry the final output
        finalStr = string

        # The approach is to keep finding the csrf token and remove it from the final string until there is no
        # more token left and the str.index() method raises value arror
        try:
            while True:
                # The beginning of the csrf token
                ind = finalStr.index('<input type="hidden" name="csrfmiddlewaretoken"')
                # The token end index
                ind2 = finalStr.index('">', ind, finalStr.index('</form>'))

                # Slicing the start and end string
                startStr = finalStr[:ind]
                endStr = finalStr[ind2+2:]

                # Saving the final value (after removing one csrf token) and looping again
                finalStr = startStr +endStr
        except ValueError:
            # It will only be returned after all the tokens have been removed :)
            return finalStr

    response = home_page(request)
    expected_html = render_to_string('lists/home.html')
    csrf_free_response = rem_csrf_token(response.content.decode())

    self.assertEqual(csrf_free_response,
                    expected_html, f'{expected_html}\n{csrf_free_response}')


text:
Q: Does AWS service clients automatically refresh tokens? Does AWS service clients like AmazonS3Client  and AmazonElastiCacheClient automatically refresh expired tokens when provided with a custom implementation of AWSCredentialsProvider with the refresh method implemented to get fresh tokens using AWSSecurityTokenServiceClient?
I use the JAVA SDK for my development.


text:
Q: Struts2 - Cross domain redirect using POST method struts 2.0.11 - Currently I'm in my local machine and have two different web applications running under tomcat (struts 2.0.11) and weblogic respectively.
Tomcat:
Link: localhost:8080/retail/order.action
struts.xml:
<action name="order" method="execute" class="com.retail.action.OrderAction">
  <result name="redirect" type="redirect">
    <param name="location">${weblogicURL}?user=${user}</param>
  </result>
</action>

I have necessary attributes like 'weblogicURL' and 'user' in OrderAction in Tomcat Web app. Now this is working and weblogic resource is getting accessed as GET method like the following,
localhost:7020/retail/orderPortal?user=test

I would like to access weblogic using POST method from tomcat, is there any way to achieve that?

A: This is what the redirect documentation says

session or with web parameters (url?name=value) which can be OGNL expressions.

Which indicates that we can only send data only by get method and what you are trying to do is not possible as of now.
One possible solution seems to use Action Chaining.Please go through the official document for details

*

*Action-Chaining


text:
Q: error correction code upper bound If I want to send a d-bit packet and add another r bits for error correction code (d>r)
how many errors I can  find and correct at most?

A: You have 2^d different kinds of packets of length d bits you want to send.  Adding your r bits to them makes them into codewords of length d+r, so now you have 2^d possible codewords you could send.  The receiver could get 2^(d+r) different received words(codewords with possible errors).  The question then becomes, how do you map those 2^(d+r) received words to the 2^d codewords?
This comes down to the minimum distance of the code.  That is, for each pair of codewords, find the number of bits where they differ,  then take the smallest of those values.
Let's say you had a minimum distance of 3.  You received a word and you notice that it isn't one of the codewords.  That is, there's an error.  So, for the lack of a better decoding algorithm, you flip the first bit, and see if its a codeword.  If it isn't you flip it back and flip the next one.  Eventually, you get a codeword.  Since all codewords differ in 3 positions, you know this codeword is the "closest" to the received word, since you would have to flip 2 bits in the received word to get to another codeword.  If you didn't get a codeword from flipping just one bit at a time, you can't figure out where the errors are, since there are multiple codewords you could get to by flipping two bits, but you know there are at least two errors.
This leads to the general principle that for a minimum distance md, you can detect md-1 errors and correct floor((md-1)/2) errors.  Calculating the minimum distance depends on the details of how you generate the codewords, otherwise known as the code.  There are various bounds you can use to figure out an upper limit on md based on d and (d+r).
Paul mentioned the Hamming Code, which is a good example.  It achieves the Hamming bound.  For the (7,4) Hamming code, you have 4 bit messages and 7 bit codewords, and you achieve a minimum distance of 3.  Obviously*, you are never going to get a minimum distance greater than the number of bits you are adding so this is the very best you can do.  Don't get too used to this though.  The Hamming code is one of the few examples of a non-trivial perfect code, and most of those have a minimum distance that is less than the number of bits you add.
*It's not really obvious, but I'm pretty sure it's true for non-trivial error correcting codes.  Adding one parity bit gets you a minimum distance of two, allowing you to detect an error.  The code consisting of {000,111} gets you a minimum distance of 3 by adding just 2 bits, but it's trivial.

A: You should probably read the wikipedia page on this:
http://en.wikipedia.org/wiki/Error_detection_and_correction
It sounds like you specifically want a Hamming Code:
http://en.wikipedia.org/wiki/Hamming_code#General_algorithm
Using that scheme, you can look up some example values from the linked table.


text:
Q: PowerShell code to check the exported filename first before Export-Mailbox as .PST doesn't work I am trying to fix the PowerShell code below:
Input file is First Last name in a .TXT format (one column), which then I was able to convert them into the proper Output.CSV file like:
"WindowsEmailAddress"
"Russel.Peters@domain.com"
"Amalia.Zebech@domain.com"
"Henry.Ho@domain.com"
"Bing.Fang@domain.com"
"Karina.Michaels@domain.com"

This is the code:
$Server = 'PRDFILESVR01-VM'
$ServerBackupUNCPath = "\\$Server\PST"
$InputCSVPath = 'C:\LOGS\Input.csv'
$ExportCSVPath = 'C:\LOGS\Output.csv'
$ExportExistsCSVPath = 'C:\LOGS\Exists.csv'

Import-PSSession ($Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://PRDEXC03-VM/Powershell/ -Authentication Kerberos)

$Users = Get-Content -Path $InputCSVPath
&{
    foreach ($User in $Users) {
        Write-Host "Processing.... $User"
        Get-Mailbox $User.ToString() | Select WindowsEmailAddress
    }
} | Export-Csv -Path $ExportCSVPath -NoTypeInformation

Import-Csv -Path $ExportCSVPath |
  Get-MailBox |
  % {
    Write-Host "Processing .... $($_.Name) ..." -ForegroundColor Green

    # Check if the file already exist or not
    $FileResult = Test-Path -Path "$ServerBackupUNCPath\$($_.WindowsEmailAddress).PST" -PathType Leaf

    if ( $FileResult -ne $True ) {
        #If there is no exported .PST file on the destination folder, then begin the export mailbox command and log if there any error to the AliasName.LOG file:
        New-MailboxExportRequest -Mailbox $_ -FilePath "$ServerBackupUNCPath\$($_.WindowsEmailAddress).PST" -BadItemLimit 50 -AcceptLargeDataLoss -WhatIf
        # wait until error or processed:
        while ( ($req = Get-MailboxExportRequest $_) | ? { $_.Status -match 'Queued|InProgress' } )
        { Start-Sleep 180 }
        $req | Get-MailboxExportRequestStatistics -IncludeReport | Select -Expand Report | Out-File "C:\LOGS\$($_.WindowsEmailAddress).log"
    } else {
        Write-Output "The user $($_.WindowsEmailAddress).PST file is already existing"
        #Append the list of already existing list of users C:\LOGS\Exist.csv
        ($_.Alias) | Out-File -FilePath $ExportExistsCSVPath -Append
    }

    # I assume, whetever line I put here will be executed regardless of any of the condition above is met or not
    Write-Host "Removing Mailbox $($_.WindowsEmailAddress)" -ForegroundColor Red
    Remove-Mailbox -Identity $_ -Confirm $false -WhatIf

  }

However, there is something not right hence the Get-Mailbox is seems to be the cause of this issue as the below error shows:
The operation couldn't be performed because object '"WindowsEmailAddress"' couldn't be found on 'PRDDC01-VM-VM.domain.com'.
+ CategoryInfo          : NotSpecified: (:) [Get-Mailbox], ManagementObjectNotFoundException
+ FullyQualifiedErrorId : [Server=PRDEXC03-VM,RequestId=c061c8a3-72b6-469a-8109-726e1b015441,TimeStamp=21/08/2018 12:12:13 AM] [FailureCategory=Cmdlet-ManagementObjectNotFoundException] ED9B9A7,Microsoft.Exchange.Management.RecipientTasks.GetMailbox
+ PSComputerName        : PRDEXC03-VM

The operation couldn't be performed because object '"Russel.Peters@domain.com"' couldn't be found on 'PRDDC01-VM-VM.domain.com'.
    + CategoryInfo          : NotSpecified: (:) [Get-Mailbox], ManagementObjectNotFoundException
    + FullyQualifiedErrorId : [Server=PRDEXC03-VM,RequestId=c061c8a3-72b6-469a-8109-726e1b015441,TimeStamp=21/08/2018 12:12:13 AM] [FailureCategory=Cmdlet-ManagementObjectNotFoundException] FE47387B,Microsoft.Exchange.Management.RecipientTasks.GetMailbox
    + PSComputerName        : PRDEXC03-VM

The operation couldn't be performed because object '"Amalia.Zebech@domain.com"' couldn't be found on 'PRDDC01-VM-VM.domain.com'.
    + CategoryInfo          : NotSpecified: (:) [Get-Mailbox], ManagementObjectNotFoundException
    + FullyQualifiedErrorId : [Server=PRDEXC03-VM,RequestId=c061c8a3-72b6-469a-8109-726e1b015441,TimeStamp=21/08/2018 12:12:13 AM] [FailureCategory=Cmdlet-ManagementObjectNotFoundException] 3DFB1CD9,Microsoft.Exchange.Management.RecipientTasks.GetMailbox
    + PSComputerName        : PRDEXC03-VM

The operation couldn't be performed because object '"Karina.Michaels@domain.com"' couldn't be found on 'PRDDC01-VM-VM.domain.com'.
    + CategoryInfo          : NotSpecified: (:) [Get-Mailbox], ManagementObjectNotFoundException
    + FullyQualifiedErrorId : [Server=PRDEXC03-VM,RequestId=c061c8a3-72b6-469a-8109-726e1b015441,TimeStamp=21/08/2018 12:12:13 AM] [FailureCategory=Cmdlet-ManagementObjectNotFoundException] 3DFB1CD9,Microsoft.Exchange.Management.RecipientTasks.GetMailbox
    + PSComputerName        : PRDEXC03-VM

A: I don't think Get-Mailbox returns WindowsEmailAddress in your first get - ie Get-Mailbox $User.ToString() | Select WindowsEmailAddress
Ref: https://msdn.microsoft.com/en-gb/library/microsoft.exchange.data.directory.management.mailbox_members.aspx


text:
Q: Custom response with http-proxy-middleware package In our project we're using the "http-proxy-middleware"(https://www.npmjs.com/package/http-proxy-middleware) npm package for proxy.
There is the "onProxyRes" function to subscribe to http-proxy's event.
And there is an example of that function:
function onProxyRes(proxyRes, req, res) {
  proxyRes.headers['x-added'] = 'foobar' // add new header to response
  delete proxyRes.headers['x-removed'] // remove header from response
}

I'm just interesting is it possible somehow based on proxyRes write changed response in res object and do not copy data directly from proxyRes object?
Just example:
proxyRes(readable stream contains the following data: {"url": "http://domain/test"}, I'd like to modify that response and have res with data like that: {{"url": "http://changedDomain/test"}} and do not copy data from proxyRes directly

A: Maybe it looks ugly little bit, but I'm able to manage that with the following code:
function onProxyRes(proxyResponse, request, serverResponse) {
  var body = "";
  var _write = serverResponse.write;
  proxyResponse.on('data', function (chunk) {
    body += chunk;
  });

  serverResponse.write = function (data) {
    try{
      var jsonData = JSON.parse(data);
      // here we can modify jsonData
      var buf = Buffer.from(JSON.stringify(jsonData), 'utf-8');
      _write.call(serverResponse,buf);
    } catch (err) {
      console.log(err);
    }
  }

}

A: I don't think it's necessary to copy data to res as proxyRes already has changedDomain.
Here is the set up I implemented:
const express = require('express');
const httpProxy = require('http-proxy-middleware');

const app = express();

app.use('/api', httpProxy({ target : 'sometarget.com', changeOrigin : true, onProxyRes})

function onProxyRes (proxyResponse, request, response) {
  console.log('proxyResponse', proxyResponse.headers);
  console.log('response', response.headers);
}

// Results
/*
proxyResponse { date: 'Wed, 02 Jan 2019 12:06:40 GMT',
  server: 'Apache',
  location: 'http://sometarget.com/api',
  'cache-control': 'max-age=30',
  expires: 'Wed, 02 Jan 2019 12:07:10 GMT',
  'content-length': '231',
  connection: 'close',
  'content-type': 'text/html; charset=iso-8859-1' }
response undefined
*/

Everything you'll need will be in proxyRes unless you have a specific use for response...


text:
Q: $(x_1,x_2,…,x_{117})A$=$(x_{117},x_1,x_2,…,x_{116})$ Find detA A is a matrix such that $(x_1,x_2,…,x_{117})A$=$(x_{117},x_1,x_2,…,x_{116})$.
Find $detA$
Is the answer 1?

A: Hint: What does $A^{2}$ do? What does $A^{117}$ do?

A: $$
\begin{align}
x^{T} \mathbf{A} & = \hat{x} \\
%
\left[ \begin{array}{ccccccc}
 x_{1} & x_{2} & x_{3} & x_{4} & x_{5} & x_{6} & x_{7}
\end{array} \right]
%
\left[
\begin{array}{c|cccccc}
 0 & 1 & 0 & 0 & 0 & 0 & 0 \\
 0 & 0 & 1 & 0 & 0 & 0 & 0 \\
 0 & 0 & 0 & 1 & 0 & 0 & 0 \\
 0 & 0 & 0 & 0 & 1 & 0 & 0 \\
 0 & 0 & 0 & 0 & 0 & 1 & 0 \\
 0 & 0 & 0 & 0 & 0 & 0 & 1 \\\hline
 1 & 0 & 0 & 0 & 0 & 0 & 0 \\
\end{array}
\right]
%
& =
%
\left[ \begin{array}{c}
 x_{7} \\ x_{1} \\ x_{2} \\ x_{3} \\ x_{4} \\ x_{5} \\ x_{6}
\end{array} \right]
%
\end{align}
$$
$$
\det \mathbf{A} = 1
$$
As pointed out by @lhf, the repeated action keeps shifting the list to the right:
$$
\hat{x}^{T} \mathbf{A} =
\left[ \begin{array}{c}
  x_{6} \\ x_{7} \\ x_{1} \\ x_{2} \\ x_{3} \\ x_{4} \\ x_{5}
\end{array} \right]
$$


text:
Q: remove border that appears when clicking button I have a rating form in which when I click on a star, the following border appears:

implement the following example: angular-material-star-rating
How can I remove this border?

A: To remove the default focus, use the following code:
:focus {
   outline:none;
}

You can then control the focus border color either individually by element
:focus {
   outline:none;
    border:1px solid red
}

A: Add this rule to the element
outline: none


text:
Q: How can the total amount of energy in the universe be zero? First of all, it is important to note that I'm not very savvy in neither general relativity nor any other area of expertise that answering this question may require. Therefore, I mean for the question to be answered in layman's terms.
Okay, now to the question itself: as far as I understand, for a given energy total in a system, its contents can theoretically be put into any other configuration of energies with the same total sum (if that makes sense). Therefore, if that sum is zero, the contents can be configured into, basically, 'nothing', which also has an energy total of zero.
However, with the universe, the only sources of negative energy are the fundamental forces. I think it may be reasonable to put all forces other than gravity aside, as only gravity is generated (sorry for funky wording) by something which itself is another source of energy (mass), and all the other forces eventually cancel out. If we also ignore the dark energy, we are left with a collection of masses that will eventually crunch together. Here is the problem I have with this: where will the mass go? Even if the potential energy of every point in the universe is zero (i.e. all the mass in the universe has now been smushed into a point), there is still mass to deal with, right?
I know I am probably wrong in many, many places in this question, but can you explain the general, underlying flaw behind my reasoning?

A: It really depends.. Settle for Feynman asserting the energy is conserved in the universe as a whole. Now you can call it $0$ if you wish. :)
According to Noether's Theorem time translation symmetry means conservation of, guess what.
Look at a free particle with momentum $p$ and energy $p^2/2m$.
So it has $0$ energy at rest? No. Einstein relation, and expand once in $p^2$
$$E=c \sqrt{m^2c^2+p^2} \approx mc^2+p^2/2m+...$$
What about the negative energies hiding there? What the hell does that mean anyway?
It has an interesting meaning to it, but the important thing is the exclusion principle for electrons for example, and the apparent positive energy they all have, if there is any. They'd rather take a more relaxed lower energy. They cannot because there is a sort of sea of positrons occupying the negative band.
No one likes Smushed "points" of mass/energy. Some variants of the general theory are free of them.
If you do want to think of a crunch of a collection of masses to a small region which looks like a point, the rest of the universe is not "void". Wait a tiny moment and you have the particle but a tad later and not mathematically vanishing velocity. There can be space like interaction from the future point to the present point as felt by the present point, but upon reaching that future nothing is sent back. That's because the the now past particle knows it is coming and counters it with anti-interaction. :). And that's crazy, i.e virtual. that's why it is not infinite, and not 0.
You say you are probably wrong in many ways like it is a bad thing.
If you come to realize you are wrong at some point about something you gain a lot more than reading what you were thinking in an academic paper, for instance.
I'm no expert but I know enough to get numerous absurdities that would counter a $0$ energy pointy, something..?
On the other hand I can just tell you to look at 15 solutions to EFE. I can tell you to go read about the Dirac equation or better to see what it does to GR if taken as matter.
I can say that before and towards your crunch you still have a continuous symmetry and it is lost at the crunch and $Q$, the conserved Noether charge operator now proves a new massless boson crying lost energy due to a new vacuum state (Nambu-Goldstone boson for you). You take a symmetry you get energy, positive, energy. and you also get to avoid the rabbit hole of no more physics :).
Yesterday you turned off dark energy and imagined a "crunch" can occur as a result. Go back a bit because you have to consider dark energy after you switch it on or off... If you don't then you don't get to be wrong! And, you cannot deduce any conclusion about the conditions for the $0$ energy universe you postulate as a question.

A: The energy density of a gravitational field is negative, so it can serve as a "reservoir" of negative energy.  If the total (negative) energy in gravitational fields throughout the universe is precisely equal in magnitude to the (positive) energy throughout the universe that resides in electromagnetic fields, kinetic energy of moving masses, "bare" particle rest masses, etc., then the total energy of the universe can be zero.  However, it is not known whether the total energy of the universe is positive, zero, or negative.


text:
Q: Can I set spine and ticks in rcParams? I tend to use the following axes options in my Matplotlib (v1.3.1) plots:
        ax.spines["top"].set_visible(False)
        ax.spines["bottom"].set_visible(True)
        ax.spines["right"].set_visible(False)
        ax.spines["left"].set_visible(True)

        ax.get_xaxis().tick_bottom()
        ax.get_yaxis().tick_left()

        ax.tick_params(axis="both", which="both", bottom="off", top="off",
                labelbottom="on", left="off", right="off", labelleft="on")

This works fine after grabbing the current axis, but I was wondering whether I could make all this default behaviour by setting things in rcParams?

A: As mentioned in ImportanceOfBeingErnest's comment, this is now possible:
plt.rcParams['axes.spines.top'] = False
plt.rcParams['axes.spines.bottom'] = False
plt.rcParams['axes.spines.left'] = False
plt.rcParams['axes.spines.right'] = False

For multiple rcParams use a dict:
plt.rcParams.update({'axes.spines.top': False, 'axes.spines.right': False})

A: I had the same problem and have, between this answer and have found the following:
Matplotlib 1.3.1 does not recognize any of these inputs as rcParams:
>>> plt.matplotlib.__version__
'1.3.1'
>>> plt.rcParams['axes.spines.top'] = False
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\<username>\Software\WinPython-64bit-2.7.6.4\python-2.7.6.amd64\lib\site-packages\matplotlib\__init__.py", line 811, in __setitem__
    See rcParams.keys() for a list of valid parameters.' % (key,))
KeyError: 'axes.spines.top is not a valid rc parameter.See rcParams.keys() for a list of valid parameters.'

Matplotlib 1.5.1 does, however:
In[1]: from matplotlib import pyplot as plt
In[2]: plt.matplotlib.__version__
Out[2]: '1.5.1'
In[3]: plt.rcParams
Out[3]:
RcParams({u'agg.path.chunksize': 0,
          [...]
          u'axes.spines.bottom': True,
          u'axes.spines.left': True,
          u'axes.spines.right': False,
          u'axes.spines.top': False,
          [...]
In[4]: x = np.linspace(0, 6)
  ...:     y = np.sin(x)
  ...:     plt.close('all')
  ...:     plt.plot(x,y,'k-')

To remove the ticks as well, I had to removee them after the fact, using ax.tick_params(top="off",  right="off"). I did not find anything related in rcParams.
I also tested matplotlib 2.2.3. There, the axes.spine.* and got no ticks on the top and bottom without specifying any additional parameters. Either the entries in the matplotlibrc remove the whole axis, including tick marks, or the new ytick.right, xtick.top entries in the rcParams dictionary are defaulting to False

Unfortunately, that still hides the last gridline on the right-hand side if it is exactly at the edge, even though the top gridline is shown under the same circumstances.
==> in other words:

*

*version 1.3.1 does not have a global switch and needs ax.spines["top"].set_visible(False) applied.

*1.5.1 can remove the lines, globally, using the method Dan suggested (set axes.spine.top and axes.spine.right to  False), but not the ticks, which still need the ax.tick_params() command

*still later versions (not sure which version introduced it) also have ytick.right and xtick.top settings which can be set to True or False to also omit the ticks on those edges.


text:
Q: late static binding in closure PHP5.5 vs 5.6 Why new static in the closure (in a class static method) is equal to new self in PHP5.5, while it's properly bound in PHP5.6 ?
Given:
abstract class Parent {
    public function __construct($something)
    {
        $this->something = $something;
    }

    public static function make($array)
    {
        return array_map(function ($el) {
            return new static($el);
        }, $array);
    }
}

class Child extends Parent {

}

then
Child::make($someArray);
// PHP5.5 FatalError: cannot instantiate abstract class Parent
// PHP5.6 works fine, as expected

In 5.5 this will work as expected:
public static function make($array)
{
    $child = get_called_class();

    return array_map(function ($el) use ($chlid) {
        return new $child($el);
    }, $array);
}

but why is this happening? I haven't found any mentions on php.net concerning static binding changes in 5.6.

A: Looks like this bug, fixed in 5.5.14.


text:
Q: Conitnue to read through NUL I got a .dat file, encoded in ANSI which contains NUL caracters (not only !).
I wan't to read it into a str object iot cut something in the whole str obtained.
But file.read() stops when the first NUL is reached.
I'm lost :)
My code :
file=open(source, mode='rt')
fulltext=file.read()
print(fulltext)

NUL is show with Notepad++ I'm on Windows XP, with PortablePython 3.2
The file is a special DAT file that can be edited with notepad as a text.

A: If you want to read bytes like 0, chances are your file is a binary file. Read in binary mode rb instead of text mode rt.

A: As Evert has commented in my question, the problem was focused on the use of Pyscripter !
So, this question is closed :)


text:
Q: Tomcat Folder as Classpath? I have a really weird issue with Tomcat that I can't seem to fix. My issue is that it seems that Tomcat sees the Tomcat folder (C:/Program Files/Apache Software Foundation/Tomcat 6) as the classpath. This issue comes into effect when I set my JAVA_OPTS to reference my properties file.
-Ddoiadmin.properties.file=doiadmin.properties

I have the properties file in my classpath (WEB-INF/classes) however when I start Tomcat, I get the error:
com.XXXXX.commons.servicecore.ServiceConfigurationException: Could not find main properties file (directly or on classpath): [doiadmin.properties]

The only way to get the application to properly start is to put the properties file in the Tomcat folder. This is annoying and not something I want to do in the long run.
I scoured the internet and asked a few people to no avail. Does anyone have any suggestions?
Thanks for any help
-Tim

A: If I understand you correctly I would do this:
In you web.xml have the following:
<env-entry>
  <env-entry-name>RootPathPropertyName</env-entry-name>
  <env-entry-type>java.lang.String</env-entry-type>
  <env-entry-value>uk.co.foo.project.path</env-entry-value>
</env-entry>

<env-entry>
  <env-entry-name>RootPathPropertyValue</env-entry-name>
  <env-entry-type>java.lang.String</env-entry-type>
  <env-entry-value>d:/foo/bar</env-entry-value>
</env-entry>

In you context set up a PlaceHolderConfigurer as follows:
<!-- Properties Configuration -->
<bean id="propertyConfigurer"
     class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="order" value="1"/>
  <property name="locations">
    <list>
      <value>file:${uk.co.foo.project.path}/config/foo.properties</value>
    </list>
  </property>
</bean>

In your tomcat config you can override the default location with the following in the file /conf/Catalina/localhost/foo.xml:
<Context path="foo" >
<Environment name="RootPathPropertyValue" value="c:/foo/bar" type="java.lang.String" override="false"/>
</Context>


text:
Q: Why does the id number of a deleted record gets skipped, when new record is added to the database (MySQL/Knex)? I am learning knex, express js and MySQL and came across an issue I cannot figure out.
What I mean is, I have, say, 5 records in my database, with IDs 1, 2, 3, 4, 5.
After I delete the record with ID number 5, and add a new one in its place, the new record gets the ID number 6, instead of 5. When I delete that new record too, and add a new one, it will be 7, and so on...  I believe that there is not really a problem, it is that I don't fully understand how indexing works...
Help is greatly appreciated, thanks in advance!

A: The Auto index uses a sequence internally which gets selected as the value. You can read up on SQL sequences they are not very complicated.

A: That's not the only case where AUTO_INCREMENT ids are "burned".
InnoDB grabs the next id when it needs it, but it may later decide to ROLLBACK or that a UNIQUE constraint is violated, etc.  Or, as you are doing, DELETE the row later.
All this is for making AUTO_INCREMENTs efficient.  Do not assume anything about them other than that they are unique.
"How indexing works" -- Think of a list of people in a club or company or city, and one of them leaves or dies or whatever.  That slot is lost.


text:
Q: My domain broke somehow Greetings and nice to meet you all.
I have a networking issue that I can't seem to overcome. Please be gentle as my networking foo is poor and I am new here.  Some specifics:

My web server. I'm hosting a domain simply to provide access to my files via dokuwiki and owncloud. I set this up a couple of years ago and it has worked fine, until it simply stopped last week. In my efforts to get it back up and running, I reinstalled the web server and my desktop. I have very good backups, but of course restoring backups hasn't solved anything.
The server:
Linux 4.4.74-desktop-1.mga5 #1 SMP Mon Jun 26 07:50:58 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
httpd -V
Server version: Apache/2.4.10 (Unix)
OpenSSL 1.0.2k  26 Jan 2017
Internet connection is fiber from my ISP (Yucca.net, formerly Plateautel.net) through a Buffalo Airstation WXR-1900DHP (Version 2.37)
Ports 80 and 443 are forwarded from the internet side of my router to the internal ip of my webserver
My domain registrar is namecheap.com.
The domain is: adams-lan.org

When this thing was working I could access my web server from inside the LAN simply by pointing my desktop's browser to https: //adams-lan.org/ dokuwiki, for example.
Now, pointing a browser to https: //adams-lan.org/  takes me to my router config page. Pointing my browser to https: //23.252.218.244 also takes me to the router's config page.  It didn't used to do that.
Ports are open according to nmap:
PORT     STATE SERVICE
80/tcp   open  http
443/tcp  open  https
8000/tcp open  http-alt

As near as I can tell, packets are moving from my ISP to my server and slamming against my router. I don't know why.
nslookup shows me the domain:
    nslookup adams-lan.org
Server:         208.67.222.222
Address:        208.67.222.222#53

Non-authoritative answer:
Name:   adams-lan.org
Address: 23.252.218.244

nslookup does not work in the other direction
nslookup 23.252.218.244
;; Got SERVFAIL reply from 208.67.222.222, trying next server
Server:         208.67.220.220
Address:        208.67.220.220#53

** server can't find 244.218.252.23.in-addr.arpa: SERVFAIL

Does my isp need a PTR record?
Pinging hostname stalls, but does eventually respond.
Pinging IP kicks right off, responds nicely.
iptables are down
iptables -t nat -L
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination
RETURN     all  --  192.168.122.0/24     base-address.mcast.net/24

The ip is not static and it's being tracked by ddclient.
What am I missing?
I'd really appreciate any help I can get.
Note: internal links are intentionally broken because I don't have enough cred yet.

A: The issue here is that your router is not configured to forward packets to your computer.  Routers generally have a couple of ways of doing it (and call the same thing by various names).   The solutions need to be programmed in your router.
The more appropriate solution is to map specific ports to IP addresses on your LAN.  This is often called "Port Forwarding" or "Pinholing", and is the more secure option.
An alternative is to set up a "DMZ" and forward all incoming traffic without an associated outbound port to a specific IP - the IP address of your server.  This does, however, mean your server is more exposed to the Internet then it need be.
(If you are landing on the router page when you enter an IP address, its not a DNS problem.  Similarly the issues with "Reverse DNS" are really irrelevant to your problem)


text:
Q: Rolling volatility estimation using GARCH family of models in python Problem: Correct usage of GARCH(1,1)
Aim of research: Forecasting volatility/variance.
Tools used: Python 3.3 with arch library
I am trying to obtain out-of-sample estimation of volatility using a fitted GARCH (or other model from the library), so I can compare it with other approaches - like recurrent neural networks.
However, I haven't found a way, how to use the fitted model in similar way to the R as  mentioned here, where they fit the model and then obtain rolling forecast one period ahead.
I have looked through many examples and tutorial, but they always use in-sample estimates, when they already have the residuals as in example with in-sample estimation. I would like to "feed" the model historical data and obtain n periods ahead prediction (e.g. day ahead).
I believe the answer is very simple, however, I have not found it. Also, admittedly, I am quite new into using these types of models and python for statistical learning (I mostly used machine learning in the past).

A: Here is an example notebook:
# In[1]:

import pandas as pd
import numpy as np
import pandas_datareader as pdr
import datetime
import arch

# In[2]:

start = datetime.datetime(1995, 1, 1)
df = pdr.data.DataReader('SPY', 'yahoo', start=start)
del df['Open']
del df['High']
del df['Low']
del df['Adj Close']
del df['Volume']

# In[3]:

df['log_price'] = np.log(df['Close'])
df['pct_change'] = df['log_price'].diff()
df.head()

# In[4]:

df['stdev21'] = df['pct_change'].rolling(window=21, center=False).std()
df['hvol21'] = df['stdev21'] * (252**0.5) # Annualize.
#df['variance'] = df['hvol21']**2
df = df.dropna() # Remove rows with blank cells.

# In[5]:

df.head()

# In[6]:

returns = df['pct_change'] * 100
am = arch.arch_model(returns)

# In[7]:

res = am.fit(disp='off')
res.summary()

# In[8]:

df['forecast_vol'] = 0.1 * np.sqrt(res.params['omega'] + res.params['alpha[1]'] * res.resid**2 + res.conditional_volatility**2 * res.params['beta[1]'])

# In[9]:

df.tail()