问:
Popover not hide when hovering over it
Currently i have the following structure

```<code><OverlayTrigger trigger={["hover", "focus", "click"]} placement="bottom" overlay={(
         <Popover className="timeline-popover-container" id="tpc-1">
             <TimelinePopover
                 alert={session}
                 previousAlert={prevSession}
                 nextAlert={nextSession}
                 status={status}
             />
         </Popover>
     )}>
         <div className="myclass">
             <div>{img}</div>
         </div>
     </OverlayTrigger>
</code>```

So, when the popover is triggered and i try to hover over the popover, the popover dissapear.
I want to be able to click inside de popover, do things inside of that and just dissapear when i move the mouse out of it.

答:
I was looking to do the same thing using React Bootstrap except with a tooltip instead of a popover. The answer here gave me a good jumping off point, which I mixed with the Custom Overlay example in the React Bootstrap docs.

I replaced OverlayTrigger with a custom Overlay, which wraps the Tooltip but is outside of the target element, whereas the OverlayTrigger wraps the target element and calls Tooltip through the overlay prop. I added onMouseEnter() and onMouseLeave() to both the tooltip and the target element to toggle the tooltip visibility state so that leaving either one will close the tooltip.

This is a bare-bones version of my implementation:

```<code>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Tooltip, Overlay } from 'react-bootstrap';

const TooltipExample extends Component {
  constructor(props) {
    super(props);

    this.state = {
      showTooltip: false,
    };
  }

  render() {
    let myTooltip = (
      <Tooltip
        onMouseEnter={() => this.setState({ showTaskTooltip: true })}
        onMouseLeave={() => this.setState({ showTaskTooltip: false })}
      >
        I'm a tooltip and I'll stay open when you leave the target element and hover over me!
      </Tooltip>
    );

    return(
      <div>
        <h3
          ref="target"
          onMouseEnter={() => this.setState({ showTooltip: true })}
          onMouseLeave={() => this.setState({ showTooltip: false })}
        >
          Hover over me!
        </h3>

        <Overlay
          show={this.state.showTooltip}
          onHide={() => this.setState({ showTooltip: false })}
          placement="bottom"
          target={() => ReactDOM.findDOMNode(this.refs.target)}
        >
          {myTooltip}
        </Overlay>
      </div>
    );
  }
}

export default TooltipExample;
</code>```

Title: Popover not hide when hovering over it

Body:
Currently i have the following structure

<OverlayTrigger trigger={["hover", "focus", "click"]} placement="bottom" overlay={(
         <Popover className="timeline-popover-container" id="tpc-1">
             <TimelinePopover
                 alert={session}
                 previousAlert={prevSession}
                 nextAlert={nextSession}
                 status={status}
             />
         </Popover>
     )}>

{img}

     </OverlayTrigger>

So, when the popover is triggered and i try to hover over the popover, the popover dissapear.
I want to be able to click inside de popover, do things inside of that and just dissapear when i move the mouse out of it.

Body:
I was looking to do the same thing using React Bootstrap except with a tooltip instead of a popover. The answer here gave me a good jumping off point, which I mixed with the Custom Overlay example in the React Bootstrap docs.

I replaced OverlayTrigger with a custom Overlay, which wraps the Tooltip but is outside of the target element, whereas the OverlayTrigger wraps the target element and calls Tooltip through the overlay prop. I added onMouseEnter() and onMouseLeave() to both the tooltip and the target element to toggle the tooltip visibility state so that leaving either one will close the tooltip.

This is a bare-bones version of my implementation:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Tooltip, Overlay } from 'react-bootstrap';

const TooltipExample extends Component {
  constructor(props) {
    super(props);

    this.state = {
      showTooltip: false,
    };
  }

  render() {
    let myTooltip = (
      <Tooltip
        onMouseEnter={() => this.setState({ showTaskTooltip: true })}
        onMouseLeave={() => this.setState({ showTaskTooltip: false })}
      >
        I'm a tooltip and I'll stay open when you leave the target element and hover over me!
      </Tooltip>
    );

    return(
      <div>
        <h3
          ref="target"
          onMouseEnter={() => this.setState({ showTooltip: true })}
          onMouseLeave={() => this.setState({ showTooltip: false })}
        >
          Hover over me!
        </h3>

        <Overlay
          show={this.state.showTooltip}
          onHide={() => this.setState({ showTooltip: false })}
          placement="bottom"
          target={() => ReactDOM.findDOMNode(this.refs.target)}
        >
          {myTooltip}
        </Overlay>
      </div>
    );
  }
}

export default TooltipExample;


来源: stackexchange

问:
Most efficient way to find the index of the only '1' bit in a char variable (in C)
This is an interview question:

You are given a char variable named ch, when you know that it represents a number that in its binary form, only one of its eight bits will be equal to '1'. I.E. , the only possible values for ch are: 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80.

Given the variable ch, I need to write the most efficient code to get the index of that '1' bit. For example: if ch == 0x1 -> result is 0. if ch == 0x4 -> result is 2.

The obvious way is to use switch-case, but I need something more efficient.

Is there any bit manipulation you can do here for efficient implementation?

答:
Number of code lines efficient could be a linear search through the bits.

```<code>short bit=0;
const char one=1;
while(!((ch >> bit) & one)) ++bit;
</code>```

Of course error checking is probably a good idea so you could also add a check to make sure you are still in a valid bit.

```<code>short bit=0;
const char one=1;
while(++bit < 8 && !((ch >> bit) & one)) {}
</code>```

It definitely isn't as computationally efficient, and it would fail to detect when more than one bit was set so the switch case is still probably the way to go for correctness.

This guy has fewer jumps in the assembly than a switch case does so maybe it is more efficient in computing the bit.

```<code>short bit=
    ch&0x2?1:
    (ch&0x4?2:
    (ch&0x8?3:
    (ch&0x10?4:
    (ch&0x20?5:
    (ch&0x40?6:
    (ch&0x80?7:8))))));
</code>```

You could skip checking the last bit too and assume if nothing else matches the its the 7th bit is set which could save one comparison.

```<code>short bit=
    ch&0x2?1:
    (ch&0x4?2:
    (ch&0x8?3:
    (ch&0x10?4:
    (ch&0x20?5:
    (ch&0x40?6:7)))));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Number of code lines efficient could be a linear search through the bits.

short bit=0;
const char one=1;
while(!((ch >> bit) & one)) ++bit;

Of course error checking is probably a good idea so you could also add a check to make sure you are still in a valid bit.

short bit=0;
const char one=1;
while(++bit < 8 && !((ch >> bit) & one)) {}

It definitely isn't as computationally efficient, and it would fail to detect when more than one bit was set so the switch case is still probably the way to go for correctness.

This guy has fewer jumps in the assembly than a switch case does so maybe it is more efficient in computing the bit.

short bit=
    ch&0x2?1:
    (ch&0x4?2:
    (ch&0x8?3:
    (ch&0x10?4:
    (ch&0x20?5:
    (ch&0x40?6:
    (ch&0x80?7:8))))));

You could skip checking the last bit too and assume if nothing else matches the its the 7th bit is set which could save one comparison.

short bit=
    ch&0x2?1:
    (ch&0x4?2:
    (ch&0x8?3:
    (ch&0x10?4:
    (ch&0x20?5:
    (ch&0x40?6:7)))));


问:
Laravel action is not authorized
I'm trying to delete a post that belongs to the user who made it, however i get this error(this was in the network log by the way)

"/Applications/MAMP/htdocs/eli42/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php"
  line : 201 message : "This action is unauthorized." trace : [{,…},…]

I'm utilizing laravel 5.5 policy not sure if im doing this right, i registered it in my AuthServiceProvider within $protected policies

Post::class => PostPolicy::class,

Route

Route::delete('auth/post/{id}', 'PostController@destroy');

PostPolicy.php

```<code><?php

namespace App\Policies;

use App\User;
use App\Post;

use Illuminate\Auth\Access\HandlesAuthorization;

class PostPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view the post.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function view(User $user, Post $post)
    {
        //
    }

    /**
     * Determine whether the user can create posts.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function create(User $user)
    {
        //
    }

    /**
     * Determine whether the user can update the post.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function update(User $user, Post $post)
    {
        //
    }

    /**
     * Determine whether the user can delete the post.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function delete(User $user, Post $post)
    {
        //

        return $user->id === $post->user_id;

    }
</code>```

PostController.php (there is more code to this file but i wanted to highlight the delete function)

```<code><?php

namespace App\Http\Controllers;

use App\Post;
use App\User;
use App\Policies\TaskPolicy;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

class PostController extends Controller
{

    public function destroy($id, Post $post)
    {
        $mypost = $this->authorize('delete',$post);

        if($mypost){
             Post::destroy($id);

        }

    }
}
</code>```

Main.js to delete post

```<code>$scope.deletePost = function(post){
    var index = $scope.myposts.indexOf(post);

    if(index != -1){
        $scope.myposts.splice(index, 1);
    }

    $http.delete('auth/post/' + post.id);

};
</code>```

html

```<code>   <button ng-click="deletePost(post)">x</button>
</code>```

before

after

答:
How about that... does that work?</p>

```<code>public function destroy($id)
    {
        $post = Post::first($id);
        $user = auth()->user();
        print_r($post);
        print_r($user);
        $mypost = $user->can('delete', $post);

        if($mypost){
             Post::destroy($id);
        }

    }
</code>```

Title: Laravel action is not authorized

Body:
I'm trying to delete a post that belongs to the user who made it, however i get this error(this was in the network log by the way)

"/Applications/MAMP/htdocs/eli42/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php"
  line : 201 message : "This action is unauthorized." trace : [{,…},…]

I'm utilizing laravel 5.5 policy not sure if im doing this right, i registered it in my AuthServiceProvider within $protected policies

Post::class => PostPolicy::class,

Route

Route::delete('auth/post/{id}', 'PostController@destroy');

PostPolicy.php

<?php

namespace App\Policies;

use App\User;
use App\Post;

use Illuminate\Auth\Access\HandlesAuthorization;

class PostPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view the post.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function view(User $user, Post $post)
    {
        //
    }

    /**
     * Determine whether the user can create posts.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function create(User $user)
    {
        //
    }

    /**
     * Determine whether the user can update the post.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function update(User $user, Post $post)
    {
        //
    }

    /**
     * Determine whether the user can delete the post.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function delete(User $user, Post $post)
    {
        //

        return $user->id === $post->user_id;

    }

PostController.php (there is more code to this file but i wanted to highlight the delete function)

<?php

namespace App\Http\Controllers;

use App\Post;
use App\User;
use App\Policies\TaskPolicy;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

class PostController extends Controller
{

    public function destroy($id, Post $post)
    {
        $mypost = $this->authorize('delete',$post);

        if($mypost){
             Post::destroy($id);

        }

    }
}

Main.js to delete post

$scope.deletePost = function(post){
    var index = $scope.myposts.indexOf(post);

    if(index != -1){
        $scope.myposts.splice(index, 1);
    }

    $http.delete('auth/post/' + post.id);

};

html

   <button ng-click="deletePost(post)">x</button>

before

after

Body:
How about that... does that work?

public function destroy($id)
    {
        $post = Post::first($id);
        $user = auth()->user();
        print_r($post);
        print_r($user);
        $mypost = $user->can('delete', $post);

        if($mypost){
             Post::destroy($id);
        }

    }


问:
Issues Opening Window WPF
I'm using VB.net and WPF 4.

I cannot seem to open a new window in WPF consistantly. It will work one time, and then the next time I execute the same script, it throws the following exception:

XAMLParseException occured
  'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' Line number '4' and line position '208'.
  {Cannot evaluate expression because the code of the current method is optimized.}

Here is the script:

```<code>Dim Window As Window = New GAME_WINDOW
Window.Show()
</code>```

Yes, "GAME_WINDOW" is a legitimate WPF window.

答: The error indicates that there is something wrong with the XAML associated with GAME_WINDOW. i.e. GAME_WINDOW.xaml on line 4 . Probably your TypeConverter on that line threw an exception. </p>

ContentLicense: CC BY-SA 2.5

Title: Issues Opening Window WPF

Body:
I'm using VB.net and WPF 4.

I cannot seem to open a new window in WPF consistantly. It will work one time, and then the next time I execute the same script, it throws the following exception:

XAMLParseException occured
  'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' Line number '4' and line position '208'.
  {Cannot evaluate expression because the code of the current method is optimized.}

Here is the script:

Dim Window As Window = New GAME_WINDOW
Window.Show()

Yes, "GAME_WINDOW" is a legitimate WPF window.


问:
tensorflow error - you must feed a value for placeholder tensor 'in'
I'm trying to implement queues for my tensorflow prediction but get the following error -

you must feed a value for placeholder tensor 'in' with dtype float and shape [1024,1024,3]

The program works fine if I use the feed_dict, Trying to replace feed_dict with queues.

The program basically takes a list of positions and passes the image np array to the input tensor.

```<code>for each in positions:
    y,x = each
    images = img[y:y+1024,x:x+1024,:]
    a = images.astype('float32')

q = tf.FIFOQueue(capacity=200,dtypes=dtypes)
enqueue_op = q.enqueue(a)
qr = tf.train.QueueRunner(q, [enqueue_op] * 1)
tf.train.add_queue_runner(qr)
data = q.dequeue()
graph=load_graph('/home/graph/frozen_graph.pb')

with tf.Session(graph=graph,config=tf.ConfigProto(log_device_placement=True)) as sess:
    p_boxes = graph.get_tensor_by_name("cat:0")
    p_confs = graph.get_tensor_by_name("sha:0")
    y = [p_confs, p_boxes]
    x = graph.get_tensor_by_name("in:0")
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord,sess=sess)
    confs, boxes = sess.run(y)
    coord.request_stop()
    coord.join(threads)
</code>```

How can I make sure the input data that I populated to the queue is recognized while running the graph in the session.

In my original run I call the

confs, boxes = sess.run([p_confs, p_boxes], feed_dict=feed_dict_testing)

答:
I'd suggest not using queues for this problem, and switching to the new tf.data API. In particular tf.data.Dataset.from_generator() makes it easier to feed in data from a Python function. You can rewrite your code to be much simpler, as follows:

```<code>def generator():
  for y, x in positions:
    images = img[y:y+1024,x:x+1024,:]
    yield images.astype('float32')

dataset = tf.data.Dataset.from_generator(
    generator, tf.float32, [1024, 1024, img.shape[3]])
# Add any extra transformations in here, like `dataset.batch()` or
# `dataset.repeat()`.
# ...
iterator = dataset.make_one_shot_iterator()
data = iterator.get_next()
</code>```

Note that in your program, there's no connection between the data tensor and the graph you loaded in load_graph() (at least, assuming that load_graph() doesn't grab data from the global state!). You will probably need to use tf.import_graph_def() and the input_map argument to associate data with one of the tensors in your frozen graph (possibly "in:0"?) to complete the task.

Body:
I'm trying to implement queues for my tensorflow prediction but get the following error -

you must feed a value for placeholder tensor 'in' with dtype float and shape [1024,1024,3]

The program works fine if I use the feed_dict, Trying to replace feed_dict with queues.

The program basically takes a list of positions and passes the image np array to the input tensor.

for each in positions:
    y,x = each
    images = img[y:y+1024,x:x+1024,:]
    a = images.astype('float32')

q = tf.FIFOQueue(capacity=200,dtypes=dtypes)
enqueue_op = q.enqueue(a)
qr = tf.train.QueueRunner(q, [enqueue_op] * 1)
tf.train.add_queue_runner(qr)
data = q.dequeue()
graph=load_graph('/home/graph/frozen_graph.pb')

with tf.Session(graph=graph,config=tf.ConfigProto(log_device_placement=True)) as sess:
    p_boxes = graph.get_tensor_by_name("cat:0")
    p_confs = graph.get_tensor_by_name("sha:0")
    y = [p_confs, p_boxes]
    x = graph.get_tensor_by_name("in:0")
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord,sess=sess)
    confs, boxes = sess.run(y)
    coord.request_stop()
    coord.join(threads)

How can I make sure the input data that I populated to the queue is recognized while running the graph in the session.

In my original run I call the

confs, boxes = sess.run([p_confs, p_boxes], feed_dict=feed_dict_testing)

Body:
I'd suggest not using queues for this problem, and switching to the new tf.data API. In particular tf.data.Dataset.from_generator() makes it easier to feed in data from a Python function. You can rewrite your code to be much simpler, as follows:

def generator():
  for y, x in positions:
    images = img[y:y+1024,x:x+1024,:]
    yield images.astype('float32')

dataset = tf.data.Dataset.from_generator(
    generator, tf.float32, [1024, 1024, img.shape[3]])
# Add any extra transformations in here, like `dataset.batch()` or
# `dataset.repeat()`.
# ...
iterator = dataset.make_one_shot_iterator()
data = iterator.get_next()

Note that in your program, there's no connection between the data tensor and the graph you loaded in load_graph() (at least, assuming that load_graph() doesn't grab data from the global state!). You will probably need to use tf.import_graph_def() and the input_map argument to associate data with one of the tensors in your frozen graph (possibly "in:0"?) to complete the task.


问:
How to break caching on exist-db of included XSLs in Transform
I have a large set of XSLs that we recently went through and implemented a shared XSL template with common bits. We included an xsl:include in all the main XSLs now to pull these in. We had no issues at first until we started to make changes to the shared XSL.

For information, the whole system is web based, calling queries to dynamically format documents in the database given different XSLs through XSL FO and RenderX.

The main transform is:

```<code>let $fo := util:expand(transform:transform($articles, doc("/db/Customer/data/edit/xsl/Custbatch.xsl"), $parameters))
</code>```

That XSL (Custbatch.xsl) has:

```<code><xsl:include href="Custshared.v1.xsl"/>
</code>```

If we make an edit to "Custshared.v1.xsl" is not reflected in the result because it is obvious that "Custshared.v1.xsl" is being cached and used. We know this because as you can see the name now includes "v1". If we make a change and change all the references say from v1 to v2, it all works. But this seems a bit ridiculous as that means we have to change the 18 XSLs that include this XSL or do something silly like restart the database.

So, what am I missing in the setup or controller.xql (which has the following on all not matched paths), to get things not to cache. I assume that is all internal so this setting likely does not matter. Is there some other setting in the config that does?

```<code><dispatch xmlns="http://exist.sourceforge.net/NS/exist">
    <cache-control cache="no"/>
</dispatch>
</code>```

In reading the document here: http://exist-db.org/exist/apps/doc/xsl-transform.xml, it states:

"The stylesheet will be compiled into a template using the standard Java APIs (javax.xml.transform). The template is shared between all instances of the function and will only be reloaded if modified since its last invocation."

However, if I change an included XSL, it is not being used.

Update #1

I even went as far as creating a query that returns the XSL that is included, then I use:

```<code><xsl:include href="http://localhost/get-include-xsl.xq"/>
</code>```

This does work as formatting is not broken, but changing the underlying XSL yields the same result. So even that Xquery result is cached.

Update #2

And yes, through some simple test all is proven.
If I make any change to the root template (like add a meaningless space) and run, it does include the changes made in the include. If I only change the included XSL, no changes happen.

So lacking anything else, we could always write a Xquery that basically touches all the main templates after a change is made to the include template. Seems so wrong as a workaround.

Update #3

So the workaround we are currently using is that we have an unused "variable" in the XSL (version) and when we update the shared template, we execute that query which basically updates the value in that variable. At least it's only one XQuery and maybe we should attach to a trigger.

答: There is a setting in $exist-db-root$/conf.xml for the XSL transformer where you can turn off caching: <transformer class="net.sf.saxon.TransformerFactoryImpl" caching="no"> (The default is 'yes')

Body:
I have a large set of XSLs that we recently went through and implemented a shared XSL template with common bits. We included an xsl:include in all the main XSLs now to pull these in. We had no issues at first until we started to make changes to the shared XSL.

For information, the whole system is web based, calling queries to dynamically format documents in the database given different XSLs through XSL FO and RenderX.

The main transform is:

let $fo := util:expand(transform:transform($articles, doc("/db/Customer/data/edit/xsl/Custbatch.xsl"), $parameters))

That XSL (Custbatch.xsl) has:

<xsl:include href="Custshared.v1.xsl"/>

If we make an edit to "Custshared.v1.xsl" is not reflected in the result because it is obvious that "Custshared.v1.xsl" is being cached and used. We know this because as you can see the name now includes "v1". If we make a change and change all the references say from v1 to v2, it all works. But this seems a bit ridiculous as that means we have to change the 18 XSLs that include this XSL or do something silly like restart the database.

So, what am I missing in the setup or controller.xql (which has the following on all not matched paths), to get things not to cache. I assume that is all internal so this setting likely does not matter. Is there some other setting in the config that does?

<dispatch xmlns="http://exist.sourceforge.net/NS/exist">
    <cache-control cache="no"/>
</dispatch>

In reading the document here: http://exist-db.org/exist/apps/doc/xsl-transform.xml, it states:

"The stylesheet will be compiled into a template using the standard Java APIs (javax.xml.transform). The template is shared between all instances of the function and will only be reloaded if modified since its last invocation."

However, if I change an included XSL, it is not being used.

Update #1

I even went as far as creating a query that returns the XSL that is included, then I use:

<xsl:include href="http://localhost/get-include-xsl.xq"/>

This does work as formatting is not broken, but changing the underlying XSL yields the same result. So even that Xquery result is cached.

Update #2

And yes, through some simple test all is proven.
If I make any change to the root template (like add a meaningless space) and run, it does include the changes made in the include. If I only change the included XSL, no changes happen.

So lacking anything else, we could always write a Xquery that basically touches all the main templates after a change is made to the include template. Seems so wrong as a workaround.

Update #3

So the workaround we are currently using is that we have an unused "variable" in the XSL (version) and when we update the shared template, we execute that query which basically updates the value in that variable. At least it's only one XQuery and maybe we should attach to a trigger.


问:
ES6 curly braces usage when extracting from an object and assigning to another object
I would like to use curly braces to replace this code:

```<code>let rUsers = children.map((user) => {
    let rUser= {};
    rUser.firstName = user.firstName;
    rUser.lastName = user.lastName;
    rUser.relation = user.patron.relation;
    return rUser;
 });
</code>```

This is what I have:

```<code>let rUsers = children.map((user) => {
    let rUser = {};
    ({
        firstName: rUser.firstName,
        lastName: rUser.lastName,
        patron.relation: rUser.relation, // I get an error here
    } = user);
    return rUser;
}
</code>```

Except for patron.relation, the rest of the extraction works.

Questions:

How should I extract value of user.patron.relation?

Is there a more succint way of writing the above?

Thanks!

答:
I'm seeing a few things wrong with your code.

patron.relation -> patron isn't defined, and can't be used as a key.

In the second example, rUser is used - I think you just want user.

My understanding of what you're trying to do essentially create a clone? If so, you should be able to do something like this.

```<code>let rUsers = children.map(user => {
    firstName: user.firstName,
    lastName: user.lastName,
    relation: user.relation
});
</code>```

Alternatively, it could be simpler to use Object.assign()

```<code>let rUsers = children.map(user => Object.assign({}, user));
</code>```

Body:
I would like to use curly braces to replace this code:

let rUsers = children.map((user) => {
    let rUser= {};
    rUser.firstName = user.firstName;
    rUser.lastName = user.lastName;
    rUser.relation = user.patron.relation;
    return rUser;
 });

This is what I have:

let rUsers = children.map((user) => {
    let rUser = {};
    ({
        firstName: rUser.firstName,
        lastName: rUser.lastName,
        patron.relation: rUser.relation, // I get an error here
    } = user);
    return rUser;
}

Except for patron.relation, the rest of the extraction works.

Questions:

How should I extract value of user.patron.relation?

Is there a more succint way of writing the above?

Thanks!

Body:
I'm seeing a few things wrong with your code.

patron.relation -> patron isn't defined, and can't be used as a key.

In the second example, rUser is used - I think you just want user.

My understanding of what you're trying to do essentially create a clone? If so, you should be able to do something like this.

let rUsers = children.map(user => {
    firstName: user.firstName,
    lastName: user.lastName,
    relation: user.relation
});

Alternatively, it could be simpler to use Object.assign()

let rUsers = children.map(user => Object.assign({}, user));


问:
Can boolean variables be used to generate random numbers?
I was playing around with bool variables. I am aware that boolean is used to represent a true (any other number besides 0) or false (the number 0). I realized that the variables create random integer numbers. I was wondering if one can one use boolean variables to generate random numbers? Can someone please elaborate on this behaviour caused by the keyword boolean?

My code is as follows:

```<code>  #include<stdio.h>
  #include<stdbool.h>

  int main()
 {
  bool a,b,c,d,e,f,g,h,i,j,k;

   printf("%d\n",a);
   printf("%d\n",b);
   printf("%d\n",c);
   printf("%d\n",d);
   printf("%d\n",e);
   printf("%d\n",f);
   printf("%d\n",g);
   printf("%d\n",h);
   printf("%d\n",i);
   printf("%d\n",j);
   printf("%d\n",k);
 }
</code>```

答: This is not behaviour specific to a bool. This is caused because you are using an uninitialized variable. This is not only not random, it is not safe. This is undefined behaviour, you should avoid it at all costs.

Body:
I was playing around with bool variables. I am aware that boolean is used to represent a true (any other number besides 0) or false (the number 0). I realized that the variables create random integer numbers. I was wondering if one can one use boolean variables to generate random numbers? Can someone please elaborate on this behaviour caused by the keyword boolean?

My code is as follows:

  #include<stdio.h>
  #include<stdbool.h>

  int main()
 {
  bool a,b,c,d,e,f,g,h,i,j,k;

   printf("%d\n",a);
   printf("%d\n",b);
   printf("%d\n",c);
   printf("%d\n",d);
   printf("%d\n",e);
   printf("%d\n",f);
   printf("%d\n",g);
   printf("%d\n",h);
   printf("%d\n",i);
   printf("%d\n",j);
   printf("%d\n",k);
 }


问:
How to create and use custom shape, i.e Constant as a drawable shape for GradientDrawable in Android?
GradientDrawable Class in Android allows with the constants(Shapes) like Oval, Rectangle etc. Is there any way to add few more shapes like circle or triangle or any other shape so that we can make its look and feel more attractive.
Also suggest if there is any other Class to be used and the way it is used.

Thanks in advance.

答:
You can use this :       </p>

```<code> final GradientDrawable drawable = (GradientDrawable) ResourcesCompat.getDrawable(getResources(), R.drawable.rect_shape, null);
</code>```

Body:
You can use this :

 final GradientDrawable drawable = (GradientDrawable) ResourcesCompat.getDrawable(getResources(), R.drawable.rect_shape, null);


问:
python3/contextlib: Converting @contextlib.contextmanager to acquire/release?
I'm using some 3rd-party code which enables locking via routines that are decorated with @contextlib.contextmanager. I'm also using large python3 code base in which we can plug in different locking software, as long as I am able to implement acquire and release methods.

I'm trying to use the 3rd-party code (without knowing how it's written) within this software structure.

To clarify what I'm looking for, suppose that one of the 3rd-party lock routines is written as a standard @contextlib.contextmanager generator, like this:

```<code>@contextlib.contextmanager
def lock(arg0, arg1):
    try:
        # This section of code corresponds to `acquire`.
        # Acquire a lock called 'lock', and then ...
        yield lock
    finally:
        # This section of code coresponds to `release`.
        # Do cleanup.
</code>```

It would normally be used like this ...

```<code>with third.party.lock(arg0, arg1):
    # Do stuff in this critical section
</code>```

But as I mentioned above, I want to write a class that has an acquire method and a release method which make use of third.party.lock, and I'd like to do it via the existing third.party.lock module, without rewriting it.

In other words, I want to write a class which looks like this ...

```<code>class LockWrapper(object):

    def __init__(self):
        # initialization

    def acquire(self):
        # Use third.party.lock to obtain a lock.
        # ??? ??? ???

    def release(self):
        # I don't know what to do here. There is no yield
        # in the `finally` section of a normal
        # @contextlib.contextmanager decorated method/
        # ??? ??? ???
</code>```

As I stated in the comments of my sample code, I don't see how to make acquire and release do anything meaningful.

It looks like I would have to steal code from the original third.party.lock module in order to accomplish this, but I'm hoping that I'm overlooking a way to do this without having to know anything about this 3rd-party code.

Am I out of luck?

Thank you very much.

答:
OK, I figured it out. My answer is based on some of the code here: https://gist.github.com/icio/c0d3f7efd415071f725b

The key is this enter_context helper function, which digs into the structure of the context manager. It's similar to a function by the same name at that site ...

```<code>def enter_context(func, *args, **kwargs):
    def _acquire():
        with func(*args, **kwargs) as f:
            yield f
    acquire_gen = _acquire()
    def release_func():
        try:
            next(acquire_gen)
        except StopIteration:
            pass
    return acquire_gen, release_func
</code>```

The following class implements acquire and release for any contextmanager function which is passed to the constructor. I encapsulate enter_context within this class ...

```<code>class ContextWrapper(object):
    @staticmethod
    def enter_context(func, *args, **kwargs):
        def _acquire():
            with func(*args, **kwargs) as f:
                yield f
        acquire_gen = _acquire()
        def release_func():
            try:
                next(acquire_gen)
            except StopIteration:
                pass
        return acquire_gen, release_func
    def __init__(self, func, *args, **kwargs):
        self._acq, self._rel = self.__class__.enter_context(func, *args, **kwargs)
    def acquire(self):
        next(self._acq)
        return True
    def release(self):
        self._rel()
    # Traditional Dijkstra names.
    P = acquire
    V = release
</code>```

Then, I can create my wrapper around third.party.lock as follows ...

```<code>mylocker = ContextWrapper(third.party.lock, arg0, arg1)
</code>```

... and I can call acquire and release as follows ...

```<code>mylocker.acquire()
# or mylocker.P()
mylocker.release()
# or mylocker.V()
</code>```

Here's another example of how to use this class ...

```<code>class ThirdPartyLockClass(ContextWrapper):
    def __init__(self, arg0, arg1):
        # do any initialization
        super().__init__(third.party.lock, arg0, arg1)
    # Implementing the following methods is optional.
    # This is only needed if this class intends to do more
    # than the wrapped class during `acquire` or `release`,
    # such as logging, etc.
    def acquire(self):
        # do whatever
        rc = super().acquire()
        # maybe to other stuff
        return rc
    def release(self):
        # do whatever
        super().release()
        # maybe do other stuff
    P = acquire
    V = release

mylocker = ThirdPartyLockClass(arg0, arg1)
mylocker.acquire()
# or mylocker.P()
mylocker.release()
# or mylocker.V()
</code>```

... or I can even do the following in the simple case where no extra functionality is added to the third party lock class ...

```<code>class GenericLocker(ContextWrapper):
    def __init__(self, func, *args, **kwargs):
        super().__init__(func, *args, **kwargs)

mylocker = GenericLocker(third.party.lock, arg0, arg1)
mylocker.acquire()
# or mylocker.P()
mylocker.release()
# or mylocker.V()
</code>```

Body:
I'm using some 3rd-party code which enables locking via routines that are decorated with @contextlib.contextmanager. I'm also using large python3 code base in which we can plug in different locking software, as long as I am able to implement acquire and release methods.

I'm trying to use the 3rd-party code (without knowing how it's written) within this software structure.

To clarify what I'm looking for, suppose that one of the 3rd-party lock routines is written as a standard @contextlib.contextmanager generator, like this:

@contextlib.contextmanager
def lock(arg0, arg1):
    try:
        # This section of code corresponds to `acquire`.
        # Acquire a lock called 'lock', and then ...
        yield lock
    finally:
        # This section of code coresponds to `release`.
        # Do cleanup.

It would normally be used like this ...

with third.party.lock(arg0, arg1):
    # Do stuff in this critical section

But as I mentioned above, I want to write a class that has an acquire method and a release method which make use of third.party.lock, and I'd like to do it via the existing third.party.lock module, without rewriting it.

In other words, I want to write a class which looks like this ...

class LockWrapper(object):

    def __init__(self):
        # initialization

    def acquire(self):
        # Use third.party.lock to obtain a lock.
        # ??? ??? ???

    def release(self):
        # I don't know what to do here. There is no yield
        # in the `finally` section of a normal
        # @contextlib.contextmanager decorated method/
        # ??? ??? ???

As I stated in the comments of my sample code, I don't see how to make acquire and release do anything meaningful.

It looks like I would have to steal code from the original third.party.lock module in order to accomplish this, but I'm hoping that I'm overlooking a way to do this without having to know anything about this 3rd-party code.

Am I out of luck?

Thank you very much.

Body:
OK, I figured it out. My answer is based on some of the code here: https://gist.github.com/icio/c0d3f7efd415071f725b

The key is this enter_context helper function, which digs into the structure of the context manager. It's similar to a function by the same name at that site ...

def enter_context(func, *args, **kwargs):
    def _acquire():
        with func(*args, **kwargs) as f:
            yield f
    acquire_gen = _acquire()
    def release_func():
        try:
            next(acquire_gen)
        except StopIteration:
            pass
    return acquire_gen, release_func

The following class implements acquire and release for any contextmanager function which is passed to the constructor. I encapsulate enter_context within this class ...

class ContextWrapper(object):
    @staticmethod
    def enter_context(func, *args, **kwargs):
        def _acquire():
            with func(*args, **kwargs) as f:
                yield f
        acquire_gen = _acquire()
        def release_func():
            try:
                next(acquire_gen)
            except StopIteration:
                pass
        return acquire_gen, release_func
    def __init__(self, func, *args, **kwargs):
        self._acq, self._rel = self.__class__.enter_context(func, *args, **kwargs)
    def acquire(self):
        next(self._acq)
        return True
    def release(self):
        self._rel()
    # Traditional Dijkstra names.
    P = acquire
    V = release

Then, I can create my wrapper around third.party.lock as follows ...

mylocker = ContextWrapper(third.party.lock, arg0, arg1)

... and I can call acquire and release as follows ...

mylocker.acquire()
# or mylocker.P()
mylocker.release()
# or mylocker.V()

Here's another example of how to use this class ...

class ThirdPartyLockClass(ContextWrapper):
    def __init__(self, arg0, arg1):
        # do any initialization
        super().__init__(third.party.lock, arg0, arg1)
    # Implementing the following methods is optional.
    # This is only needed if this class intends to do more
    # than the wrapped class during `acquire` or `release`,
    # such as logging, etc.
    def acquire(self):
        # do whatever
        rc = super().acquire()
        # maybe to other stuff
        return rc
    def release(self):
        # do whatever
        super().release()
        # maybe do other stuff
    P = acquire
    V = release

mylocker = ThirdPartyLockClass(arg0, arg1)
mylocker.acquire()
# or mylocker.P()
mylocker.release()
# or mylocker.V()

... or I can even do the following in the simple case where no extra functionality is added to the third party lock class ...

class GenericLocker(ContextWrapper):
    def __init__(self, func, *args, **kwargs):
        super().__init__(func, *args, **kwargs)

mylocker = GenericLocker(third.party.lock, arg0, arg1)
mylocker.acquire()
# or mylocker.P()
mylocker.release()
# or mylocker.V()


问:
How to extract the class name out of List< Func< Int32 > >
How do I get the name out of the list?

e.g

```<code>static void Main()
{
    var methods = new List<Func<int>>();
    methods.Add(() => new ThisCss().useThis(0));

    // Output ThisCss here from methods
    // i.e Console.WriteLine(methods[0].ClassName).. or something like that

}

class ThisCss
{
    public int useThis(int num)
    {
       return 0;
    }
}
</code>```

So just to clarify I want to get the name of the class out of the 0 index of the list of functions. So in this case it would be 'ThisCss'.

答:
What about 'Tuple' if you can change the return type?

```<code>var methods = new List<Tuple<string, Func<int>>>();

methods.Add(new Tuple<string, Func<int>>(nameof(ThisCss), () => new ThisCss().useThis(0)));
methods.Add(new Tuple<string, Func<int>>(nameof(ThisCss2), () => new ThisCss2().useThis(0)));

var className = methods[0].Item1;
</code>```

In C# 7.0

```<code>var methods = new List<(string ClassName, Func<int> Func)>();

methods.Add((nameof(ThisCss), () => new ThisCss().useThis(0)));
methods.Add((nameof(ThisCss2), () => new ThisCss2().useThis(0)));

var className = methods[0].ClassName;
</code>```

Body:
How do I get the name out of the list?

e.g

static void Main()
{
    var methods = new List<Func<int>>();
    methods.Add(() => new ThisCss().useThis(0));

    // Output ThisCss here from methods
    // i.e Console.WriteLine(methods[0].ClassName).. or something like that

}

class ThisCss
{
    public int useThis(int num)
    {
       return 0;
    }
}

So just to clarify I want to get the name of the class out of the 0 index of the list of functions. So in this case it would be 'ThisCss'.

Body:
What about 'Tuple' if you can change the return type?

var methods = new List<Tuple<string, Func<int>>>();

methods.Add(new Tuple<string, Func<int>>(nameof(ThisCss), () => new ThisCss().useThis(0)));
methods.Add(new Tuple<string, Func<int>>(nameof(ThisCss2), () => new ThisCss2().useThis(0)));

var className = methods[0].Item1;

In C# 7.0

var methods = new List<(string ClassName, Func<int> Func)>();

methods.Add((nameof(ThisCss), () => new ThisCss().useThis(0)));
methods.Add((nameof(ThisCss2), () => new ThisCss2().useThis(0)));

var className = methods[0].ClassName;


问:
Laravel 5.5 Log in user using event listener
So, I'm trying to log in a user on Laravel 5.5 using SSO. I'm using a library and it works fine, data come back correctly. However when on Listener I try to Auth::login or any Session data, it's not saved. Sessions works fine from any other point of the app, but not in Listener Events.

```<code><?php

namespace App\Listeners;

use App\User;
use Illuminate\Support\Facades\Auth;

use \Aacotroneo\Saml2\Events\Saml2LoginEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class AuthListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle(Saml2LoginEvent $event)
    {
        $messageId = $event->getSaml2Auth()->getLastMessageId();
        // your own code preventing reuse of a $messageId to stop replay attacks
        $user = $event->getSaml2User();
        $attributes = $user->getAttributes();

        $id = $attributes['id'];
        $laravelUser = User::where('id', $id)->first();

        \Session::push('name', 'test');
        Auth::login($laravelUser, true);

    }
}
</code>```

Now, at the Auth::login($laravelUser, true) the user is logged in correctly, I did check. But as soon as the page refresh sending to the final URL the session is gone.

Any Ideas?

答: I was facing the exact problem in Laravel 5.5. It seems that you are missing the routesMiddleware setting in saml2_settings.php file. The description says you need a group which includes StartSession, so you may want to put 'web' there, which has it included by default, as seen in Kernel.php

Body:
So, I'm trying to log in a user on Laravel 5.5 using SSO. I'm using a library and it works fine, data come back correctly. However when on Listener I try to Auth::login or any Session data, it's not saved. Sessions works fine from any other point of the app, but not in Listener Events.

<?php

namespace App\Listeners;

use App\User;
use Illuminate\Support\Facades\Auth;

use \Aacotroneo\Saml2\Events\Saml2LoginEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class AuthListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle(Saml2LoginEvent $event)
    {
        $messageId = $event->getSaml2Auth()->getLastMessageId();
        // your own code preventing reuse of a $messageId to stop replay attacks
        $user = $event->getSaml2User();
        $attributes = $user->getAttributes();

        $id = $attributes['id'];
        $laravelUser = User::where('id', $id)->first();

        \Session::push('name', 'test');
        Auth::login($laravelUser, true);

    }
}

Now, at the Auth::login($laravelUser, true) the user is logged in correctly, I did check. But as soon as the page refresh sending to the final URL the session is gone.

Any Ideas?


问:
Proj.4 Java - convert coordinates from WGS84 to EPSG4141?
I am using the Proj.4 java library that can be found here
And I am pretty much unsure on how can I implement a code that looks like this in Proj.4JS:

```<code>// include the library
<script src="lib/proj4js-combined.js"></script>  //adjust the path for your server
                                                 //or else use the compressed version
// creating source and destination Proj4js objects
// once initialized, these may be re-used as often as needed
var source = new Proj4js.Proj('EPSG:4326');    //source coordinates will be in Longitude/Latitude, WGS84
var dest = new Proj4js.Proj('EPSG:4141');     //destination coordinates in meters, global spherical mercators projection, see http://spatialreference.org/ref/epsg/3785/

// transforming point coordinates
var p = new Proj4js.Point(-76.0,45.0);   //any object will do as long as it has 'x' and 'y' properties
Proj4js.transform(source, dest, p);      //do the transformation.  x and y are modified in place

//p.x and p.y are now EPSG:3785 in meters
</code>```

I am new to the whole projection subjects and I really want to know what am I doing. I need to convert my coordinate system from WGS84 to EPSG:4141 but Proj.4 Java library is not documented at all and I can't really find out on how to use it.

Is anyone familiar with this?

答:
Unfortunately the library is still not well documented so for those still searching for a solution:

```<code>CRSFactory factory = new CRSFactory();
CoordinateReferenceSystem srcCrs = factory.createFromName("EPSG:4326");
CoordinateReferenceSystem dstCrs = factory.createFromName("EPSG:4141");

BasicCoordinateTransform transform = new BasicCoordinateTransform(srcCrs, dstCrs);

// Note these are x, y so lng, lat
ProjCoordinate srcCoord = new ProjCoordinate(-76.0, 45.0);
ProjCoordinate dstCoord = new ProjCoordinate();

// Writes result into dstCoord
transform.transform(srcCoord, dstCoord);
</code>```

Source code at https://github.com/Proj4J/proj4j if you need to figure anything else out.

Body:
I am using the Proj.4 java library that can be found here
And I am pretty much unsure on how can I implement a code that looks like this in Proj.4JS:

// include the library
  //adjust the path for your server
                                                 //or else use the compressed version
// creating source and destination Proj4js objects
// once initialized, these may be re-used as often as needed
var source = new Proj4js.Proj('EPSG:4326');    //source coordinates will be in Longitude/Latitude, WGS84
var dest = new Proj4js.Proj('EPSG:4141');     //destination coordinates in meters, global spherical mercators projection, see http://spatialreference.org/ref/epsg/3785/

// transforming point coordinates
var p = new Proj4js.Point(-76.0,45.0);   //any object will do as long as it has 'x' and 'y' properties
Proj4js.transform(source, dest, p);      //do the transformation.  x and y are modified in place

//p.x and p.y are now EPSG:3785 in meters

I am new to the whole projection subjects and I really want to know what am I doing. I need to convert my coordinate system from WGS84 to EPSG:4141 but Proj.4 Java library is not documented at all and I can't really find out on how to use it.

Is anyone familiar with this?

Body:
Unfortunately the library is still not well documented so for those still searching for a solution:

CRSFactory factory = new CRSFactory();
CoordinateReferenceSystem srcCrs = factory.createFromName("EPSG:4326");
CoordinateReferenceSystem dstCrs = factory.createFromName("EPSG:4141");

BasicCoordinateTransform transform = new BasicCoordinateTransform(srcCrs, dstCrs);

// Note these are x, y so lng, lat
ProjCoordinate srcCoord = new ProjCoordinate(-76.0, 45.0);
ProjCoordinate dstCoord = new ProjCoordinate();

// Writes result into dstCoord
transform.transform(srcCoord, dstCoord);

Source code at https://github.com/Proj4J/proj4j if you need to figure anything else out.


问:
Hide 'div' after specific amount of time
I have a div, which is generally used for showing some status messsage like "you have selected some xyz thing"

Now, I need to hide it at interval of specific amount of time (say, 60 secs) after page loads.

Code:

```<code> <div id="msg">You have selected 'Time and Money' magazine</div>
</code>```

How can I perform the above mentioned thing?

Thanks

答:
This should do what you need: jQuery Timers</p>

```<code>$(function(){
  $(document).oneTime(60000, function(){
    $('#msg').hide();
  });
});
</code>```

Body:
I have a div, which is generally used for showing some status messsage like "you have selected some xyz thing"

Now, I need to hide it at interval of specific amount of time (say, 60 secs) after page loads.

Code:

You have selected 'Time and Money' magazine

How can I perform the above mentioned thing?

Thanks

Body:
This should do what you need: jQuery Timers

$(function(){
  $(document).oneTime(60000, function(){
    $('#msg').hide();
  });
});


问:
Is there a Linq method to add a single item to an IEnumerable<T>?
I am trying to do something like this:

```<code>image.Layers
</code>```

which returns an IEnumerable<Layer> for all layers except the Parent layer, but in some cases, I just want to do:

```<code>image.Layers.With(image.ParentLayer);
</code>```

because it's only used in a few places compared to the 100s of the usual usage which is satisfied by image.Layers. That's why I don't want to make another property that also returns the Parent layer.

答:
Append and Prepend have now been added to the .NET Standard framework, so you no longer need to write your own. Simply do this:

```<code>image.Layers.Append(image.ParentLayer)
</code>```

See What are the 43 APIs that are in .Net Standard 2.0 but not in .Net Framework 4.6.1? for a great list of new functionality.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to do something like this:

image.Layers

which returns an IEnumerable<Layer> for all layers except the Parent layer, but in some cases, I just want to do:

image.Layers.With(image.ParentLayer);

because it's only used in a few places compared to the 100s of the usual usage which is satisfied by image.Layers. That's why I don't want to make another property that also returns the Parent layer.

Body:
Append and Prepend have now been added to the .NET Standard framework, so you no longer need to write your own. Simply do this:

image.Layers.Append(image.ParentLayer)

See What are the 43 APIs that are in .Net Standard 2.0 but not in .Net Framework 4.6.1? for a great list of new functionality.


问:
Project Euler 1:Find the sum of all the multiples of 3 or 5 below 1000, works for 10 numbers but doesn't work for 1000

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.

So I decided to try and solve some problems on Euler site to improve with programming. While trying to solve the first problem I wrote a quick code to count the sum and it worked for 10 numbers, but for 1000 it shows me the answer: 166833 which is wrong and I can't really find an issue here. If someone could give me a hint to improve my algorythm so it would work.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Multiplies_of_3_and_5
{
  class Program
  {
    static void Main(string[] args)
    {
        int[] array = new int[7000];

        for (int j = 0; j<array.Length ;j++)
        {
            array[j] = j + 1;
        }

        int n = 1;
        int z = 1;
        int numbers = 0;

        for (int i = 0; i<999; i++)
        {
            if (array[i] == 3 * n )
            {
                n++;
                numbers += array[i];
            }

            else if (array[i] == 5 * z)
            {
                z++;
                numbers += array[i];
            }
        }
        Console.WriteLine(string.Join(" ", numbers));
        Console.ReadLine();
      }
   }
}
</code>```

Body:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.

So I decided to try and solve some problems on Euler site to improve with programming. While trying to solve the first problem I wrote a quick code to count the sum and it worked for 10 numbers, but for 1000 it shows me the answer: 166833 which is wrong and I can't really find an issue here. If someone could give me a hint to improve my algorythm so it would work.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Multiplies_of_3_and_5
{
  class Program
  {
    static void Main(string[] args)
    {
        int[] array = new int[7000];

        for (int j = 0; j<array.Length ;j++)
        {
            array[j] = j + 1;
        }

        int n = 1;
        int z = 1;
        int numbers = 0;

        for (int i = 0; i<999; i++)
        {
            if (array[i] == 3 * n )
            {
                n++;
                numbers += array[i];
            }

            else if (array[i] == 5 * z)
            {
                z++;
                numbers += array[i];
            }
        }
        Console.WriteLine(string.Join(" ", numbers));
        Console.ReadLine();
      }
   }
}

Body: Enumerable.Range(1, 999).Sum(x => x % 3 == 0 || x % 5 == 0 ? x : 0);


问:
Idiom for aliasing structs
I understand that C is (mostly) call and assign "by value", and that struct assignment a = b creates a copy of b.

This leads to some verbosity when iterating through an array whose members are struct, and accessing member fields (example below). Is there an idiom for aliasing structs in a loop?

```<code>#include <stdio.h>
#define N_FOOS 2

struct Foo {
  char *bar;
  char *baz;
};

int main() {
  struct Foo foos[N_FOOS] = {
    {"foo", "bar"},
    {"baz", "qux"},
  };

  for (int i = 0; i < N_FOOS; ++i) {
    printf("foos[%d].bar = %s\n", i, foos[i].bar);
    printf("foos[%d].baz = %s\n", i, foos[i].baz);
  }
}
</code>```

In a higher-level language I would have created an alias within for to point to foos[i] and avoid repeated indexing.

Would the idiomatic way be to create a pointer that references foos[i]?

```<code>int main() {
  struct Foo *foo;
  struct Foo foos[N_FOOS] = {
    {"foo", "bar"},
    {"baz", "qux"},
  };

  for (int i = 0; i < N_FOOS; ++i) {
    foo = &foos[i];
    printf("foos[%d].bar = %s\n", i, foos[i].bar);
    printf("foos[%d].baz = %s\n", i, foos[i].baz);
    printf("foo->bar = %s\n", foo->bar);
    printf("foo->baz = %s\n", foo->baz);
  }
}
</code>```

The downside is having to do manual deallocation, but I guess that's just an inescapable part of the language.

EDIT: fixed code due to @dbush's feedback

答:
What you have will work fine.  It can be especially useful if you have a structure several layers deep to abbreviate what you're referring to and make your code more clear.

The one problem you have is a memory leak.  You dynamically assign memory to foo, but then you overwrite the address of that allocated memory with the address of another variable:

```<code>foo = &foos[i];
</code>```

Now the allocated memory is lost.

Because you're using the pointer to point to an existing variable, you don't need dynamic allocation at all.  Get rid of malloc and free.

Title: Idiom for aliasing structs

Body:
I understand that C is (mostly) call and assign "by value", and that struct assignment a = b creates a copy of b.

This leads to some verbosity when iterating through an array whose members are struct, and accessing member fields (example below). Is there an idiom for aliasing structs in a loop?

#include <stdio.h>
#define N_FOOS 2

struct Foo {
  char *bar;
  char *baz;
};

int main() {
  struct Foo foos[N_FOOS] = {
    {"foo", "bar"},
    {"baz", "qux"},
  };

  for (int i = 0; i < N_FOOS; ++i) {
    printf("foos[%d].bar = %s\n", i, foos[i].bar);
    printf("foos[%d].baz = %s\n", i, foos[i].baz);
  }
}

In a higher-level language I would have created an alias within for to point to foos[i] and avoid repeated indexing.

Would the idiomatic way be to create a pointer that references foos[i]?

int main() {
  struct Foo *foo;
  struct Foo foos[N_FOOS] = {
    {"foo", "bar"},
    {"baz", "qux"},
  };

  for (int i = 0; i < N_FOOS; ++i) {
    foo = &foos[i];
    printf("foos[%d].bar = %s\n", i, foos[i].bar);
    printf("foos[%d].baz = %s\n", i, foos[i].baz);
    printf("foo->bar = %s\n", foo->bar);
    printf("foo->baz = %s\n", foo->baz);
  }
}

The downside is having to do manual deallocation, but I guess that's just an inescapable part of the language.

EDIT: fixed code due to @dbush's feedback

Body:
What you have will work fine.  It can be especially useful if you have a structure several layers deep to abbreviate what you're referring to and make your code more clear.

The one problem you have is a memory leak.  You dynamically assign memory to foo, but then you overwrite the address of that allocated memory with the address of another variable:

foo = &foos[i];

Now the allocated memory is lost.

Because you're using the pointer to point to an existing variable, you don't need dynamic allocation at all.  Get rid of malloc and free.


答: Boolean is not randomly defined. These variables take false as  default value. In compiler. The default value is consistent rather than random 0 or 1 from time to time.

Title: Can boolean variables be used to generate random numbers?

Body:
I was playing around with bool variables. I am aware that boolean is used to represent a true (any other number besides 0) or false (the number 0). I realized that the variables create random integer numbers. I was wondering if one can one use boolean variables to generate random numbers? Can someone please elaborate on this behaviour caused by the keyword boolean?

My code is as follows:

  #include<stdio.h>
  #include<stdbool.h>

  int main()
 {
  bool a,b,c,d,e,f,g,h,i,j,k;

   printf("%d\n",a);
   printf("%d\n",b);
   printf("%d\n",c);
   printf("%d\n",d);
   printf("%d\n",e);
   printf("%d\n",f);
   printf("%d\n",g);
   printf("%d\n",h);
   printf("%d\n",i);
   printf("%d\n",j);
   printf("%d\n",k);
 }


答:
After listening to tips from You I remade my code and it works just fine. But it is surely a pain to do it this way, so I suggest using (%) for that. Anyway I will post my code here as well. Thanks for help again!</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Multiplies_of_3_and_5
{
  class Program
  {

    static void Main(string[] args)
    {

        int[] array = new int[7000];

        for (int j = 0; j < array.Length; j++)
        {
            array[j] = j + 1;
        }

        int n = 1;
        int z = 1;
        int numbers = 0;

        for (int i = 0; i < 999; i++)
        {

            if (array[i] == 3*n && array[i] == 5*z)
            {
                n++;
            }

            if (array[i] == 3 * n)
            {

                n++;
                numbers += array[i];
            }

            if (array[i] == 5 * z)
            {
                z++;
                numbers += array[i];
            }

        }
        Console.WriteLine(string.Join(" ", numbers));
        Console.ReadLine();

    }
  }
}
</code>```

Title: Project Euler 1:Find the sum of all the multiples of 3 or 5 below 1000, works for 10 numbers but doesn't work for 1000

Body:
After listening to tips from You I remade my code and it works just fine. But it is surely a pain to do it this way, so I suggest using (%) for that. Anyway I will post my code here as well. Thanks for help again!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Multiplies_of_3_and_5
{
  class Program
  {

    static void Main(string[] args)
    {

        int[] array = new int[7000];

        for (int j = 0; j < array.Length; j++)
        {
            array[j] = j + 1;
        }

        int n = 1;
        int z = 1;
        int numbers = 0;

        for (int i = 0; i < 999; i++)
        {

            if (array[i] == 3*n && array[i] == 5*z)
            {
                n++;
            }

            if (array[i] == 3 * n)
            {

                n++;
                numbers += array[i];
            }

            if (array[i] == 5 * z)
            {
                z++;
                numbers += array[i];
            }

        }
        Console.WriteLine(string.Join(" ", numbers));
        Console.ReadLine();

    }
  }
}


问:
How can I adjust a photo into a div respecting the div height
I was reading some answered questions in here, but I still have the problem, I can't "re-adjust" an image inside a div, the image doesn't respect the containing height of the div, and also I cant make the part of the image that I want show on it, this is what I mean:

HTML

```<code><nav class="navbar navbar-inverse">
   <div class="container-fluid">
      <div class="navbar-header">
         <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
         <span class="icon-bar"></span>
         <span class="icon-bar"></span>
         <span class="icon-bar"></span>
         </button>
         <a class="navbar-brand" href="#">Logo</a>
      </div>
      <div class="collapse navbar-collapse" id="myNavbar">
         <ul class="nav navbar-nav">
            <li class="active"><a href="#">Home</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Projects</a></li>
            <li><a href="#">Contact</a></li>
         </ul>
         <ul class="nav navbar-nav navbar-right">
            <li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
         </ul>
      </div>
   </div>
</nav>
<section id="about">
   <div class="container-fluid text-center">
      <div class="row content">
         <div class="col-lg-12">
            <h1>Welcome</h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
         </div>
      </div>
   </div>
</section>
<section id="img">
   <div class="container-fluid">
   <div class="row content">
      <div id="imgcont">
         <div id="header">
            <div class="title">
               <h1>Title in image centered</h1>
            </div>
         </div>
      </div>
   </div>
   <div class="row content text-center">
      <h1>More content, same section </h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit.</p>
   </div>
</section>
<section id="howto">
   <div class="container-fluid">
      <div class="row content">
         <div class="col-lg-12">
            <h1>Welcome</h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
         </div>
      </div>
   </div>
</section>
</code>```

CSS:

```<code>body {
    color: white;
}

.navbar {
    margin-bottom: 0;
    border-radius: 0;
  padding-bottom: 0;
}

.row.content {
    min-height: 450px
}

#about {
    background-color: red;
}

#img {
    background-color: gray;
    height 100%;
}

#howto {
    background-color: #003300;
}

#imgcont {
    height: 50%;
}

#header {
    background: url(http://www.qygjxz.com/data/out/162/6155406-mountain-images.jpeg);
    background-size: cover;
    height: 100vh;
    position: relative;
    top: -10px;
    overflow: hidden;
}

.title {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: white;
    text-align: center;
}

.title h1 {
    text-transform: uppercase;
    margin: 0;
    font-size: 3rem;
    white-space: nowrap;
}
</code>```

https://codepen.io/elunap/pen/ZaXKKK

I have 3 sections in which I have different content, on the second section I want to adjust the image to appear like that, without overlapping the image and the top section.

This is my goal:

https://imgur.com/a/OIeKt

Can someone guide me?

答:
Change

```<code>#header {
    height: 100vh;
}
</code>```

To

```<code>#header {
    height: 50%;
}
</code>```

Updated sample: https://codepen.io/anon/pen/bYoRNq

Body:
I was reading some answered questions in here, but I still have the problem, I can't "re-adjust" an image inside a div, the image doesn't respect the containing height of the div, and also I cant make the part of the image that I want show on it, this is what I mean:

HTML

         <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

         </button>
         Logo

Home

About

Projects

Contact

 Login

Welcome

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Title in image centered

More content, same section

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit.

Welcome

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

CSS:

body {
    color: white;
}

.navbar {
    margin-bottom: 0;
    border-radius: 0;
  padding-bottom: 0;
}

.row.content {
    min-height: 450px
}

#about {
    background-color: red;
}

#img {
    background-color: gray;
    height 100%;
}

#howto {
    background-color: #003300;
}

#imgcont {
    height: 50%;
}

#header {
    background: url(http://www.qygjxz.com/data/out/162/6155406-mountain-images.jpeg);
    background-size: cover;
    height: 100vh;
    position: relative;
    top: -10px;
    overflow: hidden;
}

.title {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: white;
    text-align: center;
}

.title h1 {
    text-transform: uppercase;
    margin: 0;
    font-size: 3rem;
    white-space: nowrap;
}

https://codepen.io/elunap/pen/ZaXKKK

I have 3 sections in which I have different content, on the second section I want to adjust the image to appear like that, without overlapping the image and the top section.

This is my goal:

https://imgur.com/a/OIeKt

Can someone guide me?

Body:
Change

#header {
    height: 100vh;
}

To

#header {
    height: 50%;
}

Updated sample: https://codepen.io/anon/pen/bYoRNq


问:
Best method to authenticate that a user is actually a college student using gmail API in iOS?
When I type in a .edu address into gmail.com it automatically takes me the CAS page for that specific university. Does anyone know how I can direct the user to that specific CAS page for the university given that he or she gives me the school that they go to in my Android or iOS application?

I need to authenticate that a student is actually in a university in my app, so this is the method I am thinking to use. Is there any other better way?

答:
I researched a little more and found out a solution to anyone who requires this specific use case:

Set up GIDSignIn instance in your mobile application using this link (For swift but there should be one for Android): https://developers.google.com/identity/sign-in/ios/sign-in?ver=swift

Then on that GIDSignIn instance you can set the correct domain using the hostedDomain property on that GIDSignIn instance you created in step 1.


问:
AssertJ `containsExactly` assertion on list with wildcard
I have a getter returning a List with a wildcard:

```<code>import java.util.List;

public interface Foo {
    List<? extends Bar> getList();
}
</code>```

Where Bar is an other interface.

When I write an assertion with AssertJ like this:

```<code>assertThat(foo.getList()).containsExactly(bar1, bar3);
</code>```

EDIT: my complete usage is to chain a usingElementComparator and to provide a Comparator<Bar> to compare the expected Bar instances.

```<code>Comparator<Bar> comparator = createBarComparator()
assertThat(foo.getList()).usingElementComparator(comparator).containsExactly(bar1, bar3);
</code>```

I get this compilation error:

The method containsExactly(capture#46-of ? extends Bar...) in the type ListAssert is not applicable for the arguments (Bar, Bar)

My first solution is to cast the result:

```<code>assertThat((List<Bar>)foo.getList()).containsExactly(bar1, bar3);
</code>```

Then I get a warning:

Type safety: Unchecked cast from List to List

Warning can be removed with @SuppressWarnings("unchecked"), but still the cast in the middle do not make the assertion really readable.

My second solution is to indicate the value the ELEMENT generic parameter:

```<code>Assertions.<Bar>assertThat(foo.getList()).containsExactly(bar1, bar3);
</code>```

A little better, but also not that nice (no static import possible, the beginning of the line do not facilitate the readability)

I guess I am looking for an other assertThat method for list, where the class type can be specified as second parameter:

```<code>@CheckReturnValue
public static <ELEMENT> ListAssert<ELEMENT> assertThat(List<? extends ELEMENT> actual, Class<ELEMENT> c) {
    return AssertionsForInterfaceTypes.assertThat(actual);
}
</code>```

This way I should be able to write something like this:

```<code>Assertions.assertThat(foo.getList(), Bar.class).containsExactly(bar1, bar3);
</code>```

答:
That used to work with the Oracle JDK 7 compiler but this was actually a bug in the compiler, this has been fixed in Java 8 JDK so having the compilation error is the normal behavior (can't find the bug reference though).

I would be happy to support but I'm not sure this is possible in AssertJ except by removing all generics usage in collections assertions.

assertThat(List, Class) already exists but for another purpose so no luck for that option.

A possible hack is to define your own assertThat method like that:

```<code>public static <T> ListAssert<Object> assertThat(final List<T> list) {
    return Assertions.assertThat(list);
}
</code>```

The trick being to return a ListAssert<Object>.

Although I understand the rationale of the compilation error I disagree with it for read only method.

Body:
I have a getter returning a List with a wildcard:

import java.util.List;

public interface Foo {
    List<? extends Bar> getList();
}

Where Bar is an other interface.

When I write an assertion with AssertJ like this:

assertThat(foo.getList()).containsExactly(bar1, bar3);

EDIT: my complete usage is to chain a usingElementComparator and to provide a Comparator<Bar> to compare the expected Bar instances.

Comparator<Bar> comparator = createBarComparator()
assertThat(foo.getList()).usingElementComparator(comparator).containsExactly(bar1, bar3);

I get this compilation error:

The method containsExactly(capture#46-of ? extends Bar...) in the type ListAssert is not applicable for the arguments (Bar, Bar)

My first solution is to cast the result:

assertThat((List<Bar>)foo.getList()).containsExactly(bar1, bar3);

Then I get a warning:

Type safety: Unchecked cast from List to List

Warning can be removed with @SuppressWarnings("unchecked"), but still the cast in the middle do not make the assertion really readable.

My second solution is to indicate the value the ELEMENT generic parameter:

Assertions.<Bar>assertThat(foo.getList()).containsExactly(bar1, bar3);

A little better, but also not that nice (no static import possible, the beginning of the line do not facilitate the readability)

I guess I am looking for an other assertThat method for list, where the class type can be specified as second parameter:

@CheckReturnValue
public static <ELEMENT> ListAssert<ELEMENT> assertThat(List<? extends ELEMENT> actual, Class<ELEMENT> c) {
    return AssertionsForInterfaceTypes.assertThat(actual);
}

This way I should be able to write something like this:

Assertions.assertThat(foo.getList(), Bar.class).containsExactly(bar1, bar3);

Body:
That used to work with the Oracle JDK 7 compiler but this was actually a bug in the compiler, this has been fixed in Java 8 JDK so having the compilation error is the normal behavior (can't find the bug reference though).

I would be happy to support but I'm not sure this is possible in AssertJ except by removing all generics usage in collections assertions.

assertThat(List, Class) already exists but for another purpose so no luck for that option.

A possible hack is to define your own assertThat method like that:

public static <T> ListAssert<Object> assertThat(final List<T> list) {
    return Assertions.assertThat(list);
}

The trick being to return a ListAssert<Object>.

Although I understand the rationale of the compilation error I disagree with it for read only method.


问:
How to make a jtable not editable in java?
I created a function which loads data into a JTable. Everything's working fine except that all the cells in this table are editable. Btw, I used defaultTableModel for the table model. Im doing this in Netbeans IDE. Please help. Here's my code:

```<code>private void updateTable(String searchText){

    if(searchText != null)
        this._sqlCmd = this._sqlCmd + " WHERE "+columnCombo.getSelectedItem()+" LIKE '%"+searchText+"%'";
    jTable1.setSurrendersFocusOnKeystroke(true);
    table = (javax.swing.table.DefaultTableModel) jTable1.getModel();

    try{
        table.setRowCount(0);
    }catch(Exception e){}

    try {
        ResultSet rs = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY).executeQuery(_sqlCmd);
        while (rs.next()){
            Object[] data = new Object[numOfCols];
            for(int i=0; i<data.length; i++){
                data[i] = rs.getObject(i+1);
            }
            table.addRow(data);
        }
        table.fireTableDataChanged();

    } catch (SQLException ex) {
        Logger.getLogger(FindContactGrid.class.getName()).log(Level.SEVERE, null, ex);
    }
}
</code>```

答:
Try This</p>

```<code>JTable table = new JTable();
table.setEnabled(false);
</code>```

Body:
I created a function which loads data into a JTable. Everything's working fine except that all the cells in this table are editable. Btw, I used defaultTableModel for the table model. Im doing this in Netbeans IDE. Please help. Here's my code:

private void updateTable(String searchText){

    if(searchText != null)
        this._sqlCmd = this._sqlCmd + " WHERE "+columnCombo.getSelectedItem()+" LIKE '%"+searchText+"%'";
    jTable1.setSurrendersFocusOnKeystroke(true);
    table = (javax.swing.table.DefaultTableModel) jTable1.getModel();

    try{
        table.setRowCount(0);
    }catch(Exception e){}

    try {
        ResultSet rs = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY).executeQuery(_sqlCmd);
        while (rs.next()){
            Object[] data = new Object[numOfCols];
            for(int i=0; i<data.length; i++){
                data[i] = rs.getObject(i+1);
            }
            table.addRow(data);
        }
        table.fireTableDataChanged();

    } catch (SQLException ex) {
        Logger.getLogger(FindContactGrid.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Body:
Try This

JTable table = new JTable();
table.setEnabled(false);


问:
How to use a variable WS name that references another WS and a variable range, with a MIN function
I have a WS named Stats and I want to fill a column with the MINIMUMs.  The data is in the same WB, but on another WS called Data.
The data is in rows, so MIN calc would be performed on range B to IQ columns.
And I need to calc the MIN for rows 14 to 1868.

The following code works, but name and range of the data is hard coded:

```<code>Worksheets("Stats").Range("B14:B1868").Formula = "=MIN(Data!B58:IQ58)"
</code>```

So my problem is that every workbook has a different worksheet name for the data.  My macro has to work for all WBs.

I've tried the Indirect function, and this configuration only works for one row of data and populates the rest of the column with the same number(note that $A$2 is the location with the Worksheet name that contains the data):

```<code>Worksheets("Stats").Range("B14:B1868").Formula = "=MIN(Indirect($A$2&""!B58:IQ58"")"
</code>```

I have tried so many different configs and can't figure this one out. I'll get a name or a ref error...it's driving me nuts, hoping someone here can help me!

Thanks in advance:-)

答:
You can use a cell reference's value just as easily as a string literal.

(Sense of deja-vu there - I wrote that as part of an answer just this morning!)

So, instead of hard-coding "Data" into the formula

```<code>Worksheets("Stats").Range("B14:B1868").Formula = "=MIN(Data!B58:IQ58)"
</code>```

you can insert the value from a cell

```<code>Worksheets("Stats").Range("B14:B1868").Formula = "=MIN('" & Worksheets("Stats").Range("A2").Value & "'!B58:IQ58)"
</code>```

(I added apostrophes around the sheet name as well, just in case it contained spaces or other special characters.)

Body:
I have a WS named Stats and I want to fill a column with the MINIMUMs.  The data is in the same WB, but on another WS called Data.
The data is in rows, so MIN calc would be performed on range B to IQ columns.
And I need to calc the MIN for rows 14 to 1868.

The following code works, but name and range of the data is hard coded:

Worksheets("Stats").Range("B14:B1868").Formula = "=MIN(Data!B58:IQ58)"

So my problem is that every workbook has a different worksheet name for the data.  My macro has to work for all WBs.

I've tried the Indirect function, and this configuration only works for one row of data and populates the rest of the column with the same number(note that $A$2 is the location with the Worksheet name that contains the data):

Worksheets("Stats").Range("B14:B1868").Formula = "=MIN(Indirect($A$2&""!B58:IQ58"")"

I have tried so many different configs and can't figure this one out. I'll get a name or a ref error...it's driving me nuts, hoping someone here can help me!

Thanks in advance:-)

Body:
You can use a cell reference's value just as easily as a string literal.

(Sense of deja-vu there - I wrote that as part of an answer just this morning!)

So, instead of hard-coding "Data" into the formula

Worksheets("Stats").Range("B14:B1868").Formula = "=MIN(Data!B58:IQ58)"

you can insert the value from a cell

Worksheets("Stats").Range("B14:B1868").Formula = "=MIN('" & Worksheets("Stats").Range("A2").Value & "'!B58:IQ58)"

(I added apostrophes around the sheet name as well, just in case it contained spaces or other special characters.)


答:
Your program is incorrect. Here's how to fix it: Remove the malloc on the RHS, replace it with NULL, and remove the free line.

You're just moving the pointer, so there's no need to do manual allocation, and if you free the last value, that's a bug because you're freeing something that wasn't malloced.

Title: Idiom for aliasing structs


问:
How do I make ordered list using javascript?
Lets say I have this

```<code><ol>
  <li>V1 One</li>
  <li>V1 Two</li>
  <li>V1 Three</li>
  <li>V1 Four</li>
</ol>`
</code>```

I want to make an ordered list using .js instead of using LI tags.
I was thinking the js. code could replace first V1 and call it 1. , replace second V1 and call it two and so on, in other words counting how many V1s there are and replacing them with ordered list.

Or maybe something like this

```<code><ol>
  <li>i++ V1 One</li>
  <li>i++ V1 Two</li>
  <li>i++ V1 Three</li>
  <li>i++ V1 Four</li>
</ol>
</code>```

Where i++ will be increased every time starting from 1

Yes, I know LI provide ordered list!

答: I would advise you to learn(use) a javascript framework to accomplish this. It will speed up your javascript development rapidly. Jquery is very popular at the moment and I think you should also use that. Stackoverflow allready has a topic using Jquery describing what you want => Generating an unordered list with jQuery</p>

Body:
Lets say I have this

V1 One

V1 Two

V1 Three

V1 Four

`

I want to make an ordered list using .js instead of using LI tags.
I was thinking the js. code could replace first V1 and call it 1. , replace second V1 and call it two and so on, in other words counting how many V1s there are and replacing them with ordered list.

Or maybe something like this

i++ V1 One

i++ V1 Two

i++ V1 Three

i++ V1 Four

Where i++ will be increased every time starting from 1

Yes, I know LI provide ordered list!


问:
Can Python print a function definition?
In JavaScript, one can print out the definition of a function.  Is there a way to accomplish this in Python?  </p>

<p>(Just playing around in interactive mode, and I wanted to read a module without open().  I was just curious).  </p>

答:
You can use the __doc__ in the function, take hog() function as example:
You can see the usage of hog() like this:

```<code>from skimage.feature import hog

print hog.__doc__
</code>```

The output will be:

```<code>Extract Histogram of Oriented Gradients (HOG) for a given image.
Compute a Histogram of Oriented Gradients (HOG) by

    1. (optional) global image normalisation
    2. computing the gradient image in x and y
    3. computing gradient histograms
    4. normalising across blocks
    5. flattening into a feature vector

Parameters
----------
image : (M, N) ndarray
    Input image (greyscale).
orientations : int
    Number of orientation bins.
pixels_per_cell : 2 tuple (int, int)
    Size (in pixels) of a cell.
cells_per_block  : 2 tuple (int,int)
    Number of cells in each block.
visualise : bool, optional
    Also return an image of the HOG.
transform_sqrt : bool, optional
    Apply power law compression to normalise the image before
    processing. DO NOT use this if the image contains negative
    values. Also see `notes` section below.
feature_vector : bool, optional
    Return the data as a feature vector by calling .ravel() on the result
    just before returning.
normalise : bool, deprecated
    The parameter is deprecated. Use `transform_sqrt` for power law
    compression. `normalise` has been deprecated.

Returns
-------
newarr : ndarray
    HOG for the image as a 1D (flattened) array.
hog_image : ndarray (if visualise=True)
    A visualisation of the HOG image.

References
----------
* http://en.wikipedia.org/wiki/Histogram_of_oriented_gradients

* Dalal, N and Triggs, B, Histograms of Oriented Gradients for
  Human Detection, IEEE Computer Society Conference on Computer
  Vision and Pattern Recognition 2005 San Diego, CA, USA

Notes
-----
Power law compression, also known as Gamma correction, is used to reduce
the effects of shadowing and illumination variations. The compression makes
the dark regions lighter. When the kwarg `transform_sqrt` is set to
``True``, the function computes the square root of each color channel
and then applies the hog algorithm to the image.
</code>```

Title: Can Python print a function definition?

Body:
In JavaScript, one can print out the definition of a function.  Is there a way to accomplish this in Python?

(Just playing around in interactive mode, and I wanted to read a module without open().  I was just curious).

Body:
You can use the __doc__ in the function, take hog() function as example:
You can see the usage of hog() like this:

from skimage.feature import hog

print hog.__doc__

The output will be:

Extract Histogram of Oriented Gradients (HOG) for a given image.
Compute a Histogram of Oriented Gradients (HOG) by

    1. (optional) global image normalisation
    2. computing the gradient image in x and y
    3. computing gradient histograms
    4. normalising across blocks
    5. flattening into a feature vector

Parameters
----------
image : (M, N) ndarray
    Input image (greyscale).
orientations : int
    Number of orientation bins.
pixels_per_cell : 2 tuple (int, int)
    Size (in pixels) of a cell.
cells_per_block  : 2 tuple (int,int)
    Number of cells in each block.
visualise : bool, optional
    Also return an image of the HOG.
transform_sqrt : bool, optional
    Apply power law compression to normalise the image before
    processing. DO NOT use this if the image contains negative
    values. Also see `notes` section below.
feature_vector : bool, optional
    Return the data as a feature vector by calling .ravel() on the result
    just before returning.
normalise : bool, deprecated
    The parameter is deprecated. Use `transform_sqrt` for power law
    compression. `normalise` has been deprecated.

Returns
-------
newarr : ndarray
    HOG for the image as a 1D (flattened) array.
hog_image : ndarray (if visualise=True)
    A visualisation of the HOG image.

References
----------
* http://en.wikipedia.org/wiki/Histogram_of_oriented_gradients

* Dalal, N and Triggs, B, Histograms of Oriented Gradients for
  Human Detection, IEEE Computer Society Conference on Computer
  Vision and Pattern Recognition 2005 San Diego, CA, USA

Notes
-----
Power law compression, also known as Gamma correction, is used to reduce
the effects of shadowing and illumination variations. The compression makes
the dark regions lighter. When the kwarg `transform_sqrt` is set to
``True``, the function computes the square root of each color channel
and then applies the hog algorithm to the image.


问:
How to get everything before and up to a certain substring within a string?
How would I return a string up to a certain character?

```<code>def get_header(s):
    '''(str) -> str
    Return the start of the given string upto and including
    </head>.'''
    return (s.split('</head>')[0])
</code>```

this is what i did but, I don't know how i would get everything before the "  "<"/heads">"" and including it.

for example:

```<code>s ="hello python world </head> , i'm a beginner "
get_header(s)
</code>```

this would return

"hello python world "<"/head">"   #without the quotient marks around the <
```

答:
Your code should work, but won't include "", so just add it at the end:

```<code>def get_header(s):
    '''(str) -> str
    Return the start of the given string upto and including
    </head>.'''
    return s.split('</head>')[0] + "</head>"
</code>```

Body:
How would I return a string up to a certain character?

def get_header(s):
    '''(str) -> str
    Return the start of the given string upto and including
    .'''
    return (s.split('')[0])

this is what i did but, I don't know how i would get everything before the "  "<"/heads">"" and including it.

for example:

s ="hello python world  , i'm a beginner "
get_header(s)

this would return

"hello python world "<"/head">"   #without the quotient marks around the <

Body:
Your code should work, but won't include "</head>", so just add it at the end:

def get_header(s):
    '''(str) -> str
    Return the start of the given string upto and including
    </head>.'''
    return s.split('</head>')[0] + "</head>"


问:
ES6 curly braces usage when extracting from an object and assigning to another object
I would like to use curly braces to replace this code:

```<code>let rUsers = children.map((user) => {
    let rUser= {};
    rUser.firstName = user.firstName;
    rUser.lastName = user.lastName;
    rUser.relation = user.patron.relation;
    return rUser;
 });
</code>```

This is what I have:

```<code>let rUsers = children.map((user) => {
    let rUser = {};
    ({
        firstName: rUser.firstName,
        lastName: rUser.lastName,
        patron.relation: rUser.relation, // I get an error here
    } = user);
    return rUser;
}
</code>```

Except for patron.relation, the rest of the extraction works.

Questions:

How should I extract value of user.patron.relation?

Is there a more succint way of writing the above?

Thanks!

答:
You can use object destructuring like this:

```<code>const {firstName, lastName, patron: {relation}} = user
</code>```

And relation has been set to the value of user.patron.relation.

You can return the object you want like so:

```<code>return {firstName, lastName, relation}
</code>```

Body:
I would like to use curly braces to replace this code:

let rUsers = children.map((user) => {
    let rUser= {};
    rUser.firstName = user.firstName;
    rUser.lastName = user.lastName;
    rUser.relation = user.patron.relation;
    return rUser;
 });

This is what I have:

let rUsers = children.map((user) => {
    let rUser = {};
    ({
        firstName: rUser.firstName,
        lastName: rUser.lastName,
        patron.relation: rUser.relation, // I get an error here
    } = user);
    return rUser;
}

Except for patron.relation, the rest of the extraction works.

Questions:

How should I extract value of user.patron.relation?

Is there a more succint way of writing the above?

Thanks!

Body:
You can use object destructuring like this:

const {firstName, lastName, patron: {relation}} = user

And relation has been set to the value of user.patron.relation.

You can return the object you want like so:

return {firstName, lastName, relation}


问:
ecma6 shortest for loop with if check
what is the shortest way to achieve this for loop in ecmascript 6:

```<code>var data = {
        sales: [
            {
                name: "Jim Frost",
                region: "USA East",
                phone: "212-555-1212",
                email: "jfrost@acme-travel.com"
            },
            {
                name: "Jan Smith",
                region: "USA West",
                phone: "310-555-1212",
            }
        ]
};
</code>```

here is my attempt to see if the key is equal to my manually set variable, then i change that key item's field, if not, i change it to something else.

```<code>var str = '0'; // could also be an integer
for (var key in data.sales) {
  key ===  str ? data.sales[key].region = 'StateChosen' : data.sales[key].region = 'stateEliminated';
}
</code>```

what is the shortest way to achieve this using ecma6, object.keys, map, filter, every, etc methods?

答:
Your example could be done just by doing:

```<code>data.sales.forEach(el => el.region = 'stateEliminated'); // Change every region to eliminated
data.sales[str].region = 'StateChosen'; // Change back the selected to StateChosen.
</code>```

Note: I am assuming that str is a valid key in data.sales.

Title: ecma6 shortest for loop with if check

Body:
what is the shortest way to achieve this for loop in ecmascript 6:

var data = {
        sales: [
            {
                name: "Jim Frost",
                region: "USA East",
                phone: "212-555-1212",
                email: "jfrost@acme-travel.com"
            },
            {
                name: "Jan Smith",
                region: "USA West",
                phone: "310-555-1212",
            }
        ]
};

here is my attempt to see if the key is equal to my manually set variable, then i change that key item's field, if not, i change it to something else.

var str = '0'; // could also be an integer
for (var key in data.sales) {
  key ===  str ? data.sales[key].region = 'StateChosen' : data.sales[key].region = 'stateEliminated';
}

what is the shortest way to achieve this using ecma6, object.keys, map, filter, every, etc methods?

Body:
Your example could be done just by doing:

data.sales.forEach(el => el.region = 'stateEliminated'); // Change every region to eliminated
data.sales[str].region = 'StateChosen'; // Change back the selected to StateChosen.

Note: I am assuming that str is a valid key in data.sales.


问:
AWS HTTP error: cURL error 60: Peer certificate cannot be authenticated with gi certificates
i am using this package

```<code>https://github.com/Vinelab/cdn
</code>```

for laravel CDN asset management
after configring all the package when i execute this command to push assets to s3 bucket

```<code>php artisan cdn:push
</code>```

its show me error

\Exception\S3Exception] executing "ListObjects" on
  "https://s3.eu-central1.amazonaws.com/moberries-assets?encode=url";
  AWS HTTP error: cURL error 60: Peer certificate cannot be
  authenticated with gi certificates

Http\Exception\RequestException] ror 60: Peer certificate cannot be
  authenticated with given CA certificates

Http\Ring\Exception\RingException] ror 60: Peer certificate cannot be
  authenticated with given CA certificates

i vitist the followign links for this issue and also include the cancert certificate in the project file.

when i run the command it always shown the above mentioned error

i consult the following links

enter link description here

Please if one has its solution for laravel project then reply fast.Thanks

答:
I have faced this similar issue after update my project library. Finally, Kashif Ali answer gives me some clue.

But I could not find where to put cacert.pem file.

After I update this below setting to config/fileSystem.php, it's solved my problem.

```<code>'s3' => [
            'driver' => 's3',
            'key' => env('S3_KEY','your key'),
            'secret' => env('S3_SECRET','your secret'),
            'region' => env('S3_REGION','your region'),
            'bucket' => env('S3_BUCKET',"bucket name"),
            'http'       => ['verify'=> public_path('cacert.pem')]
        ],
</code>```

Body:
i am using this package

https://github.com/Vinelab/cdn

for laravel CDN asset management
after configring all the package when i execute this command to push assets to s3 bucket

php artisan cdn:push

its show me error

\Exception\S3Exception] executing "ListObjects" on
  "https://s3.eu-central1.amazonaws.com/moberries-assets?encode=url";
  AWS HTTP error: cURL error 60: Peer certificate cannot be
  authenticated with gi certificates

Http\Exception\RequestException] ror 60: Peer certificate cannot be
  authenticated with given CA certificates

Http\Ring\Exception\RingException] ror 60: Peer certificate cannot be
  authenticated with given CA certificates

i vitist the followign links for this issue and also include the cancert certificate in the project file.

when i run the command it always shown the above mentioned error

i consult the following links

enter link description here

Please if one has its solution for laravel project then reply fast.Thanks

Body:
I have faced this similar issue after update my project library. Finally, Kashif Ali answer gives me some clue.

But I could not find where to put cacert.pem file.

After I update this below setting to config/fileSystem.php, it's solved my problem.

's3' => [
            'driver' => 's3',
            'key' => env('S3_KEY','your key'),
            'secret' => env('S3_SECRET','your secret'),
            'region' => env('S3_REGION','your region'),
            'bucket' => env('S3_BUCKET',"bucket name"),
            'http'       => ['verify'=> public_path('cacert.pem')]
        ],