问:
javascript modify css class property while knowing only the class' name
Here's my css class:

```<code>.my-css-class-name
{
    display: block;
}
</code>```

And I have one element at my webpage that uses this class. I want to modify this element's "display" property.

I would happily do this by getting a handle to that element and then modifying what I need, BUT, I don't know the element's name - it's being randomly generated (it's a third-party extension).

So I figured I'm gonna have to get a handle to ".my-css-class-name" and modify that property directly.

How do I get there, cross-browser (major ones) solution?

Edit #1:

I'm looking for compatibility with newer browsers.

答:
A flexible getElementsByClassName function with support for browser versions that do not support the native function as thejh suggested may be what you are looking for. It would work, at least. However, for what you are doing, it may be useful to look at the document.styleSheets property. With this route, you can change the CSS rule directly, which, if it worked consistently across browsers, would be the better route here. Unfortunately, browser compatibility in this area is far from consistent, as shown here: http://www.quirksmode.org/dom/w3c_css.html

If you are still interested, have a look at this question: Changing a CSS rule-set from Javascript

Body:
Here's my css class:

.my-css-class-name
{
    display: block;
}

And I have one element at my webpage that uses this class. I want to modify this element's "display" property.

I would happily do this by getting a handle to that element and then modifying what I need, BUT, I don't know the element's name - it's being randomly generated (it's a third-party extension).

So I figured I'm gonna have to get a handle to ".my-css-class-name" and modify that property directly.

How do I get there, cross-browser (major ones) solution?

Edit #1:

I'm looking for compatibility with newer browsers.


来源: stackexchange

问:
Having Troubles with trying to fix an error I'm receiving from MYSQL
Here is the PHP Code I have that is Causing this Error, I haven't had this error come up before and I searched and looked around before posting and Couldn't find a way to get ride of the error.

PHP (WORKING PHP) :

```<code>   <?php
    require('includes/config.php');
    $username = $_SESSION['username'];

    if($_POST['username'] != $_SESSION['user']['username'])
    {
        // Define our query parameter values
        $query_params = array(
            ':username' => $_POST['username']
        );

        $stmt = $db->prepare("SELECT username FROM members WHERE username = :username");
        $stmt->execute($query_params);

        // Retrieve results (if any)
        if($stmt->rowCount() > 0)
        {
            die("This username is already in use");
        }

        try
        {
            $query_params = array(
                ':username' => $_POST['username'],
                ':last_username' => $username
            );

            // Execute the query
            $stmt = $db->prepare("UPDATE members SET username = :username WHERE username = :last_username");
            $result = $stmt->execute($query_params);
        }
        catch(PDOException $ex)
        {
            // Note: On a production website, you should not output $ex->getMessage().
            // It may provide an attacker with helpful information about your code.
            die("Failed to run query: " . $ex->getMessage());
        }
          }

?>
</code>```

HTML:

```<code>                               <div id="changeusername" class="tab-pane">
                     <h3> Change Your Username : </h3>
  <form  method="post" action="changeusername.php" autocomplete="off">
                    <input type="text" name="username" id="username" class="form-control" placeholder="New Username" autofocus  value="<?php if(isset($error)){ echo $_POST['username']; } ?>" tabindex="1">
                    <br>
                    <input type="password" name="password" id="password" class="form-control" placeholder="Confirm Your Password">
                   <br>
                    <button class="btn btn-theme btn-block" name="submit" type="submit"><i class="fa fa-lock"></i> Change Username</button>

              </form>
</code>```

Error I'm Receiving, after I input Boom2 Which is the New Username and boom1 is the oldd Username:
Failed to run query: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''boom2' WHERE username = 'boom1'' at line 1

答:
You cannot bind column names, nor have you even specified what to set the value to.

```<code>$stmt = $db->prepare("UPDATE members SET username = :username WHERE username = '$username'");
</code>```

May be what you meant. If you really want to have a variable column, you will need to sanitise it using a whitelist or something in your PHP.

By the way, you shouldn't being placing $username straight into the string, that should also be done using the prepared statement.

ContentLicense: CC BY-SA 3.0

Body:
Here is the PHP Code I have that is Causing this Error, I haven't had this error come up before and I searched and looked around before posting and Couldn't find a way to get ride of the error.

PHP (WORKING PHP) :

   <?php
    require('includes/config.php');
    $username = $_SESSION['username'];

    if($_POST['username'] != $_SESSION['user']['username'])
    {
        // Define our query parameter values
        $query_params = array(
            ':username' => $_POST['username']
        );

        $stmt = $db->prepare("SELECT username FROM members WHERE username = :username");
        $stmt->execute($query_params);

        // Retrieve results (if any)
        if($stmt->rowCount() > 0)
        {
            die("This username is already in use");
        }

        try
        {
            $query_params = array(
                ':username' => $_POST['username'],
                ':last_username' => $username
            );

            // Execute the query
            $stmt = $db->prepare("UPDATE members SET username = :username WHERE username = :last_username");
            $result = $stmt->execute($query_params);
        }
        catch(PDOException $ex)
        {
            // Note: On a production website, you should not output $ex->getMessage().
            // It may provide an attacker with helpful information about your code.
            die("Failed to run query: " . $ex->getMessage());
        }
          }

?>

HTML:

 Change Your Username :

  <form  method="post" action="changeusername.php" autocomplete="off">
                    <input type="text" name="username" id="username" class="form-control" placeholder="New Username" autofocus  value="<?php if(isset($error)){ echo $_POST['username']; } ?>" tabindex="1">

                    <input type="password" name="password" id="password" class="form-control" placeholder="Confirm Your Password">

                    <button class="btn btn-theme btn-block" name="submit" type="submit"> Change Username</button>

              </form>

Error I'm Receiving, after I input Boom2 Which is the New Username and boom1 is the oldd Username:
Failed to run query: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''boom2' WHERE username = 'boom1'' at line 1

Body:
You cannot bind column names, nor have you even specified what to set the value to.

$stmt = $db->prepare("UPDATE members SET username = :username WHERE username = '$username'");

May be what you meant. If you really want to have a variable column, you will need to sanitise it using a whitelist or something in your PHP.

By the way, you shouldn't being placing $username straight into the string, that should also be done using the prepared statement.


问:
confused with nodejs and angular
i read many articles and posts about integrating nodeJS & angular, i don't understand at all. i tried to create the server.js, mainController and index.html, the server runs well but angular is not working. i've been stuck with this for one week and i can't solve it.

here is my server.js :

```<code>var express = require('express'),
app = express(),
port = process.env.PORT || 3000;
var routes = require('./routes/routes');

app.use(express.static(__dirname + '/application')); //static path
routes(app);

app.get('/', function(req,res){
    res.sendFile(__dirname + "/application/views/index.html")
    //res.sendFile('./views/index.html');
});

app.listen(port);
console.log('server started on: ' + port);
</code>```

here is the mainController.js :

```<code>var app = angular.module('server',[]);

// App controller
app.controller('appController', ['$scope','dataServ', function($scope, Data) {

    $scope.greetings = "hello words";

    Data.get()
        .success(function(resp) {
            $scope.greetings = resp;
        });
}]);
</code>```

and this is my index.html :

```<code><!DOCTYPE html>
<html lang="en" ng-app="mainController">
<head>
    <meta charset="UTF-8">
    <title>Testing Web</title>

    <!-- LOAD JS -->
    <script src="../lib/js/angular.min.js"></script>
    <script src="../controllers/mainController.js"></script>

</head>

<body>
    <div ng-controller="appController">
        {{greetings}}
    </div>
</body>

</html>
</code>```

here is my folder structure if needed :

application

  -- controllers

  --- mainController.js

  -- lib

  --- js

  ---- angular.min.js

  -- views

  --- index.html

routes

server.js

答: In your index.html, replace the ng-app="mainController" with ng-app="server" as it expects the main module name.

Title: confused with nodejs and angular

Body:
i read many articles and posts about integrating nodeJS & angular, i don't understand at all. i tried to create the server.js, mainController and index.html, the server runs well but angular is not working. i've been stuck with this for one week and i can't solve it.

here is my server.js :

var express = require('express'),
app = express(),
port = process.env.PORT || 3000;
var routes = require('./routes/routes');

app.use(express.static(__dirname + '/application')); //static path
routes(app);

app.get('/', function(req,res){
    res.sendFile(__dirname + "/application/views/index.html")
    //res.sendFile('./views/index.html');
});

app.listen(port);
console.log('server started on: ' + port);

here is the mainController.js :

var app = angular.module('server',[]);

// App controller
app.controller('appController', ['$scope','dataServ', function($scope, Data) {

    $scope.greetings = "hello words";

    Data.get()
        .success(function(resp) {
            $scope.greetings = resp;
        });
}]);

and this is my index.html :

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Testing Web</title>

        {{greetings}}

here is my folder structure if needed :

application

  -- controllers

  --- mainController.js

  -- lib

  --- js

  ---- angular.min.js

  -- views

  --- index.html

routes

server.js


问:
How to set minDate to current date in jQuery UI Datepicker?
This is my code and it is not working correctly. I want to set minDate to the current date. How can I do it?

```<code>$("input.DateFrom").datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: 'yy-mm-dd',
    maxDate: 'today',
    onSelect: function(dateText) {
        $sD = new Date(dateText);
        $("input#DateTo").datepicker('option', 'minDate', min);
    }
</code>```

答:
I set starting date using this method, because aforesaid or other codes didn't work for me

$(document).ready(function() {
 $('#dateFrm').datepicker('setStartDate', new Date(yyyy, dd, MM));
 });```

Body:
This is my code and it is not working correctly. I want to set minDate to the current date. How can I do it?

$("input.DateFrom").datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: 'yy-mm-dd',
    maxDate: 'today',
    onSelect: function(dateText) {
        $sD = new Date(dateText);
        $("input#DateTo").datepicker('option', 'minDate', min);
    }


问:
Laravel AJAX to controller and back with data
I am making an AJAX call from a view:

```<code>function compareProducts() {
    var productIds = [];
    $('#compare-widget tbody tr').each(function(i, ele) {
        productIds[i] = $(ele).data('product-id');
    });
    $.ajax({
        url: 'product/compare',
        type: 'POST',
        data: {
            "_token": "{{ csrf_token() }}",
            productIds: productIds
        },
        success: function(result) {
        }
    });
}
</code>```

which is triggering the controller:

```<code>public function compare(Request $request)
{
    $products = Product::whereIn('id', $request->productIds)->get();
    return view('compare', compact('products'));
}
</code>```

but it is not doing anything in browser directly. When I open chrome inspector I see a OK 200 code, and when I open triggered link there, it shows fine, but I am not able to trigger redirection with AJAX.

If I do a window.location.href = "compare"; I get redirected to right page, but I no longer have access to $products

答:
You could save the products to the session and redirect to the compare page, that way you would have access to the products when you redirect to the compare page

```<code>public function compare(Request $request)
{
    $products = Product::whereIn('id', $request->productIds)->get();

    session(['products' => $products]);

    return url('compare');
}
</code>```

and in your success callback you could redirect to the compare page

```<code>success: function (result) {
    window.location.href = result;
}
</code>```

and in your compare view access the products from the session

```<code>{{ session('products') }}
</code>```

Body:
I am making an AJAX call from a view:

function compareProducts() {
    var productIds = [];
    $('#compare-widget tbody tr').each(function(i, ele) {
        productIds[i] = $(ele).data('product-id');
    });
    $.ajax({
        url: 'product/compare',
        type: 'POST',
        data: {
            "_token": "{{ csrf_token() }}",
            productIds: productIds
        },
        success: function(result) {
        }
    });
}

which is triggering the controller:

public function compare(Request $request)
{
    $products = Product::whereIn('id', $request->productIds)->get();
    return view('compare', compact('products'));
}

but it is not doing anything in browser directly. When I open chrome inspector I see a OK 200 code, and when I open triggered link there, it shows fine, but I am not able to trigger redirection with AJAX.

If I do a window.location.href = "compare"; I get redirected to right page, but I no longer have access to $products

Body:
You could save the products to the session and redirect to the compare page, that way you would have access to the products when you redirect to the compare page

public function compare(Request $request)
{
    $products = Product::whereIn('id', $request->productIds)->get();

    session(['products' => $products]);

    return url('compare');
}

and in your success callback you could redirect to the compare page

success: function (result) {
    window.location.href = result;
}

and in your compare view access the products from the session

{{ session('products') }}


问:
Finding pattern in string using indexof
Can someone tell me why this is an infinte loop?    </p>

```<code>private void splitBody()    {
        bodyparts=new Vector();
        String body = "<br />testtestest<br />fefefefefefefefefef<br />qqqqqqqqqqqq";

        int previousIndex=0;
        while(body.indexOf("<br />",previousIndex)!=-1) {
            int index=body.indexOf("<br />",previousIndex);
            System.out.println(body.substring(previousIndex, index));
            bodyparts.addElement(body.substring(previousIndex, index));
            previousIndex=index;
        }
    }
</code>```

答:
The indexOf operation return the starting position. If you want to move forward, increment the previousIndex like this.</p>

```<code>  bodyparts=new Vector();
  String body = "<br />testtestest<br />fefefefefefefefefef<br />qqqqqqqqqqqq";

  int previousIndex=0;
  while(body.indexOf("<br />",previousIndex)!=-1) {
    int index=body.indexOf("<br />",previousIndex);
    System.out.println(body.substring(previousIndex, index));
    bodyparts.addElement(body.substring(previousIndex, index));
    previousIndex=index+("<br />".size());
  }
</code>```

ContentLicense: CC BY-SA 2.5

Title: Finding pattern in string using indexof

Body:
Can someone tell me why this is an infinte loop?

private void splitBody()    {
        bodyparts=new Vector();
        String body = "
testtestest
fefefefefefefefefef
qqqqqqqqqqqq";

        int previousIndex=0;
        while(body.indexOf("
",previousIndex)!=-1) {
            int index=body.indexOf("
",previousIndex);
            System.out.println(body.substring(previousIndex, index));
            bodyparts.addElement(body.substring(previousIndex, index));
            previousIndex=index;
        }
    }

Body:
The indexOf operation return the starting position. If you want to move forward, increment the previousIndex like this.

  bodyparts=new Vector();
  String body = "<br />testtestest<br />fefefefefefefefefef<br />qqqqqqqqqqqq";

  int previousIndex=0;
  while(body.indexOf("<br />",previousIndex)!=-1) {
    int index=body.indexOf("<br />",previousIndex);
    System.out.println(body.substring(previousIndex, index));
    bodyparts.addElement(body.substring(previousIndex, index));
    previousIndex=index+("<br />".size());
  }


问:
Copy only executable files (cross platform)
I want to copy executable files from one directory to another.

The source directory includes all sorts of files I don't care about (build artifacts). I want to grab only the executable files, using a bash script that works on both OS X and Linux.

By executable, I mean a file that has the executable permission, and would pass test -x $filename.

I know I can write some python script but then I would be introducing a dependency on python (just to copy files!) which is something I really want to avoid.

Note: I've seem a couple of similar questions but the answers seem to only work on Linux (as the questions specifically asked about Linux). Please do not mark this as duplicate unless the duplicate question is indeed about cross platform copying of executable files only.

答:
Your own answer is conceptually elegant, but slow, because it creates at least one child process for every input file (test), plus an additional one for each matching file (cp).

Here's a more efficient bash alternative that:

builds up an array of matching input files in shell code,

and then copies them using a single invocation of cp.

```<code>#!/usr/bin/env bash

exeFiles=()
for f in "$src_dir"/*; do [[ -x $f && -f $f ]] && exeFiles+=( "$f" ); done
cp "${exeFiles[@]}" "$dest_dir/"
</code>```

exeFiles=() initializes the array in which to store the matching filenames.

for f in "$src_dir"/* loops over all files and directories located directly in $scr_dir; note how * must be unquoted for globbing (filename expansion) to occur.

[[ -x $f && -f $f ]] determines whether the item at hand is executable (-x) and a (regular) file -f; note that double-quoting variable references inside [[ ... ]] is (mostly) optional.

exeFiles+=( "$f" ) appends a new element to the array

"${exeFiles[@]}" refers to the resulting array as a whole and robustly expands to the array elements as individual arguments - see Bash arrays.

Body:
Your own answer is conceptually elegant, but slow, because it creates at least one child process for every input file (test), plus an additional one for each matching file (cp).

Here's a more efficient bash alternative that:

builds up an array of matching input files in shell code,

and then copies them using a single invocation of cp.

#!/usr/bin/env bash

exeFiles=()
for f in "$src_dir"/*; do [[ -x $f && -f $f ]] && exeFiles+=( "$f" ); done
cp "${exeFiles[@]}" "$dest_dir/"

exeFiles=() initializes the array in which to store the matching filenames.

for f in "$src_dir"/* loops over all files and directories located directly in $scr_dir; note how * must be unquoted for globbing (filename expansion) to occur.

[[ -x $f && -f $f ]] determines whether the item at hand is executable (-x) and a (regular) file -f; note that double-quoting variable references inside [[ ... ]] is (mostly) optional.

exeFiles+=( "$f" ) appends a new element to the array

"${exeFiles[@]}" refers to the resulting array as a whole and robustly expands to the array elements as individual arguments - see Bash arrays.


问:
C# usercontrol not updating with DispatcherTimer Tick Event
I am having issues having a UserControl update in the main page by using a DispatcherTimer to signal to get pull new data from some temperature sensors.

Sensors.xaml.cs

```<code>public sealed partial class Sensors : UserControl
{
    public Sensors()
    {
        this.InitializeComponent();
    }

    public string Sensorlbl
    {
        get { return (string)GetValue(SensorlblProperty); }
        set { SetValue(SensorlblProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Sensorlbl.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SensorlblProperty =
        DependencyProperty.Register("SensorLbl", typeof(string), typeof(Sensors), null);
</code>```

Sensors.xaml

```<code><Grid>
    <TextBlock Name="SensorLbl" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0,5,0,0" Text="{Binding Sensorlbl, ElementName=userControl, Mode=TwoWay}"/>
</Grid>
</code>```

MainPage.xaml.cs

```<code>    public MainPage()
    {
        tempTimer = new DispatcherTimer();
        tempTimer.Tick += GetTemp;
        tempTimer.Interval = TimeSpan.FromMilliseconds(1000);
        tempTimer.Start();

        Sensor1.Sensorlbl = "test";
    }
    public void GetTemp(object sender, object e)
    {
        Sensor1.Sensorlbl = "Test Working";

        Debug.WriteLine(Sensor1.Sensorlbl);
    }
</code>```

MainPage.xaml

```<code><local:Sensors x:Name="Sensor1" Margin="0,0,0,0" Width="107" Height="155" />
</code>```

With the above example I am just using that to try to prove out updating the UserControl being used within MainPage. When I run the program I get an output of "Test Working" but the screen still only shows "test".

Thanks for any advice.

答: The registration for a DependencyProperty is case sensitive. It has to match precisely the name of the property. In your case you have a mismatch: SensorLbl vs Sensorlbl.</p>

Body:
I am having issues having a UserControl update in the main page by using a DispatcherTimer to signal to get pull new data from some temperature sensors.

Sensors.xaml.cs

public sealed partial class Sensors : UserControl
{
    public Sensors()
    {
        this.InitializeComponent();
    }

    public string Sensorlbl
    {
        get { return (string)GetValue(SensorlblProperty); }
        set { SetValue(SensorlblProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Sensorlbl.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SensorlblProperty =
        DependencyProperty.Register("SensorLbl", typeof(string), typeof(Sensors), null);

Sensors.xaml

<Grid>
    <TextBlock Name="SensorLbl" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0,5,0,0" Text="{Binding Sensorlbl, ElementName=userControl, Mode=TwoWay}"/>
</Grid>

MainPage.xaml.cs

    public MainPage()
    {
        tempTimer = new DispatcherTimer();
        tempTimer.Tick += GetTemp;
        tempTimer.Interval = TimeSpan.FromMilliseconds(1000);
        tempTimer.Start();

        Sensor1.Sensorlbl = "test";
    }
    public void GetTemp(object sender, object e)
    {
        Sensor1.Sensorlbl = "Test Working";

        Debug.WriteLine(Sensor1.Sensorlbl);
    }

MainPage.xaml

<local:Sensors x:Name="Sensor1" Margin="0,0,0,0" Width="107" Height="155" />

With the above example I am just using that to try to prove out updating the UserControl being used within MainPage. When I run the program I get an output of "Test Working" but the screen still only shows "test".

Thanks for any advice.


问:
Message prompted up onsubmit return validate but form still submits
I am having some issues which is quite similar referring to this onsubmit return false does not work, form still submits?
I've followed the solution but if I changed it to onclick, it won't work, not even a message prompts out.

Script that I am using.

```<code><script>
function validate()
{
  var validate = false;
  if(document.getElementById("nameId").value == "")
  {
    alert("NAME IS REQUIRED");
    validate   = false
  }

return true ;
}

</script>
</code>```

My codes are attached in below.

```<code><table class="<?php echo $table_style_3;?>" style='width: auto;'>
<form action="fhd_add_type.php" method="post" class="form-horizontal"   onsubmit="return validate()"> //This is the part where i've changed to onclick
<input type='hidden' name='nacl' value='<?php echo $nacl;?>'>
<input type='hidden' name='type' value='<?php echo $type;?>'>
<?php
if ($type <> 0) { ?>
    <tr><td>Name: </td><td><input type='text' name='type_name' id = "nameId"></td></tr> //This is the field where need to be validate
    <tr><td colspan='2'><input type='submit' value='add' class='btn btn-primary'></td></tr>
    </table>
<?php  }
if ($type == 0) { ?>
    <tr><td>Name</td><td><input type='text' name='type_name' id = "nameId"></td></tr> //This is the field where need to be validate
    <tr><td>Email</td><td><input type='text' name='type_email'></td></tr>
    <tr><td>Location</td><td><input type='text' name='type_location'></td></tr>
    <tr><td>Phone</td><td><input type='text' name='type_phone'></td></tr>
    <tr><td colspan='2'><input type='submit' value='add' class='btn btn-primary'></td></tr>
    </table>
<?php }?>
</form>
</table>
</code>```

答:
I think this is because you're always returning true. In your JS, try this:

```<code><script>
function validate()
{
  var validate = true;
  if(document.getElementById("nameId").value == "") {
       alert("NAME IS REQUIRED");
       validate = false;
    }

    return validate;
}
</script>
</code>```

Body:
I am having some issues which is quite similar referring to this onsubmit return false does not work, form still submits?
I've followed the solution but if I changed it to onclick, it won't work, not even a message prompts out.

Script that I am using.

My codes are attached in below.

<table class="<?php echo $table_style_3;?>" style='width: auto;'>
<form action="fhd_add_type.php" method="post" class="form-horizontal"   onsubmit="return validate()"> //This is the part where i've changed to onclick
<input type='hidden' name='nacl' value='<?php echo $nacl;?>'>
<input type='hidden' name='type' value='<?php echo $type;?>'>
<?php
if ($type <> 0) { ?>

Name: 	<input type='text' name='type_name' id = "nameId">
 //This is the field where need to be validate

<input type='submit' value='add' class='btn btn-primary'>

<?php  }
if ($type == 0) { ?>

Name	<input type='text' name='type_name' id = "nameId">
 //This is the field where need to be validate

Email	<input type='text' name='type_email'>

Location	<input type='text' name='type_location'>

Phone	<input type='text' name='type_phone'>

<input type='submit' value='add' class='btn btn-primary'>

<?php }?>
</form>

Body:
I think this is because you're always returning true. In your JS, try this:

<script>
function validate()
{
  var validate = true;
  if(document.getElementById("nameId").value == "") {
       alert("NAME IS REQUIRED");
       validate = false;
    }

    return validate;
}
</script>


答:
Well you always return true from Validate(). It should be more like the following:

```<code><script>
function validate()
{
  var valid = true;
  if(document.getElementById("nameId").value == "")
  {
    alert("NAME IS REQUIRED");
    valid = false;
  }

  return valid;
}

</script>
</code>```

Title: Message prompted up onsubmit return validate but form still submits

Body:
Well you always return true from Validate(). It should be more like the following:

<script>
function validate()
{
  var valid = true;
  if(document.getElementById("nameId").value == "")
  {
    alert("NAME IS REQUIRED");
    valid = false;
  }

  return valid;
}

</script>


问:
Creating standalone app with Microsoft Access
Once I saw a DB made in MS Access that worked as a normal program, i.e with an executable file that opened a beautiful UI and allowed access to the forms and reports. I've trying to do the same, I even googled but didn't find how do it. Anyone knows how to build such standalone App with Access?</p>

答:
You cant make an access database into an executable file. It just cant happen however you can fool people into thinking that they are not using access a number of ways, for example

Custom splash screen (just put a bmp
file in the folder and name it the
same as your database)

Hide the access window and toolbars

Change the access icon

For example take a look at this screen shot

There are lots of things going on here and it would be hard to tell that it is built using good old access 97 (Yes I know the standard toolbar kind of gives it away, it will be going at somepoint).


问:
Can't get my head around some lambda expressions in Java 8
I have this snippet of code that looks like this without using lambda expressions:

```<code>.map(new Function<List<Post>, List<Post>>() {
    @Override
    public List<Post> apply(List<Post> posts) throws Exception {
        return realm.where(Post.class).equalTo(DatabaseContract.PostTable.USER_ID, userId).findAll();
    }
})
.onErrorResumeNext(new Function<Throwable, ObservableSource<? extends List<Post>>>() {
    @Override
    public ObservableSource<? extends List<Post>> apply(Throwable throwable) throws Exception {
        Log.d("rafael", throwable.getMessage());
        return getLocalPostsObservable(userId, page);
    }
})
</code>```

Using lambda expression (converted using Intellij feature) it becomes:

```<code>.map((Function<List<Post>, List<Post>>) posts -> realm.where(Post.class).equalTo(DatabaseContract.PostTable.USER_ID, userId).findAll())
.onErrorResumeNext(throwable -> {
    Log.d("rafael", throwable.getMessage());
    return getLocalPostsObservable(userId, page);
})
</code>```

What I don't understand that why the type casting in map() from posts to Function<List<Post>, List<Post>> in

```<code>(Function<List<Post>, List<Post>>) posts -> realm.where(Post.class).equalTo(DatabaseContract.PostTable.USER_ID, userId).findAll()
</code>```

Where at the same time there's no type casting in the second expression:

```<code>throwable -> {
    Log.d("rafael", throwable.getMessage());
    return getLocalPostsObservable(userId, page);
}
</code>```

答:
It's not the posts that is casted, but the entire lambda expression and because it does not fail compilation we can deduce that posts is actually of type List<Post> and findAll is also returning List<Post>.

Could it be because of chaining methods like:

```<code>where(..).equalTo(..).findAll(..)
</code>```

You can test if this is the case by taking that code inside a method that returns List<Post> and inside your lambda expression use that method instead. If intelli does not add a cast - the problem is there.

Body:
I have this snippet of code that looks like this without using lambda expressions:

.map(new Function<List<Post>, List<Post>>() {
    @Override
    public List<Post> apply(List<Post> posts) throws Exception {
        return realm.where(Post.class).equalTo(DatabaseContract.PostTable.USER_ID, userId).findAll();
    }
})
.onErrorResumeNext(new Function<Throwable, ObservableSource<? extends List<Post>>>() {
    @Override
    public ObservableSource<? extends List<Post>> apply(Throwable throwable) throws Exception {
        Log.d("rafael", throwable.getMessage());
        return getLocalPostsObservable(userId, page);
    }
})

Using lambda expression (converted using Intellij feature) it becomes:

.map((Function<List<Post>, List<Post>>) posts -> realm.where(Post.class).equalTo(DatabaseContract.PostTable.USER_ID, userId).findAll())
.onErrorResumeNext(throwable -> {
    Log.d("rafael", throwable.getMessage());
    return getLocalPostsObservable(userId, page);
})

What I don't understand that why the type casting in map() from posts to Function<List<Post>, List<Post>> in

(Function<List<Post>, List<Post>>) posts -> realm.where(Post.class).equalTo(DatabaseContract.PostTable.USER_ID, userId).findAll()

Where at the same time there's no type casting in the second expression:

throwable -> {
    Log.d("rafael", throwable.getMessage());
    return getLocalPostsObservable(userId, page);
}

Body:
It's not the posts that is casted, but the entire lambda expression and because it does not fail compilation we can deduce that posts is actually of type List<Post> and findAll is also returning List<Post>.

Could it be because of chaining methods like:

where(..).equalTo(..).findAll(..)

You can test if this is the case by taking that code inside a method that returns List<Post> and inside your lambda expression use that method instead. If intelli does not add a cast - the problem is there.


问:
Get file url schema
How do I show the user a previously uploaded file that is stored on the website's server (I am aware uploaded files should be stored on a different server) when I know the path? To explain; below in my code I have created a button inside an  element and I am trying to get it to display the relevant file to the user by putting the relevant url in the  element shows the user the file they need to see. </p>

```<code><!DOCTYPE html>
<html>

<head>
   <meta charset="utf-8">
    <title>Total </title>
      <link type="text/css" rel="stylesheet" href="course.css">
       <script src="../jquery.js"></script>
        <script src="../jquery-ui.js"></script>

</head>
<body>

<?php
    if ($handle = opendir('../uploads'))
    {
      while (false !== ($entry = readdir($handle)))
     {

      if ($entry != "." && $entry != "..")
      {

          $real=realpath("../uploads/".$entry);

            echo  "<button class='files accordian'>$entry $real</button>
                     <div class='panel'>
                        <p>$real</p>";
            echo '<a href="WHAT WOULD GO IN HERE?"><button class="current-file" name="sent" value="View-Current-File"><img class="view-file-img" src="../images/magnify.png">View Current File</button></a>';
      }

    }
 }

 ?>

</body>
</html>
</code>```

答:
Looks like you are using $real before you define it.

```<code>echo  "<button class='files accordian'>$entry $real</button>";
$real=realpath("../uploads/".$entry);
</code>```

This should be the other way.

If you still have problems, do this and check the result.

```<code>var_dump(realpath("../uploads/".$entry));
</code>```

Title: Get file url schema

Body:
How do I show the user a previously uploaded file that is stored on the website's server (I am aware uploaded files should be stored on a different server) when I know the path? To explain; below in my code I have created a button inside an  element and I am trying to get it to display the relevant file to the user by putting the relevant url in the  element shows the user the file they need to see.

<!DOCTYPE html>

   <meta charset="utf-8">
    <title>Total </title>
      <link type="text/css" rel="stylesheet" href="course.css">

<?php
    if ($handle = opendir('../uploads'))
    {
      while (false !== ($entry = readdir($handle)))
     {

      if ($entry != "." && $entry != "..")
      {

          $real=realpath("../uploads/".$entry);

            echo  "<button class='files accordian'>$entry $real</button>

$real
";
            echo '<button class="current-file" name="sent" value="View-Current-File">View Current File</button>';
      }

    }
 }

 ?>

Body:
Looks like you are using $real before you define it.

echo  "<button class='files accordian'>$entry $real</button>";
$real=realpath("../uploads/".$entry);

This should be the other way.

If you still have problems, do this and check the result.

var_dump(realpath("../uploads/".$entry));


答:
solved your issue

```<code><script>
function validate()
{
  var validate = false;
  if(document.getElementById("nameId").value == "")
{
   alert("NAME IS REQUIRED");
   return false;
   //validate   = false
}

return true ;
}

</script>
</code>```

**update your script by this script
**

Body:
solved your issue

<script>
function validate()
{
  var validate = false;
  if(document.getElementById("nameId").value == "")
{
   alert("NAME IS REQUIRED");
   return false;
   //validate   = false
}

return true ;
}

</script>

**update your script by this script
**


问:
Using beautiful soup to obtain class contents with a conditional
I would like to use beautiful soup to find tags where the child tags(gains or losses) are greater than 0. I would then like to print the contents of the inner tags "gains" "losses" and "band.textualrepresentation". This is essentially the script I want (although this one doesn't work).

```<code>import sys
from BeautifulSoup import BeautifulSoup as Soup

def parseLog(file):
        file = sys.argv[1]
        handler = open(file).read()
        soup = Soup(handler)
        for anytype in soup('anytype', 'gains'.string>0 || 'losses'.string>0):
                gain = anytype.gains.string
                loss = anytype.losses.string
                band = anytype.band.textualrepresentation.string
                print gain loss band

parseLog(sys.argv[1])
</code>```

I am running into troubles early on, I can't even print the contents of gains, let alone print the contents that meet a certain criteria. My current Script

```<code>def parseLog(file):
        file = sys.argv[1]
        handler = open(file).read()
        soup = Soup(handler)
        for anytype in soup.findall('anytype'):
                gain = anytype.fetch('gains')
                print gain

parseLog(sys.argv[1])
</code>```

returns

```<code>Traceback (most recent call last):
  File "./soup.py", line 13, in <module>
    parseLog(sys.argv[1])
  File "./soup.py", line 9, in parseLog
    for anytype in soup.findall('anytype'):
TypeError: 'NoneType' object is not callable
</code>```

.

Sample Input

```<code>      <anytype xsi:type="GainLossStruct">
         <band>
          <textualrepresentation>
           22q11.1
          </textualrepresentation>
         </band>
         <gains>
          2
         </gains>
         <losses>
          1
         </losses>
         <structs>
          0
         </structs>
        </anytype>
        <anytype xsi:type="GainLossStruct">
         <band>
          <textualrepresentation>
           22q11.2
          </textualrepresentation>
         </band>
         <gains>
          0
         </gains>
         <losses>
          1
         </losses>
         <structs>
          0
         </structs>
        </anytype>
        <anytype xsi:type="GainLossStruct">
         <band>
          <textualrepresentation>
           22q12
          </textualrepresentation>
         </band>
         <gains>
          0
         </gains>
         <losses>
          0
         </losses>
         <structs>
          0
         </structs>
        </anytype>
</code>```

Sample output

```<code>2  1  22q11.1
0  1  22q11.2
</code>```

.

.

Update
The current solution

```<code>import sys
from BeautifulSoup import BeautifulSoup as Soup

def parseLog(file):
        file = sys.argv[1]
        handler = open(file).read()
        soup = Soup(handler)
        for anytype in soup(lambda x: x.name=='anytype' and (hasattr(x, 'gains') and int(x.gains.string) > 0 or hasattr(x, 'losses') and int(x.losses.string) > 0)):
                gain = anytype.gains.string
                loss = anytype.losses.string
                band = anytype.band.textualrepresentation.string
                print gain, loss, band

parseLog(sys.argv[1])
</code>```

Still returns the error

```<code>Traceback (most recent call last):
  File "./soup.py", line 15, in <module>
    parseLog(sys.argv[1])
  File "./soup.py", line 9, in parseLog
    for anytype in soup(lambda x: x.name=='anytype' and (hasattr(x, 'gains') and int(x.gains.string) > 0 or hasattr(x, 'losses') and int(x.losses.string) > 0)):
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 659, in __call__
    return apply(self.findAll, args, kwargs)
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 849, in findAll
    return self._findAll(name, attrs, text, limit, generator, **kwargs)
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 377, in _findAll
    found = strainer.search(i)
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 966, in search
    found = self.searchTag(markup)
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 924, in searchTag
    or (markup and self._matches(markup, self.name)) \
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 983, in _matches
    result = matchAgainst(markup)
  File "./soup.py", line 9, in <lambda>
    for anytype in soup(lambda x: x.name=='anytype' and (hasattr(x, 'gains') and int(x.gains.string) > 0 or hasattr(x, 'losses') and int(x.losses.string) > 0)):
AttributeError: 'NoneType' object has no attribute 'string'
</code>```

Even when I reduce the for loop to

```<code>for anytype in soup(lambda x: x.name=='anytype' and (hasattr(x, 'gains'))):
        gain = anytype.gains.string
        print gain
</code>```

I still get

```<code>Traceback (most recent call last):
  File "./soup.py", line 13, in <module>
    parseLog(sys.argv[1])
  File "./soup.py", line 10, in parseLog
    gain = anytype.gains.string
AttributeError: 'NoneType' object has no attribute 'string'
</code>```

答:
I would parse the entire document into a pandas dataframe, then do whatever manipulations after; this might make the data-cleanup process more transparent and easy to understand.

I'm going to use xmltojson here since I'm not familiar with beautiful soup (although I had to enclose the whole thing in "document" tags since to make it valid XML):

```<code>import xmltojson
import pandas as pd

with open(file) as f:
    j = eval(xmltojson.parse("<document> "+ f.read() + "</document>"))

df = pd.io.json.json_normalize(j['document']['anytype'])
df.columns = ['type', 'band', 'gain', 'loss', 'struct']
df[(df.gain > '0') | (df.loss > '0')][['band', 'gain', 'loss']]

      band gain loss
0  22q11.1    2    1
1  22q11.2    0    1
</code>```

Body:
I would like to use beautiful soup to find tags where the child tags(gains or losses) are greater than 0. I would then like to print the contents of the inner tags "gains" "losses" and "band.textualrepresentation". This is essentially the script I want (although this one doesn't work).

import sys
from BeautifulSoup import BeautifulSoup as Soup

def parseLog(file):
        file = sys.argv[1]
        handler = open(file).read()
        soup = Soup(handler)
        for anytype in soup('anytype', 'gains'.string>0 || 'losses'.string>0):
                gain = anytype.gains.string
                loss = anytype.losses.string
                band = anytype.band.textualrepresentation.string
                print gain loss band

parseLog(sys.argv[1])

I am running into troubles early on, I can't even print the contents of gains, let alone print the contents that meet a certain criteria. My current Script

def parseLog(file):
        file = sys.argv[1]
        handler = open(file).read()
        soup = Soup(handler)
        for anytype in soup.findall('anytype'):
                gain = anytype.fetch('gains')
                print gain

parseLog(sys.argv[1])

returns

Traceback (most recent call last):
  File "./soup.py", line 13, in <module>
    parseLog(sys.argv[1])
  File "./soup.py", line 9, in parseLog
    for anytype in soup.findall('anytype'):
TypeError: 'NoneType' object is not callable

.

Sample Input

      <anytype xsi:type="GainLossStruct">
         <band>
          <textualrepresentation>
           22q11.1
          </textualrepresentation>
         </band>
         <gains>
          2
         </gains>
         <losses>
          1
         </losses>
         <structs>
          0
         </structs>
        </anytype>
        <anytype xsi:type="GainLossStruct">
         <band>
          <textualrepresentation>
           22q11.2
          </textualrepresentation>
         </band>
         <gains>
          0
         </gains>
         <losses>
          1
         </losses>
         <structs>
          0
         </structs>
        </anytype>
        <anytype xsi:type="GainLossStruct">
         <band>
          <textualrepresentation>
           22q12
          </textualrepresentation>
         </band>
         <gains>
          0
         </gains>
         <losses>
          0
         </losses>
         <structs>
          0
         </structs>
        </anytype>

Sample output

2  1  22q11.1
0  1  22q11.2

.

.

Update
The current solution

import sys
from BeautifulSoup import BeautifulSoup as Soup

def parseLog(file):
        file = sys.argv[1]
        handler = open(file).read()
        soup = Soup(handler)
        for anytype in soup(lambda x: x.name=='anytype' and (hasattr(x, 'gains') and int(x.gains.string) > 0 or hasattr(x, 'losses') and int(x.losses.string) > 0)):
                gain = anytype.gains.string
                loss = anytype.losses.string
                band = anytype.band.textualrepresentation.string
                print gain, loss, band

parseLog(sys.argv[1])

Still returns the error

Traceback (most recent call last):
  File "./soup.py", line 15, in <module>
    parseLog(sys.argv[1])
  File "./soup.py", line 9, in parseLog
    for anytype in soup(lambda x: x.name=='anytype' and (hasattr(x, 'gains') and int(x.gains.string) > 0 or hasattr(x, 'losses') and int(x.losses.string) > 0)):
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 659, in __call__
    return apply(self.findAll, args, kwargs)
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 849, in findAll
    return self._findAll(name, attrs, text, limit, generator, **kwargs)
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 377, in _findAll
    found = strainer.search(i)
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 966, in search
    found = self.searchTag(markup)
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 924, in searchTag
    or (markup and self._matches(markup, self.name)) \
  File "/Users/jacob/homebrew/lib/python2.7/site-packages/BeautifulSoup.py", line 983, in _matches
    result = matchAgainst(markup)
  File "./soup.py", line 9, in <lambda>
    for anytype in soup(lambda x: x.name=='anytype' and (hasattr(x, 'gains') and int(x.gains.string) > 0 or hasattr(x, 'losses') and int(x.losses.string) > 0)):
AttributeError: 'NoneType' object has no attribute 'string'

Even when I reduce the for loop to

for anytype in soup(lambda x: x.name=='anytype' and (hasattr(x, 'gains'))):
        gain = anytype.gains.string
        print gain

I still get

Traceback (most recent call last):
  File "./soup.py", line 13, in <module>
    parseLog(sys.argv[1])
  File "./soup.py", line 10, in parseLog
    gain = anytype.gains.string
AttributeError: 'NoneType' object has no attribute 'string'

Body:
I would parse the entire document into a pandas dataframe, then do whatever manipulations after; this might make the data-cleanup process more transparent and easy to understand.

I'm going to use xmltojson here since I'm not familiar with beautiful soup (although I had to enclose the whole thing in "document" tags since to make it valid XML):

import xmltojson
import pandas as pd

with open(file) as f:
    j = eval(xmltojson.parse("<document> "+ f.read() + "</document>"))

df = pd.io.json.json_normalize(j['document']['anytype'])
df.columns = ['type', 'band', 'gain', 'loss', 'struct']
df[(df.gain > '0') | (df.loss > '0')][['band', 'gain', 'loss']]

      band gain loss
0  22q11.1    2    1
1  22q11.2    0    1


问:
CucumberJS / Protractor with the angular CLI
The lack of documentation for setting Cucumberjs support with the new angular is pretty upsetting.. I am wondering how we can set up cucumber instead of just plain protractor, so that way when we run our tests using the ng e2e command, it picks up feature files.

I am wondering if anyone has any experience setting this up since the introduction of typescript has changed the framework completely.. Has anyone had any success in this? I would essentially like to see an example of setting up the conf files and creating step definitions and page objects. Any help would be much appreciated!! Thanks guys

答:
I'm working on a Angular 2+ project with Angular Seed, but that won't differ much from the setup for Angular CLI.

I'm using this boilerplate I've created for my customer that has:

Typescript

CucumberJS 2 support

reporting

There is no example for a pageobject in it, but that's not much different from the "old" setup and secondly the boilerplate is just for the basic e2e setup, not for a complete coding guide ;-).

Hope it helps


问:
All input forms in MaterializeCSS in electron look smashed
Okay, so when I follow the directions here for getting started with Materialize CSS, my input form always turns out like this:

My current index.html file is this:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>IRS</title>

    <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <!--Import materialize.css-->
    <link rel="stylesheet" href="node_modules/materialize-css/css/ghpages-materialize.css">

    <!--Import jQuery before materialize.js-->
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script type="text/javascript" src="node_modules/materialize-css/js/materialize.js"></script>
  </head>

  <body>
    <div class="input-field">
      <input placeholder="Placeholder" id="first_name" type="text" class="validate">
      <label for="first_name">First Name</label>
    </div>
  </body>
</html>
</code>```

My electron version is 1.6.6 and node is at 6.10.3

答:
Add "active" class to the  tag and try

```<code> <div class="input-field">
          <input placeholder="Placeholder" id="first_name" type="text" class="validate">
          <label for="first_name" class="active">First Name</label>
        </div>
</code>```

if you want only label animation, remove the placeholder for the <input> tag

Hope it works..

Body:
Okay, so when I follow the directions here for getting started with Materialize CSS, my input form always turns out like this:

My current index.html file is this:

<!DOCTYPE html>

    <title>IRS</title>

    <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    <link rel="stylesheet" href="node_modules/materialize-css/css/ghpages-materialize.css">

      <input placeholder="Placeholder" id="first_name" type="text" class="validate">
      First Name

My electron version is 1.6.6 and node is at 6.10.3

Body:
Add "active" class to the  tag and try

 <div class="input-field">
          <input placeholder="Placeholder" id="first_name" type="text" class="validate">
          <label for="first_name" class="active">First Name</label>
        </div>

if you want only label animation, remove the placeholder for the <input> tag

Hope it works..


问:
Automatic JSON serialization and deserialization of objects in Swift
I'm looking for a way to automatically serialize and deserialize class instances in Swift. Let's assume we have defined the following class …

```<code>class Person {
    let firstName: String
    let lastName: String

    init(firstName: String, lastName: String) {
        self.firstName = firstName
        self.lastName = lastName
    }
}
</code>```

… and Person instance:

```<code>let person = Person(firstName: "John", lastName: "Doe")
</code>```

The JSON representation of person would be the following:

```<code>{
    "firstName": "John",
    "lastName": "Doe"
}
</code>```

Now, here are my questions:

How can I serialize the person instance and get the above JSON without having to manually add all properties of the class to a dictionary which gets turned into JSON?

How can I deserialize the above JSON and get back an instantiated object that is statically typed to be of type Person? Again, I don't want to map the properties manually.

Here's how you'd do that in C# using Json.NET:

```<code>var person = new Person("John", "Doe");
string json = JsonConvert.SerializeObject(person);
// {"firstName":"John","lastName":"Doe"}

Person deserializedPerson = JsonConvert.DeserializeObject<Person>(json);
</code>```

答:
As shown in WWDC2017 @ 24:48 (Swift 4), we will be able to use the Codable protocol. Example

```<code>public struct Person : Codable {
   public let firstName:String
   public let lastName:String
   public let location:Location
}
</code>```

To serialize

```<code>let payload: Data = try JSONEncoder().encode(person)
</code>```

To deserialize

```<code>let anotherPerson = try JSONDecoder().decode(Person.self, from: payload)
</code>```

Note that all properties must conform to the Codable protocol.

An alternative can be JSONCodable which is used by Swagger's code generator.

Body:
I'm looking for a way to automatically serialize and deserialize class instances in Swift. Let's assume we have defined the following class …

class Person {
    let firstName: String
    let lastName: String

    init(firstName: String, lastName: String) {
        self.firstName = firstName
        self.lastName = lastName
    }
}

… and Person instance:

let person = Person(firstName: "John", lastName: "Doe")

The JSON representation of person would be the following:

{
    "firstName": "John",
    "lastName": "Doe"
}

Now, here are my questions:

How can I serialize the person instance and get the above JSON without having to manually add all properties of the class to a dictionary which gets turned into JSON?

How can I deserialize the above JSON and get back an instantiated object that is statically typed to be of type Person? Again, I don't want to map the properties manually.

Here's how you'd do that in C# using Json.NET:

var person = new Person("John", "Doe");
string json = JsonConvert.SerializeObject(person);
// {"firstName":"John","lastName":"Doe"}

Person deserializedPerson = JsonConvert.DeserializeObject<Person>(json);

Body:
As shown in WWDC2017 @ 24:48 (Swift 4), we will be able to use the Codable protocol. Example

public struct Person : Codable {
   public let firstName:String
   public let lastName:String
   public let location:Location
}

To serialize

let payload: Data = try JSONEncoder().encode(person)

To deserialize

let anotherPerson = try JSONDecoder().decode(Person.self, from: payload)

Note that all properties must conform to the Codable protocol.

An alternative can be JSONCodable which is used by Swagger's code generator.

ContentLicense: CC BY-SA 4.0


问:
Delete row with foreign key constraints and no cascade deleting SQL
Trying to figure out how to delete a row in a SQL table that has multiple foreign keys pointing to it, and more keys pointing to those, etc, etc. Cascading Deletes aren't turned on (I have no control to turn them on), and I'm trying to avoid performing a delete on EVERY single row that is affected by this one delete.

So if I have table XXX, with columns YYY and ZZZ, where YYY is the primary key and ZZZ is a column that has multiple foreign keys pointing to it, how would I go about deleting a row based on the primary key value?

Syntax would be:
DELETE FROM XXX
WHERE YYY = some_value

Is this even possible (without performing a ton of individual deletes)? And if so, how would I do it?

答:
How about turning off the foreign key constraint check?

```<code>SET FOREIGN_KEY_CHECKS = 0;
</code>```

Then turning it on back when you delete the row?

```<code>SET FOREIGN_KEY_CHECKS = 1;
</code>```

Body:
How about turning off the foreign key constraint check?

SET FOREIGN_KEY_CHECKS = 0;

Then turning it on back when you delete the row?

SET FOREIGN_KEY_CHECKS = 1;


问:
Headroom.js header with initial static state
I'm using the awesome Headroom.js plugin to build an auto-hiding header. The header is static from start and becomes pinned after an offset (when scrolling down) and then back to static (when it's back to the top).

Here is what I have done:
http://codepen.io/netgloo/pen/KmGpBL

but I got 2 problems:

scrolling down from top: when the header becomes pinned, I see it slides down and suddenly slides up

scrolling up from middle page: when the header arrives to the offset it disappears, but I need keeping it pinned to the top

Someone could give me some help or ideas?
Thanks

Here is how I initialize the plugin:

```<code>var myElement = document.querySelector("header");

var headroom  = new Headroom(myElement, {
  "offset": 150,
  "tolerance": 0,
});

headroom.init();
</code>```

答:
The headroom.js script mainly handles the addition/removal of some classes for you. It's up to you to add the appropriate styles to achieve the effect you want. Let's start with the simplest part, the HTML:

HTML

```<code><header>
  Header
</header>
</code>```

That's it!

Now for the JS setup:

JS

```<code>var myElement = document.querySelector("header");

var headroom  = new Headroom(myElement, {
  "offset": 220,
  "tolerance": {
    up: 0,
    down: 0
  },
  "classes": {
    "initial": "header--fixed",
    "pinned": "slideDown",
    "unpinned": "slideUp",
    "top": "top",
    "notTop" : "not-top",
  }
});

headroom.init();
</code>```

The first line selects the header element. The second creates a new Headroom object using the configuration values. I've set the values based on the effect it sounds like you're trying to achieve - the header should slide away when the page is scrolled down quickly, and should slide into view when the page is scrolled up.

The offset of 205px is the distance from the top when the header can become unpinned.

The tolerance of 5px is the scroll tolerance before the state changes.

And finally we're going to define the classes that will be added to the element for the different states. At the start the element will be assigned a class of header--fixed. When pinned, the element will receive the additional slideDown class. And when unpinned the element will receive the additional slideUp class.

The final line initializes the headroom object.

Using the state-based classes we can now create the CSS needed to achieve the effect you want.

CSS

We'll start with the .header--fixed class:

```<code>.header--fixed {
  position: absolute;
  top: 0;
  width: 100%;
}

main {
  padding-top: 110px;
}
</code>```

This sets the initial placement of the header (at the top) and sets a padding for the main content of the page so it's not covered by the header.

Next we need to define the styles for various states - .top, .not-top, .slideDown and .slideUp:

```<code>.header--fixed.top {
  transition: none;
  transform: translateY(0);
}
.header--fixed.not-top {
  position: fixed;
  transform: translateY(-100%);
}
.header--fixed.slideDown.not-top {
  transition: transform 0.3s ease-in-out;
  transform: translateY(0);
}
.header--fixed.slideDown.top {
  transition: transform 0.3s ease-in-out;
  position: fixed;
}
.header--fixed.slideUp.not-top {
  transition: transform 0.3s ease-in-out;
  transform: translateY(-100%);
}
.header--fixed.slideUp.top {
  transform: translateY(-100%);
  position: absolute;
}
</code>```

Most of these styles are related to setting the position and transition for each state. In short, the .not-top class is applied when the page is scrolled below the header. .top is applied when the page is scrolled near the top (within the height of the header).

In addition to this critical CSS you would need the CSS for the styling of the header - a background color, font, etc. This could be applied by targeting the header element, or header--fixed class.

The final piece, and crux of the problem is resetting the header when the page is scrolled back to the very top - ie a window.pageYOffset of 0. When the page reaches this point, we need to remove the .slideDown class so the header scrolls with the page.

```<code>window.addEventListener('scroll', function() {
  if (window.pageYOffset === 0) {
    myElement.classList.remove('slideDown')
  }
})
</code>```

The Full Code

Putting it all together we get this:

// Headroom.js
// https://github.com/WickyNilliams/headroom.js
var myElement = document.querySelector("header");

var headroom  = new Headroom(myElement, {
  "offset": 220,
  "tolerance": {
    up: 0,
    down: 0
  },
  "classes": {
    "initial": "header--fixed",
    "pinned": "slideDown",
    "unpinned": "slideUp",
    "top": "top",
    "notTop" : "not-top",
  }
});

headroom.init();

// When the page is at the top, remove the slideDown class.
window.addEventListener('scroll', function() {
  if (window.pageYOffset === 0) {
    myElement.classList.remove('slideDown')
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.header--fixed {
  position: absolute;
  top: 0;
  width: 100%;
}
.header--fixed.top {
  transition: none;
  transform: translateY(0);
}
.header--fixed.not-top {
  position: fixed;
  transform: translateY(-100%);
}
.header--fixed.slideDown.not-top {
  transition: transform 0.3s ease-in-out;
  transform: translateY(0);
}
.header--fixed.slideDown.top {
  transition: transform 0.3s ease-in-out;
  position: fixed;
}
.header--fixed.slideUp.not-top {
  transition: transform 0.3s ease-in-out;
  transform: translateY(-100%);
}
.header--fixed.slideUp.top {
  transform: translateY(-100%);
  position: absolute;
}

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  text-align: center;
}

header {
  background: #4ECDC4;
  padding: 40px;
  font: normal 30px/1 sans-serif;
}

main {
  padding: 110px 0 0 0;
}</code>```

  Header

Lorem ipsum 1

Lorem ipsum 2

Lorem ipsum 3

Lorem ipsum 4

Lorem ipsum 5

Lorem ipsum 6

Lorem ipsum 7

Lorem ipsum 8

Lorem ipsum 9

Lorem ipsum 10

Lorem ipsum 1

Lorem ipsum 2

Lorem ipsum 3

Lorem ipsum 4

Lorem ipsum 5

Lorem ipsum 6

Lorem ipsum 7

Lorem ipsum 8

Lorem ipsum 9

Lorem ipsum 10

Lorem ipsum 1

Lorem ipsum 2

Lorem ipsum 3

Lorem ipsum 4

Lorem ipsum 5

Lorem ipsum 6

Lorem ipsum 7

Lorem ipsum 8

Lorem ipsum 9

Lorem ipsum 10

Lorem ipsum 1

Lorem ipsum 2

Lorem ipsum 3

Lorem ipsum 4

Lorem ipsum 5

Lorem ipsum 6

Lorem ipsum 7

Lorem ipsum 8

Lorem ipsum 9

Lorem ipsum 10

Lorem ipsum 1

Lorem ipsum 2

Lorem ipsum 3

Lorem ipsum 4

Lorem ipsum 5

Lorem ipsum 6

Lorem ipsum 7

Lorem ipsum 8

Lorem ipsum 9

Lorem ipsum 10

Lorem ipsum 1

Lorem ipsum 2

Lorem ipsum 3

Lorem ipsum 4

Lorem ipsum 5

Lorem ipsum 6

Lorem ipsum 7

Lorem ipsum 8

Lorem ipsum 9

Lorem ipsum 10

Lorem ipsum 1

Lorem ipsum 2

Lorem ipsum 3

Lorem ipsum 4

Lorem ipsum 5

Lorem ipsum 6

Lorem ipsum 7

Lorem ipsum 8

Lorem ipsum 9

Lorem ipsum 10

Lorem ipsum 1

Lorem ipsum 2

Lorem ipsum 3

Lorem ipsum 4

Lorem ipsum 5

Lorem ipsum 6

Lorem ipsum 7

Lorem ipsum 8

Lorem ipsum 9

Lorem ipsum 10

Lorem ipsum 1

Lorem ipsum 2

Lorem ipsum 3

Lorem ipsum 4

Lorem ipsum 5

Lorem ipsum 6

Lorem ipsum 7

Lorem ipsum 8

Lorem ipsum 9

Lorem ipsum 10

Lorem ipsum 1

Lorem ipsum 2

Lorem ipsum 3

Lorem ipsum 4

Lorem ipsum 5

Lorem ipsum 6

Lorem ipsum 7

Lorem ipsum 8

Lorem ipsum 9

Lorem ipsum 10

```

And with that we have everything we need. For a working example with the CSS done in SCSS like your example, see this Codepen.

Body:
I'm using the awesome Headroom.js plugin to build an auto-hiding header. The header is static from start and becomes pinned after an offset (when scrolling down) and then back to static (when it's back to the top).

Here is what I have done:
http://codepen.io/netgloo/pen/KmGpBL

but I got 2 problems:

scrolling down from top: when the header becomes pinned, I see it slides down and suddenly slides up

scrolling up from middle page: when the header arrives to the offset it disappears, but I need keeping it pinned to the top

Someone could give me some help or ideas?
Thanks

Here is how I initialize the plugin:

var myElement = document.querySelector("header");

var headroom  = new Headroom(myElement, {
  "offset": 150,
  "tolerance": 0,
});

headroom.init();

Body:
The headroom.js script mainly handles the addition/removal of some classes for you. It's up to you to add the appropriate styles to achieve the effect you want. Let's start with the simplest part, the HTML:

HTML

<header>
  Header
</header>

That's it!

Now for the JS setup:

JS

var myElement = document.querySelector("header");

var headroom  = new Headroom(myElement, {
  "offset": 220,
  "tolerance": {
    up: 0,
    down: 0
  },
  "classes": {
    "initial": "header--fixed",
    "pinned": "slideDown",
    "unpinned": "slideUp",
    "top": "top",
    "notTop" : "not-top",
  }
});

headroom.init();

The first line selects the header element. The second creates a new Headroom object using the configuration values. I've set the values based on the effect it sounds like you're trying to achieve - the header should slide away when the page is scrolled down quickly, and should slide into view when the page is scrolled up.

The offset of 205px is the distance from the top when the header can become unpinned.

The tolerance of 5px is the scroll tolerance before the state changes.

And finally we're going to define the classes that will be added to the element for the different states. At the start the element will be assigned a class of header--fixed. When pinned, the element will receive the additional slideDown class. And when unpinned the element will receive the additional slideUp class.

The final line initializes the headroom object.

Using the state-based classes we can now create the CSS needed to achieve the effect you want.

CSS

We'll start with the .header--fixed class:

.header--fixed {
  position: absolute;
  top: 0;
  width: 100%;
}

main {
  padding-top: 110px;
}

This sets the initial placement of the header (at the top) and sets a padding for the main content of the page so it's not covered by the header.

Next we need to define the styles for various states - .top, .not-top, .slideDown and .slideUp:

.header--fixed.top {
  transition: none;
  transform: translateY(0);
}
.header--fixed.not-top {
  position: fixed;
  transform: translateY(-100%);
}
.header--fixed.slideDown.not-top {
  transition: transform 0.3s ease-in-out;
  transform: translateY(0);
}
.header--fixed.slideDown.top {
  transition: transform 0.3s ease-in-out;
  position: fixed;
}
.header--fixed.slideUp.not-top {
  transition: transform 0.3s ease-in-out;
  transform: translateY(-100%);
}
.header--fixed.slideUp.top {
  transform: translateY(-100%);
  position: absolute;
}

Most of these styles are related to setting the position and transition for each state. In short, the .not-top class is applied when the page is scrolled below the header. .top is applied when the page is scrolled near the top (within the height of the header).

In addition to this critical CSS you would need the CSS for the styling of the header - a background color, font, etc. This could be applied by targeting the header element, or header--fixed class.

The final piece, and crux of the problem is resetting the header when the page is scrolled back to the very top - ie a window.pageYOffset of 0. When the page reaches this point, we need to remove the .slideDown class so the header scrolls with the page.

window.addEventListener('scroll', function() {
  if (window.pageYOffset === 0) {
    myElement.classList.remove('slideDown')
  }
})

The Full Code

Putting it all together we get this:

// Headroom.js
// https://github.com/WickyNilliams/headroom.js
var myElement = document.querySelector("header");

var headroom  = new Headroom(myElement, {
  "offset": 220,
  "tolerance": {
    up: 0,
    down: 0
  },
  "classes": {
    "initial": "header--fixed",
    "pinned": "slideDown",
    "unpinned": "slideUp",
    "top": "top",
    "notTop" : "not-top",
  }
});

headroom.init();

// When the page is at the top, remove the slideDown class.
window.addEventListener('scroll', function() {
  if (window.pageYOffset === 0) {
    myElement.classList.remove('slideDown')
  }
})

.header--fixed {
  position: absolute;
  top: 0;
  width: 100%;
}
.header--fixed.top {
  transition: none;
  transform: translateY(0);
}
.header--fixed.not-top {
  position: fixed;
  transform: translateY(-100%);
}
.header--fixed.slideDown.not-top {
  transition: transform 0.3s ease-in-out;
  transform: translateY(0);
}
.header--fixed.slideDown.top {
  transition: transform 0.3s ease-in-out;
  position: fixed;
}
.header--fixed.slideUp.not-top {
  transition: transform 0.3s ease-in-out;
  transform: translateY(-100%);
}
.header--fixed.slideUp.top {
  transform: translateY(-100%);
  position: absolute;
}

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  text-align: center;
}

header {
  background: #4ECDC4;
  padding: 40px;
  font: normal 30px/1 sans-serif;
}

main {
  padding: 110px 0 0 0;
}

<script src="https://unpkg.com/headroom.js"></script>
<header>
  Header
</header>

<main>
  <p>Lorem ipsum 1</p>
  <p>Lorem ipsum 2</p>
  <p>Lorem ipsum 3</p>
  <p>Lorem ipsum 4</p>
  <p>Lorem ipsum 5</p>
  <p>Lorem ipsum 6</p>
  <p>Lorem ipsum 7</p>
  <p>Lorem ipsum 8</p>
  <p>Lorem ipsum 9</p>
  <p>Lorem ipsum 10</p>
  <hr>
  <p>Lorem ipsum 1</p>
  <p>Lorem ipsum 2</p>
  <p>Lorem ipsum 3</p>
  <p>Lorem ipsum 4</p>
  <p>Lorem ipsum 5</p>
  <p>Lorem ipsum 6</p>
  <p>Lorem ipsum 7</p>
  <p>Lorem ipsum 8</p>
  <p>Lorem ipsum 9</p>
  <p>Lorem ipsum 10</p>
  <hr>
  <p>Lorem ipsum 1</p>
  <p>Lorem ipsum 2</p>
  <p>Lorem ipsum 3</p>
  <p>Lorem ipsum 4</p>
  <p>Lorem ipsum 5</p>
  <p>Lorem ipsum 6</p>
  <p>Lorem ipsum 7</p>
  <p>Lorem ipsum 8</p>
  <p>Lorem ipsum 9</p>
  <p>Lorem ipsum 10</p>
  <hr>
  <p>Lorem ipsum 1</p>
  <p>Lorem ipsum 2</p>
  <p>Lorem ipsum 3</p>
  <p>Lorem ipsum 4</p>
  <p>Lorem ipsum 5</p>
  <p>Lorem ipsum 6</p>
  <p>Lorem ipsum 7</p>
  <p>Lorem ipsum 8</p>
  <p>Lorem ipsum 9</p>
  <p>Lorem ipsum 10</p>
  <hr>
  <p>Lorem ipsum 1</p>
  <p>Lorem ipsum 2</p>
  <p>Lorem ipsum 3</p>
  <p>Lorem ipsum 4</p>
  <p>Lorem ipsum 5</p>
  <p>Lorem ipsum 6</p>
  <p>Lorem ipsum 7</p>
  <p>Lorem ipsum 8</p>
  <p>Lorem ipsum 9</p>
  <p>Lorem ipsum 10</p>
  <hr>
  <p>Lorem ipsum 1</p>
  <p>Lorem ipsum 2</p>
  <p>Lorem ipsum 3</p>
  <p>Lorem ipsum 4</p>
  <p>Lorem ipsum 5</p>
  <p>Lorem ipsum 6</p>
  <p>Lorem ipsum 7</p>
  <p>Lorem ipsum 8</p>
  <p>Lorem ipsum 9</p>
  <p>Lorem ipsum 10</p>
  <hr>
  <p>Lorem ipsum 1</p>
  <p>Lorem ipsum 2</p>
  <p>Lorem ipsum 3</p>
  <p>Lorem ipsum 4</p>
  <p>Lorem ipsum 5</p>
  <p>Lorem ipsum 6</p>
  <p>Lorem ipsum 7</p>
  <p>Lorem ipsum 8</p>
  <p>Lorem ipsum 9</p>
  <p>Lorem ipsum 10</p>
  <hr>
  <p>Lorem ipsum 1</p>
  <p>Lorem ipsum 2</p>
  <p>Lorem ipsum 3</p>
  <p>Lorem ipsum 4</p>
  <p>Lorem ipsum 5</p>
  <p>Lorem ipsum 6</p>
  <p>Lorem ipsum 7</p>
  <p>Lorem ipsum 8</p>
  <p>Lorem ipsum 9</p>
  <p>Lorem ipsum 10</p>
  <hr>
  <p>Lorem ipsum 1</p>
  <p>Lorem ipsum 2</p>
  <p>Lorem ipsum 3</p>
  <p>Lorem ipsum 4</p>
  <p>Lorem ipsum 5</p>
  <p>Lorem ipsum 6</p>
  <p>Lorem ipsum 7</p>
  <p>Lorem ipsum 8</p>
  <p>Lorem ipsum 9</p>
  <p>Lorem ipsum 10</p>
  <hr>
  <p>Lorem ipsum 1</p>
  <p>Lorem ipsum 2</p>
  <p>Lorem ipsum 3</p>
  <p>Lorem ipsum 4</p>
  <p>Lorem ipsum 5</p>
  <p>Lorem ipsum 6</p>
  <p>Lorem ipsum 7</p>
  <p>Lorem ipsum 8</p>
  <p>Lorem ipsum 9</p>
  <p>Lorem ipsum 10</p>
  <hr>
</main>

And with that we have everything we need. For a working example with the CSS done in SCSS like your example, see this Codepen.


问:
zend framework models location and autoloading
I've started to document myself regarding Zend Framework as I will soon start using it in production. Everything was working fine, until I started to use and work with models :).

The default location for models, based on Zend recommendations, is application/models/DbTable, where all the models will be thrown in. This location forces me to name a model like Application_Model_DbTable_Actors. For me, this is a very long name for a model and not a easy to use one.

The directory structure that I want to obtain looks something like this:

```<code>application/
  models/
    actors/
      ActorsMapper.php
      Actor.php
    books/
      BooksMapper.php
      Book.php
</code>```

etc.

So all my models will reside under the models directory, but grouped in their own directories.

Naming for each class should be ActorsMapper or Actor (They will both extend Zend_Db_Table or Zend_Db_Row).

I am aware of the fact that in my controllers if I instantiate a model using something like $actors = new ActorsMapper() I will get a Fatal error: Class not found and that why I'm asking for your help with this.

To solve this issue I tried to add my models directory to the include_path:

first try

added includePaths.models = APPLICATION_PATH "/models" to application.ini

but this one doesn't even add it to the include path

second try:

explicitely added the path using set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    realpath(APPLICATION_PATH . '/models'),
    get_include_path(),
)));

but even if this adds that path among the included ones, the error still persists.

I've seen this naming of models in the official documentation of the Zend_Db_Table, but I couldn't find anything related to autoloading them.

Thank you all for any solutions.

p.s. zend framework version is 1.11.1

答:
Zend Framework has a build in autoloader.  It works by mapping the class name to the directory tree, so Application_Model_Actors_Actor will get mapped to

```<code>Application\
 Models\
  Actors\
   Actor.php
</code>```

Unfortunately, you cannot change this.  The feature you are looking for is namespacing but it is only supported (and is in fact one of the major features) of Zend Framework 2 which is still being developed.

Body:
I've started to document myself regarding Zend Framework as I will soon start using it in production. Everything was working fine, until I started to use and work with models :).

The default location for models, based on Zend recommendations, is application/models/DbTable, where all the models will be thrown in. This location forces me to name a model like Application_Model_DbTable_Actors. For me, this is a very long name for a model and not a easy to use one.

The directory structure that I want to obtain looks something like this:

application/
  models/
    actors/
      ActorsMapper.php
      Actor.php
    books/
      BooksMapper.php
      Book.php

etc.

So all my models will reside under the models directory, but grouped in their own directories.

Naming for each class should be ActorsMapper or Actor (They will both extend Zend_Db_Table or Zend_Db_Row).

I am aware of the fact that in my controllers if I instantiate a model using something like $actors = new ActorsMapper() I will get a Fatal error: Class not found and that why I'm asking for your help with this.

To solve this issue I tried to add my models directory to the include_path:

first try

added includePaths.models = APPLICATION_PATH "/models" to application.ini

but this one doesn't even add it to the include path

second try:

explicitely added the path using set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    realpath(APPLICATION_PATH . '/models'),
    get_include_path(),
)));

but even if this adds that path among the included ones, the error still persists.

I've seen this naming of models in the official documentation of the Zend_Db_Table, but I couldn't find anything related to autoloading them.

Thank you all for any solutions.

p.s. zend framework version is 1.11.1

Body:
Zend Framework has a build in autoloader.  It works by mapping the class name to the directory tree, so Application_Model_Actors_Actor will get mapped to

Application\
 Models\
  Actors\
   Actor.php

Unfortunately, you cannot change this.  The feature you are looking for is namespacing but it is only supported (and is in fact one of the major features) of Zend Framework 2 which is still being developed.


问:
Is this method of initialization recommended?
So when I was coding my own project, a problem came up with initializing an object. My class has so many attributes that needs to be initiated BUT not always all of them, which . That's when I came up with this idea (but I'm not sure if it's used before anywhere):

```<code>public class MyClass {
    public static final int DEFAULT1 = 1;
    public static final int DEFAULT2 = 2;
    public static final int DEFAULT3 = 3;
    private int attr1;
    private int attr2;
    private int attr3;
    private MyClass(){
        attr1 = DEFAULT1;
        attr2 = DEFAULT2;
        attr3 = DEFAULT3;
    }
    public static MyClass create(){
        return new MyClass();
    }
    public MyClass setAttr1(int attr1){
        this.attr1 = attr1;
        return this;
    }
    public MyClass setAttr2(int attr2){
        this.attr2 = attr2;
        return this;
    }
    public MyClass setAttr3(int attr3){
        this.attr3 = attr3;
        return this;
    }
}
</code>```

When I create a new MyClass instance I would do:

```<code>MyClass obj = MyClass.create().setAttr1(3).setAttr3(1);
</code>```

It worked for me (kind of because I tested it but I haven't decided to use it in my project). My question is, is this legit? Would it create any kinds of memory/execution problems?

答:
Another name for it is Fluent Interface.

You just need to use with instead of set for method names. The set naming is kind of reserved for JavaBeans convention.

Body:
So when I was coding my own project, a problem came up with initializing an object. My class has so many attributes that needs to be initiated BUT not always all of them, which . That's when I came up with this idea (but I'm not sure if it's used before anywhere):

public class MyClass {
    public static final int DEFAULT1 = 1;
    public static final int DEFAULT2 = 2;
    public static final int DEFAULT3 = 3;
    private int attr1;
    private int attr2;
    private int attr3;
    private MyClass(){
        attr1 = DEFAULT1;
        attr2 = DEFAULT2;
        attr3 = DEFAULT3;
    }
    public static MyClass create(){
        return new MyClass();
    }
    public MyClass setAttr1(int attr1){
        this.attr1 = attr1;
        return this;
    }
    public MyClass setAttr2(int attr2){
        this.attr2 = attr2;
        return this;
    }
    public MyClass setAttr3(int attr3){
        this.attr3 = attr3;
        return this;
    }
}

When I create a new MyClass instance I would do:

MyClass obj = MyClass.create().setAttr1(3).setAttr3(1);

It worked for me (kind of because I tested it but I haven't decided to use it in my project). My question is, is this legit? Would it create any kinds of memory/execution problems?


问:
How to remove hash keys which hash value is blank?
I am using Ruby on Rails 3.2.13 and I would like to remove hash keys which corresponding hash value is blank. That is, if I have the following hash

```<code>{ :a => 0, :b => 1, :c => true, :d => "", :e => "   ", :f => nil }
</code>```

then the resulting hash should be (note: 0 and true are not considered blank)

```<code>{ :a => 0, :b => 1, :c => true }
</code>```

How can I make that?

答:
There are a number of ways to accomplish this common task

reject

This is the one I use most often for cleaning up hashes as its short, clean, and flexible enough to support any conditional and doesn't mutate the original object. Here is a good article on the benefits of immutability in ruby.

```<code>hash.reject {|_,v| v.blank?}
</code>```

Note: The underscore in the above example is used to indicate that we want to unpack the tuple passed to the proc, but we aren't using the first value (key).

reject!

However, if you want to mutate the original object:

```<code>hash.reject! {|_,v| v.blank?}
</code>```

select

Conversely, you use select which will only return the values that return true when evaluated

```<code>hash.select {|_,v| v.present? }
</code>```

select!

...and the mutating version

```<code>hash.select {|_,v| v.present? }
</code>```

compact

Lastly, when you only need to remove keys that have nil values...

```<code>hash.compact
</code>```

compact!

You have picked up the pattern by now, but this is the version that modifies the original hash!

```<code>hash.compact!
</code>```

Body:
I am using Ruby on Rails 3.2.13 and I would like to remove hash keys which corresponding hash value is blank. That is, if I have the following hash

{ :a => 0, :b => 1, :c => true, :d => "", :e => "   ", :f => nil }

then the resulting hash should be (note: 0 and true are not considered blank)

{ :a => 0, :b => 1, :c => true }

How can I make that?

Body:
There are a number of ways to accomplish this common task

reject

This is the one I use most often for cleaning up hashes as its short, clean, and flexible enough to support any conditional and doesn't mutate the original object. Here is a good article on the benefits of immutability in ruby.

hash.reject {|_,v| v.blank?}

Note: The underscore in the above example is used to indicate that we want to unpack the tuple passed to the proc, but we aren't using the first value (key).

reject!

However, if you want to mutate the original object:

hash.reject! {|_,v| v.blank?}

select

Conversely, you use select which will only return the values that return true when evaluated

hash.select {|_,v| v.present? }

select!

...and the mutating version

hash.select {|_,v| v.present? }

compact

Lastly, when you only need to remove keys that have nil values...

hash.compact

compact!

You have picked up the pattern by now, but this is the version that modifies the original hash!

hash.compact!


问:
Simple C function returns nonsense
I need to make simple function that converts binary number (string) to decimal number (long). When it returns result, it's nonsense. I've tried to return all others variables and it returned correct numbers. There is something wrong with my result variable.</p>

```<code>#include "stdio.h"
#include "string.h"
#include "math.h"

long bintodec(const char *bin_num) {
        long DIGIT, SUBTOTAL, RESULT = 0, I, LEN;
        LEN = strlen(bin_num);
        for(I = 0; I != LEN; I++) {
                sscanf(&bin_num[I], "%li", &DIGIT);
                SUBTOTAL = DIGIT * pow(2, LEN - I - 1);
                RESULT = RESULT + SUBTOTAL;
        }
        return RESULT;
}

main() {
        clrscr();
        printf("%li", bintodec("101"));
        getch();
}
</code>```

答:
sscanf is expecting a C string:

During the first iteration it receives "101" and 101 * 4 is 404

During the second iteration it receives 01 and 1 * 2 is 2

During the third iteration it receives 1 and 1 * 1 is 1

404 + 2 + 1 is 407 which must be the nonsense you are seeing

What you want is to convert each character:

```<code>DIGIT = bin_num[I] - '0';
</code>```

Title: Simple C function returns nonsense

Body:
I need to make simple function that converts binary number (string) to decimal number (long). When it returns result, it's nonsense. I've tried to return all others variables and it returned correct numbers. There is something wrong with my result variable.

#include "stdio.h"
#include "string.h"
#include "math.h"

long bintodec(const char *bin_num) {
        long DIGIT, SUBTOTAL, RESULT = 0, I, LEN;
        LEN = strlen(bin_num);
        for(I = 0; I != LEN; I++) {
                sscanf(&bin_num[I], "%li", &DIGIT);
                SUBTOTAL = DIGIT * pow(2, LEN - I - 1);
                RESULT = RESULT + SUBTOTAL;
        }
        return RESULT;
}

main() {
        clrscr();
        printf("%li", bintodec("101"));
        getch();
}

Body:
sscanf is expecting a C string:

During the first iteration it receives "101" and 101 * 4 is 404

During the second iteration it receives 01 and 1 * 2 is 2

During the third iteration it receives 1 and 1 * 1 is 1

404 + 2 + 1 is 407 which must be the nonsense you are seeing

What you want is to convert each character:

DIGIT = bin_num[I] - '0';


问:
Chart.js displays the label in a weird font in IE8
How can I find the font used in Chart.js?

I have tried to look in the documentation and see a family of fonts, but I am not sure which font is exactly used.

答:
The fontFamily config option is available for different components, and you can use that to change the font to something you know works in IE.

Based on the documentation, it seems like the default font is "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif".

I've created a JSFiddle that demonstrates changing the font for the three components mentioned below: https://jsfiddle.net/nva5hwLp/

Ticks

```<code>options: {
  scales: {
    xAxes: [{
      ticks: {
        fontFamily: 'Times New Roman'
      }
    }]
  }
}
</code>```

See the Axes Labeling documentation for more information and font styling options. It seems like the documentation currently suggests placing the fontFamily config under a key called scaleLabel, however it only works if you put it under the ticks section.

Legend

```<code>options: {
  legend: {
    labels: {
      fontFamily: 'Times New Roman'
    }
  }
}
</code>```

See the Fonts documentation for more information. Currently, the documentation says to use defaultFontFamily, however it seems to only work when you use fontFamily.

Title

```<code>options: {
  title: {
    text: 'something',
    display: true,
    fontFamily: 'Times New Roman'
  }
}
</code>```

See the Title config documentation for more information.

Body:
The fontFamily config option is available for different components, and you can use that to change the font to something you know works in IE.

Based on the documentation, it seems like the default font is "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif".

I've created a JSFiddle that demonstrates changing the font for the three components mentioned below: https://jsfiddle.net/nva5hwLp/

Ticks

options: {
  scales: {
    xAxes: [{
      ticks: {
        fontFamily: 'Times New Roman'
      }
    }]
  }
}

See the Axes Labeling documentation for more information and font styling options. It seems like the documentation currently suggests placing the fontFamily config under a key called scaleLabel, however it only works if you put it under the ticks section.

Legend

options: {
  legend: {
    labels: {
      fontFamily: 'Times New Roman'
    }
  }
}

See the Fonts documentation for more information. Currently, the documentation says to use defaultFontFamily, however it seems to only work when you use fontFamily.

Title

options: {
  title: {
    text: 'something',
    display: true,
    fontFamily: 'Times New Roman'
  }
}

See the Title config documentation for more information.


问:
All combinations of list elements without duplicate elements
Alexandria has a function map-product which takes an arbitrary number of list arguments, and generates all combinations of elements, one from each list, in order. For example:

```<code>(alexandria:map-product 'list '(1 2) '(3 4) '(5 6))
=> ((1 3 5) (1 3 6) (1 4 5) (1 4 6) (2 3 5) (2 3 6) (2 4 5) (2 4 6))
</code>```

And when there are duplicate elements in the arguments, the resulting combinations will also contain some duplicate elements:

```<code>(alexandria:map-product 'list '(1 2) '(3 4) '(5 1))
=> ((1 3 5) (1 3 1) (1 4 5) (1 4 1) (2 3 5) (2 3 1) (2 4 5) (2 4 1))
</code>```

where (1 3 1) and (1 4 1) contain duplicates.

I would like to remove all such lists containing duplicates from the result. My current solution is to simply do:

```<code>(delete-if-not #'alexandria:setp result)
</code>```

but this requires an exorbitant amount of post-processing, especially since the number of resulting combinations is typically in the hundreds. A better solution would be to write a function like map-product that did not generate duplicates in the first place.

Another post at Lisp: How to get all possible combinations of the elements from lists contained on a list? by zck provides a function roughly equivalent to map-product that seems like it could be modified to excise duplicates internally:

```<code>(defun combinations (&rest lists)
  (if (car lists)
      (mapcan (lambda (inner-val)
                (mapcar (lambda (outer-val)
                          (cons outer-val
                                inner-val))
                        (car lists)))
              (apply #'combinations (cdr lists)))
    (list nil)))
</code>```

However, it is not obvious to me how to insert a duplicates test. Also, a simple timing run seems to show that this function is about 16 times slower than alexandria:map-product. Is it feasible to get a faster version of this function, but without duplicate combinations?

答:
You might need to check this for correctness, but it should give you an idea:

```<code>CL-USER 40 > (defun combinations-1 (lists)
               (if (car lists)
                   (mapcan (lambda (inner-val)
                             (mapcan (lambda (outer-val)
                                       (unless (member outer-val inner-val)
                                         (list (cons outer-val inner-val))))
                                     (car lists)))
                           (combinations-1 (cdr lists)))
                 (list nil)))
COMBINATIONS-1

CL-USER 41 > (combinations-1 '((3 2) (1 2) (5 1)))
((3 1 5) (2 1 5) (3 2 5) (3 2 1))
</code>```

Another MAPCAN instead of MAPCAR filters the NILs. For that we need to return lists, thus the added LIST call. We add something to the list only, if it is not a member, otherwise the empty list is used.

Note that I also removed the &rest list / apply pattern.

Q: Are all sublists with repetitions reduced to NIL, so that they are removed via the MAPCAN?

Body:
Alexandria has a function map-product which takes an arbitrary number of list arguments, and generates all combinations of elements, one from each list, in order. For example:

(alexandria:map-product 'list '(1 2) '(3 4) '(5 6))
=> ((1 3 5) (1 3 6) (1 4 5) (1 4 6) (2 3 5) (2 3 6) (2 4 5) (2 4 6))

And when there are duplicate elements in the arguments, the resulting combinations will also contain some duplicate elements:

(alexandria:map-product 'list '(1 2) '(3 4) '(5 1))
=> ((1 3 5) (1 3 1) (1 4 5) (1 4 1) (2 3 5) (2 3 1) (2 4 5) (2 4 1))

where (1 3 1) and (1 4 1) contain duplicates.

I would like to remove all such lists containing duplicates from the result. My current solution is to simply do:

(delete-if-not #'alexandria:setp result)

but this requires an exorbitant amount of post-processing, especially since the number of resulting combinations is typically in the hundreds. A better solution would be to write a function like map-product that did not generate duplicates in the first place.

Another post at Lisp: How to get all possible combinations of the elements from lists contained on a list? by zck provides a function roughly equivalent to map-product that seems like it could be modified to excise duplicates internally:

(defun combinations (&rest lists)
  (if (car lists)
      (mapcan (lambda (inner-val)
                (mapcar (lambda (outer-val)
                          (cons outer-val
                                inner-val))
                        (car lists)))
              (apply #'combinations (cdr lists)))
    (list nil)))

However, it is not obvious to me how to insert a duplicates test. Also, a simple timing run seems to show that this function is about 16 times slower than alexandria:map-product. Is it feasible to get a faster version of this function, but without duplicate combinations?

Body:
You might need to check this for correctness, but it should give you an idea:

CL-USER 40 > (defun combinations-1 (lists)
               (if (car lists)
                   (mapcan (lambda (inner-val)
                             (mapcan (lambda (outer-val)
                                       (unless (member outer-val inner-val)
                                         (list (cons outer-val inner-val))))
                                     (car lists)))
                           (combinations-1 (cdr lists)))
                 (list nil)))
COMBINATIONS-1

CL-USER 41 > (combinations-1 '((3 2) (1 2) (5 1)))
((3 1 5) (2 1 5) (3 2 5) (3 2 1))

Another MAPCAN instead of MAPCAR filters the NILs. For that we need to return lists, thus the added LIST call. We add something to the list only, if it is not a member, otherwise the empty list is used.

Note that I also removed the &rest list / apply pattern.

Q: Are all sublists with repetitions reduced to NIL, so that they are removed via the MAPCAN?


问:
Detect hangup event when call is parked in Asterisk 11
Is there any way to detect a hangup event in dialplan when call is parked? I see this message in log:

features.c:   == SIP/CHANNAME got tired of being parked

A 'h' extension in context 'parkedcalls' doesn't work:

[parkedcalls]

```<code>exten => h,1,DumpChan()
</code>```

A 'h' extension in main context works, but there is no difference between hangup and pickup.
Thanks for your help.

答: You can check events in AMI or do your own parking via dialplan(pretty trivial).</p>

Body:
Is there any way to detect a hangup event in dialplan when call is parked? I see this message in log:

features.c:   == SIP/CHANNAME got tired of being parked

A 'h' extension in context 'parkedcalls' doesn't work:

[parkedcalls]

exten => h,1,DumpChan()

A 'h' extension in main context works, but there is no difference between hangup and pickup.
Thanks for your help.


问:
Authentication with both email and username (same field) (laravel API )
I am building laravel API of my website . I am using laravel 5.3

I am using the API in building mobile app .

In login section, there are two fields :

Enter email or username

Enter password

In my DB , email and username are different columns.

Here is the function:

```<code>public function authenticate()
{

$credentials=request()->only('username','password');

try {

    $token=JWTAuth::attempt($credentials);

    if(!$token){
        return response()->json(['error'=>'credentials wrong'],401);
    }
}
catch(JWTException $e) {

 return response()->json(['error'=>'something_went_wrong'],500);

}
return response()->json(['token'=>$token],200);
}
</code>```

Here only username is used,I want to use both username and password.

If need any other info please ask.

ty:)

答:
You can use FILTER_VALIDATE_EMAIL function
Like this:-

```<code>$login_type = filter_var( $data['email'], FILTER_VALIDATE_EMAIL ) ? 'email' : 'username';
</code>```

And then pass in auth attempt function like this:-

```<code>Auth::attempt([$login_type => $data['email'], 'password' => $data['password']])
</code>```

In your case:-

```<code>According to your Html you have used two input
<input type="text"required autocomplete="off" name="loginEmail" id="inputname"/>
<input type="password"required autocomplete="off" name="loginPassword" id="inputpassword"/>

And your function is:-

public function authenticate(Request $request)
{
$data = $request->all();
$login_type = filter_var( $data['loginEmail'], FILTER_VALIDATE_EMAIL ) ? 'email' : 'username';
//$credentials=request()->only('username','password');

try {

    $token=JWTAuth::attempt([$login_type => $data['loginEmail'], 'password' => $data['loginPassword']]);

    if(!$token){
        return response()->json(['error'=>'credentials wrong'],401);
    }
}
catch(JWTException $e) {

 return response()->json(['error'=>'something_went_wrong'],500);

}
return response()->json(['token'=>$token],200);
}
</code>```

Hope it Helps!

In postman I was using key in the body called 'username' so here instead of loginEmail , username will come and it will work fine ! ty

Body:
I am building laravel API of my website . I am using laravel 5.3

I am using the API in building mobile app .

In login section, there are two fields :

Enter email or username

Enter password

In my DB , email and username are different columns.

Here is the function:

public function authenticate()
{

$credentials=request()->only('username','password');

try {

    $token=JWTAuth::attempt($credentials);

    if(!$token){
        return response()->json(['error'=>'credentials wrong'],401);
    }
}
catch(JWTException $e) {

 return response()->json(['error'=>'something_went_wrong'],500);

}
return response()->json(['token'=>$token],200);
}

Here only username is used,I want to use both username and password.

If need any other info please ask.

ty:)

Body:
You can use FILTER_VALIDATE_EMAIL function
Like this:-

$login_type = filter_var( $data['email'], FILTER_VALIDATE_EMAIL ) ? 'email' : 'username';

And then pass in auth attempt function like this:-

Auth::attempt([$login_type => $data['email'], 'password' => $data['password']])

In your case:-

According to your Html you have used two input
<input type="text"required autocomplete="off" name="loginEmail" id="inputname"/>
<input type="password"required autocomplete="off" name="loginPassword" id="inputpassword"/>

And your function is:-

public function authenticate(Request $request)
{
$data = $request->all();
$login_type = filter_var( $data['loginEmail'], FILTER_VALIDATE_EMAIL ) ? 'email' : 'username';
//$credentials=request()->only('username','password');

try {

    $token=JWTAuth::attempt([$login_type => $data['loginEmail'], 'password' => $data['loginPassword']]);

    if(!$token){
        return response()->json(['error'=>'credentials wrong'],401);
    }
}
catch(JWTException $e) {

 return response()->json(['error'=>'something_went_wrong'],500);

}
return response()->json(['token'=>$token],200);
}

Hope it Helps!

In postman I was using key in the body called 'username' so here instead of loginEmail , username will come and it will work fine ! ty