Why am I getting a None value for all of my variables?

Question: So, I've attempted to make a simple Base 10 to Base 16 converter (I realize this is Base 10 integer to a mock-Base 16 string). I'm fairly new to Python; I just started learning it this week (I have prior programming experience with C#, so I'm not lost on this).
R1 = 0
R2 = 0
R3 = 0
R4 = 0
R5 = 0

number = int(raw_input("Enter a base 10 number (Smaller than 1048576): "))

def numberConvert(a=0):
  a = str(a)

  if (a == "10"):
    a = "a"
  elif (a == "11"):
    a = "b"
  elif (a == "12"):
    a = "c"
  elif (a == "13"):
    a = "d"
  elif (a == "14"):
    a = "e"
  elif (a == "15"):
    a = "f"
  else:
    a = a

#Dividing

Q1 = (number // 16)
R1 = (number % 16)

Q2 = (Q1 // 16)
R2 = (Q1 % 16)

Q3 = (Q2 // 16)
R3 = (Q2 % 16)

Q4 = (Q3 // 16)
R4 = (Q3 % 16)

Q5 = (Q4 // 16)
R5 = (Q4 % 16)

R1 = numberConvert(R1)
R2 = numberConvert(R2)
R3 = numberConvert(R3)
R4 = numberConvert(R4)
R5 = numberConvert(R5)

print R1 + R2 + R3 + R4 + R5

After running and inputting 1048575 (that's the highest it can go, so I'm expecting "fffff" as an output), it gives me:
C:\PythonPrograms\Modules>Decimal_to_Hex.py
Enter a base 10 number (Smaller than 1048576): 1048575
Traceback (most recent call last):
  File "C:\PythonPrograms\Modules\Decimal_to_Hex.py", line 50, in <module>
    print R1 + R2 + R3 + R4 + R5
TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'

After I ran some tests which mainly involved printing the R1 to R5 values at the beginning and the end of the function, I've come to the conclusion that the issue lies somewhere in the R1 = numberConvert(R1) section. At any time before that, the variables behave normally. Right at the start of the function, after being inputted, theR variables are numbers 0 through 15.
Right before function numberConvert finishes up, they are 0 through 9, or "a" through "f". However, if I were to print value R1 immediately after R1 = numberConvert(R1), it gives me None as an output.
From what I've read, this is essentially Python's null value. So, I've narrowed down the problem to the section where I'm running the function numberConvert.
Comment: Well you don't actually *return* anything from your function.
Comment: And why are you converting to a string in the beginning? Why not compare with the *number* `15` (for example)? If you want to return a string, then do the string-conversion when returning the value.
Answer: All functions in Python return None by default unless you have a return-statement.  So, if you want your numberConvert function to return a value other than None, you need to put one:
def numberConvert(a=0):
  a = str(a)

  if (a == "10"):
    a = "a"
  elif (a == "11"):
    a = "b"
  elif (a == "12"):
    a = "c"
  elif (a == "13"):
    a = "d"
  elif (a == "14"):
    a = "e"
  elif (a == "15"):
    a = "f"
  else:
    a = a

  ########
  return a
  ########

Since you say you have C# experience, perhaps you thought that doing:
R1 = numberConvert(R1)

would pass R1 as a reference which would be modified inside numberConvert whenever you did:
a = ...

This is incorrect though because a is treated as a local name that gets assigned the value of R1.  For more information on this, see How do I pass a variable by reference?

Also, there are a few things I'd like to mention about your numberConvert function:

You do not need parenthesis with if-statements in Python.  In fact, most Python programmers consider them to be bad style. Instead, you should just do:
if a == "10":
  a = "a"
elif a == "11":
  a = "b"
...

There is not really a reason to do:
a = str(a)

since you can compare with integers directly:
if a == 10:
  a = "a"
elif a == 11:
  a = "b"

If you want, you could use a dictionary to avoid all those if-statements:
def numberConvert(a=0):
    return {"10":"a","11":"b","12":"c","13":"d","14":"e","15":"f"}.get(a, a)

Comment: Ahh, I see now; I've just had a habit to use parenthesis as organization more than anything.


Diameter traffic generator

Question: I am in a hunt for a Diameter protocol simulator / traffic generator.
It needs to be robust, actively maintained, well documented and portable (Solaris and Linux OS is expected).
The goal is to generate heavy load of requests with a complex AVP structure (3GPP TS 32.299 format), and to stress-test a Diameter Server with the load.
I already checked out Seagull, but it had been discarded because it's not actively maintained (and be frank, it's horribly difficult to use).
Anybody idea?
Answer: If you have some budget to spare doing this, I would suggest talking to the folks at Spirent - we are a customer of theirs, our Avalanche box has proved invaluable in the year we have had it.
I am pretty sure they do Diameter - we have only scratched the surface so far with HTTP/S testing.

Diameter traffic generator


C++20 Returning Non-type Variadic Template Tuple of References

Question: Currently using g++11.3.0, C++20.
This is a follow up from a previous query.
I have a function foo that takes an arbitrary number of template arguments and returns a tuple that contains a value for each template argument. However, the function currently returns a tuple of l-values. I would like to return a tuple of l-value references. I've tried changing the return type to std::tuple<Args&...> and using std::tie() instead of std::make_tuple(), but gives me the error:
error: no matching function for call to 'tie'

The lambda in the function actually returns a non-local variable with the respective data type, so the line return Args(); is just there as a substitution to provide compilable code for this post.
template <typename ...Args>
std::tuple<Args...> foo()
{
    return std::make_tuple([] ()
    {
        // Do some stuff....
        // Return non-local l-value....

        return Args();
    }()...);
}

Answer: A lambda without specified return value always returns by-value, not by-reference. Specifically it returns with a return type of auto by default. So your call to the lambda never produces a lvalue, always a prvalue. std::tie then fails, because it accepts only lvalues.
If you want to have the lambda return a lvalue reference, you need to specify its return type. I wouldn't make it specifically a lvalue reference though. You can have it deduce the appropriate value category automatically with decltype(auto):
[] () -> decltype(auto)
{
    // Do some stuff....
    // Return non-local l-value....

    return Args();
}()

(However, Args() is a prvalue, not a lvalue, so this will still deduce to a non-reference type. If you actually want to have the lambda return a lvalue reference, then actually give the return statement a lvalue as operand.)
Alternatively you can specify Args& as the return type of the lambda explicitly.
After that, you can use std::tie or alternatively std::forward_as_tuple. The latter will correctly deduce whether the references should be lvalue references or rvalue references automatically, while std::tie assumes lvalue references and will fail otherwise. Typically it is desirable that the value category is deduced, although in your situation it might be a potential source of error since it would have caused UB instead of a compilation error with your wrong return type on the lambda.
Then you can also use auto as return type for foo, so that the automatically deduced value category applies, but that is a matter of style.

On a side note, if your lambdas have side effects, note that the order in which the lambdas will be evaluated is indeterminate. You can not rely on any particular ordering.


onChange callback not firing in React component

Question: My onChange() function does not run unless I use jQuery for some reason. The reason why I have to add the onChange listener in componentDidMount() is because I'm using MaterializeCSS which transforms your select tag into a ul. The code below works fine:
onChange(e) {
  let inspectionTime = e.target.value;
  this.setState({ inspectionTime });
}

componentDidMount() {
  let $inspectionDropdown = $(ReactDOM.findDOMNode(this.refs.inspection));
  $inspectionDropdown.on('change', this.onChange);
}

but this code does not:
onChange(e) {
  let inspectionTime = e.target.value;
  this.setState({ inspectionTime });
}

componentDidMount() {
  let inspectionDropdown = ReactDOM.findDOMNode(this.refs.inspection);
  inspectionDropdown.addEventListener('change', this.onChange);
}

Here is the code for the whole component if it helps at all:
import React from 'react';
import ReactDOM from 'react-dom';

class InspectionMode extends React.Component {
  constructor(props) {
    super(props);
    this.onChange = this.onChange.bind(this);
    this.defaultValue = 'selected';
    this.state = { inspectionTime: 0 };
  }

  onChange(e) {
    let inspectionTime = e.target.value;
    this.setState({ inspectionTime });
  }

  componentDidMount() {
    let inspectionDropdown = ReactDOM.findDOMNode(this.refs.inspection);
    inspectionDropdown.addEventListener('change', this.onChange);
  }

  render() {
    let classes = 'input-field col s10 offset-s1 l3';

    return (

        <select onChange={this.onChange} ref="inspection" value={this.state.inspectionTime}>
          <option value="0">None</option>
          <option value='5'>5 Seconds</option>
          <option value='10'>10 Seconds</option>
          <option value='15'>15 Seconds</option>
        </select>
        Inspection Time

    );
  }
}

export default InspectionMode;

Answer: The problem is that the plugin is emitting a custom change event. React's event system doesn't recognize custom events (not sure why).
In this case a manual change listener is the right solution. The way you improve this is by abstracting the select element to an 'atom'.
class Select extends React.Component {
  static propTypes = {
    value: React.PropTypes.string,
    options: React.PropTypes.arrayOf(
      React.PropTypes.shape({
        text: React.PropTypes.string.isRequired,
        value: React.PropTypes.string.isRequired,
      })
    ).isRequired
  };
  constructor() {
    super();
    this.onChange = this.onChange.bind(this);
  }

  onChange(e) {
    this.props.onChange(e.target.value);
  }

  componentDidMount() {
    let select = this.refs.select;
    select.addEventListener('change', this.onChange, false);
  }

  componentWillUnmount(){
    let select = this.refs.select;
    select.removeEventListener('change', this.onChange, false);
  }

  render() {
    let classes = 'input-field col s10 offset-s1 l3';

    return (

        <select ref="select" value={this.props.value}>
          {this.props.options.map((x) => {
            return <option key={x.value} value={x.value}>{x.text}</option>;
          })}
        </select>

    );
  }
}

You can then use this in InspectionMode or anywhere else in your UI.
class InspectionMode extends React.Component {
  constructor(props) {
    super(props);
    this.onChange = this.onChange.bind(this);
    this.value = 'selected';
    this.state = { inspectionTime: 0 };
  }

  onChange(inspectionTime) {
    this.setState({ inspectionTime });
  }

  render() {
    return (

        <Select
          value={this.state.inspectionTime}
          onChange={this.onChange}
          options={[
            {value: '0', text: 'None'},
            {value: '5', text: '5 seconds'},
            {value: '10', text: '10 seconds'},
            {value: '15', text: '15 seconds'},
          ]}
        />
        Inspection Time

    );
  }
}


Devexpress: An object reference is required for the non-static field

Question: I keep getting this error in my devexpress code.
Here is the code I have put in:
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Collections;
using System.ComponentModel;
using DevExpress.XtraReports.UI;
using System.Drawing.Printing;

namespace DD
{
    public partial class MasterReport : DevExpress.XtraReports.UI.XtraReport
    {
        //detailReport.catName.Value = ((DataRowView)e.Brick.Value).Row["EcoYear"].ToString();
        public MasterReport()
        {
            InitializeComponent();

        }

        private void xrLabel1_BeforePrint(object sender, PrintEventArgs e)
        {
         //   XRLabel l = sender as XRLabel;
         //   l.Tag = GetCurrentRow();

           ((XRLabel)sender).Tag = GetCurrentRow();
        }

        private void xrLabel1_PreviewClick(object sender, PreviewMouseEventArgs e)
        {
            DetailReport detailReport = new DetailReport();
            detailReport.CaID.Value = (int)((DataRowView)e.Brick.Value).Row["CaseID"];
            detailReport.EYear.Value = (int)((DataRowView)e.Brick.Value).Row["EcoYear"];
            detailReport.ShowPreviewDialog();
        }

        private void xrLabel1_PreviewMouseMove(object sender, PreviewMouseEventArgs e)
        {
            Cursor.Current = Cursors.Hand;
        }

        private void xrPictureBox1_BeforePrint(object sender, PrintEventArgs e)
        {
            ((XRLabel)sender).Tag = GetCurrentRow();
        }

        private void xrPictureBox1_PreviewClick(object sender, PreviewMouseEventArgs e)
        {
            PW pw = new PW();
            PW.CaID.Value = (int)((DataRowView)e.Brick.Value).Row["CaseCaseID"];
            PW.ShowPreviewDialog();
        }

        private void xrPictureBox1_PreviewMouseMove(object sender, PreviewMouseEventArgs e)
        {
            Cursor.Current = Cursors.Hand;
        }

    }
}

The PW.CaID.Value and the PW.ShowPreviewDialog(); are the lines that are giving me this error. Perhaps I am doing this the wrong way. What I wanted to do is click an icon (xrPictureBox1) on the main report and have it bring up the subreport (PW). I have done this in the code above for another subreport (detailreport). Thank you in advance for your help.
Answer: Your code should read:
PW pw = new PW();
pw.CaID.Value = (int)((DataRowView)e.Brick.Value).Row["CaseCaseID"];
pw.ShowPreviewDialog();

Note the case on PW/pw.


Creating an Android Trial app that expires after a certain number of actions

Question: I've searched for trial application expiry methods and I've found good answers regarding Trial periods for apps but they're time-based.
How can I create a Trial app version that expires after clicking a button 3 times?
based on this link Creating an Android trial application that expires after a fixed time period (option 2 on the accepted answer) I would like to hard code the number of times they have used it, so even an uninstall/intall would have no effect, is this possible?
Answer: Since you don't want to allow the user to get the trial again if he reinstalls the app you will have to use the third technique where you send the data to the server because that is the only way to persist the count of button clicks and tie it to the device across app installs. So instead of using the time u can keep a count of the number of times the button have been clicked on the server. Also u can configure the number of button clicks you want to allow before the app expires instead of hardcoding in the app.
If you don't want to run your own server then you use Parse to store the number of clicks of the button and the user id. It is very easy to integrate.
https://parse.com/docs/android/guide#getting-started
Comment: Thank you, I'll try to use Parse, I believe it'll help.
Answer: On top of pgitu's answer, I also suggest using Parse Anonymous user in which the anonymous user has a field for device ID (the unique identifer for their phone).
Every time the user starts the app, check if a ParseUser is logged in (the anonymous user) if not first check if a user exists with the current device ID for your app and log them in automatically if so. If not, create a new anonymous user and associate the current device id to that new user.
Now, you won't need to force a user signup / login mechanism and you can store information like clicks and such as pgitu suggests. All the remembering of information is done using Parse Anonymous Users and is fairly easy to setup and do.
The catch would be if the user has multiple devices. In this case, you cannot do much with what I'm suggesting but that is just a caveat of having a trial based application and relying on unique devices to mitigate user's and the system. It really shouldn't be an issue though considering you keep track of devices and their # of trials is limited by their # of unique devices.
Comment: The Parse Anonymous user ID is device related right? So even if the same person is installing on 2 different devices it just means that those 2 devices will log on and have a trial "button clicking" experience? Like, if I set the trial limit to 3 clicks, he would have a total of 6 clicks divided in 2 devices? It's not that much of a hassle, I think, considering the app. Thanks!
Comment: From a quick glance in the documentation, I didn't see if Parse automatically handles saving deviceId to the particular Anonymous user's created. What it does do is store the fact that the Anonymous User is logged in (in the cache of course, so a user can clear this). Since the user can clear cache is why i said associate the device id to the anonymous user so they cannot just clear cache and in effect having a new "trial".


HP StorageWorks P4500 G2 Manager Management

Question: According to the documentation, a management group should have an odd number of managers greater than 1. I have a four node SAN consisting of P4500 G2s. I plan on having two clusters with two nodes each in this management group, i.e.:
-Managent_Group1
  -Cluster1
    -Node1
    -Node2
  -Cluster2
    -Node3
    -Node4

Are there any issues running standard managers on Node1, Node2, and Node3? After reading the documentation, I'm still unclear about whether or not cluster membership matters in quorum consistency, or if they don't matter at all.
Answer: HP advised me to have 4 regular managers (1 on each node) and a Failover Manager (FOM) configured for quorum consistency in a management group that has two clusters, with two nodes for each cluster.
For example, let's say you need to update the firmware on Node 3 in Cluster 2. If you have Node 4 running a regular manager, and a FOM in place, you can bring Node 3 down without loosing any quorum consistency. When Node 3 comes back online, it will take approximately 15 minutes for it to re-sync its data with the cluster.
Another alternative is to use a "Virtual Manager". From HP:
A Virtual Manager is added to a management group, as shown in Figure 52 on page 151, but is not
started on a storage system until a failure in the system causes a loss of quorum. Unlike the Failover
Manager, which is always running, the Virtual Manager must be started manually on a storage system
after quorum is lost. It is designed to be used in two-system or two-site system configurations which
are at risk for a loss of quorum
As a small side note, you do not want to use a FOM and a Virtual Manager together, its either one or the other.....
If you have an HP Passport, you can go to this link to download a ESX, Hyper-V, or standalone version of the FOM:
https://h20392.www2.hp.com/portal/swdepot/displayProductInfo.do?productNumber=P4000SW
Scroll to the bottom of the page, click "Receive for free" and sign in with your HP Passport.
References:
HP StorageWorks P4000 SAN Solution user guide
http://h20000.www2.hp.com/bc/docs/support/SupportManual/c02008676/c02008676.pdf
Comment: In fact, after creating the actual clusters and assigning nodes, the best practice analyzer recommended that I run three managers total across both clusters, negating the need for a FOM.
Comment: I understand why you don't want to run an even number of managers. What would be the issue with running three managers and not having `Node4` run any at all? It seems that doing this would allow me to avoid having to install a FOM. In fact, on page 149 of that document, it says to run three managers on a 4 node configuration and doesn't mention that a FOM is needed. My question is about whether or not multiple clusters within a management group impact this guideline.
Answer: After testing and re-reading the HP documentation and consulting the Best Practices Summary of the CMC, it appears that running standard managers on 3 of the 4 nodes is the "correct" way to do this.
Since quorums are per management group and not per cluster, the fact that the four storage nodes are in two separate clusters is not relevant in this case.


Como usar mais de um modal bootstrap em uma só pagina web

Question: Galera, tô aprendendo a usar Bootstrap 4 e queria saber se é possível e se sim, como usar mais de um modal em uma página? queria usar 3 modais na msm página, ou até mais, no entanto, mesmo com as identificações diferentes eu n estou conseguindo chamar mais de um modal na pagina.
Segue uma parte do codigo:

Anuncio

Lorem Ipsum is simply dummy text of the printing and typesetting industry. an unknown

                Visitar

Anuncio

It is a long established fact that a reader will be dist has a more-or-less normal.

                Visitar

percebam que no segundo card eu chamo outro modal.
Agora vou mandar o código dos modais:

Modal 1

                <button type="button" class="close" data-dismiss="modal" aria-label="close">
                    ×
                </button>

Modal 2

                <button type="button" class="close" data-dismiss="modal" aria-label="close">
                    ×
                </button>

Enfim, quem puder me ajudar, da uma força, serei mt grato!!
Answer: para adicionar mais modal basta só trocar o Id id="myModal", id="myModal2" id="myModal3" ...

        <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

Some text in the modal.

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

E no botão para abrir o modal basta por o Id correspondente
Exemplo:

<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>


Why do some quadratic graphs have a flat bottom?

Question: Why do some quadratic graphs have a flat bottom? This is concerning sketching the graph on a physical graph. An example of it would be the equation:y=x^2 -5x+4
Comment: What do you mean by "flat bottom"?
Comment: @user324713 Sure, but $y$ is *smaller* for $x$ *between* $2$ and $3$
Comment: @5xum Yes, but the x can only be an integer in the question. Another thing, why did it reach the same point?
Comment: @user324713 The curve  only "turns smoothly" if you draw it for **all** values of $x$. If you only use integer values of $x$, then it doesn't really make any sense to talk about "smoothness", because you don't even have a curve. You just have a discrete set of points.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: If you plot points, don't join them with straight lines? Maybe
Comment: The "flatness" is not striking for degree 2. It is more evident for higher degrees, for example with $y=x^4, y=x^6...$
Comment: @5xum What I mean by flat bottom is that when x is 2 or 3 in the equation given above, y is -2 for both the values of x.
Comment: @Paul Yes, but in our high school textbook, it is said to do so when a curve should turn smoothly.
Comment: @user324713 For the same reason  that $x^2$ reaches the same point at $x=1$ and $x=-1$.
Comment: @5xum But I think it isn't the reason for this equation. The roots of x here, are 1 and 4.
Comment: @user324713 It is exactly the reason. Every quadratic equation takes all values (except for one) **twice**.
Comment: Welcome to Math.SE! <> Mathematically, _all_ quadratic graphs $y = ax^2+bx+c$ with $a\neq0$ are parabolas. Because you're restricting to integer values of $x$ (and connecting successive dots with line segments?), you'll see a "flat bottom" if $0 < a$ and the _vertex_ of the parabola (the point on the line of vertical symmetry) lies halfway between two integers. If the vertex lies _at_ an integer, there will be a "corner" at the vertex, between two segments of equal absolute slope; at other locations of the vertex there will be a varyingly-sloped line segment "spanning the vertex".
Answer: To illustrate the answer you've been given in the comments (using MATLAB code)
<code>x = 0:0.001:5;
plot(x,x.^2-5*x+4);
x = 0:1:5;
hold on;plot(x,x.^2-5*x+4)
</code>
Comment: I think you are right is situating the issue of the OP in the plotting **step** (I think it is important to give the name).


Access to block-system-main div

Question: I have block with image so the easy way it's to create a content type.
I have node--nodeName.tpl.php where I built correct DOM.
But this is slider, and all nodes embedded in one div with classes

block-system-main block block-system

I have to initialize slider. For this I need unique parent class\id

This is beginning of my node--nodeName.tpl:
<div class="<?php print $classes . ' slick_hero ' . ' ' . $zebra; ?>">

Answer: Looks like you're having a block of node teasers, and you want to initialize a slick slider on its items using vanilla JS, yes? There's a better way to do this, and that's to use the Slick module together with Slick Views.

Create a slick carousel view, configure it as a block and not a page.
Filter to the desired nodes
Configure to render the teaser displays
Configure the slider parameters.
On whatever block rendering mechanism you have (Block Layout, Context, Panels, whatever), position the view in the desired location.

All that and you never have to touch code or meddle with the template.

Access to block-system-main div


How to animate a swiftUI button to display another view

Question: I have a quite simple case, a view displays another one when a button is pressed.
The label on the second view is at the top of the view, which is working fine, unless I try to animate the button when it's pressed. In that case the label on the second view is sometimes at the top, sometimes lower, very eratic.
Here is the running code (simplified) :
import SwiftUI

struct ContentView2: View {
    @State private var displayScreen = ""

    var body: some View {
        ZStack {
            VStack(spacing: 20) {
                Group {
                    Button("  Play  ") {
                        displayScreen = "Level"
                    }
                    .padding(.top, 50)
                    .buttonStyle(Button2())
                }

            }
            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)

            if displayScreen == "Level" {
                Level(displayedScreen: $displayScreen)
            }
        }
        .background(Color.yellow)
    }
}

struct Button2: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .padding(6)
            .background(Color.blue)
            .scaleEffect(configuration.isPressed ? 0.7 : 1)
            .animation(.interpolatingSpring(stiffness: 400, damping: 5, initialVelocity: 10), value: configuration.isPressed) // PROBLEM WITH THIS LINE !
            .foregroundColor(.white)

    }
}

struct Level: View {
    @Binding var displayedScreen: String

    var body: some View {
        NavigationView {
            ZStack(alignment: .top) {
                VStack {
                    Button("Back") {
                        displayedScreen = ""
                    }
                    .padding(.top)
                    Spacer()
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
            }
            .background(Color.green)
        }
    }
}

struct ContentView2_Previews: PreviewProvider {
    static var previews: some View {
        ContentView2()
    }
}

If I remove the .animation line, the behavior is consistent.
Is there a way to animate the button when pressed AND display the second view correctly ?
Thanks for advice  :)
Answer: I ran your code and understood the problem. What I found is that the issue occurs only when the button is tapped and released before the animation ends (regardless of the type of animation used).
Try holding the button for a few seconds and releasing it only after the animation is completely finished. It should work.
However, it seems that the problem is related to the NavigationView used in the 'Level' view, not the animation itself.
struct Level: View {
    @Binding var displayedScreen: String

    var body: some View {
//        NavigationView { // -> this NavigationView is causing the problem
            ZStack(alignment: .top) {
                VStack {
                    Button("Back") {
                        displayedScreen = ""
                    }
                    .padding(.top)
                    Spacer()
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
            }
            .background(Color.green)
//        }
    }
}

I'm not sure about the purpose of using the NavigationView in the 'Level' view, but as far as I know, you should typically use a NavigationView in the root view. Perhaps consider restructuring the view hierarchy.
Comment: The NavigationView is here because I posted a simplified version of my views in order to minimize published code. Anyway you're right when I remove it the problem disappear, and I will restructure the view hierarchy to avoid the problem. Thanks a lot !


Finding efficient encoding scheme for combinatorial problem

Question: An online store is selling rings, necklaces, bracelets, and pendants. Suppose there are $m$ different types of each of these four commodities. A typical customer wants to buy one item of each of the four products, where for each item she has a subset of $\frac{m}{3}$ of the corresponding types and is equally happy with any of them. Prove that there is a scheme that enables each such customer to send the store at most $\log_2 m + 10$ bits (for each possible collection of $\frac{m}{3}$ types of each item), enabling the store to satisfy her request.
My ideas are as follows: we have $4$ different commodities and for each commodity, the customer will be happy with a third of the types. If we index every type for each commodity from $1$ to $m$, let's say that the customer is happy with a certain subset of the indices for each commodity. By Pigeonhole principle, at least two of the commodities will share at least one index of a type that the customer will like. Considering this scenario, I tried to minimize the number of bits required, but could not get to a tight enough bound that is $\log_2 m + 10$. Any ideas on how to proceed? May also be helpful to consider the types as vertices on a graph.
Answer: I think a random approach works here.
Let $A_i$ denote the sets of all types of commodity $i$ for $i\in\{1,2,3,4\}$. Then $|A_i|=m$ for all $i$. Let $A=A_1\times A_2 \times A_3\times A_4$ and consider a random subset $K$ of $A$ with $k=1024m$ elements. Here each such subset $K$ is chosen with probability $p=1/\binom{|A|}{k}=1/\binom{m^4}{1024m}$.
For every collection $B_1, B_2, B_3, B_4$ of subsets of $A_1,A_2,A_3,A_4$ with $|B_i|=m/3$ let $B=B_1\times B_2\times B_3\times B_4$ and consider a probability $p_0$ that we have  $B\cap K=\emptyset$. This probability is equal to number of subsets of size $k$ of $A\setminus B$ divided by the total number of sets of size $k$ chosen from $A$. So
$$p_0=\binom{|A\setminus B|}{k}/\binom{|A|}{k}=\binom{m^4-m^4/81}{1024m}/{\binom{m^4}{1024m}}< (80/81)^{1024m}.$$
Here in the last inequality expand the binomials and use that $x/y> (x-1)/(y-1)$ when $x<y$.
From this you have $p_0<(0.000003)^m$. So the probability that a random chosen $K$ does not intersect a given $B_1\times \cdots \times B_4$ is tiny.
Now, there are $N=\binom{m}{m/3}^4\leq (2^m)^4$ possible choices for $B_1,\ldots B_4$, so let $C_1,\ldots, C_N$ be the events  that the corresponding choice of $B_1,\ldots,B_4$ has an empty intersection with $K$. Then $\mathbb{P}(C_i)=p_0$ for all $i$, and
$$\mathbb{P}(\cup C_i)\leq \sum \mathbb{P}(C_i)=p_0N\leq (3\cdot 10^{-6})^m \cdot 16^m<1.$$
So probability that at least one $C_i$ happens is bounded away from 1, and so the probability that none of $C_i$ happens is positive. We now "derandomize": since the probability of none of $C_i$'s happening is positive, there is some choice of $K$ such that for all choices of $B_1,\ldots B_4$ the intersection $B_1\times B_2\times B_3\times B_4$ with $K$ is nonempty.
Now fix such a $K$ and enumerate elements of $K$ with numbers $\{1, \ldots, 1024m\}$. If the customer has a preference $B_1, \ldots, B_4$, then there is an element $k\in K$ such that $k\in B_1\times \cdots \times B_4$. Customer then send the index of the element $k$ to the store.
What course/book is this from?


Qual é a utilidade do 'declare' do Typescript?

Question: Estou lendo a documentação do Typescript e encontrei o declare:

You can declare your own types that use generics:
interface Backpack {   add: (obj: Type) => void;   get: () =>
Type; }   // This line is a shortcut to tell TypeScript there is a //
constant called backpack, and to not worry about where it came from.
declare const backpack: Backpack;   // object is a string,
because we declared it above as the variable part of Backpack. const
object = backpack.get();   // Since the backpack variable is a string,
you can't pass a number to the add function. backpack.add(23);
Argument of type 'number' is not assignable to parameter of type
'string'.

Pela documentação do TS, entendi como 'fazer funcionar' o declare, mas ainda não entendi como é aplicada essa 'funcionalidade' e porque foi criada.
qual é a utilidade de somente declarar uma variável/constante usando o declare e porque não realmente definir a variável/constante?
Comment: `declare` é usado para definir uma tipagem de algo, por exemplo, os tipos de alguma variável aplicada ao env global (`globalThis`). Um outro exemplo foi um caso em que usei o esse recurso para estender globalmente um tipo que era definido pelo framework Express, sem alterar a tipagem oficial do framework. Eu uso o declare em arquivos `.d.ts`, onde ficam essas definicoes de tipos para facilitar o trabalho do compilador. Essas definicoes não são transpiladas para codigo JS, apenas servem para auxiliar o TS quando o mesmo nao reconhece os tipos de algum dado que vc esteja trabalhando.
Comment: @CmteCardeal Sim, a forma que tenho mais visto o `declare` é em arquivos `.d.ts` como `declare module`, mas o que acontece se existirem duas funções com o mesmo nome por exemplo?
Answer: Um dos principais objetivos do design do TypeScript é a possibilidade de adoção gradual. Isto é, se alguém quiser introduzir TypeScript em um projeto já consolidado em JavaScript, deve conseguir fazer isso de forma não tão dolorosa.
O declare é uma ferramenta que ajuda nesse sentido. É uma palavra-chave que permite que se ateste ao compilador que uma variável, com um certo nome e de um determinado tipo, existe naquele contexto. O compilador simplesmente irá confiar na declaração e assumir que ela está correta conforme a especificação dada.
Type safety
Sob o ponto de vista da segurança de tipos, o declare é "inseguro" de forma similar ao as (type assertions), pois os dois funcionam de modo a permitir que o desenvolvedor ateste algo que o compilador não consegue provar, seja por falta de informações ou por limitações tecnológicas no próprio type system.
É sempre importante tomar cuidado com esse tipo de feature pois, embora extremamente convenientes, elas introduzem "buracos" no sistema de tipos, que podem comprometer a segurança de tipos de todo o programa. Isso porque, ao utilizar declare ou as, o comipilador simplesmente aceita e segue a especificação fornecida pelo código—a partir desse ponto, a segurança de tipos naquele região fica como responsabilidade dos próprios desenvolvedores, que devem ter certeza de que a asserção está correta.
Alguns exemplos
Tradicionalmente, antes da popularização de bundlers e de sistemas de módulos em JavaScript, era muito comum incluir bibliotecas JavaScript simplesmente adicionando um


Avoid printing exponential value

Question: Is there a way to print the actual value instead of exponential value?
>>> val=0.00004
>>> print(str(val))
4e-05

Comment: Checkout https://pyformat.info it's got a ton of helpful tricks regarding formatting. The section on floats may be of use to you.
Comment: `print(f'{val:f}')`
Comment: You can use simple argument specifier - `%f`. This statement prints value with the precision of 6 digits to the right of the dot: `print("%6f" val) `
Answer: As posted in here: How do I suppress scientific notation in Python?
print('{0:f}'.format(val))

Answer: Try this,
print('{:f}'.format(val))

Avoid printing exponential value


Apache httpd does not implement updates to a 301 redirect configuration

Question: I'm having a problem updating a previously-working redirect in my apache server (httpd, rhel).  I'd previously had:
RedirectMatch 301 ^/apidocs/ /old/specific/path/apidocs/

which worked.
I changed it to:
RedirectMatch 301 ^/apidocs/ /new/specific/path/apidocs/

and now it does not work.  That is, when I try to hit the simple http://<host>/apidocs url, I get a 301 with the old redirect location in the response headers, followed by a 404 in the browser, when it attempts to GET from the old location.  The httpd error-log corroborates that the browser tried to GET the old directory:
File does not exist: /var/www/html/old

Doing service httpd reload or service httpd force-reload produces only the following single line of output:
Reloading httpd:

...so it is presumably successful. Also,
(1) when httpd is started, its error log has no complaints.
(2) running apachectl configtest produces Syntax OK.
(3) running httpd -t produces Syntax OK.
(4) I've stopped and 'graceful' started httpd a number of times, to no avail.
(5) I've tried using apachectl -k stop/start, to no avail.
(6) I have now also tried clearing the cache using htcacheclean, to no avail.
worth noting here that previously though the mod cache and mod cache disk modules were loaded, there was no configuration of the CacheRoot & etc, thus I added the following:
CacheEnable disk /
CacheRoot "/var/cache/httpd"
CacheDirLength 2
CacheDirLevels 2

...and subsequently verified it was being populated and cleared it with htcacheclean.
Where else might this stale 301 data be perpetuated??
Thanks!
Hans
Comment: if you revert your configuration change, would it work then? if you run `httpd -t` it should provide you config file with line # where there is syntax error.
Comment: edited my original post, edited portion is in **bold**
Answer: first thing first, you need to address syntax error, so run httpd -t, like this (except for echo part), this way you can figure out which config file contains syntax error:
[root@wcmisdlin02 conf.d]# echo blah >> php.conf
[root@wcmisdlin02 conf.d]# httpd -t
AH00526: Syntax error on line 33 of /etc/httpd/conf.d/php.conf:
Invalid command 'blah', perhaps misspelled or defined by a module not included in the server configuration
[root@wcmisdlin02 conf.d]#

According to mod_alias - Apache HTTP Server Version 2.4, your RedirectMatch seems fine. Are you accessing right Virtual Host?
Comment: `httpd: Syntax error on line 149 of /etc/httpd/conf/httpd.conf: Cannot load /opt/CA/webagent/bin/libmod_sm22.so into server: libsmerrlog.so cannot open shared object file: No such file or directory`
Thing is - I've made both those libraries AND the containing directory (1) owned by apache, and (2) 777.....
Comment: And as I'd feared, commenting out the invalid conf line remediates the http -t error, but does not fix the broken redirect.  I'll update my original post to reflect this now.
Comment: you should either address this error or comment it out, as otherwise `httpd` won't start after reboot.
Comment: Yes, that's what I've done.  It is commented out, and the error no longer appears.  However, the redirect is still broken. :(
Comment: whatever you commented out has no effect on your redirect. I believe you're accessing it wrong, do one simple redirect and you'll see what I mean.
Comment: I understand that, but I'm not sure how to make my redirect any simpler...  it's just redirecting from one local directory url to another.  It worked before, and all I've changed is a couple elements in the (local) path of the redirect-to url.
_interesting thing is..._ creating a new redirect, pointed at the new local uri (`RedirectMatch 301 ^/test/ /new/specific/path/apidocs`) works fine.
so maybe _permanent_ really means **PERMANENT**??  I guess there must be some server-side 'routing-table' or cache that needs clearing...? (cleared my browser repeatedly, which logs reflect)
Comment: looks like apache does indeed cache 301s, and looks like **htcacheclean** is the tool to use to remedy this - now I just have to figure out how to use it correctly...
Comment: ha! that doesn't work either...  original post will, again, be amended with additional information...
Answer: ...so the "answer" is that the premise of the question is wrong.  That is, apache httpd is doing its job correctly.  The real issue is that there is a caching tier somewhere between httpd on the server and my local machine.  I take as evidence of this that:
1. a wget executed from my local machine is redirected to the old redirect-url, while
2. a wget executed from the server is correctly redirected to the new redirect-url,
and the access logs for the former look like:
"GET /old/specific/path/apidocs/ HTTP/1.1" 404

whereas the latter produced:
"GET /apidocs/ HTTP/1.0" 301
"GET /new/specific/path/apidocs/ HTTP/1.0" 200

Comment: You can use curl to try and force a cache eviction. `curl -H "Cache-Control: max-age=0" -i http://yourhost/apidocs`. Repeat for the destination URLs too. Big limitation though is the Vary header. If you have 'Vary: User-Agent', then you'd have to repeat for all the various User-Agent strings (yow!). Similarly for 'Vary: Accept-Encoding' (better, but still quite a lot). Suggest you post the response headers to the lookup that gives the 301, and the subsequent request.
Comment: @Cameron Kerr Thx for the tip. not yet an avid curl user, but aspire to be better. command results are:
`HTTP/1.1 301 Moved Permanently
Server: Apache/2.2.15 (Red Hat)
Location: http:///old/specific/path/apidocs/
Content-Length: 172
Content-Type: text/html
Date: Thu, 30 Apr 2015 20:24:41 GMT
Age: 85845
X-Cisco: WAE
301 Moved   Permanently301 Moved   Permanently`
Comment: Note the Age header, which indicates a cached response. It's also been through some Cisco appliance, which may be doing some caching (I'm not fimiliar with what WAEay mean)
Comment: Ah, Cisco WAN Accelleration Engine. I'd be very surprised if there wasn't some caching tricks going on there. I regularly find curl to be my most useful tool for diagnosis and validation for reverse-proxies and caching.
Comment: yep.  Darn, I should've seen that.  oh well, twas a long day.  At any rate, not surprised as a subsequent call to trace route shows a circuitous path from my box to the server--that's what ya get on a network managed by others--surprises!


Why aren't my pages caching?

Question: My Cache-Control header is always set to must-revalidate, no-cache, post-check=0, pre-check=0, private on the front page as well as every other page.
I've gone to configuration>performance and set Page cache maximum age to 5 mins, and I've gone to every view and set time-based caching to 5 mins as well.
There are a lot of articles about what to grep for in modules that might disable caching on a page, but these are all for Drupal 7, and I'm on Drupal 8.
What should I be looking for in my D8 modules that might be killing my caches?  If I don't fix this header, CloudFront won't like my pages very much.
EDIT: The poll module was invalidating my caches on pages that were showing poll results, but that didn't turn out to be my main issue.  After disabling the poll module, I was still getting must-revalidate, no-cache, post-check=0, pre-check=0, private, but only on my Firefox Developer Edition (with browser caching disabled, though that probably doesn't matter) while all other browsers (including regular Firefox, with or without caching disabled) are returning max-age=300, public as they should.  I'm concerned, does this mean users can bypass caching under the right circumstances?
Comment: Are there any custom modules that you wrote?
Answer: In general, this is pretty hard to answer without going into details and knowing what you did with your site. But to give you a few starting points...

To ask the obvious, you are testing this as an anonymous user without a session, right?
If you do have a session, check what values you have in there and who sets them
One thing to grep for is \Drupal::service('page_cache_kill_switch')->trigger();, although it could also be injected, so just look for ->trigger(). That's the equivalent of drupal_page_is_cacheable(FALSE) although are other ways to plug into that too.
Typical modules that set this are captcha or poll
If all else fails, look at FinishResponseSubscriber, that's the one that  adds those headers, specifically look at the request policies that return if a page is cacheable or not (the kill switch is one of those, as is the check for a session)
Comment: Thanks, Berdir, the poll module was indeed invalidating caches on pages with poll results (using the 'page_cache_kill_switch'), but please see my edit for a concern I have. I'll make a new question for it if someone thinks it's a good idea.
Comment: there are always ways to by pass page cache, all you have to do is add ?randomNumber and page cache is out. That was always like that. I'ts improved in D8 because there's also the dynamic page cache module, that only considers query arguments if something tells it that it is relevant for the page. Why that specific browser gets that header I can't say. Blind guess would be a do not track header, which I believe google analytics by default respects and will disable page caching. Or something similar like that.
Comment: Also look for modules that are setting cookies. If the browser request header includes a cookie, Drupal will return an uncached page.
Answer: to solve I used this module http_response_headers.
Can solution my bug whith headers http.
Steps:

Install Module
Configuration Response header configuration
Go path: /admin/config/system/response-headers
Add Response header configuration
Configuration the fields.
Save

For example, my case:

My Headers is change:
Before:

After:

I hope it helps in something!

Why aren't my pages caching?


Normal approximations: What is the probability that player A will have at least 10 points more than player B?

Question: Two players $A$ and $B$ play the following game. Player $A$ uses a fair 8-sided die with numbers of $1, ...,8$ and rolls it to earn points. For each roll player $A$ collects a numbers of points corresponding to the number shown on the die. Player $B$ uses a fair coin and flips it to earn points. If the outcome is "heads", then player B collects $1$ point, if "tails" player $B$ collect $8$ points. This game is as follows: Player $A$ rolls the die $n=50$ times and player $B$ flips the coin $n=50$ times, after which player $A$ has collected $Y_A$ points and player B has collected $Y_B$ points. After $n=50$ trials:
a) What is the probability that player $A$ will have at least $10$ points more than player $B$? Use normal approximations.
b) What is the probability that player $A$ and player $B$ together will have more than $340$ points? Use normal approximations.
c) What is the probability that player $B$ will have exactly $225$ points?

I have calculated the means/expected values to: mean($Y_A$) = 4,5 and mean($Y_B$) = 4,5, the variances I have calculated to: Var($Y_A$)=5,25 and Var($Y_B$)=12,25.
a)
Following @callculus answer:
I have in a table found Φ(.32) to be .6255. So 1 - 0.6255 = 0.3745, will that say that the probability for player A having at least 10 more points than player B is 37%
b)
Following the method from a):
$$P(Y_A + Y_B > 340) = 1- P(Y_A + Y_B >= 340) = 1 - Φ((340+0.5-450)/\sqrt{875}) \\= 1 - Φ(-3.7) = 1-0.00009 = 99.991\% \approx 100\%$$
There is almost 100% $P(Y_A+Y_B > 340).$
c)
Using the binomial PMF with $50$ trials and $25$ successes.
$$(50!)/((25!)*(50-25)! * 0.5^{25} * (1-0.5)^{50-25} = 0.112275173.$$
So $P(Y_B = 225) = 11\%.$
Answer: To start I give you some hints:
a) Firstly the inequlity $Y_A > Y_B + 10$ can be transformed to $Y_A-Y_B>10$. Then using the converse probability:
$P(Y_A-Y_B>10)=1-P(Y_a-Y_B\leq 9)$
The expected values of the random variables are  $E(Y_A)=E(Y_B)=50\cdot 4.5$.
The variances of the random variables are  $Var(Y_A)=50\cdot 5.25, Var(Y_B)=50\cdot 12.25$
Let $Y_D=Y_A-Y_B$. Then $E(Y_D)=50\cdot 4.5-50\cdot 4.5=0$.
And $Var(Y_D)=Var(Y_A)+Var(Y_B)=50\cdot 17.5=875$
With the help of the central limit theorem we get
$$P(Y_D\geq 10)=1-P(Y_D\leq 9)\approx 1-\Phi\left(\frac{9+0.5-0}{\sqrt{875}}\right)$$
$+0.5$ is the continuity correction factor.
b) $E(Y_A+Y_B)=E(Y_A)+E(Y_B), Var(Y_A+Y_B)=Var(Y_A)+Var(Y_B)$
c) Here you have to evaluate at what combinations of coin-flips you get exactly 225 points. If I´m right the only combination you get 225 points if you flip 25 times head and 25 times tail. Can you calculate the probability by using the binomial distribution ?
Comment: No. Something wrong there. Do you know what $\Phi$ is?
Comment: Ah forgot about the Φ. I have in a table found Φ(.32) to be .6255. So 1 - 0.6255 = 0.3745, will that say that the probability for player A having at least 10 more points than player B is 37%. Φ is the PDF of a normal distribution right?
Comment: @DanielRobotics At b) I have the same intermediate result. You can use some more decimal places. $1-\Phi(-3.735582)=1-0.00009=99.991\%\approx 100\%$
Comment: Ah alright, so the negative number will not affect the Φ-value?
Comment: @DanielRobotics If the z-value is negative then $\Phi(z)<0.5$. But if the z -value is very negative, $z<-3.5$, then $\Phi(z)\approx 0$. This is the case in b).
Comment: @DanielRobotics I´ve made an edit for c).
Comment: I have added my answer using the binomial PMF
Comment: @DanielRobotics Your result is right. Don´t be affraid to use some more digits. So $P(Y_B = 225)\approx 11.2275\%$
Comment: a) P(YD≥10)=1−P(YD≤9) = 1 - 0.3211 = 0.68, will that say that the probability for player A having at least 10 more points than player B is 68%?
Comment: I tried following the same method from your a) but I run into problem when using the central limit theorem. Edited my answer into the question text above.
Comment: It **is** supposed to be 225 points in (c), not 250. Just a typo. Because other revisions are in the queue, I didn't want to do an edit myself. // And I think you're right that a 25-25 split is the only way.
Comment: @BruceET Thanks for the hint and the confirmation about the 25-25 split. And additional you simulated result matches it as well.
Answer: Comment (not really an answer): I simulated this mainly because I was skeptical about the normal approximations. I found that $Y_A, Y_A -  Y_B,$
and $Y_A +  Y_B$ are nearly normal, but $Y_B$ is not. So I'd avoid a normally-approximated answer to (c).
In the process, I got approximate
results consistent with $E(Y_A), E(Y_B), Var(Y_A), Var(Y_B),$ and $P(Y_D \ge 10)$
in the Answer by @callculus (+1), which is an excellent guide to finishing
the problem. Other approximate numerical answers in the simulation may be of
interest.
<code>m = 10^6
a = replicate(m,  sum(sample(1:8, 50, repl=T)))
b = replicate(m,  sum(sample(c(1,8), 50, repl=T)))
mean(a);  var(a)
## 224.9918  # aprx E(Y_A) = 225
## 262.9595  # aprx Var(Y_A) = 262.5
mean(b);  var(b)
## 225.0187  # aprx E(Y_B) = 225
## 612.9044  # aprx Var(Y_B) = 612.5
mean(a-b >= 10);  mean(a + b > 340);  mean(b==225)
## 0.37403   # norm aprx P(Y_A - Y_B >= 10) = 0.374
## 0.999915
## 0.112175
</code>
Finally, here are plots of simulated distributions of the relevant random
variables, along with the 'best fitting' normal curves.
Comment: Directly. As callculus notes in their answer, this is just the probability that player B gets exactly $25$ heads and $25$ tails. You could also use a local central limit theorem in a pinch, but this seems beyond the level of the OP.
Comment: To be fair, the question did not ask to use normal approximations for part (c). The central limit theorem (at least, this version) is fairly lousy at calculating quantities of the form $P(X=x)$ anyway.
Comment: @Jason: Inconsistent with title, but you're right. How then would you do part (c)?


Redirect to non-www with HTTPS

Question: I installed an apache webserver and created a website. Let's Encrypt is used for https. I followed the auto-configuration process and the non-www url works fine. But if I want to redirect https://www to https://xxxxx.com with a .htaccess it doesn't work.
I tried with the following settings:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^.*$ https://%1/$1 [R=301,L]

mod_rewrite is enabled.
Comment: What is the error you get ? Do you have any rewrite logs ?
Answer: First of all, is the certificate even valid for the www-Host? If not, get a second one for the www-host and put that a separate <VirtualHost *:443>.
If the certificate is valid for the domain and the www-host, it sounds to me as if there is a ServerAlias for the www-Host missing in the <VirtualHost *:443>
Also, you'll have to put the "dot asterisk" in round brackets for the $1 to work (like you did in the RewriteCond for %1):
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^(.*)$ https://%1$1 [R=301,L]

Redirect to non-www with HTTPS


Hurricane Electric Tunnel with Pfsense?

Question: How would I setup a HE net Tunnel to route through PFsense so I can have v6 addresses on my servers? I already have the tunnel setup on their end, but there is no instructions for PFsense.
Answer: Note: These instructions appear to be incomplete. Read the full post before trying to follow this.

For over a year i have been using m0n0wall for its IPv6 connectivity. It isn't perfect, as m0n0wall still has a lot of IPv6 functionality missing (e.g. traffic shaping). But it does have extraordinarily simple IPv6 Tunnel Broker setup.
Now pfSense 2.1 has been released, with (hopefully) more IPv6 support than m0n0wall. On the other hand, the setup of an IPv6 tunnel is extraordinarily complicated. Now that i've spent three hours trying to make it work, i can finally document my results. It is filled with a lot out confusing, non-obvious, out-of-order, duplicated setup. Furthermore, there are still bugs that can cause your configuration to become invalid; requiring you to delete everything and start over.
Having said all that, here's how you configure IPv6 Hurricane Electric Tunnel Broker in pfSense.
But first the confusing background
But before we can setup anything, we have to take a moment to realize something utterly confusing, non-obvious, non-intuitive:

You do not send IPv6 traffic out your WAN connection

i have two network cards in my router:

WAN: (xl0, 3Com), connected to modem
LAN: (rl0, RealTek), connected to internal LAN hub

But IP (Internet Protocol) traffic does not go out my WAN 3Com interface. My connection to the Internet is through DSL, which means my router uses PPPoE to connect to my ISP.
This means that pfSense creates another interface:

WAN: (PPPoE), connects through PPPoE tunnel to Internet
OPT1: (xl0, 3Com) connected to modem
LAN: (rl0, RealTek) connected to internal LAN hub

So my connection to the internet actually goes out this virtual interface. This becomes important, because only IPv4 goes out this "PPPoE" interface.
In order to have IPv6 support, we will actually be creating a 4th interface; one that is dedicated to only IPv6 traffic:

WAN: (PPPoE), connects through PPPoE tunnel to Internet
WANv6: (HE_GW), connects through HE.net tunnel
OPT1: (xl0, 3Com) connected to modem
LAN: (rl0, RealTek) connected to internal LAN hub

Your Tunnel info
First we need your tunnel information from your TunnelBroker page:

IPv6 Tunnel Endpoints

Server IPv4 Address: 184.108.40.206
Server IPv6 Address: 2001:470:3c10:1178::1 /64
Client IPv6 Address: 2001:470:3c10:1178::2 /64

Routed IPv6 Prefixes

Routed /64: 2001:470:3c11:1178:: /64

This first section are addresses related to your tunnel connection to Hurricane Electric (addresses that will be assocated with your WAN interface and gateways). The second section is your "LAN" addresses.
Configuring pfSense 2.1 with a Hurricane Electric Tunnel Broker tunnel
Create A New Tunnel Interface

Under Interfaces -> (assign), select the GIF tab, and click the + to add a new tunnel:

Next configure the new GIF options:

Parent interface: WAN
gif remote address: 18.104.22.168 (Server IPv4 Address from HE tunnel details page)
gif tunnel local address: 2001:470:3c10:1178::2 (Client IPv6 Address from HE tunnel details page)
gif remote tunnel address: 2001:470:3c10:1178::1 64 (Server IPv6 Address from HE tunnel details page)
Description: HE.net IPv6 tunnel

and click Save.
Now your new GIF (Generic Interface) tunnel is configured:

Create a new IPv6 interface
Now that we've created a tunnel, we are going to create a separate IPv6-only interface that will send traffic out that tunnel.

Under Interfaces -> (assign), select the Interface assignments tab, and click the + to add a new interface:

Note: i happen to have an Atheros WiFi adapter, listed as OPT1. Don't let that confuse you.
In the drop-down for the newly added interface, select the previously created `GIF 188.8.131.52 (HE.net IPv6 tunnel):

and click Save.
After the interface OPT2 has been created, click it (either in the above list, or in the left menu under Interfaces -> OPT2.
Check Enable interface to reveal the configuration options:

Description: WANv6 (this is to differentiate it from your IPv4 WAN)
IPv6 Configuration Type: Static IPv6
IPv6 address: 2001:470:3c10:1178::2 64 (Client IPv6 Address from HE tunnel details page)

and click Save.
Click Apply Changes to make the new interface active.

Allow ICMP messages
In order to use IPv6 (and also IPv4) you need to ensure that your router does not attempt to block any ICMP packets. If some security expert tries to tell you that responding to ICMP packets is a security risk and they should be blocked, gently pat them on the head and tell them *"of course it is".  To allow incoming ICMP packets:

Click Firewall -> Rules
On the WAN tab, click +

Create the rule for IPv4 ICMP packets on the WAN interface:

Action: Pass
Interface: WAN
TCP/IP Version: IPv4
Protocol: ICMP
Description: Allow all IPv4 ICMP packets
Click Save

Click + to add another rule, this time to allow all IPv6 ICMP traffic on the WANv6 interface:

Action: Pass
Interface: WANv6
TCP/IP Version: IPv6
Protocol: ICMP
Description: Allow all IPv6 ICMP packets
Click Save

Click Apply Changes to apply your changes

Enable IPv6 on the pfSense LAN
Now you have to give the pfSense box an IPv6 address on your LAN interface. Just like it has a 192.168.1.1 IPv4 address on the LAN, now you need an IPv6 address. Except this address comes from Hurricane Electric; it is the Routed /64 address they give you.

Click Interfaces -> LAN
Change IPv6 Configuration Type to Static IPv6
Under the Static IPv6 configuration section, enter the routed /64 address provided by tunnelbroker:

Click Save
Click Apply Changes

Enable DHCPv6 Server
In order for clients to get IPv6 addresses, you have to enable the DHCPv6 server, and give it an address range it can assign addresses from.

Click Services -> DHCPv6 Server/RA
Check the Enable DHCPv6 server on LAN interface checkbox to reveal configuration options
In the Range from and to boxes, enter some range of addresses that are inside your Available Range, e.g.

Range: 2001:470:1f:b34::100:0 to 2001:470:1f:b34::100:fff
Comment: i never got to finish the steps and the screenshots. i came across a bug that causes pfSense to endlessly reboot without any way to recover except wipe the hard-drive. pfSense 2.1 doesn't support IPv6 fully anyway (traffic shaping); so i switched to monowall beta. It doesn't support IPv6 either (traffic shaping).
Comment: It might be nice to note this at the top of your post so people don't get disappointed when your instructions peter out.

Hurricane Electric Tunnel with Pfsense?


How to find a file name from the database

Question: I have a list of files in my html where I have removed the directory ImageFiles/ from the filename. So for example the file names look like below:
tulips.png
koala.png
jellyfish.png

Now if the user clicks on one of these file names, then I want to retrieve the file from the database, but in the database all files contain the directory ImageFiles/ at the start of the file name. So in the database the files look like this below:
ImageFiles/tulips.png
ImageFiles/koala.png
ImageFiles/jellyfish.png

My question is simply how do I finish the WHERE clause in order to retrieve the correct file from the database? For example if I am looking for the file tulips.png, how can I get the query to be able to find ImageFiles/tulips.png and only this file from the database?
Below is the mysqli query:
$getimage = $_GET['filename'];

    $imagequery = "SELECT ImageFile FROM Image WHERE (ImageFile = ?)";

            if (!$imagestmt = $mysqli->prepare($imagequery)) {
            // Handle errors with prepare operation here
    }

    // Bind parameter for statement
    $imagestmt->bind_param("s", $getimage);

    // Execute the statement
    $imagestmt->execute();

Answer: Just prepend the directory name to the $getimage variable:
$getimage = 'ImageFiles/' . $_GET['filename'];

Comment: Can I quickly ask, to display the image of the file do I just do this: ``?
Comment: @user1881090 - You have to wrap it in php tags, and echo it: `src=""`. In the future, ask such questions in a new question thread.
Comment: Thanks, I just wanted to save from adding another question, but thanks for the quick reply and for your answer :)


How to get all strokes/Rectangles which have been drawn on Frame by Graphics object?

Question: I am very new to Graphics2D and Frame library. I was trying out PDFRenderer(from PDFBox library) to draw the pdf on a Graphics2D object. Here is the code:
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
public class Example01 extends Frame {
  /**
   * Instantiates an Example01 object.
   **/
  public static void main(String args[]) {
    new Example01();
  }
  /**
   * Our Example01 constructor sets the frame's size, adds the
   * visual components, and then makes them visible to the user.
   * It uses an adapter class to deal with the user closing
   * the frame.
   **/
  public Example01() {
    //Title our frame.
    super("Java 2D Example01");
    //Set the size for the frame.
    setSize(1000,1000);
    //We need to turn on the visibility of our frame
    //by setting the Visible parameter to true.
    setVisible(true);
    //Now, we want to be sure we properly dispose of resources
    //this frame is using when the window is closed.  We use
    //an anonymous inner class adapter for this.
    addWindowListener(new WindowAdapter()
      {public void windowClosing(WindowEvent e)
         {dispose(); System.exit(0);}
      }
    );
  }
  /**
   * The paint method provides the real magic.  Here we
   * cast the Graphics object to Graphics2D to illustrate
   * that we may use the same old graphics capabilities with
   * Graphics2D that we are used to using with Graphics.
   **/
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D)g;
    try (PDDocument document = PDDocument.load(new File("C:\\Users\\prabhjot.rai\\Desktop\\xceligent\\9542899.pdf")))
    {
        PDFRenderer pdfRenderer = new PDFRenderer(document);
        pdfRenderer.renderPageToGraphics(1, g2d);
        System.out.println(g2d.getStroke());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

  }
}

What this does is, creates a frame in which I can see the whole pdf. I am trying to get the strokes drawn inside the frame - using the graphics object. How can I get those? I am open to use any library other than frame, since my method pdfRenderer.renderPageToGraphics(1, g2d) requires only a Graphics2D object.
Answer: I'm afraid this is not possible.
Graphics2D is an image based graphics tool, meaning that all actions you take are drawn to the image and forgotten, only the resulting pixels are stored.
The function getStroke() only return the current stroke, which will be used when you use any of the draw methods.
Many grahpics frameworks take a different approach (such as JavaFX), which supports drawing shapes and figures in a node based way, allowing you to decompose and change parts of the image (this renders the actual image after each change).


Rounding float/decimal to 3 decimal places exactly?

Question: I know there are many questions asking for this, but I have tried quite a few of the solutions but none seem to work exactly how I need it!
Most solutions work, however in my test data I have the float: 0.08095238095238096
If I round this to 4 I seem to get; 0.081 when I need to have 0.0809 and not rounded up that last place.
Also am I best using float or double for this type of number?
Thanks
Comment: possible duplicate of [Round a double to 2 significant figures after decimal point](http://stackoverflow.com/questions/2808535/round-a-double-to-2-significant-figures-after-decimal-point)
Comment: Your problem is your original number is wrong. If you need to get `0.809` you'll need to start with `0.8095238095238096` (not `0.08095238095238096` as you have).
Answer: You appear to want to round down to FOUR decimal places instead of rounding half up.
double d = 0.08095238095238096;
d = (long) (d * 10000) / 10000.0;

or
d = Math.floor(d * 10000) / 10000.0;

I assume you mean you want d = 0.0809 instead of 0.809.
Perhaps you are thinking of 3 significant digits which is a harder problem.
Its best to use double or BigDecimal instead of float unless you have a very good reason.
BTW: It is useful to have a clear idea of what you want, otherwise its going to be much harder to find it. ;)


How to access a button in a for loop and bind it to on_press in kivy

Question: I run into an error while trying to access two buttons from a group of buttons created in for loop and binding the button to on_press. Please what is the right way to do this (without .kv). How can I access individual button and bind them to different on_press event
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout

class TestApp(App):
        def build(self):
               layout=GridLayout(cols=1)
               for i in range(6):
                    btn = Button(text= str(i))
                    layout.add_widget(btn)

# error occurred here
              btn[0].bind(on_press=first)
              btn[1].bind(on_press=second)

         def first(self):
             pass
         def second(self):
             pass

              return layout

if __name__ == '__main__':
TestApp().run()

Answer: Code involving btn[0] implies a btn list, but there is no such list in your code. Here is a modified version of your code that does what you want:
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout

class TestApp(App):
    def build(self):
        layout=GridLayout(cols=1)
        for i in range(6):
            btn = Button(text= str(i))
            layout.add_widget(btn)
            if i == 0:
                btn.bind(on_press=self.first)
            elif i == 1:
                btn.bind(on_press=self.second)
        return layout

    def first(self, button_instance):
        print('first')

    def second(self, button_instance):
        print('second')

if __name__ == '__main__':
    TestApp().run()

Comment: using the code you gave me when I tried to change the background_color of the first button inside the ' def first()' function   it didn't change
Comment: What does the `first()` function look like?
Comment: The first function looks like this                     def first(self, button_instance):
       #this is not changing the background color
         self.btn1.background_color=(0,0,1,1)
        print('first')
Comment: The [documentation](https://kivy.org/doc/stable/api-kivy.uix.button.html#kivy.uix.button.Button.background_color) says `To set a plain color, set the background_normal to ''`
Answer: I still haven't fully solved my problem, however, the following code returned the object created on the button and the value assigned to it. So I believe that this solution can help you.
from functools import partial

for x in test:
    btn = Button(text=x["CustomerName"], background_color=[0.9, 0.9, 0.9, 0.9], size_hint_y=None, height=40)
    btn.bind(on_press=partial(self.mostra,x["CustomerName"]))
    self.ids.grd1.add_widget(btn)

def mostra(self,*args):
    print(args)

Looking at the code I posted I used bind after creating the button (btn.bind) and in it I passed the function that shows on the screen the value saved in the x of my loop. In the function (mostra) the use of self and * args is mandatory.
At the beginning there is the line (from functools import partial) that line is necessary to execute the function show inside the bind.


How can we achive tabbarcontroller like functionlity using UIbutton?

Question: I wanted two switched between two three view controller by preserving there current context exactly like what the TabBarController does. But without using TabBarController template.
See the attache screen shot.
?
Comment: please use custom tab bar controller
Answer: If you've been working on same UIView, you can do something like
Take a UISegmentedControl and three UIViews in your .h file.
Buind each view and, segment control with changeView action in IB for  UIControlEventsValueChanged
- (IBAction) changeView
{
 switch (segmentViews.selectedSegmentIndex)
 {
    case 0:
        [firstView setHidden:NO];
        [secondView setHidden:YES];
        [thirdView setHidden:YES];
        break;

    case 1:
        [firstView setHidden:YES];
        [secondView setHidden:NO];
        [thirdView setHidden:YES];
        break;

    case 2:
        [firstView setHidden:YES];
        [secondView setHidden:YES];
        [thirdView setHidden:NO];
        break;
 }
}

It will change with the change of selectedSegmentIndex gets changed. Give proper backgrondColorit will look like tapbar. You can even add animation for view transition effects.
It can be works well with different UIViewControllers, but you've to add UISegmentControl and maintain UIDesign in each controller. Also need to maintain currentIndex.
Answer: In your VC you should define 3 UIViewController and initialize them in the -(id)init method. Then when you press a button you only attach the corresponding view controller on self.view.
Answer: You can have one "master" view controller, and have it put the control at the bottom of its view. Then it would "present" and "dismiss" the 3 view controllers as the buttons are pushed (I hope that's a segmented control you are showing). This should all work nicely just using the standard features of UIViewController.
EDIT: To deal with the transition, you will need to play with various ideas to find the one you like best. Some ideas:

when a different tab is tapped, dismiss the view showing and present the new view with no animation. This should mimic what the tabBarController does
read the paragraph in UIViewController class description titled 'Implementing a Container View Controller' - it shows you the various ways container views can cause a transition from viewController A to viewController B
Comment: but tab tab do not work like this. It preserve the contain(like variable, view added on it etc) of the previous view and show to us when we come back on it. Dismissing controller leads to start from beginning again for that view.
Answer: In your Code you should define 3 UIViewController and you can set hidden property of remain two views on pressing any one view. Then when you press any other button you then you can show  hidden property and set hidden property for previous view.


Report a partir de DataSet criado em uma Class

Question: Como faço para criar um Report do Visual Studio 2013 a partir de um DataTable (ou DataSet) criado em um método?
Ao buscar a fonte de dados do Report.rdlc eu referencio a classe onde a DataTable é criada, mas ela não é listada como DataSource.
Tentei adicionar um DataSet.xsd ao meu projeto, criei um DataTable com o mesmo schema do que será gerado, mas não consigo populá-lo com os dados do método.
Como devo proceder?
Obrigado.
Answer: Ok, a resposta era mais simples do que eu imaginava.
Apenas estava faltando criar uma instância do DataSet como uma classe qualquer. Achava que não seria necessário mas aprendi na marra que sim.


Convert 19-digit string to a number accurately in Python

Question: I have a large data file with columns of numbers delimited by blank spaces.  I would like to read them in as a numpy array.
I used numpy.loadtxt(filename) to read in the file.  The problem came when the code is trying to convert this 19-digit string to a number; it seems that it can only represent the first 17 digits accurately.
Here is a simplified example:
from StringIO import StringIO
import numpy as np

#use this s string to mimick the input txt file
s = StringIO('1237657220412736271 39843.3948')
arr = np.loadtxt(s)
print int(arr[0])

If you run it, you get
1237657220412736256

I know that it is possible to specify the type of data you have from np.loadtxt(), but even though I specified it to read it the first number as long integer, it still cannot represent the 19-digit string of number accurately.
Is there a better way of doing this?
Comment: Where did you specify the data type for `loadtxt()`? I don't see it in your posted code.
Comment: Why are you using numpy for this?
Comment: Do you just need to use `float64` or `float128` instead of the default, or do you actually need to handle arbitrary-precision decimals?
Comment: @Hewgill: I probably didn't in this posted code. Sorry but I did that when I test np.loadtxt.
Comment: @FogleBird: It was someone else's code so I tried to follow the the code's format.
Answer:
even though I specified it to read it the first number as long integer

Well, given that your second value is a float, I'm not sure how you did that with a single type. But take that away, and you can read the first number as a longer integer type, and everything works fine:
>>> s = cStringIO.StringIO('1237657220412736271 39843')
>>> arr = np.loadtxt(s, dtype='i8')
>>> int(arr[0])
1237657220412736271

And likewise, if you specify a heterogeneous format like ('i8', 'f8') and feed in your original string, that works fine with the original string.
So, my suspicion is that you didn't do what you think you did, and that's why it didn't work.
Another possibility is that by "long integer" you literally meant "a C long", and you're on a 32-bit platform or 64-bit Windows, where that means a 32-bit number. But I'm pretty sure numpy took that type away long again—and, if they didn't, it would give you a different problem than the one you're seeing.
Comment: If you just specify `i8` then you still need to convert the second column into float.
Comment: @tiago: Did you not read the text, or the code, beyond that one line? I explained that you have to take the float away to use `'i8'`, and showed that it works in that case, and then I explained how to specify a heterogeneous format immediately after that.
Comment: from your answer one would be tempted to do `dtype=('i8', 'f8')`, which doesn't work.
Comment: @tiago: Then one would get a `ValueError` immediately, and either go read the docs, or ask here how to do it. I'm not trying to write his code for him.
Answer: When you call np.loadtxt, it is assuming all elements on the file are floats. This causes a precision problem when you convert it back to integer. You can specify a structured array read in np.loadtxt, which will enable it to read different columns with different data types:
arr = np.loadtxt(s, dtype={'names': ('ints', 'floats'),
                                     'formats': ('i8', 'f8')})

The difference here is that you get a structured array instead of a 2D array of a given datatype. You have to index it differently (either by name or index number), but you can check that the ints are read correctly:
>>> int(arr[0][0])
1237657220412736271
>>> int(arr['ints'][0])
1237657220412736271

(Note that this syntax will fail with your specific string s because it only has one line and will give a 0-d array, but it works with files of more than one line.)
Another alternative is to do two loads of np.loadtxt, one for each column:
arr1 = np.loadtxt(s, dtype='i8', usecols=(0,))
arr2 = np.loadtxt(s, dtype='f8', usecols=(1,))

Answer: I tried this:
>>> s = '1237657220412736271 39843.3948'
>>> a = s.split()
>>> int(a[0])
1237657220412736271

Unfortunately when numpy reads the 19-digit number as a floating point number, there is not enough precision to get all the significant digits, so there is a rounding error.  If you know the number is always going to fit in an int but is too large to be represented exactly in a double, you'll probably want need to do something like what I did above to work around that limitation.
Comment: And do what? Store it as an int plus a float? That would be hard to work with.
Comment: @abarnert Just depends on the application.  The OP was casting to int, so I assumed that they wanted an int representation.
Comment: The point is, `numpy` is loading this as a float64, and losing precision; the fact that he has an infinite-precision `int` copy of the same data outside of `numpy` doesn't seem all that useful.


boundary of the set {0, 1, 2} ∪ (0, 3) in R

Question: I came up with an answer of (0,3]
I see that each epsilon neighborhood of x intersects A and R/A.
Does this logic work for this problem? It seems simple enough as both sets share 0,1,2 but not 3.
Comment: $
\{0,1,2\}\cup (0,3)=[0,3)
$.
Comment: Ah nice catch. Thanks!
Answer: Notice that $\{0,1,2\}\cup (0,3)=[0,3)$.
The closure of the set is $[0,3]$ and the interior is $(0,3)$, so the boundary is $\{0,3\}$


When two intervals are disjoint, then outer measure is

Question: I am self-studying real analysis by Sheldon Axler. This is a problem 7 from chapter 2A. He uses $|A|$ sign to indicate the outer measure of a set $A$.
Suppose $a, b, c, d$ are real numbers with $a<b$ and $c<d$. Prove that
\begin{equation*}
|(a,b)\cup (c, d)|=(b-a)+(d-c)\text{ if and only if }(a,b)\cap (c, d)=\emptyset.
\end{equation*}
How do I prove if $(a, b)\cap(c, d)=\emptyset$ then $|(a,b)\cup (c, d)|=(b-a)+(d-c)$? I know $|(a,b)\cup (c, d)|\leq(b-a)+(d-c)$ but how do I get the equality? Thanks.
Answer: Let $\epsilon>0$ and by disjointness assume with loss  of generalty that $b<c$
Then $(a,b) \cup (c,d) \supset [a+\epsilon,b-\epsilon] \cup [c+\epsilon,d-\epsilon]=:I_1 \cup I_2$
Not that $I_1,I_2$ are compact disjoint intervals so $d(I_1,I_2)=\inf\{|x-y|:x \in I_1,y \in I_2\}>0$
From this you have that $|I_1 \cup I_2|=|I_1|+|I_2|=(b-a)+(d-c)-4\epsilon$
So $|(a,b) \cup (c,d)| \geq (b-a)+(d-c)-4\epsilon$.
Sending $\epsilon \to 0$ gives you the conclusion.


Swift Universal framework issue on Xcode 10.2

Question: I have a swift framework and I use on objective c project. I create a fat framework with script. It works till Xcode 10.2.
I try to create fat framework on Xcode 10.2. It compiled successful but when I added on my objective-c project it not working on simulator.
Apple's release notes include my error but I didn't work. (https://developer.apple.com/documentation/xcode_release_notes/xcode_10_2_release_notes in known issues)
How can I create fat framework headers file for simulator?
Comment: Hi, to help you quickly can you please share your script here.
Comment: Please also add the error message instead of sharing document that includes that message.
Answer: Try this one
https://gist.github.com/closerminds/8a8d8db6f87d2a65c4487f396f986737
This use the workaround proposed by Apple
Comment: It's ok to link to an answer but the answer must be minimally useful without the link.


New Site Design - Hard to Read?

Question: To start, I like the new design in terms of color-themes, fonts (I've always been a fan of Roboto) and usability; it looks fantastic!  That said, the lightness of font-family/low font-weight is making it harder to read questions, to navigate through the list of questions, and especially to read comments because they are a slightly smaller font-size.  I am not sure that I have a great suggestion but here are a couple of ideas:

Giving certain things (Comments, Questions-List, Question-Page text) a heavier font-weight/larger font-size or possibly a different color that would stand out more.
Utilizing background colors to make the existing text stand out a little more
Reverting to the previous font or using Arial, "Helvetica Neue", Helvetica, sans-serif; like Stack Overflow does.

I don't know if this is the correct forum to start a discussion about this (or if there even is one), and I am certainly not saying anything negative about the new design in general, but I am sure that we can all agree which of the following two screen-snips is easier to read:
Magento Stack Exchange:

Stack Overflow:
Comment: are u  from stackexchanges?
Comment: @AmitBera - If you mean do I represent Stack Exchange, No.  I am not affiliated outside of my activity within the Stack Exchange/Overflow communities.
Answer: I see magento.stackexchange.com as below

As you can see, the font seems good and which is not look like what you shared in your question. The font used here as per the browser console is Roboto, Arial, sans-serif. The font is same in both Mozilla and Chrome.
Also if you see the primary.css file which is used by this site, you can see this definition
html,body {
    color: #3D4245;
    font-family: 'Roboto',Arial,sans-serif;
    font-size: 13px;
    line-height: 1.30769231
}

And most of the elements are inheriting this style. Example:

So there may be something went wrong on your side, maybe. I cannot point out what exactly went wrong here since I am not a CSS expert.
Side note: StackOverflow seems to use Arial, "Helvetica Neue", Helvetica, sans-serif.
Comment: Thanks for pointing this out.  I typically use Chrome, but I have viewed some pages in Firefox that look the same way that you posted.  I am guessing that Chrome is using `Roboto`, which I have installed in my system fonts, and Firefox is using the fallback `Arial` which looks the same as StackOverflow, despite the different font-family assignments.  As you pointed out, this won't be affecting everyone, but I am sure I am not the only one who has Roboto installed.

New Site Design - Hard to Read?


DropzoneJS - Exibir arquivos - Como fazer?

Question: Como faço para o dropzoneJS exibir os arquivos que já foram upados ?
Segui os passos da documentação e está fazendo o upload normalmente, porém não exibir os arquivos já upados.
Meu código HTML de form:
<form action="upload.php" class="dropzone" id="my-dropzone"></form>

Script:

Código no upload.php:
<?php

$ds = DIRECTORY_SEPARATOR;
$storeFolder = 'uploads';

if (!empty($_FILES)) {

   $tempFile = $_FILES['file']['tmp_name'];
   $targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
   $targetFile =  $targetPath. $_FILES['file']['name'];
   move_uploaded_file($tempFile,$targetFile);

} else {

  $result  = array();
  $files = scandir($storeFolder);
  if ( false!==$files ) {
    foreach ( $files as $file ) {
        if ( '.'!=$file && '..'!=$file) {
            $obj['name'] = $file;
            $obj['size'] = filesize($storeFolder.$ds.$file);
            $result[] = $obj;
        }
    }
}
    header('Content-type: text/json');
    header('Content-type: application/json');
    echo json_encode($result);
}
?>

Answer: Consegui resolver e criei um botão que abre os arquivos já enviados também, fiz algumas alterações no script, segue abaixo:

Comment: Olá João, ambas as soluções, estava através de algo que fizesse o upload, download e leitura dos arquivos
Comment: Oi chico, estava procurando uma solução parecida com a sua. Estou com uma duvida. Você estava querendo "obter " os aquivos que já foram armazenados em algum momento para o usuario deletar e/ou subir outros arquivos?


Universal covering of $SO(3,\mathbb{R})$

Question: How do you prove that the universal covering of $SO(3, \mathbb{R})$ is $S^3$ ? Or equivalently, that it is diffeomorphic to $P_3\mathbb{R}$ ?
Thank you for your answers.
Comment: The group $SU(2) \cong S^3$ of unit quaternions acts by conjugation on the imaginary quaternions. Check that this gives a surjective homomorphism $SU(2) \twoheadrightarrow SO(3)$ with kernel $\pm \operatorname{id}$. See [here](http://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Conversion_to_and_from_the_matrix_representation) for an explicit formula. See also [this nice blog post](http://qchu.wordpress.com/2011/02/12/su2-and-the-quaternions/) by Qiaochu Yuan.
Answer: Any element of $SO(3)$ is rotation about an axis in $\mathbb{R}^3$ - that is each element can be represented by an axis of rotation and an angle of rotation.
$\mathbb{RP}^3$ is $\mathbb{D}^3$ with antipodal points identified. Given a point in $\mathbb{D}^3$ it is some distance (between -1 and 1) on a vector from the origin. This vector gives you the axis of rotation for a point in $\mathbb{RP}^3$. We still need the angles of rotation, but these will be given by the distance between -1 to 1. Scale those values to be $-\pi$ to $\pi$, Note that then antipodal points of $\mathbb{D}^3$ are mapped to the same point in $\mathbb{RP}^3$
Comment: @SelimGhazouani: Note that this is simply a rotation by $180°$ around the third eigenvector, e.g. it can be written $$\begin{pmatrix} \cos\theta & \sin \theta & 0\\ -\sin \theta & \cos \theta & 0 \\ 0 & 0 & 1 \end{pmatrix}$$ for $\theta = \pi$. aru is right. It is a standard theorem in linear algebra that any matrix $A\in SO(3)$ can be brought into the above form with some $\theta$ by a orthogonal change of coordinates. You can also look at it this way: Given $A$, we can find an eigenvector $v$ to the eigenvalue $1$ and the restriction of $A$ to the 2-dim subspace $v^\perp$ must be a rotation.
Comment: Wouldn't those change orientation?
Comment: Thank you for your answer. Your first statement seems false : i think you forgot the elements which are a relexion on an axis and a rotation-reflexion on the orthogonal plane.
Comment: I don't think so. Its eigenvalues are $\{-1,-1,1\}$
Comment: How do you find an eingenvector to the eingenvalue 1 ? Can't the case $\{-1, e^{i\theta}, -e^{-i\theta}\} $ occur ?
Answer: One can also show that the adjoint representation of su(2) is so(3) and find the covering map quite explicitly.


Calculate selling price to achieve at least 10% profit

Question: I need to run a loop in an SQL query. My query looks at [PROFIT_MARGIN] to ensure the %PROFIT is above 10% (in this case).
But some figures are below 10 or produce a minus figure, so I need to increase the price until the [PROFIT_MARGIN] reaches a more favorable point.
SELECT [RRP], [COST], [PROFIT], ([PROFIT/RRP]*100) AS [PROFIT_MARGIN],
       CASE WHEN ([PROFIT/RRP]*100) > 10
            THEN RRP
            ****** OH NO THE PROFIT IS LESS THAN 10, WE NEED TO INCREASE THE RRP UNTIL SUCH A POINT THAT THE PROFIT_MARGIN is EQUAL to 10 THEN SET THE PRICE TO THAT NEW FIGURE ******
       END AS [PRICE]
FROM SOME_TABLE

Some Sample Data
RRP   Cost   Profit  Profit Margin
25    8      17      68
5.95  7.08   -1.13   -18.9915966387
17    13.02  3.98    23.4117647059
1.85  4.57   -2.72  -147.027027027
2.3   4.74   -2.44   -106.0869565217
2.65  5.02   -2.37   -89.4339622642

My guess is that I need to artificially increase the [RRP] until such a point that the end [PROFIT_MARGIN] column hits 10%.
My approach, might be wrong in the requirement for the loop, I'm no SQL Pro.
Comment: If you would add sample data and expected result your question will be answered much faster.
Comment: As per my understanding, you want to increase RRP, to reach profit larger or equal 10%. So, you need to calculate Cost to RRP instead Profit to RRP. New RRP must be Cost + 10%. Am i right?
Comment: Maciej Los - Yes you are correct, the other answers are not and miss the point.  This needs to be a SELECT Query, not an UPDATE or an INSERT.  I just need to increase the RRP to a point WHERE the PROFIT MARGIN is = to 10, so I guess keep looping until it finds that point.
Answer: You don't need to use a loop for something of this nature.
Your basic check requires that profit should be at least 10%, so you simply have to check if the profit margin is < 10%, and increase the selling price otherwise.
Here's a sample with the above data that you can execute as is:
CREATE TABLE #SOME_TABLE
    (
      [RRP] NUMERIC ,
      [Cost] NUMERIC ,
      [Profit] NUMERIC ,
      [Profit_Margin] NUMERIC
    );

INSERT  INTO #SOME_TABLE
        ( [RRP], [Cost], [Profit], [Profit_Margin] )
VALUES  ( 25, 8, 17, 68 ),
        ( 5.95, 7.08, -1.13, -18.9915966387 ),
        ( 17, 13.02, 3.98, 23.4117647059 ),
        ( 1.85, 4.57, -2.72, -147.027027027 ),
        ( 2.3, 4.74, -2.44, -106.0869565217 ),
        ( 2.65, 5.02, -2.37, -89.4339622642 );

DECLARE @MinProfitMargin INT = 10

SELECT  RRP ,
        Cost ,
        Profit ,
        Profit_Margin ,
        CASE WHEN Profit_Margin < @MinProfitMargin
             THEN Cost * 1.1
             ELSE RRP
        END AS RRPor10PercentProfit
FROM    #SOME_TABLE

DROP TABLE #SOME_TABLE

The Output:
RRP Cost    Profit  Profit_Margin   RRPor10PercentProfit
25  8       17      68              25.0
6   7       -1      -19             7.7
17  13      4       23              17.0
2   5       -3      -147            5.5
2   5       -2      -106            5.5
3   5       -2      -89             5.5

The final column RRPor10PercentProfit shows you the current RRP if it achieves at least 10% profit, otherwise it shows you the value required to achieve 10% profit. This is calculated in this section of the code:
-- is the Profit_Margin less than my variable (10%)
CASE WHEN Profit_Margin < @MinProfitMargin
     -- if so add 10% to cost price
     THEN Cost * 1.1
     -- otherwise give me the RRP
     ELSE RRP
END AS RRPor10PercentProfit

Comment: `RRP = Cost * 1.1` - that's what i suggested. Great minds thinking the same ;)
Comment: @Stuart my answer provides a select query? have you run the code block to check the output? the insert is just used to populate a temp table for testing purposes.
Comment: OH!!! What an idiot am I trying to over complicate such a simple thing.  Thanks Tanner.
Comment: down vote? really? please explain what's wrong with this if anything?
Comment: It wasn't me. I upvoted your answer, very good answer! [EDIT] Please, see my answer.
Comment: @MaciejLos it's ok, I didn't suspect you. I've had a few rouge down votes in the last few days, think somebody might have a target on me.
Comment: Pure hate is hard to cure... Sad, but true.
Comment: Sorry Guys, but you have missed the point completely here.  This needs to be a SELECT Query, not an UPDATE or an INSERT.  I just need to increase the RRP to a point WHERE the PROFIT MARGIN is = to 10, so I guess keep looping until it finds that point.
Comment: Actually I retract my comment about simplicity. Increasing the price by Multipling the cost price by 1.1 is NOT the same as calculating the Margin Difference.  I have found instances where this becomes even less.  It needs to be a calculated MARGINAL Increase not Cost+ or RRP+
Answer: Please, read my comment to the question and see the solution provided by Tanner.
So, if you want to update RRP, use UPDATE statement:
UPDATE t1 SET [RRP] = t2.[COST] *1.1
FROM tableName t1 INNER JOIN tableName t2 ON t1.PKey = t2.PKey
WHERE (t1.[RRP]/t1.[COST]) < 1.1

Thanks Tanner, for your valuable comment ;)
Comment: I think your where clause is incorrect: `(t1.[COST]/t1.[RRP]*100)` - e.g. (5/5)*100 = 100. So if cost price = RRP it wouldn't be updated.
Comment: Sorry, but you have missed the point completely here. This needs to be a SELECT Query, not an UPDATE or an INSERT. I just need to increase the RRP to a point WHERE the PROFIT MARGIN is = to 10, so I guess keep looping until it finds that point.
Comment: @Stuart, i think i didn't miss anything. "Increase" means change original value. Finally, i wrote: "If you want to update...". Cheers, Maciej
Comment: YES YOU ARE RIGHT, I am a moron, I have completely tried to over engineer, the simplicity though me right off. Thank you.
Comment: Actually I retract my comment about simplicity.  Increasing the price by Multipling the cost price by 1.1 is NOT the same as calculating the Margin Difference.
Comment: @Stuart, imagine that: Profit_Margin for RRP =25 and Cost=8 is equal to 17, which means 25-8=17. Profit_margin calculated for the second record is less then zero. So, you'll never reach Profit_Margin at least equal to 10, because every number times value less then zero is always will give you less then zero. Try this (second row RRP=5,95): (12000/7.08)*100=-0.009416667 ;) Conclusion: Profi_Margin is Cost times 1.1 ;)


Translating Object in OpenTK

Question: Hello I'm currently using the
 Vector3 translation = new Vector3( tx, ty, tz);
        GL.Translate(translation);

Way of translating an object in OpenTK where the Vector3 values are from -1 to 1
How do I change this and make the values of a movable object to go pixel wise that way I
can set up a scene based on the user's screen size.
Thanks!
Answer: In legacy OpenGL 1.x, you can achieve this by setting up an orthographic projection with GL.Ortho:
GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
GL.Ortho(0, Width, Height, 0, -1, 1);

GL.MatrixMode(MatrixMode.Modelview);
GL.LoadIdentity();
GL.Translate(1.0f, 0, 0); // translates by 1 pixel

Be forewarned that this will make your application difficult to port to high-resolution (4K) monitors. I would advise using a resolution-independent approach if at all possible. For example:
GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
GL.Ortho(-1, 1, 1, -1, -1, 1);

GL.MatrixMode(MatrixMode.Modelview);
GL.LoadIdentity();
GL.Translate(1.0f / Width, 0, 0); // translates by 1 pixel

Comment: Now nothing is showing up on my screen. Thank you for the reply!
Comment: Here is my draw code:

GL.BindTexture(TextureTarget.Texture2D, textID);
                    GL.Translate(0.5, 0.7, 0);
                    drawObject(100, 20, 0.15f, 0.15f);
                    GL.Translate(-0.7, -0.3, 0);
                    drawObject(100, 60, 0.15f, 0.15f);
                    GL.Translate(0.8, -0.5, 0);
                    drawObject(100, 100,0.15f, 0.15f);
                    GL.Translate(1, 1, 0);

                    GL.PopMatrix();
                    GL.Flush();
Comment: [code](GL.BindTexture( TextureTarget.Texture2D, textID);
                    GL.Translate(0.5, 0.7, 0);
                    drawObject(100, 20, 0.15f, 0.15f);
                    GL.Translate(-0.7, -0.3, 0);
                    drawObject(100, 60, 0.15f, 0.15f);
                    GL.Translate(0.8, -0.5, 0);
                    drawObject(100, 100,0.15f, 0.15f);
                    GL.Translate(1, 1, 0);

                    GL.PopMatrix();
                    GL.Flush(); )

Translating Object in OpenTK


SQL Query to find the Row with first change of data

Question:

UniqueId
ITEM
DATE

1
A
2022-01-01

2
A
2022-01-02

3
B
2022-01-03

4
B
2022-01-04

5
A
2022-01-05

6
A
2022-01-06

7
B
2022-01-07

8
B
2022-01-08

9
A
2022-01-09

10
A
2022-01-10

11
A
2022-01-11

I have above table where the item is changing from A to B and then B to A (etc).
The the most recent item in the table based on the date is A (the last row).
I need to find the date on which this last item (A) was started to be in effect.
So in this case the item A was in effect from 2022-01-09 onwards (UniqueId 9).
How can I find the UniqueId or the date of item A, where it got changed to be in effect (Row 9)?
Thank you.
Comment: Did I understand correctly? You want to know dateTime of the last time a row modified?
Answer: with data as (
    select *,
        last_value(item) over (order by "date") as last_item,
        lag(item) over (order by "date") as prev_item
    from T
)
select
    max(case when item = last_item and item <> prev_item then "date" end) as max_date
from data;

or
with data as (
    select *,
        case when item <> lag(item)        over (order by "date")
              and item =  last_value(item) over (order by "date")
             then 1 end as flag
    from T
)
select max("date") as last_transition_date
from data
where flag = 1;

https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=bd5f6398c0167d74c26a67fafac5225e
Supposing you need all the data:
with data as (
    select *,
        case when item <> lag(item)        over (order by "date")
              and item =  last_value(item) over (order by "date")
             then 1 end as flag
    from T
)
select *,
    max(case when flag = 1 then "date" end) over () as last_transition_date
from data;

Comment: Thank you for this solution !! this  fits my requirement
Answer: Getting a flag using a comparison of current item with previous item in time, using LAG() is indeed the way.
But it's absolutely sufficient to get the highest date and highest unique (as both are sorted ascending together) where the obtained flag is 1:
WITH
-- your input
indata(UniqueId,ITEM,DATE) AS (
          SELECT 1,'A',DATE '2022-01-01'
UNION ALL SELECT 2,'A',DATE '2022-01-02'
UNION ALL SELECT 3,'B',DATE '2022-01-03'
UNION ALL SELECT 4,'B',DATE '2022-01-04'
UNION ALL SELECT 5,'A',DATE '2022-01-05'
UNION ALL SELECT 6,'A',DATE '2022-01-06'
UNION ALL SELECT 7,'B',DATE '2022-01-07'
UNION ALL SELECT 8,'B',DATE '2022-01-08'
UNION ALL SELECT 9,'A',DATE '2022-01-09'
UNION ALL SELECT 10,'A',DATE '2022-01-10'
UNION ALL SELECT 11,'A',DATE '2022-01-11'
)
-- real query starts here; replace following comma with "WITH"
,
w_change_ind AS (
  SELECT
    *
  , CASE WHEN LAG(item) OVER(ORDER BY date) <> item
      THEN 1
      ELSE 0
    END AS chg_ind
  FROM indata
)
SELECT
  MAX(uniqueid) AS uqid
, MAX(date)     AS dt
FROM w_change_ind
 WHERE chg_ind=1
;
-- out  uqid |     dt
-- out ------+------------
-- out     9 | 2022-01-09

Answer: Based on your description, this is one way to do what you want.
select top 1 * from table1
where item ='A'
order by uniqueid desc

If this is not what you want, then you will have to provide additional information.
Comment: he wants clearly line number 9, which your query doesn't provide
Comment: @nbk, corrected by changing to uniqueid.
Comment: You're still assuming that last item will always be A. And the assumption that id values are in ascending order very likely a bad idea especially when the date column is present.