text:
Q: CSS not extending? I am working on a project I created myself (www.deepsecurity.org) which people will be able to paste stuff and much more in the future.
I have a problem with this project though, if you check the site and check the "Th Bible" paste someone posted, you can clearly see that the post goes out of the black screen and you cannot read the rest anymore.
How can I fix this? Been trying for hours.
I am using Flask + SQLAlchemy + WTForms and Pygments.
Take a look at the css (I write very back css, sorry about that)
style.css
@import url('topbar_style.css');
@import url('errors.css');
@import url('showcodes.css');
@import url('addcode.css');
@import url('highlight.css');
@import url('about.css');
@import url('login.css');

html {
    font-family: 'Lucida Console', Monaco, monospace;
    font-size: 13px;
    color: #FFFFFF;
    background: #F2F2F2 url('images/bg_body.png') repeat-x 0 0;
    display: inline-block
}

.page {
    overflow: hidden;
    margin: 3em auto;
    width: 950px;
    display: inline-block
    border: 5px solid #ccc;
    padding: 0.8em;
    border: 1px solid #383838;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    background: #202020;
}

div.codes h1 {
    font-family: 'Lucida Console', Monaco, monospace;
    margin: 0px;
    color: #F2F2F2;
    border-bottom: 2px solid #eee;
}

h2 {
    font-size: 15px;
}

div.about-text {
    white-space: pre;
}

div.codes {
    white-space: pre;
}

showcodes.css
.codes {
    display: inline;
    list-style: none;
    margin: 0;
    padding: 0;
}

.codes li {
    margin: 0.2em 1em;
}

A: Ok, so, you have two problems in this page:

*

*style.css , line 44,
div.codes {
    white-space: pre;
}

delete that.

*In the "Bible" part of the page, the paste has a <code><pre> tag, which basically forces the text to be "unformatted" http://reference.sitepoint.com/html/pre
you can either change all code/pre elements to div's or p's, or you can simple add this line to your css file:
code {
    white-space: normal;
}

problem solved!

A: It is because of the white-space CSS declaration. To fix it use the following:
.codes code {
    white-space:pre-wrap;
}

This will keep the pre-formatted text as is, but force the it to wrap.

A: I believe it is because white-space: pre only follows line breaks that were preformatted, change it to white-space: normal;

A: *

*You can't read the rest of the text outside the div because of
.page {
 overflow: hidden;
}

*And it isn't wrapping because of those darn pre tags. Remove them.

*Also, change
div.codes {
 white-space: pre;
}

to
   div.codes {
    white-space: normal;
   }


text:
Q: Android room failed to open database It crashes when queried from room dao. Does anyone have ideas?
It work well on nexus 5 android 6.0, but crashes on nokia 8 android 8.1
06-23 01:19:02.469 2652-2729/com.aaa.bbb E/SQLiteLog: (14) cannot open file at line 35807 of [605907e73a]
    (14) os_unix.c:35807: (21) open(/data/user/0/com.aaa.bbb/files) -
06-23 01:19:02.472 2652-2729/com.aaa.bbb E/SQLiteDatabase: Failed to open database '/data/user/0/com.aaa.bbb/files'.
    android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
        at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
        at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:210)
        at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:194)
        at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:493)
        at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:200)
        at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:192)
        at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:864)
        at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:849)
        at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:724)
        at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:714)
        at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:295)
        at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:238)
        at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:96)
        at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:54)
        at android.arch.persistence.room.RoomDatabase.query(RoomDatabase.java:233)
        at com.aaa.bbb.manager.db.CityAreaDao_Impl$4.compute(CityAreaDao_Impl.java:229)
        at com.aaa.bbb.manager.db.CityAreaDao_Impl$4.compute(CityAreaDao_Impl.java:215)
        at android.arch.lifecycle.ComputableLiveData$2.run(ComputableLiveData.java:100)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
        at java.lang.Thread.run(Thread.java:764)

------------------- The DB Manager -------------------
@Database(entities = [(EMCityArea::class)], exportSchema = false, version = 1)
private abstract class EMDataBase : RoomDatabase() {
    abstract fun cityAreakDao():CityAreaDao
}

class EMDBManager private constructor(){
    companion object {
        val share: EMDBManager by lazy { EMDBManager() }
    }

    private val db = Room.databaseBuilder(App.applicationContext(), EMDataBase::class.java,"dbfile.db").build()

    val cityAreaDao:CityAreaDao
        get() = db.cityAreakDao()

    fun allCountry():LiveData<List<EMCityArea>>{
        return cityAreaDao.allCounty()
    }
}

------------------- Query -------------------
EMDBManager.share.allCountry().observe(this, Observer {coutryItems ->
    if (coutryItems == null){return@Observer}
    mCountryAdapter.clear()
    mCountryAdapter.addAll(coutryItems.mapNotNull { it.name })
    mCountryAdapter.notifyDataSetChanged()
})

A: The crash is caused by override getDatabasePath in my application
override fun getDatabasePath(name: String?): File {
    return filesDir
}

In my case, just delete the method.

redpajama_set_name: RedPajamaStackExchange


text:
Q: log messages appearing twice with Python Logging I'm using Python logging, and for some reason, all of my messages are appearing twice.
I have a module to configure logging:
# BUG: It's outputting logging messages twice - not sure why - it's not the propagate setting.
def configure_logging(self, logging_file):
    self.logger = logging.getLogger("my_logger")
    self.logger.setLevel(logging.DEBUG)
    self.logger.propagate = 0
    # Format for our loglines
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    # Setup console logging
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(formatter)
    self.logger.addHandler(ch)
    # Setup file logging as well
    fh = logging.FileHandler(LOG_FILENAME)
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(formatter)
    self.logger.addHandler(fh)

Later on, I call this method to configure logging:
if __name__ == '__main__':
    tom = Boy()
    tom.configure_logging(LOG_FILENAME)
    tom.buy_ham()

And then within say, the buy_ham module, I'd call:
self.logger.info('Successfully able to write to %s' % path)

And for some reason, all the messages are appearing twice. I commented out one of the stream handlers, still the same thing. Bit of a weird one, not sure why this is happening. I'm assuming I've missed something obvious.

A: If you are seeing this problem and you're not adding the handler twice then see abarnert's answer here
From the docs:

Note: If you attach a handler to a logger and one or more of its
ancestors, it may emit the same record multiple times. In general, you
should not need to attach a handler to more than one logger - if you
just attach it to the appropriate logger which is highest in the
logger hierarchy, then it will see all events logged by all descendant
loggers, provided that their propagate setting is left set to True. A
common scenario is to attach handlers only to the root logger, and to
let propagation take care of the rest.

So, if you want a custom handler on "test", and you don't want its messages also going to the root handler, the answer is simple: turn off its propagate flag:
logger.propagate = False

A: The handler is added each time you call from outside. Try Removeing the Handler after you finish your job:
self.logger.removeHandler(ch)

A: In my case I'd to set logger.propagate = False to prevent double printing.
In below code if you remove logger.propagate = False then you will see double printing.
import logging
from typing import Optional

_logger: Optional[logging.Logger] = None

def get_logger() -> logging.Logger:
    global _logger
    if _logger is None:
        raise RuntimeError('get_logger call made before logger was setup!')
    return _logger

def set_logger(name:str, level=logging.DEBUG) -> None:
    global _logger
    if _logger is not None:
        raise RuntimeError('_logger is already setup!')
    _logger = logging.getLogger(name)
    _logger.handlers.clear()
    _logger.setLevel(level)
    ch = logging.StreamHandler()
    ch.setLevel(level)
    # warnings.filterwarnings("ignore", "(Possibly )?corrupt EXIF data", UserWarning)
    ch.setFormatter(_get_formatter())
    _logger.addHandler(ch)
    _logger.propagate = False # otherwise root logger prints things again

def _get_formatter() -> logging.Formatter:
    return logging.Formatter(
        '[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s')

A: This can also happen if you are trying to create a logging object from the parent file. For e.g.
This is the main application file test.py
import logging

# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# add formatter to ch
ch.setFormatter(formatter)

# add ch to logger
logger.addHandler(ch)

def my_code():
# 'application' code
    logger.debug('debug message')
    logger.info('info message')
    logger.warning('warn message')
    logger.error('error message')
    logger.critical('critical message')

And below is the parent file main.py
import test

test.my_code()

The output of this will print only once
2021-09-26 11:10:20,514 - simple_example - DEBUG - debug message
2021-09-26 11:10:20,514 - simple_example - INFO - info message
2021-09-26 11:10:20,514 - simple_example - WARNING - warn message
2021-09-26 11:10:20,514 - simple_example - ERROR - error message
2021-09-26 11:10:20,514 - simple_example - CRITICAL - critical message

But if we had a parent logging object, then it will be printed twice. For e.g. if this is the parent file
import test
import logging
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

test.my_code()

The the output will be
2021-09-26 11:16:28,679 - simple_example - DEBUG - debug message
2021-09-26 11:16:28,679 - simple_example - DEBUG - debug message
2021-09-26 11:16:28,679 - simple_example - INFO - info message
2021-09-26 11:16:28,679 - simple_example - INFO - info message
2021-09-26 11:16:28,679 - simple_example - WARNING - warn message
2021-09-26 11:16:28,679 - simple_example - WARNING - warn message
2021-09-26 11:16:28,679 - simple_example - ERROR - error message
2021-09-26 11:16:28,679 - simple_example - ERROR - error message
2021-09-26 11:16:28,679 - simple_example - CRITICAL - critical message
2021-09-26 11:16:28,679 - simple_example - CRITICAL - critical message

A: A call to logging.debug() calls logging.basicConfig() if there are no root handlers installed. That was happening for me in a test framework where I couldn't control the order that test cases fired. My initialization code was installing the second one. The default uses logging.BASIC_FORMAT that I didn't want.

A: It seems that if you output something to the logger (accidentally) then configure it, it is too late.  For example, in my code I had
logging.warning("look out)"

...
ch = logging.StreamHandler(sys.stdout)
root = logging.getLogger()
root.addHandler(ch)

root.info("hello")

I would get something like (ignoring the format options)
look out
hello
hello

and everything was written to stdout twice.  I believe this is because the first call to logging.warning creates a new handler automatically, and then I explicitly added another handler. The problem went away when I removed the accidental first logging.warning call.

A: I was struggling with the same issue in the context of multiple processes. (For the code see the docs which I was following almost verbatim.) Namely, all log messages originating from any of the child processes got duplicated.
My mistake was to call worker_configurer(),
def worker_configurer(logging_queue):
    queue_handler = logging.handlers.QueueHandler(logging_queue)
    root = logging.getLogger()
    root.addHandler(queue_handler)
    root.setLevel(level)

both in the child processes and also in the main process (since I wanted the main process to log stuff, too). The reason this led to trouble (on my Linux machine) is that on Linux the child processes got started through forking and therefore inherited the existing log handlers from the main process. That is, on Linux the QueueHandler got registered twice.
Now, preventing the QueueHandler from getting registered twice in the worker_configurer() function is not as trivial as it seems:

*

*Logger objects like the root logger root have a handlers property but it is undocumented.

*In my experience, testing whether any([handler is queue_handler for handler in root.handlers]) (identity) or any([handler == queue_handler for handler in root.handlers]) (equality) fails after forking, even if root.handlers seemingly contains the same QueueHandler. (Obviously, the previous two expressions can be abbreviated by queue_handler in root.handlers, since the in operator checks for both identity and equality in the case of lists.)

*The root logger gets modified by packages like pytest, so root.handlers and root.hasHandlers() are not very reliable to begin with. (They are global state, after all.)
The clean solution, therefore, is to replace forking with spawning to prevent these kinds of multiprocessing bugs right from the start (provided you can live with the additional memory footprint, of course). Or to use an alternative to the logging package that doesn't rely on global state and instead requires you to do proper dependency injection but I'm digressing… :)
With that being said, I ended up going for a rather trivial check:
def worker_configurer(logging_queue):
    queue_handler = logging.handlers.QueueHandler(logging_queue)
    root = logging.getLogger()

    for handler in root.handlers:
        if isinstance(handler, logging.handlers.QueueHandler):
            return

    root.addHandler(queue_handler)
    root.setLevel(level)

Obviously, this will have nasty side effects the second I decide to register a second queue handler somewhere else.

A: From the docs:

"Loggers have the following attributes and methods. Note that Loggers should NEVER be instantiated directly, but always through the module-level function logging.getLogger(name).
Multiple calls to getLogger() with the same name will always return a reference to the same Logger object".

Make sure you don't initialise your loggers with the same name
I advise you to initialise the logger with __name__ as name param i.e:
import logging
logger = logging.getLogger(__name__)

NOTE:
even if you init a loggers from other modules with same name, you will still get the same logger, therefore calling i.e logger.info('somthing') will log as many times as you initiated the logger class.

A: You are calling configure_logging twice (maybe in the __init__ method of Boy) : getLogger will return the same object, but addHandler does not check if a similar handler has already been added to the logger.
Try tracing calls to that method and eliminating one of these. Or set up a flag logging_initialized initialized to False in the __init__ method of Boy and change configure_logging to do nothing if logging_initialized is True, and to set it to True after you've initialized the logger.
If your program creates several Boy instances, you'll have to change the way you do things with a global configure_logging function adding the handlers, and the Boy.configure_logging method only initializing the self.logger attribute.
Another way of solving this is by checking the handlers attribute of your logger:
logger = logging.getLogger('my_logger')
if not logger.handlers:
    # create the handlers and call logger.addHandler(logging_handler)

A: I'm a python newbie, but this seemed to work for me (Python 2.7)
while logger.handlers:
     logger.handlers.pop()

A: Adding to others' useful responses...
In case you are NOT accidentally configuring more than one handler on your logger:
When your logger has ancestors(root logger is always one) and they have their own handlers, they will also output when your logger outputs (by default), which will create duplicates. You have two options:

*

*Don't propagate your log event to your ancestors by setting:

my_logger.propagate = False

*

*If you only have one ancestor(root logger), you could directly configure their handler instead. For example:

# directly change the formatting of root's handler
root_logger = logging.getLogger()
roots_handler = root_logger.handlers[0]
roots_handler.setFormatter(logging.Formatter(': %(message)s')) # change format

my_logger = logging.getLogger('my_logger') # my_logger will use new formatting

A: I was getting a strange situation where console logs were doubled but my file logs were not.  After a ton of digging I figured it out.
Please be aware that third party packages can register loggers.  This is something to watch out for (and in some cases can't be prevented).  In many cases third party code checks to see if there are any existing root logger handlers; and if there isn't--they register a new console handler.
My solution to this was to register my console logger at the root level:
rootLogger = logging.getLogger()  # note no text passed in--that's how we grab the root logger
if not rootLogger.handlers:
        ch = logging.StreamHandler()
        ch.setLevel(logging.INFO)
        ch.setFormatter(logging.Formatter('%(process)s|%(levelname)s] %(message)s'))
        rootLogger.addHandler(ch)

A: If you are using any config for logging, For instance log.conf
In .conf file you can do it by adding this line in the [logger_myLogger] section: propagate=0
[logger_myLogger]
level=DEBUG
handlers=validate,consoleHandler
qualname=VALIDATOR
propagate=0

A: I had the same issue. In my case, it was not due to handlers or duplicate initial configuration but a stupid typo. In main.py I was using a logger object but in my_tool.py I was directly calling to the logging module by mistake, hence after invoking functions from my_tool module everything was messed up and the messages appeared duplicated.
This was the code:
main.py
import logging
import my_tool

logger_name = "cli"
logger = logging.getLogger(logger_name)

logger.info("potato")
logger.debug("potato)
my_tool.function()
logger.info("tomato")

my_tool.py
import logging
logger_name = "cli"
logger = logging.getLogger(logger_name)
# some code
logging.info("carrot")

and the result
terminal
>> potato
>> potato
>> carrot
>> tomato
>> tomato

A: If you use the standard construction logger = logging.getLogger('mymodule') and then accidentally mistype loggger as logging i.e.
logger = logging.getLogger('mymodule')

# configure your handlers

logger.info("my info message")  # won't make duplicate
logging.info("my info message")  # will make duplicate logs

then this will cause duplicate messages to come up because the call to logging creates a new logger.


text:
Q: Custom LinkedList: Picking alternate integer elements I have a list of Integer [21, 9, 13, 47, 5, 10, 19, 36, 20, 11, 13] and I'm trying to write a recursive function that will return every other integer from the original list as a list (i.e. [21, 13, 5, 19, 20, 13]).
I'm using a custom implementation of a LispList. The object is called LispList and it is immutable and (obviously) unindexed. It provides the following methods:
E head() - returns the first item of the list it is called on.
LispList <E> tail() - returns a new list consisting of all but the first item of the list it is called on.
LispList <E> cons(E item) - takes an argument and returns a new list whose head is the argument and whose tail is the list it is called on.
boolean isEmpty() - returns true if the list it is called on is the empty list, returns false otherwise.
static <T> LispList<T> empty() - returns an empty list.
After several hours of attempt, I've come up with a way where I'm using a counter initialised at 2 and using it to track even numbered elements, which should be picked out and put in a new LispList and returned.
However, when I run the code it throws a NullPointerException and I can't see why. Maybe I've just been staring at the screen for too long!
This is the method getting called from main:
public static <T> LispList<T> pickEveryOther(LispList<T> ls) {
        int counter = 2;
        LispList<T> ls1 = pickEveryOtherHelper(ls.tail(), counter);
        return ls1;
}

and the helper method:
public static <T> LispList<T> pickEveryOtherHelper(LispList<T> ls, int counter) {
        LispList<T> wantLs = LispList.empty();
        if(ls.isEmpty()) {
            return LispList.empty();
        }
        else {
            if(counter % DIVIDER == 0) {
                // item we want
                wantLs = wantLs.cons(ls.head());
                counter++;
            }
            else {
                // don't want item, look in tail
                pickEveryOtherHelper(ls.tail(), counter);
            }
            return wantLs;
        }
    }

Greatly appreciate your efforts.

A: This should do the trick, just take the head of, then try to take the tail two times and recurse on that. Just account for the fact that it can become an empty list after every tail. And then prepend the head to the result of the recursion.
public static <T> LispList<T> everyOther(LispList<T> lispList) {
    if (lispList.isEmpty()) {
        return lispList.empty();
    }
    T head = lispList.head();
    LispList<T> tail = lispList.tail();
    if (!tail.isEmpty()) {
        tail = tail.tail();
    }
    tail = everyOther(tail);
    return tail.cons(head);
}

A: The solution is to pop 2 values off the list on each recursion, and build a new list using one of the 2 values.
You didn't really specify whether "every other" means 1st, 3rd, 5th, ... or 2nd, 4th, 6th, ..., so here is both solutions.
public static <T> LispList<T> pickOdd(LispList<T> ls) {
    if (ls.isEmpty())
        return ls; // return empty
    LispList<T> tail1 = ls.tail();
    if (tail1.isEmpty())
        return ls; // return of(ls.head())
    LispList<T> tail2 = tail1.tail();
    if (tail2.isEmpty())
        return tail2.cons(ls.head()); // return of(ls.head())
    return pickOdd(tail2).cons(ls.head());
}

public static <T> LispList<T> pickEven(LispList<T> ls) {
    if (ls.isEmpty())
        return ls; // return empty
    LispList<T> tail1 = ls.tail();
    if (tail1.isEmpty())
        return tail1; // return empty
    LispList<T> tail2 = tail1.tail();
    if (tail2.isEmpty())
        return tail1; // return of(ls.tail().head())
    return pickEven(tail2).cons(tail1.head());
}

To test it, I did implement LispList, with two helper methods (of(...) and toString()):
final class LispList<E> {
    private final E           head;
    private final LispList<E> tail;
    private LispList(E head, LispList<E> tail) {
        this.head = head;
        this.tail = tail;
    }

    /** returns the first item of the list it is called on */
    public E head() {
        if (isEmpty()) throw new IllegalStateException();
        return this.head;
    }
    /** returns a new list consisting of all but the first item of the list it is called on */
    public LispList<E> tail() {
        if (isEmpty()) throw new IllegalStateException();
        return this.tail;
    }
    /** takes an argument and returns a new list whose head is the argument and whose tail is the list it is called on */
    public LispList<E> cons(E item) {
        return new LispList<>(item, this);
    }
    /** returns true if the list it is called on is the empty list, returns false otherwise */
    public boolean isEmpty() {
        return this.tail == null;
    }
    /** returns an empty list */
    public static <T> LispList<T> empty() {
        return new LispList<>(null, null);
    }

    @SafeVarargs
    public static <T> LispList<T> of(T ... values) {
        LispList<T> ls = empty();
        for (int i = values.length - 1; i >= 0; i--)
            ls = ls.cons(values[i]);
        return ls;
    }
    @Override
    public String toString() {
        StringJoiner joiner = new StringJoiner(", ", "[", "]");
        for (LispList<E> ls = this; ! ls.isEmpty(); ls = ls.tail())
            joiner.add(String.valueOf(ls.head()));
        return joiner.toString();
    }
}

TEST
LispList<Integer> ls = LispList.of(21, 9, 13, 47, 5, 10, 19, 36, 20, 11, 13);
System.out.println("List: " + ls);
System.out.println("Odd : " + pickOdd(ls));
System.out.println("Even: " + pickEven(ls));

OUTPUT
List: [21, 9, 13, 47, 5, 10, 19, 36, 20, 11, 13]
Odd : [21, 13, 5, 19, 20, 13]
Even: [9, 47, 10, 36, 11]


text:
Q: ¿Qué significa  en listas de Python? #Python #List Alguien podría recomendarme algun tipo de documentacion en inglés o español para este problema
def my_Function(myparameter) :
    myparameter.append('hello')

various_values = [1, 2, 3]
my_Function(various_values)
print(my_Function)

# RESULT =

<function my_Function at 0x0000023694587F70>

A: El resultado te está indicando que my_Function es una función (y que está en la dirección de memoria 0x0000023694587F70).
Para llamar a la función no te olvides de incluir () después del nombre de la función.
Por tanto, para que funcione como tú quieres, tienes que cambiar print(my_Function) por print(my_Function()). De esta última manera, imprimes lo que devuelva la llamada a la función: my_Function()
De todas formas, no va a imprimir nada a menos que modifiques la función para que devuelva algún valor, por ejemplo:
def add(myparameter) :
    myparameter.append('hello')

def my_Function():
    return various_values

various_values = [1, 2, 3]
add(various_values)
print(my_Function())

El resultado es:
[1, 2, 3, 'hello']


text:
Q: Solve the recurrence relation $a_n=4a_{n-1}-3a_{n-2}+2^n$ with $a_1=1, a_2=11$ Solve the recurrence relation:
 $$a_n=4a_{n-1}-3a_{n-2}+2^n$$
With initial conditions:
$$a_1=1, a_2=11$$
I know that this is a non-homogeneous recurrence relation meaning that the first step is to solve the homogeneous part:
$$r^n=4r^{n-1}-3^r{n-2}$$
$$r^2=4r-3$$
$$r^2-4r+3=0$$
$$(r-1)(r-3)=0$$
$$r=1,r=3$$
This gives us:
$$a_n=A(1)^n+B(3)^n$$
or (if the constant B absorbs A)
$$a_n=B(3)^n$$
The non-homogeneous part is where I seem to get stuck. I attempted:
$$a_n=B(3)^n+C(2)^n$$
subbing it into the original recurrence relation:
$$B(3)^n+C(2)^n= 4[B(3)^{n-1}+C(2)^{n-1}]-3[B(3)^{n-2}+C(2)^{n-2}]+2^n$$
I am a lost on where to proceed from here. Any help would be appreciated!

A: Let
$$
b_n=a_n+2^{n+2} \quad \forall n\ge 1.
$$
Then
$$
b_1=a_1+2^3=9,\quad b_2=a_2+2^4=27,
$$
and for every $n\ge 3$ we have:
\begin{eqnarray}
b_n&=&4(b_{n-1}-2^{n+1})-3(b_{n-2}-2^n)+2^{n+2}+2^n\\
&=&4b_{n-1}-3b_{n-2}+(-8+3+4+1)2^n\\
&=&4b_{n-1}-3b_{n-2}.
\end{eqnarray}
The characteristic equation associated to the recurrence relation
$$
b_n-4b_{n-1}+3b_{n-2}=0
$$
is
$$
r^2-4r+3=0,
$$
and its solutions are
$$
r_1=1, \quad r_2=3.
$$
Therefore
$$
b_n=c_1+c_2\cdot3^n,
$$
where $c_1$ and $c_2$ satisfy:
$$
c_1+3c_2=9,\quad c_1+9c_2=27,
$$
i.e.
$$
c_1=0,\quad c_2=3.
$$
Hence
$$
a_n=b_n-2^{n+2}=3^{n+1}-2^{n+2}
$$

A: Let us look for a solution of shape $c2^n$ of the non-homogeneous equation. Substituting we get
$$c2^n=4c2^{n-1}-3c2^{n-2}+2^n.$$
Dividing by $2^{n-2}$ we get $4c=8c-3c+4$, and now we know $c$.
Finally, we can write down the general solution of the non-homogeneous equation, and then meet the initial conditions.

A: For the non-homogeneous part of
$a_n=4a_{n-1}-3a_{n-2}+2^n
$,
I'll try
$a_n = c 2^n$.
Then
$c2^n=4c2^{n-1}-3c2^{n-2}+2^n
$
or,
dividing by $2^{n-2}$,
$4c =8c-3c+4$
or
$c=-4$.
As a check,
if $a^n = -4\,2^n
=-2^{n+2}
$,
$\begin{array}\\
4a_{n-1}-3a_{n-2}+2^n
&=-4\,2^{n+1}+3\, 2^n+2^n\\
&=2^n(-8+3+1)\\
&=-4\,2^n\\
&=a_n\\
\end{array}
$
As to how I chose this form to try,
experience.


text:
Q: XSLT - for each (or similar) loop on a combination of the values of two nodes I'm trying to perform an XSL transformation on the XML below:
<root>
    <row>
        <field1>2014-04-01</field1>
        <field2>AAA123</field2>
        <field3>text1</field3>
        <field4>text1</field4>
        <field5>text1</field5>
    </row>
    <row>
        <field1>2014-04-01</field1>
        <field2>AAA123</field2>
        <field3>text2</field3>
        <field4>text2</field4>
        <field5>text2</field5>
    </row>
    <row>
        <field1>2014-04-01</field1>
        <field2>BBB456</field2>
        <field3>text3</field3>
        <field4>text3</field4>
        <field5>text3</field5>
    </row>
</root>

What I'm trying to do is group <row> elements and their attributes based on a common <field1> and <field2> combination. The output I'm trying to achieve is something like the below:
<output>
    <common>
        <field1>2014-04-01</field1>
        <field2>AAA123</field2>
        <attributes>
            <field3>text1</field3>
            <field4>text1</field4>
            <field5>text1</field5>
        </attributes>
        <attributes>
            <field3>text2</field3>
            <field4>text2</field4>
            <field5>text2</field5>
        </attributes>
    </common>
    <common>
        <field1>2014-04-01</field1>
        <field2>BBB456</field2>
        <attributes>
            <field3>text3</field3>
            <field4>text3</field4>
            <field5>text3</field5>
        </attributes>
    </common>
</output>

I would assume this is done by using some kind of <xsl:for-each> loop, but I'm struggling to find any documentation (or answer on this site) that explains how to build an <xsl:for-each> loop that loops through a combination of nodes/values.
I'm relatively new to XSL and am a little stuck with where to approach this one. If anyone could point me to some documentation or shed any light on how to approach this, that would be greatly appreciated. For info, I'm working with xslt-2.0. Thanks in advance.

A: You can use xsl:for-each-group and group by field1 and field2.
Example...
XML Input
<root>
    <row>
        <field1>2014-04-01</field1>
        <field2>AAA123</field2>
        <field3>text1</field3>
        <field4>text1</field4>
        <field5>text1</field5>
    </row>
    <row>
        <field1>2014-04-01</field1>
        <field2>AAA123</field2>
        <field3>text2</field3>
        <field4>text2</field4>
        <field5>text2</field5>
    </row>
    <row>
        <field1>2014-04-01</field1>
        <field2>BBB456</field2>
        <field3>text3</field3>
        <field4>text3</field4>
        <field5>text3</field5>
    </row>
</root>

XSLT 2.0
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="/*">
        <output>
            <xsl:for-each-group select="row" group-by="concat(field1,'|',field2)">
                <common>
                    <xsl:apply-templates select="field1,field2"/>
                    <xsl:apply-templates select="current-group()"/>
                </common>
            </xsl:for-each-group>
        </output>
    </xsl:template>

    <xsl:template match="row">
        <attributes>
            <xsl:apply-templates select="*[not(self::field1) and not(self::field2)]"/>
        </attributes>
    </xsl:template>

</xsl:stylesheet>

XML Output
<output>
   <common>
      <field1>2014-04-01</field1>
      <field2>AAA123</field2>
      <attributes>
         <field3>text1</field3>
         <field4>text1</field4>
         <field5>text1</field5>
      </attributes>
      <attributes>
         <field3>text2</field3>
         <field4>text2</field4>
         <field5>text2</field5>
      </attributes>
   </common>
   <common>
      <field1>2014-04-01</field1>
      <field2>BBB456</field2>
      <attributes>
         <field3>text3</field3>
         <field4>text3</field4>
         <field5>text3</field5>
      </attributes>
   </common>
</output>

A: Use
<xsl:template match="root">
  <output>
    <xsl:for-each-group select="row" group-by="concat(field1, '|', field2)">
      <common>
       <xsl:copy-of select="field1, field2"/>
       <xsl:apply-templates select="current-group()"/>
     </common>
    </xsl:for-each-group>
  </output>
</xsl:template>

<xsl:template match="row">
  <attributes>
    <xsl:copy-of select="field3, field4, field5"/>
  </attributes>
</xsl:template>


text:
Q: go pg #42P01 invalid reference to FROM-clause i am trying to do a left join on query but i have an invalid reference to FROM-Clause
here are the structure of the code
this is the product table
CREATE TABLE products
(
    id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    title VARCHAR(255),
    productdesc TEXT,
    costprice DOUBLE PRECISION,
    recommendprice DOUBLE PRECISION,
    views BIGINT DEFAULT 0,
    enabled BOOLEAN DEFAULT FALSE,

    category_id BIGINT REFERENCES categories (id) ON DELETE CASCADE NOT NULL,

)

this is the category table
CREATE TABLE categories
(
    id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    pid BIGINT NOT NULL,
    title VARCHAR(255),
    image VARCHAR(255),

);

this is the type struct
type Product struct {
    TableName struct{} `sql:"products"`
    ID          int64  `json:"id"`
    TITLE string `json:"title"`
    PRODUCTDESC string `json:"product_desc"`
    COSTPRICE float64 `json:"costprice"`
    RECOMMENDPRICE float64 `json:"recommendprice"`
    VIEWS int64 `json:"views"`
    ENABLED bool `json:"enabled"`
    CATEGORYNAME string `json:"categoryname"`
}
type Category struct {
     tableName struct{} `pg:"categories"`
    ID      int64  `json:"id"`
    Title   string `json:"title"`
    Image   string `json:"image"`
}

this is the actual query to database
func (t *ProductRepo) GetAllProducts() ([]*domain.Product, error) {
    var products []*domain.Product
    query := t.DB.Model(&products).
        ColumnExpr("products.*").
        ColumnExpr("c.id AS category_id, c.title AS categoryname").
        Join("LEFT JOIN categories AS c ON c.id = products.category_id")

    err := query.Select()
    if err != nil {
        return nil, err
    }

    return products, nil
}

this is the actual error from postman
{
    "error": "ERROR #42P01 invalid reference to FROM-clause entry for table \"products\""
}

any help would be great,
thanks advance
Jason


text:
Q: Android Content Provider Test the REAL content Provider hope you can help me ...
tl:dr
How can i write JUnit Tests which will NOT use the classes IsolatedContext and MockContentResolver ? I want to affect the REAL content Provider and not the Mock Database.
General
I have to write JUnit Tests for a special ContentProvider at work.
This Content Provider is connected to some different Hardware and sets there some values. I must check the Hardware Values AND the Values of the Content Provider Database.
Construct
-> ContentProvider -> Hardware Interface -> Hardware -> HardwareInterface-> ContentProvider
Code
public class DataLayerTests extends ProviderTestCase2<DataLayer> {

private static final String TAG = DataLayerTests.class.getSimpleName();

MockContentResolver mMockResolver;

public DataLayerTests() {
    super(DataLayer.class, Constants.DATA_LAYER_AUTHORITY);
}

@Override
protected void setUp() throws Exception {
    super.setUp();
    Log.d(TAG, "setUp: ");
    mMockResolver = getMockContentResolver();
}

@Override
protected void tearDown() throws Exception {
    super.tearDown();
    Log.d(TAG, "tearDown:");
}

public void testActiveUserInsert__inserts_a_valid_record() {
    Uri uri = mMockResolver.insert(ActiveUserContract.CONTENT_URI, getFullActiveUserContentValues());
    assertEquals(1L, ContentUris.parseId(uri));
}}

 The real Database should be affected as well as the Real ContentRescolver should be used.
How could i arcive this ?

A: You can use Robolectric to test the real content provider, affecting a real sqlite database.
Robolectric is an implementation of the Android framework that can be run in any JVM, and thus can be used for tests.
Please note that the sqlite database will live in a temp folder on your computer and not on a phone or emulator.
If you want the tests to happen inside a real phone, you should look into Instrumented tests


text:
Q: Can't run Xcode 8 project; code sign error I recently started my 'developer's path', and the first thing that I have to fight with is a code sign error poping in Xcode. That's the error that appears when I try to run my project:

>
  CodeSign Build/Products/Debug-iphonesimulator/FunFacts.app
      cd "/Users/Rafal/Desktop/Projekty XCode/FunFacts"
      export CODESIGN_ALLOCATE=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate
      export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"

Signing Identity:     "-"

/usr/bin/codesign --force --sign - --timestamp=none /Users/Rafal/Desktop/Projekty\ XCode/FunFacts/Build/Products/Debug-iphonesimulator/FunFacts.app

/Users/Rafal/Desktop/Projekty XCode/FunFacts/Build/Products/Debug-iphonesimulator/FunFacts.app: resource fork, Finder information, or similar detritus not allowed
  Command /usr/bin/codesign failed with exit code 1

I tried to do some research, but nothing worked. By that I mean messing around with the terminal. Do you have any idea what's going on?


text:
Q: Issue with SMS permissions this is my problem.
I need to write an app that sends an SMS at a specific time. At that moment the user can be away from the phone.
All the examples I've read and tried about SMS permissions have the effect to seek authorization to the user through pop-up (which says that the operation may charge a cost, etc.). As said before, the user can be away from the phone, so without user authorization the SMS can't be sent at the desired time.
Is there a way to get the authorization before and avoid to re-ask at the sending moment?
The permission declared in the manifest:
<uses-permission android:name="android.permission.SEND_SMS" />

The SMS send is
SmsManager smsMgr = SmsManager.getDefault();
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent("SMS_SENT"), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent("SMS_DELIVERED"), 0);
smsMgr.sendTextMessage(Number, null, "txt", sentPI, deliveredPI);

Thanks to all

A: You need to get permission at run time for android 6+. do this
    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       int permissionCheck = ContextCompat.checkSelfPermission(RegisterActivity.this, Manifest.permission.SEND_SM);
                    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(RegisterActivity.this, new String[]{Manifest.permission.SEND_SM}, 1);
                    } else {
                        sendSMS();
                    }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        switch (requestCode) {
        case 1: {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                sendSMS();
            } else {
                finish();
            }
        }
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}


text:
Q: Why is the difference between Serializer methods and View methods? In Django DRF, I can add the following method to a serializer:
    def create(self, validated_data):
        user = User(
            email=validated_data['email'],
            username=validated_data['username']
        )
        user.set_password(validated_data['password'])
        user.save()
        return user

Previous to discovering this, I thought you typically did this within a view, by overriding a View/ViewSet methods.
I had thought that all the Serializer did was to transform the data and send it out or receive it from external calls.
Can someone explain to me the difference between doing this on the view vs doing it on a serializer?
And more broadly, what is the benefit of calling methods on the serializer instead of somewhere else?

A: A serialiser's job is to take one blob of data and convert it into another blob of data. Most typically it converts from a model to some form of dict and vice versa. You typically have at least one serialiser per model, but you may have any number of serialisers for different use cases. For example, you may get data in different forms, e.g. from a registration form and from an API call, and you want to convert both into a valid User instance. So you may define two different serialisers for those two different scenarios, which both end up with the same User instance. And you may need to customise some aspects of those serialisers to fit the occasion.
Views on the other hand take an HTTP request, do something and then decide what response to return. That doing something may involve using serialisers, but it doesn't have to. The biggest job of a view is to decide what to do when something succeeds or fails, like rendering a different response or redirecting to a different URL.
You need to decide how reusable some piece of logic is. Think of serialisers as transforming one type of data into another; call it converting type A into type B and vice versa. "Type" here being what your input/output data looks like exactly. Then consider where in your application you'll encounter a data blob of type A and whether you'll need to convert it into type B more than once. If so, you'll probably want to make a specific serialiser for it, instead of repeating the same logic inside two or more views.


text:
Q: When I update an sql table row with a content "=" there runs an error I want to run this:
UPDATE users SET about="$about" ;

but when my $about contains =, the script makes a mistake and do something like this:
$about="";

The script adds this in the database:
<img src

and nothing more.

A: try it by using double single quotes.
$about = '';
$query = "UPDATE users SET about='$about'";

As a sidenote, the query is vulnerable with SQL Injection if the value(s)  of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.

*

*How to prevent SQL injection in PHP?

A: This is called 'sql injection'. You have to take care of that anyway, so google it.
You have to escape all input you want to use inside statements, anything can happen otherwise. Best is not to use statements constructed by simply including variable content, but use a better engine. Take a look at PDO and the way it works. You "prepare" a statement and hand over parameters as an array. PDO takes care to cleanly escape as required. Much safer that way.

A: The issue is with putting quotes around string. I'm not very familiar with how php replaces variables in strings but you can try following for MS SQL server:
Set about ="'$about'"


text:
Q: Remove Single Quote from Middle of the String but not from start and end I have a string like
 String abc = "'Joe's Dinner'";

Now i need to remove the quote from the middle so that the result can be like
abc = "'Joes Dinner'"

Edited:
I realized the problem occurs in somewhere else. actually I splitting a 5 GB XML file. I am using StAX to do that. And here is my code.
public String split(String fileName){
  XMLInputFactory xif = XMLInputFactory.newInstance();
  XMLEventReader xer = xif.createXMLEventReader(new FileInputStream(new File(fileName)));

  String fileContent = "";

  while(xer.hasNext()) {
    XMLEvent e = xer.nextEvent();
    fileContent = fileContent + e.toString();
  }
  return fileContent;
}

Now, in my source XML the line comes as
<location state="Côte d'Azur" xsi:nil="true" city="Marseille" country="FRANCE"></location>

but in output the double quote in attribute values are changed to single quote resulting an error while parsing. Is there any way to keep that double quote as it is.

A: If i understand your question, then you need something like that, i make three olutions to solve your problem,
public class Cote {

    public static void main(String args[]) {
        //First Solution
        String abc = "'Joe's Dinner'";

        //Second Solution
        String abc3 = "'" + abc.replace("'", "") + "'";
        System.out.println(abc3);

        String abc2 = "'";
        for (int i = 1; i < abc.length() - 1; i++) {
            String c = abc.charAt(i) + "";
            if (!c.equals("'")) {
                abc2 += c;
            }
        }
        abc2 += "'";
        System.out.println(abc2);

        //Third Solution
        abc = "<location state='Côte d'Azur' xsi:nil='true' city='Marseille' country='FRANCE'></location>";
        abc2 = "";
        int count = abc.length() - abc.replace("'", "").length();

        int count2 = 0;
        for (int i = 0; i < abc.length(); i++) {
            String c = abc.charAt(i) + "";
            if (c.equals("'")) {
                count2++;
                if (count2 == 1 || count2 == count) {
                    abc2 += c;
                }
            } else {
                abc2 += c;
            }

        }
        System.out.println(abc2);
    }
}

Good luck

A: You can use a nice feature of regexps called positive look-ahead/look-behind, which means you can matching things which will not be considered part of the actual match. In this case you want to ignore the starting and ending characters of the string, so the replacement would be:
input.replaceAll("(?<=.)'(?=.)", "");

Where the first parenthesized part reads "proceeded by any character" and the second part means "followed by any character".
If you would like to keep the quote without corrupting your xml you might want to escape it instead, in which case you could use
input.replaceAll("(?<=.)'(?=.)", "'");

Good lock!


text:
Q: how to configure hot swap agent with liferay server I want to configure hotswap agent and DCEVM with liferay server.
I have added DCEVM in jdk and also added "-XXaltjvm=dcevm -javaagent:D:\onkar\DCEVM\hotswap-agent.jar" in setenv.bat file.
Now after deploying war file either server doesn't start properly or war file is not getting deployed properly.
Please help if anyone knows how to configure it with liferay server.

A: With Hotswap Agent you can do java code changes and check those immediately without the need to restart the TOMCAT SERVER
Double Click on Server - Runtime Environment - JRE must be mapped to the same JRE of JDK in which DECVM is patched in step-1

Add "-XXaltjvm="dcevm" -javaagent:\HotswapAgent.jar" in VM Arguments

Run Tomcat on  SErver in Debug mode
With Liferay SERVER, HOT SWAP Agent starts, but I have a PERMGEN exception.
Other info


text:
Q: How to translate following comparator into Comparator.comparing? My question may be unclear so let me clear it out by example:
Arrays.sort(arr, new Comparator<String>(){
    public int compare(String a, String b){
        return (b + a).compareTo(a + b);
    }
});

I want to use the Comparator.comparing. I tried out the following:
Arrays.sort(arr, Comparator.comparing((a, b) -> (b + a).compareTo((String)a + b)));

I get an error - bad return type in lamdba expression. How to fix this ?

A: Comparator.comparing method expects a keyExtractor of type Function. You just need a lambda to implement the Comparator<String> interface here:
Arrays.sort(arr, (a, b) -> (b + a).compareTo(a + b));

A: It is impossible to turn that into a call to comparing because it's not a valid Comparator: it doesn't satisfy the Comparator contract, and you should never use it as a Comparator.
To prove it, that Comparator will compare every string as equal to "", but not every string will be equal to each other.  That violates the transitivity property.

A: As already answered, your anonymous class implementation can be shortened into a lambda expression:
Arrays.sort(arr, (a, b) -> (b + a).compareTo(a + b));

If you insist on using Comparator.comparing(), remember it has specific parameters that don't fit your sorting problem.

*

*The Comparator.comparing(keyExtractor) returns a specified Comparator for certain key based on the natural way of comparison (Comparator.naturalOrder). Your method doesn't say what is compared, but how it is.

*The Comparator.comparing(keyExtractor, keyComparator)  looks a bit better because you can specify how the specified keys are compared using keyComparator. You can use your logics of comparing and you conclude to:
Arrays.sort(arr, Comparator.comparing(
    Function.identity(),                  // keyExtractor, WHAT is compared
    (a, b) -> (b + a).compareTo(a + b))); // keyComparator, HOW is it compared

This is a solution using Comparator.comparing that uses a keyExtractor the Function.identity() returning the input back (the same like str -> str lambda expression) since you want still compare the Strings but in a different way specified with a custom Comparator, therefore the only correct way to sort the array as you need is the simplified version omitting the keyExtractor:
Arrays.sort(arr, (a, b) -> (b + a).compareTo(a + b));

... which is finally where we started at.


text:
Q: adding images and search option in android app i have trouble in adding a search option to list various countries or cities in my timezone app.
also i want to add an image that can be set as a clock widget that displays the time according to the timezone selected from the drop down list..i do not know where to start since i am pretty new to android app development..any ideas to help improve this app will be helpful..
here is the code that i am trying to learn.
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center|top"
android:orientation="vertical"
android:padding="5dp" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >

<TextView
android:id="@+id/txtGMTTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/current" />

<TextView
android:id="@+id/txtCurrentTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:context=".MainActivity" />
</LinearLayout>

<Spinner
android:id="@+id/availableID"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >

<TextView
android:id="@+id/timezone"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<TextView
android:id="@+id/txtTimeZoneTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

</LinearLayout>

followed by the java class code.
MainActivity.java
@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

spinnerAvailableID = (Spinner) findViewById(R.id.availableID);

textTimeZone = (TextView) findViewById(R.id.timezone);
txtCurrentTime = (TextView) findViewById(R.id.txtCurrentTime);
txtTimeZoneTime = (TextView) findViewById(R.id.txtTimeZoneTime);

String[] idArray = TimeZone.getAvailableIDs();

sdf = new SimpleDateFormat("EEEE, dd MMMM yyyy HH:mm:ss");

idAdapter = new ArrayAdapter<String>this,android.R.layout.simple_spinner_item,idArray);

idAdapter.setDropDownViewResource

(android.R.layout.simple_spinner_dropdown_item);
spinnerAvailableID.setAdapter(idAdapter);

getGMTTime();

spinnerAvailableID
.setOnItemSelectedListener(new

OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?>parent,View view, int position, longid) {
getGMTTime();
String selectedId = (String) (parent.getItemAtPosition(position));
TimeZone timezone =TimeZone.getTimeZone(selectedId);
String TimeZoneName =timezone.getDisplayName();
int TimeZoneOffset =timezone.getRawOffset()/ (60 * 1000);

int hrs = TimeZoneOffset / 60;
int mins = TimeZoneOffset % 60;

miliSeconds = miliSeconds +timezone.getRawOffset();
resultdate = new Date(miliSeconds);
System.out.println(sdf.format(resultdate));
textTimeZone.setText(TimeZoneName + ": GMT " + hrs + "."+ mins);
txtTimeZoneTime.setText("" +sdf.format(resultdate));
miliSeconds = 0;
}

@Override
public void onNothingSelected(AdapterView<?>arg0) {

}
});

}
private void getGMTTime() {
current = Calendar.getInstance();
txtCurrentTime.setText("" + current.getTime());

miliSeconds = current.getTimeInMillis();

TimeZone tzCurrent = current.getTimeZone();
int offset = tzCurrent.getRawOffset();
if (tzCurrent.inDaylightTime(new Date())) {
offset = offset + tzCurrent.getDSTSavings();
}

miliSeconds = miliSeconds - offset;
resultdate = new Date(miliSeconds);
System.out.println(sdf.format(resultdate));
}
}

now where exactly do i add the search bar option and custom clock widget image in this code


text:
Q: Connect to client FTP with dynamic client IP address I want to connect to my client's FTP. He has to whitelist my IP everytime since mine is dynamic. How do I connect to his server?

A: I would recommend you to rent a virtual private server (VPS) with static IP and use it as a jump machine to access your client's FTP server from a constant address.
Now there are many particular terminologies each vendor might use, but if it's OK to use Amazon Web Services, then you might be looking for an EC2 nano instance configured with an Elastic IP.

A: He might use Port Knocking. This way, it doesn't matter what IP you have, you'll "knock" to a sequence of ports and the Knock daemon will detect the sequence and therefore add a temporary rule to allow you to connect.
In Linux-based environments you can use knockd for that matter, although I'm sure that for other OS environments there are equivalent daemons.

*

*More info (knockd)

A: *

*Setup a free domain name.

*Use OpenDNS to keep the domain name associated with your IP.

*Have your friend whitelist your domain name.


text:
Q: how to run specific file in NX cloud nestjs? folder structure:

SDK-NODE
 -> config
 -> libs
  -> sample-sdk
   -> project1
    -> src
     -> lib
      -> testcase.spec.ts

Solutions Tried:
nx run project1:test --testFile= testcase.spec.ts
ng test project1 --test-name-pattern=testcase.spec.ts
ERROR
NX   Cannot find project 'project1'


text:
Q: Get content from helper (Draggable) in event update from sortable How i can get the content declared in draggable "helper" in event "update" from sortable from object?
$(function() {
    $( "#sortable" ).sortable({
      revert: true,
      update: function(event, ui){
          ??????
      }
    });
    $( "#draggable" ).draggable({
      connectToSortable: "#sortable",
      helper: function(e){
        return $('
sample
');
    },
      revert: "invalid"
    });
    $( "ul, li" ).disableSelection();
  });

A: You could try this:
$(function () {
    $("#sortable").sortable({
        revert: true,
        update: function (event, ui) {
            var draggableHelper = $(this).data('helper');//setted in draggable start handler
        }
    });
    $("#draggable").draggable({
        connectToSortable: "#sortable",
        helper: function (e) {
            return $('
sample
');
        },
        revert: "invalid",
        start: function (event, ui) {
            $($(this).draggable('option','connectToSortable')).data('helper', ui.helper);
        }
    });
    $("ul, li").disableSelection();
});


text:
Q: Botão responsivo e centralizado Gostaria de uma ajuda para fazer um botão ficar sempre no centro da minha box de código, de maneira responsiva.
Estou construindo uma landing page em um construtor de sites chamado Zyro, nele eu tenho a opção de adicionar elementos em código, o problema é que eu não consigo de forma alguma fazer esse botão ficar centralizado verticalmente na box de código, fiz várias tentativas e o máximo que consegui foi fazer o botão ficar centralizado horizontalmente.
Segue meu código atual:

document.getElementById('randomButton').onclick = function() {
  window.open('https://google.com', '_blank')
}
div {
  margin: 0 auto;
  text-align: center;
}

button {
  position: relative;
  padding: 1em 1.8em;
  outline: none;
  border: 1px solid #303030;
  background: #000000;
  color: #00F498;
  text-transform: uppercase;
  letter-spacing: 2px;
  font-size: 15px;
  overflow: hidden;
  transition: 0.2s;
  border-radius: 20px;
  cursor: pointer;
  font-family: "Rubik";
  font-weight: 900;
}

button:hover {
  box-shadow: 0 0 10px #00F498, 0 0 25px #00BCAA, 0 0 50px #00F498;
  transition-delay: 0.6s;
}

button span {
  position: absolute;
}

button span:nth-child(1) {
  top: 0;
  left: -100%;
  width: 100%;
  height: 2px;
  background: linear-gradient(90deg, transparent, #00F498);
}

button:hover span:nth-child(1) {
  left: 100%;
  transition: 0.7s;
}

button span:nth-child(3) {
  bottom: 0;
  right: -100%;
  width: 100%;
  height: 2px;
  background: linear-gradient(90deg, transparent, #00F498);
}

button:hover span:nth-child(3) {
  right: 100%;
  transition: 0.7s;
  transition-delay: 0.35s;
}

button span:nth-child(2) {
  top: -100%;
  right: 0;
  width: 2px;
  height: 100%;
  background: linear-gradient(180deg, transparent, #00F498);
}

button:hover span:nth-child(2) {
  top: 100%;
  transition: 0.7s;
  transition-delay: 0.17s;
}

button span:nth-child(4) {
  bottom: -100%;
  left: 0;
  width: 2px;
  height: 100%;
  background: linear-gradient(360deg, transparent, #00F498);
}

button:hover span:nth-child(4) {
  bottom: 100%;
  transition: 0.7s;
  transition-delay: 0.52s;
}

button:active {
  background: #00F498;
  background: linear-gradient(to top right, #00F498, #00BCAA);
  color: #bfbfbf;
  box-shadow: 0 0 8px #00F498, 0 0 8px #00BCAA, 0 0 8px #00F498;
  transition: 0.1s;
}

button:active span:nth-child(1) span:nth-child(2) span:nth-child(2) span:nth-child(2) {
  transition: none;
  transition-delay: none;
}
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Rubik">

  <button id="randomButton">

     Comece Agora!
    </button>

Box de código - Zyro
Não sei bem como essa box de código do site funciona, acredito que ela faça uma função de 'div', mas posso estar falando besteira.
Sou novo no meio da programação, resolvo muitas coisas na tentativa e erro, mas gostaria de entender a solução para poder caminhar com as próprias pernas nas demais situações do dia-a-dia.
Se alguém puder me ajudar a resolver e conseguir explicar a resolução de uma forma que um novato entenda, ficarei muito grato!

A: Para você colocar o elemento centralizado de forma vertical no HTML com css, existe duas forma para centralizar um elemento no centro tanto vertical quanto horizontal.
Com flex box e position
1⁰ com position
div {
   display: block;
   width: 100%;
   height: 100vh;
   position: relative;
}

button {
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
   padding: 1em 1.8em;
   outline: none;
   border: 1px solid #303030;
   background: #000000;
   color: #00F498;
   text-transform: uppercase;
   letter-spacing: 2px;
   font-size: 15px;
   overflow: hidden;
   transition: 0.2s;
   border-radius: 20px;
   cursor: pointer;
   font-family: "Rubik";
   font-weight: 900;
}

2⁰ com Flex box
div {
   display: flex;
   justify-content: center;
   align-items: center;
   width: 100%;
   height: 100vh;
}

button {
   transform: transition;
   padding: 1em 1.8em;
   outline: none;
   border: 1px solid #303030;
   background: #000000;
   color: #00F498;
   text-transform: uppercase;
   letter-spacing: 2px;
   font-size: 15px;
   overflow: hidden;
   transition: 0.2s;
   border-radius: 20px;
   cursor: pointer;
   font-family: "Rubik";
   font-weight: 900;
}

Aqui testei e funcionou, espero que tenha ajudado.


text:
Q: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0' Using Spring 5.1.6,  changed the code accordingly Alternate of Spring HandlerMethodSelector.selectMethods
Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/springframework/web/method/HandlerMethodSelector


text:
Q: How to modify a recursive branch and bound tree node traversal to avoid stack overflow? I created the following Swift 3 program to solve knapsack problem using the depth-first branch and bound. Unfortunately, it's recursive. It works fine for up to 20 items. But for a higher number of items (30 or higher), it will cause the stack overflow. ( ~5400 level deep).
How to change it to a non-recursive version?
public enum BBState {
case created
case active
case death
}

public enum Direction {
case left
case right
}

public class BBTreeNode {
    public var artifact: Artifact
    public var nodeState: BBState
    public var level: Int
    public var path = [Direction]()
    public var weightSoFar: Int = 0
    public var optimumTotalValue: Int = 0
    public var estimatedOptTotalValue: Double = 0
    public weak  var parentNode: BBTreeNode?
    public var leftNode: BBTreeNode?
    public var rightNode: BBTreeNode?
    static var currentCompletedOptimumValues: Int = 0
    static var currentCompletedEstimatedOptimumValues: Double = 0
    static var currentOptimumPath = [Direction]()

// Initialization
public convenience init(artifact: Artifact) {
    self.init(artifact: artifact, level: 0, path: [], parent: nil, left: nil, right: nil)
}

public init(artifact: Artifact, level: Int, path: [Direction], parent: BBTreeNode?, left: BBTreeNode?, right: BBTreeNode?) {
    self.artifact = artifact
    self.nodeState = .created
    self.level = level
    self.path = path
    self.parentNode = parent
    self.leftNode = left
    self.rightNode = right
}

// BBTree
private func createRootAndInitiateBB(artifacts: [Artifact]) {
    // return the optimum value from Depth-First branch and bound
    let maxLevel = artifacts.count - 1
    print("Max Level: \(maxLevel)")
    // create dummy Root to start
    let root = BBTreeNode(artifact: Artifact(value: 0, weight: 0))
    root.estimatedOptTotalValue = Knapsack.calculateEstimatedOptimumValue(availableArtifacts: artifacts)
    root.nodeState = .active
    root.weightSoFar = Knapsack.capacity
    // loop here for each artifact# - selected(left) / not(right) but going recursive to left until
    // we have death node, then backtrack

    func depthFirstTraversal(bbNode: BBTreeNode?, level: Int) {
        guard let bbNode = bbNode  // not nil
            else { return }

        guard level <= maxLevel
            else { return }

        print("Currently on path: \(bbNode.path)")

        // switch to active is last state was created, else ignore
        bbNode.nodeState =  bbNode.nodeState == .created ?  .active : bbNode.nodeState

        // stop traverse down and traceback if calculated optimumValue < currentCompletedOptimumValue,
        // or current weightSoFar is 0 or less than 0
        // move up to parent
        if bbNode.estimatedOptTotalValue < BBTreeNode.currentCompletedEstimatedOptimumValues ||
            bbNode.weightSoFar < 0 {
            print("Case for estimatedOptTotalValue: \(bbNode.estimatedOptTotalValue) < currentCompletedEstimatedOptimumValues: \(BBTreeNode.currentCompletedEstimatedOptimumValues)")
            print("Or weight: \(bbNode.weightSoFar) < 0" )
            bbNode.nodeState = .death
            // remove references to children
            bbNode.leftNode = nil
            bbNode.rightNode = nil
            depthFirstTraversal(bbNode: bbNode.parentNode, level: bbNode.level - 1)
        } else if (bbNode.leftNode?.nodeState == .death &&
                bbNode.rightNode?.nodeState == .death) || level ==  maxLevel  {

            print("Case for no more path available. Need to backtrack. ")
            print("Current level: \(level)")
            // stop, record and traceback if at maxLevel or when both children are death
            if level == maxLevel && bbNode.estimatedOptTotalValue > BBTreeNode.currentCompletedEstimatedOptimumValues {
                BBTreeNode.currentCompletedEstimatedOptimumValues = bbNode.estimatedOptTotalValue
                BBTreeNode.currentCompletedOptimumValues = bbNode.optimumTotalValue
                BBTreeNode.currentOptimumPath = bbNode.path
                print("blah...")
                print("Candidate for optimum: \(bbNode.path)")
                print("Completed optimum path: \(BBTreeNode.currentCompletedOptimumValues)")
                print("Estimated optimum value: \(BBTreeNode.currentCompletedEstimatedOptimumValues)")
            }
            bbNode.nodeState = .death
            // remove references to children
            bbNode.leftNode = nil
            bbNode.rightNode = nil
            let _ = path.popLast()
            depthFirstTraversal(bbNode: bbNode.parentNode, level: bbNode.level - 1)
        } else if bbNode.leftNode == nil {
            // create left child
            print("create left child node")
            let childLeftNode = createBBNode(leftChild: true, parent: bbNode, path: bbNode.path + [.left])
            bbNode.leftNode = childLeftNode
            depthFirstTraversal(bbNode: childLeftNode, level: childLeftNode.level)
        } else if bbNode.rightNode == nil {
            // create right child
            print("create right child node")
            let childRightNode = createBBNode(leftChild: false, parent: bbNode, path: bbNode.path + [.right])
            bbNode.rightNode = childRightNode
            depthFirstTraversal(bbNode: childRightNode, level: childRightNode.level)
        }

    }

    func createBBNode(leftChild: Bool, parent: BBTreeNode, path: [Direction]) -> BBTreeNode {
        let level = parent.level + 1
        let artifact = artifacts[level]
        let newBBNode = BBTreeNode(artifact: artifact, level: level, path: path, parent: parent, left: nil, right: nil )
        if leftChild {
            newBBNode.optimumTotalValue =  parent.optimumTotalValue + artifact.value
            newBBNode.estimatedOptTotalValue = parent.estimatedOptTotalValue
            newBBNode.weightSoFar = parent.weightSoFar - artifact.weight
        } else {
            // right direction, we don't pick this item
            // Artifact is a struct,  artifacts is array of Artifact, so we don't need to write deep copy
            var artifactsWithItemsRemoved = artifacts

            print("Current artifacts before any removal: \(artifactsWithItemsRemoved)")
            print("for path \(newBBNode.path) we are going to remove artifacts...")
            // first remove the dummy artifact
            artifactsWithItemsRemoved.remove(at: 0)
            // now the real artifacts
            var indexOfItemForRemoval = [Int]()
            for (index,direction) in path.enumerated() {
                if direction == .right {
                    indexOfItemForRemoval.append(index)
                }
            }
            // actual removal, need to reverse the array index to avoid out of range index
            for idx in indexOfItemForRemoval.reversed() {
                artifactsWithItemsRemoved.remove(at: idx)
            }

            print("Artifacts with items removed: \(artifactsWithItemsRemoved)")

            newBBNode.optimumTotalValue = parent.optimumTotalValue
            newBBNode.estimatedOptTotalValue = Knapsack.calculateEstimatedOptimumValue(availableArtifacts: artifactsWithItemsRemoved)
            print("New estimatedOptValue for \(newBBNode.path) is \(newBBNode.estimatedOptTotalValue)")
            // no weight deduction if we don't pick
            newBBNode.weightSoFar = parent.weightSoFar
        }
        return newBBNode
    }

    depthFirstTraversal(bbNode: root, level: 0)
}

public func findOptimumValueAndPath(artifacts: [Artifact]) -> (Int,[Direction], Double) {
    createRootAndInitiateBB(artifacts: artifacts)
    return (BBTreeNode.currentCompletedOptimumValues, BBTreeNode.currentOptimumPath, BBTreeNode.currentCompletedEstimatedOptimumValues)
}

}

==== Update ===
I manage to limit the depth of recursion to certain limit like 4000, once the counter reach limit, I returned to caller with currentNode information. Then call the 'depthFirstTraversal' again with currentNode but with fresh new stack.
Here's how I do it:

*

*Move createRootAndInitiateBB and findOptimumValueAndPath to the caller.

*Update depthFirstTraversal to have function signature like this:
static func depthFirstTraversal(bbNode: BBTreeNode, level: Int, recursiveCount: Int, complete completeFlag: inout Bool, currentProcessedNode: inout BBTreeNode)

*Some other refactoring work to keep the counter count and some bug fixed. (e.g. parentNode should not be weak, else after return to caller, the parent of currentNode become nil and we lose capability to backtrack to higher node).

A: Here is an example that might help you or anybody else stumbles on your question:
https://github.com/evansjohnson/DynamicProgrammingWithSwift/blob/master/ProblemSet8Playground.playground/Contents.swift


text:
Q: creating a cache of byte arrays In my code, which often runs on servers I do not control the configuration of, I have collection of users and each user has a byte[] array.
Sometimes these byte[] arrays are unique to the user.  Often, though, there will be large numbers users with the exact same byte[] array.
I am trying to reduce the RAM consumption of my server.
I've tried turning my byte[] arrays into strings and interning them, but then I often run into PERM-GEN out-of-memory errors.  I also see a significant performance degradation with the encoding/decoding when I want to access the byte[] array for a user, and I see much increased worse-case memory usage - presuambly strings are much larger than arrays.
How can I have a Set<SoftReference<byte[]>> lookup when Java arrays are not hashable and SoftReferences do not wrap the hash of the object the point at either.  A Map<byte[],SoftReference<byte[]>> is obviously also defeating itself because the key is itself and prevents collection; and Set is internally implemented in terms of Mapanyway.
So how can I intern byte[] arrays?

A: If you effectively have many identical arrays, use an HashSet<ByteBuffer> as a cache. You can get the ByteBuffer array with method array() and the ByteBuffer class has hashCode and equals methods. Of course it is better if your arrays are immutable.
EDIT2 The comment from @Will is exact, to be able to get back the array, use a WeakHashMap<ByteBuffer,WeakReference<ByteBuffer>> and do something like that :
public byte[] internalize(byte[] bytes) {
 ByteBuffer wrapped = ByteBuffer.wrap(bytes);
 if(cache.containsKey(wrapped)) {
  wrapped = cache.get(wrapped).get();
 }
 else {
  cache.put(wrapped, new WeakReference<ByteBuffer>(wrapped);
 }
 return wrapped.array();
}

A:
I've tried turning my byte[] arrays into strings and interning them, but then I often run into PERM-GEN out-of-memory errors.

I agree that you need something like String.intern(), but the standard implementation is native, so not much joy.
You could have a Map<Integer,Collection<SoftReference<byte[]>>>, using the hash code of the byte arrays as the Map key. Your intern method could then look up the set of existing byte arrays with the same has code as the given byte arrays. With a good hash code that should give a small set of arrays to examine for a match.

Edit: To clarify:
Something like this:
 class ByteArrayCache
 {
      private final Map<Integer,Collection<SoftReference<byte[]>> map = new ...;

      public final byte[] intern(byte[] byteArray)
      {
           final int hash = Arrays.hashCode(byteArray);
           final Collection<SoftReference<byte[]>> arrays = map.get(hash);
           if (arrays != null) {
              // Search through arrays for a match, and return the match.
              // If no match found, add byteArray to the collection and return it
           } else {
              // create a new map entry, add byteArray to it, and return byte array
           }
      }
 }

A: I would implement a cache based on Guava weak values map. It guarantees that if theres no more strong references to byte array the entry will be automatically removed.
class Cache {
    private final ConcurrentMap<Key, byte[]> map = new MapMaker().weakValues().makeMap();

    private static class Key {
        byte[] a;
        int hash;

        Key(byte[] a) {
            this.a = a;
            hash = Arrays.hashCode(a);
        }

        @Override
        public int hashCode() {
            return hash;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof Key) {
                return Arrays.equals(a, ((Key) obj).a);
            }
            return false;
        }
    }

    public byte[] intern(byte[] a) {
        byte[] a1 = map.putIfAbsent(new Key(a), a);
        if (a1 != null) {
            return a1;
        }
        return a;
    }
}


text:
Q: Android MVVM retrofit2 model not updating Trying to call my API using retrofit and update the model. It initializes correctly and is able to pull the data but when I trigger it manually by pressing the update button the onChange QuestionResponse model is null. It seems almost like a race condition as when debugging it will hit the onChange before the onResponse is called. I've tried changing from setValue to postvalue etc.
Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mViewModel = ViewModelProviders.of(this).get(BasicViewModel.class);
    mViewModel.getQuestions().observe(this, new Observer<QuestionResponse>() {
        @Override
        public void onChanged(QuestionResponse response) {
            QuestionResponse temp = mViewModel.getQuestions().getValue();
            Toast.makeText(MainActivity.this, "Questions Updated", Toast.LENGTH_SHORT).show();
        }
    });

    updateButton = findViewById(R.id.updateButton);
    updateButton .setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            update();
        }
    });
}

private void update(){
    mViewModel.updateQuestions();
}

View Model
private Repository repository;
private Application application;
private MutableLiveData<QuestionResponse> questionMutableLiveData;

public BasicViewModel(Application application){
    super(application);
    this.application = application;
    repository = new Repository();
    questionMutableLiveData = repository.getQuotes();
}

public void updateQuestions(){
    questionMutableLiveData.setValue(repository.getQuotes().getValue());
}

public LiveData<QuestionResponse> getQuestions(){
    if(questionMutableLiveData == null){
        System.out.println("Something Is Wrong");
    }
    return questionMutableLiveData;
}

Retrofit Service
public class Repository {
    MutableLiveData<QuestionResponse> questionData;
    ApiService apiService;

    public QuoteMRepository(){
        apiService = RetrofitSingleton.getRetrofitInstance().create(ApiService.class);
    }

    public MutableLiveData<QuestionResponse> getQuotes(){
        Call<QuestionResponse> call = apiService.getQuestions();

        //Old version of doing it
        //MutableLiveData<QuestionResponse> questionData = new MutableLiveData<>();

        //New version, seems to be working but triggering twice
        if(questionData == null) {
            questionData = new MutableLiveData<>();
        }

        call.enqueue(new Callback<QuestionResponse>() {
            @Override
            public void onResponse(Call<QuestionResponse> call, Response<QuestionResponse> response) {
                if(response.isSuccessful()){
                    QuestionResponse reply = response.body();
                    questionData.setValue(reply);
                }
            }

            @Override
            public void onFailure(Call<QuestionResponse> call, Throwable t) {
                System.out.println("Failure");
            }
        });

        return questionData;
    }
}

A: You are returning an empty LiveData object and later updating it with the repository response, so your observer triggers twice, once for null, once for the response.
public MutableLiveData<QuestionResponse> getQuotes(){
    Call<QuestionResponse> call = apiService.getQuestions();
    MutableLiveData<QuestionResponse> questionData = new MutableLiveData<>();

    call.enqueue(new Callback<QuestionResponse>() {
        @Override
        public void onResponse(Call<QuestionResponse> call, Response<QuestionResponse> response) {
            if(response.isSuccessful()){
                QuestionResponse reply = response.body();
                questionData.setValue(reply);
            }
        }

        @Override
        public void onFailure(Call<QuestionResponse> call, Throwable t) {
            System.out.println("Failure");
        }
    });

    // THIS RETURNS AN EMPTY OBJECT AND LATER UPDATES
    return questionData;
}

You could filter by null on your observer, or use a SwitchMap for your LiveData and return a wrapper that indicates loading, for instance.

A: Believe I solved this one. First problem was I was always creating and returning a new mutable-list in my repository. This new list wasn't being observed but still being assigned a value. The reason onChange observable was still being triggered in the main activity is because in the ViewModel questionMutableLiveData.setValue(repository.getQuotes().getValue()) was actually changing the data but with a null value of the newly created mutable-list.
If there's any feedback if this is correct or a better way to organize the repository / viewmodel I would love to hear it!
Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mViewModel = ViewModelProviders.of(this).get(BasicViewModel.class);
    mViewModel.getQuestions().observe(this, new Observer<QuestionResponse>() {
        @Override
        public void onChanged(QuestionResponse response) {
            QuestionResponse temp = mViewModel.getQuestions().getValue();
            Toast.makeText(MainActivity.this, "Questions Updated", Toast.LENGTH_SHORT).show();
        }
    });

    updateButton = findViewById(R.id.updateButton);
    updateButton .setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            update();
        }
    });
}

private void update(){
    mViewModel.updateQuestions();
}

View Model
private Repository repository;
private Application application;
private MutableLiveData<QuestionResponse> questionMutableLiveData;

public BasicViewModel(Application application){
    super(application);
    this.application = application;
    repository = new Repository();
    questionMutableLiveData = repository.getQuotes();
}

public void updateQuestions(){
    repository.getQuotes().getValue();
}

public LiveData<QuestionResponse> getQuestions(){
    if(questionMutableLiveData == null){
        System.out.println("Something Is Wrong");
    }
    return questionMutableLiveData;
}

Retrofit Service
public class Repository {
    MutableLiveData<QuestionResponse> questionData;
    ApiService apiService;

    public QuoteMRepository(){
        apiService = RetrofitSingleton.getRetrofitInstance().create(ApiService.class);
    }

    public MutableLiveData<QuestionResponse> getQuotes(){
        Call<QuestionResponse> call = apiService.getQuestions();

        if(questionData == null) {
            questionData = new MutableLiveData<>();
        }

        call.enqueue(new Callback<QuestionResponse>() {
            @Override
            public void onResponse(Call<QuestionResponse> call, Response<QuestionResponse> response) {
                if(response.isSuccessful()){
                    QuestionResponse reply = response.body();
                    questionData.setValue(reply);
                }
            }

            @Override
            public void onFailure(Call<QuestionResponse> call, Throwable t) {
                System.out.println("Failure");
            }
        });

        return questionData;
    }
}


text:
Q: Disabling and enabling miniprofiler when working with Umbraco 7 This is a two part question, which circles around the same problematcis.
Without setting anything up in Global.Asax, and just inserting this line in my .cshtml file for my basic layout, and running my site in debug mode, the MiniProfiler is automatically displayed in my frontend.
@MiniProfiler.RenderIncludes()

Trying to shut down the MiniProfiler doesn't seem to work. I have tried something as obvious as the following code, but the MiniProfiler is still run, and is still represented in my frontend, when running my site locally:
protected void Application_BeginRequest()
{
    MiniProfiler.Stop();
    if (!Request.IsLocal)
    {
        MiniProfiler.Start();
    }
}

Furthermore In Umbraco.Core's WebProfiler I found the following code:
if (GlobalSettings.DebugMode == false)
    return false;

In my case, i would like to be able to let the Profiler run on my clients site, but that's not possible as DebugMode is always false when I publish my code to my clients site.
Ideally I would like to do something like:
protected void Application_BeginRequest()
{
    MiniProfiler.Stop();
    if (Request.IsLocal || Request.UserHostAddress == "My/developers IP")
    {
        MiniProfiler.Start();
    }
}

How can I programmatically stop the MiniProfiler to set up cases where I don't want it to run when in DebugMode? And how can I make the MiniProfiler available for developers on my customers live sites?


text:
Q: difference usage between label id and aria-labelledby I know the difference between aria-label and aria-labelledby, but what's the differences between those below, and when to use one from another?
The code is from react-testing-library
// first
Username
<input id="username-input" />

// second
Username
<input aria-labelledby="username-label" />

For the first one, according to the mdn documentation

The label text is not only visually associated with its corresponding
text input; it is programmatically associated with it too.
...
You can click the associated label to focus/activate the input, as
well as the input itself.

But the second one does not provide that functionality for browser user, since its just an ARIA attribute for the accessibility.
I also inpected chrome devtools - accessiblity, and I found that both first and second's computed properties show that input and label are associated to each other.
So as of my understanding, first one gives user programatical access but second one does not, and both first one and second one are accessed by screen reader properly.
Is second one subset of the first one? so is below code invalid pattern since the first one is a superset of second one?
Username
<input id="username-input" aria-labelledby="username-label" />

Thank you.

A: A little description of the main difference between aria-label and aria-labelledBy from my side.

Use aria-label if label text is not visible on the screen and use aria-labelledBy if label text is visible.

We can read more on the use cases of both the aria attribute here if we want.
Difference between the usage of label id and aria-labelledby
// first
Username
<input id="username-input" />

// second
Username
<input aria-labelledby="username-label" />

The first one is a legit or traditional way of associating form labels with inputs. The second one doesn't provide a focus input feature when clicking on the associated label. It is used only for web accessibility. The first one provides not only web accessibility, but also provides the focus input feature. So, we can say that the first one has more power than the second one.
There are two more ways that we can associate labels with input along with the input focus feature.
// Wrapper labels
Username <input />

// Wrapper labels where the label text is in another child element

  Username
  <input />

There is one more way that we can associate invisible or hidden labels with input but doesn't provide focus input feature.
// aria-label attributes
// Take care because this is not a label that users can see on the page,
// so the purpose of your input must be obvious to visual users.
<input aria-label="Username" />

I have some (my) rules that I use in my workplace.

*

*I use the first example always whenever it's possible.

*I use aria-label when I have don't have visible text. Imagine a form with an input element that doesn't have a label associated with it and placeholder text for giving information on what to put in the input.

*I use aria-labelledBy to associated non-label elements with the interactive elements (eg: Input)

 Is second one subset of the first one? so is below code invalid pattern since the first one is a superset of second one?
Username
<input id="username-input" aria-labelledby="username-label" />

We must know what is the main advantage of associating a label with input. One is you have mentioned in your question that is web accessibility another one is (ACcording to mdn docs)

You can click the associated label to focus/activate the input, as well as the input itself. This increased hit area provides an advantage to anyone trying to activate the input, including those using a touch-screen device.

From this pattern, you are associating a label with input by two times and one time for the focus input feature. The first one does provide both the feature at the same time so there is no point in adding one more associativity between the label and input.


text:
Q: Why is my code looping twice when using keyboard? I am writing code to alert the user when a specific string of numbers is entered. The code runs seems to run as intended but outputs "1122334455" when it should give me "12345":
import sys
sys.path.append('..')
import keyboard

line = ''
ISBN10 = ''
number = ""

def print_pressed_keys(e):
    global line, ISBN10, number
    line = line.join(str(code) for code in keyboard._pressed_events)
    if line == "2":
        number = 1
    elif line == "3":
        number = 2
    elif line == "4":
        number = 3
    elif line == "5":
        number = 4
    elif line == "6":
        number = 5
    elif line == "7":
        number = 6
    elif line == "8":
        number = 7
    elif line == "9":
        number = 8
    elif line == "10":
        number = 9
    elif line == "11":
        number = 0
    ISBN10 = ISBN10 + str(number)
    if len(ISBN10) > 10:
        ISBN10 = ISBN10[1:11]
    print("ISBN10: " + ISBN10)

keyboard.hook(print_pressed_keys)
keyboard.wait()

The output is:
ISBN10: 1
ISBN10: 11
ISBN10: 112
ISBN10: 1122
ISBN10: 11223
ISBN10: 112233

Whereas it should be:
ISBN10: 1
ISBN10: 12
ISBN10: 123

A: This is because keyboard.hook() will run its callback when you press a key and when you release it. Therefore, twice for every key press. You need to have it run just when a key is pressed:
keyboard.on_press(print_pressed_keys)
# Added hotkey so you can exit block and continue program execution
keyboard.wait("ESC")
# Run this after you press escape so it stops running the hook when you exit
keyboard.unhook_all()


text:
Q: How to pass Session from one Application to another? I am having 2 applications Suppose A and B. I am having a webpage in Application A where i am Setting the Session and in Application B i want to retrieve that session.How can i do that with out using DB?

A: Sessions are application specific and I don't believe you can share data between two applications via the session.  You will need to pass the data through some other medium.  You could serialize it and pass it via a POST parameter.  You may also be able to use a cookie.  If it is really small data, you could just pass it in the GET parameters of the query string.

A: I agree with NYSystemsAnalyst - and here's a FAQ on how to transfer session from a classic ASP app to ASP.NET.  The code can nearly be copied to do the same thing in this case.
http://www.tek-tips.com/faqs.cfm?fid=2943

A: When you say without using a Database I guess you mean without using a third party database. There is no way around the fact you need to store and retrieve data while protecting against simultaneous access of underlying data structures causing problems, and this pretty much makes it a database. You could implement something simple by allocating some shared memory and using semaphores to protect access to it. Also you could have app A inform app B of changes to session state and have app B track these. This communication could be done over a named pipe between the apps. What OS are you targeting?

A: How are you Identifying you user between the applications?
What do you need in the session?
Not sure, but a web-service or wcf that passes the session variables back and forth for a given username || id?
( maybe not the session exactly but a object you could used to build/populate the session on both applications... )
User start session in App A, just before they move to App B store a small version of the session variables needed in cache with high priority but short expiry( this is what the web service would look for).
User stars session in App B, App B calls web service to see if user was in App A... if so get variables needed for App B?
No DBs, but you will need to do some work...
And not even sure this will solve what you looking for?
Used something kind of like this to talk from Admin servers on Production servers...
But I wasn't passing the session itself...
Good Luck


text:
Q: ensuring database performance as data volume increases I am currently into a performance tuning exercise. The application is DB intensive with very little processing logic. The performance tuning is around the way DB calls are made and the DB itself.
We did the query tuning, We put the missing indexes, We reduced or eliminated DB calls where possible. The application is performing very well and all is fine.
With smaller data volume (say upto 100,000 records), the performance is fantastic. My Question is, what needs to be done to ensure such good performance at higher data volumes ?
The data volumes are expected to reach 10 million records.
I can think of table and index partitioning, suggesting filesystems optimized for DB storage and periodic archiving to keep the number of rows in check. I would like to know what else could be done. Any tips/strategies/patterns would be very helpful.

A: Monitoring.  Use some tools to monitor performance, and saturation of CPU, memory, and I/O.  Make trend lines so you know where your next bottleneck will be before you get there.
Testing.  Create mock data so you have 10 million rows on a testing server today.  Benchmark the queries you have in your application and see how well they perform as the volume of data increases.  You might be surprised at what breaks down first, or it may go exactly as predicted.  The point is that you can find out.
Maintenance.  Make sure your application and infrastructure support some downtime, because that's always necessary.  You might have to defrag and rebuild your indexes.  You might have to refactor some of the table structure.  You might have to upgrade the server software or apply patches.  To do this without interrupting continuous operation, you'll need some redundancy built in to the design.
Research. Find the best journals and blogs for the database brand you're using, and read them (e.g. http://www.mysqlperformanceblog.com if you use MySQL).  You can ask good questions like the one you ask here, but also read what other people are asking, and what they're being advised to do about it.  You can learn solutions to problems that you don't even have yet, so that when you have them, you'll have some strategies to employ.

A: You are on the right way:
1) Proper indexes
2) DBMS options tuning (memory caches, buffers, internal threads control and so on)
3) Queries tuning (especially log slow queries and then tune/rewrite them)
4) To tune your queries and indexes you may need to research your queries execution plans
5) Poweful dedicated server
6) Think about queries which your client applications send to the database. Are they always necessary? Do you need all the data you ask for? Is it possible to cache some data?

A: Different databases need to be tuned in different ways.  What RDBMS are you using?
Also,  how do you know whether or not what you have done so far will result in poor performance with larger data sets?  Have you tested your current optimisations with a large amount of test data?
When you did this, how did the performance change?  If you are able to tune the database so that it performs with the data it has now, there's no reason to think that your methods won't work with a larger data set.
Depending on the RDBMS,  the next type of solution is simple:  get bigger, beefier hardware. More RAM, more disks, more CPUs.

A: 10 million records is probably too small to bother with partitioning.  Typically partitioning will only be interesting if your data volumes are an order or magnitude or so bigger than that.
Index tuning for a database with 100,000 rows will probably get you 99% of what you need with 10 million rows.  Keep an eye out for table scans or index range scans on the large tables in the system.  On smaller tables they are fine and in some cases even optimal.
Archiving old data may help but this is probably overkill for 10 million rows.
One possible optimisation is to move reporting off onto a separate server.  This will reduce the burden on the server - reports are often quite anti-social when run on operational systems as the schema tends not to be well optimised for it.
You can use database replication to do this or make a data mart for reporting.  Replication is easier to implement but the reports will be less efficient, no more efficient than they were on the production system.  Building a star schema data mart will be more efficient for reporting but incur additional development work.


text:
Q: Undefined reference to 'yylex' bison error Hi I am new to bison and flex and I am trying to create a simple calculator however I seem to be having errors when trying to compile.
The following is my flex .l file (named a.l):
%{
#include "a.tab.h"
%}
number  [0-9]+

%%

"+"     {return ADD;}
"-"     {return SUB;}
"*"     {return MUL;}
"/"     {return DIV;}
"|"     {return ABS;}
{number}     { return NUMBER;}
\n      {return EOF;}
[ \t]   { }
.    {printf("Mystery Character %s\n", yytext); }

%%

and the following is my bison .y file(named a.y):
%{
#include <stdio.h>
int yyparse(void);
%}

%token NUMBER ADD SUB MUL DIV ABS EOL

%%

calclist: /*nothing*/ | calclist exp EOL { printf("=%d\n, $1") };

exp: factor
    | exp ADD factor { $$ = $1 + $3; }
    | exp SUB factor { $$ = $1 - $3; }
    ;

factor: term |
        | factor MUL term { $$ = $1 * $3; }
        | factor DIV term { $$ = $1 / $3; }

term: NUMBER
    | ABS term { $$ = $2 >= 0? $2 : - $2; }
    ;

%%

int main(void)
{
    return(yyparse());
}

void yyerror(char *s)
{
    fprintf(stderr, "Error : Exiting %s\n", s);
}

This is what I write in the console:

flex a.l
bison a.y
gcc a.tab.c -lfl -o a.exe

The error I get is:

a.tab.c:(.text+0x1f2): undefined reference to `yylex'
collect2.exe: error: ld returned 1 exit status

I also get the following warnings:

a.tab.c: In function 'yyparse':
a.tab.c:595:16: warning: implicit declaration of function 'yylex' [-Wimplicit-function-declaration]
# define YYLEX yylex ()
               ^
a.tab.c:1240:16: note: in expansion of macro 'YYLEX'
       yychar = YYLEX;
                ^~~~~
a.tab.c:1396:7: warning: implicit declaration of function 'yyerror' [-Wimplicit-function-declaration]
       yyerror (YY_("syntax error"));
       ^~~~~~~
a.y: At top level:
a.y:32:6: warning: conflicting types for 'yyerror'
 void yyerror(char *s)
      ^~~~~~~
a.tab.c:1396:7: note: previous implicit declaration of 'yyerror' was here
       yyerror (YY_("syntax error"));
       ^~~~~~~

Would anybody be able to explain to me why these errors/warnings may be occuring?

A: There will be two generated C files, one generated by flex and one by bison. The one created by flex will be called "lex.yy.c" and you'll need to compile that one as well.