问:
You have requested a non-existent service "templating"
i'm trying to get FOSOAuthServerBundle to work on my project
Running symfony 3.4.0

templating seems to be missing but i can't find anything about it on google.
any idea what it could be?
twig is working perfectly otherwise

i've cleared the cache
downgraded from 3.4.1 to 3.4.0

AuthorizeController.php >

```<code>return $this->container->get('templating')->renderResponse(
        'FOSOAuthServerBundle:Authorize:authorize.html.'.$this->container->getParameter('fos_oauth_server.template.engine'),
        array(
            'form'   => $form->createView(),
            'client' => $this->getClient(),
        )
);
</code>```

this is where its crashing.

答:
I'm assuming you're using Symfony Flex, since it has this minimalist approach it doesn't come with twig, which is the default templating system for Symfony.

Please install it via:

```<code>composer require twig
</code>```

In any case if you have already twig installed but it's not working, make sure your configurations has it available:

```<code># app/config/config.yml

framework:
    # ...
    templating:
        engines: ['twig']
</code>```

Body:
i'm trying to get FOSOAuthServerBundle to work on my project
Running symfony 3.4.0

templating seems to be missing but i can't find anything about it on google.
any idea what it could be?
twig is working perfectly otherwise

i've cleared the cache
downgraded from 3.4.1 to 3.4.0

AuthorizeController.php >

return $this->container->get('templating')->renderResponse(
        'FOSOAuthServerBundle:Authorize:authorize.html.'.$this->container->getParameter('fos_oauth_server.template.engine'),
        array(
            'form'   => $form->createView(),
            'client' => $this->getClient(),
        )
);

this is where its crashing.

Body:
I'm assuming you're using Symfony Flex, since it has this minimalist approach it doesn't come with twig, which is the default templating system for Symfony.

Please install it via:

composer require twig

In any case if you have already twig installed but it's not working, make sure your configurations has it available:

# app/config/config.yml

framework:
    # ...
    templating:
        engines: ['twig']


来源: stackexchange

问:
Codeigniter Multidimensional Array to Database
I'm trying to insert an array into a database table as separate rows. The array is generated from a table where the user can add additional rows. Can't get my head around what is going wrong!

Here is the view

```<code><table class="table table-bordered" id="parts">
  <thead class="table-success">
    <tr>
      <th class="table-success">Quantity</th>
      <th class="table-success">Parts</th>
      <th class="table-success">Fitted</th>
      <th class="table-success">Required</th>
      <th class="table-success">Cost</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <input type="hidden" name="job_no[]" value="<?php echo $job_number; ?>" />
      <td><input type="number" name="parts_qty[]" class="form-control" /></td>
      <td><input type="text" name="parts_description[]" class="form-control" /></td>
      <td><input type="text" name="parts_fitted[]" class="form-control" /></td>
      <td><input type="text" name="parts_required[]" class="form-control" /></td>
      <td><input type="text" name="parts_cost[]" class="form-control" /></td>
    </tr>
  </tbody>
</table>
<button type="button" class="btn btn-primary btn-xs" id="addRow"> <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"> </span> Add Row </button>
<script>
$(document).ready(function() {
    $("#addRow").click(function(){
            $("#parts").append("<tr><input type='hidden' name='job_no[]' value='<?php echo $job_number; ?>' /><td><input type='number' name='parts_qty[]' class='form-control' /></td><td><input type='text' name='parts_description[]' class='form-control' /></td><td><input type='text' name='parts_fitted[]' class='form-control' /></td><td><input type='text' name='parts_required[]' class='form-control' /></td><td><input type='text' name='parts_cost[]' class='form-control' /></td></tr>");
        });
    });
</script>
</code>```

Please note this is part of a larger form so not showing the submit buttons e.t.c

My Controller function looks like this

```<code>function add_parts_db()
    {
        $parts = array (
                    'job_number'    => $this->input->post('job_no'),
                    'quantity'      => $this->input->post('parts_qty'),
                    'parts'         => $this->input->post('parts_description'),
                    'fitted'        => $this->input->post('parts_fitted'),
                    'required'      => $this->input->post('parts_required'),
                    'cost'          => $this->input->post('parts_cost')
                );

                $this->service_model->add_parts_db($parts);
                redirect('service', 'refresh');
    }
</code>```

Here is the array being generated with some sample input in the table

```<code>Array
(
    [job_number] => Array
        (
            [0] => 2008
            [1] => 2008
            [2] => 2008
        )

    [quantity] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [parts] => Array
        (
            [0] => Part 1
            [1] => Part 2
            [2] => Parts 3
        )

    [fitted] => Array
        (
            [0] => Fitted 1
            [1] => Fitted 1
            [2] => Fitted 3
        )

    [required] => Array
        (
            [0] => Required 1
            [1] => Required 2
            [2] => Required 3
        )

    [cost] => Array
        (
            [0] => 1.00
            [1] => 2.00
            [2] => 3.00
        )

)
</code>```

Finally my model which I want to insert each item of the array into the database table as a separate row.

```<code>function add_parts_db($parts)
{
    $this->db->insert_batch('parts', $parts);
    return $this->db->insert_id();
}
</code>```

I would like the above array to be inserted into the database as separate rows so should look something like this

I'm getting the following error when submitting the form

```<code>    Error Number: 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 '0, 1, 2) VALUES ('2008','2008','2008'), ('1','2','3'), ('Part 1','Part 2','Parts' at line 1

INSERT INTO `parts` (0, 1, 2) VALUES ('2008','2008','2008'), ('1','2','3'), ('Part 1','Part 2','Parts 3'), ('Fitted 1','Fitted 1','Fitted 3'), ('Required 1','Required 2','Required 3'), ('1.00','2.00','3.00')

Filename: models/Service_model.php

Line Number: 33
</code>```

I think the problem might be in my jQuery/Javascript which I'm not quite understanding. I can set the initial key to 0 using name="parts[0][jobnumber]" but then in my jQuery I don't think it's recognising the variable properly

```<code>var $i = 1;
        $("#addRow").click(function(){
                $("#parts").append("<tr><input type='hidden' name='parts[$i][jobnumber]' value='<?php echo $job_number; ?>' /><td><input type='number' name='parts[$i][qty]' class='form-control' /></td><td><input type='text' name='parts[$i][description]' class='form-control' /></td><td><input type='text' name='parts[i][fitted]' class='form-control' /></td><td><input type='text' name='parts[$i][required]' class='form-control' /></td><td><input type='text' name='parts[$i][cost]' class='form-control' /></td></tr>");
                i++;
        });
</code>```

I think dumping the array looks like it's going to pull the correct array format through but it's not getting it because of my inept jQuery.

```<code> ["parts"]=>
  array(2) {
    [0]=>
    array(5) {
      ["jobnumber"]=>
      string(4) "2002"
      ["qty"]=>
      string(1) "3"
      ["description"]=>
      string(7) "parts 3"
      ["required"]=>
      string(10) "required 3"
      ["cost"]=>
      string(4) "3.00"
    }
    ["i"]=>
    array(1) {
      ["fitted"]=>
      string(8) "fitted 3"
    }
  }
</code>```

This is showing a syntax error if I go with the second reply

@Bhaumik Mehta

```<code> Array
    (
        [0] => Array
            (
                [job_number] => 2002
                [quantity] => 1
                [parts] => parts 1
                [fitted] => Fitted 1
                [required] => Required 1
                [cost] => 1.00
            )

        [1] => Array
            (
                [job_number] => 2002
                [quantity] => 2
                [parts] => Part 2
                [fitted] => Fitted 2
                [required] => Required 2
                [cost] => 2.00
            )

        [2] => Array
            (
                [job_number] => 2002
                [quantity] => 3
                [parts] => Parts 3
                [fitted] => Fitted 3
                [required] => Required 3
                [cost] => 3.00
            )

    )
</code>```

答:
While this solution might come handy. It's not the ideal solution.

```<code>function add_parts_db()
    {
        $parts = array (
                    'job_number'    => $this->input->post('job_no'),
                    'quantity'      => $this->input->post('parts_qty'),
                    'parts'         => $this->input->post('parts_description'),
                    'fitted'        => $this->input->post('parts_fitted'),
                    'required'      => $this->input->post('parts_required'),
                    'cost'          => $this->input->post('parts_cost')
                );

           $partsArr = [];
           $totalCnt = count($parts['job_number']);
          for($key=0; $key < $totalCnt ;$key++)
          {
           $partsArr[] = [
              'job_number' => $parts['job_number'][$key] ,
              'quantity'   => $parts['quantity'][$key] ,
              'parts'      => $parts['parts'][$key] ,
              'fitted'     => $parts['fitted'][$key] ,
              'required'   => $parts['required'][$key] ,
              'cost'       => $parts['cost'][$key]];

           }
            //just make sure that your service_model uses `insert_batch` method to  insert data
            $this->service_model->add_parts_db($partsArr);
            redirect('service', 'refresh');
     }
</code>```

For more information read documentation

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to insert an array into a database table as separate rows. The array is generated from a table where the user can add additional rows. Can't get my head around what is going wrong!

Here is the view

      Quantity
      Parts
      Fitted
      Required
      Cost

      <input type="hidden" name="job_no[]" value="<?php echo $job_number; ?>" />
      <input type="number" name="parts_qty[]" class="form-control" />
      <input type="text" name="parts_description[]" class="form-control" />
      <input type="text" name="parts_fitted[]" class="form-control" />
      <input type="text" name="parts_required[]" class="form-control" />
      <input type="text" name="parts_cost[]" class="form-control" />

<button type="button" class="btn btn-primary btn-xs" id="addRow">   Add Row </button>

Please note this is part of a larger form so not showing the submit buttons e.t.c

My Controller function looks like this

function add_parts_db()
    {
        $parts = array (
                    'job_number'    => $this->input->post('job_no'),
                    'quantity'      => $this->input->post('parts_qty'),
                    'parts'         => $this->input->post('parts_description'),
                    'fitted'        => $this->input->post('parts_fitted'),
                    'required'      => $this->input->post('parts_required'),
                    'cost'          => $this->input->post('parts_cost')
                );

                $this->service_model->add_parts_db($parts);
                redirect('service', 'refresh');
    }

Here is the array being generated with some sample input in the table

Array
(
    [job_number] => Array
        (
            [0] => 2008
            [1] => 2008
            [2] => 2008
        )

    [quantity] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [parts] => Array
        (
            [0] => Part 1
            [1] => Part 2
            [2] => Parts 3
        )

    [fitted] => Array
        (
            [0] => Fitted 1
            [1] => Fitted 1
            [2] => Fitted 3
        )

    [required] => Array
        (
            [0] => Required 1
            [1] => Required 2
            [2] => Required 3
        )

    [cost] => Array
        (
            [0] => 1.00
            [1] => 2.00
            [2] => 3.00
        )

)

Finally my model which I want to insert each item of the array into the database table as a separate row.

function add_parts_db($parts)
{
    $this->db->insert_batch('parts', $parts);
    return $this->db->insert_id();
}

I would like the above array to be inserted into the database as separate rows so should look something like this

I'm getting the following error when submitting the form

    Error Number: 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 '0, 1, 2) VALUES ('2008','2008','2008'), ('1','2','3'), ('Part 1','Part 2','Parts' at line 1

INSERT INTO `parts` (0, 1, 2) VALUES ('2008','2008','2008'), ('1','2','3'), ('Part 1','Part 2','Parts 3'), ('Fitted 1','Fitted 1','Fitted 3'), ('Required 1','Required 2','Required 3'), ('1.00','2.00','3.00')

Filename: models/Service_model.php

Line Number: 33

I think the problem might be in my jQuery/Javascript which I'm not quite understanding. I can set the initial key to 0 using name="parts[0][jobnumber]" but then in my jQuery I don't think it's recognising the variable properly

var $i = 1;
        $("#addRow").click(function(){
                $("#parts").append("
<input type='hidden' name='parts[$i][jobnumber]' value='<?php echo $job_number; ?>' /><input type='number' name='parts[$i][qty]' class='form-control' />	<input type='text' name='parts[$i][description]' class='form-control' />	<input type='text' name='parts[i][fitted]' class='form-control' />	<input type='text' name='parts[$i][required]' class='form-control' />	<input type='text' name='parts[$i][cost]' class='form-control' />
");
                i++;
        });

I think dumping the array looks like it's going to pull the correct array format through but it's not getting it because of my inept jQuery.

 ["parts"]=>
  array(2) {
    [0]=>
    array(5) {
      ["jobnumber"]=>
      string(4) "2002"
      ["qty"]=>
      string(1) "3"
      ["description"]=>
      string(7) "parts 3"
      ["required"]=>
      string(10) "required 3"
      ["cost"]=>
      string(4) "3.00"
    }
    ["i"]=>
    array(1) {
      ["fitted"]=>
      string(8) "fitted 3"
    }
  }

This is showing a syntax error if I go with the second reply

@Bhaumik Mehta

 Array
    (
        [0] => Array
            (
                [job_number] => 2002
                [quantity] => 1
                [parts] => parts 1
                [fitted] => Fitted 1
                [required] => Required 1
                [cost] => 1.00
            )

        [1] => Array
            (
                [job_number] => 2002
                [quantity] => 2
                [parts] => Part 2
                [fitted] => Fitted 2
                [required] => Required 2
                [cost] => 2.00
            )

        [2] => Array
            (
                [job_number] => 2002
                [quantity] => 3
                [parts] => Parts 3
                [fitted] => Fitted 3
                [required] => Required 3
                [cost] => 3.00
            )

    )

Body:
While this solution might come handy. It's not the ideal solution.

function add_parts_db()
    {
        $parts = array (
                    'job_number'    => $this->input->post('job_no'),
                    'quantity'      => $this->input->post('parts_qty'),
                    'parts'         => $this->input->post('parts_description'),
                    'fitted'        => $this->input->post('parts_fitted'),
                    'required'      => $this->input->post('parts_required'),
                    'cost'          => $this->input->post('parts_cost')
                );

           $partsArr = [];
           $totalCnt = count($parts['job_number']);
          for($key=0; $key < $totalCnt ;$key++)
          {
           $partsArr[] = [
              'job_number' => $parts['job_number'][$key] ,
              'quantity'   => $parts['quantity'][$key] ,
              'parts'      => $parts['parts'][$key] ,
              'fitted'     => $parts['fitted'][$key] ,
              'required'   => $parts['required'][$key] ,
              'cost'       => $parts['cost'][$key]];

           }
            //just make sure that your service_model uses `insert_batch` method to  insert data
            $this->service_model->add_parts_db($partsArr);
            redirect('service', 'refresh');
     }

For more information read documentation


问:
split string by commas, with exception
I have a string with color names, separated by commas or | characters:

```<code>$s = 'Blue | Red (light, dark) | Green, Yellow, Brown';
</code>```

I need to convert it to array:

```<code>$colors = preg_split('![\|,]!', $s);
</code>```

But the result is:

```<code>Array
(
    [0] => Blue
    [1] =>  Red (light
    [2] =>  dark)
    [3] =>  Green
    [4] =>  Yellow
    [5] =>  Brown
)
</code>```

It splits the "light, dark" string with comma. I'd like to split with commas not inside parentheses. Desired result:

```<code>Array
(
    [0] => Blue
    [1] =>  Red (light, dark)
    [2] =>  Green
    [3] =>  Yellow
    [4] =>  Brown
)
</code>```

How can I solve it?

答:
You only need to disqualify delimiters inside of the parentheticals with (*SKIP)(*FAIL).  I've also added zero or more spaces before and after the delimiter so that the output values are trimmed.

Code: (Demo)

```<code>$s = 'Blue | Red (light, dark) | Green, Yellow, Brown';
$colors = preg_split('/\([^)]+(*SKIP)(*FAIL)|\s*[,|]\s*/',$s);
var_export($colors);

echo "\n";

$str = 'Blue | Red (light, dark) | Green, Yellow, Brown (light | bright)';
$colors = preg_split('/\([^)]+(*SKIP)(*FAIL)|\s*[,|]\s*/',$str);
var_export($colors);
</code>```

Output:

```<code>array (
  0 => 'Blue',
  1 => 'Red (light, dark)',
  2 => 'Green',
  3 => 'Yellow',
  4 => 'Brown',
)
array (
  0 => 'Blue',
  1 => 'Red (light, dark)',
  2 => 'Green',
  3 => 'Yellow',
  4 => 'Brown (light | bright)',
)
</code>```

For arguement's sake, you could just use this on your sample input string:

```<code>var_export(preg_match_all('/[a-z]+(?: \([^)]+\))?/i',$str,$out)?$out[0]:'fail');
</code>```

This case-insensitively matches the colors, then optionally includes a trailing parenthetical expression.  Same output.

Title: split string by commas, with exception

Body:
I have a string with color names, separated by commas or | characters:

$s = 'Blue | Red (light, dark) | Green, Yellow, Brown';

I need to convert it to array:

$colors = preg_split('![\|,]!', $s);

But the result is:

Array
(
    [0] => Blue
    [1] =>  Red (light
    [2] =>  dark)
    [3] =>  Green
    [4] =>  Yellow
    [5] =>  Brown
)

It splits the "light, dark" string with comma. I'd like to split with commas not inside parentheses. Desired result:

Array
(
    [0] => Blue
    [1] =>  Red (light, dark)
    [2] =>  Green
    [3] =>  Yellow
    [4] =>  Brown
)

How can I solve it?

Body:
You only need to disqualify delimiters inside of the parentheticals with (*SKIP)(*FAIL).  I've also added zero or more spaces before and after the delimiter so that the output values are trimmed.

Code: (Demo)

$s = 'Blue | Red (light, dark) | Green, Yellow, Brown';
$colors = preg_split('/\([^)]+(*SKIP)(*FAIL)|\s*[,|]\s*/',$s);
var_export($colors);

echo "\n";

$str = 'Blue | Red (light, dark) | Green, Yellow, Brown (light | bright)';
$colors = preg_split('/\([^)]+(*SKIP)(*FAIL)|\s*[,|]\s*/',$str);
var_export($colors);

Output:

array (
  0 => 'Blue',
  1 => 'Red (light, dark)',
  2 => 'Green',
  3 => 'Yellow',
  4 => 'Brown',
)
array (
  0 => 'Blue',
  1 => 'Red (light, dark)',
  2 => 'Green',
  3 => 'Yellow',
  4 => 'Brown (light | bright)',
)

For arguement's sake, you could just use this on your sample input string:

var_export(preg_match_all('/[a-z]+(?: \([^)]+\))?/i',$str,$out)?$out[0]:'fail');

This case-insensitively matches the colors, then optionally includes a trailing parenthetical expression.  Same output.


问:
React-Native - undefined is not an object (“evaluating _react3.default.PropTypes.shape”)
ERROR:

```<code>undefined is not an object (“evaluating _react3.default.PropTypes.shape”)
...
<unknown>
App.js 15
...
</code>```

Refer:
http://rationalappdev.com/react-native-list-app-complete-how-to-guide/

App.js:

```<code>import React, { Component } from 'react';

import {
  Platform,
  StyleSheet,
  Text,
  View
} from 'react-native';

import NavigationExperimental from 'react-native-deprecated-custom-components';

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

const RouteMapper = (route, navigationOperations, onComponentRef) => {
  if (route.name === 'list') {
    return (
      // TODO: Add List component
      <Text>The list is going to be here</Text>
    );
  } else if (route.name === 'movie') {
    // TODO: Add Movie component for a movie detail screen
  }
};

export default class App extends Component<{}> {
  render() {
    return (
      <NavigationExperimental.Navigator
        // Default to list route
        initialRoute={{name: 'list'}}
        // Use FloatFromBottom transition between screens
        configureScene={(route, routeStack) => NavigationExperimental.Navigator.SceneConfigs.FloatFromBottom}
        // Pass a route mapper functions
        renderScene={RouteMapper}
      />
    );
  }
}
</code>```

package.json

```<code>{
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react": "16.0.0-beta.5",
    "react-native": "0.49.3",
    "react-native-deprecated-custom-components": "^0.1.1"
  },
  "devDependencies": {
    "babel-jest": "21.2.0",
    "babel-preset-react-native": "4.0.0",
    "jest": "21.2.1",
    "react-test-renderer": "16.0.0-beta.5"
  },
  "jest": {
    "preset": "react-native"
  }
}
</code>```

Any ideas? Thanks

UPDATE

still not working after install prop-types

答:
PropTypes has been moved out of react and into it's own component:
https://www.npmjs.com/package/prop-types

According to the README, they recommend adding prop-types to your dependencies block in package.json

```<code>npm install --save prop-types
</code>```

Then to use it:

```<code>import PropTypes from 'prop-types'; // ES6
var PropTypes = require('prop-types'); // ES5 with npm
</code>```

Body:
ERROR:

undefined is not an object (“evaluating _react3.default.PropTypes.shape”)
...
<unknown>
App.js 15
...

Refer:
http://rationalappdev.com/react-native-list-app-complete-how-to-guide/

App.js:

import React, { Component } from 'react';

import {
  Platform,
  StyleSheet,
  Text,
  View
} from 'react-native';

import NavigationExperimental from 'react-native-deprecated-custom-components';

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

const RouteMapper = (route, navigationOperations, onComponentRef) => {
  if (route.name === 'list') {
    return (
      // TODO: Add List component
      <Text>The list is going to be here</Text>
    );
  } else if (route.name === 'movie') {
    // TODO: Add Movie component for a movie detail screen
  }
};

export default class App extends Component<{}> {
  render() {
    return (
      <NavigationExperimental.Navigator
        // Default to list route
        initialRoute={{name: 'list'}}
        // Use FloatFromBottom transition between screens
        configureScene={(route, routeStack) => NavigationExperimental.Navigator.SceneConfigs.FloatFromBottom}
        // Pass a route mapper functions
        renderScene={RouteMapper}
      />
    );
  }
}

package.json

{
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react": "16.0.0-beta.5",
    "react-native": "0.49.3",
    "react-native-deprecated-custom-components": "^0.1.1"
  },
  "devDependencies": {
    "babel-jest": "21.2.0",
    "babel-preset-react-native": "4.0.0",
    "jest": "21.2.1",
    "react-test-renderer": "16.0.0-beta.5"
  },
  "jest": {
    "preset": "react-native"
  }
}

Any ideas? Thanks

UPDATE

still not working after install prop-types

Body:
PropTypes has been moved out of react and into it's own component:
https://www.npmjs.com/package/prop-types

According to the README, they recommend adding prop-types to your dependencies block in package.json

npm install --save prop-types

Then to use it:

import PropTypes from 'prop-types'; // ES6
var PropTypes = require('prop-types'); // ES5 with npm


问:
Why is the code body not giving the same result?
This code as follows displays the least commonly repeated number in the list and works correctly and gives me the answer 3...

```<code>    theList = [1,3,1,2,2]
listCheck, least = len(theList), 0
for theLeast in theList:
    if theList.count(theLeast) <= listCheck :
        listCheck = theList.count(theLeast)
        least = theLeast
print (least)
</code>```

However when I define & change the list to a sequence of integers, the code says that 1 is the least common??

```<code> def The_uncommon(integers):
    theList = integers
    listCheck, least = len(theList), 0
    for theLeast in theList:
        if theList.count(theLeast) <= listCheck :
            listCheck = theList.count(theLeast)
            least = theLeast
            return (least)
print(The_uncommon([1,3,1,2,2]))
</code>```

Any advice is welcome

答:
Be careful about your indentation. :)

In the first snippet, you are iterating through the entire loop, whereas in the second example where you define a function, you are returning the first least occurrence.

Body:
This code as follows displays the least commonly repeated number in the list and works correctly and gives me the answer 3...

    theList = [1,3,1,2,2]
listCheck, least = len(theList), 0
for theLeast in theList:
    if theList.count(theLeast) <= listCheck :
        listCheck = theList.count(theLeast)
        least = theLeast
print (least)

However when I define & change the list to a sequence of integers, the code says that 1 is the least common??

 def The_uncommon(integers):
    theList = integers
    listCheck, least = len(theList), 0
    for theLeast in theList:
        if theList.count(theLeast) <= listCheck :
            listCheck = theList.count(theLeast)
            least = theLeast
            return (least)
print(The_uncommon([1,3,1,2,2]))

Any advice is welcome


问:
how to add instance to the list and then to the listbox in windows form
I don't know how to add Instances of my Album class from TextBoxes to a List<Album> and then to a ListBox in my WindowsForm.

Here is the code I have written so far but I'm stuck here and I don't know what to do next.

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    List<Album> AlbumList = new List<Album>();

    private void TrackButton_Click(object sender, EventArgs e)
    {
        addTracks settingsForm = new addTracks();
        settingsForm.ShowDialog();
    }

    private void CreateButton_Click(object sender, EventArgs e)
    {
        Album g = new Album (ASINtextBox.Text, AlbumNametextBox.Text, ArtisttextBox.Text,
            ReleaseDatePicker.Text, LabeltextBox.Text, ImagetextBox.Text);

        AlbumList.Add(g);
    }
}
</code>```

I dont have eny error i just think it is not creating a new list when I'm debuging the program.

This is the code for the class:

```<code>eclass Album
{
    private string ASIN;
    private string AlbumName;
    private string Artist;
    private string ReleaseDate;
    private string Label;
    private string Image;

    public Album(int ASIN)
    {
        this.ASIN = "no value";
        this.AlbumName = "no value";
        this.Artist = "no value";
        this.ReleaseDate = "no value";
        this.Label = "no value";
        this.Image = "no value";
    }

    public Album(string ASIN, string AlbumName, string Artist, string ReleaseDate,
        string Label, string Image)
    {
        this.ASIN = ASIN;
        this.AlbumName = AlbumName;
        this.Artist = Artist;
        this.ReleaseDate = ReleaseDate;
        this.Label = Label;
        this.Image = Image;
    }

    public string aSIN
    {
        get { return this.ASIN; }
        set { ASIN = value; }
    }

    public string albumName
    {
        get { return this.AlbumName; }
        set { AlbumName = value; }
    }

    public string artist
    {
        get { return this.Artist; }
        set { Artist = value; }
    }

    public string createDate
    {
        get { return this.ReleaseDate; }
        set { ReleaseDate = value; }

    }

    public string label
    {
        get { return this.Label; }
        set { Label = value; }
    }

    public string image
    {
        get { return this.Image; }
        set { Image = value; }
    }
}
</code>```

答:
I solved the listbox by not adding in the list box but just showing the values through the labels.

```<code>private void ShowAlbumsButton_Click(object sender, EventArgs e)
    {
        int temp = AlbumList.Count();
        string talbumname = "";
        string talbumasin = "";
        string talbumartist = "";
        string talbumrelease = "";
        string talbumlabel = "";
        for (int n =0; n<temp;n++)
        {
            talbumname = talbumname + AlbumList[n].albumName;
            talbumname = talbumname + '\n';

           talbumasin = talbumasin + AlbumList[n].aSIN;
            talbumasin = talbumasin + '\n';

            talbumartist = talbumartist + AlbumList[n].artist;
            talbumartist = talbumartist + '\n';

            talbumrelease = talbumrelease + AlbumList[n].createDate;
            talbumrelease = talbumrelease + '\n';

            talbumlabel = talbumlabel + AlbumList[n].label;
            talbumlabel = talbumlabel + '\n';

        }
        label8.Text = talbumname;

        label7.Text = talbumasin;

        label9.Text = talbumartist;

        label10.Text = talbumrelease;

        label11.Text = talbumlabel;
    }
</code>```

thanks everyone for help.

Body:
I don't know how to add Instances of my Album class from TextBoxes to a List<Album> and then to a ListBox in my WindowsForm.

Here is the code I have written so far but I'm stuck here and I don't know what to do next.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    List<Album> AlbumList = new List<Album>();

    private void TrackButton_Click(object sender, EventArgs e)
    {
        addTracks settingsForm = new addTracks();
        settingsForm.ShowDialog();
    }

    private void CreateButton_Click(object sender, EventArgs e)
    {
        Album g = new Album (ASINtextBox.Text, AlbumNametextBox.Text, ArtisttextBox.Text,
            ReleaseDatePicker.Text, LabeltextBox.Text, ImagetextBox.Text);

        AlbumList.Add(g);
    }
}

I dont have eny error i just think it is not creating a new list when I'm debuging the program.

This is the code for the class:

eclass Album
{
    private string ASIN;
    private string AlbumName;
    private string Artist;
    private string ReleaseDate;
    private string Label;
    private string Image;

    public Album(int ASIN)
    {
        this.ASIN = "no value";
        this.AlbumName = "no value";
        this.Artist = "no value";
        this.ReleaseDate = "no value";
        this.Label = "no value";
        this.Image = "no value";
    }

    public Album(string ASIN, string AlbumName, string Artist, string ReleaseDate,
        string Label, string Image)
    {
        this.ASIN = ASIN;
        this.AlbumName = AlbumName;
        this.Artist = Artist;
        this.ReleaseDate = ReleaseDate;
        this.Label = Label;
        this.Image = Image;
    }

    public string aSIN
    {
        get { return this.ASIN; }
        set { ASIN = value; }
    }

    public string albumName
    {
        get { return this.AlbumName; }
        set { AlbumName = value; }
    }

    public string artist
    {
        get { return this.Artist; }
        set { Artist = value; }
    }

    public string createDate
    {
        get { return this.ReleaseDate; }
        set { ReleaseDate = value; }

    }

    public string label
    {
        get { return this.Label; }
        set { Label = value; }
    }

    public string image
    {
        get { return this.Image; }
        set { Image = value; }
    }
}

Body:
I solved the listbox by not adding in the list box but just showing the values through the labels.

private void ShowAlbumsButton_Click(object sender, EventArgs e)
    {
        int temp = AlbumList.Count();
        string talbumname = "";
        string talbumasin = "";
        string talbumartist = "";
        string talbumrelease = "";
        string talbumlabel = "";
        for (int n =0; n<temp;n++)
        {
            talbumname = talbumname + AlbumList[n].albumName;
            talbumname = talbumname + '\n';

           talbumasin = talbumasin + AlbumList[n].aSIN;
            talbumasin = talbumasin + '\n';

            talbumartist = talbumartist + AlbumList[n].artist;
            talbumartist = talbumartist + '\n';

            talbumrelease = talbumrelease + AlbumList[n].createDate;
            talbumrelease = talbumrelease + '\n';

            talbumlabel = talbumlabel + AlbumList[n].label;
            talbumlabel = talbumlabel + '\n';

        }
        label8.Text = talbumname;

        label7.Text = talbumasin;

        label9.Text = talbumartist;

        label10.Text = talbumrelease;

        label11.Text = talbumlabel;
    }

thanks everyone for help.


问:
Program iPhone Applications in Windows?
Is it possible? From what I have heard it is. I wouldn't mind just programming them in raw Objective-C. If someone could give a link to the UIKit frameworks and stuff. My iPod touch is jailbroken and I could use its frameworks, but then I couldn't utilize 3G, Camera, Phone. Please help!</p>

答:
the short answer will be NO.

However, it is possible to implement parts of your Iphone application on Windows. Start by installing GNUstep, after that you should be able to code in Objective-C.

Take as example a small two-dimensional game implementation, you can implement on your Windows machine 90% of the app (game AI, help functions etc.). If you use OpenGL ES for the graphical part you can code parts of it on Windows too.

You can find a concise introduction on how to start with Objective-C on Windows on this blog:

http://drunkenprogrammerblog.blogspot.com/

Best wishes

ContentLicense: CC BY-SA 2.5

Title: Program iPhone Applications in Windows?


问:
sending mail with image using sendgrid
"code for sending email above is the code .iam tired of scratching my head but still not able to see the image in the mail. I am converting the image into base 64 encoded string and also following the sendgrid syntax still not able to send the image .i dunno wats going wrong here.:"</p>

```<code>var app = require("../../../server/server");
var base64Img = require("base64-img");

let status = null;
let textBody,
  htmBody = null;
var DataSource = require("loopback-datasource-juggler").DataSource;
var dsSendGrid = new DataSource("loopback-connector-sendgrid", {
  api_key: app.customConfig.mail.sendgrid.api_key
});

var fs = require("fs");

function base64_encode(file) {
  var bitmap = fs.readFileSync(file);
  return new Buffer(bitmap).toString("base64");
}

function base64_decode(base64str, file) {
  var bitmap = new Buffer(base64str, "base64");
  fs.writeFileSync(file, bitmap);
  console.log(
    "******** File created from base64 encoded string ********",
    base64str
  );
}

var base64str = base64_encode("../../../images/Campaign-images/Christmas.png");

let message = {
  to: "somebody@gmail.com",
  from: "noreply@gmail.com",
  subject: "test",
  text: "hi",
  html: '<img src="cid:myimagecid"/>',
  attachment: [
    {
      filename: "Christmas2.png",
      content: base64str,
      ContentId: "myimagecid"
    }
  ]
};
console.log(message);
app.models.Email.send(message)
  .then(result => {
    return "sent";
  })
  .catch(err => {
    console.log(err);

    return "failed";
  });
</code>```

答:
If I look to the https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html

I see it is attachments not attachment

Also there is content_id instead of ContentId

Also make sure, you are using right version (I am pointing to v3 but I think you can choose to use v2)

Title: sending mail with image using sendgrid

Body:
"code for sending email above is the code .iam tired of scratching my head but still not able to see the image in the mail. I am converting the image into base 64 encoded string and also following the sendgrid syntax still not able to send the image .i dunno wats going wrong here.:"

var app = require("../../../server/server");
var base64Img = require("base64-img");

let status = null;
let textBody,
  htmBody = null;
var DataSource = require("loopback-datasource-juggler").DataSource;
var dsSendGrid = new DataSource("loopback-connector-sendgrid", {
  api_key: app.customConfig.mail.sendgrid.api_key
});

var fs = require("fs");

function base64_encode(file) {
  var bitmap = fs.readFileSync(file);
  return new Buffer(bitmap).toString("base64");
}

function base64_decode(base64str, file) {
  var bitmap = new Buffer(base64str, "base64");
  fs.writeFileSync(file, bitmap);
  console.log(
    "******** File created from base64 encoded string ********",
    base64str
  );
}

var base64str = base64_encode("../../../images/Campaign-images/Christmas.png");

let message = {
  to: "somebody@gmail.com",
  from: "noreply@gmail.com",
  subject: "test",
  text: "hi",
  html: '',
  attachment: [
    {
      filename: "Christmas2.png",
      content: base64str,
      ContentId: "myimagecid"
    }
  ]
};
console.log(message);
app.models.Email.send(message)
  .then(result => {
    return "sent";
  })
  .catch(err => {
    console.log(err);

    return "failed";
  });


问:
How to include an HTML file with jQuery?
I want to make my code separate so I decided to divide each div to html files. Each HTML file has some jQuery click events. I have 2 files index.html and menu.html.

Problem is that I have to include the jQuery library in both files to make it work.

Is there any way that I can include library one time and have it work on both files? I tried to include the library in the  index page only, but then the menu click doesn't work.

I included the menu.html file through an iframe.

```<code><iframe src="left-menu.html"></iframe>
</code>```

答:
In your HTML:

```<code><body>
<header>
     <div data-includeHTML="_HeaderPartial.html"></div>
</header>
<main>
    <div>
        This is the main content, from the index file
    </div>
</main>
<footer>
    <div data-includeHTML="_FooterPartial.html"></div>
</footer>
<script>
    $(document).ready(function () {
        $("div[data-includeHTML]").each(function () {
            $(this).load($(this).attr("data-includeHTML"));
        });
    });
</script>
</body>
</code>```

In a separate file "_HeaderPartial.html":

```<code><div>
    <h1>This is the Header from its _Partial file</h1>
</div>
</code>```

In a separate file "_FooterPartial.html":

```<code><strong>And this is from the footer partial file</strong>
</code>```

The result:

This is the Header from its _Partial file

This is the main content, from the index file

And this is from the footer partial file

Body:
In your HTML:

<body>
<header>
     <div data-includeHTML="_HeaderPartial.html"></div>
</header>
<main>
    <div>
        This is the main content, from the index file
    </div>
</main>
<footer>
    <div data-includeHTML="_FooterPartial.html"></div>
</footer>
<script>
    $(document).ready(function () {
        $("div[data-includeHTML]").each(function () {
            $(this).load($(this).attr("data-includeHTML"));
        });
    });
</script>
</body>

In a separate file "_HeaderPartial.html":

<div>
    <h1>This is the Header from its _Partial file</h1>
</div>

In a separate file "_FooterPartial.html":

<strong>And this is from the footer partial file</strong>

The result:

This is the Header from its _Partial file

This is the main content, from the index file

And this is from the footer partial file


问:
Codeception:how to color test message
I want to color message.
If test passed then output message color green else red.</p>

```<code> $I = $this->apiTester;  //$this->apiTester is instance of ApiTester.php Class

    if ($outputData['success'] == true) {        //$outputdata is json array
        $I->comment("see test status:Passed.");  //I want its color green
    } else {
        $I->comment("see test status:Failed.");  //I want its color red
    }
</code>```

答:
A good solution to do this is to create a new Color.php Helper class in your  _support/Helper directory of Codeception using this class and modifying the namespace to:
namespace Helper;

Then you can just use it like this in your tests:

```<code>$I->comment(\Helper\Color::set("see test status:Failed.", "red");
</code>```

Title: Codeception:how to color test message

Body:
I want to color message.
If test passed then output message color green else red.

 $I = $this->apiTester;  //$this->apiTester is instance of ApiTester.php Class

    if ($outputData['success'] == true) {        //$outputdata is json array
        $I->comment("see test status:Passed.");  //I want its color green
    } else {
        $I->comment("see test status:Failed.");  //I want its color red
    }

Body:
A good solution to do this is to create a new Color.php Helper class in your  _support/Helper directory of Codeception using this class and modifying the namespace to:
namespace Helper;

Then you can just use it like this in your tests:

$I->comment(\Helper\Color::set("see test status:Failed.", "red");


问:
what is the best way to argue about the big O or about theta?
We're asked to provide a  $ n+4![\sqrt{n}] =O(n) $ with having a good argumentation and a logical build up for it but it's not said how a good argumentation would look like, so I know that $2n+4\sqrt{n}$ always bigger for n=1 but i wouldn't know how to argue about it and how to logically build it since i just thought about it and it happened to be true. Can someone help out with this example so i would know how to do it?</p>

答:
A proof is a convincing, logical argument. When in doubt, a good way to write a convincing, logical argument is to use an accepted template for your argument. Then, others can simply check that you have used the template correctly and, if so, the validity of your argument follows.

A useful template for showing asymptotic bounds is mathematical induction. To use this, you show that what you are trying to prove is true for specific simple cases, called base cases, then you assume it is true in all cases up to a certain size (the induction hypothesis) and you finish the proof by showing the hypothesis implies the claim is true for cases of the very next size. If done correctly, you will have shown the claim (parameterized by a natural number n) is true for a fixed n and for all larger n. This is what is exactly what is required for proving asymptotic bounds.

In your case: we want to show that n + 4 * sqrt(n) = O(n). Recall that the (one?) formal definition of big-Oh is the following:

A function f is bound from above by a function g, written f(n) = O(g(n)), if there exist constants c > 0 and n0 > 0 such that for all n > n0, f(n) <= c * g(n).

Consider the case n = 0. We have n + 4 * sqrt(n) = 0 + 4 * 0 = 0 <= 0 = c * 0 = c * n for any constant c. If we now assume the claim is true for all n up to and including k, can we show it is true for n = k + 1? This would require (k + 1) + 4 * sqrt(k + 1) <= c * (k + 1). There are now two cases:

k + 1 is not a perfect square. Since we are doing analysis of algorithms it is implied that we are using integer math, so sqrt(k + 1) = sqrt(k) in this case. Therefore, (k + 1) + 4 * sqrt(k + 1) = (k + 4 * sqrt(k)) + 1 <= (c * k) + 1 <= c * (k + 1) by the induction hypothesis provided that c > 1.

k + 1 is a perfect square. Since we are doing analysis of algorithms it is implied that we are using integer math, so sqrt(k + 1) = sqrt(k) + 1 in this case. Therefore, (k + 1) + 4 * sqrt(k + 1) = (k + 4 * sqrt(k)) + 5 <= (c * k) + 5 <= c * (k + 1) by the induction hypothesis provided that c >= 5.

Because these two cases cover all possibilities and in each case the claim is true for n = k + 1 when we choose c >= 5, we see that n + 4 * sqrt(n) <= 5 * n for all n >= 0 = n0. This concludes the proof that n + 4 * sqrt(n) = O(n).


问:
Viewing memory usage stats of a dotnetcore 2 self contained application on Linux
I have a c# dotnet core 2 application that runs as a systemd service on Linux 14.04 LTS that slows to a crawl after a week or more of running and eventually the application and the OS hang, and I cant even open htop. I used perfcollect and perfview, but was only able to get call stack information. How can I collect memory usage statistics of my application and then display them in a readable format?</p>

答:
You could retrieve and log memory usage using System.Diagnostic.Process:

```<code>var process = Process.GetCurrentProcess();
var currentMemoryUsage = process.WorkingSet64;
</code>```

The value returned by the WorkingSet64 property represents the current size of working set memory used by the process, in bytes.

and the peak memory usage:

```<code>var peakPhysicalMemoryUsage = process.PeakWorkingSet64;
</code>```

Body:
You could retrieve and log memory usage using System.Diagnostic.Process:

var process = Process.GetCurrentProcess();
var currentMemoryUsage = process.WorkingSet64;

The value returned by the WorkingSet64 property represents the current size of working set memory used by the process, in bytes.

and the peak memory usage:

var peakPhysicalMemoryUsage = process.PeakWorkingSet64;


问:
LINQ .ToList() fails on single result
It could be that its late Friday evening and I want to go home, or more likely I just can't see the problem...

I have the fallowing LINQ code:

```<code>mthumbs = itm.Elements(nsr + "thumbnail") != null ?
      (from mt in itm.Elements(nsr + "thumbnail")
       select new MediaThumbnail
       {
         mediaThumbnailUrl = (string)mt.Attribute("url") ?? null,
         mediaThumbnailHeight = (string)mt.Attribute("height") ?? null,
         mediaThumbnailWidth = (string)mt.Attribute("width") ?? null,
         mediaThumbnailTime = (string)mt.Attribute("time").Value ?? null
        }).ToList() : null
</code>```

The MediaThumbnail Class looks like:

```<code>public class MediaThumbnail
{
    public string mediaThumbnailUrl { get; set; }
    public string mediaThumbnailWidth { get; set; }
    public string mediaThumbnailHeight { get; set; }
    public string mediaThumbnailTime { get; set; }
}
</code>```

and resides in the MediaOptElement class which looks like:

```<code>public class MediaOptElement
{
    public string mediaPlayer { get; set; }
    public string mediaRating { get; set; }
    public string mediaRatingScheme { get; set; }
    public string mediaTitle { get; set; }
    public string mediaTitleType { get; set; }
    public string mediaDescription { get; set; }
    public string mediaDescriptionType { get; set; }
    public string mediaKeywords { get; set; }
    public List<MediaThumbnail> mthumbs { get; set; }
    public string mediaCategory { get; set; }
    public string mediaCategoryScheme { get; set; }
    public string mediaCategoryLabel { get; set; }
    public string mediaHash { get; set; }
    public string mediaHashAlgorithm { get; set; }
    public string mediaCopyRights { get; set; }
    public string mediaCopyrightsUrl { get; set; }
    public string mediaRestrictions { get; set; }
    public string mediaRestrictionsRelation { get; set; }
    public string mediaRestrictionsType { get; set; }
    public List<MediaCredit> mediaCredit { get; set; }
}
</code>```

Some Sample XML:

```<code>   <?xml version="1.0" encoding="UTF-8" ?>
   <rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/">
      <channel>
        <title>wdbj7.com - Sports</title>
        <link>http://www.wdbj7.com/sports/?track=rss</link>
        <description>Headlines from wdbj7.com</description>
        <language>en</language>
        <copyright>©2011, wdbj7.com</copyright>
        <lastBuildDate>Fri, 21 Jan 2011 10:47:00 -0500</lastBuildDate>
        <item>
          <title>Brookville improves to 15-0</title>
          <link>http://www.wdbj7.com/sports/wdbj7-brookville-improves-to-150-01212011,0,675989.story?track=rss</link>
          <description><p>The Brookville girls' basketball team graduated two college basketball players last year. That was the last time they lost anything.</p> <p>The Lady Bees are 14-0 on the young season and looked to add to that mark Thursday night against Seminole district rival Liberty.</p> <p>The Minettes playing at home, had just three wins on the year.  Haley Comer gets two for the home team. Liberty takes the 2-0 lead.  That is when it becomes the Katie Deacon show.</p> <p>The four-year varsity player starts it with the defense.  She gets the steal on one end and a basket on the other.</p> <p>Deacon takes her game behind the three point arc!  That beats the buzzer at the end of the first quarter!</p> <p>Deacon still not done.  She gets another steal and feeds George Mason signee Talisha Watts.<br /><br />Brookville improves to 15-0 with the 57-34 win. <br /><br /></p></description>
          <pubDate>Fri, 21 Jan 2011 10:47:00 -0500</pubDate>
          <media:thumbnail url="http://media.trb.com/media/thumbnails/story/2011-01/276990840-21074740.jpg" />
          <media:content url="http://media.trb.com/media/alternatethumbnails/story/2011-01/276990840-21074739.jpg" />
       </item>
     </channel>
  </rss>
</code>```

When I run my code, I get the following error:

```<code>   Object reference not set to an instance of an object.
</code>```

The stack trace is:

```<code>   at RssAggregator.Reader.RssReader.<>c__DisplayClass7d.<parseFeed>b__6e(XElement mt) in E:\Aggregator\VersionControl\FeedsParserLINQ\RssAggregator\Reader \RssReader.cs:line 843
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at RssAggregator.Reader.RssReader.<>c__DisplayClass7d.<parseFeed>b__57(XElement itm) in E:\Aggregator\VersionControl\FeedsParserLINQ\RssAggregator\Reader\RssReader.cs:line 667
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at RssAggregator.Reader.RssReader.parseFeed(XDocument xmlDoc) in E:\Aggregator\VersionControl\FeedsParserLINQ\RssAggregator\Reader\RssReader.cs:line 666
</code>```

I could be wrong, but I think the problem happens when the LINQ query only returns a single result.  However, I need to be able to handle cases when there might only be one media:thumbnail node or many media:thumbnail nodes. Any ideas?!  Thanks!

答:
I would look at his line:

```<code>mediaThumbnailTime = (string)mt.Attribute("time").Value ?? null
</code>```

My guess is that mt.Attribute("time") is null, and that's what's causing the exception. It's hard to tell for sure from the information we have. Perhaps something like:

```<code>mediaThumbnailTime = (mt.Attribute("time") != null ? (string)mt.Attribute("time").Value : null)
</code>```

Title: LINQ .ToList() fails on single result

Body:
It could be that its late Friday evening and I want to go home, or more likely I just can't see the problem...

I have the fallowing LINQ code:

mthumbs = itm.Elements(nsr + "thumbnail") != null ?
      (from mt in itm.Elements(nsr + "thumbnail")
       select new MediaThumbnail
       {
         mediaThumbnailUrl = (string)mt.Attribute("url") ?? null,
         mediaThumbnailHeight = (string)mt.Attribute("height") ?? null,
         mediaThumbnailWidth = (string)mt.Attribute("width") ?? null,
         mediaThumbnailTime = (string)mt.Attribute("time").Value ?? null
        }).ToList() : null

The MediaThumbnail Class looks like:

public class MediaThumbnail
{
    public string mediaThumbnailUrl { get; set; }
    public string mediaThumbnailWidth { get; set; }
    public string mediaThumbnailHeight { get; set; }
    public string mediaThumbnailTime { get; set; }
}

and resides in the MediaOptElement class which looks like:

public class MediaOptElement
{
    public string mediaPlayer { get; set; }
    public string mediaRating { get; set; }
    public string mediaRatingScheme { get; set; }
    public string mediaTitle { get; set; }
    public string mediaTitleType { get; set; }
    public string mediaDescription { get; set; }
    public string mediaDescriptionType { get; set; }
    public string mediaKeywords { get; set; }
    public List<MediaThumbnail> mthumbs { get; set; }
    public string mediaCategory { get; set; }
    public string mediaCategoryScheme { get; set; }
    public string mediaCategoryLabel { get; set; }
    public string mediaHash { get; set; }
    public string mediaHashAlgorithm { get; set; }
    public string mediaCopyRights { get; set; }
    public string mediaCopyrightsUrl { get; set; }
    public string mediaRestrictions { get; set; }
    public string mediaRestrictionsRelation { get; set; }
    public string mediaRestrictionsType { get; set; }
    public List<MediaCredit> mediaCredit { get; set; }
}

Some Sample XML:

   <?xml version="1.0" encoding="UTF-8" ?>
   <rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/">
      <channel>
        <title>wdbj7.com - Sports</title>
        <link>http://www.wdbj7.com/sports/?track=rss</link>
        <description>Headlines from wdbj7.com</description>
        <language>en</language>
        <copyright>©2011, wdbj7.com</copyright>
        <lastBuildDate>Fri, 21 Jan 2011 10:47:00 -0500</lastBuildDate>
        <item>
          <title>Brookville improves to 15-0</title>
          <link>http://www.wdbj7.com/sports/wdbj7-brookville-improves-to-150-01212011,0,675989.story?track=rss</link>
          <description>
The Brookville girls' basketball team graduated two college basketball players last year. That was the last time they lost anything.

The Lady Bees are 14-0 on the young season and looked to add to that mark Thursday night against Seminole district rival Liberty.

The Minettes playing at home, had just three wins on the year.  Haley Comer gets two for the home team. Liberty takes the 2-0 lead.  That is when it becomes the Katie Deacon show.

The four-year varsity player starts it with the defense.  She gets the steal on one end and a basket on the other.

Deacon takes her game behind the three point arc!  That beats the buzzer at the end of the first quarter!

Deacon still not done.  She gets another steal and feeds George Mason signee Talisha Watts.

Brookville improves to 15-0 with the 57-34 win.

</description>
          <pubDate>Fri, 21 Jan 2011 10:47:00 -0500</pubDate>
          <media:thumbnail url="http://media.trb.com/media/thumbnails/story/2011-01/276990840-21074740.jpg" />
          <media:content url="http://media.trb.com/media/alternatethumbnails/story/2011-01/276990840-21074739.jpg" />
       </item>
     </channel>
  </rss>

When I run my code, I get the following error:

   Object reference not set to an instance of an object.

The stack trace is:

   at RssAggregator.Reader.RssReader.<>c__DisplayClass7d.<parseFeed>b__6e(XElement mt) in E:\Aggregator\VersionControl\FeedsParserLINQ\RssAggregator\Reader \RssReader.cs:line 843
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at RssAggregator.Reader.RssReader.<>c__DisplayClass7d.<parseFeed>b__57(XElement itm) in E:\Aggregator\VersionControl\FeedsParserLINQ\RssAggregator\Reader\RssReader.cs:line 667
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at RssAggregator.Reader.RssReader.parseFeed(XDocument xmlDoc) in E:\Aggregator\VersionControl\FeedsParserLINQ\RssAggregator\Reader\RssReader.cs:line 666

I could be wrong, but I think the problem happens when the LINQ query only returns a single result.  However, I need to be able to handle cases when there might only be one media:thumbnail node or many media:thumbnail nodes. Any ideas?!  Thanks!

Body:
I would look at his line:

mediaThumbnailTime = (string)mt.Attribute("time").Value ?? null

My guess is that mt.Attribute("time") is null, and that's what's causing the exception. It's hard to tell for sure from the information we have. Perhaps something like:

mediaThumbnailTime = (mt.Attribute("time") != null ? (string)mt.Attribute("time").Value : null)


问:
WKWebView and UIMenuController
I have an app with a WKWebView in it.  In this app, I customize the options presented in the UIMenuController.  The web view seems to add Copy and Define options to the menu no matter what I do.  If I set myself as first responder and return NO for everything, I still get copy and define options.  And I've implemented my own copy option that does special things depending on user preferences and what exactly is selected. Is there a way to remove these extra options?

Update: I've filed this as radar 18487289.

答:
For iOS 11, simply subclass WKWebView and override canPerformAction to return false:

```<code>class WebView : WKWebView {
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        return false
    }
}
</code>```

For iOS 10 or earlier, swizzle WKContentView's canPerformAction method:

```<code>@objc private extension UIResponder {
    func swizzle_canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        return false
    }
}

guard let viewClass = NSClassFromString("WKContentView") as? UIView.Type else { return }
method_exchangeImplementations(
    class_getInstanceMethod(viewClass, #selector(UIResponder.canPerformAction))!,
    class_getInstanceMethod(UIResponder.self, #selector(UIResponder.swizzle_canPerformAction))!
)
</code>```

After remove those web view's build-in menu items, you can add your custom menu items via UIMenuController.shared like normal.

Title: WKWebView and UIMenuController

Body:
For iOS 11, simply subclass WKWebView and override canPerformAction to return false:

class WebView : WKWebView {
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        return false
    }
}

For iOS 10 or earlier, swizzle WKContentView's canPerformAction method:

@objc private extension UIResponder {
    func swizzle_canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        return false
    }
}

guard let viewClass = NSClassFromString("WKContentView") as? UIView.Type else { return }
method_exchangeImplementations(
    class_getInstanceMethod(viewClass, #selector(UIResponder.canPerformAction))!,
    class_getInstanceMethod(UIResponder.self, #selector(UIResponder.swizzle_canPerformAction))!
)

After remove those web view's build-in menu items, you can add your custom menu items via UIMenuController.shared like normal.


问:
CSS Gradient does not appear
whats wrong with this: I want to put a gradient in the background of the web iste.

$(body).css({ 'background': '-moz-linear-gradient(center bottom,rgb(255,255,255) 0%,rgb(241,250,254) 100%)' });

im using this library:
ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js

答:
Here are some hints:

You forgot to surround body selector with quotes:

```<code>$('body')
</code>```

You're using 'linear-gradient' with -moz- vendor prefix
(Mozilla). Vendors add prefixes to experimental or nonstandard CSS
properties. Modern browsers don't require these prefixes when using gradient and you should use them only to support some older versions.

First argument is used to describe gradient
direction: it can be an angle, e.g. 45deg or words: 'to left',
'to right', 'to top', 'to bottom' or a combination for diagonal gradient, e.g. 'to bottom right'. Default value is 'to bottom'.

Take a look at the snippet.

$('body').css({
  'background': 'linear-gradient(to right, rgb(255,255,255) 0%,rgb(241,250,254) 100%)'
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>From white to very light blue.</p></code>```

Title: CSS Gradient does not appear

Body:
Here are some hints:

You forgot to surround body selector with quotes:

$('body')

You're using 'linear-gradient' with -moz- vendor prefix
(Mozilla). Vendors add prefixes to experimental or nonstandard CSS
properties. Modern browsers don't require these prefixes when using gradient and you should use them only to support some older versions.

First argument is used to describe gradient
direction: it can be an angle, e.g. 45deg or words: 'to left',
'to right', 'to top', 'to bottom' or a combination for diagonal gradient, e.g. 'to bottom right'. Default value is 'to bottom'.

Take a look at the snippet.

$('body').css({
  'background': 'linear-gradient(to right, rgb(255,255,255) 0%,rgb(241,250,254) 100%)'
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>From white to very light blue.</p>


问:
Tensorflow median value
How can I calculate the median value of a list in tensorflow?
Like

```<code>node = tf.median(X)
</code>```

X is the placeholder

In numpy, I can directly use np.median to get the median value. How can I use the numpy operation in tensorflow?

答:
For calculating median of an array with tensorflow you can use the percentile function, since the 50th percentile is the median.

```<code>import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np

np.random.seed(0)
x = np.random.normal(3.0, .1, 100)

median = tfp.stats.percentile(x, 50.0, interpolation='midpoint')

tf.Session().run(median)
</code>```

The code above is equivalent to np.percentile(x, 50, interpolation='midpoint').

Title: Tensorflow median value

Body:
How can I calculate the median value of a list in tensorflow?
Like

node = tf.median(X)

X is the placeholder

In numpy, I can directly use np.median to get the median value. How can I use the numpy operation in tensorflow?

Body:
For calculating median of an array with tensorflow you can use the percentile function, since the 50th percentile is the median.

import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np

np.random.seed(0)
x = np.random.normal(3.0, .1, 100)

median = tfp.stats.percentile(x, 50.0, interpolation='midpoint')

tf.Session().run(median)

The code above is equivalent to np.percentile(x, 50, interpolation='midpoint').

ContentLicense: CC BY-SA 4.0


问:
laravel eloquent where clause with pivot
i have three table like below :

```<code>members
---------
id | tag | hasOn
1  |  1  |   1
2  |  2  |   1
3  |  3  |   0
4  |  1  |   1

tags
---------
id | title | date
1  |   a   |   05.12.2017 00:00:00
2  |   b   |   01.12.2017 00:00:00
3  |   c   |   12.11.2017 00:00:00
4  |   d   |   27.11.2017 00:00:00
</code>```

and has a pivot table

```<code>member_tag
-------------
member_id | tag_id | tagActive
    1     |    1   |    1
    1     |    2   |    1
    1     |    3   |    0
    1     |    4   |    1
    2     |    1   |    1
    2     |    2   |    1
    2     |    3   |    1
    2     |    4   |    1
</code>```

this is my code ( Auth::user referred to Member Model )

Auth::user()->tags()->where('date', '<', \Carbon\Carbon::now())->orWhere(function($q){
      $q->wherePivot('tagActive', 1);
  })->first();

it is not working.
i have to checkout member tags by "date < now" or "tagActive = 1"

how could i do this? ( check it out where to own table column or where to pivot table column)

答:
Try changing the order, so you can do this:

```<code>Auth::user()->tags()
    ->wherePivot('tagActive', 1)
    ->orWhere('date', '<', \Carbon\Carbon::now())
    ->first();
</code>```

wherePivot only exists on a BelongsToMany relation. It does not exist on a scopeless QueryBuilder, and that is what you get in a where clause with a closure.

Body:
i have three table like below :

members
---------
id | tag | hasOn
1  |  1  |   1
2  |  2  |   1
3  |  3  |   0
4  |  1  |   1

tags
---------
id | title | date
1  |   a   |   05.12.2017 00:00:00
2  |   b   |   01.12.2017 00:00:00
3  |   c   |   12.11.2017 00:00:00
4  |   d   |   27.11.2017 00:00:00

and has a pivot table

member_tag
-------------
member_id | tag_id | tagActive
    1     |    1   |    1
    1     |    2   |    1
    1     |    3   |    0
    1     |    4   |    1
    2     |    1   |    1
    2     |    2   |    1
    2     |    3   |    1
    2     |    4   |    1

this is my code ( Auth::user referred to Member Model )

Auth::user()->tags()->where('date', '<', \Carbon\Carbon::now())->orWhere(function($q){
      $q->wherePivot('tagActive', 1);
  })->first();

it is not working.
i have to checkout member tags by "date < now" or "tagActive = 1"

how could i do this? ( check it out where to own table column or where to pivot table column)

Body:
Try changing the order, so you can do this:

Auth::user()->tags()
    ->wherePivot('tagActive', 1)
    ->orWhere('date', '<', \Carbon\Carbon::now())
    ->first();

wherePivot only exists on a BelongsToMany relation. It does not exist on a scopeless QueryBuilder, and that is what you get in a where clause with a closure.


问:
Custom claims vs accessing refs in security rules?
We're integrating our Firebase app with Twitter auth and use the Twitter screen_name as our main human-readable username everywhere in the db.

When it comes to security rules, this is obviously a drawback: We don't know the screen_name as it is not included in auth.token. What we can do, is root.child('users').child($screen_name).child('uid').val() === auth.uid.

Only way to get the Twitter screen_name into the auth.token security rule context is via custom claims, right? What's the preferred method of doing this? Other pattern suggestions for human readable usernames?

答:
The option to add custom claims to user tokens is a relatively new addition to Firebase Authentication. Before this feature was available, storing additional information in the database was the only way to accomplish many scenarios. For that reason you'll find that most samples, questions, and documentation shows how to store the additional information in the database.

Storing additional claims in the token has many advantages though. A few of those:

Custom claims are already available in your security rules, while reading information from the database often requires an additional read.

Custom claims are available in the security rules for all products, while reading additional information from the database only works in database rules.

There are also a few advantages to using the database to store additional information:

The information in the database can be relatively unlimited, while the custom claims information must be kept really short.

I often prefer seeing the additional information in the database, because it's easier to scan the info that way.

If you're using the Twitter screen name in your security rules, it sounds like a natural fit for custom claims. If you also want to show the Twitter screen name for users in the UI, you'll probably also want to store it in the database.


问:
Unable to locate element using xpath from Auto suggest dropdown
I am trying to locate an element from an autosuggestion list using xpath but getting InvalidSelectorException. Below is my code:-

```<code>WebDriverWait wait=new WebDriverWait(driver, 10);
driver.findElement(By.xpath(".//*[@id='EngagementCode']")).sendKeys("111");
   wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//[@id='typeahead-5-5946-option-0']/a"))).click();
</code>```

Also please suggest How can I find it using different method if possible.

Please find HTML

```<code> <ul id="typeahead-5-5946" class="dropdown-menu ng-isolate-scope" ng-show="isOpen() && !moveInProgress" ng-style="{top: position().top+'px', left: position().left+'px'}" style="display: block; top: 34px; left: 15px;" role="listbox" aria-hidden="false" typeahead-popup="" matches="matches" active="activeIdx" select="select(activeIdx)" move-in-progress="moveInProgress" query="query" position="position">
<!-- ngRepeat: match in matches track by $index -->
<li id="typeahead-5-5946-option-0" class="ng-scope active" ng-repeat="match in matches track by $index" ng-class="{active: isActive($index) }" ng-mouseenter="selectActive($index)" ng-click="selectMatch($index)" role="option">
<a class="ng-binding ng-scope" href="" tabindex="-1" ng-bind-html="match.label | typeaheadHighlight:query">
xxx
<strong>111</strong>
x  - xxx services_xxx
</a>
</li>
<!-- end ngRepeat: match in matches track by $index -->
</code>```

答:
I don't know about your locators, as I can not see any element with id 'engagement code'. I yo can provide more coverage of HTML, then it will be easier to answer.
I would suggest to use Firefox plugin Firebug to inspect elements and Firepath to validate your xpath.
I have tried Google page autosuggestion box. Giving the code snippet below, See if this can help you.</p>

```<code> WebElement searchBox= driver.findElement(By.xpath("//input[@id='lst-ib']"));
    System.out.println("searchBox.isDisplayed(): "+searchBox.isDisplayed());
    searchBox.sendKeys("Seleni");

    System.out.println("search value: "+searchBox.getAttribute("value"));
    WebDriverWait wait = new WebDriverWait(driver, 10);
    wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@class='sbqs_c']")));

    List<WebElement> autoTextList = driver.findElements(By.xpath("//div[@class='sbqs_c']"));

    System.out.println("List size: "+autoTextList.size());
    for(WebElement listItem : autoTextList){
        System.out.println("List item: "+listItem.getText());
        if(listItem.getText().equals("selenium webdriver")) {
            listItem.click();
            break;
        }
    }
</code>```

Body:
I am trying to locate an element from an autosuggestion list using xpath but getting InvalidSelectorException. Below is my code:-

WebDriverWait wait=new WebDriverWait(driver, 10);
driver.findElement(By.xpath(".//*[@id='EngagementCode']")).sendKeys("111");
   wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//[@id='typeahead-5-5946-option-0']/a"))).click();

Also please suggest How can I find it using different method if possible.

Please find HTML

xxx
111
x  - xxx services_xxx

Body:
I don't know about your locators, as I can not see any element with id 'engagement code'. I yo can provide more coverage of HTML, then it will be easier to answer.
I would suggest to use Firefox plugin Firebug to inspect elements and Firepath to validate your xpath.
I have tried Google page autosuggestion box. Giving the code snippet below, See if this can help you.

 WebElement searchBox= driver.findElement(By.xpath("//input[@id='lst-ib']"));
    System.out.println("searchBox.isDisplayed(): "+searchBox.isDisplayed());
    searchBox.sendKeys("Seleni");

    System.out.println("search value: "+searchBox.getAttribute("value"));
    WebDriverWait wait = new WebDriverWait(driver, 10);
    wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@class='sbqs_c']")));

    List<WebElement> autoTextList = driver.findElements(By.xpath("//div[@class='sbqs_c']"));

    System.out.println("List size: "+autoTextList.size());
    for(WebElement listItem : autoTextList){
        System.out.println("List item: "+listItem.getText());
        if(listItem.getText().equals("selenium webdriver")) {
            listItem.click();
            break;
        }
    }


问:
HtmlUnitDriver is unable to locate a node
I cannot get HtmlUnitDriver to find elements on a page I am trying to access. WebDriver on the other hand works fine. Both are using the same method.
Here is my code:

```<code>import java.util.logging.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import com.gargoylesoftware.htmlunit.BrowserVersion;

public class Main {

    public static void main(String[]args)
    {
        FirefoxDriver driver2=new FirefoxDriver();

        HtmlUnitDriver driver=new HtmlUnitDriver(BrowserVersion.FIREFOX_10);
        driver.setJavascriptEnabled(true);
        Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);

        runTest(driver2); //works
        runTest(driver);  //does not work
    }

    public static void runTest(WebDriver driver)
    {
        driver.get("http://10.3.1.164");
        WebElement elem=driver.findElement(By.xpath("//td[2]/input"));
        assert elem.isDisplayed();
        System.out.println(driver.getTitle());
    }
}
</code>```

Here is the stacktrace:

```<code>Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to     locate a node using //td[2]/input
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.28.0', revision: '18309', time: '2012-12-11 20:21:45'
System info: os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_10'
Driver info: driver.version: HtmlUnitDriver
at     org.openqa.selenium.htmlunit.HtmlUnitDriver.findElementByXPath(HtmlUnitDriver.java:805)
at org.openqa.selenium.By$ByXPath.findElement(By.java:344)
at org.openqa.selenium.htmlunit.HtmlUnitDriver$5.call(HtmlUnitDriver.java:1247)
at org.openqa.selenium.htmlunit.HtmlUnitDriver$5.call(HtmlUnitDriver.java:1)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.implicitlyWaitFor(HtmlUnitDriver.java:987)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElement(HtmlUnitDriver.java:1244)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElement(HtmlUnitDriver.java:393)
at Main.runTest(Main.java:28)
at Main.main(Main.java:22)
</code>```

答:
You just need to take care of timeOut. I just ran a simple HTMLUnitDriver test for today's lates availabel selenium-server-standalone.jar which is 3.8.1

Here is my java code:

```<code>import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class HD_HTMLUnitTest {
        public static void main(String[] args) throws InterruptedException {
                     // Creating a new instance of the HTML unit driver
            //System.getProperties().put("http.proxyHost", "www-proxy.us.oracle.com");
            //System.getProperties().put("http.proxyPort", "80");

            HtmlUnitDriver unitDriver = new HtmlUnitDriver();
            //unitDriver.setJavascriptEnabled(true);

            unitDriver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
            unitDriver.get("https://www.google.co.in");
            System.out.println("Title of the page is -> " + unitDriver.getTitle());

            unitDriver.findElement(By.name("q")).sendKeys("HTMLUnit through Selenium");
            //searchBox.sendKeys("Selenium");
            WebElement button = unitDriver.findElement(By.name("btnK"));
            button.click();
            System.out.println("Title of the page is -> " + unitDriver.getTitle());

            unitDriver.quit();
         }
}
</code>```

Body:
I cannot get HtmlUnitDriver to find elements on a page I am trying to access. WebDriver on the other hand works fine. Both are using the same method.
Here is my code:

import java.util.logging.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import com.gargoylesoftware.htmlunit.BrowserVersion;

public class Main {

    public static void main(String[]args)
    {
        FirefoxDriver driver2=new FirefoxDriver();

        HtmlUnitDriver driver=new HtmlUnitDriver(BrowserVersion.FIREFOX_10);
        driver.setJavascriptEnabled(true);
        Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);

        runTest(driver2); //works
        runTest(driver);  //does not work
    }

    public static void runTest(WebDriver driver)
    {
        driver.get("http://10.3.1.164");
        WebElement elem=driver.findElement(By.xpath("//td[2]/input"));
        assert elem.isDisplayed();
        System.out.println(driver.getTitle());
    }
}

Here is the stacktrace:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to     locate a node using //td[2]/input
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.28.0', revision: '18309', time: '2012-12-11 20:21:45'
System info: os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_10'
Driver info: driver.version: HtmlUnitDriver
at     org.openqa.selenium.htmlunit.HtmlUnitDriver.findElementByXPath(HtmlUnitDriver.java:805)
at org.openqa.selenium.By$ByXPath.findElement(By.java:344)
at org.openqa.selenium.htmlunit.HtmlUnitDriver$5.call(HtmlUnitDriver.java:1247)
at org.openqa.selenium.htmlunit.HtmlUnitDriver$5.call(HtmlUnitDriver.java:1)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.implicitlyWaitFor(HtmlUnitDriver.java:987)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElement(HtmlUnitDriver.java:1244)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElement(HtmlUnitDriver.java:393)
at Main.runTest(Main.java:28)
at Main.main(Main.java:22)

Body:
You just need to take care of timeOut. I just ran a simple HTMLUnitDriver test for today's lates availabel selenium-server-standalone.jar which is 3.8.1

Here is my java code:

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class HD_HTMLUnitTest {
        public static void main(String[] args) throws InterruptedException {
                     // Creating a new instance of the HTML unit driver
            //System.getProperties().put("http.proxyHost", "www-proxy.us.oracle.com");
            //System.getProperties().put("http.proxyPort", "80");

            HtmlUnitDriver unitDriver = new HtmlUnitDriver();
            //unitDriver.setJavascriptEnabled(true);

            unitDriver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
            unitDriver.get("https://www.google.co.in");
            System.out.println("Title of the page is -> " + unitDriver.getTitle());

            unitDriver.findElement(By.name("q")).sendKeys("HTMLUnit through Selenium");
            //searchBox.sendKeys("Selenium");
            WebElement button = unitDriver.findElement(By.name("btnK"));
            button.click();
            System.out.println("Title of the page is -> " + unitDriver.getTitle());

            unitDriver.quit();
         }
}


问:
python 3.x input in a different script
I found some problem trying to create a py script that call another py script and input some int to it. I explain better:

my first script is simpleScript.py

```<code>def addition ( a , b ) :
    c = a + b
    return c
x = int ( input ( 'input a int' ) )
y = int ( input ( 'input a int' ) )
summ = addition ( x , y )
</code>```

on my second script tester.py I suppose to do something like this:

```<code>call simpleScript.py ;
input 4 as x ;
input 8 as y ;
run simpleScript.py using those two input ;
</code>```

and some more stuff. The problem is that I can't really find ho to input it properly. Once I get it I'll be able to do all of the rest.

Thanks in advance.

答:
Answering to help OP as there is a slightly difference between this and the linked duplicate (although I'd still suggest this is a duplicate that should be closed). The input here is being run at the module scope - so will execute when first loaded. i.e. simpleScript.py will ask for input when it is first called by import.

To do this in a test scenario, I'd firstly recommend to change this so that simpleScript.py provides a function that can be run. That way - the same solutions as the duplicates provide can be used.

But for this specific case where simpleScript.py does directly execute code, we can test the functionality with a test script below:

```<code>from unittest.mock import patch
from io import StringIO

@patch("sys.stdin", StringIO("1\n4"))
def test_simpleScript():
    import simpleScript

test_simpleScript()
</code>```

This works by mocking the stdin (commandline input) to return 1, a new line then 4. Because of how input works with stdin this will return 1 on the first call to input and then 4 on the next call.

When we import the simpleScript module - all the code in it is executed. Because of the above mock patch we did, any calls to input during this will read the numbers we have given it. As the module only executes the first time it is loaded - you may have issues if you try multiple tests one after another. See here for how to force a module to reload if that is the case: How do I unload (reload) a Python module?

Title: python 3.x input in a different script

Body:
I found some problem trying to create a py script that call another py script and input some int to it. I explain better:

my first script is simpleScript.py

def addition ( a , b ) :
    c = a + b
    return c
x = int ( input ( 'input a int' ) )
y = int ( input ( 'input a int' ) )
summ = addition ( x , y )

on my second script tester.py I suppose to do something like this:

call simpleScript.py ;
input 4 as x ;
input 8 as y ;
run simpleScript.py using those two input ;

and some more stuff. The problem is that I can't really find ho to input it properly. Once I get it I'll be able to do all of the rest.

Thanks in advance.

Body:
Answering to help OP as there is a slightly difference between this and the linked duplicate (although I'd still suggest this is a duplicate that should be closed). The input here is being run at the module scope - so will execute when first loaded. i.e. simpleScript.py will ask for input when it is first called by import.

To do this in a test scenario, I'd firstly recommend to change this so that simpleScript.py provides a function that can be run. That way - the same solutions as the duplicates provide can be used.

But for this specific case where simpleScript.py does directly execute code, we can test the functionality with a test script below:

from unittest.mock import patch
from io import StringIO

@patch("sys.stdin", StringIO("1\n4"))
def test_simpleScript():
    import simpleScript

test_simpleScript()

This works by mocking the stdin (commandline input) to return 1, a new line then 4. Because of how input works with stdin this will return 1 on the first call to input and then 4 on the next call.

When we import the simpleScript module - all the code in it is executed. Because of the above mock patch we did, any calls to input during this will read the numbers we have given it. As the module only executes the first time it is loaded - you may have issues if you try multiple tests one after another. See here for how to force a module to reload if that is the case: How do I unload (reload) a Python module?


问:
Sleep function in ORACLE
I need execute an SQL query in ORACLE it takes a certain amount of time.
So I wrote this function:

```<code>CREATE OR REPLACE FUNCTION MYSCHEMA.TEST_SLEEP
(
TIME_  IN  NUMBER
)
RETURN INTEGER IS
 BEGIN
   DBMS_LOCK.sleep(seconds => TIME_);
RETURN 1;
 EXCEPTION
   WHEN OTHERS THEN
   RAISE;
   RETURN 1;
END TEST_SLEEP;
</code>```

and I call in this way

```<code>SELECT TEST_SLEEP(10.5) FROM DUAL
</code>```

but to work I need set grant of DBMS_LOCK to the owner of the procedure.

How I can rewrite this function without using  the DBMS_LOCK.sleep function?

答:
There is a good article on this topic: PL/SQL: Sleep without using DBMS_LOCK that helped me out. I used Option 2 wrapped in a custom package. Proposed solutions are:

Option 1: APEX_UTIL.sleep

If APEX is installed you can use the procedure “PAUSE” from the publicly available package APEX_UTIL.

Example – “Wait 5 seconds”:

```<code>SET SERVEROUTPUT ON ;
BEGIN
    DBMS_OUTPUT.PUT_LINE('Start ' || to_char(SYSDATE, 'YYYY-MM-DD HH24:MI:SS'));
    APEX_UTIL.PAUSE(5);
    DBMS_OUTPUT.PUT_LINE('End   ' || to_char(SYSDATE, 'YYYY-MM-DD HH24:MI:SS'));
END;
/
</code>```

Option 2: java.lang.Thread.sleep

An other option is the use of the method “sleep” from the Java class “Thread”, which you can easily use through providing a simple PL/SQL wrapper procedure:

Note: Please remember, that “Thread.sleep” uses milliseconds!

```<code>--- create ---
CREATE OR REPLACE PROCEDURE SLEEP (P_MILLI_SECONDS IN NUMBER)
AS LANGUAGE JAVA NAME 'java.lang.Thread.sleep(long)';

--- use ---
SET SERVEROUTPUT ON ;
BEGIN
    DBMS_OUTPUT.PUT_LINE('Start ' || to_char(SYSDATE, 'YYYY-MM-DD HH24:MI:SS'));
    SLEEP(5 * 1000);
    DBMS_OUTPUT.PUT_LINE('End   ' || to_char(SYSDATE, 'YYYY-MM-DD HH24:MI:SS'));
END;
/
</code>```

Title: Sleep function in ORACLE

Body:
I need execute an SQL query in ORACLE it takes a certain amount of time.
So I wrote this function:

CREATE OR REPLACE FUNCTION MYSCHEMA.TEST_SLEEP
(
TIME_  IN  NUMBER
)
RETURN INTEGER IS
 BEGIN
   DBMS_LOCK.sleep(seconds => TIME_);
RETURN 1;
 EXCEPTION
   WHEN OTHERS THEN
   RAISE;
   RETURN 1;
END TEST_SLEEP;

and I call in this way

SELECT TEST_SLEEP(10.5) FROM DUAL

but to work I need set grant of DBMS_LOCK to the owner of the procedure.

How I can rewrite this function without using  the DBMS_LOCK.sleep function?

Body:
There is a good article on this topic: PL/SQL: Sleep without using DBMS_LOCK that helped me out. I used Option 2 wrapped in a custom package. Proposed solutions are:

Option 1: APEX_UTIL.sleep

If APEX is installed you can use the procedure “PAUSE” from the publicly available package APEX_UTIL.

Example – “Wait 5 seconds”:

SET SERVEROUTPUT ON ;
BEGIN
    DBMS_OUTPUT.PUT_LINE('Start ' || to_char(SYSDATE, 'YYYY-MM-DD HH24:MI:SS'));
    APEX_UTIL.PAUSE(5);
    DBMS_OUTPUT.PUT_LINE('End   ' || to_char(SYSDATE, 'YYYY-MM-DD HH24:MI:SS'));
END;
/

Option 2: java.lang.Thread.sleep

An other option is the use of the method “sleep” from the Java class “Thread”, which you can easily use through providing a simple PL/SQL wrapper procedure:

Note: Please remember, that “Thread.sleep” uses milliseconds!

--- create ---
CREATE OR REPLACE PROCEDURE SLEEP (P_MILLI_SECONDS IN NUMBER)
AS LANGUAGE JAVA NAME 'java.lang.Thread.sleep(long)';

--- use ---
SET SERVEROUTPUT ON ;
BEGIN
    DBMS_OUTPUT.PUT_LINE('Start ' || to_char(SYSDATE, 'YYYY-MM-DD HH24:MI:SS'));
    SLEEP(5 * 1000);
    DBMS_OUTPUT.PUT_LINE('End   ' || to_char(SYSDATE, 'YYYY-MM-DD HH24:MI:SS'));
END;
/


问:
Jquery preload images then show div - animation choppy
I have a page that I get the detail images for a classified ad via an Ajax call, then preload the images, add them to the div holder, then show() the div.  For some reason, the animation is really choppy?  Any ideas?

Here's the code:

```<code>$(".showPixFeature.hidden").live('click', function () {
    var adID = this.id.split('_');
    $("#" + adID[0] + '_' + adID[1]);
    $.ajax({
    type: "POST",
    url: "../classifieds/classAdPics.php",
    data: "ID="+ this.id,
    success: function(r) {
        var images = r.split('~');
        var thumbs = '';
        var thumbImages = '';

        $.loadImages('../images/35.gif', function() {$('<img />').attr({
            src:'../images/35.gif',
            id:'loader'
        })
        .appendTo("#" + adID[0] + '_' + adID[1]);

        $('#loader').remove();
    });

    var i=0;
    if(((images.length) - 1) > 1){
        for (i=1;i<=(images.length) - 1;i++)
            {
            thumbs = thumbs + '<img src="../images/listings/' + adID[1] + '_' + images[i] + '_sm.jpg" id="' + adID[1] + '_' + images[i] + '" class="thumbNails">';
                thumbImages = thumbImages + '"../images/listings/' + adID[1] + '_' + images[i] + '_sm.jpg", ';
                $.loadImages('../images/listings/' + adID[1] + '_' + images[i] + '_sm.jpg', function() {

                });
            }
        }
        thumbs = thumbs + '<div><img src="../images/listings/' + adID[1] + '_1_.jpg" id="' + adID[1] + '_Preview" class="thumbNails"></div>';
        $.loadImages('../images/listings/' + adID[1] + '_1_.jpg', function() {
    });

    $("#" + adID[0] + '_' + adID[1]).html(thumbs).hide();

    $("#" + adID[0] + '_' + adID[1]).slideDown('slow');
    }
});
$(this).attr("src", "../images/close_pix.png");
$(this).removeClass('hidden').addClass('shown');
});
</code>```

The Ajax call yields something like this "~1~2~3" depending on how many images it finds for that ad.  Then I parse through and attach the AdID to it, and preload the image.  It preloads a small thumbnail for all of the pictures, and a large preview image.

What the animation does is, especially on ones that are single images is it will do the slow animation at first and then really fast to close the animation.  I want it to slideDown smoothly at a consistent rate.

You can see the page at http://www.randykrohn.com/classifieds/allAds.php?searchKey=AllAds

Thanks!

答:
I'm not sure what your comments mean, but try rewriting the code that starts:

```<code>    if(((images.length) - 1) > 1){
</code>```

like this (I've visually checked it, but I may have missed something):

```<code>    if ((images.length > 2) {
        for (i = 1; i < images.length; i++) {
            thumbs      += '<img src="../images/listings/' + adID[1] + '_' + images[i] + '_sm.jpg" id="' + adID[1] + '_' + images[i] + '" class="thumbNails">';
            thumbImages += thumbImages + '"../images/listings/' + adID[1] + '_' + images[i] + '_sm.jpg", ';
            toBeLoaded[i-1] = '../images/listings/' + adID[1] + '_' + images[i] + '_sm.jpg';
        }
    }
    thumbs += '<div><img src="../images/listings/' + adID[1] + '_1_.jpg" id="' + adID[1] + '_Preview" class="thumbNails"></div>';
    toBeLoaded[i-1] = '../images/listings/' + adID[1] + '_1_.jpg';
    $.loadImages(toBeLoaded, function(){
        $("#" + adID[0] + '_' + adID[1]).html(thumbs).hide();
        $("#" + adID[0] + '_' + adID[1]).slideDown('slow');
    });
</code>```

i.e. load the images in a single call to loadImages and do the hiding and sliding in the callback function.

Body:
I have a page that I get the detail images for a classified ad via an Ajax call, then preload the images, add them to the div holder, then show() the div.  For some reason, the animation is really choppy?  Any ideas?

Here's the code:

$(".showPixFeature.hidden").live('click', function () {
    var adID = this.id.split('_');
    $("#" + adID[0] + '_' + adID[1]);
    $.ajax({
    type: "POST",
    url: "../classifieds/classAdPics.php",
    data: "ID="+ this.id,
    success: function(r) {
        var images = r.split('~');
        var thumbs = '';
        var thumbImages = '';

        $.loadImages('../images/35.gif', function() {$('').attr({
            src:'../images/35.gif',
            id:'loader'
        })
        .appendTo("#" + adID[0] + '_' + adID[1]);

        $('#loader').remove();
    });

    var i=0;
    if(((images.length) - 1) > 1){
        for (i=1;i<=(images.length) - 1;i++)
            {
            thumbs = thumbs + '';
                thumbImages = thumbImages + '"../images/listings/' + adID[1] + '_' + images[i] + '_sm.jpg", ';
                $.loadImages('../images/listings/' + adID[1] + '_' + images[i] + '_sm.jpg', function() {

                });
            }
        }
        thumbs = thumbs + '

';
        $.loadImages('../images/listings/' + adID[1] + '_1_.jpg', function() {
    });

    $("#" + adID[0] + '_' + adID[1]).html(thumbs).hide();

    $("#" + adID[0] + '_' + adID[1]).slideDown('slow');
    }
});
$(this).attr("src", "../images/close_pix.png");
$(this).removeClass('hidden').addClass('shown');
});

The Ajax call yields something like this "~1~2~3" depending on how many images it finds for that ad.  Then I parse through and attach the AdID to it, and preload the image.  It preloads a small thumbnail for all of the pictures, and a large preview image.

What the animation does is, especially on ones that are single images is it will do the slow animation at first and then really fast to close the animation.  I want it to slideDown smoothly at a consistent rate.

You can see the page at http://www.randykrohn.com/classifieds/allAds.php?searchKey=AllAds

Thanks!

Body:
I'm not sure what your comments mean, but try rewriting the code that starts:

    if(((images.length) - 1) > 1){

like this (I've visually checked it, but I may have missed something):

    if ((images.length > 2) {
        for (i = 1; i < images.length; i++) {
            thumbs      += '<img src="../images/listings/' + adID[1] + '_' + images[i] + '_sm.jpg" id="' + adID[1] + '_' + images[i] + '" class="thumbNails">';
            thumbImages += thumbImages + '"../images/listings/' + adID[1] + '_' + images[i] + '_sm.jpg", ';
            toBeLoaded[i-1] = '../images/listings/' + adID[1] + '_' + images[i] + '_sm.jpg';
        }
    }
    thumbs += '<div><img src="../images/listings/' + adID[1] + '_1_.jpg" id="' + adID[1] + '_Preview" class="thumbNails"></div>';
    toBeLoaded[i-1] = '../images/listings/' + adID[1] + '_1_.jpg';
    $.loadImages(toBeLoaded, function(){
        $("#" + adID[0] + '_' + adID[1]).html(thumbs).hide();
        $("#" + adID[0] + '_' + adID[1]).slideDown('slow');
    });

i.e. load the images in a single call to loadImages and do the hiding and sliding in the callback function.


问:
Convert from C/C++/Java source code to unicode with python 3
I have some raw data that I want to convert to its characters in unicode.
Example:

```<code>"<http://geo.linkedopendata.gr/gag/data/id/911805> <http://www.w3.org/2000/01/rdf-schema#label> "RDF description of \u0394HMOTIKH \u0395NOTHTA \u0398\u0399\u039D\u0391\u039B\u0399\u039F\u03A5" <http://geo.linkedopendata.gr/gag/data/id/911805> ."
</code>```

I have used the classic:

```<code>with open("dump_final.nq", encoding="utf-8") as f:
</code>```

And what I should get is all the characters starting with \u converted to its unicode characters.

I get the same as the beggining, no conversion is made.

Thank you.

答:
I refer raw data because it is some data that I want to transform. It is composed of some URIs and some of them contain characters that are in C/C++/Java source code. For example if I have a string like "\u03A5" it should be transform into an Upsilon symbol, as it is shown here: https://www.fileformat.info/info/unicode/char/03a5/index.htm
Thank you.
Kind regards.</p>

Body:
I have some raw data that I want to convert to its characters in unicode.
Example:

"<http://geo.linkedopendata.gr/gag/data/id/911805> <http://www.w3.org/2000/01/rdf-schema#label> "RDF description of \u0394HMOTIKH \u0395NOTHTA \u0398\u0399\u039D\u0391\u039B\u0399\u039F\u03A5" <http://geo.linkedopendata.gr/gag/data/id/911805> ."

I have used the classic:

with open("dump_final.nq", encoding="utf-8") as f:

And what I should get is all the characters starting with \u converted to its unicode characters.

I get the same as the beggining, no conversion is made.

Thank you.


答:
Well it turns out to be much easier by simply doing</p>

```<code>background: linear-gradient(to bottom, skyblue  0%, blue 100%)
</code>```

Title: CSS Gradient does not appear

Body:
whats wrong with this: I want to put a gradient in the background of the web iste.

$(body).css({ 'background': '-moz-linear-gradient(center bottom,rgb(255,255,255) 0%,rgb(241,250,254) 100%)' });

im using this library:
ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js

Body:
Well it turns out to be much easier by simply doing

background: linear-gradient(to bottom, skyblue  0%, blue 100%)


问:
How to edit this text file as merged information with same headers
I have a huge text file with data like this:-

```<code>EAST DUBBO - Unknown
EAST MAITLAND - 1892
EAST MAITLAND - 1902
EAST MAITLAND - 1920
EAST MAITLAND - 1937
EAST MAITLAND - 1940
EAST MAITLAND - 1956
EBOR - 1905
EBOR - 1911
EDEN - Unknown
ELLENBOROUGH - 1905
ELONG ELONG - 1920
ELONG ELONG - 1955
</code>```

and I need it to be in this format:-

```<code>EAST DUBBO - Unknown
EAST MAITLAND - 1892, 1902, 1920, 1937, 1940, 1956
EBOR - 1905, 1911
EDEN - Unknown
ELLENBOROUGH - 1905
ELONG ELONG - 1920, 1955
</code>```

It will take days to do by hand so i'm wondering if it can be solved programmatically or if there is an online tool?

答:
assuming the records are contiguous in the common key</p>

```<code>$ awk -F' - ' '{if(p!=$1){if(v) print v; p=$1; v=$0}
                else v=v ", " $2}
           END {print v}' file

EAST DUBBO - Unknown
EAST MAITLAND - 1892, 1902, 1920, 1937, 1940, 1956
EBOR - 1905, 1911
EDEN - Unknown
ELLENBOROUGH - 1905
ELONG ELONG - 1920, 1955
</code>```

Body:
I have a huge text file with data like this:-

EAST DUBBO - Unknown
EAST MAITLAND - 1892
EAST MAITLAND - 1902
EAST MAITLAND - 1920
EAST MAITLAND - 1937
EAST MAITLAND - 1940
EAST MAITLAND - 1956
EBOR - 1905
EBOR - 1911
EDEN - Unknown
ELLENBOROUGH - 1905
ELONG ELONG - 1920
ELONG ELONG - 1955

and I need it to be in this format:-

EAST DUBBO - Unknown
EAST MAITLAND - 1892, 1902, 1920, 1937, 1940, 1956
EBOR - 1905, 1911
EDEN - Unknown
ELLENBOROUGH - 1905
ELONG ELONG - 1920, 1955

It will take days to do by hand so i'm wondering if it can be solved programmatically or if there is an online tool?

Body:
assuming the records are contiguous in the common key

$ awk -F' - ' '{if(p!=$1){if(v) print v; p=$1; v=$0}
                else v=v ", " $2}
           END {print v}' file

EAST DUBBO - Unknown
EAST MAITLAND - 1892, 1902, 1920, 1937, 1940, 1956
EBOR - 1905, 1911
EDEN - Unknown
ELLENBOROUGH - 1905
ELONG ELONG - 1920, 1955