问:
clock_monotonic_raw alternative in linux versions older than 2.6.28
clock_monotonic_raw is only supported as of Linux 2.6.28.

is there another way i can get a monotonic time which isn't subject to NTP adjustments or the incremental adjustments performed by adjtime?
i can't use clock_monotonic since it's affected by NTP & adjtime.

答:
Take a closer look at CLOCK_MONOTONIC instead of just CLOCK_MONOTONIC_RAW.  I wanted to use CLOCK_MONOTONIC_RAW with condition waits, but found that it was not supported (Fedora 25/Linux 4.10.17).

The situation is vaguely infuriating, but the upshot on Linux, to the best of my current understanding, is:

CLOCK_MONOTONIC_RAW is the closest you are going to get to a square-wave accumulator running at constant frequency.  However, this is well-suited to less than you might think.

CLOCK_MONOTONIC is based on CLOCK_MONOTONIC_RAW with some gradual frequency corrections applied that allow it to eventually overtake or fall behind some other clock reference.  NTP and adjtime can both make these corrections.  However, to avoid doing things like breaking the hell out of software builds, the clock is still guaranteed to monotonically advance:

"The adjustment that adjtime() makes to the clock is carried out in such a manner that the clock is always monotonically increasing."
--adjtime man page

"You lying bastard." --me

Yup-- that was the plan, but bugs exist in kernel versions before 2.6.32.19; see discussion here: https://stackoverflow.com/a/3657433/3005946 which includes a link to a patch, if that affects you.  It's hard for me to tell what the maximum error from that bug is (and I'd really, really like to know).

Even in the 4.x kernel, most POSIX synchronization objects don't seem to support CLOCK_MONOTONIC_RAW or CLOCK_MONOTONIC_COARSE.  I have found this out the hard way.  ALWAYS error-check your *_setclock calls.

POSIX semaphores (sem_t) don't support ANY monotonic clocks at all, which is infuriating.  If you need this, you will have to roll your own using condition-waits.  (As a bonus, doing this will allow you to have semaphores with negative initial levels, which can be handy.)

If you're just trying to keep a synchronization object's wait-function from deadlocking forever, and you've got something like a three-second bailout, you can just use CLOCK_MONOTONIC and call it a day-- the adjustments CLOCK_MONOTONIC is subject to are, effectively, jitter correction, well-below your accuracy requirements.  Even in the buggy implementations, CLOCK_MONOTONIC is not going to jump backwards an hour or something like that.  Again, what happens instead is that things like adjtime tweak the frequency of the clock, so that it gradually overtakes, or falls behind, some other, parallel-running clock.

CLOCK_REALTIME is in fact CLOCK_MONOTONIC with some other correction factors applied.  Or the other way around.  Whatever, it's effectively the same thing.  The important part is that, if there is any chance your application will change time zones (moving vehicle, aircraft, ship, cruise missile, rollerblading cyborg) or encounter administrative clock adjustments, you should definitely NOT use CLOCK_REALTIME, or anything that requires it.  Same thing if the server uses daylight savings time instead of UTC.  However, a stationary server using UTC may be able to get away with CLOCK_REALTIME for coarse deadlock-avoidance purposes, if necessary. Avoid this unless you are on a pre-2.6 kernel and have no choice, though.

CLOCK_MONOTONIC_RAW is NOT something you want to use for timestamping.  It has not been jitter-corrected yet, etc.  It may be appropriate for DACs and ADCs, etc., but is not what you want to use for logging events on human-discernible time scales.  We have NTP for a reason.

Hope this is helpful, and I can certainly understand the frustration.


来源: stackexchange

问:
How do I set the containment on a jQuery UI Dialog?
Is it possible to add containment (confining to the boundary of another element) to jQuery UI's Dialog?</p>

答:
@Mac's on the right track, but the solution is not complete. You must also set the containment of the dialog's Resizable widget. If you only set the Draggable, you'll get containment when you drag, but when you grab the edges and resize you'll still go out of bounds.

So you'll want to do this, assuming #mydialog is the element you initially created the dialog from, and #boundary is the element you wish to confine it to (by the way, the container parameter can also be a selector):

let ui = $('#mydialog').closest('.ui-dialog');       // get parent frame
ui.draggable('option', 'containment', '#boundary');  // <-- drag, but not resize
ui.resizable('option', 'containment', '#boundary');  // <-- don't forget!!!
```

<hr>

<p>Here's an example snippet, toggle the checkboxes to switch the corresponding widget's confinement between <code>'document'</code> (the default), and <code>'#area'</code>. Then experiment both with dragging the dialog by its title bar, <em>and</em> resizing it by its edges. Note what happens when you only select "Confine drag":</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Create dialog from #win with mostly default options.
$('#win').dialog({
  width: 200,
  height: 150,
  position: { my: 'center', at: 'center', of: '#area' }
});

// When checkbox changed, update confinement settings.
$('#draggable, #resizable').change(function () {
  let d = $('#draggable').prop('checked');
  let r = $('#resizable').prop('checked');
  let ui = $('#win').closest('.ui-dialog');
  ui.draggable('option', 'containment', d ? '#area' : 'document');
  ui.resizable('option', 'containment', r ? '#area' : 'document');
});</code>```

#area {
  position: relative;
  left: 2ex;
  top: 2ex;
  width: 400px;
  height: 300px;
  border: 1px solid red;
}

#win {
  font-size: 10pt;
  display: flex;
  flex-direction: column;
}

label {
  display: flex;
  align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
  <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</head>

<body>
  <div>Example</div>
  <div id="area"></div>
  <div id="win" title="test">
    <label><input type="checkbox" id="draggable">Contain drag</label>
    <label><input type="checkbox" id="resizable">Contain resize</label>
  </div>
</body></code>```

ContentLicense: CC BY-SA 3.0

Body:
@Mac's on the right track, but the solution is not complete. You must also set the containment of the dialog's Resizable widget. If you only set the Draggable, you'll get containment when you drag, but when you grab the edges and resize you'll still go out of bounds.

So you'll want to do this, assuming #mydialog is the element you initially created the dialog from, and #boundary is the element you wish to confine it to (by the way, the container parameter can also be a selector):

let ui = $('#mydialog').closest('.ui-dialog');       // get parent frame
ui.draggable('option', 'containment', '#boundary');  // <-- drag, but not resize
ui.resizable('option', 'containment', '#boundary');  // <-- don't forget!!!

Here's an example snippet, toggle the checkboxes to switch the corresponding widget's confinement between 'document' (the default), and '#area'. Then experiment both with dragging the dialog by its title bar, and resizing it by its edges. Note what happens when you only select "Confine drag":

// Create dialog from #win with mostly default options.
$('#win').dialog({
  width: 200,
  height: 150,
  position: { my: 'center', at: 'center', of: '#area' }
});

// When checkbox changed, update confinement settings.
$('#draggable, #resizable').change(function () {
  let d = $('#draggable').prop('checked');
  let r = $('#resizable').prop('checked');
  let ui = $('#win').closest('.ui-dialog');
  ui.draggable('option', 'containment', d ? '#area' : 'document');
  ui.resizable('option', 'containment', r ? '#area' : 'document');
});

#area {
  position: relative;
  left: 2ex;
  top: 2ex;
  width: 400px;
  height: 300px;
  border: 1px solid red;
}

#win {
  font-size: 10pt;
  display: flex;
  flex-direction: column;
}

label {
  display: flex;
  align-items: center;
}

<head>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
  <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</head>

<body>
  <div>Example</div>
  <div id="area"></div>
  <div id="win" title="test">
    <label><input type="checkbox" id="draggable">Contain drag</label>
    <label><input type="checkbox" id="resizable">Contain resize</label>
  </div>
</body>


问:
Indexing arrays with enums in C#
I have a lot of fixed-size collections of numbers where each entry can be accessed with a constant. Naturally this seems to point to arrays and enums:

```<code>enum StatType {
    Foo = 0,
    Bar
    // ...
}

float[] stats = new float[...];
stats[StatType.Foo] = 1.23f;
</code>```

The problem with this is of course that you cannot use an enum to index an array without a cast (though the compiled IL is using plain ints). So you have to write this all over the place:

```<code>stats[(int)StatType.foo] = 1.23f;
</code>```

I have tried to find ways to use the same easy syntax without casting but haven't found a perfect solution yet. Using a dictionary seems to be out of the question since I found it to be around 320 times slower than an array. I also tried to write a generic class for an array with enums as index:

```<code>public sealed class EnumArray<T>
{
    private T[] array;
    public EnumArray(int size)
    {
        array = new T[size];
    }
    // slow!
    public T this[Enum idx]
    {
        get { return array[(int)(object)idx]; }
        set { array[(int)(object)idx] = value; }
    }
}
</code>```

or even a variant with a second generic parameter specifying the enum. This comes quite close to what I want but the problem is that you cannot just cast an unspecific enum (be it from a generic parameter or the boxed type Enum) to int. Instead you have to first box it with a cast to object and then cast it back. This works, but is quite slow. I found that the generated IL for the indexer looks something like this:

```<code>.method public hidebysig specialname instance !T get_Item(!E idx) cil managed
{
    .maxstack 8
    L_0000: ldarg.0
    L_0001: ldfld !0[] EnumArray`2<!T, !E>::array
    L_0006: ldarg.1
    L_0007: box !E
    L_000c: unbox.any int32
    L_0011: ldelem.any !T
    L_0016: ret
}
</code>```

As you can see there are unnecessary box and unbox instructions there. If you strip them from the binary the code works just fine and is just a tad slower than pure array access.

Is there any way to easily overcome this problem? Or maybe even better ways?
I think it would also be possible to tag such indexer methods with a custom attribute and strip those two instructions post-compile. What would be a suitable library for that? Maybe Mono.Cecil?

Of course there's always the possibility to drop enums and use constants like this:

```<code>static class StatType {
    public const int Foo = 0;
    public const int Bar = 1;
    public const int End = 2;
}
</code>```

which may be the fastest way since you can directly access the array.

答: enums are supposed to be type safe.  If you're using them as the index of an array, you're fixing both the type and the values of the enum, so you have no benefit over declaring a static class of int constants.</p>

ContentLicense: CC BY-SA 2.5

Title: Indexing arrays with enums in C#

Body:
I have a lot of fixed-size collections of numbers where each entry can be accessed with a constant. Naturally this seems to point to arrays and enums:

enum StatType {
    Foo = 0,
    Bar
    // ...
}

float[] stats = new float[...];
stats[StatType.Foo] = 1.23f;

The problem with this is of course that you cannot use an enum to index an array without a cast (though the compiled IL is using plain ints). So you have to write this all over the place:

stats[(int)StatType.foo] = 1.23f;

I have tried to find ways to use the same easy syntax without casting but haven't found a perfect solution yet. Using a dictionary seems to be out of the question since I found it to be around 320 times slower than an array. I also tried to write a generic class for an array with enums as index:

public sealed class EnumArray<T>
{
    private T[] array;
    public EnumArray(int size)
    {
        array = new T[size];
    }
    // slow!
    public T this[Enum idx]
    {
        get { return array[(int)(object)idx]; }
        set { array[(int)(object)idx] = value; }
    }
}

or even a variant with a second generic parameter specifying the enum. This comes quite close to what I want but the problem is that you cannot just cast an unspecific enum (be it from a generic parameter or the boxed type Enum) to int. Instead you have to first box it with a cast to object and then cast it back. This works, but is quite slow. I found that the generated IL for the indexer looks something like this:

.method public hidebysig specialname instance !T get_Item(!E idx) cil managed
{
    .maxstack 8
    L_0000: ldarg.0
    L_0001: ldfld !0[] EnumArray`2<!T, !E>::array
    L_0006: ldarg.1
    L_0007: box !E
    L_000c: unbox.any int32
    L_0011: ldelem.any !T
    L_0016: ret
}

As you can see there are unnecessary box and unbox instructions there. If you strip them from the binary the code works just fine and is just a tad slower than pure array access.

Is there any way to easily overcome this problem? Or maybe even better ways?
I think it would also be possible to tag such indexer methods with a custom attribute and strip those two instructions post-compile. What would be a suitable library for that? Maybe Mono.Cecil?

Of course there's always the possibility to drop enums and use constants like this:

static class StatType {
    public const int Foo = 0;
    public const int Bar = 1;
    public const int End = 2;
}

which may be the fastest way since you can directly access the array.

OwnerDisplayName: Michael Meadows


问:
Router can ping google but firewall and PC's can't
we have a few problems trying to setup a network, we will try to explain what we got.

These are the devices that we have:

-ISP #1 modem

-ISP #2 modem

-Cisco Router 4331

-Cisco Firewall 5508

-Some switches

-An internal DNS Server and a few PC’s

Network topology

You can see the network diagram (the diagram is just to illustrate the topology).

Actual status

-The ISP #1 modem and the ISP #2 modem assign DHCP as show in images

-The Router can ping to ISP #1 modem and ISP #2 modem

-The Router can ping to google.com through ISP #1 modem and through ISP #2 modem

-The Firewall can’t ping to any ISP modem or google.com

-The PC’s can’t ping any ISP modem or google.com

-This link contains a shared folder with attached files (https://1drv.ms/f/s!AqkJyrRRfKHigetLlyGFtQ8RX_RpKg)

Edit:
Everything was solved by deleting the default network option!

答:
Are you sure the firewall the default gateway set to the router (192.168.4.247)?

It looks like PCs have the firewall as default gateway, which is correct. Also, the router has default routes as part of the DHCP negotiation with ISP#1 and ISP#2 modems. But nothing shows that the firewall knows where to send non-local packets.

Hope it helps!


问:
Is there a way to tell mercurial 'delete all files that are deleted in local' during a merge?
I've been assigned the task to do a huge merge, ~1500 commits, on a mercurial project.

In the local fork we have deleted about ~200 files, right now I need to press d and enter for each file:

```<code>remote changed file/that/is/deleted/in/local which local deleted
use (c)hanged version or leave (d)eleted?
</code>```

Is there a way to tell mercurial to choose to delete all those files?

答: You deleted them on local? You can't just do an hg addremove? If they changed after removal, but before pushing I think you are out of luck :(

Body:
I've been assigned the task to do a huge merge, ~1500 commits, on a mercurial project.

In the local fork we have deleted about ~200 files, right now I need to press d and enter for each file:

remote changed file/that/is/deleted/in/local which local deleted
use (c)hanged version or leave (d)eleted?

Is there a way to tell mercurial to choose to delete all those files?


问:
animation in index.html in Angular App
I am trying to animate a fadeout effect in the 'App Loading' screen when Angular loads the app. However, I cannot find a way through. Here is the code:

```<code><div class="container">
<my-app>
  <div class="loadingComp">
    <div class="sk-folding-cube">
      <div class="sk-cube1 sk-cube"></div>
      <div class="sk-cube2 sk-cube"></div>
      <div class="sk-cube4 sk-cube"></div>
      <div class="sk-cube3 sk-cube"></div>
    </div>
    <span>App loading, please wait.</span>
  </div>
  </my-app>
</code>```

tried the CSS below, but in vain:

```<code>my-app:empty + .loadingComp {
  opacity: 1;
}

my-app:not(:empty) + .loadingComp {
 opacity: 0;
 animation: fadeOut 0.5s ease-in-out;
}

@keyframes fadeOut {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
</code>```

Even tried with Angular Animations, but not working. Any suggestion ??

答:
I am not sure if you want to fadeOut the 'App Loading...' message or the first component that loads. But I will cover both cases.

To animate the 'App Loading' message before the root component loads, a script needs to be added that can run the animation. I am using jQuery fadeTo() functionality (doc).

index.html:

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

  <head>
    <base href="." />
    <title>angular playground</title>
    <link rel="stylesheet" href="style.css" />
    <script src="https://unpkg.com/core-js@2.4.1/client/shim.min.js"></script>
    <script src="https://unpkg.com/zone.js/dist/zone.js"></script>
    <script src="https://unpkg.com/zone.js/dist/long-stack-trace-zone.js"></script>
    <script src="https://unpkg.com/reflect-metadata@0.1.3/Reflect.js"></script>
    <script src="https://unpkg.com/systemjs@0.19.31/dist/system.js"></script>
    <script src="config.js"></script>
    <script>
      System.import('app')
        .catch(console.error.bind(console));
    </script>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

  </head>

  <body>
    <style>
      #animate {
        width: 100%;
        height: 250px;
        position: absolute;
        background-color: red;
      }
    </style>

    <my-app>
        <div id="animate"><h1>App loading, please wait.</h1></div>
    </my-app>

    <script>
      $( "#animate" ).fadeTo( 750 , 0.1, function() {
          // Animation complete.
        });
   </script>

  </body>

</html>
</code>```

To add animation to the component, I have added the animations metadata.

app.ts:

```<code>import {Component, NgModule, Input, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import {
  trigger,
  state,
  style,
  animate,
  transition
} from '@angular/animations';

@Component({
  selector: 'my-app',
  template: `
    <div [@flyInOut]="'out'">
      <h2>Hello {{name}}</h2>
    </div>
  `,
  animations: [
    trigger('flyInOut', [
      state('out', style({opacity: 0, transform: 'translateX(0)'})),
      transition('void => *', [
        style({
          opacity: 1,
          //transform: 'translateX(-100%)'
        }),
        animate('1s ease-in')
      ]),
      transition('* => void', [
        animate('0.2s 10 ease-out', style({
          opacity: 0,
          transform: 'translateX(100%)'
        }))
      ])
    ])
  ]
})
export class App {
  name:string;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }
}

@NgModule({
  imports: [ BrowserModule, BrowserAnimationsModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}
</code>```

Here's the Plunker demo for reference. Hope this helps!

Title: animation in index.html in Angular App

Body:
I am trying to animate a fadeout effect in the 'App Loading' screen when Angular loads the app. However, I cannot find a way through. Here is the code:

<my-app>

    App loading, please wait.

  </my-app>

tried the CSS below, but in vain:

my-app:empty + .loadingComp {
  opacity: 1;
}

my-app:not(:empty) + .loadingComp {
 opacity: 0;
 animation: fadeOut 0.5s ease-in-out;
}

@keyframes fadeOut {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

Even tried with Angular Animations, but not working. Any suggestion ??

Body:
I am not sure if you want to fadeOut the 'App Loading...' message or the first component that loads. But I will cover both cases.

To animate the 'App Loading' message before the root component loads, a script needs to be added that can run the animation. I am using jQuery fadeTo() functionality (doc).

index.html:

<!DOCTYPE html>
<html>

  <head>
    <base href="." />
    <title>angular playground</title>
    <link rel="stylesheet" href="style.css" />
    <script src="https://unpkg.com/core-js@2.4.1/client/shim.min.js"></script>
    <script src="https://unpkg.com/zone.js/dist/zone.js"></script>
    <script src="https://unpkg.com/zone.js/dist/long-stack-trace-zone.js"></script>
    <script src="https://unpkg.com/reflect-metadata@0.1.3/Reflect.js"></script>
    <script src="https://unpkg.com/systemjs@0.19.31/dist/system.js"></script>
    <script src="config.js"></script>
    <script>
      System.import('app')
        .catch(console.error.bind(console));
    </script>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

  </head>

  <body>
    <style>
      #animate {
        width: 100%;
        height: 250px;
        position: absolute;
        background-color: red;
      }
    </style>

    <my-app>
        <div id="animate"><h1>App loading, please wait.</h1></div>
    </my-app>

    <script>
      $( "#animate" ).fadeTo( 750 , 0.1, function() {
          // Animation complete.
        });
   </script>

  </body>

</html>

To add animation to the component, I have added the animations metadata.

app.ts:

import {Component, NgModule, Input, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import {
  trigger,
  state,
  style,
  animate,
  transition
} from '@angular/animations';

@Component({
  selector: 'my-app',
  template: `
    <div [@flyInOut]="'out'">
      <h2>Hello {{name}}</h2>
    </div>
  `,
  animations: [
    trigger('flyInOut', [
      state('out', style({opacity: 0, transform: 'translateX(0)'})),
      transition('void => *', [
        style({
          opacity: 1,
          //transform: 'translateX(-100%)'
        }),
        animate('1s ease-in')
      ]),
      transition('* => void', [
        animate('0.2s 10 ease-out', style({
          opacity: 0,
          transform: 'translateX(100%)'
        }))
      ])
    ])
  ]
})
export class App {
  name:string;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }
}

@NgModule({
  imports: [ BrowserModule, BrowserAnimationsModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

Here's the Plunker demo for reference. Hope this helps!


问:
GCC and Clang disagree about C++17 constexpr lambda captures
Consider this example which declares a variable as constexpr, captures it by copy in a lambda, and declares another constexpr variable which is the result of a constexpr function unwrapping a non-type template parameter from the original variable.

```<code>#include <utility>

template<int I>
constexpr auto unwrap(std::integral_constant<int, I>) {
  return I;
}

int main() {
  constexpr auto i = std::integral_constant<int, 42>{};
  constexpr auto l = [i]() {
    constexpr int x = unwrap(i);
  };
}
</code>```

Clang (trunk) accepts this code. (wandbox)

GCC (trunk) fails with the following error message (wandbox):

```<code>lambda_capture.cpp:11:31: error: the value of ‘i’ is not usable in a constant expression
     constexpr int x = unwrap(i);
                               ^
lambda_capture.cpp:10:28: note: ‘i’ was not declared ‘constexpr’
   constexpr auto l = [i]() {
</code>```

Which compiler is correct? It seems to me that this is a GCC bug, where the constexpr-ness of lambda captures is not correctly propagated to the lambda context.

答:
Both implementations are bugged, but I'm inclined to think that GCC got the right answer here.

Dropping the capture of i causes Clang to refuse to compile the code. That means it clearly has a bug somewhere.

[expr.const]/2.12:

An expression e is a core constant expression unless the evaluation
  of e, following the rules of the abstract machine, would evaluate
  one of the following expressions:

[...]

in a lambda-expression, a reference to [...] a variable with automatic storage duration defined outside that lambda-expression,
  where the reference would be an odr-use;

[...]

Clang's behavior is schizophrenic: if the use of i in the body is not an odr-use, then it doesn't need to be captured, yet it rejects the code in the OP if the explicit capture is removed; OTOH, if it is an odr-use, then by the above unwrap(i) isn't a constant expression, and so it should reject the initialization of x.

GCC's lambda implementation is woefully bad with respect to odr-use. It does constant-folding ultra-early, resulting in all kinds of subtle mischief. On the other hand, for explicit captures it transforms all uses, whether or not it's actually an odr-use. The aggressive constant folding means that it accepts OP's code if the capture of i is removed.

Assuming that unwrap(i) does odr-use i, then it is correct that, per [expr.const]/2.12, OP's code is ill-formed.

Does unwrap(i) actually odr-use i? That question boils down to whether copy-initializing the parameter object of unwrap counts as applying an lvalue-to-rvalue conversion to i. I don't see anything in the standard that explicitly says that an lvalue-to-rvalue conversion is applied here, and instead [dcl.init]/17.6.2 indicates that we call a constructor (in this case, the trivial implicitly defined copy constructor) passing i as the argument bound to its parameter, and reference binding is a classic example of odr-use.

To be sure, applying an l-to-r conversion would result in a copy-initialization of an integral_constant<int, 42> object from i, but the problem here is that nothing in the standard says the converse - that all copy-initializations of an integral_constant<int, 42> object from i count as l-to-r conversions.

Body:
Consider this example which declares a variable as constexpr, captures it by copy in a lambda, and declares another constexpr variable which is the result of a constexpr function unwrapping a non-type template parameter from the original variable.

#include <utility>

template<int I>
constexpr auto unwrap(std::integral_constant<int, I>) {
  return I;
}

int main() {
  constexpr auto i = std::integral_constant<int, 42>{};
  constexpr auto l = [i]() {
    constexpr int x = unwrap(i);
  };
}

Clang (trunk) accepts this code. (wandbox)

GCC (trunk) fails with the following error message (wandbox):

lambda_capture.cpp:11:31: error: the value of ‘i’ is not usable in a constant expression
     constexpr int x = unwrap(i);
                               ^
lambda_capture.cpp:10:28: note: ‘i’ was not declared ‘constexpr’
   constexpr auto l = [i]() {

Which compiler is correct? It seems to me that this is a GCC bug, where the constexpr-ness of lambda captures is not correctly propagated to the lambda context.


问:
shell_exec not working
Here's my command:

```<code>sudo /usr/local/bin/jpegoptim --max=50 /home/someuser/public_html/reports/images/r121662.jpg
</code>```

This command is supposed to compress an image. I tried running this command using backtick operator and shell_exec, neither will work. The file doesn't compress.

But this command runs when I run it directly in the shell logged in as someuser. I've modified sudoers to accept the command without requiring a password. The file is compressed when I run it in the shell.

Apache is configured to run with suPHP, and the PHP files belong to someuser as well. I've further ensured this by writing a test php script just saying system(id); and running it in the browser. That tells me that the script is indeed being run by someuser.

Also, safe_mode is off.

EDIT: Ok, I got it to output the error

```<code>sudo: sorry, you must have a tty to run sudo
</code>```

Now, what does it mean?!

答: Thanks to Catalin , I was able to get an output. It said sudo: sorry, you must have a tty to run sudo which required requiretty to be disabled for someuser. That is the best solution I got, if there's a way to disable requiretty for a single user calling a single command, please let me know.

Title: shell_exec not working

Body:
Here's my command:

sudo /usr/local/bin/jpegoptim --max=50 /home/someuser/public_html/reports/images/r121662.jpg

This command is supposed to compress an image. I tried running this command using backtick operator and shell_exec, neither will work. The file doesn't compress.

But this command runs when I run it directly in the shell logged in as someuser. I've modified sudoers to accept the command without requiring a password. The file is compressed when I run it in the shell.

Apache is configured to run with suPHP, and the PHP files belong to someuser as well. I've further ensured this by writing a test php script just saying system(id); and running it in the browser. That tells me that the script is indeed being run by someuser.

Also, safe_mode is off.

EDIT: Ok, I got it to output the error

sudo: sorry, you must have a tty to run sudo

Now, what does it mean?!


问:
how to receive strings from user to receive empty string and print them in c
how to receive strings from user to the empty string in c
receive the string and put into an array and then print it.

```<code>int main() {
    int i=0;
    char st[LEN];
    char ch;

    while(st[0]!='\0') {
        i=0;
        printf("Enter name of student:");

        while(ch!='\n') {
            ch=getchar();
            st[i]=ch;
            i++;
        }
    }
}
</code>```

答:
Alright, since I got called out, I will try to add a bit of meat around the bone. However, I will not simply hand you the code to do the task, it would spoil the fun.

The first part is to figure out how to gather the names entered by the user and store it in a variable. C does not handle String as a data type instead they are represented by an array of char (char[]) that ends with a null bytes, the character \00. There are many functions that allow you to take an input from a user : getchar, gets, fgets, scanf, etc. Here, you will need to do a bit of googling to figure out which one you should use for your particular case.

Afterwards, you want to figure out how to store the strings you collected into some sort of list. You would represent that as an array of strings. As we said, strings are not a thing in C. So you need to declare an array of array of char (char[][]). It is possible to grow the size dynamically as you add new items to the list with memory manipulation functions like malloc and realloc. But to start, I suggest that you stick to a fixed size array until you understand how it works.

The last step is to print the names you collected. Use a loop to iterate over your list of strings and print them one by one using the function printf.

Finally here's a pseudo code that boldly describes the process :

```<code>students: List of string
input: String
count: Integer

// Gather the names
while 1:
    print "Enter the name of a student : "
    input = readUserInput()

    if input is a null byte:
        break the loop
    else:
        students[count] = input
        increment count

// Print the names
for i in [0, count]:
    print students[i] + '\n' // '\n' represents a carriage return
</code>```

Here are some random links that explain some of the concepts. Remember, google is your friend!

Which is the best way to get input from user in C?

https://www.tutorialspoint.com/cprogramming/c_arrays.htm

https://www.tutorialspoint.com/cprogramming/c_loops.htm

https://www.tutorialspoint.com/c_standard_library/c_function_printf.htm

Body:
how to receive strings from user to the empty string in c
receive the string and put into an array and then print it.

int main() {
    int i=0;
    char st[LEN];
    char ch;

    while(st[0]!='\0') {
        i=0;
        printf("Enter name of student:");

        while(ch!='\n') {
            ch=getchar();
            st[i]=ch;
            i++;
        }
    }
}

Body:
Alright, since I got called out, I will try to add a bit of meat around the bone. However, I will not simply hand you the code to do the task, it would spoil the fun.

The first part is to figure out how to gather the names entered by the user and store it in a variable. C does not handle String as a data type instead they are represented by an array of char (char[]) that ends with a null bytes, the character \00. There are many functions that allow you to take an input from a user : getchar, gets, fgets, scanf, etc. Here, you will need to do a bit of googling to figure out which one you should use for your particular case.

Afterwards, you want to figure out how to store the strings you collected into some sort of list. You would represent that as an array of strings. As we said, strings are not a thing in C. So you need to declare an array of array of char (char[][]). It is possible to grow the size dynamically as you add new items to the list with memory manipulation functions like malloc and realloc. But to start, I suggest that you stick to a fixed size array until you understand how it works.

The last step is to print the names you collected. Use a loop to iterate over your list of strings and print them one by one using the function printf.

Finally here's a pseudo code that boldly describes the process :

students: List of string
input: String
count: Integer

// Gather the names
while 1:
    print "Enter the name of a student : "
    input = readUserInput()

    if input is a null byte:
        break the loop
    else:
        students[count] = input
        increment count

// Print the names
for i in [0, count]:
    print students[i] + '\n' // '\n' represents a carriage return

Here are some random links that explain some of the concepts. Remember, google is your friend!

Which is the best way to get input from user in C?

https://www.tutorialspoint.com/cprogramming/c_arrays.htm

https://www.tutorialspoint.com/cprogramming/c_loops.htm

https://www.tutorialspoint.com/c_standard_library/c_function_printf.htm


问:
Multiple Prototype cells displaying in one row in tableview in xamarin.ios
I'm having an issue with a tableview in xamarin.ios, I'm trying to use multiple prototype cells but all of the prototype cells are showing on the same row in the table view and I want them to have there own row, does anyone have the solution?

Thanks.

答:
This is the GetCell message in the table source.

public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            //Incoming message

var cell =   (IncomingCell)tableView.DequeueReusableCell("IncomingCell", indexPath);

```<code>        var message = messages[indexPath.Row];

        cell.updateCel(message);
</code>```

var cell1 =(OutGoingCell)tableView.DequeueReusableCell("OutgoingCell", indexPath);

```<code>        var message1 = messages[indexPath.Row];

        cell1.updatecell(message1);

        return cell;

    }
</code>```

Body:
This is the GetCell message in the table source.

public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            //Incoming message

var cell =   (IncomingCell)tableView.DequeueReusableCell("IncomingCell", indexPath);

        var message = messages[indexPath.Row];

        cell.updateCel(message);

var cell1 =(OutGoingCell)tableView.DequeueReusableCell("OutgoingCell", indexPath);

        var message1 = messages[indexPath.Row];

        cell1.updatecell(message1);

        return cell;

    }


问:
How to extract selected data from interactive htmlwidget plot
I am trying to figure out a way to extract data from a selection of an interactive plot in Shiny. I build a parallel coordinates plot using a package found at https://github.com/timelyportfolio/parcoords which builds a parcoords chart using htmlWidgets. It allows users to make specific slections, as seen below:

What I need is a way to extract the highlighted rows from the underlying data set, either through a download button or data table. Is there anyway to pull out this info from the underlying htmlWidget process? Any advice is appreciated.

答: Using crosstalk you can let one htmlwidget talk to another. The dev version of parcoords supports crosstalk integration as does datatable, so you can link the two with minimal effort


问:
Bootstrap columns overlapping on resize
I'm working on some responsive design but I'm having trouble with columns in bootstrap, because everything works perfectly until I resize my browser, I already checked some answers here like:
Bootstrap grid columns overlapping each other
Why do my bootstrap columns overlap?
bootstrap columns overlapping

but none of those work for my problem, I hope you can help me :)
this is what I have:

  .lil-price{
      width: 40%;
      margin-top: -15%;
      z-index: 1;
      border-radius: 50%;
      text-align: center;
      font-size: 1.5em;
      padding: 14% 0;
      line-height: 1;
      position: absolute;
      background: #111842;
      color: white;
  }

  .lil-orange{
      width: 72%;
      z-index: 0;
      border-radius: 50%;
      text-align: center;
      font-size: 1.8em;
      padding: 27% 0;
      line-height: 30px;
      position: absolute;
      background: #faa21b;
      color: white;
      margin-left: 19%;
      margin-top: 3%;

  }

  .lil-march-1{
   position: absolute;
   margin-top: 50%;
  }

  .lil-march-1 img{
      width: 80%;
      margin-left: 10%;
  }

  .lil-blue{
      width: 72%;
      z-index: 0;
      border-radius: 50%;
      text-align: center;
      font-size: 1.8em;
      padding: 27% 0;
      line-height: 30px;
      position: absolute;
      background: #00aae4;
      color: white;
      margin-left: 19%;
      margin-top: 3%;

  }

  .lil-jeep{
   position: absolute;
   margin-top: 50%;
  }

  .lil-jeep img{
      width: 80%;
      margin-left: 10%;
  }

  .lil-green{
      width: 72%;
      z-index: 0;
      border-radius: 50%;
      text-align: center;
      font-size: 1.8em;
      padding: 27% 0;
      line-height: 30px;
      position: absolute;
      background: #4e9d2d;
      color: white;
      margin-left: 13%;
      margin-top: 3%;

  }

  .lil-vento{
   position: absolute;
   margin-top: 50%;
  }

  .lil-vento img{
      width: 80%;
      margin-left: 10%;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="container lorem">
  <div>
   <center><h2 class="blue-title title-mobil">Lorem</h2></center>
  </div>
   <div class="row">
    <div class="col-sm-4">
    <div>
      <div class="lil-price">consectetur adipiscing</div>
   <div class="lil-blue">
     <p>Lorem ipsum dolor sit amet</p>
      </div>
      <div class="lil-jeep">
        <img src="http://placekitten.com/900/500">
      </div>
        </div>
    </div>
    <div class="col-sm-4">
        <div class="row">
     <div class="lil-price">consectetur adipiscing</div>
   <div class="lil-orange">
     <p>Lorem ipsum dolor sit amet</p>
      </div>
      <div class="lil-march-1">
        <img src="http://placekitten.com/900/500">
      </div>
        </div>
    </div>
    <div class="col-sm-4">
     <div class="lil-price">consectetur adipiscing</div>
       <div class="lil-green">
         <p>Lorem ipsum dolor sit amet</p>
        </div>
      <div class="lil-vento">
        <img src="http://placekitten.com/900/500">
      </div>
    </div>
   </div>
</div></code>```

https://codepen.io/phacohen/pen/RgPLjP

答:
You have to remove position: absolute property from your classes for it to stop overlapping.

Without position: absolute:

.rect {
  width: 120px;
  height: 120px;
  border: 3px solid;
  font-size: 40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="col-sm-4"><div class="rect">1</div></div>
  <div class="col-sm-4"><div class="rect">2</div></div>
  <div class="col-sm-4"><div class="rect">3</div></div>
</div></code>```

With position: absolute:

.rect {
  width: 120px;
  height: 120px;
  border: 3px solid;
  font-size: 40px;

  position: absolute;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="col-sm-4"><div class="rect">1</div></div>
  <div class="col-sm-4"><div class="rect">2</div></div>
  <div class="col-sm-4"><div class="rect">3</div></div>
</div></code>```

Title: Bootstrap columns overlapping on resize

Body:
I'm working on some responsive design but I'm having trouble with columns in bootstrap, because everything works perfectly until I resize my browser, I already checked some answers here like:
Bootstrap grid columns overlapping each other
Why do my bootstrap columns overlap?
bootstrap columns overlapping

but none of those work for my problem, I hope you can help me :)
this is what I have:

  .lil-price{
      width: 40%;
      margin-top: -15%;
      z-index: 1;
      border-radius: 50%;
      text-align: center;
      font-size: 1.5em;
      padding: 14% 0;
      line-height: 1;
      position: absolute;
      background: #111842;
      color: white;
  }

  .lil-orange{
      width: 72%;
      z-index: 0;
      border-radius: 50%;
      text-align: center;
      font-size: 1.8em;
      padding: 27% 0;
      line-height: 30px;
      position: absolute;
      background: #faa21b;
      color: white;
      margin-left: 19%;
      margin-top: 3%;

  }

  .lil-march-1{
   position: absolute;
   margin-top: 50%;
  }

  .lil-march-1 img{
      width: 80%;
      margin-left: 10%;
  }

  .lil-blue{
      width: 72%;
      z-index: 0;
      border-radius: 50%;
      text-align: center;
      font-size: 1.8em;
      padding: 27% 0;
      line-height: 30px;
      position: absolute;
      background: #00aae4;
      color: white;
      margin-left: 19%;
      margin-top: 3%;

  }

  .lil-jeep{
   position: absolute;
   margin-top: 50%;
  }

  .lil-jeep img{
      width: 80%;
      margin-left: 10%;
  }

  .lil-green{
      width: 72%;
      z-index: 0;
      border-radius: 50%;
      text-align: center;
      font-size: 1.8em;
      padding: 27% 0;
      line-height: 30px;
      position: absolute;
      background: #4e9d2d;
      color: white;
      margin-left: 13%;
      margin-top: 3%;

  }

  .lil-vento{
   position: absolute;
   margin-top: 50%;
  }

  .lil-vento img{
      width: 80%;
      margin-left: 10%;
  }

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Lorem

consectetur adipiscing

Lorem ipsum dolor sit amet

consectetur adipiscing

Lorem ipsum dolor sit amet

consectetur adipiscing

Lorem ipsum dolor sit amet

https://codepen.io/phacohen/pen/RgPLjP

Body:
You have to remove position: absolute property from your classes for it to stop overlapping.

Without position: absolute:

.rect {
  width: 120px;
  height: 120px;
  border: 3px solid;
  font-size: 40px;
}

<div class="row">
  <div class="col-sm-4"><div class="rect">1</div></div>
  <div class="col-sm-4"><div class="rect">2</div></div>
  <div class="col-sm-4"><div class="rect">3</div></div>
</div>

With position: absolute:

.rect {
  width: 120px;
  height: 120px;
  border: 3px solid;
  font-size: 40px;

  position: absolute;
}

<div class="row">
  <div class="col-sm-4"><div class="rect">1</div></div>
  <div class="col-sm-4"><div class="rect">2</div></div>
  <div class="col-sm-4"><div class="rect">3</div></div>
</div>


问:
Open video from gallery and Intent VideoView to new activity
I want make video player app that launch from gallery and play the video to 'new activity'. the problem is, i already browse the video at the gallery. the video are playing at the 'main activity' not play at the 'new activity'. please help.

MainActivity :

```<code>public class MainActivity extends Activity {

Button button1;
VideoView videoView;
private static final int SELECT_VIDEO = 1;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button1 = (Button) findViewById(R.id.button1);
    videoView=(VideoView)findViewById(R.id.videoView);
    button1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent intent = new Intent();
            intent.setType("video/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Video"), SELECT_VIDEO);

        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode != RESULT_OK) return;

    if (requestCode == SELECT_VIDEO) {
        Uri mVideoURI = data.getData();
        videoView.setVideoURI(mVideoURI);

        MediaController mediaController = new MediaController(this);
        mediaController.setAnchorView(videoView);
        videoView.setMediaController(mediaController);

        videoView.start();

        }
    }
}
</code>```

what coding should i put in my 'new activity.java'?
and i also want to put 4 video in same activity. what should i do?

答: put the intent in NewActivity not in MainActivity</p>

Body:
I want make video player app that launch from gallery and play the video to 'new activity'. the problem is, i already browse the video at the gallery. the video are playing at the 'main activity' not play at the 'new activity'. please help.

MainActivity :

public class MainActivity extends Activity {

Button button1;
VideoView videoView;
private static final int SELECT_VIDEO = 1;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button1 = (Button) findViewById(R.id.button1);
    videoView=(VideoView)findViewById(R.id.videoView);
    button1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent intent = new Intent();
            intent.setType("video/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Video"), SELECT_VIDEO);

        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode != RESULT_OK) return;

    if (requestCode == SELECT_VIDEO) {
        Uri mVideoURI = data.getData();
        videoView.setVideoURI(mVideoURI);

        MediaController mediaController = new MediaController(this);
        mediaController.setAnchorView(videoView);
        videoView.setMediaController(mediaController);

        videoView.start();

        }
    }
}

what coding should i put in my 'new activity.java'?
and i also want to put 4 video in same activity. what should i do?


问:
TcpListener request flood
Hi All: I'm trying to ensure my TcpListener can handle multiple requests from a client properly. I am trying multiple BeginSend method calls inside a for loop and finding that the output from the Listener is inconsistent in terms of how many responses I am getting. i.e. if I call BeginSend 20 times sequentially I would want the Listener to give me 20 responses. Sometimes I get 2, sometimes 3, sometimes more and, it appears, that the messages I send to the Listener are being appended to one another, rather than being treated as separate entities.

Assume I have a valid TcpClient class (see code) which wraps a basic TcpClient and a valid TcpListener class (see code) which responds to a message from a connected TcpClient by raising a DataReceived event with the received message as its argument. Pretty basic code

```<code>for(int i = 0; i < 10; i++)
{
    client.Client.BeginSend(Encoding.ASCII.GetBytes(i.ToString()), 0, i.ToString().Length, SocketFlags.None, null, null);
}
</code>```

I would expect the output from the TcpListener to be

0

1

...

9

Instead I am getting things like:

0

123456789

or,

0

1234

56

789

or,

....

or some other permutation of the 10 separate messages
Here is the relevant code for the Listener:

```<code>    private void ListenForNewClients()
    {
        Task.Run(async () =>
        {
            while (true)
            {
                var tcpClient = await tcpServer.AcceptTcpClientAsync();

                clients.Add(tcpClient.Client);
                tcpClient.Client.BeginReceive(buffer, 0, BufferSize, SocketFlags.None, ReceiveCallback, tcpClient.Client);

            }
        });
    }
</code>```

And the ReceiveCallback:

```<code>    private void ReceiveCallback(IAsyncResult ar)
    {
        var tcpClient = ar.AsyncState as Socket;
        try
        {
            var bytesRead = tcpClient.EndReceive(ar);

            if (bytesRead == 0)
            {
                tcpClient.EndReceive(ar);
            }

            var data = Encoding.ASCII.GetString(buffer, 0, bytesRead);

            DataReceived?.Invoke(this, data);

            buffer = new byte[BufferSize];
            tcpClient.BeginReceive(buffer, 0, BufferSize, SocketFlags.None, ReceiveCallback, tcpClient);

        }
        catch
        {
            clients.Remove(tcpClient);
        }
    }
</code>```

答:
it appears, that the messages I send to the Listener are being appended to one another, rather than being treated as separate entities.

That's how TCP/IP works.

If you are writing both the client and server, then I recommend using SignalR, which preserves message boundaries.

If you must use TCP/IP, then you'll need some form of message framing.

Title: TcpListener request flood

Body:
Hi All: I'm trying to ensure my TcpListener can handle multiple requests from a client properly. I am trying multiple BeginSend method calls inside a for loop and finding that the output from the Listener is inconsistent in terms of how many responses I am getting. i.e. if I call BeginSend 20 times sequentially I would want the Listener to give me 20 responses. Sometimes I get 2, sometimes 3, sometimes more and, it appears, that the messages I send to the Listener are being appended to one another, rather than being treated as separate entities.

Assume I have a valid TcpClient class (see code) which wraps a basic TcpClient and a valid TcpListener class (see code) which responds to a message from a connected TcpClient by raising a DataReceived event with the received message as its argument. Pretty basic code

for(int i = 0; i < 10; i++)
{
    client.Client.BeginSend(Encoding.ASCII.GetBytes(i.ToString()), 0, i.ToString().Length, SocketFlags.None, null, null);
}

I would expect the output from the TcpListener to be

0

1

...

9

Instead I am getting things like:

0

123456789

or,

0

1234

56

789

or,

....

or some other permutation of the 10 separate messages
Here is the relevant code for the Listener:

    private void ListenForNewClients()
    {
        Task.Run(async () =>
        {
            while (true)
            {
                var tcpClient = await tcpServer.AcceptTcpClientAsync();

                clients.Add(tcpClient.Client);
                tcpClient.Client.BeginReceive(buffer, 0, BufferSize, SocketFlags.None, ReceiveCallback, tcpClient.Client);

            }
        });
    }

And the ReceiveCallback:

    private void ReceiveCallback(IAsyncResult ar)
    {
        var tcpClient = ar.AsyncState as Socket;
        try
        {
            var bytesRead = tcpClient.EndReceive(ar);

            if (bytesRead == 0)
            {
                tcpClient.EndReceive(ar);
            }

            var data = Encoding.ASCII.GetString(buffer, 0, bytesRead);

            DataReceived?.Invoke(this, data);

            buffer = new byte[BufferSize];
            tcpClient.BeginReceive(buffer, 0, BufferSize, SocketFlags.None, ReceiveCallback, tcpClient);

        }
        catch
        {
            clients.Remove(tcpClient);
        }
    }


问:
How to access and refresh a UITableView from another class in Swift
I have a tab bar application and a tab whose view controller is controlled by a UITableView class. I have a class that is used to download data from the server that then saves it to NSDefaults. From there I want the class to be able to update the table view, but am not sure how to access the table view's class to update it.

```<code>class updates {

func checkForUpdates() {
    //start on background thread
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { [unowned self] in
        //start contacting database:
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
        let actualVersion = self.contactForUpdates()
        UIApplication.sharedApplication().networkActivityIndicatorVisible = false
        if actualVersion > self.defaults.objectForKey("version") as! Int {
            //update data
            if self.downloadUpdates() {
                //update version number
                self.defaults.setObject(actualVersion, forKey: "version")
                //Indicates progress finished
                //self.stopSpinner()
            }
        }//end updates
        else {
            //Indicates progress finished
            //self.stopSpinner()

        }
    }//end background queue
}

}
</code>```

There are two areas commented //Indicates progress finished where I want to run tableView from the class:

```<code>class connectTableVC: UITableViewController {
    ...
}
</code>```

答:
For Swift 3</p>

```<code>NotificationCenter.default.post(name: NSNotification.Name(rawValue: "newDataNotificationForItemEdit"), object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(self.shouldReload), name: NSNotification.Name(rawValue: "newDataNotificationForItemEdit"), object: nil)

func shouldReload() {
    self.tableView.reloadData()
}
</code>```

Body:
I have a tab bar application and a tab whose view controller is controlled by a UITableView class. I have a class that is used to download data from the server that then saves it to NSDefaults. From there I want the class to be able to update the table view, but am not sure how to access the table view's class to update it.

class updates {

func checkForUpdates() {
    //start on background thread
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { [unowned self] in
        //start contacting database:
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
        let actualVersion = self.contactForUpdates()
        UIApplication.sharedApplication().networkActivityIndicatorVisible = false
        if actualVersion > self.defaults.objectForKey("version") as! Int {
            //update data
            if self.downloadUpdates() {
                //update version number
                self.defaults.setObject(actualVersion, forKey: "version")
                //Indicates progress finished
                //self.stopSpinner()
            }
        }//end updates
        else {
            //Indicates progress finished
            //self.stopSpinner()

        }
    }//end background queue
}

}

There are two areas commented //Indicates progress finished where I want to run tableView from the class:

class connectTableVC: UITableViewController {
    ...
}

Body:
For Swift 3

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "newDataNotificationForItemEdit"), object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(self.shouldReload), name: NSNotification.Name(rawValue: "newDataNotificationForItemEdit"), object: nil)

func shouldReload() {
    self.tableView.reloadData()
}


问:
What's the point of a view constraint?
Where are view constraints useful? By that I mean, Oracle allows a constraint to be created on a view. They are not enforced by the database. It seems to be just more metadata that can be used by the database, but I'm trying to understand under what circumstances they are useful.

Tom Kyte answered in a question:

They are used for complex query rewrites with materialized views and such.  It is more "meta data"
  -- it gives the optimizer more information, allows for a broader range of query rewriting to take
  place.

... but that's a bit brief.

答:
Minor use in an Oracle product. In the Designer-generated PL/SQL web applications, components based on views needed a primary key defined on the view. That allowed the application to hyperlink from a list of records to a single-record display.

I remember seeing a few cases with Hibernate where it generated better code when there were PK and FK constraints defined on views. (Can anybody else confirm that?)

And Tom points to query rewrite.

So I think the answer is "if your tools can use the information, then it's better to supply it." Of course, it's going to be hard to figure out which tools will use it.

I try to include them because

It's not much work, though the scripts to recreate views are somewhat more complicated.

It helps in making the physical implementation of the logical model complete

It reminds me of real data constraints that I need to implement somehow, via triggers or background packages or in a "constraint violation" report.

Title: What's the point of a view constraint?


问:
Pandas Filter by string
I need to filter my groups to show only the groups that contain a string in all the rows of a group.

```<code>Index  A   B   C
0      A1  B5  T
1      A1  B2  T
2      A1  B2  F
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T
6      A4  F4  F
</code>```

Returns:

```<code>Index  A   B   C
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T
</code>```

Tried: df.groupby('A').apply(lambda x: x[x['C']==T])

And as you may have known it returns:

```<code>Index  A   B   C
0      A1  B5  T
1      A1  B2  T
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T
</code>```

When I change apply to filter I get an error.

Help Please!

答:
Using transform

Fastest solution that is also simple

```<code>df[df.C.eq('T').groupby(df.A.values).transform('all')]

        A   B  C
Index
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T
</code>```

Using crosstab

Shortest solution I could think of... but slow

```<code>df[df.A.map(pd.crosstab(df.A, df.C).F.eq(0))]

        A   B  C
Index
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T
</code>```

project/kill

Very fast solution... but complicated

```<code>f, u = pd.factorize(df.A.values)
t = (df.C.values == 'T').astype(int)
b0 = np.bincount(f * 2 + t)
pad = np.zeros(2 * u.size - b0.size, dtype=int)
b = np.append(b0, pad)

df[~b.reshape(-1, 2)[:, 0].astype(bool)[f]]

        A   B  C
Index
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T
</code>```

Timing

```<code>%timeit df[df.C.eq('T').groupby(df.A.values).transform('all')]
%timeit df[df.A.map(pd.crosstab(df.A, df.C).F.eq(0))]
%timeit df.groupby('A').filter(lambda x: len(x[x.C=='T'])==len(x))

1000 loops, best of 3: 1.67 ms per loop
100 loops, best of 3: 6.15 ms per loop
100 loops, best of 3: 3.05 ms per loop

%%timeit
f, u = pd.factorize(df.A.values)
t = (df.C.values == 'T').astype(int)
b0 = np.bincount(f * 2 + t)
pad = np.zeros(2 * u.size - b0.size, dtype=int)
b = np.append(b0, pad)

df[~b.reshape(-1, 2)[:, 0].astype(bool)[f]]
1000 loops, best of 3: 279 µs per loop

d1 = df.assign(mydummy=df['C']=='T')
d1['mysum'] = d1.groupby('A').mydummy.transform('sum')
d1['mycount'] = d1.groupby('A').mysum.transform('size')
d1.loc[d1.mysum == d1.mycount, df.columns]
100 loops, best of 3: 3.68 ms per loop
</code>```

Title: Pandas Filter by string

Body:
I need to filter my groups to show only the groups that contain a string in all the rows of a group.

Index  A   B   C
0      A1  B5  T
1      A1  B2  T
2      A1  B2  F
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T
6      A4  F4  F

Returns:

Index  A   B   C
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T

Tried: df.groupby('A').apply(lambda x: x[x['C']==T])

And as you may have known it returns:

Index  A   B   C
0      A1  B5  T
1      A1  B2  T
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T

When I change apply to filter I get an error.

Help Please!

Body:
Using transform

Fastest solution that is also simple

df[df.C.eq('T').groupby(df.A.values).transform('all')]

        A   B  C
Index
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T

Using crosstab

Shortest solution I could think of... but slow

df[df.A.map(pd.crosstab(df.A, df.C).F.eq(0))]

        A   B  C
Index
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T

project/kill

Very fast solution... but complicated

f, u = pd.factorize(df.A.values)
t = (df.C.values == 'T').astype(int)
b0 = np.bincount(f * 2 + t)
pad = np.zeros(2 * u.size - b0.size, dtype=int)
b = np.append(b0, pad)

df[~b.reshape(-1, 2)[:, 0].astype(bool)[f]]

        A   B  C
Index
3      A2  B5  T
4      A2  F5  T
5      A3  F4  T

Timing

%timeit df[df.C.eq('T').groupby(df.A.values).transform('all')]
%timeit df[df.A.map(pd.crosstab(df.A, df.C).F.eq(0))]
%timeit df.groupby('A').filter(lambda x: len(x[x.C=='T'])==len(x))

1000 loops, best of 3: 1.67 ms per loop
100 loops, best of 3: 6.15 ms per loop
100 loops, best of 3: 3.05 ms per loop

%%timeit
f, u = pd.factorize(df.A.values)
t = (df.C.values == 'T').astype(int)
b0 = np.bincount(f * 2 + t)
pad = np.zeros(2 * u.size - b0.size, dtype=int)
b = np.append(b0, pad)

df[~b.reshape(-1, 2)[:, 0].astype(bool)[f]]
1000 loops, best of 3: 279 µs per loop

d1 = df.assign(mydummy=df['C']=='T')
d1['mysum'] = d1.groupby('A').mydummy.transform('sum')
d1['mycount'] = d1.groupby('A').mysum.transform('size')
d1.loc[d1.mysum == d1.mycount, df.columns]
100 loops, best of 3: 3.68 ms per loop


问:
Javascript - How do I replace all spaces that are only between a number and letter
```<code>"5 Teams 7 Players" ====> 5Teams 7Players
"7 Individuals 8 Teams 8 Categories" ====> 7Individuals 8Teams 8Categories
</code>```

答:
Both prasad's and smarx's patterns can be further simplied.  Just look for a digit followed by a space and leave out the space on replacement.

var a="5 Teams 7 Players";
var b="7 Individuals 8 Teams 8 Categories";

console.log(a.replace(/(\d) /g,'$1'))
console.log(b.replace(/(\d) /g,'$1'))```
</div>
</div>
</p>

<p>Output (in case you don't want to click Run):</p>

```5Teams 7Players
7Individuals 8Teams 8Categories
```

Body:
Both prasad's and smarx's patterns can be further simplied.  Just look for a digit followed by a space and leave out the space on replacement.

var a="5 Teams 7 Players";
var b="7 Individuals 8 Teams 8 Categories";

console.log(a.replace(/(\d) /g,'$1'))
console.log(b.replace(/(\d) /g,'$1'))

Output (in case you don't want to click Run):

5Teams 7Players
7Individuals 8Teams 8Categories


问:
JS Not showing wrong result UPDATED
Instead of 39500 output i get 500. Could someone help me, i want IF gw reaches 0, there should be no more -500 on wall.

I used my code but it is not working.
HTML

```<code><li><b>Infantry: </b><span id="gw">40000</span></li>
<p class="fort"><b>Fort: </b><span id="wall">1000</span></p>
<button class="troops" onclick="send()">SEND TROOPS</button>
</code>```

JS

```<code>function send(){
    var a = document.getElementById('gw').innerHTML;
    var b = 500;
    var c = a-b;

    var label = document.getElementById('wall');
    label.innerHTML = parseInt(label.innerHTML) - b;
    var label = document.getElementById('gw');
    label.innerHTML = parseInt(label.innerHTML) - c;

}
</code>```

答:
Your main issue is that you were doing  var c = a-b;, b being a Number, but a being a String (Element.innerHTML) - without doing parseInt(value, radix) on that value... and there's other math subtraction confusion in there...

Instead:

// Helper function to set to 0 a value lower than 0
function zeroMin(val) {
  return parseInt(val, 10) < 0 ? 0 : val;
}

function send() {

  var EL_gw = document.getElementById('gw'),
    EL_wa = document.getElementById('wall'),
    gw = parseInt(EL_gw.innerHTML, 10),
    wa = parseInt(EL_wa.innerHTML, 10),
    hitVal = 500;

  // Subtract
  gw -= hitVal;
  wa -= hitVal;

  // fix to 0
  gw = zeroMin(gw);
  wa = zeroMin(wa);

  EL_gw.innerHTML = gw;
  EL_wa.innerHTML = wa;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><b>Infantry:</b> <span id="gw">40000</span> <br>
<b>Fort:</b> <span id="wall">1000</span> <br>

<button class="troops" onclick="send()">SEND TROOPS</button></code>```

If you want to stop any further action if any of the values reaches 0

function send() {

  var EL_gw = document.getElementById('gw'),
      EL_wa = document.getElementById('wall'),
    gw = parseInt(EL_gw.innerHTML, 10),
    wa = parseInt(EL_wa.innerHTML, 10),
    hitVal = 500;

  if (gw <= 0 || wa <= 0) return; // Do nothing if any is <= 0

  // else...
  gw -= hitVal;
  wa -= hitVal;

  EL_gw.innerHTML = gw;
  EL_wa.innerHTML = wa;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><b>Infantry:</b> <span id="gw">40000</span>
(will stop decreasing if FORT energy is 0 and vice-versa)<br>
<b>Fort:</b> <span id="wall">1000</span> <br>

<button class="troops" onclick="send()">SEND TROOPS</button></code>```

Title: JS Not showing wrong result UPDATED

Body:
Instead of 39500 output i get 500. Could someone help me, i want IF gw reaches 0, there should be no more -500 on wall.

I used my code but it is not working.
HTML

Infantry: 40000

Fort: 1000

<button class="troops" onclick="send()">SEND TROOPS</button>

JS

function send(){
    var a = document.getElementById('gw').innerHTML;
    var b = 500;
    var c = a-b;

    var label = document.getElementById('wall');
    label.innerHTML = parseInt(label.innerHTML) - b;
    var label = document.getElementById('gw');
    label.innerHTML = parseInt(label.innerHTML) - c;

}

Body:
Your main issue is that you were doing  var c = a-b;, b being a Number, but a being a String (Element.innerHTML) - without doing parseInt(value, radix) on that value... and there's other math subtraction confusion in there...

Instead:

// Helper function to set to 0 a value lower than 0
function zeroMin(val) {
  return parseInt(val, 10) < 0 ? 0 : val;
}

function send() {

  var EL_gw = document.getElementById('gw'),
    EL_wa = document.getElementById('wall'),
    gw = parseInt(EL_gw.innerHTML, 10),
    wa = parseInt(EL_wa.innerHTML, 10),
    hitVal = 500;

  // Subtract
  gw -= hitVal;
  wa -= hitVal;

  // fix to 0
  gw = zeroMin(gw);
  wa = zeroMin(wa);

  EL_gw.innerHTML = gw;
  EL_wa.innerHTML = wa;

}

<b>Infantry:</b> <span id="gw">40000</span> <br>
<b>Fort:</b> <span id="wall">1000</span> <br>

<button class="troops" onclick="send()">SEND TROOPS</button>

If you want to stop any further action if any of the values reaches 0

function send() {

  var EL_gw = document.getElementById('gw'),
      EL_wa = document.getElementById('wall'),
    gw = parseInt(EL_gw.innerHTML, 10),
    wa = parseInt(EL_wa.innerHTML, 10),
    hitVal = 500;

  if (gw <= 0 || wa <= 0) return; // Do nothing if any is <= 0

  // else...
  gw -= hitVal;
  wa -= hitVal;

  EL_gw.innerHTML = gw;
  EL_wa.innerHTML = wa;

}

<b>Infantry:</b> <span id="gw">40000</span>
(will stop decreasing if FORT energy is 0 and vice-versa)<br>
<b>Fort:</b> <span id="wall">1000</span> <br>

<button class="troops" onclick="send()">SEND TROOPS</button>


问:
i'm using firebase 4 , swift 3 and ios 10 and i can't find FIRAuth
i'm using firebase 4 , swift 3 and ios 10 and i can't find FIRAuth as i'm trying to work on a project to build a messenger app .
can anyone help me with it? </p>

答: Firebase has removed the class prefixes in version 4, so it is now just Auth.


问:
'Duplicate entry' error in DLL when building Desktop Bridge UWP application
I am trying to convert a Windows Forms application to UWP using the Desktop Bridge. Since I have (most of) the source code, I'm attempting the conversion using Visual Studio, as opposed to the command-line tool. My application uses some third-party DLLs whose source code I don't have.

After adding a new JavaScript UWP project to my solution, I'm placing the original application's DLLs in a project subfolder as explained in the documentation.
Some of these DLLs are causing strange errors when I build the UWP project. The errors seem to be caused by duplicate resource entries in the DLLs, but curiously enough, these DLLs are referenced without issue in my standard Windows Forms project.

The errors state:

Duplicate entry

'DevExpress.Data.PropertyNamesRes/DevExpress/XtraPrinting/XpsDocumentOptions'
or one of its parents is defined as both resource and scope, which is
not allowed

I've been digging and searching about these errors for hours but I haven't found any meaningful information. I also used ILDASM to analyze the DLL headers but found no obvious issues in them. Has anyone here faced similar issues? Thanks in advance for any information.

答:
Without seeing the complete error is difficult to say, but I've seen similar errors processing resources. If this is the case, this could be the same as this issue

And can be solved adding this property to the jsproj:

```<code><AppxGeneratePrisForPortableLibrariesEnabled>false</AppxGeneratePrisForPortableLibrariesEnabled>
</code>```

Body:
Without seeing the complete error is difficult to say, but I've seen similar errors processing resources. If this is the case, this could be the same as this issue

And can be solved adding this property to the jsproj:

<AppxGeneratePrisForPortableLibrariesEnabled>false</AppxGeneratePrisForPortableLibrariesEnabled>


问:
In Entity Framework, is it possible to "Add Foreign Key Properties to [Table Name] Entitiy" after generating the model?
We have a large entity model that has been built up over x years, and I was wondering if the following was possible:
We have a lot of old entities where we don't directly expose the foreign keys to other tables, but they have an association in entity framework. i.e. Table 1, has a 1-many relationship to Table 2, Table 2 has a Table1_ID field on the database table, but I can't access that from within my C#/Entity Framework code. Is there a clean way to show this/add this without deleting the association and readding it?
This is in Model First Entity Framework</p>

答:
You can use data annotation and add a property on your Table2 model:

```<code>using System.ComponentModel.DataAnnotations.Schema;
...
[Column("Table1_ID")]
public int Table1Id { get; set; }
</code>```

If you are using the fluent api, you can configure it like that:

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Table2>()
        .Property(t => t.Table1Id)
        .HasColumnName("Table1_ID");
}
</code>```

Then create a new migration and remove everything inside the Up and Down functions.

```<code>public partial class Add_Table1_Reference_To_Table2_Model : DbMigration
{
    public override void Up()
    {
    }

    public override void Down()
    {
    }
}
</code>```

Body:
You can use data annotation and add a property on your Table2 model:

using System.ComponentModel.DataAnnotations.Schema;
...
[Column("Table1_ID")]
public int Table1Id { get; set; }

If you are using the fluent api, you can configure it like that:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Table2>()
        .Property(t => t.Table1Id)
        .HasColumnName("Table1_ID");
}

Then create a new migration and remove everything inside the Up and Down functions.

public partial class Add_Table1_Reference_To_Table2_Model : DbMigration
{
    public override void Up()
    {
    }

    public override void Down()
    {
    }
}


问:
Dynamic Dropdown, JQuery, Not Submitting form with Value
I have the following code, which creates a dynamic dropdown (Text Color) based on the selection of another dropdown (Background Color)

It works as expected, and populates the Text Color dropdown perfectly.

However, when I submit my form, the value for textC is blank everytime. If I create a simple select for Text Color, my form submits fine, and all variables are available on the next page via POST.

Any thoughts to why the the textC value is always blank with this code?

var black = [
{display: "Gray", value: "gray" },
{display: "Warm Red", value: "red" },
{display: "White", value: "white" }];

var white = [
{display: "Black", value: "black" },
{display: "Gray", value: "gray" },
{display: "Warm Red", value: "red" }];

var gray = [
{display: "Black", value: "black" },
{display: "Warm Red", value: "red" },
{display: "White", value: "white" }];

$("#parent_selection").change(function() {
    var parent = $(this).val(); //get option value from parent

    switch(parent){ //using switch compare selected option and populate child
          case 'black':
            list(black);
            break;
          case 'white':
            list(white);
            break;
          case 'gray':
            list(gray);
            break;
          default: //default child option is blank
            $("#textC").html('');
            break;
       }
});

//function to populate child select box
function list(array_list)
    {
    $("#textC").html(""); //reset child options
    $(array_list).each(function (i) { //populate child options
        $("#textC").append("<option value=''+array_list[i].value+''>"+array_list[i].display+"</option>");
    });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p><b>Background Color ?</b><br>
<select name="theme" id="parent_selection">
    <option value="">-- Please Select --</option>
    <option value="black">Black</option>
    <option value="white">White</option>
    <option value="gray">Gray</option>
</select>

<p><b>Text Color?</b><br>
<select name="textC" id="textC">
</select>

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

答:
Can you try this instead:

```<code>//function to populate child select box
function list(array_list)
{
    $("#textC").html(""); //reset child options
    $(array_list).each(function (i) { //populate child options
        $('<option>').val(array_list[i].value).text(array_list[i].display).appendTo('#textC');
    });
}
</code>```

JSFiddle: https://jsfiddle.net/Anokrize/t1w1k463/

Body:
I have the following code, which creates a dynamic dropdown (Text Color) based on the selection of another dropdown (Background Color)

It works as expected, and populates the Text Color dropdown perfectly.

However, when I submit my form, the value for textC is blank everytime. If I create a simple select for Text Color, my form submits fine, and all variables are available on the next page via POST.

Any thoughts to why the the textC value is always blank with this code?

var black = [
{display: "Gray", value: "gray" },
{display: "Warm Red", value: "red" },
{display: "White", value: "white" }];

var white = [
{display: "Black", value: "black" },
{display: "Gray", value: "gray" },
{display: "Warm Red", value: "red" }];

var gray = [
{display: "Black", value: "black" },
{display: "Warm Red", value: "red" },
{display: "White", value: "white" }];

$("#parent_selection").change(function() {
    var parent = $(this).val(); //get option value from parent

    switch(parent){ //using switch compare selected option and populate child
          case 'black':
            list(black);
            break;
          case 'white':
            list(white);
            break;
          case 'gray':
            list(gray);
            break;
          default: //default child option is blank
            $("#textC").html('');
            break;
       }
});

//function to populate child select box
function list(array_list)
    {
    $("#textC").html(""); //reset child options
    $(array_list).each(function (i) { //populate child options
        $("#textC").append("<option value=''+array_list[i].value+''>"+array_list[i].display+"</option>");
    });
}

Background Color ?

<select name="theme" id="parent_selection">
    <option value="">-- Please Select --</option>
    <option value="black">Black</option>
    <option value="white">White</option>
    <option value="gray">Gray</option>
</select>

Text Color?

<select name="textC" id="textC">
</select>

Body:
Can you try this instead:

//function to populate child select box
function list(array_list)
{
    $("#textC").html(""); //reset child options
    $(array_list).each(function (i) { //populate child options
        $('<option>').val(array_list[i].value).text(array_list[i].display).appendTo('#textC');
    });
}

JSFiddle: https://jsfiddle.net/Anokrize/t1w1k463/


问:
How do I count the number of global variables in global scope?
I'm working on a project developed by someone else. I load the Chrome Developer Tool to check the status of a global variable. When I tick open Global under Scope, I see a colossal number of global variables. It takes me over 8 seconds to scroll through them. Having worked on this project for some time now, I know that global variables is a problem which we'll have to fix; but, *that is irrelevant to my question.

To communicate the scale of our global scope being flooded, I'd like to count the number of variables presently instantiated in the global scope

How do I do this?

I'm looking for an answer in JavaScript that I can execute immediately in my console. Basically something that may iterate over the global scope and count++.

答:
```<code>var count = 0;
for( var x in window ){
    if( window.hasOwnProperty(x) ) count++;
}
console.log(count);
</code>```


问:
"Error: [$injector:unpr] Unknown provider:" when updating controller dependencies
I'm unable to get my project to run. It's fine until I...

Update my controller to include the "$ionicPlatform, $cordovaToast, $cordovaLocalNotification"

```<code>.controller('MenuController', ['$scope', 'menuFactory', 'dishes', 'favoriteFactory', 'baseURL', '$ionicListDelegate', '$ionicPlatform', '$cordovaToast',  '$cordovaLocalNotification',
function ($scope, menuFactory, dishes, favoriteFactory, baseURL, $ionicListDelegate, $ionicPlatform, $cordovaToast, $cordovaLocalNotification) {
</code>```

I attempt to run my project and get

Error: [$injector:unpr] Unknown provider: $cordovaLocalNotificationProvider <- $cordovaLocalNotification <- MenuController

Then Angular doc and other posts I've seen suggest that that $cordovaLocalNotification has been omitted or misspelled in the dependency injection for this controller, but I'm sure they're the same.

答:
Bingo! Thanks for that. It was causing me grief...fyi. I had that script reference, but the order was wrong.

It WAS

```<code><!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ionic/js/angular/angular-resource.min.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.js"></script>//THIS is the line
</code>```

I change to the following and it resolved the issue.

```<code><!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.js"></script>//THIS is the line
<script src="lib/ionic/js/angular/angular-resource.min.js"></script>
</code>```

Body:
I'm unable to get my project to run. It's fine until I...

Update my controller to include the "$ionicPlatform, $cordovaToast, $cordovaLocalNotification"

.controller('MenuController', ['$scope', 'menuFactory', 'dishes', 'favoriteFactory', 'baseURL', '$ionicListDelegate', '$ionicPlatform', '$cordovaToast',  '$cordovaLocalNotification',
function ($scope, menuFactory, dishes, favoriteFactory, baseURL, $ionicListDelegate, $ionicPlatform, $cordovaToast, $cordovaLocalNotification) {

I attempt to run my project and get

Error: [$injector:unpr] Unknown provider: $cordovaLocalNotificationProvider <- $cordovaLocalNotification <- MenuController

Then Angular doc and other posts I've seen suggest that that $cordovaLocalNotification has been omitted or misspelled in the dependency injection for this controller, but I'm sure they're the same.

Body:
Bingo! Thanks for that. It was causing me grief...fyi. I had that script reference, but the order was wrong.

It WAS

<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ionic/js/angular/angular-resource.min.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.js"></script>//THIS is the line

I change to the following and it resolved the issue.

<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.js"></script>//THIS is the line
<script src="lib/ionic/js/angular/angular-resource.min.js"></script>


问:
Playing a Flash File in Android
Does Android  support flash? If yes then i need an example code to play a flash file. Wonder if we can play a flash file in WebView?

Waiting for reply

答: android version before 2.1 not supported flash,but from 2.1 and later support flash</p>

Title: Playing a Flash File in Android


问:
List of entire Adobe RGB colour space as hexadecimal?
I'm currently doing a project with colours, and was wondering whether there was a list or some way to generate a list of all of the Adobe RGB colours in hexadecimal? </p>

<p>Thanks! </p>

答:
Here is a python script, if run like this it will write them to a 128 megabyte file

```<code> python hexen.py > reallybiglist.txt
</code>```

Here is the script

```<code># write int as 6-digit hex
def int_6_hex(intval):
  hex = ""
  while intval != 0:
    hexValue = intval % 16
    hex = toHexChar(hexValue) + hex
    intval = intval // 16

  while len(hex) < 6:
    hex = "0" + hex

  return hex

# Convert an integer to a single hex digit in a character
def toHexChar(hexValue):
  if 0 <= hexValue <= 9:
    return chr(hexValue + ord('0'))
  else:  # 10 <= hexValue <= 15
    return chr(hexValue - 10 + ord('A'))

#loop to ffffff
def main():
  intmax = 256*256*256
  # intmax = 256  -- to see a preview
  loopint = 0
  while (loopint < intmax):
    print(int_6_hex(loopint))
    loopint = loopint + 1

main() # Call the main function
</code>```

Body:
I'm currently doing a project with colours, and was wondering whether there was a list or some way to generate a list of all of the Adobe RGB colours in hexadecimal?

Thanks!

Body:
Here is a python script, if run like this it will write them to a 128 megabyte file

 python hexen.py > reallybiglist.txt

Here is the script

# write int as 6-digit hex
def int_6_hex(intval):
  hex = ""
  while intval != 0:
    hexValue = intval % 16
    hex = toHexChar(hexValue) + hex
    intval = intval // 16

  while len(hex) < 6:
    hex = "0" + hex

  return hex

# Convert an integer to a single hex digit in a character
def toHexChar(hexValue):
  if 0 <= hexValue <= 9:
    return chr(hexValue + ord('0'))
  else:  # 10 <= hexValue <= 15
    return chr(hexValue - 10 + ord('A'))

#loop to ffffff
def main():
  intmax = 256*256*256
  # intmax = 256  -- to see a preview
  loopint = 0
  while (loopint < intmax):
    print(int_6_hex(loopint))
    loopint = loopint + 1

main() # Call the main function


问:
yii2 unique validation not working
Yii2 Unique Validation not working for combination of employee id and company id
Below are my model code.

```<code>            public function rules()
                {
                    return [
                        [['company_id', 'role_id'], 'required'],
                        [['company_id', 'role_id', 'status'], 'integer'],
                        [['employee_id'], 'string', 'max' => 15],
                        [['report_to'], 'string', 'max' => 16],
                        [['id',],'safe'],
                        ['employee_id', 'unique', 'targetAttribute' => ['company_id', 'employee_id'], 'message' => 'The combination of Company ID and Employee ID has already been taken.']
                        // ['employee_id', 'unique', 'targetAttribute' => ['company_id'], 'message' => 'The combination of Company ID and Employee ID has already been taken.']
                    ];
                }'
</code>```

And this  my controller code

```<code>                $model = new Employee();
                //$profile = new Profile();
                // $profile->scenario = 'emp_bulk_uplscenariooad';
                if($model->load(Yii::$app->request->post())) {
                    $model->company_id = $userModel->company_id;

                    $model->employee_id = Yii::$app->request->post()['Employee']['employee_id'];

                    $model->role_id = Yii::$app->request->post()['Employee']['role_id'];
                    $model->report_to = Yii::$app->request->post()['Employee']['report_to'];
                        // print_r(!$model->validate());die();
                        if($model->save(false)){
        }

*************************************************************************

    please help me with this.thanks in advance
</code>```

答:
Try performing composer update, there was a Yii2 bug fixed that was tied to unique validator when using relational data in addition to other scenarios:

See the following: https://github.com/yiisoft/yii2/issues/14211

Title: yii2 unique validation not working

Body:
Yii2 Unique Validation not working for combination of employee id and company id
Below are my model code.

            public function rules()
                {
                    return [
                        [['company_id', 'role_id'], 'required'],
                        [['company_id', 'role_id', 'status'], 'integer'],
                        [['employee_id'], 'string', 'max' => 15],
                        [['report_to'], 'string', 'max' => 16],
                        [['id',],'safe'],
                        ['employee_id', 'unique', 'targetAttribute' => ['company_id', 'employee_id'], 'message' => 'The combination of Company ID and Employee ID has already been taken.']
                        // ['employee_id', 'unique', 'targetAttribute' => ['company_id'], 'message' => 'The combination of Company ID and Employee ID has already been taken.']
                    ];
                }'

And this  my controller code

                $model = new Employee();
                //$profile = new Profile();
                // $profile->scenario = 'emp_bulk_uplscenariooad';
                if($model->load(Yii::$app->request->post())) {
                    $model->company_id = $userModel->company_id;

                    $model->employee_id = Yii::$app->request->post()['Employee']['employee_id'];

                    $model->role_id = Yii::$app->request->post()['Employee']['role_id'];
                    $model->report_to = Yii::$app->request->post()['Employee']['report_to'];
                        // print_r(!$model->validate());die();
                        if($model->save(false)){
        }

*************************************************************************

    please help me with this.thanks in advance


问:
Can I prevent comparison to NULL with overloaded operator==?
Let's say I have a String class that I want to be able to construct or assign with a pointer, but disallow compiling with an explicit std::nullptr assignment:

```<code>class String {
public:
    String(const char *);
    friend bool operator== (const String &, const char *);
    friend bool operator!= (const String &, const char *);
    // some important things left out
private:
    String(std::nullptr_t);
}
</code>```

The purpose is to give "error: 'operator=' is a private member of 'String'" if I try to write "str = NULL", which helps me identify some bugs in an old codebase.  Obviously, the public constructor should handle the nullptr case as well.  Additionally, it helps me identify some similar issues such as "str = 0", which the compiler will report as ambiguous.

My question is - can I do something similar with binary comparison operators, operator== and operator!=?  I would like the compiler to report an attempted comparison to std::nullptr_t, which is also very common in my codebase.

答:
Whenever you want to prohibit calling a certain function you can append = delete, which was introduced in C++11:

```<code>friend bool operator==(const String&, std::nullptr_t) = delete;
friend bool operator!=(const String&, std::nullptr_t) = delete;
</code>```

Whenever you try to compare your type with nullptr you get this compiler error:

```<code>function "operator==(const String &, std::nullptr_t)" cannot be referenced -- it is a deleted function
</code>```

Body:
Let's say I have a String class that I want to be able to construct or assign with a pointer, but disallow compiling with an explicit std::nullptr assignment:

class String {
public:
    String(const char *);
    friend bool operator== (const String &, const char *);
    friend bool operator!= (const String &, const char *);
    // some important things left out
private:
    String(std::nullptr_t);
}

The purpose is to give "error: 'operator=' is a private member of 'String'" if I try to write "str = NULL", which helps me identify some bugs in an old codebase.  Obviously, the public constructor should handle the nullptr case as well.  Additionally, it helps me identify some similar issues such as "str = 0", which the compiler will report as ambiguous.

My question is - can I do something similar with binary comparison operators, operator== and operator!=?  I would like the compiler to report an attempted comparison to std::nullptr_t, which is also very common in my codebase.

Body:
Whenever you want to prohibit calling a certain function you can append = delete, which was introduced in C++11:

friend bool operator==(const String&, std::nullptr_t) = delete;
friend bool operator!=(const String&, std::nullptr_t) = delete;

Whenever you try to compare your type with nullptr you get this compiler error:

function "operator==(const String &, std::nullptr_t)" cannot be referenced -- it is a deleted function


问:
Undefined method accept_modal for Capybara::Webkit::Driver
In a Rails app, I'm using RSpec (with Capybara Webkit) to test that a Delete link is working.

In my Rails template I have:

```<code><%= link_to 'Delete', movie_path(@movie),
                      method: :delete, data: { confirm: 'Are you sure?' } %>
</code>```

And this is my spec:

```<code>require 'rails_helper'

describe "Deleting a movie", js: true do
  it "destroys the movie and shows the movie listing without the deleted movie" do
    movie = Movie.create(movie_attributes)

    visit movie_path(movie)

    page.accept_confirm do
     click_link 'Delete'
    end

    expect(current_path).to eq(movies_path)
    expect(page).not_to have_text(movie.title)
  end
end
</code>```

I get the error:

```<code>NoMethodError:
   undefined method `accept_modal' for #<Capybara::Webkit::Driver:0x007febc2214908>
</code>```

It's using the right driver (Webkit) but it doesn't seem to find accept_modal (which must be called by page.accept_confirm).

I'm using:

```<code>capybara (2.14.0)
capybara-webkit (1.1.0)
rails (5.1.1)
rspec (3.6.0)
rspec-rails (3.6.0)
</code>```

Note that using the following will work:

```<code>click_link 'Delete'
page.driver.browser.accept_js_confirms
</code>```

But I'd like to understand why accept_confirm does not.

答: The capybara-webkit you are using is massively out of date (1.1.0 was realeased in December of 2013), didn't support the unified Capybara modal API (it didn't exist when capybara-webkit 1.1.0 was released), and didn't derive it's driver class from Capybara::Driver::Base, so you don't get the "NotSupportedByDriverError" you would get nowadays if a feature was not yet implemented/supported by a driver - update to the latest capybara-webkit (you may need to use the master branch if you want to use capybara 2.14.0+, otherwise you'll be stuck at capybara 2.13.x)</p>

Body:
In a Rails app, I'm using RSpec (with Capybara Webkit) to test that a Delete link is working.

In my Rails template I have:

<%= link_to 'Delete', movie_path(@movie),
                      method: :delete, data: { confirm: 'Are you sure?' } %>

And this is my spec:

require 'rails_helper'

describe "Deleting a movie", js: true do
  it "destroys the movie and shows the movie listing without the deleted movie" do
    movie = Movie.create(movie_attributes)

    visit movie_path(movie)

    page.accept_confirm do
     click_link 'Delete'
    end

    expect(current_path).to eq(movies_path)
    expect(page).not_to have_text(movie.title)
  end
end

I get the error:

NoMethodError:
   undefined method `accept_modal' for #<Capybara::Webkit::Driver:0x007febc2214908>

It's using the right driver (Webkit) but it doesn't seem to find accept_modal (which must be called by page.accept_confirm).

I'm using:

capybara (2.14.0)
capybara-webkit (1.1.0)
rails (5.1.1)
rspec (3.6.0)
rspec-rails (3.6.0)

Note that using the following will work:

click_link 'Delete'
page.driver.browser.accept_js_confirms

But I'd like to understand why accept_confirm does not.