How do I enable Middle mouse button emulation in 12.04 LTS?

Question: How do I enable Middle mouse button emulation in 12.04 LTS?
I think it was disabled by default in the last release. I'm sure this is a silly question but I can't find a generic answer, they all seem to be touchpad specific (ie, multi-touch related, which I don't have), or using what I consider not to be normal ubuntu methods (creating xorg.conf file). I'm using xubuntu variant (xfce) on a dell inspiron mini.
I was actually just testing there and if I tap with both fingers at once it brings up a context menu (like right click). Wired I didn't know this trackpad could even tell that there was a two finger tap...
Former behaviour was clicking both touchpad buttons (they are the built in kind) at the same time produced a middle clicck. They no longer do this. I never used a double tap, but the actual buttons.
To clarify I am using a built in Touchpad, not an external mouse. Gpointings detects it as synaptic touch, which I believe is correct
Update- The question @medigeek linked to below let me set a two fingered tap to emulate a middle click, but I still cant click both buttons at the same time
output from synclient is here:
LeftEdge                = 1760
RightEdge               = 5302
TopEdge                 = 1639
BottomEdge              = 4479
FingerLow               = 25
FingerHigh              = 30
FingerPress             = 256
MaxTapTime              = 180
MaxTapMove              = 232
MaxDoubleTapTime        = 180
SingleTapTimeout        = 180
ClickTime               = 100
FastTaps                = 0
EmulateMidButtonTime    = 0
EmulateTwoFingerMinZ    = 282
EmulateTwoFingerMinW    = 7
VertScrollDelta         = 105
HorizScrollDelta        = 105
VertEdgeScroll          = 1
HorizEdgeScroll         = 0
CornerCoasting          = 0
VertTwoFingerScroll     = 0
HorizTwoFingerScroll    = 0
MinSpeed                = 1
MaxSpeed                = 1.75
AccelFactor             = 0.0378931
TrackstickSpeed         = 40
EdgeMotionMinZ          = 30
EdgeMotionMaxZ          = 160
EdgeMotionMinSpeed      = 1
EdgeMotionMaxSpeed      = 422
EdgeMotionUseAlways     = 0
TouchpadOff             = 0
LockedDrags             = 0
LockedDragTimeout       = 5000
RTCornerButton          = 2
RBCornerButton          = 3
LTCornerButton          = 0
LBCornerButton          = 0
TapButton1              = 1
TapButton2              = 3
TapButton3              = 0
ClickFinger1            = 1
ClickFinger2            = 1
ClickFinger3            = 0
CircularScrolling       = 0
CircScrollDelta         = 0.1
CircScrollTrigger       = 0
CircularPad             = 0
PalmDetect              = 0
PalmMinWidth            = 10
PalmMinZ                = 200
CoastingSpeed           = 20
CoastingFriction        = 50
PressureMotionMinZ      = 30
PressureMotionMaxZ      = 160
PressureMotionMinFactor = 1
PressureMotionMaxFactor = 1
ResolutionDetect        = 1
GrabEventDevice         = 1
TapAndDragGesture       = 1
AreaLeftEdge            = 0
AreaRightEdge           = 0
AreaTopEdge             = 0
AreaBottomEdge          = 0
HorizHysteresis         = 26
VertHysteresis          = 26
ClickPad                = 1
RightButtonAreaLeft     = 0
RightButtonAreaRight    = 0
RightButtonAreaTop      = 0
RightButtonAreaBottom   = 0
MiddleButtonAreaLeft    = 0
MiddleButtonAreaRight   = 0
MiddleButtonAreaTop     = 0
MiddleButtonAreaBottom  = 0

Comment: related question: http://askubuntu.com/questions/64334/gpointing-device-settings-lost-on-reboot
Comment: I'll vote this as a duplicate of http://askubuntu.com/questions/12435/restoring-two-finger-middle-click-again -- I've already added my answer there
Answer: GUI solution
Install the package gpointing-device-settings
Description-en: configuration tool for pointing devices
 GUI tool for setting pointing devices. Currently it can configure mouse type
 device (mouse, trackpoint etc.) and touchpads.
 .
 For mouse you can configure middle button emulation, wheel emulation and
 scrolling.
 .
 It can enable and disable touchpad, or scrolling on it as well as additional
 parameters like palm detection, locked drags, tapping and scrolling.
 .
 It is a successor of GSynaptics.

Console/terminal solution #1
Alternatively, try this:
gsettings set org.gnome.settings-daemon.peripherals.mouse middle-button-enabled true

The alternative solution might require the installation of gnome-settings-daemon package.
Console/terminal solution(s) #2
Using synclient command you can view your synaptics touchpad options.

Run synclient and see what variables you have available.

You can set/change the synclient options using this command: syclient var=1 (where var is the variable you wish to change and 1 the value)
Read the manual page about each variable: http://manpages.ubuntu.com/synaptics

What worked for me
Instead of figuring out how to press both buttons of the touchpad, keep/press two fingers on the touchpad and click on the left click button of the touchpad with a third finger. This emulates a middle button by default.
What worked for the original poster
a) Setting the TapButton variable works for the two fingered tap
b) If you still want to click both buttons and produce a middle button emulation, execute:
synclient EmulateMidButtonTime=100

EmulateMidButtonTime allows you to change the time required to produce a middle button (allowed time period to click both buttons). 100 means 100 milliseconds (ms).
You may set it to even higher values, such as synclient EmulateMidButtonTime=500 (500ms).
Comment: Thanks, I tried that gpointing-device-settings option already (it was suggested in another question), but it doesn't give me the option to enable emulation. Second option doesn't seem to be working either, is an X restart required?
Comment: Did you do a clean install using the xubuntu-desktop live cd? gpointings enables middle mouse for mouse devices. What device are you using? Perhaps it's not detected properly? Btw, I'm surprised you need such a feature, nowadays mouse devices have a scroll button which you can click (press down) and that is the middle button essentially.
Comment: gpointings works with my mouse device
Comment: No it was an update from 11.10. It is a touchpad so unfortunately there is no middle button. Gpointings detects it as a syn touchpad (just like the screen above), it gives loads of options just not the emulate one!
Comment: (1) Run `synclient` and add the output in your question. (2) Try these solutions: http://askubuntu.com/questions/12435/restoring-two-finger-middle-click-again (3) you can set synclient using `syclient var=1` (var the variable and 1 the value). Read the manpage: manpages.ubuntu.com/synaptics (4) Try this: Keep two fingers on the touchpad and click on the left click with a third finger
Comment: I have updated the question with more info. Thanks for your help, setting the TapButton var works for the two fingered tap, but clicking both buttons still doesn't produce a middle click. Just fixed it- I had to set `synclient EmulateMidButtonTime=100` You showed the way so am accepting your answer, if you could edit to include this line it would be great!
Comment: console/terminal solution #1 can be GUI if you install dconf-editor and navigate to org.gnome.settings-daemon.peripherals.mouse and tick middle-button-enabled. Neither console/terminal solutions work for my mice (non-touchpads), synclient inherently because it's for touchpads. gpointing-device-settings works for different input devices. (recently had a clicking bug for me but it mostly works)
Comment: On Ubuntu 14.04 using the synclient option worked for me. I set  TapButton2=2 and TapButton3=3 to keep the right click available via 3 fingers tap and the middle click available via two fingers tap.
Comment: This does not work in more recent versions of Ubuntu, but this workaround should: http://askubuntu.com/questions/456452/
Answer: With Ubuntu 17 and in XFCE the middle mouse button copy paste did not work at all.
Same issue still in Ubuntu 20.x.
Solution
To enable the middle mouse button paste function edit the xinput.

Query your device:
 xinput list

Identify your mouse. With me it was device number 10.

xinput list-props 10 gives me the settings for the mouse.

I need to change the value for "libinput Middle Emulation Enabled (294):" and I need to do it as root:
 xinput set-prop 10 "libinput Middle Emulation Enabled" 1

Check if the value changed to 1:
 xinput list-props 10

Yes, it works:  "libinput Middle Emulation Enabled (294):   1"
In a recent Ubuntu 20.x connecting a Logitech Marble Mouse with 2 buttons (old, white model) gave me
"libinput Middle Emulation Enabled (292):   0"   and I changed it accordingly.
In Ubuntu 18 and XFCE there is a significant change: NO LONGER "libinput Button Middle". Instead "Evdev Third Button Emulation". So the whole line is now (for my machine):
sudo xinput set-prop 10 "Evdev Third Button Emulation" 1

To make it persistent, add a line in ~/.xstartup!
In my case it just looks the same like before:
xinput set-prop 10 "libinput Middle Emulation Enabled" 1

That makes it effective from start on.
HINT: If yor flavour or surface of Linux GUI does not support xinput you might get a little error line each time you open a terminal.
Better solutions are always welcome :-)
This is what is behind it.
I strongly disagree that Ubuntu and Gnome decided to disable the standard Unix Middle Mouse paste. Even in XFCE Ubuntu 17 it is devastated. May the managers behind this decision find a soon and painful end. You make my life hard.
Many, many thanks to Gilles who found the solution!!!
I had the same issues using Ubuntu 16, 14.10 and earlier:
Unix style copy paste in the terminal not working.
Disappointing default settings.
However, here is a solution (partly a wrap up of other peoples great work):

To fix the terminal issue I successfully put the following lines into my xorg.conf:

(see if  /etc/X11/xorg.conf is suitable for you. May be different for Lubuntu etc.)
Section "InputClass"
    Identifier "middle button emulation class"
    MatchIsPointer "on"
    Option "Emulate3Buttons" "on"
EndSection

The very anoying malfunction of a missing 3rd mouse button (touch pad, Marble Mouse) can actually be fixed with the
"gpointing-device-settings". Just install using CLI with:
apt-get install gpointing-device-settings

Then invoke gpointing-device-settings to get the gui window.
Remark: There is an unfixed bug in newer Ubuntus that wipes out your settings when rebooting. You may put gpointing-device-settings in auto-start but still need to prompt then. I am not aware of any proper config solution.
Probably some steps need a sudo or root access. I assume you know.
However, now I can use the unixish copy paste by mark and middle mouse button. At least in terminal.
And for the Marble Mouse there is a separate article with a lot of config details.
Addendum
With Ubuntu 17 and in XFCE the middle mouse button copy paste did not work at all.
Wayland is different.
Sometimes it is helpful to enter
gsettings set org.gnome.settings-daemon.peripherals.mouse middle-button-enabled true

With some luck it is persistent. Else try to create a start script.
Comment: outstanding! Thank you. Worked perfectly on 17.04
Comment: Doesn't work on 16.04.

fails with error 'property 'libinput Middle Emulation Enabled' doesn't exist, you need to specify its type and format'
Comment: @catbadger Maybe you need the `evdev` version.  Look at the `with evdev` section in  https://askubuntu.com/a/868173/460211 . I was getting the same error and this worked.
Comment: In Ubuntu 18 and XFCE there is a significant change: NO LONGER "libinput Button Middle". Instead "Evdev Third Button Emulation". So the whole line is now (for my machine):   sudo xinput set-prop 9  "Evdev Third Button Emulation" 1             This answers the comment from  catbadger Nov 23 '17; do I hate the missing formatting in comments? no comment - may be you get the gist anyways.
Comment: I[m finding that @opinion_no9's original suggestion, i.e., using `libinput` works with 18.04, at least for most applications.    `evdev` didn't work for me.    Maybe you have to set it up manually in `xorg.conf` before it will work?
Comment: Leo Simon' s suggestion is right: Depending on U. version and GUI (Gnome, XFCE4, Wayland) sometimes works sometimes not. In U 17.04, -.10 nothing OK,  server crashes etc.. U18.04 and U18.10 are good quality again, middle mouse works fine ;-).  I'm always surprised how great the touchpad of my Fujitsu laptop works with XFCE4: Scrolling at right side, two-finger gestures, all works. The desktop with the Marble Mouse trackball I got the scrolling work for one of the small buttons. Unfortunately I often can not reproduce the positive achievements on other machines. However: Much to discover ...
Comment: Awesome answer. I have another problem though, I have to double click the middle button for the event to be recognized by my apps (VSCode, Chrome etc), the single middle click does not work at all. Anyone faced this?
Comment: My god this is the most accurate solution ever! No need to re-login, it works like a charm!
Comment: This is a great example of the awfulness of Linux.
Answer: You can also set the middle mouse button on a triple-finger-tap by calling
synclient TapButton3=2

(Put this in a script and add it to your startup programs)
It is strange, cause there seems to have been a bugreport, that supposed to have been fixed.
source: enable a three finger tap on my synaptic touchpad:
Answer: Enable it for all users by changing the default value in /usr/share/glib-2.0/schemas/org.gnome.settings-daemon.peripherals.gschema.xml:
Look for the key middle-button-emulation that looks like this:
<key type="b" name="middle-button-enabled">
  <default>false</default>
  Middle button emulation
  <description>Enables middle mouse button emulation through simultaneous left and right button click.</description>
</key>

Change default to true:
<key type="b" name="middle-button-enabled">
  <default>true</default>
  Middle button emulation
  <description>Enables middle mouse button emulation through simultaneous left and right button click.</description>
</key>

Answer: I found a nice solution using xubuntu 14.10
(I think this is nice because it doesn't require tap to click to be enabled, I don't like tap to click)
First you need to install xdotool
sudo apt-get install xdotool

Then write a bash script to send the middle mouse click. Your going to want to write something like this
#!/bin/bash

xdotool mousedown 2;
xdotool mouseup 2;

Save it to a filename you'll remember like "MiddleClick.sh"
next change your permissions to the file to make it executable for yourself
chmod u+x MiddleClick.sh

You can now send a middle click to where ever your mouse is by running this file, in terminal it would be
bash MiddleClick.sh

However, to assign a shortcut to do this, go to Settings > Keyboard and go into the Application shortcuts. Add a new one, point to the file you created and assign a shortcut. you can now use this new shortcut to send a middle click.
Answer: I have stolen some area from the right and left buttons on the touchpad using synclient, so that I can have all 3 buttons at the bottom of touchpad:

synclient MiddleButtonAreaTop=4035
synclient RightButtonAreaLeft=3890
synclient MiddleButtonAreaRight=3890
synclient MiddleButtonAreaLeft=3155

I computed the values using the current edges as base:

LeftEdge = 1685
RightEdge = 5361
TopEdge = 1489
BottomEdge = 4409
RightButtonAreaTop = 4035
Answer: Adding to @rubo77's answer and based on the output of your synclient you should try:
synclient ClickFinger3=2

Then you can use a 3 finger tap to activate the middle button click. It worked for me.
Comment: If you want to improve another answer, please suggest an edit to it and don't create a new (incomplete) answer.


Shell BrowseForFolder preselected path

Question: I have this call:
oShell.BrowseForFolder(Me.hwnd, "Select path:", 0, "C:\dir\")

This opens a standard file browser dialog with "C:\dir\" as root.
My problem is that you can not browse above the root folder. (as specified in doc http://msdn.microsoft.com/en-us/library/bb774065(v=vs.85).aspx)
Any suggestions on oppening this dialog with a selected path and full browsing posibility?
Thanks
Comment: @Luke On the contrary, it's perfectly possible through `SHBrowseForFolder`.
Comment: Well, the underlying implementation (SHBrowseForFolder) has the same limitation so you're not going to have any luck using this API.
Comment: Nice.  Didn't even know about the callback mechanism.
Answer: The way to do this involves calling the underlying API, SHBrowseForFolder().
Since you want the entire shell namespace to be available you need to pass NULL as pidlRoot. In order to select your desired folder you will need to provide a callback in lpfn. Make this callback respond to BFFM_INITIALIZED by setting the selected folder. This selection is performed by sending the BFFM_SETSELECTION message to the dialog's window handle (passed to the callback function).
No code because I don't have VB6, but hopefully this outline of the method is enough to get you on your way.
Comment: +1 Karl Peterson's excellent VB6 website has some VB6 code showing this technique. I have provided the link in my answer
Answer: Karl E Peterson's excellent website contains a sample which demonstrates the API call SHBrowseForFolder with a callback, as in David Heffernan's answer.
The KeyStuff project
Look at MFolderBrowse.bas, routine BrowseForFolderByPIDL which passes a callback function BrowseCallbackProc.
Comment: +1 good work, I know nothing about vb so it's good to get input from someone who does
Answer: Try the old CCRP project.  It has a nicely done implementation of the Browse dialog.  I used it in several of my projects and it has properties to address the issue you are having.
Answer: Here a code ready for copy and paste in a C++ class:
// static
int CALLBACK Func::FolderBrowserCallback(HWND h_Dlg, UINT uMsg, LPARAM lParam, LPARAM lpData)
{
    if (uMsg == BFFM_INITIALIZED)
    {
        // Requires Windows XP or higher
        SendMessageW(h_Dlg, BFFM_SETEXPANDED, TRUE, lpData);
    }
    return 0;
}

// returns an empty string u16_PathOut if an error occurrs or if the user cancels the dialog
void Func::GetOpenFolder(HWND           h_Owner,
                         const WCHAR* u16_Title,     // IN:  Title at the top of dialog
                         int          s32_CsidlRoot, // IN:  Root folder for treeview (CSIDL_DRIVES -> My Computer)
                         const WCHAR* u16_Preselect, // IN:  NULL or the folder to be preselected and expanded
                         WCHAR*       u16_PathOut)   // OUT: selected path
{
    u16_PathOut[0] = 0;

    // CoInitialize(NULL);
    // InitCommonControls();

    ITEMIDLIST* pk_RootPIDL = NULL; // NULL -> Root = Desktop
    SHGetSpecialFolderLocation(h_Owner, s32_CsidlRoot, &pk_RootPIDL);

    BROWSEINFOW k_Info = {0};
    k_Info.hwndOwner = h_Owner;
    k_Info.pidlRoot  = pk_RootPIDL;
    k_Info.lpszTitle = u16_Title;
    k_Info.ulFlags   = BIF_RETURNONLYFSDIRS | BIF_USENEWUI;

    if (u16_Preselect)
    {
        k_Info.lpfn   = FolderBrowserCallback;
        k_Info.lParam = (LPARAM)u16_Preselect;
    }

    // DO NOT DISABLE Wow64FsRedirection HERE !!
    LPITEMIDLIST pk_IDlist = SHBrowseForFolderW(&k_Info);
    if (pk_IDlist)
    {
        SHGetPathFromIDListW(pk_IDlist, u16_PathOut);
        CoTaskMemFree(pk_IDlist);
    }

    CoTaskMemFree(pk_RootPIDL);
}

Shell BrowseForFolder preselected path


Over 60 Ubuntu noob dual booter seeks Win10 Ubuntu reallocation, long walks on short pier

Question: Hail penguins.
I am an ancient Dos / Windows veteran experimenting  with dual boot Ubuntu and seeking guidance on reallocating space on my HDD.
1) I'm running an older Acer Aspire with 500GB.  Currently 400GB or so allocated to Windows C:, about 20 GB allocated to Ubuntu root.
2) I just freed up 0.5 GB unallocated space on the "left" of my EFI, and 16GB on the "right" of my Ubuntu root allocation.  450GB of C: (45 % utilized) in the middle. So for all practical purposes (forgive rounding)
0.5GB unallocated
0.4GB EFI
429GB C:
20GB Ubuntu
16GB unallocated
3) I want to a) move the 0.5GB to the "right" end, b) combine it with the 16GB of unallocated space and c) make that available to Ubuntu for user directories.
Can all of this be done in Gparted or do I need to use MS Disk Management /other utilities to move the unallocated space on the "left" ?
Sorry for the poor language skills. Me talk pretty one day.
Pallama
Comment: "Long walk on a short dock" has a nicer ring to it.
Answer: Adding the 16G on the right of the current  20G Ubuntu partition (and expanding the filesystem into the new space -- easy with gparted, even on a running system.
Moving every partition to the left, including the Windows partition, just to gain 500M, probably not worth the trouble and risk.  If you really want to use that space, just put a 500Mpartition there and make it someone's home directory or just some data storage space.  This partition may be mounted and will appear to just add usable space -- low risk.
Comment: Thanks ubfan1. I expanded the Ubuntu partition to add the 16GB and that worked just fine.  Now trying to live with Ubuntu and only go back to windows when necessary.


How to draw out troops when clan castle is in middle of base

Question: I just got 0 stars in a clan war attack because the clan castle was too deep inside the enemy base. I tried sending a giant to lure them out but it got stuck at the wall. I deployed a bunch more giants and they broke through the wall and the cc troops came and I tried to drop a lightening spell on them but they moved too fast.
How do you destroy the cc troops if the cc radius is still within the boundary of the buildings? If you drop 3 lightening spells on the castle while the troops are still inside would it destroy them?
Comment: If you have hogs, use one or two well placed hogs to get them out of the cc, then archers or barbs to draw them to the outside
Comment: Sounds like you're attacking something in the TH 7 or 8 range. Bases lower than that are too small to prevent you from luring out the CC troops (and even TH7 bases would need to be really spread out to do so). If that's the case, then why are you attacking with any ground troops at all? Using 3 lightning + 11 dragons will almost assuredly 3 star a TH7 base, and depending on the level of your dragons and the target's defenses, 2 or 3 star a TH8 base as well.
Comment: I assume you are a th8 since th7 below bases are too small to be unlurable. Try bringing a KillSquad, which consists of golems, wizards, and BK. Google kill squad and find out more.
Answer: Analyse the base first:

Locate the defences on the perimeter that are within the clan castle radius. The perfect one would be the one that is located on the side from which you wish to attack.
After having chosen a defence to use to lure the cc, check if there is a wall hindering you from getting to the defence.
If there is a wall you will need hogs. If there is no wall you will need at least two giants. Two giants because there maybe a spring trap waiting for the first giant, so send them with maybe a one second difference between dropping them.
If there is a wall and a lot of defences around your chosen defence, you will need 2 or 3 hogs. This is because one hogs may get wiped out before it even reaches the intended target. The hogs may seat just outside of the clan castle radius when they reach the target so having three will make sure they plough it down quick and move deeper and therefore awakening the castle troops.
If there is no wall do not send your lure giants at once, send one first, if it gets flung out by a spring trap you still have a second one. Same applies for hogs, do not drop the lure hogs at once, if there is a trap they all get flung out (likely).

Special conditions:

If there is a wall and the clan castle is too deep, you will need a giant to distract the selected defence, and at least 3 or 4 hogs to wipe out the outer defences and then move in to a deeper defence to lure out the CC troops. Youtube search "giant hog lure" and you will definitely find this strategy.
If you absolutely want to use lightning to kill the cc, don't kill them while they are still moving. wait for them to stop moving/to settle in a cluster then drop that lightning.
If using dragons at TH7 or 8, destroying an air defence using three lightings works well. Your dragons will kill the cc themselves.
If you follow point 3 above. Do not drop your dragons on spot, if there are wizards in the clan castle they can wipe them out quickly or at least bring all their health down in that one spot. I have seen this happening a number of time with newbies.
If using dragons to try to get to a entered down hall, do not drop all of them in one spot, they will all go to the sides following the buildings on the perimeter. Instead, drop one on the left and one on the right with a space difference of 3 buildings, drop one in the middle. They will move on the perimeter, and leave an open space where they have cleaned up, this is where you drop your other dragons, they will definitely move towards the centre.
Answer: Are you sure the castle was "too deep"? Best way to know is to view the base and click on the enemy castle. The circle drawn on the map shows you where a troop must reach to draw the CC troops.  By reach, I mean must occupy. An archer outside the castle radius attacking a building inside the castle radius doesn't count.
@pnizzle's advice is spot on.
Sometimes the only troop you need is a barbarian, goblin or even a wall breaker.  Giant is recommended because it usually lives long enough to lure everything in the castle out, and is a ground troop. Anything in a clan castle will attack a ground unit, but if the CC contains e.g. balloons, a minion crossing into the castle radius will NOT draw out the CC contents. Only troops that are able to attack air troops respond to an air troop.
Answer: You seem to be at least TH7 or this shouldn't be a problem for you.
Attack the side the clan castle is closest too. If the person is farming, surround the entire base with your troops. To get at least one star, snipe the town hall if possible. If possible, reserve some troops and clan castle troops to deal with the enemy troops. Rage spells should be kept until the troops are drawn out, and when your own troops realize there are enemy troops, use a rage spell to help your troops finish them off easily. Be wary of powerful troops like balloons and dragons though.
Hogs might be good, they do cost some dark elixir though. Hogs can jump over walls and reach where the other troops cannot. Really, the best way is to charge in with most of your troops and rage them up while fighting enemy troops. Most people in Legend or Champion leagues do this method. Otherwise, place one troop and draw them out then massacre them with poison spells and your other troops.
Answer: Use 1 Hog rider(send him close to cc as possible) to lure CC it works great! and u can use balloon if u don't have Hog Rider unlocked.


What's the difference in the glow color of the message ratings?

Question: When examing message ratings some appear to have a white glow and some have a golden glow which is a bit bigger then the white ones.
What's the difference between these 2 message ratings?
White glow:

Golden glow:
Answer: It represents the high-rated messages. At the bottom right corner of the message window there is an appraisal count, if it reaches some point it will glow. I'm not sure of the exact number.
As far as I know (and if it's the same as Demon's / Dark Souls and Bloodborne), there is no difference outside of that.
Comment: If it is the same as Dark Souls, people **love** to troll with these. I remember there being one that was highly upvoted and remained for months only for it to trick people into thinking there was secret passage
Comment: @Wondercricket Yeah, I've seen that kind of message in Elden Ring too. I actually enjoy them... I upvote that kind of message just to trick other players! :P


Get JNDI Names from DataSource after lookup

Question: What I want to achieve is to get the JNDI name as a String from a DataSource object.
I have the following code to get the DataSource:
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:/comp/env/dataPool");

My weblogic-ejb-jar.xml where JNDI name is set:
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-ejb-jar xmlns="http://xmlns.oracle.com/weblogic/weblogic-ejb-jar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.oracle.com/weblogic/weblogic-ejb-jar http://xmlns.oracle.com/weblogic/weblogic-ejb-jar/1.6/weblogic-ejb-jar.xsd">
    <weblogic-enterprise-bean>
        <ejb-name>AdminBean</ejb-name>
        <stateless-session-descriptor></stateless-session-descriptor>
        <resource-description>
            <res-ref-name>dataPool</res-ref-name>
            <jndi-name>jdbc/CARGAS</jndi-name>
        </resource-description>
    </weblogic-enterprise-bean>
</weblogic-ejb-jar>

So, when I get the ds object actually I can see the JndiNames but I cannot find the way to get it out from it:

My first guess was to do something like ds.getJndiNames but I only have the folowing options:

Any ideas how to do it?
Comment: I want to do this because I want to split the way to obtain the ds depending on server. This code is shared by WebSphere and Weblogic, and WebSphere likes the `java:comp/env/dataPool` whereas that Weblogic wants the jndi name `jdbc/CARGAS`
Comment: Why do you even want this? Btw: with the debugger you look into the implementation, not the interface... you can always downcast, but do you really want to?
Answer: Ok!
So at the end I use Reflection to achieve what I want to.
Here my solution:
public String getJndiName() {
    try {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("java:/comp/env/dataPool");
        Method method = ds.getClass().getMethod("getJNDINames");
        String[] jndi = (String[])method.invoke(ds);
       return jndi[0];
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

Hope it will be helpfull for anyone else in the future :-)
Comment: Hi, what package is Method ??


$\mathcal{M}_{n}(\mathbb{C})$ as a Hilbert space

Question: Let $\mathcal{M}_{n}(\mathbb{C})$ be the set of $n\times n$ matrices over $\mathbb{C}.$ I know that for $A,B\in \mathcal{M}_{n}(\mathbb{C}),$ $$\langle A,B \rangle=\text{tr}(B^{*}A)$$ defines an inner product on $\mathcal{M}_{n}(\mathbb{C})$ and hence we can induce the norm.
I have a problem on how to verify that every Cauchy sequence of $\mathcal{M}_{n}(\mathbb{C})$ converges on $\mathcal{M}_{n}(\mathbb{C})$.
Any hint/help would be appreciated.
Comment: If you want to have a direct proof, not using arguments from some answers below, you can just look at each entry.  If a matrix sequence is Cauchy, then the $(i,j)$-entries of the matrices in this sequence must also form a Cauchy sequence of complex numbers.
Answer: The dimension of $M_n(\mathbb{C})$ is finite and in a finite-dimensional space all norms are equivalent. Therefore, you can work as if your space was $\mathbb{C}^{n^2}$, endowed with its usual norm, which is complete.
Answer: Since $\mathcal{M}_n(\mathbb{C})$ is finite-dimensional, it is complete. Whence the result.
In fact, $\mathcal{M}_n(\mathbb{C})$ equipped with the given Hermitian product is just $\mathbb{C}^{n^2}$ with its usual Hermitian structure.


When should you start working on help documentation on a large project?

Question: I'm involved in a massive project that is turning 70+ antiquated systems into one system for a large company. The whole team and the executives at the company realize that this is a huge undertaking and that some things will be different for many people and there is no way around it. I'm one of the 5 UX/Information Architects on the project and just the other day I realized that we're going to need help documentation and a help interface.
Right now everything is in flux. Since there are so many systems there is no current-state understanding of the entire system and how everything connects. As we develop requirements and document the functionality that the new system needs to have we start finding more functional requirements that we didn't know about.
I really can't fully state how big this application will be for this company. As a result I can see right now that help will be crucial when we transition over to the new application, but I don't know when we should start working on the help documentation. I really don't want to wait until the application is finished or close to finished because I know the majority of the project team will sweep it under the rug and say that training will cover it.
Basically, my question is when should we start collecting help documentation, and what is the best way to document it as the project progresses?
Answer: Now
If you are working on a managed project, there should be Design Requirements, which should give you a foundation to build from.  During development there is much in transition, but approved design documents can assist in creating help info.
The final stages of system testing and user acceptance testing, should give you the chance to fine tune your help documents.  If they are mostly complete prior to testing, they will be extremely helpful to testers, which will make their job easier, while testing your help pages at the same time.
Answer: As soon as there is anything at all that you can say -- so, if not now, then very soon.  "Anything at all" can leave place-holders for specific interfaces if they haven't been worked out yet; you can probably at least start writing your conceptual documentation ("what is a..." for the key things in your application), and you probably have some ideas about workflows that imply an outline.
The danger of waiting until the end is not just that it will get short shrift.  In every sizable documentation project that I have worked on (and I've been doing this for a couple decades), the process of trying to explain it has turned up problems in the interface.  The sooner you flush those out, the more likely it is that they'll get fixed.  This is especially true on a project with a large team where no single person has a consistent view of the entire system.  Each person works on his piece and you only find out later that they don't quite line up; documentation and test plans are the remedies for that.
Answer: The goal of a UX process should be to create an interface that won't need help at all. It'd be so naturally intuitive and meet the desires and needs of the end-user that it'd be moot.
Of course, that's rarely a reality we have the pleasure of accommodating.
As such, sometimes a means to provide help is a necessity. As to when to start working on it, I think James is close with 'now' but I'd probably go with '2 months ago'. ;)
Point being that this has to be part of the process. UI design, content, requirements, help, etc. all need to be developed in conjunction as they all influence each other.
As a bonus, as help is being created, it may provide opportunities to discover ways to circumvent the need for the help that is written through updates in the UI.


What are name of these hinges that hold the kitchen cabinet door?

Question: Here is picture of the kitchen cabinet door that is just under the sink. The hinges are rusted and I want to replace these. However, I am not sure what these hinges are called and how to get the exact same ones again. What are these called?
Comment: You've got the names from the answers. Remove the hinge and take it to your home store or a cabinet maker. Chances are they'll be able to match it.  There are many styles so bring the old one in.
Answer: Those are wide-angle hinges, definitely more than 110°.

Image from https://www.blum.com/us/en/products/hingesystems/clip-top-blumotion/programme/ (no affilations)
Answer: According to "A complete guide to hinge types," there's a strong possibility that what you have is called a full overlay hinge. A search with that term also returns a link to MyKnobs.com, largest collection of decorative hardware for something that looks pretty close to your image, a European Hinge 110 Degree Full Overlay:

Image from last linked site.
There are various configurations for this type of hinge, including angle of opening and extension length.


Number of vendors available for each product, number of PurchaseOrderIDs where these top products are present

Question: Written the Top 10 Products based on the number of Vendors available for each product.
Also, display the number of PurchaseOrderIDs where these top products are present.
select
    top 10 pod.productid,
    count(vendorid)as no_of_vendors,
    count(poh.purchaseorderid)as no_of_purorder
from purchasing.purchaseorderdetail pod join purchasing.purchaseorderheader poh  on
       pod.purchaseorderid=poh.purchaseorderid
group by pod.productid order by count(vendorid) desc

I can't get the correct output. I used adventure works 20012.  Please suggest an answer for this query.
Answer: select
    top 10 pod.productid,
    count(DISTINCT(vendorid))as no_of_vendors,
    count(poh.purchaseorderid)as no_of_purorder
from purchasing.purchaseorderdetail pod join purchasing.purchaseorderheader poh  on
       pod.purchaseorderid=poh.purchaseorderid
group by pod.productid order by count(DISTINCT(vendorid)) desc, count(poh.purchaseorderid) DESC

Without DISTINCT, it's just counting the same thing as the number of purchase orders. I don't think it matters in this data here, but I would also point out that if an item appeared twice on the same purchase order, it would also double-count that if there was no DISTINCT used on that. I am also, by the way, assuming that because there are so many products that have just three vendors that you wanted it further ranked by the number of purchase orders for that product.


Spring: java.io.NotSerializableException: MapSqlParameterSource

Question: I'm trying to insert a simple base with Spring JdbcTemplate mapping the query of parameters with MapSqlParamaterSource and am taking error as the data below:
public void adiciona(Conta conta) {
  String sql = "insert into contas (descricao, paga, valor, tipo) values (:descricao,:paga,:valor,:tipo)";
  MapSqlParameterSource pss = new MapSqlParameterSource();
  pss.addValue("descricao", conta.getDescricao());
  pss.addValue("paga", "true");
  pss.addValue("valor", conta.getValor());
  pss.addValue("tipo", conta.getTipo());
  getJdbcTemplate().update(sql, pss);
}

Error log:
mar 22, 2015 12:16:00 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [spring mvc] in context with path [/contas] threw exception [Request processing failed; nested exception is org.springframework.dao.TransientDataAccessResourceException: PreparedStatementCallback; SQL [insert into contas (descricao, paga, valor, tipo) values (:descricao,:paga,:valor,:tipo)]; Invalid argument value: java.io.NotSerializableException; nested exception is java.sql.SQLException: Invalid argument value: java.io.NotSerializableException] with root cause
java.io.NotSerializableException: org.springframework.jdbc.core.namedparam.MapSqlParameterSource

Java Bean:
public class Conta implements Serializable {

  private static final long serialVersionUID = 4678852901357132238L;

  private Long id;
  private String descricao;
  private boolean paga;
  private double valor;
  private Calendar dataPagamento;
  private TipoDaConta tipo;

  // getters and settes

Someone can tell me how to solve this problem?
Answer: I also faced the same issue, I resolved it by changing it from
this.getJdbcTemplate().update(query,mapSqlParameterSource);

to
this.getNamedParameterJdbcTemplate().update(query,mapSqlParameterSource);

Answer: Try something like:
 this.getJdbcTemplate().update(updateStatement, new Object[] {conta.getDescricao(), "true", conta.getValor(), conta.getTipo()});

Comment: Thanks, but I want to use MapSqlParameterSource in my queries, can you help me?
Comment: Yes, I understand. There is another way to use the MapSqlParameter in queries for the Spring-Jdbc?
Comment: If you are really interested in using MapSqlParameter then change your jdbc template to named parameter jdbc template defined like `

 `


F# deedle Frame, how to get row index and column index, and datatype for each column

Question: I have a few basic question regarding Frame, which seems not being address in the documentation.

How can I get the column headers?
How can I get the index (both column and row)?
How do I know the current datatype for each column?
Answer: I think most of it is in the documentation but a quick scan through the methods in VS will give you the following:
df.ColumnKeys
df.ColumnTypes
df.RowIndex
df.ColumnIndex


Extending numpy arrays

Question: I'm new to Python/numpy.
I'm trying to extend numpy.array to give it some functions that make it nice for representing images (e.g. convert to greyscale etc).
import numpy as np
import cv2
from support import *
import matplotlib.pyplot as plt

class Frame(np.array):
    def __init__(self):
        print "new frame"

f = Frame()

currently this gives me:
  File "o.py", line 6, in <module>
    class Frame(np.array):
TypeError: Error when calling the metaclass bases
    cannot create 'builtin_function_or_method' instances

I don't understand why this is an issue for Python?
Comment: Just as a side note you should check out: PIL Python Imaging Library http://www.pythonware.com/products/pil/#pil117.
It has these abilities and converting to/from ndarray is quite simple
Comment: And if you are going to go with PIL, you should try its fork [`pillow`](http://pillow.readthedocs.org/en/latest/), which is a more updated version that is also compatible with Python 3.
Answer: You want to be subclassing np.ndarray, not np.array, but it's a little more complicated than just swapping on out for the other in your example. It's probably worth taking a look at the documentation:
http://docs.scipy.org/doc/numpy/user/basics.subclassing.html
Comment: Thanks for this. In the end, I classed 'around' it, rather than extend it, looks like the safer option.

Extending numpy arrays


Cost effectiveness of fireplace with insert vs electric furnace

Question: Now that winter is here I have been using my fireplace (that has an insert) more and more instead of my furnace that has a electric heater. I was wondering which method of heating would be the most cost effective.
I pay $0.10/KWH for power and $5.00 for 0.60 cubic feet of wood.
The fireplace insert has a 80 watt motor that blows air.
There are a lot of articles about a fireplace is very inefficient since most of the air that your are heating is going up the chimney but there is little documentation on how a fireplace insert would change that. My assumption is that it would more efficient since the fire is in a chamber that is (more) sealed and the heat is being absorbed by the metal. There is also a small fan that blows the heat to the room.
Thanks for the help!
Comment: What's your budget? Let me rephrase, how much money are you using up every winter?   Also does your power company have any special electric rates?
Answer: electricity, hands down.
electricity at $0.10 = $330 / cord. (using estimate from link)
your wood is $1,065 / cord. ( 128cuft/cord * (1/0.6) * $5 ). that's high btw...
the electricity is 100% efficient, inserts are roughly 50%.
checkout http://extension2.missouri.edu/g5450 for more info and comparisons.
Comment: At that rate the op needs to go around the neighborhood looking for downed trees that  they can cut up for firewood - then it is probably cheaper.
Comment: So you are saying that if I can get wood at $150/cord (instead of $300 since wood burning is 50% efficient) or less: It will break even cost/efficiency-wise?

I agree the wood cost is high.
Comment: yes, that's what the numbers show at least. your results may somewhat vary depending on a million things. you could find a time when you have two days with equal hi/lo temps, and use one fuel exclusively each day, measuring and summing up the fuel used, to calculate an actual cost/day on your house of each fuel.


adding elements to scrollview using java when there is more then 1 child

Question: I am trying to add elements to my scrollview,
this scroll view has a vertical linear layout inside of it.
(i added another linear layout - horizontl, inside that will manage 2 textviews and an image according to the attributes i assigned them),
i am trying to add elements of this inner layout to my scroll view (id=insideLineLayout)
(each element added to scrollview will contain these 2 texts and an image)
because of the fact scrollview can only have 1 child i am unable to do this.
would appreciate some help, nothing seems to be working here.
Thanks.
my current xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/searchScreenOuterLinearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
         >

        <TextView
            android:id="@+id/catagoryselectedText"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="70dp"
            android:text="selected catagory"
            android:textSize="20dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="12dp"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/searchText"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp" />

        <ImageButton
            android:id="@+id/searchButton"
            android:layout_width="50dp"
            android:layout_height="40dp"
            android:background="@drawable/search_icon" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="10dp"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/radiusText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:paddingTop="5dp"
            android:text="Search Radius"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <SeekBar
            android:id="@+id/radiusBar"
            android:layout_width="140dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp" />
    </LinearLayout>

    <ScrollView
        android:id="@+id/searchScrollView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <LinearLayout
            android:id="@+id/searchScrollViewLinear"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical"
            android:paddingTop="10dp" >

            <LinearLayout
                android:id="@+id/insideLineLayout"
                android:layout_width="fill_parent"
                android:layout_height="30dp"
                android:orientation="horizontal"
                android:weightSum="100"
                 >

                <TextView
                    android:id="@+id/linesPrice"
                    android:layout_weight="20"
                    android:layout_width="wrap_content"
                    android:layout_height="fill_parent"
                    android:text="tmp1"
                    android:textAppearance="?android:attr/textAppearanceMedium" />

                <TextView
                    android:id="@+id/linesInfo"
                     android:layout_weight="60"
                    android:layout_width="wrap_content"
                    android:layout_height="fill_parent"
                    android:paddingLeft="15dp"
                    android:paddingRight="15dp"
                    android:text="tmp2"
                    android:textAppearance="?android:attr/textAppearanceMedium" />

                <ImageView
                    android:id="@+id/imageInfo"
                    android:layout_width="40dp"
                    android:layout_height="match_parent"
                    android:background="@drawable/tv_icon" />

            </LinearLayout>

        </LinearLayout>
    </ScrollView>

</LinearLayout>

Comment: You can make multiple copies of `insideLineLayout` and add them to `searchScrollViewLinear`. But this seems a lot like a ListView...
Comment: adding these should be done dynamically, since i won't know how many elements will be added, and their information until i get them. (otherwise you are right, and i'd do what you suggested)
Comment: @Roy what's the issue? Programmatically adding views to the LinearLayout inside the ScrollView results in an error? +1 to Sam.
Answer: Consider how long your list can get as ListView has been optimized in many ways which a regular scroll view is not. If you have too many elements you might start get out of memory exceptions.
In order to dynamically add views to a ScrollView you first need to get the container view inside the ScrollView (most likely a LinearLayout), then you simply do following for each view you add:
View view = inflater.inflate(R.layout.view_to_add, container, false); // this is used if you create from xml, if you make it in code you'd use the regular constructor.
// update the view content (view.findViewById(); etc.)
container.addView(view);


After system upgrade, blank screen with cursor flashing and won't load GUI (Nvidia driver problem)

Question: thank you in advance for your help. I know there are many threads about similar topics to this, but none have worked, trust me I have tried them all!
Ubuntu prompted a system update, including Nvidia drivers, through the GUI, I clicked accept and it updated in the OS. After the update, I could not view images, with the error message:
/lib/x86_64-linux-gnu/libpango-1.0.so.0: undefined symbol: hb_glib_script_to_script
The update prompted a restart, so I did, hoping it would fix it. After that, it would not start, and i get the infamous flashing cursor on a black screen. I can access the terminal by doing Ctrl + Alt + F2, and everything seems OK, it just will not load the main OS.
I tried so many solutions online, but I think I have narrowed down my problem to something very specific. After reinstalling Nvidia drivers multiple times, I tried to run nvidia-settings and now get the error messages;
/lib/x86_64-linux-gnu/libpango-1.0.so.0: undefined symbol: hb_glib_script_to_scrip
libinvidia-gtk3.so: cannot open the shared object file: No such file or directory
/lib/x86_64-linux-gnu/libpango-1.0.so.0: undefined symbol: hb_glib_script_to_script
libinvidia-gtk2.so: cannot open the shared object file: No such file or directory

Now this is the same error message I got when trying to open an image earlier, so narrows down further it is a graphics issue. However, after some googling, it seems the package libharfbuzz has something to do with this hb_glib_script_to_script business.
Here is where I might have made a mistake: I remember trying to reinstall/install a package called libharfbuzz, but I can't remember the reason. I downloaded a tar.gz of this package, and did the ./configure and sudo make install. After whatever I did there a couple of weeks ago, I left it, and nothing bad has happened since then.
Some things I have tried:

reinstalling all drivers
loading the old kernel in GRUB
changing GRUB settings including using nomodeset
reinstalling libpango-1.0-0 and libharfbuzzb0 packages using apt install

Currently Ubuntu is unusable for me. Please help if you can. I am happy to provide more info if it is needed.
Comment: I read ```hb_glib_script_to_script``` is implemented by ```libharfbuzz0b``` (is libharfbuzzb0 a typing error in your post? If not, did you try to reinstall the correct package?). Since you installed another version of ```libharfbuzz``` with make install you should uninstall it with ```sudo make uninstall```. I believe this manually installed package is not managed by apt and can lead to problems (different versions on your systems...). You may want to check in ```/usr/local/lib``` and in ```/usr/lib/x86_64-linux-gnu``` if you have many versions of ```libharfbuzz```
Comment: Also can you add the output of ```ldd /lib/x86_64-linux-gnu/libpango-1.0.so.0``` ?
Comment: Nice to hear. I'll put this as an answer, such that you can accept it to close the thread
Comment: @UnderTheHoud the `sudo make uninstall` in the extracted tar.gz did the trick. That was so simple! Thanks so much for the help, such a simple solution
Answer: As stated in the comments, it is possible that having different versions of the same package leads to problems. Uninstall libharfbuzz that was installed with sudo make install by running sudo make uninstall in the extracted tar.gz


Google Weave (libiota) Host Hvac

Question: I followed these steps to get the Host Light example device registered on Weave and running on a Raspberry Pi 3. I'm able to control it with Home and the Weave Console.
Now I'm trying to do the same for a Host Hvac device (I looked at the Hvac example for the MW302 as a reference), but I'm not able to register the device with ./out/host/examples/hvac/hvac -r xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
It gets stuck at the following, with no visible errors:
[(4068588.179)I daemon.c:146] Heap state at daemon_connected: free=0, iota_allocated=15721, iota_max_allocated=15754
[(4068588.180)I daemon.c:152] Daemon connected.

With the Host Light example, I do see the device registering and it works fine:
[(4069131.290)I daemon.c:268] Waiting for registration message to be sent.
[(4069131.290)I daemon.c:146] Heap state at daemon_connected: free=0, iota_allocated=15234, iota_max_allocated=15268
[(4069131.290)I daemon.c:152] Daemon connected.
[(4069131.290)I daemon.c:137] Registering with ticket xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
[(4069131.290)I weave_http.c:98] Sending PATCH Request https://www.googleapis.com/weave/v1/registrationTickets/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
[(4069133.198)I weave_register.c:205] Sending Registration Finalize Request
[(4069133.198)I weave_http.c:98] Sending POST Request https://www.googleapis.com/weave/v1/registrationTickets/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/finalize?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
[(4069135.880)I settings.c:71] Device id: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
[(4069135.880)I weave_register.c:233] Sending Registration OAuth Request
[(4069135.880)I weave_http.c:98] Sending POST Request https://accounts.google.com/o/oauth2/token
[(4069135.196)I weave_register.c:270] Registration Complete
[(4069135.196)I dev_framework.c:295] Heap state at daemon_registered: free=0, iota_allocated=23704, iota_max_allocated=35344
[(4069135.196)I dev_framework.c:296] Registration Succeeded.

> [(4069135.197)I weave.c:550] Fetching Command Queue

Has anyone managed to create a Host Hvac device successfully?
Answer:
not able to register the device with ./out/host/examples/hvac/hvac -r xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
It gets stuck at the following, with no visible errors:

I think that you add the argc, argv in the main() and HostIotaFrameworkConfig config
Eg:
int main(int argc, char** argv)

HostIotaFrameworkConfig config = (HostIotaFrameworkConfig) {

  .base =
      (IotaFrameworkConfig){
          .cli_commands = NULL,
          .num_commands = 0,
          .builder = create_daemon_,
      },
  .argc = argc,
  .argv = argv,
  .user_data = NULL,

};

Answer: There's now an Hvac host example in the Libiota repo: https://weave.googlesource.com/weave/libiota/+/master/examples/host/hvac_controller/
For those of you working on running any of the host example devices on a Raspberry Pi, note that you might need the following dependencies:
sudo apt-get install libssl-dev libldap2-dev libidn11-dev libssh2-1-dev libkrb5-dev librtmp-dev

Also weave_client (used to register the device) needs Pycurl on your Linux machine. Download the source from pycurl.io and install it with python setup.py install. You may need to install these dependencies as well:
sudo apt-get install libcurl4-gnutls-dev python-dev

Google Weave (libiota) Host Hvac


Adding lines to an open file?

Question: I have an std::ifstream object:
std::ifstream file(file_path);

I read lines from it:
std::getline(file, line);

Is it legal to add lines to this file from another place while the stream is open? E.g. even after I reach EOF in the C++ program, can lines be added through a text editor, and getline be called again to get the newly added lines? What does the standard say?
Comment: This post seems relevant? http://stackoverflow.com/questions/15385302/reading-a-file-while-it-is-being-written-by-another-process
Comment: open system call may not succeed. what are you trying to do, if you want an app to write into a file, then another to read at the same time, try to used a pipe, search for "pipe c++"
Comment: It is legal, but it's not likely to do what you want it to. You may get lucky, though...
Comment: Go ahead and try for yourself ;)
Answer: It is legal and it should do what you expect on most reasonable operating systems. Note that the input stream needs to be cleared in case you reach EOF. The output stream needs to be flushed one way or another. The code below illustrates that.
#include <iostream>
#include <fstream>
#include <string>

int main()
{
    const char *f = "f.txt";
    // create an empty file
    std::ofstream os(f);
    os.close();
    std::ifstream is(f);
    for (unsigned i = 1; 3 > i; ++i)
    {
        os.open(f, std::ios_base::out | std::ios_base::app);
        os << "line  " << i << std::endl;
        os.close();
        std::string s;
        is.clear();
        std::getline(is, s);
        std::cerr << s << std::endl;
    }
    os.open(f, std::ios_base::out | std::ios_base::app);
    for (unsigned i = 3; 6 > i; ++i)
    {
        os << "line  " << i << std::endl;
        os.flush();
        std::string s;
        is.clear();
        std::getline(is, s);
        std::cerr << s << std::endl;
    }
}

Adding lines to an open file?


Provide UserName<553> message in quick

Question: I have created an application for FIX transactions using QuickFIX c++ API. The application is connecting to the server but the server sends "Provide UserName<553>" message. I looked for and result and found that i need to add username and password to the toAdmin method created this following code to in order to achieve that
<code>void Application::toAdmin( FIX::Message& message, const FIX::SessionID& sessionID)
{
    if (FIX::MsgType_Logon == message.getHeader().getField(FIX::FIELD::MsgType))
    {
        FIX44::Logon& logon_message = dynamic_cast<FIX44::Logon&>(message);
        logon_message.setField(FIX::Username("my_username"));
        logon_message.setField(FIX::Password("my_password"));
    }
}
</code>
But then it throws and Exception. Please suggest what to do
Comment: And the exception is...?
Answer: remove this line and exception is handled
<code>   FIX44::Logon& logon_message = dynamic_cast<FIX44::Logon&>(message);
</code>
after that Put it
message.setField(FIX::Username("my_username"));
  ```````
    message.setField(FIX::Password("my_password"));

Provide UserName<553> message in quick


How to I reveal a hidden image using core graphics by drawing with finger?

Question: I have a custom UIView where I handle touch events from the user. This view contains a UIImageView where I show a hidden image. I want to use touch events from the user to slowly reveal the hidden image. I think core graphics need to be used, but I'm not sure how to do that. How can this be achieved?
What I have now:
public class customTouchView: UIView {

    var overlayImageView = UIImageView()

    override open func draw(_ rect: CGRect) {
        overlayImageView.frame = rect
    }

    func drawAt(_ point: CGPoint) {
        UIGraphicsBeginImageContextWithOptions(overlayImageView.bounds.size, false, UIScreen.main.scale)
        overlayImageView.image?.draw(in: overlayImageView.bounds)

        //Draw here, need to somehow reveal the image

        overlayImageView.image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    }

    init(image: UIImage) {
        super.init(frame: .zero)
        //Just adding overlayImageView as a subview, setting my image and alpha to 0.5. The image should be hidden at the beginning and touch events that draw over the image should reveal the image.
        addSubview(overlayImageView)
        overlayImageView.image = image
        overlayImageView.alpha = 0.5
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else { return }
        let point = touch.location(in: self)
        drawAt(point)
    }

    public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else { return }
        let point = touch.location(in: self)
        drawAt(point)
    }
}

Answer: You can do this easily by using a CAShapeLayer as a mask layer...
The portions of the mask that are clear (alpha = 0) will not show through, while the portions that are not clear (alpha = 1) will show through.
Use the touches to add points and lines to a UIBezierPath that will be used as the .path of the shape layer. As you "draw" the path will "reveal" the underlying image.
Here's a simple example...
A "Reveal Image View" (UIImageView subclass):
class RevealImageView: UIImageView {

    private var maskPath = UIBezierPath()
    private var maskLayer: CAShapeLayer = CAShapeLayer()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    func commonInit() -> Void {
        // default is false for UIImageView
        isUserInteractionEnabled = true
        // we only want to stroke the path, not fill it
        maskLayer.fillColor = UIColor.clear.cgColor
        // any color will work, as the mask uses the alpha value
        maskLayer.strokeColor = UIColor.white.cgColor
        // adjust drawing-line-width as desired
        maskLayer.lineWidth = 48
        maskLayer.lineCap = .round
        maskLayer.lineJoin = .round
        // set the mask layer
        layer.mask = maskLayer
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        maskLayer.frame = bounds
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else { return }
        let currentPoint = touch.location(in: self)
        maskPath.move(to: currentPoint)
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else { return }
        let currentPoint = touch.location(in: self)
        // add line to on maskPath
        maskPath.addLine(to: currentPoint)
        // update the mask layer path
        maskLayer.path = maskPath.cgPath
    }

}

and an example view controller:
class ViewController: UIViewController {

    let myRevealView = RevealImageView(frame: .zero)

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let img = UIImage(named: "sampleImage") else {
            fatalError("Could not load image!!!!")
        }
        myRevealView.image = img

        // a view to show the frame for the Reveal Image view
        //  so we know where we can "draw"
        let frameView = UIView()
        frameView.layer.borderWidth = 1
        frameView.layer.borderColor = UIColor.gray.cgColor

        frameView.translatesAutoresizingMaskIntoConstraints = false
        myRevealView.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(frameView)
        view.addSubview(myRevealView)

        // respect safe area
        let g = view.safeAreaLayoutGuide

        NSLayoutConstraint.activate([

            // 300 x 300 (1:1 ratio)
            myRevealView.widthAnchor.constraint(equalToConstant: 300.0),
            myRevealView.heightAnchor.constraint(equalTo: myRevealView.widthAnchor),
            // centered in view
            myRevealView.centerXAnchor.constraint(equalTo: g.centerXAnchor),
            myRevealView.centerYAnchor.constraint(equalTo: g.centerYAnchor),

            // constrain the frame view 2-pts larger
            frameView.widthAnchor.constraint(equalTo: myRevealView.widthAnchor, constant: 2.0),
            frameView.heightAnchor.constraint(equalTo: frameView.widthAnchor),
            // center it
            frameView.centerXAnchor.constraint(equalTo: myRevealView.centerXAnchor),
            frameView.centerYAnchor.constraint(equalTo: myRevealView.centerYAnchor),

        ])

    }
}

Using this as my "sampleImage":

it looks like this after "drawing" a bit:


Can I use domestic hot water from a gas combination boiler temporarily, while the pressure in the central heating circuit is low?

Question: Due to work on the heating pipes, the central heating water pressure is low.
Is there a safe way to use the gas combination boiler (Ferroli Modena 80 E, domestic hot water + central heating) for domestic hot water production (until the end of the work on the heating pipes)?
Currently the low central heating pressure light is blinking (as it should) and the fire does not turn on when hot water taps are opened.
Answer: Sure, it is safe, as it's meant to produce domestic hot water in the first place.  The problem is it won't start up because there's no water in it as it all has drained out. You need to put some sort of stops on the inlet and outlet heating pipes and re-pressurize the system before it will produce hot water.
Answer: Following the idea of GdD I put stops on more accessible pipe endings. After this I had to open a valve to restore the pressure in the central heating circuit. Than we had hot water in the taps again.
Comment: Could you edit this answer in as an **ETA** section in your original post? It's awesome to see how it all worked out, but [consensus](http://meta.diy.stackexchange.com/questions/686/would-it-be-in-bad-taste-to-post-a-picture-of-a-completed-result-of-a-question-i) is to keep info about the problem in the question and only have answers in the answer section.


fullcalendar.js slot highlighting

Question: I'm trying to fetch the selected slot of a fullcalendar instance and to access it via jQuery after a dayClick event.
<code>dayClick:
function(date, jsEvent, view)
        {
                var now = Date.now();
                var eventDate = Date.parse(date);
                if(now < eventDate)
                        {
                                selectedSlots.push(eventDate);
                        }
                else
                        {
                                $('#alert_past_event').modal('show');
                        }
        }
</code>
the correct slot is selected when clicking on it, but how can i access the slot? since it is a "dayClick" event, $(this) will always point to the whole day...
I tried "eventClick" but actually it's only working on events that have already been inserted into the calendar.
Answer: Okay while waiting for the 90 minutes questioning delay i figured out a solution for this:
instead of actually accessing the cell i render a new event on that cell:
<code>$('#calendar').fullCalendar('renderEvent',
    {
        title:'',
        color:'007A00',
        start:date,
        end:date_end,
        editable:false,
    });
</code>
so here's the full "dayClick":
<code>    dayClick:
    function(date, jsEvent, view)
        {
            var now = Date.now();
            var eventDate = Date.parse(date);
            if(now < eventDate)
                {
                    selectedSlots.push(eventDate);
                    date_end = date.clone();
                    date_end.add('30','m');
                    $('#calendar').fullCalendar('renderEvent',
                      {
                          title:'',
                          color:'007A00',
                          start:date,
                          end:date_end,
                          editable:false,
                      });
                }
           else
                {
                     $('#alert_past_event').modal('show');
                }
        }
</code>

fullcalendar.js slot highlighting


Binding doesn't work for the Textbox within a DataTemplate within a ContentPresenter

Question: My intention: Display a message box with the text entered in "userdata" control on click of "Show name" button (with the help of data binding instead of directly accessing the "userdata" control's Text property). I wrote this code to understand the template concept in WPF.
Issue with the below code: Databinding doesn't happen as intended.
NOTE: However, if I remove the "ContentPresenter" and the "DataTemplate" surrounding the "userdata" control, data binding works fine. Any leads to make this code work will be helpful.
Mainwindow.xaml:
<StackPanel>
    <Button x:Name="openFile">
        <Button.Template>
            <ControlTemplate>
                <Grid Width="300" Height="150">
                    <Rectangle Fill="Aquamarine" RadiusX="20" RadiusY="20" />
                    <Ellipse Fill="Azure"></Ellipse>
                    <ContentPresenter>
                        <ContentPresenter.ContentTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal" Height="50">
                                    <TextBlock Text="Name" />
                                    <TextBox x:Name="userdata" Text="{Binding Name, Mode=TwoWay}" Margin="5" Width="100" />
                                    <Button Content="Show Name" Click="Button_Click"></Button>
                                </StackPanel>
                            </DataTemplate>
                        </ContentPresenter.ContentTemplate>
                    </ContentPresenter>
                </Grid>
            </ControlTemplate>
        </Button.Template>
    </Button>
</StackPanel>

UserName.cs
public class UserName : INotifyPropertyChanged
{
    private string _name;

    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            FirePropertyChange("Name");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void FirePropertyChange(string propertyName)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

MainWindow.xaml.cs:
UserName user = new UserName();
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = user;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {

        MessageBox.Show(user.Name);
    }

Answer: DataBinding doesn't happen as intended in ContentTemplate, because Content is not set. Add Content binding <ContentPresenter Content="{Binding}">, and the rest will work
<ContentPresenter Content="{Binding}">
    <ContentPresenter.ContentTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Height="50">
                <TextBlock Text="Name" />
                <TextBox x:Name="userdata" Text="{Binding Name, Mode=TwoWay}" Margin="5" Width="100" />
                <Button Content="Show Name" Click="Button_Click"></Button>
            </StackPanel>
        </DataTemplate>
    </ContentPresenter.ContentTemplate>
</ContentPresenter>

Answer: That happens because DataTemplate is a "wrapper" around button's content (Button.Content) and uses this content as own DataContext. When Content is not specified then DataContext of DataTemplate is null and binding fails.
To make code work properly you should specify Button.Content property (It should be an instance of UserName class).
You may use button's DataContext as button's content (this way is ugly as duck):
<Button Content="{Binding RelativeSource={RelativeSource Self}, Path=DataContext}">
<Button.Template>
    <ControlTemplate TargetType="Button">
        <Grid Width="300" Height="150">
            <ContentPresenter>
                <ContentPresenter.ContentTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal" Height="50">
                            <TextBlock Text="Name" />
                            <TextBox x:Name="userdata" Text="{Binding Name, Mode=TwoWay}" Margin="5" Width="100" />
                            <Button Content="Show Name"></Button>
                        </StackPanel>
                    </DataTemplate>
                </ContentPresenter.ContentTemplate>
            </ContentPresenter>
        </Grid>
    </ControlTemplate>
</Button.Template>

When you remove DataTemplate and ContentPresenter from the tree then TextBox just inherits parent's DataContext (instance of UserName) so binding works properly.
The best way is following MVVM pattern.
DataContext of a window:
public class MainWindowViewModel : INotifyPropertyChanged
{
    public UserName User { get; } = new UserName();
}

Assign window data context:
public MainWindow()
{
    InitializeComponent();
    this.DataContext = new MainWindowViewModel();
}

Bind button to user:
<Button Content="{Binding User}">
    <Button.ContentTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Height="50">
                <TextBlock Text="Name" />
                <TextBox x:Name="userdata" Text="{Binding Name, Mode=TwoWay}" Margin="5" Width="100" />
                <Button Content="Show Name"></Button>
            </StackPanel>
        </DataTemplate>
    </Button.ContentTemplate>
    <Button.Template>
        <ControlTemplate TargetType="Button">
            <Grid Width="300" Height="150">
                <ContentPresenter/>
            </Grid>
        </ControlTemplate>
    </Button.Template>
</Button>

Comment: `{Binding RelativeSource={RelativeSource Self}, Path=DataContext}` can be written simply as `{Binding}`
Comment: You are right, I used full form to make it clear what's going on.
Answer: Issue was solved by changing the userdata control's XAML definition as below:
<TextBox x:Name="userdata" Text="{Binding DataContext.Name, Mode=TwoWay, RelativeSource={RelativeSource AncestorType=Button,Mode=FindAncestor}}" Margin="5" Width="100" />

When there are nested templates, compiler may not be able to identify the correct parent. Hence it is necessary to mention the relative source with the ancestor type and the path with *DataContext.*bindingdata


Unity-Ubuntu 16.04 dock and panel disappeared

Question: This happened somewhere when I switched to using Processor microcode firmware for Intel CPUs... in the Additional Drivers Settings, or uninstalled a system app called ibus. I cannot revert back now, since both the Dock and the Panel are gone, and I'm unable to find System Settings as well. It almost feels like I can't do anything now, like Ctrl+Alt+T doesn't give me a Terminal. Anyone who knows what was wrong here? Please help me out.
P.S. I have a AMD GPU driver. Previously,  the setting under additional drivers was something like do not use the device.
Comment: IMHO, anything that has to do with low level stuff like BIOS and CPU microcode should not be messed with :)
Comment: @AndroidDev one thing I'm sure of is that neither of the two were tweaked, I simply changed the Ubuntu system settings through its GUI though.
Answer: This happens when Ubuntu Unity plugin is disabled in CompizConfig Settings Manager.
Press ctrl+alt+f1 and enter your login credentials. Then run
sudo apt-get install compizconfig-settings-manager unity-desktop unity

and
DISPLAY=:0 ccsm &

Now go back to desktop by pressing ctrl+alt+f7 (or ctrl+alt+f8 if f7 doesn't work). CompizConfig Settings Manager should be there.
From ccsm, find Ubuntu Unity Plugin and enable it if it's disabled.
Finally you need to restart your computer, you can do it from the GUI or typing sudo reboot to any terminal.


Jinja DBT for loop union with some different columns across tables

Question: I'm creating a master events table, where almost all of the same columns are in every table, but a few tables are missing one or two columns. In those cases I'd like to replace those columns with null whenever the column doesn't exist in the table. When I run the code below, every cell in the output table is NULL.
Assume columns 1 and 2 are in every table, but column 3 is in table 1 and 2 but not 3.
{{ config(schema='MYSCHEMA', materialized='table') }}

{% set tables = ['table1', 'table2', 'table3'] %}

{% set possible_columns = ['col1', 'col2', 'col3'] %}

{% for table in tables %}
  {%- set table_columns = adapter.get_columns_in_relation( ref(table) ) -%}
  select
    {% for pc in possible_columns %}

      {% if not loop.last -%}

        {% if pc in table_columns %}
          {{ pc }},
        {% else %}
          null as {{ pc }},
        {%- endif %}

      {% else %}
        {% if pc in table_columns %}
          {{ pc }}
        {% else %}
          null as {{ pc }}
        {%- endif %}

      {% endif %}

    {%- endfor %}

  from
    {{ ref(table) }}

  {% if not loop.last -%}
    union all
  {%- endif %}
{% endfor %}

Answer: I'd recommend using dbt_utils.union_relations for  this. It does exactly what you describe -- it creates a superset of columns from all the tables and fills in nulls where appropriate.
{{ dbt_utils.union_relations(
    relations=[
        ref('table1'),
        ref('table2'),
        ref('table3'),
    ],
    include = ['col1', 'col2', 'col3']
) }}

BUT, if you want to roll your own...
The problem with your code is this line:
{% if pc in table_columns %}

adapter.get_columns_in_relation returns a list of Column objects, not a list of strings. To compare pc to the name of a column, you could use:
{% set cols = [] %}
{% for col in table_columns %}
    {% do cols.append(col.name) %}
{% endfor %}
...
{% if pc in cols %}

You can also remove a bunch of redundant code by pushing down the if not loop.last block to just the comma, so this all becomes:
{% for table in tables %}
    {%- set table_columns = adapter.get_columns_in_relation( ref(table) ) -%}
    {% set cols = [] %}
    {% for col in table_columns %}
        {% do cols.append(col.name) %}
    {% endfor %}
    select
    {% for pc in possible_columns %}
        {% if pc in cols %}
            {{ pc -}}
        {% else %}
            null as {{ pc -}}
        {%- endif %}{%- if not loop.last -%},{% endif %}
    {%- endfor %}
    ...

Comment: Hey thanks! i didn't know bout `adapter.get_columns_in_relation` I will check that out. I did try to replace `{% if pc in table_columns %}` with your recommendation of `{% if pc in [col.name for col in table_columns] %}` and I received the following error:

`Compilation Error in model   expected token ',', got 'for'`
Comment: My mistake, forgot that list comprehensions don't work in jinja. I've updated my answer
Comment: Awesome! I used `adapter.get_columns_in_relation` thanks!


How can I customize the SOLine InventoryID selector?

Question: I would like to customize the SOLine InventoryID selector to filter out certain inventory items based on the value of the class they are part of.  I've read about the [PXRestrictor] attribute and how it can be used to filter selectors.  This seems like it would work, except that the Item Class name is not available in that DAC, so I tried this:
[PXRestrictor(typeof(SelectFrom<InventoryItem>.
    InnerJoin<INItemClass>.On<INItemClass.itemClassID.IsEqual<InventoryItem.itemClassID>>.
    Where<INItemClass.itemClassCD.IsEqual<itemClassValue>>), "Custom items")]

but this is apparently not allowed.
It seems like I would need to override the selector itself, but the existing selector is rather convoluted and hidden beneath layers of attributes and I am not sure how to replicate even that, not to mention that option seeming rather near-sighted.
How could I go about this, or is this simply not a good option?
Answer: PXRestrictor is used with a where clause to specify how to restrict.
[PXRestrictor(typeof(
    Where<Current<InventoryItem.itemClassID>, Equal<itemClassValue>>
    ), "Custom Items")]

In the example above, itemClassValue must be a type of the classID.
You can Merge with current attributes on the field where the selector is defined as a DAC extension if it needs to exist everywhere or with CacheAttached if only within a specific graph.
Update
As you indicated that you need to allow an entire tree of item classes in the comments, you might try this approach which worked for me in a case where I needed to only allow certain values on a condition.
Add a PXInt field onto SOLine for your BASE item class.  Use the RowSelecting event to set it, and then use it in your restrictor.
Sample Base Item Class ID field:
#region BaseItemClassID
[PXInt]
public virtual int? BaseItemClassID { get; set; }
public abstract class baseItemClassID : PX.Data.BQL.BqlInt.Field<baseItemClassID> { }
#endregion

Restrictor to use in CacheAttached to limit to only items of your base item class:
[PXRestrictor(typeof(Where<InventoryItem.baseItemClassID, Equal<myBaseItemClassType>>), "")]

If this is applied to all SOLine records, you will need to add your "when to allow only my specific item class tree" to the restrictor.  Remember that the restrictor must return True to give results, so it might need to be "Where NOT my condition OR BaseItemClassID == myBaseItemClassID".
In my case, I needed a simple condition to allow using standard locations where I have some locations configured as special use for segregating certain inventory.  I just set a PXBool field to true when I want to allow use of standard locations, and the restrictor flips the allowed selection.  I think this concept might work in your case as well as outlined above.
Comment: Right, I understand, but if I can't do a join, ``itemClassCD`` is not available, and ``itemClassID`` expects an ``int``.  I'm trying to match against a ``StartsWith`` function of some sort because I have a bunch of segmented classes that start the same way and should all be excluded.  Probably should've specified that.
Comment: I think  you are making it too complicated.  If you know the ItemClassCD, then you know the ItemClassID.  The Equal must be either a type of a constant containing the value or a Current to retrieve it from somewhere.  The selector should for InventoryID should be looking up to InventoryItem already, so you are restricting to itemClassID on InventoryItem rather than SOLine.  If you need it to be variable, you could make a view for INItemClass and instead of itemClassValue as a constant, you can use Current of INItemClass.itemClassID.
Comment: You may be right.  I managed to get this working for a single (1) item class.  However, this still doesn't solve my issue of also wanting to include all child-item classes.  Do you have a solution for that?
Comment: That certainly is a bit more complicated.  I'm not sure how I would approach that.  I have been working all afternoon on getting a set of PXRestrictor attributes to limit a location list based on different conditions and noticed the syntax issue of your original post.
Comment: Would it be possible to check against an array of ``ItemClassID`` or something?
Comment: Not sure.  I have yet to need to get super sophisticated with PXRestrictor.  What I have seen in source code is that the complex issues tend to be written in their own attributes where BQL is employed to further adjust the results.
Comment: You CAN do a lot of OR's in the Where clause if your list is finite.
Comment: I tried to replicate their attribute extensions, but it always complains that I must define a body because it's not marked as abstract or extern.  I feel like I must be missing something.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/223785/discussion-between-brian-stevens-and-deetz).
Comment: Found a possible solution to your additional need.  Updating answer.
Comment: Now that is creative thinking.


Rails - best practice to store dictionaries (key value pairs)

Question: I need some architectural advice. I'm more into java, but trying to get up to speed with Ruby-on-rails. In the app I am building I need a convenient place to store some dictionary values that will be later used in various places of the application. These will be usually key value pairs - e.g. list of values to be used in select list.
The main objective is to keep this logic in one place of the application.
I am considering following options:

Store values in the database - i'm kind of reluctant from that, as values won't change very often.
Put all of the values in one class. In JAVA I'd have some static properties in one class holding this values (e.g. call Utils.getStates() will return list of states). How to do it ruby way?
Have some .yml file with values - read from the values. How to do it? I guess I have to parse the file in the initializer, but is there any tutorial how to do it?

Precise example? Let's say that have a model that have a field called "Type". Type can be: ['Type A', 'Type B', 'Type C'...]. And of course, for each type I want to have key and value.
I'd appreciate some suggestions about how you solve this problem in your apps.
Thanks,
Maciek
Answer: How often does the list change? Is it acceptable to have developers involved each time a value changes (updating code, re-deploying the app)? If the answer is no then store the values in a database.
Is the list of values reuseable? Then a gem or a yaml file with an initializer might be a good choice.
Is it just a small list and does not change often? Then you might want to consider a constant.
Answer: I think in Rails any data that would change at runtime and needs to be persisted, would normally be stored in the database.  I think that would be the "rails way".  You could save the data to yaml or json file, but that would not follow the normal flow of the MVC pattern that is so common in rails


Lambda expression without declaration?

Question: An example for Lambda expressions from MSDN
delegate int del(int i);
static void Main(string[] args)
{
    del myDelegate = x => x * x;
    int j = myDelegate(5); //j = 25
}

Is it possible to do the same, without declaring the delegate?
Well since I think declaring is not the right word, I'll write the code as I would like to do it
static void Main(string[] args)
{
    del myDelegate = x => x * x;
    int j = myDelegate(5); //j = 25
}

Why do I want to do that?
I want to reduce complex if conditions into a single expression. But I don't want to bloat my class or add some kind of helper class / whatever since it won't be used in another scope.
Comment: See http://stackoverflow.com/a/6818709/3199781
Answer:
Is it possible to do the same, without declaring the delegate?

No, it's not possible to create a lambda expression without first declaring a type. Delegates are like any other object in C#: it must have a well-defined type before you can assign it a value.
However, you may not need to declare the types yourself, because Microsoft has declared a ton of them for you. If one of the predefined delegate types works for you, feel free to use those.
For example, if you have a delegate that takes anywhere from 0 through 16 parameters, you can use one of the Action delegate types:
Action x = () => DoStuff();
Action<int> x = i => DoStuff(i);
Action<string, string, string> = (a,b,c) => DoStuff(a,b,c);

If you need to return a value, you can use one of the Func delegate types:
Func<int> x = () => 6;
Func<int, int> x = i => i * i;
Func<string, string, string, string> x = (a,b,c) => a.Replace(b, c);

etc.
There are tons more of them: every control event in Windows Forms or WPF uses a pre-defined delegate type, usually of EventHandler or RoutedEventHandler or some derivate. There are specialized version of Func such as Predicate (though those largely pre-date LINQ and are mostly obsolete).
But, if for some odd reason none of the built-in delegate types works for you, then yes, you need to define your own before you can use it.
Comment: Well - excellent answer. Thanks for your explanation. Unfortunately I just can give a single +1 ;)
Answer: You're looking for the Func<*> delegates:
Func<int, int> myDelegate = ...;

Lambda expression without declaration?


How to gotTo specific page using ngx-bootstrap pagination

Question: I have a query where I need to implement: How to gotTo a specific page using
ngx- bootstrap pagination by entering the page number to some input field.
Here is the following code snippet :
***Template:***

{{content}}

    <pagination [totalItems]="contentArray.length" (pageChanged)="pageChanged($event)"></pagination>

**.ts file**
import { Component, OnInit } from '@angular/core';
import { PageChangedEvent } from 'ngx-bootstrap/pagination';

@Component({
    // eslint-disable-next-line @angular-eslint/component-selector
    selector: 'demo-pagination-content-switching',
    templateUrl: './content-switching.html',
    styles: [`
.content-wrapper {
border: 1px solid #ddd;
border-radius: 4px;
padding-left: 10px;
margin-bottom: 10px;
}
`]
})
export class DemoPaginationContentSwitchingComponent implements OnInit {
    contentArray = new Array(90).fill('');
    returnedArray?: string[];

    ngOnInit(): void {
        this.contentArray = this.contentArray.map((v: string, i: number) => `Content line ${i + 1}`);
        this.returnedArray = this.contentArray.slice(0, 10);
    }

    pageChanged(event: PageChangedEvent): void {
        const startItem = (event.page - 1) * event.itemsPerPage;
        const endItem = event.page * event.itemsPerPage;
        this.returnedArray = this.contentArray.slice(startItem, endItem);
    }
}

Any help is appreciated!!
Thanks in advance
Answer: According to the documentation; you can bind pagination with [(ngModel)] to keep it synced with a particular instance member.
In your DemoPaginationContentSwitchingComponent declare a variable currentPage and bind it with Angular Bootstraps's pagination component like this
<pagination [totalItems]="contentArray.length (pageChanged)="pageChanged($event)" [(ngModel)]="currentPage"></pagination>

Now add the input you want to control the pagination with, you can either listen to (changed) event of this input and set the currentPage value accordingly, or simply add a button to do that.
Either way, you need to validate this input in order to avoid errors coming from the pagination component.


Find the probability distribution, knowing the conditional probability distribution.

Question: I have been working on some physics problem that I 'translated' into the following mathematical problem for which I need help to solve.

Suppose that $ \alpha $ is a random variable uniformly distributed on the interval $ [0,2 \pi] $. Then for each random (there are technicalities here) subset $ A $ of $ [0,2 \pi] $, we have
$$
\textbf{Pr}(\alpha \in A \mid \lambda(A) = x) = \frac{x}{2 \pi},
$$
where $ \lambda $ denotes the Lebesgue measure on $ [0,2 \pi] $.
Further suppose that we can randomly choose random subsets of $ [0,2 \pi] $ so that
$$
\{
A \mid
\text{$ A $ is a random subset of $ [0,2 \pi] $ and $ \lambda(A) \in [a,b] $}
\}
$$
is a random event for $ 0 \leq a \leq b \leq 2 \pi $ and that the random variable $ X $ defined by
$$
X \stackrel{\text{df}}{=}
\left\{ \begin{matrix}
\text{Random subsets of $ [0,2 \pi] $} & \to     & [0,2 \pi] \\
A                                      & \mapsto & \lambda(A)
\end{matrix} \right\}
$$
has a probability density function $ p $. Then I thought:
$$
  \textbf{Pr}(\alpha \in A)
= \int_{0}^{2 \pi} \frac{x}{2 \pi} \cdot p(x) ~ \mathrm{d}{x}.
$$

Now follow some questions that I have:

Is the above formula actually correct?
Is it possible to randomly 'choose' a random subset of $ [0,2 \pi] $ (or any other interval)?
Answer: The second question is tantamount to asking if there exist a $ \sigma $-algebra $ \Sigma $ on the Borel $ \sigma $-algebra $ \mathscr{B}([0,2 \pi]) $ on $ [0,2 \pi] $ itself and a probability measure $ \mu: \Sigma \to [0,1] $ such that
$$
\forall x \in [0,2 \pi]: \quad
\{ A \in \mathscr{B}([0,2 \pi]) \mid \lambda(A) = x \} \in \Sigma,
$$
and the function $ p: [0,2 \pi] \to [0,1] $ defined by
$$
\forall x \in [0,2 \pi]: \quad
p(x) \stackrel{\text{df}}{=}
\mu(\{ A \in \mathscr{B}([0,2 \pi]) \mid \lambda(A) = x \})
$$
is a Lebesgue-integrable function with mass $ 1 $, i.e., $ \displaystyle \| p \|_{1} \stackrel{\text{df}}{=} \int_{[0,2 \pi]} p ~ \mathrm{d}{\lambda} = 1 $.
The answer is 'no'. By way of contradiction, assume that $ \Sigma $ and $ \mu $ exist with the properties listed above. Observe that the sets
$$
\{ A \in \mathscr{B}([0,2 \pi]) \mid \lambda(A) = x \}, \quad x \in [0,2 \pi]
$$
are disjoint. As $ \| p \|_{1} = 1 $, we obviously have $ p(x) > 0 $ for uncountably many $ x \in [0,2 \pi] $. By the Infinite Pigeonhole Principle, there exist (i) an $ \epsilon > 0 $ and (ii) an uncountable subset $ S $ of $ [0,2 \pi] $ such that $ p(x) > \epsilon $ for every $ x \in S $. Let $ C \subsetneq S $ be countably infinite. Then by the $ \sigma $-additivity of $ \mu $, we have
\begin{align}
    \mu(\{ A \in \mathscr{B}([0,2 \pi]) \mid \lambda(A) \in C \})
& = \mu \!
    \left(
    \bigcup_{x \in C} \{ A \in \mathscr{B}([0,2 \pi]) \mid \lambda(A) = x \}
    \right) \\
& = \sum_{x \in C} \mu(\{ A \in \mathscr{B}([0,2 \pi]) \mid \lambda(A) = x \}) \\
& = \sum_{x \in C} p(x) \\
& > \sum_{x \in C} \epsilon \\
& = \infty.
\end{align}
This contradicts the assumption that $ \mu $ is a probability measure.
This automatically renders the first question meaningless.
Comment: Thank you very much, this helps me alot!
Comment: @Badshah: You're most welcome, my friend! I've read the questions that you've asked here on Math Stack Exchange, and all of them are very interesting.


Difference between "printf" and "print sprintf"

Question: The following two simple perl programs have different behaviors:
#file1
printf @ARGV;

#file2
$tmp = sprintf @ARGV;
print $tmp;

$> perl file1  "hi %04d %.2f" 5  7.12345
   #output:  hi 0005 7.12

$> perl file2 "hi %04d %.2f" 5  7.12345
   #output:  3

Why is the difference?  I had thought the two programs are equivalent.  Wonder if there is a way to make file2 (using "sprintf") to behave like file1.
Answer: The builtin sprintf function has a prototype:
$ perl -e 'print prototype("CORE::sprintf")'
$@

It treats the first argument as a scalar. Since you provided the argument @ARGV, it was coerced into a scalar by passing the number of elements in @ARGV instead.
Since the printf function has to support the syntax printf HANDLE TEMPLATE,LIST as well as printf TEMPLATE,LIST, it cannot support a prototype. So it always treats its arguments as a flat list, and uses the first element in the list as the template.
One way to make it the second script work correctly would be to call it like
$tmp = sprintf shift @ARGV, @ARGV

Another difference between printf and sprintf is that print sprintf appends $\ to the output, while printf does not (thanks, ysth).
Comment: Or `sprintf $ARGV[0], @ARGV[1..$#ARGV]`
Comment: Or `$tmp = &CORE::sprintf(@ARGV);` if you don't want to modify `@ARGV`
Answer: @ARGV contains the arguments passed to the script in list form. printf takes that list and prints it out as is.
In second example you are using sprintf with the array and assigning it to scalar. Which basically means it stores the length of the array in your variable $tmp. Hence you get 3 as output.
Answer: From the perl docs (jaypal said it already)
Unlike printf, sprintf does not do what you probably mean when you pass it an array as your first argument. The array is given scalar context, and instead of using the 0th element of the array as the format, Perl will use the count of elements in the array as the format, which is almost never useful.


How to import excel and/or pkl files onto iPad pro Juno app?

Question: I'm learning to code Python on iPad. I'm using Juno. I was wondering if there's any way to import excel and pickle files onto Juno so that I can do real data analysis on iPad without having to switch to a computer.
Answer: Sure, you can. The only restriction of iOS is that Juno can access only its own folder on the iPad. So you have to save the excel or csv file inside iPad's own Juno folder (I usually make a subfolder for each project) and then you can normally import the Excel sheet with
<code>import numpy as np
import pandas as pd
df = pd.read_excel(r'yourfile.xlsx')
</code>


How to predict the response variable of a speedlm model in R?

Question: I have just started using the speedglm package. I fitted a very simple model and tried to predict the response variable (yhat).
library(speedglm)

data<-data.table(x=1:10, y=5:14)

model<-speedlm(y~x, data=data)

In contrast to the lm function I cannot use the predict(model) to get the yhat. Is there any respective routine I can use for the speedglm package?
Answer: As far as I can see there is no predict method. You sacrifice convenience for speed. However, it's quite easy to calculate the yhat values:
data[, yhat := c(cbind(1, x) %*% coef(model))]
#     x  y yhat
# 1:  1  5    5
# 2:  2  6    6
# 3:  3  7    7
# 4:  4  8    8
# 5:  5  9    9
# 6:  6 10   10
# 7:  7 11   11
# 8:  8 12   12
# 9:  9 13   13
#10: 10 14   14

Comment: Thank you very much for your instant response. You are absolutely right..convenience for speed! speedlm helped me drop the modelling time from one hour to 5 minutes keeping the exact coefficient estimates. Regards, Konstantinos