text:
Q: How to create a Javascript object from an array of known keys, but with the values initialized to null? I have a JS object from which I will extract an array of keys (using Object.keys()) and then I want to use those same keys to create a different object, but this time with its values initialized to null.
In Python, I would do something like:
list_of_keys = ["key_1", "key_2"]

# The * unpacks the list, could be thought as a JS spread operator
new_dict = dict.fromkeys(*list_of_keys)

And I would retrieve a new dictionary with all its values initialized to None as a default.
I don't seem to find a similar property or method in Javascript, however.
EDIT: If using ESLint, @CerebralFart answer (the for... of...) might trigger a complaint from the linter. It can be addressed here.

A: You can use reduce method to do it:

const object = { key_1: 'value_1', key_2: 'value_2', key_3: 'value_3' };

const new_object = Object.keys(object).reduce((accumulator, currentValue)=> {
  accumulator[currentValue] = null;
  return accumulator;
}, {});

console.log(new_object)

A: There's no need to make this more complicated than a simple for loop:

const object = { key_1: 'value_1', key_2: 'value_2', key_3: 'value_3' };
const newObject = {};

for (const key in object) {
  newObject[key] = null
}

console.log(newObject);

Or, if you only have the keys

const keys = ['key_1', 'key_2', 'key_3'];
const newObject = {};

for (const key of keys) {
  newObject[key] = null
}

console.log(newObject);

ETA: You could also use Object.fromEntries with some mapping. Depending on what you want to do with the object, this may be marginally faster.

const object = { key_1: 'value_1', key_2: 'value_2', key_3: 'value_3' };

const newObject = Object.fromEntries(Object.keys(object).map(key => [key, null]));

console.log(newObject);


text:
Q: Changing default terminal As said, I'd like to change default terminal. I've set ctr+alt+t shortcut and it starts xfce4 terminal. But it's bothersome sometimes. There's an option open in terminal/open terminal when u click rmb, but it still opens previous terminal, even though I've set xfce4 as default using this:
sudo update-alternatives --config x-terminal-emulator

Does anyone know how to change it?

A: The solution is described here: Xubuntu - change default terminal to Terminator
In short, just type:
sudo exo-preferred-applications

and select the new terminal emulator.

redpajama_set_name: RedPajamaStackExchange


text:
Q: When to stop music in a music player I am building a music player with exoplayer. I am using a separate service for music playback, but the problem is that the music continues playing even when I close the main activity by going to recents. I tried to solve this problem by stopping the service when onDestroy() is called. However this also stops the music service when back button is pressed. I checked both the cases in Musixmatch and it does stop if u close the app from recents but doesn't when you press the back button in the app even though I can see that the main activity is created again when the app is started again. So how can I achieve the same in my app?

A: I have a sample android sound project - when I go to recent and 'close all' my audio stops. And using the goBack - you can pause, but if you dont it keeps playing.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_audio);
    mediaPlayer = MediaPlayer.create(this,R.raw.oldcar);
    mediaPlayer.start();
}

public void goBack(View view){
    //mediaPlayer.pause();
    Log.i("info","ending audio activity");
    finish();
}

A: So we need to stop the service when the task is removed from the recents. For that you can have a look at the solution of "stop service when remove app through recent app".
It basically suggests to stop the service when public void onTaskRemoved(Intent rootIntent) is called.
1).In your Manifest add stopWithTask attribute where you have define your service:
<service
    android:enabled="true"
    android:name=".YourService"
    android:exported="false"
    android:stopWithTask="true" />

2).If Above approach doest work then do reverse
<service
    android:enabled="true"
    android:name=".MyService"
    android:exported="false"
    android:stopWithTask="false" />  //change to false

So your service's method onTaskRemoved will be called. (Remember, it won't be called if you set stopWithTask to true).
public class YourService extends Service {

    @Override
    public void onStartService() {
        //your code
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        System.out.println("onTaskRemoved called");
        super.onTaskRemoved(rootIntent);
        //do something you want
        //stop service
        this.stopSelf();
    }
}


text:
Q: Why are new instances of a list being created when adding Tasks? I have an asp.net application in which the user can press a button to initiate a long-running operation, and may do so multiple times. Each time they do, I want to add the created task to a list so that later, when they want proceed to the next page, the page waits for all tasks in the list to be completed before redirecting.
I have the following structure:
private List<Task> tasks = new List<Task>();
private SemaphoreSlim mutex = new SemaphoreSlim(1, 1);

// Simulate some work
private async Task MyWork()
{
    int t = 0;
    while (t < 5)
    {
        await Task.Delay(TimeSpan.FromSeconds(5));
        t ++;
    }
}

// Called in the button's eventhandler
public void DoWork()
{
    mutex.Wait();
    this.tasks.Add(Task.Run(() => MyWork());
    mutex.Release();
}

When debugging I find that each time DoWork accesses the list of tasks, the list is empty when the task gets added to it, seemingly creating a separate instance of the list each time. Also, when I access the list in another method later, the list is empty there.
Why is this happening instead of each task being added to the same list instance?

A: When ASP.NET gets a new request, it creates a new instance of your page. This is why you're always seeing an empty list.
What you should do is have your button handler create a request id (e.g., a Guid), insert that request into a reliable queue, and then update the session state with that request id. So instead of a list of tasks, you have a list of request ids (strings). Then have a separate worker process read from that queue and do the actual work. Finally, the "waiting" page should poll until the requests are all completed.


text:
Q: How to select first sibling classes of a parent class with css? I've tried every possible way with numerous selectors but I cannot seem to find a way to select the class on my website. I've worked out the problem in a JS fiddle here and it works: https://jsfiddle.net/ppyjo1bk/
On my website http://wellfixreparaties.nl and I only want to show the first two reviews which are generated by a plugin. This is the structure of the css plugin:

I target the second element class like this:
.wp-google-reviews .wp-google-review: nth-of-type(2) {
     background-color: red;
}

However, this does not seem to work on my website but it does on the fiddle. I've used !important also and when not using the nth-selected I'm able to change the background of the div's.
Anyone has a idea what's holding me back from using the nth-of-type selector here?

A: there's another background-color property in your web with !Important so it's overwritting your property:
.wpac, .wpac h1, .wpac h2, .wpac h3, .wpac h4, .wpac h5, .wpac h6, .wpac p, .wpac td, .wpac dl, .wpac tr, .wpac dt, .wpac ol, .wpac form, .wpac select, .wpac option, .wpac pre, **.wpac div**, .wpac table, .wpac th, .wpac tbody, .wpac tfoot, .wpac caption, .wpac thead, .wpac ul, .wpac li, .wpac address, .wpac blockquote, .wpac dd, .wpac fieldset, .wpac li, .wpac strong, .wpac legend, .wpac em, .wpac s, .wpac cite, .wpac span, .wpac input, .wpac sup, .wpac label, .wpac dfn, .wpac object, .wpac big, .wpac q, .wpac font, .wpac samp, .wpac acronym, .wpac small, .wpac img, .wpac strike, .wpac code, .wpac sub, .wpac ins, .wpac textarea, .wpac var, .wpac a, .wpac abbr, .wpac applet, .wpac del, .wpac kbd, .wpac tt, .wpac b, .wpac i, .wpac hr {
    background-color: transparent!important;
}

add !importantto your property and it should work fine as your css sheet is loaded after that one:
.wp-google-reviews .wp-google-review: nth-of-type(2) {
         background-color: red !Important;
    }

A: Try getting rid of the space between the : and nth-of-type

A: You have a space between : and nth in your CSS. Remove that and it will work.

.wp-google-reviews .wp-google-review:nth-of-type(2) {
     background-color: red;
}

A

B

C

D

A: try this:

.wp-google-reviews div:nth-child(2) {     background-color: red;
      }

the above code selects the second div of class  wp-google-reviews


text:
Q: Unable to find a way to upload attachments using URL to ALM via REST API I have a way to attach file as binary to ALM using REST API
URL =  "https://some.almserver.com/qcbin/rest/domains/DOMAIN/projects/PROJECT/runs/<run-id>/attachments"

METHOD = "POST"

HEADERS = {

    'cache-control': "no-cache",

    "Slug": "some.html",

    'Content-Type': "application/octet-stream"

}

def attach_to_run_step():

    f = open("/path/to/some.html", "rb")

    response = requests.post(URL, headers=HEADERS, cookies=cookies, data=f.read())

    print(response.content)

I couldn't find any way to upload attachments which are in url format (from X website to ALM directly using REST)
But from ALM UI, we have option to upload attachment using URL.
Expecting METHOD, HEADERS, Request payload to upload url to ALM.

A: You need to authenticate and get the ALM session before trying to do anything else.
Check out the Documentation for details.
Here is a sample code (sorry I'm not a Python guy, but it works):
import requests
session = requests.session()
response = session.post("http://xxx.xxx.xxx.xxx:8080/qcbin/authentication-point/alm-authenticate", headers={
    'Content-Type': 'application/xml'
}, data="<alm-authentication><user>user</user><password>password</password></alm-authentication>")

response = session.post("http://xxx.xxx.xxx.xxx:8080/qcbin/rest/site-session")

file = open("/path/to/some.html", "rb")

headers = {
    'Content-Type': 'application/octet-stream',
    'Slug': 'some.html'
}
response = session.post("http://xxx.xxx.xxx.xxx:8080/qcbin/rest/domains/DEFAULT/projects/demo/run-steps/1263/attachments", headers=headers, data=file.read())
print(response.text)

Just replace user, password and run-step ID with your own.
P.S. We are developing commercial platform for integrating various test frameworks with ALM, which is called Agiletestware Bumblebee, so you might want to have a look at it.


text:
Q: Why my model field is getting prepopulated in admin? I have created a model as below.
class UserPost(models.Model):
    author = models.ForeignKey(User, related_name='userpost', null=True, on_delete=models.CASCADE)
    post_date = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=150, blank=False)
    post_body = models.TextField(blank=True, null=True, default='text')
    image = models.ImageField(upload_to='post_pics', blank=True)
    likes = models.ManyToManyField(User, blank=True, related_name='post_likes')

I am not populating likes field anywhere, my admin screenshot is below.Why my likes field is getting populated with all the users created?
admin screenshot
admin.py
from django.contrib import admin
from feed.models import UserPost
# Register your models here.
admin.site.register(UserPost)

Edit 1:
Adding a screenshot for Rishabh's answer.
trying to add user from left as suggested by him

A: You are using ManyToManyField of Django which will show you all records of User table left side and you can add them by double clicking on them or by clicking '+' sign, so your likes field is not prepopulated at all it is just showing User table data.


text:
Q: How to get past X-Frame-Options in javascript I am trying to embed the youtube live chat for youtube live events. I am having trouble when getting past the X-Frame-Options set to SAMEORIGIN. I don't have access to install php or anything on our server as it is pbs provided. I have seen solutions with pho. So is there anyway to do this with javascript?

A: No, absolutely not.
You can't use client side code to override security instructions given to the client by another site.

YouTube provide embed code for their videos, just use that (it might be possible for it to be disabled for some videos in which case this might not be an option).


text:
Q: html object to call php and return string I want to call a php script (with args) from HTML and to process the returned data
I tried various flavours of :
<object id=test1 data="object.php" type="text/plain">

where object.php just returns a string, like
<?php print "firstText:Hello World";?>

I can't work out how to retrieve the returned string.
I was hoping to find it in something like
document.getElementById("test1").firstText
But no joy
Why am I doing this, you ask?
I'd like to get the page working interactively between the user and the server, avoiding the repainting of the browser window that comes with  re-submitting with POST/GET.

A: Thanks for your responses.
I'm not happy using JQuery - another layer beyond my control
I have eventually found the returned text in
document.getElementById("test1").contentDocument.body.firstChild.textContent

which I can then work with.
Thanks

A: Use AJAX. Here's an example using jQuery:
$.get('yourpage.php', function(response){
    // response contains the string returned by your PHP page.
});

A: PaulPros idea is probably your best method. Don't forget to include jQuery.
Is there any reason you could not just make the .HTML a .php file and include your script?


text:
Q: high-level IPC library needed Suppose that we have four process A, B, C, and D.  Usually, B-D send packets to A and get a reply from A.  (The packet represents a simple command, so it is very small)  However, sometimes, 'A' broadcasts an event, so that all of B-D should be notified.
At first glance, My mind came up with 'dbus'.  Unfortunately, we need a open source library that is not GPLed. (LGPL or BSD should be nice)
Is there any good library to recommend to me?
The target will be various linux devices (kernel 2.6.x and glibc 2.8.x) without X window system.
Thanks.

A: Actually, the D-Bus daemon and reference client-side implementation is dual licensed, with the AFL version 2.1 offered as an alternative to the GPL. So perhaps it is suitable for your uses after all.


text:
Q: Grub unable to boot installation windows installation, error: cannot load image I sort of have a specific problem.
I am new to dual booting, this being my second time.
I accidentally installed and upgrade to my manjaro kernel which had rt at the end, which caused a lot of errors to me, one of the first making the efivarfs filesystem unmountable, and this is - I believe - another problem from that.
Some days after rebooting my laptop, it couldn't identify any bootable device nor partition, which was a very weird problem that I fixed by using chroot on my manjaro bootable usb, and installing grub.
I straight after that updated my kernel to a non-rt version which stopped the first problem, but isn't fixing the second: I am unable to boot into Windows from grub.
Both are UEFI. (Well, I think so. I don't think I checked Windows, but I did check Manjaro), one of the ways I tried to solve this being going into the grub commandline and trying to boot into windows using the bootmgfw.efi file in /Windows/Boot/EFI/. Which results with a screen in windows saying something about windows failing to start because of a recent hardware change.
It tells me to reinstall it, but I do not wish to lose the data and I do not have my live installation media for windows,thus it is not an option.
So, I try to use the bootmgr.efi file because it is the boot manager, but grub says it cannot load the image, even after trying grub-update.
(If you couldn't tell, most of the things I did were off reading other answers and questions online).

A: Just passing through . . . but I do have some experience with multi-booting in a Mac environment, and now in Sys76 laptop . . . .  Basically until you have added "windows" or in my case, "OSX" possibly the UUID location into grub, grub will show the OSX partitions but it won't boot them.  And, in return, any OSX upgrades will wipe all grub connections to linux . . . .
So, I use grub only to launch linux apps and I use the OSX boot manager to boot to OSX, i.e., keep them "separate" . . . .  So, in your case if you try the keystroke that takes you to the BIOS, then see if it will show "windows" listed and try to boot it that way . . . .  Or, in the case of OSX "not playing well with others,"  OSX installs go into the drive first, then linux and grub after.  Since it doesn't take much time to run a linux install, you could try erasing the Manjaro partition and then see if you only have windows installed, will it boot??  If not, then maybe there is a problem with the windows install???  If it's an OEM windows computer then the mobo should first be looking for windows to boot, and then it might go to grub.  But if grub went in with Manjaro install then grub is only going to boot . . . Manjaro.  Manjaro seems to be fairly friendly to grub updates, but ubuntu hasn't been that great for multi-booting, it seems to wipe out all other contestants and just boot itself.
So, if you need to have grub boot windows I have no experience with that, I keep apples with apples and just use grub for linux, because the situation is usually "dynamic" and your work to enter the UUID numbers for windows into grub will likely get wiped with some upgrade, although having just windows and manjaro isn't too complicated to fix.

A: There has been some time since this and I've since then deleted Windows, but I figured out how to fix this. The general problem was NOT the realtime kernel, but rather windows updating (or setting an option when it was turned off) which caused both itself and linux to not be bootable.
After restoring Linux with a different installation media, and fixing grub, it couldn't boot into Windows because of that option, I think. If you come upon this and wish to get an answer, I suggest you use an installation media of Windows that you flashed either from a different PC, or a Phone (you can look up how to do that, it's rather handy. My problem was that I didn't have access to a PC and I didn't know a phone could flash an ISO to a USB, so I re-lay this information to you.)
Plug it in to your PC that has the non-working Windows partition, boot from USB, then on the initial setup screen, enter your language and other preferences, and then select Next. If you don't see the setup screen, your PC might not be set up to boot from a drive. Check your PC manufacturer's website for info on how to change your PC's boot order, and then try again.
Then select Repair your computer.
On the Choose an option screen, select Troubleshoot. From there, you can restore from a system restore point by selecting Advanced options > System Restore. This will remove recently installed apps, drivers, and updates that might be causing your PC problems. Restoring from a restore point won't affect your personal files.
Those steps were taken from here. If it doesn't work for you, or you have a different circumstance, you might want to look up something else, good luck to you.


text:
Q: How to get Ip address in php I have installed Apache server 2.2.22, Php 5.4.5 and Mysql 5.5.27 on Windows 7 operating system. Every thing work good. But I don't get Ip address. Here is my Ip address collecting code
<?php

//Test if it is a shared client
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
    $ip = $_SERVER['HTTP_CLIENT_IP'];
    //Is it a proxy address
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
    $ip = $_SERVER['REMOTE_ADDR'];
}
//The value of $ip at this point would look something like: "192.0.34.166"
$ip = ip2long($ip);

Anyone can help me how can I get Ip address. do I need to change or modify Apache httpd.conf or php.ini file for solving this problem.

A: Simple method to get user IP address
<?PHP

function getUserIP()
{
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];

    if(filter_var($client, FILTER_VALIDATE_IP))
    {
        $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
        $ip = $forward;
    }
    else
    {
        $ip = $remote;
    }

    return $ip;
}

$user_ip = getUserIP();

echo $user_ip; // Output IP address [Ex: 177.87.193.134]

?>

A: You can get server IP with $_SERVER['SERVER_ADDR'] and $_SERVER['REMOTE_ADDR'] will return the IP address from which the user is viewing.


text:
Q: Kendo Scheduler in a Kendo Mobile App I'm trying to get the new kendo scheduler widget to work in a kendo mobile application. As soon as I switch views (Go from month to week), it crashes. Same code works great on Chrome and Firefox. The error in logcat is
Uncaught TypeError: Cannot call method 'destroy' of undefined at file:///android_asset/www/app/frameworks/kendoui/js/kendo.all.min.js:30

A: I know this question is pretty old, but I ran into this issue today. It seems like if you set the individual "editables" to false you get the same results without the error.
So instead of:
editable: false

try using:
editable: {
  create: false,
  destroy: false,
  resize: false,
  update: false
}


text:
Q: Uncaught SyntaxError: Unexpected token '!' using jquery, dataTables and ajax I have a script witch is using dataTables and an Ajax call for data.
The script in general works fine but I would like to catch a zero data return and if zero, open a modal.
But the script generates an error, see below. Can anyone see where I am going wrong.

Uncaught SyntaxError: Unexpected token '!'

rowCallback: function(row, data, index){
  $('td', row).attr('nowrap','nowrap');
  if(data.Signage == 2 || data.Signage == 1 ){
    $('#SignageOn').show();
  } else if (data.Signage == 0) {
    $('#SignageOn').hide();
  }
  $(row).find('td:eq(3)').css('color', '#009900');
  $(row).find('td:eq(4)').css('color', '#CC0000');
  if (!$.trim(data)){ // Uncaught SyntaxError: Unexpected token '!'
    // do something
  }
},


text:
Q: How set condition Jetbrains.Annotations for Task I want to give to analyzer information about nullable or not item inside of Task.
For example:
[NotNull]
[CoolAttributeForTask]
public Task<object> DoHardWordAsync()
{
    return Task.FromResult(null);
}

In this case, I want to say to analyzer: "I know that item inside task can be null, analyze it, please".
How I can do this?

A: You can use [ItemCanBeNull]/[ItemNotNull] attributes for collection-like types (e.g. List<T>, IEnumerable<T>), task-like types (Task<T>, ValueTask<T>) and Lazy<T>.


text:
Q: How to stop a child widget inheriting parent graphics effect? I'm creating a blurred shadow effect into a QLineEdit that contains a QLabel as a child being used as the caption, however, when I apply the QGraphicsDropShadowEffect to the QLineEdit it is also applied to the QLabel:

I tried subclassing QGraphicsDropShadowEffect to stop drawing the effect into the QLabel, but I'm not sure how to manage it inside of the draw function:
        void draw(QPainter* painter)
        {
            return drawSource(painter);
        };

When I call dse = new GraphicsDropShadowEffect(this);
the effect is not drawn in any widget.

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private:
    Ui::MainWindowClass ui;
};

class GraphicsDropShadowEffect : public QGraphicsDropShadowEffect
{
    Q_OBJECT
public:
    explicit GraphicsDropShadowEffect(QObject* parent = 0) {};

    void draw(QPainter* painter)
    {
        return drawSource(painter);
    };

};

class LineEdit : public QLineEdit
{
    Q_OBJECT

public:

    QGraphicsDropShadowEffect* dse;

    QLabel* label = nullptr;
    QString caption;

    LineEdit(QWidget* parent = 0) : QLineEdit(parent)
    {
        dse = new QGraphicsDropShadowEffect(this);
        setGraphicsEffect(dse);

        dse->setBlurRadius(20);
        dse->setOffset(0);
        dse->setColor(0xff0000);
        dse->setEnabled(false);
    }

    bool runtime = true;

    void showEvent(QShowEvent*)
    {
        if (runtime)
        {
            runtime = false;

            label = new QLabel(this);
            label->setGeometry(0, -30, width(), height());
            label->setText(caption);
            label->setStyleSheet(R"(
                QLabel
                {
                    font: 12px;
                    font-weight: 900px;
                    background-color: transparent;
                    color: rgb(154, 154, 154);
                }

                QLabel:hover
                {
                    color: white;
                }
            )");

            label->raise();
            label->show();
        }
    }

    void focusInEvent(QFocusEvent* event)
    {
        dse->setEnabled(true);
        QLineEdit::focusInEvent(event);
    }

    void focusOutEvent(QFocusEvent* event)
    {
        dse->setEnabled(false);
        QLineEdit::focusOutEvent(event);
    }

};

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);

    ui.centralWidget->setStyleSheet("background-color: rgba(0, 0, 0, 155);");

    auto lineEdit = new LineEdit(this);

    lineEdit->caption = "Email";
    lineEdit->setGeometry(100, 100, 200, 100);
    lineEdit->setStyleSheet(R"(
        background-color: black;
        border-radius: 8px;
        color: rgb(154, 154, 154);
        margin-top: 60px;
        padding-left: 20px;
    )");

    auto lineEdit2 = new LineEdit(this);

    lineEdit2->caption = "Password";
    lineEdit2->setGeometry(100, 190, 200, 100);
    lineEdit2->setStyleSheet(R"(
        background-color: black;
        border-radius: 8px;
        color: rgb(154, 154, 154);
        margin-top: 60px;
        padding-left: 20px;
    )");

}


text:
Q: Import QApplication fails without error (python3) I'm trying to implementate a solution provided at Take a screenshot via a python script. [Linux] in a python script:
from PyQt5.QtWidgets import QApplication
app = QApplication([])
screen = app.primaryScreen()
screenshot = screen.grabWindow(QApplication.desktop().winId())
screenshot.save('/tmp/screenshot.png')

When running this code python just stops working without spawning an error.
BTO-user@BTO /srcpython/fod
Python 3.2.5 (default, Jul 28 2014, 01:44:48)
[GCC 4.8.3] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from PyQt5.QtWidgets import QApplication

BTO-user@BTO /srcpython/fod

The module PyQt5 is installed, but these are .dll files. Normally when I install a module there should be source files. These dll files should be a binding to Qt5 and I installed this via the cygwin dev installer. Probably something is incorrect with 1 of these 2 installations, but I tried already many re-installs. It bugs me there is not a single error report.

A: The suggestion from @simonzack lead to the solution. I ran the command in the cygwin environment, but after it ran in the normal windows environment it gave more descriptive (more or less) errors.
[The error about the DLL load failed: The specified module could not be found is solved by a combination of actions:

*

*be sure to take the last possible version http://sourceforge.net/projects/pyqt/files/PyQt5/

*add to the environmentvariable path the repository of the PyQt5 installation of the windowsversion of pythong and the repository of the Qt5 installation in windows
]


text:
Q: How to add an alias to the selected field? I want to join two tables with the id fields. Later, I want to access those fields using row.get("field_name") method from sqlx.
As far as two fields have the same name I want to add an alias to prevent the naming collision.
Here is my code snippet
let (query, values) = Query::select()
    .columns([
        (DbWorkingDay::Table, DbWorkingDay::Id) // How to add aliasl here?
    ])
    .columns([
        (DbAppointment::Table, DbAppointment::Id), // ...and here
    ])
    .from(DbWorkingDay::Table)
    .inner_join(DbAppointment::Table)
    ...

Currently, both of those fields return as id. Expected result should be working_day_id and appointment_id.
Any idea how to add aliases?

A: I was able to add alias to the column names by using sea_query::query::SelectStatement::expr_as.
The working solution would look like this
let (query, values) = Query::select()
    .columns([
        (DbWorkingDay::Table, DbWorkingDay::Id)
    ])
    .columns([
        (DbAppointment::Table, DbAppointment::Id),
    ])
+   .expr_as((DbWorkingDay::Table, DbWorkingDay::Id), Alias::new("working_day_id"))
+   .expr_as((DbAppointment::Table, DbAppointment::Id), Alias::new("appointment_id"))
    .from(DbWorkingDay::Table)
    .inner_join(DbAppointment::Table)


text:
Q: "rand()" not working, i keep getting the same number after every execute So i am creating a ATM program for my programming class, long story short, i have to create about four random numbers. My issue is my program will not create different numbers, the numbers i get when i execute my program are the same over and over.
I had srand(time(NULL)); in my main function and since my variables were global i tried to move it out of main next to my global variables, this left me with a un-compliable error. HELPPP!!!!
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#include<string.h>

int account_number = rand() % 5, pin = rand() % 3, chk_acc_bal = rand() % 4, sav_acc_bal = rand() % 5;

A: srand is a function call, this can't be placed in file scope, you can only place declarations, there.
Leave it in main, this is the place where it ought to be.

A: the problem here is that you are trying to initialize your vars at file scope with function calls.
Just try initializing your variables within your main function. Something like (I tested and works):
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#include<string.h>

int account_number, pin, chk_acc_bal, sav_acc_bal;

int main(void)
{
    srand(time(NULL));

    account_number = rand() % 5;
    pin = rand() % 3;
    chk_acc_bal = rand() % 4;
    sav_acc_bal = rand() % 5;

    printf("%d\n",account_number);
    printf("%d\n",pin);
    printf("%d\n",chk_acc_bal);
    printf("%d\n",sav_acc_bal);

    return 0;
}

Hope it helps. Best!

A: Call
srand(time(NULL));

once at the start of main. To initialize global variables with some random value using rand, use:
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#include<string.h>

int account_number, pin, chk_acc_bal, sav_acc_bal;

int main()
{
  srand(time(NULL)); //Call srand in the start of main

  account_number = rand() % 5; //Initialize variables with a random value from here
  pin = rand() % 3;
  chk_acc_bal = rand() % 4;
  sav_acc_bal = rand() % 5;

  //Rest of the code


text:
Q: AsyncStorage React-native - {"_40": 0, "_55": null, "_65": 0, "_72": null} Беру пример кода с официальной страницы @react-native-async-storage/async-storage и вставляю свои данные для теста:
const setStringValue = async (value: string) => {
  try {
    await AsyncStorage.setItem('key', value)
  } catch(e) {
    // save error
  }

  console.log('Done.')
}

const getMyStringValue = async () => {
  try {
    return await AsyncStorage.getItem('key')
  } catch(e) {
    // read error
  }

  console.log('Done.')

}

setStringValue('qwerty');
console.log(getMyStringValue());

В консоли получаю это:
{"_40": 0, "_55": null, "_65": 0, "_72": null}

В чем причина?

A: Вы пытаетесь вывести в логе результат асинхронной функции.
Чтобы это сработало, вам необходимо сначала дождаться результата выполнения этой функции.
Например так:
const fn = async () => {
  const result = await getMyStringValue();
  console.log(result);
}
fn();


text:
Q: Installing msi files into virtualenv pythons on windows So have created a .reg file that will change where the system believes python is installed so that I can run an msi and install that into the intended virtualenv.  This works but is cumbersome.
But everytime I run a python .msi installer, I see this option to "Choose a python" from a rather large list box that only has one entry.  What would be really sweet would be to be able to pick my virtual environments from that list instead of having to load one .reg file to set it to the desired VirtualENV, then another to point it back at that system python that all the virtualenvs come from.
What registry entries can I create so that I have multiple 2.7 Pythons in those "Choose a python" lists I see during msi installation?

A: You don't need to manipulate the registry because you can use binary installer (.exe) to install Python package into virtualenv. See Can I install Python windows packages into virtualenvs? for details.


text:
Q: How to submit a form twice by button click Hi I am new to javascript I wanted to submit my form twice when i clicked sumbit button if someone can advice me how to implement it using javascript. I will really appreciate it. Thankyou
<script>

  $( document ).ready(function() {

      $("#submit").on('submit', function(event) {
  event.preventDefault();
  event.stopImmediatePropagation();
});

});
</script>

my button is this
<input id="submit" name="submit" class="form-button btn button" type="submit" value="Save">


text:
Q: Description box input for photo uploads I found this code on one of the many websites I have visited tonight. I am trying to set up a photo upload page in google drive, creating a dropbox.
I am trying to get the info I put into my placeholder box, city and year to attach to the uploaded photos when they get uploaded. So I can run this and I can upload multiple images to the dropbox, but none of the description info gets attached to the files?
SERVER.GS --------------------------------------------------------------

function doGet() {
  return HtmlService.createHtmlOutputFromFile('form')
    .setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

function uploadFileToDrive(base64Data, fileName) {
  try{
    var splitBase = base64Data.split(','),
        type = splitBase[0].split(';')[0].replace('data:','');

    var byteCharacters = Utilities.base64Decode(splitBase[1]);
    var ss = Utilities.newBlob(byteCharacters, type);
    ss.setName(fileName);

    var dropbox = "Google_Dropbox"; // Folder Name
    var folder, folders = DriveApp.getFoldersByName(dropbox);

    if (folders.hasNext()) {
      folder = folders.next();
    } else {
      folder = DriveApp.createFolder(dropbox);
    }
    var file = folder.createFile(ss);

    return file.getName();
  }catch(e){
    return 'Error: ' + e.toString();
  }
}

FORM.HTML --------------------------------------------------------------

     <form id="myForm" align="center">
     <input type="text" name="myName" style="font-size: 15pt; height: 30px; width:500px "placeholder="Meeting City & Meeting Year">

     Upload Photo(s):

     <input type="file" name="filename" id="myFile" multiple>

     <input type="button" value="Submit" onclick="iteratorFileUpload()">

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">

A: You need to retrieve your description input box onSubmit, pass it to Apps Script and append its value to the file with file.setDescription(). To do so
Implement the following modifications:

*

*In function iteratorFileUpload() add the line

var description = document.getElementsByName('myName')[0].value;

*

*Modify

function sendFileToDrive(file)
to
function sendFileToDrive(file, description)

*

*Call within function iteratorFileUpload()
sendFileToDrive(allFiles[i], description);
instead of
sendFileToDrive(allFiles[i]);

*

*Call within

function sendFileToDrive(file, description)
google.script.run.withSuccessHandler(updateProgressbar).uploadFileToDrive(content, file.name, description);
instead of
google.script.run.withSuccessHandler(updateProgressbar).uploadFileToDrive(content, file.name, currFolder);

*

*Within your gs. file change

function uploadFileToDrive(base64Data, fileName)
to
function uploadFileToDrive(base64Data, fileName, description)

*

*Add after

var file = folder.createFile(ss);
the line
file.setDescription(description);


text:
Q: Using LIKE in an Oracle IN clause I know I can write a query that will return all rows that contain any number of values in a given column, like so:
Select * from tbl where my_col in (val1, val2, val3,... valn)

but if val1, for example, can appear anywhere in my_col, which has datatype varchar(300), I might instead write:
select * from tbl where my_col LIKE '%val1%'

Is there a way of combing these two techniques. I need to search for some 30 possible values that may appear anywhere in the free-form text of the column.
Combining these two statements in the following ways does not seem to work:
select * from tbl where my_col LIKE ('%val1%', '%val2%', 'val3%',....)

select * from tbl where my_col in ('%val1%', '%val2%', 'val3%',....)

A: Yes, you can use this query (Instead of 'Specialist' and 'Developer', type any strings you want separated by comma and change employees table with your table)
SELECT * FROM employees em
WHERE EXISTS (select 1 from  table(sys.dbms_debug_vc2coll('Specialist', 'Developer')) mt
              where em.job like ('%' || mt.column_value || '%'));

Why my query is better than the accepted answer: You don't need a CREATE TABLE permission to run it. This can be executed with just SELECT permissions.

A: In Oracle you can use regexp_like as follows:
select *
from   table_name
where  regexp_like (name, '^(value-1|value-2|value-3....)');

The caret (^) operator to indicate a beginning-of-line character &
The pipe (|) operator to indicate OR operation.

A: What would be useful here would be a LIKE ANY predicate as is available in PostgreSQL
SELECT *
FROM tbl
WHERE my_col LIKE ANY (ARRAY['%val1%', '%val2%', '%val3%', ...])

Unfortunately, that syntax is not available in Oracle. You can expand the quantified comparison predicate using OR, however:
SELECT *
FROM tbl
WHERE my_col LIKE '%val1%' OR my_col LIKE '%val2%' OR my_col LIKE '%val3%', ...

Or alternatively, create a semi join using an EXISTS predicate and an auxiliary array data structure (see this question for details):
SELECT *
FROM tbl t
WHERE EXISTS (
  SELECT 1
  -- Alternatively, store those values in a temp table:
  FROM TABLE (sys.ora_mining_varchar2_nt('%val1%', '%val2%', '%val3%'/*, ...*/))
  WHERE t.my_col LIKE column_value
)

For true full-text search, you might want to look at Oracle Text: http://www.oracle.com/technetwork/database/enterprise-edition/index-098492.html

A: This one is pretty fast :
select * from listofvalue l
inner join tbl on tbl.mycol like '%' || l.value || '%'

A: Just to add on @Lukas Eder answer.
An improvement to avoid creating tables and inserting values
(we could use select from dual and unpivot to achieve the same result "on the fly"):
with all_likes as
(select * from
    (select '%val1%' like_1, '%val2%' like_2, '%val3%' like_3, '%val4%' as like_4, '%val5%' as like_5 from dual)
    unpivot (
     united_columns for subquery_column in ("LIKE_1", "LIKE_2", "LIKE_3", "LIKE_4", "LIKE_5"))
  )
    select * from tbl
    where exists (select 1 from all_likes where tbl.my_col like all_likes.united_columns)

A: I prefer this
WHERE CASE WHEN my_col LIKE '%val1%' THEN 1
           WHEN my_col LIKE '%val2%' THEN 1
           WHEN my_col LIKE '%val3%' THEN 1
           ELSE 0
           END = 1

I'm not saying it's optimal but it works and it's easily understood. Most of my queries are adhoc used once so performance is generally not an issue for me.

A: A REGEXP_LIKE will do a case-insensitive regexp search.
select * from Users where Regexp_Like (User_Name, 'karl|anders|leif','i')

This will be executed as a full table scan - just as the LIKE or solution, so the performance will be really bad if the table is not small. If it's not used often at all, it might be ok.
If you need some kind of performance, you will need Oracle Text (or some external indexer).
To get substring indexing with Oracle Text you will need a CONTEXT index. It's a bit involved as it's made for indexing large documents and text using a lot of smarts. If you have particular needs, such as substring searches in numbers and all words (including "the" "an" "a", spaces, etc) , you need to create custom lexers to remove some of the smart stuff...
If you insert a lot of data, Oracle Text will not make things faster, especially if you need the index to be updated within the transactions and not periodically.

A: No, you cannot do this. The values in the IN clause must be exact matches. You could modify the select thusly:
SELECT *
  FROM tbl
 WHERE my_col LIKE %val1%
    OR my_col LIKE %val2%
    OR my_col LIKE %val3%
 ...

If the val1, val2, val3... are similar enough, you might be able to use regular expressions in the REGEXP_LIKE operator.

A: select * from tbl
 where exists (select 1 from all_likes where all_likes.value = substr(tbl.my_col,0, length(tbl.my_col)))

A: You can put your values in ODCIVARCHAR2LIST and then join it as a regular table.
select tabl1.* FROM tabl1 LEFT JOIN
(select column_value txt from table(sys.ODCIVARCHAR2LIST
('%val1%','%val2%','%val3%')
)) Vals ON tabl1.column LIKE Vals.txt WHERE Vals.txt IS NOT NULL

A: You don't need a collection type as mentioned in https://stackoverflow.com/a/6074261/802058. Just use an subquery:
SELECT *
FROM tbl t
WHERE EXISTS (
    SELECT 1
    FROM (
        SELECT 'val1%' AS val FROM dual
        UNION ALL
        SELECT 'val2%' AS val FROM dual
        -- ...
        -- or simply use an subquery here
    )
    WHERE t.my_col LIKE val
)


text:
Q: Who creates /etc/{group,gshadow,passwd,shadow}-? In any linux system I have access to (a couple of Archlinuxes, an Ubuntu, a Debian Sid and a Gentoo) there are the following 4 files in /etc/, all ending with a dash:
/etc/group-
/etc/gshadow-
/etc/passwd-
/etc/shadow-

On the internet they say that these are just backup files, updated to the next to last change.
Now I'm wondering: who's creating those files? Is it my editor? Is it the application editing those files (gpasswd, useradd, groupadd and so on)? Is it something at a lower level (maybe even a kernel module)?

A: The backup files are created by the program that modifies your /etc/group or /etc/passwd files like useradd, groupadd and the like created as a safety precaution in case files get corrupted during edit.  Kernel never touches those files.


text:
Q: What is the recommended design for public-facing APIs to support multiple POD types while maximizing binary compatibility? I am currently designing a public-facing C++ API for a product which will require a pre-compiled binary/DLL (it will be cross-platform). I would like for the API to allow the user to use any POD we support (where applicable), however the base requirements are maximum flexibility and binary compatibility. I am doing something a bit similar to CPLEX's API (it's one of several inspirations), but I'm thinking there's possibly a better way of specifying type information than how they have done it (with respect to IloInt, IloNum, IloAny, Ilo*Var, etc., see link (hopefully) for IloExtractable branch) without messing with binary compatibility. Am I wrong? I've got something in mind, but I can't recall what it is or if it'll even work, I believe it resembles something like the Visitor or Decorator patterns but for types, could someone please enlighten me on the subject? I've got my Design Patterns book by the GoF out in front of me.
Note: any syntax errors there might be here aren't part of the problem at hand.
Examples of what I believe I can't use, and the reason:
Possibly.. but this is likely to make things complicated with the Expression tree.
template<typename ValueType>
Constraint : public Expression;

Probably will impact future expansion.
IntConstraint : public Expression;
LongConstraint : public Expression;
DoubleConstraint : public Expression;

Ugly as sin, may cause plenty of subtle issues.
union Value
{
 int AsInt,
 float AsFloat
};
class Constraint : public Expression
{
  public:
  Value GetValue(Edge);
  void SetValue(Value, Edge);
  void SetUpper(Value, Vertex);
  void SetLower(Value, Vertex);
  ...
};

Edit: In response to Mads Elvheim (and after finding this link) I now realize that I don't need to exclude templates from my possibilities which is good, but I am still rather unsure it's the best idea - at least for the Constraints class (even though it's conceptually sound), forgive me for not being as clear as I thought.
In order to make my API easy to use I defined the grammar using bnf (which is rather new to me). This led to an abstract syntax tree for Expression, Constraints, and other classes which will be included which interact with Constraints. Because other classes will be interacting with Constraints, I would prefer avoiding passing as munch type information as possible until "the last minute" so to speak.. I feel like I may be missing a level of abstraction.
Studying CPLEX gives me the impression that they modeled their types by following the domains of numbers (whole and real), linear equation expression (of course) and what should accordingly be possible, which absolutely makes sense, hmm...
(Apparently I can't post more than one link as I'm a new user.)
Edit 2: As a first step I've decided to stick a ConstraintExpressionArgument in between the Constraint and Expression classes so I can still identify a constraint in my expression tree without being aware of the type it manipulates which is good.
Another detail I may have neglected to mention was that unlike in CPLEX where the Constraint class is unusable by itself, my Constraint class is currently a usable user class but like in CPLEX I also want to leave room for expansion (thus the typing issue)...
Anyway, at the moment I have the equivalent of
class ConstraintExpressionArgument : public Expression;
template<typename ValueType>
class Constraint : public ConstraintExpressionArgument;

A: Most systems provide a <types.h> or <inttypes.h> header with type definitions you can use, if the exact range or number of bits is important. I don't see a good reason to throw inheritance at the problem. You can also use std::numeric_limits together with Boost's BOOST_STATIC_ASSERT() macro to generate meaningful compile-time asserts, if a specified type or template type doesn't match a requirement. The requirement could be integer vs float, range, minimum representable value, accuracy, etc. For example:
#include <limits>
#include <inttypes.h>
#include <boost/static_assert.hpp>

template<class T, int bits> T Add(const T& a, const T& b)
{
    BOOST_STATIC_ASSERT( std::numeric_limits<T>::is_integer     );
    BOOST_STATIC_ASSERT( std::numeric_limits<T>::is_signed      );
    BOOST_STATIC_ASSERT( std::numeric_limits<T>::digits == bits );

    return a + b;
}

If std::numeric_limits doesn't have all of your types, use template specialization to extend and implement them.

A: Right, I think I've got what I need, at least for now.
The above mentioned
class ConstraintExpressionArgument : public Expression;
template<typename ValueType>
class Constraint : public ConstraintExpressionArgument;

got me on the right track to separating type from constraint-ness.


text:
Q: Files greater than 1 GB and older than 6 months I want to find files which are greater than 1 GB and older than 6 months in entire server. How to write a command for this?

A: Use find:
find /path -mtime +180 -size +1G

-mtime means search for modification times that are greater than 180 days (+180). And the -size parameter searches for files greater than 1GB.

A: find / -size +1G -mtime +180 -type f -print
Here's the explanation of the command option by option: Starting from the root directory, it finds all files bigger than 1 Gb, modified more than 180 days ago, that are of type "file", and prints their path.


text:
Q: Print only table data in Lightning Web Component(lwc) When I click on the button I need to print the only table data.
Ex:
this.template.querySelector('.tablecls');

I tried the below options
Option 1
window.print();

The above option is printing the whole window, to overcome this issue I used slds-no-print SLDS class.
but I used the Lightning Web Component in Lightning App Page when I click the print button it printing whole window with other components.
Option 2
<iframe width="100%" height="100%" class="iframeCls" lwc:dom="manual"></iframe>

// In JS code
window.frames['iframeCls'].document.body.innerHTML = this.template.querySelector('.tablecls').innerHTML;
window.frames['iframeCls'].print();

above option not working, it throwing cannot read property 'document' of undefined.
any other options to overcome this issue.


text:
Q: PyQt5 QTextEdit changes color when copy / pasting into it In my application, I have a QTextEdit. It works just fine when I write normally into it but when I copy / paste text from my IDE ( as an example - in my case, pycharm in dark mode ) into it, the QTextEdit also takes the color and background of the text.
This is the normal appearance :

This is what happens when I copy paste from my IDE :

When the color is changed, the next writing inputs will keep the same colors until the next copy / paste.
How can I avoid the QTextEdit having anything else than the default colors ( black text, white background ) ?

A: QTextEdit has the acceptRichText property.
Just set it to False.

QTextEdit allows using rich text content, and if the source you're getting the text from supports rich text for the clipboard, you'll get that.
To avoid this behavior, you can subclass QTextEdit and override insertFromMimeData(mimeData)

class TextEdit(QtWidgets.QTextEdit):
    def insertFromMimeData(self, source):
        newData = QtCore.QMimeData()
        for format in source.formats():
            if format == 'text/plain':
                newData.setData(format, source.data(format))
        super().insertFromMimeData(newData)


text:
Q: `leftJoin()` does not return the joined tables data with Objection ORM using Knex.js leftJoin only returns the first tables data but not the second table when I use the Knex leftJoin() method with an Objection.js model. The same query works fine when I do it directly in the terminal with psql
the query looks like this:
const result = await Table1Model.query()
      .leftJoin(
        'table_2',
        'table_2.table_2_id',
        'table_1.table_2_id'
      )
      .where('table_1_id', '=', table1Id);

I expect the result to include all of the  table_2 columns where there is an id match with table_1.
I am only getting columns for table_1

A: if you like to get columns only from table_2-
const result = await Table1Model.query()
      .leftJoin(
        'table_2',
        'table_2.table_2_id',
        'table_1.table_2_id'
      )
      .columns('table_2.*') // add columns
      .where('table_1_id', '=', table1Id);


text:
Q: Workflow to Wait until Date Field How can a workflow be told to wait until a specific date, or date field?
It works with timeout equals date, but I would much rather use wait until process time is on or after date.
When I try this the workflow is postponed until our distant ancestors have died of old age; it is the same if I put in a date field instead of a specific date (which is the end goal):

A: You want to consider what is considered a "timeout" for the desired behavior.  The following links provide some more context.
Also, unless you have a really specific use case for using a specific date (like year end deadlines or processing) -- you'll probably want to use a datetime field on an entity as the basis for the right side of the comparison.  You can always use the dialog on the right to choose a fixed date/time before or after any of the entity datetime fields.

http://social.technet.microsoft.com/wiki/contents/articles/11291.microsoft-dynamics-crm-2011-workflows-wait-and-timeout.aspx
http://www.powerobjects.com/blog/2012/11/06/multiple-waiting-workflows-wait-conditions-and-timeouts/
http://www.dynamicscrmtrickbag.com/2009/07/12/waits-timeouts/

A: Yes, it will use the current value of the field each time the workflow is checked.
Related: CRM2011 Workflow: What happens if the field which is used in the condition of the workflow is updated after the workflow has started?


text:
Q: Problem with the HttpSession object = request.getSession (); JSP I have struggled with this problem but I don't understand it. Here is the stack trace:

This is my radio button:

Here I assign a variable for each of the radio button groups that I have, and create an object for each of the variables:

I use a variable to store what comes from the form and assign the value to it:

However, when I go to my third form and click on submit, the last page that processes the data shows me this error that only appears in that line, since the previous ones do collect the data:


text:
Q: How to center a user Control inside Pushpin with Bing Maps for Windows Phone 7 How do you get it to center the usercontrol on the point of the location of the pushpin, not inside and relative to the pushpin icon?
I tried aligning to the bottom and also giving a margin to the control.
Thanks,

A: The Pushpin has a property called PositionOrigin which specifies where the actual location point is relative to the Pushpin graphic.  For example setting PositionOrigin="0.5, 0.5" would cause the whole pushpin element to center over the actual location.
I'm not sure if that is useful to you since the wording of your question implies that you want to keep the existing Pushpin graphical but translate the a usercontrol placed in the Content.

A: Use a TranslateTransform in the RenderTransform to offset by half of the width and height of your content.
For example, in Car Finder (when it eventually passes certification), I use a crosshair icon to represent the user's current location, which is a 38x38 Path, so the offset is -19/-19:
<ControlTemplate x:Key="LocationPushpin" TargetType="maps:Pushpin">
    <Path Data="M50 0C22.43 0 0 22.43 0 50c0 27.569 22.43 50 50 50s50-22.431 50-50C100 22.43 77.57 0 50 0z M54.032 91.737V78.226h-8.064  v13.512C26.057 89.829 10.171 73.943 8.263 54.032h13.512v-8.064H8.263c1.909-19.911 17.794-35.796 37.705-37.705v13.511h8.064  V8.263c19.911 1.908 35.797 17.793 37.705 37.705H78.226v8.064h13.512C89.829 73.943 73.943 89.829 54.032 91.737z"
          Fill="#000000"
          Height="38"
          Stretch="Uniform"
          Width="38">
        <Path.RenderTransform>
            <TranslateTransform X="-19" Y="19" />
        </Path.RenderTransform>
    </Path>
</ControlTemplate>


text:
Q: Bibtex not compiling every item into the .bbl file I am writing a paper for JAIR using their style guide and APA style for my references. I have all my citations \cite{name here} in the body of my work. However, when compiling pdfLaTeX+MakeIndex+BibTex the compiler crashes and gives warnings for half of my references.
For Example:
LaTeX Warning: Citation `palacios_diagnosis_2010' on page 7 undefined. on input line 274.
I have confirmed in the Bibtex document that they are correct syntactically however Bibtex, either in that combination stated above or standalone is not compiling all of the references into the .bbl file.
The most confusing thing is that I also have a separate project for my thesis and all the references are compiling in that document.


text:
Q: wlst authentication exception prompt user again I have written a couple of wlst scripts which work as expected. The script starts by prompting the user for a username/password, connects to the admin server and then performs the tasks (deployment, startup/shutdown etc etc).
The problem I am having is at the first step - if the user enters an incorrect username/password, I want the script to prompt it one more time for this information. Note that I want the user to be prompted a second time  only if the username/password is incorrect - not if, say the admin server is down.
I am trying the following piece of code and it is not working as expected (it never enters the first except block). Apparently, my lack of OOPS programming experience is hindering completion of this simple task. Hoping someone can help out with this step.
try:
    connect(username, password, 't3://ADMIN_SERVER:ADMIN_PORT')

except SecurityException:
    print '\nAuthentication error, add logic to retry\n"
    exit(exitcode=1)

except:
    print "\n\n ALL OTHER ERRORS \n\n "

(I have also tried NamingException,AuthenticationException in place of SecurityException but it did not help either)

A: Simple except block works for me...
You can also try the following way NameError  instead of other trials

*

*try: connect(username, password,
't3://ADMIN_SERVER:ADMIN_PORT')
except NameError, e:
    print "Check username, passwd values : ", sys.exc_info()[0],
sys.exc_info()[1]
You can handle error e with your way.


text:
Q: How to convert a subdomain to a path Spring boot how to configure the application so that each client has its context?
Example:

*

*Main

*

*client1.domain.com --> domain.com/client1

*client2.domain.com --> domain.com/client2

*....

*Login

*

*client1.domain.com/Login --> domain.com/client1/Login

*client2.domain.com/Login --> domain.com/client2/Login

*....

My current application uses the configuration of subdomains because springboot itself identifies that it is in different contexts, but I can't understand how to do this through the path

A: You can always get the hostname form the request using  annotation:
  @GetMapping(path = "/secret")
  @ResponseBody public String getSecret(@RequestHeader("Host") String host ) {
    var client = getClientFromHost(host);
    // ...
  }

If there is a load balancer in front of this service, you can use the X-Forwarded-From header instead of the Host header.
And then you could simply parse the host URL, to extract the subdomain which identifies your client.


text:
Q: BuildCraft Filler with Saplings I'm trying to build a self-contained automated tree farm with redwood trees.  The main problem I have is how to replant saplings.  So I thought I would use a BuildCraft filler with height 1 to fill in the area with saplings.  The problem is that in testing, a filler will only plant a single sapling and never move beyond that:

You can see the result in this image.  The filler is programmed with nine bricks in fill mode, and powered by a full redstone energy cell.  If I take the redwood saplings out of the resource area of the filler and use cobblestone for example, the area is instantly filled up as expected.  But then if I use redwood saplings, it stops like the picture above with just a single sapling in the corner.
Is there a way to get this to work, or is there some limitation to a filler that prevents using saplings?  Is there another method in Feed-the-Beast to replant saplings over a large area?

A: As has been pointed out in the comments, you want a
Forestry MultiFarm
These can be set up such that they require only a regular supply of apatite to keep running indefinitely. Two such farms will produce enough wood to make more than enough charcoal to keep a full size high pressure boiler running full time.
This can be achieved by:

*

*Auto crafting fertilizer on an auto-crafting table, drawing from two chests, one for dirt and one for water.

*Connect a wooden pipe, with an autarchic gate set to pulse when fertilizer < 25% to automatically craft when needed.

*Use whatever system you like to keep your apatite chest(s) full.

*Autocraft plant balls from output saplings, and macerate these to generate dirt.

*Once the system is up and running, it will provide ample power for itself and a large surplus.

A: a steve's carts tree farm is probably your best bet for a fully customizable resizable tree farm that grows anything.
the cart assembler will need the following attachments:
logger
compact solar (sides)
internal inventory(for storing logs, extra saplings, and apples during its 'lap')
solar engine (normal, not basic, this goes on top)
basic coal engine (a backup incase things go horribly wrong with the solars)
a cargo distributer and manager (naming isn't right, i havent played ftb in a while)

the cargo manager will be used for pumping the logs and extra saplings out of the system and into a larger storage (mine used ED barrels and the log one filled up)
the rail system only needs one special thing
 advanced detector rail

that needs to be next to the cargo block setup, its what makes the cart stop/load/unload into the system
you can make the rail system any size you see fit, provide the cart with a few saplings and a handful of coal into the backup engine and leave it to its work.
you might want to set the priorities on the engines just to be sure the coal engine will not burn unless needed.
setting up the cargo manager/distributor is pretty straightforward, go to the steve's cart wikia or watch one of direwolf20's video on it (he's done a few) if you are confused.
I would also like to point out if you DO use redwoods with this system, you WILL have more logs than you know what to do with. My system used normal trees of a 20x20 fully covered (zigzaging tracks) and the ExtraDimensional barrel I had for the logs filled up in a matter of days, even though it was being used to power my max size steam boiler.

A: This is far from optimal, but I have designed my own farm entirely from scratch using deployers to place the saplings, transposers to pick up fallen saplings, and pneumatic tubes to transfer the saplings into the deployers to keep them supplied.  It was relatively simple to setup once I had a prototype working.  It's 100% automated and decently efficient:
Above-ground view of Tree Farm.  Roughly 50% of plantable area is taken up by equipment.  Everything is powered by red-alloy wire, which is fired off by a 30-second timer on the bottom right.  The goofy-looking cobblestone sprinkled throughout is to prevent leaves being generated on the second layer, because it will destroy the red-alloy wire (in fact you can see that happened in the tree in the back, so it's not perfect).

Below-ground view of the Tree Farm.  Every transposer feeds into pneumatic tubes that service the nearby deployers.  This keeps the deployers consistently supplied because the tubes evenly distribute among the 2-4 deployers next to the transposer.  The logger in the middle then cuts down the trees and outputs into an array of barrels.


text:
Q: Image to bytes takes long time to load I want to convert images to bytes, then to BitmapDescriptor, but it takes a lot of time to load the images, are there any ways to cache them? I am using a for loop to load my markers.
  Future<BitmapDescriptor> getClusterMarker(String url) async {
    Uint8List bytes = (await NetworkAssetBundle(Uri.parse(url)).load(url))
        .buffer
        .asUint8List();

    var bg = await bytesToImage(bytes);

    ....


text:
Q: angular 2+ component with attribute name and no parameters I want to allow a user to provide a list of one-word attributes without parameter values. For example,
<container row crosscenter wrap spacearound ...>

which results in something like this in container.html
<div [ngClass]="{ 'flexDisplay': true, 'directionRow': isRow, 'directionCol': isCol, 'contentSpaceAround': isSpaceAround}" ...>

What I'm missing is how to set
@Input('row') isRow = false;

to true if 'row' was present in the container line.
Any ideas?
Thanks in advance.
Yogi

A: This can be handled in ngOnChanges. The value can be assigned either back to input property or to some object that will be passed to ngClass
ngOnChanges(changes: SimpleChanges) {
  if ('foo' in changes) {
    this.options.foo = true;
  }
}

Since there's no way how inputs can become unassigned, there's no reason to provide bindings for them. @Attribute can be used instead:
constructor(@Attribute('foo') public foo: boolean|null) {
  this.foo = (foo != null);
}

Using attributes for regular options isn't a good decision, design-wise. This prevents from setting them dynamically. Instead, it is always preferable to accept options input. If all options are supposed to be flags, it can be a string input that will be split and processed in ngOnChanges, like:
<container options="row crosscenter wrap spacearound">

or
<container [options]="'row crosscenter wrap spacearound'">

A: I think the answer to my question is to create directives for each of the "one-word" tags (attributes) I want to use.
:-)


text:
Q: Call a procedure when there is change in data of view/table in snowflake I have a snowflake stored procedure that should be executed when there is a change in data in snowflake view/table.
I tried creating a Stream called mystream that points to a table.
create or replace stream mystream on table TEST1;

And created a Task as
    CREATE or replace TASK mytask1
  WAREHOUSE = TEST_WH
  SCHEDULE = '1 minute'
WHEN
  SYSTEM$STREAM_HAS_DATA('MYSTREAM')
AS
  CAll sp_test_proc('ABC')

However, the stored procedure didn't execute even after SYSTEM$STREAM_HAS_DATA('MYSTREAM') returned TRUE.

A: Could you check the status of the task?
show tasks;

I suspect you haven't resumed it.
https://docs.snowflake.com/en/sql-reference/sql/create-task.html#usage-notes
If it's resumed, then use the TASK_HISTORY function to check the ERROR_MESSAGE of the latest execution. You may also check the query ID.
https://docs.snowflake.com/en/sql-reference/functions/task_history.html


text:
Q: Insertion to a table column of a custom type which has only one element In PostgreSQL 10.3, I tried the following two scenarios.
1.
CREATE TYPE customtype AS (val VARCHAR(20));
CREATE TABLE structdatatable(id INTEGER, structdata customtype);

Then executed the following insert statement.
INSERT INTO structdatatable VALUES(1, ('abc'));

This results in the following error.
DETAIL:  Missing left parenthesis.

2.
CREATE TYPE customtype2 AS (val VARCHAR(20), val2 VARCHAR(20));
CREATE TABLE structdatatable2(id INTEGER, structdata customtype2);

Then executed the following insert statement.
INSERT INTO structdatatable2 VALUES(1, ('abc','def'));

This gets executed successfully with the following output.
INSERT 0 1

Also I executed a select statement to verify as well. Following is the result.
 id | structdata
----+------------
  1 | (abc,def)
(1 row)

What causes this behavior?

A: A single value in parentheses is not automatic detected as a record. You can use the row constructor syntax to make this unambiguous:
INSERT INTO structdatatable VALUES(1, row('abc'));


text:
Q: Find $\lim_{x \to 0} \frac{(\tan(\tan x) - \sin (\sin x))}{ \tan x - \sin x}$ Find $$\lim_{x\to 0} \dfrac{\tan(\tan x) - \sin (\sin x)}{ \tan x - \sin x}$$
$$= \lim_{x \to 0} \dfrac{\frac{\tan x \tan (\tan x)}{\tan x}- \frac{\sin x \sin (\sin x)}{\sin x}}{ \tan x - \sin x} = \lim_{x \to 0} \dfrac{\tan x - \sin x}{\tan x - \sin x} = 1$$
But the correct answer is $2$. Where am I wrong$?$

A: This is a nice case for composition of Taylor series. Using
$$\tan(x)=x+\frac{x^3}{3}+\frac{2 x^5}{15}+O\left(x^7\right)$$
$$\sin(x)=x-\frac{x^3}{6}+\frac{x^5}{120}+O\left(x^7\right)$$
$$\tan(\tan(x))=x+\frac{2 x^3}{3}+\frac{3 x^5}{5}+O\left(x^7\right)$$
$$\sin(\sin(x))=x-\frac{x^3}{3}+\frac{x^5}{10}+O\left(x^7\right)$$ then
$$\frac{\tan(\tan( x)) - \sin (\sin( x)}{ \tan (x) - \sin (x)}=\frac {x^3+\frac{x^5}{2}+O\left(x^7\right) } {\frac{x^3}{2}+\frac{x^5}{8}+O\left(x^7\right) }=2+\frac{x^2}{2}+O\left(x^4\right)$$ which shows the limit and also how it is approached.

A: Your second step is invalid. In general one can't replace a sub-expression by its limit while evaluating limit of a bigger expression in step by step fashion. You can get more details in this answer.
You can approach this problem by adding and subtracting $\tan(\sin x) $ in numerator. The numerator can thus be expressed as $$\{\tan \tan x-\tan \sin x\} +\{\tan \sin x-\sin\sin x\} $$ which can be further rewritten as $$\tan(\tan x - \sin x) (1+\tan\tan x\cdot\tan\sin x)+\tan\sin x-\sin\sin x$$ Now the first term divided by $\tan x - \sin x$ (denominator) tends to $1$ and hence the desired limit is equal to $$1+\lim_{x\to 0}\frac{\tan\sin x - \sin\sin x} {\tan x - \sin x} $$ The expression under limit above can be written as $$\frac{\sin\sin x} {\sin x} \cdot \frac{1-\cos\sin x} {1-\cos x}\cdot\frac{\cos x} {\cos\sin x} $$ The first and last factors tend to $1$ and the middle factor is equal to $$\frac{1-\cos\sin x} {\sin^2x}\cdot\frac{\sin^2x}{x^2}\cdot\frac{x^2}{1-\cos x} $$ and the above clearly tends to $(1/2)\cdot 1\cdot 2=1$. The desired answer is thus $2$.

A: Your way is wrong since
$${\tan(\tan x) - \sin (\sin x)}\neq { \tan x - \sin x}$$
indeed this step
$$\frac{\tan x \tan (\tan x)}{\tan x}=\tan x\cdot \frac{ \tan (\tan x)}{\tan x}\color{red}{=\tan x \cdot 1}=\tan x$$
and the similar for $\sin x$ are not allowed (in general we can't evaluate limit only for a part or factor of the whole expression; see also here).
We can avoid Tayor's expansion and use that (see here):

*

*$\lim_{x\to0}\frac{\tan x-x}{x^3}=\frac13$

*$\lim_{x\to0}\frac{\sin x-x}{x^3}=-\frac{1}6$
then
$$\dfrac{\tan(\tan x) - \sin (\sin x)}{ \tan x - \sin x}=\dfrac{\frac{\tan^3 x}{x^3}\frac{\tan(\tan x)-\tan x}{\tan^3x} - \frac{\sin^3 x}{x^3}\frac{\sin(\sin x)-\sin x}{\sin^3x}+\frac{\tan x-x}{x^3}-\frac{\sin x-x}{x^3}}{ \frac{\tan x-x}{x^3} - \frac{\sin x-x}{x^3}}\\\to\frac{1\cdot \frac13-1\cdot\left(-\frac16\right)+\frac13-\left(-\frac16\right)}{ \frac13-\left(-\frac16\right)}=2$$

A: @Surb identified your error with the choice$$f_1=\tan(\tan x),\,g_1=\tan x,\,f_2=\sin(\sin x),\,g_2=\sin x.$$One method that would work is to use$$\tan x=x+\frac13 x^3+o(x^3),\,\sin x=x-\frac16 x^3+o(x^3)$$together with$$x+cx^3+c(x+cx^3)^3=x+2cx^3+o(x^3),$$viz.$$\frac{\tan(\tan x)-\sin(\sin x)}{\tan x-\sin x}=\frac{\tan(x+\frac13 x^3+o(x^3))-\sin(x-\frac16 x^3+o(x^3))}{\frac12x^3+o(x^3)}\\=\frac{(x+\frac23 x^3)-(x-\frac13 x^3)+o(x^3)}{\frac12x^3+o(x^3)}=2+o(1).$$


text:
Q: How to send a message to StackBlitz VM from the parent window using Angular? I would like to send a message every second from the main page to the embedded stackBlitz without reloading the main page.
I have found a way by sending it by creating a json file as bellow. I am using Angular.
sdk.embedGithubProject(
    'stackblitz-frame',
    userName + '//' + repoName,
    { height: 500, width: 1500 }
).then(vm => {

    const source = interval(1000);

    const subscribe = source.subscribe(val => {

        var message = new Message();

        message.timeInfo = this.Currenttime;

        this.vm2 = vm;
        vm.applyFsDiff({
            create: {
                'src/assets/input.json': JSON.stringify({ message })
            },
            destroy: ['randomFile.ts']
        });
    });

});

In the example above I am sending videoInfo every second.
The problem is that when it starts it doesn't allow me to edit the rest of the stackblitz project.
I noticed that in StackBlitz there is a possibility to communicate through postMessage between iframes, but when trying to use it is a private variable.
vm.rdc.port.postMessage

that I believe it works like: https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/postMessage
But this is set as a private property, the problem of creating a file for communication is that the view of the application is reloading all the time.
I embedded the stackblitz: https://stackblitz.com/edit/adding-links-app
as an example of child, the View Mode of this VM container is not allowing me to create a view mode and edit while the input.json is updated.
Do you know any other way for communication between the embedded StackBlitz and the parent page where it is?
Thanks


text:
Q: angularJS controller doesn't load the first time Inside the view, I am declaring:

        Sign In

        Logout

Please note that the angular file that contains the controller is properly called before the code lines above.
Inside my controller, I am trying to load data from a node api, with an $http get request and set its result to the scope like follow:
var indexModule = angular.module ('indexModule', []);

indexModule.controller('LoginController',['$scope', '$http',
  function($scope, $http){
    $http.get('/api/data')
      .success(function(data){
          $scope.authenticated = data.authenticated;
      })
      .error(function(){
            alert('Error occured');
      });

This works only after several page refreshes. Is there something I am doing wrong?
UPDATE
Here are the node.js routes:
app.get('/api/data', function (req,res) { // this is called by the controller to populate $scope
    var sendtoFront = new Object();
    toFront.authenticated = req.isAuthenticated() ? 'yes' : 'no';
    if(req.isAuthenticated()) {
        toFront.session = req.session.passport;
    }
    res.send(toFront);
});
app.get('/', function (req,res) { // this load the view
    res.render('index');
});

UPDATE II
I tried the same code in Firefox instead of chrome and it seems to be working correctly any ideas about how to repair this.

A: EDIT : After reading error in console, it doesn't seem you want $scope.$apply().
It seems you have manually called $apply() from $rootscope.
Check in other portions of code if you have manually called $apply on $rootScope.
Similar issue :Angularjs [$rootScope:inprog] inprogress error


text:
Q: Git apply changes from master to derived branch I know this question get asked a lot around here, but after following all the answers I still can't understand something.
I have a branch called "video-messaging" which is the derived from the "master". After working a bit on "video-messaging" I encountered a bug, realizing I cannot continue to work on this feature without the fix, I asked the programmer who's responsible for that part of code to fix it, he fixed it and uploaded it to the "master". Now, I tried to git rebase "video-messaging" with  "master" to get those changes and now I have the fix listed along with the rest of the commits made after the creation of "video-message" both from "master" and from "video-message" when typing git log video-message. Great, Right? no... I can't see the fixes when looking at the actual source code! And hence I can't compile the project and continue testing my new feature.
Well I know that it rebased because the commits are all there, but why can't I see it in the actual code?


text:
Q: Hide scrollbars in an iframe I tried to hide scrollbars in an iframe whose content is loaded from an external website.
I used overflow:hidden and also overflow-x: hidden as well as overflow-y: hidden but that doesnt seem to solve my problem
What did I do wrong? Or what is wrong with my approach?
Here is my JSFIDDLE
Here is my HTML

CSS
body {
    width: 100vw;
  height: 100vh;
  margin: 0 auto;
}
.outer {
  position: relative;
  background: url("http://wrb.farm/demo/background-with-backdrop.jpg") no-repeat center;
  background-size: 100% 100%;
  width: 100%;
  height: 100%;
}
.noScrolling {
  width: 100%;
  height: 100%;

}

.inner {
  position: relative;
  width: 54%;
  height: 73%;
  top: 9%;
  left: 23%;
  overflow: hidden;

}

A: The Scrollbars are from the Element

Wich is inside the iFrame, and not the iFrame itself.
So you would have to change the style of this element (overflow:hidden)


text:
Q: Update a spreadsheet cell value with Python I'm trying to update a value in Python, here is my code :
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

global values
global sheet
global SAMPLE_SPREADSHEET_ID
global SAMPLE_RANGE_NAME

def connexion():
    # Some code ...
    # Call the Sheets API
    return service.spreadsheets()

def update(values, sheet, SAMPLE_SPREADSHEET_ID, SAMPLE_RANGE_NAME):
    body = {
        'values': values
    }
    result = sheet.values().update(
    spreadsheetId=SAMPLE_SPREADSHEET_ID, range=SAMPLE_RANGE_NAME, valueInputOption='USER_ENTERED', body=body).execute()
    if str(result.get('updatedCells')) != 0:
        return True
    return False

sheet = connexion()
values = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID, range=SAMPLE_RANGE_NAME).execute().get('values', [])
for line in values:
    if line[3] == 'Hi !':
        line[5] == 'hello'
if update(values, sheet, SAMPLE_SPREADSHEET_ID, SAMPLE_RANGE_NAME):
    print('   Update ok')
else:
    print('   Error')

I do not have any error but "Update ok" is printed. However, the value in the 6th cell line[5] is not updated... How can I do this please ? Thanks !

A: When the variable of sheet in your script can be used for getting and putting values to Google Spreadsheet, I think that your most script is correct. I think that there is only one modification point. The value of line[5] is compared with hello at line[5] == 'hello'. By this, hello is not put to line[5]. I think that the reason of your issue is this. So please modify as follows.
From:
line[5] == 'hello'

To:
line[5] = 'hello'

Note:

*

*In this modification, it supposes that the columns of values retrieved from sheet.values().get() is more than 6.


text:
Q: Copy current row and insert it below whenever I update a cell in a specific column of excel? I am creating a simple To Do list for myself in excel. As part of 1 of the function, I would like below.
Currently I write current status in Column F (Current Status) in the excel. If I update any cell in this column to "Subtask", then a macro should automatically copy the row where i updated Subtask and insert it below the current row (Except the value of cell mentioning 'Subtask'). I tweaked a code but it seems with an earlier version excel kept copying rows as with each copy a new cell with Subtask was created. I have tried couple of different options but none seem to work (I have very very little experience in VBA).
Codes I have tried till now (All hangs the excel)
Set StatusCol = Range("F2:F101")
For Each Status In StatusCol
    If Status = "Subtask" Then
        Status.EntireRow.Copy
        Status.Insert
    End If
Next Status

Another code I tried
If Not Intersect(Target, Range("F:F")) Is Nothing Then
    If Target.Value = "Subtask" Then
        Target.EntireRow.Copy
        Target.EntireRow.Insert Shift:=xlUp
        Target.Offset(1, -5).Paste
End If

Both doesn't seem to work at all. Can you please help?
Complete code below:
Private Sub Worksheet_Change(ByVal Target As Range)
    On Error Resume Next
    'This code sorts based on C column
    If Not Intersect(Target, Range("C:C")) Is Nothing Then
        Range("B1:M100").Sort Key1:=Range("C1"), _
          Order1:=xlAscending, Header:=xlYes, _
          OrderCustom:=1, MatchCase:=False, _
          Orientation:=xlTopToBottom
    End If
    'This code resets based on value of Reset in Cell R3
    If Not Intersect(Target, Range("N2:N2")) Is Nothing Then
        Set Target = Range("N2")
        If Target.Value = "Reset" Then
            Worksheets("Sheet2").Range("A1:A100").Select
            Selection.Copy
            Range("C2").Select
            Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                :=False, Transpose:=False
            Range("A2").Select
            Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                :=False, Transpose:=False
        End If
    End If
    'This code fills value Now variable in row 8 when something is written in G column
    If Not Intersect(Target, Range("G:G")) Is Nothing Then
        Cells(Target.Row, 8).Value = Int(Now())
    End If
End Sub


text:
Q: User events related to contenteditable I am a beginner in Javascript & HTML5
Suppose I have a contenteditable <div> [block-level] element in my HTML5 window.
What is the exhaustive list of JavaScript events which the user could trigger by modifying this element (or some sub-elements) through user interaction?
How should I code in JavaScript to reject some user action? or change the DOM... (i.e. replace some TextNode with e.g. some <span>)
It seems that the input event cannot "undo" or "reject" some user action...
FWIW, at this point I only care about recent Firefox browsers (mine is 21 beta 7 on Linux).
This is an answer to a related question.
In other words, I don't have a clear picture of how to design rich text editors in HTML5 & JavaScript.
PS I want plain JavaScript, not interested in any library above it yet.
Addenda
Maybe mutation observers could be relevant?
Follow-up question here...

A: The exhaustive list of events on contenteditable elements is the same as for input type=text. See this list of all events (look especially at Form Events): http://www.w3schools.com/tags/ref_eventattributes.asp
"How should I code in Javascript to reject some user action?"... just put "event.preventDefault()" at the beginning of an event listener for the event of that action. Example to reject keypresses:
contenteditableElement.addEventListener('keypress', function (e) {
    e.preventDefault();
    // do something else, maybe...
});

To undo a user's action:
document.execCommand('undo', false, '');

As to designing rich text editors, there are many good demos available. I recommend:
https://developer.mozilla.org/en-US/docs/Rich-Text_Editing_in_Mozilla
http://www.quirksmode.org/dom/execCommand/
Make sure to view source of the last link; especially the buttons.js file. Also check out the amazing commands list on the MDN article. Good luck -- but try not to re-invent the wheel. There are many well-tested editors out there; check out this list: http://www.webdesignerdepot.com/2008/12/20-excellent-free-rich-text-editors/


text:
Q: How do I check if a key-value pair is present in a dictionary? If the value of one key is a dictionary a = {'a': 1, 'b': [{'a1': 1,'b2': 2}], 'c': 3, 'd': 4, 'e': 5}

b = {'c': 3, 'b': [{'a1': 1,'b2': 2}]}

Check for the presence of b in a, and the output is a bool value
Tried solutions like this:
    for values in b.items():
        if values in a.items():
            continue
        else:
            return False
    return True

len(set(b.items()) & set(a.items())) == len(b)

The problem is with a value-pair of a key-value whose value-pair is a dictionary. I am looking for a solution to this problem.

A: maybe this works for you?
a = {'a': 1, 'b': [{'a1': 1,'b2': 2}], 'c': 3, 'd': 4, 'e': 5}
b = {'c': 3, 'b': [{'a1': 1,'b2': 2}]}
c = {'a1': 1,'b2': 3}

def issubset(a,b):
    for keyb,valueb in b.items():
        if keyb in a and a[keyb] == valueb: continue
        return False
    return True

print( issubset(a,b) )
print( issubset(a,c) )
print( issubset(a,{'a':'2'}) )

output:
True
False
False

it works for your example. However, as you see in the 2nd line, it doesn't do recursive checking, which might be what you want.


text:
Q: IP address / port is reacheable by one process but not by another We have a strange networking problem like this:
There is machine A with multiple network interfaces, one of them is 10.10.45.45/16. Connected is a Server S with ip:10.10.45.47 streaming data on port 9696. The other interfaces on machine A are 192.168.0.1, 192.168.1.1
The strange behaviour: we get data from S while connecting through a browser from machine A. We have another application (written in c) running stand alone also on machine A which cannot connect to 10.10.45.47:9696. This setup and the application is standard and works in other similar setups correctly. Tealnet is also able to connect.
Any thoughts on that? Could it be that c has weird behaviour selecting a proper interface?


text:
Q: How to Play video in another activity on clicking on button? I have made two activity on first I have list of video list in cardview I want to play that video on other activity. I add videoview in 2nd activity, I don't want multiple activities for multiple videos. Hope you guys understand.
package eras.ppt.ras;

import android.content.Intent;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;

public class FYJCActivity extends AppCompatActivity {

    CardView mycard ;
    private Intent intent;
    private Intent intent1;
    private Intent intent2;
    private Intent intent3;
    private Intent intent4;
    private Intent intent5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fyjc);

        mycard = (CardView) findViewById(R.id.physics);
        mycard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(FYJCActivity.this, VideoActivity.class);
                startActivity(intent);
//                finish();
//                onBackPressed();
            }
        });

        mycard = (CardView) findViewById(R.id.cardview);
        mycard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(FYJCActivity.this, VideoActivity.class);
                startActivity(intent1);
//                finish();
//                onBackPressed();
            }
        });

        mycard = (CardView) findViewById(R.id.cardview1);
        mycard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent2 = new Intent(FYJCActivity.this, VideoActivity.class);
                startActivity(intent2);
//                finish();
//                onBackPressed();
            }
        });

        mycard = (CardView) findViewById(R.id.cardview2);
        mycard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent3 = new Intent(FYJCActivity.this, VideoActivity.class);
                startActivity(intent3);
//                finish();
//                onBackPressed();
            }
        });

        mycard = (CardView) findViewById(R.id.cardview3);
        mycard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent4 = new Intent(FYJCActivity.this, VideoActivity.class);
                startActivity(intent4);
//                finish();
//                onBackPressed();
            }
        });

        mycard = (CardView) findViewById(R.id.cardview4);
        mycard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent5 = new Intent(FYJCActivity.this, VideoActivity.class);
                startActivity(intent5);
//                finish();
//                onBackPressed();
            }
        });

    }
}

This is my code I want to play a video on video activity.
I don't know how to play video on other activity that's why I didn't
add video link yet.

A: You have to add extra information in the intent with putExtra. For ex,
 mycard = (CardView) findViewById(R.id.physics);
        mycard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(FYJCActivity.this, VideoActivity.class);
                intent.putExtra("a_Tag","physics");
                startActivity(intent);
            }
        });

And in your VideoActivity, inside the onCreate method, you have to extract that information from the intent as follows:
String item_selected=getIntent().getStringExtra("a_Tag"); //same tag you used before
//now item_selected is "physics"

You can display the corresponding video based on item_selected's value


text:
Q: Mod shows up with OP background when viewing deleted comments As they say, a picture is worth a thousand words:

The moderator here is not the original poster, but on the comments by the aforementioned OP, his name has the OP background. On the other comments, he (correctly) doesn't.

A: This has been fixed. Going forward, only the question asker's comments (and "deleted by" records) will have the added background.

A: This actually seems to be even more important now, because it seems to control the presence of "undelete":

*

*comments deleted by former moderators can't be undeleted

*comments deleted by flags meeting the criteria for automatic deletion can't be undeleted

I've run into this with a few invalid auto-deletions that I couldn't reverse.

A: I just encountered this on The Workplace (and then looked for it on Mi Yodeya to verify it's cross-site), then started to post the bug report and found this question.  This is new behavior for me (I'm pretty sure!), though the OP reports that it's been broken on SciFi since this bug was reported in 2014.
Here are some screen shots with a little less eyeball-bleed:
The Workplace:

Mi Yodeya:


text:
Q: Wp_Insert_Post: Do not insert if the title exists i've made a simple code here to fetch and insert the last news from a feed Rss:
<?php // Get RSS Feed(s)
include_once"wp-config.php";
include_once"wp-load.php";
include_once"wp-includes/wp-db.php";

if(function_exists('fetch_feed')){
$uri = 'http://rss.cnn.com/rss/edition.rss';
$feed = fetch_feed($uri);
}

foreach ($feed->get_items() as $item){

$titlepost = $item->get_title();
$content = $item->get_content();
$description = $item->get_description();

$my_post = array();
$my_post['post_title'] = "$titlepost";
$my_post['post_name'] = "$titlepost";
$my_post['post_content'] = "$content";
$my_post['post_status'] = 'publish';
$my_post['tags_input'] = $thetags;
$my_post['post_author'] = 1;
$my_post['post_type'] = 'post';
$my_post['post_excerpt'] =  "$description";

$post_id = wp_insert_post($my_post);

}

?>

I would want check the feed regularly and insert new posts only if the post does not exist already.
Should I then insert a rule that first checks if the title exists and, in this case, declare not to insert anything, else, have regular wp_insert_post.
Can we help Me ?


text:
Q: Textarea Store and Show Linebreaks I have an Angular 2 App and I use a textarea:
<textarea [(ngModel)]="value"></textarea>

The value gets sent via a REST Api to the server. However already in the application when I want to show:
{{value}}

It won't show line breaks. How can I accomplish this? It should show the line breaks and ensure that these are also saved in the model.

A: This is more of a HTML question. Play on the white-space property (pre tags have it by default) :

const tags = [...document.querySelectorAll('#pre, #formatted, #unformatted')];
tags.forEach(tag => tag.innerHTML = "Content\nWith a line break & return");
#formatted {
  white-space: pre-wrap;
}

in a pre tag :

in a formatted tag :

in a unformatted tag :

A: <textarea  style="white-space: pre;" [(ngModel)]="value"></textarea>

your value might be like this:
value = "1234\n5678"

"\n" as linebreaks


text:
Q: Does printf only allow taking a string literal as the first argument? According to the definition of printf, it says that first argument should be an array i.e char* followed by ellipses ... i.e variable arguments after that.  If I write:
printf(3+"helloWorld"); //Output is "loWorld"`

According to the definition shouldn't it give an error?
Here is the definition of printf:
#include <libioP.h>
#include <stdarg.h>
#include <stdio.h>

#undef printf

/* Write formatted output to stdout from the format string FORMAT. */
/* VARARGS1 */
int __printf(const char *format, ...) {
    va_list arg;
    int done;

    va_start(arg, format);
    done = vfprintf(stdout, format, arg);
    va_end (arg);

    return done;
 }

 #undef _IO_printf
 ldbl_strong_alias(__printf, printf);
 /* This is for libg++.  */
 ldbl_strong_alias(__printf, _IO_printf);

A: From Pointer Arithmetic:

If the pointer P points at an element of an array with index I, then

P+N and N+P are pointers that point at an element of the same array with index I+N
P-N is a pointer that points at an element of the same array with index {tt|I-N}}

The behavior is defined only if both the original pointer and the result pointer are pointing at elements of the same array or one past the end of that array. ....

The type of string literal is char[N], where N is size of string (including null terminator).
From C Standard#6.3.2.1p3 [emphasis mine]

3 Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ''array of type'' is converted to an expression with type ''pointer to type'' that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

So, in the expression
3+"helloWorld"

"helloWorld", which is of type char [11] (array of characters), convert to pointer to character that points to the initial element of the array object.
Which means, the expression is:
3 + P
where P is pointer to initial element of "helloWorld" string

  ----------------------------------------------
  | h | e | l | l | o | W | o | r | l | d | \0 |
  ----------------------------------------------
    ^
    |
    P (pointer pointing to initial element of array)

when 3 gets added to pointer P, the resulting pointer will be pointing to 4th character:
  ----------------------------------------------
  | h | e | l | l | o | W | o | r | l | d | \0 |
  ----------------------------------------------
                ^
                |
                P (after adding 3 the resulting pointer pointing to 4th element of array)

This resulting pointer of expression 3+"helloWorld" will be passed to printf(). Note that the first parameter of printf() is not array but pointer to a null-terminated string and the expression 3+"helloWorld" resulting in pointer to 4th element of "helloWorld" string. Hence, you are getting output "loWorld".

A: This is not an error.
If you pass "helloWorld" to printf, the string literal is converted to a pointer to the first character.
If you pass 3+"helloWorld", you're adding 3 to a pointer to the first character, which results in a pointer to the 4th character.  This is still a valid pointer to a string, it's just not the whole string that was defined.

A: The answers from dbush and haccks are concise and illuminating, and I upvoted the one from haccks in support of the bounty offered by dbush.
The only thing that I find left unsaid is that the way the question title is phrased makes me wonder if the OP would think that e.g. this also should produce an error:
char sometext[] = {'h', 'e', 'l', 'l', 'o', '\0'};
printf (sometext);

since there is no string literal involved at all.  The OP needs to understand that one should never think that a function call that takes a char * argument can "only allow taking a string literal as [that] argument".
The answers from dbush and haccks hint at this by mentioning the conversion of a string literal to a char * (and how adding an integer to that evaluates), but I feel that it's worth pointing out explicitly that anything that is treated as a char * can be used, even things not converted from a string literal.

A: 3+"helloWorld" is of char * type (after conversion in call to printf). In C, the type of a string literal is char []. When passed as an argument to a function, char [] will convert to pointer to its first element (array to pointer conversion rule). Therefore, "helloWorld" will be converted to a pointer to the element h and 3+"helloWorld" will move the pointer to the 4th element of the array "helloWorld".

A: The first argument to printf is declared as const char *format. It means printf should be passed a pointer to char and the characters pointed to by this pointer will not be changed by printf. There are additional constraints on this first argument:

*

*it should point to a proper C string, that is an array of characters terminated by a null byte.

*it may contain conversion specifiers, which must be properly constructed and the corresponding arguments must be passed as extra arguments to printf, with the expected types and order as derived from the format string.

Passing a string constant such as "helloWorld" as the format argument is the most common way to invoke printf. String constants are arrays of char terminated by a null byte which should not be modified by the program. Passing them to functions expecting a pointer to char will cause a pointer to their first byte to be passed, as is the case for all arrays in C.
The expression "helloWorld" + 3 or 3 + "helloWorld" evaluates to a pointer to the 4th byte of the string. It is equivalent to the expression 3 + &("helloWorld"[0]), &("helloWorld"[3]) or simply &"helloWorld"[3]. As a matter of fact, it is also equivalent to &3["helloWorld"] but this latest form is only used for pathological obfuscation.
printf does not use the bytes that precede the format argument, so passing 3 + "helloWorld" is equivalent to passing "loWorld" and produces the same output.

A: printf(3+"helloWorld"); //Output is "loWorld"

It will not give error because String in C Language String is array of characters and Array name give base address of array.
In case of printf(3+"helloWorld"); 3+"helloWorld" is giving the address of fourth element of array of charecters i.e  of String

This is still a valid pointer to a string i.e char*
printf only allow taking a char* as the first argument

A: To be more precise, the first argument to printf() function is not an array of chars but a pointer to array of chars. the difference between them is the same difference between byval and byref in VB world.
a pointer can be incremented and decremented using (++ and --) or applying arithmetic operations (+ and -).
in your case you are passing a pointer to "helloWorld" incremented by three, thus it points to the forth element of the array of chars "helloWorld".
lets simplify this in asm  pseudo code

MOV EAX, offset ("helloWorld")
ADD EAX, 3
PUSH EAX
CALL printf

you maybe think that 3+"hello word" do concatenation between 3 and "hello world", but in C concatenation is done otherwise. the simplest way to do is sprintf(buff, "%d%s",3,"hello wrord");

A: It's pretty strange, but not wrong. By doing 3 + you are moving your pointer to a different location.
The same thing work when you initialize a char *:
char *str1 = "Hello";
char *str2 = 2 + str1;

str2 is now equal to "llo".