text:
Q: How was this really handy bijection thought up of? Here's a proof from my combinatorics textbook.
Theorem 1.6.5. For any positive integer $k$,
$$(1-x)^{-k}=\sum_{n\geq 0}\binom{n+k-1}{k-1}x^n$$
Proof: Let $S_n$ be the set of all $k$-tuples $(a_1,\dots ,a_k)\in N^k_{\geq 0}$ with $a_1+\cdots +a_k=n$. We previously showed that
$$|S_n|=[x^n](1-x)^{-k}$$Let $T_n$ denote the set of all $(k-1)$-element subsets of ${1,2,\dots ,n+k-1}$, thus
$$|T_n|={n+k-1 \choose k-1}$$
We will establish a bijection between $T_n$ and $S_n$.
For $A=\{a_1,a_2,\dots ,a_{k-1}\}\in T_n$, with $a_1<a_2<\cdots<a_{k-1}$, we define $f(A)=\sigma$ where
$$\sigma=(a_1-1,a_2-a_1-1,\dots ,a_k-a_{k-1}-1,(n+k)-a_k-1)$$
(proof that it is bijection follows)
My question is, how in earth would somebody derive such a useful bijection. Just by staring at $\sigma$, where this came from is very opaque - leading to this theorem being really hard to proof without giving you the bijection to use.

A: It's easier to think about it the other way around. Assume that you've gathered enough numerical data (by brute force, if necessary) to suspect that $|S_n|$ is a binomial coefficient with lower number $k-1$. Then you want somehow to relate solutions to $x_1+\ldots+x_k=n$ in non-negative integers to $(k-1)$-element subsets of something. The key insight is that a solution to $x_1+\ldots+x_k=n$ in non-negative integers determines a non-decreasing sequence of partial sums, one of which is automatically known and can therefore be discarded without loss of information, leaving only $k-1$ integers.
Suppose that $a_1+\ldots+a_k=n$, where each $a_i\in\Bbb N$. For $i=1,\dots,k$ let $s_i=a_1+\ldots+a_i$. Then $0\le s_1\le s_2\le\ldots\le s_k=n$. We know that $s_k=n$, so in order to reconstruct $a_1,\dots,a_k$, we need only the first $k-1$ partial sums, $s_1,\dots,s_{k-1}$. This sets up a nice correspondence between solutions to $x_1+\ldots+x_k=n$ in non-negative integers and $(k-1)$-term sequences non-decreasing sequences $\langle s_1,\dots,s_{k-1}\rangle$ of non-negative integers such that $s_{k-1}\le n$.
This doesn't quite give me $(k-1)$-element sets, since it's entirely possible that $s_i=s_{i+1}$ for some $i$, but I can always simply add $1$ to the first term, $2$, to the second, and so on: let $t_i=s_i+i$ for $i=1,\dots,k-1$. Then $1\le t_1<t_2<\ldots<t_{k-1}\le n+k-1$, and $\{t_1,\dots,t_{k-1}\}$ is a genuine $(k-1)$-element subset of $\{1,\dots,n+k-1\}$.
It's not hard to see that if I start with any $(k-1)$-element subset of $\{1,\dots,n+k-1\}$ and list it in increasing order as $\{t_1,\dots,t_{k-1}\}$, I can reverse the process by setting $s_i=t_i-i$ for $i=1,\dots,k-1$ and $s_k=n$, and then letting $a_1=s_1$ and $a_i=s_i-s_{i-1}$ for $i=1,\dots,k$.

A: Think of writing out $a_1+\cdots+a_k=n$ where the numbers in the left hand side are written in unary notation, that is $a_i$ is represented by a sequence of $a_i$ vertical strokes (the sequence is empty if $a_i=0$). Then you've always got $n+k-1$ symbols in the left hand side ($n$ strokes and $k-1$ plus signs). So you could find all such expressions by each time writing down $n+k-1$ vertical strokes in a row, and choosing any subset of $k-1$ of them to which you add a horizontal stroke to form a "$+$".
(A variation of this argument is called "stars and bars". However I find that argument presented in its Wikipedia article rather roundabout when applied to the current situation, as it amounts to taking $n+k$ stars, choosing $k-1$ of the $n+k-1$ spaces between the stars to place a bar in, and then removing one star form each of the $k$ non-empty groups of stars formed. Also the article has the names $n$ and $k$ interchanged.)
This shows that $|S_n|=\binom{n+k-1}{k-1}$, but using unary notation seems terribly primitive, so we can deduce what the numbers $a_i$ would be if we crossed the strokes at positions $p_1<p_2<\cdots<p_{k-1}$ (starting with position$~1$). Clearly $a_1=p_1-1$ and $a_n=(n+k-1)-p_{k-1}$, while all intermediate numbers are given by $a_i=p_i-p_{i-1}-1$. This gives the bijection you described (although you called the $p_i$ by the same name $a_i$).


text:
Q: Замена только в определённых линиях файла 1. Кратко
Имеется файл. В нём нужно произвести замены только на определённых линиях. Некоторые линии необходимо игнорировать.
Желательно сделать это без дублирующегося кода (для кода вроде п. 3.1 данного вопроса).

2. Минимальный пример

*

*Kira.txt:

Sasha
Sasha*-U Can't Touch This
Sasha Goddess!

*

*main.py
import re

with open("Kira.txt", "r+") as kira_file:
    file_as_string = kira_file.read()
    kira_file.seek(0)
    kira_file.write(re.sub(r'Sasha', r'Kira', file_as_string, flags=re.M))
    kira_file.truncate()

*

*Вывод (перезаписанный main.py):

Kira
Kira*-U Can't Touch This
Kira Goddess!

А нужно, чтобы любая строка, содержащая Touch (в примере — вторая), не была затронута заменами. Touch — условная метка, показывающая, что модулю ничего не следует делать с данной линией. То есть, чтобы файл перезаписался так:
Kira
Sasha*-U Can't Touch This
Kira Goddess!

3. Попытки самостоятельно справиться с заданием
Пробовал также использовать метод writelines вместо write или модуль itertools — безуспешно.
3.1. Поиск и замена на линии

*

*Онлайн-демонстрация на Repl.it
Попробую выполнить то же самое, что и в п.2, но чтобы поиск/замена велась для определённой линии.
"""Минимальный пример."""
import re

def initial_function():
    """Получаю список строк, в которых будет вестись поиск или замена.

    В реальном модуле, чтобы получить список, выполняю много действий:
    (https://www.pastery.net/npjxzx/).
    В минимальном же примере в списке убираются строки, содержащие «Touch».
    Строки, не вошедшие в список, это строки-исключения, в них поиск и замена
    вестись не должны.
    """
    with open("Kira.txt", "r+") as kira_file:
        file_as_list = kira_file.readlines()
        final_list = [_ for _ in file_as_list if 'Touch' not in _]
        yield kira_file, final_list

def find_function():
    """Функция-пример.

    Список, полученный в прошлой функции,
    нужен, чтобы по его пунктам выполнить поиск на определённое вхождение.
    Вставил эту функцию в пример, потому что хотелось бы рабочий код, где не пришлось бы
    дублировать действия для получения списка неисключённых строк
    для этой функции и в replace_function().
    """
    for kira_file, final_list in initial_function():
        for line in final_list:
            if "Goddess" in line:
                print(f"{line} contain Goddess")
            else:
                print(f"{line} not contain Goddess")

def replace_function():
    """В этой функции пытаюсь выполнить замену."""
    for kira_file, final_list in initial_function():
        for line in final_list:
            kira_file.seek(0)
            kira_file.write(re.sub(r'Sasha', r'Kira', line, flags=re.M))
            kira_file.truncate()

# find_function()
replace_function()

*

*Вывод (перезаписанный main.py):

Kira Goddess!

Всё удалилось кроме последней заменённой строки.
3.2. tell()
Пробовал не использовать seek(0) или использовать tell()

*

*Онлайн-демонстрация на Repl.it:

def replace_function():
    """В этой функции пытаюсь выполнить замену."""
    for kira_file, final_list in initial_function():
        for line in final_list:
            # kira_file.seek(0)
            kira_file.write(re.sub(r'Sasha', r'Kira', line, flags=re.M))
            kira_file.truncate()

*

*или:

def replace_function():
    """В этой функции пытаюсь выполнить замену."""
    for kira_file, final_list in initial_function():
        for line in final_list:
            last_pos = kira_file.tell()
            kira_file.seek(last_pos)
            kira_file.write(re.sub(r'Sasha', r'Kira', line, flags=re.M))
            kira_file.truncate()

*

*Вывод (перезаписанный main.py):

Sasha
Sasha*-U Can't Touch This
Sasha Goddess!Kira
Kira Goddess!

4. Пояснения

*

*Линии, где требуется и нет проводить замены, могут быть расположены в любом месте файла. Код, подобный этому, приспособить к решению данной задачи, у меня не вышло.

*Нужно перезаписать исходный файл, а не вывести конечный результат в новый файл. Использование временных файлов, если это необходимо, конечно, не возбраняется.

*Линии-исключения после проведения операции замены должны оставаться в файле. В них не требуется ничего изменять, но удалять нельзя. Вариант: записать заменённые линии в другой файл → перезаписать исходный файл, у меня не проходил.

A: Если так принципиально работать без временного файла, переоткрывайте этот
import re

def initial_function(file_name: str) -> list:
    """Получаю список строк, в которых будет вестись поиск или замена.
    В реальном модуле, чтобы получить список, выполняю много действий:
    В минимальном же примере в списке убираются строки, содержащие «Touch».
    """
    with open(file_name, 'r') as kira_file:
        text = kira_file.readlines()
    return text # просто возвращаем нефильтрованный список, полученный за много действий

def find_function(line:str) -> bool:
    """по его пунктам выполнить поиск на определённое вхождение. """
    return 'Touch' not in line

def replace_function(line:str) -> str:
    return re.sub(r'Sasha', r'Kira', line, flags=re.M)

def process_file(file_name):
    text = initial_function(file_name)
    with open(file_name, "w") as kira_file:
        for line in text:
            if find_function(line):
                line = replace_function(line)
            kira_file.write(line)

process_file("Kira.txt")

UPD: Вынес функционал получения, фильтра и замены в функции

A: Каким образом удалить строчки выборочно? - взято отсюда
from itertools import islice

with open('Kira.txt', 'r+') as file:
    write_offset = file.tell() # where to write next
    for line in islice(iter(file.readline, ''), 0, None):
        read_offset = file.tell() # where to read next
        file.seek(write_offset)
        if 'Touch' in line:
            ...
        write_offset = file.tell()
        file.seek(read_offset)
    file.truncate(write_offset)

если упростить ответ Lecron
держать в памяти не более 1 линии файла:
def process_file(file_name):
    with open(file_name + '.tmp', "w") as file_w, open(file_name, 'r') as file_r:
        for line in file_r:
            if 'Touch' not in line:
                line = re.sub(r'Sasha', r'Kira', line, flags=re.M)
            file_w.write(line)
    shutil.move(file_name + '.tmp', file_name)

держать в памяти весь файл:
def process_file(file_name):
    with open(file_name, 'r') as file_r:
        text = list(file_r)
    with open(file_name, 'w') as file_w:
        for line in text:
            if 'Touch' not in line:
                line = re.sub(r'Sasha', r'Kira', line, flags=re.M)
            file_w.write(line)

redpajama_set_name: RedPajamaStackExchange


text:
Q: fetch() POST request to Express.js generates empty body {} Goal: send some defined string data from HTML in a fetch() function e.g. "MY DATA"

My code:
HTML
<!DOCTYPE html>
<html>
<body>

<script type="text/javascript">
    function fetcher() {
      fetch('/compute',
        {
          method: "POST",
          body: "MY DATA",
          headers: {
            "Content-Type": "application/json"
          }
        }
      )
      .then(function(response) {
        return response.json();
      })
      .then(function(myJson) {
        console.log(myJson);
      });
    }
</script>

</body>
</html>

Server.js
var express = require("express");
var app     = express();
var compute = require("./compute");
var bodyParser = require("body-parser");

//not sure what "extended: false" is for
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/compute', (req, res, next) => {
    console.log(req.body);
    var result = compute.myfunction(req.body);
    res.status(200).json(result);
});

Currently: console.log(req.body) logs {}
Desired: console.log(req.body) logs "MY DATA"
NOTES:

*

*I also tried sending body in fetch() as body: JSON.stringify({"Data": "MY DATA"}) but get the same empty {}

*I either my fetch() request, or my bodyParser(), is not setup correctly.

A: I feel a bit stupid now once I worked out what bodyParser.urlencoded (source: https://www.npmjs.com/package/body-parser#bodyparserurlencodedoptions)

Returns middleware that only parses urlencoded bodies

Solution
Changed the fetch() request, from:
body: "MY DATA",
headers: { "Content-Type": "application/json" }

to
body: JSON.stringify({"Data": "MY DATA"}),
headers: { "Content-Type": "application/x-www-form-urlencoded" }

which solved the problem! Console logged:

{ '{"Data":"MY DATA"}': '' }

A: Add the following line in addition to your current bodyParser app.use() right before:
app.use(bodyParser.json());

This will enable bodyParser to parse content type of application/json.
Hopefully that helps!


text:
Q: Python decorators in classes Can one write something like:
class Test(object):
    def _decorator(self, foo):
        foo()

    @self._decorator
    def bar(self):
        pass

This fails: self in @self is unknown
I also tried:
@Test._decorator(self)

which also fails: Test unknown
I would like to temporarily change some instance variables
in the decorator and then run the decorated method, before
changing them back.

A: Here's an expansion on Michael Speer's answer to take it a few steps further:
An instance method decorator which takes arguments and acts on a function with arguments and a return value.
class Test(object):
    "Prints if x == y. Throws an error otherwise."
    def __init__(self, x):
        self.x = x

    def _outer_decorator(y):
        def _decorator(foo):
            def magic(self, *args, **kwargs) :
                print("start magic")
                if self.x == y:
                    return foo(self, *args, **kwargs)
                else:
                    raise ValueError("x ({}) != y ({})".format(self.x, y))
                print("end magic")
            return magic

        return _decorator

    @_outer_decorator(y=3)
    def bar(self, *args, **kwargs) :
        print("normal call")
        print("args: {}".format(args))
        print("kwargs: {}".format(kwargs))

        return 27

And then
In [2]:

    test = Test(3)
    test.bar(
        13,
        'Test',
        q=9,
        lollipop=[1,2,3]
    )

    start magic
    normal call
    args: (13, 'Test')
    kwargs: {'q': 9, 'lollipop': [1, 2, 3]}
Out[2]:
    27
In [3]:

    test = Test(4)
    test.bar(
        13,
        'Test',
        q=9,
        lollipop=[1,2,3]
    )

    start magic
    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    <ipython-input-3-576146b3d37e> in <module>()
          4     'Test',
          5     q=9,
    ----> 6     lollipop=[1,2,3]
          7 )

    <ipython-input-1-428f22ac6c9b> in magic(self, *args, **kwargs)
         11                     return foo(self, *args, **kwargs)
         12                 else:
    ---> 13                     raise ValueError("x ({}) != y ({})".format(self.x, y))
         14                 print("end magic")
         15             return magic

    ValueError: x (4) != y (3)

A: I found this question while researching a very similar problem. My solution is to split the problem into two parts.  First, you need to capture the data that you want to associate with the class methods.  In this case, handler_for will associate a Unix command with handler for that command's output.
class OutputAnalysis(object):
    "analyze the output of diagnostic commands"
    def handler_for(name):
        "decorator to associate a function with a command"
        def wrapper(func):
            func.handler_for = name
            return func
        return wrapper
    # associate mount_p with 'mount_-p.txt'
    @handler_for('mount -p')
    def mount_p(self, slurped):
        pass

Now that we've associated some data with each class method, we need to gather that data and store it in a class attribute.
OutputAnalysis.cmd_handler = {}
for value in OutputAnalysis.__dict__.itervalues():
    try:
        OutputAnalysis.cmd_handler[value.handler_for] = value
    except AttributeError:
        pass

A: I use this type of decorator in some debugging situations, it allows overriding class properties by decorating, without having to find the calling function.
class myclass(object):
    def __init__(self):
        self.property = "HELLO"

    @adecorator(property="GOODBYE")
    def method(self):
        print self.property

Here is the decorator code
class adecorator (object):
    def __init__ (self, *args, **kwargs):
        # store arguments passed to the decorator
        self.args = args
        self.kwargs = kwargs

    def __call__(self, func):
        def newf(*args, **kwargs):

            #the 'self' for a method function is passed as args[0]
            slf = args[0]

            # replace and store the attributes
            saved = {}
            for k,v in self.kwargs.items():
                if hasattr(slf, k):
                    saved[k] = getattr(slf,k)
                    setattr(slf, k, v)

            # call the method
            ret = func(*args, **kwargs)

            #put things back
            for k,v in saved.items():
                setattr(slf, k, v)

            return ret
        newf.__doc__ = func.__doc__
        return newf

Note: because I've used a class decorator you'll need to use @adecorator() with the brackets on to decorate functions, even if you don't pass any arguments to the decorator class constructor.

A: The simple way to do it.
All you need is to put the decorator method outside the class.
You can still use it inside.
def my_decorator(func):
    #this is the key line. There's the aditional self parameter
    def wrap(self, *args, **kwargs):
        # you can use self here as if you were inside the class
        return func(self, *args, **kwargs)
    return wrap

class Test(object):
    @my_decorator
    def bar(self):
        pass

A: What you're wanting to do isn't possible. Take, for instance, whether or not the code below looks valid:
class Test(object):

    def _decorator(self, foo):
        foo()

    def bar(self):
        pass
    bar = self._decorator(bar)

It, of course, isn't valid since self isn't defined at that point. The same goes for Test as it won't be defined until the class itself is defined (which its in the process of). I'm showing you this code snippet because this is what your decorator snippet transforms into.
So, as you can see, accessing the instance in a decorator like that isn't really possible since decorators are applied during the definition of whatever function/method they are attached to and not during instantiation.
If you need class-level access, try this:
class Test(object):

    @classmethod
    def _decorator(cls, foo):
        foo()

    def bar(self):
        pass
Test.bar = Test._decorator(Test.bar)

A: Declare in inner class.
This solution is pretty solid and recommended.
class Test(object):
    class Decorators(object):
    @staticmethod
    def decorator(foo):
        def magic(self, *args, **kwargs) :
            print("start magic")
            foo(self, *args, **kwargs)
            print("end magic")
        return magic

    @Decorators.decorator
    def bar( self ) :
        print("normal call")

test = Test()

test.bar()

The result:
>>> test = Test()
>>> test.bar()
start magic
normal call
end magic
>>>

A: import functools

class Example:

    def wrapper(func):
        @functools.wraps(func)
        def wrap(self, *args, **kwargs):
            print("inside wrap")
            return func(self, *args, **kwargs)
        return wrap

    @wrapper
    def method(self):
        print("METHOD")

    wrapper = staticmethod(wrapper)

e = Example()
e.method()

A: Decorators seem better suited to modify the functionality of an entire object (including function objects) versus the functionality of an object method which in general will depend on instance attributes.  For example:
def mod_bar(cls):
    # returns modified class

    def decorate(fcn):
        # returns decorated function

        def new_fcn(self):
            print self.start_str
            print fcn(self)
            print self.end_str

        return new_fcn

    cls.bar = decorate(cls.bar)
    return cls

@mod_bar
class Test(object):
    def __init__(self):
        self.start_str = "starting dec"
        self.end_str = "ending dec"

    def bar(self):
        return "bar"

The output is:
>>> import Test
>>> a = Test()
>>> a.bar()
starting dec
bar
ending dec

A: Would something like this do what you need?
class Test(object):
    def _decorator(foo):
        def magic( self ) :
            print "start magic"
            foo( self )
            print "end magic"
        return magic

    @_decorator
    def bar( self ) :
        print "normal call"

test = Test()

test.bar()

This avoids the call to self to access the decorator and leaves it hidden in the class namespace as a regular method.
>>> import stackoverflow
>>> test = stackoverflow.Test()
>>> test.bar()
start magic
normal call
end magic
>>>

edited to answer question in comments:
How to use the hidden decorator in another class
class Test(object):
    def _decorator(foo):
        def magic( self ) :
            print "start magic"
            foo( self )
            print "end magic"
        return magic

    @_decorator
    def bar( self ) :
        print "normal call"

    _decorator = staticmethod( _decorator )

class TestB( Test ):
    @Test._decorator
    def bar( self ):
        print "override bar in"
        super( TestB, self ).bar()
        print "override bar out"

print "Normal:"
test = Test()
test.bar()
print

print "Inherited:"
b = TestB()
b.bar()
print

Output:
Normal:
start magic
normal call
end magic

Inherited:
start magic
override bar in
start magic
normal call
end magic
override bar out
end magic

A: I have a Implementation of Decorators that Might Help
    import functools
    import datetime

    class Decorator(object):

        def __init__(self):
            pass

        def execution_time(func):

            @functools.wraps(func)
            def wrap(self, *args, **kwargs):

                """ Wrapper Function """

                start = datetime.datetime.now()
                Tem = func(self, *args, **kwargs)
                end = datetime.datetime.now()
                print("Exection Time:{}".format(end-start))
                return Tem

            return wrap

    class Test(Decorator):

        def __init__(self):
            self._MethodName = Test.funca.__name__

        @Decorator.execution_time
        def funca(self):
            print("Running Function : {}".format(self._MethodName))
            return True

    if __name__ == "__main__":
        obj = Test()
        data = obj.funca()
        print(data)

A: This is one way to access(and have used) self from inside a decorator defined inside the same class:
class Thing(object):
    def __init__(self, name):
        self.name = name

    def debug_name(function):
        def debug_wrapper(*args):
            self = args[0]
            print 'self.name = ' + self.name
            print 'running function {}()'.format(function.__name__)
            function(*args)
            print 'self.name = ' + self.name
        return debug_wrapper

    @debug_name
    def set_name(self, new_name):
        self.name = new_name

Output (tested on Python 2.7.10):
>>> a = Thing('A')
>>> a.name
'A'
>>> a.set_name('B')
self.name = A
running function set_name()
self.name = B
>>> a.name
'B'

The example above is silly, but it works.

A: You can decorate the decorator:
import decorator

class Test(object):
    @decorator.decorator
    def _decorator(foo, self):
        foo(self)

    @_decorator
    def bar(self):
        pass


text:
Q: Running t.tests on "tidy" data in R with multiple conditions I have a "tidy" dataframe and am trying to run a series of t-tests. The first column includes a series of food names. The next 3 columns include 0 or 1 values that specify the experimental condition. The last column includes the mean of the ratings of the particular food.
FoodName  Var1  Var2  Var3  Mean
hotdog    0     1     0     4.5
burger    1     1     0     5.5
fries     0     0     1     4.0
soda      1     0     1     6.0

I would like to run t.tests comparing the mean values for different groups depending on the conditions. Here are some examples of the types of t.tests I'd like to run:

*

*comparing mean food score for all foods for which var1=0 to the mean food score for all foods for which var1=1

*comparing mean foods score for all foods for which var1=0 and var2=1 to those for which var1=1 and var2=0

Here's some pseudocode for the examples:
t.test(mean if var1=0, mean if var1=1)
t.test(mean if var1=0 and var2=1, mean if var1=1 and var2=0)

How do I do this in R?


text:
Q: ms crm 2011 quote start recalculate with javascript I have copied a quote with all quotedetails. Is it possible to start the recalculate process
with javascript? How can I do this?
Many thanks in advance!

A: You need to refresh the window to get the updated quote totals:
window.location.reload(true)


text:
Q: Issues with Bootstrap Grid Alignment
I need this layout (see picture), I tried a lot but nothing works.. here is my code:

#Map

#Route

A: check out this fiddle.

Aaa

Bbb

Bbb


text:
Q: Pre-Populating HTML form, date, with Flask variable content I am working with a simple csv file which has 1 row, no header, containing two fields (both dates). The below Python script and HTML works so far, but I can nOT get the date fields to be populated with the cell content of the csv before the user (me) can change the date.
I have been trying for days now.
HTML (form.html):
<form action="{{ url_for("getdates")}}" method="post">
1st Ferment Date:
<input type="date" id="first" name="first" placeholder="first" value=firsttrial>
{{ firsttrial }}

Bottling Date:
<input type="date" id="bottled" name="bottled" placeholder="bottled">

<button type="submit">click here to Reset</button>

Python/Flask code (getdates.py)"

from flask import Flask, request, render_template
import os
import csv
app = Flask(__name__)

dir = os.path.dirname(__file__)
with open(dir+'Data/variable.csv') as f:
    data = list(csv.reader(f))
    print('after list(csv.reader)' + data[0][0])
    firsttrial = data[0][0]
    #try:
    #    last_name = data[0][1]
    #except:
    #    print("not working")
    #else:
    #    print("last"+last_name)

f.close()

@app.route('/', methods =["GET", "POST"])
def getdates():
    templateData = {
            'firsttrial' : firsttrial
            }
    if request.method == "POST":
       # getting input with name = fname in HTML form
        first = request.form.get("first")
        if first:
            # getting input with name = lname in HTML form
            bottled = request.form.get("bottled")
            input_dictionary = bottled
            dir = os.path.dirname(__file__)
            tempsfile = dir + "Data/variable.csv"
            import csv
            RESULT = [first, bottled]
            resultFile = open(tempsfile,'w')
            wr = csv.writer(resultFile, dialect='excel')
            wr.writerow(RESULT)
            resultFile.close()
        else:
            return "you did not enter the word 'reset', so counter will continue as is"
    return render_template("form.html",**templateData)

if __name__=='__main__':
    app.run()

Any help would be appreciated!

A: This:
<input type="date" id="first" name="first" placeholder="first" value=firsttrial>
{{ firsttrial }}

should be this:
<input type="date" id="first" name="first" placeholder="first" value="{{firsttrial}}">

It's the value attribute that specifies what gets placed in the field.


text:
Q: I need to validate text entered,if it's not in correct form it should be underlined in red and if correct should underline in green Thes is my code and i want to add underline part but i don't know how.
   #define ACCEPTABLE_CHARECTERS @"0123456789"

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {

if (textField==ucontact)
{        NSUInteger newLength = [textField.text length] + [string length] - range.length;

    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS] invertedSet];

    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

    return (([string isEqualToString:filtered])&&(newLength <= 10));

}
return YES;
}

A: You can achieve it through the work around. You can add one line with the help of UIView below the textField and name it as the validatorView and change the color of the line according to your wish after validation.
Hope this helps best luck.

A: You can have a look at this question.  It illustrates how you can make use of only the bottom border.  Alternatively you can also add a line as a UIView subview.
I am curious why you do not use the Numpad keyboard.
textField.keyboardType = .NumberPad (Swift)


text:
Q: Inverse of the sum of a symmetric positive definite matrix and a diagonal Suppose we have a matrix $XX^T + D$ and we want to calculate its inverse. $D$ is a diagonal matrix.  $X$ is a symmetric matrix.
We know the inverse of $X_1X_1^T, X_2X_2^T, \ldots, X_nX_n^T$, where $X_1X_1^T, X_2X_2^T, \ldots, X_nX_n^T$ are the blocks of the $XX^T$.
Is there any efficient way to calculate $(XX^T + D)^{-1}$?
Thanks a lot.


text:
Q: MariaDB: Split a semicolon separated string and calculate mean value I have a column in my MariaDB table that contains an undefined amount of semicolon separated integer values as a string (e.g. "123;456;789;123").
Inside of the INSERT-Trigger of this table I want to calculate the mean value of the integers in the string.
Any ideas on how to do this string split and mean calculation in a short and easy way?


text:
Q: Get current method name in .NET Core 6 I am looking to get the current executing method in .NET Core 6
When using
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName

the output is <MethodName>d__6
How to get only MethodName ?
What is d__6 ?

A: try this:
System.Reflection.MethodBase.GetCurrentMethod().Name;


text:
Q: RStudio won't start, R ver. 3.4.2, Rstudio ver. 1.1.383 I'm not able to start a fresh installment of RStudio. I've deleted prior versions, and are currently only running R ver. 3.4.2. Likewise I've deleted my .RData file, but nothing seems to work. The program doesn't show anything, but it is listed on running programs, and the more times I click the more times it opens a new RStudio, untill it clogs the CPU. I'm running Windows 10.
What to do?

A: I am afraid that this idea will help you or not that you can try this.
Uninstalling RStudio and R, cleaning the registry, and installing again.
If it is running then close it first from the task manager then uninstall the program.


text:
Q: Why is UITextField not allowing me to add border color? I have the below method which should add border color to a uitextfield but for some reason, it does not add the border color, although it does successfully get added to the view a can be typed in.
func setupSearchBar() {
    searchField.frame = CGRect(x: 4, y: 6.5, width: 366.58, height: 42)
    searchField.layer.cornerRadius = searchField.frame.height/2
    topBackgroundView.layer.borderWidth = 0.35
    searchField.layer.borderColor = UIColor(red: 0/225, green: 0/225, blue: 0/225, alpha: 0.49).cgColor
    searchField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
    view.addSubview(searchField)
}

A: The search field borderWidth is defaulting to 0. Try:
func setupSearchBar() {
    searchField.frame = CGRect(x: 4, y: 6.5, width: 366.58, height: 42)
    searchField.layer.cornerRadius = searchField.frame.height/2
    topBackgroundView.layer.borderWidth = 0.35
    searchField.layer.borderColor = UIColor(red: 0/225, green: 0/225, blue: 0/225, alpha: 0.49).cgColor
    searchField.layer.borderWidth = 1.0 // <- Add here
    searchField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
    view.addSubview(searchField)
}


text:
Q:  link breaks SVG path transition in Safari I have a normal SVG Triangle like this:
<svg width="200px" height="200px" viewBox="0 0 200 200" version="1.1" xmlns="http://www.w3.org/2000/svg">
  <polygon id="triangle"  fill="#000000" points="100 0 200 200 0 200 "></polygon>
</svg>

I'm using CSS to smoothly transition the color of the SVG when someone hovers over it:
#triangle { transition: 1s; }

svg:hover #triangle { fill: orange; }

This works in all browsers.
But now I want to add clickable link functionality to the same SVG,
so I surround it with link tags:

  <svg width="200px" height="200px" viewBox="0 0 200 200" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <polygon id="triangle"  fill="#000000" points="100 0 200 200 0 200 "></polygon>
  </svg>

BUT NOW in Safari my smooth color transition breaks. Instead of my original one second color transition, my SVG path now instantaneously changes color.
This does not happen in Firefox or Chrome.
Is this a glitch within Safari?
Here is my problem in Codepen http://codepen.io/TimArt/pen/lgLEp

A: I create a "fake-link" object in JS to use whenever this is the case. I can then attach '.fake-link' to any HTML element to replicate your standard  tag.
The JS:
/**
* Link namespace
*/
Link = function() {
};

/**
 * Fake a link
 */
 Link.prototype.openLink = function(el) {
    var link = $(el).attr('data-href');
    var win = null;
    win = window.open(link, '_self');
    win.focus();
};

window.Link = new Link();

$(function(){
    $(document).on('click', '.fake-link', function(e) {
        e.stopPropagation();
        window.Link.openLink($(this));
        return false;
    });
});

Some HTML:

  <svg>
    INLINE SVG CONTENT HERE
  </svg>

A: If you use <a xmlns:xlink="" data-href="URL" the transitions will work in safari/webkit browsers. You will still need  javascript to make the link work however. So for jQuery use this code also:
 $('#Element').click(function(e) {
    location.href =  $(this).attr('data-href');
    e.preventDefault();

})


text:
Q: REGEX to parse words from cell in googlesheets Hoping somebody can help me with the syntax.
Cell A1 contains the following value:
Content Type: Pitch Decks; Region: North America; Content Type: Data Sheet;

I'm trying to create a formula that parses the values between the words "Content Type: " and the semicolon that follows.
So in B1, the expected result of the formula should be:
Pitch Decks
Data Sheet

(Yes, with char(10) separating the values in B1)
I've tried a number of different combinations of REGEXEXTRACT, for example:
REGEXEXTRACT(A11,"Content Type: ([\w\/\s]*);?")

..only returns:
Pitch Decks

I've read that global modifiers are not supported in Google Sheets. That formula works when I add a global modifier in a regex test harness, but not when used within Google Sheets itself.

A: I thought this would be easy with substitution and a Lookahead but turns out Google Sheets doesn't support Lookaheads either. After some research, I came up with the following solution:
=join(CHAR(10),REGEXEXTRACT(A1,REGEXREPLACE(A1,"(Content Type: )([^;]+)","$1($2)")))

This will find all the strings that come after "Content Type: " and until the next semicolon or the end of the string. Then, it will join them using a LineFeed. If you want to join using a different character, you may replace CHAR(10) with ",", for example, to join with a comma.
Output:
Pitch Decks
Data Sheet

A: try:
=ARRAYFORMULA(SUBSTITUTE(SUBSTITUTE(TRIM(FLATTEN(QUERY(TRANSPOSE(SUBSTITUTE(
 IF(IFERROR(REGEXMATCH(SPLIT(A1:A, ";"), "Content Type")),
 REGEXEXTRACT(SPLIT(A1:A, ";"), ": (.+)"), ), " ", "♥"))
 ,,9^9))), " ", CHAR(10)), "♥", " "))


text:
Q: how do I create Class modules in other class module and passing value for the classes in vba excel I have a trouble so I need to create a class modules. Example Condition Room include some property like width, length, height, volume, Window type, Wall type, Roof type, but window, wall, roof either are class module with other properties such as window: glass single layer or double layers, frame wood or alu and so on,...
So, how do I create the class module Conditional room consist of other class modules as above
Thank you for your help.,

A: You need to create separate classes (files)
Put each of the below in a separate *.cls file:
' Windows.cls
Public Enum GlassType
    SingleLayer
    DoubleLayer
End Enum

Private m_Glass As GlassType

Public Property Get Glass As GlassType
    Glass = m_Glass
End Property
Public Property Let Glass (ByVal value As GlassType)
    m_Glass = value
End Property
' ---

' RoomDimension.cls
Private m_Height As Double
Private m_Length As Double
Private m_Width As Double

Public Property Get Height As Double
    Height = m_Height
End Property
Public Property Let Height (ByVal value As Double)
    m_Height = Abs(value)
End Property

Public Property Get Length As Double
    Length = m_Length
End Property
Public Property Let Length (ByVal value As Double)
    m_Length = Abs(value)
End Property

Public Property Get Width As Double
    Width = m_Width
End Property
Public Property Let Width (ByVal value As Double)
    m_Width = Abs(value)
End Property

Public Property Get Volume As Double
    Volume = Length * Width * Height
End Property
' ---

' ConditionRoom.cls
Private m_Window As Windows
Private m_Dimension As RoomDimension

Public Property Get Window As Windows
    Window = m_Window
End Property
Public Property Let Window (ByVal value As Windows)
    m_Window = value
End Property

Public Property Get Dimension As RoomDimension
    Dimension = m_Dimension
End Property
Public Property Let m_Dimension (ByVal value As RoomDimension)
    m_Dimension = value
End Property

Class_Initialize()
    Set Window = New Windows
    Set Dimension = New RoomDimension
End Class
' ---

' Code sample on how to use it
Dim room As ConditionRoom

Set room = New ConditionRoom

' Set the window type
room.Window.Glass = GlassType.SingleLayer

' Set room dimensions
With room.Dimension
    .Height = 250
    .Length = 500
    .Width = 500
    Debug.Print "Room volume: "; .Volume
End With

A: In excel you can not create a class inside class, parent/child or super/sub class is not supported in VBA. However you can use interface to somehow achieve similar capabilities.


text:
Q: Query between dates using date picker filter breaks in Wordpress 4.2.1 Original post:
Query between dates using Date Picker fields
I originally made a post last year on this same subject, but seems the update to WP v4.2.1 has broken my filter.  In summary, I am using ACF and date picker plugin in an Events custom post type. I am trying to query events between a start and end date.  I also have events that can span multiple months.  For example, an event may start in april but end in june.  I want that event to display in april, may, and june.
I had this working using a filter when on v3.9 of wordpress.  I'm trying to get wordpress updated on all of my websites, but this filter breaks after updating to v4.2.1.  This broke after updating WP 4.2.1 and also after updating ACF to latest version of 4.  I have since updated to ACF PRO v5.2.3
Does anyone know of a fix?
Here is the code that worked great when on WP v3.9.
My Event Widge Template:
<?php
/* Template Name: Events Widget */
$today = date('Ymd');

if (isset($_GET['_m'])) {

    $current_month = str_pad($_GET['_m'], 2, '0', STR_PAD_LEFT);
    $current_day = "01"; // day one
    $current_year = $_GET['_y'];

    $get_last_day = $current_year.$current_month.$current_day;
    $lastday = date("t", strtotime($get_last_day));

    $tempstartday = $current_year.$current_month.$current_day;
    $tempendday = $current_year.$current_month.$lastday;

    $startday = date('Ymd', strtotime($tempstartday));
    $endday = date('Ymd', strtotime($tempendday));

} else {

    $current_month = str_pad(date('m'), 2, '0', STR_PAD_LEFT);
    $current_day = "01"; // day one
    $current_year = date('Y');

    $get_last_day = $current_year.$current_month.$current_day;
    $lastday = date("t", strtotime($get_last_day));

    $tempstartday = $current_year.$current_month.$current_day;
    $tempendday = $current_year.$current_month.$lastday;

    $startday = date('Ymd', strtotime($tempstartday));
    $endday = date('Ymd', strtotime($tempendday));
}

add_filter( 'get_meta_sql', 'get_meta_sql_date', 10, 2 );

$qryevents = array(
    'post_type' => 'events',
    'posts_per_page' => 50,
    'status' => 'published',
    'meta_key' => 'event_start_date',
    'orderby' => 'meta_value',
    'order' => 'ASC',

    // produces meta join and where clauses for the query
    // which will be filtered in functions.php
    'meta_query' => array(
        'relation' => 'AND',
        array(
            'key'     => 'event_start_date',
            'compare' => '>=',
            'value'   => $startday,
            'type' => 'DATE'
        ),
        array(
            'key'     => 'event_end_date',
            'compare' => '<=',
            'value'   => $endday,
            'type' => 'DATE'
        )
    )
);

$loop = new WP_Query( $qryevents );
remove_filter( 'get_meta_sql', 'get_meta_sql_date', 10, 2 );

if ( $loop->have_posts() ) :
while ( $loop->have_posts() ) : $loop->the_post();

// Let's format the dates
$get_start_date = get_field('event_start_date');
$get_end_date = get_field('event_end_date');
$event_start_date = DateTime::createFromFormat('Ymd', $get_start_date);
$event_end_date = DateTime::createFromFormat('Ymd', $get_end_date);
// End of date definitions

// Let's get the event start and end times
$get_start_time = get_field('event_start_time');
$get_end_time = get_field('event_end_time');
// end of times

// Let's get the times of the events now
$specify_event_time = "";

$show_event_times = get_field('specify_event_times');
if($show_event_times){
        foreach($show_event_times as $specify_event_time){
            // Do nothing; this puts the yes value into the varible for us to later on the page.
            // echo $specify_event_time;
        }
}
// End of the specify times

$event_month_spans = get_field('event_month_span');
?>

<div class="<?php echo (++$j % 2 == 0) ? 'full row' : 'full row alt'; ?>">

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

    <?php if($specify_event_time == "yes"): ?>

<a href="<?php the_permalink(); ?>"><?php echo $event_start_date->format('M d, Y'); ?> <?php echo $get_start_time; ?> - <?php echo $event_end_date->format('M d, Y'); ?> <?php echo $get_end_time; ?>

  <?php else: ?>

<a href="<?php the_permalink(); ?>"><?php echo $event_start_date->format('M d, Y'); ?> - <?php echo $event_end_date->format('M d, Y'); ?>

  <?php endif; ?>

<?php
endwhile;

else:
?>

No scheduled events.

<?php endif; wp_reset_query(); ?>

In my functions.php file I have this function:
function get_meta_sql_date( $pieces, $queries ) {
    global $wpdb;

    // get start and end date from query
    foreach ( $queries as $q ) {

        if ( !isset( $q['key'] ) ) {
            return $pieces;
        }

        if ( 'event_start_date' === $q['key'] ) {
            $start_date = isset( $q['value'] ) ?  $q['value'] : '';
        }
        if ( 'event_end_date' === $q['key'] ) {
            $end_date = isset( $q['value'] ) ?  $q['value'] : '';
        }
    }

    if ( ( '' === $start_date ) || ( '' === $end_date ) ) {
        return $pieces;
    }

    $query = "";

    // after start date AND before end date
    $_query = " AND (
        ( $wpdb->postmeta.meta_key = 'event_start_date' AND ( CAST($wpdb->postmeta.meta_value AS DATE) >= %s) )
        AND ( mt1.meta_key = 'event_end_date' AND ( CAST(mt1.meta_value AS DATE) <= %s) )
    )";
    $query .= $wpdb->prepare( $_query, $start_date, $end_date );

    // OR before start date AND after end date
    $_query = " OR (
        ( $wpdb->postmeta.meta_key = 'event_start_date' AND ( CAST($wpdb->postmeta.meta_value AS DATE) <= %s) )
        AND ( mt1.meta_key = 'event_end_date' AND ( CAST(mt1.meta_value AS DATE) >= %s) )
    )";
    $query .= $wpdb->prepare( $_query, $start_date, $end_date );

    // OR before start date AND (before end date AND end date after start date)
    $_query = " OR (
        ( $wpdb->postmeta.meta_key = 'event_start_date' AND ( CAST($wpdb->postmeta.meta_value AS DATE) <= %s) )
        AND ( mt1.meta_key = 'event_end_date'
            AND ( CAST(mt1.meta_value AS DATE) <= %s )
            AND ( CAST(mt1.meta_value AS DATE) >= %s )
        )
    )";
    $query .= $wpdb->prepare( $_query, $start_date, $end_date, $start_date );

    // OR after end date AND (after start date AND start date before end date) )
    $_query = "OR (
        ( mt1.meta_key = 'event_end_date' AND ( CAST(mt1.meta_value AS DATE) >= %s ) )
        AND ( $wpdb->postmeta.meta_key = 'event_start_date'
            AND ( CAST($wpdb->postmeta.meta_value AS DATE) >= %s )
            AND ( CAST($wpdb->postmeta.meta_value AS DATE) <= %s )
        )
    )";
    $query .= $wpdb->prepare( $_query, $end_date, $start_date, $end_date );

    $pieces['where'] = $query;

    return $pieces;
}

A: There's no need for the custom meta SQL filter - the beauty of storing dates in the format Ymd is that you can treat them numerically, and MySQL will still be able to find events in a given "range" and sort them ascending/descending.
I've done this recently on another site using ACF for start/end date:
if ( ! empty( $_GET['_y'] ) )
    $year = absint( $_GET['_y'] );
else
    $year = date( 'Y ');

if ( ! empty( $_GET['_m'] ) && in_array( $month = absint( $_GET['_m'] ), range( 1, 12 ) ) )
    $month = zeroise( $month, 2 );
else
    $month = date( 'm' );

$qryevents = array(
    'post_type'      => 'events',
    'posts_per_page' => 50,
    'post_status'    => 'publish',
    'orderby'        => 'meta_value_num', // Ensure order is numerically based
    'order'          => 'ASC',

    'meta_query'     => array(
        'relation' => 'AND',
        array(
            'key'     => 'event_start_date',
            'compare' => '>=',
            'value'   => "{$year}{$month}01",
            'type'    => 'NUMERIC',
        ),
        array(
            'key'     => 'event_end_date',
            'compare' => '<=',
            'value'   => "{$year}{$month}31", // Doesn't matter if there aren't 31 days in this month, will still work,
            'type'    => 'NUMERIC',
        )
    )
);

No need for the overly complex date string calculations, and no need for the filter.

A: The Date & time utilities utilize a detachment of date & time patterns. The date () utility revisits the date in this pattern: 'YYYY-MM-DD'.
SQL Date functions oracle


text:
Q: Keep timers running in background Apps without location services Is there a way to keep timers running when an App enters background mode without location services running?
If I have a timer running in the App with location services on and enter the background then it keeps running.  However calling stopUpdatingLocation also stops the timer.  I would like the timer to be able to call startUpdatingLocation at some point in the furture but as it not being run it can't do this.
Any information on how multi-tasking works with location services would be helpful.

A: You should probably figure out when (at what time) the timer would call startUpdatingLocation and add a UILocalNotification at that time.


text:
Q: SSRS,IBM DB2 -Number of host variables not valid in query I have an SSRS Report which is getting data from AS400 Database. The query I used in the datasource is a UNION of two queries.
SELECT        'SOLD' AS STATUS, SLSMCD, SLYEAR, SLMONTH, SUM(SLDLVQT) + SUM(SLADVQT) - SUM(SLDLVQTC) - SUM(SLADVQTC) AS TotalDlvr
FROM            VEHICLE.VHTSALSUM
WHERE        (SLFRAN = ?) AND (SLBRCD = ?) AND (SLDPCD = ?) AND (SLSMCD = ?) AND (SLYEAR IN (?, ?, ?))
GROUP BY SLSMCD, SLYEAR, SLMONTH
UNION ALL
SELECT        'TARGET' AS STATUS, STGTCODE AS SLSMCD, STGTYEAR AS SLYEAR, STGTMONTH AS SLMONTH, STGTUNIT AS TotalDlvr
FROM            VEHICLE.VHTSALETGT
WHERE        STGTFRAN = ? AND STGTDPCD = ? AND STGTCODE = ? AND STGTYEAR IN (?) AND STGTTYPE = 'EXEC'

on running the query I get the error

"Number of host variables in not valid"
  The number of host variables is not same as the number of parameter markers specified in the sql statement

I copied the query in AS400 and gave the parameters the query is running successfully.
In SSRS I removed the? and put the parameters values and it is working successfully. But if there is even a single? mark I get the above error.


text:
Q: Python method like File.WriteAllBytes() in .Net There is a .net API sending the byte data as a string in JSON, I am using a python API to read it and write it in a file.
a = io.BytesIO(b"JVBERi0xLjQNJcjIyMjIyMg...")
with open('test.pdf','wb') as g:
    g.write(a.getvalue())

I created a file with this code but unable to open the file.
I need another way of doing the same.

A: instead of using io.BytesIO use base64.
import base64
data = "strin data"
base64_data =base64.b64decode(data)
with open(filename,'wb') as f:
    f.write(base64_data)


text:
Q: Got NoSuchMethodError (NoSuchMethodError: The method 'call' was called on null. error after yielding new state in flutter I got error when add new event to my bloc in flutter.
First time is ok but second time I got this error:
The following NoSuchMethodError was thrown while handling a gesture:
The method 'call' was called on null.
Receiver: null
Tried calling: call()

I add LoginEvent to bloc and in this event I yield LoadingState.
On first time is ok, but second time is not.
This is my screen:
class _AuthScreenState extends State<AuthScreen> {
  final AuthRepository repository = AuthRepository();
  PageController controller;

  @override
  void initState() {
    controller = PageController(initialPage: widget.page);
    super.initState();
  }

  void changePage(int page) {
    controller.animateToPage(
      page,
      curve: Curves.ease,
      duration: Duration(milliseconds: 300),
    );
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => AuthBloc(repository: repository),
      child: BlocBuilder<AuthBloc, AuthState>(
        builder: (context, state) {
          return ScreenContainer(
            pb: 25.0,
            withTapDetector: true,
            statusbarcolor: ColorPalette.primary,
            statusBarIconBrightness: Brightness.light,
            resizeToAvoidBottomPadding: false,
            removeAppbar: true,
            // loading: state is LoadingState,
            child: Container(
              width: double.infinity,
              height: double.infinity,
              child: Column(
                children: [
                  Expanded(
                    child: PageView.builder(
                      controller: controller,
                      physics: NeverScrollableScrollPhysics(),
                      itemCount: 2,
                      itemBuilder: (context, position) {
                        return position == 0
                            ? LoginPage(
                                onPageChange: () => changePage(1),
                                onSubmit: (req) => context.bloc<AuthBloc>().add(LoginEvent(req: req)),
                              )
                            : RegisterPage(
                                onPageChange: () => changePage(0),
                              );
                      },
                    ),
                  ),
                  googleLogin(context),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}

and this is my bloc:
class AuthBloc extends Bloc<AuthEvent, AuthState> {
  final AuthRepository repository;
  AuthBloc({
    @required this.repository,
  }) : super(InitialState());

  @override
  Stream<AuthState> mapEventToState(
    AuthEvent event,
  ) async* {
    if (event is RegisterEvent) {
      yield* _mapRegisterEventToState(event.req);
    } else if (event is LoginEvent) {
      yield* _mapLoginEventToState(event.req);
    }
  }

  Stream<AuthState> _mapRegisterEventToState(AuthReq req) async* {}

  Stream<AuthState> _mapLoginEventToState(AuthReq req) async* {
    yield LoadingState();
  }
}

A: There is 2 Mistakes in your code:

*

*You should always write your bloc-event-state code in try catch, that will make your code robust after bloc receive some error

*You are not listening to any changes in your build method and handle a default always. I think it will help you out from one time build Error

return BlocProvider(
  create: (context) => AuthBloc(repository: repository),
  child: BlocBuilder<AuthBloc, AuthState>(
    builder: (context, state) {
      if(state is State1) {
        return SocialMediaScreen()
      } else if(state is State2){
        return FullSpinnerScreen()
      } else {
        return InitialScreen()
      }
    }
  )


text:
Q: How to do some calculations in GLSL that only happens once per frame? I would like to precalculate some values to be used each time the fragment shader is called.
How/where do I do that?
I am using a full screen quad, four vertices.

A: Some profiling might be required to see if you will really benefit from precalculating these values instead of doing the calculations in the fragment shader (usually it's a win, but sometimes not).
If you will benefit from this, values calculated once per frame can be passed in as uniforms. You can also calculate these in the vertex shader and pass them along as varyings (which won't really vary), due to the small number of vertices you're talking about here.


text:
Q: warning : will never be excuted I updated an old Swift 1 app to Swift 2 using Xcode 7 and I'm getting a few warnings that were not there before I updated.
 required init(coder aDecoder: NSCoder) {

    fatalError("init(coder:) has not been implemented")

    // SWIFT 2 update
    state = .OptionsVisible
    super.init(coder: aDecoder)!
}

That function is giving me 2 warnings that both the state and the super lines will not be executed, but I'm not sure why? I figured something changed between Swift 1 and 2, but I'm not really sure what.
Thanks!

A: fatalError is now flagged as @noreturn, so the compiler can tell that nothing after that will be executed.


text:
Q: Scilab 6.02 app bounces but doesn't open up in MacOS BigSur I have installed Scilab 6.02 version in MacOS BigSur earlier after disabling the gatekeeper and it was working fine. However, after sending it for repair, I lost the application and have been trying to reinstall the app again. But even after disabling the gatekeeper, while trying to open it, the app bounces in dock but isn't opening up. This problem is not seen with other applications. Can someone help me out?
P.S: I don't have much knowledge when it comes to coding and other technical aspects. I am trying my best to understand, so I hope the answers would be in simplistic terms

A: Please install the branch-6.1 version at
https://www.utc.fr/~mottelet/scilab_for_macOS.html
unless you have a particular reason to still use 6.0.2 (I don't see any). Another point: please remove any JRE or JDK (in /Library/Java/JavaVirtualMachines/) you had before and let Scilab dowload the required one.
S.


text:
Q: how to remove the append child element in javascript <label id="1" >a</label><label id="2" > b </label>

I have two labels created. When a label is clicked, I create a div element within that I displayed. Now I need to remove the created div element if the label is again clicked.
if (click == 1) {
    var prevWin = document.createElement("div");
    prevWin.id = 1;
    prevWin.innerHTML = outMsg;
    document.body.appendChild(prevWin);
} else {
    var prevWin = document.body.getElementsById(1);
    document.body.removeChild(prevWin);
}

When a label is clicked the div element is created successfully. But when it is clicked again, the div element is not removed.

A: function labelOnClick () {
    var divs = this.getElementsByTagName("div");

    if (divs.length) {
        divs[0].parentNode.removeChild(divs[0]);
    } else {
        var div = document.createElement("div");
        div.innerHTML = outMsg;

        this.appendChild(div);
    }
}

ids have got to be unique throughout the DOM; in your example, it looks like you'll have the label and the div with the same id. You could easily append a string to the div id, if you want it to have an id (div.id = this.id + "_div").
My example wont work if you have more than one div in your label; in which case the ID approach would be best (or use a selector library).
Id's could be approached as follows:
function labelOnClick () {
    function makeDivId(id) {
        return id + "_div";
    };

    var div = this.getElementById(makeDivId(this.id));

    if (div) {
        div.parentNode.removeChild(div);
    } else {
        div = document.createElement("div");
        div.innerHTML = outMsg;
        div.id = makeDivId(this.id);

        this.appendChild(div);
    }
}


text:
Q: Filtering dates to within 7 days I have a working date filter that accepts a date string like 2018-02-09T19:35:54+00:00 and orders events by date.  I would like my filter to only push items in the next 7 days. I feel like I have a basic arithmetic error in my code.
function dashCalDateFilter() {
  return function(collection, key) {
      let output    = [];
      let keys      = [];
      let sevenDays = Date.now() + 604800000;

      angular.forEach(collection, function(item) {
        var ikey = item[key];
        if (keys.indexOf(ikey) === -1) {
          keys.push(ikey);
          item['isFirst'] = true;
        }
        console.log(item.start_time);
        if (Date.now() - Date.parse(item.start_time) < sevenDays){
          output.push(item);
        };
      });
      return output;
    };
}
export default dashCalDateFilter;

A: My math was a bit off.  Here is the working version
function dashCalDateFilter() {
  return function(collection, key) {
      let output    = [];
      let keys      = [];
      let sevenDays = 604800000;

      angular.forEach(collection, function(item) {
        var ikey = item[key];
        if (keys.indexOf(ikey) === -1) {
          keys.push(ikey);
          item['isFirst'] = true;
        }
        if ((Date.parse(item.start_time) - Date.now()) < 604800000){
          output.push(item);
        } else {
          console.log('in >7 days');
          console.log(Date.parse(item.start_time) - Date.now());
        };
      });
      return output;
    };
}
export default dashCalDateFilter;


text:
Q: Render a dictionary with object list as values in django I have a dictionary new:
new = {'Delhi-Mumbai': [<Truckdb: Truckdb object (6)>], 'Doon-Gurgaon': [<Truckdb: Truckdb object (8)>, <Truckdb: Truckdb object (6)>]}

I am not able to render the objects from TruckDb in templates
this is what i tried in views.py
return render(request, 'classroom/teachers/dispatcher_output.html',{'res':new})

this is my template:
{% for k,v in res.items %}

v value  is

      {{ v.Name }}

{% endfor %}

Models.py
class Truckdb(models.Model):

    Name = models.CharField(max_length=30)
    Category = models.CharField(max_length=30)
    Truckid = models.IntegerField(blank=True)
    Length = models.FloatField(blank=True)
    Breadth = models.FloatField(blank=True)
    Height = models.FloatField(blank=True)
    Volume = models.FloatField(blank=True)
    Weight = models.FloatField(blank=True)
    Price = models.FloatField(blank=True)

I am not able to understand what I am doing wrong ?
Edit
This is my output if use this in the template:

{% for k,v in res.items %}

v value  is

        {{ v.Name }}

{% endfor %}

What I want
I want to be able to use the objects just like any other model and get values based on the other properties the model has. Like so:
{% for k,v in res.items %}

v value  is

        {{ v.Name }}
        {{ v.Category }}
        {{ v.Truckid }}

{% endfor %}

A: You have to use two for loops because each element in the dict is a queryset
{% for k,v in res.items %}
    {% for element in v %}

v value  is

        {{ element.Name }}
    {% endfor %}

{% endfor %}


text:
Q: How to convert a string to timestamp in a desired timezone I need to convert a string that represents a timestamp without time zone (i.e. "2017-03-08T20:53:05")
in some time zone (e.g.'Etc/UTC') to a timestamp with timezone.
The issue is that the default time zone is not 'Etc/UTC'. So, when I'm trying to to
SELECT to_timestamp(field1, 'YYYY-MM-DD hh24:mi:ss')::timestamp without time zone at time zone 'Etc/UTC'

it converts the string to a value with the default timezone and then applies conversion from a local time zone to the 'Etc/UTC'. This is not what's requred.
Basically, I'm looking for a way to tell postgres that the original string value is representing time in a particular timezone, not the default local one.
Thank you.
Update: I've checked that the above statement is actually working.
SELECT to_timestamp(field1, 'YYYY-MM-DD hh24:mi:ss')::timestamp without time zone at time zone 'Etc/UTC'

I've been mislead by by the client's timezone setting.

A: In my case this did the trick (thanks to shajji answer)
to_timestamp(:date, 'YYYY-MM-DD"T"HH24:MI:SS:MS"Z"') at time zone (select current_setting('timezone')) at time zone 'Etc/UTC'

A: You could run set time zone UTC; before your query:
set time zone UTC;
SELECT to_timestamp(field1, 'YYYY-MM-DD hh24:mi:ss')::timestamp without time zone at time zone 'Etc/UTC';

Does this solve your issue ?

A: My question is different than OP's question. My string already knows its timezone. I just want to convert to the timestamptz datatype.
In other words: "how to convert a string in a desired timezone, to a timestamp". I could use the approach described here and here; casting with ::timestamptz
SELECT '2016-01-01 00:00+10'::timestamptz;

A: First find your default timezone. by using following query.
Select current_setting('timezone');
In my case Asia/Karachi
k, now just try following query.
Select Cast('1990-01-25' as Date) at time zone '<Your Default Timezone>' at time zone 'utc';

In my case.
Select Cast('1990-01-25' as Date) at time zone 'Asia/Karachi' at time zone 'utc';


text:
Q: What are the possible strategies to transfer data from an FPGA accelerator to a hard-core CPU? I am beginning with FPGAs and I am working on an accelerator that acquires data from a microphone (Pulse Density Modulation) and extracts a single frequency from the signal.
My accelerator is basically a digital filter, that multiplies each audio sample with a complex phasor and adds everything together. After n samples it should produce a complex number (representing phase and amplitude of a given frequency) and make it available to a CPU somehow.
My question is:
what is the best/simplest strategy to transfer data from the FPGA to the CPU?

Note the following:

*

*I am using a Zynq UltraScale+ MPSoC from Xilinx (more precisely the zu3eg), and CPU and FPGA are on the same physical chip.

*My accelerator is an AXI slave that should be programmed and started by the CPU

*I need to transfer approximately 240 KB/sec from the FPGA to the CPU

The possibilities I could think of are:

*

*Create a sort of FIFO within my accelerator: use some registers to store the last m results and signal the CPU with an interrupt when this output buffer is getting full. The data would be read by the CPU through the AXI interface.

*Use an external FIFO: use one of VIVADO modules to implement a FIFO between my accelerator and the CPU. I guess this forces me to implement an AXI master interface on my accelerator?

*Write the results in the FPGA's BRAM in a circular buffer

Could you explain what are the best design patterns for this type of problem?
As I said I am rather new to FPGAs and it would be great to have some advice from someone with more experience. Any pointer to good references would also be greatly appreciated
Thanks a lot!!

A: Xilinx offers reference drivers, and I think by now even some of the AXI infrastructure is in the upstream linux kernel. Other companies (ADI for example) have publicly available Linux images for RFSoC devices, that should easily port to MPSoC as well.
Since you're streaming data, a usual approach would be using a DMA controller to write into the DDR Ram that the ARM core also accesses.
You could raise an interrupt whenever a buffer is ready (that's pretty much the way PCI sound cards work) and then handle that in software. But considering audio rates are incredibly low from a modern CPU's point of view, software-polling a status register might work just as well and reduce the interrupt overhead if you have so many channels that you can always be sure that one is done.
Note that I'm assuming this targets a massive-multi-channel thing, or something requiring an impressive convolution length, or is to learn how to build such a system (not necessarily actually build that system); audio-rate convolution is really hard for normal PC-style processors. That's why I recommend "large data volume" techniques instead of "oh yeah, that rate is low enough you can directly MMIO-query that in a software loop".


text:
Q: Path finding in undirected fully connected graph I have an undirected fully connected graph. I have a start node and there is no end node. My nodes and edges don't have weights. Any path on the graph has some value. I can only know this value after going in this entire path. Path length is limited, but it can be very large.
For example:

It might be that:

*

*The value of the path node1 -> node2 is 1

*The value of the path node1 -> node3 is 1

*The value of the path node1 -> node2 -> node3 is 2

*The value of the path node1 -> node3 -> node2 is 20

My goal is to find some path with small value without traversing all possible paths. The smallest the value, the better.
I cannot use any familiar shortest-path algorithm like Dijkstra or Floyd-Warshall since i don't have an end node nor known weights in advance.
I was thinking on the following simple algorithm:

*

*Starting from the start node, go to some other node. Evaluate the path.

*From the next node, go to some other node. Evaluate the path. If the path's value is larger than before, go back and try another node.

Is there a known algorithm for that problem?
Thanks


text:
Q: elastic search suggest type broken by keywords analyzer CustomAnalyzer productIndexAnalyzer = new CustomAnalyzer
        {
            Tokenizer = "standard",
            Filter = new List<string> { TURKISH_LOWERCASE, "apostrophe", "asciifolding", ENGRAM_FILTER }
        };

        IIndicesOperationResponse indicesOperationResponse = _elasticClientFactory.Create().CreateIndex(SearchConstants.ProductIndex, c => c
            .Analysis(analysis => analysis
                .TokenFilters(tf => tf
                    .Add(TURKISH_LOWERCASE, turkishLowercaseTokenFilter)
                    .Add(ENGRAM_FILTER, edgeNgramTokenFilter))
                .Analyzers(a => a
                    .Add(PRODUCT_SEARCH_ANALYZER, productSearchAnalyzer)
                    .Add(PRODUCT_INDEX_ANALYZER, productIndexAnalyzer)
        ))
            .AddMapping<Product>(m => m.MapFromAttributes().Properties(props => props
                .Completion(s => s
                    .Name(p => p.Suggest)
                    .MaxInputLength(20)
                    .Payloads()
                    .PreservePositionIncrements()
                    .PreserveSeparators()
                )
            ))
            );

nest client mapping result on elastic:
"suggest": {
              "type": "completion",
              "analyzer": "simple",
              "payloads": true,
              "preserve_separators": true,
              "preserve_position_increments": true,
              "max_input_length": 20
           },

productIndexAnalyzer changed and  I add a TURKISH_KEYWORDS analyzer
I indexed the results as follows nest with client.It is set to suggest the type of completion.
CustomAnalyzer productIndexAnalyzer = new CustomAnalyzer
        {
            Tokenizer = "standard",
            Filter = new List<string> { TURKISH_LOWERCASE, "apostrophe", "asciifolding", ENGRAM_FILTER, "turkish_keywords" }
        };

But it suggests the type is distorted when I add a TURKISH_KEYWORDS analyzer and it's a string.
nest client mapping result on elastic:
"suggest": {
              "properties": {
                 "input": {
                    "type": "string"
                 },
                 "output": {
                    "type": "string"
                 },
                 "weight": {
                    "type": "long"
                 }
              }
           }

I'm using NEST Version 1.7.0 and Elasticsearch  Version 1.7.3


text:
Q: can you prevent Wifi from shutting off during screen lock or screen lock? I have an app that creates time lapse movies on os x from webcams available through a url. Recently I have had lots of users complaining that the recordings are dropping tons of frames. I have isolated the problem to Yosemite disconnecting the wifi when the screen locks. Is there a way to let the system know that it is important that your app keeps the network connection? It is annoying to tell the users to go in and disable screen locking just to use my app.

A: If the Wi-Fi is really turning off, that sounds like an Apple bug.
You can disable App Nap & idle sleep by registering an "activity".
The NSActivityUserInitiated option should be enough.
There's also NSActivityIdleDisplaySleepDisabled.


text:
Q: Horizontal JScrollPane inside vertical JScrollPane Good afternoon! It is necessary to make a list (vertical) from lists of events (horizontal). There are at least 2 problems:

*

*the area of the list of events (horizontal scrolling) expands beyond the borders of the panel. Apparently, the problem is with Layout, but I can not find the right combination;

*horizontal scrolling does not work (probably due to the problem described above) and the scrollbar must be different for each group of events.

import ivank.components.EventAdd;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class WindowAddCameras extends JFrame {
    public static final List<JPanel> labels = new ArrayList<JPanel>();

    public WindowAddCameras() {
        super("Добавить камеру");

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panelButton = new JPanel();

        JButton addButton = new JButton("+");
        addButton.setFocusable(false);
        panelButton.add(addButton);

        JButton remButton = new JButton("-");
        remButton.setFocusable(false);
        panelButton.add(remButton);

        JPanel externalPanel = new JPanel();
        externalPanel.setLayout(new BorderLayout(0, 0));
        JScrollPane scrollPaneGroupEvent = new JScrollPane(
                externalPanel,
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
        );

        JPanel internalPanel = new JPanel();
        internalPanel.setLayout(new GridLayout(0, 1, 0, 0));

        JScrollPane scrollPaneEvent = new JScrollPane(internalPanel);
        scrollPaneEvent.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
        scrollPaneEvent.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

        externalPanel.add(scrollPaneEvent, BorderLayout.NORTH);
        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int number = labels.size() + 1;
                EventAdd eventAdd = new EventAdd();
                Dimension labelSize = new Dimension(80, 80);

                //add event to group event
                Random rand = new Random();
                for(int a = 0; a < 20; a++) {
                    //random color border event for TEST
                    Color randomColor = new Color(rand.nextFloat(), rand.nextFloat(), rand.nextFloat());
                    eventAdd.createEventLabel("Камера " + number, labelSize, randomColor);
                }

                labels.add(eventAdd);
                internalPanel.add(eventAdd, BorderLayout.NORTH);
                scrollPaneGroupEvent.revalidate();
            }
        });

        remButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(labels.size() > 0) {
                    int index = labels.size() - 1;
                    JPanel panel = labels.remove(index);
                    internalPanel.remove(panel);
                    internalPanel.repaint();
                    scrollPaneGroupEvent.revalidate();
                }
            }
        });

        this.getContentPane().setLayout(new BorderLayout());
        this.getContentPane().add(panelButton, BorderLayout.NORTH);
        this.getContentPane().add(scrollPaneGroupEvent, BorderLayout.CENTER);

        this.setPreferredSize(new Dimension(600, 400));
        this.pack();
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }
}

package ivank.components;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;

public class EventAdd extends JPanel {
    public EventAdd() {
        super(new FlowLayout(FlowLayout.LEFT));
    }

    public JComponent createEventLabel(String name, Dimension labelSize, Color randomColor) {
        this.setBorder(BorderFactory.createTitledBorder(name));
        JLabel label = new JLabel();
        label.setPreferredSize(labelSize);
        label.setHorizontalAlignment(JLabel.CENTER);

        label.setBorder(BorderFactory.createLineBorder(randomColor, 5));
        this.add(label);

        return label;
    }
}

What I have: enter image description here
What I want to get: enter image description here

A: A scrolling area inside another scrolling area is a user interface antipattern (anti-design?).  It should be avoided.
I would create a scrollable panel based on a vertical BoxLayout:
public class WindowAddCameras extends JFrame {
    private static final long serialVersionUID = 1;

    public static final List<JPanel> labels = new ArrayList<JPanel>();

    private static class CameraListPanel
    extends JPanel
    implements Scrollable {
        private static final long serialVersionUID = 1;

        CameraListPanel() {
            setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        }

        @Override
        public Dimension getPreferredScrollableViewportSize() {
            return getPreferredSize();
        }

        @Override
        public boolean getScrollableTracksViewportWidth() {
            return true;
        }

        @Override
        public boolean getScrollableTracksViewportHeight() {
            return false;
        }

        @Override
        public int getScrollableUnitIncrement(Rectangle visibleRect,
                                              int orientation,
                                              int direction) {
            return getScrollableIncrement(30,
                visibleRect, orientation, direction);
        }

        @Override
        public int getScrollableBlockIncrement(Rectangle visibleRect,
                                               int orientation,
                                               int direction) {
            return getScrollableIncrement(
                orientation == SwingConstants.HORIZONTAL ?
                    getWidth() : getHeight(),
                visibleRect, orientation, direction);
        }

        private int getScrollableIncrement(int amount,
                                           Rectangle visibleRect,
                                           int orientation,
                                           int direction) {
            if (orientation == SwingConstants.HORIZONTAL) {
                return Math.min(amount, direction < 0 ? visibleRect.x :
                    getWidth() - (visibleRect.x + visibleRect.width));
            } else {
                return Math.min(amount, direction < 0 ? visibleRect.y :
                    getHeight() - (visibleRect.y + visibleRect.height));
            }
        }
    }

    public WindowAddCameras() {
        super("Добавить камеру");

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panelButton = new JPanel();

        JButton addButton = new JButton("+");
        addButton.setFocusable(false);
        panelButton.add(addButton);

        JButton remButton = new JButton("-");
        remButton.setFocusable(false);
        panelButton.add(remButton);

        JPanel camerasPanel = new CameraListPanel();
        JScrollPane scrollPaneGroupEvent = new JScrollPane(camerasPanel);

        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int number = labels.size() + 1;
                EventAdd eventAdd = new EventAdd();
                Dimension labelSize = new Dimension(80, 80);

                //add event to group event
                Random rand = new Random();
                for(int a = 0; a < 20; a++) {
                    //random color border event for TEST
                    Color randomColor = new Color(rand.nextFloat(), rand.nextFloat(), rand.nextFloat());
                    eventAdd.createEventLabel("Камера " + number, labelSize, randomColor);
                }

                labels.add(eventAdd);
                camerasPanel.add(eventAdd);
                scrollPaneGroupEvent.revalidate();
            }
        });

        remButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(labels.size() > 0) {
                    int index = labels.size() - 1;
                    JPanel panel = labels.remove(index);
                    camerasPanel.remove(panel);
                    camerasPanel.repaint();
                    scrollPaneGroupEvent.revalidate();
                }
            }
        });

        this.getContentPane().setLayout(new BorderLayout());
        this.getContentPane().add(panelButton, BorderLayout.NORTH);
        this.getContentPane().add(scrollPaneGroupEvent, BorderLayout.CENTER);

        this.setPreferredSize(new Dimension(600, 400));
        this.pack();
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new WindowAddCameras());
    }
}

The CameraListPanel class is mostly a basic scrollable panel;  the important part is that getScrollableTracksViewportWidth() returns true, which will cause the panel's width to match the width of any JScrollPane viewport.  This eliminates any need for a horizontal scrollbar.
Of course, you will want to show all of your child components somehow.  To do that, I would have the EventAdd class compute a height that can accommodate all of the children:
public class EventAdd extends JPanel {
    private static final long serialVersionUID = 1;

    private final FlowLayout layout;

    public EventAdd() {
        layout = new FlowLayout(FlowLayout.LEFT);
        setLayout(layout);
    }

    @Override
    public Dimension getPreferredSize() {
        Rectangle childSize = new Rectangle();
        Component[] children = getComponents();
        for (Component child : children) {
            childSize.add(new Rectangle(child.getPreferredSize()));
        }

        Insets insets = getInsets();

        int hgap = layout.getHgap();
        int vgap = layout.getVgap();
        int childWidth = childSize.width + hgap;

        Dimension size;
        if (getParent() == null) {
            size = new Dimension(
                children.length * (childWidth * hgap) + hgap,
                childSize.height + vgap * 2);
        } else {
            int width = getParent().getWidth();
            width -= insets.left + insets.right;
            int childrenPerRow =
                childWidth == 0 ? 0 : (width - hgap) / childWidth;

            int rows;
            if (childrenPerRow == 0) {
                rows = 0;
            } else {
                rows = children.length / childrenPerRow;
                if (children.length % childrenPerRow > 0) {
                    rows++;
                }
            }
            size = new Dimension(width,
                vgap + rows * (childSize.height + vgap));
        }

        size.width += insets.left + insets.right;
        size.height += insets.top + insets.bottom;

        return size;
    }

A: A JScrollPane must have a JViewport assigned using the jscrollpane method setViewportView. You should also give it a scrollbar policy
setVerticalScrollBarPolicy
setHorizontalScrollBarPolicy
The policy int is part of the class for the two previous methods and are called "constant field values" , see the API doc for JScrollPane.
To expand the JScrollPane out, put it in a JPanel with a BorderLayout and NO OTHER elements in that particular panel with the JScrollPane.
Use on the JPanel, the methods setMinimumSize and setPreferredSize and setSize or a BoxLayout in the main window(although i think main windows have a special layout so a boxlayout would not be required if so) or higher level panel in the stack, or just setPreferredSize for the JScrollPane.
A jscrollpane has a view set by its "setView" method , its view is a java.awt.Component note: a JComponent is a java.awt.Component, any javax swing J panel or J viewport is a java.awt.Component by hierarchy. NOTE a jviewport is a java.awt.Component
so get a jscrollpane.setViewportView
add the jviewport reference jviewport.setView as the JPanel with the BorderLayout , add another panel to start adding other components, but remember to give all Jcomponents a .preferredSize method use.
If you are after javax.swing.JList<E> and javax.swing.DefaultListModel<E>
The JList must be placed in a JPanel with a BorderLayout , or much more difficult system  a java.awt.GridBagLayout then in a jscrollpane.

A: You can do the horizontal and vertical scrolling with only one JScrollPane. But what you need is an underlying JComponent that renders your content. This however can be a JPanel that stretches as far as you need.
Have a look at How to use ScrollPanes.


text:
Q: CSS: Get every element inside a  and assign it a value? I have a defined style:
#style p {
    padding:10px;
}

I do not know what elements will be inside the p. Is there a way to say that all elements inside that p should also have padding of 10px? Something like:
#style p everything {
    padding:10px;
}

A: You can use the universal selector *
#style p *
{
    padding:10px;
}

It literally stands for "everything" so this selector will select any and all elements within your p. :)

A: Used to this
#style p * {
    padding:10px;
}


text:
Q: unwanted object property changed when changing another object property c# from what i understand in other posts i know that my objects use same place in memory but how to separate these objects?
i tried to use new but it didn't work or i didn't used it correctly.
Note that i didnt paste setter and getter here.
class Supermarket
{
    List<Product> _products = new List<Product>{ };
    List<Customer> _customers = new List<Customer>{ };
}

class Customer
{
    List<Product> _purchased= new List<Product>{ };
}
class Product
{
    string _id;
    string _name;
    DateTime _expireDate;
    int _cost;
    int _count;
}

i add one Product in one Method.
Product product = new Product(...);
supermarket.Products.Add(product);

and in another method i want to copy the Product from Supermarket.Products
 to Supermarket.Customers.Purchased. so i want a copy but i cant get it.
here i want to make Copy but it does not work.
Product product = supermarket.Products[productIndex];
supermarket.Customers[customerIndex].Purchased.Add(product);

now the problem is when i change Product properties in Customer class , Product properties inside Supermarket will change too.
for example
supermarket.Customers[customerIndex].Purchased.Last().Count = ...
//now the Product supermarket.Products[productIndex] will change too witch is unwanted

A: The reason why it is not working is because you are doing shallow copy by just  adding the pointer of product object into the list, not all properties. So if you change one, another will be affected accordingly.
You can use deep copy following this answer, but this way you have to mark your class as [Serializable]. The simplest way which I think is to use Json serializer:
public static class CloneHelper
{
    public static T Clone<T>(T source)
    {
        var serialized = JsonConvert.SerializeObject(source);
        return JsonConvert.DeserializeObject<T>(serialized);
    }
}

var copyProduct = CloneHelper.Clone<Product>(product);

Or simply, you can manage by yourself as the below code, then it works:
Product product = supermarket.Products[productIndex];

Product copyProduct = new Product() {
    Id = product.Id,
    Name = product.Name,
    ExpireDate = product.ExpireDate,
    Cost = product.Cost,
    Count = product.Count
};

supermarket.Customers[customerIndex].Purchased.Add(copyProduct);


text:
Q: Python. Crear listas con datos que introduce el usuario Soy nuevo en python y quisiera saber como crear dos listas de n datos ingresadas por el usuario para luego operar con sus elementos.
Desde ya gracias por la ayuda

A: @Tony
Si entendi bien lo que esperas lograr este codigo te ayudara:
#Creamos 2 listas vacias
lista1 = []
lista2 = []

#Preguntamos al usuario cuantos datos desea integrar
cantidad = int(input("Cuantos datos desea agregar: "))

#Greneramos un cilo para que se repitan las preguntas mientras la cantidad sea mayor que 0
while cantidad>0:
    #Pedimos que indique en que lista deea guardar su dato
    lista = input("En que lista desea ingresas sus datos \n1) Lista1 \n2) Lista2 \n")
    #Pedimos el dato
    dato = input("Ingrese sus datos: ")
    #Comprobamos la decision del usuario para saber en que lista se guardara el dato
    if lista == 1:
        lista1.append(str(dato))
    else:
        lista2.append(str(dato))
    #Quitamos de a uno en uno los intentos de el valor inicial que l usuario indico para poder detener el ciclo
    cantidad-=1
#Finalmente imprimimos el contenido de las listas
print("Contenido lista1:\n",lista1)

Lo que se propone:

*

*En el anterior código preguntamos al usuario un numero determinado de datos que desea ingresar para ambas listas

*Después de eso el usuario decidirá en que lista se añadirá ese dato.

*Una vez que llegue a 0 el numero de datos que ingresaría el programa finalizara mostrando el contenido de ambas listas


text:
Q: let definitions visible after error in gambit's gsi? While experimenting with gambit's gsi (4.6.6), I ran into an odd situation when I typed in something invalid inside let.
Doing it the normal way, everything is as expected. i andj are not visible.
> (let ((i 4) (j 3)) (display (+ i j)) (newline))
7
> i
*** ERROR IN (console)@2.1 -- Unbound variable: i
1> j
*** ERROR IN (console)@3.1 -- Unbound variable: j

However, if I flub up in the let block, i andj are visible. It's almost as if I'm still inside the scope of the let form. Is that what's going on? Also, looking at the numbers on the prompt e.g. >1> `2> etc. It looks like there's information there as well. If so, what is that? Maybe something related to nesting or an error mode?
2> (let ((i 2) (j 3)) (display + i j) (newline))
*** ERROR IN (console)@4.20 -- Wrong number of arguments passed to procedure
(display '#<procedure #2 +> 2 3)
3> i
2
3> j
3

This is a little different than in clojure. e.g.
user=> (defn display [n] (print n))
#'user/one-arg-function
user=> (let [i 2 j 3] (display + i j) (println))
ArityException Wrong number of args (3) passed to: user$one-arg-function clojure.lang.AFn.throwArity (AFn.java:437)

user=> i
CompilerException java.lang.RuntimeException: Unable to resolve symbol: i in this context, compiling:(NO_SOURCE_PATH:0)

user=> j
CompilerException java.lang.RuntimeException: Unable to resolve symbol: j in this context, compiling:(NO_SOURCE_PATH:0)

A: This is a feature of Gambit's interactive debugger.
From the manual: http://www.iro.umontreal.ca/~gambit/doc/gambit-c.html#Debugging

A nested REPL is then initiated in the context of the point of
  execution where the evaluation was stopped. The nested REPL's
  continuation and evaluation environment are the same as the point
  where the evaluation was stopped. For example when evaluating the
  expression '(let ((y (- 1 1))) (* (/ x y) 2))', a "divide by zero"
  error is reported and the nested REPL's continuation is the one that
  takes the result and multiplies it by two. The REPL's lexical
  environment includes the lexical variable 'y'. This allows the
  inspection of the evaluation context (i.e. the lexical and dynamic
  environments and continuation), which is particularly useful to
  determine the exact location and cause of an error.

In your case, the nested REPL started inside the let and thus had i and j bound.


text:
Q: import text files to r I'm trying to import multiple text files to R but I'm not able to
I have the text files stored in a temp file.
They are named as 1.txt, 2.txt up to 32912.txt
I need to find frequent patterns in them
Does anyone know how to import all of them once to R

A: Substituting in your own path, of course, this will do it:
library(quanteda)
mycorpus <- corpus(textfile("~/myDirectoryOfTextFiles/*.txt"))

Get the texts out using
texts(mycorpus)

or read the package instructions/vignette to see further possibilities.


text:
Q: How to get user information for specific events in Google Analytics? We have set up Google Analytics on Requestly Pricing Page. We  are already getting site-related information, anonymous statistics, events from the page like

*

*Pricing Page viewed

*Coupon Applied Successfully

*Duration Changed to Monthly

*Premium plan bought

*.. so on ..

However, Now we want to track the users who are performing a specific event like

*

*Pricing Page Viewed

but did not purchase premium plan So that we can send targetted emails to those users. If we can get the user IDs (non PII data) from Google Analytics for a particular event, we can map them from our CRM system and get their emails and send them an email.
So, How can we get the list of users associated with some event?

A: If you are sending the information to Google Analytics as a custom dimension, simply add the second dimension in the Event report.
If you are sending the userId with its defined parameter you have to enable User-ID in your Property and create a User-ID view to see the data in your Analytics reports: https://support.google.com/analytics/answer/3123666?hl=en

A:
Yes we have started sending User Ids to Analytics and now we are able to see User performing events in User explorer but I would like a reverse way. Given an event I want to know which users performed that event.

User ID in Google Analytics
There are three ways to import the User ID in Google Analytics:

*

*customizing the schema field userId

*setting up a custom dimension which contains the value

*both of the above

In case 1, you can access the data via Google Analytics in User Explorer report, setting up a User ID View.
In case 2, you can access the data in each report that allows to define a secondary dimension.
In both cases, you can access the data in Google BigQuery, if you set up the export.
About your specific need
To know which users performed a specific event I suggest you to create a custom report in which you specify the event in the filters and you set your User ID custom dimension as dimension. This approach of course assumes that you import the User ID at least as a custom dimension.


text:
Q: How to configure Apache2 for Redmine properly? I have a working Redmine installation on my Debian server, but I don't know how to configure Apache2 properly so that neither the content of the Redmine folder nor the Redmine start page will be displayed as the homepage of my website. Suppose the URL of the website was www.myexample.com.
Current state

*

*www.myexample.com shows files of /var/www/redmine folder

*with the symbolic link /var/www/redmine -> /usr/local/lib/redmine-2.1/public/
Wanted state

*

*www.myexample.com should be my usual website homepage (e.g. showing index.html)

*www.redmine.myexample.com or www.myexample.com/redmine should show the redmine page

I guess it is just a configuration problem but I cannot figure out the problem. So here are my configuration files. Do you see what I am missing here?

*

*/etc/apache2/httpd.conf
<VirtualHost *:80>
  ServerName redmine.example.com
  DocumentRoot /var/www
  <Directory /var/www>
    AllowOverride all
    Options -MultiViews
  </Directory>
</VirtualHost>

*/etc/apache2/sites-available/redmine
<VirtualHost *:80>
  DocumentRoot /var/www/redmine
  <Directory /var/www/redmine>
    AllowOverride all
    Options -MultiViews
    RailsBaseURI /redmine
  </Directory>
</VirtualHost>

*/etc/apache2/sites-available/default
<VirtualHost *:80>
    ServerAdmin webmaster@localhost

    DocumentRoot /var/www
    <Directory />
            Options FollowSymLinks
            AllowOverride None
    </Directory>
    <Directory /var/www/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride None
            Order allow,deny
            allow from all
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
            AllowOverride None
            Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

After changing any of these files, do I have to restart Apache2 or use a2ensite to activate any of the hosts?

A: I've written a how-to including this. While it is about Redmine 1.3.x it should be still relevant for the Apache part.
Full how-to: Redmine stable on Debian stable. Basically, it comes down to this:

*

*Install and configure mod_passenger in /etc/apache2/mods-available/passenger.conf:

PassengerDefaultUser www-data
# Below are some lines to tweak mod-passenger.
# This keeps some Ruby processes running,
# but the average response time is a lot lower
# on low-traffic sites.
RailsSpawnMethod smart
PassengerPoolIdleTime 3000
RailsAppSpawnerIdleTime 0
PassengerMaxRequests 1000

*Extend your current main 'site', for example /etc/apache2/sites-available/mymainsite:

<Directory /var/www/redmine>
        RailsBaseURI /redmine
        PassengerResolveSymlinksInDocumentRoot on
</Directory>

*Create another 'site' and include the same as above, changing the RailsBaseURI value to /.


text:
Q: J8583: ISO8583 MessageFactory has no parsing guide for message type "ffffff50" I try to write a stub that emulate ISO server on socket.
When I recieve the message, I get something like ths:
[pool-1-thread-5] ERROR com.solab.iso8583.MessageFactory - ISO8583 MessageFactory has no parsing guide for message type ffffff50 [ r$$? ??A??#9i.....

Message in console:
Parsing incoming message:  r$$? ??A??#@&       i?....

I don't know what message type I get..
Why does it have so strange encoding? How can I fix that?
server code:
public class SocketServer implements Runnable {
    private static final Log log = LogFactory.getLog(SocketServer.class);
    private static ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(5);
    private static MessageFactory messageFactory;
    private Socket socket;

    public SocketServer(Socket socket){
        this.socket = socket;
    }

    public void run() {
        int count = 0;
        byte[] bufferLenght = new byte[2];
        try{
            while (socket != null && socket.isConnected()
                    && Thread.currentThread().isAlive()
                    && !Thread.currentThread().isInterrupted()){
                if (socket.getInputStream().read(bufferLenght) == 2){
                    int size = ((bufferLenght[0] & 0xff) << 8) | (bufferLenght[1] & 0xff);
                    byte[] buffer = new byte[size];
                    socket.getInputStream().read(buffer);
                    count++;
                    threadPool.schedule(new Processor(buffer, socket), 400, TimeUnit.MILLISECONDS);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.debug(String.format("Count of requests: %d", count));
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

class processor which processes the message...
    private class Processor implements Runnable{

        private byte[] message;
        private Socket socket;

        public Processor(byte[] buffer, Socket socket){
            this.message = buffer;
            this.socket = socket;
        }

        public void run() {
            try{
                System.out.println(String.format("Parsing incoming message: %s", new String(message)));
                IsoMessage request = messageFactory.parseMessage(message,4);
                IsoMessage response = messageFactory.createResponse(request);
                response.setField(11, request.getField(11));
                response.setField(7, request.getField(7));
                response.write(socket.getOutputStream(), 2);
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

main
    public static void main(String[] args) throws IOException {
        messageFactory = ConfigParser.createFromClasspathConfig("config.xml");
        System.err.println("Setting up server socket...");
        ServerSocket serverSocket = new ServerSocket(8583);
        System.err.println("Waiting for connections...");
        while (true){
            Socket socket = serverSocket.accept();
            System.err.println(String.format("New connection from %s:%d", socket.getInetAddress(), socket.getPort()));
            new Thread(new SocketServer(socket),"iso8583 server").start();
        }
    }
}

part of my config.xml:
    <parse type="0100">
        <field num="2" type="NUMERIC" length="20" />
        <field num="3" type="NUMERIC" length="6" />
        <field num="4" type="AMOUNT" />
        <field num="7" type="DATE10" />

..............

        <field num="62" type="LLLVAR" />
        <field num="63" type="LLLVAR" />
        <field num="64" type="LLLVAR" />
    </parse>

Thanks in advance!

A: Seems like the message is binary encoded and you weren't expecting that? Or the other way around, maybe (message is ASCII encoded and you're trying to read it as binary encoded)