text:
Q: Android 10 - how to DISABLE VIBRATION for "Ring Volume without activating "do not disturb" On Android 10
I am trying to disable the vibration for "Ring Volume".
So I am trying to reach the state on the image, which I can reach via the UI - programmatically.

*

*Disabled vibration of Ring Volume

*Do not Disturb mode off

Problem:
I tried using the AudioManager.setRingerMode()
Its spec says:
    /**
     * Sets the ringer mode.
     *

     * Silent mode will mute the volume and will not vibrate. Vibrate mode will
     * mute the volume and vibrate. Normal mode will be audible and may vibrate
     * according to user settings.
     *
This method has no effect if the device implements a fixed volume policy
     * as indicated by {@link #isVolumeFixed()}.
     * *
From N onward, ringer mode adjustments that would toggle Do Not Disturb are not allowed
     * unless the app has been granted Do Not Disturb Access.
     * See {@link NotificationManager#isNotificationPolicyAccessGranted()}.
     * @param ringerMode The ringer mode, one of {@link #RINGER_MODE_NORMAL},
     *            {@link #RINGER_MODE_SILENT}, or {@link #RINGER_MODE_VIBRATE}.
     * @see #getRingerMode()
     * @see #isVolumeFixed()
     */
    public void setRingerMode(int ringerMode) {

Sound like it would be the way to reach the state on the image.
But the code below activates the "Do not Disturb" mode. Which despite of disabling the Vibration
also has a lot of other effects: suppress the notifications etc. which I do not want to activate.
See image below
final AudioManager audio = (AudioManager) mContext.getSystemService(mContext.AUDIO_SERVICE);
audio.setRingerMode(AudioManager.RINGER_MODE_SILENT);

Is the state on the picture above - unreachable programmatically?
According to this thread - Enable Silent Mode in android without triggering Do Not Disturb it is unreachable?
Do not DIsturb activates on RINGER_MODE_SILENT

A: I have found more about behavior described.
DND mode activates - when

*

*there was a command to go into the vibrate mode audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);

*When the phone (or the emulator in my case) does not have support for Vibration.

To support vibrate, silent, normal modes,
and the ability to adjust the volume
without going to DND mode

I do the following:
private void adjustVolume(double ringAndNotificationsVolumeInPercent, int ringMode) {

    // ringer mode applies to notification
    final AudioManager audioManager = (AudioManager) context.getSystemService(context.AUDIO_SERVICE);

     // ALWAYS set the ringer mode, cause changing the volume might implicitly change the mode
    switch (ringMode) {
        case AudioManager.RINGER_MODE_SILENT:
            /**
             * This is a tricky one:
             *
             * The goal is - to just disable Vibration and set volume to 0.
             *
             * using
             * audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
             * sets the phone to to "DontDisturb" mode,
             * having a lot of side effects: like supressing notifications etc.
             *
             * Instead - setting the phone to "RINGER_MODE_NORMAL",
             * then adjusting the volume - has the correct effect.
             */
            audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
            audioManager.adjustStreamVolume(AudioManager.STREAM_NOTIFICATION, AudioManager.ADJUST_MUTE, AudioManager.FLAG_VIBRATE);
            break;

        case AudioManager.RINGER_MODE_VIBRATE:
            Log.d(TAG, "vibrate mode");
            if (utilsVolume.isDontDisturbOff()) {

                // if there is no vibrate mode - the OS may set the phone to DontDisturb
                audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
            } else {
                Log.d(TAG, "Cant enable vibration mode, cause the Dont DIsturb Mode is on. It would cause ");
            }
            break;

        case AudioManager.RINGER_MODE_NORMAL:
            audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);

            // adjust volume
            setSoundRelativeToMax(ringAndNotificationsVolumeInPercent, AudioManager.STREAM_NOTIFICATION);
            setSoundRelativeToMax(ringAndNotificationsVolumeInPercent, AudioManager.STREAM_RING);
            break;

        default:
            Log.d("TAG", "Ignore unknown RINGER_MODE " + ringMode);
            break;
    }
}

private void setSoundRelativeToMax(double percent, int streamType) {
    // requested rights in MainActivity
    final AudioManager audio = (AudioManager) context.getSystemService(context.AUDIO_SERVICE);

    int maxVolume = audio.getStreamMaxVolume(streamType);
    int seventyVolume = (int) (maxVolume * percent);
    audio.setStreamVolume(streamType, seventyVolume, 0);
}


text:
Q: Genetic algorithm - iterative optimization Hi I am absolute beginner and I've got rather theoretical question about iterative optimization in genetic algorithms.
Where in the genetic cycle (see below) does the iterative optimization logically belong? I am not really sure, but I think it could be in population initialization or mutation, depending on given problem.
To be more specific about about the iterative optimization algorithm - I would like to use "hill climbing" or "simulated annealing".
I use this model as reference:

A: Well, there are several possibilities and basically all of them make sense.
If you put the optimisation phase after population initialization (being run once before the genetic algorithm itself) then what you get is an already optimized initial population. This might be useful because the genetic algorithm does not have to search so much, but it may be harmful in a way that you optimize to some local optima, possibly losing useful information in the process.
If you put the optimisation phase before selection, you get a so-called memetic algorithm. MA is based on the fact that an organism learns throughout its lifetime (the optimization). You have two possibilites of how to do that:

*

*Take an individual, optimize it and replace the original individual with its optimized version. This is called "Lamarckian evolution" and is based on the idea (originally by Jean-Baptiste Lamarck at the beginning of 19th century) that the learned features can be passed on to the offsprings.

*Take an individual, optimize it, but then throw the optimized individual away but assign its fitness to the original, unoptimized individual. In this variant the optimization effectively becomes the part of the fitness evaluation process. This is called "Baldwin effect" and is based on the idea (originally by James Mark Baldwin at the end of 19th century) that the learned features cannot be passed on to the offsprings and the genetic information rather describes the ability to learn. By the way, this is the way the natural evolution actually works.
The optimization can, of course, be placed in all the other places, but it is not used (at least I don't know of any such case). However, your problem and mutation/crossover operators might be such that the optimization in those places might be somehow beneficial. Or you can just try and see what you get.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What was Bruce Wayne's childhood like? On the show "Gotham", it seems that Alfred raised Bruce from the time the Waynes were killed, and that he homeschooled Bruce.
I don't remember those aspects of Bruce's childhood from the comics. (Originally, in fact, Alfred joined the household when Bruce was an adult.) I seem to remember something about teenaged Bruce traveling the world and learning martial arts and stuff, but that doesn't really address how he spent most of those years.
In the comics canon, who raised Bruce from age 8 until he became an adult? And did he go to an actual school?

A: Canon shifts constantly in comics, but you are right that at some point the canon was that Alfred was a butler that joins the household after Robin was already there, and finds out about their secret identities one night when one of the dynamic duo comes home injured.
Also it has been true in comics that Bruce, as a tweener, donned a Robin like costume so he could tag along with the world's best police detective and get training.
In the animated series we see him go off as a teenager and train in the circus as an escape artist.
Who raised Bruce shifts over the years, but a short answer might be that in early Batman he more or less raised himself.  In later Batman it was mostly Alfred.

A: Gotham (TV)
Alfred is Bruce Wayne's guardian. In S1E2, after discovering Bruce burning himself with a candle, Alfred meets with Jim about Bruce's self harm and nightmares and he tells Jim about Thomas Wayne's instructions on how to raise Bruce: to let him choose his own path.
This guardianship gets periodically reinforced through the series, At the end of Season 2, Alfred says he has the ability to take Bruce to Switzerland any time he wants, but he chooses not to. It's ultimately his choice to do what Bruce wants, which is Thomas Wayne's direction to Alfred when Waynes made Alfred Bruce's guardian.
Comics
"DC Confirms Batman Had Two Fathers"

There's no room for doubt that Alfred Pennyworth was more than a butler and legal guardian for Bruce Wayne, but as much father
as Thomas Wayne.
https://www.google.com/amp/s/screenrant.com/dc-comics-batman-alfred-pennyworth-father/amp/


text:
Q: How can I fix this error AsyncDrawableCache.java in firebase Crashlytics crash reports I get an error on the following line in my firebase Crashlytics crash reports .Please help me.
AsyncDrawableCache.java

Caused by java.util.ConcurrentModificationException
android.util.ArrayMap.put (ArrayMap.java:620)
com.mediatek.res.AsyncDrawableCache.putCacheList (AsyncDrawableCache.java:163)
com.mediatek.res.ResOptExtImpl.putCacheList (ResOptExtImpl.java:69)
android.content.res.ResourcesImpl.cacheDrawable (ResourcesImpl.java:832)
android.content.res.ResourcesImpl.loadDrawable (ResourcesImpl.java:769)
android.content.res.Resources.loadDrawable (Resources.java:1002)
android.content.res.TypedArray.getDrawableForDensity (TypedArray.java:1006)
android.content.res.TypedArray.getDrawable (TypedArray.java:981)
android.widget.ImageView. (ImageView.java:215)
android.widget.ImageView. (ImageView.java:196)
androidx.appcompat.widget.AppCompatImageView. (AppCompatImageView.java:74)
androidx.appcompat.widget.AppCompatImageView. (AppCompatImageView.java:69)
androidx.appcompat.app.AppCompatViewInflater.createImageView (AppCompatViewInflater.java:199)
androidx.appcompat.app.AppCompatViewInflater.createView (AppCompatViewInflater.java:119)
androidx.appcompat.app.AppCompatDelegateImpl.createView (AppCompatDelegateImpl.java:1551)
androidx.appcompat.app.AppCompatDelegateImpl.onCreateView (AppCompatDelegateImpl.java:1602)
android.view.LayoutInflater.tryCreateView (LayoutInflater.java:1065)
android.view.LayoutInflater.createViewFromTag (LayoutInflater.java:995)
android.view.LayoutInflater.createViewFromTag (LayoutInflater.java:959)
android.view.LayoutInflater.rInflate (LayoutInflater.java:1138)
android.view.LayoutInflater.rInflateChildren (LayoutInflater.java:1099)
android.view.LayoutInflater.rInflate (LayoutInflater.java:1141)
android.view.LayoutInflater.rInflateChildren (LayoutInflater.java:1099)
android.view.LayoutInflater.rInflate (LayoutInflater.java:1141)
android.view.LayoutInflater.rInflateChildren (LayoutInflater.java:1099)
android.view.LayoutInflater.rInflate (LayoutInflater.java:1141)
android.view.LayoutInflater.rInflateChildren (LayoutInflater.java:1099)
android.view.LayoutInflater.rInflate (LayoutInflater.java:1141)
android.view.LayoutInflater.rInflateChildren (LayoutInflater.java:1099)
android.view.LayoutInflater.inflate (LayoutInflater.java:680)
android.view.LayoutInflater.inflate (LayoutInflater.java:532)
android.view.LayoutInflater.inflate (LayoutInflater.java:479)
androidx.appcompat.app.AppCompatDelegateImpl.setContentView (AppCompatDelegateImpl.java:696)
androidx.appcompat.app.AppCompatActivity.setContentView (AppCompatActivity.java:170)
mobitech.dconproject.MotorStatus.onCreate (mainActivity.java:232)
android.app.Activity.performCreate (Activity.java:8151)
android.app.Activity.performCreate (Activity.java:8135)
android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1309)
android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3732)
android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3931)
android.app.servertransaction.LaunchActivityItem.execute (LaunchActivityItem.java:85)
android.app.servertransaction.TransactionExecutor.executeCallbacks (TransactionExecutor.java:135)
android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:95)
android.app.ActivityThread$H.handleMessage (ActivityThread.java:2356)
android.os.Handler.dispatchMessage (Handler.java:106)
android.os.Looper.loop (Looper.java:264)
android.app.ActivityThread.main (ActivityThread.java:8306)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:632)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1049)


text:
Q: Is it possible to resize with the arrow cursors like browsers' resizing actions on vuetify datatable? I would like to resize the table which I made with the vuetify datatable in a page with the arrow cursors just like any browsers could be resized.
I found the arrow cursor setting with css
cursor: ns-resize;

but, don't have any ideas of the action.
Very thankful to be shared.

A: I found a solution from css.
resize from MDN web docs
table tbody {
  overflow-y: scroll;
  resize: vertical;  // options: both, horizontal, etc.
}


text:
Q: Switch vs ArrayList Java I have multiple conditions(almost 30) to check for:
So which option would be better:

*

*Writing switch conditions for each case

*Creating a private static List and then check if the list contains that element or not.

In later case, I have to create 3 lists having 10 elements each, and then if result is found in list 1, then my variable would be say a, if found in list 2, then say b.

A: There are pros and cons of both the methods but I would recommend using switch statement because

*

*code will be readable and understandable to others.

*o(1) condition checking

*I am not sure how will the second option be useful if there are some new conditions proposed in future.

A: It looks like you need if statements to check for the three conditions. Inside the if, you can then check if the element is present in a HashMap.


text:
Q: Moment.js, how to just change a format of a date without changing timezone? I want to change a format of a date and time string. But moment.js changes timezone to my system timezone (+3):
// This is a string:
"2013-09-20 23:59:59 +0100"

// I want to change it to this:
"20-09-2013 23:59:59 +0100"

// This is what I do and what I get. 1 hour is added by force:
moment("2013-09-20 23:59:59 +0100").format("DD-MM-YYYY HH:mm:ss ZZ")
"21-09-2013 01:59:59 +0300"

How to just change a format without changing timezone?

A: See moment issue #887, directly regarding this.  It may be easier in a future version, but the current workaround is as follows:
var input = "2013-09-20 23:59:59 +0100";
var m = moment(input).zone(input);
m.format("DD-MM-YYYY HH:mm:ss ZZ")

A: In moment.js v-2.8.3:
var dateTime = "2014-12-09 13:59:59 +0930";
var parseDateTimeZone = moment.parseZone(dateTime).format("YYYY-MM-DDTHH:mm:ssZ");

Doc-API


text:
Q: Is it "make" or "makes" in this sentence?
Many clauses and phrases make the noun known to the listener by telling the listener which person or thing we are talking about.

*

*Can you give me the book on the table.

*Did you read the book which I gave you?

*etc.

The quote is from English grammar book, this is why I suppose everything should be correct. However, 'make' looks very weird to me. Isn't it a typo?

A: I think because the subjects are clauses and phrases, which are plural, it should be 'make'.

A:
The subject must agree in number with its verb.

This is the rule to be applied while deciding what to opt for.  Thus, if a subject is singular, its verb must also be singular; if a subject is plural, its verb must also be plural.
But,
This is a case of a compound sentence (means made up of two or more parts.  Two or more words can be compounded or linked by joining them with any of three words:
and, or, and nor)

Many clauses and phrases
The verb is singular if the two subjects separated by and refer to
  the same person or thing.

Both Clauses and Phrases are referring to the same thing. Hence,   the verb make is correct.


text:
Q: Adding rows to gridview dynamically How to Add Number Rows to a grid view dynamically using c# asp.net

A: To do this, add rows to the data source to which the grid is bound.
Here's an example.
Edit: The link I posted adds a row without adding to the data source.  It seems kind of kludgey to me, but it may be more like what you're looking for.

A: Add new "rows" to the datasource of the grid. If your datasource is a DataTable, then add a new DataRow to the DataTable. If your datasource is a collection of objects, then add a new object to that collection.
Don't forget to rebind the grid once you have updated the datasource.


text:
Q: Python 3 - Controle de Fluxo inesperado ao executar IF/IF NOT ou IF/ELSE Eu sou novo em Python, mas já tenho costume programa em Java.
Gostaria de entender melhor o porquê ao tentar programar um controle de fluxo usando IF/ELSE ou IF/IF NOT o bloco todo é executado.
Código Python 3.7
luz_acessa = False
def interruptor():
    global luz_acessa
    if luz_acessa:
        print("True: Luz acessa")
        luz_acessa = False
    if not luz_acessa: // Mesma coisa com 'else' ao invés de 'if not'
        print("False: Luz apagada")
        luz_acessa = True

Console Python 3.7
interruptor()
False: Luz apagada
interruptor()
True: Luz acessa
False: Luz apagada
interruptor()
True: Luz acessa
False: Luz apagada
interruptor()
True: Luz acessa
False: Luz apagada

Por exemplo em Java, se eu quiser inverter um boolean faço algo simples assim:
Código Java:
private boolean luz_ligada;
    private void interruptor(){
        if(luz_ligada){
            System.out.println("Luz acessa");
            luz_ligada = false;
        } else {
            System.out.println("Luz apagada");
            luz_ligada = true;
        }
    }

Log Java em um simples loop:
Luz apagada
Luz acessa
Luz apagada
Luz acessa
Luz apagada

Process finished with exit code 0

A: Os códigos não são equivalentes. if not não é o mesmo que else.
Em Java, o equivalente ao que você escreveu em Python é:
private boolean luz_ligada;
private void interruptor(){
    if(luz_ligada){
        System.out.println("Luz acessa");
        luz_ligada = false;
    }

    if(!luz_ligada) {
        System.out.println("Luz apagada");
        luz_ligada = true;
    }
}

Para terem o mesmo resultado, você deve alterar o código Python para:
luz_acessa = False
def interruptor():
    global luz_acessa
    if luz_acessa:
        print("True: Luz acessa")
        luz_acessa = False
    else:
        print("False: Luz apagada")
        luz_acessa = True

A: A resposta dada pelo Leonardo Lima está correta, mas apenas uma explicação mais aprofundada do porque.
De modo geral é bem simples.
Veja a seguir a diferença deste código:

luz_acessa = False

def interruptor():
    global luz_acessa
    if luz_acessa:
        print("True: Luz acessa")
        luz_acessa = False
    else:
        print("False: Luz apagada")
        luz_acessa = True

para esse código:

luz_acessa = False

def interruptor():
    global luz_acessa
    if luz_acessa:
        print("True: Luz acessa")
        luz_acessa = False
    if not luz_acessa:
        print("False: Luz apagada")
        luz_acessa = True

e para um terceiro exemplo não citado antes:

luz_acessa = False

def interruptor():
    global luz_acessa
    if luz_acessa:
        print("True: Luz acessa")
        luz_acessa = False
    elif not luz_acessa:
        print("False: Luz apagada")
        luz_acessa = True

O if, é nada mais nada menos que um operador condicional em nível de código, é um branch em nível de processador, mas focando no nível de código, ele tem por objetivo verificar a veracidade da informação colocada após ele. se estas forem verdadeiras ele executa o código que o segue.
Ao usar o else cria-se um caminho para quando a informação colocada no primeiro for falsa, ou seja:

Se a luz estiver acesa:

   Apague

Senão:

   Acenda

Fim Se

No código que você postou, como não usou o operador else para quando a informação for falsa, e ao invés disso utilizou outro operador if o que faria com que o código verificasse cada uma de forma separada e as execute uma a uma, e não de forma dependente, segue exemplo de como seu código executava:

Se a luz estiver acesa:

   Apague

Fim Se

Se a luz estiver apagada:

   Acenda

Fim Se

Isso exemplifica, que sempre que o sua função for executada, os dois executarão em seguida, fazendo com que o primeiro if sempre seja sobrescrito
Quanto ao exemplo citado por mim, o else como já citado cria um caminho para quando a informação é falsa, a diferença deste para o else if, é que o else if cria um caminho para quando a primeira informação for falsa, porém a sua informação for verdadeira, segue exemplo da execução:

Se a luz estiver acesa:

   Apague

Senão, se a luz estiver apagada:

   Acenda

Fim Se

Supondo que a luz tivesse um terceiro valor que fosse diferente de true ou false, por exemplo um indefinido, quando a luz estivesse com valor indefinido ela não seria nem acesa e nem apagada, e para alterar isso teria que, ou colocar outro else if que verificasse quando for indefinida, ou colocar um else ao final de tudo para que este seja sempre executado quando os anteriores não forem.
Enfim, espero ter ajudado


text:
Q: PySide2: Proper way to clean up grandchild threads I'm using PySide2 to write a multithreaded application. I have a Controller object already running in its own thread so that it does not block the GUI thread. This Controller needs to spin up multiple Worker threads that perform work continuously. I can manually start and stop these grandchild threads correctly with a signal, but I'm having trouble cleaning them up with signals on application exit.
Here's a toy example that replicates my problem:
import sys

import shiboken2
from PySide2.QtCore import QObject, QThread
from PySide2.QtWidgets import QApplication, QPushButton

class Grandchild(QObject):
    def __init__(self, parent=None):
        super(Grandchild, self).__init__(parent)
        print('Grandchild()')

    def __del__(self):
        print('~Grandchild()')

class Child(QObject):
    _thread = None
    _worker = None

    def __init__(self, parent=None):
        super(Child, self).__init__(parent)
        print('Child()')

    def __del__(self):
        print('~Child()')
        if shiboken2.isValid(self._thread):
            self.stop_thread()

    def start_thread(self):
        print('Starting grandchild thread')
        self._thread = QThread(self)
        self._worker = Grandchild()
        self._worker.moveToThread(self._thread)
        self._thread.finished.connect(self._worker.deleteLater)
        self._thread.start()

    def stop_thread(self):
        print('Stopping grandchild thread')
        self._thread.quit()
        self._thread.wait()

    def toggle_thread(self):
        if self._thread and self._thread.isRunning():
            self.stop_thread()
        else:
            self.start_thread()

class Parent(QPushButton):
    _thread = None
    _worker = None

    def __init__(self, parent=None):
        super(Parent, self).__init__(parent)
        print('Parent()')
        self.setText('Start Grandchild')

        self._thread = QThread(self)
        self._worker = Child()
        self._worker.moveToThread(self._thread)
        self._thread.finished.connect(self._worker.deleteLater)
        self._thread.start()

        self.clicked.connect(self.on_push)
        self.clicked.connect(self._worker.toggle_thread)

    def __del__(self):
        print('~Parent()')
        if shiboken2.isValid(self._thread):
            self._thread.quit()
            self._thread.wait()

    def on_push(self):
        if self.text() == 'Start Grandchild':
            self.setText('Stop Grandchild')
        else:
            self.setText('Start Grandchild')

def main():
    app = QApplication(sys.argv)

    widget = Parent()
    widget.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

In this example, starting and stopping the threads using the button works fine. If I start and stop the grandchild with the button and then close the application, all destructors call correctly and the application exits correctly. If I only start the grandchild and close the application, I get:
Parent()
Child()
Starting grandchild thread
Grandchild()
QThread: Destroyed while thread is still running
~Parent()

Process finished with exit code 134 (interrupted by signal 6: SIGABRT)

My first thought was to modify the Parent like so:
    stop_child = Signal()

    def __init__(self):
        self.stop_child.connect(self._worker.stop_thread)

    def __del__(self):
        print('~Parent()')
        self.stop_child.emit()
        if shiboken2.isValid(self._thread):
            self._thread.quit()
            self._thread.wait()

As is, this does not affect the problem at all. If I put a breakpoint in Child.stop_thread, I can see that it never gets executed before the SIGABRT gets thrown. If I put a breakpoint inside Parent.__del__, execution stops as expected. If I resume execution, it does stop at my Child.stop_thread breakpoint. So something about pausing in the destructor is allowing the signal to get caught in the Child thread? Anyway, this doesn't function without breakpoints, so that doesn't work.
I removed all of that and did something that seems really dumb (in the long-term):
    # Parent
    def __del__(self):
        print('~Parent()')
        self._worker.stop_thread() # Call the instance fn directly
        if shiboken2.isValid(self._thread):
            self._thread.quit()
            self._thread.wait()

And of course, it works:
Parent()
Child()
Starting grandchild thread
Grandchild()
~Parent()
Stopping grandchild thread
~Child()
~Grandchild()

Process finished with exit code 0

It seems like it would be a really terrible idea to call an instance function for an object that lives in another thread. I'm assuming it works because my stop_child function (in both this toy and in my actual code) is implicitly thread-safe.
So this leads me to my questions:

*

*What is the correct way to cleanup grandchildren threads when the primary thread is shutting down?

*What if, as in this example, I want the existence of those grandchildren threads abstracted behind a member object?

*Shouldn't the signals/slots approach have worked?

A: After more experimentation, it appears as though the signals/slots approach will work if you make the connection a Qt.BlockingQueuedConnection.
self.stop_child.connect(self._worker.stop_thread, Qt.BlockingQueuedConnection)

This means that the main thread blocks until the signal is delivered, which might not be desirable if the stop_child signal is used during normal runtime operation. It seems to be alright in the main widget's destructor, though.
The complete working example follows:
import sys

import shiboken2
from PySide2.QtCore import QObject, QThread, Signal, Qt
from PySide2.QtWidgets import QApplication, QPushButton

class Grandchild(QObject):
    def __init__(self, parent=None):
        super(Grandchild, self).__init__(parent)
        print('Grandchild()')

    def __del__(self):
        print('~Grandchild()')

class Child(QObject):
    _thread = None
    _worker = None

    def __init__(self, parent=None):
        super(Child, self).__init__(parent)
        print('Child()')

    def __del__(self):
        print('~Child()')
        if shiboken2.isValid(self._thread):
            self.stop_thread()

    def start_thread(self):
        print('Starting grandchild thread')
        self._thread = QThread(self)
        self._worker = Grandchild()
        self._worker.moveToThread(self._thread)
        self._thread.finished.connect(self._worker.deleteLater)
        self._thread.start()

    def stop_thread(self):
        print('Stopping grandchild thread')
        self._thread.quit()
        self._thread.wait()

    def toggle_thread(self):
        if self._thread and self._thread.isRunning():
            self.stop_thread()
        else:
            self.start_thread()

class Parent(QPushButton):
    _thread = None
    _worker = None

    stop_child = Signal()

    def __init__(self, parent=None):
        super(Parent, self).__init__(parent)
        print('Parent()')
        self.setText('Start Grandchild')

        self._thread = QThread(self)
        self._worker = Child()
        self._worker.moveToThread(self._thread)
        self._thread.finished.connect(self._worker.deleteLater)
        self._thread.start()

        self.clicked.connect(self.on_push)
        self.clicked.connect(self._worker.toggle_thread)
        self.stop_child.connect(self._worker.stop_thread, Qt.BlockingQueuedConnection)

    def __del__(self):
        print('~Parent()')
        self.stop_child.emit()
        if shiboken2.isValid(self._thread):
            self._thread.quit()
            self._thread.wait()

    def on_push(self):
        if self.text() == 'Start Grandchild':
            self.setText('Stop Grandchild')
        else:
            self.setText('Start Grandchild')

def main():
    app = QApplication(sys.argv)

    widget = Parent()
    widget.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()


text:
Q: Why is the IF function not working? I have a problem in excel, I want to make mathematical equation, I've tried it and I have problem with that function, it gives me error. I want have result in G6
if i type W in F6, then it will type in G6 : E6
if i type L in F6, then it will type in G6 : -D6
i think that I can get -D6 by multiplying D6 with -1

Note: KDYŽ means IF in my language

A: If I understand you correctly, this answer will help you resolve the problem you are having. It appears there are a couple issues with your formula.

*

*You need to use quotation marks around the L and W in the IF
logical test.
=IF(F6="L", D6*-1, IF(F6="W", E6,))

*You can not perform a mathematical operation on a text value of 270C. To accomplish
this you will need to tell Excel to only use the left most values of
cell D6 by using the LEFT function. The & "C" replaces the text. If you don't want the C suffix, leave it off.
=IF(F6="L",SUM(LEFT(D6,3)*-1) & "C",IF(F6="W",E6,))
Results:


text:
Q: Как рекурсивно отфильтровать элементы многомерного массива? Функция должна в массив arrayTwo добавить рекурсивно только числовые элементы arrayOne.
let arrayOne = [
    8, 2,
    [1, 6, 'm', 4, 't'],
    [[3, 'b'], [7, 'x', [7, 'f', 'l']]],
    22, 5, 'y', 3,
    [[[[['k', 1, [9, 'u', 4]]]]]]
];

let arrayTwo = [];

Так добавляю вообще все элементы (работает):
let i = 0;

function elementFiltering(array) {
    arrayTwo.push(array[i]);
    i++;
    if (i == arrayOne.length) return;
    elementFiltering(array);

    document.querySelector('.out').textContent = arrayTwo;
}

document.querySelector('button').onclick = elementFiltering(arrayOne);

Но не получается отфильтровать, пытался сделать таким способом:
for (let item in array[i]) {
    if (!isNaN(array[i][item])) {
        arrayTwo.push(array[i][item]);
    }
}
i++;
if (i == arrayOne.length) return;
elementFiltering(array);

Тогда пропускаются элементы 8 и 2, первый вложенный массив ( [1, 6, 'm', 4, 't'] ) фильтруется, а дальше ничего не происходит.
Подскажите пожалуйста, как можно решить данную задачу.
UPD
С помощью подсказки от @Neverm1ndo смог упростить код:
let arrayOne = [
    8, 2,
    [1, 6, 'm', 4, 't'],
    [[3, 'b'], [7, 'x', [7, 'f', 'l']]],
    22, 5, 'y', 3,
    [[[[['k', 1, [9, 'u', 4]]]]]]
];

let arrayTwo = [];

function elementFiltering(array) {
    for (let i = 0; i < array.length; i++) {
        if (typeof array[i] == 'number') arrayTwo.push(array[i]);
        if (Array.isArray(array[i])) elementFiltering(array[i]);
    }
    return arrayTwo;
}

elementFiltering(arrayOne);

console.log(arrayTwo);

A: Вам всего лишь нужно проверять, является ли элемент массива числом или массивом.

let arrayOne = [
    8, 2,
    [1, 6, 'm', 4, 't'],
    [[3, 'b'], [7, 'x', [7, 'f', 'l']]],
    22, 5, 'y', 3,
    [[[[['k', 1, [9, 'u', 4]]]]]]
];

let arrayTwo = [];

function elementFiltering(array) {
  const result = [];
  for(let i = 0; i < array.length; i++) {
    if (typeof array[i] == 'number') { // проверка на число
      result.push(array[i]);
      continue; // идем дальше
    }
    if (!Array.isArray(array[i])) continue; // если элемент - не массив, идем дальше
    result.push(...elementFiltering(array[i])); // оператор ... (spread) как бы разбирает массив, которого нам вернул elementFiltering на аргументы
  }
  return result;
}

arrayTwo.push(...elementFiltering(arrayOne));

console.log(arrayTwo);

UPD
Вариант, если нужно просто вызвать функцию elementFiltering

let arrayOne = [
    8, 2,
    [1, 6, 'm', 4, 't'],
    [[3, 'b'], [7, 'x', [7, 'f', 'l']]],
    22, 5, 'y', 3,
    [[[[['k', 1, [9, 'u', 4]]]]]]
];

let arrayTwo = [];

function elementFiltering(array) {
  const result = [];
  for(let i = 0; i < array.length; i++) {
    if (typeof array[i] == 'number') { // Если элемент число
      arrayTwo.push(array[i]);
      continue;
    }
    if (!Array.isArray(array[i])) continue; // Если элемент не массив, идем дальше
    result.push(...elementFiltering(array[i])); //
  }
  return result;
}

elementFiltering(arrayOne);

console.log(arrayTwo)

Справочный материал, на всякий случай, если что-то будет не понятно:

*

*Циклы while/for

*Что такое рекурсия

*Операторы rest/spread

A: Можно воспользоваться методом Array.prototype.reduce(), который перебирает массив и может сразу записывать значение в нужном виде без объявления лишних переменных
Ну логика предельна проста:

*

*Если число, то добавляем в результат

*Если нет и это массив, то запускаем для него этот же алгоритм и элементы нового результата записываем в предыдущий результат

Код:

const arrayOne = [
    8, 2,
    [1, 6, 'm', 4, 't'],
    [[3, 'b'], [7, 'x', [7, 'f', 'l']]],
    22, 5, 'y', 3,
    [[[[['k', 1, [9, 'u', 4]]]]]]
];

const getAllNums = (arr) => {
  return arr.reduce((result, el) => {
    if (typeof el === 'number') result.push(el);
    else if (Array.isArray(el)) result.push(...getAllNums(el));

    return result;
  }, []);
}

const arrayTwo = getAllNums(arrayOne);

console.log(arrayTwo);

Если нужен будет вариант без рекурсии (т.е. самому не реализовывать рекурсию), то можно так:

*

*С помощью Array.prototype.flat() (сам метод рекурсивный) преобразуем многомерный массив в одномерный

*Из получившегося массива оставлем только те, у кого тип - это число

Код:

const arrayOne = [
    8, 2,
    [1, 6, 'm', 4, 't'],
    [[3, 'b'], [7, 'x', [7, 'f', 'l']]],
    22, 5, 'y', 3,
    [[[[['k', 1, [9, 'u', 4]]]]]]
];

const arrayTwo = arrayOne.flat(Infinity).filter(x => typeof x === 'number');

console.log(arrayTwo);


text:
Q: How can I save the grep output of a curl to a variable and don't log it to the console? I have a shell script (called by apache cgi) that should curl and grep the result to check the health of a server. That's what I've got so far.
printf "Content-type: text/html\n"
PAGE="$(curl -v -u http://targetserver/xmlgatewayauth/login)"
CRES="$($PAGE|grep "login";)"
echo $CRES;

If I run the script in Linux as a shell the output is:
...
< Location: login_success.jsp
< Content-Length: 0
< Date: Mon, 15 Oct 2018 08:42:39 GMT
...

but if I call the script via CGI from the browser - the result is empty.
I've tested the CGI Script with a static output and it worked. (Hello World).
The problem is:
I don't want the script to output anything but the variable "CRES". But it outputs the whole curl (grep)(not the variable) to the console and doesnt ouput the variable to the website.
How can I solve the problem?

A: The problem is that you are printing line 1 before the other lines. So change the order to this:
PAGE="$(curl -v -u http://targetserver/xmlgatewayauth/login)"
CRES="$($PAGE|grep "login";)"
echo $CRES;
printf "Content-type: text/html\n"

or
PAGE="$(curl -v -u http://targetserver/xmlgatewayauth/login)"
CRES="$($PAGE|grep "login";)"
printf "Content-type: text/html\n"
echo $CRES;


text:
Q: Does elasticsearch support searching and reporting on serialized java.time.Instant fields? I have the following json :
Order {

   "creationDate" : 1441108800000,
   "expiryDate" : 253402300799000

}

While creating java objects I use Instant (e.g Instant.now() to set the creation date) to set the dates for creation and expiry. When I serialize this into the couchbase DB using spring data and jackson dependencies I get the above json. These documents are replicated to elastic for searching purposes.
Is elastic able to search for these type of dates? e.g. the search could be for expired orders? Can it handle date conversions etc?
If this is not the best way to store datetime please suggest a better approach to handle date-time requirements in general considering timezones, spring couchbase serialization and searching using elastic search.

A: If you plan to use the date/time manipulation functions of the N1QL query language in Couchbase, I suggest you use human-readable date/time-stamps, like 2006-01-02T15:04:05.999+00:00. They are what works best with these functions. And this format is widely supported in other contexts, too.
More here:
https://developer.couchbase.com/documentation/server/current/n1ql/n1ql-language-reference/datefun.html

A: This is what works for me :
I am storing dates as longs I found it easier to compare and do the maths on it only while showing in UI I convert it to a human readable form as per the timezone. We can get it in java by calling instant.toEpochMilli(). Spring data has not problem in serializing and deserializing it and elastic search has a Date datatype which we can set up while defining the mapping for our document.


text:
Q: Backbone Model get attribute function returns last updated value If there's an optional field in the server returned JSON top structure. Backbone Model seem to cache previously set value. Lets say i get a JSON like this
{
label: "test_label",
attr1: "test1",
attr2: "test2"
}
when I say @model.get("label") i get "test_label". So later on, if i get a JSON like this
{
attr1: "test1",
attr2: "test2"
}
i get "test_label" when i query for @model.get("label"). Is this a known issue in backbone.js? I do something like this to fetch
@modelXhr = @model.fetch
  success: (-> this.trigger('reset')).bind @model

I'm a beginner in javascript/coffeescript, What can i do so when i query for a field which doesn't exist in the latest returned model I won't get an older value? Appreciate your help

A: You should either clear the model beforehand using @model.clear() or (in my opinion the better way) ensure that the data format for a specific model type does not change. Return { label: null, ... }
You are then later on able to check for the existence of the label using @model.get("label")?
If you are not able to ensure data integrity throughout your requests, clear the model.


text:
Q: Is there the word, "Fortunity"? If there is, what does it mean? I "think" I clearly heard the word, "Fortunity" in the following statement of the Wall Street Journal Report of this week (November 5th), introducing the unique service of Sanchez Delta Airline via Far East Network Radio broadcast.

"Airlines Sanchez Delta, a charter company caters to teams with
  tricked-out jets, hand-picked flight attendants, meals from some
  players' favorite restaurants. Team charters often used to amount a
  fortunity party - beer, pizza and junk food. But the airlines say the
  days of raucous party flying have gone. Many teams ban alcohol, have
  nutritionist's select menus, and set up plane chairs so coaches can
  study games when some players can sleep."

As I've never heard the word, "Fortunity," I checked both Cambrigde and Oxford online dictionaries, neither of which carries "Fortunity."
Spell checker keeps recommending me to correct "Fortunity" into "Fortuity" or "Fortunate" while I'm typing this question.
On the other hand, I see a lot of captions including the word, "Fortunity" on Google Search, though none of them provides its definition.
Is "Fortunity" a current English word? If it is, what does it mean?

A: SF's conjecture, fraternity, appears to be correct. I couldn't find the audio, but what I take to be either the transcript or the original from which the read story was adapted is here. Below is the portion corresponding to your transcript, with departures bolded and unincluded matter italicized:

Instead, airlines—particularly Delta—and charter companies cater to teams with tricked-out jets, handpicked flight attendants and meals from players' favorite restaurants, sometimes served on silver trays.
Team charters often used to amount to a fraternity party of beer, pizza and junk food, sometimes with guitar playing and rookie hazing, but airlines say the days of raucous party flights are gone. Many teams ban alcohol, have nutritionists select menus and set up plane interiors so coaches can study game films and players can sleep.

I conjecture that what you heard as "Sanchez" was probably "such as".
For those whose cultural awareness does not extend to the 'frat party': this is a convivial assembly hosted by a 'fraternity', a university-based social club of sub-adult US males, and characterized principally by participants' indulgence of their libidinal and appetitive impulses with as little restraint as circumstances permit.

A: The Oxford English Dictionary online has citations for fortunity from the fifteenth and seventeenth centuries, and the meaning is given as 'fortune, hap'. If the word is making a comeback, it seems to be doing so with a rather different meaning. Is a fortunity party perhaps what used to be called a 'surprise party'?


text:
Q: Is there a special case of the EM algorithm for exponential family distributions? According to Wikipedia, the formal definition of the EM algorithm is

The EM algorithm seeks to find the MLE of the marginal likelihood by iteratively applying these two steps:
Expectation step (E step): Define $Q(\boldsymbol\theta\mid\boldsymbol\theta^{(t)})$ as the expected value of the log likelihood function of $\boldsymbol\theta$, with respect to the current conditional distribution of $\mathbf{Z}$ given $\mathbf{X}$ and the current estimates of the parameters $\boldsymbol\theta^{(t)}$:
$$
Q(\boldsymbol\theta\mid\boldsymbol\theta^{(t)}) = \operatorname{E}_{\mathbf{Z}\mid\mathbf{X},\boldsymbol\theta^{(t)}}\left[ \log L (\boldsymbol\theta; \mathbf{X},\mathbf{Z})  \right] \,
$$
Maximization step (M step): Find the parameters that maximize this quantity:
$$
\boldsymbol\theta^{(t+1)} = \underset{\boldsymbol\theta}{\operatorname{arg\,max}} \ Q(\boldsymbol\theta\mid\boldsymbol\theta^{(t)}) \,
$$

In instances where $p(\mathbf{x},\mathbf{z})$ is an exponential family distribution, I have found that authors used
$$
Q(\boldsymbol\theta\mid\boldsymbol\theta^{(t)}) = \log L (\boldsymbol\theta; \mathbf{X},\operatorname{E}_{\mathbf{Z}\mid\mathbf{X},\boldsymbol\theta^{(t)}}\left[\mathbf{Z}\right]) \,
$$
instead of
$$
Q(\boldsymbol\theta\mid\boldsymbol\theta^{(t)}) = \operatorname{E}_{\mathbf{Z}\mid\mathbf{X},\boldsymbol\theta^{(t)}}\left[ \log L (\boldsymbol\theta; \mathbf{X},\mathbf{Z})  \right] \,
$$
where $\operatorname{E}_{\mathbf{Z}\mid\mathbf{X},\boldsymbol\theta^{(t)}}\left[\mathbf{Z}\right]$ is the estimated data. Are these two equations equivalent?

A: Suppose we want to estimate the parameter $\theta$ of the distribution $p(z;\theta)$ of a random variable $Z$. If we had samples $z_1, z_2, \dots, z_N$, we could easily do this using maximum likelihood estimation. However, suppose instead we are given the samples $x_1,x_2,\dots,x_N$ of another random variable $X$, where $X$ and $Z$ are related via the joint distribution $p(x,z)$. Since $p(x,z) = p(x \mid z) \cdot p(z;\theta)$, then $p(x,z) = p(x,z;\theta)$.
We could then define the complete-data likelihood as
$$
p(x_1,x_2,\dots,x_N,z_1,z_2,\dots,z_N)
$$
We can also assume that each pair $(x_i,z_i)$ is independent of and identically distributed to every other pair for $i \in \{1,2,\dots,N\}$ such that
$$
p(x_1,x_2,\dots,x_N,z_1,z_2,\dots,z_N) = \prod_{i=1}^N p(x_i,z_i;\theta)
$$
and
$$
\log p(x_1,x_2,\dots,x_N,z_1,z_2,\dots,z_N) = \sum_{i=1}^N \log p(x_i,z_i;\theta)
$$
Next, let
$$
p(x_i,z_i;\theta) = h(x_i,z_i) \cdot \exp(\eta (\theta) \cdot T(x_i,z_i) + A(\theta))
$$
such that
$$
\log p(x_i,z_i;\theta) = \log h(x_i,z_i) + \eta (\theta) \cdot T(x_i,z_i) + A(\theta)
$$
Then, note that
\begin{align}
\mathbb{E}\left[\log p(x_i,z_i;\theta) \mid x_i\right] &= \mathbb{E}\left[\log h(x_i,z_i) \mid x_i\right] + \eta (\theta) \cdot \mathbb{E}\left[T(x_i,z_i) \mid x_i\right] + A(\theta) \\
\log p(x_i,\mathbb{E}\left[z_i \mid x_i\right];\theta) &= \log h(x_i,\mathbb{E}\left[z_i \mid x_i\right]) + \eta (\theta) \cdot T(x_i,\mathbb{E}\left[z_i \mid x_i\right]) + A(\theta)
\end{align}
and so, in general,
$$
\mathbb{E}\left[\log p(x_i,z_i;\theta) \mid x_i\right] \neq \log p(x_i,\mathbb{E}\left[z_i \mid x_i\right];\theta)
$$


text:
Q: Can a browser modified or create extension to give option to save playing videos? Nowadays, most sites encrypt or use DRM for playing videos. But browser can not play the file directly, it must be decrypted. Whatever the process is, ultimately browser need an actual playable video file.
So, is it possible to modify a browser like chrome to add button over video element to download video which is already decrypted and streaming?

A: Yes, there's a project called youtube-dl that lets you download a video locally, and you can even specify the format and audio/video quality.
Major browsers have extensions that integrate with this command line application, like this one for example.


text:
Q: Joint distribution of two uniform random variables Consider two uniform random variables $U, V$ . If  $ U \sim \mbox{Uniform}(0,1)$ and $V = 1 -U$ how would we show that the joint distribution of $(U, V)$ is given by $\max \{ u + v -1,0 \}$?
The reason I ask is because the joint distribution is the lower
Frechet-Hoeffding bound from the theory of Copulas. This makes sense intuitively given that the Frechet-Hoeffding bounds
correspond to cases of extreme dependency and if we set $V = 1 - U$, the random variables are perfectly negatively correlated. However, how can we show this result explicitly?


text:
Q: Android - Signed APK - animated-vector not working I am facing an issue where I am using the vector drawables along with animated vector drawables. Everything has been working fine and smooth so far on API level 15+.
Today when I was preparing to release an update, I built a Signed APK and did the last round of testing where surprisingly all the vector animations stopped working. I just see plain vector images, but no vector animations that I applied to its path.
It is only working on Android M platform. Its not working any other platform, not even Lollipop.
All of them were working fine on the dev build, I really don't understand and I am unable to find the possible reason. The only thing that comes to my mind is the proguard-rules.pro file, because that is the only thing that differentiates a signed version of an APK from a dev version.
Can someone please throw some light and help me out with this issue. I am really stuck with the release now and unable to find a solution anywhere.
I have used this approach on vectors (its my own answer). And for the vector animations, I have simply written like this
 <animated-vector
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:drawable="@drawable/vector_img"
    tools:ignore="NewApi">
  <target
      android:animation="@anim/slide_up"
      android:name="slab_one"/>
 </animated-vector>

I'm using gradle 1.5.0. This is what some relevant parts of my build.gradle file look like -
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        multiDexEnabled true
        generatedDensities = []
    }
    aaptOptions {
        additionalParameters "--no-version-vectors"
    }
    dexOptions {
        javaMaxHeapSize "4g"
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile 'com.android.support:support-vector-drawable:23.4.0'
    compile 'com.android.support:animated-vector-drawable:23.4.0'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0'
}

Would really appreciate your help. Thanks in advance !

A: Found the solution. Just had to add a line to proguard.
-keep class android.support.graphics.drawable.** { *; }

So I was right in guessing that the issue with Signed APK is related to proguard. I'm now able to see the vector animations playing on pre-lollipop devices as well.


text:
Q: How to make PostgreSQL use gin_trgm_ops index for equality comparison There is a table and a gin index, Insert 1,000,000 random numbers. 0 < number < 100,000. Test two equivalent queries
create table Test
(
    id   serial primary key,
    code varchar(255) not null
);
create index Test_code_gin on Test using gin (code gin_trgm_ops);

-- Test1
explain analyse
select * from Test where code like '1234';

-- Test2
explain analyse
select * from Test where code = '1234';

Test1 used gin_trgm_ops index, Execution Time: 1.640 ms;
Test2 does not use index, Execution Time: 24.531 ms;
What can I do to make PostgreSQL use the index? Or modify the ORM strategy and my SQL statement? Or simply add a BTree index?

A: That capability was added in v14.  So you could upgrade PostgreSQL to v14, then upgrade pg_trgm to its newest version (upgrading with pg_upgrade does not do that automatically).
But I would just create the btree index, as that should be faster for equality than using trigrams.  Upgrading just to get access to an inferior implementation is not a victory, unless the extra space needed for the index is intolerable.


text:
Q: Angular 2 Lazy load Tab content I have a set of tabs and I want a few tabs to load 'eagerly' and few to load 'lazyily'. For example if I have 2 tabs, Tab1's content should be loaded eagerly and Tab2's contents should load lazyily.
I followed this nice example
<tab tabTitle="Tab 2" lazyload="true">Something like this</tab>

How do I Lazyload the tab content on clicking the tab instead of hiding the loaded content?

A: I don't really know what you want to implement and what "lazy load" means for you... Do you want to load data asynchronously before displaying the tab? As @TGH stated, routing is a great feature you should consider, especially its @CanActivate decorator:

*

*https://angular.io/docs/ts/latest/api/router/CanActivate-decorator.html
You could consider to use a load attribute that corresponds to an Observable. The latter would wait for the observable to receive events asynchronously to be displayed.
Here is the new content of your app component:
@Component({
  selector: 'my-app',
  template: `
    <tabs>
      <tab [tabTitle]="'Tab 1'" [load]="tabLoader">Tab 1 Content</tab>
      <tab tabTitle="Tab 2">Tab 2 Content</tab>
    </tabs>
  `,
  directives: [Tabs, Tab]
})
export class App {
  constructor() {
    this.name = 'Angular2';
    this.tabLoader = Observable.create((observer) => {
      setTimeout(() => {
        observer.next();
      }, 1000);
    });
  }
}

And the update within the Tabs component:
@Component({
  (...)
})
export class Tabs implements AfterContentInit {
  (...)

  displayTab(tab) {
    // deactivate all tabs
    this.tabs.toArray().forEach(tab => tab.active = false);

    // activate the tab the user has clicked on.
    tab.active = true;
  }

  selectTab(tab: Tab) {
    if (tab.load) {
      tab.load.subscribe(() => {
        this.displayTab(tab);
      });
    } else {
      this.displayTab(tab);
    }
  }
}

Here is the corresponding plunkr: https://plnkr.co/edit/d54CzKLrJirjkA6TDBC0?p=preview.
Hope it helps you,
Thierry

A: I used Chandermani's suggestion and set up my tabs with select function that set multiple booleans. I am using ngx-bootstrap for the tabs.  I then used *ngIf to turn on (and load) the tab contents:
 import { TabsModule } from 'ngx-bootstrap';

In the component....
 tab2Loaded: boolean = false;
 getTab2() {
    this.tab2Loaded= true;
 }

in the template...
<tab heading="tab2" (select)="getTab2()">
    <div *ngIf="tab2Loaded" class="container-fluid">
        <div class="row">
               ....etc
        </div>
    </div>
</tab>

Seems to work well in Angular 4, although , of course you will need to figure out when you want to load the data. If you want to lazy load it as well, make a component that you pass an id to, which gets its own data.


text:
Q: Is it possible to .split() plucked data in Rails? I'm trying to split data I'm plucking from a user's post. Currently, it only returns the entire string of data and I cannot break it down any further. I would like to break it down to single words.
["Hello everyone Hello\r\nWhat else can I say?\r\nHello again?"]
Extra thanks if you can get the whitespace removed!

A: Isn't #split with a regexp valid for you?
var = ["Hello everyone Hello\r\nWhat else can I say?\r\nHello again?"]
var.join.split(/\s+/) # => ["Hello", "everyone", "Hello", "What", "else", "can", "I", "say?", "Hello", "again?"]


text: Q: How to load custom post type field values in Wordpress from the database? I was reading this link about creating a custom post type in Wordpress. In the example, the field value box is text and the user can enter anything inside. I was wondering if it's possible to turn that field value box to a dropdown one, which values are loaded from the database. So for example, under 'Date', there is a dropdown box next to it with dates loaded from the database. Anyone know if it's possible? Thanks!


text:
Q: Setting the Coolbits in 20.04 without blowing X I'm trying to set the Coolbits in 20.04 in order to gain manual gpu fan control.
I edited the nvidia the X configuration file 10-nvidia.conf already present in /usr/share/X11:
Section "OutputClass"
    Identifier "nvidia"
    MatchDriver "nvidia-drm"
    Driver "nvidia"
    Option "AllowEmptyInitialConfiguration"
    Option "Coolbits" "28"
    ModulePath "/usr/lib/x86_64-linux-gnu/nvidia/xorg"
EndSection

Note that I just added Option "Coolbits" "28"
This didn't have any effect whatsoever.
What is the correct way of setting the coolbits in 20.04, given my configuration?

A: From my understanding, coolbits option should be in Section "Device" and not Section "OutputClass".
For only manual GPU fan control, you can set coolbits to 4. 28 also works, as it's 16+8+4 (each being a different bit in binary), giving you two more sets of options as well (I think one is overvoltage (16), and the other is to change performance settings per clock (8).

A: You're on the right track. It's Option "Coolbits" "13". Also, my conf file is xorg.conf at /ect/x11 (you can generate one with nvidia-xconfig). It looks like this:
# nvidia-xconfig: X configuration file generated by nvidia-xconfig
# nvidia-xconfig:  version 455.28

# nvidia-settings: X configuration file generated by nvidia-settings
# nvidia-settings:  version 440.82

# nvidia-xconfig: X configuration file generated by nvidia-xconfig
# nvidia-xconfig:  version 435.21

Section "ServerLayout"

    Identifier     "Layout0"
    Screen      0  "Screen0" 0 0
    InputDevice    "Keyboard0" "CoreKeyboard"
    InputDevice    "Mouse0" "CorePointer"
    Option         "Xinerama" "0"
EndSection

Section "Files"
EndSection

Section "InputDevice"

    # generated from default
    Identifier     "Mouse0"
    Driver         "mouse"
    Option         "Protocol" "auto"
    Option         "Device" "/dev/psaux"
    Option         "Emulate3Buttons" "no"
    Option         "ZAxisMapping" "4 5"
EndSection

Section "InputDevice"

    # generated from default
    Identifier     "Keyboard0"
    Driver         "kbd"
EndSection

Section "Monitor"

    Identifier     "Monitor0"
    VendorName     "Unknown"
    ModelName      "Microstep MSI G241"
    HorizSync       180.0 - 180.0
    VertRefresh     48.0 - 144.0
    Option         "DPMS"
EndSection

Section "Device"

    Identifier     "Device0"
    Driver         "nvidia"
    VendorName     "NVIDIA Corporation"
    BoardName      "GeForce GTX 1070"
    Option         "Coolbits" "13"
EndSection

Section "Screen"

    Identifier     "Screen0"
    Device         "Device0"
    Monitor        "Monitor0"
    DefaultDepth    24
    Option         "TripleBuffer" "On"
    Option         "Stereo" "0"
    Option         "nvidiaXineramaInfoOrder" "DFP-6"
    Option         "metamodes" "DP-4: 1920x1080_144 +0+0 {AllowGSYNCCompatible=On}, HDMI-0: 1920x1080_60 +1920+0"
    Option         "SLI" "Off"
    Option         "MultiGPU" "Off"
    Option         "BaseMosaic" "off"
    SubSection     "Display"
        Depth       24
    EndSubSection
EndSection

A: TLDR:
In /etc/X11/Xwrapper.config add:
allowed_users = anybody
needs_root_rights = yes

and change permissions:
chmod 2644 /etc/X11/Xwrapper.config

I got this working in a multi GPU config with 470.63.01 drivers. I thought that the problem was with Coolbits, but it actually was the Xwrapper.config (by the way, I set the Coolbits in /etc/X11/xorg.conf).
I'm not sure why the command:
sudo nvidia-xconfig -a --cool-bits=16 --allow-empty-initial-configuration

breaks your X. For me it worked, and X is behaving normally so far. I'm using the default GNOME and multiple desktops. I cannot assist you with this, however, because it was not the problem. This command added a bunch of lines to the /etc/X11/xorg.conf file, containing 3 entries for each GPU, that look like this:
Section "Monitor"
    Identifier     "Monitor1"
    VendorName     "Unknown"
    ModelName      "Unknown"
    Option         "DPMS"
EndSection

...

Section "Device"
    Identifier     "Device1"
    Driver         "nvidia"
    VendorName     "NVIDIA Corporation"
    BoardName      "NVIDIA GeForce xxxxxxx"
    BusID          "PCI:x:0:0"
EndSection

...

Section "Screen"
    Identifier     "Screen1"
    Device         "Device1"
    Monitor        "Monitor1"
    DefaultDepth    24
    Option         "AllowEmptyInitialConfiguration" "True"
    Option         "Coolbits" "16"
    SubSection     "Display"
        Depth       24
    EndSubSection
EndSection

Even after applying the command, the fan setting won't work unless the /etc/X11/Xwrapper.config file is edited. I had to add the following lines:
allowed_users = anybody
needs_root_rights = yes

Then save it and change the permissions:
chmod 2644 /etc/X11/Xwrapper.config

Adding these lines and rebooting did the trick for me. Without them, nvidia-settings just fails.
I found this solution here.

A: I'm using Ubuntu 20.04 with Nvidia Driver 470.63.01.

*

*In Terminal run:
sudo nano /etc/X11/xorg.conf

*Under Section "Device" add this line:
Option         "Coolbits" "4"

It should look something like this:

*Press and hold Ctrl and then O to write out (save) the file, then press and hold Ctrl and x to exit nano back to Terminal.

*Then in Terminal:
sudo nano /etc/X11/Xwrapper.config

*Add # to the following line (the # means it's just a comment now, not a parameter)
# allowed_users=console

*Add these two lines:
allowed_users = anybody
needs_root_rights = yes

*Ctrl + O to write out (save). Ctrl + x to exit nano.

*Then in Terminal:
sudo chmod 2644 /etc/X11/Xwrapper.config

*Reboot your computer.


text:
Q: Power Transformation of a Spectral Density Function There is a problem I have been trying to solve for a while. Let $X_t$ be a stationary (univariate) time series. The spectral density of the moving average process $$X_t=\sum^{\infty}_{j=-\infty}a_je_{t-j}$$ is
$$f_X(\omega)=\frac{\sigma^2}{2\pi}\left(\sum^{\infty}_{j=-\infty}a_je^{-ij\omega}\right)\left(\sum^{\infty}_{j=-\infty}a_je^{ij\omega}\right)$$
Now I want to know how to write $f^{p}_{X}(\omega)$ (square the function for example, i.e. $p=2$). Can someone please give me a hint as to how to do this. Thank you very much in advance.


text:
Q: Web Inspector on iPhone 6 simulator not showing the Elements tab Im using the iPhone 8 (iOS 13.5) and the iPhone 6 (iOS 12.4) Simulator on my MacBook Pro running Catalina, and the Web Inspector in my Safari desktop browser works great.  I can see the Network tab, the Elements tab, etc while using both simulators in the Web Inspector.  But when using the Web Inspector for the iPhone 6 (iOS 10.3.1) simulator, I cannot see the Network tab or the Elements tab.  I only see Sources, Audit and Console tabs.  I would like to be able to see the Network tab and Elements tab when running the Web Inspector on the iPhone 6 simulator (iOS 10.3.1).
Any ideas?

A: I had to install the Safari Technology Preview for everything to work properly.
https://developer.apple.com/safari/technology-preview/


text:
Q: How do you use discord.py hybrid commands? I have been using discord.py for commands like
@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content == "!test":
     # do actions

But how do I convert that to a hybrid command?
I tried using this but then the command wouldnt work
@commands.hybrid_command(name="shifttoggle", with_app_command=True)
async def shifttoggle(ctx):
  # actions

EDIT
Here I put more info.
When I typed /shifttoggle there was no prompt for it. So I typed !shifttoggle and nothing neither.


text:
Q: Flash AS3 - DisplayObject Argument Error - Trying to Remove and Add Loaded Content I am working with flash and as3 to try and get a photo loader/viewer/upload tool built. I am using file reference to handle the browse/load/upload functions. My current stage has 2 loader boxes that i load the user selected image into. I need to be able to remove the image though and re-select another if the user decides.
So on the file loaded event i have this code:
// Load Image into Editor Function.
function onMovieClipLoaderComplete(event:Event):void {
    var loadedContent:DisplayObject=event.target.content;
    currentLoader =event.target.loader as Loader;

    currentLoader.x=currentX;
    currentLoader.y=currentY;

    currentContent.buttonMode=true;
    currentContent.addChild(currentLoader);
    addChild(currentContent);

    currentLoader.mask = currentMask;

    addChild(replace_btn);
}

And on my replace button i have:
replace_btn.addEventListener(MouseEvent.CLICK, replaceImage);

function replaceImage(event:Event):void {
    currentContent.removeChild(currentLoader);
    removeChild(currentContent);
}

On pressing the replace button once it works fine but when i load another image into the loader - the next time i press the replace button (or any subsequent time) i get the following argument error in my flash as3 file:
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/removeChild()
at MethodInfo-13()

Does anyone know what this means? It's odd that it only happens on the second time onwards not at first. I thought that if i have:
currentContent.addChild(currentLoader); addChild(currentContent);
on load and then just
currentContent.removeChild(currentLoader); removeChild(currentContent);
on the replace function it would work?
Full as3 code is shown below if that also helps
I have only been learning flash for 3-4 months so please go easy on me and i apologise if my code is not done in the best way! :)
Lauren
// Set Start Up Values.
var image1_loader:Loader = new Loader();
var image1_content:Sprite = new Sprite();
var image1_mask:Sprite = new Sprite(); image1_mask.graphics.beginFill(0x000000,1);         image1_mask.graphics.drawRect(54, 59, 330, 330); image1_mask.graphics.endFill();

var image2_loader:Loader = new Loader();
var image2_content:Sprite = new Sprite();
var image2_mask:Sprite = new Sprite(); image2_mask.graphics.beginFill(0x000000,1);     image2_mask.graphics.drawRect(384, 59, 330, 165); image2_mask.graphics.endFill();

var currentBtn;
var currentLoader;
var currentContent;
var currentMask;
var currentX;
var currentY;

replace_btn.visible=false;

// Define FileReference.
 var canvasImage:FileReference;

// Image Buttons Function.
image1_btn.addEventListener(MouseEvent.CLICK, start_fileRef);
image2_btn.addEventListener(MouseEvent.CLICK, start_fileRef);

image1_content.addEventListener(MouseEvent.MOUSE_DOWN, setCurrentSelection);
image2_content.addEventListener(MouseEvent.MOUSE_DOWN, setCurrentSelection);

function setCurrentSelection(e:MouseEvent):void {
if (e.currentTarget===image1_content){currentContent=image1_content;}
if (e.currentTarget===image2_content){currentContent=image2_content;}
}

// Browse File Function.
function start_fileRef(e:MouseEvent):void {
trace("onBrowse");
if (e.target===image1_btn){currentBtn=image1_btn; currentLoader=image1_loader;     currentContent=image1_content; currentMask=image1_mask; currentX=54; currentY=59;}
if (e.target===image2_btn){currentBtn=image2_btn; currentLoader=image2_loader; currentContent=image2_content; currentMask=image2_mask; currentX=384; currentY=59;}

canvasImage=new FileReference();
canvasImage.addEventListener(Event.SELECT, onFileSelected);
var imageTypeFilter:FileFilter = new FileFilter("JPG/PNG Files","*.jpeg; *.jpg;*.gif;*.png");
canvasImage.browse([imageTypeFilter]);
}

// Selected File Function.
function onFileSelected(event:Event):void {
trace("onFileSelected");
canvasImage.addEventListener(Event.COMPLETE, onFileLoaded);
canvasImage.addEventListener(ProgressEvent.PROGRESS, onProgress);

var canvasImageName = canvasImage.name;
canvasImage.load();
}

// File Progress Function.
function onProgress(event:ProgressEvent):void {
var percentLoaded:Number=event.bytesLoaded/event.bytesTotal*100;
trace("loaded: "+percentLoaded+"%");
}

// File Loaded Function.
function onFileLoaded(event:Event):void {
var fileReference:FileReference=event.target as FileReference;

var data:ByteArray=fileReference["data"];
trace("File loaded");
var movieClipLoader:Loader=new Loader();
movieClipLoader.loadBytes(data);
movieClipLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onMovieClipLoaderComplete);

canvasImage.removeEventListener(Event.COMPLETE, onFileLoaded);
}

// Load Image into Editor Function.
function onMovieClipLoaderComplete(event:Event):void {
var loadedContent:DisplayObject=event.target.content;
currentLoader =event.target.loader as Loader;

currentLoader.x=currentX;
currentLoader.y=currentY;

currentContent.buttonMode=true;
currentContent.addChild(currentLoader);
addChild(currentContent);

currentLoader.mask = currentMask;

addChild(replace_btn);

// Reveal Retry Button over Hover Function //
currentContent.addEventListener(MouseEvent.ROLL_OVER, hover);
replace_btn.addEventListener(MouseEvent.ROLL_OVER, hover);
currentContent.addEventListener(MouseEvent.ROLL_OUT, unhover);
replace_btn.addEventListener(MouseEvent.ROLL_OUT, unhover);

function hover(event:Event):void {
    replace_btn.visible=true;
}
function unhover(event:Event):void {
    replace_btn.visible=false;
}

replace_btn.addEventListener(MouseEvent.CLICK, replaceImage);

function replaceImage(event:Event):void {
    currentContent.removeChild(currentLoader);
    removeChild(currentContent);
}

}

A: This currentContent.removeChild(currentLoader); should be fine, but this  removeChild(currentContent); is most likely the problem source. Because you added it as currentContent.addChild(currentLoader), you must remove the container var (currentContent) with it as well.


text:
Q: Adding components to JPanel, No Change on screen I am doing a small animation/xml file creation editor for a private game i am making.
I have a JPanel where I add some custom components, but I never see any change.
Custom Component:
public class BasicProprety extends JPanel {
String key;
String value;

    public BasicProprety(String k, String v) {
        key = k;
        value = v;
        JTextField keyField = new JTextField(k);
        JTextField valueField = new JTextField(v);
        valueField.setVisible(true);
        keyField.setVisible(true);
        this.add(keyField);
        this.add(valueField);
        this.setVisible(true);
    }
}

I use a static method to refresh properties of the current frame :
 public static void refreshFrameProperties() {
    Frame currentFrame = DataBank.getCurrentInstance().getCurrentFrameObj();
    BasicProprety millisecs = new BasicProprety("millisecondsTillNextFrame", String.valueOf(currentFrame.getMillisecondsToNextFrame()));
    BasicProprety offsetX = new BasicProprety("offsetX", String.valueOf(currentFrame.getOffset().x));
    BasicProprety offsetY = new BasicProprety("offsetY", String.valueOf(currentFrame.getOffset().y));
    BasicProprety sizeX = new BasicProprety("sizeX", String.valueOf(currentFrame.getSize().x));
    BasicProprety sizeY = new BasicProprety("sizeY", String.valueOf(currentFrame.getSize().y));
    sizeX.revalidate();
    sizeY.revalidate();
    offsetY.revalidate();
    offsetX.revalidate();
    millisecs.revalidate();
    sizeX.repaint();
    sizeY.repaint();
    offsetY.repaint();
    offsetX.repaint();
    millisecs.repaint();
    ArrayList<BasicProprety> basicList = new ArrayList<BasicProprety>();
    for (int i = 0; i < mainInterface.getProperties().getComponentCount(); i++) {
        if (mainInterface.getProperties().getComponent(i) instanceof BasicProprety)
            basicList.add((BasicProprety)mainInterface.getProperties().getComponent(i));
    }
    for (BasicProprety bp : basicList) {
        mainInterface.getProperties().remove(bp);
    }
    mainInterface.getProperties().revalidate();
    mainInterface.getProperties().repaint();
    System.out.println("REMOVED: "+mainInterface.getProperties().getComponentCount());
    mainInterface.getProperties().getLayout().addLayoutComponent("TEST", sizeY);
    mainInterface.getProperties().add(millisecs);
    mainInterface.getProperties().add(offsetX);
    mainInterface.getProperties().add(offsetY);
    mainInterface.getProperties().add(sizeX);
    mainInterface.getProperties().add(sizeY);
    /*Random r = new Random();
    mainInterface.getProperties().setBackground(new Color(r.nextInt()));*/
    mainInterface.getProperties().revalidate();
    mainInterface.getProperties().repaint();
    mainInterface.getProperties().setVisible(true);
    System.out.println("NO: "+mainInterface.getProperties().getComponentCount());

}

My component is created with the netbeans interface editor and this is the creation code:
    properties = new javax.swing.JPanel();
    org.jdesktop.layout.GroupLayout propertiesLayout = new org.jdesktop.layout.GroupLayout(properties);
    properties.setLayout(propertiesLayout);
    propertiesLayout.setHorizontalGroup(
        propertiesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
        .add(0, 243, Short.MAX_VALUE)
    );
    propertiesLayout.setVerticalGroup(
        propertiesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
        .add(0, 386, Short.MAX_VALUE)
    );

A: They are propably added, but not to your Component but rather the contentPane. JPanel.getContentPane() which is the one and only component of your JPanel.
Not sure though.

A: The error in the component count is that you're checking mainInterface.getComponentCount(), rather than mainInterface.getProperties().getComponentCount(). Presumably mainInterface only contains your JPanel?
You can avoid similar errors to these by using a local variable, e.g.
final JPanel properties = mainInterface.getProperties();
...
System.out.println("number of properties' components: "
                       + properties.getComponentCount());

By the way, you can simplify the following loop...
ArrayList<BasicProprety> basicList = new ArrayList<BasicProprety>();
for (int i = 0; i < mainInterface.getProperties().getComponentCount(); i++) {
    if (mainInterface.getProperties().getComponent(i) instanceof BasicProprety)
        basicList.add((BasicProprety)mainInterface.getProperties().getComponent(i));
}
for (BasicProprety bp : basicList) {
    mainInterface.getProperties().remove(bp);
}

... into this:
for (Component component : properties.getComponents()) {
  if (component instanceof BasicProperty) {
    properties.remove(component);
  }
}

Make sure all of your UI modifications are done in the context of the event dispatch thread.
(PS does anyone else think Container should expose an Iterator<Component> somehow?)


text:
Q: python: specify return value of attribute of mocked module I have a module ex which has multiple attributes and another module that uses these attributes like this
import ex
def use_ex(attr):
    z = getattr(ex,attr)
    #Do something with z

In my test file, I mock the ex as I cannot import it in the test environment.
sys.modules['ex'] = Mock()

How do I specify the return_value of ex.attr when I write the test for use_ex?

A: You can specify mock return values like this :
return_value = whatyouwant
my_mock = Mock()
my_mock.return_value = return_value
sys.modules['ex'] = my_mock


text:
Q: Removing an unwanted constraint in proof of Fenchel-Rockafellar theorem I am trying to prove the Fenchel-Rockafellar theorem, that
$$ \inf_x \left[ f(x) + g(Ax) \right] = - \inf_\beta \left[ f^\star(A^T \beta) + g^\star(-\beta) \right] $$
under the usual regularity assumptions. The general outline of my proof should work, but I run into problems at the last step:

*

*Argue from Fenchel-Young inequality that $\inf_x \left( f(x) + g(Ax) \right) = -(f + g\circ A)^\star(0)$.

*Compute $(f + g \circ A)^\star$ as the infimal convolution of $f^\star$ and $(g \circ A)^\star$, which gives
$$ \inf_x \left( f(x) + g(Ax) \right) = - \inf_{\beta} \left( f^\star(\beta) + (g \circ A)^\star(-\beta) \right)$$

*Plug in the expression for $(g \circ A)^\star(\beta)$ and simplify.

The problem is that I get
$$ (g \circ A)^\star(\beta) = \begin{cases} \infty & \beta \not\in \mathcal{R}(A^T) \\
( g + I_{\mathcal{R}(A)} )^\star(u) & \beta = A^T u \end{cases}, $$
and computing the infimal convolution this can be written as
$$ (g \circ A)^\star(\beta) = \begin{cases} \infty & \beta \not\in \mathcal{R}(A^T) \\
\inf_{\substack{u=u_1 + u_2 \\ u_2 \in \mathcal{R}(A)^\perp}} g^\star(u_1) & \beta = A^T u \end{cases}. $$
When I plug this back in step 3, I get
$$ \inf_x \left( f(x) + g(Ax) \right) = - \inf_{\beta \in \mathcal{R}(A)} \left( f^\star(A^T \beta) + g^\star(-\beta) \right),$$
so I have an unwanted constraint on the right-hand side of the equality.
It may be that my calculations are wrong, but I've spent hours on them now, so I wonder if the issue is that the constraint is redundant?


text:
Q: Tensorflow: Understanding tf.contrib.layers.instance_norm graph I'm trying to understand tf.contrib.layers.instance_norm graph:
according to this graph:
x = gamma * (x + x_mean) / x_std - beta

but it should be
x = gamma * (x - x_mean) / x_std + beta

I'm missing something?

A: I get it, it's x = gamma * (x - x_mean) / x_std + beta as it should be because in Sub order is beta - 'Sub op input'.


text:
Q: Calculating the minimum size of some intersection (Olympiad problem)... any hints or solution? Please PROBLEM:
A person has a coat of area $1$ composed of five possibly overlapping patches. The area of each patch is at least $\frac{1}{2}$. Prove that there are two patches whose overlap has area at least $\frac{1}{5}$.
IDEAS THAT HAVE COME TO MY MIND:
-Using the inclusion-exclusion principle to have an equality involving the intersections of the patches
-Trying to argue by contradiction (assuming the intersection of any two is less than $\frac{1}{5}$). I found out  that the sum of the areas of the patches must be between $\frac{5}{2}$ and $\frac{6}{2}$.

A: (Note: this argument is reconstructed from writing the problem as a linear program in $2^5$ variables, solving the dual, and then interpreting the dual solution.)

Define $P_i$ for $1 \le i \le 5$ to be the size of patch $i$, and $P_{ij}$ for $1 \le i < j \le 5$ to be the size of the overlap between patches $i$ and $j$. We measure in units of coats, so that $\frac12$ is half the coat's area.
Let $z = \max_{i,j} P_{ij}$, the size of the largest overlap. Since $P_i \ge \frac12$ for all $i$, and $P_{ij} \le z$ for all $i$ and $j$, we have $$\frac15 \sum_i P_i - \frac1{10} \sum_{i<j} P_{ij} \ge \frac12 - z.\tag{$\star$}$$
Now we look at how much each bit of coat contributes to the left-hand side of $(\star)$. (By "bit of coat" we can mean a part of the coat specified by which patches it's in.)
If the bit of coat is in $k$ patches, it's contained in $\binom{k}{2}$ overlaps, so it contributes $\frac15 k - \frac1{10}\binom{k}{2} = \frac{k(5-k)}{20}$ of its area, which is maximized at $k=2$ or $k=3$ by $\frac{3}{10}$. If the left-hand side of $(\star)$ counts each bit of coat with a multiplier of at most $\frac{3}{10}$, then its value can be at most $\frac{3}{10}$ of the coat's total area.
Therefore $(\star)$ tells us that $\frac{3}{10} \ge \frac12 - z$, or $z \ge \frac15$, and we're done. (In fact, the average size of an overlap, not just the maximum, must be at least $\frac15$.)

The primal solution to the same linear program shows that this bound is tight. Divide the coat into $10$ regions $\{R_1, R_2, \dots, R_{10}\}$ of equal size. Let
\begin{align}
 A &= R_1 \cup R_2 \cup R_6 \cup R_7 \cup R_8 \\
 B &= R_3 \cup R_4 \cup R_6 \cup R_7 \cup R_9 \\
 C &= R_1 \cup R_3 \cup R_8 \cup R_9 \cup R_{10} \\
 D &= R_4 \cup R_5 \cup R_6 \cup R_8 \cup R_{10} \\
 E &= R_2 \cup R_5 \cup R_7 \cup R_9 \cup R_{10}
\end{align}
be the five patches, and you can check that each patch has area $\frac12$ but intersects with every other patch in at two regions, so each overlap has area $\frac15$.


text:
Q: In a SwiftUI lifecycle app, where exactly should I register a CoreData transformerValue? I'm trying to follow this tutorial:
https://www.avanderlee.com/swift/valuetransformer-core-data/
But I'm stumped on where (and how!) exactly to use
UIColorValueTransformer.register()

The author says to do it before setting up the persistent container... and I'm think I'm doing that here:
import SwiftUI

@main
struct ContactApp: App {

    let persistenceController = PersistenceController.shared

    var body: some Scene {
        WindowGroup {
            MainTabView()
                .environment(\.managedObjectContext, persistenceController.container.viewContext)
        }
    }
}

But I'm at a loss of what exactly to write, or if this is the right place. Maybe I should be doing it in a different place?

A: Put it into init, like
class PersistenceController {
   static let shared = PersistenceController()

   init() {
      UIColorValueTransformer.register()       // << here !!

      // ... other init code
   }

   // ... other code
}


text:
Q: "Fatal error: Using $this when not in object context" but code IS in object context I'm getting the old familiar "Fatal error: Using $this when not in object context" referring to $this->test = 'test'; in the following class:
class Example {
    public $test;
    public function index() {
        $this->test = 'test';
    }
}

The class method is called via call_user_func_array(array('example', 'index'), $params);. I can only assume that call_user_func_array has for some reason decided to call the index method as static e.g. example::index()? However I haven't figured out a fix for this and oddly I've not had a problem with it until recently.

A: This works:
$obj = new Example();
call_user_func_array(array($obj, 'index'), $params);

Your code basically does:
Example::index($params);

which calls index statically, which you correctly assumed.


text:
Q: Tag score incorrectly lowered, tag badge lost I had more than 100 points on algorithm at SO, and bronze badge. Suddenly today I have only 90 pts on the tag and badge is lost! This must be a bug, because:

*

*when I filter my answers under this tag, the sum of the scores is 103! And the newest scored answer is from last year.

*Data Explorer is from June 25th and it is still correct: see:

*

*https://data.stackexchange.com/stackoverflow/query/122332/my-score-on-the-algorithm-tag

*https://data.stackexchange.com/stackoverflow/query/122334/my-answers-on-the-algorithm-tag
My reputation is intact (or at least I have not observed lowering of it).

A: Largest rectangular sub matrix with the same number was converted to a community wiki because you edited it too many times.

Since Community wiki's don't count towards tag badges and that question was worth 13 upvotes. Your 103 went down by 13 to 90. So the amount is correct.
You might be able uncommunity wiki it by flagging your question for moderator attention and explaining you want it undone.
According to What are tag badges? How do they work?

A tag score is basically the combined total of all the upvotes (+1)
  and downvotes (-1) you've accumulated on answers under that specific
  tag (votes on questions do not count). As well, posts which are in
  community wiki status or that have been deleted do not count towards
  your tag score. Tag scores are only recalculated once daily, at
  03:00 UTC.


text:
Q: Using text files in Visual Studio Project I am making a console program in VS2010.  The structure of as layed out in the solution explorer is Project file, Properties folder, References, and Program.cs.
I want to make use of a text file for reading/writing.  What is the correct way of adding this file to the project? If I just do StreamWriter sw = new StreamWriter("maze.txt") then it'll create the file in the output folders (bin/debug or bin/release).  But it won't show up in the solution explorer.
Now if I right-click on the solution explorer and Add New Item, I can create a text file in the root project folder (same level as Program.cs).  This will show up in the solution explorer.
Is there a way for me to access this newly created file? Other than doing something like StreamWriter sw = new StreamWriter("../../maze.txt") by specifying the path to be two parents up?
How am I supposed to manage external files in a Visual Studio console applicatoin? In a WinForms application, there's a resources folder where I can add these things and a Resources.resx file to manage it.  I can access it with Properties.Resources.someres.

A: If you want to create a file at design time and have it included in your bin folder then add the text file, go to properties, and select "copy always" or "copy if newer" for the copy property.
Note that this will copy the file from the project to the bin folder, but changes in the bin folder when debugging won't be copied up into the project itself.  I doubt you want the program to interact with the version of the file in the project itself.  If you do something like that then anytime you run the program outside of VS (i.e. when you copy it to the machine of an actual user) it won't work.

A: As for your resources question, you can still use resources. Just right-click and "Add"  -> "New Item" (aka keyboard shortcut Ctrl+Shift+A) and choose "Resources File".  You could also set the text file to be an Embedded Resource.  MSDN has a lot of information on using resources on their Managing Application Resources page.

A: You can still embed resources to a console application. I've used this technique in quick apps so we don't need a installer or deploy dependencies such as these type of files. This question discusses a similar topic.


text:
Q: Return several rows in python from Excel Table I was wondering if I can return several rows of an excel sheet that where some columns consist of a unique string. And then I want to export them into a CSV.
I was considering openpyxl but am not getting too far.
If my Excel looks like that:
Sample
I would e.g. search for ID2 and return all rows
ID2,1,ping
ID2,2,pong

from openpyxl import Workbook
import openpyxl

file = "test.xlsx"
wb = openpyxl.load_workbook(file, read_only=True)
ws = wb.active

for row in ws.iter_rows("A"):
    for cell in row:
        if cell.value == "ID2":
            print(ws.cell(row=cell.row, column=1,2,3).value)

Can anyone help me?

A: Try using pandas pd.read_excel() and pd.to_csv(), for example:
import pandas as pd
df = pd.read_excel('/file/path/excel.xslx')
df_filtered = df[df['id_column'] == 'ID1']  # returns df with only rows where 'id_column' is 'ID1'
df_filtered.to_csv('/file/path/output.csv')

Would export a csv with only rows where your 'id_column' is equal to 'ID1'.


text:
Q: Product Key for Etrade Individual Development is Returning 401 Client Error So a follow up on this question, where I still have the same code: to start working with some live data, I switched from sandbox to individual key, and started getting this error with code that did work in sandbox mode:
HTTPError: 401 Client Error: Unauthorized for url: https://apisb.etrade.com/v1/market/optionexpiredate?symbol=NFLX&expiryType=ALL
Here's the authentication code, in case I messed up here:
consumer_key = "[key, double checked]"
consumer_secret = "[secret, double checked]"

def authenticate():
    #get the auth UIL
    oauth = pyetrade.ETradeOAuth(consumer_key, consumer_secret)
    oauth.setToken(consumer_key)
    oauth.setTokenSecret(consumer_secret)
    print(oauth.get_request_token())

    #ask the user to put the verification code in to get tokens
    verifier_code = input("Enter verification code: ")
    global tokens
    tokens = oauth.get_access_token(verifier_code)
    print(tokens)

    #Setting up the object used for Access Management
    global authManager
    authManager = pyetrade.authorization.ETradeAccessManager(
        consumer_key,
        consumer_secret,
        tokens['oauth_token'],
        tokens['oauth_token_secret']
    )

And this is the code that returns the error:
try:
    q = market.get_option_expire_date(thisSymbol,resp_format='xml')
    expiration_dates = option_expire_dates_from_xml(q)
except:
    raise Exception("Rip, get date not working")

I'm not sure why this is happening :( any help would be super appreciated!


text:
Q: How to increase the font size of the printed line by using python script? I have wrote python code where I am displaying a line on output screen.
#!/pro/mobile/Linux/bin/python

print '\033[1m \033[91m \033[4m' +  "SELECTED OPTION IS FOR INSERTING\n" + '\033[0m'
print "Please enter valid input\n"

Here I have used '\033[1m \033[91m \033[4m' for making the line bold, change the color of line to red and underline. These are all ok and it works fine.
But here i am unable to increase the font size of the line. I have to increase the of first line which will get displayed on same terminal, second line will be displayed in default font size of the terminal.
Please help me to increase the font size of the line.


text:
Q: Tate cohomology for group algebras Let $A=kG$ be a group algebra with a finite group  $G$ and a field $k$.
Let $T^i(M,N)= \underline{Hom_A}(\Omega^i(M),N)$ be the $i$-th Tate cohomology group. Note $T^i(M,N)= Ext_A^i(M,N)$ in case $i \geq 1$.

Question: Do we have $dim(T^i(M,M)) \geq dim(Ext_A^1(M,M))$?

This is true in case $A$ is representation-finite.


text:
Q: Export firebase real-time database collection to Bigquery is any way to Export firebase real-time database collection to bigquery?
firestore-bigquery-export@0.1.13 extension option is available for the firestore database.

A: There is no built-in or pre-built extension that I know of to provide a similar export to BigQuery from the Firebase Realtime Database. It sounds like a reasonable feature request though, so I recommend filing it here.
In the meantime, keep in mind that all Firebase Extensions are open-source, so you can take the code for the firestore-bigquery-export extension and use that to either create your own extension for RTDB, or otherwise set up an export.


text:
Q: IOS : Tabbar item click again and again it is double Tab bar button item size I implemented tab bar with custom icon size.i find many solution from stack-overflow but i didn't getting any perfect solution for this issue.
Issue : when i click tabbar item again and again it's size double every time. and after click other tab it's size is  same as orignal size.
See this Link For Issue : Screen Recording
My Code :
import UIKit

class customTabBar: UITabBarController {

override func viewDidLoad() {
    super.viewDidLoad()

    let tabHome2 = self.tabBar.items![2]
    tabHome2.image = UIImage(named: "ic_pick")?.withRenderingMode(.alwaysOriginal)
    tabHome2.selectedImage = UIImage(named: "ic_pick")?.withRenderingMode(.alwaysOriginal)
    tabHome2.imageInsets = UIEdgeInsets(top: -40, left: -10, bottom: 0, right: -10)

}

}
My Design Requirement :

Thanks In Advance.

A: Set Icons in assets. If you are using circular icons for tab bar item you should create following sizes for portrait mode:

*

*@1x : about 25 x 25 (max: 48 x 32)

*@2x : about 50 x 50 (max: 96 x 64)

*@3x : about 75 x 75 (max: 144 x 96)
Also you can refer this : custom-icons

Set image inset from the property of Tabbar item.
  Image

A: Your image insets are not balanced.
Try:

tabHome2.imageInsets = UIEdgeInsets(top: -20, left: -10, bottom: 20,
  right: 10)

*

*Try to reproduce bug.

*Bug is gone.

*Find the right values. (Image edit might be needed.)

*Open a beer.


text:
Q: Why does this output seem non-deterministic? (Is it the sprintf, printf, or syntax of hexadecimal literals?) tl;dr
Why do I get different output every time I run this code (Ideone):
#include <iostream>
#include <stdio.h>
using namespace std;

int main() {

    const char* _user = "FOO";
    const char* _password = "BAR";

    char login[21];
    sprintf(login,
        "\x15\x00\x01%-8s%-10s",
        _user,
        _password);

    for (int i = 0; i < 21; i++) {
        printf(" %02x", login[i] & 0xff);
    }

    return 0;
}

But not this code (Ideone):
#include <iostream>
#include <stdio.h>
using namespace std;

int main() {

    const char* _user = "FOO";
    const char* _password = "BAR";
    const char* _session = "ABCDEFGHIJ";
    int _expectedSeq = 123;

    char login[38];
    sprintf(login,
            "L%-6s%-10s%10s%10d\xA",
            _user,
            _password,
            _session,
            _expectedSeq);

    for (int i = 0; i < 38; i++) {
        printf(" %02x", login[i] & 0xff);
    }

    return 0;
}

Question
Deep in our application code, I came across this:
char login[38];
sprintf(login,
        "L%-6s%-10s%10s%10d\xA",
        _user,
        _password,
        _session,
        _expectedSeq);

Now, I need to write a (simpler) variant of this code:
char login[21];
sprintf(login,
       "\x15\x00\x01%-8s%-10s",
       _user,
       _password);

Somehow, this doesn't work! What's weird is that the latter produces different results every time.

Thoughts

*

*The former example only has a hex literal at the end. Is this masking the issue in the former's case?

*Or, am I actually messing up my debug output, printf? (By the way, I got the & 0xff thing from Printing hexadecimal characters in C.)

*Could it have something to do with using char instead of unsigned char? But then, why does the former case work?

A: The problem is that your string literal has an embedded NUL byte, and that marks the end of the string as far as sprintf is concerned. So your call is identical to:
sprintf(login,
       "\x15",
       _user,
       _password);

And that writes into the login array only two bytes: 0x15 0x00.
There are several approaches to solve this mixing of bytes and characters. My choice would be something along the lines of:
memcpy(login, "\x15\x00\x01", 3);
sprintf(login + 3,
   "%-8s%-10s",
   _user,
   _password);

The call to memcpy takes as parameter the number of bytes, so it is immune to the embedded NUL problem.
But note that sprintf automaticall adds a NUL byte at the end of the output string, so you actually need 22 bytes: 3 + 8 + 10 + 1 = 22:
char login[22];

A: Your issue is that second format string contains a null character (\x00) which terminates it prematurely. Change the string to use %c instead and have a null character printed there.