4 wire electric supply into 3 wires oven outlet

Question: We've got a new oven which shows a diagram requiring 3 wires for our wanted configuration.
The old oven however is supplied with a 4 wire cable.
The Old oven has each wire marked as follows:
green wire - Earth
red - PH1
white - PH2
blue - N
Is it ok to just cut plus tape the white wire and only connect up the red. Or does it need to be connected somehow?

Edit:

2 different configurations are shown.
Left side: 380v ac 3ph
Right side: 230v ac 1ph
We're not supplied with 380v so we can only do the right side configuration.
Am I missing something here?
The model of the new oven is 310100, it has no information in its manual regarding the electrical configuration other than to follow the panel. No extra parts came with the oven.
I'm unsure of what those little brackets mean on the diagram.
Edit 2:
The new oven supports single phase or a 3 phase connections.
As Simon B and Ecnerwal pointed out the brackets show that a single wire needs to be linked through the points 1 to 3 when doing a single phase connection.
The question still is, what should I do with the white PH2 wire.
Edit 3:
Got an electrician to do it. The jumpers were actually supplied. The electrician connected both the red and white wires and only used 2 of the brass jumpers.
Comment: @crip but converting from a multiphase feed to a single-phase feed requires revisiting the size of the *neutral* wire.  In a multiphase feed, neutral only carries differential current.  In single-phase it carries the whole shebang.
Comment: Where it would be really helpful to get some local input would be the question of "if you really have two phases available, might you want to jumper only 1&2 or 2&3, and connect both live phases, if you have 2 of 3 phases (but not all 3) available for whatever reason - but that **really** cries out for local knowledge of what you have there, not random experiments.
Comment: I'm in NZ. The wiring from the old oven goes into a 32A socket which has 4 pins. The new oven has a panel to wire a plug into(as shown above). We're trying to use the plug from the old oven for the new one.
Comment: If you get an answer that leaves one wire not used, would prefer a wire nut or local solid wire connector instead of just tape.
Comment: What is the model number of the oven in question?  "3 wires *for our wanted* configuration" - that is not a thing you should be "wanting", you should let the wiring in your walls tell you which configuration to use. Does the oven have instructions for 4-wire connection?  I expect it does.
Comment: The "little brackets" should have been supplied - they are to connect the 3 separate phases together when doing single-phase, and the two neutral connections together in both cases, apparently. "Shorting Jumpers" or similar terminology. Neutral needs to connect to 4 and 5, and live needs to connect to 1, 2, & 3. Ground to 6.
Comment: I'm glad you got this working. Bear in mind that a _model number_ without knowing the _manufacturer's name_ isn't really all that helpful. For future reference...
Answer: You need to check if one phase of your supply is enough to power the whole oven.  If it is, then leave the spare phase safely disconnected (in a way that won't let it come into contact with anything), and wire it like in that diagram.
If not, check to see if they provide other diagrams.  The use of three terminals marked 1, 2 and 3 strongly hints that the oven was also designed to run on a 3-phase supply.
Edit: I assume by "little brackets" you mean the brass jumpers that should have been supplied with the oven. If so, fit them as shown in the diagram.
Comment: Yes, theoretically, one phase would give 240v, but at what amperage? You also have to wonder why the property was supplied with 3-phase in the first place. I read up on NZ electrics & it appears very similar to UK. Domestic properties only receive single phase 240v… unless they're in outlying regions with potential power issues, in which case they get 415v 3-phase. I'd still be inclined to ask a local sparky about this before making assumptions.
Comment: I'm in a NZ subsurb some of our our neighbours have 3 phase, one to power his lathe, and large workshop machinery. another to power fixed appliances like heating. (I watched as powerco blocked my driveway while they replaced their feed which was damaged possibly as a result of an earthquake.
Comment: The new oven supports a 3 phase connection as well as single live wire connection. We are only supplied with a 240v connection. We tried to wire it like shown in the diagram(connected just the red,blue and green wires and taped the white wire) and the oven would not turn on.
Comment: No none were supplied, we'll get those 3 jumpers and then try with just the phase 1 wire. If it doesn't work does that mean that the oven doesn't support this 4 wire plug.


Unique items in a list and put (-) on the removed one -- Python Pandas

Question: I have the following list.
my_list = ['20/20',  '30/30',  '20/80',  '120/120',  '120/140',  '165/165', '30/170',  '165/175']

I would like to remove any duplication and would like to keep unique items on the list, keep track of them by converting the dictionary, and put (-/ or /-) on the removed duplicate items.
For example, 20/20 should change to 20 and put in the dictionary as {'20/20':20/-}, for '30/30' change to 30 and put it in the dictionary as {'30/30': 30/-}, BUT for '20/80' it shouldn't be 20 because I have 20 in a dictionary before so it should be 80 and put it in the dictionary as {'20/80':-/80}. The same procedure works for the rest of lists.
My expected result seems like the following dictionary.
my_dict = {'20/20':20/-, '30/30': 30/-,  '20/80':-/80,  '120/120':120/-, '120/140':-/140,  '165/165': 165/-,  '30/170': -/170,  '165/175':-/175}

I have this implementation but couldn't put -/ or /-.
my_dict1 = dict((elem, elem.split('/')[0]) for elem in my_list)

my_dict2 = dict((elem, elem.split('/')[1]) for elem in my_list)

Can anyone help with this?
Comment: I dont see any relevance for the [tag:pandas] tag ... why add it?
Answer: I have the expected output using the following codes:
my_list = ['20/20',  '30/30',  '20/80',  '120/120',  '120/140',  '165/165', '30/170',  '165/175']

my_dict1={}
mark={}
for data in my_list:
    x,y=data.split('/')
    #print(x,y)
    if(x==y):
        mark[x]=1
        my_dict1[data]=x+"/-"
    else:
        if(x in mark):
            my_dict1[data]="/-"+y
            mark[y]=1
        elif(y in mark):
            my_dict1[data]=x+"/-"
            mark[x]=1

print(my_dict1)

Answer: my_list = ['20/20',  '30/30',  '20/80',  '120/120',  '120/140',  '165/165', '30/170',  '165/175']
my_new_dict = {}
for i in my_list:
    temp = i.split('/')
    if((temp[0] > temp[1]) | (temp[0] == temp[1])):
        my_new_dict[i] = str(temp[0])+'/-'
    elif(temp[1] > temp[0]):
        my_new_dict[i] = '-/'+str(temp[1])

print(my_new_dict)

Answer: You can use a set to keep track of which element you already encountered, and replace them with a -, like this:
EDIT: using or trick to add elems to set within a single expression (lambda), and 2 helper lambdas to solve with a single dict comprehension:
my_list = ['20/20',  '30/30',  '20/80',  '120/120',  '120/140',  '165/165', '30/170',  '165/175']

used = set() # empty set
process_num = lambda num: '-' if num in used or used.add(num) else num
process_elem = lambda pair: '/'.join(map(process_num, pair.split('/')))
my_dict = {elem: process_elem(elem) for elem in my_list}

print(my_dict)

Output:
{'20/20': '20/-', '30/30': '30/-', '20/80': '-/80', '120/120': '120/-', '120/140': '-/140', '165/165': '165/-', '30/170': '-/170', '165/175': '-/175'}

Answer: This delivers the wanted result, although it gets slower the more elements you add:
my_list = ['20/20',  '30/30',  '20/80',  '120/120',  '120/140',  '165/165', '30/170',  '165/175']

d = {}
for item in my_list:
    key1, key2 = item.split("/")
    # quits searching as soon as the first key is found
    ks = any( k for k in d.keys() if k.startswith(f"{key1}/"))
    v = f"{key1}/-" if not ks else f"-/{key2}"
    d[item] = v

print(d)

Output:
{'20/20': '20/-', '30/30': '30/-', '20/80': '-/80',
 '120/120': '120/-', '120/140': '-/140', '165/165': '165/-',
 '30/170': '-/170', '165/175': '-/175'}


PHP use keyword is causing 500 server error

Question: I'm trying to implement PhpPresentation to convert some files, so I have the following code:
use PhpOffice\PhpPresentation\src\PhpPresentation\PhpPresentation;
use PhpOffice\PhpPresentation\src\PhpPresentation\IOFactory;
use PhpOffice\PhpPresentation\src\PhpPresentation\Style\Color;
use PhpOffice\PhpPresentation\src\PhpPresentation\Style\Alignment;

For some reason exactly this piece of code is causing 500 Internal server error. I have error reporting set to all, but no errors are shown. The path is right, i have the PhpOffice folder in my root directory(public_html) and the corresponding subfolders too.
autoloader code is loaded this way:
require_once 'PhpOffice/PhpPresentation/src/PhpPresentation/Autoloader.php';
  \PhpOffice\PhpPresentation\Autoloader::register();
  require_once 'PhpOffice/src/Common/Autoloader.php';
  \PhpOffice\Common\Autoloader::register();

Comment: Ok, that means most likely your php version is outdated and below `5.6`. You want to upgrade.
Comment: Take a look into your http servers error log file, that is where you can read what the actual issue is.
Comment: Most likely those definitions cannot be found by your auto loader.
Comment: `syntax error, unexpected 'use'` on the first use line. Here is my full function https://codeshare.io/aYAdzL
Comment: a few ideas: are there any lines before the `use` lines? maybe one with a missing `;`? and just to be sure...what is your PHP version?
Comment: I'm not missing a semicolumn and my PHP version is 5.6. The full error is `syntax error, unexpected 'use' (T_USE)`
Answer: Issue fixed, thanks to this https://stackoverflow.com/a/33355711/7926703
I was using 'use' inside a function which is wrong and error-causing.


3D Touch Application Shortcut Sorting

Question: I implemented 3D touch application shortcuts via the info.plist (static entries) and then the code implementation, all works fine.  However, I cannot seem to get the sort of the shortcuts to persist.  I tried drag/drop in Xcode 7.1 to reorder them and initially it looked fine but now again they are sorted opposite.
How are application shortcuts sorted? If any?
I'm using an iPhone 6S with iOS 9.1.
Answer: The order is plist order.  What threw me off is whether the menu opens up or down depending on where your application icon exists.  It will order in plist order starting from the application icon and then outwards from there.

3D Touch Application Shortcut Sorting


Using plotly express to show image and plot with animation

Question: I need some help making an animation with plotly express where each frame will include an image and a graph (preferably a plotly express graph) side by side. My goal is to have the animation be corresponding to time steps from each frame. Plotly express has an example of this with just images shown in the link below. But I do not know how to make a plotly express graph take the place of one of the images in the example.
The link below will lead you to the plotly express example for "Combining animations and facets"
Link to plotly for specific example: 'Combining animations and facets' (https://plotly.com/python/imshow/)
'''
from skimage import data, io
import plotly.express as px
data = io.imread("https://github.com/scikit-image/skimage-tutorials/raw/main/images/cells.tif")
data = data.reshape((15, 4, 256, 256))[5:]
fig = px.imshow(data, animation_frame=0, facet_col=1, binary_string=True)
fig.show()

'''
Update:
So I can make side my side plots with images but I'm having a difficult time with animating it. Below is my current code:
'''
imgR=np.random.rand(360,1000)
imgR2=np.random.rand(360,1000)

fig = make_subplots(rows=1, cols=2)

fig.add_trace(
    go.Scatter(x=[1, 2, 3,4,5], y=[4, 5, 6,7,8]),
    row=1, col=1
)

fig.add_trace(
    px.imshow(imgR).data[0],
    row=1, col=2
)
frames=[go.Frame(data=[go.Scatter(x=[3,5,2,5,3],y=[3,4,5,3,3]),px.imshow(imgR2).data[0]],traces=[0,1])]

fig.frames=frames

button = dict(
             label='Play',
             method='animate',
             args=[None, dict(frame=dict(duration=50, redraw=False),
                              transition=dict(duration=0),
                              fromcurrent=True,
                              mode='immediate')])

fig.update_layout(updatemenus=[dict(type='buttons',
                              showactive=False,
                              y=0,
                              x=1.05,
                              xanchor='left',
                              yanchor='bottom',
                              buttons=[button] )
                                      ],
                 width=800, height=500)
fig.update_layout(height=600, width=800, title_text="Side By Side Subplots")

fig.show()

'''
Any help will be appreciated.
Answer: There are a number of things you need to be systematic with

make sure each frame has a name
make sure each trace is using correct axes
build sliders from list of frames

from plotly.subplots import make_subplots
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
import numpy as np

imgR = np.random.rand(20, 40)

fig = make_subplots(rows=1, cols=2)
x = [1, 2, 3, 4, 5]
y = [4, 5, 6, 7, 8]

fig.add_trace(go.Scatter(x=[1, 2, 3, 4, 5], y=[4, 5, 6, 7, 8]), row=1, col=1)
fig.add_trace(px.imshow(imgR).data[0], row=1, col=2)

frames = []
for i in range(5):
    if i > 0:
        np.random.shuffle(x)
        np.random.shuffle(y)
    # need to name the frame for slider, plus make sure both traces are using
    # correct axes
    frames.append(
        go.Frame(
            name=str(i),
            data=[
                go.Scatter(x=x, y=y),
                px.imshow(np.random.rand(20, 40) if i > 0 else imgR)
                .update_traces(xaxis="x2", yaxis="y2")
                .data[0],
            ],
        )
    )

# now have all parts to puild figure
figa = go.Figure(data=fig.data, frames=frames, layout=fig.layout)

# add slider
figa.update_layout(
    sliders=[
        {
            "active": 0,
            "currentvalue": {"prefix": "animation_frame="},
            "len": 0.9,
            "steps": [
                {
                    "args": [
                        [fr.name],
                        {
                            "frame": {"duration": 0, "redraw": True},
                            "mode": "immediate",
                            "fromcurrent": True,
                        },
                    ],
                    "label": fr.name,
                    "method": "animate",
                }
                for fr in figa.frames
            ],
        }
    ],
)

Comment: Thank you! this helps. I'm also trying to do another variation of this analysis with animations but I would like the functionality of turning the particular trace on or off in the legend. Do you have any insight on this? The link to that question is here: https://stackoverflow.com/questions/71426516/how-to-add-legend-for-picture


How do I reset the map of my minecraft server?

Question: The map on my minecraft server has gotten really griefed and I would like to know how to reset it.
Answer: Recreate the map with the same seed:

Type /seed on your console after hitting T
If you are on single player, just feed the seed on the box:

If multiplayer(your case) and using the vanilla server, on your server.properties file add the following parameter on a newline: level-seed=yourseedhere


My mouse / keyboard response gets delayed if I don't use it all the time.

Question: Occasionally my mouse / keyboard would take extra long to respond to input. If I moved the mouse or pressed a key it would take an extra second to respond the work normally.
If I leave it alone for a period of time the it happens again.
In the dmesg log I see entries like this
dmesg | tail

ehci_hcd 0000:00:1d.0: PCI INT A disabled
ehci_hcd 0000:00:1d.0: PME# enabled
ehci_hcd 0000:00:1d.0: BAR 0: set to [mem 0xd9105800-0xd9105bff] (PCI address [0xd9105800-0xd9105bff])
ehci_hcd 0000:00:1d.0: restoring config space at offset 0xf (was 0x100, writing 0x10b)
ehci_hcd 0000:00:1d.0: restoring config space at offset 0x1 (was 0x2900000, writing   0x2900002)
ehci_hcd 0000:00:1d.0: PME# disabled
ehci_hcd 0000:00:1d.0: PCI INT A -> GSI 21 (level, low) -> IRQ 21
ehci_hcd 0000:00:1d.0: setting latency timer to 64

I found out which device it is but still don't know what is actually causing the issue. I know it has some thing to do with the usb controller.
lspci -n | grep 00:1d.0
00:1d.0 0c03: 8086:3b34 (rev 05)

lspci -d 8086:3b34
00:1d.0 USB controller: Intel Corporation 5 Series/3400 Series Chipset USB2 Enhanced Host Controller (rev 05)

UPDATE

After a bit of investigation I believe it has some thing to do with power management, power saving or auto suspend of the device.
Answer: After quite a bit of googling I remembered I has installed powernap.
sudo powernap-action -l

[disabled] 01cpu_online         - sh: 1: /etc/pm/power.d/01cpu_online: Permission denied
[enabled]  00flag               -
[disabled] usb                  - sh: 1: /etc/pm/power.d/usb: Permission denied
[disabled] video                - sh: 1: /etc/pm/power.d/video: Permission denied
[disabled] eth_speed            - sh: 1: /etc/pm/power.d/eth_speed: Permission denied
[enabled]  usb_autosuspend      - Auto suspend USB bus to save power.
[enabled]  cpu_frequency        - Lowers the CPU frequency, changing the scaling governor from ondemand to powersave.
[disabled] kms_powermode        - sh: 1: /etc/pm/power.d/kms_powermode: Permission denied

One of the options I had enabled was
[enabled]  usb_autosuspend      - Auto suspend USB bus to save power.

So I fixed the issue by disabling usb_autosuspend.
sudo powernap-action --disable usb_autosuspend

So Now
[disabled] usb_autosuspend      - sh: 1: /etc/pm/power.d/usb_autosuspend: Permission denied


best jQuery Swipe to slide for touch screen devices

Question: I've been looking around the net and on this board for a really good jQuery version of the Swipe to horizontal scroll like apple has on their website, http://www.apple.com/ipad/ios
If you view the website on an iPad (I think other touch devices will work the same also) their swipe gallery works beautifully (under the section The worlds largest collection of mobile apps on apples site)
Everywhere I've seen so far doesn't seem to support a gallery with such fluidity, can anyone suggest a jQuery plugin or code?  I've been having lots of difficulty finding a jQuery plugin since they pulled that part of their website offline.
Answer: Best one I've used:
http://www.photoswipe.com/
EDIT: you can test it on this site: http://islastudio.com/mobile/photos
Comment: Thanks for this however it doesn't seem to be able to support the swipe across gallery like on Apple's site. I have a horizontal gallery bar in the middle of the page just like on Apple's site but I'm using jQuery on the rest of my page and the js libraries is just no compatible on the same page as jQuery so I must use a jQuery library which can do the same thing.  If you know any other, please let me know :D
Answer: http://www.woothemes.com/flexslider/
Flexslider is an awesome, fully responsive jQuery slider toolkit. Features include:

Hardware accelerated touch swipe support
Simple, semantic markup
Supported in all major browsers
Horizontal/vertical slide and fade animations
Multiple slider support, Callback API, and more
Custom navigation options
Compatible with the latest version of jQuery

With it, you can recreate Apple's iPad page, and much much more. And it's rather simple to set up.


Problem with script substitution when running script

Question: I'm new to Linux so this probably should be an easy fix, but I cannot see it.
I have a script downloaded from official sources that is used to install additional tools for fsharp but it gives me a syntax error when running it.
I tried to replace ( and ) by { and } but eventually it lead me to another error so I think this is not the problem since the script works for everybody. I read some articles that say that my bash version maybe is not the right one.
I'm using Ubuntu 10.10 and here is the error:

install-bonus.sh: 28: Syntax error: "(" unexpected (expecting "}")

And this is line 27, 28 and 29:

{
  declare -a DIRS=("${!3}")
  FILE=$2

And the full script:

#! /bin/sh -e

PREFIX=/usr
BIN=$PREFIX/bin
MAN=$PREFIX/share/man/man1/

die()
{
    echo "$1" >&2
    echo "Installation aborted." >&2
    exit 1
}

echo "This script will install additional material for F# including"
echo "man pages, fsharpc and fsharpi scripts and Gtk# support for F#"
echo "Interactive (root access needed)"
echo ""

# ------------------------------------------------------------------------------
# Utility function that searches specified directories for a specified file
# and if the file is not found, it asks user to provide a directory

RESULT=""

searchpaths()
{
  declare -a DIRS=("${!3}")
  FILE=$2
  DIR=${DIRS[0]}
  for TRYDIR in ${DIRS[@]}
  do
    if [ -f $TRYDIR/$FILE ]
    then
      DIR=$TRYDIR
    fi
  done

  while [ ! -f $DIR/$FILE ]
  do
    echo "File '$FILE' was not found in any of ${DIRS[@]}. Please enter $1 installation directory:"
    read DIR
  done
  RESULT=$DIR
}

# ------------------------------------------------------------------------------
# Locate F# installation directory - this is needed, because we want to
# add environment variable with it, generate 'fsharpc' and 'fsharpi' and also
# copy load-gtk.fsx to that directory
# ------------------------------------------------------------------------------

PATHS=( $1 /usr/lib/fsharp /usr/lib/shared/fsharp )
searchpaths "F# installation" FSharp.Core.dll PATHS[@]
FSHARPDIR=$RESULT
echo "Successfully found F# installation directory."

# ------------------------------------------------------------------------------
# Check that we have everything we need
# ------------------------------------------------------------------------------

[ $(id -u) -eq 0 ] || die "Please run the script as root."
which mono > /dev/null || die "mono not found in PATH."

# ------------------------------------------------------------------------------
# Make sure that all additional assemblies are in GAC
# ------------------------------------------------------------------------------

echo "Installing additional F# assemblies to the GAC"
gacutil -i $FSHARPDIR/FSharp.Build.dll
gacutil -i $FSHARPDIR/FSharp.Compiler.dll
gacutil -i $FSHARPDIR/FSharp.Compiler.Interactive.Settings.dll
gacutil -i $FSHARPDIR/FSharp.Compiler.Server.Shared.dll

# ------------------------------------------------------------------------------
# Install additional files
# ------------------------------------------------------------------------------

# Install man pages

echo "Installing additional F# commands, scripts and man pages"
mkdir -p $MAN
cp *.1 $MAN

# Export the FSHARP_COMPILER_BIN environment variable

if [[ ! "$OSTYPE" =~ "darwin" ]]; then
  echo "export FSHARP_COMPILER_BIN=$FSHARPDIR" > fsharp.sh
  mv fsharp.sh /etc/profile.d/
fi

# Generate 'load-gtk.fsx' script for F# Interactive (ask user if we cannot find binaries)

PATHS=( /usr/lib/mono/gtk-sharp-2.0 /usr/lib/cli/gtk-sharp-2.0 /Library/Frameworks/Mono.framework/Versions/2.8/lib/mono/gtk-sharp-2.0 )
searchpaths "Gtk#" gtk-sharp.dll PATHS[@]
GTKDIR=$RESULT
echo "Successfully found Gtk# root directory."

PATHS=( /usr/lib/mono/gtk-sharp-2.0 /usr/lib/cli/glib-sharp-2.0 /Library/Frameworks/Mono.framework/Versions/2.8/lib/mono/gtk-sharp-2.0 )
searchpaths "Glib" glib-sharp.dll PATHS[@]
GLIBDIR=$RESULT
echo "Successfully found Glib# root directory."

PATHS=( /usr/lib/mono/gtk-sharp-2.0 /usr/lib/cli/atk-sharp-2.0 /Library/Frameworks/Mono.framework/Versions/2.8/lib/mono/gtk-sharp-2.0 )
searchpaths "Atk#" atk-sharp.dll PATHS[@]
ATKDIR=$RESULT
echo "Successfully found Atk# root directory."

PATHS=( /usr/lib/mono/gtk-sharp-2.0 /usr/lib/cli/gdk-sharp-2.0 /Library/Frameworks/Mono.framework/Versions/2.8/lib/mono/gtk-sharp-2.0 )
searchpaths "Gdk#" gdk-sharp.dll PATHS[@]
GDKDIR=$RESULT
echo "Successfully found Gdk# root directory."

cp bonus/load-gtk.fsx load-gtk1.fsx
sed "s,INSERTGTKPATH,$GTKDIR,g" load-gtk1.fsx > load-gtk2.fsx
sed "s,INSERTGDKPATH,$GDKDIR,g" load-gtk2.fsx > load-gtk3.fsx
sed "s,INSERTATKPATH,$ATKDIR,g" load-gtk3.fsx > load-gtk4.fsx
sed "s,INSERTGLIBPATH,$GLIBDIR,g" load-gtk4.fsx > load-gtk.fsx
rm load-gtk1.fsx
rm load-gtk2.fsx
rm load-gtk3.fsx
rm load-gtk4.fsx
mv load-gtk.fsx $FSHARPDIR/load-gtk.fsx

# Generate 'fsharpc' and 'fsharpi' scripts (using the F# path)
# 'fsharpi' automatically searches F# root directory (e.g. load-gtk)

echo "#!/bin/sh" > fsharpc
echo "exec mono $FSHARPDIR/fsc.exe --resident \"\$@\"" >> fsharpc
chmod 755 fsharpc

echo "#!/bin/sh" > fsharpi
echo "exec mono $FSHARPDIR/fsi.exe -I:\"$FSHARPDIR\" \"\$@\"" >> fsharpi
chmod 755 fsharpi

mv fsharpc $BIN/fsharpc
mv fsharpi $BIN/fsharpi

Thanks a lot!
Answer: Change the first line from
<code>#! /bin/sh -e
</code>
to
<code>#!/bin/bash -e
</code>
Comment: Wow! I ran it with "sudo bash install-bonus.sh" and it worked! Thanks! Why did it work?
Comment: The reason for this change is that Ubuntu uses dash as it default shell, not bash as expected by the script writer.
Comment: Still got the same error :(
Comment: @tucaz Well, Javier Rivera pointed out one reason. I guess maybe the other is that install-bonus.sh does not have execute permissions ( 'ls -la install-script.sh' )? So passing the script as an argument to BASH worked.


Can you play Portal 2 Coop with one Windows PC and one Mac?

Question: Is it possible to play coop with a windows computer and a Mac? Just wondering before I buy the game.
Comment: wha... _you haven't bought the game yet??_
Answer: Yes it is possible. It is even possible between a PC or Mac and a PS3.
Answer: It does work indeed. I have played several times on both ends. The only issues we were having were due to crowded servers from valve, as they host/initiate the coop session.


multiple types in Codable

Question: I'm using an API which can either return a Bool or a Int for one value depending on the item. I'm not familiar with how to handle different types for one value in my Codable data. The rated key can either be an object or bool, just unsure how to handle this correctly without getting a typeMismatch error. This is my first time encountering this using an API.
{"id":550,"favorite":false,"rated":{"value":9.0},"watchlist":false}

{"id":405,"favorite":false,"rated":false,"watchlist":false}

struct AccountState: Codable {
    let id: Int?
    let favorite: Bool?
    let watchlist: Bool?
    let rated: Rated?
}

struct Rated : Codable {
    let value : Int? // <-- Bool or Int
}

Comment: Check https://stackoverflow.com/questions/52681385/swift-codable-multiple-types
Comment: I would simply decode false as nil. Btw it should be Double not Int
Answer: I definitely agree with @vadian. What you have is an optional rating. IMO this is a perfect scenario for using a propertyWrapper. This would allow you to use this Rated type with any model without having to manually implement a custom encoder/decoder to each model:
@propertyWrapper
struct RatedDouble: Codable {

    var wrappedValue: Double?
    init(wrappedValue: Double?) {
        self.wrappedValue = wrappedValue
    }

    private struct Rated: Decodable {
        let value: Double
    }

    public init(from decoder: Decoder) throws {
        do {
            wrappedValue = try decoder.singleValueContainer().decode(Rated.self).value
        } catch DecodingError.typeMismatch {
            let bool = try decoder.singleValueContainer().decode(Bool.self)
            guard !bool else {
                throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Corrupted data"))
            }
            wrappedValue = nil
        }
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        guard let double = wrappedValue else {
            try container.encode(false)
            return
        }
        try container.encode(["value": double])
    }
}

Usage:
struct AccountState: Codable {
    let id: Int?
    let favorite: Bool?
    let watchlist: Bool?
    @RatedDouble var rated: Double?
}

let json1 = #"{"id":550,"favorite":false,"rated":{"value":9.0},"watchlist":false}"#
let json2 = #"{"id":550,"favorite":false,"rated":false,"watchlist":false}"#
do {
    let accountState1 = try JSONDecoder().decode(AccountState.self, from: Data(json1.utf8))
    print(accountState1.rated ?? "nil")  // "9.0\n"
    let accountState2 = try JSONDecoder().decode(AccountState.self, from: Data(json2.utf8))
    print(accountState2.rated ?? "nil")  // "nil\n"
    let encoded1 = try JSONEncoder().encode(accountState1)
    print(String(data: encoded1, encoding: .utf8) ?? "nil")
    let encoded2 = try JSONEncoder().encode(accountState2)
    print(String(data: encoded2, encoding: .utf8) ?? "nil")
} catch {
    print(error)
}

This would print:

9.0
nil
{"watchlist":false,"id":550,"favorite":false,"rated":{"value":9}}
{"watchlist":false,"id":550,"favorite":false,"rated":false}
Comment: @Cole  Just pass `rated: 0`. It is an optional Double. You can also pass `nil` (not rated). `@Published var state = AccountState(id: 0, favorite: false, watchlist: false, rated: 0)`
Comment: It's working and I don't get the type mismatch error! I can't thank you enough for the explanation, and help. It's definitely the most elegant solution. Accepting as answered :)
Comment: I'm just seeing how can my `Published` variable adapt to this change? I'm unsure of that aspect`@Published var state: AccountState = AccountState(id: 0, favorite: false, watchlist: false, rated: Rated(value: 0))`
Comment: I tried that but getting `Cannot convert value of type 'Int' to expected argument type 'RatedDouble'`
Comment: I have `@RatedDouble var rated: Double?` in my `AccountState` declaration
Comment: @Cole Check my last edit
Answer: My suggestion is to implement init(from decoder, declare rated as optional Double and decode a Dictionary or – if this fails – a Bool for key rated. In the former case rated is set to the Double value, in the latter case it's set to nil.
struct AccountState: Decodable {
    let id: Int
    let favorite: Bool
    let watchlist: Bool
    let rated: Double?

    private enum CodingKeys: String, CodingKey { case id, favorite, watchlist, rated }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decode(Int.self, forKey: .id)
        favorite = try container.decode(Bool.self, forKey: .favorite)
        watchlist = try container.decode(Bool.self, forKey: .watchlist)
        if let ratedData = try? container.decode([String:Double].self, forKey: .rated),
           let key = ratedData.keys.first, key == "value"{
            rated = ratedData[key]
        } else {
            let _ = try container.decode(Bool.self, forKey: .rated)
            rated = nil
        }
    }
}

The line to decode Bool in the else scope can even be omitted.
Comment: Is it at all possible to keep it `Codable` not `Decodable`?
Comment: Yes, then you have to implement also `encode(to:)` and specify how `rated` is supposed to be encoded.
Answer: here is an easy way to do it (it's long, but easy to understand)

Step 1 - Create 2 types of Struct for your 2 kinds of format (from your sample, rated can be Bool or has Double as value)

// Data will convert to this when rate is bool
struct AccountStateRaw1: Codable {
    let id: Int?
    let favorite: Bool?
    let watchlist: Bool?
    let rated: Bool?
}

// Data will convert to this when rate has value
struct AccountStateRaw2: Codable {
    let id: Int?
    let favorite: Bool?
    let watchlist: Bool?
    let rated: Rated?

    struct Rated : Codable {
        let value : Double?
    }
}

Step 2 - Create your AccountState which can hold both kind of format

// You will use this in your app, and you need the data you get from API to convert to this
struct AccountState: Codable {
    let id: Int?
    let favorite: Bool?
    let watchlist: Bool?
    let ratedValue: Double?
    let isRated: Bool?
}

Step 3 - Make both of your structs of Step 1 able to convert to struct of Step 2

protocol AccountStateConvertable {
    var toAccountState: AccountState { get }
}

extension AccountStateRaw1: AccountStateConvertable {
    var toAccountState: AccountState {
        AccountState(id: id, favorite: favorite, watchlist: watchlist, ratedValue: nil, isRated: rated)
    }
}

extension AccountStateRaw2: AccountStateConvertable {
    var toAccountState: AccountState {
        AccountState(id: id, favorite: favorite, watchlist: watchlist, ratedValue: rated?.value, isRated: nil)
    }
}

Final Step - data from API --convert--> structs of Steps 1 --convert--> struct of Step 2

func convert(data: Data) -> AccountState? {
    func decodeWith<T: Codable & AccountStateConvertable>(type: T.Type) -> AccountState? {
        let parsed: T? = try? JSONDecoder().decode(T.self, from: data)
        return parsed?.toAccountState
    }
    return decodeWith(type: AccountStateRaw1.self) ?? decodeWith(type: AccountStateRaw2.self)
}

multiple types in Codable


JSON Data changes while transferring from C# to ExtJS

Question: When transferring JSON data from a Webmethod in asp.net C# through an Ajax call in ExtJS 4.2.2, several characters are added to the beginning and end of the string.
JSON Data before leaving C#:
[{"ID":"0","NAME":"ALAN"},{"ID":"1","NAME":"BLAKE"}]

JSON Data as seen by firebug which is received by ExtJS
{"d":"[{"ID":"0","NAME":"ALAN"},{"ID":"1","NAME":"BLAKE"}]"}

This will also happen if the JSON Data has a set root property.
From what it appears it seems as if something somewhere along the line treated the incoming data as a variable in a JSON string or something like that.
Code on the C# end:
[WebService(Namespace = "localhost")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class Director : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true, XmlSerializeString = false)]
    public string getData()
    {
        string json = "[{\"ID\":\"0\",\"NAME\":\"ALAN\"},{\"ID\":\"1\",\"NAME\":\"BLAKE\"}]";
        System.Diagnostics.Debug.WriteLine(json);
        return json;
    }
}

Code for the ExtJS Ajax Call (already has a workaround implemented):
Ext.Ajax.request({
    async: false,
    url: Test061014.ApplicationPath + '/Director.asmx/getData',
    headers: { 'Content-Type': 'application/json' },
    scope: this,
    success: function (conn, response, options, eOpt) {
        var s = conn.responseText;
        s = s.substring(6, (s.length - 2));
        s = s.replace(/\\/g, "");
        categoryData = JSON.parse(s);
    },
});

Answer: That is inserted by ASP.NET for security reasons. Check out this article for more details.

If you aren't familiar with the ".d" I'm referring to, it is simply a
  security feature that Microsoft added in ASP.NET 3.5's version of
  ASP.NET AJAX. By encapsulating the JSON response within a parent
  object, the framework helps protect against a particularly nasty XSS
  vulnerability.

They have a nice solution of using the dataFilter property so you can stop worrying about .d.  Again, credit to the article, here is their solution. You may need to read the article's Don't make me think section as there are a couple of details I left out.
dataFilter: function(data) {
// This boils the response string down
//  into a proper JavaScript Object().
var msg = eval('(' + data + ')');

// If the response has a ".d" top-level property,
//  return what's below that instead.
if (msg.hasOwnProperty('d'))
  return msg.d;
else
  return msg;
},


Authentication request failure in PayPal Android SDK Live Mode

Question: I have to use the PayPal Android SDK, so I'm trying to Payment with Live mode from Android App. I'm trying to payment using Credit Card or Debit Card, but PayPal SDK return these error.
How can use PayPal in Live Mode. Please help me.
request failure with http statusCode:401,exception:Unauthorized
request failed with server response:
{"name":"UNAUTHORIZED_PAYMENT","message":"Unauthorized payment.","information_link":"https://developer.paypal.com/docs/api/payments/#errors","debug_id":"1b99b23b39a5e"}
UNAUTHORIZED_PAYMENT
Comment: in which country you are trying to pay?
Comment: Right now from India, but actual payment from USA.
Comment: You have to register your merchant account in USA and also submit all documents and details to PayPal before you go to live
Answer: you are getting that message because you are attempting to process direct credit card payments with a merchant account registered in a country where it's not available. Direct Credit Card transactions with the mSDK (and REST API in general) is available in US and UK only.


how do i make a active class which keep on my current page with a border effect

Question: I am working with a project where i have amde a animation effect on every a tag which the user want to go an animation would appear and after that that page will get redirected. But the problem is that i want a border bottom on below of that current navbar.
.index.html
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="style.css" />

Header-issue

HOME

ABOUT

CONTACT US

JOBS

          LOGIN

style.css
/* @import url("https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,400;1,100&family=Open+Sans&family=Raleway:wght@200;400&display=swap"); */

* {
    padding: 0px;
    margin: 0px;
    box-sizing: border-box;
    font-family: "Raleway", serif;
  }

  body {
    font-family: "Raleway", serif;
    /* font-family:'Roboto Slab', serif; */
  }
  /* --------------------------------   Rachit Gupta */
   /* .new__parent-navbar {
    display: flex;
    position: fixed;
    width: 100%;
    justify-content: space-between;
    transition: 0.6s;
    z-index: 5;
  } */

  nav.sticky {
    top: 0%;
    background: #FBFBFB;

    /* color:; */
    /* text-decoration: ; */
  }
  nav .sticky li a{
    text-decoration: none;
    color: white;
    /* background: rgb(27, 26, 90); */
    position: relative;
    font-size: 1.1rem;
  }

  /* -------------------------------  End  */
  .new__parent-navbar {
    display: flex;
    /*START of added code*/
    position: fixed;
    top: 0;
    left: 0;
    right:0;
    z-index: 999;
    /*DONE*/
    /* background: white; */
    box-shadow: 1px 1px 4px 1px rgb(152, 152, 152);
    /* border-radius: 0px 0px 5px 5px; */
    margin-bottom: 40px;
    padding: 7px 0px;
    /* width: 80%; */
  }
  /*Added*/
  a.active{
    text-decoration: 1px solid goldenrod;
    color: aquamarine;
  }
  .new__logo {
    width: 30%;/*changes*/
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 5px;
    font-weight: 300;
    position: relative;
    left: 10px;
    /* background: white; */
    color: rgb(78, 78, 167);
    /* font-size: 60px; */

    /* background-color: blue; */
  }
  .new__navbar {
    display: flex;
    /* background: white; */
    /* /* display: fixed;
    top: 0px;
    left:0px; */
    /* z-index: 3;  */
  }
  .new__nav-list {
    width: 100%;
    /* background: #15114b; */
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }

  .new__nav-list li {
    list-style: none;
    color: black;
    padding: 10px 10px;
  }
  .new__nav-list li a {
    text-decoration: none;
    color: rgb(21, 41, 123);
    position: relative;
    font-size: 1rem; /**/
  }
  .new__nav-list li a:hover {
    color: #2A528A;
  }

  .new__nav-list li a::after {
    position: absolute;
    content: "";
    display: block;
    margin-top: 5px;
    width: 0;
    height: 2px;
    background: #fcd600;
    transition: width 0.3s;
    left: 50%;
    transform: translate(-50%, 0);
  }

  .new__nav-list li a:hover::after {
    width: 100%;
  }
  #search {
    padding: 5px;
    font-size: 17px;
    border: 2px solid grey;
    border-radius: 9px;
    margin-top: 15px;
  }
  .new__burger {
    position: absolute;
    cursor: pointer;
    right: 4%;
    top: 15px;
    display: none;
  }
  .new__line {
    width: 33px;
    /* background: #fff; */
    height: 4px;
    margin: 4px 3px;
    border-radius: 43px;
  }

  .logo-link {
    margin-left: 6%;
    color: rgb(23, 27, 135);
    text-decoration: none;
    position: absolute;
    left: 80px; /*made a change : 80px, No change*/
    text-shadow: 1px 1px 1px grey; /* added */
  }
  .logo-link:hover {
    color: navy; /*midnightblue;*/
    text-decoration: none;
    transform: scale(1.05);
    text-shadow: 2px 2px 2px grey;
  }
  /* .logo-link:focus {
    color: white;
    text-decoration: none;
  } */

  @media (max-width: 992px) {
    .new__parent-navbar {
      flex-direction: column;
    }
    .new__logo {
      padding-top: 10px;
      width: 100%;
    }
    .new__nav-list {
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
    .new__navbar {
      flex-direction: column;
      justify-content: center;
      align-items: center;
      transition: all 0.5s ease-out;
      height: 100vh;
    }
    .rightNav {
      text-align: center;
    }
    #search {
      width: 100%;
    }
    .new__burger {
      display: block;
    }
    .h-nav {
      height: 11px;
      /* height: 372px; */
    }
    .v-class {
      opacity: 0;
      display: none;
    }
  }
  /*My code  yogita*/
  .login-nav{
    height: auto;
    width: 100px;
    position: relative;
    top: 10px;
    bottom: 20px;
    left: 280px;
    margin: 20px;
    padding: 2px 10px;
    background-color: navy;
    color: white;
    text-shadow: 1px 1px 1px #eee;
    border-radius: 20px;
    border: 2px solid navy;
    box-shadow: 1px 1px 5px 1px grey;
  }
  .login-nav:hover{
    box-shadow: 1px 2px 3px 1px grey;
    text-decoration: none;
    color: white;
    text-shadow: 1px 2px 3px grey;
    /* transform: scale(1.05); */
  }
  /* ---------------------end --------- */

contact.html
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="style.css" />

Header-issue

HOME

ABOUT

CONTACT US

JOBS

          LOGIN

    contact

and so on
and all the rest about, contact and job are same
Comment: Do your want css solution or you want js to add active class to current nav item dynamically?
Comment: anything which make this logic can happen i tried by putting active class in one and then .active and not active but in vain
Answer: Have you tried to get rid of the / before your page name ?
Change
CONTACT US

By
CONTACT US

Answer: The problem is that your HTML code is not semantic.
Your active class in current page with corresponding
 or  with perfectly work fine.
Just need to unwrap
s from
s.
In other words, write

in this structure and give bold/size styling via css.


Filter in WordPress/Woocommerce to disable Cash-on-Delivery for a specific shipping zone

Question: I am trying to set a filter that would calculate the cash-on-delivery payment when the customer selects a specific shipping zone (for out-of-town deliveries). I'm using the Table Rates Plug-in.
I was looking at this code (https://github.com/woothemes/woocommerce/issues/1499) at the answer by maxrice, but I can't adapt it to suit my needs:
My zone_id to exclude COD payment is table_rate-3.
Comment: Maybe you could explain some more what you've tried, and exactly what the problem is?
Answer: As you can see looking at http://docs.woothemes.com/wc-apidocs/source-class-WC_Gateway_COD.html the native woocommerce COD class has no filters or actions you can hook into for your problem.
What you could do is disable the woocommerce native COD payment gateway and make your own. This link here provides a bit of a template for making your own payment gateway.
http://docs.woothemes.com/document/woocommerce-payment-gateway-plugin-base/
You could paste the woocommerce COD class in here (where it says // Go wild in here on line 31) and make changes as necessary. I imagine you'll mostly need to make changes to the is_available() function. You put that code down in either your themes functions.php file or better yet make your own plugin.


Express product of a trigonometric function as a sum or difference

Question: How do I find sin(8x)sin(4x) as a sum or difference of trigonometric functions?
I know the sum and difference identities of sin, cos, and tan, but I do not know how to convert from a product of trigonometric functions to a sum of trigonometric functions. Do I use the sin or cos sum and difference identities? I have looked at Product-to-sum trigonometry identity but it did not help.
Comment: You want these: http://www.sosmath.com/trig/prodform/prodform.html
Comment: Ok, thanks! I didn't know those formulas so no wonder I didn't know what to do.
Comment: Also, https://en.wikipedia.org/wiki/List_of_trigonometric_identities#Product-to-sum_and_sum-to-product_identities , which includes the tangent formula and the one in your referenced Math.SE post as well.
Answer: You will notice that the product formulas for $\sin,\cos$ are not the easiest to retain in memory for any length of time. However, they can be easily derived in a couple of minutes if they are forgotten at a crucial stage, such as during an exam.
They all come from the sum and difference formulas.
To derive the formula for $\sin(A)\sin(B)$ for example, recall that you usually see such terms in the sum formulas for the cosine function.
$$ \cos(A+B)=\cos A\cos B-\sin A\sin B $$
$$ \cos(A-B)=\cos A\cos B+\sin A\sin B $$
We can get an equation with $\sin A\sin B$ on one side by subtracting the first equation from the second to obtain
$$ \cos(A-B)-\cos(A+B)=2\sin A\sin B $$
So we quickly derive
$$ \sin A\sin B =\frac{1}{2}[\cos(A-B)-\cos(A+B)]$$
Using the same two identities we can obtain an identity for $\cos A\cos B$ by adding the two identities.
To obtain the identities for the product of a sine and cosine, use the addition and subtraction identities for the $\sin(A\pm B)$.


Difference in file size on hard disk and RAM

Question: I have data file of 36MB(each value in file is double type) residing on hard disk. My question is, when I read this file via c++ in RAM putting content in matrix (provided by boost library), does it going to occupy only 36MB of RAM or different? Am I running out of memory?
The reason is that I am on 64-bit ubuntu platform with 8 GB RAM and I am getting bad allocation error. The same file reading program works fine for small data files.
Below is snippet to load the (data real-sim )[https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary.html] . x and y are boost matrix and vector respectively declared as extern in .h file.
void load_data(const char* filename)
{
   ifstream in(filename);
   string line;
    int line_num = 0;
    if (in.is_open()) {
        while (in.good()) {
            getline(in, line);
            if (line.empty()) continue;
            int cat = 0;
            if (!parse_line(line, cat, line_num)) {
                cout << "parse line: " << line << ", failed.." << endl;
                continue;
            }

            y(line_num) = cat;

            line_num += 1;
        }
        in.close();
    }
 }

bool debug = false;
using namespace boost::numeric::ublas;
vector<double> y(no_records);
matrix<double> x(no_records,no_features);
using namespace std;

template < class T>
void convert_from_string(T& value, const string& s)
{
stringstream ss(s);
ss >> value;
}

int get_cat(const string& data) {
int c;
convert_from_string(c, data);

return c;
}

bool get_features(const string& data, int& index, double& value) {
int pos = data.find(":");
if (pos == -1) return false;
convert_from_string(index, data.substr(0, pos));
convert_from_string(value, data.substr(pos + 1));

return true;
}

bool parse_line(const string& line, int& cat, const int line_num) {
if (line.empty()) return false;
size_t start_pos = 0;
char space = ' ';

while (true) {
    size_t pos = line.find(space, start_pos);

    if ((int)pos != -1) {
        string data = line.substr(start_pos, pos - start_pos);
        if (!data.empty()) {
            if (start_pos == 0) {
                cat = get_cat(data);
            }
            else {
                int index = -1;
                double v = 0;
                get_features(data, index, v);
                if (debug)
                    cout << "index: " << index << "," << "value: " << v << endl;
                if (index != -1) {
                    index -= 1; // index from 0
                    x(line_num, index) = v;
                }
            }
        }
        start_pos = pos + 1;
    }
    else {
        string data = line.substr(start_pos, pos - start_pos);
        if (!data.empty()) {
            cout << "read data: " << data << endl;
            int index = -1;
            double v = 0;
            get_features(data, index, v);
            if (debug)
                cout << "index: " << index << "," << "value: " << v << endl;
            if (index != -1) {
                index -= 1; // index from 0
                x(line_num, index) = v;
            }
        }
        break;
    }
}

return true;
}

Comment: It would occupy around the same amount yes. The crash/exception you get *might* be related to the size, but it doesn't have to be, but it's impossible to say anything without more information, preferably some code. Please try to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve) and show us, together with a small sample of the input file (if it's text).
Comment: You have made an assumption that is almost sure to be invalid.  36MB is nothing and the file size is not a direct contributor to your bug/s.
Comment: Don't blame my reading comprehension when I had nothing useful to read. Congratulations on now achieving the latter.
Comment: Guessing is not a useful tool in problem solving. Again, what is your program doing? Where does it allocate memory? and how? etc.
Comment: I just ran my program on a file (42MB on hdd) that contains 1000 rows and 5K columns(features). It ran perfectly. But, when I tried running the same code with data file containing  70K rows and 20K columns, bad allocation error occurred (also on data file of size 10K X 1M). This indicates that file size is not issue. But, can you guess why that error is occurring?
Comment: Perhaps when you load the data into a matrix, you are consuming more space than you need to for each feature.  Without example code, we can only speculate.
Comment: @underscore_d. If you please read the question carefully, I have said above that my program reads a data file in a boost matrix. FYI, I have added code.
Comment: @underscore_d. I am not blaming. As my initial question said that I got bad allocation error. I thought it may be huge amount of memory taken in RAM after file reading. To ans. to  questions raised in your first comment, useful thing that could be found in my initial Q are 1. My program is reading a file from hdd to RAM using C++ 2. I used boost matrix to allocate memory 3. If you are familiar how boost allocate memory to matrices, you should know how part of your question. Also as I said above that my program is working fine on small data file and so I thought its not programming issue.
Comment: Unrelated to your problem, but you might want to read ["Why is "while ( !feof (file) )" always wrong?"](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). While the question is specific to C the accepted answer is generic for just about all languages, especially C and C++. And it's not only `while (!in.eof())` that's bad, also the equivalent `while (in.good())` suffers from the same problem.
Comment: More related to your problem, when you define the global `x` and `y` variables, what is the values of `no_records` and `no_features`? If they are to low you will probably be writing out of bounds, and if they're to high you're wasting a lot of memory.
Answer: I found the culprit. The reason for bad allocation error was that I was running out of memory. The thing is that I was using dense matrix representation (as provided by boost library). As such, storing a matrix of size 20000x40000 as dense matrix in boost matrix representation will require RAM of size 6.4GB. Now, if one don't have that much space in RAM, bad allocation is going to pop-up.


Heat Pump - emergency electric strips - how controlled?

Question: I have a recently installed combination of a Goodman electric package unit, and an ecobee smart thermostat.
This morning with the outdoor temp at 36, I was surprised when I peered out the window and saw that my compressor fan was not running (which told me my house was being heated by the electric heat strips in the unit rather than the compressor).
I was surprised because the thermostat was set up to only run the heat strips if the outdoor temp was below 35, and the stat itself was claiming an outdoor temp of 36.
Now I am wondering if the goodman package unit has a thermostat of it's own that switches over to electric heat strip at a certain temp.
Since mid to upper 30's is such a common overnight temp around here during the winter, this could make a big difference in my power usage.  Just a few degrees one way or the other would change the percentage of my heating that was with the heat pump by a large margin.
I did some googling and can't find any detailed technical info about Goodman products on line.  Just very basic stuff.  They don't provide ANY tech support to customers, only through dealers.  argh.
Comment: It certainly is common for a heat pump to have and outside, mechanical temperature switch.  That would be the only way to handle the situation before all these high-tech smart thermostats.
Answer: Being that you are only talking about 1 degree difference I would think it is possible that the tstat began the heating cycle while the outdoor temp was at 35 and rose to 36 mid cycle.  Also, it's been 10+ years since I have been involved with Goodman, but they used to have a timer on the defrost control board so that if the unit ran for 30 ~ 120 minutes it would shutdown the heatpump and bring on the backup heat strip. The timing is set via a small dial on the defrost control board.  I believe that the default value is 90.  At 36° ambient temp, depending on the outdoor relative humidity, your heatpump certainly could have been running long enough to exceed that time.
Answer: Unless you happened to look at the unit during the defrost cycle (which lasts only a few minutes), your thermostat is probably miswired or configured incorrectly.  The heat pump should be running with outdoor at 35F, whether or not the heat strips are on.
There could be an outdoor thermostat tied into the heat strip control, but usually that disables the heat strips when 35F or warmer outside and is not for cutting off the compressor.  Even in a unit equipped with a low ambient compressor cut off, the cut off should not engage until below 20F or so.  If your winter temperature rarely goes below the 20s at night, it is doubtful the unit is equipped with a low ambient compressor cut off at all.
Post the model number of the Goodman condenser and a photo of wiring to the thermostat if you want more comments.
Answer: On some units the condenser fan can cycle to maintain certain pressures.  Not seeing the fan running does not necessarily mean that the compressor is not running.
Or it could be in defrost.
Comment: No unit that I know of will cycle the condenser fan in *heating mode* except for defrost.  Otherwise fan cycling applies only to head pressure control for *cooling mode*.


CodeIgniter form_validation and form_error - delete original error message

Question: I'm using CodeIgniter form_validation and
Everything works good except the original notification still appears in the top right.
Can anybody advise me how to delete the original notification?
I've inserted the PHP code into to view page.
<?php echo form_error('uname'); ?>

The form_error message appears the way I want but the original error message still appears in the top right, and I don't know how to delete that.
EDIT 01/08/19
Below is edited coding I've taken from the CI UserGuide.
Controller
<?php

class Form extends CI_Controller
{
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');

$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required', array('required' => 'You must provide a %s.'));
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->view('formsuccess');
}
}
}

View

<title>My Form</title>

<?php echo validation_errors(); ?>
<?php echo form_open('form'); ?>

Username

<input type="text" name="username" value="" size="50" />

Password

<input type="text" name="password" value="" size="50" />

<input type="submit" value="Submit" />
</form>

If the above is loaded the result will be the Username Text Box in the top left corner, and the Password Text Box below it.
If the Submit button is clicked without any content in the text boxes the following notifications appear in the top left corner and above the Text Boxes.
You must provide a Username.
You must provide a Password.
However, if I change the view page to the following, the same notifications STILL APPEAR IN THE TOP LEFT CORNER, as well as next to the Text Boxes, so in effect each notification appears twice.

<title>My Form</title>

<?php echo validation_errors(); ?>
<?php echo form_open('form'); ?>

Username

<input type="text" name="username" value="" size="50" />
<?php echo form_error('username'); ?>

Password

<input type="text" name="password" value="" size="50" />
<?php echo form_error('password'); ?>

<input type="submit" value="Submit" />
</form>

It is the notifications that still appear in the top left corner, that I want to delete.
I can't find any coding that positions the notifications so I guess that comes from somewhere within the CI system.
I can position the form_error notifications by using css coding.
Comment: Could you explain a bit more, what's this *error message* and what's this *original message*, or maybe you could attach a picture of it?
Answer: I found the problem.
<?php echo form_error('username'); ?> // When this is inserted.

<?php echo validation_errors(); ?> //This must be deleted.

Or put another way the coding above provides the notifications at the top right.


Failing to open Binary File

Question: 3 File I/O streams are globally declared( outside all functions )
ifstream fin;
ofstream fout;
fstream file;

These are 2 functions where problem occurs. Due to some reason the file "quizquestions.dat" is unable to be opened. Due to which the statement exit(1); is being executed and the program is terminating. The question number is not being allotted properly.  The object "universal" is an object of my class question which stores the question.
The code gets compiled and there are no errors.
void questionnumber()
{
    int file_size=0;
    fin.open("quizquestions.dat",ios::in|ios::binary);
    fin.seekg(0,ios::end);
    file_size = file.tellg();
    if(file_size==0)
        universal.assignquestion(1);
    fin.close();
    int next_question = (file_size/sizeof(question)) + 1;
    universal.assignquestion(next_question);
}
void addquestion()
{
    ch='y';
    do
    {
        cout<<"Adding question now\n";
        cout<<"Please\n";
        universal.createquestion();
        questionnumber();
        fout.open("quizquestions.dat",ios::app|ios::binary);
        if(!fout)
            exit(1);
        fout.write((char*)&universal,sizeof(question));
        fout.close();
        cout<<"Your question is added\nYour question details are as follows"<<endl;
        universal.dispquestion();
        cout<<"Do you want to add more questions?(Y/N)\n";
        cin>>ch; cin.ignore();
    }
    while(ch=='y'||ch=='Y');
    if(ch!='y'||ch!='Y')
        dispsetting();
}

Comment: are you sure the file exists on the location where your compiled exe is present??  you should also try ios::out in the flags
Comment: Even if it didn't existed, wouldn't a new file be created with same name?
Comment: why are you making a check if(!fout).. you must check !fout_isopen() function.
Answer: try using fout.open(ios::app | ios:binary | ios::out);

Failing to open Binary File


Access to attribure afterr search (query)

Question: I have in route:
import Ember from 'ember';
export default Ember.Route.extend({
model(params) {

    let city = params.city_name;
    let cuc = this.store.query('city', {
        linkname: city,
    });

    let itm = this.store.query('product', {
        uriName: params.item_name,
    });

    let dictpage = {
        currentCity: cuc,
        currentProduct: itm,

    };

    return dictpage;
},

});
I need get attribute categoryId from cuc, but when i write there:
fot(let i in itm){
   console.log(i.id);
}

dont work. How to do it?
This i need to find category from good item.
Thank you in advance for your answers!
Comment: `fot` should be `for`.
Comment: Yes, but it's a typo. When i try it, i see error!
Comment: What error, does `itm` exist?
Comment: Text error: Error while processing route: product itm.property is not a function model... And white screen
Answer: I do it! This code do, what i need:
this.store.query('product', {
            uriName: params.item_name
        }).then(function(items) {
            items.forEach(function(item) {
                console.log(item.get('categoryId'));
            });
        });


Mapbox GL JS not showing user heading, always points north

Question: I have a Mapbox-GL-JS script that is working fine. However, the arrow next to the blue user location dot always points north. I thought the showUserHeading option is supposed to point in the direction (bearing) the user is moving. Anyone have a fix for this?
<code>var geolocate = new mapboxgl.GeolocateControl({
    positionOptions: {
        enableHighAccuracy: true
    },
    trackUserLocation: true,
    showUserHeading: true,
    showUserLocation: true,
    showAccuracyCircle: true
    });
</code>
Answer: It happened to me and I had to calibrate the phone's compass by moving the phone around for a few seconds, the bearing then appeared


javafx fxml program error(no main method)

Question: i'm fairly new to javafx and fxml. I'm trying to teach myself! However, when I was creating a program for a simple login GUI I came into an issue when I finally tried to run my program. It told me there was no main method in my class and I'm unsure of how to fix it. Any ideas?
My program creates a login screen and when you enter "test" for the username and password it'll take you to another scene.
Here is my Login.java
package com;

    import javafx.application.Application;
    import javafx.fxml.FXMLLoader;
    import javafx.stage.Stage;
    import javafx.scene.Parent;
    import javafx.scene.Scene;

    /**
     *
     * @author Tyler
     */
    public class Login extends Application{

        @Override
        public void start(Stage stage) throws Exception {
            Parent root = FXMLLoader.load(getClass().getResource("Login.fxml"));
            Scene scene = new Scene(root);
            stage.setScene(scene);
            stage.setTitle("Login");
            stage.show();
        }

    }

Here is my LoginController.java
package com;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

/**
 * FXML Controller class
 *
 * @author Tyler
 */
public class LoginController implements Initializable {

    @FXML
    private Label lblMessage;
    @FXML
    private TextField txtUsername;
    @FXML
    private PasswordField txtPassword;
    @FXML
    private void btnLoginAction(ActionEvent event) throws Exception{
        if(txtUsername.getText().equals("test") && txtPassword.getText().equals("test")){
            ((Node) (event.getSource())).getScene().getWindow().hide();
            Parent parent = FXMLLoader.load(getClass().getResource("DateSelection.fxml"));
            Stage stage  = new Stage();
            Scene scene = new Scene(parent);
            stage.setScene(scene);
            stage.setTitle("Date Selection");
            stage.show();
        }else{
            lblMessage.setText("Username or Password is invalid!");
        }
    }
    /**
     * Initializes the controller class.
     * @param url
     * @param rb
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }

}

Here is my Login.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.text.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane id="AnchorPane" fx:id="lblMessage" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.LoginController">
   <children>
      <PasswordField fx:id="txtPassword" layoutX="200.0" layoutY="200.0" prefHeight="30.0" prefWidth="200.0" promptText="Password" />
      <TextField fx:id="txtUsername" layoutX="200.0" layoutY="140.0" prefHeight="30.0" prefWidth="200.0" promptText="Username" />
      <Button fx:id="btnLogin" layoutX="269.0" layoutY="251.0" mnemonicParsing="false" onAction="#btnLoginAction" prefHeight="30.0" text="Login">

         </Button>

   </children>
</AnchorPane>

Here is my DateSelectionController.java
package com;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.Initializable;

/**
 * FXML Controller class
 *
 * @author Tyler
 */
public class DateSelectionController implements Initializable {

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }

}

Here is my DateSelection.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.text.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8" fx:controller="com.DateSelectionController">
   <children>

   </children>
</AnchorPane>

Answer: From Oracle:

The main() method is not required for JavaFX applications when the JAR file for the application is created with the JavaFX Packager tool, which embeds the JavaFX Launcher in the JAR file. However, it is useful to include the main() method so you can run JAR files that were created without the JavaFX Launcher, such as when using an IDE in which the JavaFX tools are not fully integrated. Also, Swing applications that embed JavaFX code require the main() method.

So one solution is to make sure it's being built in a way that fully supports the JavaFX tools. The other solution is to add a main method to starts the application. That would avoid any potential problems like this, and doesn't cause any problems in the case where it's not needed.
Your main method should look like this:
public static void main(String[] args){
    Application.launch(Login.class, args);
}

That will simply pass control on to JavaFX to handle like it would normally.


How to fix this code to do with correct answers on a quiz

Question: I'm working on my NEA assessment and I can't seem to fix this bit of code here. The code provides the artist name (in this case BTS) and the first initial of a song (F for Fire). When I type Fire, it comes up as incorrect.
Not entirely sure what to write for background here. This is my first time trying this on Python. I've tried minor alterations here but to no avail.
file =  open("artistname.txt", "r")
artist = file.readline()
file.close()#opens file, reads it into artist variable and closes

file = open("songName.txt", "r")
song = file.readline()
file.close()#opens file, reads it into song variable and closes

score = 0
for round in range(len(artist)):
    print(artist)
    songInitial = song[:1]
    print(songInitial)#prints first initial
    if input() == song:
        print("Correct: +3 points")
        score = score + 3#adds 3 to score
        print("Score = ", score)#prints score
    else:
        print("Incorrect, try again")
        if input() == song:#allows second chance
            print("Correct: +1 point")
            score = score + 1#adds 1 to score
            print("Score = ", score)#prints score
        else:
            print("Incorrect, game over.")
            print("Score = ", score)#prints score
            break#ends code

I expect the output to be 'Correct: +3 points" when I type Fire, and to give me a second chance only when I type the incorrect answer, and then a game over once I get it wrong a second time. Instead, it repeats incorrect until the game ends no matter what I type.
Comment: What are the contents of `song` & `artist`?  Not a description, but the actual data.
Comment: most probably your files have more then 1 artist/song if not, they might have newlines after them so you compare "song" vs "song\n" . use `print( f'--{song}--')` and `print( f'--{artist}--')` to verify what exactly is in them. Then readup on ".strip()"
Comment: Don't judge haha. I'm a K-Pop nerd.
Contents of song:
```
Fire
Stay
Fancy
Senorita
Fantastic-Baby
Idol
Me
TT
Forever-Young
No
Gogobebe
Egotistic
Zimzalabim
Yes-or-Yes
Dionysus
Kill-This-ove
Knock-Knock
Hobgoblin
Peekaboo
Latata
```
Contents of artist:
```
BTS
BlackPink
Twice
(G)I-dle
BigBang
BTS
CLC
Twice
Blackpink
CLC
Mamamoo
Mamamoo
Red-Velvet
Twice
BTS
BlackPink
Twice
CLC
Red-Velvet
(G)I-dle
```
All the song names match lines to the artist names.
Each space between (most) of the names are the separate lines.
Answer: If your artists.txt looks like this:
BTS
BlackPink
Twice
(G)I-dle
BigBang
BTS
CLC
Twice
Blackpink
CLC
Mamamoo
Mamamoo
Red-Velvet
Twice
BTS
BlackPink
Twice
CLC
Red-Velvet
(G)I-dle

And your songs.txt looks like this:
Fire
Stay
Fancy
Senorita
Fantastic-Baby
Idol
Me
TT
Forever-Young
No
Gogobebe
Egotistic
Zimzalabim
Yes-or-Yes
Dionysus
Kill-This-ove
Knock-Knock
Hobgoblin
Peekaboo
Latata

Then you'll need to do more than just file.readline(). readline reads just a single line from the file. If your files really are just one line long (where all artists / songs are separated by spaces), then readline could work - I wouldn't recommend you structure your data like this though. I would at least put each artist / song on a separate line, like I've shown above. Even better would be if you had just one file, like a .csv (comma separated values) file, where artists and songs are explicitly paired together.
This code assumes you have two files, where every artist / song is on a separate line:
with open("artists.txt", "r") as file:
    artists = file.read().splitlines()

with open("songs.txt", "r") as file:
    songs = file.read().splitlines()

score = 0

# The amount of points you can earn for a given attempt
# You earn three points if you guess correctly on your first attempt
# You earn 1 point if you guess correctly on your second attempt
attempt_points = [3, 1]
max_attempts = len(attempt_points)

for artist, song in zip(artists, songs):
    song_initial = song[0]
    print("The artist is \"{}\" and the song's title begins with '{}'.".format(artist, song_initial))

    for current_attempt, points in enumerate(attempt_points, start=1):
        user_input = input("Enter your guess ({} attempt(s) remaining): ".format(max_attempts-current_attempt+1))

        if user_input == song:
            print("Correct: +{} points".format(points))
            score += points
            break
        elif current_attempt < max_attempts:
            print("Incorrect: Try again.")
    else:
        print("Game over.")
        break
    print("Score: {}".format(score))

else:
    print("Congratulations! You've managed to guess all songs correcly!")

print("Your total score is {}.".format(score))

Comment: Hi, I put the code into the rest of what I had - and edited the file I had - and it works! Thank you for your help.


How do I play Secops (custom scenarios) in CO-OP over LAN?

Question: I'm fairly new to ARMA but I've created a mission in the single player scenario tab using the mission wizard. I then copied that mission file to the multiplayer mission folder however when I play it with my friend over LAN one of us spawns on the ground alive while the rest of us fall from the helicopter to our instant deaths.
Basically I just want to be able to play Secops over LAN with my friend.
Comment: Just to be clear: Secops means custom scenarios?
Comment: Yeah (stands for secondary operations) basically you spawn and then HQ give you random tasks and enemies and things randomly spawn rather than a set mission.
Answer: I believe I found a solution to my problem although its more of a hacky work around, however at least it works...
Basically host the LAN Secops game as you would usually but only with the host in game, the AI will then take up the other slots. Once in game the helicopter will land safely with AI and host, then invite the other players to join who will take on either empty slots or an AI player.
Voila! - You'll then all be in game and in the same squad.
Steps:

Host LAN Secops game with only the host and AI.
Wait for the helicopter to land safely.
Invite other players to take over AI and empty slots.
Enjoy Secops over multiplayer!

Like I said this method isn't exactly perfect but it gets the job done. If anyone else has any other methods or indeed better ones then please don't hesitate to give your answer!


Working With Bukkit / Classpaths

Question: I'm going to attempt to be as descriptive as possible in this question, because it's difficult to explain..
Here goes. I have two jar files. One (My own), and one (The Bukkit jar). the bukkit jar, i slovated in "./Server/bukkit.jar" I'm tring to access the method "org.bukkit.Bukkit.getServer()" inside a running instance of the bukkit jar started with a processbuilder in my own jar..
So, Here..
My Own Jar's Code:
public class Fukkit {
  public static void main(String[] args){
    ProcessBuilder pb = new ProcessBuilder("java", "-cp", "bukkit.jar", "org.bukkit.craftbukkit.Main");
    pb.directory(new File(new File(".").getPath() + File.separator + "Server"));
    try {
        pb.start();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    //I now want to access that instance of bukkit.jar, and use the method
    org.bukkit.Bukkit.getServer();
    //From inside the jar..

    //I cannot add it as a library, because the jar may be swapped out
    //for another more updated version of bukkit.jar..
    //But that method will always be present. Can someone help me out..?
  }
}

Answer: This method will not work. You're trying to reference Java classes loaded in a separate system process - it doesn't matter whether it's a child of your current process or not. From the Java point of view, it's a separate Java Virtual Machine, with no Java-specific communication between the two.
What you need to do instead is:

Add the bukkit.jar to your classpath (example here).
In your main method, Fukkit.main(), execute org.bukkit.craftbukkit.Main.main(new String [] {"your arguments here"}).
You then should be able to reference org.bukkit.Bukkit.getServer()
and other methods.

When finishing this quick answer I've only now noticed your remark about the JAR being possibly updated. Well, there are some advanced methods of reloading JARs at runtime, but I would suggest to simply restart your program whenever such an update occurs.
Also, doesn't Bukkit have a plugin architecture (I'm assuming we're talking about the Minecraft Bukkit server)? Perhaps you're trying to do it the roundabout way, and that's causing the problem? Try to check whether doing what you want isn't supported by Bukkit's API.
Comment: Thanks for the input. I will look into this when i have access to my computer. :)
Comment: Also, I'm not making a plugin. I'm making a server gui. :3
Comment: I'm glad you found the answer to be satisfactory. To clarify, I was talking about the "plugin architecture" in terms of something you could use in your project, regardless of what it is. For example: if Bukkit plugins can restart the server, your project could have two components: your main program (the actual GUI) and a plugin that communicates with that program, allowing you to restart the server in a way that Bukkit "expects" it to happen. My general point is: unless you're in a huge hurry, it's almost always better to use the API of whatever you interface with.

Working With Bukkit / Classpaths


What is the best way to create a vector of meaningful data out of a comma delimited text file

Question: Consider the following:
I have a class defined :
class Human
{
public:
std::string Name;
std::string Age;
std::string Weight;

}

I have a .txt file defined:
Justin,22,170
Jack,99,210
Fred,12,95
etc...

The goal is to turn this text file into a std::vector
My current code is as follows:
vector<Human> vh;
std::ifstream fin(path);
    std::string line;

    while(std::getline(fin,line))
    {
        std::stringstream   linestream(line);
        std::string         value;
        Human h;
        int IntSwitch = 0;
        while(getline(linestream,value,','))
        {
            ++IntSwitch;
            try{
            switch(IntSwitch)
            {
            case 1 :
                h.Name = value;
                break;
            case 2:
                h.Age = value;
                break;
            case 3:
                h.Weight = value;
                vh.push_back(h);
                break;

                }

            }
            catch(std::exception ex)
                {
                    std::cout << ex.what() << std::endl;
                }
        }

    }

Now i'm just curious is there any c++11 technique or non c++11 technique that would be more efficient / easier to read then this?
Comment: Overload `operator>>` for `istream` and your class.
Comment: @0x499602D2 Actually, an identifier starting with an underscore **followed by an uppercase letter** is reserved for the implementation. As is one containing two consecutive underscores.
Answer: I write a skeleton version, it should work with line base structure:
struct Human
{
  Human(const std::string& name, const std::string& age, const std::string& weight)
    : name_(name), age_(age), weight_(weight) { }

  std::string name_;
  std::string age_;
  std::string weight_;
};

class CSVParser
{
public:
  CSVParser(const std::string& file_name, std::vector<Human>& human) : file_name_(file_name)
  {
    std::ifstream fs(file_name.c_str());
    std::string line;
    while(std::getline(fs, line))
    {
      human.push_back(ConstructHuman(line));
    }
  }
  Human ConstructHuman(const std::string& line);

private:
  std::string file_name_;

};

Human CSVParser::ConstructHuman(const std::string& line)
{
  std::vector<std::string> words;

  std::string word;
  std::stringstream ss(line);

  while(std::getline(ss, word, ','))
  {
   words.push_back(word);
  }
  return Human(words[0], words[1], words[2]);
}

int main()
{
  std::vector<Human> human;
  CSVParser cp("./word.txt", human);

  return 0;
}


Phonegap android - network.isReachable is not working?

Question: Recently I ran into another problem with PhoneGap. I try to use network.isReachable, but this method doesn't work for me. After debugging, I found that in phonegap.js in Phonegap.exec() is called PluginManager.exec(), which should return a value from Java code. For network.isReachable an empty value is returned, though. Next lines of code in Phonegap.exec() get executed only if result is not empty, but I get empty value returned for network.isReachable. What am I doing wrong? Please note, I am using phonegap version 0.9.3. on Android.
Answer: network.isReachable takes a success callback as the second argument.
Network.prototype.isReachable = function(uri, callback, options)

Nothing is returned directly from the network.isReachable call, instead the callback is called with the network status value.


Dual-monitor Wallpaper Lock Screen

Question: System info: Ubuntu Desktop 16.04.1 LTS
Dual 1920x1200 monitors (one HDMI, on mini-DP)
When using dual-monitors with a wallpaper set to span, Ubuntu does not correctly display the wallpaper at the login screen or at the lock screen. Is there a way to correct this behavior? I have tried this with several wallpapers at 3840x1200 resolution and display type set to "span." How can this behavior be corrected?
Login Screen: http://pasteboard.co/vZyIyqRKZ.jpg
Logged In (correctly displayed):    http://pasteboard.co/vZAtqFoTA.jpg
Lock Screen:  http://pasteboard.co/vZBNMVCi4.jpg
Comment: Desktop and login screen are handled by different things. I may have a few ideas how we might get around that, but I am currently at work and don't have access to my dual screen set up at home, so it may take some time to provide any answer
Comment: Have you had a chance to dig into this on your home setup?
Comment: Not yet. I'm currently on somewhat busy schedule.  I'll try to look into it on this weekend, probably on Friday.
Comment: Any news on this?
Answer: This is a confirmed bug with low priority, known since 14.04: https://bugs.launchpad.net/ubuntu/+source/unity/+bug/1291359

Dual-monitor Wallpaper Lock Screen


Texture loading- erratic working

Question: I'm a noob to the OpenGL world and am picking up ideas through practice. I've been writing some code to build retro-arcade games recently and need to load textures to provide the graphic interface. I'm using OpenGL v4.6 with GLFW3 and the stb library to load images.
To load textures, I draw a box and define the texture coordinates of the image on the box. Only some of the png's that I use have loaded properly- often, the image is blurred and distorted. There were two things I tried so far-

Look exclusively for jpg files as these were loading properly. But most of the textures that I download of google are exclusively png
Convert the png into a jpg file. Since I was converting, I decided to use other file formats as well, cropping some of the images if need be. I used GIMP to export them in jpg format. However, when I try to load it OpenGL, I still get bad-poor results.

Another possible approach I'm considering is to convert them into dxt formats and see if that does the trick. However, this seems a tad too tedious and something I'd only go for if nothing else works.
Below is the code that I'm using to load the image.
int width, height, nrChannels;
unsigned char* data = stbi_load(file_path, &width, &height, &nrChannels, 0);
GLenum format{};
if (data)
{
    if (nrChannels == 1)
        format = GL_RED;
    else if (nrChannels == 3)
        format = GL_RGB;
    else if (nrChannels == 4)
        format = GL_RGBA;
    glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
    glGenerateMipmap(GL_TEXTURE_2D);
}

I'm starting to spend a significant amount of time looking for images that will load properly and less time learning/implementing; this is quite concerning. Can someone please point out where I'm going wrong or a better way of skirting around this issue?

The image to the left is the original as loaded by OpenGL (jfif file format). The one to the bottom is the edited version (made with Gimp, stored as jpg). The image to the right is the render of the bottom image in OpenGL

Again, the image to the left is the output from Opengl while the one to the right is the original image. Note the inclination of the render and lack of colour in it.

Edit: Here are some of the implementation details-
I'm believe this portion should be correct because the render is perfect for .jpg files. rect is a vector to hold the box and texture coordinates and ind is a vector that holds the indices that are used by the element buffer to avoid repeat drawing. Both are initialised as arrays and converted into a vector (loop through array and push_back into vector).
PS. Apologies for the verbosity. I was trying to couch the drawing inside a class and this was my first attempt at it. So, please bear with me.
// Box container to hold images
//             x      y   tex-x   tex-y
const float rect[] = {
            -0.2f, -0.2f, 0.0f, 0.0f,
             0.2f, -0.2f, 1.0f, 0.0f,
             0.2f,  0.2f, 1.0f, 1.0f,
            -0.2f,  0.2f, 0.0f, 1.0f
    };

int ind[] = {
        0,1,2,
        0,2,3
    };

_num_attr_ is the number of attributes given to the vao, which in this case is 2. cumsum contains the sum of the number of attributes and is used to assign the stride and size of each attribute.
sizes = {2,2}; // initialized
cumsum = 0;
for (int i = 0; i < num_attr; ++i)
{
    attr_num_cumsum.push_back(cumsum);
    cumsum += sizes[i];
    attr_size.push_back(sizes[i]);
}
attr_num_cumsum.push_back(cumsum);

At the end of this block, cumsum has a value of 4 and _attr_num_cumsum_ = {0,2,4} and _attr_size_ = {2,2}.
_vbo_data_ contains the values in rect while _ebo_data_ contains the values in ind Here is the buffer set-up for drawing-
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, vbo_data.size()*sizeof(GL_FLOAT), &vbo_data[0], GL_DYNAMIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, ebo_data.size()*sizeof(GL_INT), &ebo_data[0], GL_DYNAMIC_DRAW);
for (int i = 0; i < num_attr; ++i)
{
    glVertexAttribPointer(i, attr_size[i], GL_FLOAT, GL_FALSE, attr_num_cumsum[num_attr] * sizeof(GL_FLOAT), (void*)(attr_num_cumsum[i] * sizeof(GL_FLOAT)));
    glEnableVertexAttribArray(i);
}

And the actual drawing
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, num_vertices, GL_UNSIGNED_INT, 0);

Vertex Shader
#version 460 core
layout(location = 0) in vec2 aPos;
layout(location = 1) in vec2 tex;
out float C;
out vec2 Tex;
uniform mat4 model;
uniform float col;
void main()
{
    gl_Position = model*vec4(aPos.x,aPos.y,0.0f, 1.0f);
    C=col;
    Tex=tex;
}

Fragment Shader
#version 460 core
out vec4 Fragcolor;
in float C;
in vec2 Tex;
uniform sampler2D texture1;
void main()
{
    Fragcolor = texture(texture1,Tex);
}

Comment: Please provide more information (code if possible). How do you define your box (vertex attributes)? How do you populate the buffers? How do your shaders look like? To me, it looks as if your texture coordinates are not set correctly, but I can't tell for sure without the corresponding code.
Comment: Which version of OpenGL are you using? The second issue (skewed texture) tends to be the result of an image dimension mismatch when uploading (glTexImage2D(...)). Double check you are specifying the correct dimensions when uploading texture to OpenGL. Also maybe check you can use NPOT (non-power of two) textures which depends on the OpenGL context version you create.
Comment: @lfgtm He is using OpenGL v4.6 as mentioned at the beginning. That's why I don't think that NPOT textures are the problem. Additionally, if there is a dimension mismatch, wouldn't there be parts missing? To me, it just looks like the textures are shifted to the right with increasing y value.
Comment: @wychmaster It's not texture coordinates. The skew and lack of colour is a dead giveaway that the texel "stride" is incorrect. If the dims and number of channels are correct, the input image is probably not aligned as GL expects it to be. `glPixelStorei` would probably be the fix, but without knowing more details about the input texture, impossible to say what arguments `glPixelStorei` should take.
Comment: @wychmaster I doubt there is a shift in the coordinates because the same code was used to display the multiple roads image. Also, just to be safe, I tested the render on this (also jpg) and it works- https://imgur.com/Sm3zuMy
Comment: @lfgtm I'm looking up what npot textures are. Never came across them on my tutorials.

Btw, I was doing a bit of reading on the .png files.. It seems they also contain other details like gamma correction. Would these be represented in a simple RGBA value? Presently, I'm trying to set-up the libpng library to see if the problem persists.
Comment: Btw, this is a render of a png with the same code- https://imgur.com/oc4fRBt
Answer: Briefly, modify the stb_load as follows and everything should work.
unsigned char* data = stbi_load(file_path, &width, &height, &nrChannels, 4);
nrChannels = 4;

Details:
Okay, after a lot of heartache trying and failing to get libpng to work, I finally decided to have a look at the stbi implementation that I'm using to load the texture files. This is where the problem comes in from.
@wychmaster was right when he suspected that there was an incorrect stride used. The problem, though, is in the reading of the image. Apparently, this has something to do with alignment of pixel data which is set by glPixelStorei.
Someone posted the same problem in https://github.com/nothings/stb/issues/335 and determined that this was solution (it works!).
The solution is to set the number of desired channels to 4 in the loading function and read the image as an RGBA instead of whatever the image format actually is. This works and all the misaligned images are now perfect. The images that worked before continue to work too.
But, I do not completely understand why nothing else is affected. This seems strange to me... If someone can explain why this works, that would be very helpful. In the event this is a niche question, I'll likely return to make a more detailed post on it.
Comment: Usually textures need to be aligned such that the total bytes in a line is divisible by 4. With RGB format your have 3 bytes per pixel so it's easier to misalign. You can also avoid this in RGB format by making sure that image width divisible by 4.
Comment: That makes sense, all the images that were skewed were not a multiple of 4 in width. Does this mean that the texture input by default expects RGBA values?

Texture loading- erratic working


How to execute a script in a virtual environment from a bash script on server?

Question: I am trying to run a python script in a virtual environment in a server using oarsub :
So firstly I run this command in a server name "a" :
oarsub -l /host=1/gpu=1,walltime=2:00:00 './training_corpus1.sh'

training_corpus1.sh looks like this at the beguinning :
#!/bin/bash

cd /home/ge/ke/anaconda3/envs

source activate env

cd ~/eXP/bert

CUDA_VISIBLE_DEVICES=0,1 python training.py \
    --exp_name bert \ ...

At the beguinning,  I am suppose to open my virtual environment and then run the script but I am always getting this error in the OAR.18651.stderr file :

./training_corpus1.sh: line 5: activate: No such file or directory
Traceback (most recent call last):
  File "training.py", line 18, in <module>
    from xlm.slurm import init_signal_handler, init_distributed_mode
  File "/home/ge/ke/eXP/bert/xlm/slurm.py", line 11, in <module>
    import torch
ImportError: No module named torch

Torch is located in my virtual environment , it seems that It did not open.Whenusing "conda " a thte place of "source" I get:
./training_corpus1.sh: line 5: conda: command not found

Comment: Does this answer your question? [calling conda source activate from bash script](https://stackoverflow.com/questions/34534513/calling-conda-source-activate-from-bash-script)
Answer: For a virtual environment and bash the activation command is
source env/bin/activate

where env is the directory of the virtual environment to activate.
PS. Let me advice you to start any script with set -e to allow fast failing on any error:
#!/usr/bin/env bash
set -e
…

Comment: So I should write  source /home/ge/ke/anaconda3/envs/env/bin/activate ?
Comment: After `cd /home/ge/ke/anaconda3/envs` you can use relative path: `source env/bin/activate`. `env` is now a subdirectory of the current directory.
Comment: it gices this :  ./training_corpus1.sh: line 8: env/bin/activate: No such file or directory it seems activate does not exist in env/bin   like :  (env) ke@dere2:~/anaconda3/envs/env/bin$ cd activate
-bash: cd: activate: Aucun fichier ou dossier de ce type
Comment: `activate` must be present in a virtual environment and must be a bash script. Not sure about `conda` though.