text:
Q: Redirect to new page after PHP validation I am very new to php and have been working on a website which contains a form for a restaurant reservation. Currently, I have one file, which contains both html and php code. The form is validated once the user clicks submit, however I was wondering how it might be possible to redirect the user to a new page, confirming their reservation, if all of the information they have entered into the form is correct.
Basically this is the process I wish the website to perform:
user fills out form

if validation not complete

   display error messages, loop back to form so user can correct fields

if form is validated fully

    Send user to confirmation page

Here is the necessary code for my reservations page:
....

<?php
$nameErr = $teleErr = $emailErr = $partyErr = $vipErr = $reservationErr = $timeErr = "";
$name = $tele = $email = $party = $vip = $reservation = $time = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["name"])) {
        $nameErr = "Please enter a full name";
    } else {
        $name = test_input($_POST["name"]);
        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
            $nameErr = "Invalid name entered";
        }
    }

    if (empty($_POST["tele"])) {
        $teleErr = "Please enter a telephone number";
    } else {
        $tele = test_input($_POST["tele"]);
        if (!preg_match("/^[0-9 ]{7,}$/",$tele)) {
            $teleErr = "Invalid telephone number entered";
        }
    }

    if (empty($_POST["email"])) {
        $emailErr = "Please enter an email address";
    } else {
        $email = test_input($_POST["email"]);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Invalid email entered";
        }
    }

    if($_POST['party']=="") {
        $partyErr = "Please select the party size";
    } else {
        $party = test_input($_POST["party"]);
    }

    if (empty($_POST["vip"])) {
        $vipErr = "Please make a VIP area selection";
    } else {
        $vip = test_input($_POST["vip"]);
    }

    if (empty($_POST["reservation"])) {
        $reservationErr = "Please enter the reservation date";
    } else {
        $reservation = test_input($_POST["reservation"]);
        if (!preg_match("/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/",$reservation)) {
            $reservationErr = "Invalid reservation date";
        }
    }

    if($_POST['time']=="") {
        $timeErr = "Please select the reservation time";
    } else {
        $time = test_input($_POST["time"]);
    }
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>

  Welcome to Steakhouse®, the number 1 restaurant for flame grilled goodness.

 Book a Table

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

* indicates a required field

 Full Name* :
 <input type="text" placeholder="John Doe" name="name" value="<?php echo $name;?>">
 <?php echo $nameErr;?>

 Contact Telephone* :
 <input type="text" placeholder="Telephone Number" name="tele" value="<?php echo $tele;?>">
<?php echo $teleErr;?>

 Contact Email* :
 <input type="text" placeholder="Example@email.com" name="email" value="<?php echo $email;?>">
<?php echo $emailErr;?>

Select Party Size* :

<select name="party" id="party" value="<?php echo $party;?>">
<option value="">Please Select</option>
<option <?php if (isset($party) && $party=="5") echo "selected";?> value="5">1 Person (+£5)</option>
<option <?php if (isset($party) && $party=="10") echo "selected";?> value="10">2 People (+£10)</option>
<option <?php if (isset($party) && $party=="15") echo "selected";?> value="15">3 People (+£15)</option>
<option <?php if (isset($party) && $party=="20") echo "selected";?> value="20">4 People (+£20)</option>
<option <?php if (isset($party) && $party=="25") echo "selected";?> value="25">5 People (+£25)</option>
<option <?php if (isset($party) && $party=="30") echo "selected";?> value="30">6 People (+£30)</option>
<option <?php if (isset($party) && $party=="35") echo "selected";?> value="35">7 People (+£35)</option>
<option <?php if (isset($party) && $party=="40") echo "selected";?> value="40">8 People (+£40)</option>
<option <?php if (isset($party) && $party=="45") echo "selected";?> value="45">9 People (+£45)</option>
<option <?php if (isset($party) && $party=="50") echo "selected";?> value="50">10+ People (+£50)</option>
</select>
<?php echo $partyErr;?>

Dietary Requirements:

Vegetarian <input type="checkbox" name="diet[]" value="Vegetarian">

Vegan <input type="checkbox" name="diet[]" value="Vegan">

Peanut Allergy <input type="checkbox" name="diet[]" value="Peanut Allergy">

Gluten Allergy <input type="checkbox" name="diet[]" value="Gluten Allergy">

 VIP area* :

Yes (+£5) <input type="radio" name="vip" <?php if (isset($vip) && $vip=="Yes") echo "checked";?> value="Yes">

<?php echo $vipErr;?>

No <input type="radio" name="vip" <?php if (isset($vip) && $vip=="No") echo "checked";?> value="No">

 Reservation Date* :
 <input type="text" placeholder="DD/MM/YYYY" name="reservation" value="<?php echo $reservation;?>">
<?php echo $reservationErr;?>

 Reservation Time* :

<select name="time" value="<?php echo $time;?>">
<option value="">Please Select</option>
<option <?php if (isset($time) && $time=="17:00") echo "selected";?> value="17:00">17:00</option>
<option <?php if (isset($time) && $time=="17:30") echo "selected";?> value="17:30">17:30</option>
<option <?php if (isset($time) && $time=="18:00") echo "selected";?> value="18:00">18:00</option>
<option <?php if (isset($time) && $time=="18:30") echo "selected";?> value="18:30">18:30</option>
<option <?php if (isset($time) && $time=="19:00") echo "selected";?> value="19:00">19:00</option>
<option <?php if (isset($time) && $time=="19:30") echo "selected";?> value="19:30">19:30</option>
<option <?php if (isset($time) && $time=="20:00") echo "selected";?> value="20:00">20:00</option>
<option <?php if (isset($time) && $time=="20:30") echo "selected";?> value="20:30">20:30</option>
<option <?php if (isset($time) && $time=="21:00") echo "selected";?> value="21:00">21:00</option>
<option <?php if (isset($time) && $time=="21:30") echo "selected";?> value="21:30">21:30</option>
<option <?php if (isset($time) && $time=="22:00") echo "selected";?> value="22:00">22:00</option>
</select>
<?php echo $timeErr;?>

 Any Additional Information:

<textarea name="comments" placeholder="Birthdays, Class Parties..." rows="7" cols="40"></textarea>

The total reservation price will be calculated automatically once submitted.

<input type="submit" id="submit" name="submit" value="Submit">
<input type="reset" value="Reset form">

....

I have put a lot of effort into my work thus far, so any suggestions are welcomed. Please remember I am new to web languages also. Thank you.

A: You can redirect your user using the header().
header('Location: http://yoursite.com/dashboard');
exit();

A: Where are you sending this form data to?. To itself or database. Anyway upon submission, you can echo
any of this javascript function to
redirect the user to a new page after 1 seconds.
echo "";

or

echo '';

A: Try this
<?php
$nameErr = $teleErr = $emailErr = $partyErr = $vipErr = $reservationErr = $timeErr = "";
$name = $tele = $email = $party = $vip = $reservation = $time = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $c = 0;

    if(empty($_POST["name"])) { {
        $nameErr = "Please enter a full name";
        $c++;
    }

    if(!empty($_POST["name"])) {
        $name = test_input($_POST["name"]);
        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
            $nameErr = "Invalid name entered";
            $c++;
        }
    }

    if (empty($_POST["tele"])) {
        $teleErr = "Please enter a telephone number";
        $c++;
    }

    if (!empty($_POST["tele"])) {
        $tele = test_input($_POST["tele"]);
        if (!preg_match("/^[0-9 ]{7,}$/",$tele)) {
            $teleErr = "Invalid telephone number entered";
            $c++;
        }
    }

    if (empty($_POST["email"])) {
        $emailErr = "Please enter an email address";
        $c++;
    }

    if (!empty($_POST["email"])) {
        $email = test_input($_POST["email"]);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Invalid email entered";
            $c++;
        }
    }

    if($_POST['party']=="") {
        $partyErr = "Please select the party size";
        $c++;
    } else {
        $party = test_input($_POST["party"]);
    }

    if (empty($_POST["vip"])) {
        $vipErr = "Please make a VIP area selection";
        $c++;
    } else {
        $vip = test_input($_POST["vip"]);
    }

    if (empty($_POST["reservation"])) {
        $reservationErr = "Please enter the reservation date";
        $c++;
    }

    if (!empty($_POST["reservation"])) {
        $reservation = test_input($_POST["reservation"]);
        if (!preg_match("/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/",$reservation)) {
            $reservationErr = "Invalid reservation date";
            $c++;
        }
    }

    if($_POST['time']=="") {
        $timeErr = "Please select the reservation time";
        $c++;
    } else {
        $time = test_input($_POST["time"]);
    }

    if($c == 0) {
        // redirect here
    }
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>

A: Here is your code
<?php
  $nameErr = $teleErr = $emailErr = $partyErr = $vipErr = $reservationErr = $timeErr = "";
  $name = $tele = $email = $party = $vip = $reservation = $time = "";

  if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $nameErr = "Please enter a full name";
  } else {
    $name = test_input($_POST["name"]);
    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
        $nameErr = "Invalid name entered";
    }
  }

  if (empty($_POST["tele"])) {
    $teleErr = "Please enter a telephone number";
  } else {
    $tele = test_input($_POST["tele"]);
    if (!preg_match("/^[0-9 ]{7,}$/",$tele)) {
        $teleErr = "Invalid telephone number entered";
    }
  }

  if (empty($_POST["email"])) {
    $emailErr = "Please enter an email address";
  } else {
    $email = test_input($_POST["email"]);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $emailErr = "Invalid email entered";
    }
  }

  if($_POST['party']=="") {
    $partyErr = "Please select the party size";
  } else {
    $party = test_input($_POST["party"]);
  }

  if (empty($_POST["vip"])) {
    $vipErr = "Please make a VIP area selection";
  } else {
    $vip = test_input($_POST["vip"]);
  }

  if (empty($_POST["reservation"])) {
    $reservationErr = "Please enter the reservation date";
  } else {
    $reservation = test_input($_POST["reservation"]);
    if (!preg_match("/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/",$reservation)) {
        $reservationErr = "Invalid reservation date";
  }
 }

 if($_POST['time']=="") {
    $timeErr = "Please select the reservation time";
 } else {
    $time = test_input($_POST["time"]);
 }

 if($nameErr == "" && $teleErr == "" && $emailErr == "" && $partyErr == "" && $vipErr == "" &&  $reservationErr == "" && $timeErr == ""){

    header('Location: http://yoursite.com/dashboard');
    exit();

}

 function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
 }

?>

A: Indeed you have done a lot of complication without using Arrays. You may in the case of an error existence set an array named $errors and its key should be the element of the form which is being on check. For example look at the following blue print code:

if (!my_check_email($_POST['email'])){
/* my_check_email() is a custom function the performs email validation. It returns true for valid email and it returns false for invalid email
*/
// Here invalid email
$errors['email'] = true;
}

The repeat similar coding style for other elements of the form you want to validate.  At the end you just have to check if the $errors is set or not as follows:
if (isset($errors)){
// do the necessary code for invalid input
}
else{
// Save the data and redirect the user using any mean of redirection.
}
Means of redirection
1- using php header function as other answers stated. However, using header function should be used before any output in your file i.e before any echo or print or even any new line or html tags in your script file.
2- using cient-side javascript like the follwoing:
echo "";

3- Using client-side meta tag:
echo '<meta http-equiv="refresh" content="0;URL=http://www.indiana.edu/~account/new-directory" />';


text:
Q: Can't insert values into table I'm trying to insert values from a register form to the database but I keep getting the message 'User Registration Failed', and I don't know why.
<?php
include("home.html");
require('connect.php');
if (isset($_POST['username']) && isset($_POST['password'])){
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];

    $query = "INSERT INTO users (username, password, email) VALUES ('$username', '$password', '$email')";
    $result = mysqli_query($connection, $query);
    if($result)
    {
        $smsg = "User Created Successfully";
    }
    else
    {
        $fmsg ="User Registration Failed";
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to work with different.xsd namespaces that contains the same elements/classes? Im having a little trouble understanding how I should work with xml files, so I hope you guys can guide me in the right dirrection :) Hopefully I can explain my problem clear enough :)
I have a lot of .xsd files which are all connected from top to bottom. So I have 10 .xsd with namespace A and 10 .xsd with namespace B. Lets say that the two namespaces represents each own car. That means they both share a lot of the same elements, like  engine, wheel ect..
I tought that I could make use of xsd.exe and then just serialize the xml files them in my C# code. But when I have converted the .xsd files into two .cs files (one for each namespace/car), they share a lot of the same classes. That makes a problem when I want to add the two .cs files to my project. Cant have two classes with the same name...
How do I solve this? Am I using the wrong tools or have I completely misunderstood what I should do? :)
The beginning of the .cs file:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.261
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

//
// This source code was auto-generated by xsd, Version=4.0.30319.1.
//

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]          [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://rep.oio.dk/sundcom.dk/medcom.dk/xml/schemas/2006/07/01/")]
[System.Xml.Serialization.XmlRootAttribute("FixedFont",     Namespace="http://rep.oio.dk/sundcom.dk/medcom.dk/xml/schemas/2006/07/01/", IsNullable=false)]
public partial class SimpleFormattedText {

private object[] itemsField;

private ItemsChoiceType[] itemsElementNameField;

private string[] textField;

/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Bold", typeof(BreakableText))]
[System.Xml.Serialization.XmlElementAttribute("Break", typeof(Break))]
[System.Xml.Serialization.XmlElementAttribute("Center", typeof(BreakableText))]
[System.Xml.Serialization.XmlElementAttribute("Italic", typeof(BreakableText))]
[System.Xml.Serialization.XmlElementAttribute("Right", typeof(BreakableText))]
[System.Xml.Serialization.XmlElementAttribute("Space", typeof(Space))]
[System.Xml.Serialization.XmlElementAttribute("Underline", typeof(BreakableText))]
[System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemsElementName")]
public object[] Items {
    get {
        return this.itemsField;
    }
    set {
        this.itemsField = value;
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("ItemsElementName")]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public ItemsChoiceType[] ItemsElementName {
    get {
        return this.itemsElementNameField;
    }
    set {
        this.itemsElementNameField = value;
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string[] Text {
    get {
        return this.textField;
    }
    set {
        this.textField = value;
    }
}

}

A: The best way might prove to feed all the XSD files to xsd.exe at the same time. Just to illustrate, assuming you have three XSD files, you just call it:
xsd.exe a.xsd b.xsd c.xsd /c

If you need to override the namespace, you just provide an extra parameter to xsd.exe:
/namespace:MyCompany.Xsd.Something

A: One way to do this is to generate the classes in different .Net namespaces.
You will then have two set of classes, but since they are in separate namespaces there won't be a conflict in your code.
EDIT:
To instruct xsd.exe to use your namespace, use the /namespace parameter, like this:
xsd.exe myxsd.xsd /namespace:MyNamespace /classes


text:
Q: Oracle SQL Pipe Delimited File w/One Comma Delimited Column to Split and Load Using SQLLDR Input sample data:
Style|Size|Codes
Modern|9|A224, B153, C166
Retro|8|D532, E533, F122
Vintage|7|G324, H243, I432

Using SQLLDR - need this output:
Style     Size     Code1      Code2      Code3
Modern    9        A224       B153       C166
Retro     8        D532       E533       F122
Vintage   7        G324       H243       I432

A: You could do a transformation on the data on the way in. It is specified in the control file.  See this recent post for an example: SQLLDR CTL: Load date field received in DDMonYYYY to db fields with formats of YYYYMM or MM/DD/YYYY
I would use REGEXP_SUBSTR to extract the various codes from their positions in the comma separated list.  Give it a try and let us know what happens.
Looks like your target table will have a finite amount of code columns.  What if your data has more coeds than the target table has columns?  Consider making codes for an item its own table, lest you violate first normal form (a single value only per column).
If the codes string from the source file is really a description as part of an item, then they should most likely remain together as a code_description column. It depends on how this data is used by your app or report.
All that being said, the trick is to define the codes field as BOUNDFILLER.  This says treat it as a FILLER and not load it, but let it be used as a bind variable in later expressions.  Try this in your control file:
LOAD DATA
INFILE 'data.txt'
APPEND
INTO TABLE X_TEST
FIELDS TERMINATED BY '|'
TRAILING NULLCOLS
(
 STYLE       CHAR
,SIZE        CHAR
,CODESTRING  BOUNDFILLER
,CODE1      "trim(regexp_substr(:CODESTRING, '([^,]*)(,|$)', 1, 1, NULL, 1))"
,CODE2      "trim(regexp_substr(:CODESTRING, '([^,]*)(,|$)', 1, 2, NULL, 1))"
,CODE3      "trim(regexp_substr(:CODESTRING, '([^,]*)(,|$)', 1, 3, NULL, 1))"
)

The regular expression can be read as "Return the nth occurrence of zero or more non-comma characters that are followed by a comma or the end of the line, and return the 1st subgroup (which is the data less the comma or end of the line).  Just wrap it in a call to TRIM() to remove the spaces or wait for one of the REGEXP wizards to give an improved REGEX. If there are only 2 codes, CODE3 will be NULL.


text:
Q: Obtain JSON output from another script I have implemented the following lines in this script.
return ContentService
    .createTextOutput(JSON.stringify(data))
    .setMimeType(ContentService.MimeType.JSON);

They return {"title":"My book","description":"Memories"} and I can see the URL changing.
I have also written a script to obtain this information. It contains the following line:
UrlFetchApp.fetch(wsURL).getContentText();

For some reason, I receive the following HTML:
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta content="width=300, initial-scale=1" name="viewport">
        <meta name="description" content="Google Drive is a free way to keep your files backed up and easy to reach from any phone, tablet, or computer. Start with 15GB of Google storage – free.">
        <meta name="google-site-verification" content="LrdTUW9psUAMbh4Ia074-BPEVmcpBxF6Gwf0MSgQXZs">
        <title>Meet Google Drive – One place for all your files</title>
        <style> @font-face { font-family: 'Open Sans'; font-style: normal; font-weight: 300; src: local('Open Sans Light'), local('OpenSans-Light'), url(//fonts.gstatic.com/s/opensans/v13/DXI1ORHCpsQm3Vp6mXoaTYnF5uFdDttMLvmWuJdhhgs.ttf) format('truetype');

            .........................

            }); })();
        </script>
    </body>
</html>

I am not sure why it is returning this HTML. How can I get my Google script to receive the external script's outputted JSON?

A: you are reaching a login page because of incorrect publishing. publish to run as "me", everyone even anonymous. make sure to use versioning. see the official docs about publishing a script for more info.


text:
Q: Simple dropdown menu with CSS in a navba I'm trying to create a simple dropdown menu (with only CSS) in a navbar with multiple links, the problem is that the dropdown menu will show with every link and not only with the desired one. Here is the code:
HTML & CSS

ul {
  list-style: none;
}

.topNav {
  background-color: #ff66b3;
  overflow: hidden;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
  position: relative;
}

.topNav a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 8px;
  text-decoration: none;
  font-size: 14px;
}

.topNav a:hover {
  background-color: #ffb3d9;
  color: black;
}

.dropDown {
  display: none;
  position: absolute;
  z-index: 1;
  min-width: 160px;
}

.dropDown a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.topNav .mainLink:hover .dropDown {
  display: block;
}

  &#9776
  NerdBook

    News
    Contact
    About

The dropdown will have to show only on the "menuIcon" link.

A: You already have an ID on the  tag you want to trigger the :hover so use that as reference selector. Also your code doesn't work because .dropDown ins't a child of your link change it to match as sibling:

#menuIcon:hover ~ .dropDown

ul {
  list-style: none;
}
.topNav {
  background-color: #ff66b3;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
  position: relative;
}
.topNav:after {
  content:"";
  display:table;
  clear:both;
}
.topNav a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 8px;
  text-decoration: none;
  font-size: 14px;
}
.topNav a:hover {
  background-color: #ffb3d9;
  color: black;
}
.dropDown {
  background:#e1e1e1;
  display: none;
  position: absolute;
  top:100%;
  z-index: 1;
  min-width: 160px;
}

.dropDown a {
  float:none;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

#menuIcon:hover ~ .dropDown, .dropDown:hover {
  display: block;
}

  &#9776
  NerdBook

    News
    Contact
    About


text:
Q: Add Compodoc documentation in Project Routing I have an Angular project running on gitlab, I have created documentation with compodoc, and it runs on its own 8080 port.
I would like to include it in my project routing such as "localhost:4200/docs" or something similar.
Does anybody have the same experience?

A: You need to configure your Angular project to serve the generated documentation. To do this, you can modify the angular.json file as follows:
"architect": {
    "serve": {
        "options": {
            "browserTarget": "<your-project-name>:build",
            "port": 4200,
            "open": true,
            "servePath": "/docs/",
            "assets": [
                "src/assets",
                "src/favicon.ico",
                "documentation"
            ]
        }
    }
}

Here, we have added "servePath": "/docs/" to serve the documentation on the /docs path.
Next, create a documentation.module.ts file in your project and add the following code:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
    {
        path: '',
        loadChildren: () => import('@compodoc/compodoc-ui').then(m => m.CompodocUiModule)
    }
];

@NgModule({
    declarations: [],
    imports: [
        CommonModule,
        RouterModule.forChild(routes)
    ]
})
export class DocumentationModule { }

Here, we have added a route for the /docs path that loads the CompodocUiModule.
Finally, you can add a route to your Angular project routing to serve the documentation. In your app-routing.module.ts file, add the following code:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'docs', loadChildren: () => import('./documentation/documentation.module').then(m => m.DocumentationModule) },
    { path: '**', component: AppComponent }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }

Here, we have added a route for the /docs path that loads the DocumentationModule.
Now, you can run your Angular project and navigate to http://localhost:4200/docs to see the generated documentation.


text:
Q: No Data holes with Mapfile / Python I am working with Python with GDAL and Mapfile and I used the following cmd line in order to remove NoData:
cmd = ["gdal_edit.py", src_img , "-unsetnodata"]

And then in my application with my mapfile I defined into my layer:
OFFSITE 0 0 0

In my app, I can see that the NoData is transparent, however I also have "no data holes" into my image.

With Gdalinfo, I have the 4 corners of my image, I need to differentiate the image and the NoData but I don't really know how to that. I thought to add a TIFF behind the image in order to cover the "no data holes" but do you have any better idea?


text:
Q: Proxy and map for a graph database I want to store a huge graph on several nodes. That is why I need a Map server which will know where each vertex is stored. It can be any database (Relational or NoSQL, doesn't matter) stores only one table with two columns like these:
vertex id | server_id
I don't want to use consistent hashing or something similar to store vertex because of traversal problems.
Also I need some proxy which will work with Map server and with graph databases (partitions).This proxy must accept requests from application (like "get Vertex by Id"), asks the Map server "where that vertex is stored" and then redirect request to correct node.
Here is example of architecture:

Is there a proxy like this? Or maybe some solution or something else? Any graph database any proxy for that graph any ideas will be pleasurable.


text:
Q: How can I flash with User-debug builds to Pixel device? Can anyone help me to say how can I flash my Pixel 2 XL device with User-debug build for Android Q version?
Any information with step by step procedure or any documented information or video links ?
I tried to googling and couldnt get to it. Since I am new to this topic I don't know how to start.
Checked this link but dont know how to proceed on the information given.
Thank you in advance!


text:
Q: Zinnia does not run after installation I'm newer for Django, just finish the Django tutorial last week. I install zinnia today in my virtualenv, and I'm sure that I have installed all the dependencies such as PIL, tag, mptt etc.
    pip install django ( version is 1.4.2)
    pip install zinnia
Then, here are the details of my steps:

*

*django-admin.py startproject yuetu

*Modify the setting.py in yuetu/yuetu directory like:

      TEMPLATE_CONTEXT_PROCESSORS = (
  'django.contrib.auth.context_processors.auth',
  'django.core.context_processors.i18n',
  'django.core.context_processors.request',
  'django.core.context_processors.media',
  'django.core.context_processors.static',
  'zinnia.context_processors.version',
) # Optional

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    #'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'django.contrib.comments',
    'tagging',
    'mptt',
    'zinnia',
)

3.Modify the urls.py like:
   url(r'^weblog/', include('zinnia.urls')), url(r'^comments/',
  include('django.contrib.comments.urls')),
4.run python manage.py validate   No errors.
  5.run python manage.py syncdb   No errors. All the tables are in my Mysql database;
  6.run python manage.py runserver No errors

but When I browse the page with 127.0.0.1:8000/weblog I got a exception like:
NoReverseMatch at /weblog/

u'admin' is not a registered namespace

Request Method:     GET
Request URL:    http://127.0.0.1:8000/weblog/
Django Version:     1.4.2
Exception Type:     NoReverseMatch
Exception Value:

u'admin' is not a registered namespace

Exception Location:     /root/Envs/yuetu_zinnia/lib/python2.7/site-packages/django/template/defaulttags.py in render, line 424
Python Executable:  /root/Envs/yuetu_zinnia/bin/python
Python Version:     2.7.3
Python Path:

['/root/Envs/yuetu_zinnia/yuetu',
 '/root/Envs/yuetu_zinnia/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg',
 '/root/Envs/yuetu_zinnia/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg',
 '/root/Envs/yuetu_zinnia/lib/python2.7/site-packages/distribute-0.6.28-py2.7.egg',
 '/root/Envs/yuetu_zinnia/lib/python2.7/site-packages/MySQL_python-1.2.4c1-py2.7-linux-x86_64.egg',
 '/usr/local/pythonbrew/lib',
 '/root/Envs/yuetu_zinnia/lib/python27.zip',
 '/root/Envs/yuetu_zinnia/lib/python2.7',
 '/root/Envs/yuetu_zinnia/lib/python2.7/plat-linux2',
 '/root/Envs/yuetu_zinnia/lib/python2.7/lib-tk',
 '/root/Envs/yuetu_zinnia/lib/python2.7/lib-old',
 '/root/Envs/yuetu_zinnia/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7',
 '/usr/local/lib/python2.7/plat-linux2',
 '/usr/local/lib/python2.7/lib-tk',
 '/root/Envs/yuetu_zinnia/lib/python2.7/site-packages',
 '/root/Envs/yuetu_zinnia/lib/python2.7/site-packages/PIL']

Error during template rendering

In template /root/Envs/yuetu_zinnia/lib/python2.7/site-packages/zinnia/templates/zinnia/entry_list.html, error at line 50
u'admin' is not a registered namespace
40  {% endif %}
41  {% endblock %}
42
43  {% block content-loop %}
44  {% for object in object_list %}
45  {% with object_content=object.html_content|truncatewords_html:100|safe continue_reading=1 %}
46  {% include "zinnia/_entry_detail.html" %}
47  {% endwith %}
48  {% empty %}
49

50  {% trans "No entries yet." %}
51

52  {% endfor %}
53  {% endblock %}
54
55  {% block content-pagination %}
56  {% if is_paginated %}
57  {% zinnia_pagination page_obj %}
58  {% endif %}
59  {% endblock %}
60

Anyone tell me what's my wrong?

A: Make sure that your project urls.py has the admin system enabled:
# urls.py
from django.conf.urls import patterns, include, url

# MAKE SURE THESE TWO LINES ARE UNCOMMENTED!
from django.contrib import admin
admin.autodiscover()

urlpatters = patterns('',
    # MAKE SURE THIS NEXT LINE IS UNCOMMENTED!
    url(r'^admin/', include(admin.site.urls)),
    url(r'^weblog/', include('zinnia.urls')),
    url(r'^comments/', include('django.contrib.comments.urls')),
)


text:
Q: Spontaneous emission, Rabi, Jaynes Cummings, damped Jaynes Cummings, spectral densities I am currently slightly confused on the different models that exists to treat the interaction of a two-level system with a radiation field.
Currently, I understood that there are several models.

*

*Rabi Model
The interaction of a two-level system (quantum mechanical treated) with one mode only of a light field (classically treated in the dipole-approximation)

*Jaynes-Cummings model
The interaction of a two-level system (quantum mechanical treated) with one mode only of a light field (quantum mechanically treated in the dipole-approximation)

*Wigner-Weisskopf model
The interaction of a two-level system (quantum mechanical treated) with all modes of a radiationfield (free field) (quantum mechanically treated in the dipole-approximation)

*Damped Jaynes-Cummings model
Here, the two level system interacts with a light mode, that is coupled to a reservoir.
I am confused.
In all models (except for the Rabi-model) I apply the dipole-approximation. Fair enough.
And all of them can be described with the total Hamiltonian
$H=H_A+H_F+H_I$, whereas $H_A=\omega_0\sigma_+\sigma_-$ ,  $ H_F=\sum_k\omega_kb_k^\dagger b_k$ and
$H_I=\sigma_+\otimes B+\sigma_-\otimes B^\dagger$ and $B=\sum_kg_kb_k$.
Here, $\omega_0$ describes the transition energy between the two levels and $\omega_k$ the field-mode frequency, $g_k$ the coupling constants.
My question now is:
This interaction hamiltonian implies interaction with all modes,
so for the JCM I need to set all but one coupling strengths to zero.
For the damped Jaynes-Cummings model, I set a Lorentz spectral density to model the reservoir-interaction the light mode interacts with. But why?
This would imply my two-level system interacts with all modes, just not equally coupled.
Also: How does the spectral density of a free field look like?
Another question:
What is meant with "correlation time of the bath" or "typical time scales", when they talk about if and how a dynamics can be Markovian or not.


text:
Q: Tomcat 7 CPU usage on Ubuntu 14.04 I deployed Java web application on Tomcat with Mongodb in Ubuntu 14.04. But Tomcat CPU usage increases suddenly to %100 after 5-6 hours. I couldn't find why. My htop logs like below.

Digital Ocean Graphs

A: I had the same problem with Tomcat 7 on Ubuntu 14.04. I believe this happens since the last Tomcat update USN-3177-2.
Someone had a similar issue with Debian 8: https://serverfault.com/q/827359
I solved this problem by disabling Port 8080 in server.xml.
Edit: The high CPU usage seems to start when someone accesses http://domain.com:8080. This also causes an error message in catalina.out:
org.apache.coyote.http11.AbstractHttp11Processor process
INFO: Error parsing HTTP request header

Commenting out the connector with port 8080 in server.xml solved the problem for me.

A: I had this exact same problem. Here's a tweet I sent to @TheApacheTomcat asking if this was an known issue. https://twitter.com/jeromeleoterry/status/831865811962908672
They responded with a link to Bug 60578 https://bz.apache.org/bugzilla/show_bug.cgi?id=60578
I was seeing the CPU spike when Nessus was scanning Tomcat servers on ports 8080 and 8009. I did a test in a QA environment with those connectors disabled, and the CPU load went up for a few seconds, then came back down.
i'm using Ubuntu 14.04 in EC2 using Tomcat 7.0.52.
Edit:
Looks like this is a known issue, and is resolved in newer versions of Tomcat.
https://bz.apache.org/bugzilla/show_bug.cgi?id=57544
Solution is to upgrade to Tomcat 7.0.60 or higher. Ubuntu 16.04 ships with Tomcat 7.0.68, so I'd recommend upgrading the OS if possible.


text:
Q: How to store cookie variables in Safari and Edge? JavaScript used to store cookies:
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=<?= site_url() ?>Portal/";
    //Cookies.set(cname, cvalue, { expires: expires });
}

PHP:
if(!isset($_COOKIE["apikey"]))
{
    redirect('/Login', 'refresh');
}

The above code is working in all browsers, except Edge and Safari.


text:
Q: Wine: Install Windows Program for Multiple Users I'm trying to install programs through wine so that it's available to all users.  Reasons are obvious: save space and I don't like the idea of doing separate multiple installations of a program for multiple users.  One installation per machine should be sufficient.
Here's what I've done:
(1)  Installing a program to my user account drops the program in [/home/me/.wine/].  I made that program read/write/execute to all users.  Programs seem to work from another user account if he/she browses to my home folder, into ~/.wine/drive_c/Program Files (x86)/the-program/program-executable.exe
Not ideal but workable.
(2) I then moved my ~/.wine folder out of my home directory onto a shared partition and  created a sym-link to it in my home folder and called it ".wine".  I've effectively replaced my .wine folder with a link to a .wine folder on a shared folder.
It seems to work alright.
My question: Does anyone know a better way to do this?  My solution seems a bit crazy and a bit hacky.  Any smart people out there think this is a bad idea?

A: I would do it the same way you did it... put the binaries in a public location and link to the home dirs for who needs access.
I do have my questions however with opening the same Windows program by multiple users at the same time. Not sure how they react to it. Most are not created for multi-user environments. Even though they operate in Linux, I think it could create unwanted behaviour...


text:
Q: elliptic pde with supercritical advection term Let $B$ denote the unit ball in $ R^N$ centered at the origin and consider
$$ -\Delta u(x) + \frac{ x \cdot \nabla u(x)}{|x|^\alpha} = f(x) \quad \mbox{ in } B$$ with $u=0$ on $ \partial B$.    (or instead work on an annulus $ \Omega_\epsilon:=\{x \in B:  |x|>\epsilon\})$.   Here $ \alpha>2$.  Here $ f$ is bounded.  I seem to be able to get estimates like $ |u(x)| \le C |x|^\alpha$.
QUESTION.  Can one expect to get the natural gradient estimate $ | \nabla u(x)| \le C |x|^{\alpha-1}$.


text:
Q: How to install only file based on condition (external configuration file) in Inno Setup I have an XML file with some tags like names of DLL files.
I want a Inno Setup script code to install only files stated in the XML file (I can read from XML file).
My question is: How can I embed all DLL files and according to the XML file, I only install only the required files.
The idea I just need one XML for each release, and I never change the DLL files.

A: Use the Check parameter to programmatically decide if a certain file should be installed:
[Files]
Source: "Dll1.dll"; DestDir: "{app}"; Check: ShouldInstallDll1
Source: "Dll2.dll"; DestDir: "{app}"; Check: ShouldInstallDll2

[Code]

function ShouldInstallDll1: Boolean;
begin
  Result := ???;
end;

function ShouldInstallDll2: Boolean;
begin
  Result := ???;
end;

If it better suits your logic, you can also use a single "check" function and use the CurrentFileName magic variable, to test, if the file being installed, is the one you want to really install:
[Files]
Source: "Dll1.dll"; DestDir: "{app}"; Check: ShouldInstallDll
Source: "Dll2.dll"; DestDir: "{app}"; Check: ShouldInstallDll

[Code]

var
  FileToInstall: string;

function InitializeSetup(): Boolean;
begin
  FileToInstall := ??? { 'Dll1.dll' or 'Dll2.dll' based on the XML file }
  Result := True;
end;

function ShouldInstallDll: Boolean;
var
  Name: string;
begin
  Name := ExtractFileName(CurrentFileName);
  Result := (CompareText(Name, FileToInstall) = 0);
end;

The latter approach can be used, even if you pack files using a wildcard:
[Files]
Source: "*.dll"; DestDir: "{app}"; Check: ShouldInstallDll


text:
Q: Service not running in background after swiping out application I am using service for sending current location of device to server continuously in background, but service is also getting killed when I swipe out the application on some phones. It's working if I remove restriction of running background services from Phone settings to the app. I will be thankful, If someone provide solution of removing this restriction  programatically.

A: Every Phone manufacturer has it's own settings for background processing apps. As there are many android device manufacturers it will be difficult to check for every device group. I'm facing the same issue for my app. It will be better if you ask to check is there any setting regarding background services in their device.


text:
Q: Inflate Multiple Layouts at Once in ListView I want a divider in my ListView when the days are different, so I'm using the code below to attempt to do that.
The problem with this is, in the getView() for the case of TYPE_SEPARATOR, I cannot inflate both the chatheader and list_right_chat or list_left_chat layout because it only returns the last view. How can I add both the divider (header) and the normal layout without directly adding the header into the List that is passed to the ListView?
Code:
public class ChatListAdapter extends ArrayAdapter<Message> {
private LayoutInflater mInflater;

public ChatListAdapter(Context context, List<Message> items) {
    super(context, 0, items);
    mInflater = LayoutInflater.from(context);
}

@Override
public int getViewTypeCount() {
    return RowType.values().length;
}

@Override
public int getItemViewType(int position) {
    //Check Dates
    DateTimeZone timeZone = DateTimeZone.getDefault();
    DateTime now = new DateTime( timeZone );
    Interval today = new Interval( now.withTimeAtStartOfDay(), now.plusDays(1).withTimeAtStartOfDay() );
    MutableDateTime epoch = new MutableDateTime();
    epoch.setDate(getItem(position).getEpochTime()); //Set to Epoch time
    DateTime dateTime = new DateTime( epoch );
    boolean messageHappenedToday = today.contains( dateTime );

    if(position == 0)
    {
        if(messageHappenedToday)
            return TYPE_MESSAGE_ITEM;

        return TYPE_SEPARATOR;
    }
    else
    {
        //Check if current message is the same date as the last message.
        //Last message
        epoch.setDate(getItem(position - 1).getEpochTime()); //Set to Epoch time
        DateTime dateTimeLastMessage = new DateTime( epoch );
        Interval oneDayLastMessage = new Interval( dateTimeLastMessage.withTimeAtStartOfDay(), dateTimeLastMessage.plusDays(1).withTimeAtStartOfDay() );

        //Current message
        MutableDateTime epochCurrentMessage = new MutableDateTime();
        epochCurrentMessage.setDate(getItem(position).getEpochTime());
        DateTime dateTimeCurrentMessage = new DateTime(epochCurrentMessage);
        boolean lastMessageHappenedToday = oneDayLastMessage.contains( dateTimeCurrentMessage );

        if(lastMessageHappenedToday)
            return TYPE_MESSAGE_ITEM;
    }
    return TYPE_SEPARATOR;
}

private static final int TYPE_MESSAGE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;

public View getView(int position, View convertView, ViewGroup parent)  {
    ViewHolder holder = null;
    int rowType = getItemViewType(position);
    View View;
    if (convertView == null) {
        Log.i("Cascade", "4: " + getItem(position).getFromName());

        holder = new ViewHolder();
        switch (rowType) {
            case TYPE_MESSAGE_ITEM:
                if(getItem(position).getSelf())
                    convertView = mInflater.inflate(R.layout.list_right_chat, null);
                else
                    convertView = mInflater.inflate(R.layout.list_left_chat, null);
                holder.View = getItem(position).getView(TYPE_MESSAGE_ITEM, mInflater, convertView);
                break;
            case TYPE_SEPARATOR:
                convertView = mInflater.inflate(R.layout.chatheader, null);
                holder.View = getItem(position).getView(TYPE_SEPARATOR, mInflater, convertView);

                if(getItem(position).getSelf())
                    convertView = mInflater.inflate(R.layout.list_right_chat, null);
                else
                    convertView = mInflater.inflate(R.layout.list_left_chat, null);
                holder.View = getItem(position).getView(TYPE_MESSAGE_ITEM, mInflater, convertView);
                break;
        }
        convertView.setTag(holder);
    }
    else
    {
        holder = (ViewHolder) convertView.getTag();
    }
    return convertView;
}

public static class ViewHolder {
    public  View View; }
}

I could always add the header to both of my layouts with View.GONE and make it visible when needed, but that seems kind of 'hacky'...

A: I don't see anything bad in including the header in both of your layouts.
Expecially, if it's possible in your case, I'd use a RecyclerView together with Data Binding for displaying the data, and just few lines of code to decide whether display the header or not.

A: You are adding Table Row into table so use TableLayout.LayoutParams instead of LinearLayout.LayoutParams.As we use LayoutParam according to parent in which we are going to add
            TableLayout table = (TableLayout) findViewById(R.id.TableLayout1);

        TableRow tr = new TableRow(this);
        LinearLayout.LayoutParams trparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        tr.setLayoutParams(trparams);

        cg[i] = new EditText(this);
        weight[i] = new EditText(this);
        cg[i].setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        weight[i].setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);

        //Here's where it goes wrong. By adding fieldparams, the text field doesn't even get generated.
        LinearLayout.LayoutParams fieldparams = new LinearLayout.LayoutParams(10, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
        tr.addView(cg[i], fieldparams);
        tr.addView(weight[i], fieldparams);

        table.addView(tr);


text:
Q: Proving That A Function is $\mu$-almost uniformly bounded Given a function $f: \Omega \to \mathbb{R}$, let $\mathcal{A}$ be a $\sigma$-algebra on $\Omega$ and $\mathcal{B}$ be the Borel $\sigma$-algebra. Assume that $f$ is $\mathcal{A}-\mathcal{B}$ measurable, $\mu$ is a measure on $\mathcal{A}$, and $\mu (\Omega) < \infty$.
Given that $$\mu( \{ \omega: f(\omega) = \pm \infty \}) = 0,$$ which basically means $f$ is finite $\mu$-almost everywhere, I have to prove that $f$ is $\mu$-almost uniformly bounded: $$\forall \epsilon > 0, \exists E_{\epsilon} \in \mathcal{A} : \mu (E_{\epsilon} ^ c) < \epsilon$$ and $f$ is bounded on $E_{\epsilon}.$
My idea was that since the set of $\omega$ such that $f(\omega)$ is infinite has zero measure, then $\forall A \in \mathcal{A}$, if we let $A' = A \cap \{ \omega: f(\omega) = \pm \infty \}$, then $$\mu(A) = \mu (A').$$
Basically, if we remove the infinite elements, the measure remains the same, which means the measure of the complement also stays the same. If I could show that doing this process makes $f$ bounded on $A'$, then I could probably formulate a proof, but I don't think this notion is correct. $A'$ could still be an uncountable set, so I don't know how to show that $f$ would be bounded.
Is this approach correct? How should I do the proof?


text: Q: Google Maps Api v2 не отображается на телефоне Пишу приложение в Android studio. Карты отображаются и работают на виртуалке а когда создаю релизовый apk и устонавливаю на телефон то карты не отображаются только бежевого цвета прямоугольник. Помогите пожалуйста разобратся, проблема в Google Api key? я вроде сделал все как подсказывала Android studio при создании Google maps Activity.


text:
Q: ASP.net core Odata Remove "@odata.context" and "value" from response Is there any way to remove the odata context and value from the Response
so its just my object as a response?
"@odata.context": "https://localhost/api/$metadata#ComplexObject",
    "value": [
       {
          "name": "SomeName"
       }

so the return object is like this:
{
   "name": "SomeName"
}

A: maybe you could write a custom middleware as described in the docs?
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-5.0
I don't know at which position you must inject the new middleware but you can inject it anywhere in the request pipeline


text:
Q: Firefox invalidate dns cache I was too quick about visiting a site I set up on a customer server, and Firefox now remembers, that the default site for (example)
testsite.mycompanyname.com (non existing subdomain, same as *.mycompanyname.com)

is
www.mycompanyname.dk - or rather the IP of the default server

I have then later set up the public DNS (a-record) to redirect to another server, but Firefox remembers the default IP adress.
Chrome/IE/Safari - no problem, as they have not visited that site before DNS kicked in...
I have set these in about:config:
network.dns.disablePrefetch = true
network.dnsCacheExpiration = 0

Anything else?
I really need firebug to debug the frontend on that site....
Cheers

A: DNS caching occurs at multiple levels:
Application asks local system,
  which asks locally configured resolving DNS server,
    which asks authoritative DNS servers.
Caching by Application varies.

*

*I've found for Firefox that quitting and restarting works. The relevant settings in about:config are network.dnsCacheEntries and network.dnsCacheExpiration, which can be set to 0 in order to disable caching.

Caching by local system is typically 1 hour.

*

*Diagnostic: ping, like other applications, uses local system DNS cache

*Flush MacOsX 10.8: sudo killall -HUP mDNSResponder (reference)
(May vary for other versions)

*Flush Windows: ipconfig /flushdns (only if the DNS caching service, HKLM\SYSTEM\CurrentControlSet\Services\Dnscache, is enabled; check with net start|findstr /i dns or compmgmt.msc)

*Linux/Unix may use nscd (name services caching daemon), or dnsmasq, or both ...

Caching by local resolving DNS server may run to several days, depending on TTL associated with DNS record.

*

*Diagnostic: nslookup first reports address of resolving server, then address requested.

*Flush BIND: rndc flush or rndc flushname DOMAIN.NAME
TTL stands for "time to live" a term used to describe how long a DNS record is to be deemed valid by the requesting client or server. A short TTL means that the requester is told not to cache a DNS lookup for too long. The TTL can range from mere seconds (e.g. for DynDNS and similar) to days or weeks.

A: Install the addon DNS Flusher, which works for me.

A: I found that network.dnsCacheExpiration = 0 alone did not quite do the trick, but if you also set network.dnsCacheEntries = 0 then the DNS cache gets disabled for good. So:
network.dnsCacheEntries = 0
network.dnsCacheExpiration = 0

A: The following methods, which worked at some point, do not work presently (doing all of them doesn't work):

*

*Restarting the browser

*Clearing the browser cache

*Setting network.dnsCacheExpiration=0

*ipconfig /flushdns
However, you can open a new private window, private windows evidently don't use the same DNS cache as the regular windows (which is comforting).

A: I've been using the "Clear Recent History\cache" solution for a while now, but I've noticed that it stopped working after one of firefox updates (probably 20.0.1). Because of that I've switched to https://addons.mozilla.org/en-US/firefox/addon/dns-cache/ add-on to do the DNS clearing. I hope this will help someone with the same problem.
Edit: Changed the url as suggested by Haozhun.
Edit2: Unfortunately as of FireFox 32, this plugin is no longer compatible and cannot be used. Possibly https://addons.mozilla.org/en-US/firefox/addon/dns-flusher/ might be able to replace it.


text:
Q: TomEE custom property provider I am running my application in TomEE 8. I want to read some property from my DB and pass it to application.
I saw one example from https://rmannibucau.wordpress.com/2014/08/06/tomee-and-more-advanced-resource-configuration/ . may be it is old. it is not working . while deploying application it expect the Resource Type. But example doesn't have Type in resource tag.
<Resource id="..." properties-provider="com.foo.MyPropertiesReader" />

What is the latest/correct way to load my custom properties to my application from my DB ?

A: I believe that Romain was trying to be concise in his examples. In his examples, it can be surmised that he was using javax.sql.DataSource or DataSource. Despite that, though, this will work for any type of resource, even custom resources. There are also already implementations that you can check out:

*

*HerokuDatabasePropertiesProvider.java

*OpenshiftMySQLPropertiesProvider.java

*OpenshiftPostgreSQLPropertiesProvider.java
In the page you mentioned, Romain also notes that your class can either implement org.apache.openejb.api.resource.PropertiesResourceProvider, or supply a Properties provides(); method.
Here is a small example:
org.superbiz.provider.MyPropertiesReader.java
package org.superbiz.provider;

import org.apache.openejb.api.resource.PropertiesResourceProvider;
import org.apache.openejb.testng.PropertiesBuilder;

import java.util.Properties;

public class MyPropertiesReader implements PropertiesResourceProvider {
    public Properties provides() {
        return new PropertiesBuilder()
                .p("JdbcDriver", "org.hsqldb.jdbcDriver")
                .p("JdbcUrl", "jdbc:hsqldb:mem:moviedb")
                .build();
    }
}

src/main/webapp/WEB-INF/resources.xml
<resources>
    <Resource id="movieDatabase"
              type="DataSource"
              properties-provider="org.superbiz.provider.MyPropertiesReader"/>
</resources>

These are the key snippets that I hope will help clear your doubts. Implementation of the datasource is left for you to code. :)


text:
Q: How to set up and build previous image working in GCP I'm new to google cloud.
Our project has been deployed on google Cloud. We are using gcloud deploy commands to deploy any build and we are good with it.
My question is: what if my current build fails during production deployment and there's lots of users using the application.
So, how can I update the previous image/build immediately in GCP? I have tried it with pull docker and push it then submitting via "gcloud build submit" command... but it's not deploying actual specified docker image, it's deploying that folder where I'm running commands of "gcloud build submit"..
Please share your suggestions..

A: Your concern to not break all the users when you are deploying a broken version is legit, and you aren't alone!!
That's why a cool feature exist on App Engine (and also on Cloud Run): Traffic splitting.
To use it efficiently, you can deploy your new version in production like this:
gcloud app deploy --no-promote

Here the new version is deployed but 0% of the traffic is routed to it. Now use this command to increase the traffic, let say 1%
gcloud app services set-traffic <YOUR_SERVICE> --splits <OldVersionName>=99,<NewVersionName>=1

Monitor your application for a while, and, if there isn't error, continue to increase gradually the traffic, up to be confident and routed 100%
In case of bad version, set the traffic to 0% to the new version and now/or low impact to your users.


text:
Q: Unetbootin USB persistence for Ubuntu 12.10 doesn't work I created a bootable USB stick for Ubuntu 12.10 using Unetbootin and set the persistent file size to 3072mb. I am able to boot into Ubuntu 12.10 just fine. However, any changes I make are lost on reboot.

A: Follow the tutorial HERE if you were successful building and booting the thumbdrive then I would check as to what format you used.
For a persistence to exist the thumbdrive needs to be formatted in FAT32. They other thing is I have never set the persistence to more than 1/3rd of the total capacity of the drive. This has been the rule-of-thumb or (thumbdrive) for me.


text:
Q: python pandas remove character I am working on a project, and I need to remove the left and right most character of a data result.  The data forms a scrape of craigslist, and the neighborhood results return as '(####)', but what I need it to be is ####.  I am using pandas, and trying to use lstrip & rstrip.  When I attempt it inside the python shell, it works, but when I use it on my data it does not work.
post_results['neighborhood'] = post_results['neighborhood'].str.lstrip('(')
post_results['neighborhood'] = post_results['neighborhood'].str.rstrip(')')

For some reason, the rstrip, does work and removes the ')' but the lstrip does not.
The full code is:
from bs4 import BeautifulSoup
import json
from requests import get
import numpy as np
import pandas as pd
import csv

print('hello world')
#get the initial page for the listings, to get the total count
response = get('https://washingtondc.craigslist.org/search/hhh?query=rent&availabilityMode=0&sale_date=all+dates')
html_result = BeautifulSoup(response.text, 'html.parser')
results = html_result.find('div', class_='search-legend')
total = int(results.find('span',class_='totalcount').text)
pages = np.arange(0,total+1,120)

neighborhood = []
bedroom_count =[]
sqft = []
price = []
link = []

for page in pages:
    #print(page)

    response = get('https://washingtondc.craigslist.org/search/hhh?s='+str(page)+'query=rent&availabilityMode=0&sale_date=all+dates')
    html_result = BeautifulSoup(response.text, 'html.parser')

    posts = html_result.find_all('li', class_='result-row')
    for post in posts:
        if post.find('span',class_='result-hood') is not None:
            post_url = post.find('a',class_='result-title hdrlnk')
            post_link = post_url['href']
            link.append(post_link)
            post_neighborhood = post.find('span',class_='result-hood').text
            post_price = int(post.find('span',class_='result-price').text.strip().replace('$',''))
            neighborhood.append(post_neighborhood)
            price.append(post_price)
            if post.find('span',class_='housing') is not None:
                if 'ft2' in post.find('span',class_='housing').text.split()[0]:
                    post_bedroom = np.nan
                    post_footage = post.find('span',class_='housing').text.split()[0][:-3]
                    bedroom_count.append(post_bedroom)
                    sqft.append(post_footage)
                elif len(post.find('span',class_='housing').text.split())>2:
                    post_bedroom = post.find('span',class_='housing').text.replace("br","").split()[0]
                    post_footage = post.find('span',class_='housing').text.split()[2][:-3]
                    bedroom_count.append(post_bedroom)
                    sqft.append(post_footage)
                elif len(post.find('span',class_='housing').text.split())==2:
                    post_bedroom = post.find('span',class_='housing').text.replace("br","").split()[0]
                    post_footage = np.nan
                    bedroom_count.append(post_bedroom)
                    sqft.append(post_footage)
            else:
                post_bedroom = np.nan
                post_footage = np.nan
                bedroom_count.append(post_bedroom)
                sqft.append(post_footage)

#create results data frame
post_results = pd.DataFrame({'neighborhood':neighborhood,'footage':sqft,'bedroom':bedroom_count,'price':price,'link':link})
#clean up results
post_results.drop_duplicates(subset='link')
post_results['footage'] = post_results['footage'].replace(0,np.nan)
post_results['bedroom'] = post_results['bedroom'].replace(0,np.nan)
post_results['neighborhood'] = post_results['neighborhood'].str.lstrip('(')
post_results['neighborhood'] = post_results['neighborhood'].str.rstrip(')')
post_results = post_results.dropna(subset=['footage','bedroom'],how='all')
post_results.to_csv("rent_clean.csv",index=False)
print(len(post_results.index))

A: This problem will happened when you have whitespace in the front
For example :
s=pd.Series([' (xxxx)','(yyyy) '])
s.str.strip('(|)')
0     (xxxx
1    yyyy)
dtype: object

What we can do is strip twice
s.str.strip().str.strip('(|)')
0    xxxx
1    yyyy
dtype: object

A: From my understanding of your question, you are removing characters from a string. You don't need pandas for this. Strings have a length and you can remove the first and last character like this;
new_word = old_word[1:-1]

This should work for you. Good luck.


text:
Q: Distributed logs in Cassandra I am finding the way to store the application logs in Cassandra.
I have three node setup (Node 1, Node 2 and Node 3) in which my web application runs as cluster in all the three nodes and load balanced so logs will be generated from all nodes.
Cassandra runs in all the three nodes and logs are dumped from all the three web application into Cassandra cluster which is partitioned for every day.
Problem in this approach :
1) I am using my web application to write the data to Cassandra.
2) For every day partition, the amount of data is very high
So Is there a better approach for this?
Is this the good design approach?

A: The choice of storing logs in Cassandra is debatable; as the analysis of that data becomes difficult but doable. ELK (Elastic-Logstash-Kibana) or Splunk are more popular choices for log analysis because of their native "text" search support and dashboards.
Having said that, lets look at the problems in hand

1) I am using my web application to write the data to Cassandra.

The suggestions that come to my mind here are:

*

*Are the writes being done asynchronously? Recommended.

*What is the consistency level used during these writes? Higher the consistency, slower the web-app is going to get as its waiting that much longer on C* (assuming synchronous writes). Remember C* could still have RF = 3, but you could do consistency = 1.

*What happens if C* cluster goes down? Does web-app go down along with it?

2) For every day partition, the amount of data is very high

*

*There are two problems here - Fat partitions and same node being hit for the entire day (resulting in hot spots). The workload isn't being distributed to the entire cluster.

*Partition sizing can be reduced to be hourly instead of entire day. But we just reduced the footprint of one node being hit from a day to an hour. Its still hot spot for the hour.

*You could do "second" level partition, to get an uniform distribution of data across nodes and not cause huge partitions (depends on how chatty the app is). But this is where merits of C* for log monitoring becomes questionable?

*What are all the queries that C* would solve? How would I aggregate the second level data partition and answer various questions arising during typical log analysis?

Revisit the design with what are all the log analysis questions (queries) that this C* DB would have to answer? Answers should line up automagically.


text:
Q: Updating one instance of a class causes another to update I am writing a basic program that simulates shuffling a deck of cards and drawing cards into a hand. After drawing, I give the class variables in the deck array for the card drawn the values of 0 and null, for rank and suit, as a check to see if the card is drawn from the deck. However, when I set the card in the deck array to 0 and null it also sets the card in the hand array to the same. Any suggestions for solutions to the problem are much appreciated. Thanks!
The code for the Draw Card button:
Card drawn = new Card(0, null);
        //
        do
        {
            i++;
            drawn = test.cards[i];
        } while (drawn.rank == 0 || drawn.suit == null);
        //
        output = drawn.rank + " " + drawn.suit;
        lblOutput.Text = output;
        //
        addToHand(drawn);
        if (handCount < 5)
        {
            handCount++;
        }
        test.cards[i].suit = null;
        test.cards[i].rank = 0;
        //
        if (i >= 51)
        {
            MessageBox.Show("You have drawn all the cards.");
            btnDraw.Enabled = false;
            btnShuffle.Enabled = false;
        }

The addToHand function:
private void addToHand(Card drawn)
    {
        if (handCount < 5)
        {
                if (hand[0].suit == null)
                {
                    hand[0] = drawn;
                    button1.Text = hand[0].rank + " " + hand[0].suit;
                    button1.Enabled = true;
                }
                else if (hand[1].suit == null)
                {
                    hand[1] = drawn;
                    button2.Text = hand[1].rank + " " + hand[1].suit;
                    button2.Enabled = true;
                }
                else if (hand[2].suit == null)
                {
                    hand[2] = drawn;
                    button3.Text = hand[2].rank + " " + hand[2].suit;
                    button3.Enabled = true;
                }
                else if (hand[3].suit == null)
                {
                    hand[3] = drawn;
                    button4.Text = hand[3].rank + " " + hand[3].suit;
                    button4.Enabled = true;
                }
                else if (hand[4].suit == null)
                {
                    hand[4] = drawn;
                    button5.Text = hand[4].rank + " " + hand[4].suit;
                    button5.Enabled = true;
                }
        }

And here are the classes for the deck and cards:
public class Deck
{
    public Card[] cards;

    public Deck() //Fills new array with 52 cards
    {
        cards = new Card[52];
        var index = 0;

        foreach (var suit in new[] { "Spades", "Hearts", "Clubs", "Diamonds", })
        {
            for (var rank = 1; rank <= 13; rank++)
            {
                cards[index++] = new Card(rank, suit);
            }
        }
    }
}

public class Card
{
    public int rank { get; set; }
    public string suit { get; set; }

    public Card(int rk, string st)
    {
        rank = rk;
        suit = st;
    }
}

A: C# objects are inherently pass by reference, not pass by value.  So when you do this:
Card card = cards[0];

You're not creating a new card, you're referencing an already created card.  So when you change the value of cards[0], every reference to that value changes.
You'll likely want to "clone" it, or in your case, just copy all the data within the card.
Card card = new Card();
card.suit = cards[0].suit;
card.rank = cards[0].rank;

Anything not a value type you will need to clone in the same manner.

A: When you write hand[0] = drawn; hand[0] and drawn are the same object.
If you want to have the same value but in two distinct object you can either :

*

*Use a copy constructor : new Hand(drawn)

*Use the Clone method of the drawn objet (impement ICloneable).

You could be interrested by the IClonneable interface :
https://msdn.microsoft.com/en-us/library/system.icloneable.clone(v=vs.110).aspx
And also by copy constructor :
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-write-a-copy-constructor


text:
Q: How to invoke script-module cmdlet from a binary cmdlet? I am writing a Powershell cmdlet in C# by inheriting from PSCmdlet. This is part of a powershell module which contains both binary and script components.
I want to be able to invoke a script module cmdlet from within my binary cmdlet.
I've worked out that inheriting from PSCmdlet gives me access to a lot more of Powershell's guts, and I have looked specifically at InvokeCommand.GetCmdlet() and InvokeCommand.GetCommand() but these both seem to return CommandInfo objects which don't appear to have a method to invoke them.
Am I supposed to call InvokeCommand.InvokeScript() to call my cmdlets? If so how/are CommandInfo objects supposed to be used to help?

A: Likely InvokeScript is what you want because you want to execute a script. Now, you likely had issues because you would use it more like
InvokeCommand.InvokeScript("Get-MyCmdlet -ParameterName value");

That being said, the real answer to your question is that you need a PowerShell object that represents the interpreter.
var ps = PowerShell.Create();
ps.AddCommand(InvokeCommand.GetCmdlet("Get-MyCmdlet"));
ps.AddParameter("ParameterName", "value");

var output = ps.Invoke();

The interpreter uses CommandInfo (and AddCommand has an overload with a string that under-the-hood would create one) for its Reflection work to interpret whatever you want.


text:
Q: Java Program Performance (running time & memory consumption) Which tools can I use to know the life-time or run-time of a program(from the beginning until the program ends)? I also want to know how much memory that program consumes from start to end. The program is written in Java and I'm running it on Windows XP.

A: You could use JConsole, here's an article describing it's usage

A: If you were using *nix you could use the 'time' command. For Windows see this other SO thread

A: Have you checked Dynatrace? Commercial one but pretty useful for what you are looking for. Have been using it and found very useful to trace down execution path, time spent on each apis etc.

A: "How much time" a program takes is a tricky question, and the answer varies tremendously depending on the state of OS disk caches, and whether you include the start-up time of the JVM itself, etc.
The other part of your question is much easier to answer: you need a profiler. A profiler will not only tell you gross memory statistics (or gross runtime), but will allow you to pinpoint the trouble spots in your programs, areas that create an inordinate number of objects per unit time, or places that burn a lot of CPU relative to other places in your code.

A: If you're interested in monitoring, you may use jconsole which is part of the JDK. Otherwise, please elaborate on your question.

A: You can try monitoring your application with the jconsole tool that ships with the JDK now.  If that isn't enough, I'd try profiling your application with something like YourKit.  Its a commercial product but extremely useful.
I understand that NetBeans has a profiler built in but I have not used it.  If you're using NetBeans, that might be an option as well.

A: I use VisualVM from Sun, and its very good, with lots of useful features. You can monitor Heap Space usage, Loaded Classes, GC Activity and Live Threads.
You can also do the same for remote Java applications.


text:
Q: What exactly is this jQuery / Regex snippet doing? I'm not very good with RegEx, and am trying to learn. I have inherited a project which contains the following line of code:
function findCourseIdFromForm(where) {
    var matchRegex = /\[course-[0-9]*\]/;
    var replaceRegex = /\[|\]|[a-z]|\-/g;
    return $(".cnumber", where.parent()).attr("name").match( matchRegex )[0].replace( replaceRegex,"" );
}

I'm not entirely sure what this piece of code is trying to do, but I know that it is causing issues on my page. I'm using jQuery validator and this specific component (".cnumber") is causing the validation to fail and I'm not entirely sure why, so some insight into this line is appreciated.
The .cnumber field in the HTML looks like this:
<input type="hidden" name="courses[course-0][cnumber]" class="cnumber" />

A: It strips out [,  ], lowercase letters and - from the name attribute in the tag, presumably to return the course number.

A: It just get the course number. In you example, it return 0

A: This function takes where node, gets its parent, finds .cnumber node within the parent, then takes [course-0] part and finally remove all [, ], -, and lowercase letters.
So the function returns the number that stands after [course- part, or empty string if there is no number


text:
Q: Numerical solution of driven infinite well with Floquet matrix I am trying to understand and replicate figure 3 of this paper.
The idea is that we have our box with a periodic drive
$$H(t) = \frac{p^2}{2m}-F_0x\cos(\omega t)$$
The author states

In order to calculate the truncated time-evolution matrix $U(T, 0)$ one takes each of the unperturbed box eigenstates as initial condition, $ψ_n(x, 0) = ϕ_n(x)$, and computes the states $ψ_n(x, T )$ resulting after one period, collecting these state vectors as columns of the monodromy matrix

I am having difficulty figuring this out.  I know the unperturbed energies and wavefunctions $|\psi(0)\rangle$.  I also know that $|\psi(t)\rangle = U(t,0)|\psi(0)\rangle$
with ($\hbar=1$)
$$U(t,0)=\exp\left[-i\int_0^tH \ dt\right]$$
This is where I am unsure of how to numerically calculate.   Usually, I would do just $\psi(t)=\psi(0)\exp[-iE_n t]$, but because of the periodicity, we actually are able to expand
$$U(t,0)=\sum_n |n\rangle\langle n| \exp[-i\epsilon_n T]$$
In quasi-energies, which I want to solve for, so I am not sure of the time dependance of H to integrate to solve for $|\psi(x,t)\rangle$.  Any suggestions on how to approach this are appreciated.

A: Here there's no fancy math that will save you - you just need to explicitly solve the TDSE numerically for a bunch of different initial conditions.
The algorithm looks more or less like this:

*

*For each $m=1,\ldots,N_\mathrm{max}$:

*

*Formulate the Schrödinger equation for the vector $(\psi_n(t))_{n=1}^{N_\mathrm{max}}$ as a set of coupled ordinary differential equations,
$$i\hbar \partial_t \psi_n(t) = E_n\psi_n(t)+\sum_{k=1}^{N_\mathrm{max}} Fx_{nk}\psi_k(t) \quad\text{under}\quad \psi_n(t) = \delta_{mn}$$

*Solve this set of coupled ODEs numerically up to $T=2\pi/\omega$.

*Store the results at the end of the period as $U_{mn} = \psi_n(T)$. This is known as the monodromy matrix.

*Assemble the results of all the different $m$ into one big matrix $U_{mn}$.

*Diagonalize this matrix. Its eigenvalues are of the form $e^{i \varepsilon_k T/\hbar}$, i.e. the exponentiated quasienergies.

*Repeat for a different coupling.

This is what the authors mean when they say

then [we] have to deal with a system of $n_\mathrm{max}$ complex coupled ordinary differential equations which can be integrated numerically by standard routines.

I gave this a brief run in Mathematica and it's not that hard (though of course this gets harder and harder as $n_\mathrm{max}$ gets bigger). The results look roughly like this:

I haven't checked the constants for normalization or the convergence with respect to $n_\mathrm{max}$, so take that as a rough guide only; the code is at

Import["http://halirutan.github.io/Mathematica-SE-Tools/decode.m"]["http://i.stack.imgur.com/rPjH2.png"]


text:
Q: How to test logic in joined promises/then I am trying to write a test for an action handler on one of my components.  I am stubbing out the save method on one of my models to return a resolved promise using Em.RSVP.Promise.resolve()
in my component, i chain on that promise using then:
return target
    .save()
    .then(function(){
        selected.rollback();
        this.sendAction('quicklinkChanged', target);
    }.bind(this),this.notify_user_of_persistence_error.bind(this, 'Save As'));
this is a pattern that i use a lot server-side where we use when for our promise library.  however, when i do this client-side, i never end up inside the function in the then block so i cannot assert any of the functionality there in my unit tests.
can anyone provide any insight on the best way to do this?

A: We moved our callbacks out of the method so we could call them separately and verify functionality, or replace them and verify they were called.
Controller Example:
App.IndexController = Em.Controller.extend({
  randomProperty: 1,
  async: function(fail){
    return new Em.RSVP.Promise(function(resolve, reject){
      if(fail){
        reject('fdas');
      }else{
        resolve('foo');
      }
    });
  },
  doAsyncThing: function(fail){
    return this.async(fail).then(this.success.bind(this), this.failure.bind(this));
  },
  success: function(){
    this.set('randomProperty', 2);
  },
  failure: function(){
    this.set('randomProperty', -2);
  }
});

Tests
test("async success", function(){
  var ic = App.IndexController.createWithMixins();
  stop();
  ic.doAsyncThing(false).then(function(){
    start();
    equal(ic.get('randomProperty'), 2);
  });

});

test("async fail", function(){
  var ic = App.IndexController.createWithMixins();
  stop();
  ic.doAsyncThing(true).then(function(){
    start();
    equal(ic.get('randomProperty'), -2);
  });

});

test("async success is called", function(){
  expect(1);
  var ic = App.IndexController.createWithMixins();
  ic.success = function(){
    ok(true);
  };
  stop();
  ic.doAsyncThing(false).then(function(){
    start();
  });

});

test("async failure is called", function(){
  expect(1);
  var ic = App.IndexController.createWithMixins();
  ic.failure = function(){
    ok(true);
  };
  stop();
  ic.doAsyncThing(true).then(function(){
    start();
  });

});

test("doAsyncThing returns a promise", function(){
  expect(1);
  var ic = App.IndexController.createWithMixins();
  ok(ic.doAsyncThing(true).then);

});

Example: http://emberjs.jsbin.com/wipo/37/edit


text:
Q: How to compile and use Kotlin code in runtime? I'm trying to create a Kotlin Vert.x language support module and I need a way to compile Kotlin files and load the results with a ClassLoader. I've tried using kotlin-compiler library and found K2JVMCompiler class, but it seems to support only command-line-style arguments with its exec method. Is there a way to compile a Kotlin file in runtime (possibly without having to save and read .class files) and immediately load the generated classes? (Kind of like Groovy does.) If not, do you have any useful compiler arguments suggestions or pretty much any advices?

A: This feels like an XY Problem.  You want to know how to compile Kotlin on the fly so that you can more easily use Vert.x by running from Kotlin source files instead of compiled code.  But really the recommended path for Vert.x usage is to create a simple bit of code that deploys your verticle within compiled code.
In the question, your link for language support says Vert.x 2 in the path "vertx.io/vertx2/language_support.html"; which is different than how it is now done in Vert.x 3. I think you are merging two thoughts into one. First that Vert.x 3 wants you to run Java/Kotlin files from source (it doesn't really; that was a Vert.x 2 thing they moved away from for compiled languages), and second that you need custom language support (you don't).
You should try to use Vert.x 3 by running compiled code.  To do so, build your classes and run your own main() that deploys a verticle programatically. Your code would be simple as:
import io.vertx.core.Vertx

fun main(args: Array<String>) {
    val vertx = Vertx.vertx()
    vertx.deployVerticle(SomeVerticleOfMine())
}

Alternatively, the docs for running and deploying from the command-line say:

Vert.x will compile the Java source file on the fly before running it. This is really useful for quickly prototyping verticles and great for demos. No need to set-up a Maven or Gradle build first to get going!

And really it is indeed just for prototyping and quick testing, and it isn't any faster than letting your IDE do the same and running from the compiled classes.  You also then have debugging features of the IDE which are infinitely valuable.
For a few helper libraries for using Kotlin with Vert.x, view these options:

*

*Vert.x 3 module for Klutter - I am the author, one of my libraries

*Vert.x 3 helpers for Kotlin  - by Cy6erGn0m

*Kovert, a REST framework for Vert.x 3  - I am the author, one of my libraries

*Vert.x nubes - not Kotlin specific, but makes Vert.x-Web friendlier for JVM languages.

There is a full sample project of running Vert.x + Kovert (specifically start with the App class).  You can look at the code of Kovert to do your own similar work of starting and running Vert.x nicely, with Promises or however you wish.  The docs for Kovert have links to code for starting Vertx and also starting a Verticle to use Vert.x-Web, so more sample code you can read.  But it helps to understand Injekt (light-weight dependency registry), Kovenant (promises library), and Klutter configuration injection to understand the complete sample.
Other quick note, Vert.x has codegen support for other languages, but since you can call all of the Java version directly, it does not need to support Kotlin either.

A: Kotlin 1.1 comes with javax.script (JSR-223) support, which means you can use it as scripting engine similarly to JavaScript with Nashorn.


text:
Q: Multimodel database vs multiple individual databases? I am working on application which requires features offered by both graph database(to store raw data) and document database(extracted reports from raw data). I planned to use neo4j and mongodb. I am having second thoughts about and looking at orientDB. is it better to have a single multimodel database than two separate databases? The reason I leaned towards neo4j is its native graph storage which might come in handy for memory locality for large graphs. OrientDB doesn't store graph natively. or does it?

A: OrientDB stores graph natively. Its engine is 100% a Graph Database like Neo4j. Actually OrientDB and Neo4j are the only Graph Databases with index-free adjacency. Some other Graph Database acts as a layer on top of an existent model (RDBMS, Column or Document stores).
So there is nothing you can do with Neo4j that you can't do with OrientDB. But OrientDB allows to model more complex data, like Document DBMS (MongoDB) can do. For example each vertices and edges in OrientDB is a document (json), so you can store in the vertex and edge complex types like embedded properties, list, sets, date, decimal, etc.

A: Don't be dazzled by terminology. "Index-free adjacency" is a term that simply means graph vertices are stored "with" their edges. Each database does this in a slightly different way. Neo4J stores them on disk in a linked list. If you have them in memory, and there's not too many of them, they're fast. If you have to hit them on disk, then you may need an index. Titan stores them as columns in a wide-column database such as Cassandra. If they're in memory, they're fast. If you have to hit them on disk, the underlying database's range queries make them fast to load in bulk, and extra indexing can decrease the cost of searching large edge lists.
This discussion is fairly valuable: How does Titan achieve constant time lookup using HBase / Cassandra?
Whether you're using OrientDB or any other database, your efficiency at graph queries will rely in large part on the indexing you put in place so that you start your graph queries on, and traverse through, a relatively small set of nodes. Be sure to model some of the queries you're doing to make sure that whatever database you choose will support the right indexes, whether they're across the whole graph, or local to each vertex.


text:
Q: How to parse xsd using xsd-parser-rs? Do you know how to parse xsd file into Rust structs using https://github.com/lumeohq/xsd-parser-rs?
I do not know how to run the program and how to put files there.

A: Here's a basic example that parses a file sample.xsd and then prints out the debug representation of the parsed result:
src/main.rs:
use anyhow::{format_err, Result};
use std::fs;
use xsd_parser::parser::parse as xsd_parse;

fn main() -> Result<()> {
    let sample = fs::read_to_string("sample.xsd")?;
    let parsed = xsd_parse(&sample).map_err(|_| format_err!("failed to parse XSD file"))?;
    println!("{:#?}", &parsed);

    Ok(())
}

Cargo.toml:
[package]
name = "xsd-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
anyhow = "1"
xsd-parser = { git = "https://github.com/lumeohq/xsd-parser-rs", rev = "7f3d433e4f033b55f057e97c0a30de221dbe3ae1" }

sample.xsd:
I used the sample XSD file from here.

From the project folder, you can invoke rustdoc like cargo doc -p xsd-parser --no-deps --open to generate and open the API docs for the xsd-parser crate, which is what allowed me to figure out how to use the crate.


text:
Q: A $\sigma$-finite measure on $[0,1]$ Let $f:[0.1] \to \Bbb{R}$ such that $$f(x)=\sum_{n=1}^\infty \frac{1}{n^2}\frac{1}{\sqrt{|x-r_n|}}$$ where $\{r_1,r_2...r_n...\}=\Bbb{Q} \cap [0,1]$
We define the measure $$μ(Ε)=\int_E f^2 dx$$ for every Lebesgue measurable subset $E$ of $[0,1]$
I have to prove that this measure is sigma finite.
I already proved that: $$\mu <<m$$ $$f \in L^1([0,1])$$ $$\forall (a,b) \subseteq [0,1] \Rightarrow \mu((a,b)=+\infty$$
Can someone give me a hint to prove that this measure is sigma finite?
Thank you in advance.

A: $f \in L^{1}([0,1])$ implies that $|f| <\infty$ almost everywhere w.r.t $m$, hence w.r.t. $\mu$. The sets $\{x:|f(x)| \leq n \}$ have finite $\mu$-measure and their union  differs from  $[0,1]$ only by a $\mu$ null set. Hence $\mu$ is sigma finite.


text:
Q: How to create a clipping display window area without using an iframe or a library? I have a project that contains a bordered div where I would like to dynamically display some other div elements that represent visualized data points.  I have no trouble creating the elements and positioning them using javascript, but I'm now trying to keep them confined within the "display div."  I've looked into some clipping and masking ideas out there, but I'm not sure it's applicable (a lot of them deal with actual images - here, I'm not).  Below is a simplified representation of the page I'm building:
CSS:
#info {
    width:100px;
    height:100px;
    float:left;
    display:inline-block;
    border: 2px solid blue;
}

#display {
    width:400px;
    height:300px;
    display:inline-block;
    border: 1px solid black;
}

#data {
    position:absolute;
    width:100px;
    height:100px;
    border-radius:100px;
    background:green;
    left:70px;
    top:30px;
}

HTML:
Div Window Test

Info Sidebar

As you can see, there is a black-bordered display area, and a floating green circular-shaped  element to represent a data point drawn inside the display.  As shown, the data point div is partly outside the display.  There will be many, many data points of varying size AND location - some well inside the display, and some outside (and even some past the browser window).  What I would like to is somehow constrict/mask the data points to only show what's rendered within the display div boundaries.  Is there a simple way to do this using CSS or a mask?

A: Is this what you look for?
In below sample I added position: relative; to have your absolute positioned children relate to the #display element and overflow: hidden; to cut off any overflowed parts.

#info {
  width:100px;
  height:100px;
  float:left;
  display:inline-block;
  border: 2px solid blue;
}

#display {
  width:400px;
  height:300px;
  display:inline-block;
  border: 1px solid black;
  position: relative;              /*  added  */
  overflow: hidden;                /*  added  */
}

#data {
  position:absolute;
  width:100px;
  height:100px;
  border-radius:100px;
  background:green;
  left:70px;
  top:-30px;
}
Div Window Test

Info Sidebar


text:
Q: How to use Oracle ODP.NET? I need to know if i am sayng true:
1.I have installed on client machine oracle 11.xxx client and i can install anyone of odp.net version to connect from .net to oracle database
2 Other way to use odp.net is to put

*

*oci.dll

*ociw32.dll

*Oracle.DataAccess.dll

*orannzsbb11.dll

*oraocci11.dll

*oraociicus11.dll

*OraOps11w.dll
into application directory (which has reference to Oracle.DataAccess.dll). This way i dont have to install odp.net yes?

A: yes, you are right though 2nd option looks better as you may need not to install oracle on PROD machine while deploying you application.


text:
Q: R Waterfall chart x values Im new and self taught to R, so please bear with me.
I am trying to plot waterfall charts with the following data frame [called balancefinal]:
X1  X2  type    end start   id
Actual  1.09112725  Actual  1.09112725  0   1
Actual Est  1.345028317 Estimated   1.345028317 0   2
Factor1 -0.28842558 Change  1.056602737 1.345028317 3
Factor2 -0.091360211    Change  0.965242526 1.056602737 4
Factor3 0.110622374 Change  1.0758649   0.965242526 5
Factor4 0.227710095 Change  1.303574995 1.0758649   6
Factor5 0.27353189  Change  1.577106884 1.303574995 7
Factor6 0.006879353 Change  1.583986238 1.577106884 8
Factor7 0.135077259 Change  1.719063497 1.583986238 9
Factor8 0.00591948  Change  1.724982976 1.719063497 10
Factor9 0.077394066 Change  1.802377042 1.724982976 11
Factor10    0.05212228  Change  1.854499322 1.802377042 12
Factor11    0.062991126 Change  1.917490448 1.854499322 13
Actual Est  1.836828552 Estimated   0   1.917490448 14
ActualB 1.278994    Actual  1.278994    0   15

I have tried the following code (rearranging code from here)
Code for stacking x variable names: strwr <- function(str) gsub(" ", "\n", str)
  ggplot(balancefinal, aes(X1, fill = type)) + geom_rect(aes(x = X1,  xmin = id - 0.45, xmax = id + 0.45, ymin = end, ymax = start), colour = "black") +
    scale_fill_manual (values =c("#90353B", "#1A476F","burlywood1"))  + scale_x_discrete("", breaks = levels(balancefinal$X1), labels = strwr(levels(balancefinal$X1))) +
    theme(legend.position = "bottom", legend.title=element_blank(), axis.text= element_text(size = 8), plot.title = element_text(vjust = 1)) +
    scale_y_continuous("", labels = dollar, breaks = seq(0, max(balancefinal$start) + 0.25, by = 0.25))

Ideally, the order of the variables in the x axis should be Actual, Actual Est, Factor1,...,Factor11, Actual Est, ActualB. This is not the case, it seems that the boxes representing the values of X2 are correct but the order of the labels is not. Do you have any idea why this may be happening? Any help/hint would be hugely appreciated.
PS:Sorry if it is a basic question. If you think it is let me know and I will remove it.

A: Setting up your data:
text <- "X1  X2  type    end start   id
Actual  1.09112725  Actual  1.09112725  0   1
Actual Est  1.345028317 Estimated   1.345028317 0   2
Factor1 -0.28842558 Change  1.056602737 1.345028317 3
Factor2 -0.091360211    Change  0.965242526 1.056602737 4
Factor3 0.110622374 Change  1.0758649   0.965242526 5
Factor4 0.227710095 Change  1.303574995 1.0758649   6
Factor5 0.27353189  Change  1.577106884 1.303574995 7
Factor6 0.006879353 Change  1.583986238 1.577106884 8
Factor7 0.135077259 Change  1.719063497 1.583986238 9
Factor8 0.00591948  Change  1.724982976 1.719063497 10
Factor9 0.077394066 Change  1.802377042 1.724982976 11
Factor10    0.05212228  Change  1.854499322 1.802377042 12
Factor11    0.062991126 Change  1.917490448 1.854499322 13
Actual Est  1.836828552 Estimated   0   1.917490448 14
ActualB 1.278994    Actual  1.278994    0   15"

text <- gsub("[ ]+"," ",text)
text <- gsub("Actual Est", "ActualEst",text) # Ugh, dealing with spaces in a name.

balancefinal <- read.delim(textConnection(text), header = TRUE, sep=" ",strip.white=TRUE)

library(ggplot2)
strwr <- function(str) gsub(" ", "\n", str)
dollars <- paste0("$",seq(0, max(balancefinal$start) + 0.25, by = 0.25))

So you have to be careful with factors in R.  You have a repeated factor 'ActualEst' twice, ggplot2 will combine them, and list them alphabetically on your chart (how R factored your data).
Let's refactor and rename the extra level:
# You have to be careful how you define factors in R:
balancefinal$X1 = as.character(balancefinal$X1)
balancefinal$X1[14] = "ActualEst2"  # We need to make this a new factor (unique label)

# Here we reorder your factors in X1
balancefinal$X1_1 <- factor(balancefinal$X1, as.character(balancefinal$X1))

ggplot(balancefinal, aes(X1_1, fill = type)) +
  geom_rect(aes(x = X1_1,  xmin = id - 0.45, xmax = id + 0.45, ymin = end, ymax = start), colour = "black") +
  scale_fill_manual (values =c("#90353B", "#1A476F","burlywood1")) +
  scale_x_discrete("", breaks = levels(balancefinal$X1_1), labels = strwr(levels(balancefinal$X1_1))) +
  theme(legend.position = "bottom", legend.title=element_blank(),
    axis.text= element_text(size = 8), plot.title = element_text(vjust = 1)) +
  scale_y_continuous("", labels = dollars, breaks = seq(0, max(balancefinal$start) + 0.25, by = 0.25))

Now it works, albeit you have 'ActualEst2' instead of 'ActualEst'.


text:
Q: Entlib Custom exception handler missing mappings I implemented custom exception handler which works, except mappings from xml configuration policy. Those mapping works with standard Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler
My implementation
[ConfigurationElementType(typeof(CustomHandlerData))]
    public class IdentityFaultContractExceptionHandler : IExceptionHandler
    {
        public IdentityFaultContractExceptionHandler(NameValueCollection attributes)
        {
        }

        public IdentityFaultContractExceptionHandler(Type faultContractType, NameValueCollection attributes)
        {
        }

        public IdentityFaultContractExceptionHandler(Type faultContractType, string exceptionMessage, NameValueCollection attributes)
        {
        }

        public IdentityFaultContractExceptionHandler(IStringResolver exceptionMessageResolver, Type faultContractType, NameValueCollection attributes)
        {
        }

        public Exception HandleException(Exception exception, Guid handlingInstanceId)
        {
            return new Exception();
        }

and part of the configuration
<add name="All Exceptions" type="System.Exception, mscorlib" postHandlingAction="ThrowNewException">
          <exceptionHandlers>
            <add type="MyClass.IdentityFaultContractExceptionHandler, MyClass" exceptionMessage="An error occurred in the service." faultContractType="MyClass.UnexpectedServerFault, MyClass" name="Fault Contract Exception Handler" >
              <mappings>
                <add source="{Message}" name="Message" />
              </mappings>
            </add>
          </exceptionHandlers>
        </add>

When I remove mappping node service works, when I add, then I got error : unrecognize element mappings.

A: If you are using a CustomHandlerData attribute then your configuration needs to use XML Attributes which then get passed in as a NameValueCollection to the custom handler constructor.  If you want to have custom XML then you will have to use Full Design-time Integration.  If you want to go down that road then you should look at the FaultContractExceptionHandlerData source code since your code would probably be quite similar.


text:
Q: Probability that $n$ vectors of a binary superimposed code will have $k$ collisions I was reading a pre-print (https://arxiv.org/abs/1904.10102) and in this paper they discuss collisions, which is defined as when two or more binary vectors of a superimposed code contain a $1$ in the same position across the multiple vectors.
So my question is how would one determine the probability that $n$ vectors will have $k$ collisions?
The paper discusses $2$ errors causing $1$ collision in a superimposed code of finite size, but it does not discuss the probability that a collision occurs. I want to explore this further, and so I am trying to find the probability that $n$ vectors in a superimposed code of arbitrary size will have $3$ collisions, and then generalize to $k$ collisions.
My work so far has been noting that the probability that any $n$ number of vectors will have three $1$s in the same position is $\left(\frac{1}{2}\right)^{n-3}$ and then trying to expand that to a Poisson distribution,
$$P\left(X=3\right)=\frac{\mu^{x}e^{-\mu}}{x!}=\frac{\left(\frac{1}{2}\right)^{3}e^{-\frac{1}{2}}}{3!}=0.01263$$.
Any input, feedback, or advice, would be greatly appreciated. Thanks in advance.


text:
Q: datetime.date - Can't create correct input in script When I use datetime.date like beyond it works:
endeDate = datetime.date(1999, 6, 7)

when I create the input in my script it looks same as I would type in manually :
yerMonthDay = (str(year) + str(", ") + str(month) + str(", ") + str(day))
print(yerMonthDay)
1999, 6, 7

I know that datetime.date can just work with integer. I am not able to create the correct input for datetime.date in my script. I tried different things but nothing works:
endeDate = datetime.date(int(year) + int(month) + int(day))
TypeError: function missing required argument 'month' (pos 2

endeDate = datetime.date(f'{int(year)}{str(", ")}{int(month)}{str(", ")}{int(day)}')
TypeError: an integer is required (got type str

endeDate = datetime.date(int(year) + str(", ") + int(month) + str(", ") + int(day))
TypeError: unsupported operand type(s) for +: 'int' and 'str'

endeDate = datetime.date(int(year) + int(", ") + int(month) + int(", ") + int(day))
ValueError: invalid literal for int() with base 10: ', '

It would be great if you could tell me how I can create the input in my script that datetime.date(xxx) accepts it.
Thanks in advance

A: Assuming year, month, and day are integers, just use
year_month_day = datetime.date(year, month, day)

There's no need to try and format a string with commas , in it. datetime.date() takes 3 arguments, and you need to supply them the normal way.


text:
Q: How to increase jvm memory available to Scala worksheet? How can the jvm memory available to Scala worksheet be increased ?
There does not seem to be an option available in the Eclipse preferences ?

A: I don't know how recent is this feature, but it's certainly a possibility in Scala IDE 3.0.1. Just enter the appropriate value into the VM arguments field, e.g.:

Screenshot of full preference window from Window->Preferences... for reference: