text:
Q: Homepage url redirect when logged in users type it in I want users for my site to be redirected when they are logged in. Example: Homepage for logged out users is www.test.com and when they are logged in i want them to be redirected to a different URL when they go to www.test.com, is there any way i can achieve this with some code?

A: Solution is using login_redirect hook
if you want to set redirect url role wise then use below code please.
Open theme functions.php file
Copy and paste the following code:
Please modify code as per your role wise.
function rl_login_redirect( $redirect_to, $request, $user ) {
    //is there a user to check?
    global $user;
    if ( isset( $user->roles ) && is_array( $user->roles ) ) {

        if ( in_array( 'author', $user->roles ) ) {
            // enter url which you link redirect for author role users. default is home page.
            return home_url();
        } else {
            return home_url();
        }
    } else {
        return $redirect_to;
    }
}
add_filter( 'login_redirect', 'rl_login_redirect', 10, 3 );

if you want to set redirect url for all users then use below code please.
function rl_user_default_page() {
  return '/new-page-url';
}

add_filter('login_redirect', 'rl_user_default_page');


text:
Q: Can a Failover Cluster CSV volume be owned by two clusters during the upgrade process? We have a 2-node Hyper-V failover cluster running Windows Server 2012 (R1) with about 60 virtual machines running; upgrading to Windows Server 2016 RTM.  Since we aren't on 2012R2, we can't use the new rolling cluster upgrade process.
So, during the upgrade process, at the point where one of the two nodes is now running 2016, will I be able to add the CSV volumes that are still attached to the 2012 server, at the same time?

A: There is no upgrade path from Windows 2012 Cluster to Windows 2016 Cluster.
You will have to do a migration. Which in effect is:

*

*Create a new cluster with one node on 2016

*Migrate services (including VM's and their related storage

*Once all is migrated, add in nodes

This means that a CSV volume/disk can only be on one cluster, and one cluster only. As you are migrating the answer to your question is; no the CSV volume/disk can only be accessible by either the node(s) of the old Windows 2012 cluster or the new Windows 2016 cluster node(s), but certainly not both.
There are migration processes defined by Microsoft, here
However for 2016 it lists:

Updated migration guides for Windows Server 2016 are under
  development. Check back at this location for updates as they become
  available. In many cases, the steps in the Windows Server 2012 R2
  migration guides are still relevant for Windows Server 2016.

This won't detail a step by step process for what you are asking. There is a migration guide how to migrate from 2012 to 2012-R2 Cluster, this guide is largely valid, but you will have to adapt it to suite your migration from 2012 Cluster to 2016 Cluster. This guide can be found here
Furthermore, I would certainly not do this the first time on a production cluster, I would find a way to test this process. You could consider creating a Windows 2012 test cluster with VM's, then upgrade this test cluster to 2016 using the adapted process as indicated above. This would allow you to validate and fine-tune your process.
HTH, Edwin.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Como selecionar um elemento em uma seleção do jQuery Por exemplo, tenho o seguinte código:
var $els = $('elementos'); // cerca de 8 elementos selecionados

Então desse grupo de elementos, quero um elemento que tenha a classe active. Tentei algo como:
$els.find('.active');

Porém não deu certo, porque o método find procura por elementos filhos. Não tentei o método siblings pois tenho mais de um elemento selecionado e eles não são necessariamente "irmãos".
Como encontrar um determinado elemento neste grupo e depois poder navegar entre eles como next() e prev(), é possível?

A: Nesse caso você usa filter:
var $els = $('elementos');
var $el = $els.filter('.active');

Agora, se você navegar com next e prev a partir do $el, vai estar navegando pelos irmãos dele no DOM, não na sua lista original $els.

A: Complementando a resposta, sobre como navegar entre os elementos:
Basta:

*

*Pegar o objeto anterior: $el.prevObject $el.end() (como mencionado pelo @bfavaretto)

*Pegar o índice do objeto selecionado: $els.index($el)

*Navegar entre eles: $el.prevObject[$els.index($el)-1] ou $el.prevObject[$els.index($el)+1]

*Navegar entre eles: $el.end()[$els.index($el)-1] ou $el.end()[$els.index($el)+1]

$els = $('li');
$el = $els.filter('.active');

$prev = $( $el.end()[$els.index($el)-1] );
$next = $( $el.end()[$els.index($el)+1] );

$('.prev').text('Anterior: ' + $prev.text() );
$('.el').text( 'Ativo: '     +  $el.text()  );
$('.next').text( 'Próximo: ' + $next.text() );
.active{
   color: #2376D0;
}

Item 1 1

Item 1 2

Item 1 3

Item 1 4

Item 1 5

Item 2 1

Item 2 2

Item 2 3

Item 2 4

Item 2 5


text:
Q: Проверка инпутов на цифры и буквы на чистом js У каждого инпута есть атрибут data-rule устанавливающий правила проверки на цифры и буквы. Задача в том чтобы при не верном заполнение инпута вылезало сообщение либо "Введите буквы" либо "Введите цифры" и работало автоматом без указания номера коллекции элемента ([0], [1] и тд). И соответственно сообщение об ошибке исчезало при исправление. Это основной вопрос.
И ещё один, возможно ли в эту функцию вставить валидацию на пустоту строки инпута?
Нужен код на чистом js.
<form>

            <input type="text" data-rule="number">

            <input type="text" data-rule="number">

            <input type="text" data-rule="string">

        <button>Отправить</button>
</form>

function checkInputs() {
    let inputs = document.querySelectorAll('input[data-rule]');

    for(let input of inputs){
        input.addEventListener('blur', function(){
            let result = document.getElementsByClassName('result');
            let rule = this.dataset.rule;
            let value = this.value;
            let check;

            switch(rule){
                case 'number':
                check = /^\d+$/.test(value);
                break;

                case 'string':
                check = /^[a-zа-яё]+$/i.test(value);
                break;
            }

            if (check){
                this.classList.remove('invalid')
                this.classList.add('valid')
                result[0].remove()
                result[2].remove()
            }
            else{
                this.classList.remove('valid')
                this.classList.add('invalid')
                result[0].innerHTML= 'Введите цифры'
                result[2].innerHTML= 'Введите буквы'
            }
        });
    }
}

checkInputs()

.valid {
    border: 1px solid green;
}

.invalid {
    border: 1px solid red;
}

form {
    width: 10%;
    display:flex;
    flex-flow: column nowrap;
}

A:

let check = {
  number: {err: 'Введите цифры!', reg: /^\d+$/},
  string: {err: 'Введите буквы!', reg: /^[a-zа-яё]+$/i},
}

function checkInputs() {
  let inputs = document.querySelectorAll('input[data-rule]');
  let result = document.querySelectorAll('.result');

  for ( let i = 0; i < inputs.length; i++ ) {
    inputs[i].addEventListener('input', function() {
      let rule = this.dataset.rule;
      let value = this.value;

      if( check[rule].reg.test( value ) && value ){
        // Если value - пустая строка, это false
        this.classList.remove('invalid');
        this.classList.add('valid');
        result[i].innerText = "";
        // Номер результата чудесным образом совпадает с номером инпута!)
      } else {
        this.classList.remove('valid');
        this.classList.add('invalid');
        result[i].innerText = check[rule].err;
      }
    });

    inputs[i].addEventListener('blur', function() {
      if( !this.value ) {
        result[i].innerText = "Поле не может быть пустым!";
      }
    });
  }
}

checkInputs();
.one { margin: 5px; }
input[data-rule] { outline: none; }
.valid { border: 1px solid green; }
.invalid { border: 1px solid red; }

  <input type="text" data-rule="number">

  <input type="text" data-rule="number">

  <input type="text" data-rule="string">


text:
Q: What is the code behind the knit html button in rstudio 0.98.501? I followed the Rstudio advice to Customize Markdown Rendering. And created an .Rprofile file at the root of the project directory that overrides default markdown rendering options. But there seems to be an issue with equation rendering (see my earlier question).
What is the code behind the "knit html" button in RSTUDIO Version 0.98.501 ?

A: it's running rmarkdown::render('your_file.Rmd')
by default it will create an output file with the same name as your .Rmd file and in the same directory.  If you checkout the documentation [1]  for the code, you'll see you can actually specify output_file and output_dir for different file names and different directory, respectively.
[1] http://cran.r-project.org/web/packages/rmarkdown/


text:
Q: How to connect the signal and slot in multi-thread program? The mainwindow.cpp:
#include "ui_mainwindow.h"
#include <QtCore>

/* ****** Thread part ****** */
myThread::myThread(QObject *parent)
    : QThread(parent)
{
}

void myThread::run()
{
    while(1){
        qDebug("thread one----------");
        emit threadSignal1();
        usleep(100000);
    }
    exec();
}

myThread2::myThread2(QObject *parent)
    : QThread(parent)
{
}

void myThread2::run()
{
    while(1){
        qDebug("thread two");
        emit threadSignal2();
        usleep(100000);
    }
    exec();
}
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    onethread = new myThread(this);
    onethread->start(QThread::NormalPriority);

    twothread = new myThread2(this);
    twothread->start(QThread::NormalPriority);

    connect(onethread, SIGNAL(onethread->threadSignal1()),
            this, SLOT(mySlot1()));
    connect(twothread, SIGNAL(threadSignal2()),
            this, SLOT(mySlot2()),Qt::QueuedConnection);
}

void MainWindow::mySlot1()
{
    ui->textEdit1->append("This is thread1");
}

void MainWindow::mySlot2()
{
    ui->textEdit1->append("This is thread2");
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    ui->textEdit1->append("textEdit1");
    ui->textEdit2->append("textEdit2");
}

The mainwindow.h:
#define MAINWINDOW_H

#include <QMainWindow>
#include <QThread>

namespace Ui {
class MainWindow;
}

class myThread : public QThread
{
  Q_OBJECT

public:
    myThread(QObject *parent = 0);
    void run();

signals:
    void threadSignal1();
};

class myThread2 : public QThread
{
  Q_OBJECT

public:
    myThread2(QObject *parent = 0);
    void run();

signals:
    void threadSignal2();
};

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void mySlot1();
    void mySlot2();

private slots:
    void on_pushButton_clicked();

private:
    Ui::MainWindow *ui;
    myThread *onethread;
    myThread2 *twothread;
};

#endif // MAINWINDOW_H

Please check the above code. It can give the qDebug output normally while the textEdit1/2 have no any output. And it seems to be a multi-thread signal/slot connect issue. Who can help? Thanks!

A: You need to define the slots as slots:
class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

public slots:
    void mySlot1();
    void mySlot2();
...

Also a few other things. You don't need the exec() call in each of the threads. They are going into an endless loop anyways and would never reach that statement. And, the purpose of exec() is to start an event loop in the thread so that it can receive and process events, like having its own slots. You are just emitting.
Are you sure this connection works?
connect(onethread, SIGNAL(onethread->threadSignal1()),
        this, SLOT(mySlot1()));

It should probably be:
connect(onethread, SIGNAL(threadSignal1()),
        this, SLOT(mySlot1()));

I believe QueuedConnection will be implied for the connections because they are targeting a slot on an owner in a different thread than the emitter.


text:
Q: Default date in datetimepicker in visual studio If the user selects the date in the DateTimePicker, it only picks up the date, which is what I need. However, if the user doesn't select any date and leaves the DateTimePicker as today's date, it shows date + time. The data is stored in an Access database. I want to store the date only in the Access store when the user leaves the DateTimePicker to today's date (without changing any date).
Me.DateTimePicker1.CustomFormat = "dd-MM-yyyy"
Me.DateTimePicker1.DataBindings.Add(New System.Windows.Forms.Binding("Value", Me.OrderdetailsBindingSource, "OrderDate", True))
Me.DateTimePicker1.DataBindings.Add(New System.Windows.Forms.Binding("Text", Me.OrderdetailsBindingSource, "OrderDate", True))
Me.DateTimePicker1.Font = New System.Drawing.Font("Tahoma", 10.2!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.DateTimePicker1.Format = System.Windows.Forms.DateTimePickerFormat.Custom
Me.DateTimePicker1.Location = New System.Drawing.Point(158, 39)
Me.DateTimePicker1.Name = "DateTimePicker1"
Me.DateTimePicker1.Size = New System.Drawing.Size(294, 28)
Me.DateTimePicker1.TabIndex = 2
Me.DateTimePicker1.Value = New Date(2019, 6, 18, 0, 0, 0, 0)

A: Access does not have a short date format such as SQL Server. See this link for lists of data types.
Access:

*

*Date/Time,    Use for dates and times,    8 bytes
SQL Server:

*

*datetime, From January 1, 1753 to December 31, 9999 with an accuracy of 3.33 milliseconds,    8 bytes

*date, Store a date only. From January 1, 0001 to December 31, 9999,   3 bytes
So Access only has one date/time type which must be able to store time, which has the same number of bytes as SQL Server datetime. The date without a timestamp you see is actually 12 AM. This is what you are doing when you set the date/time on your DateTimePicker Me.DateTimePicker1.Value = New Date(2019, 6, 18, 0, 0, 0, 0). This is incidentally your best solution, to set the DateTimePicker to today's date (just the date portion using the DateTime.Date property I menioned).
To solve your problem, do this in Form_Load:
Me.DateTimePicker1.Value = Now.Date ' this makes it today at 12 AM

If you want to better understand what is going on, check out the value of your DateTimePicker at any time with this, to see that there is always a time in it, even if it's 12 AM:
MessageBox.Show($"{DateTimePicker1.Value:yyyy-MM-dd HH:mm:ss}")

And run this query on your database to see that there is also always a time in an Access Date/Time field, and that Access automatically hides the time when it is 12 AM:
select
orderdate
, format(orderdate, 'General Date') as GeneralDate
, format(orderdate, 'Short Time') as ShortTime
, format(orderdate, 'Medium Time') as MediumTime
, format(orderdate, 'Long Time') as LongTime
, format(orderdate, 'Short Date') as ShortDate
, format(orderdate, 'Medium Date') as MediumDate
, format(orderdate, 'Long Date') as LongDate
from orderdetails

A: Sorry, if I am not able to answer you perfectly in vb.net
i will give you an Answer in vb (how i mean it is correct)
and in correct c#
i understood that you want the code to save values in the database, if the date of the DateTimePicker is set today.
c#
if(dateTimePicker1.Value.Date == DateTime.Today)
{
    //insert your code here
}

vb.net
if dateTimePicker1.Value.Date == DateTime.Today
//Code here
end if

this if asks, if the picket Date of the DateTime is the same Date as today
if you just want to save the whole value of the date in the DataBase if the picked date is today so like: "25.06.2019 17:25" then you will have a problem.
If you save it as String you could format it:
dateTimePicker1.Value.ToString("HH:mm dd.MM.yyyy")

or
dateTimePicker1.Value.ToString("HH:mm")

so put the second in the "else" braket.
if you only need Date or time, you can format it like the above.
(sorry i am not sure if i understood your question right, so if it doesn't help you, just comment. I will answer)


text:
Q: Countif loop on external excel sheets Currently i'm trying to consolidate the information from 3000 different xls sheets into one file.
The master file looks like this
http://i.imgur.com/lQWxQxO.png
All the other excels are contained in 1 folder like this. They are only 1 sheet each.
http://i.imgur.com/VxmaLCf.png
and lastly would be that the information inside the files are like this
http:// i.imgur.com/w3erGgN.png
I'm trying to count the number of "pos", "neg" and "neu" inside the files and consolidate on the master sheet and the current way i'm doing is to manually input countif codes while leaving the document open. Is there any other way to make it faster? I've tried sumproduct but it never works. it only returns 0 as i think it might be the wildcard problem.
I think the following code could be of use to me but I'm not sure how to code it such that it works accordingly.
Sub RunCodeOnAllXLSFiles()
Dim lCount As Long
Dim wbResults As Workbook
Dim wbCodeBook As Workbook
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False

On Error Resume Next
    Set wbCodeBook = ThisWorkbook
        With Application.FileSearch
            .NewSearch
            'Change path to suit
            .LookIn = "C:\MyDocuments\TestResults"
            .FileType = msoFileTypeExcelWorkbooks
            'Optional filter with wildcard
            '.Filename = "Book*.xls"
                If .Execute > 0 Then 'Workbooks in folder
                    For lCount = 1 To .FoundFiles.Count 'Loop through all
                        'Open Workbook x and Set a Workbook variable to it
                        Set wbResults = Workbooks.Open(Filename:=.FoundFiles(lCount), UpdateLinks:=0)

                    'DO YOUR CODE HERE

                    wbResults.Close SaveChanges:=False
                Next lCount
            End If
    End With
On Error GoTo 0
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
End Sub

Please help.

A:             Sub Merge()
            Path = "C:\path to the folder\"
            Filename = Dir(Path & "*.xls")
              Do While Filename <> ""
              Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
                 For Each Sheet In ActiveWorkbook.Sheets
                 Sheet.Copy After:=ThisWorkbook.Sheets(1)
              Next Sheet
                 Workbooks(Filename).Close
                 Filename = Dir()
              Loop
            End Sub

Found here: http://www.extendoffice.com/documents/excel/456-combine-multiple-workbooks.html


text:
Q: Returning a struct with a function member that refer to a variable in parent scope I'm trying to implement a function that returns a struct with a member function that refer to a variable in parent scope.
struct Scanner {
  int nextToken();
}

Scanner test() {
  token = 1;
  return {
    int nextToken() {
      return token;
    }
  };
}

I don't know if this is doable in C++.  I'm a JavaScript developer and I don't know how to accomplish this. Are there any suggestion on how to refer to the variable token and return a struct or class that can provide a function nextToken()?

A: You can't do it in older versions of the C++ standard (at least not as easy).
The far better (and easier) approach would be using C++11's lambdas.
Something like this (untested right now and most likely includes some syntax problem or other mistake somewhere):
struct Scanner {
    std::function<int()> nextToken;
};

Scanner test() {
    token = 1;
    return {
        [=](){ return token; }
    };
}

However, are you really sure you'll need to do it this way? This seems like a perfect use case for simple/classic class inheritance (which is possible with structs as well):
struct Scanner {
    virtual int nextToken() { return 0; }
}

struct TestScanner : public Scanner {
    virtual int nextToken() { return 1; }
}


text:
Q: Reference to App Delegate "lost" I have the strangest error in an app with a Root Viewcontroller containing a menu with 13 buttons to 13 separate viewcontrollers.
(All 13 are declared and initialized the same way in the App Delegate, and the Root view calls an App Delegate functions that pushes one of them on the Navcontroller stack. All view controllers load and are navigated to correctly.)
I just now copied a working viewcontroller's (of the 13) code for later adaptation to another tableview with different functionality. The only thing I've changed so far is the name of the .h and @interface and @implementation clauses so it will compile.
Suddenly, all the macros declared in the App Delegate (and that worked in the viewcontroller I copied the code from) give errors ('undeclared').
Importing AppDelegate.h fixes the .m file (edit: the .h file contains only 'local' macros), but I'm curious as to why it works without the import in one of the 13 and not in another of the 13 - as they are identically implemented!
It's obviously either some declaration difference or some difference in MainWindow.xib somehow, but I can see no differences!
So... what else could it be? Any ideas?
Edit: relevant code from AppDelegate.h: (I copied code from nyheterVC.h/m to narmastedepaVC.h/m)
@class foretagsinfoVC;
@class harfinnsviVC;
@class uthyrningVC;
@class utbildningVC;
@class nyheterVC;
@class kontakterVC;
@class narmastedepaVC;
@class bruksanvisningarVC;
@class minabyggplatserVC;
@class minauppgifterVC;
@class appTipsVC;
@class heatworkDetail;
@class stripehogDetail;

    foretagsinfoVC *foretagsinfo;
    harfinnsviVC *harfinnsvi;
    uthyrningVC *uthyrning;
    utbildningVC *utbildning;
    nyheterVC *nyheter;
    kontakterVC *kontakter;
    narmastedepaVC *narmastedepa;
    bruksanvisningarVC *bruksanvisningar;
    minabyggplatserVC *minabyggplatser;
    minauppgifterVC *minauppgifter;
    appTipsVC *apptips;
    heatworkDetail *heatwork;
    stripehogDetail *stripehog;

@property (nonatomic, retain) IBOutlet foretagsinfoVC *foretagsinfo;
@property (nonatomic, retain) IBOutlet harfinnsviVC *harfinnsvi;
@property (nonatomic, retain) IBOutlet uthyrningVC *uthyrning;
@property (nonatomic, retain) IBOutlet utbildningVC *utbildning;
@property (nonatomic, retain) IBOutlet nyheterVC *nyheter;
@property (nonatomic, retain) IBOutlet kontakterVC *kontakter;
@property (nonatomic, retain) IBOutlet narmastedepaVC *narmastedepa;
@property (nonatomic, retain) IBOutlet bruksanvisningarVC *bruksanvisningar;
@property (nonatomic, retain) IBOutlet minabyggplatserVC *minabyggplatser;
@property (nonatomic, retain) IBOutlet minauppgifterVC *minauppgifter;
@property (nonatomic, retain) IBOutlet appTipsVC *apptips;
@property (nonatomic, retain) IBOutlet heatworkDetail *heatwork;
@property (nonatomic, retain) IBOutlet stripehogDetail *stripehog;

A: Well you need to check what was the difference in the AppDelegate.h file
Post some code here


text:
Q: How To Add ImageTools GIF To Grid in Windows Phone 8 Silverlight I am making a program that will use the Windows Phone 8 Silverlight
I want to Show GIF Image with ImageTools on Grid but I can't add ExtendedImage grid's children.
Decoders.AddDecoder<GifDecoder>();
ExtendedImage eAt = new ExtendedImage();
eAt.UriSource = new Uri("medias/at.gif", UriKind.Relative);
grd.Children.Add(eAt);

Error : Argument 1: cannot convert from 'ImageTools.ExtendedImage' to 'System.Windows.UIElement'
I'll be glad if you fix it, thank you :)

A: Have you tried to use Image like this:
Decoders.AddDecoder<GifDecoder>();
ExtendedImage eAt = new ExtendedImage();
eAt.UriSource = new Uri(@"/medias/at.gif", UriKind.RelativeOrAbsolute);
eAt.LoadingCompleted += new EventHandler((ss, ee) =>
{
    Dispatcher.BeginInvoke(() =>
    {
        Image img = new Image();
        img.Source = eAt.ToBitmap();
        grd.Children.Add(img);
    });
});


text:
Q: Nano gallery not found "jQuery(...).nanogallery2 is not a function" I have a problem with nanogallery does not charge me even though I charge the libraries correctly:
    <!-- nano gallery-->
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  <link href="https://unpkg.com/nanogallery2@2.3.0/dist/css/nanogallery2.min.css" rel="stylesheet" type="text/css">
  <script type="text/javascript" src="https://unpkg.com/nanogallery2@2.3.0/dist/jquery.nanogallery2.min.js"></script>

And in console I get the following error:
jQuery(...).nanogallery2 is not a function

A: I could already solve the error, I just had to put the script call at the footer


text:
Q: How to call method requiring parameters type int using stack of a different type I have a stack of type UserEntry which takes in either 3 or 4 ints.
Using method overloading I've written two methods.
public void addUserEntry(int row, int col, int rowTwo, int colTwo) {
    do something
}

public void addUserEntry(int row, int col, int num) {
    do something
}

I'm trying to call the methods using a for each loop on the stack
for(UserEntry ue : stack){
        addUserEntry(ue);
}

I'm getting the error no suitable method found (UserEntry). I was thinking as the loop iterated through the stack it could output 3 or 4 ints and call the correct method but it seems I need a new method which accepts type UserEntry as a parameter.
Is there a way to make the method accept the numbers from the stack as type int and not as type UserEntry?


text:
Q: How to keep input stream open after piping to PHP process? When a PHP process accepts input on STDIN it seems that no further use of the input stream is possible.
Example: echo foo | php foo.php
<?php
$file = stream_get_contents(STDIN);
$line = fgets(STDIN);

Once the initial stream content has been read, further calls to fgets(STDIN) will fail rather than block for new input.
Using the readline extension produces the same result.
I can work around this problem by piping to a temporary file and reading from that, but is there a way to effectively keep the input stream open, or prevent it from reaching EOF?
I've tried closing and reopening the STDIN stream, but that doesn't work.
I've also tried preempting EOF by reading only the exact number of input bytes. This does prevent the eof flag being set on the stream metadata, but any subsequent read triggers EOF and the same effect is produced.


text:
Q: OpenLayers 3: not all lines in LineString are rendering i am trying to draw a lineString using the same coordinates that are used to draw a collection of markers on a map. The markers are drawn, then the lineString should draw joining the markers, the lineString uses the same coords as the markers.
I am having strange issues though, sometimes all the lines draw, sometimes only one of the lines draw. but usually there will be one or two lines missing. when i run getCoordinates() on the lineString, it returns me all the same coordinates as the marker locations, yet some of the lines are not drawn.
some code:
// location data, contains x/y coords
var locs = JSON.parse(loc_data);
var lineCoords = [];
var lat;
var lng;

// loop through loc data and output the markers
for (var key in locs) {
    if (locs.hasOwnProperty(key)) {

        lat = locs[key].lat;
        lng = locs[key].lng;

        // store the coords in an array to be used for the lineString
        lineCoords.push([lat,lng]);

        // create marker and add to map
        var iconFeature = new ol.Feature({
            geometry: new ol.geom.Point([lat, lng]),
        });

        var vectorSource = new ol.source.Vector({
            features: [iconFeature]
        });

        var vectorLayer = new ol.layer.Vector({
            source: vectorSource
        });

        map.addLayer(vectorLayer);
    }
}

// draw lineString using coordinates in lineCoords array
var line = new ol.geom.LineString(lineCoords);

var layerLines = new ol.layer.Vector({
    source: new ol.source.Vector({
        features: [new ol.Feature({
                geometry: line,
                name: 'Line'
            })]
    }),
});

map.addLayer(layerLines);

the code above seems pretty logical, i can't see where there could be a problem with it, and like is said, sometimes all lines are drawn and sometimes only one is drawn.
can anyone shine some light on this?

A: Try with the changes:
// location data, contains x/y coords
var
    locs = JSON.parse(loc_data),
    lineCoords = [], features = [],
    lat, lng, iconFeature
;

// loop through loc data and output the markers
for (var key in locs) {
    if (locs.hasOwnProperty(key)) {

        lat = locs[key].lat; //is this already EPSG:3857 ?
        lng = locs[key].lng;

        // store the coords in an array to be used for the lineString
        lineCoords.push([lng, lat]);

        // create marker and add to map
        iconFeature = new ol.Feature({
            geometry: new ol.geom.Point([lng, lat]),
        });
        features.push(iconFeature);
    }
}

var
    vectorSource = new ol.source.Vector({
        features: features //your LineString could also be included here
    }),
    vectorLayer = new ol.layer.Vector({
        source: vectorSource
    }),
    // draw lineString using coordinates in lineCoords array
    line = new ol.geom.LineString(lineCoords),
    layerLines = new ol.layer.Vector({
        source: new ol.source.Vector({
            features: [new ol.Feature({
                geometry: line,
                name: 'Line'
            })]
        })
    })
;
map.addLayer(vectorLayer);
map.addLayer(layerLines);


text:
Q: Qt - Maemo application - how to handle CTRL+C? I wrote a simple application to take pictures in c++ and am guessing I probably should do some cleanup whenever CTRL+C is pressed.  I am using QTCreator to write the application along with MADDE, but am not really using any Qt hooks that I know of.
How can I handle CTRL+C in my application?
Thanks,
Walter

A: It appears that maemo is based on linux. In linux C programs, you get an OS signal that you must write a handler for. You can go that route, but Qt seems to offer a signal that it fires when a program is ready to quit.. http://doc.qt.nokia.com/stable/qcoreapplication.html#aboutToQuit
Here is some more info about how to go about catching the OS signal in question, and then acting on it. Note that if you catch the OS signal, you probably won't get the "aboutToQuit" signal automatically anymore.
http://doc.qt.nokia.com/4.7/unix-signals.html


text:
Q: How to display files from a folder in django I have made a django app that has images in a folder.I have to create a dropdown menu as to which image it has to select.One has to provide the path to the folder and this image should be displayed on the html page.

A: The questions is somewhat modified version of:
Django: Auto-generating a list of files in a directory
(Credits: @Hoff for accepted answer to above mentioned post):
Bit of code:
views.py
import os

def gallery(request):
    path="C:\\somedirectory"  # insert the path to your directory
    img_list =os.listdir(path)
    return render_to_response('gallery.html', {'images': img_list})

gallery.html
{% for image in images %}

{% endfor %}

A: This is a modification of Fakkabir's answer and an assumption that the images you're trying to load are available via /static/
views.py
from django.shortcuts import render
import os

def gallery(request):
    path="C:\\somedirectory"  # insert the path to your directory
    img_list =os.listdir(path)
    return render(request, 'gallery.html', {'images': img_list})

gallery.html
{% load static %}

{% for image in images %}

{% endfor %}


text:
Q: Interpretation of ip routes rules The citation comes from: https://github.com/docker/labs/blob/master/networking/concepts/05-bridge-networks.md

When we peek into the host routing table we can see the IP interfaces
  in the global network namespace that now includes docker0. The host
  routing table provides connectivity between docker0 and eth0 on the
  external network, completing the path from inside the container to the
  external network.
host$ ip route default via 172.31.16.1 dev eth0
172.17.0.0/16 dev docker0  proto kernel  scope link  src 172.17.42.1
172.31.16.0/20 dev eth0  proto kernel  scope link  src 172.31.16.102

It is written: The host table provides connectivity between docker0 and eth0. I cannot see where in that rules the connectivity is introduced. Can you explain?


text:
Q: Cookie is sometimes lost with WebBrowser control I added WebBrowser control to form X, it is used in rare cases to download a file. On form load I invoke
WebBrowser1.Navigate2 "about:blank"

However sometimes my application session cookies are lost after form unload (and user gets a message to relogin). The problem is reproducible on some machines, and not consistent.
Is there a workaround or an explanation to this problem?

A: The issue is that it uses Internet Explorer's settings.  One of those settings dictate that the cookies should not be maintained.
My suggestion would be to have your app handle knowledge of data, and simply pass it back to the web pages appropriately.
Or, if you have access to the web pages, make it so it uses an ID for session data instead of cookies.
For PHP:
<?php ini_set('session.use_cookies', '0'); ?>


text:
Q: SVN to Git tags in weird location I have a couple of my projects on a SVN server. But when I started with the SVN server I had no clue about how a SVN setup should be.
So my current SVN repo layout is like this:
https://mysvn/svn
    trunk
        project1
        project2
    tags
        project1-tag1
        project1-tag2
        project2-tag1
        project2-tag2

After some thought I decided to go to Git, and followed the SVN to Git tutorial of Atlassian, and I am able to define my custom trunk layout, but my tags are a problem.
I can use the command
git svn clone --trunk=/trunk/project1/ --authors-file=authors.txt https://mysvn/svn/ Project1AsGit

But how do I incorporate the tags without having the tags of project2 inside of project1?

A: git-svn is not the right tool for one-time conversions of repositories. It is a great tool if you want to use Git as frontend for an existing SVN server, but for one-time conversions you should not use git-svn, but svn2git which is much more suited for this use-case.
There are pleny tools called svn2git, the probably best one is the KDE one from https://github.com/svn-all-fast-export/svn2git. I strongly recommend using that svn2git tool. It is the best I know available out there and it is very flexible in what you can do with its rules files.
If you are not 100% about the history of your repository, svneverever from http://blog.hartwork.org/?p=763 is a great tool to investigate the history of an SVN repository when migrating it to Git.
You will be able to setup the rules file so that you end up with two Git repositories where stuff is exactly where you want it and named like you want it and all with one run of the tool. You can even rename the tags in the process from project1-tag1 to tag1 and so on in the process.


text:
Q: SQL query - fill missing value I have a table:
id   type   place
1    X1      10
2    X2      10
3    X3      10
1    X1      50
2    X2      50
3    X3      50
1    null    70
2    null    70
3    null    70

I have three parts with id (1,2,3) and these parts are of any type in different places. However, on the place, "70" hasn't written type.
However, as part of piece counting, I need to count for location 70 for a given type (for example, X5). But the one in place 70 is not listed. How can I add this data in my selection within a subquery? For example, I take those ids and somehow refer that those ids are of type X5?
I want:
SQL query to select all columns for location 70 with the type added for the given id.
I tried this sql query, but it is wrong:
SELECT id, type, place
FROM TABLE t1
WHERE type = (
        SELECT type
        FROM TABLE t2
        WHERE t1.id = t2.id
            AND place = 10
        )
    AND place = 70

A: I found part of answer to your question here:
SELECT id,
  CASE WHEN type is null
    then (
        SELECT type
        FROM T as t2
        WHERE t1.id is t2.id and t2.type is not null)
    else type
  end as type,
place
FROM T as t1

my demo (I made it here):
id     type    place
1      X1      10
2      X2      10
3      null    70
2      null    70
1      null    70
3      X3      50
3      X3      50
2      X2      50
1      X1      50
1      X1      50
1      X1      50
3      X3      10

returns
id   type  place
1    X1    10
2    X2    10
3    X3    70
2    X2    70
1    X1    70
3    X3    50
3    X3    50
2    X2    50
1    X1    50
1    X1    50
1    X1    50
3    X3    10

MySQL solution (demo):
SELECT id,
  CASE WHEN type is null
    then (
        SELECT type
        FROM T as t2
        WHERE (t1.id = t2.id) and (t2.type is not null) LIMIT 1)
    else type
  end as type,
place
FROM T as t1

A: I would strongly recommend window functions.  For instance:
select t.*,
       max(type) over (partition by id) as imputed_typ
from t;

To "fill in" the existing value:
select id, place,
       coalesce(type, max(type) over (partition by id)) as type
from t;

Not only are these queries much simpler than a subquery, but they should have better performance.


text:
Q: How do I create a pandas dataframe to show each topic (index/keywords) with all the keywords in each row. I'd like the keywords to be present How do I turn this:
for index,topic in enumerate(LDA.components_):
    #print(f'Top 10 words for Topic #(index)')
    print([cv.get_feature_names()[i] for i in topic.argsort()[-15:]])
    print('\n')

Which prints this: [u'instance', u'breached', u'utilization', u'file', u'query', u'Threshold', u'Custom', u'Oracle', u'Device', u'Host', u'SRC', u'Name', u'prod', u'net', u'pncint']
into my existing df dataframe?
I am able to get the topic models numbers to print BUT NOT the actually words themselves. I would like for the topic number to be in a separate column from the words printed out.
Desired output:
DF:
Column(1)                             column (2)
CN Topic:                        CN Topic results:
1,                               intranet, help
7,                               mac, mouse
5, (going down)               heres, by, computer


text:
Q: Django Model with composite primary key isn't updated I have a model with composite primary key

class ChatUserModel(CModelMixin):
    user = models.ForeignKey(Users, models.DO_NOTHING, primary_key=True)
    chat = models.ForeignKey(ChatModel, models.DO_NOTHING)
    chat_permissions = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'tbl_chat_users'
        unique_together = (('user', 'chat'),)

And service, which use this model

def connect_to_chat(self, serializer: ChatInfoSerializer) -> ChatUserModel:

    chat_id = serializer.validated_data.get('chat')

    if ChatUserModel.objects.filter(user_id=self.user.id, chat_id=chat_id).exists():
        raise exceptions.ValidationError('User is already member of this chat')

    bundle = ChatUserModel.objects.create(user=self.user, chat_id=chat_id)

    if self.user.status == enum_status_of_user.confirmed_email:
        bundle.chat_permissions = ChatPermissions.canWrite.value
        bundle.save()

    return bundle

when running, I get an error:

Traceback (most recent call last):   File
"/Users/tatyanakorneeva/.local/share/virtualenvs/webcam-backend-GgKKOkUN/lib/python3.9/site-packages/django/db/backends/utils.py",
line 84, in _execute
return self.cursor.execute(sql, params) psycopg2.errors.UniqueViolation: duplicate key value violates unique
constraint "pk_tbl_chat_user_user_id" DETAIL:  Key (user_id,
chat_id)=(26b01213-b9c3-4abc-b1d2-f7213781a2c6,
ef4f0c4f-8edf-42b5-b01f-880856d55cd4) already exists.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):   File
"/Users/tatyanakorneeva/.local/share/virtualenvs/webcam-backend-GgKKOkUN/lib/python3.9/site-packages/django/core/handlers/exception.py",
line 47, in inner
response = get_response(request)   File "/Users/tatyanakorneeva/.local/share/virtualenvs/webcam-backend-GgKKOkUN/lib/python3.9/site-packages/django/core/handlers/base.py",
line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)   File "/Users/tatyanakorneeva/.local/share/virtualenvs/webcam-backend-GgKKOkUN/lib/python3.9/site-packages/django/views/decorators/csrf.py",
line 54, in wrapped_view
return view_func(*args, **kwargs)   File "/Users/tatyanakorneeva/.local/share/virtualenvs/webcam-backend-GgKKOkUN/lib/python3.9/site-packages/django/views/generic/base.py",
line 70, in view
return self.dispatch(request, *args, **kwargs)   File "/Users/tatyanakorneeva/.local/share/virtualenvs/webcam-backend-GgKKOkUN/lib/python3.9/site-packages/rest_framework/views.py",
line 509, in dispatch
response = self.handle_exception(exc)   File "/Users/tatyanakorneeva/.local/share/virtualenvs/webcam-backend-GgKKOkUN/lib/python3.9/site-packages/rest_framework/views.py",
line 469, in handle_exception
self.raise_uncaught_exception(exc)   File "/Users/tatyanakorneeva/.local/share/virtualenvs/webcam-backend-GgKKOkUN/lib/python3.9/site-packages/rest_framework/views.py",
line 480, in raise_uncaught_exception
raise exc   File "/Users/tatyanakorneeva/.local/share/virtualenvs/webcam-backend-GgKKOkUN/lib/python3.9/site-packages/rest_framework/views.py",
line 506, in dispatch
response = handler(request, *args, **kwargs)   File "/Users/tatyanakorneeva/projects/webcam_test_dev/webcam-backend/webcam69/chat/views/ConnectChatView.py",
line 18, in post
chat.connect_to_chat(serializer)   File "/Users/tatyanakorneeva/projects/webcam_test_dev/webcam-backend/webcam69/chat/services/ChatService.py",
line 54, in connect_to_chat
bundle.save()   File "/Users/tatyanakorneeva/.local/share/virtualenvs/webcam-backend-GgKKOkUN/lib/python3.9/site-packages/django/db/models/base.py",
line 753, in save
self.save_base(using=using, force_insert=force_insert,   File "/Users/tatyanakorneeva/.local/share/virtualenvs/webcam-backend-GgKKOkUN/lib/python3.9/site-packages/django/db/models/base.py",
line 790, in save_base
updated = self._save_table(   File "/Users/tatyanakorneeva/.local/share/virtualenvs/webcam-backend-GgKKOkUN/lib/python3.9/site-packages/django/db/models/base.py",
line 872, in _save_table
updated = self._do_update(base_qs, using, pk_val, values, update_fields,   File
"/Users/tatyanakorneeva/.local/share/virtualenvs/webcam-backend-GgKKOkUN/lib/python3.9/site-packages/django/db/models/base.py",
line 926, in _do_update
return filtered._update(values) > 0   File "/Users/tatyanakorneeva/.local/share/virtualenvs/webcam-backend-GgKKOkUN/lib/python3.9/site-packages/django/db/models/query.py",
line 803, in _update
return query.get_compiler(self.db).execute_sql(CURSOR)   File "/Users/tatyanakorneeva/.local/share/virtualenvs/webcam-backend-GgKKOkUN/lib/python3.9/site-packages/django/db/models/sql/compiler.py",
line 1522, in execute_sql
cursor = super().execute_sql(result_type)   File "/Users/tatyanakorneeva/.local/share/virtualenvs/webcam-backend-GgKKOkUN/lib/python3.9/site-packages/django/db/models/sql/compiler.py",
line 1156, in execute_sql
cursor.execute(sql, params)   File "/Users/tatyanakorneeva/.local/share/virtualenvs/webcam-backend-GgKKOkUN/lib/python3.9/site-packages/django/db/backends/utils.py",
line 98, in execute
return super().execute(sql, params)   File "/Users/tatyanakorneeva/.local/share/virtualenvs/webcam-backend-GgKKOkUN/lib/python3.9/site-packages/django/db/backends/utils.py",
line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)   File
"/Users/tatyanakorneeva/.local/share/virtualenvs/webcam-backend-GgKKOkUN/lib/python3.9/site-packages/django/db/backends/utils.py",
line 75, in _execute_with_wrappers
return executor(sql, params, many, context)   File "/Users/tatyanakorneeva/.local/share/virtualenvs/webcam-backend-GgKKOkUN/lib/python3.9/site-packages/django/db/backends/utils.py",
line 84, in _execute
return self.cursor.execute(sql, params)   File "/Users/tatyanakorneeva/.local/share/virtualenvs/webcam-backend-GgKKOkUN/lib/python3.9/site-packages/django/db/utils.py",
line 90, in exit
raise dj_exc_value.with_traceback(traceback) from exc_value   File "/Users/tatyanakorneeva/.local/share/virtualenvs/webcam-backend-GgKKOkUN/lib/python3.9/site-packages/django/db/backends/utils.py",
line 84, in _execute
return self.cursor.execute(sql, params) django.db.utils.IntegrityError: duplicate key value violates unique
constraint "pk_tbl_chat_user_user_id" DETAIL:  Key (user_id,
chat_id)=(26b01213-b9c3-4abc-b1d2-f7213781a2c6,
ef4f0c4f-8edf-42b5-b01f-880856d55cd4) already exists.

Object being created, then we go into the loop with 'if' (condition is true) - the object cannot be updated.
I think Django instead update instance try create, but i don't know why.
Parameter force_update=True didn't help me.


text:
Q: Error loading dll for ODP.NET in Windows 10 C# I am running:

*

*Windows 10 Home

*Oracle Database 11g Enterprise Edition 11.2.0.1 - 64 bit version

*Visual Studio Express 2013

I want to write a simple C# application to read data from the Oracle database and want to use ODP.NET.  However, when running the program I'm getting an immediate Runtime Error.

*

*I started a new Windows Forms project.

*I linked service Oracle.DataAccess.dll in directory c:\app\Dave\product\11.2.0\dbhome_1\ODP.NET\bin\2.x\
My code is:
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace testapp_2
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

Code :
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;

namespace testapp_2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            OracleConnection conn = new OracleConnection();
        }
    }
}

The error is:

Could not load file or assembly 'Oracle.DataAccess, Version=2.112.1.0,
  Culture=neutral, PublicKeyToken=89b483f429c47342' or one of its
  dependencies. An attempt was made to load a program with an incorrect
  format.

When running in debug mode, the program halts at line:
Application.Run(new Form1());

I have used this in the past successfully with Visual Stdio Express 2008 and Oracle 10g under Windows XP and thought this would be very simple just like before, but apparently not.
Has anyone else encountered this error and hopefully have found a workaround for it?  I would be most appreciative of any help or information.
Thank you very much!
-Dave.

A: In some cases where .net DLL is not targeting both x86 and x64 platform (like Microsoft Expression Encoder) under 64-bit system. this error might occur when launching debugging (not sure it's the same case for ODP.NET). The solution is to change your build settings in the project to target x86 instead of Any CPU.

A: Thanks to everyone for posting so many helpful comments.
I tried following the suggestion to change the target CPU to x86 instead of Any CPU (I also tried x64), but it made no difference.
But thinking about that topic got me thinking that perhaps this is an old ODP.NET dll, and isn't compatible with the current/latest versions of .NET.
So (in Properties and the Application tab, I changed the target .NET framework to be .NET 3.5 and sure enough that solved my problems!
I'm now able to read and write data to and from the database from C#!  I'm very happy and relieved that it is now working.
Thanks again to everyone for their assistance in leading me to solving this issue!  :-)
-D.


text:
Q: SEO meta tags are showing in page source but cannot preview them In my Next.js app I'm trying to insert og meta tags with dynamic content on a product page. So the content of the meta tags will change based on the product data fetched from server.
I am fetching product data using getServerSideProps and passing product data to page component as props.
export const getServerSideProps = wrapper.getServerSideProps(
    store => async (context) => {

        const response = await fetch(url, {
            method: 'GET',
        });
        const data = await response.json();

        return {
            props: {
                host: context.req.headers.host,
                product: data.product
            }
        }
    }
)

First Approach
I tried to insert meta tags directly on my product page component within  component. Here meta tags even with static conetnt are not showing in page source.
const Product = ({product}) => {
    return (
        product ?
            <>

                    <title>{product.title}</title>
                    <meta name="description"
                          content={product.description}/>
                    <meta property="og:title" content={product.title}/>
                    <meta property="og:type" content="video.movie"/>
                    <meta property="og:url" content={`${props.host}/products/${product.slug}`}/>
                    <meta property="og:description" content={product.description}/>
                    <meta property="og:image" content={product.thumbnail}/>

                <Course/>
            </> : null
    );
};

Second Approach
return (

            {/*<meta property="og:image" content="https://static.onlinevideobooks.com/abed1e5658b3ad23c38c22646968e4f2/files/media/images/2022/04/5b0645b9-ab03-4233-b5f3-86b092d4062b/conversions/cad47d2beb9143eab3d65ea4a75b0b0e-1280x720.webp" />*/}

            {/*<title>your keyword rich title of the website and/or webpage</title>*/}
            <meta name="description"
                  content="description of your website/webpage, make sure you use keywords!"/>
            <meta property="og:title" content="short title of your website/webpage"/>
            <meta property="og:type" content="video.movie"/>
            <meta property="og:url" content="https://example.com/"/>
            <meta property="og:description" content="description of your website/webpage"/>
            <meta property="og:image"
                  content="https://example.com/image"/>

);

I tried inserting meta tags within  in _document.js file. Here I am passing only static conetnt as I don't have dynamic data in _document.js. This time meta tags are showing up in page source and I can also preview them on facebook.
Third Approach
Then I try to insert those tag in _app.js file as I receive pageProps in this component.
Unfortunately when I pass dynamic content in meta tags like first approach, they do not show up in page source but they do when I pass static conetnt similar to second approach.
full _app.js code gist
UPDATE
As regard to my third approach, I checked once again and surprisingly I can see all meta tags in page source when inserted either with static or dynamic content in _app.js. I can preview the url when content is static but when content is dynamic I can not preview the url using either Facebook debug or Open graph
My Next.js version is 12.2.0

A: It's possible that the code you have in your _app.js is blocking the meta tags from being rendered. The "View page source" in browsers will not wait for client code to finish rendering. You can verify this and click "View page source" from your browser. Do you see any of the HTML you are expecting, for example do you see your meta tags and product html?
I expect that you probably don't see anything except some static HTML tags. One thing you could try is moving your use of hooks and rendering logic down into its own MainLayout component.
You can then try your first approach where you do something like this:
const Product = ({product}) => {
    return (
        product ?
            <>

                    <title>{product.title}</title>
                    <meta name="description"
                          content={product.description}/>
                    <meta property="og:title" content={product.title}/>
                    <meta property="og:type" content="video.movie"/>
                    <meta property="og:url" content={`${props.host}/products/${product.slug}`}/>
                    <meta property="og:description" content={product.description}/>
                    <meta property="og:image" content={product.thumbnail}/>

                <MainLayout>
                    <Course/>
                <MainLayout>
            </> : null
    );
};

Where MainLayout contains all the logic you have in your _app.js. This should keep your actual _app.js free of any client side code that is blocking the meta tags from rendering.
Basically we want to utitlize Next.js static optimization and have it pre-render the meta tags for your page so that the browser and web crawlers get the data without having to wait for any client side rendering.

A: Hopefully this helps someone, but my issue was the placement of the  tags within _app.js.  For some reason, when it was nested under <Auth0ProviderWithHistory> the meta tags would not render, moving it outside of this gave me victory.
Broken
<Auth0ProviderWithHistory>

  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />

            {openGraphData.map((og) => (
                <meta {...og} />
            ))}

            <title>{pageProps.title}</title>

        <CssBaseline>

                    <NavBar />
                    <Component {...pageProps} />

        </CssBaseline>
    </Auth0ProviderWithHistory>

Fixed

            <meta http-equiv="X-UA-Compatible" content="IE=edge" />
            <meta name="viewport" content="width=device-width, initial-scale=1" />

            {openGraphData.map((og) => (
                <meta {...og} />
            ))}

            <title>{pageProps.title}</title>

    <Auth0ProviderWithHistory>
        <CssBaseline>

                    <NavBar />
                    <Component {...pageProps} />

        </CssBaseline>
    </Auth0ProviderWithHistory>

A: Not sure what's going under the hood, but removing the Head tag resolves this for me.
I just put my meta tags without nesting them inside Head, and it worked.


text:
Q: What is the functional way to swap two values in a Map in elixir? I have a map defined as below:
iex(tbc@192-168-1-8)2> map = %{ 1 => {name => "Joey"}, 2 => {name => "Lee"}}

I want to swap the value of the two name to make it looks like:
%{1 => %{"name" => "Lee"}, 2 => %{"name" => "Joey"}}

I know I can use below code to implement this:
iex(tbc@192-168-1-8)3> name1 = Map.get(map, 1)
%{"name" => "Joey"}
iex(tbc@192-168-1-8)4> name2 = Map.get(map, 2)
%{"name" => "Lee"}
iex(tbc@192-168-1-8)5> map = Map.put(map, 1, name2)
%{1 => %{"name" => "Lee"}, 2 => %{"name" => "Lee"}}
iex(tbc@192-168-1-8)6> map = Map.put(map, 2, name1)
%{1 => %{"name" => "Lee"}, 2 => %{"name" => "Joey"}}

but I don't think this is elixir style of coding. What is the functional way to implement this logic in elixir?

A: You can go about with using the with block, extracting the names first, and then creating a new map with them:
with name1 <- Map.get(map, 1),
     name2 <- Map.get(map, 2)
do
     %{1 => name2, 2 => name1}
end

Or you can do a simple function, pattern match on the keys, get the values and produce a new map:
def swap(%{1 => name1, 2 => name2} do
     %{1 => name2, 2 => name1}
end

The end result is the same in both occasions, it's up to your own preference on which you'd use.

A: You can define a new map by accessing the values of the old one:
%{1 => map[2], 2 => map[1]}

If you want to swap two elements while preserving the rest of the map, you can use
%{ map | 1 => map[2], 2 => map[1] }

In iex:
iex(1)> map = %{1 => "one", 2 => "two", 3 => "three", 4 => "four"}
%{1 => "one", 2 => "two", 3 => "three", 4 => "four"}
iex(2)> %{ map | 1 => map[2], 2 => map[1] }
%{1 => "two", 2 => "one", 3 => "three", 4 => "four"}


text:
Q: Generate multiple builds in one makefile I want to have my unit test built along with my project every time I run make. I tried to do this with the following code in my Makefile:
DEPS = Parallel.cpp Resistor.cpp Series.cpp Source.cpp
TEST = Parallel.cpp Resistor.cpp Series.cpp Test.cpp

resistor: $(DEPS)
        g++ -std=c++11 -o resistor $(DEPS) -I. -g
test: $(TEST)
        g++ -std=c++11 -o test $(TEST) -I. -g

Yet when I look at the directory I only see ./resistor and not ./test.... BTW any advice for improving my makefile in other ways is welcome.

A: You could add the following rule as the first rule in your Makefile:
all: resistor test

Then run make:
$ make
g++ -std=c++11 -o resistor Parallel.cpp Resistor.cpp Series.cpp Source.cpp -I. -g
g++ -std=c++11 -o test Parallel.cpp Resistor.cpp Series.cpp Test.cpp -I. -g

Per the make documentation:

By default, make starts with the first target (not targets whose
  names start with '.').


text:
Q: Why can't all plastics form electrets? What property should a dielectric need to become an electret?
At first, I though polar dielectrics formed electrets, but non polar dielectrics like polypropylene also form electrets.
So what property do you need to become an electret?


text:
Q: Standard argument for making the class group of a number field trivial Let $K$ be a number field and let $R=\mathcal{O}_K$ be its ring of integers. Let $a_1, \ldots, a_h$ be ideals of $R$ generating the class group $Cl(K)$. Let $S$ denote the set of valuations corresponding to prime ideals dividing $a_1\cdots a_h$. Let
$$R_S = \{a \in K \mid v(a)\geq 0,\ v \text{ non-Archimedean valuation on } K, \  v \notin S \}$$
Silverman (p.213 Arithmetic of Elliptic Curves) claims that $R_S$ has trivial class group. I'm sure this is a standard and simple fact, but I'm having trouble proving it.
We have an inclusion $R \to R_S$ and a map $Cl(R) \to Cl(R_S)$. Let $I$ be an ideal of $R_S$, we want to show it is principal. We have $I \cap R \equiv \prod a_i^{e_i}$ in the class group so there exists principal ideal $P,P'$ of $R$ such that
$$P(I\cap R) = P' \prod a_i^{e_i}$$
$$P(I\cap R)R_S = P' \prod a_i^{e_i}R_S$$
Got stuck. Somehow the $a_iR_S$ become principal in $R_S$. I know
$$R=\bigcap\limits_\mathfrak{p} R_\mathfrak{p}$$
$$R_S=\bigcap\limits_{\mathfrak{p} \notin S} R_\mathfrak{p}$$
Where $\mathfrak{p}$ ranges over all maximal ideals of $R$

A: $
\newcommand{\O}{\mathcal O}
\newcommand{\Cl}{\mathrm{Cl}}
\newcommand{\p}{\mathfrak{p}}
$
Let $K$ be a number field, and $a_1, ..., a_h$ be ideals of $\O_K$ which are representatives of the ideal classes of $\Cl(\O_K)$ (in particular, $h$ is the class number of $K$).
Let $S$ be a finite set of places of $\O_K$, containing all the prime factors of all $a_i$, as well as all infinite places.
Claim : The ring $\O_{K, S}$ is a principal ideal domain.
Proof :
By proposition 23.2 b) and d), the ring $\O_{K, S}$ is a Dedekind domain, and every ideal of $\O_{K,S}$ is an extended ideal, i.e. of the form $J\O_{K,S}$ for some ideal $J \subset \O_K$.
By definition of the ideals $a_i$, there is an element $x \in K^{\times}$ and an index $i$ such that
$$J = x a_i.$$
The ideal $a_i^h = y \O_K$ is principal (where $y \in \O_K$), since the class group is annihilated by $h$. One sees that $y \in a_i \cap \O_{K,S}^{\times}$ (because $a_i^h \subset a_i$ and the only primes dividing $y$ are in $S$), which implies that
$a_i \O_{K,S} = (1)$
and finally
$$J \O_{K,S} = x \O_{K,S} \subset \O_{K,S}$$
is a principal ideal, as claimed.

Remarks:
1)
Instead of using proposition 23.2 above, one can first show that $\O_{K,S}$ is equal to a localization $\Sigma^{-1}\O_K$, namely for the multiplicative set $\Sigma$ of elements $a \in \O_K \setminus \{0\}$ such that the only prime factors of $a \O_K$ belong to $S$, that is
$$\Sigma = \bigcap_{\p \not \in S} (\O_K \setminus \p) = \O_K \setminus \bigcup_{\p \not\in S} \p.$$
(There seems to be a typo on page 41 of this book. The "multiplicative" set they are considering doesn't even contain $1$).
Notice that we want to show the equality
$$\left( \bigcap_{\p \not \in S} (\O_K \setminus \p)  \right)^{-1} \O_K = \bigcap_{\p \not \in S} ((\O_K \setminus \p)^{-1} \O_K),$$
which is not obvious.
$$ $$
A) We clearly have $\Sigma^{-1} \O_K \subseteq \O_{K,S}$. The reverse inclusion is not obvious: it uses the fact that the class group of $\O_K$ is torsion (because finite) — see here. In fact the argument is similar as above: pick $x \in \O_{K,S}$. For every $\p \in S$ such that $v_{\p}(x) < 0$, write $\p^h = b_{\p} \O_K$ as an principal ideal. Then
$b := \prod\limits_{v_{\p}(x) < 0} b_{\p}^{-v_{\p}(x)}$ is an element of $\O_K$ only divisible by primes in $S$, so that $b \in \Sigma$.
Finally, $bx \in \O_K$, so we conclude that $x \in \Sigma^{-1} \O_K$ as desired.
[Here is a wrong proof that  $\O_{K,S} \subset \Sigma^{-1} \O_K$ : if $x \in \O_{K,S}$ is non-zero, then fix $b_p \in p^{-v_p(x)}$ for every prime $p \in S$ such that $v_p(x)<0$. Then $b = \prod_p b_p \in \Sigma$ and $xb \in \O_K$, so that $x \in  \Sigma^{-1} \O_K$. The problem is that $b$ may have prime factors outside $\{ \p \mid a_i \}$, so that $b \in \Sigma$ is not true].
See also here, or here about relation between overrings and localizations. Moreover, remark 2.1 here might be of interest (but there is no proof there).
Finally, more general statements are given in theorem 2 here, mostly proven in Fossum, The Divisor Class Group of a Krull Domain.
$$ $$
B) Once you know that $\O_{K,S} \cong \Sigma^{-1}\O_K$, you can apply proposition 3.11.1) in Atiyah, MacDonald, Introduction to Commutative Algebra, to conclude that any ideal of $\O_{K,S}$ is indeed an extended ideal $J \O_{K,S}$, where $J$ is an ideal of $\O_K$. (Moreover, any localization of a Dedekind domain is still Dedekind, see here).
$$ $$
C) You can also look at prop. 4.19 here, but notice that they define $\O_{K,S}$ as a localization.
$$ $$
2) Here we are considering the multiplicative set
$\Sigma = \O_K \setminus \bigcup\limits_{\p \in \mathrm{Spec}(\O_K) \setminus S} \p.$
If instead you consider $\Sigma' = \O_K \setminus \p$ for a single fixed prime $\p$ of $\O_K$, you also get that $(\Sigma')^{-1}\O_K = (\O_K)_{\p}$ is a PID : it is even a DVR.
This is a result similar to the claim above, but which is in fact quite unrelated, since $\Sigma$ deals with the cofinite set $\mathrm{Spec}(\O_K) \setminus S$ of primes, while $\Sigma'$ deals with the finite set $\{\p\}$...


text:
Q: sudo apt install gcc not working I already tried this Unable to install GCC, depends gcc-7
It did not work.
Here is what I get
$ sudo apt install gcc

**Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:
The following packages have unmet dependencies:
 gcc : Depends: gcc-7 (>= 7.3.0-12~) but it is not going to be installed
*E: Unable to correct problems, you have held broken packages.**

Even sudo apt install build-essential is not working.
My Ubuntu version is 18.04.4.


text:
Q: Ansible docker_container command failing with no output I'm having an issue here with the ansible docker_container command.
- name: Start Docker
  docker_container:
    name: postgres
    image: "centos/postgresql-94-centos7"
    state: started
    recreate: yes
    pull: yes
    env:
      POSTGRESQL_USER: "test"
      POSTGRESQL_PASSWORD: "test"
      POSTGRESQL_DATABASE: "test"
      POSTGRESQL_MAX_CONNECTIONS: 100
      POSTGRESQL_SHARED_BUFFERS: 32M
    exposed_ports:
      - 5432
    ports:
      - 5432:5432
  become: yes
  become_method: sudo

When this command runs, it boots the container, but the container immediately exits with some output that I can't see because ansible doesn't print sys out for that for some reason.
Here's an example of some output that is printed when the container refuses to boot (due to incorrect config):
$ sudo docker run --name postgres -e POSTGRESQL_USER="test" -p 5432:5432 centos/postgresql-94-centos7
You must either specify the following environment variables:
  POSTGRESQL_USER (regex: '^[a-zA-Z_][a-zA-Z0-9_]*$')
  POSTGRESQL_PASSWORD (regex: '^[a-zA-Z0-9_~!@#$%^&*()-=<>,.?;:|]+$')
  POSTGRESQL_DATABASE (regex: '^[a-zA-Z_][a-zA-Z0-9_]*$')
Or the following environment variable:
  POSTGRESQL_ADMIN_PASSWORD (regex: '^[a-zA-Z0-9_~!@#$%^&*()-=<>,.?;:|]+$')
Or both.
Optional settings:
  POSTGRESQL_MAX_CONNECTIONS (default: 100)
  POSTGRESQL_MAX_PREPARED_TRANSACTIONS (default: 0)
  POSTGRESQL_SHARED_BUFFERS (default: 32MB)

For more information see /usr/share/container-scripts/postgresql/README.md
within the container or visit https://github.com/openshift/postgresql.

This is the output that I do not see when I run it from ansible, it just says its up (success) and then I check docker ps and its not up because presumably it immediately exited. What's more weird is that I can get this to work just fine with the same configuration passed to the ansible command module, but with the docker_container maybe its not passing the env correctly? I'm really not sure because I can't even get the error output.

A: Check
docker ps -a

to see if ansible managed to at least create the container. If it did, check
docker logs postgres

Hopefully that should give you a clue where it's failing. If you're confused with that maybe you can post some of the (redacted) logs to show where it's failing?

A: You can do this with registered.ansible_facts.docker_container.Output, where registered is the fact you used to register your docker_container play with.
More information here: https://wordpress.com/post/carlosonunez.wordpress.com/1440


text:
Q: List manipulation Python I have 2 lists:
name_info = ['0.abc','450.xyz','7.garfunkl','Coma','Cancer']
XY_coorinfo = ['1234:5678', '2345:6543','3245:1234', '4587:2346', '6785:23987']

Output I want :
0,abc,1234,5678
450,xyz,2345,6543
7,garfunkl,3245,1234
,Coma,4587,2346
,Cancer,6785,23987

I think I need list manipulation but not sure how to match 1:1 on two lists? I tried an IF clause inside the name_id and it works but I want an else clause to say if it doesn't find the "." make it empty?
def name_table(cur_ic,table_names, column_name,print_out=False ):
    #print (table_names)
    id = []
    name_info = []
    name_info = cur_ic.execute("SELECT nameandid FROM one_table ; " ).fetchall()
    XY_Coordinfo = []
    XY_Coordinfo = cur_ic.execute('''SELECT coor_rot FROM another_table WHERE id < '431'; ''').fetchall()
    return name_info, XY_Coordinfo

def write_outfile(cur_ic, name_info, XY_coordinfo,print_out=True):
    #print name_info, XY_Coordinfo

    name_id = [x.split('.', 1)[0] for x in partitioninfo if '.' in x ]

if __name__ =='__main__':
    sqlite_db = "sample.sqLiteDB"
    conn_ic,cur_ic = connect(sqlite_db)
    all_db_fetch(cur_ic, print_out=False)
    table_names,column_name = all_db_fetch(cur_ic)
    name_table(cur_ic,table_names,column_name, print_out=False)
    name_info,XY_Coordinfo = info_table(cur_ic,table_names,column_name)
    write_outfile(cur_ic, name_info, XY_coordinfo,print_out=True)

A: Use zip() to iterate over two lists simultaneously and split and join to the required format:
name_info = ['0.abc','450.xyz','7.garfunkl','Coma','Cancer']
XY_coorinfo = ['1234:5678', '2345:6543','3245:1234', '4587:2346', '6785:23987']

for x, y in zip(name_info, XY_coorinfo):
    print(','.join(x.split('.') + y.split(':')))

# 0,abc,1234,5678
# 450,xyz,2345,6543
# 7,garfunkl,3245,1234
# Coma,4587,2346
# Cancer,6785,23987

For the exact output:
name_info = ['0.abc','450.xyz','7.garfunkl','Coma','Cancer']
XY_coorinfo = ['1234:5678', '2345:6543','3245:1234', '4587:2346', '6785:23987']

for x, y in zip(name_info, XY_coorinfo):
    l, _ , r = x.partition('.')
    if not r:
        l = f',{l}'
        print(','.join([l] + y.split(':')))
    else:
        print(','.join([l, r] + y.split(':')))

# 0,abc,1234,5678
# 450,xyz,2345,6543
# 7,garfunkl,3245,1234
# ,Coma,4587,2346
# ,Cancer,6785,23987

A: Another approach to produce exactly your output:
name_info_split = [e.split('.') if (len(e.split('.')) == 2) else ['', e] for e in name_info]
XY_coorinfo_split = [e.split(':') for e in XY_coorinfo]
for i in range(len(name_info_split)):
    print("{},{},{},{}".format(name_info_split[i][0], name_info_split[i][1], XY_coorinfo_split[i][0], XY_coorinfo_split[i][1]))

A: A simple way to do this might be:
# split up the first list into elements
n = []
for i in name_info:
   n.append(i.split('.'))
# split up the second list into elements
m = []
for j in XY_coordinfo:
   m.append(j.split(':'))
# now create your final list
x = []
for k in range(len(n)) # here we assume they are the same length
   x.append(n[k] + m[k])

This results in x where of:
[['0', 'abc', '1234', '5678'],
 ['450', 'xyz', '2345', '6543'],
 ['7', 'garfunkl', '3245', '1234'],
 ['Coma', '4587', '2346'],
 ['Cancer', '6785', '23987']]

If you need to combine this for printable form you can do that with:
for l in x:
   print(','.join(l))

resulting with:
""""
0,abc,1234,5678
450,xyz,2345,6543
7,garfunkl,3245,1234
Coma,4587,2346
Cancer,6785,23987
"""

Done!

A: name_info = ['0.abc','450.xyz','7.garfunkl','Coma','Cancer']
XY_coorinfo = ['1234:5678', '2345:6543','3245:1234', '4587:2346', '6785:23987']

for i,j in zip(name_info,XY_coorinfo):

    io = (i[:i.index('.')],i[i.index('.')+1:]) if '.' in i else ('',i)
    print(*io,*j.split(':'),sep=',')

    """
    output

    0,abc,1234,5678
    450,xyz,2345,6543
    7,garfunkl,3245,1234
    ,Coma,4587,2346
    ,Cancer,6785,23987

    """


text:
Q: Getting iPhone location from a remote server How does a remote server trigger an iPhone app to get current location? Apps that help locate your stolen/lost iPhone seem to be able to do this.
How is this possible? Does it use some kind of stealth push notification? Also, the phone app would have to update the remote server of its location, which means it will need to use the NSURLConnection features while backgrounded or terminated. Seems like magic to me.

A: No. That's not possible. It's always the device (iPhone) that reports its current location.
If Find My iPhone does it, it's probably running some special background application to report its location on a regular basis, or when the server requests it (through push notifications). But it's always the phone sending its location information.

A: An application on your phone can subscribe to a push service.  When the push is sent to the phone, it can send it's location to a server.


text:
Q: javax.ws.rs.NotAllowedException: HTTP 405 Method Not Allowed I have 2 Wildfly 14 instances running on the same Windows server EC2 instance. One is making a request to another:
List<Long> ids = ...
WebTarget target = client.target("http://localhost:8080/test");
boolean put = target.request().put(Entity.entity(ids, MediaType.APPLICATION_JSON), boolean.class);

The endpoint on the other server is:
@PUT
@Path("/test")
@Produces(MediaType.APPLICATION_JSON)
public boolean prepareGame(List<Long> ids) {
    return true;
}

I'm getting
17:30:05,640 ERROR [stderr] (EE-ManagedExecutorService-default-Thread-2) javax.ws.rs.NotAllowedException: HTTP 405 Method Not Allowed

17:30:05,641 ERROR [stderr] (EE-ManagedExecutorService-default-Thread-2)    at org.jboss.resteasy.resteasy-jaxrs@3.6.1.Final//org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.handleErrorStatus(ClientInvocation.java:223)

17:30:05,641 ERROR [stderr] (EE-ManagedExecutorService-default-Thread-2)    at org.jboss.resteasy.resteasy-jaxrs@3.6.1.Final//org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.extractResult(ClientInvocation.java:191)

17:30:05,641 ERROR [stderr] (EE-ManagedExecutorService-default-Thread-2)    at org.jboss.resteasy.resteasy-jaxrs@3.6.1.Final//org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.invoke(ClientInvocation.java:463)

17:30:05,641 ERROR [stderr] (EE-ManagedExecutorService-default-Thread-2)    at org.jboss.resteasy.resteasy-jaxrs@3.6.1.Final//org.jboss.resteasy.client.jaxrs.internal.ClientInvocationBuilder.put(ClientInvocationBuilder.java:207)

(at the line: boolean put = target.request()... )

When I run these on my local machine it works, so i suspect a configuration issue and not a code issue, but I don't know.
The amazon instance allows all outgoing traffic and all incoming TCP traffic on 8080 where the server is listening (jboss.http.port:8080). The firewall on the machine also allows this traffic. I have tested that traffic is accepted there via sending a request from my local machine to the remote server with client.target("http://x.x.x.x:8080/..."); where x.x.x.x is the public ip of the instance. There was no problem.
What would cause this error on the amazon instance but not on my local machine since the address is localhost?

A: I just found the answer: the Startup Poller and Shutdown Poller were (under "Server State Detectors") were set to Management Service instead of Web Port. This happens, i think, when the Behavior profile/Server Adapter profile is set to Controlled By: Managment Operations instead of Filesystem and shell operations.
I don't know how the poller works or why it causes this error, but that was the solution.


text:
Q: How to write a recipe to install oh-my-zsh using its install.sh in chef? I am trying to build a recipe that basically does 2 things:

*

*Install zsh

*Install oh-my-zsh

Currentltly I am doing the follwoing to install them in my finsal.sh file. # Added zsh shell.
# Install ZSH
sudo apt-get install zsh
wget --no-check-certificate https://github.com/robbyrussell/oh-my-zsh/raw/master/tools/install.sh -O - | sudo ZSH=/home/vagrant/.oh-my-zsh sh
export ZSH=/home/vagrant/.oh-my-zsh
sudo chsh -s /bin/zsh vagrant
zsh

# Change the oh my zsh default theme.
cp /home/vagrant/.oh-my-zsh/templates/zshrc.zsh-template /home/vagrant/.zshrc
chown vagrant:vagrant /home/vagrant/.zshrc
chown -R vagrant:vagrant /home/vagrant/.oh-my-zsh

I looked for existing cookbooks and found a few. However, they all seem to be more that what I need. For example, I found this one https://github.com/shingara/oh-my-zsh-chef but it has dependencies that I don't need.
The questions is how do I replace the above bash script with a chef recipe?

A: https://github.com/shingara/oh-my-zsh-chef has ONE dependency, git.  If that's too much for you, I'd suggest you fork the cookbook and strip out the git dependency.  In either case, that cookbook provides a pretty good starting point for you.  If you have specific questions regarding how to modify it, let us, know.


text:
Q: How to do a grep in a ascii with confidence 1.0 file I'm using windows 10. I 'm encountering something odd. I can not get any output from my grep command in a list of log files.
For testing, I used these kind of command on the word which contains all the files :
Select-String -Path *.log -Pattern OPENED
findstr /i "OPENED" *.log
grep -r "OPENED" *.log

I've not any output.
I installed chardetect python script that gave the version of charactère of the log files :
chardetect file.log
file.log: ascii with confidence 1.0

How to do a grep in these kind of files ?

A: I post my solution, it might help.
Here this page help me to find the good option of Select-String command :
https://ss64.com/ps/select-string.html
I used the -Encoding option like this :
Select-String -Path *.log -Pattern OPENED -Encoding unicode

I got something I search :
ID_647318.log:1:LOG FILE OPENED
ID_647318.log:12:LOG FILE OPENED
ID_645559.log:1:LOG FILE OPENED
ID_645559.log:12:LOG FILE OPENED
ID_645562.log:1:LOG FILE OPENED
ID_645562.log:12:LOG FILE OPENED


text:
Q: LazyColumn notify about modification of item I have a composable function that looks something like this:

@Composable
fun listScreen(context: Context, owner: ViewModelStoreOwner) {
    val repository = xRepository(getAppDatabase(context).xDao()
    val listData by repository.readAllData.observeAsState(emptyList())
    // repository.readAllData returns LiveData<List<xEntity>>
   // listData is a List<xEntity>

    LazyColumn(){
        items(listData.size) {
            Card {
                  Text(listData[it].name)
                  Text(listData[it].hoursLeft.toString())
                  Button(onClick = {updateInDatabase(owner, name = listData[it], hoursLeft = 12)}) {...}
                  }
        }
    }

}

fun updateInDatabase(owner: ViewModelStoreOwner, name: String, hoursLeft: Int) {
     val xViewModel....
     val newEntity = xEntity(name=name, hoursLeft = Int)
     xViewModel.update(newEntity)
}

and as you propably can guess, the LazyColumn doesn't refresh after modification of entity, is there a way to update listData after every update of entity?
edit:
class xRepository(private val xDatabaseDao) {
    val readAllData: LiveData<List<xEntity>> = xDatabaseDao.getallXinfo()
    ...
    suspend fun updatePlant(x: xEntity) {
        plantzDao.updateX(x)
    }
}

interface xDatabaseDao {
    @Query("SELECT * FROM xInfo ORDER BY id DESC")
    fun getAllXInfo(): LiveData<List<xEntity>>
    ....

    @Update(onConflict = OnConflictStrategy.REPLACE)
    suspend fun updateX(x: xEntity?)
}

modification of entity:

fun updatePlantInDatabase(owner: ViewModelStoreOwner, name: String, waterAtHour: Int, selectedDays: ArrayList<Int>) {
    val xViewModel: xViewModel = ViewModelProvider(owner).get(xViewModel::class.java)
    val new = xEntity(name = name, waterAtHour = waterAtHour, selectedDays = selectedDays)
    xViewModel.updatePlant(new)
}

A: I use mutableStateOf to wrap fields that need to recomposed. Such as
class TestColumnEntity(
    val id: String,
    title: String = ""
){
    var title: String by mutableStateOf(title)
}

View:
        setContent {
            val mData = mutableStateListOf(
                TestColumnEntity("id_0").apply { title = "cnm"},
                TestColumnEntity("id_1").apply { title = "cnm"},
                TestColumnEntity("id_2").apply { title = "cnm"},
                TestColumnEntity("id_3").apply { title = "cnm"},
                TestColumnEntity("id_4").apply { title = "cnm"},
                TestColumnEntity("id_5").apply { title = "cnm"},
            )
            Column {
                Button(onClick = {
                    mData.add(TestColumnEntity("id_${Random.nextInt(100) + 6}").apply { title = "ccnm" })
                }) {
                    Text(text = "add data")
                }
                Button(onClick = {
                    mData[1].title = "test_${Random.nextInt(100)}"
                }) {
                    Text(text = "update data")
                }
                TestLazyColumn(data = mData, key = {index, item ->
                    item.id
                }) {
                    Text(text = it.title)
                }
            }
        }

It works in my testcase

A: If you want to update lazy column (say recompose in jetpack compose) so use side effects.
Put list getting function in side effect (Launch Effect or other side effects) when list is change side effect automatic recompose your function and show updated list.


text:
Q: RegEx in python is testing fine, but not implementing properly I'm working on a personal project and this is my first time using RegEx, so forgive me if I've misunderstood the documentation. In my program I am reading a webpage and trying to parse information from it. I've tested my expression at pythex (link), and it accurately highlights the part of the string I'm interested in, yet when I test the code with the same input in my command line, I get a strange output.
I've tried using search, findall, and match with varying strange outputs, but no luck.
def getStats():
    playername = input("Enter your OSRS name: ")
    try:
        with urllib.request.urlopen("https://secure.runescape.com/m=hiscore_oldschool/index_lite.ws?player=" + playername) as response:
            page = response.read()
            page = str(page)
            levels = re.findall(r'[,\d\d,]', page)
            print(levels)

This is the section of code that I want to parse the digits from the webpage and store them in a list. If you look at my pythex link, the output should be
Output: ['77', '80', '76', '91', ...

Instead, the output I get is
Output: ['2', '9', '1', '2', '2', ...

Any glaring issues with the code I've posted? I assume something is wrong with the way I've written my expression in python.

A: You don't need the square brackets in your expression -- these are for character classes and mean 'only one of these characters'.  Your [,\d\d,] expression actually means 'a comma or a digit or a digit or a comma'.
What you need is parentheses for capturing groups: r',(\d\d),'
Example on Regex101: https://regex101.com/r/FoaKZL/1
For more details: https://docs.python.org/3/library/re.html

A: Try this one:
re.findall('(?<=,)\d{2}(?=,)', page)

output:
['77', '80', '76', '91', '99', '70', '84', '91', '64', '63', '80', '82', '70', '51', '67', '48', '65', '60', '70', '58', '50', '71', '52']

A: From https://regex101.com here's an example on how to achieve that in Python and how to obtain only the numbers (not the commas)
import re

regex = r",(\d\d),"

test_str = "291230,1619,43801314 426005,77,1526319 324883,80,2064954 669155,76,1440237 320402,91,5933387 144963,99,13040711 380507,70,743124 387592,84,3119589 151260,91,6150297 703369,64,413056 599216,63,393779 195668,80,2096232 191977,82,2540831 326908,70,748218 709559,51,113909 405685,67,547977 572221,48,83492 443568,65,456357 325912,60,273874 436817,70,789871 364612,58,232633 314387,50,106976 184820,71,853614 378565,52,131877 -1,-1 -1,-1 -1,-1 401271,17 -1,-1 218157,8 610933,1 319030,7 247208,1 -1,-1"

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))


text:
Q: How to create compile-time constant string with prepended length byte? I have some old code that uses #define to, um, define some string literals, e.g.
#define FredString "\004FRED"

That I would like to update to avoid using #define. Closest I get is something like the following:
static constexpr char* FSraw= "FRED";
static constexpr char FSlen= (char)(sizeof(FSraw) - 1);
static constexpr char* FredString= FSlen FSraw;

but the compiler seems unhappy on the third line.
What would be the best way to construct such a string at compile time? Obviously I could still explicitly encode the length, but also obviously, that's more error prone.
Looking for solutions for C++17 or earlier.

A: template <std::size_t N>
constexpr std::array<char, N+1> AddLenPrefix(const char (&str)[N])
{
    std::array<char, N+1> ret{};
    ret[0] = N-1; // Exclude the '\0'.
    for (std::size_t i = 0; i < N; i++)
        ret[i+1] = str[i];
    return ret;
}

static constexpr auto FredString = AddLenPrefix("FRED");

A: You can also have something like:
#include <string_view>
#include <utility>

template <std::string_view const& S, typename>
struct prepend_length_impl;

template <std::string_view const& S, std::size_t ... Is>
struct prepend_length_impl<S, std::index_sequence<Is...>> {
    static constexpr const char value[]{ (sizeof...(Is) + '0'), S[Is]..., 0 };
};

template <std::string_view const& S>
struct prepend_length {
    static constexpr std::string_view value =
        prepend_length_impl<S, std::make_index_sequence<S.size()>>::value;
};

and then use it like:
static constexpr std::string_view raw = "fred";
static constexpr std::string_view fred = prepend_length<raw>::value; // "4fred"

DEMO


text:
Q: How would I approach sorting something like this  1
  14
    141
        141010
        141020
        141030
        141040
        141050
        141060
    142
        142010
        142020
    144
        1440
          144010
          144020
          144030
          144040

Currently for a school project I have to make an array based on similar numbers.
Any number that has 1-2-3-4 numbers as length can have children.
However I can't figure how to solve this programmatically as when the number 1440 in this scenario doesn't exist 144010~ has to sort itself under 144 and if 144 doesn't exist it goes below 14 but stay under the numbers that start with 142.
Any help on how I would approach this problem would be highly appreciated.
EDIT:
Some code I've tried:
 Public Class DataSet
        Public Property one As Integer
        Public Property two As New List(Of Two)
        Public Property three As New List(Of three)
        Public Property four As New List(Of four)
    End Class

    Public Class Two
        Public Property two As Integer
        Public Property three As New List(Of three)
    End Class

    Public Class three
        Public Property three As Integer
        Public Property four As New List(Of four)
    End Class

    Public Class four
        Public Property four As Integer
        Public Property six As New List(Of String)
    End Class

    Sub Main()
        Dim ds As New List(Of DataSet)
        Dim one As New List(Of String)
        Dim two As New List(Of String)
        Dim three As New List(Of String)
        Dim three_found As New List(Of String)
        Dim four As New List(Of String)
        Dim six As New List(Of String)
        Dim words() As String = File.ReadAllLines("Numbers.txt")
        For Each w In words
            Dim length = w.Length
            Dim number = Convert.ToInt32(w)
            Select Case length
                Case 1
                    one.Add(w)
                Case 2
                    two.Add(w)
                Case 3
                    three.Add(w)
                Case 4
                    four.Add(w)
                Case 6
                    six.Add(w)
            End Select
        Next

        For Each i In one
            Dim dso As New DataSet
            dso.one = i
            For Each t In two
                If t.StartsWith(i.ToString()) Then
                    Dim newtwo = New Two
                    newtwo.two = t
                    dso.two.Add(newtwo)
                End If
                For Each th In three
                    If th.StartsWith(i) Then
                        three_found.Add(th)
                        Dim twoc = th.Substring(0, 2)
                        If twoc.StartsWith(t) Then
                            Dim threec As New three
                            threec.three = th
                            Dim threef = dso.two.Where(Function(w) w.two = twoc).FirstOrDefault()
                            If threef IsNot Nothing Then
                                threef.three.Add(threec)
                            Else
                                dso.three.Add(threec)
                            End If
                        End If
                    End If
                Next
            Next
            ds.Add(dso)
        Next

    End Sub

A: As I said before check Treeview. It already does this type of hierarchy for you.
This code is in C# but you can easily convert to VB (manually or by using an online converter like Telerik's and editing a bit):
void Main()
{
    string values = @"1
  14
    141
        141010
        141020
        141030
        141040
        141050
        141060
    142
        142010
        142020
    144
       1440
          144010
          144020
          144030
          144040
    145020
    145030
    145010
          ";

    int myValue;
    var myData = values.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
        .Select(s => int.TryParse(s.Trim(), out myValue)?myValue:-1)
        .Where(n => n != -1);

    Func<int, IEnumerable<int>, int?> parent = (value, list) =>
    {
        while (value > 0)
        {
            value /= 10;
            if (list.Any(l => l == value))
            {
                return value;
            }
        }
        return null;
    };

    var nodes = myData
        .Select(d => new { d, parentNode = parent(d, myData) })
        .OrderBy(d => d.parentNode)
        .ThenBy(d => d.d);

    TreeView tv = new TreeView();
    foreach (var n in nodes)
    {
        var v = n.d.ToString();
        ((n.parentNode == null)
        ? tv.Nodes
        : tv.Nodes.Find("_" + n.parentNode.ToString(), true).First().Nodes)
        .Add("_" + v, v);
    }

    foreach (TreeNode node in tv.Nodes)
    {
        WriteNode(node, 0);
    }
}

private void WriteNode(TreeNode node, int level)
{
    Console.WriteLine("".PadLeft(level, '\t') + node.Text);
    foreach (TreeNode n in node.Nodes)
    {
        WriteNode(n, level + 1);
    }
}

The output is:
1
  14
    141
      141010
      141020
      141030
      141040
      141050
      141060
    142
      142010
      142020
    144
      1440
        144010
        144020
        144030
        144040
    145010
    145020
    145030

Note: If you want to do without a Treeview, then use a logic like:

*

*Create a list,

*Loop your values,

*For each value, get the value as a string,

*Loop starting with length towards 0 and get substring, (say value is 144010)

*Check if that substring exists, (you would find 1440)

*If it does prefix your value with that value plus a separator, (1440\144010)

*Now continue the search with new parent (1440),

*Append any "parents" as you find (final would become 1/14/144/1440/144010)

*Add this to the list you have at top.

*Sort your list (because of directory like structure all values would find their place).

*You can dump your values indented by count of your separator + the value after last separator (like the last folder name in a directory structure).

A: Here is how you would do that without using a Treeview (why wouldn't you I don't know):
void Main()
{
    string values = @"1
  14
    141
        141010
        141020
        141030
        141040
        141050
        141060
    142
        142010
        142020
    144
       1440
          144010
          144020
          144030
          144040
    145020
    145030
    145010
          ";

    int myValue;
// Splitting and converting to a collection of integers ordered by randomly
// just to show initial order doesn't matter
    var myData = values.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
        .Select(s => int.TryParse(s.Trim(), out myValue) ? myValue : -1)
        .Where(n => n != -1)
        .OrderBy(n => Guid.NewGuid());

// We have the collection. Sort it "directory" style
    List<string> myList = new List<string>();
    var list = myData.Select(d => d.ToString());
    foreach (var v in myData)
    {
        myList.Add(Fullpath(v.ToString(), list));
    }
    var ordered = myList.OrderBy(l => l);
// Write out the result intended
    foreach (var element in ordered)
    {
        var levels = element.Count(e => e == '/');
        var value = levels > 0 ? element.Remove(0, element.LastIndexOf('/') + 1) : element;
        Console.WriteLine("".PadLeft(levels, '\t') + value);
    }
}

// Get the full path for a value with ancestors
// ie: 1/14/1440/144010 is the full path for 144010
private string Fullpath(string key, IEnumerable<string> list)
{
    List<string> paths = new List<string>();
    for (int i = 1; i <= key.Length; i++)
    {
        if (list.Any(v => key.Substring(0, i) == v))
        {
            paths.Add(key.Substring(0, i));
        }
    }
    return string.Join("/", paths);
}

Note that values are shuffled before starting to sort and this is what you get:
1
  14
    141
      141010
      141020
      141030
      141040
      141050
      141060
    142
      142010
      142020
    144
      1440
        144010
        144020
        144030
        144040
    145010
    145020
    145030

A: And this is VB version (warning: I don't use VB and don't know it, used Telerik converter and modified slightly to make it work, due to VB.Net lack of literals like "\t" I used 4 spaces to intend - didn't want to add VisualBasic namespace):
Private Sub Main()
    Dim values As String = <values>
1
  14
    141
        141010
        141020
        141030
        141040
        141050
        141060
    142
        142010
        142020
    144
       1440
          144010
          144020
          144030
          144040
    145020
    145030
    145010
</values>

' Splitting and converting to a collection of integers ordered by randomly
' just to show initial order does not matter
    Dim myValue As Integer
    Dim myData = values _
        .Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries) _
        .Select(Function(s) If(Integer.TryParse(s.Trim(), myValue), myValue, -1)) _
        .Where(Function(n) n <> -1) _
        .OrderBy(Function(n) Guid.NewGuid())

' We have the collection. Sort it "directory" style
    Dim myList As List(Of String) = New List(Of String)()
    Dim list = myData.Select(Function(d) d.ToString())
    For Each v In myData
        myList.Add(Fullpath(v.ToString(), list))
    Next

' Write out the result intended
    Dim ordered = myList.OrderBy(Function(l) l)
    For Each element In ordered
        Dim levels = element.Count(Function(e) e = "/"c)
        Dim value = If(levels > 0, element.Remove(0, element.LastIndexOf("/"c) + 1), element)
        Console.WriteLine("".PadLeft(levels * 4, " ") + value)
    Next
End Sub

' Get the full path for a value with ancestors
' ie: 1/14/1440/144010 is the full path for 144010
Private Function Fullpath(ByVal key As String, ByVal list As IEnumerable(Of String)) As String
    Dim paths As List(Of String) = New List(Of String)()
    For i As Integer = 1 To key.Length
        If list.Any(Function(v) key.Substring(0, i) = v) Then
            paths.Add(key.Substring(0, i))
        End If
    Next

    Return String.Join("/", paths)
End Function

'=======================================================
'Service provided by Telerik (www.telerik.com)
'Conversion powered by Refactoring Essentials.
'Twitter: @telerik
'Facebook: facebook.com/telerik
'=======================================================


text:
Q: How nested loop works with jade? How nested loop works in jade?
I am trying to generate multiple div with increasing and decreasing value in class attribute. I am trying below jade syntax for that and getting very weird output of 60 div.
jade code:
.row
  - for (var j = 1; j < 12; j++)
    - for (var i = 11; i >= 1; i--)
      div(class="col-"+j+" col-offset-"+i)= val

HTML output(with about jade syntax which is unwanted):

.
.
.

HTML output(Desired):

A: According to your nested loops, what you get is the desired behaviour. Because, outer loop waits until the inner loop completes execution before go to the next iteration. What you need is only one loop with 2 variables.
.row
   - for (var j = 1, i = 11; j < 12; j++, i--)
     div(class="col-"+j+" col-offset-"+i)= val

Below script demonstrates how that loop works.

for(var j = 1, i = 11; j < 12; j++, i--) {
  console.log("col-" + j+ " col-offset-" + i);
}


text:
Q: Return IObservable from WCF I'd like to be able to return an IObservable from a WCF call, either directly or from a callback.  The reason for this is so that I can receive an enumerable that I will subscribe to and be able to process the results one at a time.
I could easily use a callback to just get push notification of the results one at a time, but then I would have no knowledge of when the series ends, and not be able to unsubscribe.
The obvious reason I can't return an IObservable would seem to be because IObservable isn't serializable.  Is there something I haven't thought of that will get this to work?

A: An IObservable pushes results at you. You can't tell when an IObservable will end, only that it has. This is their nature.
There is no reason for you to serialize the interface itself.
I'm a bit confused about what you are expecting this method to return - you mention you are expecting an enumerable (i.e. IEnumerable?) making this a request/response call with a single result. If this is the case, you can use Observable.FromAsyncPattern to easily create a IObservable for the result.
If, however, the results will be pushed individually from the Server over a Stream or via a Callback, then you can just create a wrapper via Observable.Create that initiates the connection/request on Subscribe and pushes results out via OnNext as they come back, and have the Dispose close the stream etc.
Essentially either way, you are creating a proxy on the client side that exposes a regular WCF client through a locally created IObservable interface. This is pretty much how all IObservable services work.
If on the server side you have an IObservable to return, you'll need to do the reverse there - translate a regular client side call into a subscription against the IObservable from which you send results back to the client via regular WCF Streams or Callbacks.


text:
Q: Why is my for loop not re-evaluating condition after 'continue'? I am learning js and I can't figure out why my loop isn't working. pos is an object {i, j}. I want the loop to start at pos.i-1 until pos.i+1 and the same for j. Board is a matrix(table) and the if statements are to make sure the i and j values don't go beyond the matrix size and that the cell in the given position is skipped. The problem is when the code gets to 'continue' it does i++ or j++ but doesn't return to the condition in the for loop and just keeps going. I would love to know why that is and what I can do to make it work the way I need it to.

function expandShown(board, pos) {
    for (var i = pos.i - 1; i <= pos.i + 1; i++) {
        if (i < 0 || i >= board.length) continue;

        for (var j = pos.j - 1; j <= pos.j + 1; j++) {
            if (j < 0 || j >= board.length) continue;
            if (i === pos.i && j === pos.j) continue;

            var currCell = board[i][j];
            if (!currCell.isShown) {
                currCell.isShown = true;
                gGame.shownCount++;
                var cellToRender = document.querySelector(`#cell-${i}-${j}`);
                var strToRender = (currCell.isMine) ? MINE : currCell.minesAroundCount;
                renderCell(cellToRender, strToRender);
            }
        }
    }
}

A: Thats how continue work: https://www.w3schools.com/jsref/jsref_continue.asp
The continue statement breaks one iteration (in the loop) if a specified condition occurs, and continues with the next iteration in the loop.

A: A continue statement is used to stop the execution of the current iteration of a loop, and jump straight to the next iteration:

The continue statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
— MDN Web Docs