text:
Q: Intent provided by Cursor is not fired correctly (LiveFolders) In my desperation with trying to get LiveFolders working, I have tried the following in my LiveFolder ContentProvider:
public Cursor query(Uri uri, String[] projection, String selection,
        String[] selectionArgs, String sortOrder) {
    MatrixCursor mc = new MatrixCursor(new String[] { LiveFolders._ID, LiveFolders.NAME, LiveFolders.INTENT } );
    Intent i = null;

    for (int j=0; j < 5; j++) {
        i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com/"));
        mc.addRow(new Object[] { j, "hello", i} );
    }

    return mc;
}

Which, in all normalness, should launch the Browser and display the Google homepage when clicking on an item in the LiveFolder. But it doesn't. It gives a Application is not installed on your phone error. No, I'm not defining a base intent for my LiveFolder.
logcat says:
I/ActivityManager(   74): Starting activity: Intent { act=android.intent.action.VIEW dat=Intent { act=android.intent.action.VIEW dat=http://www.google.com/ } flg=0x10000000 }

It seems it embeds the Intent I give it in the data section of the actually fired Intent. Why is it doing this? I'm really starting to believe it's a platform bug.

Update: I have filed an issue and removed the LiveFolders feature. I will include it in my app when I'll get a response either here or there that clarifies this thing. If I get the time I think I'll upload a demo app to that issue.

Update: I have received a notification that the bounty is expiring in 3 days. No one wants it? :)

Update 04/25/2010: I have updated the issue on the Android project and uploaded a test application. It would be nice if someone could test this application on a device, maybe it's such a subtle problem that it only appears on the emulator.

A: I face the same; and can unfortunately confirm it: The intent is wrapped into the data part of the intent to be fired.
I an wondering if the other predefined CURSOR-columns are evaluated correctly; I thought about filing a bug for the case custom icons (per entry, not one for all of them) are to be returned; but failed. In the whole web I did not find any example or person who were successfull using these columns; only name and id seem to work.
This is one of the main USP features of Android, and it looks like it just failed to be accepted commonly.

A: I'm having a similar issue as well.  I think it is because when the Cursor sends it's data to CursorWindow in fillWindow it can only putBlob, putString, putLong, etc.  I'm not sure how an actual Bitmap object (ICON_BITMAP) or Intent object (INTENT) can be passed.  The MatrixCursor will do a .toString() on any object.  On an Intent object would be something like: "Intent { act=android.intent.action.EDIT dat=URI }".  I don't think the system is correctly interpreting this back to the proper URI.
I've tried serializing the intent into putBlob, but Intent isn't serializable. What I have gotten to work is simply passing a URI as the Intent field.  This only gives you the default action on a particular URI, but works.  I'm also having the problem where if I specify "null" for the Intent it errors as well, even if I specify a EXTRA_LIVE_FOLDER_BASE_INTENT.  If I don't specify the field at all in the cursor the base intent works, but if I specify the field as null it fails.  It doesn't appear to fall back to the base intent.
Hope this helps...

A: Can you try hardcoding component name.
Intent intent = new Intent();
ComponentName comp = new ComponentName("com.google.android.browser",
                                   "com.google.android.browser.BrowserActivity");
intent.setComponent(comp);
intent.setAction("android.intent.action.VIEW");
intent.addCategory("android.intent.category.BROWSABLE");
Uri uri = Uri.parse(url);
intent.setData(uri);


text:
Q: Weight Multiple columns by different range of factors I have a dataframe, df, with 3 columns. A, B and C. I want to create a weighted average column but test different weights (weights need to equal to 100%).
So I can do;
weights  =np.arange(0,1,0.05)
if i+j+k=1:

for i in weights:
     for j in weights:
         for k in weights:
outname=str(i)+'A'+str(j)+'B'+str(k)+'C'

df[outname]=df['A'].multiply(k)+df['B'].multiply(i)+df['C'].multiply(j)
else:
    pass

However the number of columns may change to a larger number. Therefore this method will stop working.
Can anyone see a clever way of doing this?

A: Is this what you are looking for:
from random import randint
import pandas as pd

df = pd.DataFrame([[0,1,2],[3,4,5],[6,7,8]], columns=['A','B','C'])
weightpool = np.arange(0,1,0.05)
weights =  np.linspace(0, 0, num=df.columns.size)

for times in range(1,3):
    #all weights sum up to 1
    while weights.sum()!=1:
        #choose weights out of pool
        for i in range(len(weights)-1):
            weights[i] = weightpool[randint(0, len(weightpool)-1)]

    for i in range(len(weights)-1):
        outname =  outname + str(weights[i]) + df.columns[i]
        outvalue = df[df.columns[i]].multiply(weights[i])
        df[outname] = pd.Series(outvalue, index=df.index)

df

redpajama_set_name: RedPajamaStackExchange


text:
Q: record updated? when $stmt->execute() $stmt->affected_rows considering the following for my question:
$success = false;
$err_msg = '';
$sql = 'UPDATE task SET title = ? WHERE task_id = ?';

$conn = connect('w'); // create database connection: r= read, w= write

$stmt = $conn->stmt_init(); // initialize a prepared statement
$stmt->prepare($sql);
$stmt->bind_param('si', $_POST['title'], $_POST['id']);
$stmt->execute();

If i want to check if an insert or a deletion was succesfull, i could easily check for the affected_rows, like this:
if ($stmt->affected_rows > 0) {
   $success = true;
} else {
   $err_msg = $stmt->error;
}

If $stmt->affected_rows equals -1, it means that $stmt->execute() executed correctly but did not insert the record or did not delete the record successfully.
But, what about an update ? What is the correct way to deal with an update?
The way i do it is by checking for the return value :
$isRecordUpdated = $stmt->execute();

if (!$isRecordUpdated) {
   // execute failed, therefore NO record updated!
} else {
   //execute success, record updated!
}

Is that the correct way you guys are doing it?

A: It seems to me that there are really two equivalent and correct ways of doing this: either by checking the return value of execute as you do, or by checking the affected_rows value. -1 means the query errored out; 0 means that it did not affect (delete or update) any rows because there were none matching the query.
Since it seems there is no "better" way, you should pick what would be most convenient for your code. If e.g. using one approach over the other means that you can then share code among all types of queries, you might want to pick that one.

A: Why not store the value from mysql-affected-rows into a property of that object when you call execute()?
http://php.net/manual/en/function.mysql-affected-rows.php


text:
Q: ServiceBusTrigger Unit testing with XUNIT I have an Azure Function as below. In the following code, I'm adding a product to the database using Repository & EF Core. Is there any way we can test it using Xunit? Currently, I'm testing this using Azure Service Bus Explorer.
[FunctionName("SaveProductData")]
public void Run([ServiceBusTrigger("mytopicname", Connection = "ServiceBusConnectionString")]
ProductItemUpdate message, ILogger log)
{
    var product = new Domain.Entities.Product()
    {
       ... prop init goes here.....
    };

    log.LogInformation($"Processed Product - Sain: {message.ProductId}");
    _productRepository.Add(product);
 }

A: To elaborate on scottdavidwalker's comment with a full example:
public class SaveProductDataTests
{
    private readonly Mock<IProductRepository> _mockProductRepository = new Mock<IProductRepository>();
    private readonly Mock<ILogger> _mockLogger = new Mock<ILogger>();

    private readonly SaveProductData _saveProductData;

    public SaveProductDataTests()
    {
        _saveProductData = new SaveProductData(_mockProductRepository.Object);
    }

    [Fact]
    public void Given_When_Then()
    {
        // arrange
        var productItemUpdate = new ProductItemUpdate();

        // act
        _saveProductData.Run(productItemUpdate, _mockLogger.Object);

        // assert
        _mockProductRepository.Verify(x => x.Add(It.Is<Product>(p => p.SomeProperty == "xyz")));
    }
}

You need to create an instance of the class you are testing and mock the dependencies.
The Azure function is essentially a method (.Run()) inside the class which you can call on the instance.
In your unit test, you create the data to trigger the method and then make assertions on your mocks for what you expect to happen when the code runs for real.


text:
Q: RAID array: cannot access files on one partition, getting Input/output error I'm hitting an access error with part of a raid array and need help in troubleshooting this.
History: Several raid partitions live on 4 disks.  Four days ago some ticking noises were heard from the workstation, and the GUI ubuntu disk utility showed some bad sectors, but things were otherwise green.  Yesterday (Thurs, April 17) we got hit with a power failure and a hard reboot.  Following the hard reboot the system comes up and mounts most of the raid partitions, but one large critical one (containing /home) is throwing input/output errors.
bpbrown@eguzki:/$ ls home
ls: cannot access home: Input/output error
bpbrown@eguzki:/$

We're in Ubuntu 12.04, and owing to the loss of /home, we're at command line only.
On reboot, mdadm showed that the array was resyncing; that seems to have completed but still no luck in accessing /home.
Here are the results of mdadm:
bpbrown@eguzki:/$ sudo mdadm -D /dev/md10
/dev/md10:
    Version : 0.90
  Creation Time : Thu Feb  4 16:49:43 2010
   Raid Level : raid5
 Array Size : 2868879360 (2735.98 GiB 2937.73 GB)
Used Dev Size : 956293120 (911.99 GiB 979.24 GB)
Raid Devices : 4
 Total Devices : 4
Preferred Minor : 10
Persistence : Superblock is persistent

Update Time : Fri Apr 19 10:03:46 2013
      State : clean
 Active Devices : 4
Working Devices : 4
 Failed Devices : 0
  Spare Devices : 0

     Layout : left-symmetric
 Chunk Size : 64K

       UUID : 317df11d:4e2edc70:fa3efedc:498284d3
     Events : 0.2121101

Number   Major   Minor   RaidDevice State
   0       8       10        0      active sync   /dev/sda10
   1       8       26        1      active sync   /dev/sdb10
   2       8       42        2      active sync   /dev/sdc10
   3       8       58        3      active sync   /dev/sdd10
bpbrown@eguzki:/$

and here's mdstat:
bpbrown@eguzki:/$ cat /proc/mdstat
Personalities : [raid1] [raid6] [raid5] [raid4] [linear] [multipath] [raid0] [raid10]
md1 : active raid1 sda1[0] sdb1[1] sdc1[2] sdd1[3]
      497856 blocks [4/4] [UUUU]

md8 : active raid5 sda8[0] sdb8[1] sdc8[2] sdd8[3]
      5301120 blocks level 5, 64k chunk, algorithm 2 [4/4] [UUUU]

md6 : active raid5 sda6[0] sdb6[1] sdc6[2] sdd6[3]
      20530752 blocks level 5, 64k chunk, algorithm 2 [4/4] [UUUU]

md7 : active raid5 sda7[0] sdc7[2] sdd7[3] sdb7[1]
      5301120 blocks level 5, 64k chunk, algorithm 2 [4/4] [UUUU]

md5 : active raid5 sda5[0] sdd5[3] sdc5[2] sdb5[1]
      5301120 blocks level 5, 64k chunk, algorithm 2 [4/4] [UUUU]

md10 : active raid5 sda10[0] sdc10[2] sdd10[3] sdb10[1]
      2868879360 blocks level 5, 64k chunk, algorithm 2 [4/4] [UUUU]

unused devices: <none>
bpbrown@eguzki:/$

Unmounting and remounting /dev/md10 doesn't seem to help, though I may well have missed a step in correctly mounting the raid array.
If helpful, here's the contents of /etc/fstab:
bpbrown@eguzki:/$ more /etc/fstab
# /etc/fstab: static file system information.
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
proc            /proc           proc    defaults        0       0
/dev/md5    /               reiserfs relatime        0       1
/dev/md1    /boot           reiserfs notail,relatime 0       2
/dev/md10   /home           xfs      relatime        0       2
/dev/md8    /tmp            reiserfs relatime        0       2
/dev/md6    /usr            reiserfs relatime        0       2
/dev/md7    /var            reiserfs relatime        0       2
/dev/sda9   none            swap    pri=1           0       0
/dev/sdb9   none            swap    pri=1           0       0
/dev/sdc9   none            swap    pri=1           0       0
/dev/sdd9   none            swap    pri=1           0       0
/dev/scd0       /media/cdrom0   udf,iso9660 user,noauto,exec,utf8 0       0
bpbrown@eguzki:/$

Update April 23:
Tried mounting the filesystem directly again and got a possibly useful error message.  Here's a short version, omitting some of the call trace:
bpbrown@eguzki:/$dmesg | tail
[  788.335968] XFS (md10): Mounting Filesystem
[  788.516845] XFS (md10): Starting recovery (logdev: internal)
[  790.082900] XFS: Internal error XFS_WANT_CORRUPTED_GOTO at line 1503 of file /build/buildd/linux-3.2.0/fs/xfs/xfs_alloc.c.  Caller 0xffffffffa0226837
[  790.082905]
[  790.083004] Pid: 3211, comm: mount Tainted: P           O 3.2.0-38-generic #61-Ubuntu
[  790.083010] Call Trace:
   <omitted for brevity>
[  790.084139] XFS (md10): xfs_do_force_shutdown(0x8) called from line 3729 of file /build/buildd/linux-3.2.0/fs/xfs/xfs_bmap.c.  Return address = 0xffffffffa0236e52
[  790.217602] XFS (md10): Corruption of in-memory data detected.  Shutting down filesystem
[  790.217654] XFS (md10): Please umount the filesystem and rectify the problem(s)
[  790.217761] XFS (md10): xfs_imap_to_bp: xfs_trans_read_buf() returned error 5.
[  790.217775] XFS (md10): xlog_recover_clear_agi_bucket: failed to clear agi 5. Continuing.
<last 2 lines repeat 8 times>
[  790.388209] XFS (md10): Ending recovery (logdev: internal)
bpbrown@eguzki:/$

Thank you in advance for any suggestions on how to proceed,
--Ben

A: Turns out, the root problem here was indeed the XFS file system corruption during the unclean powerdown.  Worse, the XFS filesystem had an unresolved log file, leading to the following warnings:
bpbrown@eguzki:/$ sudo xfs_check /dev/md10
ERROR: The filesystem has valuable metadata changes in a log which needs to
be replayed.  Mount the filesystem to replay the log, and unmount it before
re-running xfs_repair.  If you are unable to mount the filesystem, then use
the -L option to destroy the log and attempt a repair.
Note that destroying the log may cause corruption -- please attempt a mount
of the filesystem before doing this.

Mounting was still failing, so we proceeded with xfs_repair -L.  This worked quickly (less than 5 minutes) and despite the dire warnings  the /home partition was mountable and readable immediately afterwards.
bpbrown@eguzki:/$ sudo xfs_repair -L /dev/md10
Phase 1 - find and verify superblock...
Phase 2 - using internal log
        - scan filesystem freespace and inode maps...
agi unlinked bucket 34 is 50978 in ag 1 (inode=536921890)
<...>
Phase 7 - verify and correct link counts...
resetting inode 97329 nlinks from 2 to 3
resetting inode 536921890 nlinks from 0 to 2
done
bpbrown@eguzki:/$

As far as we can tell, the system is functional and didn't suffer any critical data loss.
Cray ended up having some useful documentation on xfs_check and xfs_repair for someone new to those tools like myself, so I've included their link in case anyone else runs into these problems for the first time:
http://docs.cray.com/books/S-2377-22/html-S-2377-22/z1029470303.html
Cheers, and thanks to all who were reading this and thinking of ideas,
--Ben


text:
Q: VS 2017 error: "Attempted TextBuffer edit operation while another edit is in progress" As the title suggests, I often get the error when I try to edit code after running the program. I have to restart VS to make it work again.
Any other solution?

A: Closing and opening the file again should resolve the issue.This may be caused by an extension or may be "ActivityLog.xml" is lock to write by other process. Don't need to restart VS just current file.

A: In my case, I have the text:
@(@*refs.tipo + " - " +*@ (refs.tipo == "I" ? "Investigando" : "Encerrado"))

I replaced it with:
@((refs.tipo == "I" ? "Investigando" : "Encerrado"))

And it worked.

A: In my case, I was trying to edit a comment in a .cshtml in VS 2019 @**@ and whit the second character inside the comment the error popped up, so I had to write it first and then comment it.


text:
Q: Does high rep or high vote count determine whether the votes are removed when the user is deleted? If a high rep user is deleted, his "votes aren't removed as that can be destructive to the site".
I'm wondering:

*

*How high is "high rep"

*What if a user was lower reputation than the cut-off line, but was a very active user (with tons of votes).

How would a situation like this be handled
Is it done on a per-account basis at the discretion of the moderators?

A: "High rep" doesn't mean a whole lot, because it's an arbitrary number that differs from person-to-person, and even has potentially different meaning in several places of our system. For the purposes of deletion, we always considered a user "high rep" if they had 1,000 reputation. In the old deletion system, that was enough to kick you out of the automated system and send a support ticket to us instead.
But reputation and votes are not the ultimate deciding factors in whether or not votes are preserved. As I explained in another question, it's just correlative. Generally speaking, higher reputation users have more votes and are less likely to be involved in voting fraud, so their votes are more likely to be kept. A lower reputation user having a very high number of votes is more likely to be doing some inappropriate with those votes, so it's much less likely that a low reputation user's votes will be preserved. On the opposite hand, a high-rep user's votes could be destroyed (it's happened before), but that's much less common.
Ultimately, any time a user has cast enough votes to pass our thresholds, their profile will be held up for manual review by staff. But we can't explain all of the fine details of deletion and vote retention in a help center article meant to provide a basic overview of how things work.


text:
Q: Помогите поправить программу с сигналами. Qt 5.10 Добрый вечер.
Возникла проблема с сигналами.
Нужно передать данные с Form, на MainWindow. Без дополнительной формы всё реализовано, но не понятно, как соединить две вместе.
Помогите, пожалуйста.
Заранее извиняюсь за быдлокод.
Не могу правильно вставить код сюда, поэтому ссылка на скачивание: тык

mainwindow.h
public slots:
    void recieveData(QString str);

private slots:

    void on_ResultButton_clicked();

    void on_EnterDataButton_clicked();

form.h
signals:
    void sendData(QString str);

private slots:
    void on_pushButton_clicked();
    void onButtonSend();

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

form.cpp
void Form::on_pushButton_clicked()
{
    connect(this, SIGNAL(sendData(QString)), mainwindow,
SLOT(recieveData(QString)));
}

void Form::onButtonSend()
{
    QString str_DataEditForm (ui -> dateEditForm -> text());
    ui -> HBDay -> setText(str_DataEditForm);
    emit sendData(ui -> HBDay -> text());
    connect(ui -> pushButton, SIGNAL(clicked()), this,
SLOT(onButtonSend()));
}

mainwindow.cpp
void MainWindow::recieveData(QString str)
{
    connect(myform, SIGNAL(sendData(QString)), this, SLOT(recieveData(QString)));
    QString data = str;
    ui -> HBDay -> setText(data);
}

    void MainWindow::on_EnterDataButton_clicked()
{
    connect(ui->EnterDataButton, SIGNAL(clicked()), myform, SLOT(show()));
}

A: Вот работающий вариант:
Ссылка для скачивания готовый исходный код
form.h
#ifndef FORM_H
#define FORM_H

#include <QWidget>
#include <QDate>

namespace Ui {
class Form;
}

class Form : public QWidget
{
Q_OBJECT

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

signals:
void sigSetDateTime(QDate);

private slots:
void slotSetDateTime();

private:
Ui::Form *ui;
};

#endif // FORM_H

form.cpp
#include "form.h"
#include "ui_form.h"
#include <QPushButton>
#include <QDateEdit>
#include <QDebug>
#include "mainwindow.h"
#include "ui_mainwindow.h"

Form::Form(QWidget *parent) :
QWidget(parent),
ui(new Ui::Form)
{
ui->setupUi(this);
    connect(ui->pushButton, SIGNAL(clicked(bool)), this,     SLOT(slotSetDateTime()));
}

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

void Form::slotSetDateTime()
{
//-- Создали промежуточный слот для формирования сигнала со значением дата
qDebug() << "Signal from form";
emit sigSetDateTime(ui->dateEditForm->date());
}

mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include "form.h"
#include <QMainWindow>
#include <QStringList>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
 Q_OBJECT

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

private slots: //определение функций и кнопок
void on_ResultButton_clicked();
    void on_EnterDataButton_clicked();

private:
Ui::MainWindow *ui;
Form *myform;
};

#endif // MAINWINDOW_H

mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QDateEdit>
#include "form.h"

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
myform = new Form();

    //-- соединяем сигнал из формы с полем "дата" в главном окне
    connect(myform, SIGNAL(sigSetDateTime(QDate)), ui->dateEdit, SLOT(setDate(QDate)));
}

void MainWindow::on_ResultButton_clicked()
{
qint64 y;

//Вывод текущей даты
QDate currDate = QDate::currentDate();
ui -> NowTimeLabel -> setText(currDate.toString("MM/dd/yyyy"));

//Вывод введенной даты
QString str_DataEdit (ui -> dateEdit -> text());
ui -> HBDay -> setText(str_DataEdit);
QDate d = ui -> dateEdit -> date();

//Сравнение
QDate entDate(d.year(), d.month(), d.day());
y = entDate.daysTo(currDate);

//Вывод разницы между датами в label
QString y1 = QString::number(y);
ui -> DiffLabel -> setText(y1);

//Вычисление данных и их вывод
int Prospal, Morgnul, Udarov, Perekachalo, Vipito, Smeyalsya;
Prospal = 8;
Prospal = Prospal * y;
QString Prospal1 = QString::number(Prospal);
ui -> ProspalCounter -> setText(Prospal1);

Morgnul = 230137;
Morgnul = Morgnul * y;
QString Morgnul1 = QString::number(Morgnul);
ui -> MorgnulCounter -> setText(Morgnul1);

Udarov = 70000;
Udarov = Udarov * y;
QString Udarov1 = QString::number(Udarov);
ui -> UdarovCounter -> setText(Udarov1);

Perekachalo = 2000;
Perekachalo = Perekachalo * y;
QString Perekachalo1 = QString::number(Perekachalo);
ui -> PerekachaloCounter -> setText(Perekachalo1);

Vipito = 2;
Vipito = Vipito * y;
QString Vipito1 = QString::number(Vipito);
ui -> VipitoCounter -> setText(Vipito1);

Smeyalsya = 20;
Smeyalsya = Smeyalsya * y;
QString Smeyalsya1 = QString::number(Smeyalsya);
ui -> SmeyalsyaCounter -> setText(Smeyalsya1);
}

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

void MainWindow::on_EnterDataButton_clicked()
{
myform->show(); // показываем форму
}


text:
Q: Adding a class to all English text in HTML? The requirement is to add an englishText class around all english words on a page. The problem is similar to this, but the Javascript solutions wont work for me. I require a PHP example to solve this problem. For example, if you have this:

Hello, 你好

It is me, 你好

你好, how are you

Afterwards I need to end with:

Hello, 你好

It is me, 你好

你好, how are you

There are more complicated cases, such as:
你好, TEXT?

It is me, 你好

This should become:
你好, TEXT?

It is me, 你好

But I think I can sort out these edge cases once I know how actually iterate over the document correctly.
I can't use javascript to solve this because:

*

*This needs to work on browsers that don't support javascript

*I would prefer to have the classes in place on page load so there isn't any delay in rendering the text in the correct font.

I figured the best way to iterate over the document would be using PHP Simple HTML DOM Parser.
But the problem is that if I try this:
foreach ($html->find('div') as $element)
{
    // make changes here
}

My concern is that the following case will cause chaos:

       Hello , 你好

Hello, 你好

As you can see, it's going to go into the first div and then if I process that node, I will be processing the node within that too.
Any ideas how to get around this and only select the nodes for processing once?
UPDATE
I realise now that what I effectively need is a recursive way to iterate over HTML elements with the ability to change them as I iterate over them.

A: You should travel through siblings that way you won't get in trouble with such a cases...
Something like that:
<?php

foreach ($html->find('div') as $element)
{
   foreach($element->next_sibling() as $sibling){
      echo $sibling->plaintext()."\n";
   }
}

?>

Or much easier way imo:
Just...

*

*Change every <*> to "\n"."<*>" with preg_replace();

*Make an array of lines  like $lines = explode("\n",$html_string);
3.
   foreach($lines as $line){
      $text = strip_tags($line);
      echo $text;
   }


text:
Q: No logro que funcione el codicional if blade laravel Estoy intentando mostrar secciones del sitio dependiendo del rol de usuario.
Actualmente quiero filtrar una seccion que solo lo puede visualiar el rol admin y supervisor.
Esta son las tablas relacionadas:

Este es el modelo user.php
<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Notifications\UserResetPassword;

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;

    protected $fillable = [
        'id','name', 'email', 'password','role_id','password','empresa',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    // uno role puede tener varios usuarios (inversa)
    public function role(){
        return $this->belongsTo(Role::class,'role_id','id');
    }
}

Este es el modelo role.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model

{

    protected $table='roles';
    protected $primaryKey='id';

    public $timestamps=false;

    //campos que se pueden modificar
    protected $fillable=[
        'nombre'
    ];

    public function users(){
        return $this->hasMany(User::class, 'id', 'role_id');
    }
}

Hasta ahora he intentado estas opciones:
1.
{{-- solo los supervisores y admin pueden ver la seccion de accesos --}}
                    @if  (auth()->user()->role->nombre=='Admin')

                                    Acceso

                                        Usuarios

                    @endif

*

{{-- solo los supervisores y admin pueden ver la seccion de accesos --}}
                            @if  (auth()->user()->role==1 or auth()->user()->role==3)

                                            Acceso

                                                Usuarios

                            @endif

*

{{-- solo los supervisores y admin pueden ver la seccion de accesos --}}
                        @if  (auth()->user()->role==1 || auth()->user()->role==3)

                                        Acceso

                                            Usuarios

                        @endif

No me genera error pero tampoco cumple lo que necesito

A: Estás haciendo mal la consulta, si vas a evaluar el valor de la llave foránea entonces debe ser de está forma
auth()->user()->role_id === 1

Es decir debes ocupar la columna que sirve como llave foránea
Ahora sí lo que buscas es aprovechar la relación definida entonces debe ser así
auth()->user()->role->nombre === 'algo'

A: El primer problema esta en esta linea
@if  (auth()->user()->role==1 or auth()->user()->role==3)

->role no es un attributo de la tabla users, role es una relacion de users hacia la tabla roles, por lo que ->role te va a entregar un "modelo" de la tabla roles, no puedes compararlo directamente contra uno con role==1.
Recomendacion una de dos
@if (auth()->user()->role_id == 1 || ...
o
@if (auth()->user()->role->nombre === 'Admin' || ...
La segunda situacion, que no tiene que ver con esto pero lo hago notar, es que en tu Modelo User, en el $fillable tiene un attributo empresa y en tu tabla esta como empresas_id, eventualmente esto tampoco va a funcionar.
protected $fillable = [
        'id','name', 'email', 'password','role_id','password','empresa',
    ];

Ahora para que cuides mejor tus practicas te recomendaria crear una clase tipo "helper" class RolesHelper por ejemplo en donde definas los tipos de roles y sus accesos y mandas llamar esas metodos en vez de tener este tipo de definiciones por TODO tu codigo.
Si algun dia quieres modificar y actualizar "algun rol" vas a tener que andar buscando por TODO tu codigo, en cambio asi solo vas y actualizas tu class RolesHelper y punto.

A: la forma mas eficaz de administrar las secciones seria utilizar middleware debido a que es un filtrado desde el http,si llegaras a implementar lo que estas haciendo introduciendo la ruta especifica del recurso cualquier usuario independientemente de su rol podría entrar.
en caso de que quieras imprentar el middleware acá te dejo la documentación.
https://laravel.com/docs/8.x/middleware#defining-middleware
Pero una solución rápida para tu proyecto sería crear un condicional al inicio de tu vista, lo cual no es recomendable por optimización y buenas practicas, pero te puede funcionar.
<?php
 if  (auth()->user()->role!=1 || auth()->user()->role!=3){
  header("Location: http://localhots:8000/error");
   die();
 }
 ?>

Lo más recomendable es el Filtrado desde las rutas con middleware
Te dejo este link en donde se encuentra la solución detallada del middleware


text:
Q: WHILE and DO-WHILE loop not executing and gets stuck at the output FOR loop is executing but this code is not executing for while and do-while and it gets stuck after I enter the input, please help me, I am using VS Code as my IDE, compiler -- GNU GCC.
P.S :- I am executing this code on arch linux.
P.S.S :- This code is executing effectively on Windows 10 though.

    #include <stdio.h>
    int main() {
    int i,f = 1,n;
    printf("Enter a number :: ");
    scanf("%d",&n);
    i = 1;
    do
    {
        f *= i;
    }while (i <= n);
     printf("The Factorial of %d is  %d\n\n",n,f);
    return 0;
}

A:     do
    {
        f *= i;
    }while (i <= n);

nothing is changing n or i. So if i <= n it will be infinitive loop , otherwise it will exit in first comparison.


text:
Q: File copy operation does not work in a separate thread? I am trying to run code of copying files in other thread so that it may not freeze the GUI of the application.
I found that it does not seem to work in a separate thread.
Why is it not working ?
void CopyOperation::run()
{
    CopyFilesToFolder(list,sFolder);
}

bool CopyOperation::CopyFilesToFolder(const QStringList &oFileList,const QString
&sTargetFolder)
{

if(sTargetFolder.isEmpty())
 {

    status = false;
    return false;
}

QDir dir(sTargetFolder);

if(!dir.exists()) dir.mkdir(sTargetFolder);

QString sOldDirPath = dir.currentPath();

//if(!dir.setCurrent(sTargetFolder)) return false;

QFile file;
status = true;

foreach(QString sFileName,oFileList)
{
    file.setFileName(sFileName);

    QFileInfo info(sFileName);

    QString newfile =  sTargetFolder + "/" +  info.fileName();

    qDebug() << "\n name = " << newfile;

    if(!QFile::copy(sFileName,newfile))
    //if(!file.copy(newfile))
    {
        qDebug() << "\n File copy failed .. " + file.fileName() + " Error : " + file.errorString();
        status = false;
        break;
    }

}

qDebug() << "\n Result .. " << file.errorString() << "code " <<  file.error();
//dir.setCurrent(sOldDirPath);

return status;
}

A: Since you didn't post code, I just can try to guess what is the problem. Qt has a static function:
bool copy ( const QString & fileName, const QString & newName )

There is also a copy which is not static:
bool    copy ( const QString & newName )

Both of them will fail if file defined by newName already exists, ie. existing file will not be overwritten. Also, maybe path doesn't exists. Without some portion of code is difficult to guess what is the problem.


text:
Q: javascript: how can I extract the values entered in this form? This is not working for me. Can anyone tell me what I'm doing wrong?

function showValues() {
  var uIwD;
  uIwD = document.getElementById(uInputs.fWD);
  alert ("You entered: " + uIwD);
}
<form id="uInputs">
  Enter a value in the first field, then press Submit:

  <input type="number" id="fWD" value="" min="0" max ="6">
  Weekday (0 to 6 for Sun to Sat)

  <input type="number" name="fHr" value="" min="0" max ="23">
  Hour (0 to 23)

  <input type="number" name="fMins" value="" min="0" max ="59">
  Minutes (0 to 59)

  <input type="number" name="fSecs" value="" min="0" max ="59">
  Seconds (0 to 59)

  <input type="number" name="fWOffset" value="-6" min="-12" max ="12">
  wOffsetHours (-12 to 12)

  <input type="button" value="Submit" onclick="showValues()">
</form>

I enter a value of 3 in the first input field, then I click "Submit" and I get a js alert popup saying "You entered: null"
I have tried replacing name= with ID= in the first input field, and then using just that ID in GetElementbyID(), but the result is the same.
Here is a working page where you can see the result. (I tried making a fiddle for it, but when I run it in jsfiddle, I get no alert message at all. It would seem js alert pop-ups don't work in jsfiddle.)

A: You are accessing it wrong. id should be a string and then you can access the Childs with id's as  properties.
For example to test the first input box

  function showValues() {
    var uIwD;
    var uIwD = document.getElementById("uInputs");
    alert ("You entered: " + uIwD.fWD.value);
    }

 <form id="uInputs">
 Enter a value in the first field, then press Submit:

 <input type="number" id="fWD" value="" min="0" max ="6">
 Weekday (0 to 6 for Sun to Sat)

 <input type="number" name="fHr" value="" min="0" max ="23">
 Hour (0 to 23)

 <input type="number" name="fMins" value="" min="0" max ="59">
 Minutes (0 to 59)

 <input type="number" name="fSecs" value="" min="0" max ="59">
 Seconds (0 to 59)

 <input type="number" name="fWOffset" value="-6" min="-12" max ="12">
 wOffsetHours (-12 to 12)

 <input type="button" value="Submit" onclick="showValues()">
 </form>


text:
Q: How can I reference a list based on a variable within a data.frame? I have a simple table with emp_id and job_code. I would like to return the correct payout based on the job_code
I've managed this with nested ifelse's but what if I have more job_code's?
library(dplyr)
set.seed(1)

emp_id   <- round(rnorm(100, 500000, 10000))
job_code <- sample(c('a', 'b', 'c'), 100, replace = TRUE)
result   <- sample(c(1,2,3,4), 100, replace = TRUE)

df <- data.frame(emp_id = emp_id, job_code = job_code, result = result)

job_a <- c(0, 500, 1000, 5000)
job_b <- c(0, 200, 500, 750)
job_c <- c(0, 250, 750, 1000)

# Works but sucky
df %>% mutate(payout = ifelse(job_code == 'a', job_a[result],
  ifelse(job_code == 'b', job_b[result],
    job_c[result])))

and dput if you prefer:
structure(list(emp_id = c(493735, 501836, 491644, 515953, 503295,
491795, 504874, 507383, 505758, 496946, 515118, 503898, 493788,
477853, 511249, 499551, 499838, 509438, 508212, 505939, 509190,
507821, 500746, 480106, 506198, 499439, 498442, 485292, 495218,
504179, 513587, 498972, 503877, 499462, 486229, 495850, 496057,
499407, 511000, 507632, 498355, 497466, 506970, 505567, 493112,
492925, 503646, 507685, 498877, 508811, 503981, 493880, 503411,
488706, 514330, 519804, 496328, 489559, 505697, 498649, 524016,
499608, 506897, 500280, 492567, 501888, 481950, 514656, 501533,
521726, 504755, 492901, 506107, 490659, 487464, 502914, 495567,
500011, 500743, 494105, 494313, 498648, 511781, 484764, 505939,
503330, 510631, 496958, 503700, 502671, 494575, 512079, 511604,
507002, 515868, 505585, 487234, 494267, 487754, 495266), job_code = structure(c(1L,
1L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 3L, 3L, 1L, 3L, 3L, 3L, 1L, 2L,
3L, 3L, 2L, 1L, 1L, 1L, 2L, 3L, 2L, 1L, 1L, 2L, 3L, 2L, 1L, 2L,
2L, 2L, 3L, 3L, 2L, 2L, 2L, 1L, 2L, 3L, 1L, 2L, 1L, 2L, 1L, 2L,
3L, 3L, 3L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 3L, 2L, 1L, 1L, 3L, 3L,
1L, 1L, 3L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 3L, 1L,
2L, 3L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 1L, 2L, 3L, 1L,
1L, 1L, 3L), .Label = c("a", "b", "c"), class = "factor"), result = c(3,
1, 2, 2, 2, 4, 1, 4, 1, 2, 1, 1, 4, 3, 2, 2, 1, 2, 4, 3, 3, 2,
2, 4, 4, 4, 4, 4, 2, 4, 4, 2, 2, 4, 1, 2, 2, 1, 3, 4, 4, 1, 3,
2, 3, 2, 2, 1, 2, 3, 2, 1, 4, 2, 4, 2, 4, 1, 4, 2, 1, 2, 4, 2,
3, 4, 1, 3, 3, 2, 2, 3, 4, 1, 1, 2, 2, 4, 1, 2, 2, 3, 3, 4, 1,
1, 4, 4, 1, 4, 1, 1, 4, 3, 1, 2, 3, 2, 2, 1)), .Names = c("emp_id",
"job_code", "result"), row.names = c(NA, -100L), class = "data.frame")

What I'd like to do ideally is have the payouts within a data.frame but not sure how to reference it properly:
job_payouts <- data.frame(a = job_a, b = job_b, c = job_c)
# Won't work...
df %>% mutate(payout = job_payouts$job_code[result])

A: Without changing your data structure, you can do this by defining a function:
job_search <- function(code){
  var_name <- paste0("job_",code)
  if (exists(var_name)){
    return(get(var_name))
  }else{
    return(NA)
  }
}

library(data.table)
setDT(df)
df[, payout := job_search(job_code)[result], by = .(emp_id)]
df
        emp_id job_code result payout
  1: 493735        a      3   1000
  2: 501836        a      1      0
  3: 491644        b      2    200
  4: 515953        a      2    500
  5: 503295        a      2    500
  6: 491795        b      4    750
  7: 504874        b      1      0
  8: 507383        a      4   5000
  9: 505758        a      1      0
 10: 496946        c      2    250
 11: 515118        c      1      0
 12: 503898        a      1      0
 ...

However, this is a fairly unstable way to keep your data, and the paste + get syntax is convoluted.
A better way to store your data would be in a lookup table:
library(data.table)

job_a <- data.frame(payout = c(0, 500, 1000, 5000))
job_b <- data.frame(payout = c(0, 200, 500, 750))
job_c <- data.frame(payout = c(0, 250, 750, 1000))

job_lookup <- rbindlist( #this is a data.table
  l = list(a = job_a,b = job_b,c = job_c),
  idcol = TRUE
)

# create your result index
job_lookup[, result := 1:.N, by = .id]
job_lookup
    .id payout result
 1:   a      0     1
 2:   a    500     2
 3:   a   1000     3
 4:   a   5000     4
 5:   b      0     1
 6:   b    200     2
 7:   b    500     3
 8:   b    750     4
 9:   c      0     1
10:   c    250     2
11:   c    750     3
12:   c   1000     4

# merge to your initial data.frame
merge(df, job_lookup, by.x = c("job_code","result"), by.y = c(".id","result"), all.x = TRUE)

    job_code result emp_id payout
1          a      1 505758      0
2          a      1 501836      0
3          a      1 503898      0
4          a      1 494575      0
5          a      1 487464      0
6          a      1 503700      0
7          a      1 505939      0
8          a      1 503330      0
9          a      1 512079      0
10         a      1 481950      0
11         a      1 507685      0
12         a      1 490659      0
...

A: Using tools from tidyverse:
library(dplyr)
library(stringr)
library(tidyr)

# your data
set.seed(1)

emp_id <- round(rnorm(100, 500000, 10000))
job_code <- sample(c('a', 'b', 'c'), 100, replace = TRUE)
result <- sample(c(1,2,3,4), 100, replace = TRUE)

# construct a data frame
df <-
  data.frame(emp_id = emp_id,
             job_code = job_code,
             result = result,
             stringsAsFactors = FALSE)

# your jobs
job_a <- c(0, 500, 1000, 5000)
job_b <- c(0, 200, 500, 750)
job_c <- c(0, 250, 750, 1000)

# construct a data frame
my_job <-
  data.frame(job_a, job_b, job_c) %>%
  gather(job, value) %>%
  group_by(job) %>%
  mutate(result = 1:n(),
         job_code = str_replace(job, "job_", "")) %>%
  ungroup %>%
  select(-job)

# join df and my_job into my_results table
my_results <-
  left_join(df, my_job)

Results:
my_results %>% tbl_df

Source: local data frame [100 x 4]

   emp_id job_code result value
    (dbl)    (chr)  (dbl) (dbl)
1  493735        a      3  1000
2  501836        a      1     0
3  491644        b      2   200
4  515953        a      2   500
5  503295        a      2   500
6  491795        b      4   750
7  504874        b      1     0
8  507383        a      4  5000
9  505758        a      1     0
10 496946        c      2   250
..    ...      ...    ...   ...

A: This can be achieved through the super cool method of matrix indexing in base R which is extremely fast and efficient.
# build jobs payout lookup matrix, by hand (see edit below for an extension)
jobs <- rbind(job_a, job_b, job_c)

# add row names to the matrix for convenient reference
rownames(jobs) <- levels(df$job_code)

# get payout using matrix indexing
df$payout <- jobs[cbind(df$job_code, df$result)]

This returns
# print out first 6 observations
head(df)
  emp_id job_code result payout
1 493735        a      3   1000
2 501836        a      1      0
3 491644        b      2    200
4 515953        a      2    500
5 503295        a      2    500
6 491795        b      4    750

# print out jobs matrix for comparison
jobs
  [,1] [,2] [,3] [,4]
a    0  500 1000 5000
b    0  200  500  750
c    0  250  750 1000

There are a couple of details that worth mentioning.

*

*The data.frame function converts the job_code character vector, so that df$job_code is a factor variable where labels are associated with the natural numbers 1, 2, 3, ... By default, levels of the factor are ordered alphabetically by label so, in this example, the label "a" corresponds to 1, "b" to 2, and "c" to 3. You can use the levels function to find the order of the factor variable and construct the jobs matrix following that template.

*The jobs matrix is used as a lookup table. It is constructed so that these integers refer to row numbers of the jobs matrix. Then, the columns can be subset as you do with the original payout vectors.

*cbind(df$job_code, df$result) forms a 2 by nrow(df) (100) matrix which is used to look up the nrow(df) payoff values for each employee from the jobs matrix using matrix indexing. The R intro manual has a nice intro section on matrix indexing and additional details can be found in help("[").

Edit: Automating the construction of the lookup matrix
In the comments to this answer, the OP expresses concern that building the lookup matrix (which I called "jobs"), by hand would be tedious and prone to error. To address these valid concerns, we can use a somewhat obscure argument to the mget function, "ifnotfound." This argument allows us to control the output of elements of the list that mget returns when they are present in the vector of names, but not present in the environment.
In the comments, I suggested using NA to fill in missing levels in the comment below. We can extend this by using NA as the input for "ifnotfound."
Suppose df$job_code is a factor that has levels "a", "aa", "b", and "c" in that order. Then we build the look up matrix as follows:
# build vector for example, the actual code, using levels(), follows as a comment
job_codes <- c("a", "aa", "b", "c") # job_codes <- levels(df$jobcodes)

# get ordered list of payouts, with NA for missing payouts
payoutList <- mget(paste0("job_", job_codes), ifnotfound=NA)

which returns a named list.
payoutList
$job_a
[1]    0  500 1000 5000

$job_aa
[1] NA

$job_b
[1]   0 200 500 750

$job_c
[1]    0  250  750 1000

Note that payoutList$job_aa is a single NA. Now, build the matrix from this list.
# build lookup matrix using do.call() and rbind()
jobs.lookupMat <- do.call(rbind, payoutList)

jobs.lookupMat
       [,1] [,2] [,3] [,4]
job_a     0  500 1000 5000
job_aa   NA   NA   NA   NA
job_b     0  200  500  750
job_c     0  250  750 1000

The rows of the matrix are properly ordered according to the levels of the factor df$job_code, conveniently named, and NAs fill in rows wherever there is no payout.


text:
Q: Not able to navigate to a route which has a redirectTo specified in Angular2 by name My RouteConfig has the following paths defined
@RouteConfig ([
    { path:'/main',name:'Home',redirectTo: ['Setup']},
    { path:'/setup',name:'Setup',component:SetupComponent},
    { path:'/configuration',name:'Configuration',component:ConfigurationComponent},
])

In the template I have

Setup

Configuration

Home

In the component, in a method I have tried
this._Router.navigate(['Home']);

In both cases, (Using routerLink directive and Router.navigate method) when trying to navigate to 'Home' route, I am getting the following error.
Component "AppComponent" has no route named "Home"

Whereas both the routes which has a component associated to them are working as expected. The same is the behavior when they are invoked from Children routers.
How can I route/navigate to the route defined by the name 'Home'?

A: You can't assign a name to a redirect route. Since Home redirects to the route named Setup, I'd use the Setup name instead.

A: you should use / before router name this._Router.navigate(['/Home']);
see another example at Routing through links in Angular2

A: In your example code you have the home/main route object which is:
{
   path:'/main',
   name:'Home',
   redirectTo: ['Setup']
},

You need to route to the path - /main and not name - Home. So your html should be:

Setup

Configuration

Home

Your TypeScript should be
this._Router.navigate(['/main']);

Also I don't see a name property in the route interface so do consider removing it.
Hope it helps.


text:
Q: Get a file from a plugin in Microsoft Dynamics 365 I´ve installed Dynamics Version 1612 (8.2.2.112) (DB 8.2.2.112) on-premises. I wrote a plugin to connect to a web API, work perfect, now I need to add more situations. The API can return an url to a zipped file with the response in a JSON file. Well, there're any change to point me in the right direction? First, to get the file. STFW so far he gave me no clue. Thanks in advance.

A: If you have an URL then get unzip and process.
Example how to get and unzip file.
WebClient wc = new WebClient();
using (MemoryStream stream = new MemoryStream(wc.DownloadData("URL")))
{
    using (var zip = new ZipArchive(stream, ZipArchiveMode.Read))
    {
       ...
    }
}


text:
Q: Modifying a uniform variable inside a shader program to be used by another shader program - RenderMonkey RenderMonkey is pretty ancient so I'm struggling to find a way to do this. To be clear, the only reason I'm using RenderMonkey is because it's for a University assignment.
RenderMonkey allows you to define uniform variables in the workspace that your shader programs can refer to. They also offer "variable semantics" which are predefined variables that change depending on the situation. For example, time elapsed. As time increases, the float "time" increases.
I have an elephant with a gun strapped to it's back (strange I know). The gun fires particles over time. The gun also rotates over time. In order for the bullet particles to fire in the correct direction, they also need to be rotated in the same way as the gun. Applying the same rotation calculation (the one that depends on time elapsed) used for the gun, to the bullets was my first thought but this causes the bullets to continue rotating after they've been fired which isn't ideal.
I was wondering if there's a way to have one uniform variable "gunAngle" that is edited in the gun shader (i.e rotated in the gun pass) and then that modified value is given to the bullet particle shader. If that's not possible in Rendermonkey, does anyone have any ideas for a workaround to this?

A: The "gunAngle" must be calculated on the CPU and set to the uniforms in each frame. If you want to use data in multiple shader programs you have to use a Shader Storage Buffer Object or Uniform Block.


text:
Q: Windows Phone Glance Features - Developer Access? As a developer what WP Glance features can I program into my apps?
My phone tells me my current splashscreen isn't Glance compatible and nor are any of those of other apps on my phone. The fact this information is available suggests that it is possible to make such a splashscreen. Can we do this as ordinary developers, and if so, how? Or is it only for Microsoft and selected partners?
What about notifications on the Glance screen? Can we add those to our apps capabilities?

A: I managed to get the content of my wide tile onto the lock screen and onto the Glance screen, which will do me for now.
This is how I did it.
On my wide tile I have 3 lines of content. In TileAgent.ScheduledAgent.cs I set:
WideBackContent = "Line1" + "\n" + "Line2" + "\n" + "Line3";

This appears as the text content of my wide tile and after further changes to the project as 3 lines on the lock screen. On the glance screen the CRLFs get lost and it appears as one line.
To achieve this I added a lock screen icon to the project and made some changes to the app manifest file and that was it!
1) Lock Screen Icon
I created a 38x38 png file with just white and transparent pixels called LockImage.png and put it in the Assets directory immediately under the main project directory.
2) Update app manifest for Lock Screen Icon
In the
<Tokens><PrimaryToken><TemplateFlip>

section I set:
<DeviceLockImageURI IsRelative="true" IsResource="false">Assets\LockImage.png</DeviceLockImageURI>

3) Update app manifest for wide tile text on lock / glance screen
Immediately after the Tokens section I added:
<Extensions>
  <Extension ExtensionName="LockScreen_Notification_TextField" ConsumerID="{111DFF24-AA15-4A96-8006-2BFF8122084F}" TaskID="_default" />
</Extensions>

4) On the phone
In Settings/Lock Screen there is a section:
notifications
Choose an app to show detailed status.
Here I chose my app and then my wide tile text appeared on the lock screen.
In settings / glance screen I set glance screen always on (you may want a less battery intensive mode).
Then under content where it says "Select notifications and other content from lock screen settings" I set "Detailed status notification" to "On"
I still get the message "Your current app does not work with glance screen" which is fine. My apps lock screen isn't used as the glance screen but the all important text appears albeit with the CRLFs removed.


text:
Q: GCC 4.7 istream::tellg() returns -1 after reaching EOF The following code works with gcc 4.4.
But gcc 4.7 will give assertion failure.
#include <assert.h>
#include <iostream>
#include <sstream>

using namespace std;

int main()
{

    string input("abcdefg");
    stringstream iss(input);
    ostringstream oss;
    oss << iss.rdbuf();

    assert (!iss.eof());
    (void) iss.peek();
    assert (iss.eof());

    // the following assertion will fail with gcc 4.7
    assert( streamoff(iss.tellg()) ==
            streamoff(input.length()) );

    return 0;
}

In gcc 4.7, if the istream has reached EOF, tellg() will return -1. no pubseekoff() nor seekoff() will be called
In gcc 4.4 it is not a problem.
Which is the supposed to be behavior, gcc 4.4 or gcc 4.7? Why?

A: According to C++11 section 27.7.2.3p40,

if fail() != false, returns pos_type(-1)

So gcc 4.7 has the correct behavior for the current version of C++ (assuming that peek() at end of stream causes failbit to be set, and it does during sentry construction, since skipws is set by default).
Looking at the wording of C++03, it is the same.  27.6.1.3p37.  So the behavior you describe in gcc 4.4 is a bug.

A: To be precise, eofbit won't cause tellg() to return -1. But the fact that you read past EOF sets the failbit, and tellg() will return -1 if badbit or failbit are set.
The solution is to clear the status flags before calling tellg():
iss.clear();
iss.tellg();  // should work


text:
Q: How to subscribe to an event through Get-WinEvent in powershell? I'm trying to listen for a specific log entry in the windows event log, that signifies that the computer has connected to the internet:
LogName: Microsoft-Windows-NetworkProfile/Operational
Event ID: 10000

I found some code from an existing SO question and tried to adapt it for my purpose. The problem is that I can seemingly only find my event using Get-WinEvent instead of the suggested (deprecated) Get-EventLog.
The EntryWritten event does not seem to exist for WinEvent entries, is there some other event I can 'subscribe' to to listen for new entries for my event? Or should I try some other method?

$networklog = Get-WinEvent -LogName 'Microsoft-Windows-NetworkProfile/Operational'

Register-ObjectEvent -InputObject $networklog -SourceIdentifier NewEventLogEntry -EventName EntryWritten -Action {

    $entry = $event.SourceEventArgs.Entry

    if($entry.EventID -eq 10000) {
        # check_url($url)
        Write-Host "Connected"
    }
    else {
        Write-Host "Something else"
    }
}

My end goal is to have a simple script running continuously that calls a function as soon as a connection to a specific url is available. Any other suggestions for achieving this would be greatly appreciated as I feel I'm in rather deep water having not touched powershell previously.

A: For the cmdlet mentioned, you could get info by doing the following.
Tested on
(Get-CimInstance -ClassName Win32_OperatingSystem).Version
# Results
<#
10.0.19041
#>

This works in getting the info
(Get-WinEvent -LogName 'Microsoft-Windows-NetworkProfile/Operational').Count
# Results
<#
2054
#>

Get-WinEvent -LogName 'Microsoft-Windows-NetworkProfile/Operational' |
Select-Object -First 3 |
Format-Table -AutoSize
# Results
<#
   ProviderName: Microsoft-Windows-NetworkProfile

TimeCreated           Id LevelDisplayName Message
-----------           -- ---------------- -------
09-Jul-20 08:54:25  4004 Information      Network State Change Fired...
09-Jul-20 08:54:22  4004 Information      Network State Change Fired...
09-Jul-20 08:54:18 20002 Information      NSI Set Category Result...
#>

You can only get the properties present then you have to ask for text in the property
(Get-WinEvent -LogName 'Microsoft-Windows-NetworkProfile/Operational' |
Select-Object -First 1) |
Sort-Object -Property Name |
Get-Member
# Results
<#
   TypeName: System.Diagnostics.Eventing.Reader.EventLogRecord

Name                 MemberType   Definition
----                 ----------   ----------
...
Message              NoteProperty string Message=Network State Change Fired...
...
Id                   Property     int Id {get;}
Keywords             Property     System.Nullable[long] Keywords {get;}
KeywordsDisplayNames Property     System.Collections.Generic.IEnumerable[string] KeywordsDisplayNames {get;}
Level                Property     System.Nullable[byte] Level {get;}
LevelDisplayName     Property     string LevelDisplayName {get;}
LogName              Property     string LogName {get;}
MachineName          Property     string MachineName {get;}
...
ProcessId            Property     System.Nullable[int] ProcessId {get;}
Properties           Property     System.Collections.Generic.IList[System.Diagnostics.Eventing.Reader.EventProperty] Properties {get;}
...
ProviderName         Property     string ProviderName {get;}
...
RecordId             Property     System.Nullable[long] RecordId {get;}
RelatedActivityId    Property     System.Nullable[guid] RelatedActivityId {get;}
Task                 Property     System.Nullable[int] Task {get;}
TaskDisplayName      Property     string TaskDisplayName {get;}
ThreadId             Property     System.Nullable[int] ThreadId {get;}
TimeCreated          Property     System.Nullable[datetime] TimeCreated {get;}
...
#>

Event logs store details in the Message property and you can select from there.
(Get-WinEvent -LogName 'Microsoft-Windows-NetworkProfile/Operational').Message |
Select-Object -First 1
# Results
<#
Network State Change Fired
    New Internet Connection Profile: false
    Connection Cost Changed: false
    Domain Connectivity Level Changed: false
    Network Connectivity Level Changed: false
    Host Name Changed: true
    Wwan Registration State Changed: false
    Tethering Operational State Changed: false
    Tethering Client Count Changed: false
#>

You can use a hash table to filter for your ID
Get-WinEvent -FilterHashTable @{
    LogName   = 'Microsoft-Windows-NetworkProfile/Operational'
    ID        = 10000
}

# Results
<#
TimeCreated                      Id LevelDisplayName Message
-----------                      -- ---------------- -------
09-Jul-20 08:54:18            10000 Information      Network Connected...
09-Jul-20 08:54:14            10000 Information      Network Connected...
09-Jul-20 08:54:08            10000 Information      Network Connected...
...
#>

Then it's a matter of parsing that Message into the format you choose.
Or just ask for the whole message as is
(Get-WinEvent -FilterHashTable @{
    LogName   = 'Microsoft-Windows-NetworkProfile/Operational'
    ID        = 10000
}).Message

Or
(Get-WinEvent -FilterHashTable @{
    LogName   = 'Microsoft-Windows-NetworkProfile/Operational'
    ID        = 10000
}) | Select-Object -ExpandProperty Message

See also:

*

*PowerShell Get-WinEvent XML Madness: Getting details from event
logs

*Script Get-WinEventData - Extract custom EventData from the Event
Log
Update
As LeeDaily points out, you might just be better served just setting this in TaskScheduler. If you did a direct filter config in EventViewer, you get stuff like this.
<QueryList>
  <Query Id="0" Path="Microsoft-Windows-NetworkProfile/Operational">
    <Select Path="Microsoft-Windows-NetworkProfile/Operational">*[System[(Level=1  or Level=2 or Level=3 or Level=4 or Level=0 or Level=5) and (EventID=10000)]]</Select>
  </Query>
</QueryList>

So, you can see the limitation of what you can natively return, and then specifically saying, if you want more, you have to dig at the Message Property value. Take a deeper look at the XML info in the link provided where when you do you end up with code like the below, with all possible output.
# Collect the filtered events
$Events = Get-WinEvent -FilterHashTable @{
    LogName   = 'Microsoft-Windows-NetworkProfile/Operational'
    ID        = 10000
} -MaxEvents 1

# Parse out the event message data
ForEach ($Event in $Events)
{
    # Convert the event to XML
    $eventXML = [xml]$Event.ToXml()

    # Iterate through each one of the XML message properties
    For ($i=0; $i -lt $eventXML.Event.EventData.Data.Count; $i++)
    {
        # Append these as object properties
        $AddMemberSplat = @{
            InputObject = $Event
            MemberType  = 'NoteProperty'
            Force       = $true
            Name        = $eventXML.Event.EventData.Data[$i].Name
            Value       = $eventXML.Event.EventData.Data[$i].'#text'
        }
        Add-Member @AddMemberSplat
    }
}

# View the results
$Events | Select-Object * | Format-List


text:
Q: Connecting REST Proxy to Confluent Cloud trying to connect to zookeeper I'm trying to connect kafka rest proxy to confluent cloud.
kafka-rest-start ccloud-kafka-rest.properties

Here is my file with properties ccloud-kafka-rest.properties
client.ssl.endpoint.identification.algorithm=https
client.sasl.mechanism=PLAIN
consumer.request.timeout.ms=20000
bootstrap.servers=***-****.us-east-1.aws.confluent.cloud:9092
consumer.retry.backoff.ms=500
client.security.protocol=SASL_SSL
id=kafka-rest-with-ccloud
producer.acks=1
admin.request.timeout.ms=50000
client.sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required username="***" password="***";

After I run kafka-rest-start it tries connect to zookeeper (zookeeper.connect = localhost:2181).

ERROR Server died unexpectedly:  (io.confluent.kafkarest.KafkaRestMain:63)
  org.I0Itec.zkclient.exception.ZkTimeoutException: Unable to connect to zookeeper server 'localhost:2181' with timeout of 30000 ms

Also I tried to set zookeeper host empty, It didn't help.
How to turn off connecting to zookeeper?

A: The default value for the zookeeper.connect property is localhost:2181. See here
You need to populate it with the address of the zookeeper of the confluent cloud.
See the instructions for connecting a rest-proxy to kafka cloud here


text:
Q: What is a good ratio between Life, Armor and Resistances? For critical strikes there's a rule of thumb to keep crit-chance and crit-damage in a 1:10 ratio to get a good damage output.
Is there a similar calculation for the defensive values Life, Armor and Resistances?

A: There is an equally simple answer for Armor vs Resistances - you should also keep them at 10:1. One point of Resistance provides exactly the same benefit as ten points of Armor.
Formulas:

*

*Damage Resistance from Armor = Armor / (50*Level + Armor)

*Damage Resistance from Resistances = Resist / (5*Level + Resist)

Assuming attacker level to be 70, and combining both formulas together multiplicatively (as they are in the game) we can define Relative Toughness as the relation of Toughness (Effective Hit Points) to naked, no-mitigation Life.

*

*Relative Toughness = (1 + (A / 3500)) * (1 + (R / 350))

In simple terms, each 35 Armor and each 3,5 Resistance make you 1% tougher. These are multiplied together, thus:
Armor   Resistance  Relative Toughness
  0         0             100%
7000        0             300%
  0        700            300%
3500       350            400%

Concerning Life vs Mitigation there are two things to consider.
First, you need to maximize your Toughness. For this, ideal ratio would be "50% mitigation for each 500 Vitality over 1000", but this formula is practically useless, because your mitigation is going to rise at at least quadratic rate (from Armor multiplied by Resistance), and your Life will also depend on both Vitality and +% Life.
Practical advice about maximizing Toughness is simply "use item tooltips". For high-risk cases, like crafting and cubing, it is better to go the long way, comparing the complete formula for both cases.
And the most complex case is Recovery. Best survivability is not achieved by Toughness, but rather by just enough Toughness to not be one-shot, and plenty of Recovery to survive indefinitely without having to rely on potions. There is no hard rule on Recovery, but Diablo's gradual difficulty increase allows to judge for yourself - as soon as you start to rely on Potions and run in circles, you need more Recovery.
And Recovery benefits from lower Life and higher mitigation, so above mentioned "50% DR to 500 Vitality" goes out of the window :-)


text:
Q: Why would you ever need (?(R)...|...) if condition in a regex? I was looking though some regex documentation and was confused by something.  The (R) condition in the context of (?(R)...|...) is said to be:
perl was a little cryptic:

(R)

*Checks if the expression has been evaluated inside of recursion. Full syntax: (?(R)then|else)

PCRE wasn't much use:

(?(R)               overall recursion condition

and regular-expressions.info had nothing to say about it.
Is this condition to say if the subroutine stack is more than 1 level deep or does it mean something else?

A: See this explanation:

if there is no subpattern named 'R', the condition is true if a recursive call to the whole pattern or any subpattern has been made

This implies that (?(R) condition checks if the whole pattern was recursed at least once, and the result of the check is boolean, either True if recursion took place, or False otherwise.
If you need to check some examples, see https://github.com/PhilipHazel/pcre2/blob/587b94277b50ababde2380b5877c93e36ca65db8/src/pcre2_jit_test.c.


text:
Q: Python-map: builtins.KeyError in line 568 of nmap.py I am wanting to have a script which scans my local network for anybody who has opened an SSH login. I have a script which randomly generates a local IP and sees if the IP is "up". However, I keep getting a dictionary "builtins.KeyError" no matter how I change and fiddle with my code. This error only arises when I use my ipGenerator which returns an ip address as a string. If I manually enter in the IP address into the variable ip it runs fine. I am using WingIDE and I have even stopped the code at the offending line and manually entered the ip variable which was generated and the code ran fine. Yet whenever the variable is referencing the random IP generator function, the code fails with builtins.KeyError: [generated ip address]. The line of code which fails is port22 = nm[ip]['tcp'][22]['state']. Here is the code thus far:
import nmap
from generate_ip import ipPick

nm = nmap.PortScanner()

ip = ipPick()
nm.scan(ip, '22')
port22 = nm[ip]['tcp'][22]['state']

Interestingly enough the line nm.scan(ip, '22') works completely find. But it seems to fail when the dictionary entry is accessed by the problem line of code. Any ideas as to why it fails with the function and not with the manual entry?
Thanks.

A: You're trying to use nm -- a PortScanner object -- as a dictionary.
>>> type(nm)
<class 'nmap.nmap.PortScanner'>

Use this instead:
>>> scanned=nm.scan(ip, '22')
>>> scanned.keys() # list keys
dict_keys(['nmap', 'scan'])
>>> scanned['scan'][ip]['tcp'][22]['state']
'closed'


text:
Q: At what velocity was this car traveling? Throughout schooling we are given problems in which we are to solve for velocity, force, mass, etc. I have a real life situation in which I would love to solve these exact things. Please consider: Car A is a minivan stopped at a driveway, waiting to turn southbound across traffic. Car B is a large vehicle in the right lane of the northbound traffic, velocity unknown, but assumed as going plus or minus the speed limit of a road set at 40mph. Car C is a compact car completely hidden from view of Car A as it is in perfect synchronicity of angle behind Car B at the time Car A begins to cross over the northbound lanes. There is an impact between Car A and Car C, Car B not being affected at all and able to continue on, yet playing the part of being able to determine the speed of Car C. Distance traveled by Car B is approximately 1/8 of a mile before judgment by Car A determines it is safe to enter traffic. At impact, Car A is moved about 25 feet forward into the northbound lane by Car C and turned from perpendicular with the oncoming cars to almost parallel. Fortunately injuries are minimal. This is a two-part question: What would be the force at which Car A was hit, thereby determining the assumed velocity of Car C?

A: There's really no way to determine from the collision how fast C was going. There are too many variables involved to calculate anything exactly; even things like which way A's front tires were pointed can have a noticeable effect.
However, if C was in fact completely obscured by B for the duration in question, then you can use the geometric/trigonometric facts to determine C's speed given B's speed, since you can use the line of sight as a shared hypotenuse of two triangles, the northbound side of which represents the distances B and C travel in an equal time period. This also would imply that C was accelerating during that period, as would be necessary to remain obscured by B from A's perspective to one side of the road.


text:
Q: Deleting the string element from a list in python x=['152525', '852452', '85965645', 'NOSUCHINSTANCE']

I have x as shown above i wanted to remove the 'NOSUCHINSTANCE' from the array so that my output would be:
x=['152525', '852452', '85965645']

I have tried using x=x.remove('NOSUCHINSTANCE')
but its throwing me an error, is there any other way to delete bases on index.


text:
Q: Access 365 vba problem with moving specific outlook 365email message to subfolder Having problems moving Outlook specific mail item to subfolder.  I have spent time with an Outlook MVP on Access Vba Code To Move Outlook Mail Item To Different Folder Fails - Sometimes to figure this out.
Just determined that Windows 10 Access and Outlook 2019 show the same behavior.  so it must be in the code??
Maybe need an experienced Access person to take a look.
I have verified that:
Dim Mailobject As Outlook.MailItem
Dim myDestFolder As Outlook.MAPIFolder
immediately before the MOVE code, I have verified that Mailobject is still defined  and is what I want by printing mailobject.subject and mailobject.sender.
I have verified myDestFolder by printing mydestfolder.name and mydestfolder.folderpath
Note that the code does work occasionally but certainly not very often.
I have listed below my code without the processing I do on each message and hiding an email address:
Public Sub ReadInbox()
Dim a As Boolean
'''http://www.blueclaw-db.com/read_email_access_outlook.htm
Dim TempRst As DAO.Recordset
Dim TempRst2 As DAO.Recordset
Dim TempRst3 As DAO.Recordset
Dim TempRst4 As DAO.Recordset
Dim rst As DAO.Recordset

Dim mynamespace As Outlook.NameSpace
Dim myOlApp As Outlook.Application
On Error Resume Next
Set myOlApp = GetObject(, "outlook.Application")
If Err.Number <> 0 Then
    Set myOlApp = CreateObject("Outlook.Application")
    End If
    On Error GoTo 0

Set mynamespace = myOlApp.GetNamespace("MAPI")

Dim Inbox As Outlook.MAPIFolder
Dim InboxItems As Outlook.Items
Dim Mailobject As Outlook.MailItem
Dim db As DAO.Database
Dim selstr As String
Dim myDestFolder As Outlook.MAPIFolder
Dim myInbox As Outlook.folder

Dim myInbox2 As Outlook.MAPIFolder
    Dim myitems As Outlook.Items
    Dim strFilter As String

    ' let the user choose which account to use
    Set myaccounts = myOlApp.GetNamespace("MAPI").Stores

    For i = 1 To myaccounts.Count

       If myaccounts.Item(i).DisplayName = "volunteerform@?????.org" Then

        Set Items = GetFolderPath("volunteerform@?????.org\inbox").Items

            Set myInbox2 = mynamespace.Folders("volunteerform@?????.org")

            Exit For
        End If
    Next
    If myInbox2 Is Nothing Then
     'If Items Is Nothing Then
        MsgBox ("mailbox not found")
        Exit Sub ' avoid error if no account is chosen
        End If

'
'''''Set InboxItems = myInbox2.Items
Set InboxItems = Items
'
For Each Mailobject In InboxItems

If Mailobject.Subject <> "test" Then GoTo NextMessage

        MsgBox ("found one message")

        '**** do my processing here *****

    On Error GoTo 0

    'Set myDestFolder = GetFolderPath("volunteerform@????.org\inbox\Volunteeremailsprocessed")

    Set myDestFolder = myInbox2.Folders("Inbox")
    Set myDestFolder = myDestFolder.Folders("Volunteeremailsprocessed")
    'Set myDestFolder = myInbox2.Folders("Volunteeremailsprocessed")

     Stop

       Mailobject.Move myDestFolder

NextMessage:
    ' Next email message

    Next Mailobject

'''Set OlApp = Nothing
Set myInbox2 = Nothing
Set InboxItems = Nothing
Set Mailobject = Nothing

Exit Sub

error_Handling:
Stop
Dim errornumber As String
Dim errordescr As String
errornumber = Err.Number

errordescr = Err.Description
MsgBox (errornumber + "  " + errordesc)
Exit Sub

End Sub

Note that I have tried this in windows 10 with Access 2019 and Outlook 2019 with the same results/same problem.

A: OK this is code that works. It obviously has a backwards processing of messages in the inbox to avoid problems with inability to MOVE more than one matching message. However my original code code not MOVE ANY matching messages.
The code I used as a base for this solution is from a web site listed at the beginning of my code as a comment. I am thankful for that code.
Public Sub ReadInbox()
''  http://www.vbaexpress.com/forum/showthread.php?58433-VBA-Outlook-Move-mail-shared-Folder-to-shared-subfolder

Dim a As Boolean

'''******Open Outlook if not already open

On Error Resume Next
Set myOlApp = GetObject(, "outlook.Application")
If Err.Number <> 0 Then
    Set myOlApp = CreateObject("Outlook.Application")
    End If

On Error GoTo error_Handling

'''http://www.blueclaw-db.com/read_email_access_outlook.htm
'''On Error GoTo error_Handling

Dim TempRst As DAO.Recordset
Dim TempRst2 As DAO.Recordset
Dim TempRst3 As DAO.Recordset
Dim TempRst4 As DAO.Recordset
Dim rst As DAO.Recordset
Dim mynamespace As Outlook.namespace
Dim OlApp As Outlook.Application
Dim Inbox As Outlook.MAPIFolder
Dim InboxItems As Outlook.items
Dim Mailobject As Object
Dim db As DAO.Database
Dim dealer As Integer
Dim MessageBody As String
Dim selstr As String
Dim myDestFolder As Outlook.folder
Dim myInbox As Outlook.folder
Dim alreadyindb As Boolean
Dim n As Integer

'****

Set mynamespace = myOlApp.getnamespace("MAPI")

Dim NS As namespace

Dim Destinationfolder As folder
Dim myitems As Outlook.items
Dim myInbox2 As folder

Set NS = myOlApp.getnamespace("MAPI")
Set myInbox = NS.Folders("volunteerform@?????.org").Folders("Inbox")
Set myitems = myInbox.items

Set myInbox2 = NS.Folders("volunteerform@?????.org").Folders("inbox")

If myInbox2 Is Nothing Then
    Exit Sub ' avoid error if no account is chosen
    End If

Set myitems = myInbox2.items
'
''''For Each Mailobject In myitems
For n = myitems.Count To 1 Step -1

'''MsgBox ("process mailobject")

If myitems(n).Subject <> "ANV Volunteer Form Submission for Import" Then GoTo NextMessage

'************* all my processing here ********************

NextMessage:

' Next email message

Next n

'''Set OlApp = Nothing
Set myInbox2 = Nothing
Set InboxItems = Nothing
Set Mailobject = Nothing

Exit Sub

error_Handling:
Dim errornumber As String
Dim errordescr As String
errornumber = Err.Number
errordescr = Err.Description
a = WriteHistory("Process Form Retrieve_ProcessEmails", "Error = " & errornumber & " Mysection = " & MySection & "  errordescription = " & errordescr & "  MySection=" & MySection)
Exit Sub
End Sub


text:
Q: Too many if's and else if's ?? - Must be better way Everyone on this forum has helped me tremendously. Thank you.  I now have a page that functions the way I want it but my code seems to be cumbersome.  To figure out a string to echo I have a long series of if else if statements that I can't figure out how to streamline.
Here is the code in full:

Ongoing

  <?php // This is the loop for quering an individual page's events and upcoming events
  date_default_timezone_set('America/New_York');
  $todaysDate = date('Y/m/d'); // Get today's date in the right format
  $today = date("Y-m-d 00:00");  // set today's date with eastern timezone
  $todayevening = date("Y-m-d 17:00");// set limit for "today" events extending to 5 pm same day
  $tonight = date("Y-m-d 03:00", strtotime("+1 day"));// set limit for "tonight" events extending to 3:00 am next day
  $tomorrow = date("Y-m-d 03:00", strtotime("+2 days"));// set limit for "tonight" events extending to 3:00 am next next day
  $lastWeek = date("Y-m-d", strtotime("-7 days"));
  $nextWeek = date("Y/m/d", strtotime("+7 days"));

  $eventsloop = new WP_Query('post_type=event&location=' . $whatCity .'&meta_key=end_date&meta_compare=>=&meta_value=' . $todaysDate . '&orderby=meta_value&order=ASC'); // Displays the events that have not ended yet

  while($eventsloop->have_posts()) : $eventsloop->the_post(); // begin the loop after sorting the posts by location date and removing old end dates

  /* Let's get all the meta date in one call rather then so many queries */
  $event_custom_meta=get_post_custom($post->ID); // Get all the data
  if  ( $event_custom_meta )
  {
  $event_start_date = $event_custom_meta['start_date'][0];
  $event_end_date = $event_custom_meta['end_date'][0];
  $event_opening_time = $event_custom_meta['opening_time'][0];
  $event_closing_time = $event_custom_meta['closing_time'][0];
  $event_artist_talk_time = $event_custom_meta['artist_talk_time'][0];
  $event_lecture_time = $event_custom_meta['lecture_time'][0];
  $event_panel_time = $event_custom_meta['panel_time'][0];
  $event_special_event_time = $event_custom_meta['special_event_time'][0];
  $event_workshop_time = $event_custom_meta['workshop_time'][0];
  $event_custom_event_venue = $event_custom_meta['custom_event_venue'][0];
  $event_venue_info = $pieces = explode("***", $event_custom_meta[$prefix.'event_venue'][0]);
  $event_featured_event = $event_custom_meta['featured_event'][0];
  }   /* The test works. Alright, now I can echo these variables anyplace that I want */
  ?>

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

  <a href="<?php echo $event_venue_info[1]; ?>" title="<?php echo $event_venue_info[0]; ?>">

  <?php
      if ($event_venue_info[0] != 'other') {
          echo $event_venue_info[0];
          }
      if ($event_venue_info[0] == 'other') {
          echo $event_custom_event_venue;
          }
  ?>

  <?php // Format the running dates
  $writestart = preg_split ( '/\//', $event_start_date );
  $writeend = preg_split ( '/\//', $event_end_date );
  ?>

  <?php // and print nicely
  if ($event_end_date <= $nextWeek) {
      echo 'Last Chance: ';
  }
  echo date('F j', mktime( 0, 0, 0, $writestart[1], $writestart[2], $writestart[0] ) );
  echo ' through ';
  echo date('F j, Y', mktime( 0, 0, 0, $writeend[1], $writeend[2], $writeend[0] ) );
  ?>

  <?php // Check if Opening or Closing dates exist and echo the information
  $convertedtime2 = "F j, Y | g:i a"; // convert to 12 hour clock and minutes
  $opening_time_formated = date($convertedtime2, strtotime($event_opening_time));
  $closing_time_formated = date($convertedtime2, strtotime($event_closing_time));
  $artist_talk_time_formated = date($convertedtime2, strtotime($event_artist_talk_time));
  $lecture_time_formated = date($convertedtime2, strtotime($event_lecture_time));
  $panel_time_formated = date($convertedtime2, strtotime($event_panel_time));
  $special_event_time_formated = date($convertedtime2, strtotime($event_special_event_time));
  $workshop_time_formated = date($convertedtime2, strtotime($event_workshop_time));
  $end_date_formated = date('F j, Y', mktime( 0, 0, 0, $writeend[1], $writeend[2], $writeend[0] ) );

  if ($event_opening_time >= $today) {
      echo '
';
      if ($event_opening_time <= $todayevening) {
          echo 'Today: ';
      }
      else if ($event_opening_time > $todayevening && $event_opening_time <= $tonight) {
          echo 'Tonight: ';
      }
      else if ($event_opening_time > $tonight && $event_opening_time <= $tomorrow) {
          echo 'Tomorrow: ';
      }
      echo 'Opening: '.$opening_time_formated .'
';
  }

  if ($event_closing_time >= $today) {
      echo '
';
      if ($event_closing_time <= $todayevening) {
          echo 'Today: ';
      }
      else if ($event_closing_time > $todayevening && $event_closing_time <= $tonight) {
          echo 'Tonight: ';
      }
      else if ($event_closing_time > $tonight && $event_closing_time <= $tomorrow) {
          echo 'Tomorrow: ';
      }
      echo 'Closing: '.$closing_time_formated .'
';
  }

  if ($event_artist_talk_time >= $today) {
          echo '
';
      if ($event_artist_talk_time <= $todayevening) {
          echo 'Today: ';
      }
      else if ($event_artist_talk_time > $todayevening && $event_artist_talk_time <= $tonight) {
          echo 'Tonight: ';
      }
      else if ($event_artist_talk_time > $tonight && $event_artist_talk_time <= $tomorrow) {
          echo 'Tomorrow: ';
      }
      echo 'Artist Talk: '.$artist_talk_time_formated .'
';
  }

  if ($event_lecture_time >= $today) {
      echo '
';
      if ($event_lecture_time <= $todayevening) {
          echo 'Today: ';
      }
      else if ($event_lecture_time > $todayevening && $event_lecture_time <= $tonight) {
          echo 'Tonight: ';
      }
      else if ($event_lecture_time > $tonight && $event_lecture_time <= $tomorrow) {
          echo 'Tomorrow: ';
      }
      echo 'Lecture: '.$lecture_time_formated .'
';
  }

  if ($event_panel_time >= $today) {
      echo '
';
      if ($event_panel_time <= $todayevening) {
          echo 'Today: ';
      }
      else if ($event_panel_time > $todayevening && $event_panel_time <= $tonight) {
          echo 'Tonight: ';
      }
      else if ($event_panel_time > $tonight && $event_panel_time <= $tomorrow) {
          echo 'Tomorrow: ';
      }
      echo 'Panel: '.$panel_time_formated .'
';
  }

  if ($event_special_event_time >= $today) {
      echo '
';
      if ($event_special_event_time <= $todayevening) {
          echo 'Today: ';
      }
      else if ($event_special_event_time > $todayevening && $event_special_event_time <= $tonight) {
          echo 'Tonight: ';
      }
      else if ($event_special_event_time > $tonight && $event_special_event_time <= $tomorrow) {
          echo 'Tomorrow: ';
      }
      echo 'Special Event: '.$special_event_time_formated .'
';
  }

  if ($event_workshop_time >= $today) {
      echo '
';
      if ($event_workshop_time <= $todayevening) {
          echo 'Today: ';
      }
      else if ($event_workshop_time > $todayevening && $event_workshop_time <= $tonight) {
          echo 'Tonight: ';
      }
      else if ($event_workshop_time > $tonight && $event_workshop_time <= $tomorrow) {
          echo 'Tomorrow: ';
      }
      echo 'Workshop: '.$workshop_time_formated .'
';
  }

  the_excerpt();
  ?>

  <a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php echo get_the_post_thumbnail($post_id, 'half_postcard'); ?>

  <?php endwhile; ?>

Here are the inefficient if statements:
 if ($event_opening_time >= $today) {
      echo '
';
      if ($event_opening_time <= $todayevening) {
          echo 'Today: ';
      }
      else if ($event_opening_time > $todayevening && $event_opening_time <= $tonight) {
          echo 'Tonight: ';
      }
      else if ($event_opening_time > $tonight && $event_opening_time <= $tomorrow) {
          echo 'Tomorrow: ';
      }
      echo 'Opening: '.$opening_time_formated .'
';
  }

  if ($event_closing_time >= $today) {
      echo '
';
      if ($event_closing_time <= $todayevening) {
          echo 'Today: ';
      }
      else if ($event_closing_time > $todayevening && $event_closing_time <= $tonight) {
          echo 'Tonight: ';
      }
      else if ($event_closing_time > $tonight && $event_closing_time <= $tomorrow) {
          echo 'Tomorrow: ';
      }
      echo 'Closing: '.$closing_time_formated .'
';
  }

  if ($event_artist_talk_time >= $today) {
          echo '
';
      if ($event_artist_talk_time <= $todayevening) {
          echo 'Today: ';
      }
      else if ($event_artist_talk_time > $todayevening && $event_artist_talk_time <= $tonight) {
          echo 'Tonight: ';
      }
      else if ($event_artist_talk_time > $tonight && $event_artist_talk_time <= $tomorrow) {
          echo 'Tomorrow: ';
      }
      echo 'Artist Talk: '.$artist_talk_time_formated .'
';
  }

  if ($event_lecture_time >= $today) {
      echo '
';
      if ($event_lecture_time <= $todayevening) {
          echo 'Today: ';
      }
      else if ($event_lecture_time > $todayevening && $event_lecture_time <= $tonight) {
          echo 'Tonight: ';
      }
      else if ($event_lecture_time > $tonight && $event_lecture_time <= $tomorrow) {
          echo 'Tomorrow: ';
      }
      echo 'Lecture: '.$lecture_time_formated .'
';
  }

  if ($event_panel_time >= $today) {
      echo '
';
      if ($event_panel_time <= $todayevening) {
          echo 'Today: ';
      }
      else if ($event_panel_time > $todayevening && $event_panel_time <= $tonight) {
          echo 'Tonight: ';
      }
      else if ($event_panel_time > $tonight && $event_panel_time <= $tomorrow) {
          echo 'Tomorrow: ';
      }
      echo 'Panel: '.$panel_time_formated .'
';
  }

  if ($event_special_event_time >= $today) {
      echo '
';
      if ($event_special_event_time <= $todayevening) {
          echo 'Today: ';
      }
      else if ($event_special_event_time > $todayevening && $event_special_event_time <= $tonight) {
          echo 'Tonight: ';
      }
      else if ($event_special_event_time > $tonight && $event_special_event_time <= $tomorrow) {
          echo 'Tomorrow: ';
      }
      echo 'Special Event: '.$special_event_time_formated .'
';
  }

  if ($event_workshop_time >= $today) {
      echo '
';
      if ($event_workshop_time <= $todayevening) {
          echo 'Today: ';
      }
      else if ($event_workshop_time > $todayevening && $event_workshop_time <= $tonight) {
          echo 'Tonight: ';
      }
      else if ($event_workshop_time > $tonight && $event_workshop_time <= $tomorrow) {
          echo 'Tomorrow: ';
      }
      echo 'Workshop: '.$workshop_time_formated .'
';
  }

Thank you in advance for your help.  Excuse my lack of ability to use php efficiently.

A: This question probably belongs to Code Review.
Anyway, you can fill your event properties inside an array, which you can iterate:
$events = array(
  'opening'  => array(
                 'time'             => '...time here...',
                 'formatted_time'   => '...time here...',
                 'label'            => __('Opening:'),      // or ucfirst($type) if you want...
                 ),

  'closing'  => array(
                 'time'             => '...time here...',
                 'formatted_time'   => '...time here...',
                 'label'            => __('Clsoing:'),
                 ),

  'artist_talk'  => array(
                 'time'             => '...time here...',
                 'formatted_time'   => '...time here...',
                 'label'            => __('Artist Talk:'),
                 ),

  // and so on...
);

foreach($events as $type => $properties){
 if($properties['time'] >= $today) {
      echo '
';

      if ($properties['time'] <= $todayevening) {
          echo 'Today: ';
      }
      elseif ($properties['time'] > $todayevening && $properties['time'] <= $tonight) {
          echo 'Tonight: ';
      }
      elseif ($properties['time'] > $tonight && $properties['time'] <= $tomorrow) {
          echo 'Tomorrow: ';
      }

      echo ''.$properties['label'].' '.$properties['formatted_time'] .'
';
  }
}


text:
Q: liferay build-service I encountered problem in Liferay. I want to create new service exactly the same service like the one that presented in the Liferay's developer documentation. However, after copy-pasting the XML to the portlet folder I try to build t using the command on my command prompt:
ant build-service

I get nothing. It only say on the console like this:
Buildfile: D:\Program\liferay-plugins-sdk-6.1.1\portlets\NewPortlet-portlet\build.xml
build-service:

It stayed like that for so damn long, and still. I don't know what's the problem, is it because the Ant? I use the latest version of apache ant(currently: Apache Ant(TM) version 1.8.4 compiled on May 22 2012)
Is it because of configuration in the build.xml in the portlet folder?
Anybody encountered the same problem? or is it just me?

A: Ant hanging during a build task is typically because there is a cluster config enabled in a properties file.
Remove/comment out the cluster configurations and that should clear the problem.


text:
Q: [NSView reloadData]: unrecognized selector sent to instance

I am trying to learn a bit of Swift and xcode by creating a three-level outlineView in the master side of a splitView. The code crashes after exiting to reloadData (see below).  It makes one successful pass through the NSOutlineViewDataSource numberOfChildrenOfItem function (I expected a second pass before anything else happened) and then crashes with the "[NSView reloadData]:unrecognized selector sent to instance" error.  Here is what is probably the relevant code:
import Cocoa

// import WebKit
class MasterViewController: NSViewController {

@IBOutlet weak var outlineView: NSOutlineView!

var categories = [Category]()

override func viewDidLoad() {
    super.viewDidLoad()

    // Do view setup here.
    if let filePath = Bundle.main.path(forResource: "Subjects", ofType:          "plist"){
        categories = Category.categoryList(filePath)
        print(categories)
    }
    self.outlineView.reloadData()
}

}

//These are extension functions required by a NSOutlineViewDataSource
/*
Returns the number of children or grandchildren.
 One thing to note: item is an optional, and will be nil
 for the root objects of your data model. In this case,
 it will be nil for Category; otherwise it will contain
 the parent of the object. For categoryItem objects,
 item will be a Category.
 */
extension MasterViewController: NSOutlineViewDataSource {
func outlineView(_ outlineView: NSOutlineView,
                 numberOfChildrenOfItem item: Any?) -> Int {

    if let category = item as? Category {

        return category.children.count
    }else if let categoryItem = item as? CategoryItem {

        return categoryItem.grandchildren.count
    }

    return categories.count
}

And here is the error dump (I am not knowledgeable enough to make much of this):
[<ProbleMatic.Category: 0x600000048190>, <ProbleMatic.Category: 0x604000049630>, <ProbleMatic.Category: 0x60400004e100>]

2017-12-11 11:16:30.361189-0700 ProbleMatic[11382:4324228] -[NSView reloadData]: unrecognized selector sent to instance 0x6000001237a0

2017-12-11 11:16:30.361701-0700 ProbleMatic[11382:4324228] [General] -[NSView reloadData]: unrecognized selector sent to instance 0x6000001237a0

2017-12-11 11:16:30.365690-0700 ProbleMatic[11382:4324228] [General] (

    0   CoreFoundation                      0x00007fff390b300b
 __exceptionPreprocess + 171

    1   libobjc.A.dylib                     0x00007fff5fc91c76
 objc_exception_throw + 48

    2   CoreFoundation                      0x00007fff3914bcd4
 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132

    3   CoreFoundation                      0x00007fff390293f0
 ___forwarding___ + 1456

    4   CoreFoundation                      0x00007fff39028db8
 _CF_forwarding_prep_0 + 120

    5   ProbleMatic                         0x0000000100001cbc
 _T011ProbleMatic20MasterViewControllerC11viewDidLoadyyF + 1148

    6   ProbleMatic                         0x0000000100001e44
 _T011ProbleMatic20MasterViewControllerC11viewDidLoadyyFTo + 36

    7   AppKit                              0x00007fff3665b632
 -[NSViewController _sendViewDidLoad] + 97

    8   AppKit                              0x00007fff36bffd99
 _noteLoadCompletionForObject + 641

    9   AppKit                              0x00007fff365dfe21
 -[NSIBObjectData nibInstantiateWithOwner:options:topLevelObjects:] + 2042

    10  AppKit                              0x00007fff366db13a
 -[NSNib _instantiateNibWithExternalNameTable:options:] + 679

    11  AppKit                              0x00007fff366dad96
 -[NSNib _instantiateWithOwner:options:topLevelObjects:] + 136

    12  AppKit                              0x00007fff366da06c
 -[NSViewController loadView] + 343

    13  AppKit                              0x00007fff36651f32
 -[NSViewController _loadViewIfRequired] + 75

    14  AppKit                              0x00007fff36651e9d
 -[NSViewController view] + 30

    15  AppKit                              0x00007fff3666c96b
 -[_NSSplitViewItemViewWrapper wrapView] + 94

    16  AppKit                              0x00007fff3666319e
 -[NSSplitViewController _setupSplitView] + 593

    17  AppKit                              0x00007fff36662d15
 -[NSSplitViewController viewDidLoad] + 155

    18  AppKit                              0x00007fff3665b632
 -[NSViewController _sendViewDidLoad] + 97

    19  AppKit                              0x00007fff3665206d
 -[NSViewController _loadViewIfRequired] + 390

    20  AppKit                              0x00007fff36651e9d
 -[NSViewController view] + 30

    21  AppKit                              0x00007fff36aa4cc7
 __67-[NSStoryboardEmbedSegueTemplate newDefaultPerformHandlerForSegue:]_block_invoke + 171

    22  AppKit                              0x00007fff36652015
 -[NSViewController _loadViewIfRequired] + 302

    23  AppKit                              0x00007fff36651e9d
 -[NSViewController view] + 30

    24  AppKit                              0x00007fff36eeaa23
 +[NSWindow windowWithContentViewController:] + 41

    25  AppKit                              0x00007fff3714c44d
 +[NSWindowController windowControllerWithContentViewController:] + 41

    26  AppKit                              0x00007fff36aa4888
 __66-[NSStoryboardShowSegueTemplate newDefaultPerformHandlerForSegue:]_block_invoke + 172

    27  AppKit                              0x00007fff36aa4602
 -[NSStoryboardShowSegueTemplate _perform:] + 275

    28  AppKit                              0x00007fff36da775a
 -[NSApplication(NSResponder) sendAction:to:from:] + 312

    29  AppKit                              0x00007fff3684d933
 -[NSControl sendAction:to:] + 86

    30  AppKit                              0x00007fff3684d85b
 __26-[NSCell _sendActionFrom:]_block_invoke + 136

    31  AppKit                              0x00007fff3684d761
 -[NSCell _sendActionFrom:] + 183

    32  AppKit                              0x00007fff3688ea18
 -[NSButtonCell _sendActionFrom:] + 97

    33  AppKit                              0x00007fff3684bfca
 -[NSCell trackMouse:inRect:ofView:untilMouseUp:] + 2438

    34  AppKit                              0x00007fff3688e75f
 -[NSButtonCell trackMouse:inRect:ofView:untilMouseUp:] + 777

    35  AppKit                              0x00007fff3684aa64
 -[NSControl mouseDown:] + 965

    36  AppKit                              0x00007fff36f46959
 -[NSWindow(NSEventRouting) _handleMouseDownEvent:isDelayedEvent:] + 5891

    37  AppKit                              0x00007fff36f435b0
 -[NSWindow(NSEventRouting) _reallySendEvent:isDelayedEvent:] + 2359

    38  AppKit                              0x00007fff36f4285c
 -[NSWindow(NSEventRouting) sendEvent:] + 497

    39  AppKit                              0x00007fff36da3617
 -[NSApplication(NSEvent) sendEvent:] + 307

    40  AppKit                              0x00007fff36604d9d
 -[NSApplication run] + 812

    41  AppKit                              0x00007fff365d3f1a
 NSApplicationMain + 804

    42  ProbleMatic                         0x000000010000f50d
 main + 13

    43  libdyld.dylib                       0x00007fff60881115
 start + 1

    44  ???                                 0x0000000000000003
 0x0 + 3

)

Any suggestions? Thanks in advance.

A: Your outlet is probably connected to something that isn't the outline view (Most likely its superview).
You can check by…

*

*Hovering your mouse over the outlet circle

*or ctrl clicking the outline view in the view hierarchy.


text:
Q: Finding the value of the selected option in a dropdown I have the following HTML markup:

        Item Name
        Quantity

        <input type="text" class="itemized-list-item" size="20"/>
        <select>
                <option class="quantity" value="1">1</option>
                <option class="quantity" value="2">2</option>
                <option class="quantity" value="3">3</option>
                <option class="quantity" value="4">4</option>
                <option class="quantity" value="5">5</option>
            </select>

        <input type="text" class="itemized-list-item" size="20"/>
        <select>
                <option class="quantity" value="1">1</option>
                <option class="quantity" value="2">2</option>
                <option class="quantity" value="3">3</option>
                <option class="quantity" value="4">4</option>
                <option class="quantity" value="5">5</option>
            </select>

I tried the following to get the item value in the input type and the selected quantity option in the dropdown:
var quantity;
var item;
$('.itemized-list-item').each(function() {
    item = $(this).val();
    quantity = $(this).next('.quantity:selected').attr('value');
}

I get the item value but not the selected option.
I have tried many methods for hours but no avail. I hope someone can shed some light on where I am going wrong.
Cheers,
nav

A: If you're going to loop through the inputs then one way to get the associated select elements is to navigate up from the current input to the closest tr, then back down to the select:
var quantity;
var item;
$('.itemized-list-item').each(function() {
    item = $(this).val();
    quantity = $(this).closest('tr').find('select').val();
    // do something with item and quantity
});

Your use of .next('.quantity:selected') didn't work because the .next() method doesn't search through the document looking for the next matching element, it simply selects the immediate following sibling if there is one and it matches the selector you supplied and otherwise selects nothing.

A: Try this:
var quantity;
var item;
$('.itemized-list-item').each(function() {
    item = $(this).val();
    quantity = $(this).parent().next.find('.quantity:selected').attr('value');
}

A: var quantity,
    item;

$('.itemized-list-item').each(function() {
    item = this.value;
    quantity = $(this).parent().next().find('select').val();
});


text:
Q: PHP awkward function declaration
Possible Duplicate:
What does it mean to start a PHP function with an ampersand?

Recently I stumbled upon this piece of code:
public static function &get_instance()
{
return self::$instance;
}

What does this kind of function declaration &get_instance() mean? Can the function name be a variable?

A: It's part of the singleton pattern, in old-style code.
Singleton is a pattern used to make sure that there is only one instance of a class. (Technically it can be used to make sure that there are a certain number of instances of any class, but that number is almost always one.) It's one of the Gang of Four patterns and you can find endless discussion of its use and abuse all over the web.

A: It means that the result of get_instance() is being returned by reference.  Since objects are always by reference since PHP 5, it doesn't make sense to write code like that anymore.  Incidentally, the public is also particularly curious, since that means this is PHP 5 code.