问:
How to update a angular 4+ form values using console devtools?
I'm trying to fill a Angular 4+ form using console (devtools).

This is what I'm doing now:

function fillForm(){
    let el = document.querySelector('input[ng-reflect-name="my_input"]');
    let elProbe = ng.probe(el);
    elProbe._debugContext.component.value = 'new-value';
}
```

Some references I'm trying to use (if it helps anyone):

https://juristr.com/blog/2016/02/debugging-angular2-console/

Trigger Angular change detection from console

答:
There are two options. The first one is to work with component property bound to a form and it requires manual change detection triggering. The second one is to work with the form control associated with the input and it doesn't require manual change detection.

Neither is better.

For the first option see @yurzui's answer. Here is the answer for the second option - update the form control directly without the need for change detection:

```<code>function fillForm(){
    let el = document.querySelector('input[ng-reflect-name="my_input"]');
    let elProbe = ng.probe(el);

    const NgControlClassReference = elProbe.providerTokens.find((p)=>{
        return p.name === 'NgControl';
    });

    let directive = elProbe.injector.get(NgControlClassReference);
    let control = directive.control;

    control.setValue('some');
}
</code>```

In this case you don't need change detection because when you call setValue on the control directly it notifies valueAccessor about the change:

```<code>FormControl.prototype.setValue = function (value, options) {
  ...
  this._onChange.forEach(function (changeFn) {
      return changeFn(_this._value, options.emitViewToModelChange !== false); });
</code>```

where changeFn is a subscriber added in the setUpContorl function:

```<code>  control.registerOnChange((newValue: any, emitModelEvent: boolean) => {
    // control -> view
    dir.valueAccessor !.writeValue(newValue);
</code>```

which calls writeValue on the accessor directly and it in turn writes the value into input:

```<code>export class DefaultValueAccessor implements ControlValueAccessor {
  ...

  writeValue(value: any): void {
    const normalizedValue = value == null ? '' : value;
    this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', normalizedValue);
  }
</code>```

You also might find this article useful

Everything you need to know about debugging Angular applications

Body:
I'm trying to fill a Angular 4+ form using console (devtools).

This is what I'm doing now:

function fillForm(){
    let el = document.querySelector('input[ng-reflect-name="my_input"]');
    let elProbe = ng.probe(el);
    elProbe._debugContext.component.value = 'new-value';
}

Some references I'm trying to use (if it helps anyone):

https://juristr.com/blog/2016/02/debugging-angular2-console/

Trigger Angular change detection from console

Body:
There are two options. The first one is to work with component property bound to a form and it requires manual change detection triggering. The second one is to work with the form control associated with the input and it doesn't require manual change detection.

Neither is better.

For the first option see @yurzui's answer. Here is the answer for the second option - update the form control directly without the need for change detection:

function fillForm(){
    let el = document.querySelector('input[ng-reflect-name="my_input"]');
    let elProbe = ng.probe(el);

    const NgControlClassReference = elProbe.providerTokens.find((p)=>{
        return p.name === 'NgControl';
    });

    let directive = elProbe.injector.get(NgControlClassReference);
    let control = directive.control;

    control.setValue('some');
}

In this case you don't need change detection because when you call setValue on the control directly it notifies valueAccessor about the change:

FormControl.prototype.setValue = function (value, options) {
  ...
  this._onChange.forEach(function (changeFn) {
      return changeFn(_this._value, options.emitViewToModelChange !== false); });

where changeFn is a subscriber added in the setUpContorl function:

  control.registerOnChange((newValue: any, emitModelEvent: boolean) => {
    // control -> view
    dir.valueAccessor !.writeValue(newValue);

which calls writeValue on the accessor directly and it in turn writes the value into input:

export class DefaultValueAccessor implements ControlValueAccessor {
  ...

  writeValue(value: any): void {
    const normalizedValue = value == null ? '' : value;
    this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', normalizedValue);
  }

You also might find this article useful

Everything you need to know about debugging Angular applications


来源: stackexchange

问:
Unable to connect to ftp server java
I should be able to successfully send and receive file to/from FTP server.

But then, no changes occurred in the code and I started getting this :

Error: java.net.ConnectException: Connection timed out: connect

What I am doing is:

```<code>FTPClient ftp = new FTPClient();

ftp.connect( IPADDRESS of FTP server);
</code>```

connect() is giving this execption. I am not understanding the cause for it.

答:
Signals that an error occurred while attempting to connect a socket to a remote address and port. Typically, the connection was refused remotely (e.g., no process is listening on the remote address/port).

Source: JavaDoc.

ContentLicense: CC BY-SA 2.5

Title: Unable to connect to ftp server java

Body:
I should be able to successfully send and receive file to/from FTP server.

But then, no changes occurred in the code and I started getting this :

Error: java.net.ConnectException: Connection timed out: connect

What I am doing is:

FTPClient ftp = new FTPClient();

ftp.connect( IPADDRESS of FTP server);

connect() is giving this execption. I am not understanding the cause for it.


问:
Which React cycle method should I use to re-render component when redux state has changed?
The React doc are unfortunately unclear for me at my level of understanding.

What cycle method should I use here instead of componentDidMount()? I want this component to update Google Map every time it gets new state from state.selectedShopInfo.

In my app user is clicking some list and every time he clicks this component gets new data.

I'm checking it with console.log(_.last(this.props.selectedShopInfo)); and it is working.

So what React cycle method should I use so every time { selectedShopInfo: state.selectedShopInfo } will change GoogleMap Component will change as well?

```<code>    import _ from 'lodash';
    import React, { Component } from 'react';
    import { connect } from 'react-redux';

    class GoogleMap extends Component {
      componentDidMount() {
        const lastSelectedShopInfo = _.last(this.props.selectedShopInfo);
        if (lastSelectedShopInfo !== undefined) {
          new google.maps.Map(this.refs.map, {
            zoom: 20,
            center: {
              lat: Number(lastSelectedShopInfo.latitude),
              lng: Number(lastSelectedShopInfo.longitude),
            },
          });
        }
      }

      render() {
        console.log(_.last(this.props.selectedShopInfo));
        return (
          <div>
            <hr />
            <div className="google-map" ref="map" />
            <hr />
          </div>
        );
      }
    }

    function mapStateToProps(state) {
      return { selectedShopInfo: state.selectedShopInfo };
    }

    export default connect(mapStateToProps)(GoogleMap);
</code>```

答: You should render the map initially in componentDidMount and update the map in componentWillReceiveProps.

ContentLicense: CC BY-SA 3.0

Body:
The React doc are unfortunately unclear for me at my level of understanding.

What cycle method should I use here instead of componentDidMount()? I want this component to update Google Map every time it gets new state from state.selectedShopInfo.

In my app user is clicking some list and every time he clicks this component gets new data.

I'm checking it with console.log(_.last(this.props.selectedShopInfo)); and it is working.

So what React cycle method should I use so every time { selectedShopInfo: state.selectedShopInfo } will change GoogleMap Component will change as well?

    import _ from 'lodash';
    import React, { Component } from 'react';
    import { connect } from 'react-redux';

    class GoogleMap extends Component {
      componentDidMount() {
        const lastSelectedShopInfo = _.last(this.props.selectedShopInfo);
        if (lastSelectedShopInfo !== undefined) {
          new google.maps.Map(this.refs.map, {
            zoom: 20,
            center: {
              lat: Number(lastSelectedShopInfo.latitude),
              lng: Number(lastSelectedShopInfo.longitude),
            },
          });
        }
      }

      render() {
        console.log(_.last(this.props.selectedShopInfo));
        return (

        );
      }
    }

    function mapStateToProps(state) {
      return { selectedShopInfo: state.selectedShopInfo };
    }

    export default connect(mapStateToProps)(GoogleMap);


问:
Minimize sum of columns in matrix by permutating elements in python
I have the following matrix:

```<code>([2, 5, 5, 10]
 [7, 1, 4, 1]
 [1, 3, 3, 9])
</code>```

If the columns are summed the result is:

```<code>[10, 9, 12, 20]
</code>```

My objective is to determine the optimum way to sort the elements in the diferent rows in order to minimize the maximum element in the sum of columns.

For example, one possibility would be:

```<code>([2, 5, 5, 10]
 [7, 1, 4, 1]
 [1, 9, 3, 3])
</code>```

If the columns are summed the result is:

```<code>[10, 15, 12, 14]
</code>```

This is a better solution than the first one.

The easiest way to do this is checking all the possible permutations, but this method gets incredible slow in python as the matrix grows.

Any idea to do this in a faster way?

答:
Here is an idea:

Pick 2 columns with smallest and largest sum. Note their difference, d.

Inspect elements in both columns. Find a row with largest absolute value of difference d' such that d' < d and d' > 0.

Swap the elements in that row.

Repeat steps 1-3, until step 2 is no longer possible.

Example:
Given

```<code>([2, 5, 5, 10]
 [7, 1, 4, 1]
 [1, 3, 3, 9])
</code>```

We pick 2 columns with smallest and largest sum. Here we have column 1 with smallest sum and column 3 with largest sum.
For these 2 columns, the difference of their sum, d, is 11.

```<code>([5, 10]
 [1, 1]
 [3, 9])
</code>```

Now we find largest difference d' such that d' < d and d' > 0, which is 9 - 3 = 6.
We now swap the elements in that row. So we have

```<code>([2, 5, 5, 10]
 [7, 1, 4, 1]
 [1, 9, 3, 3])
</code>```

This matrix has column-sum of [10, 15, 12, 14]

Repeat the above process one more time, then you will end up with the following:

```<code>([5, 2, 5, 10]
 [7, 1, 4, 1]
 [1, 9, 3, 3])
</code>```

This resulting matrix has the sum of [13, 12, 12, 14]. At this point, step 2 is no longer possible. So we are done.

Body:
I have the following matrix:

([2, 5, 5, 10]
 [7, 1, 4, 1]
 [1, 3, 3, 9])

If the columns are summed the result is:

[10, 9, 12, 20]

My objective is to determine the optimum way to sort the elements in the diferent rows in order to minimize the maximum element in the sum of columns.

For example, one possibility would be:

([2, 5, 5, 10]
 [7, 1, 4, 1]
 [1, 9, 3, 3])

If the columns are summed the result is:

[10, 15, 12, 14]

This is a better solution than the first one.

The easiest way to do this is checking all the possible permutations, but this method gets incredible slow in python as the matrix grows.

Any idea to do this in a faster way?

Body:
Here is an idea:

Pick 2 columns with smallest and largest sum. Note their difference, d.

Inspect elements in both columns. Find a row with largest absolute value of difference d' such that d' < d and d' > 0.

Swap the elements in that row.

Repeat steps 1-3, until step 2 is no longer possible.

Example:
Given

([2, 5, 5, 10]
 [7, 1, 4, 1]
 [1, 3, 3, 9])

We pick 2 columns with smallest and largest sum. Here we have column 1 with smallest sum and column 3 with largest sum.
For these 2 columns, the difference of their sum, d, is 11.

([5, 10]
 [1, 1]
 [3, 9])

Now we find largest difference d' such that d' < d and d' > 0, which is 9 - 3 = 6.
We now swap the elements in that row. So we have

([2, 5, 5, 10]
 [7, 1, 4, 1]
 [1, 9, 3, 3])

This matrix has column-sum of [10, 15, 12, 14]

Repeat the above process one more time, then you will end up with the following:

([5, 2, 5, 10]
 [7, 1, 4, 1]
 [1, 9, 3, 3])

This resulting matrix has the sum of [13, 12, 12, 14]. At this point, step 2 is no longer possible. So we are done.


问:
Call php function from different class, namespace and file using include
I am aware that this question is very similar if not exactly the same as a few others but I seem to have problems Calling the function even after following those advises. Thanks for your understanding.

I'm trying set the username with "setUserName" function from this file Calling the function from Another file as shown below. I seem to be missunderstanding how to call classes and namespaces.

```<code>namespace StructType;

use \WsdlToPhp\PackageBase\AbstractStructBase;

/**
 * This class stands for webExport StructType
 * @subpackage Structs
 */
class WebExport extends AbstractStructBase
{
    /**
     * The userName
     * Meta informations extracted from the WSDL
     * - nillable: true
     * @var string
     */
    public $userName;
    /**
     * The passwordMd5
     * Meta informations extracted from the WSDL
     * - nillable: true
     * @var string
     */
    public $passwordMd5;
    /**
     * The ecfFile
     * Meta informations extracted from the WSDL
     * - nillable: true
     * @var string
     */
    public $ecfFile;
    /**
     * Constructor method for webExport
     * @uses WebExport::setUserName()
     * @uses WebExport::setPasswordMd5()
     * @uses WebExport::setEcfFile()
     * @param string $userName
     * @param string $passwordMd5
     * @param string $ecfFile
     */
    public function __construct($userName = null, $passwordMd5 = null, $ecfFile = null)
    {
        $this
            ->setUserName($userName)
            ->setPasswordMd5($passwordMd5)
            ->setEcfFile($ecfFile);
    }
    /**
     * Get userName value
     * @return string|null
     */
    public function getUserName()
    {
        return $this->userName;
    }
    /**
     * Set userName value
     * @param string $userName
     * @return \StructType\WebExport
     */
    public function setUserName($userName = null)
    {
        // validation for constraint: string
        if (!is_null($userName) && !is_string($userName)) {
            throw new \InvalidArgumentException(sprintf('Invalid value, please provide a string, "%s" given', gettype($userName)), __LINE__);
        }
        $this->userName = $userName;
        return $this;
    }
    /**
     * Get passwordMd5 value
     * @return string|null
     */
    public function getPasswordMd5()
    {
        return $this->passwordMd5;
    }
    /**
     * Set passwordMd5 value
     * @param string $passwordMd5
     * @return \StructType\WebExport
     */
    public function setPasswordMd5($passwordMd5 = null)
    {
        // validation for constraint: string
        if (!is_null($passwordMd5) && !is_string($passwordMd5)) {
            throw new \InvalidArgumentException(sprintf('Invalid value, please provide a string, "%s" given', gettype($passwordMd5)), __LINE__);
        }
        $this->passwordMd5 = $passwordMd5;
        return $this;
    }
    /**
     * Get ecfFile value
     * @return string|null
     */
    public function getEcfFile()
    {
        return $this->ecfFile;
    }
    /**
     * Set ecfFile value
     * @param string $ecfFile
     * @return \StructType\WebExport
     */
    public function setEcfFile($ecfFile = null)
    {
        // validation for constraint: string
        if (!is_null($ecfFile) && !is_string($ecfFile)) {
            throw new \InvalidArgumentException(sprintf('Invalid value, please provide a string, "%s" given', gettype($ecfFile)), __LINE__);
        }
        $this->ecfFile = $ecfFile;
        return $this;
    }
    /**
     * Method called when an object has been exported with var_export() functions
     * It allows to return an object instantiated with the values
     * @see AbstractStructBase::__set_state()
     * @uses AbstractStructBase::__set_state()
     * @param array $array the exported values
     * @return \StructType\WebExport
     */
    public static function __set_state(array $array)
    {
        return parent::__set_state($array);
    }
    /**
     * Method returning the class name
     * @return string __CLASS__
     */
    public function __toString()
    {
        return __CLASS__;
    }
}
</code>```

Heres how im trying to set the username Calling the function from Another file.

```<code><?php

require_once __DIR__ . '/vendor/autoload.php';

    class Class2{
        use \StructType\webExport;
        public static function staticFunction(){
            setUserName("webservice");
        }
    }
</code>```

Where am i going wrong? Everything works as intended if I set the password directly in the consctruct as following:

```<code> public function __construct($userName = "ws", $passwordMd5 = "qwerty", $ecfFile = null)
</code>```

Last error message:

Fatal error: Class2 cannot use StructType\WebExport - it is not a trait in index.php on line 289

答:
So, a couple of things here...
When you have a use statement inside a class's definition, it will be expecting a Trait. That use statement does need to be outside of the class's definition since you are using a Class and not a Trait here. Also, when you want to use a class, case matters (could just be a type-o in the OP's question). WebExport not webExport. And lastly, if you are setting an instance variable of a class, you need to have an instance of that class in order to set one of it's member/instance variables. I'm not sure if your Class2 is intending to extend the WebExport class, or if you're wanting to use composition and set the userName on a WebExport property of your new Class2. (I'm not sure how you intend your class to be structured), but I would expect any one of several possible uses...

```<code>require_once __DIR__ . '/vendor/autoload.php';
use \StructType\WebExport;

class Class2 {

   protected $webExportMemberVariable;

   public function __construct() {
       $this->webExportMemberVariable = new WebExport();
   }

   public function noLongerStaticFunction() {
      $this->webExportMemberVariable->setUserName("webservice");
   }
}
</code>```

^ note in the above, that WebExport has capital 'W' in the use statement, and I'm calling setUserName on an instance of type WebExport. Doing this statically seems a little odd but still possible...

```<code>require_once __DIR__ . '/vendor/autoload.php';
use \StructType\WebExport;

class Class2 {

   protected static $webExportStaticVariable = new WebExport();

   public static function staticFunction() {
      self::$webExportMemberVariable->setUserName("webservice");
   }
}
</code>```

^ doing this from a static method is a little wonky IMHO. In any case you must have an instance of type \StructType\WebExport to be setting a member variable like it seems you want to do here.

Body:
I am aware that this question is very similar if not exactly the same as a few others but I seem to have problems Calling the function even after following those advises. Thanks for your understanding.

I'm trying set the username with "setUserName" function from this file Calling the function from Another file as shown below. I seem to be missunderstanding how to call classes and namespaces.

namespace StructType;

use \WsdlToPhp\PackageBase\AbstractStructBase;

/**
 * This class stands for webExport StructType
 * @subpackage Structs
 */
class WebExport extends AbstractStructBase
{
    /**
     * The userName
     * Meta informations extracted from the WSDL
     * - nillable: true
     * @var string
     */
    public $userName;
    /**
     * The passwordMd5
     * Meta informations extracted from the WSDL
     * - nillable: true
     * @var string
     */
    public $passwordMd5;
    /**
     * The ecfFile
     * Meta informations extracted from the WSDL
     * - nillable: true
     * @var string
     */
    public $ecfFile;
    /**
     * Constructor method for webExport
     * @uses WebExport::setUserName()
     * @uses WebExport::setPasswordMd5()
     * @uses WebExport::setEcfFile()
     * @param string $userName
     * @param string $passwordMd5
     * @param string $ecfFile
     */
    public function __construct($userName = null, $passwordMd5 = null, $ecfFile = null)
    {
        $this
            ->setUserName($userName)
            ->setPasswordMd5($passwordMd5)
            ->setEcfFile($ecfFile);
    }
    /**
     * Get userName value
     * @return string|null
     */
    public function getUserName()
    {
        return $this->userName;
    }
    /**
     * Set userName value
     * @param string $userName
     * @return \StructType\WebExport
     */
    public function setUserName($userName = null)
    {
        // validation for constraint: string
        if (!is_null($userName) && !is_string($userName)) {
            throw new \InvalidArgumentException(sprintf('Invalid value, please provide a string, "%s" given', gettype($userName)), __LINE__);
        }
        $this->userName = $userName;
        return $this;
    }
    /**
     * Get passwordMd5 value
     * @return string|null
     */
    public function getPasswordMd5()
    {
        return $this->passwordMd5;
    }
    /**
     * Set passwordMd5 value
     * @param string $passwordMd5
     * @return \StructType\WebExport
     */
    public function setPasswordMd5($passwordMd5 = null)
    {
        // validation for constraint: string
        if (!is_null($passwordMd5) && !is_string($passwordMd5)) {
            throw new \InvalidArgumentException(sprintf('Invalid value, please provide a string, "%s" given', gettype($passwordMd5)), __LINE__);
        }
        $this->passwordMd5 = $passwordMd5;
        return $this;
    }
    /**
     * Get ecfFile value
     * @return string|null
     */
    public function getEcfFile()
    {
        return $this->ecfFile;
    }
    /**
     * Set ecfFile value
     * @param string $ecfFile
     * @return \StructType\WebExport
     */
    public function setEcfFile($ecfFile = null)
    {
        // validation for constraint: string
        if (!is_null($ecfFile) && !is_string($ecfFile)) {
            throw new \InvalidArgumentException(sprintf('Invalid value, please provide a string, "%s" given', gettype($ecfFile)), __LINE__);
        }
        $this->ecfFile = $ecfFile;
        return $this;
    }
    /**
     * Method called when an object has been exported with var_export() functions
     * It allows to return an object instantiated with the values
     * @see AbstractStructBase::__set_state()
     * @uses AbstractStructBase::__set_state()
     * @param array $array the exported values
     * @return \StructType\WebExport
     */
    public static function __set_state(array $array)
    {
        return parent::__set_state($array);
    }
    /**
     * Method returning the class name
     * @return string __CLASS__
     */
    public function __toString()
    {
        return __CLASS__;
    }
}

Heres how im trying to set the username Calling the function from Another file.

<?php

require_once __DIR__ . '/vendor/autoload.php';

    class Class2{
        use \StructType\webExport;
        public static function staticFunction(){
            setUserName("webservice");
        }
    }

Where am i going wrong? Everything works as intended if I set the password directly in the consctruct as following:

 public function __construct($userName = "ws", $passwordMd5 = "qwerty", $ecfFile = null)

Last error message:

Fatal error: Class2 cannot use StructType\WebExport - it is not a trait in index.php on line 289

Body:
So, a couple of things here...
When you have a use statement inside a class's definition, it will be expecting a Trait. That use statement does need to be outside of the class's definition since you are using a Class and not a Trait here. Also, when you want to use a class, case matters (could just be a type-o in the OP's question). WebExport not webExport. And lastly, if you are setting an instance variable of a class, you need to have an instance of that class in order to set one of it's member/instance variables. I'm not sure if your Class2 is intending to extend the WebExport class, or if you're wanting to use composition and set the userName on a WebExport property of your new Class2. (I'm not sure how you intend your class to be structured), but I would expect any one of several possible uses...

require_once __DIR__ . '/vendor/autoload.php';
use \StructType\WebExport;

class Class2 {

   protected $webExportMemberVariable;

   public function __construct() {
       $this->webExportMemberVariable = new WebExport();
   }

   public function noLongerStaticFunction() {
      $this->webExportMemberVariable->setUserName("webservice");
   }
}

^ note in the above, that WebExport has capital 'W' in the use statement, and I'm calling setUserName on an instance of type WebExport. Doing this statically seems a little odd but still possible...

require_once __DIR__ . '/vendor/autoload.php';
use \StructType\WebExport;

class Class2 {

   protected static $webExportStaticVariable = new WebExport();

   public static function staticFunction() {
      self::$webExportMemberVariable->setUserName("webservice");
   }
}

^ doing this from a static method is a little wonky IMHO. In any case you must have an instance of type \StructType\WebExport to be setting a member variable like it seems you want to do here.


问:
What are some of the more obscure parts of C++?
I've read quite a few beginner's books on C++, and a little beyond that, but what are some of the more obscure aspects of C++, or where can I find information/tutorials on these?</p>

答:
Very obscure:

void operator,();

precedence of operator||() and    operator&&() when short circuiting

logical expressions

what happens when you overload
operator&()

order of initialization of stateful
virtual inhertiance.

deferencing pointers to template
members

function try blocks

the allocator::rebind syntax

non default behaviour of std::unexpected

std::cout.imbue()

Anything with locales,especially
custom facets

overriding via dominance

trigraphs

Just to name a few


问:
is it possible to passing a variable/function-return as a template argument
Is it possible to pass a variable or a value returned by a function as a template argument.

Example:

```<code>QVariantHash options;
options.insert("fontStyle", fontStyleObject);  // QFont fontStyleObject
options.insert("fontColor", fontColorObject);  // QColor fontColorObject
Q_FOREACH(const QVariant &option, options){
    qDebug() << option.value<option.typeName()>();
}
</code>```

As you saw, I have passed option.typeName() as a template argument and that method returns the type of the object as QString.

I have already done that but there is an error message: error: C2974: 'QVariant::value': invalid template argument for 'T', type expected.

Is it possible to pass a variable or a value returned by a function as a template argument? and if not, what's the alternative way to do that?

答:
I think you don't need that at all, you can just use

T QVariant::value() const

you can feed the resulting T to qDebug() operator <<. You might need to define how you print your T, have a look at: http://doc.qt.io/qt-4.8/qdebug.html#writing-custom-types-to-a-stream

```<code>for ( auto const & option : options)
  qDebug() << option.value(); //returns T automatically
</code>```

Body:
Is it possible to pass a variable or a value returned by a function as a template argument.

Example:

QVariantHash options;
options.insert("fontStyle", fontStyleObject);  // QFont fontStyleObject
options.insert("fontColor", fontColorObject);  // QColor fontColorObject
Q_FOREACH(const QVariant &option, options){
    qDebug() << option.value<option.typeName()>();
}

As you saw, I have passed option.typeName() as a template argument and that method returns the type of the object as QString.

I have already done that but there is an error message: error: C2974: 'QVariant::value': invalid template argument for 'T', type expected.

Is it possible to pass a variable or a value returned by a function as a template argument? and if not, what's the alternative way to do that?

Body:
I think you don't need that at all, you can just use

T QVariant::value() const

you can feed the resulting T to qDebug() operator <<. You might need to define how you print your T, have a look at: http://doc.qt.io/qt-4.8/qdebug.html#writing-custom-types-to-a-stream

for ( auto const & option : options)
  qDebug() << option.value(); //returns T automatically


问:
how to close sweet alert on ajax request completion
I am using Sweet-alert in my angular app.

```<code>function GetDataFromServer(url) {
        SweetAlert.swal(
    {
        title: "",
        text: "Please wait.",
        imageUrl: "../../app/app-img/loading_spinner.gif",
        showConfirmButton: false
    });
        return $http.get(url)
        .then(success)
        .catch(exception);
        function success(response) {
            //SweetAlert.swal(
            //  {
            //      title: "",
            //      text: "data loaded",
            //  });
            return response.data;
        }
        function exception(ex) {
            return (ex);
        }

    }
</code>```

Req #1 (Main Objective of my this post)

What I am looking for is when the ajax request completes i.e.,
  controls enters in the then(), Sweet alert should automatically hide.

Req #2
Also while request processing, I don't want to have the Close pop-up button (Ok button) in the sweet alert.

As per the documentation,showConfirmButton: false should hide it but it's not.

Any help/suggestion highly appreciated.

Thanks.

答:
SweetAlert has close method if you check the docs at http://t4t5.github.io/sweetalert/

You can use SweetAlert.close() to close the sweetalert in angular.

Body:
I am using Sweet-alert in my angular app.

function GetDataFromServer(url) {
        SweetAlert.swal(
    {
        title: "",
        text: "Please wait.",
        imageUrl: "../../app/app-img/loading_spinner.gif",
        showConfirmButton: false
    });
        return $http.get(url)
        .then(success)
        .catch(exception);
        function success(response) {
            //SweetAlert.swal(
            //  {
            //      title: "",
            //      text: "data loaded",
            //  });
            return response.data;
        }
        function exception(ex) {
            return (ex);
        }

    }

Req #1 (Main Objective of my this post)

What I am looking for is when the ajax request completes i.e.,
  controls enters in the then(), Sweet alert should automatically hide.

Req #2
Also while request processing, I don't want to have the Close pop-up button (Ok button) in the sweet alert.

As per the documentation,showConfirmButton: false should hide it but it's not.

Any help/suggestion highly appreciated.

Thanks.


问:
Convert select query to update MYSQL
How to convert select to update for this query for field 'year_from':

```<code>SELECT CONCAT_WS('.', LEFT(year_from, 4), SUBSTRING(year_from, 5)) FROM
lc_vehicles
</code>```

edit:
when using select i get results from 198501 to 1985.01, but when update I get 1985.0

答:
If you want to update your year_from field in your lc_vehicles table with some condition, you can use this query.</p>

```<code>UPDATE lc_vehicles
SET year_from = CONCAT_WS('.', LEFT(year_from, 4), SUBSTRING(year_from, 5))
where [condition];
</code>```

Title: Convert select query to update MYSQL

Body:
How to convert select to update for this query for field 'year_from':

SELECT CONCAT_WS('.', LEFT(year_from, 4), SUBSTRING(year_from, 5)) FROM
lc_vehicles

edit:
when using select i get results from 198501 to 1985.01, but when update I get 1985.0

Body:
If you want to update your year_from field in your lc_vehicles table with some condition, you can use this query.

UPDATE lc_vehicles
SET year_from = CONCAT_WS('.', LEFT(year_from, 4), SUBSTRING(year_from, 5))
where [condition];


问:
SQL count using multiple join
I have three tables related to each other in the following way:

host (has multiple sessions)

session (has multiple processes)

processes

The table structure is as follows:

host table - id, name

session table - id, host_id, name

process table - id, session_id, name

What I am trying to achieve is the count of the number of sessions and the count of the number of processes on each host. To achieve this I tried the following query, but the output is wrong.

```<code>select host.id,
       count(sessions.id) as "session count",
       count(process.id) as "process count"
from host as host
     left outer join sessions as sessions on host.id = sessions.host_id
     left outer join process as process on sessions.id = process.session_id
group by host.id;
</code>```

Here's the SQLFiddle to the schema.

As per the data in the fiddle, the output should be:

```<code>id | session count | process count
----------------------------------
1  |     2         |   3
2  |     1         |   2
3  |     1         |   2
4  |     2         |   3
</code>```

But what I get is:

```<code>id | session count | process count
----------------------------------
1  |     3         |   3
2  |     2         |   2
3  |     2         |   2
4  |     3         |   3
</code>```

What can be the correct query to get the desired output?

答:
If you query without the group by-clause, you will see that you are getting the same session id multiple times. Therefore you sessions count is too high.

```<code>select h.id as hid, s.id as sid, p.id as pid
from host h
left join sessions s on h.id = s.host_id
left join process p on s.id = p.session_id
order by h.id, s.id, p.id;

hid sid pid
-----------
1   1   1
1   1   2
1   2   5
2   5   8
2   5   9
3   3   3
3   3   7
4   4   4
4   4   6
4   6   10
</code>```

Therefore use count(distinct s.id) for the sessions:

```<code>select h.id as hid, count(distinct s.id) as session_count, count(p.id) as process_count
from host h
left join sessions s on h.id = s.host_id
left join process p on s.id = p.session_id
group by h.id
</code>```

Title: SQL count using multiple join

Body:
I have three tables related to each other in the following way:

host (has multiple sessions)

session (has multiple processes)

processes

The table structure is as follows:

host table - id, name

session table - id, host_id, name

process table - id, session_id, name

What I am trying to achieve is the count of the number of sessions and the count of the number of processes on each host. To achieve this I tried the following query, but the output is wrong.

select host.id,
       count(sessions.id) as "session count",
       count(process.id) as "process count"
from host as host
     left outer join sessions as sessions on host.id = sessions.host_id
     left outer join process as process on sessions.id = process.session_id
group by host.id;

Here's the SQLFiddle to the schema.

As per the data in the fiddle, the output should be:

id | session count | process count
----------------------------------
1  |     2         |   3
2  |     1         |   2
3  |     1         |   2
4  |     2         |   3

But what I get is:

id | session count | process count
----------------------------------
1  |     3         |   3
2  |     2         |   2
3  |     2         |   2
4  |     3         |   3

What can be the correct query to get the desired output?

Body:
If you query without the group by-clause, you will see that you are getting the same session id multiple times. Therefore you sessions count is too high.

select h.id as hid, s.id as sid, p.id as pid
from host h
left join sessions s on h.id = s.host_id
left join process p on s.id = p.session_id
order by h.id, s.id, p.id;

hid sid pid
-----------
1   1   1
1   1   2
1   2   5
2   5   8
2   5   9
3   3   3
3   3   7
4   4   4
4   4   6
4   6   10

Therefore use count(distinct s.id) for the sessions:

select h.id as hid, count(distinct s.id) as session_count, count(p.id) as process_count
from host h
left join sessions s on h.id = s.host_id
left join process p on s.id = p.session_id
group by h.id


问:
How to declare a generic type Multi-Dimensional array in java
I want to store an array of 100 int elements in rows ie 1 row of 100 int datatypes.And every single element contains an array of 100 objects.How to do this in java or android. </p>

Body:
I think you need this.

100 T(Your Object) Objects in 200x100 matrix(array)

T[][][] t = new T[200][100][100] ;

t[0][0][1] = new T();
t[0][0][2] = new T();
...
t[0][0][99] = new T();


问:
Bootstrap 4 tabs - Only one isn't working
I'm trying to build an admin section for a site where admins can go in and change things about the site. I've split this page up into different sections using tabs and they've been working up until I added the most recent one and as soon as I did, one of the ones that was already there, stopped working.
Here's the code - The one that isn't working is the "Historical Fact of The Day" tab:

```<code><!-- This is within a .container-fluid -->
<ul class="nav nav-tabs">
    <li class="nav-item">
        <a href="#potd" data-toggle="tab" role="tab" class="nav-link active">Photo of the Day</a>
    </li>
    <li class="nav-item">
        <a href="#users" data-toggle="tab" role="tab" class="nav-link">Users</a>
    </li>
    <li class="nav-item">
        <a href="#forum" data-toggle="tab" role="tab" class="nav-link">Forum</a>
    </li>
    <li class="nav-item">
        <a href="#hfotd" data-toggle="tab" role="tab" class="nav-link">Historical Fact of The Day</a>
    </li>
    <li class="nav-item">
        <a href="#cntdwn" data-toggle="tab" role="tab" class="nav-link">Countdown</a>
    </li>
</ul>

<div class="tab-content">
    <div class="tab-pane active" id="potd">
        <h3>Add a Photo of The Day</h3>
        <?php include 'create_potd.php'; ?>
        <h3>View Upcoming Photos of the Day</h3>
        <?php include 'view_potd.php'; ?>
    </div>
    <div class="tab-pane" id="forum">
        <h3>Create a category</h3>
        <?php include 'create_cat.php'; ?>
    </div>
    <div class="tab-pane" id="users">
        <h3>User List</h3>
        <?php include 'user_list.php'; ?>
    </div>
    <div class="tab-pane" id="hfotd">
        <h3>Add a Historical Fact of The Day</h3>
        <?php include 'create_hfotd.php'; ?>
        <h3>View Upcoming Historical Facts of the Day</h3>
        <?php include 'view_hfotd.php'; ?>
    </div>
    <div class="tab-pane" id="cntdwn">
        <h3>Change the current countdown</h3>
    </div>
</div>
</code>```

I really have no idea what the problem is. Thanks in advance!

答:
There is nothing wrong with the code you have shown. If your tabs are not working, then it must be to do with your included content. Check the browser console for errors, then check that the includes are producing valid HTML with all tags correctly opened and closed. Here is your code proven to work:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

        Photo of the Day

        Users

        Forum

        Historical Fact of The Day

        Countdown

Add a Photo of The Day

        php include 'create_potd.php';

View Upcoming Photos of the Day

        php include 'view_potd.php';

Create a category

        php include 'create_cat.php';

User List

        php include 'user_list.php';

Add a Historical Fact of The Day

        php include 'create_hfotd.php';

View Upcoming Historical Facts of the Day

        php include 'view_hfotd.php';

Change the current countdown

```

Body:
I'm trying to build an admin section for a site where admins can go in and change things about the site. I've split this page up into different sections using tabs and they've been working up until I added the most recent one and as soon as I did, one of the ones that was already there, stopped working.
Here's the code - The one that isn't working is the "Historical Fact of The Day" tab:

        Photo of the Day

        Users

        Forum

        Historical Fact of The Day

        Countdown

Add a Photo of The Day

        <?php include 'create_potd.php'; ?>

View Upcoming Photos of the Day

        <?php include 'view_potd.php'; ?>

Create a category

        <?php include 'create_cat.php'; ?>

User List

        <?php include 'user_list.php'; ?>

Add a Historical Fact of The Day

        <?php include 'create_hfotd.php'; ?>

View Upcoming Historical Facts of the Day

        <?php include 'view_hfotd.php'; ?>

Change the current countdown

I really have no idea what the problem is. Thanks in advance!

Body:
There is nothing wrong with the code you have shown. If your tabs are not working, then it must be to do with your included content. Check the browser console for errors, then check that the includes are producing valid HTML with all tags correctly opened and closed. Here is your code proven to work:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<!-- This is within a .container-fluid -->
<ul class="nav nav-tabs">
    <li class="nav-item">
        <a href="#potd" data-toggle="tab" role="tab" class="nav-link active">Photo of the Day</a>
    </li>
    <li class="nav-item">
        <a href="#users" data-toggle="tab" role="tab" class="nav-link">Users</a>
    </li>
    <li class="nav-item">
        <a href="#forum" data-toggle="tab" role="tab" class="nav-link">Forum</a>
    </li>
    <li class="nav-item">
        <a href="#hfotd" data-toggle="tab" role="tab" class="nav-link">Historical Fact of The Day</a>
    </li>
    <li class="nav-item">
        <a href="#cntdwn" data-toggle="tab" role="tab" class="nav-link">Countdown</a>
    </li>
</ul>

<div class="tab-content">
    <div class="tab-pane active" id="potd">
        <h3>Add a Photo of The Day</h3>
        php include 'create_potd.php';
        <h3>View Upcoming Photos of the Day</h3>
        php include 'view_potd.php';
    </div>
    <div class="tab-pane" id="forum">
        <h3>Create a category</h3>
        php include 'create_cat.php';
    </div>
    <div class="tab-pane" id="users">
        <h3>User List</h3>
        php include 'user_list.php';
    </div>
    <div class="tab-pane" id="hfotd">
        <h3>Add a Historical Fact of The Day</h3>
        php include 'create_hfotd.php';
        <h3>View Upcoming Historical Facts of the Day</h3>
        php include 'view_hfotd.php';
    </div>
    <div class="tab-pane" id="cntdwn">
        <h3>Change the current countdown</h3>
    </div>
</div>


问:
How to dynamically populate a RadioButtonList from the database within a Repeater control
This is the first time I have tried to dynamically populate a RadioButtonList from within a Repeater control. It is not going very well so far.

I am trying this code that I found here that supposedly worked for the guy who wrote it:

```<code>protected void fillRepeater_onitembound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        sql = "select PurchaseTypeID,PurchaseType from PurchaseType";
        object obj = null;
        ds = obj.openDataset(sql);
        ListItem li;

        RadioButtonList rbtl = (RadioButtonList)e.Item.FindControl("radioatt");
        if (rbtl != null)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                li = new ListItem();
                li.Text = dt.Rows[i]["PurchaseType"].ToString();
                li.Value = dt.Rows[i]["PurchaseTypeID"].ToString();
                rbtl.Items.Add(li);
            }
        }
    }
}

<asp:Repeater ID="Repeater2" runat="server" OnItemDataBound="fillRepeater_onitembound">
  <ItemTemplate>
     <table style="width:100%;border: 1px solid black;">
         <tr>
          <td style="width:50%;border-collapse: collapse;border: 1px solid black;">
             Purchased:<asp:radiobuttonlist ID="rblPurchaseType" runat="server" RepeatDirection="Horizontal" TextAlign="Right" style="display:inline;"></asp:radiobuttonlist></td>
              <td style="text-align:center;border: 1px solid black;">
          </td>
         </tr>
         <tr>
     </table>
     ...
     ...
     ...
  </asp:Repeater>
</code>```

However, I am running into bugs:

'object' does not contain a definition for 'openDataset' and no extension method 'openDataset' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?

Any ideas what's wrong?

UPDATE:

```<code>    public DataTable LoadDataFromDatabase(string query)
    {
        DataTable dt = new DataTable();

        using (SqlConnection connection = new SqlConnection(connStr))
        using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
        {
            try
            {
                adapter.Fill(dt);
            }
            catch (Exception ex)
            {
                //handle error if needed
            }
        }

        return dt;
    }
    string myQuery = "SELECT PurchaseTypeID, PurchaseType FROM PurchaseType ORDER BY PurchaseType";
    string rbtl = Repeater2.FindControl("rblPurchaseType");
    rbtl.DataSource = LoadDataFromDatabase(myQuery);
    rbtl.DataTextField = "PurchaseType";
rbtl.DataValueField = "PurchaseTypeID";
rbtl.DataBind();
</code>```

答:
What exactly is obj? Unless you cast it back to something that has an openDataset property this is never gonna work.

What I use is a simple method that returns a DataTable from a query and bind that to the RadioButtonList

```<code>public DataTable LoadDataFromDatabase(string query)
{
    DataTable dt = new DataTable();

    using (SqlConnection connection = new SqlConnection(YourConnectionString))
    using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
    {
        try
        {
            adapter.Fill(dt);
        }
        catch (Exception ex)
        {
            //handle error if needed
        }
    }

    return dt;
}
</code>```

Now you can use this method to quickly and simple get your needed content from the database and bind it to whatever Control you need.

```<code>string myQuery = "SELECT PurchaseTypeID, PurchaseType FROM PurchaseType ORDER BY PurchaseType";

rbtl.DataSource = LoadDataFromDatabase(myQuery);
rbtl.DataTextField = "PurchaseType";
rbtl.DataValueField = "PurchaseTypeID";
rbtl.DataBind();
</code>```

PS rbtl is always gonna be null in your case since the ID of the RadioButton in the aspx is rblPurchaseType and you use FindControl on radioatt, make sure these are the same.

Body:
This is the first time I have tried to dynamically populate a RadioButtonList from within a Repeater control. It is not going very well so far.

I am trying this code that I found here that supposedly worked for the guy who wrote it:

protected void fillRepeater_onitembound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        sql = "select PurchaseTypeID,PurchaseType from PurchaseType";
        object obj = null;
        ds = obj.openDataset(sql);
        ListItem li;

        RadioButtonList rbtl = (RadioButtonList)e.Item.FindControl("radioatt");
        if (rbtl != null)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                li = new ListItem();
                li.Text = dt.Rows[i]["PurchaseType"].ToString();
                li.Value = dt.Rows[i]["PurchaseTypeID"].ToString();
                rbtl.Items.Add(li);
            }
        }
    }
}

<asp:Repeater ID="Repeater2" runat="server" OnItemDataBound="fillRepeater_onitembound">
  <ItemTemplate>

             Purchased:<asp:radiobuttonlist ID="rblPurchaseType" runat="server" RepeatDirection="Horizontal" TextAlign="Right" style="display:inline;"></asp:radiobuttonlist>

     ...
     ...
     ...
  </asp:Repeater>

However, I am running into bugs:

'object' does not contain a definition for 'openDataset' and no extension method 'openDataset' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?

Any ideas what's wrong?

UPDATE:

    public DataTable LoadDataFromDatabase(string query)
    {
        DataTable dt = new DataTable();

        using (SqlConnection connection = new SqlConnection(connStr))
        using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
        {
            try
            {
                adapter.Fill(dt);
            }
            catch (Exception ex)
            {
                //handle error if needed
            }
        }

        return dt;
    }
    string myQuery = "SELECT PurchaseTypeID, PurchaseType FROM PurchaseType ORDER BY PurchaseType";
    string rbtl = Repeater2.FindControl("rblPurchaseType");
    rbtl.DataSource = LoadDataFromDatabase(myQuery);
    rbtl.DataTextField = "PurchaseType";
rbtl.DataValueField = "PurchaseTypeID";
rbtl.DataBind();

Body:
What exactly is obj? Unless you cast it back to something that has an openDataset property this is never gonna work.

What I use is a simple method that returns a DataTable from a query and bind that to the RadioButtonList

public DataTable LoadDataFromDatabase(string query)
{
    DataTable dt = new DataTable();

    using (SqlConnection connection = new SqlConnection(YourConnectionString))
    using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
    {
        try
        {
            adapter.Fill(dt);
        }
        catch (Exception ex)
        {
            //handle error if needed
        }
    }

    return dt;
}

Now you can use this method to quickly and simple get your needed content from the database and bind it to whatever Control you need.

string myQuery = "SELECT PurchaseTypeID, PurchaseType FROM PurchaseType ORDER BY PurchaseType";

rbtl.DataSource = LoadDataFromDatabase(myQuery);
rbtl.DataTextField = "PurchaseType";
rbtl.DataValueField = "PurchaseTypeID";
rbtl.DataBind();

PS rbtl is always gonna be null in your case since the ID of the RadioButton in the aspx is rblPurchaseType and you use FindControl on radioatt, make sure these are the same.


问:
arrange side bar, navigation bar and footer

html {
  position: relative;
  min-height: 100%;
}
body {
  /* Margin bottom by footer height */
  margin-bottom: 60px;
  overflow-x: hidden;
}
/*footer*/
.footer {
  position: absolute;
  bottom: 0;
  width: 100%;

  /* Set the fixed height of the footer here */
  height: 60px;
  background-color: #f5f5f5;
}

/*navbar*/
.navbar{
 background-color:black;

 font-family: sans-serif;
 font-size: 20px;
}
.navbar-brand{
 font-size: 20px;

}
.logo1{
 height: 50px;
 width: 75px;
 opacity: 0.1px;
 left: 0px;
 top: 0px;
 position: absolute;
}

.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
color: #000;  /*Sets the text hover color on navbar*/
}

.navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active >
 a:hover, .navbar-default .navbar-nav > .active > a:focus {
color: white; /*BACKGROUND color for active*/
background-color: #030033;
}

  .navbar-default {
    background-color: #0f006f;
    border-color: #030033;
}

  .dropdown-menu > li > a:hover,
   .dropdown-menu > li > a:focus {
    color: #262626;
   text-decoration: none;
  background-color: #66CCFF;  /*change color of links in drop down here*/
   }

 .nav > li > a:hover,
 .nav > li > a:focus {
    text-decoration: none;
    background-color: silver; /*Change rollover cell color here*/
  }

  .navbar-default .navbar-nav > li > a {
   color: whites; /*Change active text color here*/
    }
body > .container {
  padding: 60px 15px 0;
}
.container .text-muted {
  margin: 20px 0;
}
/* side bar*/
/* Toggle Styles */

#wrapper {
    padding-left: 0;
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}

#wrapper.toggled {
    padding-left: 250px;
}

#sidebar-wrapper {
    z-index: 1000;
    position: fixed;
    left: 250px;
    width: 0;
    height: 100%;
    margin-left: -250px;
    overflow-y: auto;
    background: #000;
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}

#wrapper.toggled #sidebar-wrapper {
    width: 250px;
}

#page-content-wrapper {
    width: 100%;
    position: absolute;
    padding: 15px;
}

#wrapper.toggled #page-content-wrapper {
    position: absolute;
    margin-right: -250px;
}

/* Sidebar Styles */

.sidebar-nav {
    position: absolute;
    top: 0;
    width: 250px;
    margin: 0;
    padding: 0;
    list-style: none;
 z-index: 1;
}

.sidebar-nav li {
    text-indent: 20px;
    line-height: 40px;
}

.sidebar-nav li a {
    display: block;
    text-decoration: none;
    color: #999999;
}

.sidebar-nav li a:hover {
    text-decoration: none;
    color: #fff;
    background: rgba(255,255,255,0.2);
}

.sidebar-nav li a:active,
.sidebar-nav li a:focus {
    text-decoration: none;
}

.sidebar-nav > .sidebar-brand {
    height: 65px;
    font-size: 18px;
    line-height: 60px;
}

.sidebar-nav > .sidebar-brand a {
    color: #999999;
}

.sidebar-nav > .sidebar-brand a:hover {
    color: #fff;
    background: none;
}
.btn>.btn-default{

}

@media(min-width:768px) {
    #wrapper {
        padding-left: 0;
    }

    #wrapper.toggled {
        padding-left: 250px;
    }

    #sidebar-wrapper {
        width: 0;
    }

    #wrapper.toggled #sidebar-wrapper {
        width: 250px;
    }

    #page-content-wrapper {
        padding: 20px;
        position: relative;
    }

    #wrapper.toggled #page-content-wrapper {
        position: relative;
        margin-right: 0;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap 101 Template</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
 <link rel="stylesheet" type="text/css" href="style1.css" />
 <link href="bootstrap.min1.css" rel="stylesheet">
  </head>
  <body>
  <!--top bar-->
  <nav class="navbar navbar-inverse navbar-static-top">
 <div class="container">
  <div class="navbar-header">
   <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
    <span class="sr-only">Toggle navigation</span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
   </button>
   <img class="logo1" src="images/capture.png" alt=" logo">
   Web Portax
  </div>
  <form class="navbar-form navbar-left" role="search">
  <div class="form-group">
  <input type="text" class="form-control" placeholder="Search">
  </div>
  <button type="submit" class="btn btn-default">Submit</button>
  </form>
  <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
   <ul class="nav navbar-nav navbar-right">
    <li>Account Setting</li>
    <li>Message</li>
    <li class="dropdown">
     Services<span class="caret"></span>
     <ul class="dropdown-menu">
      <li>Log Out</li>
      <li>Edit Profile</li>
      <li>Manage prefrences</li>
     </ul>
    </li>
   </ul>
  </div>
 </div>
</nav>

<div id="wrapper">

        <!-- Sidebar -->
        <div id="sidebar-wrapper">
            <ul class="sidebar-nav">
                <li class="sidebar-brand">

                        Start Bootstrap

                </li>
                <li>
                    Dashboard
                </li>
                <li>
                    Shortcuts
                </li>
                <li>
                    Overview
                </li>
                <li>
                    Events
                </li>
                <li>
                    About
                </li>
                <li>
                    Services
                </li>
                <li>
                    Contact
                </li>
            </ul>
        </div>
        <!-- /#sidebar-wrapper -->

        <!-- Page Content -->
        <div id="page-content-wrapper">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-lg-12">

                    </div>
                </div>
            </div>
        </div>
        <!-- /#page-content-wrapper -->

    </div>
    <!-- /#wrapper -->

    <!-- jQuery -->
    <script src="jquery1.js"></script>

    <!-- Bootstrap Core JavaScript -->
    <script src="bootstrap.min1.js"></script>

    <!-- Menu Toggle Script -->
    <script>
    $("#menu-toggle").click(function(e) {
        e.preventDefault();
        $("#wrapper").toggleClass("toggled");
    });
    </script>

<!-- body-->

    <!-- Footer -->
    <div class="container">
      <div class="page-header">
        <h1>Content</h1>
      </div>

    </div>

    <footer class="footer">
      <div class="container">
   <div class="row">
        <p class="text-muted"> All rights reserved.  </p>
  </div>
      </div>
    </footer>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
  </body>
</html></code>```

Hey guys can anyone help me as my current page looks like this[enter image description here]

enter image description here

When i click toogle to expand my side bar it looks like this.
enter image description here

How can i fix the white spaces that is in between the header and the sidebar? How can i shift the little grey thing to toggle the sidebar to left corner? and lastly how can i shift "Web Portax" from the top nav bar slightly to the right so when i minimize it the logo and the text do not crumple together?

I am new to html thing so sorry for the amateur question. Thank you!

答:
Use  the margin property in CSS to adjust the space around your elements.

Example:

    margin-top: 100px;
 margin-bottom: 100px;
 margin-right: 150px;
 margin-left: 80px;

and the padding element to adjust the space in between the content and the border of the element.

Example:

padding-top: 50px;
 padding-right: 30px;
 padding-bottom: 50px;
 padding-left: 80px;

You can also use the height and width properties to adjust the size of the element.

Example height: 100px;

Body:
html {
  position: relative;
  min-height: 100%;
}
body {
  /* Margin bottom by footer height */
  margin-bottom: 60px;
  overflow-x: hidden;
}
/*footer*/
.footer {
  position: absolute;
  bottom: 0;
  width: 100%;

  /* Set the fixed height of the footer here */
  height: 60px;
  background-color: #f5f5f5;
}

/*navbar*/
.navbar{
 background-color:black;

 font-family: sans-serif;
 font-size: 20px;
}
.navbar-brand{
 font-size: 20px;

}
.logo1{
 height: 50px;
 width: 75px;
 opacity: 0.1px;
 left: 0px;
 top: 0px;
 position: absolute;
}

.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
color: #000;  /*Sets the text hover color on navbar*/
}

.navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active >
 a:hover, .navbar-default .navbar-nav > .active > a:focus {
color: white; /*BACKGROUND color for active*/
background-color: #030033;
}

  .navbar-default {
    background-color: #0f006f;
    border-color: #030033;
}

  .dropdown-menu > li > a:hover,
   .dropdown-menu > li > a:focus {
    color: #262626;
   text-decoration: none;
  background-color: #66CCFF;  /*change color of links in drop down here*/
   }

 .nav > li > a:hover,
 .nav > li > a:focus {
    text-decoration: none;
    background-color: silver; /*Change rollover cell color here*/
  }

  .navbar-default .navbar-nav > li > a {
   color: whites; /*Change active text color here*/
    }
body > .container {
  padding: 60px 15px 0;
}
.container .text-muted {
  margin: 20px 0;
}
/* side bar*/
/* Toggle Styles */

#wrapper {
    padding-left: 0;
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}

#wrapper.toggled {
    padding-left: 250px;
}

#sidebar-wrapper {
    z-index: 1000;
    position: fixed;
    left: 250px;
    width: 0;
    height: 100%;
    margin-left: -250px;
    overflow-y: auto;
    background: #000;
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}

#wrapper.toggled #sidebar-wrapper {
    width: 250px;
}

#page-content-wrapper {
    width: 100%;
    position: absolute;
    padding: 15px;
}

#wrapper.toggled #page-content-wrapper {
    position: absolute;
    margin-right: -250px;
}

/* Sidebar Styles */

.sidebar-nav {
    position: absolute;
    top: 0;
    width: 250px;
    margin: 0;
    padding: 0;
    list-style: none;
 z-index: 1;
}

.sidebar-nav li {
    text-indent: 20px;
    line-height: 40px;
}

.sidebar-nav li a {
    display: block;
    text-decoration: none;
    color: #999999;
}

.sidebar-nav li a:hover {
    text-decoration: none;
    color: #fff;
    background: rgba(255,255,255,0.2);
}

.sidebar-nav li a:active,
.sidebar-nav li a:focus {
    text-decoration: none;
}

.sidebar-nav > .sidebar-brand {
    height: 65px;
    font-size: 18px;
    line-height: 60px;
}

.sidebar-nav > .sidebar-brand a {
    color: #999999;
}

.sidebar-nav > .sidebar-brand a:hover {
    color: #fff;
    background: none;
}
.btn>.btn-default{

}

@media(min-width:768px) {
    #wrapper {
        padding-left: 0;
    }

    #wrapper.toggled {
        padding-left: 250px;
    }

    #sidebar-wrapper {
        width: 0;
    }

    #wrapper.toggled #sidebar-wrapper {
        width: 250px;
    }

    #page-content-wrapper {
        padding: 20px;
        position: relative;
    }

    #wrapper.toggled #page-content-wrapper {
        position: relative;
        margin-right: 0;
    }
}

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap 101 Template</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">

 <link rel="stylesheet" type="text/css" href="style1.css" />
 <link href="bootstrap.min1.css" rel="stylesheet">

   <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
    Toggle navigation

   </button>

   Web Portax

  <form class="navbar-form navbar-left" role="search">

  <input type="text" class="form-control" placeholder="Search">

  <button type="submit" class="btn btn-default">Submit</button>
  </form>

Account Setting

Message

     Services

Log Out

Edit Profile

Manage prefrences

                        Start Bootstrap

                    Dashboard

                    Shortcuts

                    Overview

                    Events

                    About

                    Services

                    Contact

Content

 All rights reserved.

Hey guys can anyone help me as my current page looks like this[enter image description here]

enter image description here

When i click toogle to expand my side bar it looks like this.
enter image description here

How can i fix the white spaces that is in between the header and the sidebar? How can i shift the little grey thing to toggle the sidebar to left corner? and lastly how can i shift "Web Portax" from the top nav bar slightly to the right so when i minimize it the logo and the text do not crumple together?

I am new to html thing so sorry for the amateur question. Thank you!


问:
jquery drag and drop
I found the  following example on this website.

What I want is:

I want to be able to drag items back from the Thrash

How can I get the total number of pictures in an album and trash to store in MySQL using PHP?

答: What you'll want to do is create an AJAX call. Using the $.ajax function to send data from the browser when the user performs a drag and drop to the server. With the php code, you'll need to setup handlers to accept the data coming from the javascript.</p>

Title: jquery drag and drop


问:
Is it possible to make an sql query that counts from one table and then subtract the number it obtained from another table?
I have an access db that i must use to manage interns and the places they work at. Right now, I have two tables: one for the persons, with their personal detail and a bridge to where they work, and another table with the name of the workplace with the respective boss.

Like so:

(table 1, where the persons are listed)

Cadastro_de_estagiarios

id | Ativo | Nível | Lotação | Nome

1 | Verdadeiro | Superior | 1ª Vara Cível | Marina x

3 | Verdadeiro | Médio | 1ª Vara Cível | Raquel x

and so on...

(table 2, where the locations and bosses are specificated)

Cadastro_de_varas_e_juizes

id | Vara | Juiz responsável | Vagas totais nível superior | Vagas totais nível médio

1 | 1ª Vara Cível | fist boss | 2 | 3

2 | 2ª Vara Cível | sec boss | 2 | 4

3 | 3ª Vara Cível | third boss | 2 | 3

and so on...

To clarify, I have two kinds of interns (nível superior e nível médio), as well as two kinds of job vacancies per workplace. Like this: In 1ª Vara Cível, I can have 2 interns with "superior" and 3 with "médio".

What I need to do is get the info on how many interns are placed on each workplace per job type, and then have a query that tells me how many vacancies I still have per place and type.

I appreciate any help. Thanks!

Translating the tables

table1

id | Active | Education level of intern | Workplace | Name

table2

id | Workplace | Boss | Vacancies for college students | Vacancies for high school students

答:
This should give you a starting point:
SQL Fiddle

MySQL 5.6 Schema Setup:

```<code>CREATE TABLE table1 (
  id INT,
  Active VARCHAR(50),
  Education_level VARCHAR(50),
  Workplace VARCHAR(50),
  Name VARCHAR(50)
);

CREATE TABLE table2  (
  id INT,
  Workplace VARCHAR(50),
  Boss VARCHAR(50),
  Vacancies_college INT,
  Vacancies_high_school INT
);

INSERT INTO table1 VALUES
(1, 'Verdadeiro', 'Superior', '1ª Vara Cível', 'Marina x'),
(3, 'Verdadeiro', 'Médio', '1ª Vara Cível', 'Raquel x');

INSERT INTO table2 VALUES
(1, '1ª Vara Cível', 'fist boss', 2, 3),
(2, '2ª Vara Cível', 'sec boss', 2, 4),
(3, '3ª Vara Cível', 'third boss', 2, 3);
</code>```

Query 1:

```<code>SELECT t1.Workplace, t1.Active, t1.Education_level,
(CASE
 WHEN t1.Education_level = 'Médio' THEN t2.Vacancies_college
 WHEN t1.Education_level = 'Superior' THEN t2.Vacancies_high_school
END)  - COUNT(*) AS vacancies
FROM table1 t1 LEFT JOIN table2 t2
ON (t1.Workplace = t2.Workplace)
GROUP BY t1.Workplace, t1.Active, t1.Education_level
</code>```

Results:

```<code>|     Workplace |     Active | Education_level | vacancies |
|---------------|------------|-----------------|-----------|
| 1ª Vara Cível | Verdadeiro |           Médio |         1 |
| 1ª Vara Cível | Verdadeiro |        Superior |         2 |
</code>```

Body:
This should give you a starting point:
SQL Fiddle

MySQL 5.6 Schema Setup:

CREATE TABLE table1 (
  id INT,
  Active VARCHAR(50),
  Education_level VARCHAR(50),
  Workplace VARCHAR(50),
  Name VARCHAR(50)
);

CREATE TABLE table2  (
  id INT,
  Workplace VARCHAR(50),
  Boss VARCHAR(50),
  Vacancies_college INT,
  Vacancies_high_school INT
);

INSERT INTO table1 VALUES
(1, 'Verdadeiro', 'Superior', '1ª Vara Cível', 'Marina x'),
(3, 'Verdadeiro', 'Médio', '1ª Vara Cível', 'Raquel x');

INSERT INTO table2 VALUES
(1, '1ª Vara Cível', 'fist boss', 2, 3),
(2, '2ª Vara Cível', 'sec boss', 2, 4),
(3, '3ª Vara Cível', 'third boss', 2, 3);

Query 1:

SELECT t1.Workplace, t1.Active, t1.Education_level,
(CASE
 WHEN t1.Education_level = 'Médio' THEN t2.Vacancies_college
 WHEN t1.Education_level = 'Superior' THEN t2.Vacancies_high_school
END)  - COUNT(*) AS vacancies
FROM table1 t1 LEFT JOIN table2 t2
ON (t1.Workplace = t2.Workplace)
GROUP BY t1.Workplace, t1.Active, t1.Education_level

Results:

|     Workplace |     Active | Education_level | vacancies |
|---------------|------------|-----------------|-----------|
| 1ª Vara Cível | Verdadeiro |           Médio |         1 |
| 1ª Vara Cível | Verdadeiro |        Superior |         2 |


问:
Google style docstring Example section is not rendering as a code snippet
I recently started adding documentation to my project and I'm trying to follow the Google style guide. I am using Sphinx to generate the documents and the Sphinx extension napoleon to bridge the gap between the Google styleguide and reST.

I have no problem rendering params and Notes but I can't seem to get the Example section to render a code snippet.

```<code>class Chicken(object):
      """Animal that lays egg and has feathers

         Note:
             Chickens love to eat feed

         Example:
             chicken.eats(feed)
      """
</code>```

I have also tried a double colon with the Example section.

```<code>Example::
</code>```

答:
You need a double colon AND a blank line between the Example:: section break and the literal block.

See the example from the Napoleon docs:

```<code>"""Example Google style docstrings.

This module demonstrates documentation as specified by the `Google Python
Style Guide`_. Docstrings may extend over multiple lines. Sections are created
with a section header and a colon followed by a block of indented text.

Example:
    Examples can be given using either the ``Example`` or ``Examples``
    sections. Sections support any reStructuredText formatting, including
    literal blocks::

        $ python example_google.py

Section breaks are created by resuming unindented text. Section breaks
are also implicitly created anytime a new section starts.
"""
</code>```

So, in your example, try this:

```<code>class Chicken(object):
      """Animal that lays egg and has feathers

         Note:
             Chickens love to eat feed

         Example::

             chicken.eats(feed)
      """
</code>```

Body:
I recently started adding documentation to my project and I'm trying to follow the Google style guide. I am using Sphinx to generate the documents and the Sphinx extension napoleon to bridge the gap between the Google styleguide and reST.

I have no problem rendering params and Notes but I can't seem to get the Example section to render a code snippet.

class Chicken(object):
      """Animal that lays egg and has feathers

         Note:
             Chickens love to eat feed

         Example:
             chicken.eats(feed)
      """

I have also tried a double colon with the Example section.

Example::

Body:
You need a double colon AND a blank line between the Example:: section break and the literal block.

See the example from the Napoleon docs:

"""Example Google style docstrings.

This module demonstrates documentation as specified by the `Google Python
Style Guide`_. Docstrings may extend over multiple lines. Sections are created
with a section header and a colon followed by a block of indented text.

Example:
    Examples can be given using either the ``Example`` or ``Examples``
    sections. Sections support any reStructuredText formatting, including
    literal blocks::

        $ python example_google.py

Section breaks are created by resuming unindented text. Section breaks
are also implicitly created anytime a new section starts.
"""

So, in your example, try this:

class Chicken(object):
      """Animal that lays egg and has feathers

         Note:
             Chickens love to eat feed

         Example::

             chicken.eats(feed)
      """


问:
How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)?
I have this in my package.json file (shortened version):

```<code>{
  "name": "a-module",
  "version": "0.0.1",
  "dependencies": {
    "coffee-script":      ">= 1.1.3"
  },
  "devDependencies": {
    "stylus":             ">= 0.17.0"
  }
}
</code>```

I am using NPM version 1.1.1 on Mac 10.6.8.

When I run the following command from the project root, it installs both the dependencies and devDependencies:

```<code>npm install
</code>```

I was under the impression that this command installed the devDependencies:

```<code>npm install --dev
</code>```

How do I make it so npm install only installs dependencies (so production environment only gets those modules), while something like npm install --dev installs both dependencies and devDependencies?

答:
It's worth mentioning that you can use the NODE_ENV environment variable to achieve the same result. Particularly useful if you're containerizing your Node application (e.g. Docker).

NODE_ENV=production npm install
```

<p>The above code will install all your dependencies but the dev ones (i.e. <code>devDependencies</code>).</p>

<p>if you need to use environment variables in your <code>Dockerfile</code> more information can be found here.</p>

<p>Environment variables are easy to overwrite whenever needed (e.g. if you want to run your test suite say on Travis CI). If that were the case you could do something like this:</p>

<pre class="lang-sh prettyprint-override"><code>docker run -v $(pwd):/usr/src/app --rm -it -e NODE_ENV=production node:8 npm install
</code>```

NPM Documentation here

production

Default: false

Type: Boolean
  Set to true to run in "production" mode.

devDependencies are not installed at the topmost level when running local npm install without any arguments.

Set the NODE_ENV="production" for lifecycle scripts.

Happy containerization =)

Body:
I have this in my package.json file (shortened version):

{
  "name": "a-module",
  "version": "0.0.1",
  "dependencies": {
    "coffee-script":      ">= 1.1.3"
  },
  "devDependencies": {
    "stylus":             ">= 0.17.0"
  }
}

I am using NPM version 1.1.1 on Mac 10.6.8.

When I run the following command from the project root, it installs both the dependencies and devDependencies:

npm install

I was under the impression that this command installed the devDependencies:

npm install --dev

How do I make it so npm install only installs dependencies (so production environment only gets those modules), while something like npm install --dev installs both dependencies and devDependencies?

Body:
It's worth mentioning that you can use the NODE_ENV environment variable to achieve the same result. Particularly useful if you're containerizing your Node application (e.g. Docker).

NODE_ENV=production npm install

The above code will install all your dependencies but the dev ones (i.e. devDependencies).

if you need to use environment variables in your Dockerfile more information can be found here.

Environment variables are easy to overwrite whenever needed (e.g. if you want to run your test suite say on Travis CI). If that were the case you could do something like this:

docker run -v $(pwd):/usr/src/app --rm -it -e NODE_ENV=production node:8 npm install

NPM Documentation here

production

Default: false

Type: Boolean
  Set to true to run in "production" mode.

devDependencies are not installed at the topmost level when running local npm install without any arguments.

Set the NODE_ENV="production" for lifecycle scripts.

Happy containerization =)


问:
Odoo accounting wants to change tax in paid invoices
I would like to reset tax in invoice just because I have proceed sales order and invoice with wrong tax. So how could I do this.

That I would like to achieve using code or manual.

答:
You could use the module account_cancel which will allow a cancellation of journal entries for special configured journals.

After installation you can configure journals, but you have to be in debug mode to see this option in journals.

In your example it should be the "Sales Journal". After configuring the journal, you can cancel the invoice and set it back to draft. Now just change the tax and validate the invoice again. You will get the same invoice number.

Attention: in some countries such accounting data manipulation is forbidden.


问:
Mule ESB Instance Monitoring
what is the best way to monitor the Mule ESB instances. Is there a way i can get alerted when my mule instance goes down for some reason. I have 4 instances of Mule running and how will I come to know if 1 of them got down due to some reason.

Thanks!

答:
You can set up a JMX agent by adding the following lines into your "conf/wrapper.conf" file :

```<code>wrapper.java.additional.19=-Dcom.sun.management.jmxremote
wrapper.java.additional.20=-Dcom.sun.management.jmxremote.port=10055
wrapper.java.additional.21=-Dcom.sun.management.jmxremote.authenticate=false
wrapper.java.additional.22=-Dcom.sun.management.jmxremote.ssl=false
wrapper.java.additional.23=-Djava.rmi.server.hostname=127.0.0.1
</code>```

don't forget to change the values accordingly. Also you can implement SSL authentication with a few extra lines.

Now once your monitoring platform is set up you can always activate Java pollers and start the server.

Title: Mule ESB Instance Monitoring

Body:
You can set up a JMX agent by adding the following lines into your "conf/wrapper.conf" file :

wrapper.java.additional.19=-Dcom.sun.management.jmxremote
wrapper.java.additional.20=-Dcom.sun.management.jmxremote.port=10055
wrapper.java.additional.21=-Dcom.sun.management.jmxremote.authenticate=false
wrapper.java.additional.22=-Dcom.sun.management.jmxremote.ssl=false
wrapper.java.additional.23=-Djava.rmi.server.hostname=127.0.0.1

don't forget to change the values accordingly. Also you can implement SSL authentication with a few extra lines.

Now once your monitoring platform is set up you can always activate Java pollers and start the server.


问:
How to debug a lambda expression using jdb
I am facing a problem in a clustered production server, I manage to isolate a single instance from users, so I have it available for debugging, I am doing this using jdb. Long intro end. My problem is that I need to debug the code into a lambda expression

```<code>public void method(){
    this.privateField = Util.methodCall(); // Here the breakpoint works
    Clazz.staticMethod(() -> {
       Integer x = 1;
       Long y = 2;
       y = x * y; // I need a Break point here
       /*
         And a lot of non related code
       */
       });
}
</code>```

When I create the breakpoint in jdb in that line, it simply ignores my break point. I am pretty sure that the method is called because the breakpoint reach the first line of the method, but simply ignores the other, I am using next and step commands, but doesn't work. So what could be wrong with my process ? how to debug lambda expressions with jdb ?

答:
Here an answer for people landing here and are intersted in.

create the class

```<code>import java.util.concurrent.Callable;
public class Clazz {

    public static void main(String[] args) throws Exception {
        new Clazz().method();
    }

    public void method() throws Exception {
        Clazz.staticMethod(() -> {
            Integer x = 1;
            Long y = 2L;
            y = x * y; // I need a Break point here
            return y;
        });
    }

    private static void staticMethod(Callable i) throws Exception {
        System.out.println("i = " + i.call());
    }
}
</code>```

compile it

```<code>javac Clazz.java
</code>```

start jdb for this class

```<code>jdb Clazz
Initializing jdb ...
</code>```

set a breakpoint in the main method using stop

```<code>> stop in Clazz.main
Deferring breakpoint Clazz.main.
It will be set after the class is loaded.
</code>```

start the debugging session with run

```<code>> run
run Clazz
Set uncaught java.lang.Throwable
Set deferred uncaught java.lang.Throwable
>
VM Started: Set deferred breakpoint Clazz.main

Breakpoint hit: "thread=main", Clazz.main(), line=6 bci=0
6            new Clazz().method();
</code>```

Now the debugger is stopped in the main method, just before invoking new Clazz().method();.

To find the line we are interested in we list the source

```<code>main[1] list
2
3    public class Clazz {
4
5        public static void main(String[] args) throws Exception {
6 =>         new Clazz().method();
7        }
8
9        public void method() throws Exception {
10            Clazz.staticMethod(() -> {
11                Integer x = 1;
main[1] list 12
8
9        public void method() throws Exception {
10            Clazz.staticMethod(() -> {
11                Integer x = 1;
12 =>             Long y = 2L;
13                y = x * y; // I need a Break point here
14                return y;
15            });
16        }
17
</code>```

The command list 12 is needed to list the following lines. In the output we can see that we want to stop at line 13. So let's set a new breakpoint there with the stop command

```<code>main[1] stop at Clazz:13
Set breakpoint Clazz:13
</code>```

to continue the execution till next breakpoint issue the command cont

```<code>main[1] cont
>
Breakpoint hit: "thread=main", Clazz.lambda$method$0(), line=13 bci=12
13                y = x * y; // I need a Break point here
</code>```

we are not on line 13 and for example could dump the values of x and y.

```<code>main[1] dump x
 x = {
    MIN_VALUE: -2147483648
    MAX_VALUE: 2147483647
    TYPE: instance of java.lang.Class(reflected class=int, id=568)
    digits: instance of char[36] (id=569)
    DigitTens: instance of char[100] (id=570)
    DigitOnes: instance of char[100] (id=571)
    sizeTable: instance of int[10] (id=572)
    value: 1
    SIZE: 32
    BYTES: 4
    serialVersionUID: 1360826667806852920
    java.lang.Number.serialVersionUID: -8742448824652078965
}
main[1] dump y
 y = {
    MIN_VALUE: -9223372036854775808
    MAX_VALUE: 9223372036854775807
    TYPE: instance of java.lang.Class(reflected class=long, id=574)
    value: 2
    SIZE: 64
    BYTES: 8
    serialVersionUID: 4290774380558885855
    java.lang.Number.serialVersionUID: -8742448824652078965
}
</code>```

going one step further

```<code>main[1] step
>
Step completed: "thread=main", Clazz.lambda$method$0(), line=14 bci=26
14
</code>```

we could now dump again the value of y

```<code>main[1] dump y
 y = {
    MIN_VALUE: -9223372036854775808
    MAX_VALUE: 9223372036854775807
    TYPE: instance of java.lang.Class(reflected class=long, id=574)
    value: 2
    SIZE: 64
    BYTES: 8
    serialVersionUID: 4290774380558885855
    java.lang.Number.serialVersionUID: -8742448824652078965
}
</code>```

Body:
I am facing a problem in a clustered production server, I manage to isolate a single instance from users, so I have it available for debugging, I am doing this using jdb. Long intro end. My problem is that I need to debug the code into a lambda expression

public void method(){
    this.privateField = Util.methodCall(); // Here the breakpoint works
    Clazz.staticMethod(() -> {
       Integer x = 1;
       Long y = 2;
       y = x * y; // I need a Break point here
       /*
         And a lot of non related code
       */
       });
}

When I create the breakpoint in jdb in that line, it simply ignores my break point. I am pretty sure that the method is called because the breakpoint reach the first line of the method, but simply ignores the other, I am using next and step commands, but doesn't work. So what could be wrong with my process ? how to debug lambda expressions with jdb ?

Body:
Here an answer for people landing here and are intersted in.

create the class

import java.util.concurrent.Callable;
public class Clazz {

    public static void main(String[] args) throws Exception {
        new Clazz().method();
    }

    public void method() throws Exception {
        Clazz.staticMethod(() -> {
            Integer x = 1;
            Long y = 2L;
            y = x * y; // I need a Break point here
            return y;
        });
    }

    private static void staticMethod(Callable i) throws Exception {
        System.out.println("i = " + i.call());
    }
}

compile it

javac Clazz.java

start jdb for this class

jdb Clazz
Initializing jdb ...

set a breakpoint in the main method using stop

> stop in Clazz.main
Deferring breakpoint Clazz.main.
It will be set after the class is loaded.

start the debugging session with run

> run
run Clazz
Set uncaught java.lang.Throwable
Set deferred uncaught java.lang.Throwable
>
VM Started: Set deferred breakpoint Clazz.main

Breakpoint hit: "thread=main", Clazz.main(), line=6 bci=0
6            new Clazz().method();

Now the debugger is stopped in the main method, just before invoking new Clazz().method();.

To find the line we are interested in we list the source

main[1] list
2
3    public class Clazz {
4
5        public static void main(String[] args) throws Exception {
6 =>         new Clazz().method();
7        }
8
9        public void method() throws Exception {
10            Clazz.staticMethod(() -> {
11                Integer x = 1;
main[1] list 12
8
9        public void method() throws Exception {
10            Clazz.staticMethod(() -> {
11                Integer x = 1;
12 =>             Long y = 2L;
13                y = x * y; // I need a Break point here
14                return y;
15            });
16        }
17

The command list 12 is needed to list the following lines. In the output we can see that we want to stop at line 13. So let's set a new breakpoint there with the stop command

main[1] stop at Clazz:13
Set breakpoint Clazz:13

to continue the execution till next breakpoint issue the command cont

main[1] cont
>
Breakpoint hit: "thread=main", Clazz.lambda$method$0(), line=13 bci=12
13                y = x * y; // I need a Break point here

we are not on line 13 and for example could dump the values of x and y.

main[1] dump x
 x = {
    MIN_VALUE: -2147483648
    MAX_VALUE: 2147483647
    TYPE: instance of java.lang.Class(reflected class=int, id=568)
    digits: instance of char[36] (id=569)
    DigitTens: instance of char[100] (id=570)
    DigitOnes: instance of char[100] (id=571)
    sizeTable: instance of int[10] (id=572)
    value: 1
    SIZE: 32
    BYTES: 4
    serialVersionUID: 1360826667806852920
    java.lang.Number.serialVersionUID: -8742448824652078965
}
main[1] dump y
 y = {
    MIN_VALUE: -9223372036854775808
    MAX_VALUE: 9223372036854775807
    TYPE: instance of java.lang.Class(reflected class=long, id=574)
    value: 2
    SIZE: 64
    BYTES: 8
    serialVersionUID: 4290774380558885855
    java.lang.Number.serialVersionUID: -8742448824652078965
}

going one step further

main[1] step
>
Step completed: "thread=main", Clazz.lambda$method$0(), line=14 bci=26
14

we could now dump again the value of y

main[1] dump y
 y = {
    MIN_VALUE: -9223372036854775808
    MAX_VALUE: 9223372036854775807
    TYPE: instance of java.lang.Class(reflected class=long, id=574)
    value: 2
    SIZE: 64
    BYTES: 8
    serialVersionUID: 4290774380558885855
    java.lang.Number.serialVersionUID: -8742448824652078965
}


问:
Which React cycle method should I use to re-render component when redux state has changed?
The React doc are unfortunately unclear for me at my level of understanding.

What cycle method should I use here instead of componentDidMount()? I want this component to update Google Map every time it gets new state from state.selectedShopInfo.

In my app user is clicking some list and every time he clicks this component gets new data.

I'm checking it with console.log(_.last(this.props.selectedShopInfo)); and it is working.

So what React cycle method should I use so every time { selectedShopInfo: state.selectedShopInfo } will change GoogleMap Component will change as well?

```<code>    import _ from 'lodash';
    import React, { Component } from 'react';
    import { connect } from 'react-redux';

    class GoogleMap extends Component {
      componentDidMount() {
        const lastSelectedShopInfo = _.last(this.props.selectedShopInfo);
        if (lastSelectedShopInfo !== undefined) {
          new google.maps.Map(this.refs.map, {
            zoom: 20,
            center: {
              lat: Number(lastSelectedShopInfo.latitude),
              lng: Number(lastSelectedShopInfo.longitude),
            },
          });
        }
      }

      render() {
        console.log(_.last(this.props.selectedShopInfo));
        return (
          <div>
            <hr />
            <div className="google-map" ref="map" />
            <hr />
          </div>
        );
      }
    }

    function mapStateToProps(state) {
      return { selectedShopInfo: state.selectedShopInfo };
    }

    export default connect(mapStateToProps)(GoogleMap);
</code>```

答:
Your component will re-render anytime a props or state change. This is the default behavior for React components.

So your component will re-render, but the logic you have in componentWillMount will not be applied more than once.

To solve this, move that logic to a separate function and call that both in componentDidMount() and in componentDidUpdate(). Something like this:

```<code>componentDidMount() {
  this.mapsInit();
}

componentDidUpdate(prevProps) {
  if (JSON.stringify(this.props) !== JSON.stringify(prevProps)) {
    this.mapsInit();
  }
}

mapsInit() {
  const lastSelectedShopInfo = _.last(this.props.selectedShopInfo);
    if (lastSelectedShopInfo !== undefined) {
      new google.maps.Map(this.refs.map, {
        zoom: 20,
        center: {
          lat: Number(lastSelectedShopInfo.latitude),
          lng: Number(lastSelectedShopInfo.longitude),
        },
      });
    }
  }
}
</code>```

Body:
The React doc are unfortunately unclear for me at my level of understanding.

What cycle method should I use here instead of componentDidMount()? I want this component to update Google Map every time it gets new state from state.selectedShopInfo.

In my app user is clicking some list and every time he clicks this component gets new data.

I'm checking it with console.log(_.last(this.props.selectedShopInfo)); and it is working.

So what React cycle method should I use so every time { selectedShopInfo: state.selectedShopInfo } will change GoogleMap Component will change as well?

    import _ from 'lodash';
    import React, { Component } from 'react';
    import { connect } from 'react-redux';

    class GoogleMap extends Component {
      componentDidMount() {
        const lastSelectedShopInfo = _.last(this.props.selectedShopInfo);
        if (lastSelectedShopInfo !== undefined) {
          new google.maps.Map(this.refs.map, {
            zoom: 20,
            center: {
              lat: Number(lastSelectedShopInfo.latitude),
              lng: Number(lastSelectedShopInfo.longitude),
            },
          });
        }
      }

      render() {
        console.log(_.last(this.props.selectedShopInfo));
        return (

        );
      }
    }

    function mapStateToProps(state) {
      return { selectedShopInfo: state.selectedShopInfo };
    }

    export default connect(mapStateToProps)(GoogleMap);

Body:
Your component will re-render anytime a props or state change. This is the default behavior for React components.

So your component will re-render, but the logic you have in componentWillMount will not be applied more than once.

To solve this, move that logic to a separate function and call that both in componentDidMount() and in componentDidUpdate(). Something like this:

componentDidMount() {
  this.mapsInit();
}

componentDidUpdate(prevProps) {
  if (JSON.stringify(this.props) !== JSON.stringify(prevProps)) {
    this.mapsInit();
  }
}

mapsInit() {
  const lastSelectedShopInfo = _.last(this.props.selectedShopInfo);
    if (lastSelectedShopInfo !== undefined) {
      new google.maps.Map(this.refs.map, {
        zoom: 20,
        center: {
          lat: Number(lastSelectedShopInfo.latitude),
          lng: Number(lastSelectedShopInfo.longitude),
        },
      });
    }
  }
}


问:
Angular 4 params with json stringify
I have to stringify some parameter to put it in a http patch request my method is something like this

```<code>let param = JSON.stringify({
code : this.code,
name : this.name,
fieldName: this.data
});
</code>```

In that case I have a param like this:

code:3,name:'asdf',fieldName: 'col'

But I want the value of fieldName ond not the word fieldName...
Is there a method to expand or evaluate this parameter name?

答:
If you want value of code variable to be used as a key name, then you need to use computed object property notation:

```<code>let param = JSON.stringify({
  [code]: this.code,
  [name]: this.name,
  [fieldName]: this.data
});
</code>```

In the old days we would have to create object separately and assign variable keys in separate step using bracket notation:

```<code>let params = {}
params[code] = this.code
params[name] = this.name
params[fieldName] = this.data

let param = JSON.strigify(params)
</code>```

Title: Angular 4 params with json stringify

Body:
I have to stringify some parameter to put it in a http patch request my method is something like this

let param = JSON.stringify({
code : this.code,
name : this.name,
fieldName: this.data
});

In that case I have a param like this:

code:3,name:'asdf',fieldName: 'col'

But I want the value of fieldName ond not the word fieldName...
Is there a method to expand or evaluate this parameter name?

Body:
If you want value of code variable to be used as a key name, then you need to use computed object property notation:

let param = JSON.stringify({
  [code]: this.code,
  [name]: this.name,
  [fieldName]: this.data
});

In the old days we would have to create object separately and assign variable keys in separate step using bracket notation:

let params = {}
params[code] = this.code
params[name] = this.name
params[fieldName] = this.data

let param = JSON.strigify(params)


问:
laravel 5.4 how to write select from multi table query
How am using laravel 5.4,

to write sql query to get data from multiple tables for below query

```<code>select l.party_id,l.container_id,p.party_name from
`tbl_container_lease` l, `tbl_partys` p
where l.`party_id` = p.`id` and l.`user_id` = 5
</code>```

Now am using this

```<code>Containerlease::whereHas('getpartys',function($q){})
->where('user_id','=',$user_id)
->get();
</code>```

but it is getting too confuse to use

is there any better alternative to use this query by using model..

答:
You would have to join the tables to do this.

```<code>Containerlease::join('tbl_partys', 'tbl_partys.id', '=', 'tbl_container_lease.party_id')
    ->where('tbl_container_lease.user_id', 5)
    ->select('tbl_partys.*', 'tbl_container_lease.*');
    ->get();
</code>```

However, an even better way would be to create relations if you are using Eloquent. The documentation for this can be found here: https://laravel.com/docs/5.4/eloquent-relationships

Body:
How am using laravel 5.4,

to write sql query to get data from multiple tables for below query

select l.party_id,l.container_id,p.party_name from
`tbl_container_lease` l, `tbl_partys` p
where l.`party_id` = p.`id` and l.`user_id` = 5

Now am using this

Containerlease::whereHas('getpartys',function($q){})
->where('user_id','=',$user_id)
->get();

but it is getting too confuse to use

is there any better alternative to use this query by using model..

Body:
You would have to join the tables to do this.

Containerlease::join('tbl_partys', 'tbl_partys.id', '=', 'tbl_container_lease.party_id')
    ->where('tbl_container_lease.user_id', 5)
    ->select('tbl_partys.*', 'tbl_container_lease.*');
    ->get();

However, an even better way would be to create relations if you are using Eloquent. The documentation for this can be found here: https://laravel.com/docs/5.4/eloquent-relationships