Slice a volume in GLSL using raymarching

Question: I'm currently visualizing scientific data as volumes using Three and GLSL. I have a raymarching script that is pretty standard and colors based on a colormap I feed into the shader.
It looks like this

I want to be able to slice through the data using the slice sliders. However, I'm not certain how to implement this in my raymarching script. I originally had it discard fragments with positions less than the slice sliders. However, that method discards all rays if the camera is also positioned to the negative of that slice value. Not to mention it won't show me the side of the volume.
Here is the main of my shader.
void main(){
    vec3 rayDir = normalize( vDirection );
    vec2 bounds = hitBox( vOrigin, rayDir );

    if ( bounds.x > bounds.y ) discard;

    bounds.x = max( bounds.x, 0.0 );

    vec3 p = vOrigin + bounds.x * rayDir;
    vec3 inc = 1.0 / abs( rayDir );
    float delta = min( inc.x, min( inc.y, inc.z ) );
    delta /= steps;

    for ( float t = bounds.x; t < bounds.y; t += delta ) {

        float d = sample1( p/scaleVec/scale + 0.5 );
        bool cond = d > threshold;
        cond = flip ? !cond: cond;

        if ( cond ) {
            color.rgb = texture2D(cmap, vec2(d, 0.5)).rgb;
            color.a = 1.;

            break;
        }

        p += rayDir * delta;

    }

    if ( color.a == 0.0 ) discard;

}

What is the correct way to be able to slice this while also seeing the side of the volume?
Answer: I was over thinking it.
Instead of discarding it, I needed to just let the ray keep marching.
adding
if (p.x < xSlicer.x){
       p += rayDir * delta;
       continue;
   }

To the top of the for loop fixed it.


AS3 for loop with instance names + i

Question: I have some AS3 (I am new to this!) and the only way I could get the code to work was to be very literal and duplicate it over and over so I wondered if anyone was able to offer a more elegant solution that works?
I promise I will learn from it - I just couldn't get a for loop to work due to the dynamic movieclips not being recognised by their instance name when trying to use the integer from the for loop to build the name (if that makes sense?)...
Here is my (bulky) code so far, I want it to cater for 50 clicks not just the 6 I have here:
import flash.display.*
pic.addEventListener(MouseEvent.CLICK,addNewPoint);

var n:Number = 0;

function addNewPoint(e:MouseEvent):void {
    n++;
    pointNo.text = String(n);
    // Create a new MovieClip
    var nextPoint:MovieClip = new newPoint();

    // Add the new MovieClip to the MainTimeline
    // so that we can see it.
    addChild(nextPoint);
    nextPoint.name = "mc"+pointNo.text;

    // Set the location of the new MovieClip
    nextPoint.x = e.target.mouseX;
    nextPoint.y = e.target.mouseY;

    //Draw the line between points
    if (n == 1) {
        var joinPoints:MovieClip = new MovieClip();
        this.addChild(joinPoints);
        joinPoints.graphics.lineStyle(0.5,0xFF0000);
        joinPoints.graphics.moveTo(this.getChildByName("mc1").x, this.getChildByName("mc1").y);
    }else if (n == 2) {
        var joinPoints:MovieClip = new MovieClip();
        this.addChild(joinPoints);
        joinPoints.graphics.lineStyle(0.5,0xFF0000);
        joinPoints.graphics.moveTo(this.getChildByName("mc1").x, this.getChildByName("mc1").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc2").x, this.getChildByName("mc2").y);
    }else if (n == 3) {
        var joinPoints:MovieClip = new MovieClip();
        this.addChild(joinPoints);
        joinPoints.graphics.lineStyle(0.5,0xFF0000);
        joinPoints.graphics.moveTo(this.getChildByName("mc1").x, this.getChildByName("mc1").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc2").x, this.getChildByName("mc2").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc3").x, this.getChildByName("mc3").y);
    }else if (n == 4) {
        var joinPoints:MovieClip = new MovieClip();
        this.addChild(joinPoints);
        joinPoints.graphics.lineStyle(0.5,0xFF0000);
        joinPoints.graphics.moveTo(this.getChildByName("mc1").x, this.getChildByName("mc1").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc2").x, this.getChildByName("mc2").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc3").x, this.getChildByName("mc3").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc4").x, this.getChildByName("mc4").y);
    }
    else if (n == 5) {
        var joinPoints:MovieClip = new MovieClip();
        this.addChild(joinPoints);
        joinPoints.graphics.lineStyle(0.5,0xFF0000);
        joinPoints.graphics.moveTo(this.getChildByName("mc1").x, this.getChildByName("mc1").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc2").x, this.getChildByName("mc2").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc3").x, this.getChildByName("mc3").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc4").x, this.getChildByName("mc4").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc5").x, this.getChildByName("mc5").y);
    }
    else if (n == 6) {
        var joinPoints:MovieClip = new MovieClip();
        this.addChild(joinPoints);
        joinPoints.graphics.lineStyle(0.5,0xFF0000);
        joinPoints.graphics.moveTo(this.getChildByName("mc1").x, this.getChildByName("mc1").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc2").x, this.getChildByName("mc2").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc3").x, this.getChildByName("mc3").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc4").x, this.getChildByName("mc4").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc5").x, this.getChildByName("mc5").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc6").x, this.getChildByName("mc6").y);
    }
}

pic.addEventListener(MouseEvent.CLICK, addNewPoint);

function fillDriveway(eventObject:MouseEvent) {
    var joinPoints:MovieClip = new MovieClip();
    this.addChild(joinPoints);
    if (n == 3) {
        var joinPoints:MovieClip = new MovieClip();
        this.addChild(joinPoints);
        joinPoints.graphics.lineStyle(0.5,0xFFFFFF);
        joinPoints.graphics.beginFill(0xFFFFFF, 0.2);
        joinPoints.graphics.moveTo(this.getChildByName("mc1").x, this.getChildByName("mc1").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc2").x, this.getChildByName("mc2").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc3").x, this.getChildByName("mc3").y);
        this.getChildByName("mc1").visible=false;
        this.getChildByName("mc2").visible=false;
        this.getChildByName("mc3").visible=false;
    }else if (n == 4) {
        var joinPoints:MovieClip = new MovieClip();
        this.addChild(joinPoints);
        joinPoints.graphics.lineStyle(0.5,0xFFFFFF);
        joinPoints.graphics.beginFill(0xFFFFFF, 0.2);
        joinPoints.graphics.moveTo(this.getChildByName("mc1").x, this.getChildByName("mc1").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc2").x, this.getChildByName("mc2").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc3").x, this.getChildByName("mc3").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc4").x, this.getChildByName("mc4").y);
        this.getChildByName("mc1").visible=false;
        this.getChildByName("mc2").visible=false;
        this.getChildByName("mc3").visible=false;
        this.getChildByName("mc4").visible=false;
    }else if (n == 5) {
        var joinPoints:MovieClip = new MovieClip();
        this.addChild(joinPoints);
        joinPoints.graphics.lineStyle(0.5,0xFFFFFF);
        joinPoints.graphics.beginFill(0xFFFFFF, 0.2);
        joinPoints.graphics.moveTo(this.getChildByName("mc1").x, this.getChildByName("mc1").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc2").x, this.getChildByName("mc2").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc3").x, this.getChildByName("mc3").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc4").x, this.getChildByName("mc4").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc5").x, this.getChildByName("mc5").y);
        this.getChildByName("mc1").visible=false;
        this.getChildByName("mc2").visible=false;
        this.getChildByName("mc3").visible=false;
        this.getChildByName("mc4").visible=false;
        this.getChildByName("mc5").visible=false;
    }else if (n == 6) {
        var joinPoints:MovieClip = new MovieClip();
        this.addChild(joinPoints);
        joinPoints.graphics.lineStyle(0.5,0xFFFFFF);
        joinPoints.graphics.beginFill(0xFFFFFF, 0.2);
        joinPoints.graphics.moveTo(this.getChildByName("mc1").x, this.getChildByName("mc1").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc2").x, this.getChildByName("mc2").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc3").x, this.getChildByName("mc3").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc4").x, this.getChildByName("mc4").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc5").x, this.getChildByName("mc5").y);
        joinPoints.graphics.lineTo(this.getChildByName("mc6").x, this.getChildByName("mc6").y);
        this.getChildByName("mc1").visible=false;
        this.getChildByName("mc2").visible=false;
        this.getChildByName("mc3").visible=false;
        this.getChildByName("mc4").visible=false;
        this.getChildByName("mc5").visible=false;
        this.getChildByName("mc6").visible=false;
    }
}

btn1.addEventListener(MouseEvent.CLICK, fillDriveway);

function undoit(eventObject:MouseEvent) {
    if(n > 0) {
        this.removeChild(this.getChildAt(this.numChildren -1));
        this.removeChild(this.getChildAt(this.numChildren -1));
        n--;
        pointNo.text = String(n);
    }
}

undo.addEventListener(MouseEvent.CLICK, undoit);

**EDIT --------------------------------------------
Thanks to Eduardo - finished code looks like:**
import flash.display.*

pic.addEventListener(MouseEvent.CLICK,addNewPoint);

var n:Number = 0;

function addNewPoint(e:MouseEvent):void {
    n++;
    pointNo.text = String(n);
    // Create a new MovieClip
    var nextPoint:MovieClip = new newPoint();

    // Add the new MovieClip to the MainTimeline
    // so that we can see it.
    addChild(nextPoint);
    nextPoint.name = "mc"+pointNo.text;

    // Set the location of the new MovieClip
    nextPoint.x = e.target.mouseX;
    nextPoint.y = e.target.mouseY;

    //Draw the line between points
    var joinPoints:MovieClip = new MovieClip();
    this.addChild(joinPoints);
    joinPoints.graphics.lineStyle(0.5,0xFF0000);
    joinPoints.graphics.moveTo(this.getChildByName("mc1").x, this.getChildByName("mc1").y);
    for(var i:int=2; i<=n; ++i){
      joinPoints.graphics.lineTo(this.getChildByName("mc"+i).x, this.getChildByName("mc"+i).y);
    }
}

pic.addEventListener(MouseEvent.CLICK, addNewPoint);

function fillDriveway(eventObject:MouseEvent) {
    var joinPoints:MovieClip = new MovieClip();
    this.addChild(joinPoints);
    joinPoints.graphics.lineStyle(0.5,0xFFFFFF);
    joinPoints.graphics.beginFill(0xFFFFFF, 0.2);
    joinPoints.graphics.moveTo(this.getChildByName("mc1").x, this.getChildByName("mc1").y);
    for(var i:int=2; i<=n; ++i){
      joinPoints.graphics.lineTo(this.getChildByName("mc"+i).x, this.getChildByName("mc"+i).y);
    }
}

btn1.addEventListener(MouseEvent.CLICK, fillDriveway);

Answer: You could simplify the ifs by doing:
var joinPoints:MovieClip = new MovieClip();
this.addChild(joinPoints);
joinPoints.graphics.lineStyle(0.5,0xFF0000);
joinPoints.graphics.moveTo(this.getChildByName("mc1").x, this.getChildByName("mc1").y);
for(var i:int=2; i<=numpoints; ++i){
  joinPoints.graphics.lineTo(this.getChildByName("mc"+i).x, this.getChildByName("mc"+i).y);
}

That would take care of the first set of ifs, the second could be dealt with in a similar way

AS3 for loop with instance names + i


What is that colorful display under MechJeb's Maneuver Planner, advanced transfer to another planet option?

Question: I've been using MechJeb mod successfully for some time now. But there is one piece of its user interface that is puzzling me.
On the Maneuver Planner, when I select the advanced transfer to another planet option, I get this colorful display below, that apparently can be used to select a maneuver node. I'm saying that because the Δv and maneuver details change as I pass the mouse over the colors on that display. But I have no idea what the colors mean or how the display can be effectively used.

Screenshot taken when selecting a transfer maneuver from a highly elliptical orbit around Duna towards Jool.
My questions are:

What is this colorful display showing?
What do the colors represent?
How can I use this display to select a particular maneuver node?

I searched but couldn't find information about it anywhere.

I'm using MechJeb 2.5.8 on KSP v188.8.131.529 (x64).
Answer: Well, right on top it says "Porkchop selection", and that is what it shows, a porkchop plot.
It plots launch date vs. flight time on the axes, and the color represents the needed delta-v. Blue is lower delta-v, and red is higher delta-v.
This means that the more right you go on the plot, the later is your departure, and the higher you go the longer is the flight. Selecting blue areas means you need less delta-v.
The "Lowest dv" button automatically chooses the most delta-v efficient transfer.
You can also scroll into he plot to see some areas in greater detail using the mouse wheel.


iOS AppDelegate didReceiveRemoteNotification not triggered with silient push on cellular network in background

Question: I have an application that receives silent push notifications from Firebase and triggers upload by URLSession with background configuration.
Everything works well on WiFi network, application woke up in the background, didReceiveRemoteNotification triggered and upload request is preparing.
But after disabling WiFi, on the cellular network it's not happened and continues immediately after WiFi-enabled and connected...
Answer: Make sure you have turn on background refresh for cellular data too. You can turn on from following:
Settings > General > Background App Refresh:
Off
Wi-Fi
Wi-Fi & Cellular Data
Comment: yes, thanks, of course it's turned on, i have tested it on several devices, but with no success...


How to select an item from a filling of a DataGridViewComboBox

Question: Project: Winforms, .NET framework: 3.5 (Visual Studio 2008)
My problem is:
I have a DataGridView with several columns, some of the type and another type DataGridViewTextBoxColumn, DataGridViewComboBoxColumn, DataGridViewComboBoxColumn column is filled by an entity supplied by the Entity Framework.
// Example
((System.ComponentModel.ISupportInitialize)(this.EntityBindingSource)).BeginInit();
this.EntityBindingSource.DataSource = this.dtContext.ExampleEntity;

this.ComboColumn.DataSource = this.EntityBindingSource;
this.ComboColumn.DataPropertyName = "ExampleId";
this.ComboColumn.DisplayMember = "Example";
this.ComboColumn.ValueMember = "ExampleId";

When you run and load the form, fine
But the problem comes when at runtime I want to select an item from the collection of DataGridViewComboBoxColumn
That in the event CellEndEdit
private void dgvDetalle_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
   DataGridViewCell cell = dgvDetalle.CurrentCell;
   DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)this.dgvDetalle.CurrentRow.Cells["ComboColumn"];

   // Attempt 1
   comboCell.Value = (ExampleEntity)comboTarifaImpuesto.Items[0];

   // Attempt 2
   comboCell.Value = ObjetoEntity;

   // Attempt 3
   comboCell.Value = "ValueExample"

   // Attempt 4
   comboCell.Value = ObjetoEntity.ToString();
}

Try selecting one item from combobox
Try selecting an object of the entity
Try selecting by means of a chain or Display Member Value

and I can not select the desired items, I get the exception:

DataGridViewComboBoxCell value is invalid
Answer: thanks to assistance provided in another question:
DataGridViewComboBoxCell Binding - "value is not valid"
I could fix it, tube to re-enter the following properties of DataGridViewComboBoxCell:
comboCell.DisplayMember="Example";
comboCell.ValueMember="ExampleId";

as I had specified in the type column DataGridViewComboBoxColumn
I already worked with this property correctly. Value
comboCell.Value = ObjetoEntity.ExampleId.ToString();


Application 32/64 bit and OS 32/64 bit

Question: I would like to know the following things :

Can a 32 bit application run under a 32-bit operating system?
Can a 32 bit application run under a 64-bit operating system?
Can a 64 bit application run under a 32-bit operating system?
Can a 64 bit application run under a 64-bit operating system?

Thank you.
Comment: It depends a lot of the operating system, and what you call an operating system.
Comment: yes, (typically)yes, no and yes
Comment: 62bit? Really funny.....
Comment: "Can a 32 bit application run under a 32-bit operating system?" is a very odd question; how could the answer ever be "no"?.  Suggests you do not know anything about what the words "application" and "operating system" mean.
Answer: Yes. If not directly (case 3 is tough), then by means of emulation/virtualization.
Answer:
Yes, of course...
Yes
No
Yes of course...

Maybe you should read something about computers, CPUs and x86 acrhitecture in general.
Answer: 1) Yes
2) Yes
3) No (As said above without running a virtual machine or emulating or something)
4) Yes
http://www.techsupportalert.com/content/32-bit-and-64-bit-explained.htm
There is some reading for you to help with why :)
Answer: Yes
Yes
No
Yes
In a 32 bit system and application , variables are of size "x".
In a 64 bit system and application , variables are of size "2x"
thus a pointer in a 64 bit system can point to twice as much data as a pointer in a 32 bit system ... thats why a pointer in a 64 bit system can access anything in 32 bit application and in a 32 bit system a pointer can access only access half of the data it is supposed to in a 64 bit application...

Application 32/64 bit and OS 32/64 bit


Is there any way to control how fast Wild Gunman fires with Duck Hunt's Down B?

Question: Duck Hunt has a Down B that summons a random Wild Gunman, each of which seem to have their own damage percent and fire rate.
Is there any way to make the gunman fire early, or to control which Wild Gunman Duck Hunt summons?
Is there any pattern to which gunman appears when the Down B move is used, or is it completely random?
Answer: Each of the individual gunmen has their own independent damage and firing speed. It is not possible to alter when they shoot, or control which one appears.
The specific gunman that appears is random, but with limitations - all five must appear before one can appear twice. Or in other words, they're like a deck of cards - draw one of the five without replacement every time you use the move, and shuffle them again after the fifth time.


DRY principle for useState in React?

Question: I am learning react and trying to wrap around my head on the best practices for creating multiple useStates that essentially do the same thing except for different items in my code.
For example, my code is the follow:
import { Button, Typography } from '@mui/material';
import { Box } from '@mui/system';
import React, {useState} from 'react';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import FormControl from '@mui/material/FormControl';
import Select from '@mui/material/Select';

export default MenuPage(){

   const menuItems = [
    {
        name: 'Americano',
        price: 1.50,
    },
    {
        name: 'Espresso',
        price: 3.50,
    },
    {
        name: 'Macchiato',
        price: 5.50,
    },
    {
        name: 'Cafe Mocha',
        price: 8.50,
    },
    {
        name: 'Latte',
        price: 6.50,
    },
    {
        name: 'Cappucino',
        price: 5.50,
    },
    {
        name: 'Frappe',
        price: 8.50,
    },
];

//*********************************************
// code that needs to be changed here instead of creaing n many useStates for n many items in menuItems list.

   const [order, setOrder] = useState('');

   const handleChange = (event) => {
    setOrder(event.target.value);
   };

//*********************************************

return(
     {menuItems.map((item) => {
            return (
                <Box display='flex' flexDirection='row' alignItems='center' justifyContent='center' textAlign='center' borderBottom='0.5px solid black' sx={{ my: 10, mx: 10 }}>
                    <Box flex={1} textAlign='center' sx={{ fontSize: '35px', }}>
                        {item.name}:
                    </Box>

                    <Box flex={1} textAlign='center' sx={{ fontSize: '25px' }}>
                        ${item.price}0
                    </Box>
                    <Box flex={0.5} textAlign='center'>
                        <FormControl fullWidth>
                            <InputLabel id="demo-simple-select-label">Order</InputLabel>
                            <Select
                                value={order}
                                label="Order"
                                onChange={handleChange}>
                                <MenuItem value={1}>1</MenuItem>
                                <MenuItem value={2}>2</MenuItem>
                                <MenuItem value={3}>3</MenuItem>
                            </Select>
                        </FormControl>
                    </Box>
                </Box>

            );
        })}

);
}

So my question is that instead of creating n many const [nthOrder, setNthOrder] = useState('') whats the best way to create as many useStates for each order ? I know we cannot run useState in a callBack or in forloops.
Thanks for your help in advance.
Comment: May be in this scenario, you could add a prop named `order` to your `menuItems` array programmatically like so: `{menuItems.map(it => ({...it, order: ''})).map((item) => {`. Now, within the JSX for select: `<Select name={item.name} value={item.order}`. And, finally `handleChange` can use `event.target.name` to get the exact menuItem and update the order to it.
Answer: My solution is to maintain the menuItems as a state of the component. Add the order field to each menu item. Put the state and its CRUD logic into a custom hook, keep your component clean.
import React, { useState } from 'react';

function useMenuItems() {
  const [menuItems, setMenuItems] = useState([
    { name: 'Americano', price: 1.5, order: '' },
    { name: 'Espresso', price: 3.5, order: '' },
    { name: 'Macchiato', price: 5.5, order: '' },
    { name: 'Cafe Mocha', price: 8.5, order: '' },
    { name: 'Latte', price: 6.5, order: '' },
    { name: 'Cappucino', price: 5.5, order: '' },
    { name: 'Frappe', price: 8.5, order: '' },
  ]);

  const setOrderForMenuItem = (nOrder, itemName) => {
    setMenuItems((pre) => {
      return pre.map((v) => (v.name === itemName ? { ...v, order: nOrder } : v));
    });
  };

  return { menuItems, setOrderForMenuItem } as const;
}

export default function MenuPage() {
  const { menuItems, setOrderForMenuItem } = useMenuItems();

  const handleChange = (event, item) => {
    setOrderForMenuItem(event.target.value, item.name);
  };

  return (

      {menuItems.map((item, i) => {
        return (
          <select
            data-testid={`menu-order-${i}`}
            key={item.name}
            value={item.order}
            onChange={(e) => handleChange(e, item)}
          >
            <option value={1}>1</option>
            <option value={2}>2</option>
            <option value={3}>3</option>
          </select>
        );
      })}

  );
}

Answer: If you want to have several orders in the same state, you can set the state as array and add the order to the array.
   const [order, setOrder] = useState(['']);

   const handleChange = (event) => {
    setOrder(prevState => { return [...prevState, event.target.value]});
   };

In this example you can see that i use the spread operator to return a new array with the previous values plus the new value, that way you can avoid the repetition.

DRY principle for useState in React?


Desktop doesn't load

Question: I installed Ubuntu 12.10 yesterday and today when I try to login my desktop interface doesn't load. I only see my wallpaper and my one icon (steam) on it, but I don't see left/top taskbars. Please help.
my computer specs:
proc: Intel Core 2 Duo E8400 3GHz
graphics: ATI HD 6850
mainboard: Asus P5K PRO
RAM: 6GB

Comment: Can you add a little more info, especially regarding your graphics card and whether you installed drivers for it
Comment: Yes, i tried installing some graphic drivers in order to get better performance in Team Fortress 2. I wrote the details on [Steam Forums](http://steamcommunity.com/app/440/discussions/0/864959809894014925/)
Comment: I will post my hardware here too:
ATI HD 6850
Intel Core 2 Duo E8400 3GHz
6 GB of RAM
Asus P5K PRO
Comment: I am struggling to find a definitive answer on Ask but there are several including this http://askubuntu.com/questions/202857/cant-install-ati-proprietary-drivers-in-12-10 . The key seems to be `sudo apt-get install linux-headers-generic`
Comment: Thank you Chris, this solved my problem with installing ATI driver.
I also found solution for invisible taskbar in Unity 3D, thank you all for help. This is the magic that solved my problem (that Unity 3D desktop wasn't showing up properly):
I wrote these commands in terminal, one at a time:
"sudo apt-get purge fglrx lightdm"
"sudo apt-get install lightdm ubuntu-desktop"
Comment: Glad to of been of help, enjoy Ubuntu :)
Answer: Try to select at the loginscreen Unity 2D (this is done via the little 'radar-icon' nearby your login name (the one were you type in your name and password)
If this loads correct, you can adjust some things so Unity 3D loads properly. I suspect the Steam-program got a little bit in the way with something. (This you have to test over and over again)
If Unity 2D doesn't load:
Can you start up in recovery mode ?

To achieve this simply open up Grub (after Bios-screen press and hold SHIFT) and select the recovery modus. From there on you can try to initialise Unity again.

We need a bit more information, I see you've installed Steam is that program shut down correctly before you quited Ubuntu ?
Apparently it's clear that Unity doesn't load fully; so if tweaks were made (e.g. CCSM used) it could be they are in the way of things.
Comment: see also Chris Carter's comment please
Comment: There is no Unity/Ubuntu 2d with 12.10. 12.04 was the last to have it.
Comment: Yea i don't see any "unity". I installed gnome (according to Michael post) but want the default one (it's called "ubuntu" too i think) cause i like it more.
Earlier i tried to install graphic drivers, i wrote the details on [Steam forums](http://steamcommunity.com/app/440/discussions/0/864959809894014925/)
Answer: I was having the same issue earlier and never quite fixed it. I did, however, simply install a different GUI to replace the default one which kept disappearing on me.
So just open up the terminal after you've logged in and the GUI still hasn't appeared and type in sudo apt-get install gnome-shell
Once it's done, reboot and chose one of the GNOME settings in the dropdown menu instead of Ubuntu when you log in.
Answer: Write in console these commands, one at a time:

sudo apt-get purge fglrx lightdm
  sudo apt-get install lightdm ubuntu-desktop

Desktop doesn't load


Do I need to leave space between insulation and the roof deck with a cathedral ceiling?

Question: I'm finishing a 14x14 shed that has 2x6 rafters in Austin TX, and I want a cathedral ceiling. The shed builder says they usually recommend filling the cavity with R-19 fiberglass insulation, leaving no room for airflow.
But I've also read many suggestions like this for vaulted ceilings:

Remember that a two-inch breathing space between the insulation and the roof sheathing must be included to allow for ventilation.

If I leave room, it's hard to fit more than R-13 without going to rigid foam board.
Do I really need the space? I don't have any venting. And I don't envision having much excess moisture in the shed, as it's going to be an office. Does that apply more to cold climates, where moisture becomes an issue as the hot inside air meets cold outer air?
Edit: The roof appears to be OSB.
Comment: @ThreePhaseEel Ah. Shingles (presumably asphalt).
Comment: A bit of air would help in cooling down the roof deck.  Austin TX, hot hot sun beating down, bet you could fry an egg on roof.  Think what that would do to asphalt shingles.
Comment: Hmm it might help the roof longevity, but at the cost of heating up the interior, which is not what I want. Better to put elastomeric paint over the shingles if that's what I'm trying to solve.
Comment: If you use white paint, that will probably be more helpful than an extra R 7.  Just need about an inch of air, so maybe just foam or a mixture.
Comment: The crux of my question is whether that inch of air is even necessary. Right now I'm thinking it's not.
Comment: Probably not.  That inch of air would probably reduce the temperature on top of insulation by quite a few degrees, reducing the need for extra R value and maybe a few extra years of life for the roof.  Could also nail 2x2s, or 2x3s to rafters to give more space, imagine a couple of inches will not cause headaches.
Comment: If you are in a particularly hot climate the air gap and extra insulation may be necessary as well, especially if you intend to cool the place.
Comment: What material are you planning to use for the roof sheathing? Asphalt shingles? Metal roofing of some sort? Something else?
Comment: @KH I think Austin qualifies as "particularly hot." I've found 8.25" fiberglass and 7.25" rock wool at R-30 (but it's more expensive). So for fiberglass it sounds like I'd have to add at least (8.25-5.5+1) = 3.75" of spacing to make this work well? BTW I'm having my drywall guys do it. I suppose they probably know how to add furring or whatever?
Comment: @ThreePhaseEel Good question! I've updated the post to show an image. Appears to be OSB :(
Comment: @KH Or maybe just use 5.5" R-21 and add furring(?) to the rafters to give that extra inch for breathing. Kinda leaning that way right now.
Comment: @A_P -- that OSB is the roof decking, sorry about my terminology, I meant the roof cladding
Comment: Update: the only material available at any nearby Lowe's or HD is R-30 rockwool at 7.25". So I'll use that with an inch above and call it good I think!
Answer: Yes, cold climates require the insulation in walls to dry towards the outside through breathing gaps in the sheathing, with a vapour barrier separating the insulation from the warm inside moisture.
Roofs are similar, where ventilation is provided through soffits and ridge or gable vents.
Also, the airflow from soffit to gable provides for cooling (!) of the shingles in the winter. Otherwise warmth from the house would melt the snow near the top where heat accumulates, and melt water would re-freeze towards the bottom of the roof, causing ice and ice-dams to form.
In a hot and dry climate I could imagine that the convection through the roof's air gap will more than offset the reduced insulation.
A compromise is to leave a gap and slightly compress the R19 insulation with strapping (length- not cross-strapping, applied in the direction of the slope).
The R value will drop a bit due to compression, but it will be better than R13.
A rule of thumb is that for every 2 inches compressed you loose only 1 inch of equivalent R-value.
Additional insulation from heat can be obtained with reflective foil insulation (e.g. Reflectix) applied to the roof sheathing on the inside.
Comment: Thanks! Unfortunately there is no venting. I can't find any 4.5" thick insulation, so I think my choices are (1) 5.5" with no air gap (R-21), (2) 5.5" but add an inch to the rafters for air gap, (3) add a few inches to the rafters and fill it with R-30, (4) add a few inches plus one for R-30 plus air gap. Right now I'm leaning toward (3) to balance insulation and ceiling height. What would you choose?
Comment: @A_P what do you mean with "add a few inches to the rafters", upgrade from 2x6 to 2x8?
Comment: The structure is already built (see first link), so I guess they'd have to add furring?
Comment: @A_P, ah, yes, ok. I am not familiar with building in your climate, but I still think the airflow will be better for summer cooling and for the life of your roofing.  So (2). You can also ask a local roofing company for a 2nd opinion.


How can you get fire/cold resistance in WazHack?

Question: In Wazhack cold resistance is pretty damn useful as being frozen by a winter wolf can be a death sentence, not to mention annoying. Fire resistance is also very, very useful.
You can sometimes get fire resistance by eating Hellhound remains.
You can sometimes get cold resistance by eating Winter Wolf remains.
There is also a ring of fire resistance.
Is there any other way to get fire/cold resistance, especially cold resistance?
Answer: I have discovered that also eating brown molds can give you cold resistance, very handy.
Comment: Positive effect seems to correlate to  seeing the message "you feel full of hot air"
Comment: Have found it best to keep the blob of brown mold goo until its status is "old" - fresh never seems to work
Answer: There is a potion of fireproofing. Not sure if you can quaff it and become inherently fireproof, but pour it on a hat or cape and it seems to work to good effect. The message will run something like "your feathered cap looks moist". Also good on a bag of swag. Then in the midst of a gang attack of monsters may ye read the blessed scroll of fire with impunity. Well, assuming you fireproof your scrolls or keep them in the fireproof bag.
Have also noticed that when you eat a blob of goo from an acid blob, it will sometimes (p~0.1?) cause the message "you feel a momentary chill", which may relate to subsequently observed fire resistance.


How to UPDATE `table` SET the_col = current_timestamp in Laravel

Question: How to do this mysql query in laravel?
UPDATE table SET the_col = current_timestamp
Comment: thanks for the advice ^^ but I rather keep the question short cause I already searched for it but found none, but havent tried by myself yet, so i posted it first and then try by myself
Answer: You can do like this
DB::table('table_name')->where('condition','vlaue')->update(['col1'=>'val1', 'col2'=>'val2']);

For more please have a look at this
EDIT:
 DB::table('table_name')->update(['accept_time' => DB::raw('CURRENT_TIME')]);

Comment: okay have you tried like this.  update(['accept_time' => DB::raw('CURRENT_TIME')]); Also look at my edit
Comment: Yeah, but how to use current_timestamp that mysql provided, I searched on doc and google but dont have any idea on updating by using current_timestamp value
Comment: you want to update timestamp colums like 'created_at' and updated_at?
Comment: hmm maybe? but its not always updated when it is updated? its like accept_time when it is accepted the accept_time col will be updated
Comment: Yeah that worked, Order::where('id','selected')
            ->update(['accept_time'=>DB::raw('CURRENT_TIMESTAMP')]); Thanks sir, for helping


Codenameone UIDesigner out of sync with file

Question: I'm developing a Codenameone app using Eclipse, Git and Bitbucket.
I'm doing work on two computers, one at my home office and one laptop when I'm on the go.  Therefore I use Git and Bitbucket to ensure that my files are kept in sync across both computers.
I've run into a strange issue with the UIDesigner on my laptop.  It seems that it has cached an old version of the .res-file and when I open the file with the UIDesigner I see old design in it.  My changes from the other computer are not visible in the designer.  I have tried to copy the file to a new filename and open that new file and then I see the changes, so therefore I suspect some caching of the file contents are going on.
Is there a way to disable the caching (at least temporarily) and ensure that the UIDesigner actually reads the file contents from disk?
Answer: The "simple" solution is to commit the res directory or turn off the File->XML Team Mode in the designer.
The res file is a binary file which makes working with versioning systems hard. That's why we effectively "shadow" it using the res directory where its content is "exploded" as XML and data files to prevent conflicts.
So if you have 2 people on the team who modified the res file you can just pick any version in the merge but merge the res folder properly. Then when you open the designer and save the res folder will be preferred and as you save the binary res file will be recreated.
If you are working on the project alone you can just turn off team mode to avoid the noise of additional files.


Laravel + Nginx. Session is accessed randomly

Question: We have an app build in laravel and we are trying to switch from apache to nginx but when we enable the nginx, the users are getting logged into random users account on every refresh.
For example,
I am logged in as USER1, refresh the page and now I am in USER2 account, USER3 account randomly.
We are using redis as session driver.
Thanks.
Answer: For those facing the same problem. This happens because Nginx cached both static and dynamic content of the website. What you have to do is just disable the dynamic caching and everything will work normally.
We used the Engintron plugin for WHM so I can tell you the configuration for that.
Edit common_http.conf file and set this value to 1
set $CACHE_BYPASS_FOR_DYNAMIC 1;


Metronome for Gnome desktop

Question: Does anybody know about a metronome that resembles a real one? Look at this online version http://simple.bestmetronome.com/ That is exactly what I am looking for, but installable instead of online. Thnx.
Comment: Does this answer your question? [Where can I find a metronome for music practice?](https://askubuntu.com/questions/814759/where-can-i-find-a-metronome-for-music-practice)
Answer: I'd suggest the simple gtick application:

I does not provide an animated picture of a real metronome but does the job.
From a terminal:
sudo apt-get install gtick

Comment: Actually, I have already downloaded that one, as well as gtklick, both of them do the job.
Comment: haha sure dude, I knew about that one but at least you showed some interest on my post.
Answer: You can use GNOME Metronome.

 GNOME Metronome on Kubuntu 22.04.
It is available on the official repositories.
sudo apt install gnome-metronome

The latest version is available on Flatpak.
flatpak install flathub com.adrienplazas.Metronome

Metronome for Gnome desktop


Strange font rendering after installing Dolphin

Question: After installing and testing KDE's Dolphin for a while the font rendering (or maybe anti-aliasing?) in non-GTK (e.g. Chrome and Thunderbird) programs looks strange. Playing around with QT(4) and KDE settings didn't help.
Example of right render in Nautilus and the wrong in Thunderbird:
Comment: I half remember something similar --- it was something that created a `~/.fontconfig/*` file and getting rid of it solved the problem. But I am not sure --- so a comment and not an answer.
Comment: Thanks a lot! Deleting a file called fonts.conf with wrong AA instructions helped to fix the issue.
Answer: Like Rmano guessed I had to delete ~/.config/fontconfig/fonts.conf which included (wrong) settings for the antialiasing of fonts. Any problematic program started after deleting that file, rendered the fonts right again.
Answer: If the config file mentioned in Marvin Janosch's answer doesn't exist, configuration can also be adjusted using Unity Tweak Tool.
Go to Fonts, and under Appearance, adjust Hinting.


Change background color of embedded Terminal in Android Studio

Question: Currently this is the appearance of my embedded Terminal in Android Studio, very unconfortable when reading. Can someone help me to strip out the black background around the characters?
Thanks in advance!
Answer: Make Foreground colours of standard output and system output of Console Colors to white.

If you are using windows machine, you can change the font colors of the PowerShell/cmd.


FML appears to be missing any signature data. This is not a good thing (?)

Question: I installed a fresh Forge (1.8.9-18.104.22.1682) server (with Sponge 1.8.9-1691-3.1.0-BETA-1046). The host (running Debian) is headless, Minecraft starts correctly, but one line in the startup log is worrisome:
[main/ERROR] [FML]: FML appears to be missing any signature data. This is not a good thing

There are no more errors (only INFO messages). I believe that FML means Forge Mod Loader, which then appears with its own log messages (like [FML]: Forge Mod Loader has successfully loaded 4 mods) and otherwise the server works fine (at least seems to do so, I connected from a client and walked around without issues.
Is this something I should be worried about?
Comment: Did some googling... are you using the original launcher? It sounds like you shouldn't be worried unless the game breaks.
Comment: @aman207: I googled the message as well but found nothing. I use a headless server, not sure what you mean by "original launcher"? (sorry, this is my first minecraft server and I went according to the docs - I will update my question with these two points)
Answer:
Is this something I should be worried about?

[main/ERROR] [FML]: FML appears to be missing any signature data. This is not a good thing

tl;dr, Nope.
Unless you have downloaded Minecraft Forge from a sketchy location, it's something you do not need to be worried about.
That basically means that it could not verify the file's integrity. It's nothing important, unless you're wary of viruses, etc.
Also, this error mostly happens when you use the Universal version of Forge.
The only thing you need to worry about is whether the game server runs or not (throws an exception and goes to the console/launcher/crash screen).


Print String with Space in it

Question: When i try to output the string it doesnt output the text after the space. It should ask for student name and then output it when asked. This is C++. I have no more info to give but the site wont let me post it so this sentence is here.
/***************************************************/
/* Author:     Sam LaManna                         */
/* Course:     CSC 135 Lisa Frye                   */
/* Assignment: Program 4 Grade Average             */
/* Due Date:   10/10/11                            */
/* Filename:   program4.cpp                        */
/* Purpose:    Write a program that will process   */
/*             students are their grades. It will  */
/*             also read in 10 test scores and     */
/*             compute their average               */
/***************************************************/

#include <iostream>     //Basic input/output
#include <iomanip>      //Manipulators

using namespace std;

string studname ();     //Function declaration for getting students name

int main()
{
  string studentname = "a";     //Define Var for storing students name

  studentname = studname ();    //Store value from function for students name

  cout << "\n" << "Student name is: " <<studentname << "\n" << "\n";     //String output test

  return 0;
}

/***************************************************/
/* Name: studname                                  */
/* Description: Get student's first and last name  */
/* Paramerters: N/A                                */
/* Return Value: studname                          */
/***************************************************/

string studname()
{
  string studname = "default";

  cout << "Please enther the students name: ";
  cin >> studname;

  return studname;
}

Comment: possible duplicate: http://stackoverflow.com/questions/8052009/returning-a-string  (same problem, different context)
Answer: You should use the getline() function, not the simple cin, for cin only gets the string before white space.
istream& getline ( istream& is, string& str, char delim );

istream& getline ( istream& is, string& str );

Extracts characters from is and stores them into str until a delimiter character is found.
The delimiter character is delim for the first function version, and '\n' (newline character) for the second. The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.
If the delimiter is found, it is extracted and discarded, i.e. it is not stored and the next input operation will begin after it.
Answer: you can use getline so like this
string abc;
cout<<"Enter Name";
getline(cin,abc);
cout<<abc;

Getline
Answer: Another alternative is to use the std::strings getline() function like this
getline(cin, studname);

This will get the whole line and strip of the newline. But any leading/trailing spaces will be in your string.
Answer: cin likes to break things up by whitespace, so that is why you are only getting one name. Likely, since the assignment is telling you to grab the first and last name, you can likely assume that these will be separated by whitespace. In this case, you can just grab both separately, then concatenate them:
string firstname = "default";
string lastname = "default";

cin >> firstname >> lastname;

return firstname + " " + lastname;

Answer: To get an entire line, you'll want to use getline instead of >>:
getline(cin, myString);

Print String with Space in it


How to remove bathtub drain flange with nubs?

Question: I have a non-standard bathtub drain flange that I'd like to replace (and also clean up the rust) that has a pair of interior nubs.  The drain is 1.75 inches in diameter, and the nubs sit about 0.5 inches down from the top of the flange.

I saw two previous questions (one and two) that describe removing a flange with no crossbars/spokes, but can I take advantage of these nubs and use common tools to remove the flange?  I'm concerned that the nubs will even disallow the use of an expanding plug.
EDIT:  Also, it would be very difficult to remove the drain with channel locks due to how it's seated in the tub.
Comment: @AloysiusDefenestrate with a generous amount of penetrating oil the tool you suggested did end up working!  Bits of the handle broke off where the breaker bar contacted it but eventually it gave.  If you provide an answer I'll mark it accepted.
Comment: I would just grab a piece of steel flat bar and use it like a big screwdriver, but I have tons of scrap metal to use. There is a universal tool that most plumbing or big box stores have it will lock onto cross bars or nubs in this case.
Comment: Universal tool: https://www.amazon.com/Superior-Tool-Wrench-Dumbell-Ratchet/dp/B000AO193S (absolutely not an endorsement of that particular one or amazon)
Comment: @EdBeal Good idea -- I just don't have the appropriate scrap metal lying around; most everything I have is sheet metal scraps.
Comment: @AloysiusDefenestrate I actually bought one of those to put in the new drain, which has crossbars.  When I tried it on the nubs it barely caught, and I fear that the tool and/or nubs will be damaged if I put any torque into it.
Comment: @calcium3000 there's every chance the nubs will break off, then you'll be back to some of the other methods. (The tool itself is very unlikely to break.) I'd say 'go for it'.
Answer: You CAN use Channellock type pliers, just not the way in the linked picture/answer shows. You use the handles of the pliers, adjusted to the width of the throat of the tub drain, as spanners. Insert the handles into the drain so they are against the nubs, then turn those pliers by putting a pipe wrench, large adjustable wrench, or another set of pliers on the jaws of those pliers (which are pointing up) and turn counter-clockwise.
I have removed numerous tub drains using this method.


Cross domain Angular JSONP request to Python Bottle

Question: I'm trying to do a cross-domain JSONP request with AngularJS to Bottle, but I'm getting an error.
Angular:
<code>// this angular code is on localhost:8888, so it's cross domain

var URL = "http://localhost:8000/test";
    URL = $sce.trustAsResourceUrl(URL);

$http.jsonp(URL, {jsonpCallbackParam: 'callback'})
.then(function successCallback(response) {
    console.log(response);
}, function errorCallback(error) {
    console.log(error);
});
</code>
Bottle:
<code>@route('/test')
def test():
    response.headers['Content-Type'] = 'application/json'
    return json.dumps({"random": "JSON"})
</code>
Error:
Answer: You need to return an JavaScript application (wrapper function in this case) not an json object. This site explains you the basics of JSONP handling.
<code>def jsonp(request, dictionary):
    if (request.query.callback):
        # wrap the dictionary in the callback parameter
        return "%s(%s)" % (request.query.callback, dictionary)
    return dictionary

@route('/test')
    if (request.query.callback):
        response.content_type = "application/javascript"
    return jsonp(dict(success="It worked"))
</code>
Comment: Perfect! Thank you!
Comment: Will do! It never really occurred to me to do it before for some reason..
Comment: It seems for me, request.query.callback is not (equivalent of) True, even though I call with jQuery AJAX `jsonp`. Any idea what's going on?


Can I have more than one submit that almost does the same action?

Question: I have a form that is submitted, it show all the comments from a table
which are showing properly and able to submit good.
I would like to add ( if possible ) a submit button for EVERY comment that
display. In the original code below it has one submit button, so when a user
click on it it will submit all comments.
I would like it to be a option to have 'submit all' button and
'submit' individual comment, if this is possible?
What would be the best way to approced this?
<form method="post" action="cse_execoffice_pending.cfm" name="review_comments">
<cfoutput>
<input type="hidden" name="txtApprovedBy" value="#GetCurrentUser.emp_id#">
<input type="hidden" name="txtTotalRecords" value="#Mush2.Recordcount#">
</cfoutput>
<cfoutput query="Mush3">

            <input type="hidden" name="txtResponseID#CurrentRow#" value="#response_id#">
            <input type="radio" name="execoffice_status#CurrentRow#" id="approve#CurrentRow#" value="1" checked="checked"> Approve

            <input type="radio" name="execoffice_status#CurrentRow#" id="deny#CurrentRow#" value="2"> Deny

        <div class="clearfloat<cfif (#commentpositive# eq '')> hideempty</cfif>"> Positive Comments:

        <cfset reReplaceCommentpositive = reReplace(commentpositive, '
', '', 'ALL')>
        <textarea rows="3" name="txtCommentPositive#CurrentRow#">#reReplaceCommentpositive#</textarea>

        <div class="clearfloat<cfif (#commentnegative# eq '')> hideempty</cfif>"> Negative Comments:

        <cfset reReplaceCommentnegative = reReplace(commentnegative, '
', '', 'ALL')>
        <textarea rows="3" name="txtCommentNegative#CurrentRow#">#reReplaceCommentnegative#</textarea>

Rating	Question

        <cfloop index="i" from="1" to="5">
        <cfset rating = Mush3["rating" & i][Mush3.CurrentRow]>
        <cfset question = Mush3["csedept_question" & i][Mush3.CurrentRow]>

                    <cfif #rating# eq 5></cfif>
                    ........more code ...

                #question#

        </cfloop>

</cfoutput>

<input type="submit" name="Submit" value="Submit">

</form>

Answer: Yes you can...Here is a simple example of using buttons to do different things (in the same form).
<cfif form.action is "insert">

</cfif>
<cfif form.action eq "update">

</cfif>
<cfif form.action eq "delete">

</cfif>
<form action="">
    <input type="submit" name="action" value="insert">
    <input type="submit" name="action" value="update">
    <input type="submit" name="action" value="delete">
</form>

More:
You asked if you can submit a record without spinning through all the others. Right?
In that case you need to wrap your cfoutput tag around your form.  You will spawn many forms. Notice that I have a unique name for each form when I loop over the recurs using your currentrow as a unique-ifyer :) I rendered your form to a basic example so you can see without all that other stuff...
<cfoutput query="Mush3">
<form method="post" action="" name="comments#CurrentRow#">
<input type="hidden" name="txtApprovedBy" value="#GetCurrentUser.emp_id#">
<input type="hidden" name="txtTotalRecords" value="#Mush2.Recordcount#">
<input type="hidden" name="txtResponseID#CurrentRow#" value="#response_id#">
Approve or Deny:

<input type="radio" name="execoffice_status#CurrentRow#" id="approve#CurrentRow#" value="1" checked="checked">Approve

<input type="radio" name="execoffice_status#CurrentRow#" id="deny#CurrentRow#" value="2">Deny

Positive comment:

<textarea rows="3" name="txtCommentPositive#CurrentRow#">#reReplaceCommentpositive#</textarea>

Negative comment:

<textarea rows="3" name="txtCommentNegative#CurrentRow#">#reReplaceCommentnegative#</textarea>

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

If you take this basic example.  Add a
<cfdump var="#form#">

You will see you have a unique set of form data for only one form / currentrow.
And I believe that is what you are looking for, yes?
Comment: i see but can it be done for each individual comment, like it will be submitter for each comment or submit all
Comment: @yes i was asking if i could add a record without spinning through all the others, and it the end have a submit that you can submit them all
Comment: with all the changes , gives me erros
Comment: Refactoring code is not fun. I assume the code that processes the form is expecting something different than what you are feeding it? I would approach the problem like this. Get your cfoutput loop to spawn the individual forms in a new page. Inspect the form and determine if all the variables look correct (view the clientside source). Populating properly? Then make a new form processing page that matches the data you are trying to submit. If you can create a new question with your new form and form process code fresh eyes can make suggestions.


Go gorilla websocket write deadline

Question: I am unable to understand this part of the code which uses c.conn.SetWriteDeadline function.

    // Time allowed to write a message to the peer.
    writeWait = 10 * time.Second

    // Time allowed to read the next pong message from the peer.
    pongWait = 60 * time.Second

    // Send pings to peer with this period. Must be less than pongWait.
    pingPeriod = (pongWait * 9) / 10

// A goroutine running writePump is started for each connection. The
// application ensures that there is at most one writer to a connection by
// executing all writes from this goroutine.
func (c *Client) writePump() {
    ticker := time.NewTicker(pingPeriod)
    defer func() {
        ticker.Stop()
        c.conn.Close()
    }()
    for {
        select {
        case message, ok := <-c.send:
            // LOGIC TO WRITE MESSAGE TO THE CONNECTION
        case <-ticker.C:
            c.conn.SetWriteDeadline(time.Now().Add(writeWait)) //  ??
            if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
                return
            }
        }
    }
}

I am unable to wrap my head around the ticket channel logic. What are we trying to achieve here?
I am referring to the official docks for go/gorilla/websocket here
Answer: From the SetWriteDeadline function documentation:
SetWriteDeadline sets the write deadline on the underlying network connection.
After a write has timed out, the websocket state is corrupt and
all future writes will return an error.
A zero value for t means writes will not time out.

So every ticker on the goroutine it is setting the write deadline to the current time plus whatever you have the writeWait const set to. The subsequent line then sends a ping message, with that deadline. This all happens on the ticker interval which is the const pingPeriod. The other go-routine, readPump(), should be setting a read deadline and handler for the pong message. This constant ping-pong keeps the connection alive according to the wait times you have set.

Go gorilla websocket write deadline


Integers $m$ and $n$ such that $9|(m + 2n + 1)$ and $9|(5m + n)$?

Question: I'm attempting to disprove this statement by contradiction and just want to check if what I've done makes any sense at all:
"There exists a pair of integers $m$ and $n$ such that $9|(m + 2n + 1)$ and $9|(5m + n)$."
Disproof:
For the sake of contradiction, assume there is a pair of integers $m$ and $n$ such that $9|(m+2n+1)$ and $9|(5m+n)$.
From here I was thinking I could do the following:
$$m+2n+1 = 5m+n$$
$$n=4m-1$$
So then, $$m+2(4m-1)+1 = 9m-1$$ and $$5(4m-1)=9m-1$$
As it is not the the case that $9|(9m-1)$, $m$ and $n$ does not exist.
Looking over this, I feel like there is a flaw in my first step. That I can't actually set $m+2n+1$ and $5m+n$ equal to each other. But I also am not sure where to start otherwise. I would appreciate some opinions. Thank you everyone!
Comment: Your last step is not valid either. You argue that $9$ does not divide the right side, but why should it divide the left side ?
Comment: **Hint** $\ 9\mid 5m\!+\!n\,\Rightarrow\, \color{#c00}n \equiv_9 -5m \,\Rightarrow\, m\!+\!\!\underbrace{2\color{#c00}n}_{-10m}\!\!+1 \equiv_9 1$ ($\not\equiv 0)\ \ $
Answer: If $9$ divides $(5m+n)$ and $(m+2n+1)$, then $9$ divides any  number of the form $A(5m+n) + B(m+2n+1)$ (can you see why?). What happens if you set $A=2$ and $B=-1$?
Comment: I forgot to thank you for your answer. I understand this concept a lot better now!
Comment: I suggest that this answer is accepted. Nothing to add. (+1)
Comment: @UnderMathUate. Good.
Answer: There is no way to deduce $b=c$ from the fact that $a\mid b$ and $a\mid c$. For instance $9\mid 18$ and $9\mid 27$.
What you can deduce is that there are integers $x,y$ such that
$$
m+2n+1=9x,\quad 5m+n=9y
$$
If you subtract the first equation from twice the second one, in order to eliminate $n$, you get
$$
9m-1=9(2y-x)
$$
Can you now see the contradiction?
Comment: Yeah, I could tell there was faulty logic in that statement but I wasn't sure where to go otherwise. This makes a lot more sense now!


Wav to Ogg or MP3 in PHP

Question: Is there any solution for converting Wav to Ogg or MP3 by using pure PHP?
Technically it's possible. But what about ready-made libraries?
Im talking about 1-7 sec wav.
Comment: I'd really really recommend against attempting this.  While it may be theoretically possible, the code would be extremely complicated, and PHP would run it really slowly.
Comment: None that I am familiar with. PHP wasn't really made for this. I usually do this type of stuff by sending it off to another program written in a different language.
Comment: check [here](http://stackoverflow.com/questions/5330486/how-to-convert-wav-to-mp3-file-in-php)
Comment: Unfortunally i havent access to server that i could install ffmpeg or something other. Maybe is there some algorithm of converting wav to ogg that could be implemented in PHP by for example me :d?
Comment: @KamilKrzyszczuk Surely your time could be spent wiser than to attempt wav conversion by yourself :)
Answer: Writing this in pure PHP will melt your brain for sure. That said, you can create a PHP extension wrapper around ffmpeg if you know enough C. That would probably be the most optimal.
Alternatively, you can just use exec() unless you want to distribute your code and hate to have this as a (reasonable) dependency.
In both cases you would need to have a working ffmpeg library installed on the server.
Disclaimer
I didn't read this answer before writing my own :)

Wav to Ogg or MP3 in PHP


Is $\prod_{i\in I}x_i$ equal to $1-\prod_{i\in I}(1-x_i)$?

Question: Are these 2 equations equivalent? If so how can I prove it, if not how can I disprove it?
$CI(t)=\prod_{t_i<t}(d_i/n_i)$
$CI(t)=1-\prod_{t_i<t}(1-(d_i/n_i))$
Comment: $ab \neq 1-(1-a)(1-b)$ in general
Comment: [Quick beginner guide for asking a well-received question](https://math.meta.stackexchange.com/questions/35391/quick-beginner-guide-for-asking-a-well-received-question) + please [avoid "no clue" questions](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question/27933#27933) (don't just ask, do some work), and don't use [the tag proof-writing](https://math.stackexchange.com/questions/tagged/proof-writing) to ask for a proof. And use a more descriptive title, and include the question in the body of the post.
Comment: Could you please delete the question? I can't unfortunately. @AnneBauval
Comment: [You cannot](https://math.stackexchange.com/help/deleted-questions) because it has an upvoted or accepted answer. Neither can I vote for its deletion because there is no Delete button yet on the line below it. I was only able to vote for its closure.
Answer: Just try it:
$$ab \stackrel{?}{=} 1 - (1-a) \cdot (1-b)$$
Well:
$1 - (1-a) \cdot (1-b) = 1 - (1 - a - b + ab) = a + b - ab \ne ab$
So, no. Those equations are not equal.
Comment: This question does not meet the [standards for the site](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question). Instead of answering
 (which encourages low-quality questions), why not look for a good duplicate target, or help the user by posting comments suggesting improvements? Please also read the [meta announcement](https://math.meta.stackexchange.com/questions/33508/enforcement-of-quality-standards) regarding quality standards.


Passing pointers to different variable types to a function and reuse them later for assignmet

Question: In a GUI based project I need Page1 to mark a variable to be changed and call Page2, Page2 reads user's input and updates the marked variable with the new value.
The variable type is always different and all the variables are held by an external linked library.
How to achieve that without creating fname_uint8, fname_uint16, fname_giventype variants for markers and setters?
This example sums up the scenario:
There is the VarHolder class that holds a lot of structs with a lot of variables, e.g.:
class VarHolder
{
public:
    typedef struct {
        int8_t var1;
        int16_t var2;
        int32_t var3;
        char str1[40];
        float var4;
    } struct1_t;
    /* ...continues... */

struct1_t struct1;
}

Now the class FirstStage wants to mark one variable for change, and calls a member of the committer_instance instance of the class Committer
class FirstStage
{
    /* ... */
    void doFirstStage(void)
    {
        /* Globally defined committer instance */
        g_committer_instance->mark_var_change(&varholder_instance->struct1.var1);
    }
}

Committer::mark_var_change(T*) is defined as follows:
template <typename T>
void Committer::mark_var_change(T *var)
{
    /* Store a pointer to the variable */
    /* SAVE SOMEWHERE PRESERVING TYPE */ = var;
}

A member of SecondStage, finally, wants to use a now available value to update the variable marked for change through the same g_committer_instance, like this:
class SecondStage
{
    /* ... */
    template <typename T>
    void doSecondStage(T new_value)
    {
        g_committer_instance->commit_change(new_value);
    }
}

where Committer::commit_change(T) is defined as follows:
template <typename T>
void Committer::commit_change(T new_value)
{
    /* Dereferencing the previously stored pointer */
    *(/*WHATEVER I STORED BEFORE*/) = new_value;
}

Of course what I am not able to do is realize a type-indipendent "marker and retriever" that can seamlessy update variable based upon their address.
Any suggestion is very much appreciated.
MCVE
### varholder.h
#include <stdint.h>
class VarHolder
{
public:
VarHolder() {}
virtual ~VarHolder() {}
typedef struct
{
int8_t var1;
uint8_t var2;
int64_t var3;
char str1[40];
} struct1_t;

struct1_t struct1;
}

### firststage.h
#include global.h

class FirstStage
{
public:
    FirstStage() {}
    ~FirstStage() {}

    void doFirstStage(void)
    {
        /* Globally defined committer instance */
        g_committer_instance->mark_var_change(&varholder_instance->struct1.var1);
    }
}

### secondstage.h
#include global.h

class SecondStage
{
    public:
    SecondStage() {}
    ~SecondStage() {}
    template <typename T>
    void doSecondStage(T new_value)
    {
        g_committer_instance->commit_change(new_value);
    }
}
### committer.h
#include global.h

class Committer
{
    public:
    Committer() {}
    ~Committer() {}
template <typename T>
void Committer::mark_var_change(T *var)
{
    /* Store a pointer to the variable */
    /* SAVE SOMEWHERE PRESERVING TYPE */ = var;
}

template <typename T>
void Committer::commit_change(T new_value)
{
    /* Dereferencing the previously stored pointer */
    *(/*WHATEVER I STORED BEFORE*/) = new_value;
}
}

### global.h

#include varholder.h
#include committer.h

extern Committer *g_committer_instance;
extern VarHolder *varholder_instance;

### main.cpp

#include global.h
#include varholder.h
#include firststage.h
#include secondstage.h

Committer *g_committer_instance;
VarHolder *varholder_instance;

int main()
{
g_committer_instance = new Committer();
varholder_instance = new VarHolder();
FirstStage *fstage = new FirstStage();
SecondStage *sstage = new SecondStage();

int8_t var_new = 100;

/* First stage */
fstage->doFirstStage();
/* Second stage */
sstage->doSecondStage(var_new);

return 0;
}

Comment: You may look at `boost::any`.
Comment: Please create an [MCVE](http://stackoverflow.com/help/mcve) that describes your problem.
Comment: Is there only one variable per type in `struct1_t`? If so, why not use a union? Also, what will be the behaviour if the type of `new_value` is not convertible to `varholder_instance->struct1.var1`
Comment: @Component10 nope, any number per type. the user of the facility has to check convertibility, anyway casting is done at compile time.
Comment: @TobiMcNamobi I added a MCVE as requested
Answer: You may use void* without (unsafe) or with typeid:
class Committer
{
public:

    template <typename T>
    void mark_var_change(T *var)
    {
        mPointer = var;
        mTypeInfo = &typeid(T*);
    }

    template <typename T>
    void commit_change(T new_value)
    {
        if (*mTypeInfo != typeid(T*)) {
            throw std::runtime_error("Bad type");
        }
        if (mPointer == nullptr) {
            throw std::runtime_error("nullptr was stocked");
        }
        *reinterpret_cast<T*>(mPointer) = new_value;
    }

private:
    void* mPointer = nullptr;
    const std::type_info* mTypeInfo = nullptr;
};

without typeid Live example
with typeid Live example

or a safer boost::any which manage by itself the type:
class Committer
{
public:

    template <typename T>
    void mark_var_change(T *var)
    {
        mPointer = var;
    }

    template <typename T>
    void commit_change(T new_value)
    {
        T* pointer = boost::any_cast<T*>(mPointer); // throw with bad type
        if (pointer == nullptr) {
            throw std::runtime_error("nullptr was stocked");
        }
        *pointer = new_value;
    }

private:
    boost::any mPointer;
};

Live example
Comment: Already tried the first solution, but even a typo would be fatal in that case, overwriting subsequent parts of the struct (if lucky)...does a non-boost boost::any exist by the way?
As of now boost is a non viable solution...
Comment: @FrancisStraccia: `void*` version modified to use `typeid` to check type.


PyWAVES: simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Question: import pywaves as pw

def main():
    node = "https://nodes.wavesnodes.com"
    chain = "mainnet"

    pw.setNode(node=node, chain=chain)

    private_key = #############
    my_address_statement = pw.Address(privateKey=private_key)
    WAVES_balance = my_address_statement.balance()

    print("Your WAVES balance is: %d." % WAVES_balance)
    main()

main()

Eventually this code produces the error indicated in the title. How can this be avoided?
Comment: For which part from the code does it throw this error?
Can you for example do a print(my_address_statement) ?
Also pywaves is default set on a node and on mainnet. So no need to reset it.

It would be good to have some added debug steps/ full error/stack trace
Comment: It looks like removing
```node = "https://nodes.wavesnodes.com"
    chain = "mainnet"

    pw.setNode(node=node, chain=chain)```

as you suggested, took care of the issue. Thanks so much!
Answer: As it turns out this segment of code is redundant:
node = "https://nodes.wavesnodes.com"
chain = "mainnet"

pw.setNode(node=node, chain=chain)

Refactoring without it resolved the issue.


Looking for studs in thick plasterboard to attach 12" kitchen cabinet

Question: I have the Ikea 12" kitchen cabinet. It is standalone (between sink that's separately attached and stove). It is a pullout, so I need to attach it to wall.
I cannot find the studs in that wall at all. I have the Franklin sensor that just shows that theres something there for 80% of the space behind the cabinet, and it varies as i move it up and down.
When I use a strong magnet (type that can hold a hammer) - it stick to a small horizontal part above the cabinet but does not feel anything below it (so not a stud).
2 part question:
1 - how can I find a stud (I dragged the franklin sensor and magnet across that whole wall and not getting anything reliable)
2 - potentially it is a concrete wall or somehow solid? (it's between my apartment and neighbors). The building was build in 1930s, can I use on of the screw in anchors regardless of whether its a stud or not? and would it be safe to use? I don't foresee us putting anything extremely heavy into the kitchen cabinet, but I expect there will be pots and dishes.
Answer: Most likely it's a lathe and plaster wall, which can give stud finders fits. Since it's behind a cabinet anyway try measuring from a known stud and drilling a test hole with a small bit. You know there will be studs at windows and alongside electrical boxes. (Though you may need to remove the over plate and peek to find the correct side.)
Comment: If you can't find a stud, being a 12" cabinet, then yes, you can use an anchor system. But rather that the little plastic ones, try a metal one, one that will support more weight than you think you might have. Or a hurricane/earthquake strap. If you are just holding it to the wall to keep from moving, you won't have a lot of weight to it in that regards, and you could probably use 2 of the plastic anchors, one top and one lower down.
Comment: when i say 'behind a cabinet' i meant behind the cabinet that i want to attach, i'll have to do test holes as you said, there's an electrical box on the other end of the wall, and i think the studs are 16" apart in the house, so ill try that out first.


No heat but fan and blower continuous run

Question: I have a Trane gas pack 1998 unit that heats with propane. The fan and blower are running, but there's no heat blowing in vents: just cold air. What is wrong?
Answer: The high limit switch is dead.  Contact a local HVAC contractor for a replacement. While you're at it, replace the air filter on the furnace. Dirty filters are the number one cause of premature high limit failure.


Passing -P parameters to gradle from android studio

Question: Is there a functionality inside android studio to do things like this.
Basically my gradle script reads parameter named version based on which it sets dependency version of a certain library.
So when I do gradlew -Pversion='1.2.3' I get this string inside gradle. But this only works if I invoke gradle from console.
Is there a way to pass parameters to gradle when started using configuration for project inside Android Studio (pressing little play triangle)?
NOTE:I did find Gradle VM options and Script prameters under default configs but adding -Pversion='1.2.3' there doesn't seem to have an effect.
Answer: In order to provide parameter to run option of Android Studio you should setup them under AndroidStudios Compile Preferences
AndroidStudio > Preferences...
Under Compiler: ComandLineOptions
Comment: On AS 3.0.1, this worked for me, and allows Instant Run capability while passing gradle properties. It's unfortunate that this must be set globally, and cannot be set per run configuration.  Also, as @KMP answered, using gradle task directly with a property works, but it breaks Instant Run for me.
Comment: Instant Run is overrated. :)
Comment: For me it worked with not -P but -D like -DminSDK=23
Answer: Run > Edit Configurations..

Replace "abcdef" in Script parameters by your params.
Comment: Unfortunately this is not working in my case. I want to pass the parameter to gradle when using Android Application configuration (first option on the left in your screenshot) i don't want to run Gradle task directly.
Answer: For example let's try to pass server base endpoint while building project. First we need to define a method which gets url and sets it
def serverUrl = "https://mydefaulturl.com"
task(runProgram){
   if(project.hasProperty("url")){
       serverUrl = url;
   }
}

In your buildTypes create your base url with this value:
debug{
   buildConfigField("java.lang.String","BASE_URL","$serverUrl")
}

Now we can pass debug build an url and use it.
You can build your project from terminal with the command below:
./gradlew installDebug task runProgram '-Purl="https://yournewurl.com"'

Comment: if you add these codes to your build gradle and run gradlew code from terminal in android studio, this'll be a way to do within the android studio. :)
Comment: @Burf2000 The effort to try it out would have been less then writing your comment...
Comment: What is the use of adding a field to build config here?
Comment: if you use two or more different urls for test and production you can generate your base url with build variants or build types. before production it's not a good case commenting in or commenting out some critical variables such as base url.
Comment: i'm not sure why people down vote my answer but the code is working and i'm still using it in production :)
Comment: this is done in the app gradle file or the project gradle file?
Comment: app gradle file
Comment: @ABS this answer should work, do not rely too much on GUI
Comment: @BitwiseDEVS Well the question is asking how to do it from "Android Studio". So it does not really answers it.
Comment: @ABS and you can do it using "Android Studio" terminal, WDYT?
Comment: @BitwiseDEVS Yeah sure. I guess it makes the cut :) I answered it this way because I am used to use the play button in Android Studio, so that's basically makes it more convenient.
Answer: Put version="1.2.3" in gradle.properties or under
buildscript {
    ext{
        version="1.2.3"
    }
...
}


What's the difference between 'killall' and 'pkill'?

Question: After using just plain kill <some_pid> on Unix systems for many years, I learned pkill from a younger Linux-savvy co-worker colleague1.
I soon accepted the Linux-way,pgrep-ing and pkill-ing through many days and nights, through slow-downs and race conditions.   This was all well and good.
But now I see nothing but killall.  How-to's seem to only mention killall, and I'm not sure if this is some kind of parallel development, or if killall is a successor to pkill, or something else.
It seems to function as a more targeted pkill, but I'm sure I'm missing something.
Can an Ubuntu/Debian-savvy2 person explain when (or why) killall should be used, especially if it should be used in preference to pkill (when pkill often seems easier, because I can be sloppier with name matching, at least by default).
When speaking of killall, I'm not thinking of the command that on some Unix systems (Solaris, AIX, ?) would kill all user processes.   Here's a description of that version, from a manpage for IBM's AIX:

The killall command cancels all
  processes that you started, except
  those producing the killall process.
  This command provides a convenient
  means of canceling all processes
  created by the shell that you control.
  When started by a root user, the
  killall command cancels all
  cancellable processes except those
  processes that started it. If several
  Signals are specified, only the last
  one is effective.

1 'colleague' is free upgrade from 'co-worker', so might as well.
2 Originally I thought this was a Linux or Debian thing, but some sources are saying that the Linux killall is derived from BSD-flavored Unix.
Answer: I think you see killall in how-to's because by default it requires the precise process name, whereas pkill does basic pattern matching. Thus, killall is safer for users to blindly copy and paste.
Pkill and killall both have distinguishing options. Killall has a flag to match by process age, pkill has a flag to only kill processes on a given tty. Etcetera ad nauseum. Neither is better, they just have different specialties.
I see from their man pages that killall comes from the psmisc package, which has several process managing utilities, but notably doesn't contain ps. It's the procps package that has ps, top, kill, and pkill (among others). I'd wager procps didn't originally have pkill, so psmisc scratched an itch and came up with killall.
The pkill/pgrep man page says they were introduced in Solaris 7. As you mention, jgbelacqua, Solaris's killall was not the utility psmisc provides, thus Solaris probably only had the procps package. Someone wanted a pattern matching process tool, thus pkill and pgrep. Whether it was developed by the procps dev or added in afterwards, I don't know. Regardless, it made it in and became part of *nixes everywhere.
More sources:

http://www.freebsdsoftware.org/sysutils/linux-procps.html
http://www.freebsdsoftware.org/sysutils/psmisc.html
http://procps.sourceforge.net/faq.html
OpenSolaris (now Illumos) source code for ps, at launch in 2005
Comment: @manish -- er, there was a different killall on SysV systems.
Comment: @Manish: pkill (no kill) doesn't need the pid number, nor the process name. It does patter match on the process name.
Comment: `killall is safer for users to blindly copy and paste`, except if you're on a machine where killall does really kill all. It's unfortunate that the two different utilities come to have the same name.
Comment: Hmm -- there was a `killall` on (old?) Solaris systems, but it behaved differently.  It killed everything.
Comment: @djeikyb  The thought about killall being safer sounds right, or at least that could account for a lot of its popularity.
Comment: `killall` kills all the process with the specified name.
Comment: @jgbelacqua: It is easier to use `killall` since the process guess is easy to guess whereas finding pid itself takes one extra step.
Comment: @LieRyan what gnu/linux provides a `killall` that behaves like solaris's? As well documented in both the question and answer, we're not talking about *that* `killall`.
Answer: Please be careful with "killall".  On some systems (I forget which), killall kills all processes.  It will silently ignore arguments and bring your system to a complete halt.
Comment: This is not true.  killall without any arguments will do nothing, and killall will not ignore the arguments.  `kill -9 -1` might kill your system, and `killall -9 -1` might as well.  But not just `killall [program]`
Comment: It's true on SysV systems, as now mentioned in the original question.
Answer: if you activate /etc/bash_completion, after killall <part_of_process_name> and hit tab - auto completes the process name from the list of running processes
Comment: The same auto-completion will be done with pgrep/pkill.  Something I commonly do is `pkill plug` to kill the flash plugin for firefox when I know that I don't have anything I want to use for a while but still want to actively use firefox.  This is a function of the shell, not a difference between killall and pgrep/pkill.
Comment: I didn't say is a difference - just a nice feature to avoid searching for PIDs, process names and etc.
Answer: If you look at the options on both programs, you'll see that they both do about the same thing, but in different ways.
pkill will perform matching on various attributes of a process (CMD, PID, PPID, UID...) and will send the given signal to each process that matches. (For CMD, a regular expression is used, for others it is a string). pkill is not interactive, but better for batch programs.
killall will perform matching on the process name (comm) or user (user), not on the whole command string. The argument is used as a simple string and must be match the entire 'comm' value (there is also a --regexp option to change this).  killall has --interactive and --younger-than options, which pkill does not have.
There is also a killall5 is from SysV days and was ported to other UNIX variants (supposedly under the Ubuntu package 'sysutils').  This behaves differently in the old fashion manner.  This was often used internally to the init scripts to shutdown or change to single-user mode.
Comment: No, neither `pkill` nor `killall` should be used in scripts, only interactively, and with caution.
Answer: On top of the other answers, another difference making it a bit more idiot proof is that killall will tell you

no process found

if that process doesn't exist, while pkill won't.


File Not Found for private files that contains arabic characters in their names in Drupal

Question: Edit: Now, I have managed to solve error 500 error.Now I receive a purely Drupal "File Not Found" for the private files that contained arabic characters in their file names. I have checked the file_managed table and If I change the filename for any of the mentioned files from anything in Arabic to anything in English, the error is gone. Does anybody know why would Drupal have a problem in handling private files with unicode (arabic) characters in their file names?
Thanks!
Comment: yes it could do with the contents of the `.htaccess` file but we are clairvoyant.  No info, no specific answer. :-(
Comment: sorry but it's way past my bedtime so I am turning in.  Can I suggest that you edit your Q and add any pertinent details, test cases, etc.  The more info that you give the better chance of a informed response.  I will delete my answer since its not relevant, to knock the responses down to zero -- this might help with other responses :)
Comment: put some info (`.htaccess` content,log file, ...). We have no skill in mind reading:-D
Comment: why are you serving a private file? what is a "private" file?
Answer: Problem is probably that you are saving the file without setting permissions that would allow the web-server user to read it. I'm going to suggest a solution which ignores .httaccess entirely because you have not provided us with the contents of that file.
[BTW root user has the uid of 0. Who is user 1 and why would she be relevant?]

find out "who" is running apache
make sure "who" can read the file you cannot access

Assuming your web server is apache, this command will tell you which user is running apache:
<code> $ ps aux|grep apach[e]
root     19874  1.0  0.6  84008 12736 ?        Ss   00:24   0:00 /usr/sbin/apache2 -D (...)
apache   19876  0.0  0.4  48576  8380 ?        S    00:24   0:00 /usr/sbin/apache2 -D (...)
(...)
</code>
The user apache is running the binary apache2 on my system. Ignore the first line which shows who started apache2. Now, make the file readable by apache.
<code>$ chmod 644 /path/to/whereever/you/put/system/files/docFiles/nameoffile.pdf
</code>
now everyone can read the file and the owner may write to it.


Add, remove "Active" class bootstrap carousel according to the available images

Question: I have 5 images configurable from some back-end configurable enable yes/no
In my slider i want If I haven't some image, I remove that slide, this is Ok for me, the problem that encountered is with the "active" class it must be present in the first slide.
I don't know how to manage this class to add it in the first slide
 available.
Example : if I haven't no image for the $image1, $image2 the active class must be added in the next one : the third.
info :if the $images varibles if they are empty, it returns Null
The active class is added in two places:
1.<li data-target="#carouselExampleIndicators" data-slide-to="0"
2.<div class="carousel-item img1

        <?php if($image1) :?>

 // Here class="active"
        <?php endif; ?>
        <?php if($image2) :?>

        <?php endif; ?>
        <?php if($image3) :?>

        <?php endif; ?>
        <?php if($image4) :?>

        <?php endif; ?>
        <?php if($image5) :?>

        <?php endif; ?>

        <?php if($image1) :?>

 //here active
            <img class="d-block w-100" src="<?php echo $mediaUrl.'slider/'.$image1; ?>" alt="First slide">

        <?php endif; ?>
        <?php if($image2) :?>

            <img class="d-block w-100" src="<?php echo $mediaUrl.'slider/'.$image2; ?>" alt="Second slide">

        <?php endif; ?>
        <?php if($image3) :?>

            <img class="d-block w-100" src="<?php echo $mediaUrl.'slider/'.$image3; ?>" alt="Third slide">

        <?php endif; ?>
        <?php if($image4) :?>

            <img class="d-block w-100" src="<?php echo $mediaUrl.'slider/'.$image4; ?>" alt="Third slide">

        <?php endif; ?>
        <?php if($image5) :?>

            <img class="d-block w-100" src="<?php echo $mediaUrl.'slider/'.$image5; ?>" alt="Third slide">

        <?php endif; ?>

        Previous

        Next

Answer: Try this
$('.carousel-item').first().addClass('active')
Answer: $(".carousel-inner").next().addClass('active');


Not created client object of laravel unit testing

Question: I have laravel TestCase class
<?php

class TestCase extends Illuminate\Foundation\Testing\TestCase {

    /**
     * Creates the application.
     *
     * @return \Symfony\Component\HttpKernel\HttpKernelInterface
     */
    public function setUp(){
        return true;
    }

    public function createApplication()
    {
        $unitTesting = true;

        $testEnvironment = 'testing';

        return require __DIR__.'/../../bootstrap/start.php';
    }

}

I'm extending this class into ExampleTest as follows
<?php

class ExampleTest extends TestCase {

    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {

        $inputs = array('username' => '', 'password' => '');
        $this->client->request('POST', '/app/1.0/auth/testLogin', $inputs);

        $this->assertTrue(true);
    }

}

While run this test
PHP Fatal error:  Call to a member function request() on a non-object in /opt/Work/tapes/backend/api/app/tests/ExampleTest.php on line 14
error occured.
I go through debug and came to know client object is not created.
I tried my best, but not able to solve this problem.
Please help me to resolve this issue.
Thanks.
Answer: I got the same problem, I solved it by changing TestCase class file as follows -
<?php

namespace Illuminate\Foundation\Testing;

use Illuminate\View\View;
use Illuminate\Auth\UserInterface;

abstract class TestCase extends \PHPUnit_Framework_TestCase {

    /**
     * The Illuminate application instance.
     *
     * @var \Illuminate\Foundation\Application
     */
    protected $app;

    /**
     * The HttpKernel client instance.
     *
     * @var \Illuminate\Foundation\Testing\Client
     */
    protected $client;

    /**
     * Setup the test environment.
     *
     * @return void
     */
    public function setUp()
    {
        if ( ! $this->app)
        {
            $this->refreshApplication();
        }
    }

    /**
     * Refresh the application instance.
     *
     * @return void
     */
    protected function refreshApplication()
    {
        $this->app = $this->createApplication();

        $this->client = $this->createClient();

        $this->app->setRequestForConsoleEnvironment();

        $this->app->boot();
    }

    /**
     * Creates the application.
     *
     * Needs to be implemented by subclasses.
     *
     * @return Symfony\Component\HttpKernel\HttpKernelInterface
     */
    abstract public function createApplication();

    /**
     * Call the given URI and return the Response.
     *
     * @param  string  $method
     * @param  string  $uri
     * @param  array   $parameters
     * @param  array   $files
     * @param  array   $server
     * @param  string  $content
     * @param  bool    $changeHistory
     * @return \Illuminate\Http\Response
     */
    public function call()
    {
        call_user_func_array(array($this->client, 'request'), func_get_args());

        return $this->client->getResponse();
    }

    /**
     * Call the given HTTPS URI and return the Response.
     *
     * @param  string  $method
     * @param  string  $uri
     * @param  array   $parameters
     * @param  array   $files
     * @param  array   $server
     * @param  string  $content
     * @param  bool    $changeHistory
     * @return \Illuminate\Http\Response
     */
    public function callSecure()
    {
        $parameters = func_get_args();

        $parameters[1] = 'https://localhost/'.ltrim($parameters[1], '/');

        return call_user_func_array(array($this, 'call'), $parameters);
    }

    /**
     * Call a controller action and return the Response.
     *
     * @param  string  $method
     * @param  string  $action
     * @param  array   $wildcards
     * @param  array   $parameters
     * @param  array   $files
     * @param  array   $server
     * @param  string  $content
     * @param  bool    $changeHistory
     * @return \Illuminate\Http\Response
     */
    public function action($method, $action, $wildcards = array(), $parameters = array(), $files = array(), $server = array(), $content = null, $changeHistory = true)
    {
        $uri = $this->app['url']->action($action, $wildcards, true);

        return $this->call($method, $uri, $parameters, $files, $server, $content, $changeHistory);
    }

    /**
     * Call a named route and return the Response.
     *
     * @param  string  $method
     * @param  string  $name
     * @param  array   $routeParameters
     * @param  array   $parameters
     * @param  array   $files
     * @param  array   $server
     * @param  string  $content
     * @param  bool    $changeHistory
     * @return \Illuminate\Http\Response
     */
    public function route($method, $name, $routeParameters = array(), $parameters = array(), $files = array(), $server = array(), $content = null, $changeHistory = true)
    {
        $uri = $this->app['url']->route($name, $routeParameters);

        return $this->call($method, $uri, $parameters, $files, $server, $content, $changeHistory);
    }

    /**
     * Assert that the client response has an OK status code.
     *
     * @return void
     */
    public function assertResponseOk()
    {
        $response = $this->client->getResponse();

        $actual = $response->getStatusCode();

        /** @noinspection PhpInconsistentReturnPointsInspection */
        return $this->assertTrue($response->isOk(), 'Expected status code 200, got ' .$actual);
    }

    /**
     * Assert that the client response has a given code.
     *
     * @param  int  $code
     * @return void
     */
    public function assertResponseStatus($code)
    {
        /** @noinspection PhpUndefinedMethodInspection */
        /** @noinspection PhpInconsistentReturnPointsInspection */
        return $this->assertEquals($code, $this->client->getResponse()->getStatusCode());
    }

    /**
     * Assert that the response view has a given piece of bound data.
     *
     * @param  string|array  $key
     * @param  mixed  $value
     * @return void
     */
    public function assertViewHas($key, $value = null)
    {
        if (is_array($key)) /** @noinspection PhpInconsistentReturnPointsInspection */
            return $this->assertViewHasAll($key);

        /** @noinspection PhpUndefinedFieldInspection */
        $response = $this->client->getResponse()->original;

        if ( ! $response instanceof View)
        {
            /** @noinspection PhpInconsistentReturnPointsInspection */
            return $this->assertTrue(false, 'The response was not a view.');
        }

        if (is_null($value))
        {
            $this->assertArrayHasKey($key, $response->getData());
        }
        else
        {
            $this->assertEquals($value, $response->$key);
        }
    }

    /**
     * Assert that the view has a given list of bound data.
     *
     * @param  array  $bindings
     * @return void
     */
    public function assertViewHasAll(array $bindings)
    {
        foreach ($bindings as $key => $value)
        {
            if (is_int($key))
            {
                $this->assertViewHas($value);
            }
            else
            {
                $this->assertViewHas($key, $value);
            }
        }
    }

    /**
     * Assert whether the client was redirected to a given URI.
     *
     * @param  string  $uri
     * @param  array   $with
     * @return void
     */
    public function assertRedirectedTo($uri, $with = array())
    {
        $response = $this->client->getResponse();

        $this->assertInstanceOf('Illuminate\Http\RedirectResponse', $response);

        $this->assertEquals($this->app['url']->to($uri), $response->headers->get('Location'));

        $this->assertSessionHasAll($with);
    }

    /**
     * Assert whether the client was redirected to a given route.
     *
     * @param  string  $name
     * @param  array   $parameters
     * @param  array   $with
     * @return void
     */
    public function assertRedirectedToRoute($name, $parameters = array(), $with = array())
    {
        $this->assertRedirectedTo($this->app['url']->route($name, $parameters), $with);
    }

    /**
     * Assert whether the client was redirected to a given action.
     *
     * @param  string  $name
     * @param  array   $parameters
     * @param  array   $with
     * @return void
     */
    public function assertRedirectedToAction($name, $parameters = array(), $with = array())
    {
        $this->assertRedirectedTo($this->app['url']->action($name, $parameters), $with);
    }

    /**
     * Assert that the session has a given list of values.
     *
     * @param  string|array  $key
     * @param  mixed  $value
     * @return void
     */
    public function assertSessionHas($key, $value = null)
    {
        if (is_array($key)) /** @noinspection PhpInconsistentReturnPointsInspection */
            return $this->assertSessionHasAll($key);

        if (is_null($value))
        {
            $this->assertTrue($this->app['session.store']->has($key), "Session missing key: $key");
        }
        else
        {
            $this->assertEquals($value, $this->app['session.store']->get($key));
        }
    }

    /**
     * Assert that the session has a given list of values.
     *
     * @param  array  $bindings
     * @return void
     */
    public function assertSessionHasAll(array $bindings)
    {
        foreach ($bindings as $key => $value)
        {
            if (is_int($key))
            {
                $this->assertSessionHas($value);
            }
            else
            {
                $this->assertSessionHas($key, $value);
            }
        }
    }

    /**
     * Assert that the session has errors bound.
     *
     * @param  string|array  $bindings
     * @param  mixed  $format
     * @return void
     */
    public function assertSessionHasErrors($bindings = array(), $format = null)
    {
        $this->assertSessionHas('errors');

        $bindings = (array)$bindings;

        $errors = $this->app['session.store']->get('errors');

        foreach ($bindings as $key => $value)
        {
            if (is_int($key))
            {
                /** @noinspection PhpUndefinedMethodInspection */
                $this->assertTrue($errors->has($value), "Session missing error: $value");
            }
            else
            {
                $this->assertContains($value, $errors->get($key, $format));
            }
        }
    }

    /**
     * Assert that the session has old input.
     *
     * @return void
     */
    public function assertHasOldInput()
    {
        $this->assertSessionHas('_old_input');
    }

    /**
     * Set the currently logged in user for the application.
     *
     * @param  \Illuminate\Auth\UserInterface  $user
     * @param  string  $driver
     * @return void
     */
    public function be(UserInterface $user, $driver = null)
    {
        $this->app['auth']->driver($driver)->setUser($user);
    }

    /**
     * Seed a given database connection.
     *
     * @param  string  $class
     * @return void
     */
    public function seed($class = 'DatabaseSeeder')
    {
        $this->app['artisan']->call('db:seed', array('--class' => $class));
    }

    /**
     * Create a new HttpKernel client instance.
     *
     * @param  array  $server
     * @return \Symfony\Component\HttpKernel\Client
     */
    protected function createClient(array $server = array())
    {
        return new Client($this->app, $server);
    }

}