text:
Q: create button in main page to redirect to a response function I have  a csv file  in a server. I  have  created a response function to download it in the  users  browser. It work fine. Now  I need   to create a button  in the  main index.html  and create a response  function so  that  file  gets downloaded on clicking it. I just need the download , no redirect to new page required
@app.route('/csv/')
def download_csv():
    csv = p
    response = make_response(csv)
    cd = 'attachment; filename=RosterUnified.csv'
    response.headers['Content-Disposition'] = cd
    response.mimetype='text/csv'

    return response

A: Your question is quite confusing, but if you are simply asking for a button to download the file without making the browser leave the current page:
Download the file

This creates a link which you can style in CSS to appear like a button.
Please tell me if I misunderstood the question.


text:
Q: calling python builtin dict on a mock I'd like to be able to setup a mock that allows me to return something when I apply the builtin dict method.
I've tried using __iter__ to no avail.  I can't seem to get anything but an empty dictionary:
import mock
mocked_object = mock.MagicMock()
mocked_object.__iter__.return_value = [1, 2, 3]
dict(mocked_object)
# {}

A: From dict documentation

If a positional argument is given and it is a mapping object, a dictionary is created with the same key-value pairs as the mapping object. Otherwise, the positional argument must be an iterable object. Each item in the iterable must itself be an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value.

MagicMock objects expose a keys method just because are mock objects and so dict() will consider they mapping objects. Unfortunately that way is little bit complicated to use if we want that on dict call mock become a dictionary with predefined key-values. The follow examples show how to implement a dict conversion to a predefined dictionary by use mapping object protocol:
>>> m = MagicMock()
>>> d = {"a":"A", "b":"B", "c":"C"}
>>> m.keys.return_value.__iter__.return_value = ["a", "b", "c"]
>>> m.__getitem__.side_effect = ["A","B","C"]
>>> dict(m)
{'a': 'A', 'c': 'C', 'b': 'B'}
>>> #Little bit generic
>>> m.keys.return_value.__iter__.return_value = d.keys()
>>> m.__getitem__.side_effect = lambda k:d[k]
>>> dict(m)
{'a': 'A', 'c': 'C', 'b': 'B'}

Both are little bit hard to read and in our test we would like something of simpler to read.
To lead dict to use iterator instead mapping we can just remove keys method from our mock and set __iter__.return_value:
>>> del m.keys
>>> m.__iter__.return_value = [("a","A"),("b","B"),("c","C")]
>>> dict(m)
{'a': 'A', 'c': 'C', 'b': 'B'}
>>> #Little bit generic
>>> m.__iter__.return_value = d.items()
>>> dict(m)
{'a': 'A', 'c': 'C', 'b': 'B'}

IMHO that is a simple and neat way to set up your mock and get a predefined dictionary from dict call.

A: Actually I think you need to do something like this:
mocked_object.keys.return_value.__iter__.return_value = [1, 2, 3]

With this, the dict method will give you an object with those keys, and the result of getattr(mocked_object, '1') (so, another mocked method) as values. I think you might be able to do what you want by mocking the keys() method as well if you want more control on the result.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Im trying to run compass compiler through Grunt but it does not do anything I'm trying to compile my scss with compass compiler using Grunt, but I get stuck when it runs the task, and it only say: Running compass:dist  task and never shows anything else in the console.
This is what I'm getting, and I leave it there for hours and never shows me anything else:

Versions:

*

*Ruby: v2.1.6p336

*NPM: v3.10.8

*Sass: v3.4.22

*Compass: v1.0.3

*Grunt: v0.4.5

*Grunt-cli: v0.1.13


text:
Q: Unable to open visual basic project I've made some changes in a visual basic 6.0 project. When I try to open it later, I'm getting a dialog with the following error.

Errors during load. Refer to '' for details.

Its failing to load one form. In the log file its saying that frmFileName.fr could not be loaded. Please note the file extension is shown as .fr, not .frm in the log.
How to resolve this?

A: Open your applicable vbp file with a text editor and look for the entry:
Form=frmFileName.frm
Make sure is says 'frm' instead of 'fr'. Perhaps this file got modified or corrupted. Also, make sure the form is in the same directory, or, if not, that the vbp references the correct path, and that the actual file is correctly named 'frmFileName.frm'.
If this doesn't work. Try removing the entry from the vbp, and then after saving and opening the project, you could try importing the form file.


text:
Q: Issues with onclick/onserverclick with buttons, HtmlButtons, and LinkButtons I'm having an issue with the functions to be called not firing off.
I have moved from hardcoding the buttons on HTML, to using the add controls method in the cs; and I have shifted from using Button and HtmlButton to using LinkButton.  However none of these seem to work.  In Onserverclick and onclick not work Anup Sharma recommends using the LinkButton, and Keyvan Sadralodabai indicates that if the runat="server" is displayed in the insect element, then he control was set up wrong.
So here's a stripped down simplified version of what I'm working with:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Drawing;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.Web.Services;

    using System.Data;
    using MySql.Data;
    using MySql.Data.MySqlClient;

    public partial class backCodeExper : System.Web.UI.Page
    {

        protected void saveRecord(string recordID, string buttonId, string dropdownId)
        {

            PlaceHolder db = Page.FindControl("TestingCS") as PlaceHolder;
            HtmlTable tbl = db.FindControl("TestTable") as HtmlTable;
            HtmlTableRow tr = tbl.FindControl("TheRow") as HtmlTableRow;
            HtmlTableCell tc = tr.FindControl("TheCell2") as HtmlTableCell;
            DropDownList ddl = tc.FindControl(dropdownId) as DropDownList;

            var status = ddl.SelectedValue.ToString();

            HttpContext context = HttpContext.Current;
            MySqlConnection conn = new MySqlConnection();
            conn.ConnectionString = "Server=localhost; Database********; User=********; Password=********; Port=3306";
            conn.Open();
            MySqlCommand cmd = new MySqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.CommandText = "updatetesttable";
            cmd.Parameters.AddWithValue("@param", status);
            cmd.ExecuteNonQuery();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            HtmlTable myTable = new HtmlTable();
            myTable.ID = "TestTable";
            myTable.BorderColor = "teal";
            myTable.BgColor = "black";
            TestingCS.Controls.Add(myTable);

            HtmlTableRow newRow;
            HtmlTableCell cell;
            DropDownList DropList;
            LinkButton saveButton;

            newRow = new HtmlTableRow();
            newRow.ID = "TheRow";
            cell = new HtmlTableCell();
            cell.ID = "TheCell1";
            DropList = new DropDownList();
            DropList.ID = "StatusDD";
            DropList.Items.Add(new ListItem("", "0"));
            DropList.Items.Add(new ListItem("A", "1"));
            DropList.Items.Add(new ListItem("B", "2"));
            DropList.Items.Add(new ListItem("C", "3"));
            cell.Controls.Add(DropList);

            newRow.Cells.Add(cell);

            cell = new HtmlTableCell();
            cell.ID = "TheCell2";
            cell.BgColor = "black";
            saveButton = new LinkButton();
            saveButton.ID = "saveButton";

            saveButton.CommandName = "saveRecord";
            saveButton.CommandArgument = "'1A',this.id,'StatusDD'";
            saveButton.BackColor=Color.Green;
            saveButton.ForeColor=Color.Cyan;
            saveButton.BorderColor=Color.Maroon;
            saveButton.Text = "Save";
            saveButton.Visible = true;
            cell.Controls.Add(saveButton);
            newRow.Cells.Add(cell);
            myTable.Rows.Add(newRow);
        }
    }

It loads the screen just fine with the simple dropdown and with the (unstylish) button (frankly the HtmlButton looks much nicer, but I'm aiming for functionality first).
When I select an item from the dropdown and then click save, the screen appears to refresh, keeping the value of the dropdown the same as that which was selected. However, when I check the database, the procedure hasn't fired.  Additionally I cannot get this code segment Response.Write("<script>alert('Hello');</script>"); to execute when placed in the method/function saveRecord.
Furthermore, when I run the debugging mode and put break points in saveRecord, none of them are hit.
After inspecting element, this is what I get:
InspectElementResults
Any suggestions? What am I missing?
If I don't use LinkButton (or Button/HtmlButton with onServerClick) then I get errors saying the function isn't defined - which makes since as the function/method is define on the aspx.cs not the aspx within JS script tags.

A: I've got it figured out. At least, it is functional.
I was trying to set the function to pass the values I want in the format I wanted, but apparently the when you set up a LinkButton, it prefers the object and Event Args as parameters, and the object is the ListButton itself, so if that ListButton object holds the values you need in its attributes, then when the function is called you parse out the attributes you need.  There's likely a better way than to assign the two values I need to CommandName and CommandArgument, but this works.  (I had thought of using .Attributes.Add("ROW_ID","1a") and .Attributes.Add("DD_ID","StatusDD") ... but couldn't initially figure out how to retrieve those values from the sender object...to be investigated later, in the meantime, rolling forward with a functional solution.
    ...
        protected void saveRecord(object sender, EventArgs e)
        {
            LinkButton lb = (LinkButton)sender;
            string ROW_ID = (string)lb.CommandName;
            string DD_ID = (string)lb.CommandArgument;
            Response.Write("<script>alert('Hello');</script>");
            ...
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            ...

            saveButton.CommandName = "1a";
            saveButton.CommandArgument = "StatusDD";
            saveButton.Click += new EventHandler(saveRecord);
            ...
        }
    }


text:
Q: VB .Net 2010 to run crystal reports 11 and I am getting This field name not found error Net 2010 to run crystal reports 11 and I am getting This field name not found error when I use any table value in the formula field.
I am trying to check a date field isNull or not and then picking the non null value from the database/view field. If I build as a report in Crystal Reports 11 stand alone it works. But with CrystalReportViewer in VB .Net 2010 I am getting this error. This field name is not known.Error in formula ..... Details: errorKind
This is my Vb code inside the formula section.
Dim x as date
If {@PI} = "PI" Then
    x = DateValue({VIEW_GROUP_TOTALS.CH_PI_OPEN_DATE})
else
    If IsNull({VIEW_GROUP_TOTALS.CH_OPEN_DATE}) Then
        x = DateValue({VIEW_GROUP_TOTALS.CH_PI_OPEN_DATE})
    else
        x = DateValue({VIEW_GROUP_TOTALS.CH_OPEN_DATE})
    End If
End If

formula = x
Basically I cannot get any field value inside the formula section.
Any help is much appreciated.
Thank you,
Ravin
![enter image description here][1]

A: The issue has been fixed. The fix was ... I was not getting the field value which I was validating inside the formula. That is the sql which queries the view did not has the field name in the sql. When I modified the SQL by adding the field name, I did not get that error from the formula section.
Thank you Siva - it was a SQL query issue your clue helped me to fix the issue.


text:
Q: Summation of the Sine Function I was messing around on Wolfram Alpha's summation calculator and when I plugged in the summation
$$\sum_{i=1}^n\sin\frac{i\pi}{180}$$
and it gave me the value
$$\frac12\left(\cot\frac\pi{360}-\csc\frac\pi{360}\cos\frac{(2n+1)\pi}{360}\right)$$
I don't understand... how does it arrive at this formula? And how do I verify this? If I wanted to, how could I find similar formulas in the future?

A: We have
$$ 2\sin{A}\sin{B} = -\cos{(A+B)}+\cos{(A-B)} $$
by using the angle addition formulae. Putting $A=ak+b$, $B=a/2$ gives
$$ 2\sin{\left(\frac{a}{2}\right)}\sin{(ak+b)} = -\cos{\left(a\left(k+\frac{1}{2}\right)+b\right)} + \cos{\left(a\left(k-\frac{1}{2}\right)+b\right)}. $$
Summing from $k=1$ to $n$ gives
$$ 2\sin{\left(\frac{a}{2}\right)}\sum_{k=1}^n \sin{(ak+b)} = \sum_{k=0}^n \left(  - \cos{\left(a\left(k+\frac{1}{2}\right)+b\right)} + \cos{\left(a\left(k+\frac{1}{2}\right)+b\right)} \right). $$
The sum on the right telescopes, and the only remaining terms give
$$ \sum_{k=1}^n \sin{(ak+b)} = \frac{1}{2}\csc{\left(\frac{a}{2}\right)} \left( \cos{\left(\frac{a}{2}+b\right)} - \cos{\left(a\left(n+\frac{1}{2}\right)+b\right)} \right) $$
This is essentially the most general formula of its kind: choosing different values for $a$ and $b$ gives a number of useful trigonometric sums. In your case, $a=\pi/180$, $b=0$, which gives
$$ \sum_{k=1}^n \sin{\frac{k\pi}{180}} = \frac{1}{2}\csc{\left(\frac{\pi}{360}\right)} \left( \cos{\left(\frac{\pi}{360}\right)} - \cos{\left(\frac{(2n+1)\pi}{360}\right)} \right), $$
as expected.
These formulae may also be used in integrating the trigonometric functions from first principles.


text:
Q: Find the solution of binary xor operator equation I am working in binary xor operator $\mathbb Z_2$. I have to resolve my problem such as
$$\begin {cases}
x_1+x_2+x_3=1\\
x_1+x_2=0\\
x_1+x_3=1\\
\end {cases}$$
Could you suggest to me any method to find the solution. I hear that gaussian elimination is one option. How about the other solution?
Solution for this equation is
$$x_1=0,x_2=0,x_3=1$$
For more complex equation
$$\begin {cases}
x_1+x_2=0\\
x_2+x_3=1\\
x_3+x_4=1\\
\end {cases}$$
In this case we can see we have only 3 equation but we must find 4 variances. The solution is
$$x_1=0;x_2=0; x_3=1, x_4=0$$

A: Substitution works fine.  Plug your second into the first to get $x_3=1$ and so on.  Another ways is that the second gives you $x_1=x_2$ and you can plug that in to eliminate one of the variables.

A: Since you ask for any method, I will add that making an exhaustive search for a solution is perfectly viable here. For the first exercise, you only have $2^3=8$ cases to try and in the second $2^4=16$.
It may not be as elegant or give as much insight and understanding, but sometimes it's the most practical way to go.


text:
Q: How to show image using smarty, when it is stored on amazon? My images are stored on Amazon servers and I have to display them (using smarty) in a smarty template.
currently I am able to show an image using following PHP code:
header('Content-type:image/jpeg');
header("Content-disposition: inline; filename=\"".basename($formatted_filename)."\"");

How could I show it on smarty page?

A: You do it the same way you would do it in html
<img src="image_url" alt="whatever"/>

in your case the url of the image is the script you created in php, i.e. show_image.php?image_id=33


text:
Q: MongoDb not registering field in query specifier Im querying a mongodb collection and only retriving a subdocument like this:
db.Category.find({"Children.Url" : "www.myurl.com"}, {"Children.$" : 1})

But when trying to run a similar query but with regex :
db.Category.find({"Children.Url" : /myurl/i}, {"Children.$" : 1})

I get this error:
error: {
"$err" : "positional operator (Children.$) requires corresponding field in query specifier",
"code" : 16352
}

Why is it not registering that the corresponding field is actually specified when using regex?

A: This seems to be a bug in mongodb and also previously answered here : How do I search for a string in a MongoDB document array and project the array value in a find operation?
Modifying the query like this gives expected results:
db.Category.find({"Children.Url" : {$in : [/myurl/i]}}, {"Children.$" : 1})

A: This is a known Jira SERVER-9028 issue. A workaround is:
db.Category.find({"Children": {$elemMatch: {Url: /myurl/i}}}, {"Children.$": 1})


text:
Q: Show that the Limit of ODE Solutions Tends to $0$ I am revising some exercises from a course on ODE's that I have not managed to do. This exercise asks the reader to show that any solution to an ODE of the following form goes to $0$ as $t\rightarrow\infty$: $$y'+a(t)y=f(t)$$
with $a(t)$ and $f(t)$ continuous, $a(t) \geq c>0$ and $\lim\limits_{t\rightarrow\infty}f(t)=0$.
We can find an integrating factor for this ODE, namely $\mu(t)=e^{\int a(t)}$, so that we find that any solution looks like $$y = e^{-\int a(t)}\int f(t)e^{\int a(t)}$$ and from the property that $a(t) \geq c>0$ we can conclude that $$|y| \leq e^{-ct}\int f(t)e^{\int a(t)}$$
however I don't know how to continue from here. Any help would be appreciated.

A: Let $A(t) = \int_0^t a(s)\, ds$. By method of integrating factors,
$$y(t) = e^{-A(t)}y(0) + e^{-A(t)}\int_0^t e^{A(s)}f(s)\, ds$$ For $t \ge 0$, the exponential $e^{-A(t)}$ is bounded by $e^{-ct}$, so the term $e^{-At}y(0)\to 0$ as $t \to \infty$. Now $$e^{-A(t)}\int_0^t e^{A(s)}f(s)\, ds = \int_0^t f(s)e^{-\int_s^t a(u)\, du}\, ds$$ is bounded by $\int_0^t \lvert f(s)\rvert e^{-c(t-s)}\, ds$, which we'll show tends to $0$ as well. Fix a positive number $\varepsilon$. Using the condition $\lim\limits_{t\to \infty} f(t) = 0$, we may choose a positive number $M$ such that for all $t \ge M$, $\lvert f(s)\rvert < \varepsilon$. For $t > M$, $$\int_0^t \lvert f(s)\rvert e^{-c(t-s)}\, ds = \int_0^M \lvert f(s)\rvert e^{-c(t-s)}\, ds + \int_M^t \lvert f(s)\rvert e^{-c(t-s)}\, ds \le Ce^{-ct} + \frac{\varepsilon}{c}\left[1-e^{-c(t-M)}\right]$$ where $C$ is the constant $\int_0^M \lvert f(s)\rvert e^{cs}\, ds$. Taking the limit superior as $t \to \infty$ results in $$\limsup_{t\to \infty} \int_0^t \lvert f(s)\rvert e^{-c(t-s)}\, ds \le \frac{\varepsilon}{c}$$ As $\varepsilon$ was arbitrary, $\int_0^t \lvert f(s)\rvert e^{-c(t-s)}\, ds$ tends to $0$ as $t\to \infty$, as desired.

A: Let $0 < \varepsilon \le 2$, let $T > 0$ be such that $|f(t)| \le \varepsilon$ for $t \ge T$, and set $z(t) = |y(t)|^2$. Then for $t \ge T$
$$
\frac{d}{dt} z(t) = - 2a(t) z(t) + |f(t)y(t)| \le -2cz(t) + \varepsilon \sqrt{z(t)}
\le - 2 c z(t) +\varepsilon (\frac{1}{2c} + \frac{c}{2} z(t))
$$
and therefore
$$
\frac{d}{dt} z(t) \le - cz(t) + \frac{\varepsilon}{2c} \,
$$
Now set $w(t) = e^{ct}z(t)$, then $\frac{d}{dt} w(t) \le \frac{\varepsilon e^{ct}}{2c}$.
Integrating this inequality from $T$ to $t > T$, it follows that
$$
w(t) \le w(T) + \frac{\varepsilon}{2c^2}(e^{c(t-T)}-1)
$$
and therefore
$$
z(t) \le e^{-ct}\cdot const. + \frac{\varepsilon}{2c^2} \,
$$
Consequently $\limsup_{t \to \infty} z(t) \le \frac{\varepsilon}{2c^2}$.
Since $\varepsilon$ was arbitrary, it follows that $y(t) \to 0$.
This argument also works for vector valued differential equations, even nonlinear ones. An integrating factor for the equation is not needed.


text:
Q: Error while converting jar to dll using IKVM I had created a library project in android. This library project selects the real path of the image from gallery. I want to reference this application in asp.net. So, i converted it in dll using ikvm, But there was a warning that "".
the code follows below.
public String BrowseImageFromGallery(){
    Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(galleryIntent, GALLERY_REQUEST);
    if(imageRealPath != null)
    {
        return imageRealPath;
    }
    return null;
}

public String TakeImageFromCamera(){

    TakeImage();
    return imageRealPath;
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent ){

    switch (resultCode){

    case GALLERY_REQUEST : {
        selectedImageUri = intent.getData();
        imageRealPath = GetRealPathFromUri(selectedImageUri);
    }
    break;

    case CAMERA_REQUEST : {
        imageRealPath = GetRealPathFromUri(selectedImageUri);
    }
    break;
    }

}

private String GetRealPathFromUri(Uri imageUri) {

    try
    {
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(imageUri, proj, null, null, null);
        int column_Index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_Index);
    }
    catch(Exception e)
    {
        return imageUri.getPath();
    }
}

private void TakeImage() {
    ContentValues values = new ContentValues();
     imageName = String.valueOf(System.currentTimeMillis());
    values.put(MediaStore.Images.Media.TITLE, imageName);
    selectedImageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            values);

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, selectedImageUri);
    startActivityForResult(intent, CAMERA_REQUEST);

}

}
the problem is due to the fact that i am extending Activity class and it is not referencing when i am converting it to the dll. So, I add the reference of  android.jar. Everything working fine, But when i run the program there was error.
To check what is the i made a simple add method in the java library and called it from c# code on button click. The error follows below

A: IKVM is for Java SE. You can only use API of the Java SE or of third party. Your Android.jar is only a stup jar file for the compiler. At runtime it contains native calls to the Android Java VM.
Create your own stub android.app.Activity and not the Android.jar. Your stub should call only API of the standard Java API.


text:
Q: Middleware using cookie nuxt I just setup middleware by checking cookie in nuxt but it's give me blank error, nothing error in console

this is my middleware authenticate.js
export default function({ store, redirect }) {
  const Cookie = process.client ? require('js-cookie') : undefined
  // If the user is not authenticated
  let token = Cookie.get('token')
  const userIsLoggedIn = token != null //cookie ada
  const userNeedLogin = token == null //cookie gak ada
  if (userNeedLogin) {
    return redirect('/login')
  }
  if (userIsLoggedIn) {
    return redirect('/dashboard')
  }
}

and this is my nuxt.config.js
router: {
    middleware: 'authenticate'
  }

it should redirect to page login when cookies is null but if cookie exist it redirect goes to dashboard, do i miss something ?


text:
Q: How do i do a onclick who reload 3 different divs How can I reload 3 JavaScript datecodes every time I press a image?
I don't want the whole paga to refresh just some divs, can this be done?

A: You might be searching for something like jquery's find:
http://api.jquery.com/find/
You can 'find' all the divs you want to reload and do something with them when the image is clicked.


text:
Q: Evaluate XACML 3.0 combining algorithms I am studying XACML 3.0 access control and I found this complex question about Evaluate XACML 3.0 combining algorithms. I can solve a simple exercise but this one hard for me and I need some help with it
policy p1:
- op: permit-overrides

*

*rule: permit if match all: group = staff, resource = file1

*rule: permit if match all: group = student, resource = file2

*rule: deny if match: any
policy p2:

*

*op: deny-overrides

*rule: deny if match all: time [MBP] = night

*rule: permit if match all: time [MBP] = day
policy p3:

*

*op: deny-overrides

*policy: p1

*policy: p2
Evaluate for each policy the following requests q1, q2 and q3:

*

*q1 = {(group, staff), (resource, file1), (time, day)}

*q2 = {(group, student), (resource, file2), (time, night)}

*q3 = {(group, staff), (resource, file1)}

A: Evaluation Results using P1 only

*

*q1 = {(group, staff), (resource, file1), (time, day)}

*

*Response: Permit. The first rule in P1 kicks in and the combining algorithm makes the process stop there. The time of day has no impact on the decision making.

*q2 = {(group, student), (resource, file2), (time, night)}

*

*Response: Permit. The second rule in P1 kicks in and the combining algorithm makes the process stop there. The time of day, again, has no impact on the decision making.

*q3 = {(group, staff), (resource, file1)}

*

*Response: Permit. This is essentially the same as q1.

Evaluation Results using P2 only

*

*q1 = {(group, staff), (resource, file1), (time, day)}

*

*Response: Permit because all access is permitted in day time. Rule 1 inside P2 does not apply. Rule 2 grants access.

*q2 = {(group, student), (resource, file2), (time, night)}

*

*Response: Deny because all access is denied at nighttime. Rule 1 inside P2 applies. The combining algorithm is such that the processing stops after rule 1.

*q3 = {(group, staff), (resource, file1)}

*

*Response: Not applicable. The two rules only trigger if the time of day has been specified, which isn't the case in this request. Therefore the evaluation ends in NotApplicable.

Evaluation Results using P3 (a combination of P1 and P2)

*

*q1 = {(group, staff), (resource, file1), (time, day)}

*

*Response: Access is permitted because staff is allowed to view file1 in daytime.

*q2 = {(group, student), (resource, file2), (time, night)}

*

*Response:  Access is denied regardless of what the student is trying to view. In this case, the nighttime policy trumps all other policies because of the over-arching combining algorithm (deny-overrides) in P3.

*q3 = {(group, staff), (resource, file1)}

*

*Response: Access is permitted because staff is allowed to view file1 and no time has been specified.

Notes
The policy that grants access during daytime is not necessary. As a matter of fact, it might even open up access you would not want to have. For instance, given the current policy, a student can edit their own exam grades so long as it's daytime.

A: The other answer is detailed and largely correct except for two cases involving a Rule's Target missing an attribute for which MustBePresent is set to true.
Only those cases will be addressed here in this answer.
policy p2 - request q3

*

*rule: deny if match all: time [MBP] = night -> Indeterminate{D} because of missing time attribute and MustBePresent = true and the rule effect is Deny

*rule: permit if match all: time [MBP] = day -> Indeterminate{P} because of the similar reason

*op:denyOverrides -> Indeterminate{DP}

The evaluation result is Indeterminate{DP}
policyset p3 - request q3:

*

*policy p1

*

*rule: permit if match all: group = staff, resource = file1 -> Permit

*op:permitOverrides -> Permit regardless of the outcome of any other rules

*policy p2 -> Indeterminate{DP} as explained in the previous case

*op:denyOverrides -> Indeterminate{DP}

The evaluation result is Indeterminate{DP}
References
The XACML 3.0 specification contain all the details necessary for your understanding

*

*For the attribute retrieval and MustBePresent flag refer to section 7.3.5

*For the combining algorithms refer to Appendix C


text:
Q: PHP MSQLI Forgot Password Reset page I am setting up a PHP lost password page for my website (www.qbstaxsubmission.co.uk) and the code for creating a lost password email which is sent to a user is working just fine. However when the user clicks on the email link he arrives at a new password php page. It's the script on this page which produces a error message 'Registration failure in updating recovery key: INSERT' which fires up my styled error page to transfer the user back to my standard login page.
So my problem is I cannot see what's wrong with my new password2.php. Can anyone help with this?
Here's the full new password2.php code:
<?php
ob_start();
include ('config.php');
include ('function.php');
$error_msg = "";

$token = $_GET['token'];
$userID = UserID($email);
$verifytoken = verifytoken($userID, $token);

// Sanitize and validate the data passed in
if (isset($_POST['submit'],$_POST['username'], $_POST['email'],       $_POST['p'])) {
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$new_password = filter_input(INPUT_POST, 'new_password', FILTER_SANITIZE_STRING);
$retype_password = filter_input(INPUT_POST, 'retype_password', FILTER_SANITIZE_STRING);
$id = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_STRING);}

$new_password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);
if (strlen($new_password) != 128) {
// The hashed pwd should be 128 characters long.
// If it's not, something really odd has happened
$error_msg .= '
Invalid password configuration.
';
}

$prep_stmt = "SELECT id FROM members WHERE email = ? LIMIT 1";
$stmt = $db ->prepare($prep_stmt);
if ($stmt) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows == 1) {
// A user with this email address already exists
$error_msg .= '
A user with this email address already exists.
';
}
} else {
$error_msg .= '
Database error
';
}

if($new_password != $retype_password) {
// Create a random salt
$salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));
// Create salted password
$new_password = hash('sha512', $random_salt . $salt);

}

// Insert the new hashed password into the database
if ($insert_stmt = $db->prepare("UPDATE members SET password = ? WHERE id = ? ")) {
$insert_stmt->bind_param('si', $newpassword, $id);
// Execute the prepared query.
if (!$insert_stmt->execute()) {
header('Location: ../error.php?err=Database Registration failure: INSERT');
}

// Update recovery key
if ($insert_stmt = $db->prepare("UPDATE recovery_keys SET valid = 0 WHERE  id = ?  AND token = ? "));
$insert_stmt->bind_param('is', $id, $token);
// Execute the prepared query.
if ($insert_stmt->execute())
$msg = 'Your password has changed successfully. Please login with your new password.';

}else
{

header('Location: ../error.php?err=Registration failure in updating recovery key: INSERT'); }

{exit();}

?>

When the code above is run I get a blank page with the the correct token code shown in the site link.
This password2.php page has an include to a functions page which is shown below.
function checkUser($email)
{
global $db;

$query = mysqli_query($db, "SELECT id FROM members WHERE email = '$email'");

if(mysqli_num_rows($query) > 0)
{
return 'true';
}else
{
return 'false';    }
}

function id($email)
{
global $db;

$query = mysqli_query($db, "SELECT id FROM members WHERE email = '$email'");
$row = mysqli_fetch_assoc($query);

return $row['id'];
}

function generateRandomString($length = 25) {
// This function has taken from stackoverflow.com

$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return md5($randomString);
}

function send_mail($to, $token)
{
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
//$mail->SMTPDebug = 3;

$mail->isSMTP();
$mail->Host = '';
$mail->SMTPAuth = true;
$mail->Username = '';
$mail->Password = '';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->SetFrom = '';
$mail->FromName = '';
$mail->addAddress($to);
$mail->addReplyTo('', 'Reply');
$mail->isHTML(true);
$mail->Subject = 'Company Password Recovery Instruction';
$link = 'x.php?email='.$to.'&token='.$token;
$mail->Body  = "Hi

You have just requested a new password for your company account with QBS Tax Submission. Click here to reset your password. If you are unable to click the link then copy the hyper link below and paste into your browser to reset your password.
". $link."";

$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
return 'fail';
} else {
return 'success';
}
}

function verifytoken($id, $token)
{
global $db;
$query = mysqli_query($db, "SELECT valid FROM recovery_keys WHERE id = $id AND token = '$token'");
$row = mysqli_fetch_assoc($query);
if(mysqli_num_rows($query) > 0)
{
if($row['valid'] == 1)
{
return 1;
}else
{
return 0;
}
}else
{
return 0;
}

}

function login($email, $password, $mysqli) {
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, username, email, password, salt
              FROM members
                              WHERE email = ? LIMIT 1")) {
$stmt->bind_param('s', $email);  // Bind "$email" to parameter.
$stmt->execute();    // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($id, $username, $db_password, $salt);
$stmt->fetch();
// hash the password with the unique salt.
$password = hash('sha512', $password . $salt);
if ($stmt->num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (checkbrute($id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return false;
} else {
// Check if the password in the database matches
// the password the user submitted.
if ($db_password == $password) {
// Password is correct!
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
// XSS protection as we might print this value
$id = preg_replace("/[^0-9]+/", "", $id);
$_SESSION['id'] = $id;
// XSS protection as we might print this value
$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512', $password . $user_browser);
// Login successful.
return true;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
if (!$mysqli->query("INSERT INTO login_attempts(id, time)
VALUES ('$id', '$now')")) {
header("Location: ../error.php?err=Database error: login_attempts");
exit();
}
return false;
}
}
} else {
// No user exists.
return false;
}
} else {
// Could not create a prepared statement
header("Location: ../error.php?err=Database error: cannot prepare statement");
exit();
}
}
function checkbrute($id, $mysqli) {
// Get timestamp of current time
$now = time();
// All login attempts are counted from the past 2 hours.
$valid_attempts = $now - (2 * 60 * 60);
if ($stmt = $mysqli->prepare("SELECT time
                              FROM login_attempts
                              WHERE id = ? AND time > '$valid_attempts'")) {
$stmt->bind_param('i', $id);
// Execute the prepared query.
$stmt->execute();
$stmt->store_result();
// If there have been more than 5 failed logins
if ($stmt->num_rows > 5) {
return true;
} else {
return false;
}
} else {
// Could not create a prepared statement
header("Location: ../error.php?err=Database error: cannot prepare statement");
exit();
}
}
function login_check($mysqli) {
// Check if all session variables are set
if (isset($_SESSION['id'], $_SESSION['username'],      $_SESSION['login_string'])) {
$id = $_SESSION['id'];
$login_string = $_SESSION['login_string'];
$username = $_SESSION['username'];
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
if ($stmt = $mysqli->prepare("SELECT password
                  FROM members
                  WHERE id = ? LIMIT 1")) {
// Bind "$id" to parameter.
$stmt->bind_param('i', $id);
$stmt->execute();   // Execute the prepared query.
$stmt->store_result();
if ($stmt->num_rows == 1) {
// If the user exists get variables from result.
$stmt->bind_result($password);
$stmt->fetch();
$login_check = hash('sha512', $password . $user_browser);
if ($login_check == $login_string) {
// Logged In!
return true;
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
} else {
// Could not prepare statement
header("Location: ../error.php?err=Database error: cannot prepare statement");
exit();
}
} else {
// Not logged in
return false;
}
}
function esc_url($url) {
if ('' == $url) {
    return $url;
}
$url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);

$strip = array('%0d', '%0a', '%0D', '%0A');
$url = (string) $url;

$count = 1;
while ($count) {
    $url = str_replace($strip, '', $url, $count);
}

$url = str_replace(';//', '://', $url);
$url = htmlentities($url);

$url = str_replace('&', '&', $url);
$url = str_replace("'", ''', $url);
if ($url[0] !== '/') {
    // We're only interested in relative links from $_SERVER['PHP_SELF']
    return '';
} else {
    return $url;
}
}

A: I believ this is where the issue is:
    if (! $insert_stmt->execute())
    $msg = 'Your password has changed successfully. Please login with your new password.';

}else{..}

 if (! $insert_stmt->execute()) this means if the query fails echo that password fails.....
the reason your code always display Registration failure in updating recovery key: INSERT its because you instructed your code that when the query does not fail it must produce that.
And your code all of it is in mess, you need to clean it up.
Thi is how this should look.
 if ($insert_stmt = $db->prepare("UPDATE recovery_keys SET valid = 0 WHERE userID =  ?  AND token = ? "));
    $insert_stmt->bind_param('ss', $userID, $token);
    // Execute the prepared query.
    if ($insert_stmt->execute())
    $msg = 'Your password has changed successfully. Please login with your new password.';

    }else
    {
    $msg = "Password doesn't match";

    header('Location: ../error.php?err=Registration failure in updating recovery key: INSERT'); }

    {exit();}

Edit
Tried to clean up some of the mess in your code. Now this how should look.
<?php
ob_start();
include('config.php');
include('function.php');
$error_msg = "";

$token       = $_GET['token'];
$userID      = UserID($email);
$verifytoken = verifytoken($userID, $token);

// Sanitize and validate the data passed in
if (isset($_POST['submit'], $_POST['username'], $_POST['email'], $_POST['p'])) {
    $email           = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
    $username        = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
    $new_password    = filter_input(INPUT_POST, 'new_password', FILTER_SANITIZE_STRING);
    $retype_password = filter_input(INPUT_POST, 'retype_password', FILTER_SANITIZE_STRING);
    $id              = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_STRING);
}

$new_password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);
if (strlen($password) != 128) {
    // The hashed pwd should be 128 characters long.
    // If it's not, something really odd has happened
    $error_msg .= '
Invalid password configuration.
';
}

$prep_stmt = "SELECT id FROM members WHERE email = ? LIMIT 1";
$stmt      = $db->prepare($prep_stmt);

if ($stmt) {
    $stmt->bind_param('s', $email);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows == 1) {
        // A user with this email address already exists
        $error_msg .= '
A user with this email address already exists.
';
    }
} else {
    $error_msg .= '
Database error
';
}

if ($new_password != $retype_password) {
    // Create a random salt
    $salt         = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));
    // Create salted password
    $new_password = hash('sha512', $random_salt . $salt);

}

// Insert the new hashed password into the database
if ($insert_stmt = $db->prepare("UPDATE members SET password = ? WHERE id = ?")) {
    $insert_stmt->bind_param('si', $new_password, $userID);
    // Execute the prepared query.
    if (!$insert_stmt->execute()) {
        header('Location: ../error.php?err=Database Registration failure: INSERT');
        exit();
    }

    // Update recovery key
    if ($insert_stmt = $db->prepare("UPDATE recovery_keys SET valid = 0 WHERE userID = ? AND token = ? "));
    $insert_stmt->bind_param('is', $userID, $token);
    // Execute the prepared query.
    if ($insert_stmt->execute())
        $msg = 'Your password has changed successfully. Please login with your new password.';

} else {
    $msg = "Password doesn't match";

    header('Location: ../error.php?err=Registration failure in updating recovery key: INSERT');
    exit();
}

?>

Important things you need to learn proper.
Update : here's the link
Prepared statements : link here
password hashing : link here
Your hashing method is very easy php does provide better and secure ways, please follow the links above.


text:
Q: Is it possible to find angles inside a shape if I am only given the slopes and lengths of the lines? I was given a math problem listing 4 ordered pairs of points to plot. So I plotted them, found their slopes and distances. The question asks me to determine the most precise name of the quadrilateral. I know their opposite sides are parallel and all sides are congruent so I concluded it was a rhombus. But then I was thinking it could also be a square but to be a square all angles must be right angles. In short my question is with this information that I know is there any way to find out the angles so I can call the quadrilateral a square? Or is the most specific name for it a rhombus? Thank you.

A: Here's an approach to categorization based mainly on line lengths. Suppose the points are $a_1=(x_1,y_1),\dots, a_4=(x_4,y_4)$. If you find the point $O=\dfrac{a_1+a_2+a_3+a_4}4$ and define $a_i'=a_i-O$, this will move the center of the quadrilateral to the origin and make several patterns easier to spot.

*

*The quadrilateral is a parallelogram iff $a_1'=-a_3'$ and $a_2'=-a_4'$. This is saying that both diagonals go through the center, and from this you can see that $|a_1-a_2|=|a_3-a_4|$ and $|a_1-a_3|=|a_2-a_4|$, so opposite sides are congruent.

*

*A parallelogram is a rectangle iff $|a_1'|=|a_2'|$. This says that the diagonals have the same length, so adjacent sides are perpendicular.

*A parallelogram is a rhombus iff $a_1'$ is perpendicular to $a_2'$. If $a_1'=(x_1',y_1')$ and $a_2'=(x_2',y_2')$ this is equivalent to $x_1'x_2'+y_1'y_2'=0$. Alternatively you can check that $|a_1'-a_2'|=|a_3'-a_2'|$, which says directly that the edges have the same lengths.

*Finally, a parallelogram is a square iff it is a rectangle and a rhombus.


text:
Q: How do I do a linq query to find fields in a dataset that are present in every record of a set? I have an XML data set with 10K records, each containing a set of fields.
I'd like to know which fields need to be null and which can be non-null in the database schema that matches the dataset.
Does linq offer way to produce a big intersection?
Example:
<set>
 <item>

  <foo />

  <c/>
 </item>
 <item>

   <foo />

   <c/>
  </item>
 <item>

 </item>
 <item>

   <foo />

  </item>
</set>

Prototype:
string[] CommonFieldNames(XElement[] elements)
{
  // ...
}

Desired Result:
{ "a", "b" }

A: In bellow code, selectedValue is your not null columns.
XDocument doc = XDocument.Parse("<set><item><foo /><c/></item><item><foo /><c/></item></set>");
var items =
          doc.Descendants("item")
          .Select(x=>x.Descendants().Select(y=>y.Name).ToList()).ToList();
 var selectValue = items[0];
 foreach (var item in items)
 {
    selectValue = selectValue.Intersect(item).ToList();
 }

A: You could use a GroupBy and compare the group size to the total number of elements:
XDocument doc = XDocument.Parse("<set><item><foo /><c/></item><item><foo /><c/></item><item></item><item><foo /></item></set>");
var items = doc.Document.Element("set").Elements("item");
var commonElementNames = items.SelectMany(x => x.Elements()) // Get all immediate children
                              .GroupBy(x => x.Name) // Group by name
                              .Where(g => g.Count() == items.Count()) // Filter for only those which show in every group.
                              .Select(g => g.Key.LocalName) // Select just the element names
                              ;


text:
Q: IPSec Tunnel is up but I cannot ping destination ip I am attempting to setup an IPSec tunnel to an external service that we do not control. The tunnel appears to be up but I am unable to ping the private IP address at all. I just receive a Destination host unreachable.
ifconfig
docker0   Link encap:Ethernet  HWaddr 02:42:5d:6c:5b:ff
          inet addr:172.17.0.1  Bcast:0.0.0.0  Mask:255.255.0.0
          inet6 addr: fe80::42:5dff:fe6c:5bff/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:153830963 errors:0 dropped:0 overruns:0 frame:0
          TX packets:157996702 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:10393890115 (10.3 GB)  TX bytes:15013754691 (15.0 GB)

eth0      Link encap:Ethernet  HWaddr 0c:c4:7a:7d:c2:ac
          inet addr:129.111.191.242  Bcast:129.111.191.247  Mask:255.255.255.248
          inet6 addr: fe80::ec4:7aff:fe7d:c2ac/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:131498746 errors:0 dropped:0 overruns:0 frame:0
          TX packets:166120812 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:27289309652 (27.2 GB)  TX bytes:163175029250 (163.1 GB)
          Memory:fb200000-fb280000

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:88829366 errors:0 dropped:0 overruns:0 frame:0
          TX packets:88829366 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:1816449755157 (1.8 TB)  TX bytes:1816449755157 (1.8 TB)

veth1a733da Link encap:Ethernet  HWaddr 52:e1:f1:58:ec:1d
          inet6 addr: fe80::50e1:f1ff:fe58:ec1d/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:204 errors:0 dropped:0 overruns:0 frame:0
          TX packets:266 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:1755510 (1.7 MB)  TX bytes:33966 (33.9 KB)
+ A WHOLE WHACK OF OTHER DOCKER CONTAINERS

ipsec.conf
version 2.0 # conforms to second version of ipsec.conf specification

config setup
        #plutodebug="dpd control"
        plutostderrlog=/var/log/openswan.log
        dumpdir=/var/run/pluto/
        nat_traversal=no
        virtual_private=%v4:10.0.0.0/8,%v4:192.168.0.0/16,%v4:172.16.0.0/12,%v4:25.0.0.0/8,%v6:fd00::/8,%v6:fe80::/10
        oe=off
        protostack=netkey
        interfaces="%defaultroute"

conn easypay-ipsec-vpn
        authby=secret
        auto=start
        ike=3des-sha1;modp1024
        ikelifetime=86400s
        phase2alg=3des-sha1;modp1024
        salifetime=3600s
        pfs=yes
        left=129.111.191.242
        leftsubnet=129.111.191.242/32
        right=196.25.143.85
        rightsubnet=192.168.200.125/32

ip xrfm policy
src 129.111.191.242/32 dst 192.168.200.125/32
    dir out priority 2080
    tmpl src 129.111.191.242 dst 196.25.143.85
        proto esp reqid 16385 mode tunnel
src 192.168.200.125/32 dst 129.111.191.242/32
    dir fwd priority 2080
    tmpl src 196.25.143.85 dst 129.111.191.242
        proto esp reqid 16385 mode tunnel
src 192.168.200.125/32 dst 129.111.191.242/32
    dir in priority 2080
    tmpl src 196.25.143.85 dst 129.111.191.242
        proto esp reqid 16385 mode tunnel
src 0.0.0.0/0 dst 0.0.0.0/0
    socket out priority 0
src 0.0.0.0/0 dst 0.0.0.0/0
    socket in priority 0
src 0.0.0.0/0 dst 0.0.0.0/0
    socket out priority 0
src 0.0.0.0/0 dst 0.0.0.0/0
    socket in priority 0
src 0.0.0.0/0 dst 0.0.0.0/0
    socket out priority 0
src 0.0.0.0/0 dst 0.0.0.0/0
    socket in priority 0
src 0.0.0.0/0 dst 0.0.0.0/0
    socket out priority 0
src 0.0.0.0/0 dst 0.0.0.0/0
    socket in priority 0

Checking IPSec is up
sudo /usr/sbin/ipsec auto --status | grep easypay
000 "easypay-ipsec-vpn": 129.111.191.242/32===129.111.191.242<129.111.191.242>...196.25.143.85<196.25.143.85>===192.168.200.125/32; erouted; eroute owner: #3
000 "easypay-ipsec-vpn":     myip=unset; hisip=unset;
000 "easypay-ipsec-vpn":   ike_life: 86400s; ipsec_life: 3600s; rekey_margin: 540s; rekey_fuzz: 100%; keyingtries: 0
000 "easypay-ipsec-vpn":   policy: PSK+ENCRYPT+TUNNEL+PFS+UP+IKEv2ALLOW+SAREFTRACK+lKOD+rKOD; prio: 32,32; interface: eth0;
000 "easypay-ipsec-vpn":   newest ISAKMP SA: #4; newest IPsec SA: #3;
000 "easypay-ipsec-vpn":   IKE algorithms wanted: 3DES_CBC(5)_000-SHA1(2)_000-MODP1024(2); flags=-strict
000 "easypay-ipsec-vpn":   IKE algorithms found:  3DES_CBC(5)_192-SHA1(2)_160-MODP1024(2)
000 "easypay-ipsec-vpn":   IKE algorithm newest: 3DES_CBC_192-SHA1-MODP1024
000 "easypay-ipsec-vpn":   ESP algorithms wanted: 3DES(3)_000-SHA1(2)_000; pfsgroup=MODP1024(2); flags=-strict
000 "easypay-ipsec-vpn":   ESP algorithms loaded: 3DES(3)_192-SHA1(2)_160
000 "easypay-ipsec-vpn":   ESP algorithm newest: 3DES_000-HMAC_SHA1; pfsgroup=MODP1024
000 #4: "easypay-ipsec-vpn":500 STATE_MAIN_R3 (sent MR3, ISAKMP SA established); EVENT_SA_REPLACE in 84419s; newest ISAKMP; lastdpd=-1s(seq in:0 out:0); idle; import:not set
000 #3: "easypay-ipsec-vpn":500 STATE_QUICK_R2 (IPsec SA established); EVENT_SA_REPLACE in 1621s; newest IPSEC; eroute owner; isakmp#1; idle; import:admin initiate
000 #3: "easypay-ipsec-vpn" esp.7f654c9@196.25.143.85 esp.273d0069@129.111.191.242 tun.0@196.25.143.85 tun.0@129.111.191.242 ref=0 refhim=4294901761
000 #1: "easypay-ipsec-vpn":500 STATE_MAIN_I4 (ISAKMP SA established); EVENT_SA_REPLACE in 83601s; lastdpd=-1s(seq in:0 out:0); idle; import:admin initiate

route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         129.111.191.241 0.0.0.0         UG    0      0        0 eth0
129.111.191.240 0.0.0.0         255.255.255.248 U     0      0        0 eth0
172.17.0.0      0.0.0.0         255.255.0.0     U     0      0        0 docker0
172.18.0.0      0.0.0.0         255.255.0.0     U     0      0        0 br-c8dc65a94bb2
172.19.0.0      0.0.0.0         255.255.0.0     U     0      0        0 br-82217b810a12
172.20.0.0      0.0.0.0         255.255.0.0     U     0      0        0 br-7850aa98111b
172.21.0.0      0.0.0.0         255.255.0.0     U     0      0        0 br-b1a7c55d62b6
172.22.0.0      0.0.0.0         255.255.0.0     U     0      0        0 br-825780b49c2d
172.23.0.0      0.0.0.0         255.255.0.0     U     0      0        0 br-c54a8b4052f1
172.28.0.0      0.0.0.0         255.255.0.0     U     0      0        0 br-9403e62934e3
172.29.0.0      0.0.0.0         255.255.0.0     U     0      0        0 br-4b089299a6c4
172.30.0.0      0.0.0.0         255.255.0.0     U     0      0        0 br-c9e5b9d15f93
172.31.0.0      0.0.0.0         255.255.0.0     U     0      0        0 br-20e8b7596a16
192.168.0.0     0.0.0.0         255.255.240.0   U     0      0        0 br-69356c2ae863
192.168.16.0    0.0.0.0         255.255.240.0   U     0      0        0 br-fef7a8477c50
192.168.32.0    0.0.0.0         255.255.240.0   U     0      0        0 br-0f934a7b6bbc
192.168.48.0    0.0.0.0         255.255.240.0   U     0      0        0 br-f436be453bc0
192.168.64.0    0.0.0.0         255.255.240.0   U     0      0        0 br-f58d5b3092b2
192.168.80.0    0.0.0.0         255.255.240.0   U     0      0        0 br-861678c58b1d
192.168.96.0    0.0.0.0         255.255.240.0   U     0      0        0 br-0bea6a9a8ba3
192.168.128.0   0.0.0.0         255.255.240.0   U     0      0        0 br-38704ca6d035
192.168.144.0   0.0.0.0         255.255.240.0   U     0      0        0 br-dd2a427832dc
192.168.160.0   0.0.0.0         255.255.240.0   U     0      0        0 br-f402e867a089
192.168.176.0   0.0.0.0         255.255.240.0   U     0      0        0 br-55b8290a7912
192.168.192.0   0.0.0.0         255.255.240.0   U     0      0        0 br-aad43c0bdf40
192.168.208.0   0.0.0.0         255.255.240.0   U     0      0        0 br-22d7856d7bf3
192.168.224.0   0.0.0.0         255.255.240.0   U     0      0        0 br-f968a9b6da10
192.168.240.0   0.0.0.0         255.255.240.0   U     0      0        0 br-5ee84192e789

So it appears that the Tunnel is up and running but I cannot ping the ip address 192.168.200.125 from the server, neither can I traceroute to it. Any assistance would be greatly appreciated.
Thanks
Update 1
I've made a bit more progress.
sudo ip route get 192.168.200.125
The command above showed that a docker network was somehow getting in the middle. I removed the docker network and now instead of just receiving Destination unreachable it's attempting to ping. Still no luck connecting to the ip though. Might be docker still messing with the routing but not 100% sure.
Update 2
Restarting IPsec seems to resolve the problem.

A: I had the same problem about ipsec tunnel(using Libreswan).
Although the IPsec Tunnel is established, I get the message "Destination host unreachable" when ping to IPv4 address of the host another side.
In my case, because of wrongly setting masquerade table, packets going to a private address are masqueraded with the global IPv4 address which the interface eth0 has.
Therefore, I make new masquerade rules below not to let overwrite the source address of outgoing packet which has the private address destination.
i.e.
# iptables -t nat -A POSTROUTING -s 172.30.0.0/24 -d 192.168.0.0/16,172.16.0.0/12,10.0.0.0/8 -o eth0 -j RETURN
# iptables -t nat -A POSTROUTING -s 172.30.0.0/24 -o eth0 -j MASQUERADE

The first rule returns packets whose destination address is of private networks.
Those packets are going to IPsec Tunnel without masquerade processing.
The second rule is normal masquerade. Only the other packets are masqueraded and are going to the Internet.


text:
Q: JDBI3 reverse of AbstractArgumentFactory.build My MySQL table looks have three columns one long(user_id) another varchar(name) and finally varchar(rules(this is a JSON array as string)). I have integrated JDBI3 recently and I am using its @BindBean option. My bean(user class) looks as follows.
public class User {
    private long id;
    private String name;
    private List<Rule> rules;
}

and my rule class looks as follow.
public class Rule {
    private long id;
}

I have also created an AbstractArgumentFactory as follows
public class RuleArgumentFactory extends AbstractArgumentFactory<List<Rule>> {

    public RuleArgumentFactory() {
        super(Types.VARCHAR);
    }

    @Override
    protected Argument build(List<Rule> value, ConfigRegistry config) {
        return (position, statement, ctx) -> statement.setString(position, valueToJson());
    }
}

I have finally attached the ArgumentFactory to handle while performing DB queries. Now when I am doing an update or insert operation like as follows it works well.
this.jdbi.useHandle(handle -> {
    handle.registerArgument(new RuleArgumentFactory());
    handle.createUpdate(UPDATE_QUERY)
        .bindBean(User)
        .execute();
});

But the problem is when I perform a select query,
return this.jdbi.withHandle(handle -> {
    handle.registerArgument(new RuleArgumentFactory());
    return handle.createQuery(SELECT_QUERY)
            .bind(param, paramValue)
            .mapToBean(User.class)
            .findFirst();
});

I am unable to get the User Object because when JDBI tries to execute the build function. Arguments to the function gets mismatched as they become (String, ConfigRegistry) while it is accepting (List<Rule>, ConfigRegistry) finally throwing the error argument type mismatch. Is there a way where I can serialise the JSON to the List<Rule> object. Perhaps something opposite to build().


text:
Q: Show that if two sets $A, B$ are NOT equal, then $(A\cup B)$ is NOT a subset of $ (A\cap B)).$ I am learning set theory and am stuck at this question:
Show that:
$$(A\neq B) \rightarrow \neg((A\cup B) \subseteq (A\cap B)).$$
Then deduce that:
$$((A\cup B) \subseteq (A\cap B)) \rightarrow (A=B).$$

A: If $A \neq B$ then $A \nsubseteq B$ or $B \nsubseteq A$.
Suppose, without loss of generality, that $A \nsubseteq B$, and let $a \in A \setminus B$.
Then $a \in A \cup B$, but $a \notin A \cap B$.


text:
Q: WorkManager WorkName table not being cleared after jobs complete I'm using WorkManager by calling WorkManager.enqueueUniqueWork(String, ExistingWorkPolicy, OneTimeWorkRequest), I examined on the db on disk androix.work.workdb and noticed in the WorkName table there is an entry for each job I started. They aren't removed after the work completed. Is this normal? Will they automatically be cleared? When and by whom? (the system or WorkManager?)

A: This is normal. WorkManager keeps finished jobs in its database so that you can continue to query for its WorkInfo via getWorkInfosForUniqueWorkLiveData() or other methods that give you the stats back (a fact pointed out by the keepResultsForAtLeast() documentation). If this was not the case, you'd never be able to find out that your job has succeeded, failed, or been cancelled.
As per the pruneWork() documentation:

You do not normally need to call this method - WorkManager takes care to auto-prune its work after a sane period of time

Where 'a sane period of time', according to the source code is currently set to 1 day (previously 7 days).


text:
Q: Different between functions and regression models in R? I'm really confused about regression models and functions in R. Here is my problem. I'm using the PLS package to make a model like Y~x. To do that I have to use 'plsr':
model=plsr(Y~X,ncomp=10,data=df1,center=TRUE, scale=TRUE, validation="LOO")

I couldn't find the source of the 'plsr' in the PLS source code but in the help document it says it refers to 'mvr{pls}' which I could find it. first is 'plsr' a function or model.. in the R terminology? is it built in R? and how does it refer to 'mvr' function in pls package?
Thanks


text:
Q: Campo do Formulário preenchido, mas dado como $pristine Estou fazendo uma requisição $http, o retorno é um JSON, atribuo ao model ($scope.elaborador), porém o campo ainda fica definido como $pristine.

  Data.post('getElaborador', $rootScope.codigo, 'Listagens').then(
   function(success){
    $scope.elaborador = success;
   }, function(error){
    console.log('Erro ao consulta informações do elaborador');
   });

    .state("perfil", {
        url: "/perfil",
        templateUrl: "views/profile/perfil.html",
        data: {pageTitle: 'Perfil de Usuário'},
        controller: "UserProfileController",
        resolve: {
            deps: ['$ocLazyLoad', function($ocLazyLoad) {
                return $ocLazyLoad.load({
                    name: 'MetronicApp',
                    insertBefore: '#ng_load_plugins_before',
                    files: [
                    '../assets/global/plugins/angularjs/plugins/ui-select/select.min.css',
                    '../assets/global/plugins/angularjs/plugins/ui-select/select.min.js',

                    '../assets/pages/css/profile.css',
                    '../assets/js/angular-viacep.min.js',

                    'js/controllers/UserProfileController.js'
                    ]
                });
            }]
        }
    })
    // User Profile Dashboard
    .state("perfil.cadastro", {
        url: "/cadastro",
        templateUrl: "views/profile/elaborador.html",//onde esta o formulario
        data: {pageTitle: 'Perfil de Usuário'}
    })

 {{dados[0]}}

 {{(dados[1]==1?'Elaborador':'Membro da Comissão')}}

                    <button type="button" class="btn btn-circle green-haze btn-sm">Follow</button>
                    <button type="button" class="btn btn-circle btn-danger btn-sm">Message</button>

                                 Cadastro

                                 Formação

//elaborador.html

<form name="elaboradorFrm" id="elaboradorFrm" data-toggle="validator" role="form" style="margin-top:20px;margin-right:5px;margin-left:5px;" autocomplete="off">

  <fieldset>
   <legend style="border-bottom: 1px dashed #f7dfd5;">Dados Pessoais</legend>

      Nome *
      <input class="form-control" type="text" id="cadNome" name="cadNome" ng-model="elaborador.cadNome" ng-minlength="3" ng-required="true">

  </fieldset>

</form>

A: Ao atribuir programaticamente um valor, utilize $setDirty() para remover o estado pristino do formulário.
Exemplo:
Data.post('getElaborador', $rootScope.codigo, 'Listagens').then(
        function(success){
            $scope.elaborador = success;
            $scope.nomeDoFormulario.$setDirty();
        }, function(error){
            console.log('Erro ao consulta informações do elaborador');
        });


text:
Q: Shiny selectizeInput: on click remove the initial selected value i would like to remove the initial value (selected=) from selectizeInput when the user click on the widget.
Here is a sample code:
library(shiny)
library(dplyr)

ui= fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectizeInput(inputId= "cyl", label= "cyl",
                     choices= NULL,
                     selected= sort(unique(mtcars$cyl))[1],
                     multiple=T)
    ),
    mainPanel(
      tableOutput("tab")
    )
  )
)

server= function(input, output,session) {

  updateSelectizeInput(session = session,inputId ="cyl",choices=sort(unique(mtcars$cyl)),selected=sort(unique(mtcars$cyl))[1], server = TRUE)

  df_filtered= reactive({
    mtcars %>%
    {if (is.null(input$cyl)) . else filter(., cyl %in% input$cyl)}
  })
  output$tab= renderTable(df_filtered())
}

shinyApp(ui, server)

Just a bit of explanation on base of sample code:
The initial selected value in selectizeInput "cyl" is 4. When the user press on this widget, i would like that the value 4 is removed and the selected option is cleared. Any ideas?
*I have used the function updateSelectizeInput in server because in my shiny app choice selection is very big leading to too long loading time

A: You can use shinyjs::onclick to call updateSelectizeInput when the user clicks on the selectize field, eg:
library(shiny)
library(dplyr)
library(shinyjs)

ui= fluidPage(
  useShinyjs(),
  sidebarLayout(
    sidebarPanel(
      selectizeInput(inputId= "cyl", label= "cyl",
                     choices= NULL,
                     selected= sort(unique(mtcars$cyl))[1],
                     multiple=T)
    ),
    mainPanel(
      tableOutput("tab")
    )
  )
)

server= function(input, output,session) {

  updateSelectizeInput(session = session,inputId ="cyl",choices=sort(unique(mtcars$cyl)),selected=sort(unique(mtcars$cyl))[1], server = TRUE)

  df_filtered= reactive({
    mtcars %>%
    {if (is.null(input$cyl)) . else filter(., cyl %in% input$cyl)}
  })
  output$tab= renderTable(df_filtered())

  onclick("cyl", {
    updateSelectizeInput(session, "cyl", selected = "")
  })
}

shinyApp(ui, server)


text:
Q: How to overlap children while keeping parents as is in flex direction column I have two parent flex items positioned as flex-direction: column.
The first parent has two children. One child is optional, and sometimes it is removed.
I want the optional child to be on top of the other child. When I add/remove the optional content, I want the layout to not be affected.
I tried setting negative margin on the optional child (see commented css), then the outer parent below overlaps the first parent with children.
Why does that happen, and how can I overlap two children while keeping outer parents as is?

      content

      more content

    content

.container {
  display: flex;
  flex-direction: column;
}
.parent {
  width: 10vw;
  border: 1px solid black;
}

.child {
  border: 1px solid red;
  height: 50px;
}

.optional {
  /* margin-top: -60px; */
}

http://codepen.io/eguneys/pen/JdzWqK

A: My 1st advice to you is not to use a class name with a space in it like "optional child". Choose a name like "optional-child".

My 2nd advice is not using negative margins almost never. I can't even imagine a situation in which it could be a good solution.
The solution to the problem may be: Setting the div tag with class name "optional-child" before the div tag with class name "child". And If you want to remove it with a js code for use the command
document.getElementByClassName("optional-child")='0px'


text:
Q: Can you simulate any probability with biased coin throws? What you're given:
$p \in (0,1)$, but you don't know the value of $p$.
You have an algorithm $\mathcal{A}_p$ that returns $1$ with a probability of $p$ and $0$ with a probability of $(1-p)$. You can think of this as a biased coin throw. You may throw the coin as often as you want and the bias doesn't change.
What I've concluded:
You can get an algorithm $\mathcal{A}_\frac{1}{2}$ that returns 1 with a probability of $0.5$ and $0$ with a probability of $0.5$:
A_0.5() {
    int x = 0, y = 0;
    while (x == y) {
        x = A_p();
        y = A_p();
    }
    return x;
}

It is obvious that you can get any algorithm $\mathcal{A}_\frac{1}{2^n}$ by executing $\mathcal{A}_\frac{1}{2}$ $n$ times in a row.
The corner cases $\mathcal{A}_1$ and $\mathcal{A}_0$ are easy:
A_1() {
    return 1;
}

A_0() {
    return 0;
}

The question:
Can you get any algorithm $\mathcal{A}_q$ with $q \in \mathbb{Q} \cap [0,1]$?
Can you get any algorithm $\mathcal{A}_r$ with $r \in \mathbb{R} \cap [0,1]$?

A: You have shown how to simulate a fair coin. We now deal with the general case. There is no problem if $r=0$ and $r=1$. Let $r$ be a real number strictly between $0$ and $1$. Then $r$ has a binary expansion. To be precise, sometimes it has two. If relevant, use the expansion that is ultimately all $0$'s rather than the one which is ultimately all $1$'s.
Let random variable $X$ be uniformly distributed on $(0,1)$, and let $E$ be the event $X\l r$.  Then $\Pr(E)=r$.
Record the results of "tossing the fair coin," $0$ for head and $1$ for tail. As long as the sequence coin tosses agree with the binary expansion of $r$, keep tossing. Terminate the first time that the bit $a$ obtained from the "coin" differs from the corresponding bit $b$ of $r$.
If $a=0$ and $b=1$, the algorithm declare that $E$ has happened, since now for sure the number our sequence of tosses generates is $\lt r$.  If $a=1$, and $b=0$, declare that the event $\lnot E$ has happened.
Note that one can only say that the algorithm terminates with probability $1$.  This was already the case for the simulating the fair coin part.

A: It cannot be possible for any $r\in \mathbb R$ since these are more than countable, while the algorithms are countable.
It is simple to adapt your algorithm for every rational of the form $1/n$ and hence should be possible for every rational $m/n$.
code for $1/3$
A_iii() {
  while (1) {
     x = A_p();
     y = A_p();
     z = A_p();
     if (x==1 && y==0 && z==0) return 1;
     if (x==0 && y==1 && z==0) return 0;
     if (x==0 && y==0 && z==1) return 0;
  }
}

A: Referring to your question on Emanuele Paolini's answer: an algorithm for $A_n$ in Python might look like
 def A(n):
    while(True):
        x = [Ap() for i in range(n)]
        if sum(x)==1: return x[0]

The idea is the following sum(x) is one if exactly one x[i] is non-zero. Each of these cases has the same probability namely $p_i=p (1-p)^n$, so the probability of the algorithm to return 1 is the conditional probability $p(x_0=1|\sum_i x_i=1)=p (1-p)^n / (n p (1-p)^n)=1/n$.
(Since I'm only building this up on answers already given here, I marked this as community wiki).

A: Here is an algorithm that takes $r \in [0,1]\cap\mathbb{R}$ as a parameter and returns $1$ with probability $r$ and $0$ with probability $1-r$.
A(real r)
{
  while (true)
  {
    int b = random_bit();
    if (r>=0.5)
    {
      if (b==0) return 1;
      else r=r*2.0-1.0;
    }
    else
    {
      if (b==1) return 0;
      else r=r*2.0;
    }
  }
}


text:
Q: My "camera" is reversed when i get to a certain location in the z direction, what could be causing this? I am Using c++, OpenGL, SOIL graphics library, and Microsoft Visual c++ 2010 Express.
i've added a video to demonstrate the problem
http://www.youtube.com/watch?v=7F7YDN0zbc4&feature=youtu.be
This is my current problem;
Our stage, or environment is a 3D[x][y][z].
The problem doesn't occur when we move in the x direction and neither on the y(we don't allow moving in the y direction in terms of steps, we can jump).
But once we get to z=70, the camera turns around. so if moving towards z=70 whilst x and y are 1, lets consider our facing + in the z direction, but once we reach 70, our camera turns around but our facing is still +. I know this because i have a cout << that tells me the direction and coordinate system position.
cout << "The player is at position: " << player.getXPos() << ", " << player.getYPos()  << ", " << player.getZPos() << ", " << player.getFacing() << "\n";

I am not sure what kind of code i need to put in here, so what kind of functions should i put in here.
//this is our starting position
void demo(){
     gameState = 1;
     player.setPos(4,1,15);
     player.setFacing(3);
     setPos();
     cout << "The player is at position: " << player.getXPos() << ", " << player.getYPos() << ", " << player.getZPos() << ", " << player.getFacing();
}

//this is how we set our position
void setPos(){
     currentXPos = player.getXPos()+(player.getXWidth()/2);
     currentYPos = player.getYPos()+(player.getYHeight());
     currentZPos = player.getZPos()+(player.getZDepth()/2);
     currentYFace = currentYPos;
     if(player.getFacing() == 0){
         currentXFace = MAPWIDTH;
         currentZFace = currentZPos;
     }else if(player.getFacing() == 2){
         currentXFace = 0;
         currentZFace = currentZPos;
     }else if(player.getFacing() == 3){
         currentXFace = currentXPos;
         currentZFace = MAPDEPTH;
     }else{
         currentXFace = currentXPos;
         currentZFace = 0;
     }
}

//this is our display function
 void /*GraphicsEngine::*/display(){
      glClearColor (0.0, 0.0, 0.0, 1.0);
       glLoadIdentity ();
      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
      glShadeModel(GL_FLAT);
       glClearDepth(1.0);
      glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
      glMatrixMode(GL_MODELVIEW);
      glLoadIdentity();
      setPos();
      gluLookAt(currentXPos,currentYPos,currentZPos,currentXFace,currentYFace,currentZFace,0,1,0);
      generateMap();
      graphicsFloor();
      int i = 0;
      if(projectiles.size()>0){
         for(i= 0; i< projectiles.size(); i++){
             arrow(projectiles.operator[](i).getXPos(),projectiles.operator[](i).getYPos(),projectiles.operator[](i).getZPos(),0.5,BLOCKWIDTH);
         }
         projectileMotion();
         player.advance();
         glutPostRedisplay();
      }else if(player.advance()){
          glutPostRedisplay();
      }
      glFlush();
      glutSwapBuffers();
 }

//this is our reshape function
void reshape(int w, int h){
        glViewport(0, 0, (GLsizei) w, (GLsizei) h);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluPerspective(60.0, (GLfloat) w/(GLfloat) h, 1.0, 200.0);
        glMatrixMode(GL_MODELVIEW);
            glTranslatef(0.0, 0.0, -3.6);
        glLoadIdentity();
}

//this is how we control what the user does with keyboard, i won't post all of the other cases since, they are blank
 void userAction(unsigned int userInput){
int i;
switch(userInput){
    case 1:
        player.turnLeft();
        glutPostRedisplay();
        break;
    case 2:
        player.turnRight();
        //apply graphics
        glutPostRedisplay();
        break;
    case 3:
        if(player.getFacing() == 0){
            player.setPos(player.getXPos()-1,player.getYPos(),player.getZPos());
            cout << "The player is at position: " << player.getXPos() << ", " << player.getYPos() << ", " << player.getZPos() << ", " << player.getFacing() << "\n";
        }else if(player.getFacing() ==3){
            player.setPos(player.getXPos(),player.getYPos(),player.getZPos()-1);
            cout << "The player is at position: " << player.getXPos() << ", " << player.getYPos() << ", " << player.getZPos() << ", " << player.getFacing() << "\n";
        }else if(player.getFacing() == 2){
            player.setPos(player.getXPos()+1,player.getYPos(),player.getZPos());
            cout << "The player is at position: " << player.getXPos() << ", " << player.getYPos() << ", " << player.getZPos() << ", " << player.getFacing() << "\n";
        }else{
            player.setPos(player.getXPos(),player.getYPos(),player.getZPos()+1);
            cout << "The player is at position: " << player.getXPos() << ", " << player.getYPos() << ", " << player.getZPos() << ", " << player.getFacing() << "\n";
        }
        //apply graphics
        glutPostRedisplay();
        break;
    case 4:
        if(player.getFacing() == 0){
            player.setPos(player.getXPos()+1,player.getYPos(),player.getZPos());
            cout << "The player is at position: " << player.getXPos() << ", " << player.getYPos() << ", " << player.getZPos() << ", " << player.getFacing() << "\n";
        }else if(player.getFacing() ==3){
            player.setPos(player.getXPos(),player.getYPos(),player.getZPos()+1);
            cout << "The player is at position: " << player.getXPos() << ", " << player.getYPos() << ", " << player.getZPos() << ", " << player.getFacing() << "\n";
        }else if(player.getFacing() == 2){
            player.setPos(player.getXPos()-1,player.getYPos(),player.getZPos());
            cout << "The player is at position: " << player.getXPos() << ", " << player.getYPos() << ", " << player.getZPos() << ", " << player.getFacing() << "\n";
        }else{
            player.setPos(player.getXPos(),player.getYPos(),player.getZPos()-1);
            cout << "The player is at position: " << player.getXPos() << ", " << player.getYPos() << ", " << player.getZPos() << ", " << player.getFacing() << "\n";
        }
        //apply graphics
        glutPostRedisplay();
        break;
    case 5:
        if(player.getFacing() == 0){
            player.setPos(player.getXPos(),player.getYPos(),player.getZPos()-1);
            cout << "The player is at position: " << player.getXPos() << ", " << player.getYPos() << ", " << player.getZPos() << ", " << player.getFacing() << "\n";
        }else if(player.getFacing() == 2){
            player.setPos(player.getXPos(),player.getYPos(),player.getZPos()+1);
            cout << "The player is at position: " << player.getXPos() << ", " << player.getYPos() << ", " << player.getZPos() << ", " << player.getFacing() << "\n";
        }else if(player.getFacing() == 3){
            player.setPos(player.getXPos()+1,player.getYPos(),player.getZPos());
            cout << "The player is at position: " << player.getXPos() << ", " << player.getYPos() << ", " << player.getZPos() << ", " << player.getFacing() << "\n";
        }else{
            player.setPos(player.getXPos()-1,player.getYPos(),player.getZPos());
            cout << "The player is at position: " << player.getXPos() << ", " << player.getYPos() << ", " << player.getZPos() << ", " << player.getFacing() << "\n";
        }
        glutPostRedisplay();
        break;
    case 6:
        if(player.getFacing() == 0){
            player.setPos(player.getXPos(),player.getYPos(),player.getZPos()+1);
            cout << "The player is at position: " << player.getXPos() << ", " << player.getYPos() << ", " << player.getZPos() << ", " << player.getFacing() << "\n";
        }else if(player.getFacing() == 2){
            player.setPos(player.getXPos(),player.getYPos(),player.getZPos()-1);
            cout << "The player is at position: " << player.getXPos() << ", " << player.getYPos() << ", " << player.getZPos() << ", " <<player.getFacing() << "\n";
        }else if(player.getFacing() == 1){
            player.setPos(player.getXPos()+1,player.getYPos(),player.getZPos());
            cout << "The player is at position: " << player.getXPos() << ", " << player.getYPos() << ", " << player.getZPos() << ", " << player.getFacing() << "\n";
        }else{
            player.setPos(player.getXPos()-1,player.getYPos(),player.getZPos());
            cout << "The player is at position: " << player.getXPos() << ", " << player.getYPos() << ", " << player.getZPos() << ", " << player.getFacing() << "\n";
        }
        glutPostRedisplay();
        break;
 }

//and this is how we set the face
 void PlayerCharacter::setFacing(unsigned short newFace){
      facing = newFace % 4;
 }

//and this is for the position
bool PlayerCharacter::setPos(int x, int y, int z){
positionData pTemp;
pTemp.x = x;
pTemp.y = y;
pTemp.z = z;
pTemp.id = p.id;
pTemp.w = p.w;
pTemp.h = p.h;
pTemp.d = p.d;
pTemp.type = p.type;
 if(/*phys->*/openBlocks(pTemp) && /*phys->*/validPosition(pTemp)==0){
      p.x=x;
      p.y=y;
      p.z=z;
      /*phys->*/updatePlacements(p);
      return true;
 }else{
      return false;
 }
}

A: currentZPos = player.getZPos(); Doing this fixes the problem


text:
Q: Include URL with city parameter based on user's IP The javascript code below works perfectly in the HTML of my site. It is a geo-target server that shows the city based on the user's IP.

What I am doing is and I can not get it to work within a link I want to be generated according to the person's city. Example:
New York

I tried to work the way down but the response to the end of the URL after ?Q= is the code itself. I tried this:
New York

I have no experience with this, so any solution either in PHP or javascript would be welcome. I thank you!

A: In Jquery this is quite easy:
function cityUrl( ){
var url = "http://www.example.net/?q=";
var city;
$.get("http://promos.fling.com/geo/txt/location.php?testip=", function(data){
url += data;
city = data
}
var html = ""+city+"";
$( "div" ).append( html );
}

This generates a url based on the location, makes a link out of that url and sets the city as the clickable part of the link. Then this will be appended to the element specified (in this case div)
This might need some tweeking for your purposes but im sure you get the idea

I believe I was too much unclear about everything so I`ll try to clarify:
This is a function you need to call once for the page you want to show them on. Of course you cannot copy and paste this code and expect it to work.
Fiddle doesnt 100% work due to https and cross origin requests, but does reflect the idea


text:
Q: How to control shadow of element with CSS? I am playing around with animating shadow. I want it to work like this: When i click on box, i want class of "shadow" to be added. When it does, i want to animate shadow like it is lifting up, and when removed class, i want shadow to disappear the same way it appears (reverse). I have created keyframes and set the blur and opacity to change.
One thing i notice is, the animation is not smooth, it goes by steps. Why is it so? I want shadow animation to be smooth.
Second, how to create that shadow will also disappear in reverse when class is removed?
Here is my code so far:

const box = document.querySelector(".box");
function shadowHandle(){
 box.classList.toggle("shadow");
}

box.addEventListener("click", shadowHandle);
body{
  margin: 100px;
}
.box{
  width: 100px;
  height: 300px;
  background-color: red;
}

@-webkit-keyframes shadow { /* Webkit */
 0%   { box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2); }
  25%  { box-shadow: -1px 0px 15px rgba(0, 0, 0, 0.5); }
 50%  { box-shadow: -2px 0px 20px rgba(0, 0, 0, 0.7); }
  75%  { box-shadow: -3px 0px 30px rgba(0, 0, 0, 0.9); }
 100% { box-shadow: -4px 0px 40px rgba(0, 0, 0, 1); }
}
@-moz-keyframes shadow { /* Webkit */
 0%   { box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2); }
  25%  { box-shadow: -1px 0px 15px rgba(0, 0, 0, 0.5); }
 50%  { box-shadow: -2px 0px 20px rgba(0, 0, 0, 0.7); }
  75%  { box-shadow: -3px 0px 30px rgba(0, 0, 0, 0.9); }
 100% { box-shadow: -4px 0px 40px rgba(0, 0, 0, 1); }
}
@keyframes shadow { /* Webkit */
 0%   { box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2); }
  25%  { box-shadow: -1px 0px 15px rgba(0, 0, 0, 0.5); }
 50%  { box-shadow: -2px 0px 20px rgba(0, 0, 0, 0.7); }
  75%  { box-shadow: -3px 0px 30px rgba(0, 0, 0, 0.9); }
 100% { box-shadow: -4px 0px 40px rgba(0, 0, 0, 1); }
}
.shadow {
 animation:         shadow 2s forwards; /* CSS3 */
 -moz-animation:    shadow 2s forwards; /* Firefox */
 -webkit-animation: shadow 2s forwards; /* Webkit */
}

A: I think using a transition is the way to go here. It will animate back "mid-animation".
here's an example with :hover, but you can use an added class as well.

.box{
  width: 100px;
  height: 100px;
  background: silver;
  box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
  transition: box-shadow 0.3s ease-in-out;
}

.box:hover {
  box-shadow: -4px 0px 40px rgba(0, 0, 0, 1);
}

A: This can be simply achieved through transition
Follow the snippet below:
Add the box-shadow to class shadow
now add CSS transition to the `.box.
transition: all 1s linear
This will animate all css properties which can be animated
For a duration of 1s
In a linear rate. Other values are ease ease-in ease-out, etc
Play around and find out.

const box = document.querySelector(".box");

function shadowHandle() {
  box.classList.toggle("shadow");
}

box.addEventListener("click", shadowHandle);
body {
  margin: 100px;
}

.box {
  width: 100px;
  height: 300px;
  background-color: red;
  transition: all 1s linear;
}

.shadow {
  box-shadow: -4px 0px 40px rgba(0, 0, 0, 1);
}

A: Added another animation class no-shadow with reverse styles.
@-webkit-keyframes no-shadow { /* Webkit */
    0%   { box-shadow: -4px 0px 40px rgba(0, 0, 0, 1); }
    25%  { box-shadow: -3px 0px 30px rgba(0, 0, 0, 0.9); }
    50%  { box-shadow: -2px 0px 20px rgba(0, 0, 0, 0.7); }
    75%  { box-shadow: -1px 0px 15px rgba(0, 0, 0, 0.5); }
    100% { box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2); }
}
@-moz-keyframes no-shadow { /* Webkit */
    0%   { box-shadow: -4px 0px 40px rgba(0, 0, 0, 1); }
    25%  { box-shadow: -3px 0px 30px rgba(0, 0, 0, 0.9); }
    50%  { box-shadow: -2px 0px 20px rgba(0, 0, 0, 0.7); }
    75%  { box-shadow: -1px 0px 15px rgba(0, 0, 0, 0.5); }
    100% { box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2); }
}
@keyframes no-shadow { /* Webkit */
    0%   { box-shadow: -4px 0px 40px rgba(0, 0, 0, 1); }
    25%  { box-shadow: -3px 0px 30px rgba(0, 0, 0, 0.9); }
    50%  { box-shadow: -2px 0px 20px rgba(0, 0, 0, 0.7); }
    75%  { box-shadow: -1px 0px 15px rgba(0, 0, 0, 0.5); }
    100% { box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2); }
}

.no-shadow {
    animation:         no-shadow 2s forwards; /* CSS3 */
    -moz-animation:    no-shadow 2s forwards; /* Firefox */
    -webkit-animation: no-shadow 2s forwards; /* Webkit */
}

const box = document.querySelector(".box");
function shadowHandle(){
 box.classList.toggle("shadow");
 box.classList.toggle("no-shadow");
}

box.addEventListener("click", shadowHandle);
body{
  margin: 100px;
}
.box{
  width: 100px;
  height: 300px;
  background-color: red;
}

@-webkit-keyframes shadow { /* Webkit */
 0%   { box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2); }
 25%  { box-shadow: -1px 0px 15px rgba(0, 0, 0, 0.5); }
 50%  { box-shadow: -2px 0px 20px rgba(0, 0, 0, 0.7); }
 75%  { box-shadow: -3px 0px 30px rgba(0, 0, 0, 0.9); }
 100% { box-shadow: -4px 0px 40px rgba(0, 0, 0, 1); }
}
@-moz-keyframes shadow { /* Webkit */
 0%   { box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2); }
 25%  { box-shadow: -1px 0px 15px rgba(0, 0, 0, 0.5); }
 50%  { box-shadow: -2px 0px 20px rgba(0, 0, 0, 0.7); }
 75%  { box-shadow: -3px 0px 30px rgba(0, 0, 0, 0.9); }
 100% { box-shadow: -4px 0px 40px rgba(0, 0, 0, 1); }
}
@keyframes shadow { /* Webkit */
 0%   { box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2); }
 25%  { box-shadow: -1px 0px 15px rgba(0, 0, 0, 0.5); }
 50%  { box-shadow: -2px 0px 20px rgba(0, 0, 0, 0.7); }
 75%  { box-shadow: -3px 0px 30px rgba(0, 0, 0, 0.9); }
 100% { box-shadow: -4px 0px 40px rgba(0, 0, 0, 1); }
}
.shadow {
 animation:         shadow 2s forwards; /* CSS3 */
 -moz-animation:    shadow 2s forwards; /* Firefox */
 -webkit-animation: shadow 2s forwards; /* Webkit */
}

@-webkit-keyframes no-shadow { /* Webkit */
 0%   { box-shadow: -4px 0px 40px rgba(0, 0, 0, 1); }
 25%  { box-shadow: -3px 0px 30px rgba(0, 0, 0, 0.9); }
 50%  { box-shadow: -2px 0px 20px rgba(0, 0, 0, 0.7); }
 75%  { box-shadow: -1px 0px 15px rgba(0, 0, 0, 0.5); }
 100% { box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2); }
}
@-moz-keyframes no-shadow { /* Webkit */
 0%   { box-shadow: -4px 0px 40px rgba(0, 0, 0, 1); }
 25%  { box-shadow: -3px 0px 30px rgba(0, 0, 0, 0.9); }
 50%  { box-shadow: -2px 0px 20px rgba(0, 0, 0, 0.7); }
 75%  { box-shadow: -1px 0px 15px rgba(0, 0, 0, 0.5); }
 100% { box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2); }
}
@keyframes no-shadow { /* Webkit */
 0%   { box-shadow: -4px 0px 40px rgba(0, 0, 0, 1); }
 25%  { box-shadow: -3px 0px 30px rgba(0, 0, 0, 0.9); }
 50%  { box-shadow: -2px 0px 20px rgba(0, 0, 0, 0.7); }
 75%  { box-shadow: -1px 0px 15px rgba(0, 0, 0, 0.5); }
 100% { box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2); }
}

.no-shadow {
 animation:         no-shadow 2s forwards; /* CSS3 */
 -moz-animation:    no-shadow 2s forwards; /* Firefox */
 -webkit-animation: no-shadow 2s forwards; /* Webkit */
}

A: You don't need Keyframes. This is much more easier with transition

const box = document.querySelector(".box");
function shadowHandle(){
 box.classList.toggle("shadow");
}

box.addEventListener("click", shadowHandle);
body{
  margin: 100px;
}
.box{
  width: 100px;
  height: 300px;
  background-color: red;
  box-shadow: none;
  transition: all 1s ease;

}

.box.shadow {
  box-shadow: 0 14px 28px rgba(0,0,0,0.25), 0 10px 10px rgba(0,0,0,0.22);
 }


text:
Q: How to ImportKey() to get CryptoObject from ExportedKey? Trying to use the SubtleCrypto Web API to generate a public/private key pair, then use that keypair for encryption from a user inputting the public key, but importKey() keeps giving result as undefine. For public/private key generation, I have the following:
window.crypto.subtle.generateKey(
    {
        name: "RSA-OAEP",
        modulusLength: 2048, // can be 1024, 2048 or 4096
        publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
        hash: {name: "SHA-256"} // or SHA-512
    },
    true,
    ["encrypt", "decrypt"]
).then(function(keyPair) {

    console.log(keyPair);

    window.crypto.subtle.exportKey(
        "pkcs8",
        keyPair.privateKey
    ).then(function(exportedPrivateKey) {
        // converting exported private key to PEM format
        var pem = toPem(exportedPrivateKey);
        console.log(pem);
    }).catch(function(err) {
        console.log(err);
    });

    window.crypto.subtle.exportKey(
        "spki",
        keyPair.publicKey
    ).then(function(exportedPublicKey) {
        // converting exported private key to PEM format
        var pem = toPemP(exportedPublicKey);
        console.log(pem);
        let resultingKey = importPublicKey(pem)
        console.log('keyPairPublic: ', keyPair.publicKey)
        console.log('resultingKey: ', resultingKey)

    }).catch(function(err) {
        console.log(err);
    });
});

the toPem() and toPemP() functions are as follows:
function toPem(privateKey) {
    var b64 = addNewLines(arrayBufferToBase64(privateKey));
    var pem = "-----BEGIN PRIVATE KEY-----\n" + b64 + "-----END PRIVATE KEY-----";

    return pem;
}

function toPemP(publicKey) {
    var b64 = addNewLines(arrayBufferToBase64(publicKey));
    var pem = "-----BEGIN PUBLIC KEY-----\n" + b64 + "-----END PUBLIC KEY-----";

    return pem;
}

function arrayBufferToBase64(arrayBuffer) {
    console.log('arrayBuffer', arrayBuffer);
    var byteArray = new Uint8Array(arrayBuffer);
    var byteString = '';
    for(var i=0; i < byteArray.byteLength; i++) {
        byteString += String.fromCharCode(byteArray[i]);
    }
    var b64 = window.btoa(byteString);

    return b64;
}

function addNewLines(str) {
    var finalString = '';
    while(str.length > 0) {
        finalString += str.substring(0, 64) + '\n';
        str = str.substring(64);
    }

    return finalString;
}

The importKey() function is as follows:
function importPublicKey(pem) {
    // base64 decode the string to get the binary data
    // fetch the part of the PEM string between header and footer
    const pemHeader = "-----BEGIN PUBLIC KEY-----";
    const pemFooter = "-----END PUBLIC KEY-----";
    let pemContents = pem.substring(pemHeader.length, pem.length - pemFooter.length)
    pemContents = pemContents.replace(/\s/g, '');
    console.log('pemContents:', pemContents)
    let binaryDerString = window.atob(pemContents);
    // convert from a binary string to an ArrayBuffer
    const binaryDer = str2ab(binaryDerString);
    console.log('binaryDer', binaryDer)

    window.crypto.subtle.importKey(
        "spki",
        binaryDer,
        {
            name: "RSA-OAEP",
            hash: { name: "SHA-256" }
        },
        true,
        ["encrypt"]
    ).then(function(result) {
        return result;
    }).catch(function(err) {
        console.log('err: ', err);
    })
}

Where str2ab() is as follows:
function str2ab(str) {
    const buf = new ArrayBuffer(str.length);
    const bufView = new Uint8Array(buf);
    for (let i = 0, strLen = str.length; i < strLen; i++) {
        bufView[i] = str.charCodeAt(i);
    }
    return buf;
}

All of the above functions were from the SubtleCrypto documentation. When I run the above, I get the following:

I'm not sure why it comes out as undefined, but I can notice that arrayBuffer and binaryDer don't have the exact same size. Don't know if it means anything and not sure how to fix this, any help is appreciated!


text:
Q: Correct login to 'parse' Database I'm trying to create a login page for my application in swift.
I have a view with username and password and two buttons, one for the login and one (signup now) that calls another view in order to create a user.
The login button has to perform a segue to the home page when the login works good, it means that if the username field text or the password field text are empty, the application doesn't have to perform the segue. The problem is that the application calls the home view also if username and password are empty. This is the code:
import UIKit
import Parse

class LoginViewController: UIViewController {

    @IBOutlet weak var field_username: UITextField!
    @IBOutlet weak var field_password: UITextField!

    var currentUser :PFUser?

    @IBAction func login_clicked(sender: UIButton) {

            login(field_username.text, password: field_password.text)

    }

    func login(username : String, password : String) {

        PFUser.logInWithUsernameInBackground(field_username.text, password: field_password.text) { (user, error) -> Void in
            if user != nil {
                println("[PARSE] Login effettuato con successo")
                self.performSegueWithIdentifier("segueToHome", sender: self)
            } else {
                println("[ERROR] login with error: \(error!.description)")
            }
        }

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        if currentUser != nil {
            println("[Parse] The user \(currentUser!.username!) is already logged in")
            self.performSegueWithIdentifier("segueToHome", sender: self)
        } else {
            println("No user is logged in. \n Login or signup")
        }

    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func returnToLoginView(sender: UIStoryboardSegue) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
}

I was pretty sure that self.performSegueWithIdentifier(...) is executed if user is != from nil.
Anyone can help me to fix this thing? Thanks

A: If you want to perform a conditional segue you can achieve it by creating segue this way:

After that at your login you can call segue this way:
PFUser.logInWithUsernameInBackground(field_username.text, password: field_password.text) { (user, error) -> Void in
        if user != nil {
            println("[PARSE] Login effettuato con successo")
            //segue will perform here
            performSegueWithIdentifier("segueToHome", sender: self)
        } else {
            //Segue will not call here
            println("[ERROR] login with error: \(error!.description)")
        }
    }


text:
Q: Executing Java programs through Python How do I do this?

A: Of course, Jython allows you to use Java classes from within Python. It's an alternate way of looking at it that would allow much tighter integration of the Java code.

A: You can execute anything you want from Python with the os.system() function.

os.system(command)
  Execute the command
  (a string) in a subshell. This is
  implemented by calling the Standard C
  function system, and has the same
  limitations. Changes to os.environ,
  sys.stdin, etc. are not reflected in
  the environment of the executed
  command.

For more power and flexibility you will want to look at the subprocess module:

The subprocess module allows you to
  spawn new processes, connect to their
  input/output/error pipes, and obtain
  their return codes.


text:
Q: Implementing Events in a Base Class Consider the following objects:
Public MustInherit Class FileRepository

    Public MustOverride Sub SaveStringToFile(ByVal FileText As String, ByVal FilePath As String)

    Public Event FileSaved(ByRef sender As Object, ByVal EventArgs As EventArgs)

End Class

Public Class XMLFileRepository
    Inherits FileRepository

    Public Overrides Sub SaveStringToFile(ByVal FileText As String, ByVal FilePath As String)

    End Sub

    Private Sub XMLFileRepository_FileSaved(ByRef sender As Object, ByVal EventArgs As System.EventArgs) Handles Me.FileSaved

    End Sub
End Class

I want my base class to raise the FileSaved event in it's implentation of SaveStringToFile once it's saved the file.  However in VB.NET you can't have a derived class raise a base classes event.  I suppose I can treat XMLFileRepository_FileSaved as a standard function call and have my SaveStringToFile implementation call it directly but I think I'm approaching the problem the wrong way.  Any help would be great!

A: Add an overridable sub in your base class that raises the base classes FileSaved-Event:
Public MustInherit Class FileRepository

    Public MustOverride Sub SaveStringToFile(ByVal FileText As String, ByVal FilePath As String)

    Public Event FileSaved(ByVal FileText As String, ByVal FilePath As String)

    Protected Overridable Sub OnFileSaved(ByVal FileText As String, ByVal FilePath As String)
        RaiseEvent FileSaved(FileText, FilePath)
    End Sub

End Class

Public Class XMLFileRepository
    Inherits FileRepository

    Public Overrides Sub SaveStringToFile(ByVal FileText As String, ByVal FilePath As String)
        MyBase.OnFileSaved(FileText, FilePath)
    End Sub

    Private Sub XMLFileRepository_FileSaved(ByVal FileText As String, ByVal FilePath As String) Handles MyBase.FileSaved

    End Sub
End Class


text:
Q: Render a new page on react-routing but it renders it inside the current page This displays a card component that the user sees if the user clicks the <Link>read</Link> it should re-render a new page.
import React from "react";
import { Button } from "react-bootstrap";
import "./CardComponent.css";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import Content from "./ContentFolder/Content";

function CardComponent(props) {
  return (
    <Router>

{props.title}

By{props.author}

{props.points}

        <Link to={"/" + props.title + props.author}>Read</Link>

      <Switch>
        <Route
          exact
          path={`/${props.title+props.author}`}
          component={Content}
        >
          <Content title={props.title} author={props.author}
            points={props.points}
          />

        </Route>
      </Switch>
    </Router>
  );
}

export default CardComponent;

On clicking read I want to render this content component on a different page.
In summary, the goal is to display all the information on a new page when the user clicks on one of the card components.
import React from "react";
import Mynavbar from "../Partials/Mynavbar";
import MyFooter from "../Partials/Footer";
import { Container } from "react-bootstrap";
import "./Content.css";

function Content(props) {
  return (

      <Mynavbar />
      <Container className="main">

{props.title}

By {props.author}

          {props.points.map((point, i) => {
            return
{point}
;
          })}

      </Container>
      <MyFooter />

  );
}
export default Content;

A: Problem: Router inside of CardComponent
The Router needs to exist at the highest level of the App.  Everything that is inside of the Router and outside of the Switch will be rendered on every page.  So right now your card code will show up even on the Content route.  We want the Card and the Content to be separate Routes.
Problem: Ambiguous URL Structure
Do you need for your urls to look like "/${props.title+props.author}"?  This is a very bad structure because you cannot possibly work backwards from the URL to the content.  What is the content for "/Harry PotterJ.K. Rowling"?  Which part is the title and which part is the author?  There is no separator so you don't know.  You would have to loop through a list of all books, joining their title and author and comparing it to your string.
A typical URL would be based on an id, like "/book/5". I don't see any mention of an id here so we can use the title.
Solution
An app routing might look like this:
function App() {
  return (
    <Router>
      <Switch>
        <Route path="/book/:title" component={BookDetails}/>
        <Route path="/" component={BookList}/>
      </Switch>
    </Router>
  )
}

Let's get rid of all the routing in CardComponent and make it just show a card for a book with a link to the book details.
function CardComponent(props: Book) {
  return (

{props.title}

By{props.author}

{props.points}

      <Link to={"/book/" + props.title}>Read</Link>

  );
}

Our home page might show a list of these cards.
function BookList() {
  // get books from somewhere -- a database? a json file?
  const books = ???;

  return (

      {books.map((book) => (
        <CardComponent {...book} key={book.title} />
      ))}

  );
}

BookDetails is a separate route, so we need to get the book from the URL.
function BookDetails(props: RouteComponentProps) {
  // get the title from the URL
  // is automatically encoded and needs to be decoded
  const title = decodeURIComponent(props.match.params.title);
  // find the book object from your data source
  const book = ???
  // from a JSON array: BOOKS.find(book => book.title.toLowerCase() === title.toLowerCase() );

  // redirect to error page if no matching book
  if ( ! book ) {
    return <Redirect to="/404" />
  }

  // can render your Content component, but only after we get the book
  return (
    <Content {...book} />
  )
}