问:
Call a trigger function after page got refreshed/reload
I have a anchor tag in one page on click am redirecting to other page. Once page got refreshed , i want to call a trigger function which is present in current page.
Tried with below code.

```<code>$('#id').click(function() {

  $('.class').trigger('click'); // class present in other page

});
</code>```

Kindly help me.

答:
Pass a query to the page you open, an example you be:

Assuming you have an index.html that has a link to other page.html:

```<code><a href="page.html?flag=true">Open Page</a>
</code>```

Then in page.html:

```<code>function getQueryStringValue (key) {
  return decodeURIComponent(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}
if (getQueryStringValue('flag') === 'true') {
  // do what you need
};
</code>```

Body:
I have a anchor tag in one page on click am redirecting to other page. Once page got refreshed , i want to call a trigger function which is present in current page.
Tried with below code.

$('#id').click(function() {

  $('.class').trigger('click'); // class present in other page

});

Kindly help me.

Body:
Pass a query to the page you open, an example you be:

Assuming you have an index.html that has a link to other page.html:

<a href="page.html?flag=true">Open Page</a>

Then in page.html:

function getQueryStringValue (key) {
  return decodeURIComponent(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}
if (getQueryStringValue('flag') === 'true') {
  // do what you need
};


来源: stackexchange

问:
laravel eloquent mark objects with relation
```<code>class PaymentMethod extends Model
{
     ....

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
    ...
}

class User extends Authenticatable
{
    ...

    public function payment_methods()
    {
        return $this->hasMany(PaymentMethod::class, $this->getForeignKey())->orderBy('created_at', 'desc');
    }

    public function default_payment_method()
    {
        return $this->hasOne(PaymentMethod::class, 'id', 'default_payment_method_id');
    }

    ...
}
</code>```

In the views

```<code>@if($user -> getDefautPaymentMethod()->type == PaymentMethod::PAYPAL_ACCOUNT)
    <div><strong>Paypal: </strong> {{$user -> getDefautPaymentMethod()-> paypal_email}}</div>
@else
    <div><strong>Card: </strong>{{$user -> getDefautPaymentMethod()-> card_brand}} **** **** **** {{$user -> getDefautPaymentMethod()-> card_last_four}}</div>
@endif
</code>```

This work fine. And outputs default payment method for user.

But i want't output all payments method for user. And for each method output label if this is default for user.

I don't want't DB::RAW or sub queries in cicle

```<code>    @foreach($user->payment_methods()->get() as $payment_method)
        @if($payment_method ->type == PaymentMethod::PAYPAL_ACCOUNT)
            <div><strong>Paypal: </strong> {{$payment_method -> paypal_email}}</div>
        @else
            <div><strong>Card: </strong>{{ $payment_method -> card_brand }} **** **** **** {{$payment_method -> card_last_four}}</div>
        @endif
    @endforeach
</code>```

How affect this cicle and model code for output if method default?

答:
You can loop through the payment methods, and compare the ID's with the default payment method's ID. They can match, you know it's the default.</p>

```<code>@foreach ($user->payment-methods()->get() as $payment_method)
    <div>
        @if ($user->get_default_payment_method()->id === $payment_method->id)
            <strong>Default Payment Method</strong>
        @endif
        {{ $payment_method }}
    </div>
@endforeach
</code>```

ContentLicense: CC BY-SA 3.0

Body:
class PaymentMethod extends Model
{
     ....

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
    ...
}

class User extends Authenticatable
{
    ...

    public function payment_methods()
    {
        return $this->hasMany(PaymentMethod::class, $this->getForeignKey())->orderBy('created_at', 'desc');
    }

    public function default_payment_method()
    {
        return $this->hasOne(PaymentMethod::class, 'id', 'default_payment_method_id');
    }

    ...
}

In the views

@if($user -> getDefautPaymentMethod()->type == PaymentMethod::PAYPAL_ACCOUNT)

Paypal:  {{$user -> getDefautPaymentMethod()-> paypal_email}}

@else

Card: {{$user -> getDefautPaymentMethod()-> card_brand}} **** **** **** {{$user -> getDefautPaymentMethod()-> card_last_four}}

@endif

This work fine. And outputs default payment method for user.

But i want't output all payments method for user. And for each method output label if this is default for user.

I don't want't DB::RAW or sub queries in cicle

    @foreach($user->payment_methods()->get() as $payment_method)
        @if($payment_method ->type == PaymentMethod::PAYPAL_ACCOUNT)

Paypal:  {{$payment_method -> paypal_email}}

        @else

Card: {{ $payment_method -> card_brand }} **** **** **** {{$payment_method -> card_last_four}}

        @endif
    @endforeach

How affect this cicle and model code for output if method default?

Body:
You can loop through the payment methods, and compare the ID's with the default payment method's ID. They can match, you know it's the default.

@foreach ($user->payment-methods()->get() as $payment_method)
    <div>
        @if ($user->get_default_payment_method()->id === $payment_method->id)
            <strong>Default Payment Method</strong>
        @endif
        {{ $payment_method }}
    </div>
@endforeach


问:
ServiceNow create a script to add a field to a form
I am currently trying to add a field to a form design programatically.  I have already declared a column on the Base Configuration Item (cmdb) table and am now trying to find out how to add that field to children of that table programatically.  I am already able to go into each child's form design and and drag the field in because I have already added it as a column on the base table but I would like to know how to write a script that places a field in a form design so that I can do it for multiple children and fields.  </p>

答:
If you're using the same view name, adding the field to the parent table should cause it to trickle down to all child tables.
In order for this to work, you'll want to do this via Configure>Form Layout, not the Form Designer.

More info here:  https://community.servicenow.com/thread/169202


问:
Vue.js view doesn't update when an event is received using an eventbus
I'm new to Vue.js 2 and am building my first (vue) web application.
The application uses two components, one header component and one login component.
When the login is succesfull a "loggedIn"-flag variable will be toggled in a singleton authentication service.
This service is responsible to emit an event to the header component (and maybe other listening components) to notify that the user is logged in. The header in turn should update it's view and display the username.

Everything works as described, events are generated and emitted/received using a global event bus.
However, when the event is received by the header component it's unable to update the view.

I already tried different approaches: basic subscriber pattern, vuex and now the event bus. Nothing seems to work. Does anyone know what the problem might be?

EventBus.js:

import Vue from 'vue'
var eventBus = new Vue()
export default eventBus
```

<p><strong>SessionService.js</strong>
</p>

```import eventBus from '../util/EventBus'

class SessionService {
  loggedIn=false
  constructor () {
    if (this.isValid(this.getSessionToken())) {
      this.loggedIn = true
    }
  }
  setSessionToken (token) {
    localStorage.setItem('token', token)
    if (this.isValid(token)) {
      eventBus.$emit('LOGGEDIN')
    } else {
      eventBus.$emit('LOGGEDOUT')
    }
  }
  getSessionToken () {
    return localStorage.getItem('token')
  }
  isValid (token) {
    return token !== undefined && token != null && token !== ''
  }
}
var sessionService = new SessionService()
export default sessionService
```

<p><strong>Header.vue: Script</strong></p>

<pre class="lang-js prettyprint-override"><code>  import eventBus from '../../services/util/EventBus'
  var loggedIn = false
  var m = this
  eventBus.$on('LOGGEDIN', function () {
    console.log('RECEIVED')
    m.loggedIn = true
  })

  export default{
    name: 'Header',
    data () {
      return {loggedIn}
    }
  }
</code>```

Header.vue: HTML

```<code><template>
  <div>
  <nav class="navbar navbar-expand-lg ap-top-nav">
    <div class="container" >
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">

        <form class="form-inline my-2 my-lg-0 mr-auto">
          <div class="ap-searcher">
            <input class="ap-search" type="text" placeholder="Search" aria-label="Search"/>
            <i class="fa fa-search"></i>
          </div>

        </form>
        <div class="logo ml-auto mr-auto">
          <img src="../../assets/images/logo.png"/>
        </div>
        <ul class="navbar-nav ml-auto">
          <li class="nav-item ap-button blue wide">
            <router-link to="/login">Login: {{loggedIn}}</router-link>
          </li>
          <li class="nav-item ap-button light-blue wide">
            <router-link to="/registration">Register</router-link>
          </li>
          <li class="nav-item ap-button blue-border">
            <a href="#">EN <i class="fa fa-sort-desc" aria-hidden="true"></i></a>
          </li>
        </ul>
      </div>

    </div>
  </nav>
    <nav class="navbar navbar-expand-lg ag-bottom-nav">
      <div class="container">
        <div class="collapse navbar-collapse " id="navbarNav">
          <ul class="navbar-nav ml-auto">
            <li class="nav-item active">
              <router-link class="nav-link ap-link" to="/">Auctions</router-link>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Lots</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">About</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Organize your own auction</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Contact </a>
            </li>
          </ul>
        </div>
      </div>

    </nav>
    <div class="ap-line">
    </div>
  </div>
</template>
</code>```

答:
In your Header.vue component, when you are registering the 'LOGGEDIN' listener, you are trying to access the Vue instance via this outside the scope of the Vue instance.

Move that logic inside the created hook of the component so that the eventBus listener is still registered when the component is instantiated, but so that this is referencing the Vue instance:

```<code>import eventBus from '../../services/util/EventBus'

export default {
  name: 'Header',
  data() {
    return { loggedIn: false }
  },
  created() {
    let self = this;
    eventBus.$on('LOGGEDIN', function () {
      console.log('RECEIVED')
      self.loggedIn = true
    })
  }
}
</code>```

Body:
I'm new to Vue.js 2 and am building my first (vue) web application.
The application uses two components, one header component and one login component.
When the login is succesfull a "loggedIn"-flag variable will be toggled in a singleton authentication service.
This service is responsible to emit an event to the header component (and maybe other listening components) to notify that the user is logged in. The header in turn should update it's view and display the username.

Everything works as described, events are generated and emitted/received using a global event bus.
However, when the event is received by the header component it's unable to update the view.

I already tried different approaches: basic subscriber pattern, vuex and now the event bus. Nothing seems to work. Does anyone know what the problem might be?

EventBus.js:

import Vue from 'vue'
var eventBus = new Vue()
export default eventBus

SessionService.js

import eventBus from '../util/EventBus'

class SessionService {
  loggedIn=false
  constructor () {
    if (this.isValid(this.getSessionToken())) {
      this.loggedIn = true
    }
  }
  setSessionToken (token) {
    localStorage.setItem('token', token)
    if (this.isValid(token)) {
      eventBus.$emit('LOGGEDIN')
    } else {
      eventBus.$emit('LOGGEDOUT')
    }
  }
  getSessionToken () {
    return localStorage.getItem('token')
  }
  isValid (token) {
    return token !== undefined && token != null && token !== ''
  }
}
var sessionService = new SessionService()
export default sessionService

Header.vue: Script

  import eventBus from '../../services/util/EventBus'
  var loggedIn = false
  var m = this
  eventBus.$on('LOGGEDIN', function () {
    console.log('RECEIVED')
    m.loggedIn = true
  })

  export default{
    name: 'Header',
    data () {
      return {loggedIn}
    }
  }

Header.vue: HTML

<template>

      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

      </button>

        <form class="form-inline my-2 my-lg-0 mr-auto">

            <input class="ap-search" type="text" placeholder="Search" aria-label="Search"/>

        </form>

            <router-link to="/login">Login: {{loggedIn}}</router-link>

            <router-link to="/registration">Register</router-link>

            EN

              <router-link class="nav-link ap-link" to="/">Auctions</router-link>

              Lots

              About

              Organize your own auction

              Contact

</template>

Body:
In your Header.vue component, when you are registering the 'LOGGEDIN' listener, you are trying to access the Vue instance via this outside the scope of the Vue instance.

Move that logic inside the created hook of the component so that the eventBus listener is still registered when the component is instantiated, but so that this is referencing the Vue instance:

import eventBus from '../../services/util/EventBus'

export default {
  name: 'Header',
  data() {
    return { loggedIn: false }
  },
  created() {
    let self = this;
    eventBus.$on('LOGGEDIN', function () {
      console.log('RECEIVED')
      self.loggedIn = true
    })
  }
}


问:
Multiple URLs pointing to same tab in hook_menu
Here's a basic menu structure I'm working with:

```<code>function events_menu()
{
    $items = array();

    $items['events'] = array(
        'title' => 'Current Events',
        'access callback' => true,
        'page callback' => 'page_event',
        'type' => MENU_CALLBACK,
    );
      $items['events/current'] = array(
          'access callback' => true,
          'type' => MENU_DEFAULT_LOCAL_TASK,
          'weight' => 1,
      );
      $items['events/regions'] = array(
          'title' => 'Event By Region',
          'access callback' => true,
          'type' => MENU_LOCAL_TASK,
          'weight' => 2,
      );
      $items['events/range/%/to/%'] = array(
          'title' => 'Current Events by Range',
          'access callback' => true,
          'page callback' => 'page_event_range',
          'page arguments' => array(2, 4),
          'type' => MENU_LOCAL_TASK,
          /* Don't want this to be a tab.
             I want it to activate the default tab */
      );

    return $items;
}
</code>```

The URL (and default tab) events displays some data.  I'd like the URL events/range/%/to/% to filter the data based on the passed URL parameters.

The hook_menu above works, but I don't want events/range/%/to/% to be it's own tab.  When you use the filtered URL, I want the default tab, Current Events, to remain active -- to give the illusion that you're looking at the same page as events, only filtered.  Can multiple URL's point to the same tab?

I guess I could handle the url parameters manually with arg() in the events page callback, but this seems hacky.  Isn't there a way to do this using hook_menu?

Edit (stated more clearly):

Normally there are two tabs Current Events and Event By Region at the URLs events and events/regions.  I want a hidden (callback only) url at events/range/%/to/%.  But when you visit it, I want the two tabs to remain visible and Current Events active - as if we'd never left that page.

答: Have you tried 'context' Module. You can set path pattern you want for the active menu. Check out this quick video demo.</p>

ContentLicense: CC BY-SA 2.5

Body:
Here's a basic menu structure I'm working with:

function events_menu()
{
    $items = array();

    $items['events'] = array(
        'title' => 'Current Events',
        'access callback' => true,
        'page callback' => 'page_event',
        'type' => MENU_CALLBACK,
    );
      $items['events/current'] = array(
          'access callback' => true,
          'type' => MENU_DEFAULT_LOCAL_TASK,
          'weight' => 1,
      );
      $items['events/regions'] = array(
          'title' => 'Event By Region',
          'access callback' => true,
          'type' => MENU_LOCAL_TASK,
          'weight' => 2,
      );
      $items['events/range/%/to/%'] = array(
          'title' => 'Current Events by Range',
          'access callback' => true,
          'page callback' => 'page_event_range',
          'page arguments' => array(2, 4),
          'type' => MENU_LOCAL_TASK,
          /* Don't want this to be a tab.
             I want it to activate the default tab */
      );

    return $items;
}

The URL (and default tab) events displays some data.  I'd like the URL events/range/%/to/% to filter the data based on the passed URL parameters.

The hook_menu above works, but I don't want events/range/%/to/% to be it's own tab.  When you use the filtered URL, I want the default tab, Current Events, to remain active -- to give the illusion that you're looking at the same page as events, only filtered.  Can multiple URL's point to the same tab?

I guess I could handle the url parameters manually with arg() in the events page callback, but this seems hacky.  Isn't there a way to do this using hook_menu?

Edit (stated more clearly):

Normally there are two tabs Current Events and Event By Region at the URLs events and events/regions.  I want a hidden (callback only) url at events/range/%/to/%.  But when you visit it, I want the two tabs to remain visible and Current Events active - as if we'd never left that page.


问:
Check if Cookie has Secure Flag set and update using JavaScript ONLY
My issue is we set some cookies, using JS, with a 1 year expiration and that particular cookie didn't have the secure flag set. We now want to update the cookies to have the secure flag set. The code that creates the cookies now has the "secure" attribute and all new cookies have the "secure" flag. The issue is how do I update existing cookies? I'm assuming I have to destroy the cookie and then recreate it with the secure flag set? I don't know if there is any other way to do this? Also is there a way using JavaScript to detect if the cookie does have the flag set before deleting it?

Thanks!

答:
You can't check cookies flags with pure JavaScript. If you want to add flag, just create a new one cookie and browser will overwrite old.

Example:

Type in console:

```<code>const year = 60*60*24*365;
document.cookie = 'mytestcookie=1;max-age='+year;
</code>```

And look into cookies tab in your browser developer tools. You will see it's insecure.
Now, type:

```<code>document.cookie = 'mytestcookie=2;max-age='+year+';secure';
</code>```

Look again.

Body:
You can't check cookies flags with pure JavaScript. If you want to add flag, just create a new one cookie and browser will overwrite old.

Example:

Type in console:

const year = 60*60*24*365;
document.cookie = 'mytestcookie=1;max-age='+year;

And look into cookies tab in your browser developer tools. You will see it's insecure.
Now, type:

document.cookie = 'mytestcookie=2;max-age='+year+';secure';

Look again.


问:
simpleCV and Raspberry Pi: no module named simplecv
No module named SimpleCv

I installed simplecv on my RPi using the tutorial link: http://simplecv.readthedocs.io/en/latest/HOWTO-Install%20on%20RaspberryPi.html and installed svgwrite.

I have the simplecv working alone, but when running a python file I get the error:

```<code>Traceback (most recent call last):
  File "my-file.py", line 1, in <module>
    from SimpleCv import *
ImportError: No module named SimpleCv
</code>```

Is it to do with that my Python and simplecv are in different locations?

which python gives: /usr/bin/python

which simplecv gives: /usr/local/bin/simplecv

Many thanks,

Ben

答:
Resolved!

For future readers make sure you capitalise all 3 letters in from SimpleCV import *

Stupid mistake, thought I'd tried every combination of capitals.

Body:
No module named SimpleCv

I installed simplecv on my RPi using the tutorial link: http://simplecv.readthedocs.io/en/latest/HOWTO-Install%20on%20RaspberryPi.html and installed svgwrite.

I have the simplecv working alone, but when running a python file I get the error:

Traceback (most recent call last):
  File "my-file.py", line 1, in <module>
    from SimpleCv import *
ImportError: No module named SimpleCv

Is it to do with that my Python and simplecv are in different locations?

which python gives: /usr/bin/python

which simplecv gives: /usr/local/bin/simplecv

Many thanks,

Ben


问:
How can I oscillate numbers in a list?
Question: How can I make these oscillate as such that the first digits or expression is + the next is - the one after is + and so on and so forth for the lists provided below (without using a specially made function for oscillation if one even exists).

I'm currently getting output as shown below:

```<code>    x + x^3/6 + x^5/120 + x^7/5040 + x^9/362880
1. {1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61, 65, 69,
73, 77, 81, 85, 89}
</code>```

Expected output:

```<code>x - x^3/6 + x^5/120 - x^7/5040 + x^9/362880
2. {1, -5, 9, -13, 17, -21, 25, -29, 33, -37, 41, -45, 49, -53, 57, -61, 65, -69, 73, -77, 81, -85, 89}

Sum[x^j/Factorial[j], {j, 1, 9, 2}];
myOsc = Table[i, {i, 1, 89, 4}];
</code>```

Title: How can I oscillate numbers in a list?

Body:
Question: How can I make these oscillate as such that the first digits or expression is + the next is - the one after is + and so on and so forth for the lists provided below (without using a specially made function for oscillation if one even exists).

I'm currently getting output as shown below:

    x + x^3/6 + x^5/120 + x^7/5040 + x^9/362880
1. {1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61, 65, 69,
73, 77, 81, 85, 89}

Expected output:

x - x^3/6 + x^5/120 - x^7/5040 + x^9/362880
2. {1, -5, 9, -13, 17, -21, 25, -29, 33, -37, 41, -45, 49, -53, 57, -61, 65, -69, 73, -77, 81, -85, 89}

Sum[x^j/Factorial[j], {j, 1, 9, 2}];
myOsc = Table[i, {i, 1, 89, 4}];

Body:
A small improvement that does not require the extra s variable:

MapIndexed[(-1)^(1 + #2[[1]])*#1 &, x + x^3/6 + x^5/120 + x^7/5040 + x^9/362880]

x - x^3/6 + x^5/120 - x^7/5040 + x^9/362880


问:
Retrieving the last record in each group, older than given time
As in this question: Retrieving the last record in each group, I want to query the latest entries of each group.

In difference to the linked question, I also want to add a criteria for the maximum time.

I have tried the following:

```<code>SELECT m1.*
FROM messages m1
LEFT JOIN messages m2
ON (
    m1.name = m2.name AND
    m1.id < m2.id AND
    m2.time <= nnnnnnn
)
WHERE m2.id IS NULL
AND m1.time <= nnnnnnn;
</code>```

I am not sure if this is 100% correct, Is there a better solution? Maybe without the duplicate time <= nnnnnnn condition?

答:
This is what you're looking for. last-n-per-group-less-than-x</p>

```<code> SELECT m1.*
    FROM messages m1
    LEFT JOIN messages m2 ON (
        m2.name = m1.name AND
        IF(m2.date < 'nnnnnnn',m2.date > m1.date, m1.date > 'nnnnnnn'))
    WHERE m2.idIS NULL
</code>```

Body:
As in this question: Retrieving the last record in each group, I want to query the latest entries of each group.

In difference to the linked question, I also want to add a criteria for the maximum time.

I have tried the following:

SELECT m1.*
FROM messages m1
LEFT JOIN messages m2
ON (
    m1.name = m2.name AND
    m1.id < m2.id AND
    m2.time <= nnnnnnn
)
WHERE m2.id IS NULL
AND m1.time <= nnnnnnn;

I am not sure if this is 100% correct, Is there a better solution? Maybe without the duplicate time <= nnnnnnn condition?

Body:
This is what you're looking for. last-n-per-group-less-than-x

 SELECT m1.*
    FROM messages m1
    LEFT JOIN messages m2 ON (
        m2.name = m1.name AND
        IF(m2.date < 'nnnnnnn',m2.date > m1.date, m1.date > 'nnnnnnn'))
    WHERE m2.idIS NULL


问:
How to set up tables correctly in MS Access 2016
Context

I work for a metal building screw manufacturer we paint and bag them. Blanks are the parts we start with. On the following commas separate part numbers and the corresponding part and back slash separate # and parts from other parts all the parts in a row come from same blank.  The 100,250 and CTN on the same row are the same color but are bagged 100, 250 or just boxed.

Blank #,Blank Part-Color-powder #,powder part-bagged 100#,bagged 100
  part-bagged 250#, bagged 250 part-CTN#,CTN part

I have a price line # that is the same per type of screw no matter how they are processed.  This is how 1 line looks.  I have over 500 lines BTW.

10110/67543,12B100DMCOZ/56471,12B100DMCOPS
  BN03/BN03/09879,12B100DMC0PS BN03-100/65987,12B100DMC0PS
  BN03-250/12121,12B100DMC0PS BN03-CTN

Blanks make painted item, painted item then there are 3 Choices  bagged 100,250, CTN or a mix of them.

I am just starting out with Access coming from using Excel I can use very very little VBA learning it still.  This is with MS  Office 365.

Problem

What is the best way to separate the table or even if I should? I will need to be able to add parts in the Future.

Thanks for the help.

答: There is a powerful import tool that allows you to import data and to specify things like separators (comma, pipe, whatever-you-say-it-is) and whether the data comes with headers, etc. You can also save the import rules so that you can use this specification to import the data again down the road, or even to link the text-file in dynamically so that it's treated as a table from within your database. starting point</p>


问:
Lightbox 2.51 - how to move close button and image number to the top?
I'm using Lightbox 2.51 and I can't find a solution to move lb-dataContainer with close button and current image number etc to the top

I only found solutions for the old versions.

Code can be found here: http://lokeshdhakar.com/projects/lightbox2/releases/lightbox2.51.zip

答:
This is YEARS later, but if you want the easiest way to do this by far, simply use the following 4 lines of CSS:

```<code>#lightbox {
  display: flex;
  flex-direction: column-reverse;
}
</code>```

The flexbox will flip the display order on the container to be in reverse from the DOM.

Body:
This is YEARS later, but if you want the easiest way to do this by far, simply use the following 4 lines of CSS:

#lightbox {
  display: flex;
  flex-direction: column-reverse;
}

The flexbox will flip the display order on the container to be in reverse from the DOM.


问:
pycairo "ImportError: DLL load failed: The specified module could not be found." even after DLLs installed
I'm following the pycairo installation instructions here :
http://www.cs.rhul.ac.uk/home/tamas/development/igraph/tutorial/install.html
to install pycairo for use with igraph.

However, even after running the installer and unzipping/copying all DLL's into the site-packages cairo directory according to the instructions, I still get the following error:

```<code>
>>> import cairo
Traceback (most recent call last):
  File "", line 1, in
  File "c:\Python26\lib\site-packages\cairo__init__.py", line 1, in
    from _cairo import *
ImportError: DLL load failed: The specified module could not be found.
>>>
```

I am running python 2.6.6 under Windows 7.

Any ideas?

答: Open _cairo.pyd in Dependency Walker and figure out what it's missing.</p>

Body:
I'm following the pycairo installation instructions here :
http://www.cs.rhul.ac.uk/home/tamas/development/igraph/tutorial/install.html
to install pycairo for use with igraph.

However, even after running the installer and unzipping/copying all DLL's into the site-packages cairo directory according to the instructions, I still get the following error:

>>> import cairo
Traceback (most recent call last):
  File "", line 1, in
  File "c:\Python26\lib\site-packages\cairo__init__.py", line 1, in
    from _cairo import *
ImportError: DLL load failed: The specified module could not be found.
>>>

I am running python 2.6.6 under Windows 7.

Any ideas?


问:
Use SYS_REFCURSOR with CTE (includes Update statement)
I am using CTE to fetch some values and then using UPDATE statement to clear the returned values from database table.

This is happening inside a stored procedure.

```<code>UPDATE TABLE1
   SET AA = NULL, BB = NULL
 WHERE EXISTS
          (WITH T1 AS (SELECT AA, BB, CC FROM TABLEABC)
               ,T2
                AS (SELECT AA, BB, CB
                      FROM T1
                     WHERE T1.AA > 100)
           SELECT *
             FROM T2
            WHERE TABLE1.CC = T2.CC
</code>```

My column BB has some identification data which I want to capture before it is cleared by the Update statement. Can anyone guide me on how I can capture this column data and return as Procedure output.

```<code>OPEN SYS_REFCURSOR FOR
</code>```

答:
Unfortunately, the RETURNING INTO clause of an UPDATE statement will give you the values after the update, not the prior values.

So, if you want to save off the old values, you must do so before the UPDATE statement.  Take care to lock the rows and only actually update rows that you've saved, because it is possible that your table could be modified between the time you save off the data and the time to update it.

Then, return the saved data in a ref cursor.

Here is code that puts that all together:

```<code>CREATE TABLE TABLE1 ( AA number, BB number );

CREATE OR REPLACE PACKAGE so_test AS

  TYPE TABLE1_LIST_TAB IS TABLE OF TABLE1%ROWTYPE;

  FUNCTION do_it return sys_refcursor;

END so_test;

CREATE OR REPLACE PACKAGE BODY so_test AS

  FUNCTION do_it RETURN SYS_REFCURSOR IS
    l_old_data TABLE1_LIST_TAB;
    l_rc SYS_REFCURSOR;
  BEGIN

    SELECT AA, BB
    BULK COLLECT INTO l_old_data
    FROM table1
    WHERE -- put your conditions here of what you intend to update
    FOR UPDATE;

    UPDATE TABLE1
      SET AA = NULL, BB = NULL
    WHERE EXISTS ( SELECT 'record old data is captured'
                 FROM   TABLE(l_old_data) od
                 WHERE  od.aa = table1.aa   -- Assuming AA is a primary key
               )
    RETURNING AA, BB BULK COLLECT INTO l_old_data;

    OPEN l_rc FOR SELECT * FROM TABLE(l_old_data);

    RETURN l_rc;

  END do_it;
END so_test;
</code>```

NOTE: if you are not on 12c, you will need to define TABLE1_LIST_TAB as an OBJECT type in the database instead of in the package spec, or else the package body won't compile.

Body:
I am using CTE to fetch some values and then using UPDATE statement to clear the returned values from database table.

This is happening inside a stored procedure.

UPDATE TABLE1
   SET AA = NULL, BB = NULL
 WHERE EXISTS
          (WITH T1 AS (SELECT AA, BB, CC FROM TABLEABC)
               ,T2
                AS (SELECT AA, BB, CB
                      FROM T1
                     WHERE T1.AA > 100)
           SELECT *
             FROM T2
            WHERE TABLE1.CC = T2.CC

My column BB has some identification data which I want to capture before it is cleared by the Update statement. Can anyone guide me on how I can capture this column data and return as Procedure output.

OPEN SYS_REFCURSOR FOR

Body:
Unfortunately, the RETURNING INTO clause of an UPDATE statement will give you the values after the update, not the prior values.

So, if you want to save off the old values, you must do so before the UPDATE statement.  Take care to lock the rows and only actually update rows that you've saved, because it is possible that your table could be modified between the time you save off the data and the time to update it.

Then, return the saved data in a ref cursor.

Here is code that puts that all together:

CREATE TABLE TABLE1 ( AA number, BB number );

CREATE OR REPLACE PACKAGE so_test AS

  TYPE TABLE1_LIST_TAB IS TABLE OF TABLE1%ROWTYPE;

  FUNCTION do_it return sys_refcursor;

END so_test;

CREATE OR REPLACE PACKAGE BODY so_test AS

  FUNCTION do_it RETURN SYS_REFCURSOR IS
    l_old_data TABLE1_LIST_TAB;
    l_rc SYS_REFCURSOR;
  BEGIN

    SELECT AA, BB
    BULK COLLECT INTO l_old_data
    FROM table1
    WHERE -- put your conditions here of what you intend to update
    FOR UPDATE;

    UPDATE TABLE1
      SET AA = NULL, BB = NULL
    WHERE EXISTS ( SELECT 'record old data is captured'
                 FROM   TABLE(l_old_data) od
                 WHERE  od.aa = table1.aa   -- Assuming AA is a primary key
               )
    RETURNING AA, BB BULK COLLECT INTO l_old_data;

    OPEN l_rc FOR SELECT * FROM TABLE(l_old_data);

    RETURN l_rc;

  END do_it;
END so_test;

NOTE: if you are not on 12c, you will need to define TABLE1_LIST_TAB as an OBJECT type in the database instead of in the package spec, or else the package body won't compile.


问:
Icinga2 does not start because he could not load library "db_ido_mysql"
Here is the Error:

```<code>root@taurus:/etc/icinga2/features-available# service icinga2 checkconfig
* checking Icinga2 configuration
information/cli: Icinga application loader (version: r2.7.2-1)
information/cli: Loading configuration file(s).
critical/config: Error: Error while evaluating expression: Could not load library 'libdb_ido_mysql.so.2.7.2': libdb_ido_mysql.so.2.7.2: cannot open shared object file: No such file or directory
Location: in /etc/icinga2/features-enabled/ido-mysql.conf: 6:1-6:22
/etc/icinga2/features-enabled/ido-mysql.conf(4): */
/etc/icinga2/features-enabled/ido-mysql.conf(5):
/etc/icinga2/features-enabled/ido-mysql.conf(6): library "db_ido_mysql"
^^^^^^^^^^^^^^^^^^^^^^
/etc/icinga2/features-enabled/ido-mysql.conf(7):
/etc/icinga2/features-enabled/ido-mysql.conf(8): object IdoMysqlConnection "ido-mysql" {

* checking Icinga2 configuration. Check '/var/log/icinga2/startup.log' for details.

root@taurus:/etc/icinga2/features-available# icinga2 feature list
Disabled features: command compatlog debuglog gelf graphite influxdb livestatus opentsdb perfdata statusdata syslog
Enabled features: api checker ido-mysql ido-pgsql mainlog notification
</code>```

Does anybody know what i did wrong during the installation?
there were no problems, i dont get the answer.

答:
Do you want to use Icingaweb2 with your Icinga2 installation? Then you have to install the

```<code>icinga2-ido-mysql
</code>```

Package for your distribution and configure it. Here you can find a step by step instruction on how to install and configure it. If not, disable the following features:

```<code>ido-mysql ido-pgsql
</code>```

Regards,
Jan

Body:
Here is the Error:

root@taurus:/etc/icinga2/features-available# service icinga2 checkconfig
* checking Icinga2 configuration
information/cli: Icinga application loader (version: r2.7.2-1)
information/cli: Loading configuration file(s).
critical/config: Error: Error while evaluating expression: Could not load library 'libdb_ido_mysql.so.2.7.2': libdb_ido_mysql.so.2.7.2: cannot open shared object file: No such file or directory
Location: in /etc/icinga2/features-enabled/ido-mysql.conf: 6:1-6:22
/etc/icinga2/features-enabled/ido-mysql.conf(4): */
/etc/icinga2/features-enabled/ido-mysql.conf(5):
/etc/icinga2/features-enabled/ido-mysql.conf(6): library "db_ido_mysql"
^^^^^^^^^^^^^^^^^^^^^^
/etc/icinga2/features-enabled/ido-mysql.conf(7):
/etc/icinga2/features-enabled/ido-mysql.conf(8): object IdoMysqlConnection "ido-mysql" {

* checking Icinga2 configuration. Check '/var/log/icinga2/startup.log' for details.

root@taurus:/etc/icinga2/features-available# icinga2 feature list
Disabled features: command compatlog debuglog gelf graphite influxdb livestatus opentsdb perfdata statusdata syslog
Enabled features: api checker ido-mysql ido-pgsql mainlog notification

Does anybody know what i did wrong during the installation?
there were no problems, i dont get the answer.

Body:
Do you want to use Icingaweb2 with your Icinga2 installation? Then you have to install the

icinga2-ido-mysql

Package for your distribution and configure it. Here you can find a step by step instruction on how to install and configure it. If not, disable the following features:

ido-mysql ido-pgsql

Regards,
Jan


问:
Can I memcpy std::weak_ptr?
First off, what is the typical implementation of a std::weak_ptr? Particularly is std::weak_ptr just a pointer to the control block of a std::shared_ptr?

If all the std::shared_ptr references are gone is the internal control block deleted? If so, how does std::weak_ptr::expired() function properly if that memory is re-purposed?

I have an object that contains a std::weak_ptr, and I want to memcpy the object to a buffer to be processed later. Is doing so going to break the internal workings of the smart pointer in some way?

答:
When all std::shared_ptr objects are gone, the control block still exists (that's how std::weak_ptr's work), only the referenced object is deleted.

Now, a C++ object can be safely copied via std::memcpy only if it is trivially copyable. Checking the requirements of TriviallyCopyable concept, we see that std::weak_ptr does not satisfy it due to having a non-trivial copy constructor. In fact, this constructor will increase the weak-pointers-counter inside the control block, so copying it with std::memcpy would break its invariants.

To be honest, storing an std::weak_ptr in a raw buffer sounds like a terrible idea in usual code. Buffers are normally used for serialization, sending/writing data, etc, and all these tasks are nonsensical for a smart pointer. If, however, you are absolutely sure that you need to store it in a buffer, you need placement new:

```<code>std::weak_ptr<T> the_one_i_want_to_copy;

std::weak_ptr<T> * buffer = ...;
new (buffer) std::weak_ptr<T> { the_one_i_want_to_copy };
</code>```

Notice the (buffer) after new: it tells new not to allocate the memory, but to use an already prepared place (thus placement new). When preparing buffer, be sure to provide the required size and alignment.

Title: Can I memcpy std::weak_ptr?

Body:
When all std::shared_ptr objects are gone, the control block still exists (that's how std::weak_ptr's work), only the referenced object is deleted.

Now, a C++ object can be safely copied via std::memcpy only if it is trivially copyable. Checking the requirements of TriviallyCopyable concept, we see that std::weak_ptr does not satisfy it due to having a non-trivial copy constructor. In fact, this constructor will increase the weak-pointers-counter inside the control block, so copying it with std::memcpy would break its invariants.

To be honest, storing an std::weak_ptr in a raw buffer sounds like a terrible idea in usual code. Buffers are normally used for serialization, sending/writing data, etc, and all these tasks are nonsensical for a smart pointer. If, however, you are absolutely sure that you need to store it in a buffer, you need placement new:

std::weak_ptr<T> the_one_i_want_to_copy;

std::weak_ptr<T> * buffer = ...;
new (buffer) std::weak_ptr<T> { the_one_i_want_to_copy };

Notice the (buffer) after new: it tells new not to allocate the memory, but to use an already prepared place (thus placement new). When preparing buffer, be sure to provide the required size and alignment.


问:
Sinatra access-control-allow-origin for sinatra public folder
How do I set up Sinatra so that static files in the public folder
are returned with the response Access-Control-Allow-Origin = "*" ?</p>

答:
I did this on a server side, my file was called server.rb:</p>

```<code>before do
   content_type :json
   headers 'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Methods' => ['OPTIONS', 'GET', 'POST']
end
</code>```

Body:
I did this on a server side, my file was called server.rb:

before do
   content_type :json
   headers 'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Methods' => ['OPTIONS', 'GET', 'POST']
end


问:
Error INSTALL_FAILED_CONFLICTING_PROVIDER without any provider on my app
I'm getting this error:

INSTALL_FAILED_CONFLICTING_PROVIDER - multiple apps using same
  authority provider name

But I don't have any provider on my app, then I noticed that the final AndroidManifest.xml has the following provider:

```<code>    <provider
        android:name="com.google.android.gms.measurement.AppMeasurementContentProvider"
        android:authorities="com.google.android.gms.measurement.google_measurement_service"
        android:exported="false" />
</code>```

This seems an analytics issue on the latest Google Play Services library.

答:
First of all, The error message you see above happens only when you want to install the same application instance on the same device.

```<code>flavors {
   prod {
     applicationId "your.package.name.prod"
   }
   qa {
     applicationId "your.package.name.qa"
   }
}
</code>```

From the error message you can clearly identify the issue, which occurred due to provider tag in your AndroidManifest.xml file.

Solution:
  1. Identify which provider tag is causing the issue.
  2. Most probably the issue could be android:authroties field.
  3. Extend the same provider in your AndroidManifest.xml and add tools:merge="${applicationId}.some.string" field

Basically you should have a unique provider name (android:authroties) in all of your application apks.

Body:
I'm getting this error:

INSTALL_FAILED_CONFLICTING_PROVIDER - multiple apps using same
  authority provider name

But I don't have any provider on my app, then I noticed that the final AndroidManifest.xml has the following provider:

    <provider
        android:name="com.google.android.gms.measurement.AppMeasurementContentProvider"
        android:authorities="com.google.android.gms.measurement.google_measurement_service"
        android:exported="false" />

This seems an analytics issue on the latest Google Play Services library.

Body:
First of all, The error message you see above happens only when you want to install the same application instance on the same device.

flavors {
   prod {
     applicationId "your.package.name.prod"
   }
   qa {
     applicationId "your.package.name.qa"
   }
}

From the error message you can clearly identify the issue, which occurred due to provider tag in your AndroidManifest.xml file.

Solution:
  1. Identify which provider tag is causing the issue.
  2. Most probably the issue could be android:authroties field.
  3. Extend the same provider in your AndroidManifest.xml and add tools:merge="${applicationId}.some.string" field

Basically you should have a unique provider name (android:authroties) in all of your application apks.


问:
how to use <map> with mouseover to automatically link into another page
I wanted to use MAP so whenever a person hovers the cursor over the area of a picture so he/she automatically links into another page. I cannot seem to figure out. HELP! :(

this is only the partial code. The code is working fine. Thanks in advance!

```<code>document.write('<td> <img src="Ishaharah Plates/p ' + nCount + '.jpg" height="500" width="500" usemap="#green" border="0">');
        document.write('<map name="green">');

        <script>
        function AutoLink(sLink){document.housec.src = sLink}
        </script>

    if(parseInt(nxCount)==16)
        document.write('<area shape="rect" onmouseover="ShowPic(this.href)" coords="375,190,450,240" href="Plate_19_1.php?XCount=' + nxCount + '&Number=1&Count=' + nCount + '&Correct=' + nCorrect + '">');

    if(parseInt(nxCount)==15)
        document.write('<area shape="rect" coords="335,210,385,265" href="Plate_' + nCount + '_1.php?XCount=' + nxCount + '&Number=' + nAnswer + '&Count=' + nCount + '&Correct=' + nCorrect + '">');
</code>```

答:
Assuming you have an href set on the area tag, try onmouseover="window.location.href=this.href"

It would be easier to help you if you isolated the problem and posted a complete example.

Body:
I wanted to use MAP so whenever a person hovers the cursor over the area of a picture so he/she automatically links into another page. I cannot seem to figure out. HELP! :(

this is only the partial code. The code is working fine. Thanks in advance!

document.write(' ');
        document.write('<map name="green">');

    if(parseInt(nxCount)==16)
        document.write('<area shape="rect" onmouseover="ShowPic(this.href)" coords="375,190,450,240" href="Plate_19_1.php?XCount=' + nxCount + '&Number=1&Count=' + nCount + '&Correct=' + nCorrect + '">');

    if(parseInt(nxCount)==15)
        document.write('<area shape="rect" coords="335,210,385,265" href="Plate_' + nCount + '_1.php?XCount=' + nxCount + '&Number=' + nAnswer + '&Count=' + nCount + '&Correct=' + nCorrect + '">');


问:
nodeJS - cannot reach properties of this in constructor function's prototype methods
I am describing properties in the constructor function but when I called the Server.request method in index.js its not showing properties at

```<code>console.log(this)
</code>```

it outputs {} (empty object)

Constructor

```<code>function Server(){
  if(!(this instanceof Server)) return new Server()

  this.actions = { // accepted actions
    login: {
      post: [['email', 'username'], 'password']
    },
    register: {
      post: 'name,surname,password,email,haveLicence,licenceKey'.split(',')
    }
  }
}
</code>```

Request function

```<code>Server.prototype.request = (req /* express request object */)=>{
  console.log(this) // {}
  return new Promise((r,j)=>{
    let action = (req.url.match(/[a-z\-]+/i) || [])[0]

    if(!action) return r([400, 'NoAction']);

    action = this.actions[action] // Cannot read property 'register' of undefined.
...
}
</code>```

答:
This is the nature of es6 arrow functions. They bind this differently.

Try:

```<code>Server.prototype.request = function(req) {
    console.log(this) //
    // etc.
}
</code>```

A simplified example:

function Server() {
  this.string = "hello"
}

Server.prototype.request = function(req) {
  return this.string
}
Server.prototype.request_arrow = (req) => {
  return this.string
}
var s = new Server()

console.log(s.request())
console.log(s.request_arrow())```

Body:
I am describing properties in the constructor function but when I called the Server.request method in index.js its not showing properties at

console.log(this)

it outputs {} (empty object)

Constructor

function Server(){
  if(!(this instanceof Server)) return new Server()

  this.actions = { // accepted actions
    login: {
      post: [['email', 'username'], 'password']
    },
    register: {
      post: 'name,surname,password,email,haveLicence,licenceKey'.split(',')
    }
  }
}

Request function

Server.prototype.request = (req /* express request object */)=>{
  console.log(this) // {}
  return new Promise((r,j)=>{
    let action = (req.url.match(/[a-z\-]+/i) || [])[0]

    if(!action) return r([400, 'NoAction']);

    action = this.actions[action] // Cannot read property 'register' of undefined.
...
}

Body:
This is the nature of es6 arrow functions. They bind this differently.

Try:

Server.prototype.request = function(req) {
    console.log(this) //
    // etc.
}

A simplified example:

function Server() {
  this.string = "hello"
}

Server.prototype.request = function(req) {
  return this.string
}
Server.prototype.request_arrow = (req) => {
  return this.string
}
var s = new Server()

console.log(s.request())
console.log(s.request_arrow())


问:
.NET Core 2 with MySQL on OSX
I'm wanting to develop an ASP.NET Core Web API on VS for OSX (MacBook Pro) and want to connect to MySQL. I downloaded the MySQL.Data NuGet package but when I run the site it gives me errors/warnings that it's built for .NET framework and not built for .NET Core 2 and some other errors about System.Security.Permissions missing and the like.

VS on OSX only runs .NET Core 2 sites from the version I have it looks like, there are no options for .NET Core 1.1 or .NET Framework like VS Community. What I'm wanting to do is connect to my MySQL DB and run queries, I'll need Views/Stored Procs support, what I'm wanting to do will be mixed between ORM tables and running Views/SPs, and I'm not sure if that's available in EF Core.

What do I need to do to get up and running?

I'm already looking at Django/Python as it does what I need, but .NET Core is much sleeker for Web API I think. Would be great to run on VS/OSX as VirtualBox/Win 10/VS 2017 Community is very slow on my machine and not a good solution here.

答:
You may also want to take a look at the DevExpress XPO that was ported to .NET Standard 2.0 a few weeks ago. Previously, this ORM existed for more than a decade, so it is stable and reliable already, because it shares 99% of codebase. To see what creating a Web API may look like, check out this demo: https://github.com/DevExpress/XpoNetCoreDemos/blob/master/XpoASPNETCoreDemo/DevExpress.Xpo.AspNetCoreDemo/Pages/Data.cshtml.cs

Examples for working with direct SQL and SP are given here and there in the online documentation. Mapping persistent classes to database views is also supported. There is also a large support knowledge base with questions answered for the last 13 years or so (see under the Frameworks (XAF & XPO) on the right side). As for tooling, there is a visual designer (for Visual Studio for Windows) and Nuget support for the rest (I think this doc will help you). See this tutorial to get started.

Title: .NET Core 2 with MySQL on OSX


问:
Maven WADL plugin for REST API spanning multiple project
I'm trying the maven-wadl-plugin. (I didn't find any documentation besides the Javadoc.)

My project has the classes used for REST endpoints amongst different Maven modules. And the WADL plugin seems not to be able to reach for them. So running on a single module fails with:

```<code>[ERROR] Failed to execute goal
   com.sun.jersey.contribs:maven-wadl-plugin:1.19.4:generate (generate)
on project bpds-resources: Execution generate of goal com.sun.jersey.contribs:maven-wadl-plugin:1.19.4:generate
failed: A required class was missing while executing
  com.sun.jersey.contribs:maven-wadl-plugin:1.19.4:generate: com/.../common/dto/BoxRequestDto
</code>```

The plugin doesn't support running from the root project either.

1) AFAIK, maven-wadl-plugin parses the sources. My project results in a one big shaded .jar so the plugin could consume that and not care about the internal dependencies. Can I make the plugin scan the artifact instead?

2) Is there a way to make it work over multiple projects?

答:
I figured out that adding the project dependency to the scanned module works. So I have added the attribute with the DTO classes and now it works:</p>

```<code><build>
    <plugins>
        <plugin>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>maven-wadl-plugin</artifactId>
            <version>1.19.4</version>
            <dependencies>
                <dependency>
                    <groupId>org.glassfish.jersey.core</groupId>
                    <artifactId>jersey-server</artifactId>
                    <version>2.25.1</version>
                </dependency>
                <dependency>
                    <groupId>com.fasterxml.jackson.jaxrs</groupId>
                    <artifactId>jackson-jaxrs-json-provider</artifactId>
                    <version>2.8.10</version>
                </dependency>
                <dependency>
                    <groupId>org.glassfish.jersey.media</groupId>
                    <artifactId>jersey-media-multipart</artifactId>
                    <version>2.25.1</version>
                </dependency>
                <dependency>
                    <groupId>com.mycompany.bpds</groupId>
                    <artifactId>bpds-common</artifactId>
                    <version>${project.version}</version>
                </dependency>
            </dependencies>
            <executions>
                <execution>
                    <id>generate</id>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                    <phase>package</phase>

                    <configuration>
                        <wadlFile>${project.build.directory}/endpoints.wadl</wadlFile>
                        <formatWadlFile>true</formatWadlFile>
                        <baseUri>http://localhost:9021/</baseUri>
                        <packagesResourceConfig>
                            <param>com.mycompany.rest</param>
                        </packagesResourceConfig>
                        <wadlGenerators>
                            <!-- Doesn't work wit current version of Xerces.
                            <wadlGeneratorDescription>
                                <className>com.sun.jersey.server.wadl.generators.WadlGeneratorApplicationDoc</className>
                                <properties>
                                    <property>
                                        <name>applicationDocsFile</name>
                                        <value>${project.build.directory}/app-wadl-doc.xml</value>
                                    </property>
                                </properties>
                            </wadlGeneratorDescription>
                            <wadlGeneratorDescription>
                                <className>com.sun.jersey.server.wadl.generators.WadlGeneratorGrammarsSupport</className>
                                <properties>
                                    <property>
                                        <name>grammarsFile</name>
                                        <value>${project.build.directory}/app-wadl-grammar.xml</value>
                                    </property>
                                </properties>
                            </wadlGeneratorDescription>
                            -->
                        </wadlGenerators>
                    </configuration>
                </execution>
            </executions>
        </plugin>
</code>```

Body:
I'm trying the maven-wadl-plugin. (I didn't find any documentation besides the Javadoc.)

My project has the classes used for REST endpoints amongst different Maven modules. And the WADL plugin seems not to be able to reach for them. So running on a single module fails with:

[ERROR] Failed to execute goal
   com.sun.jersey.contribs:maven-wadl-plugin:1.19.4:generate (generate)
on project bpds-resources: Execution generate of goal com.sun.jersey.contribs:maven-wadl-plugin:1.19.4:generate
failed: A required class was missing while executing
  com.sun.jersey.contribs:maven-wadl-plugin:1.19.4:generate: com/.../common/dto/BoxRequestDto

The plugin doesn't support running from the root project either.

1) AFAIK, maven-wadl-plugin parses the sources. My project results in a one big shaded .jar so the plugin could consume that and not care about the internal dependencies. Can I make the plugin scan the artifact instead?

2) Is there a way to make it work over multiple projects?

Body:
I figured out that adding the project dependency to the scanned module works. So I have added the attribute with the DTO classes and now it works:

<build>
    <plugins>
        <plugin>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>maven-wadl-plugin</artifactId>
            <version>1.19.4</version>
            <dependencies>
                <dependency>
                    <groupId>org.glassfish.jersey.core</groupId>
                    <artifactId>jersey-server</artifactId>
                    <version>2.25.1</version>
                </dependency>
                <dependency>
                    <groupId>com.fasterxml.jackson.jaxrs</groupId>
                    <artifactId>jackson-jaxrs-json-provider</artifactId>
                    <version>2.8.10</version>
                </dependency>
                <dependency>
                    <groupId>org.glassfish.jersey.media</groupId>
                    <artifactId>jersey-media-multipart</artifactId>
                    <version>2.25.1</version>
                </dependency>
                <dependency>
                    <groupId>com.mycompany.bpds</groupId>
                    <artifactId>bpds-common</artifactId>
                    <version>${project.version}</version>
                </dependency>
            </dependencies>
            <executions>
                <execution>
                    <id>generate</id>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                    <phase>package</phase>

                    <configuration>
                        <wadlFile>${project.build.directory}/endpoints.wadl</wadlFile>
                        <formatWadlFile>true</formatWadlFile>
                        <baseUri>http://localhost:9021/</baseUri>
                        <packagesResourceConfig>
                            <param>com.mycompany.rest</param>
                        </packagesResourceConfig>
                        <wadlGenerators>
                            <!-- Doesn't work wit current version of Xerces.
                            <wadlGeneratorDescription>
                                <className>com.sun.jersey.server.wadl.generators.WadlGeneratorApplicationDoc</className>
                                <properties>
                                    <property>
                                        <name>applicationDocsFile</name>
                                        <value>${project.build.directory}/app-wadl-doc.xml</value>
                                    </property>
                                </properties>
                            </wadlGeneratorDescription>
                            <wadlGeneratorDescription>
                                <className>com.sun.jersey.server.wadl.generators.WadlGeneratorGrammarsSupport</className>
                                <properties>
                                    <property>
                                        <name>grammarsFile</name>
                                        <value>${project.build.directory}/app-wadl-grammar.xml</value>
                                    </property>
                                </properties>
                            </wadlGeneratorDescription>
                            -->
                        </wadlGenerators>
                    </configuration>
                </execution>
            </executions>
        </plugin>


问:
Uninitialised value was created by a stack allocation,segmentation fault
I am writing to perform and test a binary search. The aim is to get the maximum x when y<=0 for the function y=x-1, and the search range is [-2,2),obviously the answer should be 1.
for test part, I should test if the invocations of function f is less than the calculated max_invoke
a segmentation fault appeared, and when I valgrind it, the error is:

```<code>    ==126667== Use of uninitialised value of size 8
    ==126667==    at 0x400C8A: binarySearchForZero(Function<int, int>*, int,
    int) (in /home/jw562/ece551/092_tests_binsrch/test)
    ==126667==    by 0x400DD5: check(Function<int, int>*, int, int, int,
    char const*) (in /home/jw562/ece551/092_tests_binsrch/test)
    ==126667==    by 0x400E81: main (in
    /home/jw562/ece551/092_tests_binsrch/test)
    ==126667==  Uninitialised value was created by a stack allocation
    ==126667==    at 0x400E41: main (in
    /home/jw562/ece551/092_tests_binsrch/test)
</code>```

below is my code:

```<code>    #include <iostream>
    #include <cstdlib>
    #include <cstdio>
    #include <cmath>

    using namespace std;

    template<typename R, typename A>
    class Function {
    public:
      virtual R invoke(A arg) = 0;
      virtual ~Function() {}
    };

    class CountedIntFn : public Function<int,int>{
    protected:
      unsigned remaining;
      Function<int,int> * f;
      const char * mesg;
    public:
      CountedIntFn(unsigned n, Function<int,int> * fn, const char * m):
      remaining(n),f(fn),mesg(m) {}
      virtual int invoke(int arg) {
        if (remaining == 0) {
          fprintf(stderr,"Too many function invocations in %s\n", mesg);
          exit(EXIT_FAILURE);
      }
      remaining--;
      return f->invoke(arg);
    }

    class linearFunction : public Function<int, int> {
      public:
      virtual int invoke(int arg) {
        int ans = arg-1;
        return ans;
      }
      virtual ~linearFunction(){}
    };

    int binarySearchForZero(Function<int, int> * f, int low, int high){
        if (high <= low){
            cout << "high less or equal than low" << endl;
            return EXIT_FAILURE;
        }
        int low_ans = f->invoke(low);
        int high_ans = f->invoke(high);
        int mid = (high-low)/2+low;
        int mid_ans = f->invoke(mid);
        if (low_ans > 0){
             return low;//all positive
        }
        if (high_ans < 0){
             return high-1;//all negtive
        }
        if (low_ans = high_ans){
             return low;//all zero
        }
        if (mid_ans <= 0){
             low = mid;
        }
        if (mid_ans >= 0){
             high = mid;
        }
        return binarySearchForZero(f,low,high);
      }

      void check(Function<int,int> * f,int low,int high,int
      expected_ans,const char * mesg){
        int max_invoke = 0;//the maximum number of invocations allowed
        if (high > low){
           max_invoke = (int)(log2(high-low))+1;
        }
        else {
           max_invoke = 1;
        }
        CountedIntFn count(max_invoke,f,mesg);
        int ans = binarySearchForZero(f,low,high);
        if (ans != expected_ans){
           cout << "wrong answer" <<endl;
        }
      }

      int main(void){
         linearFunction *fl;
         const char * message = "linearFunction";
         int low = -2;
         int high = 2;
         int expected_ans = 1;
         check(fl,low,high,expected_ans,message);
         return EXIT_SUCCESS;
      }
</code>```

答:
This is because variable fl of type linearFunction* is uninitialized.

You can change it to a non-pointer, and invoke with address-of operator:

```<code>linearFunction fl;
...
check(&fl, low, high, expected_ans, message);
</code>```

Body:
I am writing to perform and test a binary search. The aim is to get the maximum x when y<=0 for the function y=x-1, and the search range is [-2,2),obviously the answer should be 1.
for test part, I should test if the invocations of function f is less than the calculated max_invoke
a segmentation fault appeared, and when I valgrind it, the error is:

    ==126667== Use of uninitialised value of size 8
    ==126667==    at 0x400C8A: binarySearchForZero(Function<int, int>*, int,
    int) (in /home/jw562/ece551/092_tests_binsrch/test)
    ==126667==    by 0x400DD5: check(Function<int, int>*, int, int, int,
    char const*) (in /home/jw562/ece551/092_tests_binsrch/test)
    ==126667==    by 0x400E81: main (in
    /home/jw562/ece551/092_tests_binsrch/test)
    ==126667==  Uninitialised value was created by a stack allocation
    ==126667==    at 0x400E41: main (in
    /home/jw562/ece551/092_tests_binsrch/test)

below is my code:

    #include <iostream>
    #include <cstdlib>
    #include <cstdio>
    #include <cmath>

    using namespace std;

    template<typename R, typename A>
    class Function {
    public:
      virtual R invoke(A arg) = 0;
      virtual ~Function() {}
    };

    class CountedIntFn : public Function<int,int>{
    protected:
      unsigned remaining;
      Function<int,int> * f;
      const char * mesg;
    public:
      CountedIntFn(unsigned n, Function<int,int> * fn, const char * m):
      remaining(n),f(fn),mesg(m) {}
      virtual int invoke(int arg) {
        if (remaining == 0) {
          fprintf(stderr,"Too many function invocations in %s\n", mesg);
          exit(EXIT_FAILURE);
      }
      remaining--;
      return f->invoke(arg);
    }

    class linearFunction : public Function<int, int> {
      public:
      virtual int invoke(int arg) {
        int ans = arg-1;
        return ans;
      }
      virtual ~linearFunction(){}
    };

    int binarySearchForZero(Function<int, int> * f, int low, int high){
        if (high <= low){
            cout << "high less or equal than low" << endl;
            return EXIT_FAILURE;
        }
        int low_ans = f->invoke(low);
        int high_ans = f->invoke(high);
        int mid = (high-low)/2+low;
        int mid_ans = f->invoke(mid);
        if (low_ans > 0){
             return low;//all positive
        }
        if (high_ans < 0){
             return high-1;//all negtive
        }
        if (low_ans = high_ans){
             return low;//all zero
        }
        if (mid_ans <= 0){
             low = mid;
        }
        if (mid_ans >= 0){
             high = mid;
        }
        return binarySearchForZero(f,low,high);
      }

      void check(Function<int,int> * f,int low,int high,int
      expected_ans,const char * mesg){
        int max_invoke = 0;//the maximum number of invocations allowed
        if (high > low){
           max_invoke = (int)(log2(high-low))+1;
        }
        else {
           max_invoke = 1;
        }
        CountedIntFn count(max_invoke,f,mesg);
        int ans = binarySearchForZero(f,low,high);
        if (ans != expected_ans){
           cout << "wrong answer" <<endl;
        }
      }

      int main(void){
         linearFunction *fl;
         const char * message = "linearFunction";
         int low = -2;
         int high = 2;
         int expected_ans = 1;
         check(fl,low,high,expected_ans,message);
         return EXIT_SUCCESS;
      }

Body:
This is because variable fl of type linearFunction* is uninitialized.

You can change it to a non-pointer, and invoke with address-of operator:

linearFunction fl;
...
check(&fl, low, high, expected_ans, message);


问:
Merge multiple variables in R
I have a dataset such that the same variable is contained in difference columns for each subject. I want to merge them to the same columns.

E.g.:, I have this dataframe, and there are three DVs, but they are in different columns (A,B,C) for different subjects.

```<code>data.frame(ID = c(1,2,3), DV1_A=c(1,NA,NA), DV1_B= c(NA,4,NA), DV1_C = c(NA,NA,5), DV2_A=c(3,NA,NA), DV2_B=c(NA,3,NA), DV2_C=c(NA,NA,5), FACT = c("A","B","C"))
</code>```

How can I merge them to just two columns? so the result is:

```<code>data.frame(ID = c(1,2,3), DV1_A=c(1,NA,NA), DV1_B= c(NA,4,NA), DV1_C = c(NA,NA,5), DV2_A=c(3,NA,NA), DV2_B=c(NA,3,NA), DV2_C=c(NA,NA,5), FACT = c("A","B","C"), DV_1 = c(1,4,5), DV_2 = c(3,3,5))
</code>```

答:
Another solution similar to @userR, but rather than creating each column individually, this creates a list of expressions that get evaluated all at once. It may still suffer the same "don't splice data frames into calls with !!!" fault that was mentioned in the comments since it uses select(.), but I thought I would post anyways.

library(rlang)
library(dplyr)

df <- data.frame(ID = c(1,2,3), DV1_A=c(1,NA,NA),
                 DV1_B= c(NA,4,NA), DV1_C = c(NA,NA,5),
                 DV2_A=c(3,NA,NA), DV2_B=c(NA,3,NA),
                 DV2_C=c(NA,NA,5), FACT = c("A","B","C"))

create_DV <- function(num) {
  DV_name <- sym(paste0("DV_", num))
  DV_char <- paste0("DV", num)

  expr(!! DV_name := select(., contains(!! DV_char)) %>% rowSums(na.rm = TRUE))
}

DV_expr_list <- c(1,2) %>%
  lapply(create_DV)

df %>%
  mutate(
    !!! DV_expr_list
  )
#>   ID DV1_A DV1_B DV1_C DV2_A DV2_B DV2_C FACT DV_1 DV_2
#> 1  1     1    NA    NA     3    NA    NA    A    1    3
#> 2  2    NA     4    NA    NA     3    NA    B    4    3
#> 3  3    NA    NA     5    NA    NA     5    C    5    5
```

Title: Merge multiple variables in R

Body:
I have a dataset such that the same variable is contained in difference columns for each subject. I want to merge them to the same columns.

E.g.:, I have this dataframe, and there are three DVs, but they are in different columns (A,B,C) for different subjects.

data.frame(ID = c(1,2,3), DV1_A=c(1,NA,NA), DV1_B= c(NA,4,NA), DV1_C = c(NA,NA,5), DV2_A=c(3,NA,NA), DV2_B=c(NA,3,NA), DV2_C=c(NA,NA,5), FACT = c("A","B","C"))

How can I merge them to just two columns? so the result is:

data.frame(ID = c(1,2,3), DV1_A=c(1,NA,NA), DV1_B= c(NA,4,NA), DV1_C = c(NA,NA,5), DV2_A=c(3,NA,NA), DV2_B=c(NA,3,NA), DV2_C=c(NA,NA,5), FACT = c("A","B","C"), DV_1 = c(1,4,5), DV_2 = c(3,3,5))


问:
networkx, moore-neighbourhood, shortest path issue
I am trying to build a rectangular graph in a Moore-neighbourhood. Within that, I am searching for the shortest path (nx.shortest_path) but get strange (zig-zag) .

I am quite sure, the reason for that is how i build the graph, but dont find the problem.

First, I build the Grid and the nodes:

```<code>#Building the Grid and the nodes
resolution = 1
length = 10
index = 0
xGrid = np.arange(0, length+1, resolution)
yGrid = np.arange(0, length+1, resolution)
G = nx.Graph()
print(xGrid)
meshNumber = np.zeros((length, length))
for i in range(length):
    for j in range(length):
        G.add_node(index, pos=(
            xGrid[j], yGrid[i]))
        meshNumber[j,i] = index
        index += 1
</code>```

Then, i calcuate the edges and its weights

```<code># Building the edges
diag = np.sqrt(2) * resolution
for i in range(1, length-2):
    for j in range(1, length-2):
        if meshNumber[j, i]:
            if meshNumber[j - 1, i]:
                G.add_edge(
                    meshNumber[j, i], meshNumber[j - 1, i], weight=resolution)
            if meshNumber[j + 1, i]:
                G.add_edge(
                    meshNumber[j, i], meshNumber[j + 1, i], weight=resolution)
            if meshNumber[j, i - 1]:
                G.add_edge(
                    meshNumber[j, i], meshNumber[j, i - 1], weight=resolution)
            if meshNumber[j, i + 1]:
                G.add_edge(
                    meshNumber[j, i], meshNumber[j, i + 1], weight=resolution)
            if meshNumber[j - 1, i - 1]:
                G.add_edge(
                    meshNumber[j, i], meshNumber[j - 1, i - 1], weight=diag)
            if meshNumber[j - 1, i + 1]:
                G.add_edge(
                    meshNumber[j, i], meshNumber[j - 1, i + 1], weight=diag)
            if meshNumber[j + 1, i + 1]:
                G.add_edge(
                    meshNumber[j, i], meshNumber[j + 1, i + 1], weight=diag)
            if meshNumber[j + 1, i - 1]:
                G.add_edge(
                    meshNumber[j, i], meshNumber[j + 1, i - 1], weight=diag)
</code>```

searching for the path:

```<code># Finding the path
start = 5
end = 66
try:
    path = set(nx.shortest_path(G, start, end))

except nx.exception.NetworkXNoPath:
    raise AssertionError("Could not find a good Path")
</code>```

plotting:

```<code># Plotting
flatten = np.ones((index), dtype=np.int)
for p in path:
    flatten[int(p)] = 900
flatten[start] = 1000
flatten[end] = 1000
colors = []
for f in flatten:
    colors.append(str(f))
pos = nx.get_node_attributes(G, 'pos')
fig = plt.figure(1, figsize=(12, 12), dpi=90)
ax = fig.add_subplot(111)
pos = nx.get_node_attributes(G, 'pos')
nx.draw_networkx_nodes(G, pos, node_color=colors, node_size=500, alpha=0.8,
                       linewidths=3)
nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5)
nx.draw_networkx_edges(G, pos, width=4, alpha=0.5, edge_color='#6985a5')
labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
plt.savefig("zigzag.png")
plt.show()
</code>```

答:
That strange zigzag is a valid shortest path of 6 edges, I don't see what is the problem. On the other hand the zigzag is not the shortest path if we take into account the weight of the edges. For which case you must use:

```<code>try:
    path = set(nx.shortest_path(G, start, end, weight='weight'))

except nx.exception.NetworkXNoPath:
    raise AssertionError("Could not find a good Path")
</code>```

Giving you the following path:

Body:
I am trying to build a rectangular graph in a Moore-neighbourhood. Within that, I am searching for the shortest path (nx.shortest_path) but get strange (zig-zag) .

I am quite sure, the reason for that is how i build the graph, but dont find the problem.

First, I build the Grid and the nodes:

#Building the Grid and the nodes
resolution = 1
length = 10
index = 0
xGrid = np.arange(0, length+1, resolution)
yGrid = np.arange(0, length+1, resolution)
G = nx.Graph()
print(xGrid)
meshNumber = np.zeros((length, length))
for i in range(length):
    for j in range(length):
        G.add_node(index, pos=(
            xGrid[j], yGrid[i]))
        meshNumber[j,i] = index
        index += 1

Then, i calcuate the edges and its weights

# Building the edges
diag = np.sqrt(2) * resolution
for i in range(1, length-2):
    for j in range(1, length-2):
        if meshNumber[j, i]:
            if meshNumber[j - 1, i]:
                G.add_edge(
                    meshNumber[j, i], meshNumber[j - 1, i], weight=resolution)
            if meshNumber[j + 1, i]:
                G.add_edge(
                    meshNumber[j, i], meshNumber[j + 1, i], weight=resolution)
            if meshNumber[j, i - 1]:
                G.add_edge(
                    meshNumber[j, i], meshNumber[j, i - 1], weight=resolution)
            if meshNumber[j, i + 1]:
                G.add_edge(
                    meshNumber[j, i], meshNumber[j, i + 1], weight=resolution)
            if meshNumber[j - 1, i - 1]:
                G.add_edge(
                    meshNumber[j, i], meshNumber[j - 1, i - 1], weight=diag)
            if meshNumber[j - 1, i + 1]:
                G.add_edge(
                    meshNumber[j, i], meshNumber[j - 1, i + 1], weight=diag)
            if meshNumber[j + 1, i + 1]:
                G.add_edge(
                    meshNumber[j, i], meshNumber[j + 1, i + 1], weight=diag)
            if meshNumber[j + 1, i - 1]:
                G.add_edge(
                    meshNumber[j, i], meshNumber[j + 1, i - 1], weight=diag)

searching for the path:

# Finding the path
start = 5
end = 66
try:
    path = set(nx.shortest_path(G, start, end))

except nx.exception.NetworkXNoPath:
    raise AssertionError("Could not find a good Path")

plotting:

# Plotting
flatten = np.ones((index), dtype=np.int)
for p in path:
    flatten[int(p)] = 900
flatten[start] = 1000
flatten[end] = 1000
colors = []
for f in flatten:
    colors.append(str(f))
pos = nx.get_node_attributes(G, 'pos')
fig = plt.figure(1, figsize=(12, 12), dpi=90)
ax = fig.add_subplot(111)
pos = nx.get_node_attributes(G, 'pos')
nx.draw_networkx_nodes(G, pos, node_color=colors, node_size=500, alpha=0.8,
                       linewidths=3)
nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5)
nx.draw_networkx_edges(G, pos, width=4, alpha=0.5, edge_color='#6985a5')
labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
plt.savefig("zigzag.png")
plt.show()

Body:
That strange zigzag is a valid shortest path of 6 edges, I don't see what is the problem. On the other hand the zigzag is not the shortest path if we take into account the weight of the edges. For which case you must use:

try:
    path = set(nx.shortest_path(G, start, end, weight='weight'))

except nx.exception.NetworkXNoPath:
    raise AssertionError("Could not find a good Path")

Giving you the following path:


问:
Access VBA Pop Up Sub Form for Submission of Entries
Here's what I've got:
I have an Access form that accepts entries, and places them into a table when the ENTER button is clicked.  At the moment, I have a popup message box that comes up when the button is clicked, asking them to confirm that their entries are ok (your standard pop up box, with OK and CANCEL options).  This popup box comes up right in the middle of the data that the user has entered, and is pretty inconvenient for the user to deal with.

Instead of this popup message box, I came up with the idea of using a pop-up SUB-FORM, that would lie invisible just under the ENTER button, and would come up visible when ENTER is clicked. (Same options as the message box, etc, just different placement.  Making the "physical" subform design was a no brainer).  Since this is a new form/subform, how would I code this in order to make it work like the message box did?  The old code won't work.  This is the best idea I could come up with.  If there's an even better way to accomplish this, I'm open to suggestions...

答:
This is an atypical approach, but not necessarily a wrong one. I don't see  why you would need the overhead of a sub_form though. Maybe just create a normal form (modal, no menu controls, no borders, etc., whatever looks pleasing to you) to serve as your Confirm Dialog, use a DoCmd.OpenForm from your Save button to open in (with modal attribute set), and then a DoCmd.MoveSize to move it, with parameters that are derived from the position of your button.

```<code>DoCmd.MoveSize cmdSaveButton.Left + cmdSaveButton.Height + 10, etc.
</code>```

The Primary Save can happen from the Popup form calling a method in the originating form, and then closing itself.

https://msdn.microsoft.com/en-us/vba/access-vba/articles/docmd-movesize-method-access

Or use the form itself:

```<code>Form.Move Left:=11500, Top:=6500, Width:=7000, Height:=6000
</code>```

Body:
This is an atypical approach, but not necessarily a wrong one. I don't see  why you would need the overhead of a sub_form though. Maybe just create a normal form (modal, no menu controls, no borders, etc., whatever looks pleasing to you) to serve as your Confirm Dialog, use a DoCmd.OpenForm from your Save button to open in (with modal attribute set), and then a DoCmd.MoveSize to move it, with parameters that are derived from the position of your button.

DoCmd.MoveSize cmdSaveButton.Left + cmdSaveButton.Height + 10, etc.

The Primary Save can happen from the Popup form calling a method in the originating form, and then closing itself.

https://msdn.microsoft.com/en-us/vba/access-vba/articles/docmd-movesize-method-access

Or use the form itself:

Form.Move Left:=11500, Top:=6500, Width:=7000, Height:=6000


问:
What is the usefulness of `enable_shared_from_this`?
I ran across enable_shared_from_this while reading the Boost.Asio examples and after reading the documentation I am still lost for how this should correctly be used.  Can someone please give me an example and explanation of when using this class makes sense.

答:
It's exactly the same in c++11 and later: It is to enable the ability to return this as a shared pointer since this gives you a raw pointer.

in other word, it allows you to turn code like this

```<code>class Node {
public:
    Node* getParent const() {
        if (m_parent) {
            return m_parent;
        } else {
            return this;
        }
    }

private:

    Node * m_parent = nullptr;
};
</code>```

into this:

```<code>class Node : std::enable_shared_from_this<Node> {
public:
    std::shared_ptr<Node> getParent const() {
        std::shared_ptr<Node> parent = m_parent.lock();
        if (parent) {
            return parent;
        } else {
            return shared_from_this();
        }
    }

private:

    std::weak_ptr<Node> m_parent;
};
</code>```

OwnerDisplayName: MGoDave

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: MGoDave

Body:
It's exactly the same in c++11 and later: It is to enable the ability to return this as a shared pointer since this gives you a raw pointer.

in other word, it allows you to turn code like this

class Node {
public:
    Node* getParent const() {
        if (m_parent) {
            return m_parent;
        } else {
            return this;
        }
    }

private:

    Node * m_parent = nullptr;
};

into this:

class Node : std::enable_shared_from_this<Node> {
public:
    std::shared_ptr<Node> getParent const() {
        std::shared_ptr<Node> parent = m_parent.lock();
        if (parent) {
            return parent;
        } else {
            return shared_from_this();
        }
    }

private:

    std::weak_ptr<Node> m_parent;
};


问:
Windows 10 Pip No Output
I have installed pip on my Windows 10 laptop the same way I have been doing for the past few years (via python -m pip install -U pip setuptools). The weird part is, on my laptop, Pip causes no output. It just causes a blank line. For example

```<code>C:\Users\...> pip install hvjkdfghfdkghdkgf

C:\Users\...>
</code>```

When it should throw an error that the module hvjkdfghfdkghdkgf does not exist.

I have read that you must edit the configuration file, but when I checked where the configuration file should be, there was none to be found. I tried creating the configuration file, and there was no change (I do not remember where, as this was over a month ago, sorry).

I have tried pip install ___ -v, and pip install ___ --verbose as found on the pip website: https://packaging.python.org/tutorials/installing-packages/#install-pip-setuptools-and-wheel, and still no luck.

Thanks in advance.

[EDIT]

By the way, It still installs modules, I just want to be able to see the progress of the installation, and if the module was even found.

答:
I uninstalled pip:

```<code>python -m pip uninstall pip setuptools
</code>```

And then followed the instructions here:
https://pip.pypa.io/en/stable/installing/#do-i-need-to-install-pip

By first downloading setup.py from https://bootstrap.pypa.io/get-pip.py, and running > python get-pip.py in the command line in the directory where the python file is saved.

Thanks anyways.

Title: Windows 10 Pip No Output

Body:
I have installed pip on my Windows 10 laptop the same way I have been doing for the past few years (via python -m pip install -U pip setuptools). The weird part is, on my laptop, Pip causes no output. It just causes a blank line. For example

C:\Users\...> pip install hvjkdfghfdkghdkgf

C:\Users\...>

When it should throw an error that the module hvjkdfghfdkghdkgf does not exist.

I have read that you must edit the configuration file, but when I checked where the configuration file should be, there was none to be found. I tried creating the configuration file, and there was no change (I do not remember where, as this was over a month ago, sorry).

I have tried pip install ___ -v, and pip install ___ --verbose as found on the pip website: https://packaging.python.org/tutorials/installing-packages/#install-pip-setuptools-and-wheel, and still no luck.

Thanks in advance.

[EDIT]

By the way, It still installs modules, I just want to be able to see the progress of the installation, and if the module was even found.

Body:
I uninstalled pip:

python -m pip uninstall pip setuptools

And then followed the instructions here:
https://pip.pypa.io/en/stable/installing/#do-i-need-to-install-pip

By first downloading setup.py from https://bootstrap.pypa.io/get-pip.py, and running > python get-pip.py in the command line in the directory where the python file is saved.

Thanks anyways.


问:
WHERE all IS NOT NULL
How can I run a MySQL query that selects everything that is not null? It would be something like

```<code>SELECT * FROM schedule WHERE ((all)) IS NOT NULL
</code>```

Do I just remove the all and go..?

```<code>SELECT * FROM schedule WHERE IS NOT NULL
</code>```

答:
Use XML so you don't have to iterate through all your columns:</p>

```<code>--Your Source Table
CREATE TABLE [dbo].[schedule](
    [id] [nchar](10) NULL,
    [col1] [nchar](10) NULL,
    [col2] [nchar](10) NULL,
    [col3] [nchar](10) NULL
) ON [PRIMARY]

--I know my result should show items NOT NULL, like id:2,col1,val:'a'
  INSERT INTO [schedule](id,col1,col2,col3)
  values
  (1,null,null,null),
  (2,'a',null,null),
  (3,null,'b',null),
  (4,null,null,null),
  (5,null,null,'c')

--temp placeholder table
CREATE TABLE #tempsch (id VARCHAR(max) not null, schColumns XML)

--Load temp table with XML version of your table
INSERT INTO #tempsch (id, schColumns)
        SELECT  s.id,
            (   SELECT *
                FROM    [schedule] AS x
                WHERE   x.id = s.id
                FOR XML PATH('bar'), TYPE, ROOT('foo')
            ) AS xml_format_string
        FROM [schedule] AS s

--This select should return all values Where all is NOT NULL
SELECT id,
sd.c.value('local-name(.)', 'VARCHAR(MAX)') AS elementName,
sd.c.value('.', 'VARCHAR(MAX)') AS elementValue
FROM #tempsch s
CROSS APPLY schColumns.nodes('/foo/bar/*') sd(c)
WHERE
sd.c.value('local-name(.)', 'VARCHAR(MAX)') <> 'id'
</code>```

Title: WHERE all IS NOT NULL

Body:
How can I run a MySQL query that selects everything that is not null? It would be something like

SELECT * FROM schedule WHERE ((all)) IS NOT NULL

Do I just remove the all and go..?

SELECT * FROM schedule WHERE IS NOT NULL

Body:
Use XML so you don't have to iterate through all your columns:

--Your Source Table
CREATE TABLE [dbo].[schedule](
    [id] [nchar](10) NULL,
    [col1] [nchar](10) NULL,
    [col2] [nchar](10) NULL,
    [col3] [nchar](10) NULL
) ON [PRIMARY]

--I know my result should show items NOT NULL, like id:2,col1,val:'a'
  INSERT INTO [schedule](id,col1,col2,col3)
  values
  (1,null,null,null),
  (2,'a',null,null),
  (3,null,'b',null),
  (4,null,null,null),
  (5,null,null,'c')

--temp placeholder table
CREATE TABLE #tempsch (id VARCHAR(max) not null, schColumns XML)

--Load temp table with XML version of your table
INSERT INTO #tempsch (id, schColumns)
        SELECT  s.id,
            (   SELECT *
                FROM    [schedule] AS x
                WHERE   x.id = s.id
                FOR XML PATH('bar'), TYPE, ROOT('foo')
            ) AS xml_format_string
        FROM [schedule] AS s

--This select should return all values Where all is NOT NULL
SELECT id,
sd.c.value('local-name(.)', 'VARCHAR(MAX)') AS elementName,
sd.c.value('.', 'VARCHAR(MAX)') AS elementValue
FROM #tempsch s
CROSS APPLY schColumns.nodes('/foo/bar/*') sd(c)
WHERE
sd.c.value('local-name(.)', 'VARCHAR(MAX)') <> 'id'


问:
scraping a single html table in python using find
I am absolutely new to python and am trying to scrape a single table from a webpage.  I have accessed the html via "inspect" in Chrome.  The web page is here:

https://www.basketball-reference.com/players/a/abdelal01.html

The following is the code I have used

```<code>import bs4
from urllib2 import urlopen as uReq
from bs4 import BeautifulSoup as soup

#name a page to scrape
my_url = 'https://www.basketball-reference.com/players/a/abdelal01.html'

uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

#perform html parsing
page_soup = soup(page_html, "html.parser")
</code>```

There is a table on the page called "Salaries".  I would like to scrape this table, along with the Title of the page and eventually put them in a csv file.  However, I first need to get the salary table.  I have been trying to use the find function from BeautifulSoup since it's only one table that I am interested in. The problem is that I get no results when I run the following code:

```<code>page_soup.find("table", id = "all_salaries")
</code>```

I am using Chrome and when I use the "inspect" tool on the table it looks like the id is "all_salaries" but I am getting no results.  Is there a reason why I am getting no results?  What is the proper way to do this?

答:
This can be accomplished via csv writer and the find_all function.

```<code>import bs4, csv
from urllib2 import urlopen as uReq
from bs4 import BeautifulSoup as soup

#name a page to scrape
my_url = 'https://www.basketball-reference.com/players/a/abdelal01.html'

uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

#perform html parsing
page_soup = soup(page_html, "html.parser")

with open('csvOut.csv','w') as myFile:
    writer = csv.writer(myFile, lineterminator='\n')
    table = page_soup.find({"class" : "full_table"})
    for row in page_soup.find_all("tr"):
        rowTds = [td.text for td in row.find_all("td")]
        if len(rowTds):
            writer.writerow(rowTds)
</code>```

Body:
I am absolutely new to python and am trying to scrape a single table from a webpage.  I have accessed the html via "inspect" in Chrome.  The web page is here:

https://www.basketball-reference.com/players/a/abdelal01.html

The following is the code I have used

import bs4
from urllib2 import urlopen as uReq
from bs4 import BeautifulSoup as soup

#name a page to scrape
my_url = 'https://www.basketball-reference.com/players/a/abdelal01.html'

uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

#perform html parsing
page_soup = soup(page_html, "html.parser")

There is a table on the page called "Salaries".  I would like to scrape this table, along with the Title of the page and eventually put them in a csv file.  However, I first need to get the salary table.  I have been trying to use the find function from BeautifulSoup since it's only one table that I am interested in. The problem is that I get no results when I run the following code:

page_soup.find("table", id = "all_salaries")

I am using Chrome and when I use the "inspect" tool on the table it looks like the id is "all_salaries" but I am getting no results.  Is there a reason why I am getting no results?  What is the proper way to do this?

Body:
This can be accomplished via csv writer and the find_all function.

import bs4, csv
from urllib2 import urlopen as uReq
from bs4 import BeautifulSoup as soup

#name a page to scrape
my_url = 'https://www.basketball-reference.com/players/a/abdelal01.html'

uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

#perform html parsing
page_soup = soup(page_html, "html.parser")

with open('csvOut.csv','w') as myFile:
    writer = csv.writer(myFile, lineterminator='\n')
    table = page_soup.find({"class" : "full_table"})
    for row in page_soup.find_all("tr"):
        rowTds = [td.text for td in row.find_all("td")]
        if len(rowTds):
            writer.writerow(rowTds)


问:
What reference do I need to call UpdateModel?
I am trying to use UpdateModel in a class other than my controller and it doesn't work.
When I call UpdateModel in my controller class it works perfectly. The references are the same in both classes.

Would someone please help me out on this?

答: Unfortunately this is not a reference issue.  Your controller inherits from Controller which has a virtual UpdateModel method.  This allows you to call the method in a derived class.  This method will only be available in other types that inherit from Controller and in instances of Controller itself.

LastEditorDisplayName: Andrew Hare

OwnerDisplayName: Andrew Hare


问:
How to think about O(nlogn) solution in the first shot?
I always come up with a solution which is O(n^2) (brute force) but I never get to O(nlogn) or O(n) in the first few mins or after some time when I read through the problem (thought process I meant). For larger data sets the O(n^2) always fails. How to approach in thinking of a problem to gain optimal solution. Could you share some thoughts about this. Here is one problem I am working on which gets timed out for larger data sets (full description here).

Code :-

```<code>import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    static int pairs(int[] a,int k) {

        if( a.length==0 || a==null )
        return 0;

        int counter=0;

        for( int i=0;i<a.length;i++ ){
            for( int j=i+1;j<a.length;j++) {
                if( Math.abs(a[i]-a[j])==k )
                    counter++;
            }
        }
        return counter;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int res;

        String n = in.nextLine();
        String[] n_split = n.split(" ");

        int _a_size = Integer.parseInt(n_split[0]);
        int _k = Integer.parseInt(n_split[1]);

        int[] _a = new int[_a_size];
        int _a_item;
        String next = in.nextLine();
        String[] next_split = next.split(" ");

        for(int _a_i = 0; _a_i < _a_size; _a_i++) {
            _a_item = Integer.parseInt(next_split[_a_i]);
            _a[_a_i] = _a_item;
        }

        res = pairs(_a,_k);
        System.out.println(res);
    }
}
</code>```

答:
One thing I do is sit down and look for how you would solve the problem as a human. Look for shortcuts, or patterns.

In this problem you are looking for two numbers that are k apart. Iterate through the numbers. As you go, add them to a set. Then if that number plus or minus k is in the set, increase your counter.

Pseudocode:

```<code>Set<Integer> set;
for(int i:a){
  set.add(i);
  if(set.contains(i-k)
    counter++;
  if(set.contains(i+k)
    counter++;
}
Return counter;
</code>```

O(n) solution

Body:
I always come up with a solution which is O(n^2) (brute force) but I never get to O(nlogn) or O(n) in the first few mins or after some time when I read through the problem (thought process I meant). For larger data sets the O(n^2) always fails. How to approach in thinking of a problem to gain optimal solution. Could you share some thoughts about this. Here is one problem I am working on which gets timed out for larger data sets (full description here).

Code :-

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    static int pairs(int[] a,int k) {

        if( a.length==0 || a==null )
        return 0;

        int counter=0;

        for( int i=0;i<a.length;i++ ){
            for( int j=i+1;j<a.length;j++) {
                if( Math.abs(a[i]-a[j])==k )
                    counter++;
            }
        }
        return counter;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int res;

        String n = in.nextLine();
        String[] n_split = n.split(" ");

        int _a_size = Integer.parseInt(n_split[0]);
        int _k = Integer.parseInt(n_split[1]);

        int[] _a = new int[_a_size];
        int _a_item;
        String next = in.nextLine();
        String[] next_split = next.split(" ");

        for(int _a_i = 0; _a_i < _a_size; _a_i++) {
            _a_item = Integer.parseInt(next_split[_a_i]);
            _a[_a_i] = _a_item;
        }

        res = pairs(_a,_k);
        System.out.println(res);
    }
}

Body:
One thing I do is sit down and look for how you would solve the problem as a human. Look for shortcuts, or patterns.

In this problem you are looking for two numbers that are k apart. Iterate through the numbers. As you go, add them to a set. Then if that number plus or minus k is in the set, increase your counter.

Pseudocode:

Set<Integer> set;
for(int i:a){
  set.add(i);
  if(set.contains(i-k)
    counter++;
  if(set.contains(i+k)
    counter++;
}
Return counter;

O(n) solution


问:
PHP SQL - Json like search
I'm sending json via dataloader like this:

```<code>{"person":{"name":[{"tag":"peter"},{"tag":"frank"},{"tag":"jeff"}]}}
</code>```

I have the below query and as of right now I filter by exact values. But how do I search 'like' for the values this example?

php:

```<code>...

$arr = json_decode($data,true);

$name = $arr['person']['name'];
foreach($name as $t=>$tag){
    $name[] = $tag['tag'];
}

$query = "SELECT name, id
          FROM accounts
          WHERE visible != '1'";
if ($name) {
    $query.=" AND name IN ('".implode("', '", $name)."')";
}
    $query.=" ORDER BY name DESC";

...
</code>```

答:
Adding an OR and the REGEXP function will allow both exact and like.</p>

```<code>$query.=" AND name IN ('".implode(', ', $name)."') OR name REGEXP ('".implode('|', $name)."')";
</code>```

Title: PHP SQL - Json like search

Body:
I'm sending json via dataloader like this:

{"person":{"name":[{"tag":"peter"},{"tag":"frank"},{"tag":"jeff"}]}}

I have the below query and as of right now I filter by exact values. But how do I search 'like' for the values this example?

php:

...

$arr = json_decode($data,true);

$name = $arr['person']['name'];
foreach($name as $t=>$tag){
    $name[] = $tag['tag'];
}

$query = "SELECT name, id
          FROM accounts
          WHERE visible != '1'";
if ($name) {
    $query.=" AND name IN ('".implode("', '", $name)."')";
}
    $query.=" ORDER BY name DESC";

...

Body:
Adding an OR and the REGEXP function will allow both exact and like.

$query.=" AND name IN ('".implode(', ', $name)."') OR name REGEXP ('".implode('|', $name)."')";