text:
Q: Looking for a more efficient way to use multiple input type submit buttons with one ISSET($_POST[submit?]) code I need a little help with some code. I have html and PHP code that right now uses 13 input type submit buttons. Right now, I will have to duplicate the php isset for submit1 through submit13, even though the code is the same for each. Is there an easier way to use one isset($_POST[submit?]) no matter which of the input type submit buttons is pressed?
<?php
session_start();
global $current_user;
(get_currentuserinfo());
$link=mysqli_connect($host, $dbUsername, $dbPassword, $dbname);
$_SESSION["user_sex"] = $current_user->gender2;
$abc = "";
    if (isset($_POST['submit1']))
{
    $abc = "show";
    $tdate = $_POST['tdate'];
    $_SESSION["LeagueType_ID"] = (int)$_POST['lgType_id'];
    $sql1 = "SELECT * FROM `wp_tournaments` WHERE `start_tourn` = '$tdate' AND tourn_level_type_id = $_SESSION[LeagueType_ID] ";
    $ressql1 = mysqli_query($link, $sql1) or die("Bad Query: $sql1");
    $_SESSION["MinAge"] = 18;
    $_SESSION["Facility_ID"] = 541;
    $_SESSION["Facility2_ID"] = 1520;
// League Player Dropdown - Men for Women(MX) or Same Sex for Doubles
// Needed for Men's Doubles - Male looking for male partner
if (($_SESSION["user_sex"] == "Male") and ($_SESSION["LeagueType_ID"] == 3) and ($_SESSION["MinAge"] == 18)) {
        $queryPartner = "SELECT * FROM `wp_players` WHERE wp_players.gender2 = 'Male' AND region_id = 1";
}elseif (($_SESSION["user_sex"] == "Male") and ($_SESSION["LeagueType_ID"] == 3) and ($_SESSION["MinAge"] == 18)) {
    $bd = reverse_birthday($_SESSION["MinAge"]);
    $queryPartner = "SELECT * FROM `wp_players` WHERE wp_players.gender2 = 'Male' AND region_id = 1 AND birth_date < '$bd'";
}
// Needed for Mixed - Male looking for Female partner
if (($_SESSION["user_sex"] == "Male") and ($_SESSION["LeagueType_ID"] == 5) and ($_SESSION["MinAge"] == 18)) {
        $queryPartner = "SELECT * FROM `wp_players` WHERE wp_players.gender2 = 'Female' AND region_id = 1";
}elseif (($_SESSION["user_sex"] == "Male") and ($_SESSION["LeagueType_ID"] == 5) and ($_SESSION["MinAge"] == 18)) {
    $bd = reverse_birthday($_SESSION["MinAge"]);
    $queryPartner = "SELECT * FROM `wp_players` WHERE wp_players.gender2 = 'Female' AND region_id = 1 AND birth_date < '$bd'";
}
// Needed for Women's Doubles - Female looking for Female partner
if (($_SESSION["user_sex"] == "Female") and ($_SESSION["LeagueType_ID"] == 4) and ($_SESSION["MinAge"] == 18)) {
        $queryPartner = "SELECT * FROM `wp_players` WHERE wp_players.gender2 = 'Female' AND region_id = 1";
}elseif (($_SESSION["user_sex"] == "Female") and ($_SESSION["LeagueType_ID"] == 4) and ($_SESSION["MinAge"] == 18)) {
    $bd = reverse_birthday($_SESSION["MinAge"]);
    $queryPartner = "SELECT * FROM `wp_players` WHERE wp_players.gender2 = 'Female' AND region_id = 1 AND birth_date < '$bd'";
}
// Needed for Mixed Doubles - Female looking for Male partner
if (($_SESSION["user_sex"] == "Female") and ($_SESSION["LeagueType_ID"] == 5)) {
        $queryPartner = "SELECT * FROM `wp_players` WHERE wp_players.gender2 = 'Male' AND region_id = 1";
}elseif (($_SESSION["user_sex"] == "Female") and ($_SESSION["LeagueType_ID"] == 5) and ($_SESSION["MinAge"] == 18)) {
    $bd = reverse_birthday($_SESSION["MinAge"]);
    $queryPartner = "SELECT * FROM `wp_players` WHERE wp_players.gender2 = 'Male' AND region_id = 1 AND birth_date < '$bd'";
}
$resultDbls = mysqli_query($link, $queryPartner);
// End of Tournament Player Dropdown - Men for Women(MX)
}
    if (isset($_POST['submit2']))
{
    $abc = "show";
    $tdate = $_POST['tdate'];
    $_SESSION["LeagueType_ID"] = (int)$_POST['lgType_id'];
    $sql1 = "SELECT * FROM `wp_tournaments` WHERE `start_tourn` = '$tdate' AND tourn_level_type_id = $_SESSION[LeagueType_ID] ";
    $ressql1 = mysqli_query($link, $sql1) or die("Bad Query: $sql1");
    $_SESSION["MinAge"] = 18;
    $_SESSION["Facility_ID"] = 541;
    $_SESSION["Facility2_ID"] = 1520;
// League Player Dropdown - Men for Women(MX) or Same Sex for Doubles
// Needed for Men's Doubles - Male looking for male partner
if (($_SESSION["user_sex"] == "Male") and ($_SESSION["LeagueType_ID"] == 3) and ($_SESSION["MinAge"] == 18)) {
        $queryPartner = "SELECT * FROM `wp_players` WHERE wp_players.gender2 = 'Male' AND region_id = 1";
}elseif (($_SESSION["user_sex"] == "Male") and ($_SESSION["LeagueType_ID"] == 3) and ($_SESSION["MinAge"] == 18)) {
    $bd = reverse_birthday($_SESSION["MinAge"]);
    $queryPartner = "SELECT * FROM `wp_players` WHERE wp_players.gender2 = 'Male' AND region_id = 1 AND birth_date < '$bd'";
}
// Needed for Mixed - Male looking for Female partner
if (($_SESSION["user_sex"] == "Male") and ($_SESSION["LeagueType_ID"] == 5) and ($_SESSION["MinAge"] == 18)) {
        $queryPartner = "SELECT * FROM `wp_players` WHERE wp_players.gender2 = 'Female' AND region_id = 1";
}elseif (($_SESSION["user_sex"] == "Male") and ($_SESSION["LeagueType_ID"] == 5) and ($_SESSION["MinAge"] == 18)) {
    $bd = reverse_birthday($_SESSION["MinAge"]);
    $queryPartner = "SELECT * FROM `wp_players` WHERE wp_players.gender2 = 'Female' AND region_id = 1 AND birth_date < '$bd'";
}
// Needed for Women's Doubles - Female looking for Female partner
if (($_SESSION["user_sex"] == "Female") and ($_SESSION["LeagueType_ID"] == 4) and ($_SESSION["MinAge"] == 18)) {
        $queryPartner = "SELECT * FROM `wp_players` WHERE wp_players.gender2 = 'Female' AND region_id = 1";
}elseif (($_SESSION["user_sex"] == "Female") and ($_SESSION["LeagueType_ID"] == 4) and ($_SESSION["MinAge"] == 18)) {
    $bd = reverse_birthday($_SESSION["MinAge"]);
    $queryPartner = "SELECT * FROM `wp_players` WHERE wp_players.gender2 = 'Female' AND region_id = 1 AND birth_date < '$bd'";
}
// Needed for Mixed Doubles - Female looking for Male partner
if (($_SESSION["user_sex"] == "Female") and ($_SESSION["LeagueType_ID"] == 5)) {
        $queryPartner = "SELECT * FROM `wp_players` WHERE wp_players.gender2 = 'Male' AND region_id = 1";
}elseif (($_SESSION["user_sex"] == "Female") and ($_SESSION["LeagueType_ID"] == 5) and ($_SESSION["MinAge"] == 18)) {
    $bd = reverse_birthday($_SESSION["MinAge"]);
    $queryPartner = "SELECT * FROM `wp_players` WHERE wp_players.gender2 = 'Male' AND region_id = 1 AND birth_date < '$bd'";
}
$resultDbls = mysqli_query($link, $queryPartner);
// End of Tournament Player Dropdown - Men for Women(MX)
}
$def = "";
if (isset($_POST['submitform1']))
{
    $def = "show";
}
$ghi = "";
if (isset($_POST['submitpaypal']))
{
    $ghi = "show";
}
?>

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css">

    <form method="POST">

        Adult Mixed Doubles Tournament

        Adult Doubles Tournament - Men's/Women's

        Dates: April

        NTRP Levels: 6.0, 7.0, 8.0, 9.0, 10.0

        Location:Tennis Center - (555) 528-2626

        Address:

        Location: Tennis Center - (555) 454-3777

        Address:

        <input type='hidden' name='lgType_id' value=5>
        <input type='hidden' name='tdate' value='2020-02-27'>
        <input type="submit" value="Register to Play" name="submit1">

    </form>

    <form method="POST">

        Adult Singles Tournament - Men's/Women's

        Adult Doubles Tournament - Men's/Women's

        Dates: April

        NTRP Levels: 6.0, 7.0, 8.0, 9.0, 10.0

        Location:Tennis Center - (555) 528-2626

        Address:

        Location: Tennis Center - (555) 454-3777

        Address:

        <?php if ($_SESSION["user_sex"] =='Male') { ?>
        <input type='hidden' name='lgType_id' value=1>
        <?php } ?>
        <?php if ($_SESSION["user_sex"] =='Female') { ?>
        <input type='hidden' name='lgType_id' value=2>
        <?php } ?>
        <input type='hidden' name='tdate' value='2020-03-05'>
        <input type="submit" value="Register to Play" name="submit2">

    </form>

    <form method="POST">

        Adult Doubles Tournament - Men's/Women's

        Dates: April

        NTRP Levels: 6.0, 7.0, 8.0, 9.0, 10.0

        Location:Tennis Center - (555) 528-2626

        Address:

        Location: Tennis Center - (555) 454-3777

        Address:

        <?php if ($_SESSION["user_sex"] =='Male') { ?>
        <input type='hidden' name='lgType_id' value=3>
        <?php } ?>
        <?php if ($_SESSION["user_sex"] =='Female') { ?>
        <input type='hidden' name='lgType_id' value=4>
        <?php } ?>
        <input type='hidden' name='tdate' value='2020-04-02'>
        <input type="submit" value="Register to Play" name="submit3">

    </form>

<form method='POST'>

Adult Tournament <?php echo $tdate; echo $lgType_id; ?>

    <select class="chosen" name="formtournlvl" id="TournLevel" required>
            <option value="">Select Your Tournament Level....</option>
        <?php while($row1 = mysqli_fetch_assoc($ressql1)):;?>
        <option value=<?php echo $row1['ID'];?>><?php echo $row1['description'];?></option>
        <?php endwhile;?>
    </select>

    <select class="chosen" name="DblsPartner" id="selectPartner" >
        <option value="">Doubles Partner Selection:</option>
        <option value=0>**** Partner not Listed ****</option>
        <?php
            while($row1 = mysqli_fetch_assoc($resultDbls)):;?>
        <option value=<?php echo $row1['id'];?>><?php echo $row1['display_name'] . " - " . $row1['user_city'] . ", " . $row1['user_state'] . ", " . $row1['user_zip'] . "";?></option>
            <?php
            endwhile;
            ?>
    </select>

    <input class="pull-right" type="submit" name="submitform1" value="Move to Step 2" required>
</form>

<form method='POST'>

Page 2

    <input type="submit" class="pull-right" name="submitpaypal" value="Next Step" style="margin-left:10px;">
</form>

Page 3

<?php
if($abc!=""){
    ?>

<?php
}elseif($def!=""){
    ?>

    <?php
}elseif($ghi!=""){
    ?>

<?php
}else{
    ?>

<?php
}
?>

I have read through a number of questions previously submitted and was not able to find one that was similar to what I was asking. A number of answers submitted on other questions helped me get this far.
I like the format of having all of the input type submit buttons, but would like to only have one isset($_POST[submit?] php code.

A: You can try like this for all submit button
if($_SERVER['REQUEST_METHOD']=="POST")
  {
      // access all your form data here
  }


text:
Q: como hacer vlookup en macros de dos libros de excel diferentes Hola muy buenos días colegas, tengo una pregunta que aun no he podido resolver, resulta que tengo dos libros de excel A y B, en uno de ellos un registro como base de datos y en el otro una lista de códigos de productos y lo que quiero es buscar los datos en el libro B de acuerdo a los código del libro A con macros Vlookup alguna ayuda sera muy agradecido gracias!.
Aquí dejo unas lineas de codigo.
Application.CutCopyMode = False
conteo As Long
Dim Marca As Variant
Dim Rango As Variant
Dim Archivo As String
Dim bCarpeta As String
Dim codigoBuscado As String
Dim Final As Long

    bCarpeta = ActiveWorkbook.Path & "\"
    Archivo = Dir(bCarpeta & "Maestro Dinet" & "*.xl*")
    Workbooks.OpenText Filename:=Archivo
    Application.ScreenUpdating = False
    Archivo = ActiveWorkbook.Name
    Windows(Archivo).Activate

    ActiveCell.FormulaR1C1 = _
    "=VLOOKUP(RC[-5],'[Maestro Dinet.xlsb]01'!C1:C38,31,0)"
    Range("G5").Select
    Selection.AutoFill Destination:=Range("G5:G86") ', Type:=xlFillDefault

MsgBox "Proceso terminado", vbInformation, "Resultado"

A: El problema es que el código creado por el grabador de macros no funciona bien.
Intenta algo cómo esto:
With Sheets("Hoja_donde_aplicas_buscarv").Range("G5:G86")
    .Formula = "=VLOOKUP(RC[-5],'" & Archivo & "01'!C1:C38,31,0)"
    .Formula = .Value
End With

redpajama_set_name: RedPajamaStackExchange


text:
Q: Number increment animation duration slow as numbers increase I have a count up code here:
HTML:

700

1000

JavaScript:
function animateValue(id, start, end, duration) {
    var start= 0 ;
    var end = parseInt(document.getElementById(id).textContent, 10);
    var duration = 10000;
    var range = end - start;
    var current = start;
    var increment = end > start? 1 : -1;
    var stepTime = Math.abs(Math.floor(duration / range));
    var obj = document.getElementById(id);
    var timer = setInterval(function() {
        current += increment;
        obj.innerHTML = current;
        if (current == end) {
            clearInterval(timer);
        }
    }, stepTime);
}
animateValue("value2",0,0,0);
animateValue("value",0,0,0);

In this code numbers start from 0 to end with 10000ms duration. How can I set this duration be slower than this when it's close to the end?
For example:
Numbers: 0 To 100.
Duration : 50ms To 10ms.

A: Use some easing functions instead of incrementing at a constant rate.
Please note, however, that your total execution time will likely always be at least somewhat inaccurate due to the fact that each increment of the value takes some execution time which is not accounted for using this setTimeout approach. The problem is exacerbated by higher values.

//No easing
function constant (duration, range, current) {
  return duration / range;
}

//Linear easing
function linear (duration, range, current) {
  return ((duration * 2) / Math.pow(range, 2)) * current;
}

//Quadratic easing
function quadratic (duration, range, current) {
  return ((duration * 3) / Math.pow(range, 3)) * Math.pow(current, 2);
}

function animateValue(id, start, duration, easing) {
  var end = parseInt(document.getElementById(id).textContent, 10);
  var range = end - start;
  var current = start;
  var increment = end > start? 1 : -1;
  var obj = document.getElementById(id);
  var startTime = new Date();
  var offset = 1;
  var remainderTime = 0;

  var step = function() {
    current += increment;
    obj.innerHTML = current;

    if (current != end) {
      setTimeout(step, easing(duration, range, current));
    }
    else {
      console.log('Easing: ', easing);
      console.log('Elapsed time: ', new Date() - startTime)
      console.log('');
    }
  };

  setTimeout(step, easing(duration, range, start));
}

animateValue("value", 0, 10000, constant);
animateValue("value2", 0, 10000, linear);
animateValue("value3", 0, 10000, quadratic);

100

100

100


text:
Q: How to map the localhost path for magento 2 index file, to a domain name I have created a magento 2 setup and currently accessing the site by punching the whole url like

localhost\bla\bla\bla.....\magento-root-directory\

But I would like it to be

localhost\www.xyz.com

How to achieve the same.

A: I am waiting for about 2 hours for an answer but as no one posted so am giving my answer. Not sure if it's a proper way to do it or it's a hack but it should work.
Create a folder in htdocs named xyz.com and create an index.php file in it. Open that file and write this code.
<?php
$url ='url to to your magento ';
header('Location: '.$url);


text:
Q: Pause code until getting the response of an UIAlertController in Swift I have been trying to get the answer from a user from the UIAlertController. The problem is that the code still runs while the UIAlertController is displayed. I would like to show the alert, and then wait until the user gives an answer to continue the code.
func showPopUp(name:String)->String{
   var genre = ""
   let alert = UIAlertController(title: "What are you "+name+"?", message: nil, preferredStyle: .alert)

   alert.addAction(UIAlertAction(title: "Boy", style: .default, handler: { action in
    genre = "Boy"
}))

   alert.addAction(UIAlertAction(title: "Girl", style: .default, handler: { action in
    genre = "Girl"
}))

   self.present(alert, animated: true)
   return genre
}

override func viewDidLoad() {
        super.viewDidLoad()
        print("This should appear before the alert")
        let a = showPopUp(name: "John)

        print("This should appear after the response")
        print("John is a "+a)
        [...more code using variable 'a' ...]

}

I cannot put the code inside the action of the alert because is very long, and it also runs in other processes.

A: Alerts don't work as you might expect , it supposes to ask the user and waits for his action , so it's asynchronous
var genre = "Boy" // default

func showPopUp(name:String) {

   let alert = UIAlertController(title: "What are you "+name+"?", message: nil, preferredStyle: .alert)

   alert.addAction(UIAlertAction(title: "Boy", style: .default, handler: { action in
       self.genre = "Boy"
       self.handleSelection()
   }))

   alert.addAction(UIAlertAction(title: "Girl", style: .default, handler: { action in
       self.genre = "Girl"
       self.handleSelection()
   }))

   self.present(alert, animated: true)

}

func handleSelection() {
  print("current selected genre is \(genre)")
}

Plus this
showPopUp(name: "John")

should be inside viewDidAppear as it's too early to present anything inside viewDidLoad where vc' views is yet to be laid completely
var once = true
override func viewDidAppear(_ animated:Bool) {
  super.viewDidAppear(animated)
  if once {
     showPopUp(name: "John")
     once = false // to prevent re-showing it again
  }
}

A:
I cannot put the code inside the action of the alert

Yes, you can, and that is what you must do. The action is your signal that the alert has been dismissed (and it also tells you what button was tapped in the alert). You don't have to put the code itself inside the action; all you need is to call that code.
Example:
alert.addAction(UIAlertAction(title: "Boy", style: .default, handler: { action in
    self.myVeryLongFunction(genre:"Boy")
}))

A: Create a separate function, and call it from teh completion handler for your actions.
like this
func showPopUp(name:String)->String{
   var genre = ""
   let alert = UIAlertController(title: "What are you "+name+"?", message: nil, preferredStyle: .alert)

   alert.addAction(UIAlertAction(title: "Boy", style: .default, handler: { action in
    genre = "Boy"
    self.afterPopup()
}))

   alert.addAction(UIAlertAction(title: "Girl", style: .default, handler: { action in
    genre = "Girl"
    self.afterPopup()
}))

   self.present(alert, animated: true)
   return genre
}

override func viewDidLoad() {
        super.viewDidLoad()
        print("This should appear before the alert")
        let a = showPopUp(name: "John)
}

func afterPopup(){
        print("This should appear after the response")
        print("John is a "+a)
        [...more code using variable 'a' ...]
}

Also, watch-out for presenting a popup in ViewDidLoad. if this view is being presented, you'll have a warning thrown (and may lead to weird behavior of app)


text:
Q: How to get edge indices from selection? Is there's a way to get the indices properly from a Pymel/Maya API function?
I know Pymel has a function called getEdges() however according to their docs this get's them from the selected face, however I just need them from the selected edges.
Is this possible?

A: While your answer will work theodox, I did find a much simpler resolution, after some serious digging!
Turns out, hiding and not very well documented, was a function ironically called indices(), I did search for this but nothing came up in the docs.
Pymel
selection[0].indices()[0]
The above will give us the integer of the selected edge. Simple and elegant!

A: Do you mean you just the expanded list of selected edges?  That's just FilterExpand -sm 32 or cmds.filterExpand(sm=32) or pm.filterExpand(sm=32) on an edge selection. Those commands are always strings, you grab the indices out them with a regular expression:
# where objs is a list of edges, for example cmds.ls(sl=True) on an edge selection
cList = "".join(cmds.filterExpand( *objs, sm=32))
outList = set(map ( int, re.findall('\[([0-9]+)\]', cList ) ) )

which will give you a set containing the integer indices of the edges (I use sets so its easy to do things like find edges common to two groups without for loops or if tests)


text:
Q: Adding left navigation bar I am facing a problem with alignment in css while integrating an existing top aligned navbar with a left navbar.
I have used thymeleaf to achieve my top navbar.
header.html:

         <link rel="stylesheet" type="text/css" href="webjars/bootstrap/3.3.7/css/bootstrap.min.css" />
         <link rel="stylesheet" th:href="@{/css/main.css}" href="../../css/main.css" />

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".nav-collapse" aria-expanded="false">

               </button>

                     Tasks

Dashboard

Orders

Income

                      Sign in

                      Sign out

                     <form style="visibility: hidden" id="form" method="post" action="#" th:action="@{/logout}"></form>

admin.html:
<!DOCTYPE HTML>

      <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans" />
      <link rel="stylesheet" type="text/css" href="webjars/bootstrap/3.3.7/css/bootstrap.min.css" />
      <link rel="stylesheet" th:href="@{/css/main.css}" href="../../css/main.css" />

            Options

Home

Service

Portfolio

About

Contact

            <form class="form-horizontal" id="uploadForm" action="#">

                  Upload File:

                     <input id="upload" class="form-control" type="file" file-model = "uploadedFile" placeholder="Upload File"></input>

                  <button type="submit" class="uploadButton" ng-click = "doUploadFile()">Upload</button>

            </form>

PAS MDM Reject Records

Loading...

                     Policy Number
                     First Name
                     Last Name
                     Error Description
                     Validated/Corrected in PAS
                     Note
                     Action

                     {{row.PolicyNumber}}
                     {{row.FirstName}}
                     {{row.LastName}}
                     {{row.ErrorDescription}}
                     {{row.PASValidated}}
                     {{row.Note}}
                     <button type="button" class="btn btn-danger" ng-click="deletRecord(row.PolicyNumber)">

                        </button>

                        <button type="button" class="submitButton" ng-click="submit(employees)">Submit</button>

main.css:
h1 {
    color: #0000FF;
    display: inline;
}

h2 {
    color: #FF0000;
}

footer {
    margin-top: 60px;
}

div.container {
    position: relative;
    left: 60px;
}

.logoImg {
    background-size: 70.7%;
    background-repeat: no-repeat;
    background-position: 50%;
}

.submitButton {
    background-color:#24b54b;
    -moz-border-radius:6px;
    -webkit-border-radius:6px;
    border-radius:6px;
    border:1px solid #18ab29;
    display:inline-block;
    cursor:pointer;
    color:#ffffff;
    font-family:Arial;
    font-size:17px;
    padding:4px 31px;
    text-decoration:none;
}
.submitButton:hover {
    background-color:#15ad3b;
}
.submitButton:active {
    position:relative;
    top:1px;
}

.uploadButton {
    background-color:#16529c;
    -moz-border-radius:6px;
    -webkit-border-radius:6px;
    border-radius:6px;
    border:1px solid #2958b0;
    display:inline-block;
    cursor:pointer;
    color:#ffffff;
    font-family:Arial;
    font-size:17px;
    padding:4px 31px;
    text-decoration:none;
}
.uploadButton:hover {
    background-color:#0c458a;
}
.uploadButton:active {
    position:relative;
    top:1px;
}

.leftNavbar {
    width: 10%;
    float: left;
}

.navbar .navbar-brand {
  padding-top: 5px;
}
.navbar .navbar-brand img {
  height: 40px;
  width: 70px;
}

body {
  padding: 0;
  margin: 0;
  height: 100vh;
}
.buttons {
  position: absolute;
  right: 0;
  top: 0;
  a {
    display: block;
    text-decoration: none;
    padding: 5px 10px;
    margin: 5px;
    background: #000;
    color: #ccc;
  }
}
.sidebar {
  background: #1a1c1d;
  color: #787d80;
  width: 200px;
  height: 100%;
  text-align: center;
  transform-origin: left;
  transform-style: preserve-3d;
  transition: all 0.5s;
  overflow: hidden;

  &.hideDown {
    transform: rotateY(90deg) skewY(10deg);
  }
  &.hideUp {
    transform: rotateY(90deg) skewY(-10deg);
  }
  .sidebarHeader {
    padding: 20px 10px;
    font-weight: 700;
  }
  ul {
    padding: 0;
    margin: 0;
    list-style-type: none;
    li {
      padding: 15px 10px;
      a {
        text-decoration: none;
        color: inherit;
        transition: color 0.5s;
        &:hover {
          color: #ccc;
        }
      }
    }
  }
}

The left navbar is overlapping with the existing top navbar and hiding the contents I have defined in a div tag. (The upload functionality is admin.html)
Without left navbar:

With left navbar:

Could anyone please guide me on how to resolve this?
PS: I would like to have the left navbar added in admin.html and not header.html, since I am using header.html for login page too, which should not have the left navbar.

A: admin.html
<!DOCTYPE HTML>

      <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans" />
      <link rel="stylesheet" type="text/css" href="webjars/bootstrap/3.3.7/css/bootstrap.min.css" />
      <link rel="stylesheet" th:href="@{/css/main.css}" href="../../css/main.css" />

            Options

Home

Service

Portfolio

About

Contact

            <form class="form-horizontal" id="uploadForm" action="#">

                  Upload File:

                     <input id="upload" class="form-control" type="file" file-model = "uploadedFile" placeholder="Upload File"></input>

                  <button type="submit" class="uploadButton" ng-click = "doUploadFile()">Upload</button>

            </form>

PAS MDM Reject Records

Loading...

                     Policy Number
                     First Name
                     Last Name
                     Error Description
                     Validated/Corrected in PAS
                     Note
                     Action

                     {{row.PolicyNumber}}
                     {{row.FirstName}}
                     {{row.LastName}}
                     {{row.ErrorDescription}}
                     {{row.PASValidated}}
                     {{row.Note}}
                     <button type="button" class="btn btn-danger" ng-click="deletRecord(row.PolicyNumber)">

                        </button>

                        <button type="button" class="submitButton" ng-click="submit(employees)">Submit</button>

main.css
h1 {
    color: #0000FF;
    display: inline;
}

h2 {
    color: #FF0000;
}

footer {
    margin-top: 60px;
}

/*div.container {
    position: relative;
    left: 60px;
}*/

.uploadposition{
position:absolute;
right:0px;
top:100px;
width:85%;
}

.navbar-inverse {
    margin-bottom: 0px !important;
    position: relative !important;
}

.logoImg {
    background-size: 70.7%;
    background-repeat: no-repeat;
    background-position: 50%;
}

.submitButton {
    background-color:#24b54b;
    -moz-border-radius:6px;
    -webkit-border-radius:6px;
    border-radius:6px;
    border:1px solid #18ab29;
    display:inline-block;
    cursor:pointer;
    color:#ffffff;
    font-family:Arial;
    font-size:17px;
    padding:4px 31px;
    text-decoration:none;
}
.submitButton:hover {
    background-color:#15ad3b;
}
.submitButton:active {
    position:relative;
    top:1px;
}

.uploadButton {
    background-color:#16529c;
    -moz-border-radius:6px;
    -webkit-border-radius:6px;
    border-radius:6px;
    border:1px solid #2958b0;
    display:inline-block;
    cursor:pointer;
    color:#ffffff;
    font-family:Arial;
    font-size:17px;
    padding:4px 31px;
    text-decoration:none;
}
.uploadButton:hover {
    background-color:#0c458a;
}
.uploadButton:active {
    position:relative;
    top:1px;
}

.leftNavbar {
    width: 10%;
    float: left;
}

.navbar .navbar-brand {
  padding-top: 5px;
}
.navbar .navbar-brand img {
  height: 40px;
  width: 70px;
}

body {
  padding: 0;
  margin: 0;
  height: 100vh;
}
.buttons {
  position: absolute;
  right: 0;
  top: 0;
  a {
    display: block;
    text-decoration: none;
    padding: 5px 10px;
    margin: 5px;
    background: #000;
    color: #ccc;
  }
}
.sidebar {
  background: #1a1c1d;
  color: #787d80;
  width: 200px;
  height: 100%;
  text-align: center;
  transform-origin: left;
  transform-style: preserve-3d;
  transition: all 0.5s;
  overflow: hidden;

  &.hideDown {
    transform: rotateY(90deg) skewY(10deg);
  }
  &.hideUp {
    transform: rotateY(90deg) skewY(-10deg);
  }
  .sidebarHeader {
    padding: 20px 10px;
    font-weight: 700;
  }
  ul {
    padding: 0;
    margin: 0;
    list-style-type: none;
    li {
      padding: 15px 10px;
      a {
        text-decoration: none;
        color: inherit;
        transition: color 0.5s;
        &:hover {
          color: #ccc;
        }
      }
    }
  }
}

Check Updated Screenshot Here...


text:
Q: slick filter from any other class I have a case class, mappings and the object defined like this
import slick.driver.PostgresDriver.api._

import scala.concurrent.Await
import scala.concurrent.duration.Duration

case class Coffee(name : String, supID: Int, price: Double, sales: Int, total: Int) {

  def save(): Coffee = { Coffees.save(this) }

  def delete() { Coffees.delete(this) }
}

class Coffees(tag: Tag) extends Table[Coffee](tag, "coffee") {
  def name = column[String]("cof_name", O.PrimaryKey)
  def supID = column[Int]("sup_id")
  def price = column[Double]("price")
  def sales = column[Int]("sales", O.Default(0))
  def total = column[Int]("total", O.Default(0))
  def * = (name, supID, price, sales, total) <> (Coffee.tupled, Coffee.unapply)
}

object Coffees extends TableQuery(new Coffees(_)) {
  lazy val db = DatabaseAccess.databases("db.test")
  def save(coffee: Coffee): Coffee = {
    val saveQuery = (this returning this).insertOrUpdate(coffee)
    Await.result(db.run(saveQuery), Duration.Inf) match {
      case Some(x) => x
      case None => coffee
    }
  }

  def delete(coffee: Coffee) = {
    Await.result(db.run(this.filter(_.name === coffee.name).delete), Duration.Inf)
  }
}

Now I want to write queries from other classes like this :
import com.typesafe.config.ConfigFactory
import org.scalatest.{FeatureSpec, GivenWhenThen, Matchers}

class CoffeeSpec extends FeatureSpec with GivenWhenThen with Matchers {
  feature("Accessing coffees in the database") {
    scenario("Adding a new coffee") {
      val config = ConfigFactory.load()
      DatabaseAccess.loadConfiguration(config)
      lazy val db = DatabaseAccess.databases("db.test")

      val coffee = Coffee("nescafe", 1, 20, 20, 40).save()

      val temp = Coffees.filter(_.name === "nescafe")

      temp.length should be (1)

      coffee.delete()
    }
  }
}

This line
val temp = Coffees.filter(_.name === "nescafe")

Throws an error like this:

What is the best way to write the filter queries on the Coffees object?
Using slick 2.0 I have queries like:
Query(Coffees).filter(_.name is "coffee").firstOption.getOrElse(None)

I want to be able to do the similar queries using the new setup for all the data mappings.
Why am I getting these errors and how should I be able to make similar queries in slick 3?

A: Your queries are fine, but your CoffeeSpec file is missing an import:
import slick.driver.PostgresDriver.api._
Compilation should pass then.


text:
Q: ERROR on compilation Cannot use import statement outside a module I have made my first own project and i try to build my app and launch it after compilation. When I am using my app in dev mode with ts-node there is no problem, no error everything is okay. Now I compile with the build script: npm run start (check package.json below) and after my app is build in the dist folder I try to launch it and i see this errors:
Cannot use import statement outside a module
Unexpected token 'export' file: ./src/modules/authentication/events/authentication.event.ts
Cannot use import statement outside a module file: ./src/modules/users/events/user.event.ts
I have check on the web, but I have seen many response: add type:module in package.json, change typescript options, ... but nothing seems to work and I am a little lost among the different response I have seen.
I let you my config file to see if there is a problem:
Thx by advance for helping
Best regards
package.json
{
"name": "stygma-api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"types": "dist/index.d.ts",
"keywords": [],
"author": "Seyrinian",
"license": "MIT",
"scripts": {
    "dev": "cross-env NODE_ENV=development nodemon --exec ts-node ./src/index.ts",
    "lint": "eslint . --fix",
    "start": "tsc && node dist/index.js",
    "test": "cross-env NODE_ENV=test jest --verbose --forceExit --coverage --runInBand",
    "test-watch": "cross-env NODE_ENV=test jest --verbose --watchAll --runInBand",
    "ts-check": "tsc --noEmit --pretty"
},
"dependencies": {
    "bcrypt": "^5.0.0",
    "dotenv": "^8.2.0",
    "eventemitter2": "^6.4.3",
    "express": "^4.17.1",
    "glob": "^7.1.6",
    "jsonwebtoken": "^8.5.1",
    "lodash": "^4.17.20",
    "moment": "^2.28.0",
    "mongoose": "^5.10.2",
    "mongoose-id-validator": "^0.6.0",
    "mongoose-unique-validator": "^2.0.3",
    "supertest": "^5.0.0",
    "swagger-jsdoc": "^5.0.1",
    "swagger-ui-express": "^4.1.4",
    "winston": "^3.3.3"
},
"devDependencies": {
    "@types/bcrypt": "^3.0.0",
    "@types/express": "^4.17.8",
    "@types/glob": "^7.1.3",
    "@types/jest": "^26.0.12",
    "@types/jsonwebtoken": "^8.5.0",
    "@types/lodash": "^4.14.165",
    "@types/mongoose": "^5.7.36",
    "@types/mongoose-id-validator": "^0.6.0",
    "@types/mongoose-unique-validator": "^1.0.4",
    "@types/node": "^14.6.2",
    "@types/supertest": "^2.0.10",
    "@types/swagger-jsdoc": "^3.0.2",
    "@types/swagger-ui-express": "^4.1.2",
    "@typescript-eslint/eslint-plugin": "^4.1.1",
    "@typescript-eslint/parser": "^4.1.1",
    "cross-env": "^7.0.2",
    "eslint": "^7.9.0",
    "eslint-config-airbnb-base": "^14.2.0",
    "eslint-config-prettier": "^6.11.0",
    "eslint-plugin-import": "^2.22.0",
    "eslint-plugin-prettier": "^3.1.4",
    "jest": "^26.4.2",
    "nodemon": "^2.0.4",
    "prettier": "^2.1.1",
    "ts-jest": "^26.3.0",
    "ts-node": "^9.0.0",
    "typescript": "^4.0.2"
}

}
tsconfig.json
{
"include": ["src/**/*"],
"exclude": ["node_modules", ".vscode", "dist"],
"compilerOptions": {
    "target": "es6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
    "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
    "declaration": true /* Generates corresponding '.d.ts' file. */,
    "outDir": "dist" /* Redirect output structure to the directory. */,
    "rootDir": "src" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
    "strict": true /* Enable all strict type-checking options. */,
    "noUnusedLocals": true /* Report errors on unused locals. */,
    "noUnusedParameters": true /* Report errors on unused parameters. */,
    "noImplicitReturns": true /* Report error when not all code paths in function return a value. */,
    "noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */,
    "typeRoots": ["./src/typings", "./node_modules/@types"] /* List of folders to include type definitions from. */,

    "resolveJsonModule": true /* Authorize import JSON file*/,
    "skipLibCheck": true /* Skip type checking of declaration files. */,
    "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}

}

A: Setting the type to module inside the package js normally fixes this problem.
Are you sure you have set it right?
Please try to set it once again by adding it to the top layer of your package.json like this:
{
  ...
  "main": "index.js",
  "type": "module",
  ...
}

The "main" part here is just for clarification on where the "type" property has to go.


text:
Q: Login Page to verify NIC number I am facing the followingj problem: I have a database on Access 2010 with fields NIC,Active and Page, all are of number types. I want to create a login page that takes NIC (numeric) as an input from the user and then redirects them to specific page as per their NICs.
Different people will see different pages.. I am getting an error in ExecuteScalar command, maybe my query is not correct or maybe ExecuteScalar can't hold the query... I am getting data type mismatch error.
try
{
    FirsstPage f = new FirsstPage();
    SecondPage second = new SecondPage();
    oledcon.Open();

    string NIc = ( TextBox1.Text);
    // string query = "select * from LogINTable where NIC='" + NIc + "'AND Active=0 AND page=1";
    //string query = "select * from LogINTable where NIC='" + nic + "'AND Active=0";
    string query = "SELECT * FROM LogINTable WHERE NIC= '" + NIc + "' AND Active=0 AND page=1";
    //string query = "select
    OleDbCommand comm = new OleDbCommand( query,oledcon);
    string a = (string) comm.ExecuteScalar();
    if (a != null)
    {
        Response.Redirect("FirsstPage.aspx");
        string update = "update into LogINTable Active='1' where NIC='" + NIc + "' ";
        //OleDbCommand com = new OleDbCommand();
        //int b = Convert.ToInt32( com.ExecuteScalar());
    }
    else
    {
        Response.Redirect("SecondPage.aspx");
        string update = "update into LogINTable Active='1' where NIC='" +NIc + "' ";
    }

    oledcon.Close();
}
catch (Exception ex)
{
    Label1.Text = ex.Message;
}
finally
{
    oledcon.Close();
}

A: Problem is that you are using ExecuteScalar with wrong query.
string a = (string) comm.ExecuteScalar();

ExecuteScalar() will return single value as a result from query.
Please change your query to the query like blow which return single value from database in place of entire colomn
Select NIC FROM LogINTable WHERE NIC= '" + NIc + "' AND Active=0 AND page=1"

Source :http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
I hope it will help you.


text:
Q: faster column-multiply in dataframe I have a pandas dataframe A that has 2 columns x and y. I want to multiply them like B = A['x'] * A['y']. Is there any faster way to do this? would A['a'].mul(A['y']) be faster?

A: To check which is faster you can check the time that it takes for each case:
In Ipython or Jupiter would be:
%%timeit
    d['a'] * d['b']

For a dataframe like this one:
a = np.arange(0,10000)
b = np.ones(10000)

d = pd.DataFrame(np.vstack([a,b]).T, columns=["a","b"])

Get your multiplication:
1- in pandas
d['a'] * d['b']
81.2 µs ± 977 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

2 - in numpy. avoiding pandas overhead
d['a'].values * d['b'].values
9.21 µs ± 41.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

... If you are worried so much about speed, use just numpy. Take advantage of the nice feature of pandas to allow you to access the array with the feature values.

A: Numpy is much faster, you use np.arrays if your columns are lengthy
import numpy as np

B=np.array(A.x)*np.array(A.y)

A quick test on my PC on a dataframe with 55K rows reduced the time from 0.78 sec (your original method) to 0.54 sec (above method)

A: I could only agree with @IoaTzimas 's comment, Numpy is faster. So you'd be better off converting the Dataframe's columns that you want to multiply to Numpy arrays and work with them.
If you have the initial data in arrays, you can just convert them to a numpy array and use that.
If you have your data in a Dataframe and need to extract it beforehand you could do the following:
from numpy import multiply as npMultiply

# get the values from the Dataframe to arrays
x_array = A['x'].values
y_array = A['y'].values

B = npMultiply(x_array, y_array)


text:
Q: If $T : V \to V$, $\operatorname{nullity}(T) = 0$, is $T$ onto?
Use the given information to determine whether the linear operator is
one-to-one, onto, both, or neither.

Given: $T : V \to V$ is linear and $\operatorname{null}(T)=0$
I know it is one to one because the $\operatorname{null}(T)=0$, but I'm not sure if it is onto or not.
According my text book;
Theorem 8.1.3:
(a) The kernel of $T$ is a subspace of $V$.
(b)The range of $T$ is a subspace of $W$.
In this Theorem it shows that $b$ ($b = T(V)$) is a subspace of $V$.
Is this subspace - $T(V)$ - equal to $V$ in this given these conditions? As we know, a subspace of $V$ can be itself.

A: It is true that the range of $T$ is a vector subspace of $V$, but it may not always be all of $V$.
Specifically, if $T:V\to V$ is linear, $V$ is finite dimensional, and $\dim\ker T = 0$, then $T$ is surjective (in fact, $T$ is an isomorphism). To prove this, pick a basis $\{v_1,\dots,v_n\}$ for $V$ and show that $\{Tv_1,\dots,Tv_n\}\subseteq\text{im}\,T$ is a basis for $V$.
Conclude that

 $\dim\text{im}\,T=\dim V$ so $\text{im}\,T=V$.

In the case that $V$ is infinite dimensional, this may not be true.
Hint: Set $V$ to be

$\mathbb{R}[x]$, the set of all polynomials with real coefficients in the variable $x$

and define $T:V\to V$ by

$T(p) = xp$.


text:
Q: Why doesn't User.Identity.IsAuthenticated work on a page loaded using ajax? Why doesn't User.Identity.IsAuthenticated work on page that has been loaded using ajax?
In my view have this code:
@if (User.Identity.IsAuthenticated)
{
  ...
}
else
{
  ...
}

but when this View/Controller is loaded using ajax @if (User.Identity.IsAuthenticated) is always false and goes to the else section.
I don't know why this happens.
Is it possible that this problem is due to the loading with ajax?


text:
Q: Count With Conditional on PostgreSQL I have a table with people and another with visits. I want to count all visits but if the person signed up with 'emp' or 'oth' on ref_signup then remove the first visit. Example:
This are my tables:
PEOPLE:
   id    |  ref_signup
---------------------
   20    |   emp
   30    |   oth
   23    |   fri

VISITS
  id     |   date
-------------------------
  20     |   10-01-2019
  20     |   10-05-2019
  23     |   10-09-2019
  23     |   10-10-2019
  30     |   09-10-2019
  30     |   10-07-2019

On this example the visit count should be 4 because persons with id's 20 and 30 have their ref_signup as emp or oth, so it should exclude their first visit, but count from the second and forward.
This is what I have as a query:
SELECT COUNT(*) as visit_count FROM visits
LEFT JOIN people ON people.id = visits.people_id
WHERE visits.group_id = 1

Would using a case on the count help on this case as I just want to remove one visit not all of the visits from the person.

A: Subtract from COUNT(*) the distinct number of person.ids with person.ref_signup IN ('emp', 'oth'):
 SELECT
  COUNT(*) -
  COUNT(DISTINCT CASE WHEN p.ref_signup IN ('emp', 'oth') THEN p.id END) as visit_count
FROM visits v LEFT JOIN people p
ON p.id = v.id

See the demo.
Result:
| visit_count |
| ----------- |
| 4           |

Note: this code and demo fiddle use the column names of your sample data.

A: Premise, select the count of visits from each person, along with a synthetic column that contains a 1 if the referral was from emp or oth, a 0 otherwise.  Select the sum of the count minus the sum of that column.
SELECT SUM(count) - SUM(ignore_first) FROM  (SELECT COUNT(*) as count, CASE WHEN ref_signup in ('emp', 'oth') THEN 1 ELSE 0 END as ignore_first as visit_count FROM visits
LEFT JOIN people ON people.id = visits.people_id
WHERE visits.group_id = 1 GROUP BY id) a

A: where's "people_id" in your example ?
SELECT COUNT(*) as visit_count
FROM visits v
JOIN people p ON p.id = v.people_id
WHERE p.ref_signup IN ('emp','oth');

then remove the first visit.

You cannot select count and delete the first visit at same time.
DELETE FROM visits
  WHERE id IN (
      SELECT id
      FROM visits v
      JOIN people p ON p.id = v.people_id
      WHERE p.ref_signup IN ('emp','oth')
      ORDER BY v.id
      LIMIT 1
);

edit: typos

A: -- First get the corrected counts for all users
WITH grouped_visits AS (
  SELECT
    COUNT(visits.*) -
      CASE WHEN people.ref_signup IN ('emp', 'oth') THEN 1 ELSE 0 END
      AS visit_count
  FROM visits
    INNER JOIN people ON (people.id = visits.id)
  GROUP BY people.id, people.ref_signup
)
-- Then sum them
SELECT SUM(visit_count)
FROM grouped_visits;

This should give you the result you're looking for.

On a side note, I can't help but think clever use of a window function could do this in a single shot without the CTE.
EDIT: No, it can't since window functions run after needed WHERE and GROUP BY and HAVING clauses.

A: First, I create the tables
create table people (id int primary key, ref_signup varchar(3));
insert into people (id, ref_signup) values (20, 'emp'), (30, 'oth'), (23, 'fri');
create table visits (people_id int not null, visit_date date not null);
insert into visits (people_id, visit_date) values (20, '10-01-2019'), (20, '10-05-2019'), (23, '10-09-2019'), (23, '10-10-2019'), (30, '09-10-2019'), (30, '10-07-2019');

You can use the row_number() window function to mark which visit is "visit number one":
select
  *,
  row_number() over (partition by people_id order by visit_date) as visit_num
from people
join visits
  on people.id = visits.people_id

Once you have that, you can do another query on those results, and use the filter clause to count up the correct rows that match the condition where visit_num > 1 or ref_signup = 'fri':
-- wrap the first query in a WITH clause
with joined_visits as (
  select
    *,
    row_number() over (partition by people_id order by visit_date) as visit_num
  from people
  join visits
    on people.id = visits.people_id
)
select count(1) filter (where visit_num > 1 or ref_signup = 'fri')
from joined_visits;


text:
Q: wcf web service return message in format depents on request Accept In this
post in answer was show that we can force service to return message in json. But wcf have feature that allows automatic convert return message in soap or rest format like json using few endpoints typed in config ? For example I set WebInvoke attribute on service and set two address for endpoint like serviceAddress/soap , serviceAddress/json and wcf choose good endpoint for specific format result?


text:
Q: TypeScript: Accessing JQuery children as array I'm going through a porting exercise going from JavaScript to TypeScript and have hit the following issue.
In the original JavaScript code I've got:
var children = someJQueryElement.children('div');
var sortedChildren = children.sort(someSortFunction);

In TypeScript (1.4) all the jQuery methods return JQuery which isn't an array and therefore can't have sort called on it.
How should I go about solving this?

A: As an idea, have you tried to tell TypeScript to treat it as an array using casting?
var children = someJQueryElement.children('div');
var sortedChildren = (<Array>children).sort(someSortFunction);

This seems like a fairly tedious solution, though, if you have to do this in many places.  Hopefully someone has a better answer.

A: You can use Array.slice.apply to pass in the array-like object and convert it to a proper array.
var children = [].slice.apply(someJQueryElement.children('div'));

This is also a useful practice if you're not using jQuery but want to convert any other array-like objects, like arguments, for example.

A: You can change to a normal array using .get()
children.get().sort(someSortFunction);


text:
Q: How to rename entire java package name in Eclipse so that its all occurences gets renamed? I want to rename entire package and it's all ocurences includeing package name and imports, change in eclipse.
For example com.google.gdata.client and its classes to com.xyz.google.gdata.client and its all occurences.
Actually, I want to customize gdata-core.1.47.jar source code as per my requirement. First thing I need to do is to change the package structure as per my requirements. But when I followed the above mentioned steps, some more imports were automatically added
For example before refctor,
For class com.google.api.gbase.client has following import
import com.google.gdata.util.common.xml.XmlWriter;
import com.google.gdata.data.Extension;
import com.google.gdata.data.ExtensionProfile;
import com.google.gdata.data.AttributeHelper;
import com.google.gdata.data.ExtensionDescription;
import com.google.gdata.util.ParseException;
import com.google.gdata.util.XmlParser;

But after after rename it to com.google.gdata.client  to com.xyz.google.gdata.client it add some more imports like below,
import com.google.api.gbase.client.AddValueHandler;
import com.google.api.gbase.client.AttributeHistogram;
import com.google.api.gbase.client.GoogleBaseAttributeId;
import com.google.api.gbase.client.GoogleBaseAttributeType;
import com.google.api.gbase.client.GoogleBaseEntry;
import com.google.api.gbase.client.UniqueValue;
import com.google.gdata.util.XmlWriter;
import com.xyz.google.gdata.data.AttributeHelper;
import com.xyz.google.gdata.data.Extension;
import com.xyz.google.gdata.data.ExtensionDescription;
import com.xyz.google.gdata.data.ExtensionProfile;
import com.xyz.google.gdata.util.ParseException;
import com.xyz.google.gdata.util.XmlParser;

A: In the Project Explorer, right click the package name and choose Refactor->Rename.


text:
Q: Modified Intermediate Theorem Implies Continuity... Counterexample to Question from Spivak Question 13b of chapter 7 in Spivak's Calculus (which I've been slowly working through over the last few months) says this:
'Suppose that f satisfies the conclusion of the Intermediate Value Theorem, and that f takes on each value only once. Prove that f is continuous.'
What I think he means by this is that if, for some $f$ defined on [a,b] and for all $u$, if $f(a)\leq u \leq f(b)$, then there is one and only one $c$ in $[a,b]$ such that $f(c) = u$. If this is true then $f$ is continuous.
I spent a few minutes trying to prove this, but in the end created a 'counterexample'. Right now I'm just wondering where I've gone wrong...
$$
 f(x) =
  \begin{cases}
   x+\frac{1}{2} & \text{if } 0 \leq x \leq\frac{1}{2} \\
   1-x       & \text{if } \frac{1}{2} < x \leq 1
  \end{cases}
$$
$f$ is not continuous on $[0,1]$ but the IVT definitely holds over this interval and, furthermore, there's a 1-1 correspondence between $x$ values and $f(x)$ values over this interval.
Where have I gone wrong???
Thanks

A: I think this may be a question of interpretation. Your example is correct with the interpretation you are usng: your function $f$ takes every value in $[0,1]$ exactly once, but is not continuous on $[0,1].$ But one possible interpetation of what Spivak meant is that whenever $a < c < d < b$, $f$ takes each value between $f(c)$ and $f(d)$ exactly once on $[c,d]$, and then your example would not be a counterexample to the continuity of such an $f.$

A: Note that $f(1/4)=3/4$ and $f(3/4)=1/4$. Certainly $1/2$ is between $f(1/4)$ and $f(3/4)$. But there is no $x$ between $1/4$ and $3/4$ at which $f(x)=1/2$. So your $f$ does not satisfy the Intermediate Value Theorem.
The IVT says that if $f$ is continuous on $[a,b]$, then for any $u$ and $v$ such that $a \le u \le v\le b$, and any $y$ between $f(u)$ and $f(v)$, there is an $x$ between $u$ and $v$ such that $f(x)=y$. The conclusion of the IVT is the part after the "then."
Remark: A somewhat simpler example of the type you described is given by $f(x)=x$ on $(0,1)$, $f(1)=0$, $f(0)=1$. Again, it does not satisfy the IVT.
Question $13$(b) can be attacked as follows. Suppose that $a \le x <b$. Imagine a sequence $x_1,x_2, \dots$ that approaches $x$ steadily from the right. If the $f(x_i)$ ever wiggle, the conclusion of the IVT quickly lets us contradict the "each value only once" condition. If the $f(x_i)$ form a monotone sequence, but this sequence does not approach $f(x)$, again we can use the conclusion of the IVT and the only once condition to get a contradiction.

A: Between $1/2-\varepsilon$ and $1/2+\varepsilon$ there is no point where the value of the function is $3/4$, even though $3/4$ is between the values of $f$ at those points (provided $\varepsilon$ is small enough).  Hence the conclusion of the IVT is not satisfied by this function.

A: A hint: Looking at various graphs one is lead to conjecture that a function satisfying the IVT and taking any value at most once is strictly increasing or strictly decreasing. Therefore it is a good strategy to begin by proving that the given $f$ is strictly monotone. In this way the set of $f$'s to be considered for the continuity proof gets decisively restricted.


text:
Q: About the Dell Nautilus Firmware Update Utility; I cannot find UsbMake.exe file I am a new Server install user trying to wrench on a Dell R710. Box from eBay came with 2016 Server Evaluation Edition. Trying to learn AD, PowerShell, VMWare etc. So I bought extra memory, and 6 Hitachi drives (600MBs at 10k) to fill out the box because it only had 2 dell harddrives (300Mbs at 10K) with the buy. I can see the 6 HSBT drives in the BIOS but they won't RAID. Now I'm updating the the firmware but I don't see the UsbMake.exe file as per instructions on the Dell website. Dell says : "Once you have downloaded and extracted the file, you should run the UsbMake.exe file, located in the folder you extracted the files to". When I looked for this .exe file I cannot find it!! I must be missing something....I downloaded the latest ver that I saw on the site....Dell Nautilus Firmware Update Utility dated Oct/2018. And saw no/searched no find this UsbMake.exe file to run the boot file. I must be doing something wrong....can someone point out my error?? Thanks
Stan**

A: I went to youtube and found an answer. The Dell site lists this file as UsbMake.exe but the file others ran was dddp.exe otherwise known as the diagnostic distribution package. I don't know when it was re-named or what is going on. But Dell should straighten it out. It took me two days to get on the right track. It sucks.


text:
Q: How much conservative ZF+AC and ZF+DC are over ZF? A logical theory $T_2$ is a (proof theoretic) conservative extension of a theory $T_1$ if the language of $T_2$ extends the language of $T_1$; every theorem of $T_1$ is a theorem of $T_2$; and any theorem of $T_2$ that is in the language of $T_1$ is already a theorem of $T_1$.
More generally, if $\Gamma$ is a set of formulas in the common language of $T_1$ and $T_2$, then $T_2$ is $\Gamma$-conservative over $T_1$ if every formula from $\Gamma$ provable in $T_2$ is also provable in $T_1$.

Question 1: How much conservative ZF+AC and ZF+DC are over ZF? In the other words, what are the largest known sets of formulas $\Gamma_1$, $\Gamma_2$ in the language of set theory such that
$\forall \varphi\in\Gamma_1~~~~~ZF+DC\vdash \varphi \Longleftrightarrow ZF\vdash \varphi$
$\forall \varphi\in\Gamma_2~~~~~ZF+AC\vdash \varphi \Longleftrightarrow ZF\vdash \varphi$
Question 2: It follows from Shoenfield's absoluteness theorem that restricted to the statements about natural numbers ZF+AC is $\Pi_{3}^1$ conservative over ZF. What can we say about $ZF+DC$ over $ZF$?

A: I don't know if there is a very neat answer. In the case of $\sf ZF$ and $\sf ZFC$, you have the Levy absoluteness theorem which tells us that $\Delta_1$ statements are absolute between $V$ and $L$. I extended this in this note by introducing a new notion of "bounded quantifiers", and showing that the class of absolute statements is strictly larger than just that (it's not new, I just tried to give it some structure).
In the case of $\sf ZF+DC$ things are a bit different. We can probably push the conservativity of $\sf ZFC$ over $\sf ZF+DC$ a bit more in the same way the Levy absoluteness can be extended to $\Pi_1$ statements in that case (by using countable elementary submodels and the Shoenfield absoluteness theorem). I expect that such example can be used to give a statement which is not absolute between $\sf ZF$ and $\sf ZF+DC$ and has a relatively minimal complexity.


text:
Q: Finding the closed form of a real valued power series First of all the task was to find the radius of convergence $\rho$ of:
$$\sum\limits_{k=1}^\infty \left ( \frac{(-1)^{k+1}}{2k}\right)(2x-4)^{2k}$$
I am pretty sure $\rho=\frac{1}{2}$ is correct.
Now we had to look for the derivative of the power series which I think should be:
$$\sum\limits_{k=1}^\infty (-1)^{k+1}2^{2k}(x-2)^{2k-1}$$
And finally we should find the closed form of:
$$f:(2-\rho,2+\rho) \longrightarrow \mathbb{R}:x \mapsto \sum\limits_{k=1}^\infty (-1)^{k+1}2^{2k}(x-2)^{2k-1}$$
$\sum\limits_{k=0}^\infty (-1)^k2^{2k+2}(x-2)^{2k+1}=4(x-2)\sum\limits_{k=0}^\infty(-1)^k2^{2k}(x-2)^{2k}=4(x-2)\sum\limits_{k=0}^\infty \left ( -4(x-2)^2 \right )^k$
$$=4(x-2)\left( \frac{1}{1+4(x-2)^2} \right ) = \frac{4(x-2)}{1+4(x-2)^2}$$
This should be justified, since $x \in (1.5,2.5)$
Is this correct? Would be great if someone could look over it :)

A: Now the sum of the antiderivative of the series I found the closef form already:
$$\int \frac{4(x-2)}{4(x-2)^2+1}dx$$
$u=x-2 \Longrightarrow dx=du$
Substituting:
$$\int \frac{4u}{4u^2+1}du$$
$v=4u^2+1 \Longrightarrow du=\frac{dv}{8u}$
Substituting:
$$\int \frac{4u}{v}\frac{1}{8u}dv=\int \frac{1}{2v}dv=\frac{1}{2}\int \frac{1}{v}dv=\frac{1}{2}\left [ \ln(|v|) \right ]$$
Resubstituting:
$$\frac{1}{2}\left [ \ln(|4u^2+1|) \right ]$$
Resubstituting:
$$\frac{1}{2}\left [ \ln(|4(x-2)^2+1|) \right ]=\frac{1}{2}\left [ \ln(4(x-2)^2+1) \right ]=\int\sum\limits_{k=1}^\infty(-1)^{k+1}2^{2k}(x-2)^{2k-1}dx=\sum\limits_{k=1}^\infty\frac{(-1)^{k+1}2^{2k}}{2k}(x-2)^{2k}$$
So yes as @jijijojo promised me the closed form of the second series was $\frac{1}{2}\left [ \ln(4(x-2)^2+1) \right ]$ :)


text:
Q: Why do I get internal server error with JMeter 5.1? I am migrating scripts from version 2.9 to 5.1. One request is failing in both versions sending me this error:

:internal server error code 500.

What could be the issue?

A: Almost each JMeter version contains some incompatible changes, you need to walk through the JMeter Changelog, identify all the changes and properly amend your script.
Given JMeter 2.9 was released in February 2013 and now we're in March 2020 I believe it would be easier to record the tests from scratch as application could change in 7 years hence "old" JMeter scripts are not valid anymore.
With regards to HTTP Status Code 500

The HyperText Transfer Protocol (HTTP) 500 Internal Server Error server error response code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.
This error response is a generic "catch-all" response. Usually, this indicates the server cannot find a better 5xx error code to response. Sometimes, server administrators log error responses like the 500 status code with more details about the request to prevent the error from happening again in the future.

So you need to look into your server logs, most probably you will get the clue regarding what went wrong from them.


text:
Q: Is there any chance for the hash codes of two different objects of being same? The collection frameworks like HashSet, HashMap, HashTable call hashCode() and equals() in order, to check the two objects are same(For reference, the language I'm learning is java).
However if the return values of hashCode() are the same, how could it be possible that the return values of equals() are different?
I'm very confused. Does that mean the hash codes of two different objects can be the same?


text:
Q: adding a list of points in mapbox for Android I would like to add a list of points to my mapbox mapin my Android app. I am able to draw polygons and lines to my map, but there is no function to draw a single point to the map. Is there a solution to draw 1000+ points to the mapbox map?
Something like this:

or
this
I would like to do this for Android and refresh the points and change their position.

A: You can add a single marker using the addMarker() method (full example). If you need more complex views, you can also create view-based markers (full example).

A: I was looking at documentation and it looks like you can accomplish what you want using the annotations plugin for mapbox! (https://docs.mapbox.com/android/plugins/overview/annotation/#options)
Assuming you already have the dependency initialized there are a few steps you need to do to start using this annotation plug-in!
The documentation goes into great detail on how to use this so that is really helpful, but I'll include an example for using this feature to create an annotation. All of the code below is taken from the documentation and pieced together as described. Hope this helps!
First add this code snippet to your gradle file
repositories {
  mavenCentral()
}

dependencies {
  implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-annotation-v9:0.8.0'
}

Next add this code to your fragment/activity you have your mapbox created in.
    @Override
public void onMapReady(@NonNull final MapboxMap mapboxMap) {
    mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
      @Override
      public void onStyleLoaded(@NonNull Style style) {

        // Use a layer manager here
        // create symbol manager object
        SymbolManager symbolManager = new SymbolManager(mapView, mapboxMap, style);

        // add click listeners if desired
        symbolManager.addClickListener(symbol ->

        );

        symbolManager.addLongClickListener(symbol -> {

        });

        // set non-data-driven properties, such as:
        symbolManager.setIconAllowOverlap(true);
        symbolManager.setIconTranslate(new Float[]{-4f,5f});
        symbolManager.setIconRotationAlignment(ICON_ROTATION_ALIGNMENT_VIEWPORT);

        symbolManager.setIconAllowOverlap(true);
        symbolManager.setIconIgnorePlacement(true);

        // Add symbol at specified lat/lon
        Symbol symbol = symbolManager.create(new SymbolOptions()
            .withLatLng(new LatLng(60.169091, 24.939876))
            .withIconImage(ICON_ID)
            .withIconSize(2.0f));

       }
    });
}


text:
Q: Calculate the mean and variance given a random variable of a beta distribution Two quantities, $a$ and $b$, are estimated as the minimum and maximum length of time it will take for a project to be completed. Experience shows that the actual length of time it takes for a project to be completed is a random variable defined by $Y = a + (b-a)X$, where $X\sim \mathrm{Beta}(\alpha,\beta)$, where $\alpha$ and $\beta$ are also determined for each project. Suppose that for a particular project it is estimated $a=2$ years, $b=4$ years, $\alpha = 2$ and $\beta = 2$.
How do I find the mean and variance of the time it will take to complete the project?
What is the probability it will take less than 3 years to complete the project?

A: $\mathbf{E}Y=a+(b-a)\mathbf{E}X=a+(b-a)\frac{\alpha}{\alpha+\beta}=2+2 \cdot \frac{1}{2}=3$
$\mathbf{Var}Y=(b-a)^2 \mathbf{Var}X=(b-a)^2 \cdot \frac{\alpha \beta}{(\alpha+\beta)^2(\alpha+\beta+1)}=4 \cdot \frac{4}{4^2 \cdot 5}=\frac{1}{5}$
$\mathbf{P}(Y \leq 3)=\mathbf{P}(a+(b-a)X \leq 3)=\mathbf{P}(X\leq\frac{3-a}{b-a} )=P(X \leq \frac{1}{2})$
Values for the expectation and variance can be found in Wikipedia for Beta RV


text:
Q: Working Precision Slowing Down Numerical Integration Computation f1[x_, n_] :=
 1/(1 + 10000000000000000000000000 (\[Pi]^8 (-2 Sqrt[(89 + x)^2] +
          Sqrt[31363 + (n + Sqrt[-31363 + 4 (89 + x)^2])^2])^8 -
       4/3 \[Pi]^10 (-2 Sqrt[(89 + x)^2] + Sqrt[
          31363 + (n + Sqrt[-31363 + 4 (89 + x)^2])^2])^10 +
       38/45 \[Pi]^12 (-2 Sqrt[(89 + x)^2] + Sqrt[
          31363 + (n + Sqrt[-31363 + 4 (89 + x)^2])^2])^12))

NIntegrate[(E^(2 I Pi (n + Sqrt[321 + 712 x + 4 x^2])))^21  N[
   f1[x, n], 25], {x, 0, 10^35}, {n, -1/100, 1/100},
 MaxRecursion -> 500, Method -> "LevinRule"]

The above works flawlessly, but once I try to set the Working Precision of the numerical integral like below, the integration time increases exponentially.
NIntegrate[(E^(2 I Pi (n + Sqrt[321 + 712 x + 4 x^2])))^21  N[
   f1[x, n], 25], {x, 0, 10^35}, {n, -1/100, 1/100},
 MaxRecursion -> 500, Method -> "LevinRule", WorkingPrecision -> 25]

Is there any way to speed this up and get that level of accurate digits of computation?, I know this is because of the default machine precision on most systems, but is there a work around?


text:
Q: How can I solve TypeError: a bytes-like object is required, not 'str'? I have this programm, but it says to me the error on the title, I think I have to put something for apply utf-8, but I don't know where or how
 #!/usr/bin/python3

import socket

status = 0

mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mySocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
mySocket.bind(('localhost', 1234))

mySocket.listen(5)

while True:
    print('Waiting for connections')
    (recvSocket, address) = mySocket.accept()
    print('HTTP request received:')
    print(recvSocket.recv(1024))
    request = recvSocket.recv(1024)

    slot = request.split(' ')

    try:
        num = int(slot[1][1:])
    except ValueError:
        msg = ("Asegurese que su URL contiene un numero al final. Ejemplo: localhost:1234/56")
        recvSocket.send("HTTP/1.1 200 OK\r\n\r\n" + "" + msg + "" + "\r\n")
        status = 0

A: send expects bytes, not string. Strings in Python 3 are unicode, you have to specify how the string should be converted to bytes. Use something like socket.send("some string".encode("utf-8")) to convert string to bytes first.


text:
Q: jQuery fade in effect on my home-made lightbox I don't really know how to solve this problem. I have this image. It is a thumnail picture, and when someone clicks on it, the bigger picture pops up. Please don't tell me I should use a downloadable lightbox, this is just perfect for me, except I want a fade in effect also when someone clicks on it, not just the popup thing.

Some text asdasdasdasd.

And this is my CSS (lightbox and underlay classes):
.underlay{
display:none;
position:fixed;
top:0;
left:0;
width:100%;
height:100%;
background-color:#000;
-moz-opacity:0.5;
opacity:.50;
filter:alpha(opacity=50);
}

.lightbox{
display:none;
position:fixed;
top:100px;
left:25%;
width:50%;
z-index:100000;
background-color:#fff;
box-shadow:0px 0px 10px 5px #161616;
text-decoration:none;
}

A: You can use fadeIn() method from jQuery : http://jsfiddle.net/WTPUj/

Some text asdasdasdasd.

fadeIn method documentation : http://api.jquery.com/fadeIn/


text:
Q: PyODConverter Fails for Files with Japanese name I am unable to use PyODConverter to convert files to other formats, if the files are having filename in Japanese or Chinese.
Break point:
document = self.desktop.loadComponentFromURL(inputUrl, "_blank", 0, self._toProperties(loadProperties))

This fails incase if the file-name is in Japanese works great for English.
Steps to regenerate the issue:

*

*file path : /home/vivek/workspace/qwiktrans/code//media/multiuploader/201401業務委託契約書QUIKSILVER様_3_55.doc

*generate inputURL using inputUrl = self._toFileUrl(inputFile)

*The input URL:
/home/vivek/workspace/qwiktrans/code//media/multiuploader/201401%E6%A5%AD%E5%8B%99%E5%A7%94%E8%A8%97%E5%A5%91%E7%B4%84%E6%9B%B8QUIKSILVER%E6%A7%98_3_55.doc
4) when you will apply this inputUrl it will Fail.
document = self.desktop.loadComponentFromURL(inputUrl, "_blank", 0, self._toProperties(loadProperties))
Error message:

com.sun.star.lang.IllegalArgumentException: Unsupported URL file:///home/vivek/workspace/qwiktrans/code/media/multiuploader/201401%E6%A5%AD%E5%8B%99%E5%A7%94%E8%A8%97%E5%A5%91%E7%B4%84%E6%9B%B8QUIKSILVER%E6%A7%98_3_55.doc: ""

Please suggest
Note: I am using Django1.4 with python2.7 on ubuntu12.04 having libreoffice and unoconv 0.6


text:
Q: Using GetHashCode to test equality in Equals override Is it ok to call GetHashCode as a method to test equality from inside the Equals override?
For example, is this code acceptable?
public class Class1
{
  public string A
  {
    get;
    set;
  }

  public string B
  {
    get;
    set;
  }

  public override bool Equals(object obj)
  {
    Class1 other = obj as Class1;
    return other != null && other.GetHashCode() == this.GetHashCode();
  }

  public override int GetHashCode()
  {
    int result = 0;
    result = (result ^ 397) ^ (A == null ? 0 : A.GetHashCode());
    result = (result ^ 397) ^ (B == null ? 0 : B.GetHashCode());
    return result;
  }
}

A: No, it is not ok, because it's not
equality <=> hashcode equality.
It's just
equality => hashcode equality.
or in the other direction:
hashcode inequality => inequality.
Quoting http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx:

If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values.

A: I would say, unless you want for Equals to basically mean "has the same hash code as" for your type, then no, because two strings may be different but share the same hash code. The probability may be small, but it isn't zero.

A: The others are right; your equality operation is broken. To illustrate:
public static void Main()
{
    var c1 = new Class1() { A = "apahaa", B = null };
    var c2 = new Class1() { A = "abacaz", B = null };
    Console.WriteLine(c1.Equals(c2));
}

I imagine you want the output of that program to be "false" but with your definition of equality it is "true" on some implementations of the CLR.
Remember, there are only about four billion possible hash codes. There are way more than four billion possible six letter strings, and therefore at least two of them have the same hash code. I've shown you two; there are infinitely many more.
In general you can expect that if there are n possible hash codes then the odds of getting a collision rise dramatically once you have about the square root of n elements in play. This is the so-called "birthday paradox". For my article on why you shouldn't rely upon hash codes for equality, click here.

A: No this is not an acceptable way to test for equality.  It is very possible for 2 non-equal values to have the same hash code.  This would cause your implementation of Equals to return true when it should return false

A: You can call GetHashCode to determine if the items are not equal, but if two objects return the same hash code, that doesn't mean they are equal.  Two items can have the same hash code but not be equal.
If it's expensive to compare two items, then you can compare the hash codes.  If they are unequal, then you can bail.  Otherwise (the hash codes are equal), you have to do the full comparison.
For example:
public override bool Equals(object obj)
  {
    Class1 other = obj as Class1;
    if (other == null || other.GetHashCode() != this.GetHashCode())
        return false;
    // the hash codes are the same so you have to do a full object compare.
  }

A: You cannot say that just because the hash codes are equal then the objects must be equal.
The only time you would call GetHashCode inside of Equals was if it was much cheaper to compute a hash value for an object (say, because you cache it) than to check for equality. In that case you could say if (this.GetHashCode() != other.GetHashCode()) return false; so that you could quickly verify that the objects were not equal.
So when would you ever do this? I wrote some code that takes screenshots at periodic intervals and tries to find how long it's been since the screen changed. Since my screenshots are 8MB and have relatively few pixels that change within the screenshot interval it's fairly expensive to search a list of them to find which ones are the same. A hash value is small and only has to be computed once per screenshot, making it easy to eliminate known non-equal ones. In fact, in my application I decided that having identical hashes was close enough to being equal that I didn't even bother to implement the Equals overload, causing the C# compiler to warn me that I was overloading GetHashCode without overloading Equals.

A: There is one case where using hashcodes as a short-cut on equality comparisons makes sense.
Consider the case where you are building a hashtable or hashset. In fact, let's just consider hashsets (hashtables extend that by also holding a value, but that isn't relevant).
There are various different approaches one can take, but in all of them you have a small number of slots the hashed values can be placed in, and we take either the open or closed approach (which just for fun, some people use the opposite jargon for to others); if we collide on the same slot for two different objects we can either store them in the same slot (but having a linked list or such for where the objects are actually stored) or by re-probing to pick a different slot (there are various strategies for this).
Now, with either approach, we're moving away from the O(1) complexity we want with a hashtable, and towards an O(n) complexity. The risk of this is inversely proportional to the number of slots available, so after a certain size we resize the hashtable (even if everything was ideal, we'd eventually have to do this if the number of items stored were greater than the number of slots).
Re-inserting the items on a resize will obviously depend on the hash codes. Because of this, while it rarely makes sense to memoise GetHashCode() in an object (it just isn't called often enough on most objects), it certainly does make sense to memoise it within the hash table itself (or perhaps, to memoise a produced result, such as if you re-hashed with a Wang/Jenkins hash to reduce the damage caused by bad GetHashCode() implementations).
Now, when we come to insert our logic is going to be something like:

*

*Get hash code for object.

*Get slot for object.

*If slot is empty, place object in it and return.

*If slot contains equal object, we're done for a hashset and have the position to replace the value for a hashtable. Do this, and return.

*Try next slot according to collision strategy, and return to item 3 (perhaps resizing if we loop this too often).

So, in this case we have to get the hash code before we compare for equality. We also have the hash code for existing objects already pre-computed to allow for resize. The combination of these two facts means that it makes sense to implement our comparison for item 4 as:
private bool IsMatch(KeyType newItem, KeyType storedItem, int newHash, int oldHash)
{
  return ReferenceEquals(newItem, storedItem) // fast, false negatives, no false positives (only applicable to reference types)
    ||
    (
      newHash == oldHash // fast, false positives, no fast negatives
      &&
      _cmp.Equals(newItem, storedItem) // slow for some types, but always correct result.
    );
}

Obviously, the advantage of this depends on the complexity of _cmp.Equals. If our key type was int then this would be a total waste. If our key type where string and we were using case-insensitive Unicode-normalised equality comparisons (so it can't even shortcut on length) then the saving could well be worth it.
Generally memoising hash codes doesn't make sense because they aren't used often enough to be a performance win, but storing them in the hashset or hashtable itself can make sense.

A: *

*It's wrong implementation, as others have stated why.

*You should short circuit the equality check using GetHashCode like:
if (other.GetHashCode() != this.GetHashCode()
    return false;

in the Equals method only if you're certain the ensuing Equals implementation is much more expensive than GetHashCode which is not vast majority of cases.

*In this one implementation you have shown (which is 99% of the cases) its not only broken, its also much slower. And the reason? Computing the hash of your properties would almost certainly be slower than comparing them, so you're not even gaining in performance terms. The advantage of implementing a proper GetHashCode is when your class can be the key type for hash tables where hash is computed only once (and that value is used for comparison). In your case GetHashCode will be called multiple times if it's in a collection. Even though GetHashCode itself should be fast, it's not mostly faster than equivalent Equals.
To benchmark, run your Equals (a proper implementation, taking out the current hash based implementation) and GetHashCode here
var watch = Stopwatch.StartNew();
for (int i = 0; i < 100000; i++)
{
    action(); //Equals and GetHashCode called here to test for performance.
}
watch.Stop();
Console.WriteLine(watch.Elapsed.TotalMilliseconds);


text:
Q: How can I change time format of a label ? Swift In my App I want to show the user the Time he needed. At the moment it looks like this:

This is the actual code:
if counter <= 59.0 {
            resultTimeLabel.text = String(format: "%.1", counter)
            resultTimeLabel.text = "in \(counter) seconds"
        }
        if counter >= 60.0 {
            let minutes = counter / 60.0
            resultTimeLabel.text = String(format: "%.1", counter)
            resultTimeLabel.text = "in \(minutes) minutes"

Which format is the right one to make it looks like: 1.5 and not 1.5000000023

A: The issue there is that you are assigning a new string over the previous formatted string and it is missing an "f" in your string format:
if counter < 60 {
    resultTimeLabel.text = "in " + String(format: "%.1f", counter) + " seconds"
}
else
if counter >= 60 {
    let minutes = counter / 60.0
    resultTimeLabel.text = "in " + String(format: "%.1f", minutes) + " minutes"


text:
Q: How to get input parameter in MainLayout?
*

*Blazor App: I have custom header logo and custom footer links that
will change, based on the input parameter {id}.

*Input parameter ID is used in a query to retrieve company logo, and
footer link information from database.
The dynamic header and footer is apart of the mainlayout, how do I get the input parameter via mainlayout?

A: Suppose you've created a Company parent component which can get a route parameter to represent a company ID, the value of which is used to retrieve the company's details that may be displayed in a child component. You may define the parent component like this:
Company.razor
@page "/company"
@page "/company/{ID}"

@code {
    [Parameter]
    public string ID { get; set; }
}

Note: The two route templates above are necessary...
Answering your question...
Add this code to the MainLayout component
@code{

    public string ID { get; set; }

    protected override void OnParametersSet()
    {
        // pull out the "ID" parameter from the route data
        object id = null;
        if ((this.Body.Target as RouteView)?.RouteData.RouteValues?.TryGetValue("ID", out id) == true)
        {
            ID = id?.ToString();
        }

    }
}

Note: The code above extricates the value of the ID parameter from the RouteData, and stores it in the ID property. Now you can do with it, whatever you want... including passing it to the the NavMenu Component if it's necessary there. This is how you can do it:
Add a Component Parameter property to the NavMenu Component, like this:
[Parameter]
public string ID { get; set; }

And add an ID component parameter attribute to the NavMenu component instance (located at the top of the MainLayout component. It should be now  <NavMenu  ID="@ID"/>
Are you happy now ?


text:
Q: going back an activity I can go to my SoundActivity class from my mainActivity, which is a menu. However when i click the device back button it does not go back to my mainActivity instead it just closes the app. I have put finish() at the end but that hasn't seemed to work. I have also tried the super.backPressed() and that hasn't worked either.
This is the code for the sound class
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.ToggleButton;

 public class SoundActivity extends Activity
    {
MediaPlayer ourSong;

private SeekBar volumeSeekbar = null;
private ToggleButton muteButton = null;
private AudioManager audioManager = null;

private AudioManager mAm;
private boolean mIsMute;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    setContentView(R.layout.soundmenu);
    initControls();

    ourSong = MediaPlayer.create(SoundActivity.this, R.raw.beat2);
    ourSong.start();

}

private void initControls()
{
    try
    {
        volumeSeekbar = (SeekBar)findViewById(R.id.sbVolumeBar);
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        volumeSeekbar.setMax(audioManager
                .getStreamMaxVolume(AudioManager.STREAM_MUSIC));
        volumeSeekbar.setProgress(audioManager
                .getStreamVolume(AudioManager.STREAM_MUSIC));

        volumeSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
        {
            public void onStopTrackingTouch(SeekBar arg0)
            {
            }

            public void onStartTrackingTouch(SeekBar arg0)
            {
            }

            public void onProgressChanged(SeekBar arg0, int progress, boolean arg2)
            {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                        progress, 0);
            }
        });

        muteButton = (ToggleButton)findViewById(R.id.toggleButton1);
        muteButton.setOnClickListener(new View.OnClickListener()
        {

            public void onClick(View v) {
                // TODO Auto-generated method stub
            if(muteButton.isChecked())
            {
                AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
                  am.setStreamMute(AudioManager.STREAM_MUSIC, true);
            }
            else
            {
                AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
                  am.setStreamMute(AudioManager.STREAM_MUSIC, false);
            }
        }
        });
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    ourSong.release();
    finish();

    }
}

If anyone could help me i would be really grateful. Confused at the moment
ok heres the mainActivity that starts sound activity
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ToggleButton;
import android.os.Bundle;

public class PinballShooterActivity extends Activity {
/** Called when the activity is first created. */
MediaPlayer ourSong;

private ToggleButton muteButton = null;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ourSong = MediaPlayer.create(PinballShooterActivity.this, R.raw.beat2);
    ourSong.start();

    Button soundBtn = (Button) findViewById(R.id.sound);
    soundBtn.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
        // TODO Auto-generated method stub
        startActivity(new Intent(PinballShooterActivity.this, SoundActivity.class));
        }
    });

    Button highScrBtn = (Button) findViewById(R.id.highscores);
    highScrBtn.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
        // TODO Auto-generated method stub
        startActivity(new Intent(PinballShooterActivity.this, HighScoreActivity.class));
        }
    });

    Button gameBtn = (Button) findViewById(R.id.startgame);
    gameBtn.setOnClickListener(new View.OnClickListener() {

         public void onClick(View v) {
        // TODO Auto-generated method stub
        startActivity(new Intent(PinballShooterActivity.this, GameActivity.class));
        }
    });
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    ourSong.release();
    finish();
    }
}

and here is the android manifest

    <uses-sdk android:minSdkVersion="10" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".SoundActivity" />
        <activity
            android:name=".HighScoreActivity" />
        <activity
            android:name=".GameActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="com.pinball.shooter.GAMEACTIVITY" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            </activity>
        <activity
            android:name=".Splash"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".PinballShooterActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action           android:name="com.pinball.shooter.faiz.PINBALLSHOOTERACTIVITY"/>

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

A: @Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    ourSong.release();
    finish();
    }
}

You have finish() in your onPause(). Everytime your SoundActivity is called, MainActivity goes to the background and its onPause() is called, which in turn calls your finish() and finishes the Activity.

A: As I pointed out in my comment above, the problem lies not in SoundActivity, but in MainActivity: when MainActivity is paused after launching SoundActivity, it finishes due to finish() in onPause():
public class PinballShooterActivity extends Activity {

    ...

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        ourSong.release();
        finish();
        }
    }

    ...

}

Simply remove finish() and your problem will be resolved.

A: Yes you can move anywhere in your application by pressing the phone back button. you just have to use the onBackPressed() method and use some lines of code  as i show u below
public void onBackPressed() {

     Intent start = new Intent(Current activity.this,on which activity you want to move .class);
        startActivity(start);
        finishActivity(0);
        }


text:
Q: OpenCV outline generation and color detection I am new to OpenCV and looking for some general guidance on how to proceed from the point I am at.
I am trying to make a program that can tell me what kind of weapon a video game character is holding. The weapons can be inspected in inventory to produce a standardized viewpoint, and color is an important differentiating factor. I know which color ranges correspond to which weapons and which shapes correspond to which weapon types.
My approach so far has been:
cvtColor RGB to GRAY then use canny edge detection with the following arguments [java]: (mat2, mat1, 5000, 5000, 7, true) - perhaps findContours or morphologyEx GRADIENT function is better for this?
get the RGB pixel colors of the whole image using a brute force approach and simply iterating through every pixel
my goal was to somehow get to the point where i have an outline of the weapon itself, then searching for the colors within just that outline to save time while still using the naive approach. I need to know the exact proportions of the colors for this analysis to be valuable, so I was thinking of implementing some sort of data structure (hash map?) to be able to quickly find the number of pixels for any given RGB range.
can anyone give me some guidance on the best way to proceed? I simply do not have the experience to decide how to proceed from here. What is the best way to accomplish my goal?
Thanks!


text:
Q: Open camera in middle of screen android for qr code I am trying to make a QR code scanner that is open in a fragment, I am using zxing library to do so. Now I can successfully open the camera to scan a QR code. However since I am using intent to open the camera it opens up another activity instead. What I am trying to do is open the camera within the fragment and only in the middle part of the screen. I am believing surface view and camera preview can help me do so but I am not sure how to implement it
public class QRscanner extends Fragment {
private IntentIntegrator qrScan;
public QRscanner() {
}
public static QRscanner newInstance(String text){
    Bundle args = new Bundle();
    QRscanner qrScanner = new QRscanner();
    qrScanner.setArguments(args);
    return qrScanner;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.qr_scanner, container, false);
    IntentIntegrator qrScan = new IntentIntegrator(getActivity());
    qrScan.initiateScan();
    return rootView;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
    if (result != null) {
        //if qrcode has nothing in it
        if (result.getContents() == null) {
            Toast.makeText(getActivity(), "Result Not Found", Toast.LENGTH_LONG).show();
        } else {
            //if qr contains data
            try {
                //converting the data to json
                JSONObject obj = new JSONObject(result.getContents());
                String testing = obj.getString("test");
                System.out.println(testing);
                //setting values to textviews
            } catch (JSONException e) {
                e.printStackTrace();
                //if control comes here
                //that means the encoded format not matches
                //in this case you can display whatever data is available on the qrcode
                //to a toast
                Toast.makeText(getActivity(), result.getContents(), Toast.LENGTH_LONG).show();
            }
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}
}

A: Please visit  ZXing  library on GitHub.
It might help you.


text:
Q: Modification of the law of large numbers for Binomial random variables. Let $(p_n)_{n \geq 1}$ be a sequence of numbers in $[0,1]$ such that $p_n \to p$. Let $(X_n)_{n \geq 1}$ be a sequence of independent random variables where $X_n \sim Bin(n,p_n)$. Is it true that $X_n/n \to p$ almost surely as $n \to \infty$? In such case, how can it be proved?

A: Ok, I think I have the answer using the following:
Lemma (approximation): Let $\eta, (\eta_n)_{n \geq 1}, (\rho_k)_{k \geq 1}$ and $(\rho_{k,n})_{k,n \geq 1}$ be random elements taking values in some metric space $(S,d)$ such that $\rho_{k,n} \to \rho_k$ in distribution (as $n \to \infty$, for $k$ fixed), and $\rho_k \to \eta$ in distribution (as $k \to \infty$). Then $\eta_n \to \eta$ in distribution (as $n \to \infty$) holds under the further condition
\begin{equation}
\lim_{k \to \infty}  \limsup_{n \to \infty} E[d(\rho_{k,n},\eta_n)\wedge 1] = 0.
\end{equation}
(The proof of the above lemma can be found in Kallenberg's Foundations of Modern Probability)
Here's my proof
Let $Z^{i}_k \sim Ber(p_k)$ independently for $i,k \geq 1$. Define $Y_{n,k} = \sum_{i=1}^{n} Z^{i}_k$ for $k,n \geq 1$ so that $X_n \overset{d}{=} Y_{n,n}$. Now by the strong law of large numbers $Y_{n,k}/n \to p_k$ a.s. (as $n \to \infty$) an by hypothesis $p_k \to p$, (notice that above limits aslo hold in distrbution).
Now,
\begin{align}
E\left[\left(\frac{Y_{n,k}}{n}-\frac{Y_{n,n}}{n}\right)^2\right] & = \frac{1}{n^2}\left( E[(Y_{n,k})^2] - 2E[Y_{n,k}]E[Y_{n,n}] + E[(Y_{n,n})^2]\right)\\
& = \frac{1}{n^2}\left( np_k(1-p_k)+(np_k)^2 - 2n^2p_kp_n + np_n(1-p_n)+(np_n)^2\right)\\
& = \frac{p_k(1-p_k)+p_n(1-p_n)}{n} + (p_k-p_n)^2
\end{align}
Thus
\begin{align}
\lim_{k \to \infty} \limsup_{n \to \infty}E\left[\left(\frac{Y_{n,k}}{n}-\frac{Y_{n,n}}{n}\right)^2\right] = \lim_{k \to \infty} (p_k-p)^2 = 0
\end{align}
By the approximation lemma
\begin{equation}
\frac{X_n}{n} \overset{d}{=} \frac{Y_{n,n}}{n} \to p \quad \text{ in distribution.}
\end{equation}
Finally, since $p$ is constant, then we can conclude $X_n/n$ converges a.s. to $p$.
Can anyone tell if this is correct?


text:
Q: H-Bridge inverter I'm trying to build a Mosfet based (IRFZ44N) inverter circuit with a tubular battery as DC source.
Inverter circuit using IRS2110 Mosfet driver

The Inverter output was fed to the LC filter circuit and then to the 12v/220v transformer. Theoretically, as far as I know, the output must be provided with the power required by the load. But in my below case, the required load demand is not fulfilled.
Experiment :
Used a 3W LED bulb across the transformer, the bulb glows but distorts the output waveform. When using 25W bulb the bulb start to fliker with the output voltage waveform across the filter as shown.
Waveform across the input of the transformer with 3W load

Waveform across transformer input with 25W load

Waveform across transformer input with 40W load

Waveform across transformer input open circuit output

I'm unable to understand where am I going wrong. The signal generation is using Atmega 328P microcontroller used to drive IRS2110 mosfet driver.
The following are my questions :
1 - Why is the output power demand not met ?
2 - Do I need to implement a DC-DC converter before the inverter stage ?
3 - How to reduce distortion at the output with load ?
4 - How to stabilize the output voltage at 230V at any load ?
Edit :
Battery specs : 12V, 150Ah (Amaron)
LC filter is used before the transformer. L = 100uH and C = 100uF

A: Can you see the problems of commutating a DC voltage with only 2 levels in a transformer with load ESR impedance referred to source with 400:1 Z ratio and ESR of battery?
Consider the also the reduced 3rd harmonic using a 3 level inverter using a centre tapped  Tfmr with dual bridges.

A: In order to take load, ur LC filter must satisfy the following..   Rload=(0.707)*sqrt(L/C).       Thus to take load reduce the inductance and increase the capacitance  and also maintain the frequency.  Then connect the transformer to the capacitor without connecting the load in the secondary and make sure that your filter output does not get distored because the inductance of the primary will affect the filter.

A: Try to to check with the filter alone , connecting the required resistive load across the filter capacitor.As per your circuit aprox 12 pk on both sides will come. Connect the load as per power required and check weather the voltage is stable and then move to transformer becoz transformer is just for voltage step up any ways power is going to be constant.


text:
Q: Nuxt3 data fetching not working after client-side navigation I am working on a Nuxt3 app locally. I have a page component [slug].vue page component for blog posts which fetches data from a Strapi endpoint. When I navigate from the home page to a blog post via <nuxt-link> I get an empty page. When I reload the page in the browser, the data gets displayed. At this point I am kinda lost and don't know what's wrong. Here is the code of the [slug].vue
<template>

    <LayoutMoContainer is-narrow>

        Loading ...

          <AtomsMoHeadline v-if="post.title" class="text-center" headline-type="h1" :text="post.title" />

    </LayoutMoContainer>

</template>

Nuxt Project Info
- Operating System: `Darwin`
- Node Version:     `v18.7.0`
- Nuxt Version:     `3.0.0-rc.6`
- Package Manager:  `yarn@1.22.19`
- Builder:          `vite`
- User Config:      `publicRuntimeConfig`, `app`, `css`, `buildModules`, `build`, `vite`
- Runtime Modules:  `-`
- Build Modules:    `@pinia/nuxt@0.3.1`

A: The problem was due to a page component having more than one root element.


text:
Q: Symfony2 : Checking for old ROLE returns true I am using FOSUserBundle for my symfony2 project. Upon registration, I check with the function below if the user has the default role ROLE_USER that FOSUB gives.
 /**
  * Returns true if user has ROLE_USER
  *
  * @return boolean
  */
 public function hasDefaultRole() {
     return ($this->hasRole('ROLE_USER'));
 }

If this function returns true, I set up a new account registration form and on submit the roles are changed and ROLE_USER is removed.
EDIT :
$user = $this->container->get('security.context')->getToken()->getUser();
...
$userManager = $this->container->get('fos_user.user_manager');
$user->removeRole("ROLE_USER");
$user->setRoles(array("ROLE_TEACHER", "ROLE_TEACHER_BASIC"));
$user->setStatus(1);
$userManager->updateUser($user);
$this->resetToken($user);

restetToken does this  :
 $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
 $this->container->get('security.context')->setToken($token);

I have checked the database and there is no role user anymore. If I logout, and login back again, $user->hasDefaultRole() still returns true. What am I not seeing here? Or is this an expected behaviour?

A: FOSUserBundle always add the default role (ROLE_USER) to the list of roles to ensure that users always have at least on role, so no matter what you do you won't be able to remove it.
FOSUserBundle\Model\User
/**
 * Returns the user roles
 *
 * @return array The roles
 */
public function getRoles()
{
    $roles = $this->roles;

    foreach ($this->getGroups() as $group) {
        $roles = array_merge($roles, $group->getRoles());
    }

    // we need to make sure to have at least one role
    $roles[] = static::ROLE_DEFAULT;

    return array_unique($roles);
}

FOSUserBundle\Model\UserInterface
const ROLE_DEFAULT = 'ROLE_USER';

Also you will never find the ROLE_USER in your database as it never actually adds it.
FOSUserBundle\Model\User
public function addRole($role)
{
    $role = strtoupper($role);
    if ($role === static::ROLE_DEFAULT) {
        return $this;
    }

    if (!in_array($role, $this->roles, true)) {
        $this->roles[] = $role;
    }

    return $this;
}